- #1
doktorwho
- 181
- 6
Homework Statement
Define a procedure that does the following:
From the string of numbers from 1 - 9 it creates a list that contains the numbers that are bigger than the preceding number and adds the smaller ones to a sub-list. Example:
string='3057842103'
print(numbers_in_list(string))
>>>[3,[0],5,7,8,[4,2,1,0,3]]
This is a Udacity CS101 problem from the ProblemSet in Lecture 3 named, Numbers in List.
Homework Equations
3. The Attempt at a Solution [/B]
Python:
def numbers_in_lists(string):
list=[int(string[0])]
list2=[]
a=int(string[0])
i=1
while i<len(string):
if a<int(string[i]):
a=int(string[i])
list.append(int(string[i]))
list2=[]
i+=1
if a>=int(string[i]):
list2.append(int(string[i]))
if list2 not in list:
list.append(list2)
i+=1
return list
Python:
# Numbers in lists by SeanMc from forums
# 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.
#Hint - "int()" turns a string's element into a number
def numbers_in_lists(string):
list=[int(string[0])]
list2=[]
a=int(string[0])
i=1
while i<len(string):
if a<int(string[i]):
a=int(string[i])
list.append(int(string[i]))
list2=[]
i+=1
if a>=int(string[i]):
list2.append(int(string[i]))
if list2 not in list:
list.append(list2)
i+=1
return list
#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
Python:
Traceback (most recent call last): File "vm_main.py", line 33, in <module> import main File "/tmp/vmuser_kzfoxtgohv/main.py", line 44, in <module> print repr(string), numbers_in_lists(string) == result File "/tmp/vmuser_kzfoxtgohv/main.py", line 25, in numbers_in_lists if a>=int(string[i]): IndexError: string index out of range
'543987' True '987654321' True '455532123266' True '123456789'