0

The problem is add up all numbers from 1 to num. e.g: If the input is 4 then your program should return 10 because 1 + 2 + 3 + 4 = 10.

so this is my solution

def SimpleAdding(num):
  total = []
  for i in range(1,num+1):
    total.append(i)

 return sum(total)

and this is the top solution of the problem

def SimpleAdding(num): 
    if num == 1:
      return 1
    else:
      return num + SimpleAdding(num-1)

I wanna know how this kind of solution work without looping. It doesn't make sense to me at all. I'm just a beginner btw.

6
  • this is a recursive solution, which is generally avoided in idiomatic python Commented Oct 24, 2019 at 8:51
  • 1
    use (N*(N+1))/2 Commented Oct 24, 2019 at 8:51
  • Top solution uses a thing called function recursion, basically you can just initialize a function that will call itself over and over again Commented Oct 24, 2019 at 8:51
  • Also please consider using snake_case for naming variables and functions instead of CamelCase Commented Oct 24, 2019 at 8:53
  • oh..I don't know that there's something like that Commented Oct 24, 2019 at 8:54

1 Answer 1

1

here is diagram

enter image description here

def SimpleAdding(num): if num == 1: return 1 else: return num + SimpleAdding(num-1)

this is recursion

for SimpleAdding(5) this is happening :

1. 5 + SimpleAdding(4)
2. 5 + 4+ SimpleAdding(3) # recall again as no exit condition meet
3. 5+ 4+ 3 + SimpleAdding(2)
4. 5 + 4+ 3+ 2+ SimpleAdding(1)
5. 5+ 4 + 3+ 2+ 1 # finally giving 1 
Sign up to request clarification or add additional context in comments.

1 Comment

wow, I gotta learn this recursion thing. thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.