1

Suppose I have a list of strings like this:

['001+11', '010+10', '011+01', '100+11']

I want to get this:

['0*0*1+1*1', '0*1*0+1*0', '0*1*1+0*1', '1*0*0+1*1']

I understand that the condition here is that whenever there is a 0 or 1 we must replace the digit by the digit+"*",but not do this when the next element to the digit is a "+".So i wrote a python code as follows-

binary=["0","1"]
for string in out:#out is the list of strings
    for i in range(len(string)):
        if string[i] in binary:
            out[out.index(string)]=change(string,string[i],string[i]+"*")
            break
print out

This gives the output as-

['0*01+01', '0*00+01', '0*11+00', '0*10+00', '1*01+11', '1*00+11', '1*11+10', '1*10+10']

So,I realized if I ran a "while loop" for some more times I would get what I want(a while loop as we have to mention the number of loop repetitions in a "for loop",not a choice here).But I cant figure out what the condition of the while should be. And a lot of all of this sounds a bit complex,so I thought,maybe there is some other way so that I can achieve the thing I want.Hence,the question.

Note--This is part of a larger program to get truth table from any Boolean expression not written in Python format.If this part is solved,rest of it can probably be solved using eval.Thanks in advance!

EDIT1--change is a user defined function which changes a substring of a bigger string.

def change(string,old,new):
    pos=string.index(old)
    return string[:pos]+new+string[pos+1:]
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
Manas Dogra
  • 317
  • 1
  • 15

3 Answers3

5

Here's a one-liner using a list comprehension, with join and split doing the work:

>>> lst = ['001+11', '010+10', '011+01', '100+11']
>>> [ '+'.join('*'.join(x) for x in s.split('+')) for s in lst ]
['0*0*1+1*1', '0*1*0+1*0', '0*1*1+0*1', '1*0*0+1*1']
kaya3
  • 47,440
  • 4
  • 68
  • 97
2

I like kaya3’s solution but here’s another one, using regex:

>>> import re
>>> [re.sub(r'(\d)(?=\d)', r'\1*', s) for s in out]
['0*0*1+1*1', '0*1*0+1*0', '0*1*1+0*1', '1*0*0+1*1']
Seb
  • 4,422
  • 14
  • 23
2
re.sub('\B', '*', s)

Demo:

>>> lst = ['001+11', '010+10', '011+01', '100+11']
>>> [re.sub('\B', '*', s) for s in lst]
['0*0*1+1*1', '0*1*0+1*0', '0*1*1+0*1', '1*0*0+1*1']
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107