optimized the code and added a bunch of comment

please accept this pr pl0x pl0x pl0x pl0x pl0x pl0x
This commit is contained in:
zombie maniac 2022-12-03 14:00:20 -05:00
parent b76699fca6
commit 102988caed
Signed by untrusted user: nbrooks211
GPG key ID: F43C85C0DF0C334E

View file

@ -1,23 +1,32 @@
if __name__ == "__main__": if __name__ == "__main__":
elves = {} # Initialize empty list to store sums
sums = []
# Open input file
with open('input', 'r') as f: with open('input', 'r') as f:
elf = 0 # Initialize sum for current group of numbers
elves[0] = 0 current_sum = 0
# Read lines from file
for line in f: for line in f:
# If line is empty, append current sum to list and reset sum
if line.strip() == '': if line.strip() == '':
elf += 1 sums.append(current_sum)
elves[elf] = 0 current_sum = 0
else: else:
elves[elf] += int(line.strip()) # Add number from line to current sum
current_sum += int(line.strip())
largest = max(elves, key=elves.get) # Add last sum to list
print(f'Index: {largest}\nValue: {elves[largest]}') sums.append(current_sum)
top3 = 0 # Sort sums in descending order
for i in range(3): sums.sort(reverse=True)
largest = max(elves, key=elves.get)
top3 += elves[largest] # Print index and value of largest group of numbers
del elves[largest] print(f'Index: 0\nValue: {sums[0]}')
# Calculate sum of top 3 groups of numbers
top3_sum = sums[0] + sums[1] + sums[2]
print(f'Top 3: {top3_sum}')
print(f'Top 3: {top3}')