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']
0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Apalala, it's not generating the desired output.
Hi @Apalala , can you take a look at this related question, stackoverflow.com/q/54732494/7644562 please!

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.