计算用户给出的两个输入之间的匹配字符

时间:2015-03-13 06:04:18

标签: python count match

我如何获得此python输出?计算匹配和不匹配

String1:aaabbbccc #aaabbbccc是用户输入
String2:aabbbcccc #aabbbcccc是用户输入

匹配:?
MisMatches:?
String1:aaAbbBccc #mismatches是大写的 String2:aaBbbCccc

5 个答案:

答案 0 :(得分:1)

假设您从文件或用户输入中获取了字符串,那么:

import itertools

s1 = 'aaabbbccc'
s2 = 'aabbbcccc'

# This will only consider n characters, where n = min(len(s1), len(s2))
match_indices = [i for (i,(c1, c2)) in enumerate(itertools.izip(s1, s2)) if c1 == c2]
num_matches   = len(match_indices)
num_misses    = min(len(s1), len(s2)) - num_matches

print("Matches:    %d" % num_matches)
print("Mismatches: %d" % num_misses)
print("String 1:   %s" % ''.join(c if i in match_indices else c.upper() for (i,c) in enumerate(s1)))
print("String 2:   %s" % ''.join(c if i in match_indices else c.upper() for (i,c) in enumerate(s2)))

输出:

Matches:    7
Mismatches: 2
String 1:   aaAbbBccc
String 1:   aaBbbCccc

如果您想计算长度不均匀的字符串(额外字符计为未命中),您可以更改:

num_misses  = min(len(s1), len(s2)) - num_matches
# to
num_misses  = max(len(s1), len(s2)) - num_matches

答案 1 :(得分:1)

import itertools
s1 = 'aaabbbccc'
s2 = 'aabbbcccc'
print "Matches:", sum( c1==c2 for c1, c2 in itertools.izip(s1, s2) )
print "Mismatches:", sum( c1!=c2 for c1, c2 in itertools.izip(s1, s2) )
print "String 1:", ''.join( c1 if c1==c2 else c1.upper() for c1, c2 in itertools.izip(s1, s2) )
print "String 2:", ''.join( c2 if c1==c2 else c2.upper() for c1, c2 in itertools.izip(s1, s2) )

这会产生:

Matches: 7
Mismatches: 2
String 1: aaAbbBccc
String 2: aaBbbCccc

答案 2 :(得分:0)

您可以尝试下面的内容。

>>> s1 = 'aaabbbccc'
>>> s2 = 'aabbbcccc'
>>> match = 0
>>> mismatch = 0
>>> for i,j in itertools.izip_longest(s1,s2):
        if i == j:
            match += 1
        else:
            mismatch +=1

在python3中使用itertools.zip_longest而不是itertools.izip_longest。 如果您想将aA视为匹配项,请将if条件更改为,

if i.lower() == j.lower():

最后从变量matchmismatch获取匹配和不匹配计数。

答案 3 :(得分:0)

您可以尝试:

    index = 0
    for letter in String1:
        if String1[index] != String2[index]:
            mismatches +=1
    index += 1
print "Matches:" + (len(String1)-mismatches)
print "Mismatches:" + mismatches  

答案 4 :(得分:0)

>>>s= list('aaabbbccc')
>>>s1=list('aabbbcccc')
>>>match=0
>>>mismatch=0
>>>for i in range(0,len(s)):
...     if(s[i]==s1[i]):
...             match+=1
...     else:
...             mismatch+=1
...             s[i]=s[i].upper()
...             s1[i]=s1[i].upper()
>>>print 'Matches:'+ str(match)
>>>print 'MisMatches:'+str(mismatch)
>>>print 'String 1:' +''.join(s)
>>>print 'String 2:' +''.join(s1)