简体   繁体   中英

Comparing string differences to a list of strings

I have a method, that computes the number of differences in two strings, and outputs where the differences are.

def method(a):
    count=0
    s1="ABC"
    for i in range (len(a)):
        if not a[i]==s1[i]:
            count=count+1
        else:
            count=count+0
    return a,count,difference(a, s1)

On input ex CBB, this method outputs

('CBB', 2, [1, 0, 1])

What I really need is for this method to do the same, but where is not only compares to a single string in s1, but to a list of strings

s1 = ['ACB', 'ABC', 'ABB']

Anyone with a smart method to do this?

Ok, after clarification, instead of hardcoding s1, make your method take it as argument:

def method(a, s1):
    count=0
    for i in range (len(a)):
        if not a[i]==s1[i]:
            count=count+1
        else:
            count=count+0
    return a,count,difference(a, s1)

Then use list compherension:

 result = [method(a, s1) for s1 in list]

Be careful though, as your method will fail if a is longer than s1. As you really don't say what the result should be in that case, i left it as is.

the compare function calculates the number of differences (and map of differences that you had been creating with difference() ). I rewrote the compare function to take a base string to be compared to, src , so that you don't get stuck with comparing to "ABC" all the time.

def compare(src, test):
    if len(src) != len(test):
        return # must be the same length
    diffmap = [0]*len(src)
    count = 0
    for i, c in enumerate(src):
        if not c == test[i]:
            count = count+1
            diffmap[i] = 1
    return test, count, diffmap

The compare_to_many function simply goes through a list of strings to compare to, srcs , and creates a list of the comparisons between those base strings and a test string test .

def compare_to_many(srcs, test):
    return map(lambda x: compare(x, test), srcs)

EDIT:

After clarification in the comments, @X-Pender needs the source list to be hardcoded. This can be reflected by the following, single function:

def compare(test):
    def compare_one(src, test):
        diffmap = [0]*len(src)
        count = 0
        for i, c in enumerate(src):
        if not c == test[i]:
            count = count+1
            diffmap[i] = 1
        return test, count, diffmap
    sources = ["ABC", "CDB", "EUA"] # this is your hardcoded list
    return map(lambda x: compare_one(x, test), sources)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM