I am having difficulty keeping a track of the total number of inputs. I want my program to keep track of the total number of inputs and print it when my while loop breaks. Any help is appreciated!
r = float(input("enter r:"))
def main(r):
a = 3.14 * (float(r ** 2))
s_v = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
total += r
print("Total = " , total)
break
else:
print("Area = ", a)
continue
main(r)
I assume that you want your program to re-calculate the area with each iteration. As written, it will only be calculated the first time you run the mymian function. You don't need to pass any arguments to the function.
def mymian():
sentinal_value = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
print("Total number of r provided to this program" , total)
break
else:
print("Area = ", 3.14 * (float(r ** 2)))
total += 1
continue
Related
I want the sum of all prime numbers till 2 million. My program logic is correct but it takes too much time with 2 million. How can I make it faster?
num_l=[]
y = int(input("enter till what number do you want the sum"))
for count in range(0,y):
num_l.append(count)
total = 0
for counter in range(0,y):
num = num_l[counter]
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
total = total + num
print(total)
just use a function to check that it is prime or not and if it is then add it to a counter (for total). The code below takes about 20 seconds to find what you want.
One more thing is that your algorithm for testing if a number is prime or not is having a long range of numbers to go through you don't need to test to the last number you just need to go through for a range of square root of the number.
import time
def is_prime(n):
if n == 1:
return False
elif n == 2:
return True
else:
for i in range(2, int(n**0.5)+1): # this range is just enough
if n % i == 0:
return False
return True
counter = 0
start = time.time()
for i in range(1, 2*10**6): # you can change this range for taking it as input
if is_prime(i):
counter += i
print(counter)
print(time.time() - start)
I'm new to python and want to make a program that generates Pi with the given decimal numbers. Problem is that I don't know how to check if the user has inputted a positive number.
This is the function that generates Pi (I don't know for sure how it works)
def PiBerekening(limiet):
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimaal = limiet
teller = 0
while teller != decimaal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if teller == 0:
yield '.'
# end
if decimaal == teller:
print('')
break
teller += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
And this is how I ask the user how many decimals he wants to see
while not verlaatloop:
try:
pi_cijfers = PiBerekening(int(input("With how many decimals would you like to calculate Pi?")))
assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True
This is how I show the calculated Pi
for pi_cijfer in pi_cijfers:
print(pi_cijfer, end='')
You can first validate the input and then pass it to the PiBerekening function. Something like this:
while not verlaatloop:
try:
no_decimals = int(input("With how many decimals would you like to calculate Pi?"))
if no_decimals > 0:
pi_cijfers = PiBerekening(no_decimals)
#assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True
I've to create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. The program should display an appropriate error message if the first value entered by the user is 0.
Note: Number of inputs by the user can vary. Also, 0 marks the end of the
input it should not be included in the average
x = int(input("Enter Values\n"))
num = 1
count = 0
sum = 0.0
if x == 0:
print("Program exits")
exit()
while (x>0):
sum += num
count += 1
avg = (sum/(count-1))
print("Average: {}".format(avg))
You were not taking input inside while loop. You were taking input on the first line for once. So your program was not taking input repeatedly.
You may be looking for this -
sum = 0.0
count = 0
while(1):
x=int(input("Enter Values: "))
if x == 0:
print("End of input.")
break;
sum+=x;
count+=1;
if count == 0:
print("No input given")
else:
avg = sum/count;
print("Average is - ",avg)
Your code does not work because int function expect only one number.
If you insert the numbers one by one, the following code works:
num = int(input("Enter a value: "))
count = 0
sum = 0.0
if num <= 0:
print("Program exits")
exit()
while (num>=0):
sum += num
count += 1
num = int(input("Enter a value: "))
avg = (sum/count)
print(f"Average: {avg}")
def get_nearest_multiple(minnum, factor):
"""
function get_nearest_multiple will calculate the nearest multiple that is greater than the min. value,
Parameters are the minimum value and factor,
Will return the ans - the nearest multiple
"""
ans = 0
x = 1
while ans < minnum:
if minnum == 0:
ans = 0
else:
ans = x * factor
x += 1
return ans
get_nearest_multiple(0, 1)
if __name__ == '__main__':
get_nearest_multiple(0, 1)
Can't seem to figure out why my function doesn't print out anything. The output doesn't even show up as an error. Just blank.
Nowhere in your code do you have a print() statement which is required to produce an output in the console
I have solved euler problem 12, but it needs some optimization. I have read on the euler forums, but it has not helped me optimized it. However, I have managed to get the solution, I just need to speed it up. It currently takes 4 minutes to run. Here is my code:
import time
def nthtriangle(n):
return (n * (n + 1)) / 2
def numberofnfactors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
def FirstTriangleNumberWithoverxdivisors(divisors):
found = False
counter = 1
while not found:
print(int(nthtriangle(counter)), " ", numberofnfactors(nthtriangle(counter)))
if numberofnfactors(nthtriangle(counter)) > divisors:
print(" first triangle with over ",divisors, " divisors is ", int(nthtriangle(counter)))
found = True
break
counter += 1
start_time = time.time()
FirstTriangleNumberWithoverxdivisors(500)
print("My program took", time.time() - start_time, "to run")
Instead of calculating each triangle number individually, use a generator to get the triangle numbers
from timeit import timeit
def triangle_numbers():
count = 1
num = 0
while True:
num += count
count += 1
yield num
def count_divisors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
print(timeit('next(num for num in triangle_numbers() if count_divisors(num) >= 500)',
globals=globals(), number=1))
Gives me 3.8404819999996107 (seconds) on my machine. You could probably also improve the divisor counting.
What's really slowing you down is calling nthtriangle and numberoffactors more than once in your loop! Plus, those calls to print aren't free.