I have this simple code using recursion that calculates the exponent. I understand how the recursion works here except for the: if exp <= 0: return 1. Say I call the function to give me five to the second power. If I have it return 1, it will give me the correct value of 25, but if 2 it returns 50, and 3, 75.
I am having a little trouble seeing how exactly this works within the environment:
def recurPower(base,exp):
if exp <= 0:
return 1
return base*recurPower(base,exp-1)
print str(recurPower(5,2))
I'm not sure if I understand the question. The 1 in the base case is there it is base^0 (for any non-zero base) and also because it is the multiplicative identity, so you can freely multiply by it.
It might help you try "unrolling" the recursion, to see where the numbers go:
recurPower(5, 2) =
5 * recurPower(5, 1) =
5 * 5 * recurPower(5, 0) =
5 * 5 * 1 =
25
Putting 2 or 3 in place of the 1 gets you two or three times the exponent you are trying to calculate.
whats happening here, is you'll end up with a cascade of returning values that will start with the value which is returned by that return 1 statement, for example:
recurPower(5,2) ==
recurPower(5,2) -> recurPower(5,1) -> recurPower(5,0)
the return statements will then make this:
1 -> (1)*5 -> (5)*5
(in reverse of the previous chain since we're cascading up the chain).
if you change the return value to 2 you will get:
2 -> (2)*5 -> (10)*5
(in reverse of the previous chain since we're cascading up the chain).
Numbers in brackets are returned from lower down the recursion chain.
Related
I'm given the task to define a function to find the largest pyramidal number. For context, this is what pyramidal numbers are:
1 = 1^2
5 = 1^2 + 2^2
14 = 1^2 + 2^2 + 3^2
And so on.
The first part of the question requires me to find iteratively the largest pyramidal number within the range of argument n. To which, I successfully did:
def largest_square_pyramidal_num(n):
total = 0
i = 0
while total <= n:
total += i**2
i += 1
if total > n:
return total - (i-1)**2
else:
return total
So far, I can catch on.
The next part of the question then requires me to define the same function, but this time recursively. That's where I was instantly stunned. For the usual recursive functions that I have worked on before, I had always operated ON the argument, but had never come across a function where the argument was the condition instead. I struggled for quite a while and ended up with a function I knew clearly would not work. But I simply could not wrap my head around how to "recurse" such function. Here's my obviously-wrong code:
def largest_square_pyramidal_num_rec(n):
m = 0
pyr_number = 0
pyr_number += m**2
def pyr_num(m):
if pyr_number >= n:
return pyr_number
else:
return pyr_num(m+1)
return pyr_number
I know this is erroneous, and I can say why, but I don't know how to correct it. Does anyone have any advice?
Edit: At the kind request of a fellow programmer, here is my logic and what I know is wrong:
Here's my logic: The process that repeats itself is the addition of square numbers to give the pyr num. Hence this is the recursive process. But this isn't what the argument is about, hence I need to redefine the recursive argument. In this case, m, and build up to a pyr num of pyr_number, to which I will compare with the condition of n. I'm used to recursion in decrements, but it doesn't make sense to me (I mean, where to start?) so I attempted to recall the function upwards.
BUT this clearly isn't right. First of all, I'm sceptical of defining the element m and pyr_num outside of the pyr_num subfunction. Next, m isn't pre-defined. Which is wrong. Lastly and most importantly, the calling of pyr_num will always call back pyr_num = 0. But I cannot figure out another way to write this logic out
Here's a recursive function to calculate the pyramid number, based on how many terms you give it.
def pyramid(terms: int) -> int:
if terms <=1:
return 1
return terms * terms + pyramid(terms - 1)
pyramid(3) # 14
If you can understand what the function does and how it works, you should be able to figure out another function that gives you the greatest pyramid less than n.
def base(n):
return rec(n, 0, 0)
def rec(n, i, tot):
if tot > n:
return tot - (i-1)**2
else:
return rec(n, i+1, tot+i**2)
print(base(NUMBER))
this output the same thing of your not-recursive function.
I'm currently taking a course in Computer Science, I got an assignment to use either Python or pseudocode to ask the user to enter a digit, then divide it by 2, and then count how many divisions it takes to reach 1 (and add 1 more as it reaches 1). I've never coded before but I came up with this; but it only returns a 1 no matter what I input.
def divTime (t):
if d <= 1:
return t + 1
else:
return t + 1, divTime(d / 2)
d = input("Enter a number:")
t = 0
print (divTime)(t)
You can add 1 to the recursive call with the input number floor-divided by 2, until the input number becomes 1, at which point return 1:
def divTime(d):
if d == 1:
return 1
return 1 + divTime(d // 2)
so that:
print(divTime(1))
print(divTime(3))
print(divTime(9))
outputs:
1
2
4
This works:
def div_time(d, t=0):
if d < 1:
return t
else:
return div_time(d/2, t+1)
d = input("Enter a number:")
print(f"t = {div_time(int(d))}")
It always returns 1 because you're always passing it 0.
It looks like you're "thinking in loops" – you don't need a separate counter variable.
How many times does it take to divide:
k smaller than 2? None.
k greater than or equal to 2? One more than it takes to divide k // 2.
That is,
def divTime(x):
if x < 2:
return 0
return 1 + divTime(x // 2)
or
def divTime(x):
return 0 if x < 2 else 1 + divTime(x //2)
Instead of providing a straight forward answer, I'll break the problem out into a few steps for students:
Ignore the input and edge cases for now, let's focus on writing a function that solves the problem at hand, then we may come back to providing an input to this function.
Problem statement confusion - You will often divide an odd number with a remainder, skipping the exact number 1 due to remainders. There is ambiguity with your problem from dealing with remainders - we will reword the problem statement:
Write a function that returns the number of times it takes to divide an input integer to become less than or equal to 1.
The next part is identifying the type of algorithm that can solve this type of problem. Since we want to run the function an unknown amount of times using the same function, this seems to be a perfect use case of recursion.
Say I provide 10 as an input. We then want to say 10/2=5 (count 1), 5/2=2.5 (count 2), 2.5/2=1.25 (count 3), 1.25/2=0.625 (count 4), return [4] counts.
Now we know we need a counter (x = x+1), recursion, and a return/print statement.
class solution:
''' this class will print the number of times it takes to divide an integer by 2 to become less than or equal to 1 '''
def __init__(self):
#this global counter will help us keep track of how many times we divide by two. we can use it in functions inside of this class.
self.counter=0
def counter_2(self, input_integer):
#if the input number is less than or equal to 1 (our goal), then we finish by printing the counter.
if input_integer<=1:
print(self.counter, input_integer)
#if the input is greater than 1, we need to keep dividing by 2.
else:
input_integer=input_integer/2
#we divided by two, so make our counter increase by +1.
self.counter=self.counter+1
#use recursion to call our function again, using our current inputer_integer that we just divided by 2 and reassigned the value.
self.counter_2(input_integer)
s=solution()
s.counter_2(10)
I'm new to Python, which is why I'm having trouble on a problem which others might find easy.
Background to this problem: Euler Project, question 2. The problem essentially asks us to add all the even terms in the Fibonacci sequence, so long that each term is under 4,000,000. I decided to do the problem a little differently than what many solutions online show, by calculating the nth Fibonacci term from a closed formula. For now, suppose this function is called Fibonacci(n).
What I'd essentially like to do is loop through an unknown amount of integers that represent the indexes of the Fibonacci set (i.e., 1, 2, 3, 4... etc) and plug each value into Fibonacci(n). If the result has no remainder when divided by 2, then add this Fibonacci number to some value initially set at 0.
Here's what I have so far:
def Fibonacci(n):
return (1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n))
i=0
FibSum = 0
nFib = 0
while (nFib <= 10):
nFib = Fibonacci(i)
if(nFib%2==0):
FibSum += nFib
i += 1
print FibSum
(Yes, as you can see, I'm constraining the Fibonacci sequence to end at 10 as opposed to 4,000,000; this is done merely for testing's sake.)
Now, here's my problem: when I run this code, I get 2.0 instead of 10.0 (2 and 8 are the two Fibonacci numbers that should be added together).
How come? My guess is that the loop stops after it gets to the third Fibonacci number (2) and doesn't continue beyond that. Does anyone see something wrong with my code?
Please comment if you have any further questions. Thanks in advance.
Solution provided by Gal Dreiman is fine but, conversion with in function is more better, below is your revised code:
def Fibonacci(n):
return int((1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n)))
You have a floating point problem (which you can read on here)- the returned value 'nFib' is not an integer and not a rounded value. I ran your code and added print for this value in every iteration and got:
0.0
1.0
1.0
2.0
3.0000000000000004
5.000000000000001
8.000000000000002
13.000000000000002
The solution for this is to modify your code as the following:
nFib = int(Fibonacci(i))
After that I got the output: 10
The problem is with nFib%2==0 comparison. Here you try to compare the float LHS with integer 0. So either modify the if loop as below or modify the return as return int((1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n))).
>>> def Fibonacci(n):
... return (1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n))
...
>>> i=0
>>> FibSum = 0
>>> nFib = 0
>>> while (nFib <= 10):
... nFib = Fibonacci(i)
... if(int(nFib%2)==0):
... FibSum += nFib
... i += 1
...
>>> print FibSum
10.0
def fact( n ):
"""fact( number ) -> number
Returns the number of permutations of n things."""
if n == 0:
return 1L
return n*fact(n-1L)
Anyone can explain me what this code does?
I am confused about the return statement ... n*fact(n-1L)! This seems Infinite for me :/
Thanks.
This is a recursive function.
Line by line
Line 1: if n == 0:
This is pretty self explanatory. In this if statement, we check to see if n is equal to 0.
Line 2: return 1L
If n is indeed equal to 0, we return 1L (1 Long, or essentially 1 in this case.) Note, that if we get to this return, we do not go on to the 3rd line because a return is like a break.
Line 3: return n*fact(n-1L)
We multiply n times n-1 and pass it back into the recursive function because it is checking for factorials, and we want to go all the way until n is 0 (6! shouldn't yield 6*5, it should yield 6*5*4*3*2*1.)
Not infinite. It is, in fact, a classic example of inductive definition, which in programming translates into recursion. For it to work, there need to be two parts:
Terminating condition, that describes when the problem is simple enough that we know the answer. In this case, what to do for fact(0).
Non-terminating condition, that describes how to break down a complex problem into simpler ones. In this case, look up fact(n - 1) and multiply by n.
So... let's say you have fact(3). It is not terminating, so it is 3 * fact(2). Still not terminating, so it is 3 * (2 * fact(1)). Still going! 3 * (2 * (1 * fact(0))). And there's our terminating condition, which does not call fact any more: 3 * (2 * (1 * (1))). So... not so infinite :)
Consider this basic recursion in Python:
def fibonacci(number):
if number == 0: return 0
elif number == 1:
return 1
else:
return fibonacci(number-1) + fibonacci(number-2)
Which makes sense according to the (n-1) + (n-2) function of the Fibonacci series.
How does Python execute recursion that contains another recursion not within but inside the same code line? Does the 'finobacci(number-1)' complete all the recursion until it reaches '1' and then it does the same with 'fibonacci(number-2)' and add them?
For comparison, the following recursive function for raising a number 'x' into power 'y', I can understand the recursion, def power calling itself until y==0 , since there's only one recursive call in a single line. Still shouldn't all results be '1' since the last command executed is 'return 1' when y==0, therefore x is not returned?
def power(x, y):
if y == 0:
return 1
else:
return x*power(x, y-1)
Short Answer
Each time Python "sees" fibonacci() it makes another function call and doesn't progress further until it has finished that function call.
Example
So let's say it's evaluating fibonacci(4).
Once it gets to the line return fibonacci(number-1) + fibonacci(number-2), it "sees" the call fibonacci(number-1).
So now it runs fibonacci(3) - it hasn't seen fibonacci(number-2) at all yet. To run fibonacci(3), it must figure out fibonacci(2)+fibonacci(1). Again, it runs the first function it sees, which this time is fibonacci(2).
Now it finally hits a base case when fibonacci(2) is run. It evaluates fibonacci(1), which returns 1, then, for the first time, it can continue to the + fibonacci(number-2) part of a fibonacci() call. fibonacci(0) returns 0, which then lets fibonacci(2) return 1.
Now that fibonacci(3) has gotten the value returned from fibonacci(2), it can progress to evaluating fibonacci(number-2) (fibonacci(1)).
This process continues until everything has been evaluated and fibonacci(4) can return 3.
To see how the whole evaluation goes, follow the arrows in this diagram:
In the expression fibonacci(number-1) + fibonacci(number-2) the first function call will have to complete before the second function call is invoked.
So, the whole recursion stack for the first call has to be complete before the second call is started.
does the 'finobacci(number-1)' completes all the recursion until it reaches '1' and then it does the same with 'fibonacci(number-2)' and add them?
Yes, that's exactly right. In other words, the following
return fibonacci(number-1) + fibonacci(number-2)
is equivalent to
f1 = fibonacci(number-1)
f2 = fibonacci(number-2)
return f1 + f2
You can use the rcviz module to visualize recursions by simply adding a decorator to your recursive function.
Here's the visualization for your code above:
The edges are numbered by the order in which they were traversed by the execution. The edges fade from black to grey to indicate order of traversal: black edges first, grey edges last.
(I wrote the rcviz module on GitHub.)
I would really recommend that you put your code in the Python tutor.
You will the be able to get it on the fly. See the stackframe, references, etc.
You can figure this out yourself, by putting a print function in the function, and adding a depth so we can print it out prettier:
def fibonacci(number, depth = 0):
print " " * depth, number
if number == 0:
return 0
elif number == 1:
return 1
else:
return fibonacci(number-1, depth + 1) + fibonacci(number-2, depth + 1)
Calling fibonacci(5) gives us:
5
4
3
2
1
0
1
2
1
0
3
2
1
0
1
We can see that 5 calls 4, which goes to completion, and then it calls 3, which then goes to completion.
Matthew and MArtjin are right but I thought I might elaborate:
Python does stuff from left to right whenever it can. Exceptions to this rule are implied by brackets.
in x*power(x, y-1): x is evaluated then power is evaluated
While in fibonacci(number-1) + fibonacci(number-2), fibonacci(number-1) is evaluated (recursively, til it stops) and then fibonacci(number-1) is evaluated
Your second recursion functions does this (example), so 1 will not be returned.
power(2, 3)
2 * power(2, 2)
2 * 2 * power(1,2)
2 * 2 * 2 * power(0,2) # Reaching base case
2 * 2 * 2 * 1
8
def fib(x):
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
print(fib(4))
def fib(n):
if n <= 1:
return n
else :
return fib(n - 1) + fib(n - 2)