adventofcode2020's Issues
Use generator for day 1
Loved your day 1 blog post and code!
I noticed a quick way to improve the performance, by turning a list into a generator since only one answer is needed to be computed (in case there is more than one answer) and the search for more than the first answer can be deferred. Here's my benchmark and result:
import timeit
import math
from itertools import combinations
def get_answer(numbers: list[int], combos: int = 2) -> int:
result = [pair for pair in combinations(numbers, combos) if sum(pair) == 2020]
multiplied = math.prod(result[0])
return multiplied
def generator_get_answer(numbers: list[int], combos: int = 2) -> int:
result = (pair for pair in combinations(numbers, combos) if sum(pair) == 2020)
multiplied = math.prod(next(result))
return multiplied
if __name__ == "__main__":
with open("input.txt") as f:
numbers = [int(item.strip()) for item in f.readlines()]
n = 100
print(f"list: {timeit.timeit(lambda: get_answer(numbers, combos=3), number=n)}")
print(
f"generator: {timeit.timeit(lambda: generator_get_answer(numbers, combos=3), number=n)}"
)
Result:
list: 25.837099567
generator: 21.768024056000005
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.