如何查找输入字符串中的公共字符数

时间:2019-02-03 05:45:56

标签: python string set

我想接受输入并执行操作以查找输入(字符串)中的常用字母数。

示例输入:

abcaa
bcbd
bgc

输出为2,因为b和c都存在。

我尝试编写代码,但在第四行停留在这里:

t = int(input())
for i in range(3):
    s1=input()
    #a=list(set(s1)&set(s2))
print(a)

'''
input:
3
abcaa
bcbd
bgc

output:
2
because  'b' and 'c' are present in all three
'''

4 个答案:

答案 0 :(得分:2)

输入要比较的数字:

as_many_inputs = 3
asked_inputs = [set(input("Enter the string you want\t")) for i in range(as_many_inputs)]
from functools import reduce
print("Number of common is:\t", len(reduce(set.intersection, asked_inputs)))

在这里您可以使用内置的reduce()函数找到交点。另外,len()将返回数字。

Enter the string you want   aah

Enter the string you want   aak

Enter the string you want   aal
Number of common is:    1

我也用5个进行了测试:

Enter the string you want   agh

Enter the string you want   agf

Enter the string you want   age

Enter the string you want   agt

Enter the string you want   agm
Number of common is:     2

答案 1 :(得分:1)

您可以尝试以下方法:

t = int(input("How many inputs there will be:\t"))  # take the number of inputs will be given

inputs = []     # empty list for inputs

a = []  # empty list for inputs as set of letters

# loop through the range of t (total number of inputs given at first)
for i in range(t):
    input_taken = input("Enter your input:\t")  # take the input
    inputs.append(input_taken)  # store input to the inputs list

# loop through inputs, make sets of letters for each item and store them in a
for i in inputs:
    a.append(set(i))

u = set.intersection(*a)    # find the common letter's set from all items of a and save it as a set(u)

print(len(u), u)    # print the length of u and u(different letters from each items of a)

答案 2 :(得分:1)

@Rohitjojo09,您可以尝试这样。

注意:我正在使用变量n代替您的ts代替s1,这在大多数情况下是有道理的。

  

您可以在https://rextester.com/ISE37337在线尝试此代码。

def get_count():
    n = int(input())

    for i in range(n):
        s = input().strip()

        if not i:
            l = list(set(s))
        else:
            i = 0
            while l and i < len(l) - 1:
                ch = l[i]
                if not ch in s:
                    l.remove(ch)
                else:
                    i += 1                       
    return len(l)

count = get_count()                    
print(count) # 2
输出:
3
abcaa
bcbd
bgc

答案 3 :(得分:0)

检查一下!

s=set()   #create empty set
c=1
num=int(input("Enter no of strings you want to enter: "))
for i in range(num):
    x= input("enter string: ")
    if c < 2:
        for j in x:
            s.add(j)   #adding elemnts of x in set
        c+=1
    else:
        s=s.intersection(x)    

print(s,len(s))