First, I randomly choose a number
And then, using input from others, I ask them for the numbers
And finally, the closest number to my number should be displayed
How do I write this code?
who can help me ?
import random
randomNumber = random.randint(1,10)
players = 5
userGuesses = []
for i in range(players):
userGuesses.append(int(input("Enter your guess here: ")))
closestNumber = userGuesses[0]
for number in userGuesses:
difference = abs(number-randomNumber)
if abs(closestNumber-randomNumber) > difference:
closestNumber = number
print(closestNumber)
This should work - you can change the 'players' variable to the number of users that are competing.
My answer is in the form of a game in the terminal, where you write your answers:
from random import randint
number_of_players = int(input('Enter number of players: '))
minimum = int(input('Enter minimum number: '))
maximum = int(input('Enter maximum number: '))
answer = randint(minimum, maximum) # draw a secret random number
answers = {}
for player in range(1, number_of_players + 1): # collect answers from players
answers[str(player)] = int(input(f'Player {player} answer: '))
winner, value = min(answers.items(), key=lambda x: abs(answer - x[1])) # search closest answer
print(f'Answer is {answer}. Winner is player {winner} with {value}.')
Related
Write a program in Python that reads a sequence of integer inputs (data) from the user and then prints the following results:
the total of all the inputs
the smallest of the inputs
the largest of the inputs
the number of even inputs
the number of odd inputs
the average of all of the inputs
You do not know how many numbers the user will want to type in, so you must ask her each time if she has another number to add to the sequence.
So far this is my code but I want to know if there's a way without using the sys module
import sys
# declare a variable largest which has smallest integer value
# -sys.maxsize gives the smallest integer value,you can also use any smallest value
largest = -sys.maxsize
# declare a variable smallest, that is assigned with maximum integer value
smallest = sys.maxsize
# declare variables total to store the sum of all numbers
total = 0
# option variable is to store the user option Y or N
option = 'y'
# declare variables to count odd, even and totalCount
evenCount = 0
oddCount = 0
totalCount = 0
print("This program will calculate statistics for your integer data.")
# run the loop when the user enters y or Y
while option == 'y' or option == 'Y':
# take input of number
number = int(input("Please type a number: "))
# add the number to total
total = total + number
# increase totalCount
totalCount = totalCount + 1
# calculate smallest
if number < smallest:
smallest = number
# calculate largest
if number > largest:
largest = number
# calculate count of even and odd numbers
if number % 2 == 0:
evenCount = evenCount + 1
else:
oddCount = oddCount + 1
option = input("Do you have another number to enter? ")
# calculate average
average = total / totalCount
# print the output
print("\nThe total of your numbers is:", total)
print("The smallest of your numbers is:", smallest)
print("The largest nof yout numbers is:", largest)
print("The number of even numbers is:", evenCount)
print("The number of odd numbers is:", oddCount)
print("The average of your numbers is:", average)
The answer to "can it be done?" when it comes to programming is almost always "yes."
In this case, you can test if you're on the first loop iteration and set smallest and largest accordingly.
E.g.
option = 'y'
first_loop = True
while option.lower() == 'y':
x = int(input("Please type a number: "))
if first_loop:
smallest = x
first_loop = False
elif x < smallest:
smallest = x
option = input("Do you have another number to enter? ")
print(f"Smallest number entered is {smallest}")
You might also collect the input numbers into a list.
option = 'y'
inputs = []
while option.lower() == 'y':
x = int(input("Please type a number: "))
inputs.append(x)
option = input("Do you have another number to enter? ")
Now if you have all of the input numbers in inputs, then calculating a minimum and maximum is just min(inputs) and max(inputs).
Interesting approach, when I have problems like this I use float('inf') or float('-inf'). Can easily be worked into your approach.
The question is: In Bagels, a deductive logic game, you must guess a secret three-digit number based on clues. The game offers one of the following hints in response to your guess: “Pico” when your guess has a correct digit in the wrong place, “Fermi” when your guess has a correct digit in the correct place, and “Bagels” if your guess has no correct digits. You have 10 tries to guess the secret number.
I am new in Python. Any suggestions are appreciated:
#Generating a random 3-digit number
import random
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
random_number=random_with_N_digits(3)
print(random_number)
#Making a dictionary From the integers of the number
#Indexes as Keys and integers as values
rand_list = [int(x) for x in str(random_number)]
rand_dictionary=dict(zip(range(len(rand_list)),rand_list))
#rand_dictionary
#For loop for 10 tries
for i in range(10):
input_num = int(input('Please guess that three digit number : '))
#Validating the input
if input_num < 999 and input_num > 100:
#Making dictionary for the inputted number in similar way like the random number
input_list = [int(x) for x in str(input_num)]
input_dictionary = dict(zip(range(len(input_list)), input_list))
if random_number == input_num:
print("Your answer is correct!!")
break
elif [i for (i, j) in zip(rand_list, input_list) if i == j]:
print("Fermi")
if set(rand_list) & set(input_list):
print("Pico")
elif set(rand_list) & set(input_list):
print("Pico")
else:
print("Bagels")
else:
print("This is not a valid three digit number. Please try again.")
print("The test is finished.")
I don't know if i got what you wanted but try this:
#Generating a random 3-digit number
import random
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
random_number=random_with_N_digits(3)
print(random_number)
#Making a dictionary From the integers of the number
#Indexes as Keys and integers as values
rand_list = [int(x) for x in str(random_number)]
rand_dictionary=dict(zip(range(len(rand_list)),rand_list))
#rand_dictionary
#For loop for 10 tries
i = 0
while i < 10:
try:
input_num = int(input('Please guess that three digit number : '))
#Validating the input
if input_num < 999 and input_num > 100:
#Making dictionary for the inputted number in similar way like the random number
input_list = [int(x) for x in str(input_num)]
print(input_list)
input_dictionary = dict(zip(range(len(input_list)), input_list))
if input_num == random_number:
print("Your answer is correct!!")
break
elif set(rand_list) & set(input_list):
correct_place = 0
for j in range(0, len(input_list)):
if rand_list[j] == input_list[j]:
correct_place += 1
correct_digits = len(set(rand_list) & set(input_list))
print("Fermi "*correct_place + "Pico "*(correct_digits - correct_place))
else:
print("Bagels")
i += 1
else:
print("This is not a valid three digit number. Please try again.")
except:
print("Not a valid input")
print("The test is finished.")
This question already has answers here:
Generate 'n' unique random numbers within a range [duplicate]
(4 answers)
Closed 2 years ago.
I have to ask the user how many numbers they want to generate and then i can generate integers according to them in the range of 0 to a 100. If the user wants 5 numbers I have to generate 5 random numbers, but have no clue how.
input("How many numbers should the string consist of? ") #The user gives a number
for i in range(4): # I used a 4 but its going to be the users input
print(random.randint(0, 100)) #The integers will print
Afterwards I have to calculate the total of all the integers generated,
The total is: sum of generated integers.
from random import randint
def random_generate(count: int):
for _ in range(count):
yield randint(0, 100)
for num in random_generate(20):
print("random number is:", num)
Change the for i in range loop iteration count to the number of integers the user wants:
num = int(input("How many numbers should the string consist of? "))
for i in range(num):
print(random.randint(0, 100)) #The integers will print
Afterwards I have to calculate the total of all the integers generated, The total is: sum of generated integers.
Add a variable to count all the integers, in this case it is count:
num = int(input("How many numbers should the string consist of? "))
count=0
for i in range(num):
randomnumber = random.randint(0, 100)
print(randomnumber)
count += randomnumber
print(count)
Looks like i posted at the same time as Daniil
To add to Daniils answer:
You could also do a validation for when the user does not enter an integer it gets promted again.
import random
while True:
try:
user_input_str = input("How many numbers should the string consist of?") #The user gives a number
num = int(user_input_str)
break
except ValueError:
print(f"{user_input_str} is not an integer, please enter an integer)")
total_sum = 0
for i in range(num): # I used a 4 but its going to be the users input
random_int = random.randint(0, 100)
print(f"#{i} Random int: {random_int}")
total_sum = total_sum + random_int
print(f"Total sum: {total_sum}")
I need to modify my program so it includes a prime read with a loop. the document is saying for my getNumber function it should ask the user only to input a number between 2 and 30, the getScores function should ask the user to input a number between 0 and 100. it they don't get a number between that it should tell them re enter a number. I don't get any errors when running the program but not sure what I am missing in order to make sure its running properly to include the re enter a number part. here is the code:
# main
def main():
endProgram = 'no'
print
while endProgram == 'no':
totalScores = 0
averageScores = 0
number = 0
number = getNumber(number)
totalScores = getScores(totalScores, number)
averageScores = getAverage(totalScores, averageScores, number)
printAverage(averageScores)
endProgram = input('Do you want to end the program? yes or no ')
while not (endProgram != 'yes' or endProgram != 'no'):
print('Enter yes or no ')
endProgram = input('Do you want to end the program? (yes or no )')
# this function will determine how many students took the test
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
# this function will get the total scores
def getScores(totalScores, number):
for counter in range(0, number):
score = int(input('Enter their score: '))
return totalScores
while score < 0 or score > 100:
print('Please enter a number between 0 and 100')
score = int(input('Enter their score: '))
return score
# this function will calculate the average
def getAverage(totalScores, averageScores, number):
averageScores = totalScores / number
return averageScores
# this function will display the average
def printAverage(averageScores):
print ('The average test score is: ', averageScores)
# calls main
main()
First suggestion is to change this:
number = int(input('How many students took the test: '))
reason is that, as it is written, this takes the user input and implicitly assumes that it can be cast to an int. What happens if the user enters "hello, world!" as input? It is necessary to take the user input first as a string, and check if it would be valid to convert it:
number = input("enter a number:")
if number.isdecimal():
number = int(number)
Next, the function as a whole has some structural problems:
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
number is passed in as an argument to getNumber. Then the name number is reassigned to the result of reading the user input, and returned... Make sure you understand what the return statement does: once the control flow reaches a return statement, that function terminates, and it sends that value back to the caller. So your while loop never runs.
Maybe this would work better:
def getNumber():
while number := input("enter a number"):
if number.isdecimal() and int(number) in range(0, 31):
return int(number)
print('Please enter a number between 2 and 30')
I have a list that gets generated when a user inputs a random number they want. I want to add the sum together with out using sum(). How could I do this?
xAmount = int(input("How man numbers would you like to input: "))
numList = []
for i in range(0, xAmount):
numList.append(int(input("Enter a number: ")))
print(numList)
From here
Store the sum in a temp variable. Keep adding the input numbers to the temp variable:
xAmount = int(input("How man numbers would you like to input: "))
numList = []
numList_sum = 0
for i in range(0, xAmount):
inputted_number = int(input("Enter a number: "))
numList_sum += inputted_number
numList.append(inputted_number)
print(numList)
print(numList_sum)
You don't need a list at all.
xAmount = int(input("How man numbers would you like to input: "))
result = 0
for i in range(0, xAmount):
result = result + int(input("Enter a number: "))
print(result)
To sum a list just iterate over the list, adding up the individual values:
num_total = 0
for value in numList:
num_total += value
You could also use reduce but this might not meet your h/w requirements either:
from functools import reduce
from operator import add
num_total = reduce(add, numList, 0)