简体   繁体   English

两个字符串列表python之间的交集

[英]Intersection between two list of strings python

This is in reference to problem that is done in Java:这是参考在 Java 中完成的问题:
Finding the intersection between two list of string candidates . 查找两个字符串候选列表之间的交集

I tried to find an equivalent solution in python:我试图在 python 中找到一个等效的解决方案:

def solution(S):
    length = len(S)
    if length == 0:
        return 1
    count = 0
    i = 0
    while i <= length:
        prefix = S[0:i:]
        suffix = S[length-i:length]
        print suffix
        if prefix == suffix:
            count += 1
        i += 1
    return count

print solution("")
print solution("abbabba")    
print solution("codility")

I know I am not doing the step in terms of suffix.我知道我没有在后缀方面做这一步。

I am getting the values as 1,4,2 instead of 1,4,0我得到的值为 1,4,2 而不是 1,4,0

Your current code runs through giving the following prefix, suffix pairs for the second two examples:您当前的代码通过为后两个示例提供以下前缀和后缀对来运行:

a a
ab ba
abb bba
abba abba
abbab babba
abbabb bbabba
abbabba abbabba

c y
co ty
cod ity
codi lity
codil ility
codili dility
codilit odility
codility codility

I presume you are trying to return the number of times the first n characters of a string are the same as the last n .我假设您正在尝试返回字符串的前n字符与最后一个n相同的次数。 The reason the word codility is returning 2 is because you are starting the index from zero, so it is matching the empty string and the full string. codility一词返回2的原因是因为您从零开始索引,因此它匹配空字符串和完整字符串。 Try instead:试试吧:

def solution(S):
    length = len(S)
    if length == 0:
        return 1
    count = 0
    i = 1 # Don't test the empty string!
    while i < length: # Don't test the whole string! Use '<'
        prefix = S[:i] # Up to i
        suffix = S[length-i:] # length - i to the end
        print prefix, suffix
        if prefix == suffix:
            count += 1
        i += 1
    return count

print solution("")
print solution("abbabba")    
print solution("codility")

This returns 1, 2, 0.这将返回 1、2、0。

Perhaps you were looking to test if the prefix is the same as the suffix backwards , and only test half the length of the string?也许您想测试前缀是否与后缀backs相同,并且只测试字符串长度的一半? In this case you should try the following:在这种情况下,您应该尝试以下操作:

def solution(S):
    length = len(S)
    if length == 0:
        return 1
    count = 0
    i = 1 # Don't test the empty string!
    while i <= (length + 1)/2: # Test up to halfway
        prefix = S[:i] # Up to i
        suffix = S[:length-i-1:-1] # Reverse string, up to length - i - 1
        print prefix, suffix
        if prefix == suffix:
            count += 1
        i += 1
    return count

print solution("")
print solution("abbabba")    
print solution("codility")

This returns 1, 4, 0.这将返回 1、4、0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM