2

I'm trying to extend my hangman game so that your able to select the amount of letters you want your word to be. I'll do this by using the selection method (e.g. if,else) however after making the function i come across an error so i threw away the whole function after finding where the error came from and started working on solving the error. Basically I'm trying to use index() function to locate where the element is but for some reason it doesn't work it always outputs 0.

def wordLength(word):
    r = word
    num=word.index(r)
    print(num)
Ivan
  • 117
  • 1
  • 1
  • 9
  • 1
    Can you give an example of input with an expected output? I'm having trouble understanding what you want. – juanpa.arrivillaga Mar 24 '17 at 20:59
  • problem with index is that it returns the first occurrence. – Jean-François Fabre Mar 24 '17 at 21:00
  • 2
    But your code essentially searches a string for itself, so it will always return position `0` – juanpa.arrivillaga Mar 24 '17 at 21:06
  • Are you using a GUI or is everything done in console? – Mike - SMT Mar 24 '17 at 21:07
  • I have a long list of around 100 words and ive used the split() function to split them up so like where there is a space thats where it will make a split. If you guys want i could insert the hole hangman game into the description above so you get a better idea. i have also make another function which chooses a random word from the 100 words and i use the assigned variable which is the parameter of the function – Ivan Mar 24 '17 at 21:18
  • No need to post the whole game, just *properly specify what you are trying to accomplish*. E.g. example input, example output. – juanpa.arrivillaga Mar 24 '17 at 21:24
  • ok so if the input is Lizard the output has to be where lizard is located in the split string for example element 3 – Ivan Mar 24 '17 at 21:29

5 Answers5

1

I think what you are trying to achieve is this (since you mentioned you used .split() in the comments on your question:

sentence = "this is a sentence"
sentence_split = sentence.split()

def wordLength(word, sentence):
    try:
        index = sentence.index(word)
        print(index)
    except:
        print("word not in sentence")

wordLength("a", sentence_split)

Results in '3', which is the position of 'a' within your sentence.

EDIT

Or, if you want the index number of each letter within each word..

sentence = "this is a sentence"
sentence_split = sentence.split()

letter_index = []
def index_letters():
    for i in sentence_split:
        # I results in "this" (1st loop), "is" (2nd loop), etc.
        for x in range(len(i)):
            # loops over every word, and then counts every letter. So within the i='this' loop this will result in four loops (since "this" has 4 letters) in which x = 0 (first loop), 1 (second loop), etc. 
            letter = i[x]
            index = i.index(letter)
            letter_index.append([index, letter])
    return letter_index

print(index_letters())

Results in: [[0, 't'], [1, 'h'], [2, 'i'], [3, 's'], [0, 'i'], [1, 's'], [0, 'a'], [0, 's'], [1, 'e'], [2, 'n'], [3, 't'], [1, 'e'], [2, 'n'], [6, 'c'], [1, 'e']]

Montmons
  • 1,416
  • 13
  • 44
  • It may be my mistake im sorry as in when i descibed my problem but im trying to find for example where the word 'heat' is in a split string ( the element number) – Ivan Mar 24 '17 at 21:32
  • Then my first option should work. It tells you where the word ("a") is in a string ("This is a string"). Which results in.. 3. – Montmons Mar 24 '17 at 21:33
  • raises a `ValueError`, if the word is not in the sentece – DahliaSR Mar 24 '17 at 21:46
  • Which is only logical and easy to correct by wrapping it in a try-statement, or simply checking if word has a value.. I'll adapt my answer – Montmons Mar 24 '17 at 21:53
  • 1
    @SB87 LYBL is not very pythonic. Pythonistas ussually prefer EAFP so try-except would be nicer, I think. – DahliaSR Mar 24 '17 at 22:00
  • Ah, wasn't aware of that! Some new abbreviations for me. But found their meaning and seems you're right. Edited my answer once more.. – Montmons Mar 24 '17 at 22:17
  • @SB87 can you tell me where i could give you my code to check why there is constantly an Index error in the line 'if len(word[index]) >= 5:' – Ivan Mar 26 '17 at 14:09
  • You could copy paste your code in an online editor like [this one](https://trinket.io/python) and post the share-url here. I can then see what's going wrong and adapt or explain any mistakes – Montmons Mar 26 '17 at 15:32
  • Ok thanks so heres the code: https://trinket.io/python/f138c1d9ac when you run it on that website it shows an error that is false so run it on python shell. When you first run the code on python shell it will ask you to enter 1 or 2 Please enter 1 so that the error that im working on will appear as when we fix that error i'll be able to fix all the errors :D The error that is going to appear will be an index error on line 79. if len(word[index]) >= 5: – Ivan Mar 26 '17 at 16:04
  • You are asking the index of the word in a list of words. So if `word = baboon`, then `index=1`. Then you call `len(word[index])`, `word[index]` would translate into `baboon[1]`, which = b. So `len(word[index])` will always be `1`. Furthermore, if the word has a higher index in de wordList (e.g. zebra), the index will be 42 and `word[index]` would result in `zebra[41]`, which gives an index error as zebra only has 5 letters... So, remember: Something[index] retrieves an item at the given indexnr. If something is a list it will retrieve a list-item, if something is a word it'll retrieve a letter – Montmons Mar 26 '17 at 16:25
  • So, on change line 81 into `if len(word) >= 5:`. Also change line 122 into `print(letter)` and the code will also work in the online interpreter. Not sure what you where trying to achieve with the original `print(letter, end=' ')` statement? Since this is incorrect syntax. – Montmons Mar 26 '17 at 16:36
  • Ah, not entirely true, check [this post](http://stackoverflow.com/a/2456292/4041795) for the `end = ' '` problem. Could be it is the online interpreter at fault here. – Montmons Mar 26 '17 at 16:38
  • Ya i agree however on line 80 on trinket i did ' index=index=1 and shouldnt the 'except IndexError:' on line 89 and the statements below it solve the problem with when the Index is out of range – Ivan Mar 26 '17 at 16:39
  • No, because line 89 is only executed if line 81 can be properly evaluated.. However, this is turning into a code review, please post your question on [the correct Stack](http://codereview.stackexchange.com) for that. Thnx! (also, have to go now.. good luck!) – Montmons Mar 26 '17 at 16:41
  • Ps `index = index -1` will only change zebra[41] into zebra[40] which is still an obvious index error and thus, line 89 is never even executed. – Montmons Mar 26 '17 at 16:43
  • @SB87 I fixed the problem now here is the result https://trinket.io/python/9c63720d43 between the lines of 77 - 99 the problem was that i was trying to change a a variable that had only 1 index because it was the variable that i got from the Random Word selector and i hadnt realised that but anyways you helped me a lot THANKS :D! – Ivan Mar 26 '17 at 19:38
1

If I understand what you are asking then you should be able to take the word chosen for the hangman game and create a list of every letter in the word then finding the index() of the letter in the list.

Without the question being more clear it seams like you are asking for the index of a letter in a word. What I have for that is below.

something like this should help:

hm_word = []   #the list to be created for the given word

def wordlist(hangman_word): #Creates a list of each letter of the word
    for letter in hangman_word:  
        hm_word.append(letter)  

wordlist("bacon")# calls the function and puts in the word chosen

print (hm_word) #just to show the list has been created
print (hm_word.index("o")+1) #This prints the index of the letter 'o' however you can use a user input here.
#NOTE: I used +1 in the print for the index to show the index number starting from 1 not 0

you can use this as a starting point to get the index of the letter being guessed by taking the user input and placing it in the index(). I only used "o" as an example of how it works.

Mike - SMT
  • 14,784
  • 4
  • 35
  • 79
1
def find_word(word, word_list):
    try:
        return word_list.index(word)
    except ValueError:
        return None    # or what ever you need

>>> word_list = ['bubble', 'lizzard', 'fish']
>>> find_word('lizzard', word_list)
1
>>> print(find_word('blizzard', word_list))
None
DahliaSR
  • 77
  • 6
0

It's returning 0, because you are running index on the input variable for itself. You will need to index on a segment of the input variable. A slight modification of your example, that will return something other than 0:

def wordLength(word):
    r = 'r'
    num=word.index(r)
    print(num)

This should print the number 2.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
0

"wordLength" is a bit of a misnomer here for your function. If you want the length of a word, you can just do: len(word)

def findChar(word, char):
    # don't go any further if they aren't strings
    assert isinstance(word, basestring)
    assert isinstance(char, basestring)
    # return the character you are looking for,
    # in human friendly form (1 more than the python index)
    return word.lower().index(char.lower()) + 1

to use:

>>>print findChar('heat', 'a')
3   # a is in the third position.

This does not address a single character being in a word many times, obviously.

JacobIRR
  • 8,545
  • 8
  • 39
  • 68
  • It may be my mistake im sorry as in when i descibed my problem but im trying to find for example where the word 'heat' is in a split string ( the element number) – Ivan Mar 24 '17 at 21:32
  • does a split string imply a sentence like "The heat is on" ? and you want to see '2' printed as a result? – JacobIRR Mar 24 '17 at 21:36