Good day folks.I'm new to coding and currently trying to figure out if I have a set of 5 die. die1, die2, die3, die4, die5 and I want to check if 3/5 have the same value. Is it possible without the help of an array? :)
-
what is 3/5 here? Can you elaborate your question please? – min2bro Nov 07 '19 at 02:51
-
Sure. You need a variable per possible dice value (as counters) and a lot of "if"s. Edit: Could even work without counters and a single, massive "if". – Michael Butscher Nov 07 '19 at 02:53
-
Sorry for my poor explanation. I'm trying to check if at least 3 dice have the same values out of all 5. Hope this helps :) – numnah Nov 07 '19 at 02:54
3 Answers
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 :-)

- 1,749
- 2
- 14
- 20
Certainly. Use 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. You could always change it to a tuple
...

- 19,325
- 4
- 32
- 58
-
Thanks, your code is really good, but I'm trying to avoid using [d1, d2, d3, d4, d5]. – numnah Nov 07 '19 at 03:02
-
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)
for item in diceValues: count = diceValues.count(item) print(count)

- 21
- 2
-
2
-
I'm just practicing stuff. Super new to coding and I want to learn as much as I can :) , gotta google tuple now – numnah Nov 07 '19 at 03:11
-
1A `tuple` is exactly the same as a `list` except that you can't change what's in it. – gmds Nov 07 '19 at 03:16