Check if condition matches in python - python

Having trouble figuring out my list comprehension in python. I have 3 conditions that I'm looking for, and I know how to do two of them, but one of the conditions doesn't seem to work right.
My conditions are:
If all the numbers in my list are the same and they are all a specific number, then add points
If all numbers in my list are the same but they do not equal a specific number then do something else
If numbers in list do not match, but they equal a specific number than do something else.
I have 1 working, and I know how to do number 3, but I can't get number 2 working properly. No matter what numbers I put into my list (rolls), this condition still matches True. Can someone please assist? Here is my current code:
def check_conditions(rolls, round_number):
"""
Check if number on rolled die matches one of three conditions
:param rolls:
:param round_number:
:return round:
"""
round_score = ROUND_TOTAL
rolls = str(rolls)
bunco = all(roll == ROUND_NUMBER for roll in rolls)
mini_bunco = all(roll == roll[0] and roll != ROUND_NUMBER for roll in rolls)
if bunco == True:
print("BUNCO!")
round_score += 20
elif mini_bunco == True:
print("MINI-BUNCO!")
round_score += 5
else:
pass
return round_score
OUTPUT:
Starting Round Number 1
You rolled: [2, 3, 3]
MINI-BUNCO!
Points this round: 5

Something like this should get you there...
rolls = [5,5,5,5,5,5]
specificNum = 6
if len(set(rolls)) == 1:
if rolls[0] != specificNum:
print 'Do something'

#imports
import random
#variables
Roll_1_return = False
Roll_2_return = False
round_score = ROUND_TOTAL
#assuming you only want to roll twice
def Rolls():
Roll_1 = random.randrange(1, 10)
Roll_2 = random.randrange(1, 10)
While True:
if Roll_1 == 3:
Roll_1_return = True
return Roll_1_return
break
else:
break
While True:
if Roll_2 == 7:
Roll_2_return = True
return Roll_2_return
break
else:
break
Rolls()
if Roll_1_return == True:
print('Roll 1 is correct!')
round_score + 25
else:
print('Roll 1 is incorrect..')
if Roll_2_return == True:
print('Roll 2 is correct!')
round_score + 25
else:
print('Roll 2 is incorrect..')
if round_score == 50:
print('You won $100!')
elif round_score == 25:
print('You won $50!')
else:
print('Too bad, you lost!')
If I understand correctly, this should give you what you need! If this is not what you wanted, plz do not downvote me! I tried my hardest to understand.

Related

How to only show the final result after adding or multiplying all natural numbers

It has been a week since I started to self-study python and I tried making a program that adds or multiplies all natural numbers and the problem is I want to only show the final result of all the sum or product of all natural numbers. How do I do it?
repeat = 'y'
a=0
while repeat.lower() == 'y':
result = 0
choice = 0
i=0
product = 1
num = int(input("Enter the value of n: "))
if num < 1 or num > 100 :
print('must be from 1-100 only')
repeat = input("\nDo you want to try again?Y/N\n>>> ")
continue
print('1. Sum of all natural numbers')
print('2. Product of all numbers')
choice = int(input("Enter choice: "))
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
while repeat.lower() == 'n':
print('\nthank you')
break
The program prints you all the numbers because the print statement is in a while loop, so it gets executed with each run of the loop. Just move the print function out of the while.
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
You have two problems. First, your print statements that print the results need to be un-indented by one step, so they are not PART of loop, but execute AFTER the loop. Second, you need to initialize product = 1 after the if choice == 2:. As a side note, you don't need that final while loop. After you have exited the loop, just print('Thanks') and leave it at that.
So the end of the code is:
if choice == 1:
while num > 0 :
result += num
num -= 1
print(' ',result)
if choice == 2:
product = 1
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
print('thank you\n')
I presume you'll learn pretty quickly how to do those with a for loop instead of a while loop.

hailstone program in python

i have to write a hailstone program in python
you pick a number, if it's even then half it, and if it's odd then multiply it by 3 and add 1 to it. it says to continue this pattern until the number becomes 1.
the program will need methods for the following:
accepting user input
when printing the sequence, the program should loop until the number 1.
print a count for the number of times the loop had to run to make the sequence.
here's a sample run:
prompt (input)
Enter a positive integer (1-1000). To quit, enter -1: 20
20 10 5 16 8 4 2 1
The loop executed 8 times.
Enter a positive integer (1-1000). To quit, enter -1: 30
30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
The loop executed 19 times.
Enter a positive integer (1-1000). To quit, enter -1: -1
Thank you for playing Hailstone.
right now i have this:
count = 0
def hailstone(n):
if n > 0
print(n)
if n > 1:
if n % 2 == 0:
hailstone(n / 2)
else:
hailstone((n * 3) + 1)
count = count + 1
i don't know what to do after this
Try to think in a modular way, make two functions: check_number() and user_call(). Check_number will verify if the current number in the loop is odd or even and the user_call() just wraps it to count how many times the loop did iterate.
I found the exercise in a great book called Automate Boring Stuff with Python, you have to check it out, if you don't know it already.
Here's my code. Try to use what serves you the best.
from sys import exit
def check_number(number):
if number % 2 ==0:
print(number // 2)
return(number // 2)
else:
print(number*3+1)
return number*3+1
def user_call(number):
count = 0
while number != 1:
count += 1
number = check_number(number)
return count
if __name__ == "__main__":
try:
number = int(input('Give a number \n'))
count = user_call(number)
print('count ',count)
except Exception as e:
exit()
you can use global
visit https://www.programiz.com/python-programming/global-keyword to learn more
import sys
res = []
def hailstone(number):
global res
if number > 1:
if number % 2 == 0:
res.append( number // 2 )
hailstone(res[len(res)-1])
else:
res.append(number * 3 + 1)
hailstone(res[len(res)-1])
return res
number = int(input('Enter a positive integer. To quit, enter -1: '))
if number <= 0 or number == 0:
print('Thank you for playing Hailstone.')
sys.exit()
else:
answers = hailstone(number)
for answer in answers:
print(answer)
print('The loop executed {} times.'.format(len(answers) + 1))
I used recursion to solve the problem.
Heres my code:
Edit: All criteria met
count = 0
list_num = []
def input_check():
number = int(input("Enter a positive integer (1-1000). To quit, enter -1: "))
if number >= 1 and number <= 1000:
hailstone_game(number)
elif number == -1:
return
else:
print("Please type in a number between 1-1000")
input_check()
def hailstone_game(number):
global count
while number != 1:
count += 1
list_num.append(number)
if number % 2 == 0:
return hailstone_game(int(number/2))
else:
return hailstone_game(int(number*3+1))
list_num.append(1) # cheap uncreative way to add the one
print(*list_num, sep=" ")
print(f"The loop executed {count} times.")
return
input_check()
Additional stuff that could be done:
- Catching non-integer inputs using try / except
Keep in mind when programming it is a good habit to keep different functions of your code separate, by defining functions for each set of 'commands'. This leads to more readable and easier to maintain code. Of course in this situation it doesn't matter as the code is short.
Your recursive function is missing a base/terminating condition so it goes into an infinite loop.
resultArray = [] #list
def hailstone(n):
if n <= 0: # Base Condition
return
if n > 0:
resultArray.append(n)
if n > 1:
if n % 2 == 0:
hailstone(int(n/2))
else:
hailstone((n * 3) + 1)
# function call
hailstone(20)
print(len(resultArray), resultArray)
Output
8 [20, 10, 5, 16, 8, 4, 2, 1]
Here's a recursive approach for the problem.
count=0
def hailstone(n):
global count
count+=1
if n==1:
print(n)
else:
if n%2==0:
print(n)
hailstone(int(n/2))
else:
print(n)
hailstone(3*n+1)
hailstone(21)
print(f"Loop executed {count} times")

Python: Cow And Bull Game

*Q.Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed the number in the wrong place is a “bull.”
Every time the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout the game and tell the user at the end.*
**Now, the problem is that I've made the program but it could generate any 4 - digit number, and that's when the problem arises. For example:
The generated number is 3568.
The user types: 3266
Then user gets 2 Cows And 2 Bulls.
But the user has no way of knowing which are the correct numbers in the number that he typed.
I want a function that can tell the user the numbers that he guessed right.
In the example, the program should tell the user that 3 and 6 are correct in the following places.**
import random
def compare_number(number, user_guess):
cowbull = [0, 0]
for i in range(len(number)):
if number[i] == user_guess[I]:
cowbull[1] += 1
else:
cowbull[0] += 1
return cowbull
if __name__ == "__main__":
playing = True
number = str(random.randint(1000, 10000))
guesses = 0
print("Let's Play A Game Of Cows And Bulls!")
print("I Will Generate A 4 Digit Number, And You Have To Guess The Numbers One Digit At A Time.")
print("For Every Number I The Wrong Place, You Get A Bull. For Every Number In The Right Place,
You Get A Cow.")
print("The Game Will End When You Get 4 Bulls.")
print("Type Exit At Any Prompt To Exit!")
while playing:
user_guess = input("Give Me The Best You Got!: ")
if user_guess.lower() == "exit":
break
cowbull_count = compare_number(number, user_guess)
guesses += 1
print(f"You Have {cowbull_count[1]} Cows, And {cowbull_count[0]} Bulls.")
if cowbull_count[1] == 4:
playing = False
print(f"You Win The Game After {guesses} Guess(es)!. The Number Was {number}.")
break
else:
print(f"Your Guess Isn't Quite Right, Tyr Again!.")
You can do something like this:
import random
def compare_number(number, user_guess):
cowbull = [0, 0, 0, 0]
for i in range(len(number)):
if number[i] == user_guess[i]:
cowbull[i] += 1
return cowbull
if __name__ == "__main__":
playing = True
number = str(random.randint(1000, 10000))
guesses = 0
print("Let's Play A Game Of Cows And Bulls!")
print("I Will Generate A 4 Digit Number, And You Have To Guess The Numbers One Digit At A Time.")
print("For Every Number I The Wrong Place, You Get A Bull. For Every Number In The Right Place, You Get A Cow.")
print("The Game Will End When You Get 4 Bulls.")
print("Type Exit At Any Prompt To Exit!")
while playing:
user_guess = input("Give Me The Best You Got!: ")
if user_guess.lower() == "exit":
break
cowbull_count = compare_number(number, user_guess)
guesses += 1
correct = sum(cowbull_count)
wrong = len(number) - correct
print(f"You Have {correct} Cows, And {wrong} Bulls.")
if correct == 4:
playing = False
print(f"You Win The Game After {guesses} Guess(es)!. The Number Was {number}.")
break
else:
print(f"Your Guess Isn't Quite Right, Try Again!.")
if correct >= 1:
print(str([user_guess[i] for i, x in enumerate(cowbull_count) if x == 1]) + " was correct!")
Changes made to your original code:
Instead of returning [numOfCorrect,numOfWrong], i returned [is 1 correct?, is 2 correct?, is 3 correct? is 4 correct?] // you need this to know which was right and which was wrong
the number of cows is = the number of correct which is equal to sum of 1's in cowbull_count //changed because of different return of compare_number
the number of bulls is = the number of wrong which is equal to number of digits - number of wrongs = len(numbers) - correct //changed because of different return of compare_number
if not all 4 digits were correct, show them which number they got correct // this is what you wanted
Sample run
You can replace your compare number function to print the index and value of the correct number.
def compare_number(number, user_guess):
cowbull = [0, 0]
for i in range(len(number)):
if number[i] == user_guess[I]:
cowbull[1] += 1
print("The number " + number[i] + " at index " + i " is correct")
else:
cowbull[0] += 1
print("The number " + number[i] + " at index " + i " is incorrect")
return cowbull
Add another method that return a list of positions: 4 element list, 0 if the user didn't guess a digit, 1 if he did. You can use it as you want in your function.
def digit_position(number, user_guess):
right_guesses = [0, 0, 0, 0]
for i in range(len(number)):
if number[i] == user_guess[i]:
right_guesses[i] = 1
return right_guesses
# Cow and Bull Game is a game in which User
# tries to guess the Secret code chosen by computer.
# We have 2 use cases i.e
# If Value in index of both User's and Computer's number are same than it is Cow.
# If Value Exists but not on same index as computer's than ita a Bull.
import random
# Following function generate a unique 4-digit number
def checkDuplication():
r = str(random.randint(1000, 9999))
for i in r:
if r.count(i) > 1:
return checkDuplication()
return r
# Following function check both number and returns Cow and Bull COUNTS.
def cowBullGame(human):
cow_count = bull_count = 0
for i in human:
if i in computer:
if human.count(i) > 1:
print('No Repeatative Numbers Allowed!')
return 0
if human.index(i) == computer.index(i): # Checking if both the value in index i are same or not
cow_count += 1
else:
bull_count += 1
print(str(cow_count)+' Cows, '+str(bull_count)+' Bulls')
return cow_count # Returning Cow_Count to check All Numbers are on right place.
computer = checkDuplication()
print(computer)
guesses = 1
# Infinite Loop till user gets 4 Cow_Counts
while True:
human = str(int(input('Guess a Number :')))
if cowBullGame(human) == 4:
print('Game Over. You made '+str(guesses)+' guesses')
break
guesses += 1

check if a number combination is found in a list of combinations

I am creating a program in Python simulating multiplication flash cards. I've gotten pretty far but I can't figure out how to not repeat combinations of numbers. How do I check if a pair of numbers has already been presented?
from __future__ import division
from itertools import combinations
import random
amountCorrect = 0
amountMissed = 0
comb = combinations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 2)
print("Type 0 at any time to exit and see your score.")
while True:
firstNumber = random.randint(1,12)
secondNumber = random.randint(1,12)
ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
if ans == 0:
break
elif ans == firstNumber * secondNumber:
amountCorrect += 1
else:
amountMissed += 1
totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems
if .9 < percentCorrect <= 1:
print("Great job, you are doing awesome!")
elif .7 <= percentCorrect <= .89:
print("You are doing well,keep it up.")
elif .5 <= percentCorrect <= .69:
print("You are half way to becoming a master.")
else:
print("Keeping practicing, you will be a master one day.")
In short, use a set to store the pairs of numbers you have already used. Here is some code. You never use combinations in your code so I removed it.
from __future__ import division
import random
amountCorrect = 0
amountMissed = 0
highestNumber = 12
print("Type 0 at any time to exit and see your score.")
used = set()
while True:
if len(used) == highestNumber ** 2:
break
while True:
firstNumber = random.randint(1,highestNumber)
secondNumber = random.randint(1,highestNumber)
pair = (firstNumber, secondNumber)
if pair not in used:
used.add(pair)
break
ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
if ans == 0:
break
elif ans == firstNumber * secondNumber:
amountCorrect += 1
else:
amountMissed += 1
totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems
if .9 < percentCorrect <= 1:
print("Great job, you are doing awesome!")
elif .7 <= percentCorrect <= .89:
print("You are doing well,keep it up.")
elif .5 <= percentCorrect <= .69:
print("You are half way to becoming a master.")
else:
print("Keeping practicing, you will be a master one day.")
I just created an empty set called used, and added a new inner loop. That loop test if the pair of numbers has already been used. If so, it just loops again and tries a new pair of numbers. I also added a variable to store the highest possible number, and test of the used set is full. I end the quiz if it is full. Without this, when all possibilities are tried the program will go into an infinite loop.
Note that this code will allow both 1,2 and 2,1. If you want to allow only one of those, add both (firstNumber, secondNumber) and (secondNumber, firstNumber) to the used set.

Python multiple number guessing game

I am trying to create a number guessing game with multiple numbers. The computer generates 4 random numbers between 1 and 9 and then the user has 10 chances to guess the correct numbers. I need the feedback to display as YYYY for 4 correct numbers guessed, YNNY for first and last number guessed etc. (you get the point). the code below keeps coming back saying IndexError: list index out of range.
from random import randint
guessesTaken = 0
randomNumber = []
for x in range(4):
tempNumber = randint(1, 9)
randomNumber.append(tempNumber)
Guess = []
Guess.append(list(input("Guess Number: ")))
print(randomNumber)
print(Guess)
if randomNumber[0] == Guess[0]:
print("Y")
elif randomNumber[1] == Guess[1]:
print("Y")
elif randomNumber[2] == Guess[2]:
print("Y")
elif randomNumber[3] == Guess[3]:
print("Y")
elif randomNumber[0] != Guess[0]:
print("N")
elif randomNumber[1] != Guess[1]:
print("N")
elif randomNumber[2] != Guess[2]:
print("N")
elif randomNumber[3] != Guess[3]:
print("N")
You need four guesses to match for random numbers, you can also shorted your code using a list comp:
from random import randint
guessesTaken = 0
randomNumber = []
Guess = []
for x in range(4):
tempNumber = str(randint(1, 9)) # compare string to string
randomNumber.append(tempNumber)
Guess.append(input("Guess Number: "))
print("".join(["Y" if a==b else "N" for a,b in zip(Guess,randomNumber)]))
You can also use enumerate to check elements at matching indexes:
print("".join(["Y" if randomNumber[ind]==ele else "N" for ind, ele in enumerate(Guess)]))
To give the user guesses in a loop:
from random import randint
guessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
while guessesTaken < 10:
guesses = list(raw_input("Guess Number: ")) # create list of four digits
check = "".join(["Y" if a==b else "N" for a,b in zip(guesses,randomNumber)])
if check == "YYYY": # if check has four Y's we have a correct guess
print("Congratulations, you are correct")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
Right now you're only asking the user for one guess, and appending the guess to the Guess list. So the Guess list has one element, but you're using Guess[1], Guess[2], etc., which of course results in the IndexError
I'll rearrange your code a bit, so it doesn't stray too far from what you've done.
from random import randint
guessesTaken = 0
randomNumbers = []
Guess = [] # Combine your guesses with your loop
for x in range(4):
tempNumber = randint(1, 9)
randomNumbers.append(tempNumber)
# This should be done four times too
# In Python 2, instead of this:
# Guess.append(input("Guess Number: "))
# do this:
Guess.append(int(raw_input("Guess Number: "))) # raw_input and pass to int
# in python 3, raw_input becomes input, so do this instead:
# Guess.append(int(input("Guess Number: ")))
print(randomNumbers)
print(Guess)
You can combine these in a loop to avoid the repetitive code:
if randomNumbers[0] == Guess[0]:
print("Y")
else:
print("N")
if randomNumbers[1] == Guess[1]:
print("Y")
else:
print("N")
if randomNumbers[2] == Guess[2]:
print("Y")
else:
print("N")
if randomNumbers[3] == Guess[3]:
print("Y")
else:
print("N")
Perhaps, to print your desired result e.g. YNNY, like this:
result = []
for index in range(4):
if randomNumbers[index] == Guess[index]:
result.append("Y")
else:
result.append("N")
print(''.join(result))
If you want terser code use Python's ternary operation:
result = []
for index in range(4):
result.append("Y" if randomNumbers[index] == Guess[index] else "N")
print(''.join(result))
Or use the fact that True == 1 and False == 0 as indexes:
result = []
for index in range(4):
result.append("NY"[randomNumbers[index] == Guess[index]])
print(''.join(result))

Categories