计算我们给出的两个输入之间的匹配字符

2024-09-30 10:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

如何获得这个python输出?计算匹配和不匹配

字符串1:aaabbbcc#aaabbccc是用户输入
字符串2:aabbbcccc#aabbbcccc是用户输入

匹配:?
不匹配:?
字符串1:aaAbbBccc不匹配项大写
字符串2:aaBbbCccc


Tags: 字符串用户大写aaabbbcccaaabbcccaabbbccccaaabbbcaabbbccc
3条回答

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

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)))

输出:

^{pr2}$

如果要计算长度不均匀的字符串(其中多余的字符被视为未命中),可以更改:

num_misses  = min(len(s1), len(s2)) - num_matches
# to
num_misses  = max(len(s1), len(s2)) - num_matches
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) )

这会产生:

^{pr2}$

你可以试试:

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

相关问题 更多 >

    热门问题