What is wrong with my python hyperoperation recursive function? - python

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.

Related

Python fibonacci unexpecred indent

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))

Python: Loop through the elif section of an if statement

I'm relatively new to python, so I'm not even sure if I'm approaching this in the correct way. But I haven't found a good solution anywhere.
In order to avoid very ugly and repetitive code, i want to loop the elif part of the if statement.
This is the ugly code i want to fix:
def codeToChar(code):
chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"
if code == ord(chars[0]): ##### SUPER UGLY
return chars[0]
elif code == ord(chars[1]):
return chars[1]
elif code == ord(chars[2]):
return chars[2]
elif code == ord(chars[3]):
return chars[3]
elif code == ord(chars[4]):
return chars[4]
elif code == ord(chars[5]):
return chars[5]
..... etc .....
else:
return "wat"
As you can see, the index is incrementing by one, so I thought looping would be very simple. However, when I tried the following, it didn't work because this must be formulated as an if, elif, elif, else statement, and not many if statements.
My failed attempt:
for x in xrange(0,len(chars)-1):
if code == ord(chars[x]):
return chars[x]
else:
return "wat"
How would I go about looping this?
Note: if it's of any relevance, I'm coding this using the curses module, building a keyboard interface for a project.
Many thanks
for c in chars:
if code == ord(c):
return c
return "wat"
the second return is executed only if no previous return has been previously executed (i.e. no character matched).
It seems like you are just checking whether the code is one of the characters or not. One clean solution would be:
c = chr(code)
return c if c in chars else "wat"
Use a dict:
chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"
chars_dict = {ord(c): c for c in chars}
return chars_dict.get(code, 'wat')
You don't want to return "wat" inside the loop as it'll trigger as soon as the if statement fails once. You only want to return an error if all iterations failed. Unindent the else block to do this.
for x in xrange(0,len(chars)-1):
if code == ord(chars[x]):
return chars[x]
else:
return "wat"
The else block is optional. You could also write:
for x in xrange(0,len(chars)-1):
if code == ord(chars[x]):
return chars[x]
return "wat"

Name 'absolute value' not defined in Python

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")

Confused with recursive functions in python

Hey guys am new to python app development.i have came to learn about recrusive functions in python. The code which i have done
def something(a):
if a == 0:
return 0
else:
return 2 + something(a)
When i called the function like pythons(5) it calls me error like TypeError: something() missing 1 required positional argument: 'b'
I would like to do add two to a number like if i call something(5) it must return 5+2 = 7
I dunno why am getting this error.Hope you guys can help me out in solving this..I aplogise if this is a low grade question on so..
Any help would be appreciated ..Thanks in advance..
There are a couple of issues here. Firstly python code is whitespace sensitive when it comes to indentation (note that the question got edited, the formatting was not correct previously). Then secondly you need to match up the number of arguments provided to the functions:
def pythons(a,b):
if a == 0:
return a
else:
return a * pythons(a,b-1)
When you write def pythons(a,b): you are defining a function with the name pythons and you are specifying that it takes exactly 2 arguments, a and b. Previously you tried to call it with pythons(b-1), the error message tells you exactly what has gone wrong, you only provided 1 argument when the function expected to get 2 arguments.
That is because in your method, when you recursively call pythons, you are not passing two arguments. This is probably what you want:
def pythons(a,b):
if a == 0:
return a
else:
return a * (b-1)
or simply (with same results):
def pythons(a,b):
return a * (b-1)
If your aim is to add two numbers recursively then this would be a more appropriate recursive function.
def add(a, b):
if a == 0 and b ==0:
return 0
elif b == 0 and a>= 0:
return 1 +add(a-1, 0)
elif a ==0 and b>= 0:
return 1 + add(0, b-1)
else: return 2 + add(a-1, b-1)

Flow of recursion in python roman to arabic

So I just solved the last quiz on recursion on codeacademy. But while I was trying to understand the flow of execution of this code on pythontutor.org, I just couldnt follow the flow of this code.
def rval(letr):
if(letr=='I'):
return 1
elif(letr=='V'):
return 5
elif(letr=='X'):
return 10
elif(letr=='L'):
return 50
elif(letr=='C'):
return 100
elif(letr=='D'):
return 500
elif(letr=='M'):
return 1000
else:
return "error"
def arabic(n):
if len(n)==0:
return 0
elif len(n)==1:
return rval(n)
elif len(n)==2:
if rval(n[0])>rval(n[1]):
return rval(n[0])+rval(n[1])
else:
return rval(n[1])-rval(n[0])
else:
return arabic(n[len(n)-2:])+arabic(n[:len(n)-2])
arabic('DXCVI')
======PROBLEM FACED======
My question is this --
Suppose I run arabic('DXCVI'), then how does this line arabic(n[len(n)-2:])+arabic(n[:len(n)-2]) get executed
Do both arabic(n[len(n)-2:]) & arabic(n[:len(n)-2]) start getting executed simultaneously or does the second term wait until the first is done/returns a value ?
The left part arabic(n[len(n)-2:]) is always called first. An easy way to find this out is to put a print statement in your arabic(n) function.
Try something like this:
def arabic(n):
print n
if len(n)==0:
return 0
elif len(n)==1:
return rval(n)
elif len(n)==2:
# more code
Which would output this:
DXCVI
VI
DXC
XC
D
Proving that the left side, arabic(n[len(n)-2:]), gets called before +arabic(n[:len(n)-2]).
First arabic(n[len(n)-2:]) (the left part) is executed, then arabic(n[:len(n)-2]) (the right part) is executed.
Remember that the first part may also have recursive calls, so the second one must wait until it returns a value to get executed.

Categories