简体   繁体   English

在没有数组帮助的情况下,如何检查 3/5 值是否相同?

[英]How do I check if 3/5 values are the same without the help of an array?

Good day folks.I'm new to coding and currently trying to figure out if I have a set of 5 die.大家好。我是编码新手,目前正试图弄清楚我是否有一组 5 个骰子。 die1, die2, die3, die4, die5 and I want to check if 3/5 have the same value. die1, die2, die3, die4, die5 我想检查 3/5 是否具有相同的值。 Is it possible without the help of an array?没有数组的帮助有可能吗? :) :)

Without array:没有数组:

s = (die1==1)+(die2==1)+(die3==1)+(die4==1)+(die5==1)
if s >= 3:
    print('yes')
else:
    s = (die1==2)+(die2==2)+(die3==2)+(die4==2)+(die5==2)
    if s >= 3:
        print('yes')
    else:
        s = (die1==3)+(die2==3)+(die3==3)+(die4==3)+(die5==3)
        if s >= 3:
            print('yes')
        else:
            s = (die1==4)+(die2==4)+(die3==4)+(die4==4)+(die5==4)
            if s >= 3:
                print('yes')
            else:
                s = (die1==5)+(die2==5)+(die3==5)+(die4==5)+(die5==5)
                if s >= 3:
                    print('yes')
                else:
                    s = (die1==6)+(die2==6)+(die3==6)+(die4==6)+(die5==6)
                    if s >= 3:
                        print('yes')
                    else:
                        print('no')

Editing my post since I found a better solution:因为我找到了更好的解决方案,所以编辑我的帖子:

dice = (10**die1 + 10**die2 + 10**die3 + 10**die4 + 10**die5) // 10

print(dice % 10 >= 3 or dice // 10 % 10 >= 3 or dice // 100 % 10 >= 3 or 
      dice // 1000 % 10 >= 3 or dice // 10000 % 10 >= 3 or dice // 100000 % 10 >= 3)

I know it would be faster to do a loop or explicit string / integer search for a digit >= 3, but in this case implicit array looping is possible:-)我知道执行循环或显式字符串/ integer 搜索数字> = 3会更快,但在这种情况下,可以进行隐式数组循环:-)

Certainly.当然。 Use collections.Counter :使用collections.Counter

from collections import Counter

d1 = 1
d2 = 3
d3 = 4
d4 = 3
d5 = 3

counter = Counter([d1, d2, d3, d4, d5])
roll, count = counter.most_common()[0]

if count >= 3:
    print('At least 3 out of 5 values are the same.')

Strictly speaking, this does make use of a list (which I think is what you mean; an array is something else entirely), so it depends on what exactly your restriction means.严格来说,这确实使用了一个list (我认为这就是你的意思;一个数组完全是另外一回事),所以这取决于你的限制到底意味着什么。 You could always change it to a tuple ...您总是可以将其更改为tuple ...

Quick update.快速更新。 Thanks for all the fast answer folks.感谢所有快速回答的人。 Fount my answer in another forum: Counting repeated characters in a string in Python Here's how I did mine: diceValues = str(die1), str(die2), str(die3), str(die4), str(die5) print(diceValues)在另一个论坛中找到我的答案: 在 Python 中计算字符串中的重复字符这是我的做法:diceValues = str(die1), str(die2), str(die3), str(die4), str(die5) print(diceValues )

for item in diceValues: count = diceValues.count(item) print(count)对于 diceValues 中的项目:count = diceValues.count(item) print(count)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM