The result is coming back correct but not in correct format - python-3.x

I am doing an assignment and the answers are coming back correctly but I would need them to say 5! = 120 instead of just = 120. How would I go about that?
def getInt():
getInt = int
done = False
while not done:
print("This program calcultes N!")
# get input for "N
N = int(input("Please enter a non-negative value for N: "))
if N < 0:
print("Non-Negative integers, please!")
else:
done = True
return N
def main():
n = getInt()
for i in range(n-1):
n = n * (i+1)
print("=" ,n)
main()

I hope this code will help.
print('Enter a positive integer')
a = int(input())
def factorial(n):
if n == 0:
return(1)
if n == 1:
return(1)
if n > 1:
return(n * factorial(n-1))
if a < 0:
print('Non-Negative integers, please!')
if a >= 0:
print(str(a) + '! = ' + str(factorial(a)))

In the for i in range(n-1)you could use another integer instead of n just to be sure things don't mess up and you can print like joel said print(i,"!=", n) but instead of n the integer you will use.

can you show me your homework instructions?
i'm not sure what the first value is in your example.. the current iteration or the original number entered?
# declare getInt()
def getInt():
getInt = int
done = False
while not done:
# write "this program calculates N!"
print("This program calcultes N!")
# get input for "N
N = int(input("Please enter a non-negative value for N: "))
# if N < 0 then
if N < 0:
print("Non-Negative integers, please!")
# else
else:
# done = true
done = True
# return N
return N
# main
def main():
n = entry = getInt()
for i in range(n-1):
n = n * (i+1)
print("{0}! = {1}".format(entry, n))
main()
results:
/*
This program calcultes N!
Please enter a non-negative value for N: 5
5! = 120
*/

Related

How to check if this input is a negative number

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

Given a positive integer, determine if it's the nth Fibonacci number for some n

I try to find out the index of a certain Fibonacci number. However my program returned to me this result "Your program took too long to execute. Check your code for infinite loops, or extra input requests" after typing in 1134903171.
num = 1
num_prev = 1
n = int(input())
i = 1
if n < 2:
print(1, 2)
else:
while i <= n + 2:
num_prev, num = num, num + num_prev
i += 1
if n == num:
print(i + 1)
break
elif i == n + 3:
print(-1)
#break`
Thank you guys. The problem of last code is that: if the number isn't a Fibonacci number and meanwhile it is too large, it will took to many loops for the calculation. As I used a web compiler to calculate, they do not allow such "infinity" loop to operate. Then I used a math methode to limite the loop.
import math
N=int(input())
root1=math.sqrt(5*N*N+4)
root2=math.sqrt(5*N*N-4)
i=1
num, num_prev = 1, 1
if root1%1==0 or root2%1==0:
while i <= N+2:
num_prev,num = num,(num+num_prev)
i+=1
if N==num:
print(i+1)
break
else:
print(-1)
But the best answer could be:
prev, next = 1, 1
index = 2
possible_fib = int(input())
while possible_fib > next:
prev, next = next, prev + next
index += 1
if possible_fib == next:
print(index)
else:
print(-1)

Why my code does't execute this statement : int(n)?

This code is to convert decimals to binary.
What I'm trying to do is to chop off the decimal part after diving by 2.
binary = []
n = 25
while n != 0:
binary.append(n % 2)
n = n / 2
int(n) #this part
print(binary)
print(n)
choose = input("continue?[Y/N]")
if choose == 'y':
continue
else:
break
print(list(reversed(binary)))
Is this what you want?
binary = []
n = 25
while n != 0:
binary.append(n % 2)
n = n / 2
n = int(n) #assign result to n
print(binary)
print(n)
choose = input("continue?[Y/N]")
if choose == 'y':
continue
else:
break
print(list(reversed(binary)))

Logic to find out the prime factors of a number

I have created the below script to find out the prime factors of a number :
def check_if_no_is_prime(n):
if n <= 3:
return True
else:
limit = int(math.sqrt(n))
for i in range(2,limit + 1):
if n % i == 0:
return False
return True
def find_prime_factors(x):
prime_factors = []
if check_if_no_is_prime(x):
prime_factors.append(1)
prime_factors.append(x)
else:
while x % 2 == 0 and x > 1:
prime_factors.append(2)
x = x // 2
for i in range(3,x+1,2):
while x % i == 0 and x > 1:
if check_if_no_is_prime(i):
prime_factors.append(i)
x = x // i
if x <= 1:
return prime_factors
return prime_factors
no = int(input())
check = find_prime_factors(no)
print (check)
I am not sure whether this is the best and efficient way to do this ?
Can someone please point out any better way to do this ?
using sieve of erathnostanes to get all prime numbers from 2 to whatever limit inputted
def sieve(N):
from math import floor,sqrt
A=[1 for x in range(N+1)]
for count in range(2):
A[count]=0
for i in range(floor(sqrt(N))+1):
if A[i]==1:
for k in range(i*i,N+1,i):
A[k]=0
ans=list(enumerate(A))
res=[]
for (i,j) in ans:
if j==1:
res+=[i]
return res
print(sieve(100))
#my code

Invalid Syntax; nth prime number

def primetest(x):
if x < 2:
return False
if x == 2:
return True
if x % 2 == 0:
return False
for i in range(3,(x**0.5)+1):
if x % i == 0:
return False
return True
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return list(-1)
print nthprime(10001)
Whenever I try to run this it says that "print nthprime(10001)" is invalid syntax.
-prime test is to test wether a number is prime and nthprime creates a list of prime numbers a certain lengths and then return the last element of the list.
print is a function in Python 3, not a statement. You should change your last line of code to:
print(nthprime(10001))
In your code:
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return list(-1) // this is the error
I think you meant primes[-1], like this:
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return primes[-1] // this is now correct
You're also going to need to specify a range in integers, not float. So this:
for i in range(3,(x**0.5)+1):
Becomes this:
for i in range(3,int((x**0.5)+1)): // note the "int"

Resources