forked from su-ntu-ctp/5m-data-1.1-intro-data-science
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassignment.py
112 lines (82 loc) · 2.64 KB
/
assignment.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
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
106
107
108
109
110
111
112
# Question 1
# Write a function that prints "Fizz" when the number is divisible by 3, "Buzz" when the number is divisible by 5
# and "FizzBuzz" when the number is divisible by both 3 and 5.
# If the number is not divisible by either 3 or 5, the function should return the number itself.
def fizz_buzz(number):
"""Returns Fizz if number is divisible by 3, Buzz if divisible by 5, FizzBuzz if divisible by both 3 and 5.
If not divisible by either 3 or 5, returns the number itself.
>>> fizz_buzz(3)
'Fizz'
>>> fizz_buzz(5)
'Buzz'
>>> fizz_buzz(15)
'FizzBuzz'
"""
if number % 3 == 0 and number % 5 == 0:
return "FizzBuzz"
elif number % 3 == 0:
return "Fizz"
elif number % 5 == 0:
return "Buzz"
else:
return number
# Question 2
# Write a function that takes a list of numbers and returns the sum of the squares of all the numbers.
def sum_of_squares(numbers):
"""Returns the sum of the squares of all the numbers in a list.
>>> sum_of_squares([1, 2, 3])
14
>>> sum_of_squares([2, 4, 6])
56
"""
return sum(x ** 2 for x in numbers) # if list is too big use generator instead?
# Question 3
# Write a function that counts the number of vowels in a string.
def count_vowels(string):
"""Returns the number of vowels in a string.
>>> count_vowels("hello")
2
>>> count_vowels("aeiou")
5
"""
return sum(1 for char in string if char in 'aeiouAEIOU')
# Question 4
# Write a function that counts the number of repeated characters in a string.
def count_repeats(string):
"""Returns the number of repeated characters in a string.
>>> count_repeats("hello")
2
>>> count_repeats("aeiou")
0
"""
# This count the total numbers of repeated char
counts = {}
sum = int(0)
# for char in string:
# counts[char] = counts.get(char, 0) + 1
for char in string:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
#print(counts)
for count in counts.values():
if count > 1:
sum =+ count
return sum
# return sum(counts.values() for count in counts.values() if count > 1)
''' The set unique data structure will give clear sepration of repeated or not
seen = set()
repeats = set()
for char in string:
if char in seen:
repeats.add(char)
else:
seen.add(char)
# Return the total number of unique repeated characters
return len(repeats)
'''
#print(count_repeats("hellohello"))
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)