首页 > 解决方案 > 戴帽子的猫-挑战。Python

问题描述

我得到了这个问题的解决方案,但是:我很难看到解决方案背后的逻辑!有人可以解释一下它是如何工作的吗?

你有 100 只猫。有一天,你决定把你所有的猫都排成一个大圆圈。最初,您的猫都没有戴任何帽子。你绕着圆圈走 100 次,总是从同一个地方开始,第一只猫(猫 #1)。每次你停在一只猫身上时,如果它没有戴帽子,你就给它戴上帽子,或者如果它戴上帽子,你就把它摘掉。

  1. 第一轮,你停在每只猫身上,给每只猫戴上帽子。
  2. 第二轮,你只停在每第二只猫(#2、#4、#6、#8 等)。
  3. 第三轮,你只停在每三只猫(#3、#6、#9、#12 等)。
  4. 你继续这个过程,直到你绕着猫跑了 100 圈(例如,你只拜访了第 100 只猫)。

编写一个程序,简单地输出最后哪些猫有帽子。

这是解决方案解决方案#1:

def get_cats_with_hats(array_of_cats):
    cats_with_hats_on = []

    for num in range(1, 100 + 1):
        for cat in range(1, 100 + 1):
            if cat % num == 0:
                if array_of_cats[cat] is True:
                    array_of_cats[cat] = False
                else:
                    array_of_cats[cat] = True
    for cat in range(1, 100 + 1):
        if cats[cat] is True:
            cats_with_hats_on.append(cat)
    return cats_with_hats_on


cats = [False] * (100 + 1)
print(get_cats_with_hats(cats))

解决方案#2:

number_of_cats = 100
cats_with_hats = []
number_of_laps = 100

# We want the laps to be from 1 to 100 instead of 0 to 99
for lap in range(1, number_of_laps + 1):
    for cat in range(1, number_of_cats + 1):

        # Only look at cats that are divisible by the lap
        if cat % lap == 0:
            if cat in cats_with_hats:
                cats_with_hats.remove(cat)
            else:
                cats_with_hats.append(cat)

print(cats_with_hats)

标签: pythonpython-3.x

解决方案


我认为你正在努力编码。这些解决方案可能很耗时,我的意思是编程竞赛效率不高。
First cat = true 因为圈子从这只猫开始,永远不会是同一个地方
Second cat =false 因为圈子将在这个地方第二次开始在这之后你可以知道你是否知道这只猫的分隔符
例如: 8th cat
dividers of 8 = 1,2,4,8
8 th cat will be = false
如果分隔符计数 %2 ==0 则为假,否则为真

能分享下问题的链接吗?


推荐阅读