Reputation: 381
So I have this function and I have done much of the work on it so far. I am trying to feed the results from the addseries function into the power function to give me for example:
6^6 + 5^5 + 4^4 + 3^3 + 2^2 + 1+ 0 .. I am having a problem with getting it to work. Any suggestions?
def power(n):
if(n<=0):
return 0
else:
return n**n
def addseries(num):
if(num == 0):
return 0
else:
print(num)
return sumseries(num - 1) + power(num)
Upvotes: 1
Views: 41
Reputation: 109616
Ignoring recursion:
n = 6
>>> sum(x ** x for x in range(n, 0, -1))
50069
# 6 ** 6 + 5 ** 5 + 4 ** 4 + 3 ** 3 + 2 ** 2 + 1 ** 1
# = 46656 + 3125 + 356 + 27 + 4 + 1
# = 50069
Using recursion:
def power_function(n):
if n < 1:
return 0
return n ** n + power_function(n - 1)
>>> power_function(6)
50069
Upvotes: 1
Reputation: 106863
Your code would actually work if you simply fix the indentation and typos (sumseries
should be addseries
, for example):
def power(n):
if(n<=0):
return 0
else:
return n**n
def addseries(num):
if(num == 0):
return 0
else:
return addseries(num - 1) + power(num)
so that:
print(addseries(6))
would output:
50069
which you can verify in Python shell:
>>> 1**1 + 2**2 + 3**3 + 4**4 + 5**5 + 6**6
50069
>>>
Upvotes: 1
Reputation: 28703
A bit simplified:
def addseries(num):
if(num == 0):
return 0
else:
print(num)
return num**num + addseries(num - 1)
Upvotes: 1