0

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

2
  • 1
    So what's your question? Commented Jun 14, 2017 at 6:02
  • Updated the end of the question since it wasn't clear. Basically, the list doesn't fill itself out, it just stops on the iteration after it finishes a sublist. Commented Jun 14, 2017 at 6:07

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.