Read And Add The Last Value From An Array Pulled From A Text File
Solution 1:
Algebraically, what you describe is much simpler than the process you've laid out. You add up all the numbers and see whether the result is in the range [-15, 15]. Replace your two intended loops with this conditional check:
if -15 <= sum(value) <= 15:
# Here, insert the code for matching stuff.
As for why your given code fails ... the loops are not correct. I'm not sure what you're trying to do with the two +1 expressions; they don't affect the data flow in any way, because you don't store the value.
The second loop is confused. In each iteration, you take a single value from the list. Your print statement treats that single value as if it were a list, too (you can make a list of lists in Python, but this program doesn't do that). When you try to access the last element of a single integer, Python informs you of the confusion.
To print the last value of the list, simply use print value[-1]; don't iterate through the entire list to find the last item.
That said, we now have the original problem: how to sum the negative and positive values using the algorithm you describe. You need to run your lists in the reverse order. I'll do this in two loops, one each for positive and negative:
time = range(10)
value = [213, -999, 456, -1100, -16, 5, 42, -80, 9, 10]
last_neg = 0for i inrange(len(value)-1, -1, -1): # Go through the list in reverse orderif value[i] < 0:
value[i] += last_neg
last_neg = value[i]
last_pos = 0for i inrange(len(value)-1, -1, -1): # Go through the list in reverse orderif value[i] > 0:
value[i] += last_pos
last_pos = value[i]
print"pos & neg sums", value[0], value[1]
value[0] += value[1]
print"grand sum", value[0]
print"Check the summation:", value
Output:
pos & neg sums 735 -2195
grand sum -1460
Check the summation: [-1460, -2195, 522, -1196, -96, 66, 61, -80, 19, 10]
Post a Comment for "Read And Add The Last Value From An Array Pulled From A Text File"