Home > Net >  Reference next Item in List - Python
Reference next Item in List - Python

Time:03-20

I am working through a program that requires me to determine if a list of strings is a word chain. A word chain is a list of words in which the last letter of a word is the first letter of the next word in the last. The program is to return True if the list is a word chain, and false otherwise. My code is as follows:

def is_word_chain(word_list):
    for i in word_list:
        if i[-1] == (i 1[0]):
            result = True
        else:
            result = False 
    return result

and it returns the following error:

SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
  if i[-1] == (i 1[0]):
Traceback (most recent call last):
  if i[-1] == (i 1[0]):
TypeError: 'int' object is not subscriptable

I am wondering how I would properly reference the next item in the list in order to execute this function

CodePudding user response:

Given:

>>> li1=['word','chain','test','test']
>>> li2=['word','chain','test']

You can use zip to get a pair of words to test:

>>> list(zip(li1,li1[1:]))
[('word', 'chain'), ('chain', 'test'), ('test', 'test')]

Once you have that, you can return True or False like so:

>>> any(t[0][-1]==t[1][0] for t in zip(li1,li1[1:]))
True

>>> any(t[0][-1]==t[1][0] for t in zip(li2,li2[1:]))
False

CodePudding user response:

Fixed it :)

def is_word_chain(word_list):
    for i in range(len(word_list)-1):
        if word_list[i][-1] == word_list[i 1][0]:
            result = True
        else:
            result = False 
            break
    return result

print(is_word_chain(['apple', 'egg', 'grapes', 'sand']))
print(is_word_chain(['apple', 'egg', 'sand', 'grapes']))

CodePudding user response:

def is_word_chain(word_list):
for i in range(0,len(word_list)-1):
    if word_list[i][-1] == word_list[i 1][0]:
        result = True
    else:
        result = False 
return result

in your code you iterate through strings and in if condition you are trying use that string as sort of list which is technically blunder here.

use range and iterate over word_chain as list.

  • Related