 Σqu -3 years ago 40
Python Question

# Appending Elements of a String into a List (python)

This program is designed to take a string consisting of numbers (any length) and outputting the contents of the string into a list, one digit at a time. Should a number, x, be less than or equal to the preceding number, y, the number x is to be inserted into a sublist. Until a number, z, is greater than y, everything between x and z will also be added to the sublist. Here is the code

``````def numbers_in_lists(string):
final = []
temp = []
prev = 0

for i in range(len(string)):
value = int(string[i])

if value<=prev:
temp.append(value)
else:
if temp != []:
final.append(temp)
temp = []
final.append(value)
prev = int(string[i])

print final
return final
``````

To test this function, add the following to the remainder of the code:

``````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, ]
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
``````

After the code creates and returns a sublist, it finds a new maximum value and doesn't add anything else to the list, thus leaving the final list incomplete.

If I test with the string
`'543987'`
the prefered result is
`[5,[4,3],9,[8,7]]`
whereas my result is
`[5,[4,3],9]` themiurge
Answer Source

You need to check `temp` after the `for` loop ends, it might still contain something:

``````def numbers_in_lists(string):
final = []
temp = []
prev = 0

for digit in string:
value = int(digit)

if value<=prev:
temp.append(value)
else:
if temp:
final.append(temp)
temp = []
final.append(value)
prev = int(digit)

if temp:
final.append(temp)

print final
return final
``````

I also slightly re-worked your `for` loop (no need to use indexed access) and replaced `temp != []` with `temp` (see here).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added