1

I am trying to write a loop that calculates the total of the following series of numbers: 1/30 +2/29+3/28+…+30/1. I'm having trouble figuring out how to add, because the program below just displays the total as 0.033333333....

def main():
  A=1
  B=30
  sum=(A/B)
  while A<=30:
      A+=1
      B-=1
  print('Total:',sum)
main()
1
  • To compute the exact sum directly: f = sum(fractions.Fraction(i, 31-i) for i in range(1, 31)); print(f, float(f)) Commented Mar 2, 2014 at 14:36

4 Answers 4

4

You are not adding anything to sum on each iteration. You must add

sum = sum + A / B

inside the while loop. But you have to initialize sum with zero:

sum = 0

Note:

Don't use sum as name of a variable because it's a built-in function of Python. You can call that variable result, my_sum, ...

Code:

def main():
    A = 1
    B = 30
    result = 0
    while A <= 30:
        print A, B
        result += (A / B)
        A += 1
        B -= 1

    print('Total:', result)
main()

Also:

You can see that in each term of the sum, A + B == 31, so B == 31 - A. Therefore, the code can be simplified:

def main():
    A = 1
    result = 0
    while A <= 30:
        result += (float(A) / (30 - A + 1))
        A += 1
    print('Total:', result)
Sign up to request clarification or add additional context in comments.

Comments

4

Create two lists of the desired numbers, compute the value of each fraction, then sum then.

sum(( a/b for a,b in zip(range(1,31),range(30,0,-1))))

1 Comment

Since he said he got 0.0333..., he must be using Python 3.x
2

You may mean this to be your code:

def main():
    A=1
    B=30
    sume= A/B
    while B>1:
        A+=1
        B-=1
        sume += A/B
    print('Total:',sume)

main()

Moreover, you shouldn't override sum unless you know you are not using it in your program elsewhere. sum is a reserved word in python.

Comments

0

total = 0.0

for x in range(1, 31, 1):

z = x / (31-x)

total += z

print(f'The total is {total:.2f}.')

1 Comment

Hello, please don't just submit code in your answer(s), add some details as to why you think this is the optimal solution.

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.