why is the print statement on "total bones" not running? - python-3.x

Im trying to get the print statement to run without it having to run each time the "bones" iteration runs. it should be after the two guesses have been made.
[ ]Complete Foot Bones Quiz
foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
"intermediate cuneiform", "medial cuneiform"]
def foot_bones_quiz(guess, answer):
total_bones = 0
for bones in answer:
total_bones += bones.count(bones)
if guess.lower() == bones.lower():
return True
else:
pass
return False
**print("Total number of identified bones: ", total_bones)**
guess = 0
while guess < 2:
guess = guess + 1
user_guess = input("Enter a bone: ")
print("Is ", user_guess.lower(), " a foot bone?", foot_bones_quiz(user_guess, foot_bones))
print("Bye, Thanks for your answers.")

foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
"intermediate cuneiform", "medial cuneiform"]
# Declare total as global variable rather than in the loop, as we are calling this loop twice, and this will not store the count from previous loop iteration
total_bones = 0
def foot_bones_quiz(guess, answer):
global total_bones
for bones in answer:
# First bones is a string, so bones.count(bones) is just giving 1 all the time, so you have to increase the count, only when a bone is actually identified
if guess.lower() == bones.lower():
total_bones += bones.count(bones)
return True
else:
pass
return False
guess = 0
while guess < 2:
guess = guess + 1
user_guess = input("Enter a bone: ")
print("Is ", user_guess.lower(), " a foot bone?", foot_bones_quiz(user_guess, foot_bones))
print("Bye, Thanks for your answers.")
# Now we actually print, how many guesses were correct out of the 2 made
print("Total number of identified bones: ", total_bones)
Tested it on Ubuntu, python 3.6, attaching the screen shots as well.

Related

How to separate if statements and exit code to execute the program properly?

I was doing beginner python projects as I am a beginner still. I came upon this guessing game project and Wanted to do a Yes or No type of question on whether the user wants to take part in guessing or not.
If user enters Yes, they take part, if anything else ("No" or anything the program exits the code)
However I seem to be doing something wrong, when I enter Yes, the program exits the code anyway. What am I doing wrong? Thank you all,
Here is the code. I am only posting a part of it, where I most probably get the error.
import random
guess = 0
name = input("Hello what is your name?: ")
num = random.randint(1 , 50)
response = input("Well hello there " + name + " I have a number between 1-50, Want to play? You have 10 tries")
if response != "Yes" and response != "yes":
exit()
else:
while guess <= 10:
guess += 1
take = int(input("Guess a number!"))
if take == num:
print("You win! You guessed " + str(guess) + " times")
elif take > num:
print("Too high!")
elif take < num:
print("Thats too low!")
elif take >= guess:
print("You lose... The number was "+ num)
if response != "Yes" or "yes":
equates to this:
if response != "Yes" # which resolves to False when response is a 'no'
OR
"yes" # which is a non-empty string, which Python equates to True.
So basically, you code is equivalent to:
if False OR True:
and thus it always runs the exit() function.
In addition to the items noted above, the if statement should be checking both conditions and thus it should be using and instead of using or, as shown below (HT to #tomerikoo):
What you need is TWO separate tests in the if statement:
if response != "Yes" and response != "yes":
If you believe that you might have other versions of yes answers OR if you think that doing a comparison against a general sequence of terms might be easier to understand, you can also do this test instead:
if response in ['Yes', 'yes', 'y', 'Y', 'YES']:
Debugging:
For folks who are new to programming, in Python, it is sometimes fast and easy to use a simple print() function to rapidly evaluate the current state of a variable, to ensure that it really points at the value you believe it does. I added a print statement below with a comment. It would be beneficial to see what value is associated with response. (Caveat: there are professional tools built into Python and into code editors to help with watching variables and debugging, but this is fast and easy).
import random
guess = 0
name = input("Hello what is your name?: ")
num = random.randint(1 , 50)
response = input("Well hello there " + name + " I have a number between 1-50, Want to play? You have 10 tries")
print(response) # checking to see what was actually returned by the
# input() method
if response != "Yes" and response != "yes":
print(response) # check to see what the value of response is at
# the time of the if statement (i.e. confirm that
# it has not changed unexpectedly).
exit()
else:
while guess <= 10:
guess += 1
take = int(input("Guess a number!"))
if take == num:
print("You win! You guessed " + str(guess) + " times")
elif take > num:
print("Too high!")
elif take < num:
print("Thats too low!")
elif take >= guess:
print("You lose... The number was "+ num)
In python "non-empty random str" is True and empty string "" is False for conditional usages. So,
if "yes":
print("foo")
prints 'foo'
if "":
print("foo")
else:
print("bar")
prints 'bar'
In your case you want program to exit if response is not "Yes" or not "yes". You have two conditions evaluated in if statement:
response == "Yes" --> False
"yes" --> True
if 1 or 2 --> True --> so exit.
so it should be like that:
if response not in ["Yes", "yes"]:
exit()
else:
do_something()

Problem with guessing game, player has infinite guesses

I'm trying to build a guessing game in Python. You have a limited number of around 5 guesses/lives and if you run out of them, you will lose the game. (for reference: it uses both random(for random number) and termcolor(for color) modules)
Program:
from termcolor import colored
import random
def lostit():
print(colored("Sorry! You lost!", "red"))
decideto = input("Try again? (yes/no):")
while decideto not in ("yes", "no"):
decideto = input(colored("Invalid response:", "red"))
if decideto is "yes":
guessnum()
elif decideto is "no":
print("Bye, bye.")
def guessnum():
numtoguess = random.randint(1, 10)
print(colored("I've picked a random number from 0 to 9! Guess what it is! You've got 3 hints and 5 guesses!", "green"))
usernum = input(colored("Try to guess it: ", "cyan"))
guesses = 5 # The limit
usertries = 0 # Chances
if guesses >= usertries:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
elif guesses == usertries:
lostit()
print(colored("Great job! You guessed it!", "green"))
So far, it works when you type in the right number. However, I've experienced problems with the lives/guesses part. I've tried to set a limit to how many tries the player has, however the program seems to ignore this, meaning the player basically has infinite lives. How do I solve this?
print(colored("Sorry! You lost!", "red"))
decideto = input("Try again? (yes/no):")
should likely be indented.
This is also strange. You don't have a variable called lostit, but you have a loop with that variable:
while lostit not in ("yes", "no"):
The logic on your code is simply wrong. See this loop:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
You are looping while the guess isn't equal to number you selected.
I would reorg. Main function defines the number to guess, how many guesses they get, it loops while two things are true (guess isn't equal to number and guess count is less than total number of guesses). Also note the scope of variables.
from termcolor import colored
import random
def guessnum():
numtoguess = random.randint(1, 10)
print(colored("I've picked a random number from 0 to 9! Guess what it is! You've got 3 hints and 5 guesses!", "green"))
usernum = input(colored("Try to guess it: ", "cyan"))
guesses = 5 # The limit
usertries = 1 # Chances, but they already used a guess
while (usernum != numtoguess) and (guesses >= usertries):
again = input("Try again? (yes/no):")
while again not in ("yes", "no"):
again = input(colored("Invalid response choose yes/no:", "red"))
if decideto is "yes":
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1
elif decideto is "no":
print("Bye, bye.")
return
if usernum == numtoguess:
print(colored("Great job! You guessed it!", "green"))
if guesses >= usertries:
print(colored("Sorry! You lost!", "red"))
Take a look at this section:
if guesses >= usertries:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
elif guesses == usertries:
lostit()
First of all, your if and elif are not mutually exclusive: let's say guesses is equal to usertries. It will enter to first if (since you use >=) and not the second elif (because it entered the first one). In other words, Elif code is not reachable.
Seoncd, your while loop is inside the if. It keeps running until you guess the right number, and only then compare your guess with "lives". You should substitute the statements to check the lives inside the loop:
while guesses >= usertries:
usernum = input(colored("Wrong! Guess again: ", "red"))
if usernum != numtoguess:
usertries += 1
# User is wrong. We add one to our counter
else
# user is right. Do something to break the loop
# When we reach here, we ended loop: means user lost
lostit()
The logic is: as long as user has guesses, ask him for another number. compare the number: if he is right, do something. else, keep loop.

Why does my solution to problem 3 of the CodeJam 2020 Qualification Round not work?

I would like to receive help in understanding why my solution to Problem 3 of the Google CodeJam 2020 Qualifier does not work.
Link to problem: https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/000000000020bdf9
My solution:
High-level overview:
take input
figure out if the given input is impossible by sorting according to start times and then checking if more than 2 subsequent activities are 'active' at once (which is impossible)
if it is, output accordingly; if it isn't, proceed with the procedure below
arbitrarily assign the first person: in my solution I choose Cameron (C).
next, since we know that a solution exists, and the array I iterate through is sorted according to start times, if the very next activity interval (chronologically) overlaps in its duration with the current, assign it to the person who is not currently busy. This is purely because a solution exists, and it clearly cannot be the current person, so it must be the other.
moreover, if the very next activity interval (chronologically) does not overlap with the current activity, then assign it to the person who is currently busy (because he will not be busy for the next activity)
in addition, quoted directly from the problem's official analysis: "If an assignment is possible, there cannot be any set of three activities that pairwise overlap, so by the contrapositive of the the previous argument, we will be able to assign the activity to at least one of Jamie or Cameron at every step."
At this moment, I believe that these arguments suffice to show that my logic is valid, although my code evidently does not always produce the correct answer. I would greatly appreciate any help on this, since I have spent hours trying to debug, un-reason, or find a counter-example to my code to no avail. I have included my code, for reference, below.
Code:
for p in range(int(input())):
s = int(input())
l = []
for i in range(s):
l.append(list(map(int, list(input().split()))))
unsort = l.copy()
l = sorted(l, key=lambda tup: (tup[0],tup[1]))
enumerated = list(enumerate(unsort))
enumerated.sort(key=lambda x: x[1][0])
impossible = False
endings = sorted([(x[1], False) for x in unsort])
startings = sorted([(x[0], True) for x in unsort])
total = sorted(endings + startings, key=lambda tup: (tup[0], tup[1]))
size = 0
for i in total:
if i[1] == True:
size += 1
else:
size -= 1
if size > 2:
impossible = True
def overlap(a,b):
if not max(a[0], b[0]) >= min(a[1], b[1]):
return True
else:
return False
ans = "C"
def opp(a):
if a == "C":
return "J"
else:
return "C"
if impossible == True:
print("Case #" + str(p+1) + ": " + "IMPOSSIBLE")
else:
for i in range(0, s-1):
if overlap(l[i], l[i+1]) == True:
ans = ans + opp(ans[len(ans)-1])
else:
ans = ans + opp(opp(ans[len(ans)-1]))
#the stuff below is to order the activity assignments according to input order
key_value = [(ans[i], l[i]) for i in range(s)]
fans = ""
for i in range(s):
for j in range(s):
if enumerated[j][0] == i:
fans = fans + key_value[j][0]
print("Case #" + str(p + 1) + ": " + fans)

Python error in while loop

I am coding an impossible quiz game, and it doest work. I want the program to exit when the var fails is equal to 3.
Instead, when you enter a wrong answer three times, the program loops rather quitting.
print("Welcome to impossible quiz")
print("")
print("You get 3 fails then you're out")
print("")
startcode = int(input("Enter 0 to continue: "))
fails = 0
if startcode != 0:
exit(1)
print("Welcome")
print("")
print("Level one")
L1ans = input("1+1= ")
while L1ans != "window":
print("incorect")
fails = fails + 1
L1ans = input("1+1= ")
if fails = 3:
exit(1)
if fails == 3:
should do the job
Your logic is a bit convoluted, and you have a syntax error. Try this:
fails = 0 # Set your failure flag
correct = False # Set your correct flag
while not correct: # if not correct loop
answer = input("1+1= ") # get the user's answer here
correct = answer == "window" # check for correctness
if not correct: # Handle incorrect case
print("Incorrect.")
fails += 1
if fails > 3: # quit if we've looped too much. > is better than == for this
exit()
print("Correct!")
Note that this is easily encapsulated in a class that can handle any question:
def ask_question(question, answer, fails) {
correct = False # Set your correct flag
while not correct: # if not correct loop
answer = input(question) # get the user's answer here
correct = answer == answer # check for correctness
if not correct: # Handle incorrect case
print("Incorrect.")
fails += 1
if fails > 3: # quit if we've looped too much. > is better than == for this
exit()
print("Correct!")
return fails
}
fails = 0
fails = ask_question("1+1= ", "window", fails)
fails = ask_question("Red and earth is", "Macintosh", fails)
Welcome to Stackoverflow!
I can only see 1 problem with your code, so your were nearly there!
Your if statement needs to have 2 equal symbols.
if fails == 3:
exit(1)

How can you compare frequency of letters between two words in python?

I'm trying to create a word guessing game, after each guess the computer should return the frequency of letters in the right place, however it is this part that I have been unable to manage to get working. Can anyone help me?
import random
def guess(secret,testWord):
return (len([(x, y) for x, y in zip(secret, testWord) if x==y]))
words = ('\nSCORPION\nFLOGGING\nCROPPERS\nMIGRAINE\nFOOTNOTE\nREFINERY\nVAULTING\nVICARAGE\nPROTRACT\nDESCENTS')
Guesses = 0
print('Welcome to the Word Guessing Game \n\nYou have 4 chances to guess the word \n\nGood Luck!')
print(words)
words = words.split('\n')
WordToGuess = random.choice(words)
GameOn = True
frequencies = []
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
Guesses += 1
print(Guesses)
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('Congragulations, You Won!')
GameOn = False
else:
print(correctLength, '/', len(WordToGuess), 'correct')
if Guesses >= 4:
GameOn = False
print('Sorry you have lost the game. \nThe word was ' + WordToGuess)
In your guess function, you are printing the value, not returning it. Later, however, you try to assign something to correctLength. Just replace print by return, and your code should work.
Update to answer question in comments:
I think a very easy possibility (without a lot of changes to your code posted in the comment) would be to add an else clause, such that in case that the input is empty, you return directly to the start of the loop.
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
if len(currentguess) <=0:
print('Sorry you must enter a guess')
else:
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('statement')
GameOn = False
elif Guesses <= 0:
GameOn = False
print('statement')
else:
Guesses = Guesses -1
print('statement')
print('statment')

Resources