-
Notifications
You must be signed in to change notification settings - Fork 0
/
nums_in_lists
61 lines (55 loc) · 2.22 KB
/
nums_in_lists
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
# defines a procedure that takes in a string of numbers from 1-9 and
# outputs a list with the following parameters:
# Every number in the string should be inserted into the list.
# If a number x in the string is less than or equal
# to the preceding number y, the number x should be inserted
# into a sublist. Continue adding the following numbers to the
# sublist until reaching a number z that
# is greater than the number y.
# Then add this number z to the normal list and continue.
def numbers_in_lists(string):
"""
Takes a string of numbers as input and outputs a list.
"""
# create empty lists: result list and buffer list
result = []
buffer_list = []
compare = int(string[0])
# check if input is not empty
if len(string) >= 1:
# append first element to result list
result.append(int(string[0]))
idx = 1
# iterate through rest of the elements of the string
while idx < len(string):
# if the num at the next position is greater
if int(string[idx]) > compare:
# see if something in buffer, add to result, empty buffer
if buffer_list:
result.append(buffer_list)
buffer_list = []
# set that bigger number as the new comparison value
compare = int(string[idx])
# append it to result list
result.append(compare)
else:
# if num at next pos is smaller, add to buffer and continue
buffer_list.append(int(string[idx]))
idx = idx + 1
# if still something in buffer, add to result at very end
if buffer_list:
result.append(buffer_list)
return result
#testcases
string = '543987'
result = [5,[4,3],9,[8,7]]
print repr(string), numbers_in_lists(string) == result
string= '987654321'
result = [9,[8,7,6,5,4,3,2,1]]
print repr(string), numbers_in_lists(string) == result
string = '455532123266'
result = [4, 5, [5, 5, 3, 2, 1, 2, 3, 2], 6, [6]]
print repr(string), numbers_in_lists(string) == result
string = '123456789'
result = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print repr(string), numbers_in_lists(string) == result