So I am doing a project where I try to guess the key of a message that has been changed. The message was converted from character to ascii number had the key added onto the ascii number and then converted back to character. I am struggling to figure out how to get a if statement that would return something if there is an intersection between the message and a word bank. It never returns the correct thing. Thoughts?
import re
from list_maker import *
message = input("what is your code? ")
list_broken = [ord(i) for i in message]
key = 27
num = 26
for l in list_broken:
key -= 1
list_decoded = [chr(i - key) for i in list_broken]
final = ''.join(list_decoded)
word_list = re.sub("[^\w]", " ", final).split()
S1 = set(word_list)
S2 = set(set_of_words)
i = 0
for e in S1:
if e in S2:
break
print(word_list)
print(key)
Sets have an intersection operator just for this.
S1&S2 returns the set of elements in both given sets.
So for your case, you can just check:
if S1&S2:
...
Related
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")
I am currently working on python, and I do not understand this much. I am looking for help with this question, before the dictionaries. This question is to be completed without any dictionaries. The problem is I do not know much about the max function.
So Far I have:
AlphaCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in text:
ch = ch.upper()
index=Alpha.find(ch)
if index >-1:
AlphaCount[index] = AlphaCount[index]+1
You can use Counter
from collections import Counter
foo = 'wubalubadubdub'
Counter(list(foo))
To get the most frequent letter
Counter(list(foo)).most_common(1)
You can use set which will get only unique characters from the input. Then iterate over them and count how many times it occurs in the input with count. If it occurs more often then the max and isalpha (not a space) then set max to the count.
text='This is a test of tons of tall tales'
un=set(text.upper())
max=0
fav=''
for u in un:
c=text.upper().count(u)
if c>max and u.isalpha():
max=c
fav=u
print(fav) # T
print(max) # 6
EDIT
To do this from your code: fix capitalization(for, if) and then find and print/return the most common letter. Also AlphaCount has an extra 0, you only need 26.
text='This is a test of tons of tall talez'
AlphaCount=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in text:
ch= ch.upper()
index=Alpha.find(ch)
if index >-1:
AlphaCount[index]+=1
print(AlphaCount) # the count of characters
print(max(AlphaCount)) # max value in list
print(AlphaCount.index(max(AlphaCount))) # index of max value
print(Alpha[AlphaCount.index(max(AlphaCount))]) # letter that occurs most frequently
def main():
string = input('Enter a sentence: ')
strings=string.lower()
counter = 0
total_counter = 0
most_frequent_character = ""
for ch in strings:
for str in strings:
if str == ch:
counter += 1
if counter > total_counter:
total_counter = counter
most_frequent_character = ch
counter = 0
print("The most frequent character is", most_frequent_character, "and it appears", total_counter, "times.")
main()
Asked my friend to give me an assignment for me to practice. It is:
If a user enters a string "AAABNNNNNNDJSSSJENDDKEW" the program will return
"3AB6NDJ2SJEN2DKEW" and vice versa.
This what I tried so far:
from collections import Counter
list_user_input =[]
list_converted_output=[]
current_char = 0 #specifies the char it is reading
next_char = 1
cycle = 0 # counts number of loops
char_repeat = 1
prev_char=""
count = 1
user_input = input("Enter your string: ")
user_input_strip = user_input.strip()
user_input_striped_replace = user_input_strip.replace(" ", "").lower()
list_user_input.append(user_input_striped_replace[0:len(user_input_striped_replace)])
print(list_user_input)
print(user_input_striped_replace)
I have "cleaned" the code so it removes white spaces and keeps it in low cap
Here is where I am stuck - the logics. I was thinking to go the through the string one index at a time and compare the next on to the other. Is this the wright way to go about it? And I'm not even sure about the loop construction.
#counter = Counter(list_user_input)
#print(counter)
#while cycle <= len(user_input_striped_replace):
for letter in user_input_striped_replace:
cycle+=1
print("index nr {}, letter: ".format(current_char)+letter +" and cycle : " + str(cycle))
current_char+=1
if letter[0:1] == letter[1:2]:
print("match")
print("index nr {}, letter: ".format(current_char)+letter +" and cycle : " + str(cycle))
current_char+=1
Counter is a good choice for such task but about the rest you can use sorted to sort the items of Counter then use a list comprehension to create the desire list then concatenate with join :
>>> from collections import Counter
>>> c=Counter(s)
>>> sor=sorted(c.items(),key=lambda x:s.index(x[0]))
>>> ''.join([i if j==1 else '{}{}'.format(j,i) for i,j in sor])
'3AB7N3D2J3S2EKW'
I'd do it with regular expressions. Have a look at those.
Spoiler:
import re
def encode(s):
return re.sub(r'(.)\1+', lambda m: str(len(m.group(0)))+m.group(1), s)
def decode(e):
return re.sub('(\d+)(.)', lambda m: int(m.group(1))*m.group(2), e)
s = "AAABNNNNNNDJSSSJENDDKEW"
e = encode(s)
print(e, decode(e) == s)
Prints:
3AB6NDJ3SJEN2DKEW True
Your "and vice versa" sentence sounds like the program needs to detect itself whether to encode or to decode, so here's that (proof of correctness left as an exercise :-)
def switch(s):
e = re.sub(r'(\D)\1+', lambda m: str(len(m.group(0)))+m.group(1), s)
d = re.sub('(\d+)(.)', lambda m: int(m.group(1))*m.group(2), s)
return e if e != s else d
This is a simple encryption code that I've come up with. It uses a single character key.
ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')
def encrypt1(key,ar):
i = 0
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
print(br)
encrypt1(key,ar)
print('Input string = ' + ar+'\n'+'key = '+key)
If I input "CMPUT" for the string to be encrypted and 'a' as the key I will get this printed output:
"
,
1
4
5
Which is the correct encryption (according to my assignment example). Now I just have to get those outputs into a single string and print them in the shell like such:
>>>decrypted string: ",145
I've looked through google and old questions on this website but I've still come up empty. I would appreciate your help.
Check out this code, I believe this is what you need (I changed print(br) line):
ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')
def encrypt1(key,ar):
i = 0
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
print(br, end='')
encrypt1(key,ar)
print('\nInput string = ' + ar+'\n'+'key = '+key)
Most obvious way for a beginner would be to simply accumulate to a string
def encrypt1(key,ar):
i = 0
result = ""
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
result += br
return result
Usually you would just write it using a generator expression
def encrypt1(key,ar):
return ''.join(chr(ord(i) ^ ord(key)) for i in ar)
After much frustration, I have made my first Caesar Decoder :)
But the problem now is to make the program circular...
For example if we want to shift doge by 1, no problem, it's ephf...
But what about xyz, and the shift was 4???
So programming pros help a first time novice aka newb out :P
Thanks...
import string
def main():
inString = raw_input("Please enter the word to be "
"translated: ")
key = int(raw_input("What is the key value? "))
toConv = [ord(i) for i in inString] #now want to shift it by key
toConv = [x+key for x in toConv]
#^can use map(lambda x:x+key, toConv)
result = ''.join(chr(i) for i in toConv)
print "This is the final result due to the shift", result
Here is Python code that I wrote to be easy to understand. Also, I think the classic Caesar cipher didn't define what to do with punctuation; I think the classic secret messages were unpunctuated and only contained letters. I wrote this to only handle the classic Roman alphabet and pass any other characters unchanged.
As a bonus, you can use this code with a shift of 13 to decode ROT13-encoded jokes.
def caesar_ch(ch, shift):
"""
Caesar cipher for one character. Only shifts 'a' through 'z'
and 'A' through 'Z'; leaves other chars unchanged.
"""
n = ord(ch)
if ord('a') <= n <= ord('z'):
n = n - ord('a')
n = (n + shift) % 26
n = n + ord('a')
return chr(n)
elif ord('A') <= n <= ord('Z'):
n = n - ord('A')
n = (n + shift) % 26
n = n + ord('A')
return chr(n)
else:
return ch
def caesar(s, shift):
"""
Caesar cipher for a string. Only shifts 'a' through 'z'
and 'A' through 'Z'; leaves other chars unchanged.
"""
return ''.join(caesar_ch(ch, shift) for ch in s)
if __name__ == "__main__":
assert caesar("doge", 1) == "ephf"
assert caesar("xyz", 4) == "bcd"
assert caesar("Veni, vidi, vici.", 13) == "Irav, ivqv, ivpv."
The part at the end is a "self-test" for the code. If you run this as a stand-alone program, it will test itself, and "assert" if a test fails.
If you have any questions about this code, just ask and I'll explain.
Just add the key to all the actual character codes, then if the added value is greater than z, modulo with character code of z and add it with the character code of a.
inString, key = "xyz", 4
toConv = [(ord(i) + key) for i in inString] #now want to shift it by key
toConv = [(x % ord("z")) + ord("a") if x > ord("z") else x for x in toConv]
result = ''.join(chr(i) for i in toConv)
print result # cde
I'd recommend using string.translate().
So, we can do the following:
key = 1
table = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[key:] + string.ascii_lowercase[:key] + string.ascii_uppercase[key:] + string.ascii_uppercase[:key])
And then we can use it as follows:
'doge'.translate(table) # Outputs 'ephf'
'Doge'.translate(table) # Outputs 'Ephf'
'xyz'.translate(table) # Outputs 'yza'
In particular, this doesn't change characters that are not ascii lowercase or uppercase characters, like numbers or spaces.
'3 2 1 a'.translate(table) # Outputs '3 2 1 b'
in general, to make something "wrap" you use the modulo function (% in Python) with the number you want to wrap, and the range you want it to wrap in. For example, if I wanted to print the numbers 1 through 10 a bajillion times, I would do:
i = 0
while 1:
print(i%10+1)
# I want to see 1-10, and i=10 will give me 0 (10%10==0), so i%10+1!
i += 1
In this case it's a little more difficult because you're using ord, which doesn't have a nice happy "range" of values. If you had done something like string.ascii_lowercase you could do...
import string
codex = string.ascii_lowercase
inString = "abcdxyz"
key = 3
outString = [codex[(codex.index(char)+key)%len(codex)] for char in inString]
However since you're using ord, we're kind of going from ord('A') == 65 to ord('z')==122, so a range of 0 -> 57 (e.g. range(58), with a constant of 65. In other words:
codex = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz"
# every char for chr(65) -> chr(122)
codex = ''.join([chr(i+65) for i in range(58)]) # this is the same thing!
we can do this instead, but it WILL include the characters [\]^_`
inString, key = 'abcxyzABCXYZ', 4
toConv = [(ord(i)+key-65)%58 for i in inString]
result = ''.join(chr(i+65) for i in toConv)
print(result)
# "efgBCDEFG\\]^"
I know this is kind of an old topic, but I just happened to be working on it today. I found the answers in this thread useful, but they all seemed to use a decision to loop. I figured a way to accomplish the same goal just using the modulus(remainder) operator (%). This allows the number to stay within the range of a table and loop around. It also allows for easy decoding.
# advCeaser.py
# This program uses a ceaser cypher to encode and decode messages
import string
def main():
# Create a table to reference all upper, lower case, numbers and common punctuation.
table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz1234567890,.!?-#'
print 'This program accepts a message and a key to encode the message.'
print 'If the encoded message is entered with the negative value of the key'
print 'The message will be decoded!'
# Create accumulator to collect coded message
code =''
# Get input from user: Message and encode key
message = raw_input('Enter the message you would like to have encoded:')
key = input('Enter the encode or decode key: ')
# Loop through each character in the message
for ch in message:
# Find the index of the char in the table add the key value
# Then use the remainder function to stay within range of the table.
index = ((table.find(ch)+key)%len(table))
# Add a new character to the code using the index
code = code + table[index]
# Print out the final code
print code
main()
The encode and decode output look like this.
encode:
This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:The zephyr blows from the east to the west!
Enter the encode or decode key: 10
croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
decode:
This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
Enter the encode or decode key: -10
The zephyr blows from the east to the west!
Sorry if my formatting looks catywompus I literally found stackoverflow yesterday! Yes, I literally mean literally :)