Home > database >  How to use the print command from a filter function in python?
How to use the print command from a filter function in python?

Time:03-11

I have an assignment to write some code in python to filter palindromes. It should look like this:

enter image description here

This is the code I have currently but I am not able to have it print out the filtered and reversed user input:

palindrome=(input("Enter a sentence: "))
print("You typed in: ", palindrome)

def myFunc(s):
    r = ""
    for i in range(len(s)):
        c = s[i]
        if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z'):
            r  = c.upper()
    return r

filtered = filter(myFunc, palindrome)
filtered2 = (filtered)

def isPalindrome(s):         #This string reverse code was take from https://www.geeksforgeeks.org/python-program-check-string-palindrome-not/
    return s == s[::-1]
s = palindrome
ans = isPalindrome(s)
if ans:
    print("Filtered:", filtered2)
    print("Reversed:", )
    print("It is a palindrome")
else:
    print("Filtered:", filtered2)
    print("Reversed:", )
    print("It is NOT a palindrome")

This is how is displays:

enter image description here

What am I missing/doing wrong? I appreciate any help that can be provided.

CodePudding user response:

I think you should not use filter in this case. You can use myFunc directly for your input.


palindrome=(input("Enter a sentence: "))
print("You typed in: ", palindrome)

def myFunc(s):
    r = ""
    for i in range(len(s)):
        c = s[i]
        if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z'):
            r  = c.upper()
    return r

filtered = myFunc(palindrome)

def isPalindrome(s):        
    return s == s[::-1]

ans = isPalindrome(filtered)
if ans:
    print("Filtered:", filtered)
    print("Reversed:", filtered[::-1])
    print("It is a palindrome")
else:
    print("Filtered:", filtered)
    print("Reversed:", filtered[::-1])
    print("It is NOT a palindrome")

Also if you want to print the result of filter(myFunc, palindrome) you have to first convert it into a list or tuple to see what's inside of it.

In [11]: x = filter(lambda x:x%3, [1,2,3,4,5,6])                                                                                                                                

In [12]: print(x)                                                                                                                                                               
<filter object at 0x7f9c4014d580>

In [13]: print(list(x))                                                                                                                                                         
[1, 2, 4, 5]
  • Related