1

I am trying to write code that produces a deck of cards. The deck is a 2D array that contains each card as an array. Each card array contains its card value as well as its suit, represented by the values 0 to 3. However, the code outputs this:

[[ 1.  1.]
...
 [13.  1.]
 [ 1.  1.]
...
 [13.  1.]
 [ 1.  2.]
...
 [13.  2.]
 [ 1.  3.]
...
 [13.  3.]]

The first 13 indecies are my issue here, as the code I have written I believe should output [1. 0.] up until [13. 0.]

My code is designed to have 13 of each suit, increasing from 1 to 13 (inclusive). Index 0 of each card represents the card value, Ace to King. Index 1 represents its suit (0=S,1=H,2=C,3=D).

suits = 4
suitsize = np.empty(shape=(13,2))
suitsize[:,0] = np.arange(1,suitsize.shape[0]+1)
a = suitsize
print(suitsize)
for i in range(1,suits):
    a[:,1] = i
    suitsize = np.concatenate([suitsize,a])
print(suitsize)

Whether I use np.empty, or np.zeros, the first 13 indecies all still have their index 1 value (suit) replaced with 1. This means that I end up producing a deck of cards with 0 spades, 26 hearts, 13 clubs, and 13 diamonds.

If anyone could explain to me what is happening here or a fix, please let me know. Thank you!

3
  • a = suitsize --> a = suitsize.copy() but I don't see the point of concatenation here at all. Commented Apr 30 at 16:00
  • 1
    This question is similar to: How to modify/update an array in numpy without changing original. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Apr 30 at 16:04
  • 2
    One simpler approach: cards = np.zeros((52, 2)), cards[:, 0] = np.tile(np.arange(13) + 1, 4), cards[:, 1] = np.repeat(np.arange(4), 13). Commented Apr 30 at 16:11

1 Answer 1

2

You have a classic NumPy issue — mutable arrays. The problem is that when you write a = suitsize, you're not creating a new copy of the array. You're just making a new reference to the same array in the computer's memory. So when you do a[:,1] = i, you're also modifying suitsize at the same time.

You need to create an actual copy of the array, not just a reference. Just change this line a = suitsize to a = suitsize.copy() .

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.