I'm trying to generate 20 random numbers in python and say whether they are odd or even, this is what I have so far:
import random
def main():
i = 0
num = 0
#while loop
while i<20:
#user enters input
num = random.randint(input("enter lowest number:\t"))
i = random.randint(input("enter highest number:\t"))
#if else
if num>=0 and num<=100:
num = num+i
i = i +1
print(num)
else:
print("error")
#for loop
for i in range(num):
main()
would someone be able to help me finish it as I'm completely lost
here is the question:
Write a program which generates 20 random integers and indicates whether each number is odd or even. The program should begin by asking the user to input two integers which will act as the range for the generation of 20 random integers.
use list comprehension
import random
lower = int(raw_input("enter lowest number:\t"))
greater = int(raw_input("enter highest number:\t"))
print [random.randint(lower, greater) for a in range(100)]
I would rather rewrite that function completely
import random
def main():
lower = int(raw_input("enter lowest number: "))
upper = int(raw_input("enter highest number: "))
for i in range(20):
num = random.randint(lower, upper)
print(num)
main()
I think you will be able to easily modify it to suite your needs :)
EDIT: As suggested, I rewrote the function so it wouldnt ask for lower and upper bound every step of for loop, but only once before entering the for loop. Which is much less annoying and probably the thing you wanted to do.
def odd_or_even(num):
if num % 2 == 0:
print(num, 'is even')
else:
print(num, 'is not even')
lst = [random.randint(lower, upper) for x in range(20)]
for num in lst:
print(even_or_odd(num))
Here is a working program but if you couldn't be bothered to figure this out I doubt you are going to enjoy this class very much as it's only going to get more difficult.
import random
import time
start = time.time()
for i in range(10000):
random.choice([i for i in range(1000)])
print 'random.choice()', time.time() - start
start = time.time()
for i in range(10000):
random.randint(0,1000)
print 'random.randint()', time.time() - start
start = time.time()
for i in range(10000):
int(random.random() * 1000)
print 'random.random()', time.time() - start
[out]:
random.choice() 0.849874973297
random.randint() 0.015105009079
random.random() 0.00372695922852
First ask the user the top and bottom numbers,
Then use a generator to get the numbers.
import random
def randnums(number, startnum=0, endnum=100):
for i in range(1, number + 1):
yield random.randint(startnum, endnum)
def getparams():
return int(input('Lowest number: ')), int(input('Highest number: '))
def main():
bottom, top = getparams()
nums = list(randnums(20, startnum=bottom, endnum=top))
for number in nums:
print(number, ',', sep='')
if __name__ == '__main__':
main()
Related
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?
I need to make a list of random numbers than separate each number, odd or even.
Here is my current progress.
import random
def main():
for x in range(20):
number=list(random.randint(1,101))
for number in number:
list=number
for x in list:
if (number % 2) == 0:
print("{0} is Even number".format(num))
else:
print("{0} is Odd number".format(num))
I think too much terms like number in number will make you confused, so I modified your code like this, I think this will help you to understand comprehensively.
import random
def main():
ls = [] #define a space list
ls_e = [] #even number
ls_o = [] #odd number
for x in range(20): #for loop 0-20
number=random.randint(1,101) #create random number between 1-101
ls.append(number) #put number into ls
print(ls)
for x in range(len(ls)): #for numbers in ls
if (ls[x] % 2) == 0: #check logic
print("{0} is Even number".format(ls[x]))
ls_e.append(ls[x]) #put into even list
else:
print("{0} is Odd number".format(ls[x]))
ls_o.append(ls[x]) #put into odd list
main()
Use this code.
import random
L_odd = []
L_even = []
for x in range(20):
number = random.randint(1, 101)
if number % 2 == 0:
L_even.append(number)
else:
L_odd.append(number)
In this code, append is a method to append element to the list (for example, L_even.append(number) means to append number to the list L_even)
As the comments from #Harshal Parekh and #PM 77-1, you need to know the importance of indent of Python, and I think you need to study python basic.
You could use list comprehension to keep it simple. Hope this helps!
from random import randint
rand_nums = [randint(0, 101) for i in range(20)]
rand_odds = [i for i in rand_nums if i % 2 == 1]
rand_evens = [i for i in rand_nums if i % 2 == 0]
print(rand_nums)
print(rand_evens)
print(rand_odds)
The program asks the user for a number N.
The program is supposed to displays all numbers in range 0-N that are "super numbers".
Super number: is a number such that the sum of the factorials of its
digits equals the number.
Examples:
12 != 1! + 2! = 1 + 2 = 3 (it's not super)
145 = 1! + 4! + 5! = 1 + 24 + 120 (is super)
The part I seem to be stuck at is when the program displays all numbers in range 0-N that are "super numbers". I have concluded I need a loop in order to solve this, but I do not know how to go about it. So, for example, the program is supposed to read all the numbers from 0-50 and whenever the number is super it displays it. So it only displays 1 and 2 since they are considered super
enter integer: 50
2 is super
1 is super
I have written two functions; the first is a regular factorial program, and the second is a program that sums the factorials of the digits:
number = int(input ("enter integer: "))
def factorial (n):
result = 1
i = n * (n-1)
while n >= 1:
result = result * n
n = n-1
return result
#print(factorial(number))
def breakdown (n):
breakdown_num = 0
remainder = 0
if n < 10:
breakdown_num += factorial(n)
return breakdown_num
else:
while n > 10:
digit = n % 10
remainder = n // 10
breakdown_num += factorial(digit)
#print (str(digit))
#print(str(breakdown_num))
n = remainder
if n < 10 :
#print (str(remainder))
breakdown_num += factorial(remainder)
#print (str(breakdown_num))
return breakdown_num
#print(breakdown(number))
if (breakdown(number)) == number:
print(str(number)+ " is super")
Existing answers already show how to do the final loop to tie your functions together. Alternatively, you can also make use of more builtin functions and libraries, like sum, or math.factorial, and for getting the digits, you can just iterate the characters in the number's string representation.
This way, the problem can be solved in a single line of code (though it might be better to move the is-super check to a separate function).
def issuper(n):
return sum(math.factorial(int(d)) for d in str(n)) == n
N = 1000
res = [n for n in range(1, N+1) if issuper(n)]
# [1, 2, 145]
First I would slightly change how main code is executed, by moving main parts to if __name__ == '__main__', which will execute after running this .py as main file:
if __name__ == '__main__':
number = int(input ("enter integer: "))
if (breakdown(number)) == number:
print(str(number)+ " is super")
After that it seems much clearer what you should do to loop over numbers, so instead of above it would be:
if __name__ == '__main__':
number = int(input ("enter integer: "))
for i in range(number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
Example input and output:
enter integer: 500
1 is super
2 is super
145 is super
Small advice - you don't need to call str() in print() - int will be shown the same way anyway.
I haven't done much Python in a long time but I tried my own attempt at solving this problem which I think is more readable. For what it's worth, I'm assuming when you say "displays all numbers in range 0-N" it's an exclusive upper-bound, but it's easy to make it an inclusive upper-bound if I'm wrong.
import math
def digits(n):
return (int(d) for d in str(n))
def is_super(n):
return sum(math.factorial(d) for d in digits(n)) == n
def supers_in_range(n):
return (x for x in range(n) if is_super(x))
print(list(supers_in_range(150))) # [1, 2, 145]
I would create a lookup function that tells you the factorial of a single digit number. Reason being - for 888888 you would recompute the factorial of 8 6 times - looking them up in a dict is much faster.
Add a second function that checks if a number isSuper() and then print all that are super:
# Lookup table for single digit "strings" as well as digit - no need to use a recursing
# computation for every single digit all the time - just precompute them:
faks = {0:1}
for i in range(10):
faks.setdefault(i,faks.get(i-1,1)*i) # add the "integer" digit as key
faks.setdefault(str(i), faks [i]) # add the "string" key as well
def fakN(n):
"""Returns the faktorial of a single digit number"""
if n in faks:
return faks[n]
raise ValueError("Not a single digit number")
def isSuper(number):
"Checks if the sum of each digits faktorial is the same as the whole number"
return sum(fakN(n) for n in str(number)) == number
for k in range(1000):
if isSuper(k):
print(k)
Output:
1
2
145
Use range.
for i in range(number): # This iterates over [0, N)
if (breakdown(number)) == number:
print(str(number)+ " is super")
If you want to include number N as well, write as range(number + 1).
Not quite sure about what you are asking for. From the two functions you write, it seems you have solid knowledge about Python programming. But from your question, you don't even know how to write a simple loop.
By only answering your question, what you need in your main function is:
for i in range(0,number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
import math
def get(n):
for i in range(n):
l1 = list(str(i))
v = 0
for j in l1:
v += math.factorial(int(j))
if v == i:
print(i)
This will print all the super numbers under n.
>>> get(400000)
1
2
145
40585
I dont know how efficient the code is but it does produce the desired result :
def facto():
minr=int(input('enter the minimum range :')) #asking minimum range
maxr=int(input('enter the range maximum range :')) #asking maximum range
i=minr
while i <= maxr :
l2=[]
k=str(i)
k=list(k) #if i=[1,4,5]
for n in k: #taking each element
fact=1
while int(n) > 0: #finding factorial of each element
n=int(n)
fact=fact*n
n=n-1
l2.append(fact) #keeping factorial of each element eg : [1,24,120]
total=sum(l2) # taking the sum of l2 list eg 1+24+120 = 145
if total==i: #checking if sum is equal to the present value of i.145=145
print(total) # if sum = present value of i than print the number
i=int(i)
i=i+1
facto()
input : minr =0 , maxr=99999
output :
1
2
145
40585
I am making a random number generator but I do not want the numbers over again. so for example
[1,2,3,4] is perfect -
[1,1,2,4] is not what I want because a number recurring.
I have looked on here and no one has the answer to the problem I am searching for, in my logic this should work but I do not know what I am doing wrong.
I am new to python and I saw a couple questions like mine but none with the same problem
import random, timeit
random_num = random.randint(1,10)
cont_randomized_num = random.randint(1,10)
tries = 0
start = timeit.default_timer()
num_guess = 0
stored_numbers = []
while cont_randomized_num != random_num:
if cont_randomized_num == stored_numbers:
cont_randomized_num = random.randint(1,10)
elif cont_randomized_num != stored_numbers:
print(num_guess)
stored_numbers.append(cont_randomized_num)
print(stored_numbers)
cont_randomized_num = random.randint(1,10)
tries +=1
print()
print()
stop = timeit.default_timer()
print(random_num)
print('Number of tries:',tries)
print('Time elapsed:',stop)
input('press ENTER to end')
I guess I did not make myself clear enough.
I want to generate a random number = ANSWER
I want a second number generated to try and match the ANSWER, if it is not the ANSWER then STORE it somewhere. If the second generated number is generated a second time and it is the same as the first time it was generated I want it to skip and generate a new one. Keep this going until the second generated number is equal to the first number generated.
I have figured it out (finally) here is the code that is not over complicated and have nothing to do with any answer or critique given! This is what I have been asking for this entire time.
import random
import timeit
start = timeit.default_timer()
stored_numbers = []
cont_random = random.randint(1,10)
random_num = random.randint(1,10)
times_guessed = 0
while random_num not in stored_numbers:
if cont_random in stored_numbers:
cont_random = random.randint(1, 10)
elif cont_random not in stored_numbers:
print(cont_random)
stored_numbers.append(cont_random)
cont_random = random.randint(1, 10)
times_guessed += 1
print('Answer has been guessed!')
print('Stored numbers',stored_numbers)
print()
print()
stop = timeit.default_timer()
print('Time elapsed:',stop)
print('Times guessed -', times_guessed)
print('The random number:',random_num)
input('Press ENTER to exit')
Use random.sample() instead of populating the list one by one (see docs):
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
random.sample(range(10), 5)
>>>> [5, 9, 1, 6, 3]
random.sample() needs to be fed a list (or any iterable, really) to choose a subset from. Here, I gave it a list of the first 10 numbers starting from 0.
Here is my solution, you can add more functionality to it if you want by adding more code in the loop.
import random, timeit
def main():
tries = 0
NUMBER_OF_RANDOMS = 4
stored_numbers = []
start = timeit.default_timer()
while len(stored_numbers) != NUMBER_OF_RANDOMS:
current = random.randint(1,10)
tries += 1
if current not in stored_numbers:
stored_numbers.append(current)
stop = timeit.default_timer() - start
print 'Number of tries:', tries
print 'Time elapsed:', stop
print stored_numbers
if __name__ == '__main__':
main()
Does this do what you were wanting? I believe you do unnecessarily complicated code.
I am suppose to set up a list with a range of 5 plugging in your own numbers and then finding the sum of those numbers. I am stuck on how to do the range.
import math
list(range(1, 5))
n = input("Enter a number: ")
range(1, 5)
#number.append(n)
print(n)
#print(len(number))
while(True):
n = (input("Enter a number: "))
#number.append
if(n == -1):
break;
for i in range(1, 5):
print(i)
#average = (len(number))
#average += (len(number))
print("Your average is: ")
Loop in range(5) appending each num the user enters then sum:
nums = []
for _ in range(5): # ask user to enter a num 5 times
n = int(input("Enter a number")) # get and cast input to int
nums.append(n) # append each num
print(sum(n)) # call sum on the list of 5 numbers
I presume by random you mean 5 numbers the user may enter.
You could use list comprehension:
randomNumbers = [int(input("enter a number")) for n in range(5)]
total = sum(randomNumbers)
average = sum(randomNumbers)/5
This will prompt the user to enter a number 5 times, each number will be added to the list
If you do just want to generate a list of random numbers as your title suggests:
>>>import random
>>>random.sample(range(1, 100), 5)
[96, 87, 3, 70, 46]
You can either let the computer generate random numbers like this:
import random #Put this at the top of the file for clarity
nums = []
[nums.append(random.randint(1, 5)) for x in range(0, 5)] #Replace list(range(0, 5)) with this.
One line for loops like this are basically a short hand way of writing something like for x in range(0, 5): #Do stuff.
Or, you could do this for user input.
#DO NOT IMPORT RANDOM HERE. THIS IS NOT A CODE I ACTUALLY MEAN IT DO NOT PUT IMPORT RANDOM FOR THIS CODE BECAUSE IT WILL BE POINTLESS
#Replace the list(0, 5) again
nums = []
[nums.append(int(input("Please enter a number")) for x in range(0, 5)]
Then, for the sum, add up every element
total = sum(nums)
Lastly, for the average.
print(total/len(nums)) #len(nums) is basically the length of the numbers array which is how many numbers you are adding
There is a three-line solution in case you want to surprise people.
def avg(arr):
return sum(arr)/len(arr)
print(avg([int(input("Enter a number") for x in range(0, 5))]))