Skip to content

Instantly share code, notes, and snippets.

@bartier
Created July 28, 2021 00:28
Show Gist options
  • Save bartier/90674ad0dc433239fe18eaf2c1a3150e to your computer and use it in GitHub Desktop.
Save bartier/90674ad0dc433239fe18eaf2c1a3150e to your computer and use it in GitHub Desktop.
Average of integers + recursion
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