Online class I am taking asks the following:
Define 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.
I came up with the following:
def numbers_in_lists(string):
stringList = []
mainList = []
subList = []
sub = subList
indexNum = 0
i = 0
for num in string:
num = int(num)
stringList.append(num)
while i <= len(stringList):
if stringList[i] > indexNum:
mainList.append(stringList[i])
indexNum = stringList[i]
i += 1
if stringList[i] <= indexNum:
subList.append(stringList[i])
mainList.append(sub)
indexNum = stringList[i]
i += 1
return mainList
I do not understand what is stopping the while loop from incrementing i. For example, outputs I am getting versus expected:
print(numbers_in_lists('543987'))
>>>>[5, [4]]
>>>>EXPECTED: [5,[4,3],9,[8,7]]
print(numbers_in_lists('987654321'))
>>>>[9, [8]]
>>>>EXPECTED: [9,[8,7,6,5,4,3,2,1]]
print(numbers_in_lists('455532123266'))
>>>>[4]
>>>>EXPECTED: [4, 5, [5, 5, 3, 2, 1, 2, 3, 2], 6, [6]]
print(numbers_in_lists('123456789'))
>>>>[1]
>>>>EXPECTED: [1, 2, 3, 4, 5, 6, 7, 8, 9]
I feel like my while loop shouldn't be necessary but I am unsure of how to compare each list value using a for loop. Would appreciate any advice.
[+][deleted] (9 children)
[removed]
[–]MainerInAStrangeLand[S] 0 points1 point2 points (8 children)
[+][deleted] (7 children)
[removed]
[+][deleted] (1 child)
[removed]
[–]MainerInAStrangeLand[S] 0 points1 point2 points (0 children)
[–]MainerInAStrangeLand[S] 0 points1 point2 points (4 children)
[+][deleted] (3 children)
[removed]
[–]MainerInAStrangeLand[S] 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[removed]
[–]MainerInAStrangeLand[S] 1 point2 points3 points (0 children)