Having trouble with function in Python hangman game

EladX14

I am trying to make a Hangman game in Python, and I'm having some trouble with a certain function. Before I work on the game itself, I need to make some functions.

The last one I need to make is a function that will receive a file path to a txt file that contains words separated by space, and it will receive a number that represents the index of a certain word. The function need to return a tuple made of two parts:

  1. the number of unique words in the file, meaning excluding the words that repeat themselves.
  2. the word in the index that was received, that will be used for the secret word.

The index that the player inputs needs to start from 1 and not 0, and if the index is bigger than the number of words in the file, the function will continue to count in a circular manner (meaning, when it comes back to the first word in the file).

Here is an example of a file with words called words.txt:

'''hangman song most broadly is a song hangman work music work broadly is typically'''

And here is how the function should run:

>>> choose_word(r"c:\words.txt", 3)
(9, 'most')
>>> choose_word(r"c:\words.txt", 15)
(9, 'hangman')

I did most of the things already, but I am having trouble with what to do when the index is higher than the number of words in the file. This is my current code:

def choose_word(file_path, index):
    file = open(file_path, 'r')
    num = index - 1
    list1 = []
    list2 = []
    word = ''
    counter = 0
    for x in file.split(" "):
        counter += 1
        if x not in list1:
            list1.append(x)
        if counter == num:
            word = word + x
    list2.append(len(list1))
    list2.append(word)
    list2 = tuple(list2)
    return list2

I would be glad for any help I can get, thank you in advance for taking your time to help me.

Yuval.R

You can use modulo (%) to calculate the index, like so:

def choose_word(file_path, index):
    file = open(file_path, 'r').read()
    num = (index-1) % len(file.split(" "))
    list1 = []
    list2 = []
    word = ''
    counter = 0
    for x in file.split(" "):
        if x not in list1:
            list1.append(x)
        if counter == num:
            word = x
        counter += 1
    list2.append(len(list1))
    list2.append(word)
    list2 = tuple(list2)
    return list2

See if it works for you!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related