100 random numbers with an odd and even counter - python

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

Related

How I add to a list same number multiple times by count?

I've got 2 problems here.
my first problem is that the code shows me only one time a factor even though it's multiple x times by the same factor. I don't know how to add it to the factor list.
Another problem is I'm not sure in print - how the sep works and how can I write "*" only between elements of factor list.
I can't use any import functions here (intertools, maths etc.)
Please help me.
def factorize(n):
prvocisla = []
faktor = []
#prime numbers
for num in range(1, 2000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prvocisla.append(num)
count = 0
for i in prvocisla:
if n % i == 0:
count += 1
faktor.append(i)
print(n, " =", *faktor , sep=' *', end='\n')
factorize(360)
My result:
360 * = *2 *3 *5
The right result:
360 = 2 * 2 * 2 * 3 * 3 * 5
I try the count function with adding same factor to the list "count times" but it shows me an Error.
The problem is that in your second 'for' loop you evaluate if there is a prime number in your number, but not how many times it is present.
To do this you need to repeat the cycle every time you find a prime number and divide the initial number by the prime number. this way you will get to 1 and get all the factors in the array.
Here the right code:
def factorize(n):
prvocisla = []
faktor = []
#prime numbers
for num in range(1, 2000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prvocisla.append(num)
count = 0
t = n # <-- a temporary variable which get n value
while t>1:
for i in prvocisla:
if t % i == 0:
count += 1
faktor.append(i)
t = t/i <-- divide t every time you find a factor
break
print(f"{n!s} = {' * '.join(str(k) for k in faktor)}")
factorize(360)
For the print I use the #CreepyRaccoon suggestion.

How do I keep a loop going with a variable that changes in every loop

So I'm new to coding and I'm struggling with the following exercise
So we start with a random number and we have to count the even numbers and the odd numbers. With this, we make a second number that starts with the amount of the even numbers, amount of the odd numbers, and the amount of numbers in total. We should continue this until the number 123 is reached.
For example:
number = 567421 --> odd numbers = 3 , even numbers = 3 , total numbers = 6 --> new number = 336 -->...
I had an idea to write it like this:
number = input()
evennumbers = ''
oddnumbers = ''
a = len(number)
while number != '123':
for i in str(number):
if int(i) % 2 == 0:
evennumbers += i
else:
oddnumbers += i
b = len(evennumbers)
c = len(oddnumbers)
number = input(print(f"{b}{c}{a}"))
But I have no idea how to keep this loop going with the variable 'number' until 123 is reached
You need your variable initialization to be inside the while loop, and remove the input(print(... on the final line.
number = '567421'
while number != '123':
print(number)
evennumbers = ''
oddnumbers = ''
a = len(number)
for i in str(number):
if int(i) % 2 == 0:
evennumbers += i
else:
oddnumbers += i
b = len(evennumbers)
c = len(oddnumbers)
number = f"{b}{c}{a}"
You could simplify like this:
while number != '123':
print(number)
total = len(number)
odds = sum(int(digit) % 2 for digit in number)
evens = total - odds
number = f"{evens}{odds}{total}"

How to execute this in command line(I am using spyder)

Write a python program to accept 10 numbers through command line arguments and calculate the sum of prime numbers among them.
This is my question.
I tried this
for Number in range (1, 101):
count = 0
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count = count + 1
break
if (count == 0 and Number != 1):
print(" %d" %Number, end = ' ')
but this is naive and works only for given range. I want to input 10 numbers in command prompt and it should find the sum of prime numbers in my input. I tried using import sys and giving sys.args[input] but it is showing errors.
Can someone please help with this?I am just starting to learn coding.
Thanks in advance:)
A solution can be this:
import sys
nums = sys.argv
def with_loop():
total = 0 # to collect the prime numbers
count = 1 # a counter for the numbers that you entered
for i in range(10):
num = int(input("{}. Please enter a number: ".format(count)))
if num > 1: # if number is larger than 1, we need to check
for j in range(2, num):
if (num % j) == 0:
break
else:
total += num
elif num == 1: # 1 is a prime number
total += num
else: # otherwise the number is negative so we skip.
pass
count += 1
print("\nTotal : {}".format(total))
def with_argv(nums):
total = 0 # to collect the prime numbers
count = 1 # a counter for the numbers that you entered
for i in range(1, len(nums)):
if int(nums[i]) > 1: # if number is larger than 1, we need to check
for j in range(2, int(nums[i])):
if (int(nums[i]) % j) == 0:
break
else:
total += int(nums[i])
elif int(nums[i]) == 1: # 1 is a prime number
total += int(nums[i])
else: # otherwise the number is negative so we skip.
pass
count += 1
print("\nTotal : {}".format(total))
with_loop()
with_argv(nums)
A simple example:
sum = 0
for count in range(1,11):
sum += int(input(f'Enter number {count} : '))
print(f'Total sum : {sum}')
To solve this problem, I would first define a function that checks whether a number is prime or not. It would only return a Boolean and nothing else.
Then I would create two lists- one for storing all the numbers entered by a user and another for storing all the prime numbers among the numbers entered by the user. I would use my predefined function for this check.
When the list of prime numbers is ready, I would use the sum() method to find the sum of the items of the list viz. the primes numbers the user has entered.
Here is the code-
def isPrime(num): #defining a function to check a given number is prime
factors = []
if num == 2:
return True
else:
for i in range(1, num + 1):
if (num % i == 0):
factors.append(i)
if len(factors) == 2:
return True
else:
return False
numbers = [] #list for user entered numbers
primes = [] #list for prime numbers among them
print("Enter 10 numbers.\n")
for i in range(10):
numbers.append(int(input(f'Enter number #{i + 1}:')))
#adding user inputs to numbers list
for i in numbers: #checking if the entered numbers are prime
if isPrime(i):
primes.append(i)
print("Sum of the prime numbers enters by the user is " + str(sum(primes)))
#sum() method adds all elements in an iterable
This code will do.
Spyder uses IPython Console. That is the command line referred in the question. So, if you run the code in Spyder, the IPython console will run this program.

In Python, how do I print only the final answer in a while loop when adding values between 1 and 20

So this is what I've got. The output is every answer leading up to the final outcome of Odd = 100 and Even = 110. I was hoping someone could maybe suggest what I could do to only print the final answers rather than the whole list of iterations.
Thanks a million x
#inputs
odd = 0
even = 0
counter = 0
# calculations for even numbers
while counter <= 20 and counter % 2 == 0:
even = even + counter
print("The sum of the EVEN numbers between 1 and 20 is", even)
counter += 1
# calculations for odd numbers
if counter <= 20 and counter % 2 != 0:
odd = odd + counter
print("The sum of the ODD numbers between 1 and 20 is", odd)
counter += 1
use the print statement after incrementing the counter, outside the while loop
#inputs
odd = 0
even = 0
counter = 0
# calculations for even numbers
while counter <= 20 and counter % 2 == 0:
even = even + counter
counter += 1
# calculations for odd numbers
if counter <= 20 and counter % 2 != 0:
odd = odd + counter
counter += 1
print("The sum of the ODD numbers between 1 and 20 is", odd)
print("The sum of the EVEN numbers between 1 and 20 is", even)
Something like this should work; note the print statement is outside the while loop and the arithmetic is being done on odd and even using the if statement to determine which is to be added. Hope this makes sense
odd = 0
even = 0
counter = 0
while counter <= 20:
if counter % 2 == 0:
even += counter
elif counter % 2 != 0:
odd += counter
counter += 1
print("Sum of odd numbers is: {}, sum of even numbers is: {}".format(odd, even))

Python code for the coin toss issues

I've been writing a program in python that simulates 100 coin tosses and gives the total number of tosses. The problem is that I also want to print the total number of heads and tails.
Here's my code:
import random
tries = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
if coin == 2:
print ('Tails')
total = tries
print(total)
I've been racking my brain for a solution and so far I have nothing. Is there any way to get the number of heads and tails printed in addition to the total number of tosses?
import random
samples = [ random.randint(1, 2) for i in range(100) ]
heads = samples.count(1)
tails = samples.count(2)
for s in samples:
msg = 'Heads' if s==1 else 'Tails'
print msg
print "Heads count=%d, Tails count=%d" % (heads, tails)
import random
total_heads = 0
total_tails = 0
count = 0
while count < 100:
coin = random.randint(1, 2)
if coin == 1:
print("Heads!\n")
total_heads += 1
count += 1
elif coin == 2:
print("Tails!\n")
total_tails += 1
count += 1
print("\nOkay, you flipped heads", total_heads, "times ")
print("\nand you flipped tails", total_tails, "times ")
You have a variable for the number of tries, which allows you to print that at the end, so just use the same approach for the number of heads and tails. Create a heads and tails variable outside the loop, increment inside the relevant if coin == X block, then print the results at the end.
Keep a running track of the number of heads:
import random
tries = 0
heads = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
heads += 1
print('Heads')
if coin == 2:
print ('Tails')
total = tries
print('Total heads '.format(heads))
print('Total tails '.format(tries - heads))
print(total)
import random
tries = 0
heads=0
tails=0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
heads+=1
if coin == 2:
print ('Tails')
tails+=1
total = tries
print(total)
print tails
print heads
tosses = 100
heads = sum(random.randint(0, 1) for toss in range(tosses))
tails = tosses - heads
You could use random.getrandbits() to generate all 100 random bits at once:
import random
N = 100
# get N random bits; convert them to binary string; pad with zeros if necessary
bits = "{1:>0{0}}".format(N, bin(random.getrandbits(N))[2:])
# print results
print('{total} {heads} {tails}'.format(
total=len(bits), heads=bits.count('0'), tails=bits.count('1')))
Output
100 45 55
# Please make sure to import random.
import random
# Create a list to store the results of the for loop; number of tosses are limited by range() and the returned values are limited by random.choice().
tossed = [random.choice(["heads", "tails"]) for toss in range(100)]
# Use .count() and .format() to calculate and substitutes the values in your output string.
print("There are {} heads and {} tails.".format(tossed.count("heads"), tossed.count("tails")))
I ended up with this.
import random
flips = 0
heads = 0
tails = 0
while flips < 100:
flips += 1
coin = random.randint(1, 2)
if coin == 1:
print("Heads")
heads += 1
else:
print("Tails")
tails += 1
total = flips
print(total, "total flips.")
print("With a total of,", heads, "heads and", tails, "tails.")
Here is my code. Hope it will help.
import random
coin = random.randint (1, 2)
tries = 0
heads = 0
tails = 0
while tries != 100:
if coin == 1:
print ("Heads ")
heads += 1
tries += 1
coin = random.randint(1, 2)
elif coin == 2:
print ("Tails ")
tails += 1
tries += 1
coin = random.randint(1, 2)
else:
print ("WTF")
print ("Heads = ", heads)
print ("Tails = ", tails)
import random
print("coin flip begins for 100 times")
tails = 0
heads = 0
count = 0
while count < 100: #to flip not more than 100 times
count += 1
result = random.randint(1,2) #result can only be 1 or 2.
if result == 1: # result 1 is for heads
print("heads")
elif result == 2: # result 2 is for tails
print("tails")
if result == 1:
heads +=1 #this is the heads counter.
if result == 2:
tails +=1 #this is the tails counter.
# with all 3 being the count, heads and tails counters,
# i can instruct the coin flip not to exceed 100 times, of the 100 flips
# with heads and tails counter,
# I now have data to display how of the flips are heads or tails out of 100.
print("completed 100 flips") #just to say 100 flips done.
print("total tails is", tails) #displayed from if result == 2..... tails +=1
print("total heads is", heads)

Categories