Home > database >  Palidromes List using a function definition
Palidromes List using a function definition

Time:10-07

input_list = ['tacocat', 'bob', 'davey']

def palindromes(input_list):
    for word in input_list:
        if input_list[word]==reversed(input_list[word]):
            print("True")
        else:
            print("False")

output=palindromes(input_list)
print(output)

the output should be [True, True, False] but its given me error

CodePudding user response:

Reverse the string and check

input_list = ['tacocat', 'bob', 'davey']
results = [x == x[::-1] for x in input_list]
print(results)

output

[True, True, False]

CodePudding user response:

Here is a fix of your code, there were many issues:

  1. you were printing, not actually outputting anything (I added an output list and a return statement)
  2. you tried to slice input_list incorrectly (just use word)
  3. reversed does return an iterator, so the matches would always be False (use [::-1] instead)
def palindromes(input_list):
    out = []
    for word in input_list:
        if word==word[::-1]:
            out.append("True")  # used strings here, maybe you wanted booleans?
        else:
            out.append("False")
    return out

output=palindromes(input_list)

That said, here is a shorter version:

[w==w[::-1] for w in input_list]

output:

[True, True, False]

CodePudding user response:

If you would write return statement instead of print, then it would work. Also try just calling the function without assigning any variable

  • Related