The prompt for the exercise is as follows:
Uses a for loop to sum count values from start by increment. Use: total = sum_count(start, increment, count) Parameters: start - the range start value (int) increment - the range increment (int) count - the number of values in the range (int)
What i've come up with:
def sum_count(start, increment, count):
total = start
for i in range(start, count):
i = increment
total = i
else:
return total
When i call and print the function using values 2, 2, 5, the return should be 30, however I am only returning a value of 17. Which part of my code is wrong?
CodePudding user response:
If you want to repeat something x
times, you can use a loop for _ in range(x)
that doesn't do anything with the value _
itself.
Reading the task as
Use a for loop to sum
count
values fromstart
byincrement
means that count
is not the upper boundary of the range - that's what you did - but the number of values to add up. So for count
times, increase the start
value by increment
and take the sum of the values.
def sum_count(start, increment, count):
total = 0
for _ in range(count):
total = start
start = increment
return total
CodePudding user response:
You actually don't need a loop for that. It can be done in O(1)
Time complexity with help of Math.
# Arithmetic Progression
def sum_count(start, increment, count):
total = 2 * start (count -1) * increment
total = (n * total) // 2
return total
CodePudding user response:
def sum_count(start, increment, count):
total = 0
for i in range(start, count):
i = start increment
total = i
else:
return total
start
and increment
never change during the loop. They are always 1.
So you're adding (1 1)
four times, for a total of eight.
I don't understand why you expected 15.
CodePudding user response:
First you should note that the loop iterates 4 times not 5 times as you pass count as 5. Now if you want to have a loop to get 15 with 1,1,5 as parameters you can modify your code as:
def sum_count(start, increment, count):
total = 1
for i in range(start, count):
i = start increment
total = total i
start = start increment
print("Total: ", total)
return total
And if the total=0 then you get 14 instead of 15.