-2

I’m currently completing a go fish program and python and am struggling to determine how to “check” if there are 4 cards of the same rank (ace, 2, etc) in one hand and remove them. My current code is as follows,

def check(hand, score):

   for i in range(len(hand)- 1):

    j = hand[i]

    if j == 4:

      print("you have completed a set :)")

      for j in range(4):

        hand.remove[j]

    score += 1

  else:

    print("no sets have been found ☹")

Any suggestions?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    Hi @studentcoder, welcome to Stack Overflow. Your code doesn't make very much sense right now because the indentation has been messed up, probably by the process of copying the code into the site's question box. Can you [edit] it so it looks the same here as it does in your editor? Since indentation has syntactic meaning in Python it is going to be hard to interpret your code the way it currently looks. Furthermore, can you describe what is wrong with your current code? Is it raising an exception? If so, give the full traceback. Is it giving the wrong answer? Show example inputs and outputs. – Blckknght May 18 '20 at 05:03
  • Please repeat [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). – Prune May 18 '20 at 05:08
  • Please note that python function arguments are [passed by-assignment](https://stackoverflow.com/a/986145/2546289). I guess you want to return `score`. – Stefan Scheller May 18 '20 at 05:08
  • Note in particular that we expect you to research your question before posting here. This is a subset of evaluating power hands, which has been described in detail, in many programming languages, both on Stack Overflow and elsewhere. – Prune May 18 '20 at 05:09

1 Answers1

0

You could use a set to get unique cards in your checked hand and then count the number of occurrences:

def check(hand):
    score = 0
    for card in set(hand):
        count = len([x for x in hand if (x == card)])
        if count >= 4:
            score += 1
            print("you have completed a set of '{}' :)".format(card))
            for j in range(count):
                hand.remove(card)
    if score == 0:
        print("no sets have been found ☹")

    return score

h1 = [i for i in range(12)]
h2 = [i for i in (['A', 'A', 'A', 'A', 7, 7, 7, 'J'] + h1)]

print(h1)
print('Score: {}\n'.format(check(h1)))

print(h2)
print('Score: {}'.format(check(h2)))

Result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
no sets have been found ☹
Score: 0

['A', 'A', 'A', 'A', 7, 7, 7, 'J', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
you have completed a set of '7' :)
you have completed a set of 'A' :)
Score: 2
Stefan Scheller
  • 953
  • 1
  • 12
  • 22