2

I have the following array (3 decks of 7 cards). They are sorted by row and I want to see if there are 5 consecutive numbers. The below code works but has a mistake: when there is a duplicate (like in row 1) the result is incorrect:

cards=
[[ 12.   6.   6.   5.   4.   2.   1.]
 [ 12.   9.   6.   6.   1.   1.   1.]
 [  6.   6.   1.   1.   0.   0.   0.]]

cardAmount=cards[0,:].size
has4=cards[:,np.arange(0,cardAmount-4)]-cards[:,np.arange(cardAmount-3,cardAmount)]
isStraight=np.any(has4 == 4, axis=1)

has4 (shows if there is a difference of 4 between any of the cards 5 positions apart)

[[  8.   4.   5.]
 [ 11.   8.   5.]
 [  6.   6.   1.]]

isStraight checks if any of the rows contains a 4, which means there is a straight. Result is incorrect for the first row because the duplicates are not ignored.

[ True False False]

The difficulty is that there is no way in numpy to do a np.unique with return_counts=True on a by row basis, as the results would have different lengths.

Any suggestions are appreciated. It has to be numpy only (or pandas if the speed is not compromised).

4
  • When I've done card hand classification, I compared the sorted numbers to range(5) or looked at the differences (which would a string of 1s). Commented Feb 24, 2016 at 23:21
  • Not sure I understand what you mean Commented Feb 24, 2016 at 23:36
  • Could you use a sample case that has 5 consec. numbers and also has duplicates in at least one row? Also, please add expected o/p for such a case. Commented Feb 25, 2016 at 8:08
  • yes that would also count as a straight in poker Commented Feb 25, 2016 at 8:54

1 Answer 1

0

I think this is the solution. Is there a way to make it even simpler?

iterations=3
cardAmount=cards[0,:].size
counts=(cards[:,:,None] == np.arange(12,0,-1)).sum(1) # occurences of each cards
present=counts
present[present>1]=1
s1=np.sum(present[:,0:5], axis=1)
s2=np.sum(present[:,1:6], axis=1)
s3=np.sum(present[:,2:7], axis=1)
s=np.stack((s1,s2,s3)).T
s[s < 5] = -1
s[s == 6] = 5
s[s ==7] = 5
s_index=np.argmax(s,axis=1)
straight=s[np.arange(iterations),s_index]>=0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.