-1

I'm trying to sum a number like: n -> n + (n-1) + (n-2) + ... + 1. My code is working, but not doing what I wanted it to do. I would like to know if I'm missing a parameter or something like this.

def s(n):
    a = n-1
    r = 0
    while a != 1:
        r = r + a
        a = a - 1
    return r
print (s(10))
Marina
  • 1
  • 1
  • 1
    How can it be both working and not doing what you wanted it to do? What do you want the result of `s(10)` to be, and what is your code printing? – Samwise Oct 05 '22 at 14:41
  • @Samwise: Reading between the lines working means it throws no exceptions and not-working means it doesn't give the desired result. – Steven Rumbalski Oct 05 '22 at 14:43
  • Can you clarify with some sample input, expected results, and what this thing is returning instead? Like what do you expect `s(10)` to spit out? – JNevill Oct 05 '22 at 14:43
  • If `n` is 1 do you expect the answer to be 2 or 1? – Steven Rumbalski Oct 05 '22 at 14:44
  • 1
    it looks like based on your description you are starting at the wrong index. Did you try setting `a=n` then decrementing from there? – amstergc20 Oct 05 '22 at 14:44
  • 1
    A simpler solution might be `return sum(range(1, n+1))`. – Samwise Oct 05 '22 at 14:45
  • My naive assumption is that you want `10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1` or `55`. If that's the case then change `a = n - 1` to `a = n` (otherwise you never add `10` to your total) and change `while a != 1` to `while >= 1:` (otherwise you never add `1` to your total) and rerun. – JNevill Oct 05 '22 at 14:46
  • Make sure you only ever call this function with values greater than 1. Easier would be *return int(n/2*(n+1))* – DarkKnight Oct 05 '22 at 15:16
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 05 '22 at 15:17

1 Answers1

1

A good way to debug code is to try walking through its execution with a simple example.

Let's try 4. We would expect to get the answer 4+3+2+1 = 10.

  • s(4)
  • Before the loop starts, a=3, r=0.
  • After the first iteration, a=2, r=3.
  • After the second iteration, a=1, r=5.
  • a != 1 is now False, so the loop ends, and we return r, which is 5. We only ever added 3 and 2 to it, and forgot to add 4 and 1.

Looking at this a level higher, your function is always missing the first (n) and the last (1) values of the sum. Fix both of these mistakes and your function should work how you expect. These are both examples of the classic fencepost error - your fence is missing posts at both ends.

Jacob Krall
  • 28,341
  • 6
  • 66
  • 76