Created
August 2, 2017 19:39
-
-
Save arkenidar/b7442be2e9e4735af49dd074d089777d to your computer and use it in GitHub Desktop.
Simple algorithm implementation (multiplication with sums), simple concept of optimization (with measurement of performance improvement), PyLint applied (10/10)
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
#!/usr/bin/env python | |
''' Multiplication with sums. ''' | |
def multiplication(first, second): | |
''' Multiply: first*second. ''' | |
accumulator = 0 | |
for _ in range(second): | |
accumulator += first | |
return accumulator | |
def multiplication_optimized(first, second): | |
''' Multiply: first*second. ''' | |
repetitions = min(first, second) | |
added = max(first, second) | |
accumulator = 0 | |
for _ in range(repetitions): | |
accumulator += added | |
return accumulator | |
def testing(): | |
''' Tests unoptimized vs optimized versions. ''' | |
import timeit | |
print multiplication(3, 4) | |
print multiplication(100, 400) | |
time_multiplication = timeit.timeit('multiplication(100, 400)', | |
number=10000, | |
setup="from __main__ import multiplication") | |
print multiplication_optimized(100, 400) | |
time_multiplication_opt = timeit.timeit('multiplication_optimized(100, 400)', | |
number=10000, | |
setup="from __main__ import multiplication_optimized") | |
print time_multiplication, \ | |
time_multiplication_opt, \ | |
time_multiplication-time_multiplication_opt | |
if __name__ == '__main__': | |
testing() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment