Giter Site home page Giter Site logo

adventofcode2020's Introduction

adventofcode2020's People

Contributors

driscollis avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

dearbhupi

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 photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.