Leetcode 771.宝石与石头

给定字符串 J 代表你现在拥有代表宝石的类型,和字符串 S 代表你拥有的石头。S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。

J 中的字母不重复,JS 中的所有字符都是字母。字母区分大小写,因此"a""A"是不同类型的石头。


Python版

def numJewelsInStones(J, S):
    i = 0
    for s in S:
        if s in J:
            i += 1
    return i

def numJewelsInStones(J, S):
    return sum([s in J for s in S])
或[1 for s in S if s in J]

#注意列表推倒式的写法

sum(iterable,start) iterable为可迭代对象,start默认为0,是起始值。

sum([],start) iterable为list

sum((),start) iterable为tuple

猜你喜欢

转载自blog.csdn.net/qq_36428318/article/details/80180534