forked from kiteco/kite-python-blog-post-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples.py
More file actions
86 lines (58 loc) · 1.25 KB
/
Copy pathexamples.py
File metadata and controls
86 lines (58 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# profiling
import cProfile
def fib(n):
if n < 2:
return 1
return fib(n - 1) + fib(n - 2)
cProfile.run('fib(30)')
# basic timeit usage
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
timeit.timeit('"-".join(map(str, range(100)))', number=10000)
# creating a decorator
from timeit import default_timer
def timer(func):
def wrapper(*args, **kwargs):
begin = default_timer()
result = func(*args, **kwargs)
end = default_timer()
print(f"{func.__name__} took {end - begin} seconds to compute.")
return result
return wrapper
@timer
def my_join():
return "-".join(map(str, range(10000)))
my_join()
# Optimizing for speed
my_var = 'beautiful'
# slow
msg = 'hello ' + my_var + ' world'
# better
msg = 'hello %s world' % my_var
# even better:
msg = 'hello {} world'.format(my_var)
# best (and most Pythonic in Python 3)
msg = f'hello {my_var} world'
x = 1
y = 2
# Bad
temp = x
x = y
y = temp
# Good
x, y = y, x
# Bad
a = 42
x = a
y = a
# Good
a = 42
x = y = a
# New Fibonacci calculator
def fibon(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a + b
list(fibon(5))