Last active
October 30, 2020 01:10
-
-
Save classmember/b3b77d49b00b253e65e15aec0dad1854 to your computer and use it in GitHub Desktop.
Examining various approaches to mathematical software solutions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://www.facebook.com/photo?fbid=3769368939762114&set=gm.1306912559653197 | |
from itertools import chain | |
import timeit | |
# Interesting Code Sample | |
# expected = [x for xs in [[x]*int(expected_dist[x]) for x in range(0, N+1)] for x in xs] | |
# Original Appraoch | |
def whaaat(): | |
expected_dist = range(0,10) | |
N = 9 | |
return [x for xs in [[x]*int(expected_dist[x]) for x in range(0, N+1)] for x in xs] | |
# FP Approach | |
def flatten(x): | |
return list(chain.from_iterable(x)) | |
def ideal_matrix_fp(expected_dist = range(0,10), N = 9): | |
return [[x]*int(expected_dist[x]) for x in range(0, N+1)] | |
# Imperative Approach | |
def ideal_matrix_imperative(expected_dist = range(0,10), N = 9): | |
matrix = [] | |
for x in range(0, N+1): | |
matrix.append([x] * int(expected_dist[x])) | |
return matrix | |
# Output | |
ideal_matrix = ideal_matrix_fp | |
expected = flatten(ideal_matrix()) | |
print(expected) # [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9] | |
# Performance | |
timeit.timeit(ideal_matrix_fp) # 3.8432489000000487 <- fastest | |
timeit.timeit(ideal_matrix_imperative) # 4.300187199999982 | |
timeit.timeit(whaaat) # 4.519539700000003 <- slowest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment