-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThe_Function_problems.py
73 lines (53 loc) · 1.7 KB
/
The_Function_problems.py
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
# version code 542eddf1f327+
coursera = 1
# Please fill out this stencil and submit using the provided submission script.
## 1: (Problem 1) Tuple Sum
def tuple_sum(A, B):
'''
Input:
-A: a list of tuples
-B: a list of tuples
Output:
-list of pairs (x,y) in which the first element of the
ith pair is the sum of the first element of the ith pair in
A and the first element of the ith pair in B
Examples:
>>> tuple_sum([(1,2), (10,20)],[(3,4), (30,40)])
[(4, 6), (40, 60)]
>>> tuple_sum([(0,1),(-1,0),(2,2)], [(3,4),(5,6),(7,8)])
[(3, 5), (4, 6), (9, 10)]
'''
return [(x1+x2, y1+y2) for ((x1, y1), (x2, y2)) in zip(A, B)]
## 2: (Problem 2) Inverse Dictionary
def inv_dict(d):
'''
Input:
-d: dictionary representing an invertible function f
Output:
-dictionary representing the inverse of f, the returned dictionary's
keys are the values of d and its values are the keys of d
Example:
>>> inv_dict({'goodbye': 'au revoir', 'thank you': 'merci'}) == {'merci':'thank you', 'au revoir':'goodbye'}
'''
return {value:key for (key, value) in d.items()}
## 3: (Problem 3) Nested Comprehension
def row(p, n):
'''
Input:
-p: a number
-n: a number
Output:
- n-element list such that element i is p+i
Examples:
>>> row(10,4)
[10, 11, 12, 13]
'''
return [p+i for i in range(n)]
comprehension_with_row = [row(i, 20) for i in range(15)]
comprehension_without_row = [[i+j for j in range(20)] for i in range(15)]
## 4: (Problem 4) Probability Exercise 1
Pr_f_is_even = 0.7
Pr_f_is_odd = 0.3
## 5: (Problem 5) Probability Exercise 2
Pr_g_is_1 = 0.4
Pr_g_is_0or2 = 0.6