0

I just started learning programming so when I thought to write code for summation of numbers using recursion in python. I encountered this problem, here how can I make add = 0 as static, Can someone pls help since my ans is coming as 0

def sum(n):  
    add = 0
    if n > 0: 
        add = add + n
        sumf (n-1)
        print add

sum(10) 
4
  • 1
    What do you mean by "make add = 0 as static"? Commented Jun 7, 2013 at 17:15
  • That won't work properly even in a language with static variables. The result would be sum(5) -> 15, sum(3) -> 21, should be 6. The static variable will only get initialized once in your program, not every time you compute a new (non-recursive) sum. Commented Jun 7, 2013 at 17:25
  • 2
    BTW, renaming a built-in such as sum() is a bad habit that will cause future pain. Commented Jun 7, 2013 at 17:36
  • Possible duplicate of Simulating a 'local static' variable in python Commented Mar 2, 2018 at 6:10

9 Answers 9

3

I think I see what you are asking. You can try to emulate a static variable like this in python:

def test():
    test.static_variable += 1
    print test.static_variable

test.static_variable = 0
test()
Sign up to request clarification or add additional context in comments.

Comments

2

If I'm reading your question correctly, you aren't really solving the problem with recursion here. You need to do something like this instead:

def sum(n):
    if n == 0:
        return n

    return n + sum(n - 1)

sum(n - 1) will return (n - 1) + sum(n - 2), so sum(n) ends up returning n + (n - 1) + sum(n - 2). It'll keep expanding until n is 0, and at that point, you have the sum of all the numbers from 0 to n.

3 Comments

or mySum = lambda n: n if n is 0 else n + mySum(n-1)
@dansalmo: Or just sum = lambda n: n * (n + 1) / 2
:), yeah but that is not recursive.
2

You can use a global, but that is generally poor practice. Instead, write it as a class. This way you can keep the variable add "bundled" with the code that needs it.

class Sum(object):
    def __init__(self, add=0):
        self.add = add
    def __call__(self, n):
        if n > 0:
            self.add += n
            sumf(n-1)
            print self.add

sum = Sum()   # create an instance
sum(10)       # 10
sum(10)       # 20

Comments

1

Aside from the fact that python has no static variables, do not use static values for recursion, use return values. Or if you do want to maintain state between calls, use a class.

Comments

0

Sadly, in Python, there is no such thing as a static variable. However, you could try to emulate this (to an extent) by defining add outside of the scope of your function. In addition, your 5th line reads sumf (n-1); is this intentional?

Comments

0

Python doesn't actually have practical static variables; more information is available here. Python also doesn't support passing numbers by reference.

Comments

0

Here is the right way to do this recursively:

def sum(n):
    if (n > 0):
        return n + sum(n-1)
    else:
        return 0

Comments

0

You could add attribute to a function and use hasattr() to initialize.

def func(n):  
    if not hasattr(func, "add"):
        func.add = 0

    func.add = func.add + n
    print func.add

func(10) # print 10
func(5)  # print 15
func(20) # print 35

Comments

0

You're trying to use a static variable as an accumulator variable -- as it is sometime done in C.

If you really want to do something like that, you might pass the accumulator down while recursively calling your function. And the function should return the accumulated value.

>>> def my_recursive_fct(n, acc = 0):
...     if n > 0:
...         acc = my_recursive_fct(n-1, acc)
...     return acc+n
... 
>>> my_recursive_fct(5)
15
>>> my_recursive_fct(0)
0

Not sure this is the best Python style. At least in that case ;)

For purists, you might wish to reorder instructions in order to end your function by the recursive call -- but I think this is pointless in Python as it does not perform tail call optimization (or am I wrong?)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.