2

So, I want to create a loop that will increase the cost of an item any given amount of times while also logging the total of cost of the instance. The issue is that whenever I execute the program the output seems to be more than it should be, and if I change the value of the variable cost to 10, then it seems to go over slightly more than it should. Here's the code:

amount = 3
cost = 0
increase = 10

for i in range(amount):
  cost += increase
  increase += increase


total = cost
print(total)

When cost = 0 total becomes 70, when I think it should be 60, and then when cost = 10 total becomes 80 when I think it should be 90.

Any help would be appreciated- sorry for asking such a stupid question. It's probably a super simple fix.

2 Answers2

5

You double increase every time through the loop. I'm not sure how you expect to get 60 and 90 for results. I inserted a simple print at the bottom of the loop:

for i in range(amount):
  cost += increase
  increase += increase
  print("TRACE", cost, increase)

Output:

TRACE 10 20
TRACE 30 40
TRACE 70 80
70

Does this let you solve your problem? Perhaps what you need is to increase cost be an linearly escalating amount:

for i in range(amount):
  cost += increase
  increase += 10

Output:

TRACE 10 20
TRACE 30 30
TRACE 60 40
60
Prune
  • 76,765
  • 14
  • 60
  • 81
3

Pen + Paper helps to understand algorithms. In a pinch: comments inside the editor will do:

amount = 3
cost = 0
increase = 10

for i in range(amount)  #  0  #  1 #  2     # rounds
  cost += increase      # 10  # 30 # 70     # cost after increase
  increase += increase  # 20  # 40 # 80     # increased doubles

  # print(i, cost , increase)   # or debugging via outputting


total = cost                                # senseless
print(total) # 70

You might want to investigate Python debugging tips

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • I see. Knew I was doing something wrong. I was referring to the beginning instance of increase rather than looking at the new one. – 360programmer Jan 08 '19 at 17:29