Skip to content

Commit 362a031

Browse files
authored
Create unit9_ex9.2.3.py
1 parent 005caf0 commit 362a031

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

unit9_ex9.2.3.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# exercise 9.2.3 from unit 9
2+
'''
3+
Write a function called who_is_missing defined as follows:
4+
5+
def who_is_missing(file_name):
6+
The function accepts as a parameter a path to a text file (string).
7+
The file we return is passed as an argument and contains a list of integers from 1 to some n, which are not sorted, separated by commas, when one of the numbers in the sequence disappears (that is, missing from the sorted list).
8+
9+
The operation of the who_is_missing function:
10+
A. The function returns the missing number in the sequence (int).
11+
B. The function writes the missing number in sequence to a new file called found.txt.
12+
13+
An example of an input file and the execution of the who_is_missing function
14+
A file called findMe.txt:
15+
16+
8,1,9,7,4,6,3,2
17+
Running the who_is_missing function on the findMe.txt file:
18+
19+
>>> who_is_missing("c:\findMe.txt")
20+
5
21+
After the above run of the who_is_missing function, a new file called found.txt is created:
22+
23+
5
24+
'''
25+
26+
def who_is_missing(file_name):
27+
# Read the file and extract the numbers
28+
with open(file_name, 'r') as f:
29+
numbers = [int(num) for num in f.read().split(',')]
30+
31+
# Find the missing number
32+
expected_sum = sum(range(1, len(numbers) + 1))
33+
actual_sum = sum(numbers)
34+
missing_number = expected_sum - actual_sum
35+
36+
# Write the missing number to a new file
37+
with open('found.txt', 'w') as f:
38+
f.write(str(missing_number))
39+
40+
return missing_number
41+
42+
def main():
43+
result = who_is_missing("c:\findMe.txt")
44+
print(result)
45+
46+
if __name__ == "__main__":
47+
main()

0 commit comments

Comments
 (0)