Python Forum
Palindrome program - I can't figure it out.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Palindrome program - I can't figure it out.
#1
from string import ascii_letters, digits

s = open("saxo.txt").read()
s = s.lower()
s = "".join([c for c in s if c in ascii_letters or c in digits])

def is_palindrome(s):
    if len(ascii_letters) >=7 and ascii_letters== ascii_letters[::-1]:
        return ascii_letters
    
print(is_palindrome(s))
# I want to create a program that computes all palindromic substrings of length ≥ 7 from the file.
# But somehow I can't make it work. I'm new to Python
Reply
#2
You almost have it right.
The file was read in as one big chunk, so s contained the whole file, not just one item.
you needed to strip the line feed off
and notes for other changes below

# Don't need this
#from string import ascii_letters, digits

# s = open("saxo.txt").read()
# read file this way

def ispalendrome(s):
    s1 = s.replace(' ', '').lower()
    return str(s1) == str(s1)[::-1]

def main():
    with open ("saxo.txt") as f:
        for s in f:
            s = s.strip()
            if len(s) > 6:
                if ispalendrome(s):
                    print('{} is a palandrome'.format(s))
                else:
                    print('{} is not a palandrome'.format(s))
main()

# Don't need this
# s = s.lower()
# s = "".join([c for c in s if c in ascii_letters or c in digits])
This line:
s1 = s.replace(' ', '').lower()
compresses the string and makes all characters lower case.

This line:
return str(s1) == str(s1)[::-1]
uses the same logic as you already had, but assures s is a string
Reply
#3
I'm sorry I tried your method, but it doesn't return what I'm exactly looking for.
It just takes the whole text and after every sentence it writes whether it's a palindrome or not.
My aim is to find alle the palindrome with length =>=7.


For a given string s, we learned to find substrings with length =>2 like this:

s = 'ahrabaabrahfhalla'

for i in range(len(s)):
for j in range(i+2, len(s)):
t = s[i:j]
if t == t[::-1]:
print(t)

I tried the same method in this task, but it doesn't return anything.
Reply
#4
Please use code tags.
Sorry, I misunderstood the task.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Bug Program to check whether a number is palindrome or not PythonBoy 18 2,641 Sep-12-2023, 09:27 AM
Last Post: PythonBoy
  Palindrome checker case sensive edwdas 3 2,634 Nov-07-2019, 05:57 PM
Last Post: nilamo
  Palindrome.strip pirts.emordnilaP RodNintendeaux 4 3,845 Oct-08-2017, 02:30 AM
Last Post: RodNintendeaux

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020