views:

93

answers:

3

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.

+1  A: 

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.

Mike D.
this is more of a comment ..
The MYYN
A: 

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
Michal Čihař
A: 
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.

jsbueno