· 9 years ago · Oct 27, 2016, 10:44 PM
1
2#
3# fold
4
5def sum_nums(lst):
6 sum = 0
7 for el in lst:
8 sum = sum + el
9 return sum
10
11def sum_strs(lst):
12 sum = ""
13 for el in lst:
14 sum = sum + el
15 return sum
16
17print(sum_nums([1, 2, 3]))
18print(sum_strs(["A", "B", "C"]))
19
20init = 0
21
22def f(a, b):
23 return a + b
24
25def fold(lst):
26 acc = init
27 for el in lst:
28 acc = f(acc, el)
29 return acc
30
31
32print(fold([1, 2, 3]))
33
34def ave_grade(lst):
35 acc = 0
36 for el in lst:
37 acc = f(acc, el)
38 return acc / len(lst)
39
40
41print(ave_grade([80, 92, 65, 72])) # 77.25
42
43# [fold] Create a function that finds the minimum of a list of numbers
44
45def min_of_2(a, b):
46 if (a < b):
47 return a
48 else:
49 return b
50
51def min_num(lst):
52 acc = lst[0]
53 for el in lst:
54 acc = min_of_2(acc, el)
55 return acc
56
57print(min_num([80, 92, 65, 72])) # 65
58print(min_num(["A", "B", "C"])) # "A"
59
60
61# fold] Create a function that counts the number of vowels in a string
62
63def to_lower(ch):
64 return ch.lower()
65
66def is_vowel(upper_ch):
67 ch = to_lower(upper_ch)
68 return ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u"
69
70
71def count_vowel(count, ch):
72 if (is_vowel(ch)):
73 return count + 1
74 else:
75 return count
76
77def num_vowels(lst):
78 count = 0
79 for el in lst:
80 count = count_vowel(count, el)
81 return count
82
83print(num_vowels("Jheno Astillero Mollejon")) # 9
84
85# create a function that counts the number of gmail.com email addresses in a list
86def count_gmail(count, email):
87 if (email[-10:] == "@gmail.com"):
88 return count + 1
89 else:
90 return count
91
92def num_gmail(lst):
93 count = 0
94 for email in lst:
95 count = count_gmail(count, email)
96 return count
97
98print(num_gmail([ "abc@yahoo.com", "hij@gmail.com", "klj@gmail.com" ]))
99
100# Determine whether every name in the list begins with J
101
102def begins_with_j(acc, el):
103 return acc and (el[0] == 'j' or el[0] == 'J')
104
105 # if (acc == False):
106 # return False
107 # elif (el[0] == 'j' or el[0] == 'J'):
108 # return True
109 # else:
110 # return False
111
112def all_begins_with_j(lst):
113 acc = True
114 for el in lst:
115 acc = begins_with_j(acc, el)
116 return acc
117
118print(all_begins_with_j(["jheno", "joshua", "janice"]))
119print(all_begins_with_j(["jheno", "nisha", "janice"]))