Reverse Engineering a string in python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
Improve this question
we have encoded strings that want to decryption it.
First, the first letter of the string, then the last letter. Then the rest of the letters are stored in the same way. For example, the string amir is first added to the new letter. Then the last letter is r. This process continues in the same way, ie in the next stage m and in the next stage after the addition. (That is, first the first letter and the last letter, then the second letter and then the last letter of the last letter, and this process continues until the word)
In the second step, the whole string is reversed.
In the third step, the letter a becomes 4. The letter o is replaced by 0. The letter t becomes 7 and finally the letter i becomes 1.
Note: It is guaranteed that the number of letters is always even and only includes lowercase English letters
example:
input 1mr4
output amir
input w00lrlledh
output helloworld
I read this but I have no idea of write a program

You can use replace to make the character replacements.
For the encoding part: to apply the permutation of the characters, apply the logic with a variable i that you let run from 0 to the half of the string. Take the character at index i and the one that is i positions from the right (i.e. you can use -1-i). Then concatenate those characters. You can reverse the order at the same time.
To do the opposite, replace the opposite characters.
For the permutation, analyse how it works on a piece of paper and you'll find the logic of where to find the characters that need to be placed from left to right.
Here is code:
def encrypt(s):
for a, b in "a4", "o0", "i1", "t7":
s = s.replace(a, b)
return "".join(s[-1-i] + s[i] for i in range(len(s) // 2 - 1, -1, -1))
def decrypt(s):
for a, b in "a4", "o0", "i1", "t7":
s = s.replace(b, a)
return "".join(s[-1-i*2] for i in range(len(s) // 2)) + \
"".join(s[i*2] for i in range(len(s) // 2))

Related

How can I parse only string without using regex in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I am learning Python and have a question about parsing strings without regex. We should use a while loop. Here is the question;
We will have a string from the user with the input function. And then we will export just alpha characters from this sentence to a list.
For example, sentence: "The weather is so lovely today. Jack (our Jack) – Jason - and Alex went to park..? "
Example output: ["The", "weather", "is", "so","lovely","today","Jack","our","Jack","and","Alex","went","to","park"]
I have to note that punctuation marks and special characters such as parentheses are not part of words.
Below you can find I tried my codes. I couldn't find where I had an error.
s=" The weather is so lovely today. Jack (our Jack) – Jason - and Alex went to park..?"
i = 0
j = 0
l=[]
k=[]
count = 0
while s:
while j<len(s) and not s[j].isalpha():
j+=1
l = s[j:]
s=s[j:]
while j < len(s) and l[j].isalpha():
j+=1
s=s[j:]
k.append(l[0:i])
print(k)
print(l)
On the other hand, I did parse the first word with the code below.
s=" The weather is so lovely today. Jack (our Jack) – Jason - and Alex went to park..?"
i = 0
j = 0
l=[]
k=[]
while j<len(s) and not s[j].isalpha():
j+=1
l = s[j:]
while i < len(l) and l[i].isalpha():
i+=1
s=s[i:]
k.append(l[0:i])
print(k)
print(l)
Thanks for your help.
By and large, if your goal is to parse a string and you find yourself modifying the string, you're probably doing it wrong. That's particularly true of languages like Python where strings are immutable, and modifying a string really means creating a new one, which takes time proportional to the length of the string. Doing that in a loop effectively turns a linear scan into a quadratic-time algorithm; you might not notice the dramatic consequences with a few short test cases, but sooner or later you (or someone) will try your code out on a significantly longer string, and the quadratic time will come back to bite you.
Anyway, there's no need. All you need to do is to look at the characters, or more accurately, look at each position between two characters, in order to find the positions of the beginnings of the words (where an alphabetic character follows a non-alphabetic character) and the ends of the words (where a non-alphabetic character follows an alphabetic character). Once the beginning and end of each word is discovered, the complete word can be added to the word list.
Note that we don't actually care what each character is, only whether it is alphabetic. So in the following code, I don't save the previous character; rather I save the boolean value of whether the previous character was alphabetic. At the start of the scan, previous_was_alphabetic is set to False, so if the first character in the string is alphabetic, that counts as the start of a word.
There's one little Python trick here, to handle the end of the string. If the last character in the string is alphabetic, then it's the end of a word, so it would be convenient to ensure that the string ends with a non-alphabetic character. But I don't really want to create a modified string, and I'd prefer not to have to write special purpose code for the end of the string. What I do instead is to use a slice; instead of looking at s[i] (the ith character), I use s[i:i+1], the one-character slice starting at position i. Conveniently, if i happens to be the length of s, then s[i:i+1] is an empty string, '', and even more conveniently, ''.isalpha() is False. So that will act as though there were an invisible non-alphabetic character at the end of the string.
This is not really very Pythonic, but your assignment seems to be insisting that you use a while loop rather than the much more natural for loop (which would require a different way of dealing with the end of the string).
def words_from(s):
"""Returns a list of the "words" (contiguous sequences of alphabetic
characters) from the string s
"""
words = []
previous_was_alphabetic = False
i = 0
while i <= len(s):
next_is_alphabetic = s[i:i+1].isalpha()
if not previous_was_alphabetic and next_is_alphabetic:
# i is the start of a word
start = i
elif previous_was_alphabetic and not next_is_alphabetic:
# i is the position after the end of a word
words.append(s[start:i])
# Move to the next position
previous_was_alphabetic = next_is_alphabetic
i += 1
return words
I think you might want sth like this:
s = "The weather is so lovely today. Jack (our Jack) – Jason - and Alex went to park..? "
punc = '''!()-[]{};:'"\,–,<>./?##$%^&*_~'''
# Removing punctuations in string
# Using loop + punctuation string
for i in s:
if i in punc:
s = s.replace(i, "")
print(s.split())
output:
['The', 'weather', 'is', 'so', 'lovely', 'today', 'Jack', 'our', 'Jack', 'Jason', 'and', 'Alex', 'went', 'to', 'park']

How can I write "EvenWord" Recursive in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
We tried to solve the following problem with friends but we couldn't come to a conclusion. How can we approach this question?
The full question is:
Even Words Problem: An even word is a word that contains an even number of copies of every letter. For example, the word "tattletale"
is an even word, since there are four copies of 't' and two copies of
'a,' 'e,' and 'l.' Similarly, "appeases" and arraigning" are even
words. However, "banana" is not an even word, because there is just
one 'b' and three copies of 'a.'
Write a function def isEvenWord(word) that accepts as input a string
representing a single word and returns whether or not that word is an
even word.
Your solution should be recursive and must not use any loops (e.g.
while, for). As a hint, this problem has a beautiful recursive
decomposition:
• The empty string is an even word, since it has 0 copies of every
letter.
• Otherwise, a word is an even word if there are at least two copies
of the first letter and the word formed by removing two copies of the
first letter is itself an even word.
For example, we can see that the word "appeases" is an even word using
the following logic:
"appeases" is an even word, because "ppeses" is an even word, because
"eses" is an even word, because "ss" is an even word, because "" is an
even word.
Screenshot of the problem description
I assume the tricky part is not using loop since this the solution must be recursive.
In this problem, you want to find whether the count of each letter can be divided by two.
Here are the steps you can follow:
1) Define your base condition
In this problem, the base condition is when there are no more letters in the word to check; in other words, your word is an empty string ''.
If the base condition is reached, it means that you have checked the count of all the letters in the word and the count was always even. So you can stop there. You've checked all the letters in the word and their count and they are even --> you return True and you are done.
2) Define what you do if the base condition is not reached:
In this problem, you need to check that the count of each letter in the word is even. You can store the letter in a variable and check its count in the word.
You must check the last letter each time, create a new word that doesn't contain the letter already checked, and run the isEvenWord(word) function again on the new word.
If when you check the count of the letter, it is not even, then you are done, you know that the word is not even since at least one letter in the word is not even so you return False.
If the count of the letter you are checking is even then you continue the check the next letter by calling your function again on the new word made of the remaining letters that you haven't checked yet.
Here is the code version of the explanation above:
def isEvenWord(word):
if word == '': # base condition
return True
else:
last_letter = word[-1]
if word.count(last_letter) % 2 != 0:
return False
else:
next_word = word[0:-1] #create the next word you want to test (ie the word except the last letter)
next_word = word.replace(last_letter, '') # in the new word, replace the variable last_letter (the letter you just counted) by an empty string '' which is like removing it
return isEvenWord(next_word)
Very nice little puzzle, thanks for sharing.
I hope this helps.

Why doesn't my front_back programme in Python work? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The task is:
Given a string, return a new string where the first and last chars have been exchanged.
def front_back(str):
if len(str)<=0:
return str
else:
front=str[0]
back=str[-1]
new = str.replace(str[0], back)
print new
new_2=new.replace(new[-1], front)
print new_2
front_back("code")
Why?
It won't work because .replace() will replace all occurrences of that character, not necessarily only the first and last
Below is a solution that constructs the string with first, body and last portions
text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'
String literals can be sliced and added:
>>> s = "hello world"
>>> s[-1] + s[1:-1] + s[0]
'dello worlh'
P.S. str is a builtin in python, so using it as a variable name is a bad idea.
First, never call a variable str. Why? Because that is the name of the class for Python strings. If you use the same name then you loose it. I use txt.
Your test with the length is sensible, but the lower limit can be increased (a single character would be silly).
But using str.replace() is not feasible. Why? Well it could work in your test case, but only because each character is unique. str.replace() replaces every occurrence of the specified string. So if the first or last character was repeated elsewhere then that would be changed as well.
You can use slicing, where the first (leftmost) character is 0 (zero). You can also index from the right using negative numbers, so -1 is the last (rightmost) character. The range of characters goes from the start to the character after the last. So [1:-1] goes from the second character to the last but one.
def front_back(txt):
if len(txt) <= 1:
return txt
else:
new_txt = txt[-1] + txt[1:-1] + txt[0]
return new_txt
print front_back("code")
I use return in the function, since that would be the normal way of processing text, and that is asked for in your question.

Duplicate words in a list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How can I return a duplicated word in a list?
I was asked to create a function, word_count(text, n). The text is converted into a list and then return the word that is repeated n times. I've tried to write it but it seems to return every single word.
>>> repeat_word_count("one one was a racehorse two two was one too", 3)
['one']
I've used the for loop and conditioned it. I'm wanted to post my code but I'm scared that my school will find the code online :(
I think I know what it is that you are wanting to do and without seeing your code I can't point out exactly where you're going wrong so I'll take you through creating this function step by step and you should be able to figure out where you went wrong.
I think you are trying to create this:
def function(a,b):
"""where a is a sentence and b is the target number.
The function will return to you each word in the
given sentence that occurs exactly b times."""
To do this we have to do the following:
converts the sentence into a list of words and removes punctuation,capitalization,and spaces.
iterates through each unique word in the sentence and print it if it occurs exactly b times in the sentence
put these together to make a function
so in your example your sentence was "one one was a racehorse two two was one too", and you're looking for all words that occur exactly 3 times, so the function should return the word "one"
We'll look at each step one at a time.
FIRST STEP -
we have to take the sentence or sentences and convert them into a list of words. Since I don't know if you will be using sentences with punctuation and/or capitalization I'll have to assume that its possible and plan to deal with them. We'll have to omit any punctuation/spaces from the list and also change all the letters in each word to lowercase if they happened to have a capital letter because even though "Cat" and "cat" are the same word, according to a computer brain, "Cat" does NOT equal any of these:
"cat" - lowercase c doesn't match uppercase C in "Cat"
" Cat" - there is an extra space at the start of the word
"Cat." - There is a period after the word
"Cat " - There is a space after the word
So if we use "One one was a racehorse two two was one, too." as our input we'll need to handle spaces, punctuation, and capitalization. Luckily all of this work can be done with 2 lines of code by using a regular expression and list comprehension to get rid of all the junk and create a list of words.
import re
wordlist=[i.lower() for i in re.findall(r"[\w']+",sentence)]
This gives us our list of words:
['one', 'one', 'was', 'a', 'racehorse', 'two', 'two', 'was', 'one', 'too']
SECOND STEP -
Now we need to iterate through each Unique word in the wordlist and see if it occurs exactly b times. Since we only need unique words we can create a list that only contains each word exactly once by converting the wordlist from a list to a set and looping through each word in the set and counting the number of times they appear in the wordlist. Any that occur exactly b number of times are our solutions. I'm not exactly sure how you were wanting the results returned but i'm going to assume you want to have each word that fits the criteria to be printed one at a time.
for word in set(wordlist):
if wordlist.count(word)==b:
print word
THIRD STEP -
Now I'll put all this together to create my function:
import re
def repeat_word_count(a,b):
wordlist=[i.lower() for i in re.findall(r"[\w']+",a)]
for word in set(wordlist):
if wordlist.count(word)==b:
print word
I hope this helps you understand a bit better

Filter sentence by word length [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have to get a sentence from the user and an integer, divide that sentence into words. And then count the characters in each word. Each word that has more characters than the integer put in from the user is supposed to be printed. So if the user puts in the sentence "i love cats" and the number 3. All the words that have more than 3 characters (in this case just love) are supposed to appear as well as the amount of characters it contains (in this case 4). The problem is that I don't know how to get the program to count the letters in each specific word. Is there a way that I can cut a list into sublists and then count the characters in each sublist?
If you can isolate the word in a string, you can simply use len to get the number of letters.
To isolate those words, you can split the string on whitespace using .split().
Other than that, iterate through the words with a for loop, or use a list comprehension.
s = "i love cats"
n = 3
[(x, len(x)) for x in s.split() if len(x) > n]
Prints
[('love', 4), ('cats', 4)]

Categories

Resources