Skip to content

Commit 4300b16

Browse files
authored
Merge pull request #28 from code-for-tomorrow/ch11-ke-hao
Ch. 11 Exercise Count Magical
2 parents f97ea7a + 52c8b98 commit 4300b16

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Write a function called count_magical
2+
# that returns the number of even numbers
3+
# in a given list. In the function,
4+
# if the number of evens is greater than
5+
# half of the length of the list, print "Magical"
6+
# Else, print "Not Magical"
7+
#
8+
# Write a function called main which tests
9+
# the count_magical function on at least
10+
# 3 different lists of integers. Use the main
11+
# function to test count_magical by calling main().
12+
13+
# write code here
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Write a function called count_magical
2+
# that returns the number of even numbers
3+
# in a given list. In the function,
4+
# if the number of evens is greater than
5+
# half of the length of the list, print "Magical"
6+
# Else, print "Not Magical"
7+
#
8+
# Write a function called main which tests
9+
# the count_magical function on at least
10+
# 3 different lists of integers. Use the main
11+
# function to test count_magical by calling main().
12+
13+
14+
def count_magical(my_list):
15+
number_of_evens = 0
16+
for n in my_list:
17+
if n % 2 == 0:
18+
number_of_evens += 1
19+
20+
if number_of_evens > len(my_list) / 2:
21+
print("Magical")
22+
else:
23+
print("Not Magical")
24+
25+
return number_of_evens
26+
27+
28+
def main():
29+
list_1 = [1, 2, 3, 4, 5, 6] # not magical, 3 evens
30+
list_2 = [0, 35, 1, 35, 2, 4] # not magical, 3 evens
31+
list_3 = [10, 20, 12, 3, -9] # magical, 3 evens
32+
33+
print("Number of evens in list 1:", count_magical(list_1))
34+
print("Number of evens in list 2:", count_magical(list_2))
35+
print("Number of evens in list 3:", count_magical(list_3))
36+
37+
38+
main()

0 commit comments

Comments
 (0)