# 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 the first number in the string is greater than or equal # to the proceeding numbers, the proceeding numbers should be inserted # into a sublist. Continue adding to the sublist until the proceeding number # is greater than the first number before the sublist. # Then add this bigger number to the normal list. # ie [5, [3,2,4,5,1,2], 6] all the numbers in the subset are <= 5 #Hint - "int()" turns a string's element into a number def numbers_in_lists(string): array = [] for i in string: array.append(int(i)) temp_list = [] final_list = [array[0]] i = 0 while i+1 < len(array): if array[i] >= array[i+1]: j = 0 while j+1 < len(array[i:]) and array[i] >= array[i:][j+1]: temp_list.append(array[i:][j+1]) j += 1 final_list.append(temp_list) i += len(temp_list) temp_list = [] else: final_list.append(array[i+1]) i += 1 #print final_list return final_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
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question