max_cal = 0 cur_cal = 0 withopen('01.txt', 'r') as fp: for line in fp: line = line.strip() iflen(line): cur_cal += int(line) else: max_cal = max(max_cal, cur_cal) cur_cal = 0 print(max_cal)
Answer: 70720
Part Two
取前 k 大的或前 k 小的這種用 heap 應該就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import heapq
pq = [] cur_cal = 0 withopen('01.txt', 'r') as fp: for line in fp: line = line.strip() iflen(line): cur_cal += int(line) else: heapq.heappush(pq, -cur_cal) cur_cal = 0 total = 0 for i inrange(3): total -= heapq.heappop(pq) print(total)