this problem is available online please check on website before posting: http://
ID: 3593911 • Letter: T
Question
this problem is available online please check on website before posting: http://www.codestepbystep.com/problem/view/python/fileio/negative_sum
Write a function named negative_sum that accepts a string as a parameter representing a file name, which reads input from that file containing a series of integers, and determine whether the sum starting from the first number is ever negative. The function should pra message indicating whether a negative sum is possible and should return True if a negative sum can be reached and False if not. For example, if the file contains the following text, your function will consider the sum of just one number (38), the sum of the first two numbers (38 + 4), the sum of the first three numbers (38 + 4 + 19), and so on up to the sum of all of the numbers:
None of these sums is negative, so the function would produce the following message and return False:
If the file instead contains the following numbers, the function finds that a negative sum of -8 is reached after adding 6 numbers together (14 + 7 + -10 + 9 + -18 + -10):
It should output the following and return True, indicating that a negative sum can be reached:
Type your Python solution code here:
Explanation / Answer
def negative_sum(filename):
sumNumber = 0
i = 0
with open(filename) as fh:
for line in fh:
linedata = line.split()
for d in linedata:
try:
a = int(d)
i += 1
sumNumber += a
if sumNumber < 0:
print("%d after %d steps" % (sumNumber, i))
return True
except ValueError:
continue
print("no negative sum")
return False
When ran for
output
When ran for
output
# copy pastable code link: https://paste.ee/p/5Xmpp
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.