Function check Caesar cipher Python? - python-3.x

I have to words. They have tehe same lenght. I want to check if the second word is encoded with a Caesar cipher correctly. I wrote a simple function, but sometimes it works but sometimes not. I dont know what is wrong.
This may code:
def check_Ceaesar(word1, word2):
t=word1
s=word2
k=ord(s[0])-ord(t[0])
if k>0:
k=ord(s[0])-ord(t[0])
else: k=26+(ord(s[0])-ord(t[0]))
for i in range(1,len(t)):
if ord(t[i])<ord(s[i]):
temp=ord(s[i])-ord(t[i])
else: temp=26+(ord(s[i])-ord(t[i]))
if temp!=k:
return "YES"
break
else:
return "NO"

You should return 'NO' if temp is not equal to k instead, and wait for the loop to finish before returning 'YES'.
Change:
for i in range(1,len(t)):
if ord(t[i])<ord(s[i]):
temp=ord(s[i])-ord(t[i])
else: temp=26+(ord(s[i])-ord(t[i]))
if temp!=k:
return "YES"
break
else:
return "NO"
to:
for i in range(1,len(t)):
if ord(t[i])<ord(s[i]):
temp=ord(s[i])-ord(t[i])
else: temp=26+(ord(s[i])-ord(t[i]))
if temp!=k:
return "NO"
return "YES"
You can also check that the differences between the ordinary numbers of the corresponding letters of the two words after taking the modulo of 26 are of only one number by converting them to a set and checking that the length of the set is 1:
def check_Ceaesar(word1, word2):
return len({(ord(a) - ord(b)) % 26 for a, b in zip(word1, word2)}) == 1

Related

Adding sums in a loop while also using the def function

I am working on a function that sums up the amount of positive and negative numbers a user inputs. It has to be in a loop and has to have two functions(on for pos, one for neg) to return True or False. I have tried everything and am so lost and don't even know where to start anymore. This is what I have so far:
pos = 0
neg = 0
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
while num > -100 or num < 100:
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
if num > 100 or num < -100:
print("Please only enter integers between -100 to 100")
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
elif num == 0:
print("Here is your summary: ")
print("You entered: ", pos, "positives number(s) and", neg, "negative number(s)")
def if_positive(pos):
if num > 0:
pos = pos + 1
def if_negative(neg):
if num < 0:
neg = neg + 1
if_positive(pos)
if_negative(neg)
Every time I try something, I get one part correct and then the other wrong. Python for Everybody hasn't helped at all and I've done hours of research and nothing helps. Please help me. Every time I post a question on here it gets removed! I have no idea what I'm doing wrong, I am just trying to ask a simple question :( So I will try for the third time!
Lets do it as follow
Lets have while loop then if the num is zero just break it otherwise check the conditions
I have added two lists but if you just count how many numbers positive and negative then you don't need lists you can use integer count variables
postive_numbers =[]
negative_numbers =[]
while True:
num = int(input("Please enter a positive or negative number. Or 0 to quit\n Enter the number: "))
if num>100 or num < -100:
print("Please only enter integers between -100 to 100")
continue
if num == 0:
print("Here is your summary:\n ")
print("You entered: \npositives number(s) {} \nnegative number(s){} ".format(len(postive_numbers),len(negative_numbers)))
break
elif num< 0:
negative_numbers.append(num)
else:
postive_numbers.append(num)
If I had to guess, I'd say your questions are being removed because they sound like school assignments, and people tend to sour a little at the idea of people going to StackOverflow to have others do their homework for them. That said, it seems to me like you've put in a good-faith effort based on what you've already written, and there's nothing wrong with asking for help when you don't understand something after trying to figure it out yourself.
Try this:
def is_positive(number):
"""
This could be shortened to simply:
`return number > 0`
"""
if number > 0:
return True
else:
return False
def is_negative(number):
"""
Similarly, this could be shortened to:
`return number < 0`
"""
if number < 0:
return True
else:
return False
n_positive = 0
n_negative = 0
while True:
num_entered = int(input("Please enter a positive or negative number. Or 0 to quit"))
if not -100 < num_entered < 100:
print("Please only enter integers between -100 to 100")
elif is_positive(num_entered):
# this is a shortcut for `n_positive = n_positive + 1`
n_positive += 1
elif is_negative(num_entered):
n_negative += 1
else:
break
print("Here is your summary:")
# this is equivalent to what you had in your question, but uses "f-strings",
# which were implemented in Python 3.6 and are super convenient
print(f"You entered {n_positive} positive number(s) and {n_negative} negative number(s)")
A few extra notes you might find helpful:
if not -100 < num_entered < 100: is equivalent to if num > 100 or num < -100:, but just a cleaner way of writing it
while True is an idiom in Python that essentially means "keep looping forever until I break out of it or exit the program." From the code you had written, it seems like you want to keep allowing the user to input numbers until they enter "0 to quit". That's the condition upon which you want to break out of the loop.
"def" itself isn't a function -- def is a keyword that defines a function, which is a snippet of code that performs a single task that can be re-used later. You said your two functions needed to return True or False. In Python, the return keyword causes a function to exit and "return" the value specified.
This is why you're able to use those pre-defined functions directly in the the if and elif statements later. You can think of the way "if" works as taking the code between if and : and evaluating it. If it evaluates to True, then the block of code inside (i.e., indented under) the if statement is executed and any elif or else statements you may or may not have after that are skipped. Or, if it evaluates to False, then Python "moves on," and if you have an elif statement after the if, it repeats the same process there. Finally, if neither or if or elif blocks evaluate to True and you have an else block, that code is run.
This is a very long way of saying that in your case, the logical flow is: "if the number isn't between -100 and 100, remind the user of the acceptable range of values. Otherwise, if the number is_positive, add 1 to the running count of positive numbers entered. Or, if the number is_negative, add 1 to the count of negative numbers. Otherwise, the only remaining possibility is that the number is 0, so the user is finished entering numbers and we should break out of the loop and show them their summary.
Hope this helps! Feel free to comment with any other questions you have.

A simple question about Collatz Function,Why this is a unreachable code?

I'm a new learner of python, when I try to write a Collatz function I find that pycharm shows me one line is unreachable. I wonder why the function can't run the code
def Collatz(numBer):
if numBer%2 == 0:
return numBer//2
else:
return 3*numBer+1
print(numBer) #this code is unreachale
print('Please input the number:')
numBer = int(input())
while numBer != 1:
Collatz(numBer)
print(Collatz(numBer)) #because the former code are unreachable,so I write this to print the results
numBer = Collatz(numBer)
All code within the same scope below a return statement is unreachable because the function will finish its execution there. In your case you are returning the result so there is no need to rerun the function again to print it. Just take it in a variable and use it:
def Collatz(numBer):
if numBer%2 == 0:
return numBer//2
else:
return 3*numBer+1
print('Please input the number:')
numBer = int(input())
while numBer != 1:
numBer = Collatz(numBer)
print(numBer)
Hello welcome to Stack Overflow!
The reason why the print is "unreachable" is because of the return before the print. return ends a control flow so any code after the return is disregarded. Basically, the control flow goes like this (based on your function):
"Is the numBer divisible by 2?"
"If yes, then give me the integer division of that number and 2"
"Otherwise, give me the 3*number + 1"
If you wanted to print the number before you return it, it would be best to store it first into a variable and then return that variable, like so:
def Collatz(numBer):
if Collatz % 2 == 0:
value = numBer // 2
else:
value = 3 * numBer + 1
print(value)
return value

finding largest and smallest number in python

I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))

How to verify if input is not a letter or string?

I'm writing a basic program in IDLE with a menu choice with options from 1 to 4.
If a user input anything else then a number, it gives a ValueError: invalid literal for int() with base 10: 'a'
How can I check if the input is not a letter, and if it is, print a error message of my own?
def isNumber (value):
try:
floatval = float(value)
if floatval in (1,2,3,4):
return True
else:
return False
except:
return False
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
while isNumber(number_choice) == False:
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
else:
print('You have chosen ' + number_choice + '.\n')
This will check if the number is 1,2,3 or 4 and if not will ask the user to input the number again until it meets the criteria.
I am slightly unclear on whether you wish to test whether something is an integer or whether it is a letter, but I am responding to the former possibility.
user_response = input("Enter an integer: ")
try:
int(user_response)
is_int = True
except ValueError:
is_int = False
if is_int:
print("This is an integer! Yay!")
else:
print("Error. The value you entered is not an integer.")
I am fairly new to python, so there might very well be a better way of doing this, but that is how I have tested whether or not input values are integers in the past.
isalpha() - it is a string method which checks that whether a string entered is alphabet or words(only alphabets, no spaces or numeric) or not
while True:
user_response = input("Enter an integer : ")
if user_response.isalpha():
print("Error! The value entered is not an integer")
continue
else:
print("This is an integer! Yay!")
break
This program is having infinite loop i.e. until you enter an integer this program will not stop. I have used break and continue keyword for this.

Python -Need to match DNA from 2 inputs

Currently working on a project to do the following:
Ask user to enter a first strand of dna
Checks to make sure that the strand is valid (A,C,T and G, lower case is also accepted).
After first strand is entered, the program asks for the second strand and checks if is
complementary
A is Complementary of T, T to A. and G is complementary with C and C to G.
Result should be:
Enter first sequence of dna: ATGC
Enter second sequence of dna:TACG
"They are Complementary"
Enter first sequence of dna: GTC
Enter second sequence of dna:GAC
not complementary.
Enter second sequence of dna: exit
exiting program.....
#Code starts here:
def compare_DNA_lenght(dna1,dna2):
if len(dna1) != len(dna2):
print ('Input sequence incorrect')
def complement(sequence):
""" (str) -> str"""
replace={'a':'t','t':'a','c':'g','g':'c'}
complement=''
print('in the loop',sequence)
for i in sequence:
complement=complement+replace[i]
print(sequence)
while (dna1 != "exit" and dna2 != "exit"):
dna1= input('Please enter your first sequence:')
dna2= input('Please enter your second sequence:')
dna1=dna1.lower()
dna2=dna2.lower()
if (dna1 =="exit" and dna2 =="exit"):
print ("Exiting program")
if(dna2 == complement):
print ("They are complementary")
elif(dna2 != complement):
print ("Not a complementary strand")
print (complement)
You should read up on how while loops work in Python. In the meantime, here's the basic structure of one:
while condition:
code
Keep in mind that you should always make sure that condition will eventually evaluate to false, otherwise you'll end up in an infinite loop, causing your program to hang. A simple example would be printing the numbers 1 through 5:
i = 1
while (i <= 5):
print(i)
i = i + 1
Eventually, i is 6, so the while loop will not execute the code inside, because 6 is not equal to or less than 5.
Before your while loop, you need to declare your dna1 and dna2 variables so your program doesn't throw an error saying it can't find those variables.
dna1= input('Please enter your first sequence:')
dna2= input('Please enter your second sequence:')
while (dna1 != "exit" and dna2 != "exit"):
Additionally, you don't need to check if both strings say "exit" to break out of the loop. Just one should suffice.
if (dna1 =="exit" or dna2 =="exit"):
On an unrelated note, it's considered good practice to spell your method names correctly. "compare_DNA_lenght" should probably be "compare_DNA_length".
Check valid DNA strand
So the first thing you need to do is to check whether or not the used input is a valid DNA. Since a DNA only contains A,T,G and C we can check the validity by creating a formula that checks for A,T,G and C. True if these are present and False if any letters other than A,T,G and C.
def is_dna_strand(x):
"""
(str) -> bool
Returns True if the DNA strand entered contains only the DNA bases.
>>> is_dna_strand("AGTC")
'True'
>>> is_dna_strand("AGHFJ")
'False'
"""
a=x.lower()
i=0
while i != (len(a)):
if ((a[i])!= "a") and ((a[i])!="t")and((a[i])!="c")and((a[i])!="g"):
return False
i+=1
return True
Check the base pairs
def is_base_pair(x,y):
"""
(str,str) -> bool
Returs true if two parameters form a base pair.
>>> is_base_pair("A","T")
'True'
>>> is_base_pair("A","G")
'False'
"""
a=x.lower()
b=y.lower()
if a=="a" and b=="t":
return True
elif a=="t" and b=="a":
return True
elif a=="c" and b=="g":
return True
elif a=="g" and b=="c":
return True
else:
return False
Check whether it's a valid DNA or not.
So the final step in this process is check the validity of the entire molecule.
def is_dna(x,y):
"""
(str,str) -> bool
Returs true if the two strands form a properly base-paired DNA.
>>> is_dna("AAGTC","TTCAG")
'True'
>>> is_dna("TCGA","TCAG")
'False'
"""
i=0
j=0
if len(x)==len(y):
while i < (len(x)):
b=x[i]
c=y[i]
i=i+1
return is_base_pair(b,c)
else:
return False

Resources