I just started to study Python. I must use Python3.7.
Could someone show me a working factorial code?
i tried some i found here but i always get this error:
=================== RESTART: C:\programozás\pytutorial.py ===================
Code:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Your code is working, even though you could simply use the math library:
import math
print(math.factorial(5))
The problem does not come from your script, so maybe you should try to reinstall your python, and avoid paths with special characters as Adam Toth pointed out.
Update: to get the input and return a factorial as asked in comments
import math
print(math.factorial(int(input(">>"))))
The problem is most likely caused because you have a special character in the path to the .py file. So should use a folder like C:\programming, or anything without a special character, like 'á'.
It's very important to do like this, even if it does not solve your current problem, it can prevent many more in the future.
Ps.: Jó kiszúrni magyar programozót is :)
I see a related (older) thread here about this error
For the logic:
We have to consider:
Negative numbers
Zero
Positive numbers
So one way to write it will be:
def factorial(n):
if n < 0:
result = "Factorial doesn't exist for negative numbers"
elif n == 0:
result = 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result
You can try the concept of recursion as well.
To get the factorial of a number "num":
print(factorial(num))
Make sure you indent the code properly, indentation is important in python.
Hope it helps!
Python Code of Factorial Using Recursive Function:
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
factorial(5)
Note: The First Condition will only meet when the input is 0 or 1 and in else block n will be recursively multiplying n * n - 1.
Related
def fac(n):
if (n < 1):
return 1
else:
n * fac(n-1)
print fac(4)
Why does return command cause the function to go back up and multiply the factorials? I have trouble understanding this.
1). You need to write a return in your code.
def fac(n):
if (n < 1):
return 1
else:
return n * fac(n-1)
print(fac(4))
2). I am uploading a picture which will help you to understand the concept of recursion. Follow the arrow from start to end in the picture.
You need to consider the call stack. The way this code needs to operate is for every fac(n) is equal to n * (n-1) * (n-2) ... (n - n + 1).
Your code was wrong. For a recursive function to work, you must be returning a value each time. You were getting None back because you never returned anything.
def fac(n):
if n == 1:
return 1
return n * fac(n - 1)
if __name__ == "__main__":
num = 2
print(fac(num))
Keep practicing recursion. It is extremely useful and powerful.
For more of a why it works than how it works perspective:
Calling a function recursively is no different than calling a different function: it just happens to execute the same set of instructions. You don't worry about Python getting confused between locals and parameters of different functions, or knowing where to return to; this is no different. In fact, if each recursive invocation had its own name instead of re-using the same name, you probably wouldn't be here.
Showing that it works properly is a bit different, because you need to make sure the recursion ends at some point. But this is no different than worrying about infinite loops.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I was curious if anyone could fix my code, this is for project Euler Question 3 (What is the largest prime factor of the number 600851475143 ?), as of now, I am sticking to a program that will find all the prime factors in 100, but am getting an error message for divide by 0, in my head the code seems to work, but it isn't. Unless absolutely necessary, I'd like to keep the while loops. Thanks.
def isPrime(A):
x = 2
while x < A:
if A % x == 0:
return False
x += 1
return A
def isInt(x):
if x == int(x):
return True
return False
A = int(input("Number? "))
counter = 2
while counter <= A:
if isInt(A/isPrime(counter)) == True:
print(counter)
counter += 1
print ("Done")
It seems the key issue is that isPrime() sometimes returns a boolean, and other times returns the input (an integer). You should avoid having functions that do too many things at once - a function called isPrime() should just indicate whether the input is prime or not (i.e. always return a boolean). Some other suggestions inline:
def isPrime(n): # n is a common variable name to use for "some number"
x = 2
while x < n:
if n % x == 0:
return False
x += 1 # this isn't an ideal way to detect primes, can you think of any improvements?
return True
def isInt(n): # use consistent variables - you used A above and x here, which is confusing
return n == int(n) # you can just return the boolean result directly
input = int(input("Number? ")) # use meaningful variable names when possible
counter = 2
while counter <= input:
# I *think* this is what you were trying to do:
# if counter is prime and input/counter is an integer.
# If not you may need to play with this conditional a bit
# also no need to say ' == True' here
if isPrime(counter) and isInt(input/counter):
print(counter)
counter += 1
print ("Done")
This should run (whether it works or not, I leave to you!), but it's still not as efficient as it could be. As you get into harder Project Euler problems you'll need to start paying careful attention to efficiency and optimizations. I'll let you dig into this further, but here's two hints to get you started:
Incrementing by one every time is wasteful - if you know something is not divisible by 2 you also know it's not divisible by 4, 8, 16, and so on, yet your code will do those checks.
In general finding primes is expensive, and it's a very repetitive operation - can you re-use any work done to find one prime when finding the next one?
I want to performe
[√(1/2+1/2*√1/2)] ---------(P1)
[√(1/2+1/2*√(P1)] ----------(P2)
[√(1/2+1/2*√(P2)]
etc.
to find out the P(nth)term
I have this for now
from math import *
n=eval(input('fjeowijo'))
i=sqrt(1/2+1/2*(sqrt(1/2)))
def P(n):
for i in range(n):
g=sqrt(1/2+1/2*i)
i=sqrt(1/2+1/2*i)
print(g)
P(n)
When I enter 1 for n, the result is 0.7071067811865476, which is only equal to the part " sqrt(1/2) ". Why?
In case you want to make it recursive do
def P(n):
if n <= 0:
return 0.5
else:
return sqrt(0.5*(1+sqrt(P(n-1))))
which works out as
>>> P(1)
0.9238795325112867
>>> P(2)
0.9902490907008235
>>> P(3)
0.9987774031336784
>>> P(4)
0.9998471169658009
As #JoshRomRock points out, python generally limits the maximum depth of the recursion (the default max depth is platform-dependent).
In case of CPython, the default limit is 1000.
In case you want to alter such limit do:
import sys
sys.setrecursionlimit(5000)
Note: in this case, the precision offered by the floating point representation may well be the biggest hurdle to the calculation. Please see the official docs for further info on what to expect using floats.
Second note: in case the P function is going to be used several times and/or in multiple points of the code of a program, as a library function, it would make sense to implement it using Memoization.
Please see here for a few examples in python.
def P(n):
i = 0
g = sqrt(0.5+.5*sqrt(0.5)
while(i < n):
g = sqrt(0.5+0.5*g)
print(g)
Could it be what you're looking for ?
I have a problem with a this piece of code that I'm writing to check if a number is prime.
import sys
import math
def is_prime(num):
for j in range(2,(int(math.sqrt(num)+1))):
if (num % j) == 0:
return False
else:
return True
for a in range(1,10):
if is_prime(a):
print a
What I get is: 5, 7, 9
I don't understand why is 3 excluded? I went back to the first portion of the code and tried is_prime(3), but it returned me neither True nor False. Does this mean that 3 is outside the range of divisors I'm checking? How should I correct the code such that 3 is included in my list of primes?
Edit:
Hello again, thanks for the answers so far, so I've tried to solve the problem of truncation using int(round()). I've also tried putting the else block outside the loop, but it doesn't seem to work. Can anyone please explain why this is insufficient and suggest how I should correct it so it works? Thanks in advance! :)
import sys
import math
def is_prime(num):
for j in range(2,int(round(math.sqrt(num)+1)):
if (num % j) == 0:
return False
return True
Your function returns True as soon as it sees that the number is not divisible by any j. It should only return True if the number is not divisible by all j.
As a side-effect of fixing this bug, you'll also fix the bug whereby your function sometimes returns None (for example, when num is 3).
int() truncates, not rounds, so int(math.sqrt(3) + 1) == 2. range(2, 2) is empty, so nothing will be returned.
Another problem is that your else block is inside of the loop. If you test the first 100 numbers, you will quickly notice that your is_prime function will return True for any odd number.
The square root of 3 is less than 2, so the loop is never entered and nothing is returned.
I am writing a program that must find if a number is even or not. It needs to follow this template. I can get it to find if a number is even or not recursively
The key is that you need to return a boolean value:
def isEven(num):
if (num <= 0):
return (num == 0)
return isEven(num-2)
For larger numbers though this quickly exceeds the default maximum recursion depth for Python. That can be remedied by calling sys.setrecursionlimit(n) where n is the number of recursive calls you want to allow. n in turn is limited by the platform you are on.
Try this, it works for integer values with 0 <= n <= sys.getrecursionlimit()-2:
def even(n):
return True if n == 0 else odd(n - 1)
def odd(n):
return False if n == 0 else even(n - 1)
It's a nice example of a pair of mutually recursive functions. Not the most efficient way to find the answer, of course - but nevertheless interesting from an academic point of view.
This template will help. You need to fill in the commented lines. The one you have in the question won't work - you aren't passing anything into isEven. This will only work if n >= 0, otherwise it will crash your program. Easy enough to fix if you ever need to deal with negative numbers.
def isEven(n):
if n == 0:
# Number is even
elif n == 1:
# Number is odd
else:
# Call the function again, but with a different n
Taking up wim's challenge to find a "different" way to do this: The prototypical recursive pattern is foo(cdr(x)), with a base case for the empty list… so let's write it around that:
def isEven(num):
def isEvenLength(l):
if not l:
return True
return not isEvenLength(l[1:])
return isEvenLength(range(num))
A really dumb use case for recursion, but here is my version anyway
import random
def isEven(num):
if random.random() < 0.5:
# let's learn about recursion!
return isEven(num)
else:
# let's be sane!
return num % 2 == 0
disclaimer: if you submitted this you'd probably tick off the teacher and come across as a smartypants.