0

in a string suppose 12345 , i want to take nested loops , so that i would be able to iterate through the string in this following way :-

  1. 1, 2, 3, 4, 5 would be taken as integers
  2. 12, 3, 4,5 as integers
  3. 1, 23, 4, 5 as integers
  4. 1, 2, 34, 5 as integers ...

And so on. I know what's the logic but being a noob in Python, I'm not able to form the loop.

5
  • what's the difference between 2nd and 3rd? Commented Dec 15, 2009 at 13:41
  • So if you know the logic, perhaps you should try describing it in words, as a complement to the example output. Commented Dec 15, 2009 at 13:42
  • in 2nd , 12 is an integer , in 3rd , 23 is an integer . Commented Dec 15, 2009 at 13:43
  • @mekaspersky: that's not what you posted. Commented Dec 15, 2009 at 13:47
  • So bascially you're looking for an algorithm that yields 1. the 1 possibility to omit no commas in your array 2. the 4 possibilities to omit one comma 3. the 6 possibilities to omit two commas 4. the 4 possibilities to omit three commas 5. the 1 possibility to omit four commas ? Commented Dec 15, 2009 at 14:10

3 Answers 3

2

This smells a bit like homework.

Try writing down the successive outputs, one per line, and look for a pattern. See if you can explain that pattern with slices of the input string. Then look for a numeric pattern to the slicing.

Also, please edit your question to put quotes around your strings. What you've written isn't very clear in terms of the outputs, whether you output strings with commas or lists of substrings.

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

Comments

1

You can do the inner traversals by following code, the first traversal is trivial.

s = '12345'

chars = [c for c in s]

for i in range(len(s) - 1):
    print '%d:' % i,
    for el in chars[:i] + [chars[i] + chars[i + 1]] + chars[i + 2:]:
        print el,
    print

Comments

1
number = 12345

str_number = str(number)

output = []
for index, part in enumerate(str_number[:-1]):
    output_part = []
    for second_index, second_part in enumerate(str_number):
        if index == second_index:
            continue
        elif index == second_index - 1:
            output_part.append(int(part + second_part))
        else:
            output_part.append(int(second_part))
    output.append(output_part)

print output

STick it inside a function definition and put an "yield output_part" in place of the "output.append" line to get a usefull interator.

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.