确定列表中的任何两个字符串是否在功能上以相同的字符开头

时间:2017-07-30 11:39:59

标签: python python-3.x

所以基本上,我希望这是False

('click', 'bait', 'carrot', 'juice')

这是True,因为每个字符串都以与其他字符串不同的字符开头:

('click', 'bait', 'juice', 'silly')

我得到的最接近的是以下,但它看起来并不是很好。

functools.reduce(lambda x, y: (y, x[0] != y[0]), map(operator.itemgetter(0), ('click', 'bait', 'carrot', 'juice')))[1]

它失败了,因为它只检查彼此相邻的字符串。

3 个答案:

答案 0 :(得分:3)

data = ('click', 'bait', 'carrot', 'juice')

len(set(w[0] for w in data)) == len(data)
# -> False

答案 1 :(得分:2)

I assume by functional you mean no state mutation.

any(n > 1 for n in collections.Counter(s[0] for s in ('click', 'bait', 'carrot', 'juice')).values())

答案 2 :(得分:1)

This will do the job:

l=('click', 'bait', 'carrot', 'juice')
def f(l):
    s=set()
    for i in l:
        if i[0] in s:
            return False
        s.add(i[0])
    return True

The set s consists of the first letters that were seen so far. At each iteration you move to the next word and check whether the first letter is in s. If it is there, you return False. Otherwise, you add the first letter to s and continue. The advantage of the loop is that if a first letter repeats early you stop the iterations and do not proceed. Thus avoiding unnecessary work.