random number list generator - python

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)

Related

Removing prime numbers from a linked list

I have a linked list that I am trying to generate a random list and then remove all of its prime numbers. This is what I have so far. I know how to find the primes I'm just not sure where to go on removing them from the list. This is my updated list, it only removes one number instead of deleting all primes.
import random
from linkListDef import *
def is_prime(llist):
number = llist[0]
half = int(number / 2)
status = True
for count in range(2, half + 1):
if number % count == 0:
status = False
return status
def main():
llist = LinkedList()
counter = 0
while counter != 20:
numbers = random.randrange(1, 101)
counter += 1
llist.push(numbers)
print ("Created Linked List: ")
llist.printList()
llist.deleteNode(numbers)
print ("Linked List after Deletion of primes:")
llist.printList()
if __name__ == '__main__':
main()
You can do a for loop on the now generated linked list, check the number using your isPrime method and running .remove(item) on the list, where item is the current iteration over the list

I've declared variable "x" but i did not call it, is it ok to not call variables that have values assigned?

import random
def add_sums(Num):
total = 0
all_num = []
for x in range(1, Num+1):
gen = random.randint(1, 30)
all_num.append(gen)
print("List:", all_num)
for y in all_num:
total += y
print("List total:", total)
user_max = int(input("Max numbers in list: "))
add_sums(user_max)
In this program, the user will enter the total amount of numbers in a list.
the random module will generate random numbers between 1 to 30.
Then all the numbers from the list will be added together.
I've tried to use the variable x but it doesn't give the results I want, does anyone know a better/simpler way of creating this program. Also, is it bad practice to create a variable and not call it?
Maybe this better/simpler way of creating this program
import random
def add_sums(Num):
all_num = []
for x in range(Num):
all_num.append(random.randint(1, 30))
print("List:", all_num)
print("List total:", sum(all_num))
user_max = int(input("Max numbers in list: "))
add_sums(user_max)
When you're iterating through a list but don't need the index, it's common to use an underscore to indicate the index isn't used.
for _ in range(1, Num+1):
gen = random.randint(1, 30)
all_num.append(gen)

Find prime numbers with list comprehension

I was trying to write a code to select the prime numbers in a list. The user gives a limit and the program displays all prime number from 2 to the limit. I was trying to reduce the maximum amount of lines I could and was surprised with some situations I can't understand. If you can help me, I'd be grateful.
I wrote this code:
# returns all integers from 2 to a limit given by the user.
def primes(limit):
# generates the numbers.
lista = range(2, limit + 1)
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in lista if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#Ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
It runs as I expected, but when I tried deleting the first list assignment line and include the range function directly into the comprehension, it doesn't work. Why?
# returns all integers from 2 to a limit given by the user.
def primes(limit):
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in range(2, limit + 1) if i == p or i % p != 0]
#or lista = [i for i in range(2, limit + 1) if i == p or i % p != 0]
#or lista = [i for i in [*range(2, limit + 1)] if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#Ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
Other problem. As the line with range is not a list I fixed it only to improve the code, but when I changed the name of the value from 'lista' to another name, I saw that it doesn't work too. Why?
# returns all integers from 2 to a limit given by the user.
def primes(limit):
# generates the numbers.
nums = range(2, limit + 1)
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in nums if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
Thanks for your attention.
This one-liner works perfectly :
def primes(val):
return [x for x in range(2, val) if all(x % y != 0 for y in range(2, x))]
print(primes(10))
Thank you for your attention.I liked the answer of our friend Yash Makan, but when I tried larger numbers, like 100000, it never led me to the result (or I was not so patient to wait). So I continued thinking about the problem and got the following that is the fastest way to compute this problem I could achieve with list comprehension. Note how fast you can compute millions of numbers.
# returns all integers from 2 to a limit given by the user.
def primes(limit):
l = [i for i in range(2, limit + 1) if all(i % j != 0 for j in [2, 3, 5])]
lista = []
return [2, 3, 5] + [lista.append(i) or i for i in l if all( i % j != 0 for j in lista[:int((len(lista) ** .5) + 1)])]
def main():
l = int(input("Enter the limit: "))
return print(primes(l))
if __name__ == '__main__':
main()

Python: Summing Odd/Even Random Numbers Generates TypeError: 'int' object is not iterable

Yes, this question has been asked, but I cannot seem to apply the answers to my problem. There are several parts to this problem, and this is the biggest obstacle I've hit.
I need to generate a random list of 10 numbers between 10 & 90. From those random numbers, I need to sum the totals of both the even and odd numbers.
def playlist():
nums = []
for nums in range(10):
# Get random list of 10 numbers
my_nums = random.randint(10, 90)
print (my_nums,end=' ')
even = []
odd = []
for x in my_nums:
if x % 2 == 0:
even.append[x]
print(even)
else:
odd.append[x]
print(odd)
When I run this, sometimes I get one or two numbers (usually the first two odd numbers), but mostly I get TypeError: 'int' object is not iterable.
Not gonna lie - my first language is PHP, not Python and that's becoming a huge problem for me :(
Any help is appreciated.
Creating list with randoms
n = [random.randint(10,90) for x in range(10)]
Getting even and odds:
even = [x for x in n if x % 2 == 0]
odd = [x for x in n if x % 2 == 1]
You should be doing this.
def playlist():
nums1 = []
for nums in range(10):
# Get random list of 10 numbers
my_nums = random.randint(10, 90)
nums1.append(my_nums)
print my_nums
even = []
odd = []
for x in nums1:
if x % 2 == 0:
even.append(x)
print(even)
else:
odd.append(x)
print(odd)
playlist()
There are a few things you seem to have misunderstood:
range(10) will give you (something that looks like) this list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
You can use it with a for-loop to do something 10 times
random.randint(10, 90) will give you a single random number between 10 and 90 (not a list)
With this information we can change your script to:
import random
even_sum = 0
odd_sum = 0
for number_of_turns in range(10):
# Get a random number
number_this_turn = random.randint(10, 90)
print(number_this_turn,end=' ')
if number_this_turn % 2 == 0:
even_sum += number_this_turn
print("Sum of even numbers so far:", even_sum)
else:
odd_sum += number_this_turn
print("Sum of odd numbers so far:", odd_sum)
print("Final sum of even numbers:", even_sum)
print("Final sum of odd numbers:", odd_sum)
But we can do better. You will learn that in Python, you will want very often to define a list (or an iterable) with the terms you need then do something with every term. So we can change your script to:
import random
even_sum = 0
odd_sum = 0
random_numbers = [random.randint(10, 90) for x in range(10)]
for number in random_numbers:
print(number,end=' ')
if number % 2 == 0:
even_sum += number
print("Sum of even numbers so far:", even_sum)
else:
odd_sum += number
print("Sum of odd numbers so far:", odd_sum)
print("Final sum of even numbers:", even_sum)
print("Final sum of odd numbers:", odd_sum)
random_numbers = [random.randint(10, 90) for x in range(10)] is using a list comprehension to generate a list of 10 random numbers. You can then do a for-loop on each of these numbers where you can add to the evens' sum or to the odds' sum.
You can even simplify it even further like in #Take_Care_ 's answer but I guess you have a lot more to learn before you reach this level.
As mentioned the comments, you can't write for x in followed by a number. I guess what you want is for x in range(my_nums) rather than for x in my_nums.
This is ultimately what I needed:
def playlist():
nums = []
for nums1 in range(10):
# Get random list of 10 numbers
my_nums = random.randint(10, 90)
nums.append(my_nums)
print (my_nums,end=' ')
even = []
odd = []
for x in nums:
if x % 2 == 0:
even.append(x)
else:
odd.append(x)
print ("\n")
print("Total of Even Numbers: ",sum(even))
print ("\n")
print("Total of Odd Numbers: ",sum(odd))
Thanks to everyone for their help...yes I know the call to run the function is missing - like I said this is just one part of the program :)
Following code works:
"""
I need to generate a random list of 10 numbers between 10 & 90. From those random numbers, I need to sum the totals of both the even and odd numbers.
"""
from random import randint
MIN = 10
MAX = 90
sum_odds = sum_evens = 0
for i in range(10):
r = randint(MIN,MAX)
if r % 2:
sum_odds += r
else:
sum_evens += r
return sum_evens, sum_odds

how do you generate 20 random numbers in python

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

Categories