def bounce(n):
if n < 1:
return 0 #if I change this value to 1 n gets printed out correctly, why?
else:
return n * bounce(n - 1)
print(bounce(5))
Your base case is return 0. After the line return n * bounce(n - 1) where n is 1, bounce(0) will be executed, returning 0 and multiplying all your previous results by 0.
Following the calls, we see:
5>=1, so return 5*bounce(4)
4>=1, so return 5*4*bounce(3)
3>=1, so return 5*4*3*bounce(2)
2>=1, so return 5*4*3*2*bounce(1)
1>=1, so return 5*4*3*2*1*bounce(0)
0<1, so return 5*4*3*2*1*0
meaning everything gets zeroed out at the end.
You want the base case to be 1 for that reason.
You sould add an check that returns the value for 0.
Otherwise you recursion multiplys with 0 at the final call of the recursiv function.
def bounce(n):
if n < 1:
return 0
elif n == 1:
return 1
else:
return n * bounce(n - 1)
This recursion is returning 0 because when n = 1, your compiler goes inside the else block and calls return 1 * bounce(0), and this time the compiler returns 0 because the if-condition is satisfied here. If you want your output to be 120 (in this case), you can change your code like this:
def bounce(n):
if n < 1:
return 0
else :
if n == 1:
return n ;
return n * bounce(n - 1)
print(bounce(5))
Yes, you have a loop that will continually repeat until you get to the point that n = 0, and you are printing a product where at least one value has "n * 0" in it.
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...
I need help with with writing a python script to sum a multi digit number until a single digit is left. So any number equal to 10 or greater.
The program will accept 10 for instance and return 1.
Numbers 1 - 9 should return as an error and 0 should return as 0. Entries that are not int should return an error too.
I have written multiple versions of this but I can not seem to get it to work the way I want it to.
Here is some code I am working with:
def SumDig(n):
n = []
if(not isinstance(n, int)) or (n <= 9) or (n >= 1):
return ("Error")
elif(n >= 10):
return (n - 1) % 9 + 1;
return SumDig(n)
You don't need it to be recursive:
def sumDigits(N):
if N is 0: return 0
if not isinstance(N,int) or N < 10: return "error"
return (N-1)%9+1
I can't seem to understand why the function fix_teen returns 13 and not 0.
As we have r in the range of 13-19, we check if n in r, it even returns "True" when outside the if/else function.
I also tried it this way if 13 <= n <= 19: and the issue still persists.
def fix_teen(n):
r = range(13,19)
if n in r :
return n == 0
elif n == 15 or n ==16:
return n
else :
return n
def no_teen_sum(a, b, c):
print(fix_teen(a))
print(fix_teen(b))
print(fix_teen(c))
print(a+b+c)
no_teen_sum(2, 13, 1)
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before the specified number.
range(start, stop)
for example to create a sequence of numbers from 0 to 5, and print each item in the sequence:
x = range(6)
for n in x:
print(n)
so r = range(13,19) has to be replaced with r = range(13,20)
The bit of code below, returns the result of an equality operator (n == 0).
if n in r :
return n == 0
If you want to return 0 if the n is in the range, simply return 0:
if n in r:
return 0
I need a function that takes n and returns 2n - 1 . It sounds simple enough, but the function has to be recursive. So far I have just 2n:
def required_steps(n):
if n == 0:
return 1
return 2 * req_steps(n-1)
The exercise states: "You can assume that the parameter n is always a positive integer and greater than 0"
2**n -1 is also 1+2+4+...+2n-1 which can made into a single recursive function (without the second one to subtract 1 from the power of 2).
Hint: 1+2*(1+2*(...))
Solution below, don't look if you want to try the hint first.
This works if n is guaranteed to be greater than zero (as was actually promised in the problem statement):
def required_steps(n):
if n == 1: # changed because we need one less going down
return 1
return 1 + 2 * required_steps(n-1)
A more robust version would handle zero and negative values too:
def required_steps(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 0
return 1 + 2 * required_steps(n-1)
(Adding a check for non-integers is left as an exercise.)
To solve a problem with a recursive approach you would have to find out how you can define the function with a given input in terms of the same function with a different input. In this case, since f(n) = 2 * f(n - 1) + 1, you can do:
def required_steps(n):
return n and 2 * required_steps(n - 1) + 1
so that:
for i in range(5):
print(required_steps(i))
outputs:
0
1
3
7
15
You can extract the really recursive part to another function
def f(n):
return required_steps(n) - 1
Or you can set a flag and define just when to subtract
def required_steps(n, sub=True):
if n == 0: return 1
return 2 * required_steps(n-1, False) - sub
>>> print(required_steps(10))
1023
Using an additional parameter for the result, r -
def required_steps (n = 0, r = 1):
if n == 0:
return r - 1
else:
return required_steps(n - 1, r * 2)
for x in range(6):
print(f"f({x}) = {required_steps(x)}")
# f(0) = 0
# f(1) = 1
# f(2) = 3
# f(3) = 7
# f(4) = 15
# f(5) = 31
You can also write it using bitwise left shift, << -
def required_steps (n = 0, r = 1):
if n == 0:
return r - 1
else:
return required_steps(n - 1, r << 1)
The output is the same
Have a placeholder to remember original value of n and then for the very first step i.e. n == N, return 2^n-1
n = 10
# constant to hold initial value of n
N = n
def required_steps(n, N):
if n == 0:
return 1
elif n == N:
return 2 * required_steps(n-1, N) - 1
return 2 * required_steps(n-1, N)
required_steps(n, N)
One way to get the offset of "-1" is to apply it in the return from the first function call using an argument with a default value, then explicitly set the offset argument to zero during the recursive calls.
def required_steps(n, offset = -1):
if n == 0:
return 1
return offset + 2 * required_steps(n-1,0)
On top of all the awesome answers given earlier, below will show its implementation with inner functions.
def outer(n):
k=n
def p(n):
if n==1:
return 2
if n==k:
return 2*p(n-1)-1
return 2*p(n-1)
return p(n)
n=5
print(outer(n))
Basically, it is assigning a global value of n to k and recursing through it with appropriate comparisons.
why this function doesn't work as a factorial function?
def Factor(n):
while n>=1:
print n*(n-1)
return 1
This will work
def Factor(n):
val=1
while n>=1:
val = val * n
n = n-1
return val
You have recursion and iteration mixed. Take a look at these two:
def factor_recursion(n):
while n>=1:
return n * factor_recursion(n-1)
return 1
def factor_iteration_for(n):
factor = 1
for i in range(n):
factor *= i+1
return factor
def factor_iteration_while(n):
factor = 1
while n >= 1:
factor *= n
n -= 1
return factor
print factor_iteration_for(4)
print factor_iteration_while(4)
print factor_recursion(4)
You never change the value of n to anything other than what is passed into the function.
I don't think this is going to do what you think it will. Looks like you've mixed recursion and iteration.
First of all, none of your code changes the value of n, so the loop will run indefinitely unless n == 1 when the function is called.
Secondly, you aren't accumulating a partial product inside the loop (hint: before the loop set result =, then inside it multiply the current value of result by the value of n.
Finally, you should then return the accumulated result rather than one.
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
print factorial(5)