-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunit_eighteen.py
More file actions
105 lines (85 loc) · 2.19 KB
/
unit_eighteen.py
File metadata and controls
105 lines (85 loc) · 2.19 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""recursive functions"""
"""def display_a():
print('start a')
display_c()
print('c executed')
print('end a')
def display_b():
print('start b')
display_a()
print('a executed')
print('end b')
def display_c():
print('start c')
display_b()
print('b executed')
print('end c')
display_c()
"""
"""
n = int(input('Enter: `'))
def fact(n):
if n == 0:
return 1
else:
return n + fact(n - 1)
print(fact(n))"""
"""def fibonacci(n): # A recursive implementation of the Fibonacci function
if n <= 1:
return n
else:
return (fibonacci(n - 1) + fibonacci(n - 2)) # F_n = F_(n-1) + F_(n-2)
nterms = int(input('How many Fibonacci numbers do you want?'))
# Cannot find Fibonacci number if it is negative
if nterms <= 0:
print('Error : Enter a positive number.')
else:
print('Fibonacci sequence:', end = ' ')
for i in range(nterms):
print(fibonacci(i), end = ' ')"""
def fibonacci(n, memo={}):
if n in memo:
return memo[n] # Return cached result if available
if n == 0:
return 0
elif n == 1:
return 1
else:
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
return memo[n]
nterms = int(input('How many Fibonacci numbers do you want? '))
if nterms <= 0:
print('Error: Enter a positive number.')
else:
print('Fibonacci sequence:', end=' ')
for i in range(nterms):
print(fibonacci(i), end=' ')
"""Paper Coding 1"""
print()
def sum(n):
if n == 1:
return 1
else:
return n + sum(n - 1)
n = int(input('Enter a number: '))
print(sum(n))
"""PAper Coding 2"""
def sum_pow(x, n):
if n == 0:
return 1
else:
return x * sum_pow(x, n - 1)
x = int(input('Enter a x : '))
n = int(input('Enter a n : '))
print(sum_pow(x, n))
"""Pair Programming"""
def factorial(k):
if k == 0:
return 1
else:
return k * factorial(k - 1)
def euler(n):
if n == 0:
return 1
return 1 / factorial(n) + euler(n - 1)
print('eular(20) =', round(euler(20), 5))