两个由CodingBat谜语

时间:2016-04-27 00:27:20

标签: python

def twoTwo(list_2):

    two_count = list_2.index(2)

    if two_count == 0:
        if list_2[1] == 2:
            print True
        else:
            print False
    elif two_count > 0:
        if list_2[two_count - 1] == 2 or list_2[two_count + 1] == 2:
            print True
        else:
            print False

问题: 编写一个函数twoTwo(),给定一个整数列表,如果列表中出现的每个2都在另一个2旁边,则返回true。

twoTwo([4, 2, 2, 3]) → true       
twoTwo([2, 2, 4]) → true          
twoTwo([2, 2, 4, 2]) → false  

它适用于第二个,但不是最后一个,并没有尝试尝试第一个......

3 个答案:

答案 0 :(得分:1)

一个简洁的解决方案是使用itertools.groupby查找相同数字的运行,然后检查没有运行具有密钥2和长度1(使用sum(g) == 2进行检查,因为a 2的运行总和等于其长度的两倍。)

import itertools

def two_two(xs):
    return not any(k == sum(g) == 2 for k, g in itertools.groupby(xs))

这是一些简单的测试代码:

cases = [
    ([], True),
    ([2], False),
    ([2, 2], True),
    ([2, 3], False),
    ([3, 2], False),
    ([4, 2, 2, 3], True),
    ([2, 2, 4], True),
    ([2, 2, 4, 2], False),
    ([2, 2, 2, 3], True),
]

for xs, want in cases:
    got = two_two(xs)
    if got != want:
        print 'two_two(%s) = %d, want %d' % (xs, got, want)

答案 1 :(得分:0)

您可以使用for循环来检查2。一个简单的例子就是这样(不是写整个函数,但你应该得到这个想法......):

for vm1, v, vp1 in zip( list_2, list_2[1:], list_2[2:]):
    if v == 2 and ( vm1 != 2  and vp1 != 2) return False

return True

这比查找索引简单得多。

请务必分别检查第一个和最后两个

答案 2 :(得分:0)

Y'所有事情都过于复杂。这是python;只需将问题的语言转换为代码即可。如果列表中出现的每2个与另一个2相邻,则返回True,否则返回False。

等效:如果列表中出现的任何2不在另一个2旁边,则返回False,否则返回True。

def two_two(lst):
    for i, val in enumerate(lst):
        # if any two that appears in the list
        if val == 2:
            left = i > 0 and lst[i - 1] == 2
            right = i < len(lst) - 1 and lst[i + 1] == 2
            # is not next to another two
            if not left and not right:
                return False
    # otherwise,
    return True

print two_two([4, 2, 2, 3]) # True
print two_two([2, 2, 4]) # True
print two_two([2, 4, 2, 4]) # False
print two_two([2, 2, 4, 2]) # False
print two_two([3, 4, 1]) # True