1

Yesterday, I was trying to solve a problem with python, and I encountered something really odd:

# create matrix
for i in range(N):
    tmp.append(0)

for i in range(N):
    marker.append(tmp)

# create sum of 2 first cards
for i in range(N) :
    for j in range(N):
      if i != j and marker[i][j] == 0:
          comCard.append(deck[i]+deck[j])
          taken[deck[i]+deck[j]] = [i,j]
          marker[i][j] = 1
          marker[j][i] = 1

The idea is that I want to calculate all the possible sums of each pair of cards in the deck (these cards need to be different), so I think that with a marker, I can avoid calculating the same 2 cards again. for example: deck[1]+deck[2] and deck[2]+deck[1]. But these lines didn't work as they were supposed to do:

marker[i][j] = 1
marker[j][i] = 1
2

2 Answers 2

2

I can recommend another way using standard python modules:

# suppose this is a deck - list of cards (I don't know how to mark them :)
>>> deck = ['Ax', 'Dy', '8p', '6a']

>>> from itertools import combinations
# here's a list of all possible combinations of 2 different cards
>>> list(combinations(deck, 2)))
[('Ax', 'Dy'), ('Ax', '8p'), ('Ax', '6a'), ('Dy', '8p'), ('Dy', '6a'), ('8p', '6a')]

You may work with this list: check some combinations and so on.

I recommend to pay attention to library itertools - it's really awesome for such type computations!

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

Comments

0

You're using the same instance of tmp, only shallow-copied. That's why it doesn't work. You need a new copy of each line to add in your matrix.

This can be done with:

marker.append(list(tmp))

Also, you may benefit from using True and False instead of 0 and 1 someday. So the initialisation of your matrix could rahter look like this:

tmp = list()
marker = list()
for i in range(N):
    tmp.append(False)
for j in range(N):
    marker.append(list(tmp))

This way, when you try marker[i][j] = True, only the index (i, j) will be affected.


That being said, Eugene Lisitsky's answer gives you a far more adapted tool for this kind of matter (permutation listing).

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.