Python -Need to match DNA from 2 inputs - python-3.x

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

Related

If condition is "None" the loop starts somewhere else than I want

I try to code my first little text based role play game.
The first step would be to enter your character name and then type "y" if you are fine with the name and "n" if you want to change the name.
So I want that the Program is asking you again to enter "y" or "n" if you fatfinger a "g" for example. And only let you reenter your name if you type "n"
Instead of these the program will let you reenter your name directly if you enter "g".
I already tried to do a "while True or False" loop around the _yesorno function.
Here is the code:
main.py
from Classes.character import character
from functions.yesorno import _yesorno
#character
char = character()
while True:
print("please enter a name for your character")
char.set_name(input())
print("Your name is: " + char.name + ". Are you happy with your choice? Type 'y' for yes, 'n' for no.")
if _yesorno(input()):
break
else:
continue
_yesorno.py
def _yesorno(input:str)->bool:
if input == "y":
return True
elif input == "n":
return False
else:
print("please use y for yes and n for no")
return None
As I am pretty new I would be happy, if you can explain your answer newbie friendly and not only with "your logic is wrong" :D
Thanks in advance!
if None is equal to while if False. Python have dynamic typing for types.
To check wrong input you can do things like:
def _yesorno(input_:str)->bool:
while input_ not in ['y', 'n']:
print("please use y for yes and n for no")
input_ = input()
return input_ == 'y'
That code check input directly instead itself. input_ not in ['y', 'n'] that part check if your input_ is one of array element.
After user enter 'y' or 'n' the function return proper result.
I would approach this with a pair of recursive functions. One that ran until the user gave a valid response, the other until a name was properly set.
Note that in many cases, recursive functions can be rewritten as loops and since python lacks tail call optimization, some people will prefer not using recursion. I think it is usually fine to do so though.
def get_input_restricted(prompt, allowed_responses):
choice = input(prompt)
if choice in allowed_responses:
return choice
print(f"\"{choice}\" must be one of {allowed_responses}")
return get_input_restricted(prompt, allowed_responses)
def set_character_name():
prospective_name = input("Enter a name for your character: ")
print(f"Your name will be: {prospective_name}.")
confirmation = get_input_restricted("Are you happy with your choice (y|n)? ", ["y", "n"])
if "y" == confirmation:
return prospective_name
return set_character_name()
character_name = set_character_name()
print(f"I am your character. Call me {character_name}.")
The reason why an input of 'g' is making the user reenter their name is because 'None' is treated as False therefore the loop will continue... you could try a simple if statement in a while loop and disregard your _yesorno function with
while(True):
print("please enter a name for your character")
charName = input()
while(True):
print("Your name is: " + charName + ". Are you happy with your choice? Type 'y' for yes, 'n' for no.")
yesorno = input()
if(yesorno == 'y' or yesorno == 'n'):
break
if(yesorno == 'y'):
break
char.set_name(charName)
print("and your name is {0}".format(char.name))

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.

Function check Caesar cipher Python?

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

Mastermind Python Using "ABCDEF"

Mastermind Game using "ABCEF"I dont know how to check whether it is partial correct. I have to use red to mean correct letter and position. I use white to mean correct letter.
import random
def play_one_round():
N_code=''.join(random.sample("ABCDEF",4))
print (N_code)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess= 1
while N_code != guess and count_guess < 10:
check(N_code,guess)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess=count_guess + 1
print("This is your",count_guess, "guess")
if guess==N_code:
print('r') #Here I have if the code and guess are equal print r, which mean its the right letters in the right order.
def check(N_code,guess):
result=['r' if c1==c2 else c2 for c1,c2 in zip(guess, N_code)]
for index, char in enumerate(guess):
if result[index] !='r':
if char in result:
result[result.index(char)]='w'
print(result)
def Master_m():
print("Welcome to Mastermind!\n")
print("Start by Choosing four letters")
play_one_round()
answer=input("Play Again? ")
if answer[0]=='y':
Master_m()
Master_m()
I wrote this ages ago but it will do the trick
import random
import itertools
def start():
""" this function is used to initialise the users interaction with the game
Primarily this functions allows the user to see the rules of the game or play the game"""
print ('Mastermind, what would you like to do now?\n')
print ('Type 1 for rules')
print ('Type 2 to play')
path = input('Type your selection 1 or 2: ')
if path == '1':
print ('Great lets look at the rules')
rules()
elif path == '2':
print('Great lets play some Mastermind!\n')
begingame()
start()
else:
print('that was not a valid response there is only one hidden option that is not a 1 or a 2')
start()
def rules():
"""This just prints out the rules to the user."""
print ('The rules are as follows:\n')
print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n')
print ('2)You will have 12 attempts to guess the correct number.\n')
print ('3)Whites represent a correct number that is not in the correct order\n')
print ('4)Reds represent a correct number in the correct order.\n')
print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n')
print ('6)to WIN you must guess the 4 numbers in the correct order.\n')
print ('7)If you run out of guesses the game will end and you lose.\n')
print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.')
start()
def makeRandomWhenGameStarts():
"""A random 4 digit number is required this is created as its own
variable that can be passed in at the start of the game, this allows the user
to guess multiple times against the one number."""
#generate a 4 digit number
num = random.sample(range(1,9), 4)
#roll is the random 4 digit number as an int supplied to the other functions
roll = int(''.join(map(str,num)))
return roll
def begingame():
"""This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is
passed in anbd then an exception handling text input is used to ask the user for their guees """
print ('please select 4 numbers')
#bring in the random generated number for the user to guess.
roll = makeRandomWhenGameStarts()
whiteResults = []
redResults = []
collectScore = []
guessNo = 0
#setup the while loop to end eventually with 12 guesses finishing on the 0th guess.
guesses = 12
while (guesses > 0 ):
guessNo = guessNo + 1
try:
#choice = int(2468) #int(input("4 digit number"))
choice = int(input("Please try a 4 digit number: "))
if not (1000 <= choice <= 9999):
raise ValueError()
pass
except ValueError:
print('That was not a valid number, you lost a turn anyway!')
pass
else:
print ( "Your choice is", choice)
#Use for loops to transform the random number and player guess into lists
SliceChoice = [int(x) for x in str(choice)]
ranRoll = [int(x) for x in str(roll)]
#Take the individual digits and assign them a variable as an identifier of what order they exist in.
d1Guess = SliceChoice[0:1]
d2Guess = SliceChoice[1:2]
d3Guess = SliceChoice[2:3]
d4Guess = SliceChoice[3:4]
#combine the sliced elements into a list
playGuess = (d1Guess+d2Guess+d3Guess+d4Guess)
#Set reds and whites to zero for while loop turns
nRed = 0
nWhite = 0
#For debugging use these print statements to compare the guess from the random roll
# print(playGuess, 'player guess')
# print(ranRoll,'random roll')
#Use for loops to count the white pegs and red pegs
nWhitePegs = len([i for i in playGuess if i in ranRoll])
nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)])
print ('Oh Mastermind that was a good try! ')
#Take the results of redpegs and package as turnResultsRed
TurnResultsRed = (nRedPegs)
#Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite
TurnResultsWhite = ( nWhitePegs - nRedPegs) #nWhite-nRed
#Create a unified list with the first element being the guess number
# using guessNo as an index and storing the players choice and results to feedback at the end
totalResults = ( guessNo,choice , TurnResultsWhite ,TurnResultsRed)
# collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses
collectScore.append(totalResults)
#End the while loop if the player has success with 4 reds
if nRed == (4):
print('Congratulations you are a Mastermind!')
break
#Return the results of the guess to the user
print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n')
#remove 1 value from guesses so the guess counter "counts down"
guesses = guesses -1
print ('You have', guesses, "guesses left!")
#First action outside the while loop tell the player the answer and advise them Game Over
print('Game Over!')
print('The answer was', roll)
#At the end of the game give the player back their results as a list
for x in collectScore:
print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites')
if __name__ == '__main__':
start()
When you are stuck, decompose into smaller chunks and test those. Focusing on check, you can check whether a guess letter exactly matches the code via its index and whether its in the code at all with in. Here is a self-contained example. Notice that I've pulled out everything except the problem at hand.
If this works for you, I suggest writing a self-contained example of your next problem, test it, and if you are still stuck, post that as a new question.
def check(N_code, guess):
print('code', N_code, 'guess', guess)
result = []
# enumerate gives you each letter and its index from 0
for index, letter in enumerate(guess):
if N_code[index] == letter:
# right letter in right position
vote = 'red'
elif letter in N_code:
# well, at least the letter is in the code
vote = 'white'
else:
# not even close
vote = 'black'
# add partial result
result.append('{} {}'.format(letter, vote))
# combine and print
print(', '.join(result))
check('ABCD', 'ABCD')
check('DEFA', 'ABCD')

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.

Resources