-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathunit4_assignment_02.py
More file actions
54 lines (43 loc) · 1.71 KB
/
Copy pathunit4_assignment_02.py
File metadata and controls
54 lines (43 loc) · 1.71 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
__author__ = 'Kalyan'
notes = '''
For this assignment, you have to define a few basic classes to get an idea of defining your own types.
'''
# For this problem, define a iterator class called Repeater which can be used to generate an infinite
# sequence of this form: 1, 2, -2, 3, -3, 3, etc. (for each number N is repeated N times with opposing signs).
# Use the class instance state to keep track of the iteration state. Do not allocate large amounts of memory :)!
# Refer to: https://docs.python.org/3/library/stdtypes.html#iterator-types
class Repeater:
pass
# get the sum of next n numbers returned by the repeater
def get_sum(r, n):
sum = 0
count = 0
# we can write code like this as r is an iterator
for value in r:
sum += value;
count += 1
if count == n:
break
return sum
def test_repeater_basic():
r = Repeater()
assert hasattr(r, "__init__")
assert hasattr(r, "__iter__")
assert hasattr(r, "__next__")
def test_repeater_function():
assert 1 == get_sum(Repeater(), 1)
assert 3 == get_sum(Repeater(), 2)
r1 = Repeater()
r2 = Repeater()
# state must be remembered across calls
assert 1 == get_sum(r1, 1)
assert 2 == get_sum(r1, 1)
assert -2 == get_sum(r1, 1)
assert 4 == get_sum(r2, 6)
assert 3 == get_sum(r1, 3)
assert 0 == get_sum(r2, 4)
assert 0 == get_sum(r1, 4)
# note that this should not result in any large lists or memory anywhere!
# uncomment this for testing, but COMMENT IT OUT AGAIN BEFORE SUBMITTING AS IT TAKES SOMETIME TO RUN.
# assert 501263 == get_sum(Repeater(), 10**6)
# assert 4999696 == get_sum(Repeater(), 10**7)