Last active
March 11, 2020 16:51
-
-
Save espoirMur/64e2218dba740d8e144668a587793947 to your computer and use it in GitHub Desktop.
Read a file containing integer and return the average of the integer in the file. the file can have path to another file which contain integer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 | |
2 | |
3 | |
4 | |
5 | |
another_file.txt | |
3 | |
4 | |
5 | |
6 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 | |
11 | |
12 | |
13 | |
14 | |
the_third_file.txt |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def read_file_recursively(filename): | |
""" | |
Read a file recursively and return the | |
sum and the count of integer in the file | |
Args: | |
filename ([string]): path to the base file to read | |
Returns: | |
[tuple]: sum of all items in the list, the number of items | |
""" | |
sum_, len_ = 0, 0 | |
with open(filename, 'r') as the_file: | |
for line in the_file.readlines(): | |
try: | |
sum_ += int(line) | |
len_ +=1 | |
except ValueError: | |
sub_sum, sub_leng = read_file_recursively(line.strip()) | |
sum_ += sub_sum | |
len_ += sub_leng | |
return sum_, len_ | |
if __name__ == "__main__": | |
sum_, len_ = read_file_recursively('a_file.txt') | |
print('the average is : ', sum_/len_) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 | |
50 | |
60 | |
70 | |
80 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment