|
|
|
|
|
by ue_
3495 days ago
|
|
I have no idea if this works (it did for 3 test cases), and I still end up reading through the array (but not the file) twice. # assuming file with $100\n$200\n$23\n$50 etc.
linenum_vals = []
with open('numbers.txt') as input_file:
for i, line in enumerate(input_file):
try:
linenum_vals.append([i, float(line[:-1][1:])])
except ValueError:
print("Not a number value on line", i)
total = 0
for i in linenum_vals:
total += i[1]
half = total/2.0
for p in range(len(linenum_vals)):
if linenum_vals[p][1] == half:
print("Half of total found on line", linenum_vals[p][0])
break
else:
if linenum_vals[p-1][1] < half and linenum_vals[p][1] > half:
print("Half of total in between lines", p-1, p)
break
else:
if p+1 != len(linenum_vals):
if linenum_vals[p][1] < half and linenum_vals[p+1][1] > half:
print("Half of total in between lines", p, p+1)
break
print("Half of total wasn't found in the file.") # probably because the list of values isn't in order
What way would you do it? I feel like I'm missing something. |
|
At the end, return the highest key in the dictionary for your total, and then run a reduce that returns the first key/value pair that is >= half the total