Forgive me, I'm new, but I want to build a recursive function that takes a natural number and returns the product of all the natural numbers from 1 up to the given number. So factorial(5) should return 120 (5·4·3·2·1 = 120). However, I think I am just stuck. Here is what I have so far:
def factorial(x):
"""returns the product of all natural numbers from 1 up to the given number
natural number -> natural number"""
if x <= 0:
return 1
else:
return x*(x-1)
Would the best route be to implement a counter?
First the statement in else needs to return a value, and because it's a factorial it should be x times the factorial of one less than x.
return x * factorial(x - 1)
The base case cannot be zero, firstly because the factorial of any number less than zero is undefined and any number times zero is zero, which makes the whole function pointless.
You should instead use the base case of:
if x <= 1:
return 1
So your function is:
def factorial(x):
if x <= 1:
return 1
else:
return x * factorial(x - 1)
def factorial(x):
"""returns the product of all natural numbers from 1 up to the given number
natural number -> natural number"""
if x <= 0:
return 1
else:
return x*(factorial(x-1))
You also need to recursively call the function again.
Related
I have to write code to manually input n number and code should find that n member of sequence.n should be natural number. Formula for that sequence is
f(n)=(f(n-1))²-1
First member is 2 second 3 third 8 and every next is one less than square of number before. The code should print that n member of sequence which is inputted.
For example
In:3
Out:8
In:4
Out:63
I wrote code but it don't work
n = int(input("'input n:"))
def f(n):
if n < 0:
print('Undefined')
else:
return (f(n - 1) ** 2) - 1
print(f(n))
In recursion, you need to return a definite value for the stop index.
Here you just have to write in your code that the first value of the sequence is 2:
def f(n):
if n < 0:
raise ValueError('Undefined') # better to raise to make sure to abort
elif n == 0:
return 2
else:
return (f(n - 1) ** 2) - 1
That is enough for f(1) to return 3 and f(2) to return 8...
How to write a recursive function that will calculate this sum for a given n?
n
∑ 1/k
k=1
My code:
def sum(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return sum(1/n) + sum(1/n+1)
print(sum(3))
For n = 3 the output should be: 1.8333333333333333
You should avoid declaring a new function with the name sum as there already exists a built-in function with this name.
You can recursively calculate
n n-1
∑ 1/k == 1/n + ∑ 1/k
k=1 for n > 0 k=1
with
def my_recursive_sum(n):
if n <= 0:
return 0
if n == 1:
return 1
return 1/n + my_recursive_sum(n-1)
print(my_recursive_sum(3))
Your solution would easily reach the maximum recursion limit.
when you call again the function using 1/n and 1/n+1 you would use the same n and increase it, so you would never reach the end condition.
the next couple of sum would never have an n value equal to 0 or 1.
Also you should not call again the function with 1/n otherwise you would endup looping forever in the function recall
you should use something like:
>>> def my_sum(n):
... if n < 1:
... return 0
... return 1/n + my_sum(n-1)
...
>>> print(my_sum(3))
1.8333333333333333
>>> 11/6
1.8333333333333333
>>>
edit:
Like mentioned in another answer you should avoid using sum as a name of a function because it's a name already use by python
So far I have the code posted below. I am basically inputting any number into the function and I should be returned with the number closest to the input which is a power of two, and smaller than the input. Nothing is being printed or outputted.
def pow2(num):
x=0
expo = 2**x
while num > 0:
x+=1
if expo > num:
print(expo)
expo = 2 ** (x-1)
return expo
pow2(55)
Your while loop is an endless one since num never changes and you only recalculate expo if it is greater than num, which remains False if it was initially False.
A fixed implementation could be:
def pow2(num):
x = 0
while 2**(x+1) < num:
x += 1
return 2**x
print(pow2(55))
Note that the function only returns a value and does not print it. It is advisable for the functions to only return values and not have side effects such as printing.
i have to write a recursive function which calculates sum of a number digits,here's the code i tried :
def sum_digit(n):
sum=0
a = n % 10
n //= 10
sum += a
while n > 0 :
sum = sum + sum_digit(n)
return sum
print(sum_digit(67154))
i don't know why i don't get the 23 as answer...my program doesn't come to an end
for example 23 number(please correct me if I'm wrong,I'm a newbie in python),the 3 goes to sum, and n become2,since its > 0 then it should go to while,so now it should calculate sum digit(2),the a become 2 and 2 goes to sum and n become 0 and sum digit(2) returns 2,then it sum with the 3 and i must get 5.
i appreciate your help.
You have an infinite loop because n never changes within the loop. Note that assigning a new value to n in the scope of the called function will not change n in the outer scope.
Also, it seems you are mixing an iterative solution with a recursive one. If you do the recursive call, you do not need the loop, and vice versa.
You can either do it recursively:
def sum_digit(n):
if n > 0:
return sum_digit(n // 10) + n % 10
else:
return 0
Or in an iterative way:
def sum_digit(n):
s = 0
while n > 0:
s += n % 10
n //= 10
return s
Or just using bultin functions (probably not what your teacher wants to see):
def sum_digit(n):
return sum(map(int, str(n)))
i must change the while with a if, and it works,thanks for your comments and sorry for posting such a question here.
This will do the trick:
def sum_digit(n, current_sum=0):
if n == 0:
return current_sum
else:
digit = n % 10
current_sum += digit
n //= 10
return sum_digit(n, current_sum)
The output:
print(sum_digit(67154))
> 23
You were mixing up an iterative method (the while loop) and the recursive method (the function call).
In a recursive function, must make sure you get these things right:
The end condition (in our case, we return the sum when the digit is 0)
and
The recursive call (in our case, going down one digit each time)
Change your code as following:
def sum_digit(n):
sum=0
a = n % 10
n //= 10
sum += a
if n > 0 :
sum = sum + sum_digit(n)
return sum
The reason is n is assigned new reference inside function, but it's invisible outside. so while part is loop died. In fact, while part is executed at most once, so code was changed as above.
I wrote a function to calculate whether or not a number is prime, but try as it might, it just seems unable to give the correct response. It also prints the n value that is being incremented. Here is the code for the function (in Python, by the way):
def isPrime(x):
for n in range(1, x):
print n
if x % n == 0:
return False
return True
If I input
isPrime(17)
the function returns
1
False
What is going wrong here?
Every number is divisible by 1 and itself. A prime number is a natural number that has no positive divisors other than 1 and itself. Therefore, if you start your for-loop with 1, every number x will pass the condition x % 1 == 0 in the first iteration, returning False.
To fix it, you need to start your loop with 2 instead of 1. Also, as a side-note, you just need to loop from 2 to sqrt(x), since if there exists a number q > sqrt(x) that divides x, then there must also be a number p = x / q which also divides x, and p < sqrt(x).