TurkuPythonExercises / Week 6 Files and errors /15. Fix and copy calculations
KaiquanMah's picture
Create 15. Fix and copy calculations
57f0652 verified
raw
history blame
2.28 kB
'''
The file calculations.csv contains totals. However, the file is corrupt - each invoice contains an error.
The errors can be either in one of the addends or in the result (but only in one of them). As a result of the error, one of the original numbers in the calculation has been replaced by random letters.
So, for example, if the calculation had originally been
2+4=6
...it could now be in the form, for example
2+XY=6
or
ZRQ+4=6
or even
2+4=UIJMN
Write a function
fix_and_copy()
which reads the invoices from the file calculations.csv, corrects them to their original form and then writes the corrected invoices in the same order to the file corrected_calculations.csv
'''
# approach 1
def fix_and_copy():
with open('calculations.csv', 'r') as source_file, open('corrected_calculations.csv', 'w') as dest_file:
for line in source_file:
# Strip whitespace and split the line
parts = line.strip().split('=')
left_side, result = parts
addends = left_side.split('+')
lhsdigit = addends[0].isdigit()
rhsdigit = addends[1].isdigit()
resultdigit = result.isdigit()
if lhsdigit == False:
lhs = int(result) - int(addends[1])
fixed_line = f"{lhs}+{addends[1]}={result}"
elif rhsdigit == False:
rhs = int(result) - int(addends[0])
fixed_line = f"{addends[0]}+{rhs}={result}"
else:
result = int(addends[0]) + int(addends[1])
fixed_line = f"{addends[0]}+{addends[1]}={result}"
# If we reach here, we've found the correct fix
dest_file.write(fixed_line + '\n')
# Call the function
fix_and_copy()
'''error
Error in program execution
line 135, in
fix_and_copy()
File "/tmp/untrusted/test064f7b918-53d7-4381-bdac-1616c59e0764/test.py", line 107, in fix_and_copy
with open('calculations.csv', 'r') as source_file, open('corrected_calculations.csv', 'w') as dest_file:
File "/tmp/untrusted/test064f7b918-53d7-4381-bdac-1616c59e0764/test.py", line 13, in open
if fname in content:
NameError: name 'content' is not defined
'''