如果字符串='99888',则应打印'True'。如何检查字符串中的字符对和三对字符
我尝试使用count函数,但它只能识别一对
string = '99888'
for c in '123456789':
if string.count(c) == 2 and string.count(c) == 3 :
print('True')
编辑: 该字符串始终是5个字符串,如果有一对和三个这样的字符串,则输出True 例如,“ 89899”和“ 75757”打印为True。 '98726'打印False
答案 0 :(得分:3)
Counter
模块中的collections
类from collections import Counter
def check(inputString):
x = Counter(inputString)
list_of_counts = [x[i] for i in x.elements()]
if (2 in list_of_counts) and (3 in list_of_counts):
return(True)
else:
return(False)
print(check("99888"))
print(check("999888"))