Reputation: 45
How do I check the frequency of an item in a list and then if that item has a frequency of 4 remove all the matching items?
context:
trying to make a go fish game in python and I need to be able to check if a players hand has four matching numbers if the player's hand does then I need to remove all four of the matching items and increase there score by 1
input
score = 0
[1,2,4,3,5,6,1,1,1]
output
[2,4,3,5,6]
score += 1
the player's hand is a list of numbers.
here is the file for the game: ''' https://github.com/StarSpace-Interactive/GoFish/tree/master/GoFish
Upvotes: 0
Views: 173
Reputation: 2895
Personally, I find pandas
value_count
function more user-friendly than numpy.histogram
suggested above. You could use it like this, assuming your hand is a List (of course this solution is simpler if the hand is a Series):
import pandas as pd
hand = [1,1,2,3,4,1,1]
cards_count = pd.Series.value_counts(hand)
# count how many times each card appears
score += (cards_count>=4).sum()
# add 1 to score for each card that repeats at least 4 times
hand = [card for card in hand if card not in cards_count.index[cards_count>=4]]
# keeps only cards that did not appear >=4 times
Upvotes: 0
Reputation: 143
You can do achieve your goal by Counter
. For example,
from collections import Counter
mylist = [1,2,4,3,5,6,1,1,1]
counter = Counter(mylist)
Then, the counter
is
Counter({
1: 4,
2: 1,
4: 1,
3: 1,
5: 1,
6: 1
})
Then, you can write a python function to update the score and the counter.
def update_score(counter, curr_score):
remove_keys = list()
# update score
for key, value in counter.items():
if value >= 4:
curr_score += 1
remove_keys.append(key)
# remove key
for key in remove_keys:
del counter[key]
return counter, curr_score
It will return the new current score and the updated counter back.
Upvotes: 0
Reputation: 539
from collections import defaultdict
score = 0
hand = [1,2,4,3,5,6,1,1,1] # current hand
# im guessing you are doing this in a loop
d= defaultdict( int )
for card in hand:
d[card] += 1
fourList = []
for key, value in d.items():
if value >= 4:
fourList.append(key)
hand = [n for n in hand if n not in fourList]
score += len(fourList)
print(hand)
print(score)
Upvotes: 0
Reputation: 376
Here's a solution:
from collections import Counter
score = 0
hand = [1,2,4,3,5,6,1,1,1]
counts = Counter(hand)
for num, count in counts.items():
if count >= 4:
hand = list(filter((num).__ne__, hand))
score += 1
print(hand)
print(score)
And the output is:
[2, 4, 3, 5, 6]
1
Upvotes: 1