如何找到普通字符输入中的字符串数

问题描述 投票:1回答:4

我想借此输入并执行操作,找到共同的字母输入(串)的数量。

示例性输入:

abcaa
bcbd
bgc

输出是2,因为B和存在。c在所有。

我尝试写代码,但是我在4号线卡住位置:

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
'''
python string set
4个回答
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)))

在这里,您可以使用内置的减少()函数来寻找交集。此外,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
投票

你可以试试这个:

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)

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
Output:
3
abcaa
bcbd
bgc

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

© www.soinside.com 2019 - 2024. All rights reserved.