Skip to content Skip to sidebar Skip to footer

How Can I Correct My Python Code To Convert Binary String Into Position Specific Code

def convertSeq(s, index): result = [i+1 for i,ch in enumerate(s) if ch=='1'] result = ' '.join([str(index)+':'+str(i) for i in result]) result = str(index)+' '+result

Solution 1:

If convertSeq works then this should do:

line_num = 1for line in open(filename):
    print convertSeq(line, line_num)
    line_num += 1

Solution 2:

Iterate over the file using enumerate() to count the lines:

with open(filename) as f:
    for line_no, seq in enumerate(f, start=1):
        print convertSeq(seq, line_no)

Solution 3:

you can do like this, read the whole file as string and pass to your function

def convertSeq(s, index):
    result = [i+1for i,ch in enumerate(s) if ch=='1']
    result = ' '.join([str(index)+':'+str(i) for i in result])
    result = str(index)+' '+result
    return result

# read the sequence from file
with open ("file.txt",'r') as f:
   f_seq=f.readlines()

for line, seq in enumerate(f_seq, start=1):
    a = convertSeq(seq, line)print a

From the content you have given, it gives following output

1 1:5 1:25 1:45 1:65
2 2:1 2:23 2:43 2:63
3 3:3 3:23 3:43 3:63
4 4:5 4:25 4:45 4:65
5 5:1 5:23 5:43 5:63
6 6:3 6:23 6:43 6:63

You can also read the file name as arg to your program, so you don't have to hard code file name

import sys
def convertSeq(s, index):
    result = [i+1for i,ch in enumerate(s) if ch=='1']
    result = ' '.join([str(index)+':'+str(i) for i in result])
    result = str(index)+' '+result
    return result

#take the file name as arg
seqFile = sys.argv[1]

with open (seqFile,'r') as f:
   f_seq=f.readlines()

for line, seq in enumerate(f_seq, start=1):
    a = convertSeq(seq, line)print a

Post a Comment for "How Can I Correct My Python Code To Convert Binary String Into Position Specific Code"