2

I'm working on a Python(3) program in which I have to write a function to generate an output which will be a list of strings in lexicographically order.

Here's an example: if we pass a string like: ??2??00 which i called a pattern then it has to replace the question mark with an integer for example 1 and a keyword called scheule denotes the number of ? and generate an output like below:

0020100
0021000
0120000
1020000

and, here's what I have tried: so, if pattern= '??2??00' and scheule=4 then:

for ind, p in enumerate(pattern):
    if p == '?':
       s = pattern[ind].replace('?', str(scheule))
       available_schedule.append(s)
       break
     else:
       continue

which is not generating the required output, but here's what it generates:

['1', '2', '2', '3', '4', '4', '4']
Abdul Rehman
  • 5,326
  • 9
  • 77
  • 150

1 Answers1

2

In Python, if you enumerate a str you obtain a list of characters (strings of length 1). Thus the output.

str.replace() will do nothing if the pattern is not found in the string, and will replace all occurrences of the pattern otherwise.

This fragment produces the desired output:

pattern = '??2??00'
pattern_pos = [i for i, c in enumerate(pattern) if c == '?']
schedule = '1'
result = pattern.replace('?', '0')
for i in reversed(pattern_pos):
    print(''.join([result[:i], schedule, result[i+1:]]))

Output:

0020100
0021000
0120000
1020000
Apalala
  • 9,017
  • 3
  • 30
  • 48