Skip to content

Commit bc39e47

Browse files
committed
add decorator example
1 parent 96b29be commit bc39e47

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Copyright 2021 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import time
16+
import functools
17+
18+
19+
def memoize(func):
20+
answers = {}
21+
22+
@functools.wraps(func)
23+
def memoized(n):
24+
if n not in answers:
25+
answers[n] = func(n)
26+
return answers[n]
27+
28+
return memoized
29+
30+
31+
@memoize
32+
def fibonacci(n):
33+
if n <= 2:
34+
return 1
35+
return fibonacci(n - 1) + fibonacci(n - 2)
36+
37+
start = time.perf_counter()
38+
fib = fibonacci(40)
39+
end = time.perf_counter()
40+
41+
print(fib)
42+
print(end - start)
43+

0 commit comments

Comments
 (0)