Generating 5 unique numbers for a Powerball simulator - python

I wrote this from pseudo-code provided during class, and I've got most of it figured out. Only issue I'm running into is it's returning duplicate numbers for the first 5 'balls' and I can't at all figure out why. One of the lines in the pseudo-code I wasn't sure about was: "if that number is not in the main number sequence". I coded it like this:
if number != mainNumbers:
which could be the issue, but I'm not sure how else to code that.
from random import *
def drawing():
balls=0
mainNumbers=[]
while balls < 5:
number=randint(1,69)
if number != mainNumbers:
mainNumbers.append(number)
balls = balls + 1
mainNumbers.sort()
pBall=randint(1,26)
return mainNumbers, pBall
def main():
print("This program simulates a user defined number of Powerball drawings\n")
runs = int(input("What's the total number of drawings? "))
print()
count = 1
while count <= runs:
balls, pBall = drawing()
print("Drawing: {0} - The numbers are: {1} and the Powerball is: {2}".format(count, balls, pBall))
count = count + 1
main()

Related

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")

Take input from the keyboard using a loop till the time the user presses 0 and print their average value on the screen

What this is supposed to do is:
To ask the user for numbers using while loop until they enter 0
when 0 is pressed we need to print the average of the numbers entered so far.
(Kindly help)
import statistics as st
provided_numbers = []
while True:
number = int(input('Write a number'))
if number == 0:
break
else:
provided_numbers.append(number)
print(f'Typed numbers: {provided_numbers}')
print(f'The average of the provided numbers is {st.mean(provided_numbers)}')
Take each number and print the average so far and stop it when input is zero, right?
s = 0
count = 0
while True:
num = int(input('Write a number: '))
if num == 0:
break
s += num
count += 1
print("Average so far:",(s/count))
Could you add a piece of code you have tried or sample input and output too?

Counting Heads and Tails in a coin flip program

For my assignment, I have to use Functions within Python to simulate a coin flip. I managed to get the coin flip to showcase heads and tales for the amount the user has inputted. However, for the next portion, I have to get the program to read how many times Heads and Tails appeared. The error I am getting is
'NameError: name 'heads' is not defined'.
import random
def main():
tosses = int(input("Please enter the amount of coin tosses:"))
coin(tosses)
count = 0
heads = 0
tails = 0
def coin(tosses):
for toss in range(tosses):
if random.randint(1, 2) == 1:
print('Heads')
heads += 1
count += 1
else:
print('Tails')
heads += 1
count += 1
print (heads)
print (tails)
main()
Problem
heads was defined out of the scope of the function coin.
Solution
Try defining the variables inside the function, then returning them. Note: the same had to be done with main.
import random
def main():
tosses = int(input("Please enter the amount of coin tosses:"))
coin(tosses)
heads, tails, count = coin(tosses)
return heads, tails
def coin(tosses):
count = 0
heads = 0
tails = 0
for toss in range(tosses):
if random.randint(1, 2) == 1:
print('Heads')
heads += 1
count += 1
else:
print('Tails')
tails += 1 # note you had this say heads before
count += 1
return heads, tails, count
heads, tails = main()
print(heads)
print(tails)
More on why this problem occurred
When you use def and create a new function, all of the variables in that function are accessible just to that function.
What was happening to you, is that you were trying to update the heads variable with heads += 1, but the function literally didn't know what the variable you were referring to is! (That variable was defined in main, and is only accessible from within the main function.)

print the out put of python program based on Permituation and combination

I write a program in python to find no of combinations of series
there is one dice which has 6 faces.
user input 2
then the out is shown is as no of count where two is come in combinations
ex if we throw dice for to get 2 as sum the maximum are two dice thrown are required
(1+1) and (2) so count is 2
if i throw for sum of 3, the out-put is
(1+1+1),(1+2),(2+1),(3) so count is 4 enter code here
if i throw for sum of 4 then the out put is
(1+1+1+1),(1+1+2),(1+2+1),(2+1+1),(2+2),(3+1),(1+3),(4) count is 8
I write the code is
# I am considering the Board is horizontal single line
def count_values(values,num):
for i in range(num):
print(values[i]," ",end='')
print('')
def print_list(out_put,values,num,count=0,show=False):
dice=6
if num == 0:
count_values(values,count)
out_put[0] += 1
elif num > 0:
for k in range(1,dice+1):
values[count] = k
print_list(out_put,values,num-k, count+1,show)
n=int(input('Enter A number'))
values=[0]*n
out_put=[0]
print_list(out_put,values,n)
print(out_put)
it shows out put for small inputs likes 10,20,30
but
i want the out put for 100 and 500 and 610 like inputs ,
but is get more time (around 5-6 hours still running) and the count of combination is more than 1145201564
still it is counting
any one has solution for this
Any one has any solution. for this
import numpy
def findway(m,n,x):
table = numpy.zeros((2,x+1))
for j in range(1,x+1):
table[1][j] = 1
for j in range(1,x+1):
for k in range(1,j):
table[1,j] += table[1][j-k]
print table[1][x]
n=input('Enter a number')
findway(6,1,n)
but here is also one problem, i want out put for 600 ,but it shows out-put in format (2.07475778444e+180)
but i want in integer format

Python: display the number of one's in any user given integer number

How do I display the number of one's in any given integer number?
I am very new to python so keep this in mind.
I need the user to input a whole number.
Then I want it to spit out how many one's are in the number they input.
i am using python 3.3.4
How would I be able to do this with this following code?
num = int(input ("Input a number containing more than 2 digits"))
count = 0
for i in range (0):
if num(i) == "1":
count = count + 1
print (count)
I don't know what i'm doing wrong
it gives me 'int' object is not callable error
Something like this:
Int is not iterable so you may need to convert into string:
>>> num = 1231112
>>> str(num).count('1')
4
>>>
str(num).count('1') works just fine, but if you're just learning python and want to code your own program to do it, I'd use something like this, but you're on the right track with the code you supplied:
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print(count)
Just to help you, here is a function that will print out each digit right to left.
def count_ones(num):
while num:
print(num % 10) # last digit
num //= 10 # get rid of last digit
num = 1112111
answer = str(num).count("1")
num = int(input (" Input a number to have the number of ones be counted "))
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print (' The number of ones you have is ' + str(count))
So i took the user input and added it to the correct answer since when i tried the answer from crclayton it didn't work. So this works for me.

Categories