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, 2, 3, 4, 5 would be taken as integers
- 12, 3, 4,5 as integers
- 1, 23, 4, 5 as integers
- 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.
-
what's the difference between 2nd and 3rd?SilentGhost– SilentGhost2009年12月15日 13:41:22 +00:00Commented 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.unwind– unwind2009年12月15日 13:42:45 +00:00Commented Dec 15, 2009 at 13:42
-
in 2nd , 12 is an integer , in 3rd , 23 is an integer .Hick– Hick2009年12月15日 13:43:25 +00:00Commented Dec 15, 2009 at 13:43
-
@mekaspersky: that's not what you posted.SilentGhost– SilentGhost2009年12月15日 13:47:19 +00:00Commented 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 ?Johannes Charra– Johannes Charra2009年12月15日 14:10:32 +00:00Commented Dec 15, 2009 at 14:10
3 Answers 3
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.
Comments
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
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.