Created
July 28, 2021 00:28
-
-
Save bartier/90674ad0dc433239fe18eaf2c1a3150e to your computer and use it in GitHub Desktop.
Average of integers + recursion
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 average_integers(filename, recursion=False): | |
integers_count = 0 | |
with open(filename.strip(), 'r') as reader: | |
lines = reader.readlines() | |
sum = 0 | |
for line in lines: | |
try: | |
sum += int(line) | |
integers_count = integers_count + 1 | |
except ValueError: | |
sum_file, integers_count_file = average_integers(line, recursion=True) | |
sum += sum_file | |
integers_count += integers_count_file | |
if recursion: | |
return sum, integers_count | |
average = sum / integers_count | |
return average | |
if __name__ == '__main__': | |
average = average_integers(filename="integers.txt") | |
print(average) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment