Why does my 'secret message/code-breaking' code not work? - python-3.x

I have created a code that (should) be able to convert a string into an ascii 'code'. However, it doesn't output what i want it to. Here is the code concerned:
if Code_Decode=='C':
print("What is your 'Shift number'?")
SNum=int(input("> "))
print("What is your message?")
msg=input("> ")
code=[ord(c) for c in msg]
new_code=[x+(SNum) for x in code]
print(','.join(str(x) for x in code))
else:
print("What is your 'Shift number'?")
SNum=int(input("> "))
print("Type in your ASCII values, separated by a comma")
a = [int(x) for x in input().split(",")]
ans=[x-(SNum) for x in a]
ans2=[chr(i) for i in ans]
print(' '.join(str(x) for x in ans2))
The user should input a 'Shift Number', then a string, And it should be converted into ascii, with the Shift Number added to each individual value.
However, when I run the code, the shift number is not added. Ignore the if and else lines.
Example: (This is what happens when I run the code)
Do you want to Create(C) a message, or Decode(D) a message? (C/D)> C
What is your 'Shift number'?
> 2
What is your message?
> Hello World
72,101,108,108,111,32,87,111,114,108,100
Again? Y/N > Y
Do you want to Create(C) a message, or Decode(D) a message? (C/D)> D
What is your 'Shift number'?
> 2
Type in your ASCII values, separated by a comma
72,101,108,108,111,32,87,111,114,108,100
F c j j m U m p j b
As you can see, the program outputs with some jumbled-up letters. How do I fix it?

Wrong: print(','.join(str(x) for x in code))
Right: print(','.join(str(x) for x in new_code))

Related

The algorithm receives a natural number N > 1 as input and builds a new number R from it as follows:

Python.
It's a problem:
The algorithm receives a natural number N > 1 as input and builds a new number R from it as follows:
We translate the number N into binary notation.
Invert all bits of the number except the first one.
Convert to decimal notation.
Add the result with the original number N.
The resulting number is the desired number R. Indicate the smallest odd number N for which the result of this algorithm is greater than 310. In your answer, write this number in decimal notation.
This is my solution:
for n in range(2, 10000):
s = bin(n)[2:]
for i in range(len(s)):
if s[i+1] == 0:
s[i] = '1'
else:
s[i] = 'k'
for i in range(len(s)):
if s[i] == 'k':
s[i] = '0'
h = int(s, 2)
r = h + n
if n % 2 == 1 and r > 310:
print(n)
break
So it doesn't work and i dont know why. I am now preparing for the exam, so I would be grateful if you could explain the reason to me
the bin function returns a string and my idea is to go through the binary elements of this string, starting from the second element, to replace 0 with 1, and 1 with k. Then iterate over the elements of a new line again and replace k with 0
Took me longer than I expected but feels good.
Comments might make it look chaotic but will make it easily understandable.
#since N is supposed to be odd and >1 the loop is being run from 3
for N in range(3, 10000,2):
#appending binary numbers to the list bin_li
bin_li=[]
bin_li.append((bin(N)[2:]))
for i in bin_li:
#print("bin_li item :",i)
#storing 1st digit to be escaped in j
j=i[:1]
#reversing the digits
for k in i[1:]:
if k=='0':
#putting together the digits after reversing
j=j+'1'
else:
j=j+'0'
#print("reversed item :",j) #note first digit is escaped
#converting back to decimal
dec=int(j,2)
R=dec+N
#print("current sum:---------" ,R)
if R > 310:
print("The number N :",N)
print("The reversed binary number:",dec)
print("Sum :",R)
break
#break will only break the inner loop
# for reference https://www.geeksforgeeks.org/how-to-break-out-of-multiple-loops-in-python/
else:
continue
break

python function call not printing as expected

So I have 2 functions - displayHand(hand) and calculateHandlen(hand)
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ")
print()
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
handLen = 0
for i in hand:
handLen = handLen + hand.get(i,0)
return handLen
There's a loop in another function that is dependent on the above functions -
def playHand(hand, wordList, n):
"""
hand = dictionary
wordList = list of valid words
n = an integer passed while function call
"""
totalscore = 0
while(calculateHandlen(hand)>0):
print("Current Hand: " +str(displayHand(hand)))
newWord = input('Enter word, or a "." to indicate that you are finished: ')
Function call for playHand() is as follows:
wordList = loadWords() #loadWords could be a list of words
playHand({'n':1, 'e':1, 't':1, 'a':1, 'r':1, 'i':2}, wordList, 7)
I'm expecting the output to be:
Current Hand: n e t a r i i
Enter word, or a "." to indicate that you are finished:
However, it displays the following:
n e t a r i i
Current Hand: None
Enter word, or a "." to indicate that you are finished:
Don't know where I'm going wrong.
Note: I'm not allowed to make any changes to the first 2 functions.
displayHand() doesn't return anything, so the default None is returned. When you call it, it prints the output directly.
If you are not allowed to alter displayHand(), you need to print your label first, then call the function:
print("Current Hand: ", end='')
displayHand(hand)
The end='' removes the newline print() would normally write.

count the number of words in a string separated by spaces and/or punctuation marks

Can someone help please .
I want to create a program that can count the number of words in a string separated by spaces and/or punctuation marks. You should only count words where the vowels and consonants are alternating. A word can not have two consecutive vowels or consonants. Single letter words are not counted. Ignore anything in the file that is not a vowel or a constant. Replace anything that is not in the alphabet with a single space. Case sensitivity of each letter does not matter.
Alphabet to use
Vowels -- A E I O U Y
Consonants -- B C D F G H J K L M N P Q R S T V W X Z
Input:
A string eg "Hello there great new world"
Output:
Number of desired words found in the input string above. eg 1
Sample:
"Welcome to Radix!!!" == 2 (to Radix)
"Everybody, thanks you for trying this out." == 2 (everybody for)
"Hello there great new world" == 1 (new)
"Mary,had,a,little,lamb" == 2 (Mary had)
This is a homework, isn't it?
Try this regular expression:
\b[aeiouy]?([bcdfghjklmnpqrstvwxz][aeiouy])*[bcdfghjklmnpqrstvwxz]?\b
It will find all words with alternating vowels/consonants. Beware, it will pass single-letter words as well, filter them out subsequently. And run it with ignore-case flag.
import string,re
VOWELS=[x.lower() for x in "A E I O U Y".split(" ")]
CONSONANTS = [x.lower() for x in "B C D F G H J K L M N P Q R S T V W X Z".split(" ") ]
FILE_PATH = 'sentences.txt'
PUNCT = '[ %s]'% string.punctuation #[ !"#$%&'()*+,-./:;<=>?#[\]^_`{|}~]
def isAlt(word):
#True if word is valid
word=word.lower() #Non-case-sensitive
for x in range(len(word)-1):
if not (word[x] in VOWELS and word[x+1] in CONSONANTS)and not(word[x+1] in VOWELS and word[x] in CONSONANTS):
#Sorry about that condition, I can probably return that whole line
return False
return True
for line in open(FILE_PATH,'r'):
out=re.split(PUNCT,line.strip())
out=[x for x in out if x and len(x)>1 and isAlt(x)]
print(len(out))
This scans the file and for each line finds the valid words and prints out the number of words that match your conditions. You can change len(out) to out for the list instead of the number.

Python novice: Setting limits for multiple integers taken as input

I'm trying to write a program that would take an input of 3 numbers (i, j & k) in a single line separated by spaces, with limits for each number being from 1 to 1000 (inclusive). I need some advice regarding how to set the limit for all three numbers at once. Thanks in advance! My buggy code is below:
i, j, k = input("Please input 3 numbers between 1 and 1000:").split()
i, j, k = int(i), int(j), int(k)
if i, j, k >1000 or i, j, k <1:
print ("Please try again")
else:
print ("Thank you!")
Use Python's any() and all() functions for testing conditions on large number of values. In your case it should look like
if all([1<=x<=1000 for x in [i,j,k]]):
print ("Thank you!")
else:
print ("Please try again")

Counting the number of capital letters in an input?- in python

On python how do you make a program that asks for an input and the program works out the number of capital letters in that input and output the number of capital letters?
Loop through the string and use .isupper() to check if the letter is uppercase and increment the count. Finally print the count.
inpt = raw_input('Enter something: ')
c = 0
for i in inpt:
if i.isupper():
c += 1
print "No. of uppercase letters: ", c
len(filter(lambda x:isupper(x),list(input("Enter String"))))
Try the following function:
def capital(word):
num = 0
for char in word:
if char.isupper():
num+=1
return num
And incorporate it as such:
word = input('Enter: ')
print capital(word)

Resources