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