0

I would like to figure out if any deal is selected twice or more.

The following example is stripped down for sake of readability. But in essence I thought the best solution would be using a dictionary, and whenever any deal-container (e.g. deal_pot_1) contains the same deal twice or more, I would capture it as an error.

The following code served me well, however by itself it throws an exception...

    if deal_pot_1:
       duplicates[deal_pot_1.pk] += 1

    if deal_pot_2:
        duplicates[deal_pot_2.pk] += 1

    if deal_pot_3:
        duplicates[deal_pot_3.pk] += 1

...if I didn't initialize this before hand like the following.

    if deal_pot_1:
       duplicates[deal_pot_1.pk] = 0

    if deal_pot_2:
        duplicates[deal_pot_2.pk] = 0

    if deal_pot_3:
        duplicates[deal_pot_3.pk] = 0

Is there anyway to simplify/combine this?

5 Answers 5

3

There are basically two options:

  1. Use a collections.defaultdict(int). Upon access of an unknown key, it will initialise the correposnding value to 0.

  2. For a dictionary d, you can do

    d[x] = d.get(x, 0) + 1
    

    to initialise and increment in a single statement.

Edit: A third option is collections.Counter, as pointed out by Mark Byers.

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

1 Comment

Couldnt get teh first one working, but the second one worked for me thanks.
3

It looks like you want collections.Counter.

Comments

1

Look at collections.defaultdict. It looks like you want defaultdict(int).

Comments

1

So you only want to know if there are duplicated values? Then you could use a set:

duplicates = set()
for value in values:
    if value in duplicates():
        raise Exception('Duplicate!')
    duplicates.add(value)

If you would like to find all duplicated:

maybe_duplicates = set()
confirmed_duplicates = set()

for value in values:
    if value in maybe_duplicates():
        confirmed_duplicates.add(value)
    else:
        maybe_duplicates.add(value)

if confirmed_duplicates:
    raise Exception('Duplicates: ' + ', '.join(map(str, confirmed_duplicates)))

Comments

0

A set is probably the way to go here - collections.defaultdict is probably more than you need.

Don't forget to come up with a canonical order for your hands - like sort the cards from least to greatest, by suit and face value. Otherwise you might not detect some duplicates.

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.