我试图阅读两个列表:第一个列表是secret = [5, 5, 6, 0, 3]
,第二个列表是proposition =[5, 6, 4, 5, 5]
,每个项目代表一种颜色
我的问题是策划者问题:给定一份秘密清单和一个提议,我需要: 对于一个给定的颜色,比如说5,我需要说我的命题中有多少是根据秘密列表正确定位的。 以及在给定位置正确的“5”和位置不正确的“5”的情况下返回元组
在我的proposition [5, 6, 4, 5, 5]
中,第一个“5”是根据秘密正确定位的。
因此,正确定位的“5”的答案是1。
为了计算我的命题{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的任何强大武器来解决我的问题
我已经根据您的输入编辑了代码,但不确定它是否违反了您的规则
相关问题 更多 >
编程相关推荐