Jhern603
Jhern603

Reputation: 11

Counting recurring characters that occur more than two times

I am working on making a complete Hangman project as my first independent project since I finished learning Python on Code Academy. (Github: https://github.com/jhern603/Python-Hangman)

Currently, it is able to identify recurring characters in a string but if it happens more than twice, it won't count the additional times the character is repeated.

For example, if the user selectes 'movies' as the category and the program selects, 'full metal jacket,' it'll count two "l's" but does not count any additional "l's" afterwards, leaving the program in a state of limbo where the user is unable to complete it unless he maxes out on mistakes on purpose. This is what it would look like on the console (the array of guessed letters are print):


Pick a letter:k

'K' was correct.

f u l l m e e t t a a j c k


Blocks in question:

... def word_selector(self, category): if category in self.words: self.properCategory = True print("\nYou selected: '" + category + "' as the category for this round.\n") self.picker = random.randint(0, len(self.words[category])) - 2 self.selected_category = self.words[category] self.word = self.selected_category[self.picker].lower() self.word_=self.word.replace(' ','') self.word_sorted=sorted(self.word_) self.counter = collections.Counter(self.word) self.isAlpha = True ...

... def correct(self): if self.user_choice in self.word and len(self.guessed_correctly) <= len(self.word): self.guessed_correctly.append(self.user_choice) if self.user_choice in self.charRepeated: self.guessed_correctly.append(self.user_choice) print("\n'"+self.user_choice.upper() + "' was correct.\n") print(' '.join(self.guessed_correctly))

Upvotes: 0

Views: 105

Answers (2)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15568

I would simply loop through all places and replace the guess letter. Here is a silly terrible and inefficient working code just to give you a possible way to do it.

import random
import re

class Hang:

    def __init__(self):
        print('Hello Hangma: \n')


    def replacer(self):
        if not self.position:
            self.position = []

        while self.guess in self.selected:
            self.position.append(self.selected.index(self.guess))
            self.selected = self.selected.replace(self.guess,'_',1)
        return self.position

    def hang(self):
        self.guess = input('\nGuess a letter:\n')
        assert len(self.guess)==1
        #do something
        if self.guess in self.selected:
            self.position = self.replacer()

            for i in self.position:
                self.dash = f'{self.dash[:i]}{self.guess}{self.dash[i+1:]}'
        else:
            print(f'Nope! {self.guess} is not there')

        self.position = []  
        print(self.dash)
        return self.dash

    def play(self):
        self.category = {'movies':['full metal jacket','rambo','commando']}

        self.selected = random.choice(self.category['movies'])
        self.dash = re.sub('\w','_',self.selected)

        self.position = None

        print(f'Hit:\n{self.dash}')
        while '_' in self.dash:
            self.dash = self.hang()


if __name__=='__main__':
    game = Hang()
    game.play()

What I did is created three functions. play is simply a main part that calls the rest. replacer is a function that replaces all places the letter appears in the word and hang calls replacer function to do its magic. You can now add counts of tries, and build a hangman. At the moment, there is no limit ;)

Upvotes: 0

Silver
Silver

Reputation: 1468

from collections import Counter

Counter(word)

You can use pythons Counter to get a count of how many times each character appears in a word. From there it's very easy to filter out those which occur more than once.

For example, in your case you can use something like:

word = "full metal jacket"
counts = Counter(word)

recurring = {k:v for k, v in counts.items() if v > 1}

which will give you:

{'e': 2, 't': 2, ' ': 2, 'a': 2, 'l': 3}

Upvotes: 3

Related Questions