KaiquanMah commited on
Commit
57f0652
·
verified ·
1 Parent(s): e44fd07

Create 15. Fix and copy calculations

Browse files
Week 6 Files and errors/15. Fix and copy calculations ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ The file calculations.csv contains totals. However, the file is corrupt - each invoice contains an error.
3
+
4
+ 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.
5
+
6
+
7
+
8
+ So, for example, if the calculation had originally been
9
+ 2+4=6
10
+ ...it could now be in the form, for example
11
+ 2+XY=6
12
+
13
+ or
14
+ ZRQ+4=6
15
+
16
+ or even
17
+ 2+4=UIJMN
18
+
19
+
20
+
21
+ Write a function
22
+ fix_and_copy()
23
+ 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
24
+ '''
25
+
26
+
27
+
28
+
29
+ # approach 1
30
+ def fix_and_copy():
31
+ with open('calculations.csv', 'r') as source_file, open('corrected_calculations.csv', 'w') as dest_file:
32
+ for line in source_file:
33
+ # Strip whitespace and split the line
34
+ parts = line.strip().split('=')
35
+ left_side, result = parts
36
+
37
+ addends = left_side.split('+')
38
+
39
+ lhsdigit = addends[0].isdigit()
40
+ rhsdigit = addends[1].isdigit()
41
+ resultdigit = result.isdigit()
42
+
43
+ if lhsdigit == False:
44
+ lhs = int(result) - int(addends[1])
45
+ fixed_line = f"{lhs}+{addends[1]}={result}"
46
+ elif rhsdigit == False:
47
+ rhs = int(result) - int(addends[0])
48
+ fixed_line = f"{addends[0]}+{rhs}={result}"
49
+ else:
50
+ result = int(addends[0]) + int(addends[1])
51
+ fixed_line = f"{addends[0]}+{addends[1]}={result}"
52
+
53
+
54
+ # If we reach here, we've found the correct fix
55
+ dest_file.write(fixed_line + '\n')
56
+
57
+
58
+ # Call the function
59
+ fix_and_copy()
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+ '''error
68
+
69
+ Error in program execution
70
+ line 135, in
71
+ fix_and_copy()
72
+ File "/tmp/untrusted/test064f7b918-53d7-4381-bdac-1616c59e0764/test.py", line 107, in fix_and_copy
73
+ with open('calculations.csv', 'r') as source_file, open('corrected_calculations.csv', 'w') as dest_file:
74
+ File "/tmp/untrusted/test064f7b918-53d7-4381-bdac-1616c59e0764/test.py", line 13, in open
75
+ if fname in content:
76
+ NameError: name 'content' is not defined
77
+ '''
78
+