Im new to code and learning python . I got homework to make print Fibonacci
numbers for N = 11 and N = 200 using method called Memoization . I found solution but when im running the code i getting two things : 1 .
Traceback (most recent call last):
**File "python", line 7
if n== 1:
^**
**IndentationError: unexpected indent**
and second i got empty result sometime when im running. what is wrong which the code :
def fibonacci (n) :
# If we have cached the value, then return it
if n in fibonacci_cache:
return fibonacci_cache[n]
# Compute the Nth term
if n== 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = fibonacci(n-1) + fibonacci(n-2)
# Cache the value and return it
fibonacci_cache[n] = value
return value
print(n, ":", fibonacchi(11))
See #Alexis Drakopoulos for a direct fix to your code. If you want to simplify implementing memoization you can use a decorator called lru_cache.
from functools import lru_cache
#lru_cache(maxsize=None)
def fibonacci(n):
if n<= 2:
return 1
return fibonacci(n-1)+fibonacci(n-2)
def fibonacci(n):
# If we have cached the value, then return it
if n in fibonacci_cache:
return fibonacci_cache[n]
# Compute the Nth term
if n == 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = fibonacci(n-1) + fibonacci(n-2)
# Cache the value and return it
fibonacci_cache[n] = value
return value
print(n, ":", fibonacchi(11))
in Python indentation is everything, I am not sure if this is correct with the last lines with the cache.
I suggest using 4 spaces (using tabs) in order to be consistent.
Python looks at indentations to understand what you are trying to do.
Welcome to programming in Python and to StackOverflow :-)
There are three problems with your code:
1. The indentation: Python needs you to pay attention to the indentation, such that code at a particular level is indented the same amount.
For code that runs after something like an if statement, you need to put the next block of code indented. Then when you have the elif (which is at the same level as the if statement) you need to bring the indenting back out to match the level of the if.
You can indent with spaces or tabs, but you need to be consistent (ie stick to one)
It's possible that the editor you're using has messed up the intenting when you pasted the code in, and it's also possible that some of the indenting got messed up when you put it into StackOverflow too, but you need it to look like that below. In this case, each intent is two spaces (so indenting is first no spaces, then two spaces, then four spaces etc.)
2. Typos: The final statement has a typo (so you're not actually calling the function you define!)
3. Fibbonacci_cache: it isn't defined, so that's been added at the top
Hope that helps - good luck with the rest of your journey into programming... it will need perseverance but you'll get the hang in time I'm sure!
fibonacci_cache = {}
def fibonacci (n) :
# If we have cached the value, then return it
if n in fibonacci_cache:
return fibonacci_cache[n]
# Compute the Nth term
if n== 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = fibonacci(n-1) + fibonacci(n-2)
# Cache the value and return it
fibonacci_cache[n] = value
return value
print("n:", fibonacci(11))
Related
I tried to use the definition from Wikipedia for Hyperoperations and translate it into Python code.
My goal was to make it readable, making it fast was a task for later.
Here's the definition I used and below it is my code.
from Wikipedia: https://en.wikipedia.org/wiki/Hyperoperation#Definition
And now here's my code:
def hyperation(n, a, b):
if n == 0:
return b+1
if n == 1 and b == 0:
return a
if n == 2 and b == 0:
return 0
if n >= 3 and b == 0:
return 1
return hyperation(n-1, a, hyperation(n, a, b-1))
When I tried it with hyperation(n=1, a=3, b=3), what should basically be the same as
3 + 3
I always hit the recursion limit, doesn't matter how high I set it.
When trying this on paper by hand, it works perfectly fine. And while debugging I couldn't figure out what happens.
Thanks for every help!!!
In your last line the return keyword is missing.
First, your code was not formatted right, cause python is a indentation sensitive language.
Second, The last line of the error log indicates that the error is the addition of NoneType and int. You didn't return anything in the final else block, so that will return NoneType. Just add return at the beginning of the last sentence.
Third, you can delete every elif after return and just use if.
The problem is my code keeps reflecting a variable as zero and this is caused by the fact that the variable is assigned at the start of my function, so each time I call the function the value evaluates to zero. However I need this variable assignment for the code to work and placing it within the elif statements still evaluates to zero and placing the the variable outside the function causes the function not work.
The aim of the program is to count pairs of consecutive letters in a string using recursion with no for/while loops in the code.
def countpairs(s):
pairs=0
if len(s)<2:
return 0 #base case
elif s[0].lower() == s[1].lower(): #recursion
pairs=+1
return countpairs(s[1:])
else: #recursion
pairs=+0
return countpairs(s[1:])
print(countpairs('Hello Salaam'))
This code is supposed to evaluate to 2 because of "ll" and "aa".
You need to wrap your head a little around what the recursion will do: it will call the function recursively to count the pairs from that point on, then (it should) add the pair, if any, found by this instance.
So your function needs to do something with the result of the recursive call, not just return it unchanged. For example, instead of this
elif s[0].lower() == s[1].lower():
pairs = +1
return countpairs(s[1:])
you might write this:
elif s[0].lower() == s[1].lower():
return countpairs(s[1:]) + 1
Something along these lines. You'll need to do a bit more work to get it just right, but I hope you get the idea.
The problems is that the variable pairs resets every recursive call...
When using counting recursive algorithms you don't need a variable that counts, that's the beauty
Instead, try to think how to recursive call can help you count.
def countpairs(s):
if len(s)<2:
return 0
elif s[0].lower() == s[1].lower():
return countpairs(s[1:])+1
else:
return countpairs(s[1:])
print(countpairs('Hello Salaam'))
There you go, in the recursive call the "counter" gets bigger every time it should be, think of the counter as a part of the function stack (or something like that).
You need to fix the syntax: pairs=+1 should be pairs+=1, same for pairs=+0. And you can pass the total into the next level.
def countpairs(s, pairs=0):
if len(s)<2:
return pairs #base case
elif s[0].lower() == s[1].lower(): #recursion
pairs+=1
return countpairs(s[1:], pairs)
else: #recursion
pairs+=0
return countpairs(s[1:], pairs)
print(countpairs('Hello Salaam')) # 2
You can do it by creating a recursive nested function and defining pairs in the outer function. Here's what I mean (with fixes for other issues encountered):
def countpairs(s):
pairs = 0
def _countpairs(s):
nonlocal pairs # Since it's not local nor global.
if len(s) < 2: # base case
return pairs
elif s[0].lower() == s[1].lower():
pairs += 1
return _countpairs(s[1:]) # recursion
else:
return _countpairs(s[1:]) # recursion
return _countpairs(s)
print(countpairs('Hello Salaam')) # -> 2
The code will always evaluate to zero because the last recursion will always have the length of s being less than 2. Instead use the global keyword to be able to grab the value of pairs.
numberOfPairs = 0
pairsList = []
def countpairs(s):
global numberOfPairs
if len(s)<2:
print("doing nothing")
return 0 #base case
elif s[0].lower() == s[1].lower(): #recursion
numberOfPairs+=1
newString = f"{s[0]} is equal to {s[1]}"
print(newString)
pairsList.append(newString)
return countpairs(s[1:])
else:
print(f"nothing happened: {s[0]}") #recursion
return countpairs(s[1:])
print(f"\nThe returned value of countpairs is: {countpairs('Hello Salaam')}")
print(f"Number of pairs: {numberOfPairs}")
print(pairsList)
I have some textbook code that calls itself recursively. I don't understand the program flow. Here is the code:
def Recur_Factorial_Data(DataArray):
numbers = list(DataArray)
num_counter = 0
list_of_results = []
for num_float in numbers:
n = int(num_float)
1. result = Recur_Factorial(n)
list_of_results.append(result)
def Recur_Factorial(num):
if num == 1:
2. return num
else:
result = num*Recur_Factorial(num-1)
3. return result
if num < 0:
return -1
elif num == 0:
return 0
else:
return 0
In Recur_Factorial_Data, I loop through the data elements and call Recur_Factorial, which returns its value back to the calling function (Recur_Factorial_Data). I would expect that the lines marked 2 ("return num") and 3 ("return result") would always return a value back to the calling function, but that's not the case. For example, where the initial value (from the array DataArray) is 11, the function repeatedly calls itself until num is 1; at that point, the program falls to the line marked 2, but it does not loop back to the line marked 1. Instead, it falls through to the next line. The same happened on the line marked 3 -- I would expect it to return the result back to the calling function, but it does that in some cases and not in others.
I hope this is enough description to understand my question -- I just don't know why each return does not loop back to return the result to the calling function.
EDIT: The question at Understanding how recursive functions work is very helpful, and I recommend it to anyone interested in recursion. My question here is a bit different -- I asked it in the context of the program flow of the Python code where the recursive function is called.
If it call itself recursively 10 times, it will be at the 10th level of recursion and should go back 10 times at the point where there was a recursive call with an intermediate result and only then exit from the recursive function to the place where it was called. Learn more about recursion
Also try to rearrange instructions in Recur_Factorial function in this way:
def Recur_Factorial(num):
if num < 0:
return -1
elif num == 0:
return 0
elif num == 1:
return num
else:
return num * Recur_Factorial(num-1)
So I am really knew to coding, this is problem occurred about 5 minutes after I started. So I am currently doing this Coursera course made by an associate professor at Wesleyan (https://www.coursera.org/learn/python-programming-introduction). One of the exercises was:
Write a function absolutevalue(num) that computes the absolute value of
a number. You will need to use an 'if' statement. Remember if a number is less than zero then you must multiply by -1 to make it greater than zero.
So I figured my answer should be something like this:
absolutevalue(num):
""" Computes the absolute value of a number."""
if num >> 0:
absolutevalue =num
print(absolute value)
elif num<< 0:
absolutevalue == -1*num
print(absolutevalue)
else:
print("Absolute value is 0")
But when I run the code the console keeps saying:
Traceback (most recent call last):
File "", line 1, in
absolutevalue(5)
NameError: name 'absolutevalue' is not defined
For the past hour, I have been trying to fix the problem, yet I don't know how.
Could someone please help me, and keep in mind this is one of my first times trying to code something.
Thanks
A few errors:
Your def statement is missing. Normally a function definition should start with a line like def absolutevalue(num) rather than just absolutevalue(num).
You're using double comparators >> where you should be using single ones >. The former is a bit-shifting operator.
Within the function, you're using a variable with the same name as the function itself: absolutevalue. It's not necessarily wrong, but definitely not particularly handy.
Your function doesn't actually return the absolute value; it just prints it.
Edit: now that your question has been edited to use code blocks: your indentation is missing. :)
Hope that helps!
Function definitions in python need to start with def. Function blocks also need to be indented correctly, for example:
def absolutevalue(num):
""" Computes the absolute value of a number."""
if num > 0:
return num
elif num < 0:
return -1 * num
return 0
print(absolutenumber(-1))
print(absolutenumber(1))
print(absolutenumber(0))
>>> 1
>>> 1
>>> 0
You need to define the function absolutevalue and pass num into it. If you need to return the value instead, use return rather than print()
def absolutevalue(num):
if num > 0:
print(num)
elif num < 0:
abs_value = num * -1
print(abs_value)
else:
print("Absolute value is 0")
Basically, my question is about how to run this code? Finding the second smallest number from the given list using divide-and-conquer. I tried with print..But it gives me nothing. Just wanna see how this code works. Sorry for simple question, totally New in Python.
Well, just use a function call to run it, and a print to print it:
def two_min(arr):
n = len(arr)
if n==2: # Oops, we don't consider this as comparison, right?
if arr[0]<arr[1]: # Line 1
return (arr[0], arr[1])
else:
return (arr[1], arr[0])
(least_left, sec_least_left) = two_min(arr[0:n/2])
(least_right, sec_least_right) = two_min(arr[n/2:])
if least_left < least_right: # Line 2
least = least_left
if least_right < sec_least_left: # Line 3
return (least, least_right)
else:
return (least, sec_least_left)
else:
least = least_right
if least_left < sec_least_right: # Line 4
return (least, least_left)
else:
return (least, sec_least_right)
print two_main([12,2])
If you'd like to know how this works, you can take a look at the online python visualizer. Link.