I'm trying to create a lottery ticket generator. Lottery tickets in Norway can have 10 rows that you bet on. They contain each 7 numbers. The numbers you can choose from is 1-34. In total i can choose 70 numbers within this range of numbers, but i want every number to be picked two times(68) and two can be picked three times(total of 70 numbers). My program will only give me nine rows of numbers and i can't figure out what I'm doing wrong.
import random as r
# picks random number
def pickNumber():
number = r.randint(1, 34)
return number
# checks if number is in the list
def checkList(lst, number):
if not number in lst:
return True
return False
# checks the amount a number has occured
def checkNumber(lst, number):
my_set = None
if lst[number - 1] == 1:
return False
else:
lst[number - 1] += 1
my_set = set(lst)
if len(my_set) == 1:
for i in range(len(lst)):
lst[i] = 0
return True
# Run program
def main():
occured = []
for i in range(34):
occured.append(0)
ticket = []
counter = 1
while True:
row = []
while True:
number = pickNumber()
if checkList(row, number):
if checkNumber(occured, number):
row.append(number)
if len(row) >= 7:
break
ticket.append(row)
counter += 1
if counter == 10:
break
for i in range(len(ticket)):
print(ticket[i])
main()
(moving comment to answer)
Start with counter = 0. You check for 10 before processing the tenth row.
Related
I am making a piece of code that generates bingo cards. It makes sure that there are going to be 5 numbers on each horizontal row and that each vertical column has the numbers between 1-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, 70-79, and 80-90. However the list values never has anything appended to it, so it can never get to the next loop. Here is the code:
def generate_nums(nums): #nums looks like this: [[],[],[]] - which is how it is inputed
for i in range(0, len(nums)):
while True:
values = []
Min = 1
Max = 9
counter = 0
for j in range(0, len(nums[i])):
value = random.randint(0, 1)
values.append(value)
if value == 1:
counter += 1
if counter == 5:
for item in values:
if item == 1:
nums[i].append(random.randint(Min, Max))
else:
nums[i].append(" ")
if Min == 1:
Min = 10
else:
Min += 10
if Max == 79:
Max = 90
else:
Max += 10
break
#Function call
if __name__ == "__main__":
nums = [[],[],[]]
print(generate_nums(nums))
Any help is appreciated, I am only looking to improve my knowledge as I am doing computer science GCSE and I love python and the challenges it presents, though I don't know what to do here.
Thanks!
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")
My task is to:
"Write a program that will keep asking the user for some numbers.
If the user hits enter/return without typing anything, the program stops and prints the average of all the numbers that were given. The average should be given to 2 decimal places.
If at any point a 0 is entered, that should not be included in the calculation of the average"
I've been trying for a while, but I can't figure out how to make the programs act on anything I instruct when the user hits 'enter' or for it to ignore the 0.
This is my current code:
count = 0
sum = 0
number = 1
while number >= 0:
number = int(input())
if number == '\n':
print ('hey')
break
if number > 0:
sum = sum + number
count= count + 1
elif number == 0:
count= count + 1
number += 1
avg = str((sum/count))
print('Average is {:.2f}'.format(avg))
You're very close! Almost all of it is perfect!
Here is some more pythonic code, that works.
I've put comments explaining changes:
count = 0
sum = 0
# no longer need to say number = 1
while True: # no need to check for input number >= 0 here
number = input()
if number = '': # user just hit enter key, input left blank
print('hey')
break
if number != 0:
sum += int(number) # same as sum = sum + number
count += 1 # same as count = count + 1
# if number is 0, we don't do anything!
print(f'Average is {count/sum:.2f}') # same as '... {:.2f} ...'.format(count/sum)
Why your code didn't work:
When a user just presses enter instead of typing a number, the input() function doesn't return '\n', rather it returns ''.
I really hope this helps you learn!
Try this:
amount = 0 # Number of non-zero numbers input
nums = 0 # Sum of numbers input
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
nums+=int(number)
amount += 1
print(round(nums/amount,2)) # Print out the average rounded to 2 digits
Input:
1
2
3
4
Output:
2.5
Or you can use numpy:
import numpy as np
n = []
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
n.append(int(number))
print(round(np.average(n),2)) # Print out the average rounded to 2 digits
A list can store information of the values, number of values and the order of the values.
Try this:
numbers = []
while True:
num = input('Enter number:')
if num == '':
print('Average is', round(sum(numbers)/len(numbers), 2)) # print
numbers = [] # reset
if num != '0' and num != '': numbers.append(int(num)) # add to list
Benefit of this code, it does not break out and runs continuously.
I have the following assignment:
In this chapter you saw an example of how to write an algorithm that determines whether
a number is even or odd. Write a program that generates 100 random numbers, and keeps
a count of how many of those random numbers are even and how many are odd.
This is how far I've been able to get, I can get the 100 numbers, but I can't figure out how to total up the odd and evens. This is supposed to include a value returning boolean function as well.
All we're allowed to use is loops, if-elif-else, functions, and other basic things.
import random
NUMBER_LIST = [random.randint(0,1000)]
def main():
for numbers in range(100):
number = print(NUMBER_LIST)
number
is_even(number)
print('The total amount of even numbers is', even_count)
print('The total amount of odd numbers is', 100 - even_count)
def is_even(number):
even_count = 0
for number in NUMBERS_LIST:
if (number % 2):
even_count += 1
return even_count
main()
EDIT:
I'm not supposed to use a List, so if theres a way to do it without, let me know!
import random
def main():
numberList = [] # create an empty list, to add 100 random ints to
for i in range(100):
numberList.append(random.randint(1,1000)) # add a random int
# now, numberList has 100 random numbers in it
# keep track of how many odd numbers
oddCount = 0
# loop through numberList
for number in numberList:
if number%2 == 1: # number is odd
oddCount += 1
evenCount = 100 - oddCount # if a number is not odd, it is not even
print("There are", oddCount, "odd numbers, and", evenCount, "even numbers")
Okay, now that we have that hard-coded version, let's try a more flexible way that allows you to specify as many things as possible:
def main(numNumbers, smallestNumber, biggestNumber):
numberList = []
for i in range(numNumbers):
numberList.append(random.randint(smallestNumber, biggestNumber))
oddCount = 0
for number in numberList:
if number%2: # oh look, I didn't have to do the `== 1` part
oddCount += 1
evenCount = numNumbers - oddCount
print("There are", oddCount, "odd numbers, and", evenCount, "even numbers")
import random
NUMBER_LIST = [random.randint(0,1000)]
even = 0;
odd = 0;
for numbers in range(100):
if (numbers%2 == 1):
odd = odd+1
if (numbers%2 == 0):
even = even+1
print('number of evens is: ',even)
print('number of odds is: ',odd)
So you can just do this sort of thing.
from random import randrange
even = 0
for i in range(100):
num = randrange(1000)
if num % 2 == 0:
even += 1
print('There were {0} even numbers and {1} odd numbers.'.format(even, 100-even))
You can do this without a list, but let's do that since your problem may require so.
First of all, note that your code just creates a list with one random number inside it. If you want to populate the list with 100 random numbers, you must do something similar to this:
NUMBER_LIST = []
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
i += 1
Then, you check if the number is even, with number % 2 == 0 (That is, the remainder of the division of number by 2 is 0. this will return either true or false) and increment the respective counter:
NUMBER_LIST = []
# initialize both counters
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
Then, you just need to print the counts:
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
The full code would then be:
import random
NUMBER_LIST = []
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
print("The numbers were: " + str(NUMBER_LIST))
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
And without the list:
import random
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
#!/usr/bin/env python3
import random
def main(n=100):
NUMBER_LIST = [random.randint(0,1000) for x in range(0,n)]
odds = len(list(filter(lambda x: x % 2, NUMBER_LIST)))
print("Odd Numbers: {}\nEven Numbers: {}".format(odds, n-odds))
if __name__ == "__main__":
main()
I am in the same class! This code worked for me.
import random
def main ():
counter = 1
even_numbers = 0
odd_numbers = 0
while counter < 101:
a = random.randint(1,100)
if a % 2 == 0:
even_numbers += 1
else:
odd_numbers += 1
counter += 1
if counter == 101 :
reveal_total(even_numbers, odd_numbers)
def reveal_total(even_numbers, odd_numbers):
print("This many evens : ", even_numbers)
print("This many odds : ", odd_numbers)
main()
I'm new to python and I'm trying to create a coinflip loop which will keep flipping and counting the number of flips until the number of heads = the number of tails, where it will stop and print the total number of flips it took to reach that. I'm trying to get the results in order to work on my maths coursework, but I cannot seem to figure out how to get it to stop or print the results, and when I do it prints 0. Here is the code I have so far:
import random
heads = 1
tails = sum(random.choice(['head', 'tail']) == 'tail'
count = 0
while True:
coinresult = random.randint(1, 2) if heads == tails:
break
print("The number of flips was {count}".format(count = heads + tails))
not sure what is going on with your indentation but try this:
import random
heads = 0 #initialize the count variables
tails = 0
while True:
coinresult = random.randint(1, 2) #flip coin
if coinresult == 1: #if result = 1 then increment heads counter
heads += 1
elif coinresult == 2: #if result = 2 then increment tails counter
tails += 1
if heads == tails: #check if counts are equal and break loop if they are
break
print("The number of flips was {count}".format(count = heads + tails))
import itertools as it
import random
def flips():
while True:
yield (random.getrandbits(1)<<1) - 1
def cumsum(seq):
s = 0
for i in seq:
s += i
yield s
def length(seq):
n = 0
for _ in seq:
n += 1
return n
print("The number of flips was {}".format(length(it.takewhile((0L).__cmp__, cumsum(flips())))))
I think this will be a nice implementation
import random
s = 0
iteration = 0
while True:
coin = random.sample([-1,1], 1)[0]
s = s + coin
iteration = iteration + 1
if s == 0:
break
print(iteration)