gpt4 book ai didi

python - 在 Python 3 的列表中连续计算四个

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:57 26 4
gpt4 key购买 nike

用户掷了五个骰子。如果其中四个是连续的,则用户将获得 30 分,否则将不获得任何积分。当我有 5 个数字的列表来表示骰子时,我如何能够搜索该列表以查看它是否连续包含四个数字?我现在的代码如下:

diceList = sorted(diceList)
elif letterChoice == "J" and diceCombinations[9] == False:
diceList = list(set(diceList))
print (diceList)
if diceList in [[1,2,3,4], [2,3,4,5], [3,4,5,6]]:
score = score + 30
diceCombinations[9] = True

这在大多数情况下都有效,但如果我掷出 1,2,3,4,6 则不够用。感谢您的帮助

最佳答案

反转你的in使用 any 进行测试, 并保持 diceList作为set :

diceList = set(diceList)
if any(match <= diceList for match in (
{1, 2, 3, 4},
{2, 3, 4, 5},
{3, 4, 5, 6},
)):
# do something

解释:

set s 只保留一个唯一元素的副本,所以 {1, 1, 1, 3, 2, 6}最终成为 {1, 3, 6, 2} (不保留顺序),所以通过类型转换 diceList对于一个集合,我们会丢失任何重复项。

然后我们遍历“四连胜”的可能解,比如{1, 2, 3, 4}看看是否diceList是一场比赛。该部分通过使用 <= 来工作表示法,用于 set s 表示 LHS(左侧)的元素是否少于 RHS(右侧)(<)或与 RHS 相同的元素(=),并且没有 RHS 中不存在的元素.所以:

  • {1, 2}< {1, 2, 3} .
  • {1, 2, 3}= {1, 2, 3}
  • {1, 2, 5}不是 <也不={1, 2, 3}

注意:这被称为部分排序,因为一个 set 是可能的不是 = , 不是 < , 而不是 >另一个 set .

关于python - 在 Python 3 的列表中连续计算四个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35879842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com