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) 
Blender
  • 289,723
  • 53
  • 439
  • 496
lijo050
  • 233
  • 4
  • 14
  • 1
    What do you mean by "make `add = 0` as static"? – Blender Jun 07 '13 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. – morningstar Jun 07 '13 at 17:25
  • 2
    BTW, renaming a built-in such as sum() is a bad habit that will cause future pain. – dansalmo Jun 07 '13 at 17:36
  • Possible duplicate of [Simulating a 'local static' variable in python](https://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python) – Udayraj Deshmukh Mar 02 '18 at 06:10

9 Answers9

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()
Mark Beilfuss
  • 602
  • 4
  • 12
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
kindall
  • 178,883
  • 35
  • 278
  • 309
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.

Blender
  • 289,723
  • 53
  • 439
  • 496
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.

Joe
  • 6,497
  • 4
  • 29
  • 55
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?

jhunter_d
  • 65
  • 8
0

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

Community
  • 1
  • 1
IanPudney
  • 5,941
  • 1
  • 24
  • 39
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
Alper
  • 12,860
  • 2
  • 31
  • 41
0

Here is the right way to do this recursively:

def sum(n):
    if (n > 0):
        return n + sum(n-1)
    else:
        return 0
morningstar
  • 8,952
  • 6
  • 31
  • 42
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?)

Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125