简体   繁体   English

如何在python中优化此代码

[英]How to optimize this code in python

I need to optimize this code, that basically checks if every character of string s1 is contained in s2 , taking in consideration doubles. 我需要优化此代码,基本上检查字符串s1每个字符是否包含在s2 ,并考虑加倍。

s1, s2 = list(s1), list(s2)
for s in s2:
    if s in s1:
        s1.remove(s)
    else:
        return False
return True

I did some research on map , iterators and generators, and I'm sure in one or more of these there is a solution, but right now I'm pretty confused and frustrated (I'm very new to python, just a couple weeks), so maybe you can help me understand what's the best strategy in this case. 我对map ,迭代器和生成器进行了一些研究,并且我肯定其中有一个或多个解决方案,但是现在我非常困惑和沮丧(我对python很陌生,仅仅几个星期),那么也许您可以帮助我了解这种情况下的最佳策略。 Thanks! 谢谢!

A solution using Counter that will handle duplicated characters correctly: 使用Counter的解决方案将正确处理重复的字符:

from collections import Counter
c1 = Counter(s1)
c2 = Counter(s2)
return all(c2[c]>=c1[c] for c in c1)

You can count the number of occurrences of each character in both strings. 您可以计算两个字符串中每个字符的出现次数。 You also don't need to make either string a list: strings are their own iterators. 您也不需要将任何一个字符串都设为列表:字符串是它们自己的迭代器。

First, create a set as sets have an average lookup of O(1) . 首先,创建一个set ,使集合的平均查找值为O(1) Then, iterate through the set and get the counts of each character. 然后,遍历集合并获得每个字符的计数。 If any counts aren't equal, return False . 如果任何计数不相等,则return False It also scales much better as the size of the string grows, than your current solution: 与当前解决方案相比,随着字符串大小的增长,它的伸缩性也要好得多:

s1 = 'Stack Overflow'
s2 = 'woltk fcrSeavO'

def equal_chars(s1, s2):
    chars = set(s2)
    for char in chars:
        if s1.count(char)!= s2.count(char):
            return False
    return True

print(equal_chars(s1, s2))

A slight adjustment on Adrien's great answer which is (maybe?) more efficient: 对Adrien的好答案稍作调整,这可能会更有效:

from collections import Counter

s1 = "hello"
s2 = "helo"

def count_chars(s1,s2):
    c2 = Counter(s2)
    for k,v in Counter(s1).items():
        if c2[k] < v:
            return False
    return True

print (count_chars(s1,s2))

result: 结果:

False

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

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