Repository navigation
Expand file tree
/
Copy pathexercises.py
More file actions
181 lines (122 loc) · 5.64 KB
/
Copy pathexercises.py
File metadata and controls
181 lines (122 loc) · 5.64 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""A series of exercises to work through after completing the software carpentries.
Note: there are non-exhaustive tests at the bottom of the file that you can reference
"""
def every_other_element(in_list):
"""Task:
Given a list return the elements at the odd indices
Hint: This can be done in a one-liner using a list comprehension but you're welcome to use a for-loop, too
"""
return in_list[::]
# raise NotImplementedError
def is_palindrome(in_str):
"""Task:
Determine if an input string is a palindrome. There are multiple ways of doing this but you should try doing
this with a for-loop (you will have to do some indexing) and using string slicing.
Additional consideration:
- test your implementation with both strings and lists! See what happens
"""
raise NotImplementedError
def fizzbuzz(n):
"""Task:
Given an integer n that is greater than 1, return a list of length n, where the entries are strings.
The element at the i-th index should be defined by the following:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
For example, given:
- fizzbuzz(3) you should output ["1", "2", "Fizz"]
- fizzbuzz(5) you should output ["1", "2", "Fizz", "4", "Buzz"]
"""
raise NotImplementedError
def happy_numbers(n):
"""Context:
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a
cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.
Task:
Return true if n is a happy number, and false if not.
"""
raise NotImplementedError
def nth_fibonacci_number(n):
"""Context:
A Fibonacci number is a number where the i-th Fibonacci number is the sum of the i-1th and i-2 Fibonacci numbers i.e.
F_i = F_{i - 1} + F_{i - 2}
A natural way of calculating this is via recursion.
Task:
When the input is 0 or negative, it should return 0. When the input is 1 or 2 it should return 1.
In all other cases it should follow the recurrence formula we specified earlier.
You may assume that the input number is greater-than-or-equal-to 0
"""
raise NotImplementedError
def safe_divide(numerator, denominator):
"""Context:
1) there are multiple ways to handle errors:
- Look Before You Leap (LBYL)
- Easier to Ask Forgiveness Than Permission ( EAFP )
the gist of these are that in one you defensively program, but in the other you let the error occur and then recover.
There are arguments for one over the other, but we will make you use the EAFP approach here.
For more information see: https://realpython.com/python-lbyl-vs-eafp/
Task:
Division by zero in python throws an exception: ZeroDivisionError. However, we might want to recover from this!
For this task, do not check if the denominator is zero. Instead, catch the exception and return a tuple of the
numerator, denominator, and a string describing what happened. If the division is successful, return the quotient
"""
raise NotImplementedError
def count_frequencies(in_str, ignore_case=False):
"""Task:
count the frequencies of the words coming into `in_str`. There is an optional argument
that the user can pass in where they want to ignore the case of the words.
Return a dictionary where the keys are the words and the values are the counts
Hint:
You might find the "split" and "lower" functions useful here
"""
raise NotImplementedError
#####################################
# Simple test Cases:
# Note: the following tests do not test all the edge-cases! You should think through
# them and add any others that might be necessary
#####################################
def test_every_other_element():
assert every_other_element([1, 2, 3]) == [2]
assert every_other_element(["uh-oh"]) == []
def test_is_palindrome():
assert is_palindrome("racecar") == True
assert is_palindrome("wow") == True
def test_fizzbuzz():
assert fizzbuzz(3) == ["1", "2", "Fizz"]
assert fizzbuzz(5) == ["1", "2", "Fizz", "4", "Buzz"]
def test_happy_numbers():
assert happy_numbers(4) == False
assert happy_numbers(13) == True
def test_fibonacci():
assert nth_fibonacci_number(8) == 21
assert nth_fibonacci_number(10) == 55
def test_safe_divide():
# Normal division returns the quotient
assert safe_divide(10, 2) == 5
assert safe_divide(7, 2) == 3.5
# Division by zero is recovered from: (numerator, denominator, message)
result = safe_divide(10, 0)
assert result[0] == 10
assert result[1] == 0
assert isinstance(result[2], str)
def test_count_frequencies():
assert count_frequencies("the cat the dog") == {"the": 2, "cat": 1, "dog": 1}
# Case matters by default
assert count_frequencies("The the") == {"The": 1, "the": 1}
# ...unless we ignore it
assert count_frequencies("The the", ignore_case=True) == {"the": 2}
# Edge case: empty string
assert count_frequencies("") == {}
if __name__ == "__main__":
# test_every_other_element()
# test_is_palindrome()
# test_fizzbuzz()
# test_happy_numbers()
# test_fibonacci()
# test_safe_divide()
# test_count_frequencies()
print("All done!")