【发布时间】:2021-03-11 13:06:41
【问题描述】:
我正在尝试阅读两个列表:假设第一个列表是 secret = [5, 5, 6, 0, 3],第二个列表是 proposition =[5, 6, 4, 5, 5],每个项目代表一种颜色。
我的问题是策划者问题:给定一个秘密清单和一个命题,我需要: 对于给定的颜色,比如说 5,我需要说出我的命题中有多少根据秘密列表正确定位。 并返回一个给定正确定位的 '5' 和未正确定位的 '5' 的元组。
在我的proposition [5, 6, 4, 5, 5] 中,第一个“5”根据秘密正确定位。
所以正确定位的“5”的答案是 1。
对于在我的命题[5, 6, 4, 5, 5] 中评估错误定位的“5”的答案,根据秘密[5, 5, 6, 0, 3],我需要计算每个列表中“5”的出现次数并取最小值并删除正确定位的数量'5'(此处为 1),秘密我有 2,在命题中我有 3。我将是:min(2,3)-1 = 1。
所以我需要返回 tuple (1,1) :表示 1 个正确定位,1 个错误定位。
为了计数,我写了这个(我知道存在一个计数函数,但我不允许使用它):
def countColour (c : int, l : List[int]) -> int:
"""return # occurences of the color c inside the list l
"""
nb : int = 0
for i in range(0, len(l)):
if (l[i] == c):
nb = nb + 1
return nb
现在我要尝试返回元组,我编写了这段代码,它似乎可以完成这项工作,但是:
def eval_color(secret : List[int], prop : List[int], coul : int) -> Tuple[int,int]:
"""Return the couple (right positionned, wrong positionned) for the color c.
"""
i : int = 0 #
j : int = 0 #
pbp : int = 0 # right positionned
pmp : int = 0 # wrong positionned
nbc_s : int = 0 # nb occurencies of color in secret
nbc_p : int = 0 # nb occurencies of color in proposition
c : int = coul # my color as a parameter of the function
s : List[int] = secret
p : List[int] = prop
nbc_s = countColour(c,s)
nbc_p = countColour(c,p)
while (i <= len(s)-1) and (j <= len(p)-1):
if (p[j] == s[i] == c):
pbp = pbp + 1
i += 1
j += 1
return (pbp, min(nbc_s,nbc_p) - pbp)
像这样的测试似乎一切正常:
assert eval_color([5, 5, 6, 0, 3], [5, 6, 4, 5, 5], 5) == (1, 1)
表示一个“5”的位置正确,一个“5”的位置不正确。
如果我不只考虑一种特定颜色,而是想使用此函数循环查找秘密列表中的每种颜色(不仅仅是“5”),并说出我的命题中有多少正确定位和错误定位,该怎么办。
我试过这个:
def evaluation(secret : List[int], prop : List[int]) -> Tuple[int,int]:
"""return the couple (total right, total wrong)
"""
pmp_tot : int = 0 # total right
pbp_tot : int = 0 # total wrong
s : List[int] = secret
p : List[int] = prop
Lt : List[Tuple(int,int)] = []
e : int
for e in s:
Lt.append(evaluation_couleur(s,p,e))
for(pbp,pmp) in Lt:
pmp_tot = pmp_tot + pmp
pbp_tot = pbp_tot + pbp
return (pbp_tot, pmp_tot)
如果我尝试用这个进行测试:
assert evaluation([5, 5, 6, 0, 3], [5, 6, 4, 5, 5]) == (1, 2)
我不工作,因为函数 eval_color 内部出现问题,特别是在 while 循环内部:
while (i <= len(s)-1) and (j <= len(p)-1):
if (p[j] == s[i] == c):
pbp = pbp + 1
i += 1
j += 1
return (pbp, min(nbc_s,nbc_p) - pbp)
我认为这不是编程语言的问题,而是算法的问题。我需要了解如何正确思考。
感谢您的帮助。 PS : 请记住,我无法使用 Python 的任何强大武器来解决我的问题。
【问题讨论】:
-
p[j] == s[i] == c现在您将布尔值与数字进行比较,(p[j] == s[i]) == c -
我不明白你的第一个例子,显然有两个正确定位的五,对吧?除非我错过了什么。
-
你是对的,在这种情况下。我打错了,我更正了。秘密是 [5,5,6,0,3]
-
致@rioV8:我将p的第j个元素,即p[j]与s的第i个元素,即s[i]进行比较。如果它们都等于 c,那么做 pbp = pbp +1。我不明白您的意思是“将布尔值与数字进行比较”
-
p[j] == s[i]是一个布尔值(真/假),阅读运算符优先级,将()放入表达式中以查看运算符优先级,就像我做的那样
标签: python list algorithm loops tuples