473,842 Members | 1,337 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Palindrome

Does anyone know how i can fix my Palindrome program?

s = raw_input('Ente r a String: ')
punctuation = '%$!*.,-:? ;()\'\"\\'
i = 0
h = 0
t = 0
p = ''
z = 0
while s!= ' ':
while i <= len(s) - 1:
punct = s[i]
if punctuation.fin d(punct) == -1:
p = p + punct
i = i + 1
t = p.lower()
t[h] == t[len(t)-1-h]
Jul 18 '05 #1
24 13031
On 13 Nov 2003 03:31:35 GMT, Runic911 wrote:
Does anyone know how i can fix my Palindrome program?

i = 0
h = 0
t = 0
p = ''
z = 0


You can start by using mnemonic variable names. These ones make the
algorithm a chore to read. Feel free to re-post it when you've done so.

--
\ "I believe in making the world safe for our children, but not |
`\ our children's children, because I don't think children should |
_o__) be having sex." -- Jack Handey |
Ben Finney <http://bignose.squidly .org/>
Jul 18 '05 #2
Knowing what your program should do, could also help.
G-:

"Runic911" <ru******@aol.c om> wrote in message news:20******** *************** ****@mb-m12.aol.com...
| Does anyone know how i can fix my Palindrome program?
|
| s = raw_input('Ente r a String: ')
| punctuation = '%$!*.,-:? ;()\'\"\\'
| i = 0
| h = 0
| t = 0
| p = ''
| z = 0
| while s!= ' ':
| while i <= len(s) - 1:
| punct = s[i]
| if punctuation.fin d(punct) == -1:
| p = p + punct
| i = i + 1
| t = p.lower()
| t[h] == t[len(t)-1-h]
--
Georgy Pruss
E^mail: 'ZDAwMTEyMHQwMz MwQGhvdG1haWwuY 29t\n'.decode(' base64')
Jul 18 '05 #3
Georgy Pruss wrote:
Knowing what your program should do, could also help.
G-:


As far as I know is a palindrome a word that you can read from both
sides. Sorry, but English is not my native language. So I don´t have an
English example handy. But the German name 'OTTO' is a palindrome.
--
-- Ulli
www.u-schramme.de

Jul 18 '05 #4
Hi Runic911,

You probably want this

t = p.lower()
t[h] == t[len(t)-1-h]

to do something. As it is now you don't report anything.
Looking at it some more I see it has several other problems.
The code starting at 't=p.lower()' needs to be dedented a
few levels so it is outside of the 'while s != '':' loop.
Also, that should be 'if s != '':' and likely doesn't
even need to be there at all.

In addition, you could shorten it by quite a bit by using
some of this higher-level functions available in Python.
Here's some pointers.

1) get rid of puncutation in one step rather than several.

You can use the re module for that, as in
s = "A man, a plan, a canal -- Panama!"
import re
re.sub(r'[%$!*.,:? ;()\'\"\\-]', '', s) 'Amanaplanacana lPanama'
This is tricky, in part because the '-' must be at the end of pattern.
You could also use the translate function, as in
punctuation = '%$!*.,-:? ;()\'\"\\'
identity = "".join([chr(i) for i in range(256)])
s.translate(ide ntity, punctuation) 'Amanaplanacana lPanama'
This is also tricky because you have to use an identity
translation table. (On the other hand, done correctly this
could also convert everything to lower case.) I would
like a function which only removed a selected set of
characters.

Or you could make your own function for it
def remove_punctuat ion(s): .... letters = []
.... for c in s:
.... if c not in punctuation:
.... letters.append( c)
.... return "".join(letters )
.... remove_punctuat ion(s) 'Amanaplanacana lPanama'
You could put this all into your palindrome code but
it's usually easier to understand your code if each
step does one thing. By the way, an experienced
Python programmer might write this function as

def remove_punctuat ion(s):
return "".join([c for c in s if c not in punctuation])

(since I didn't test this one, odds are good there's
a typo ;)

2) convert everything to the same case. If you use
the regular expression way then use the lower() method,
which you know about already.

The translate function can do it like this
for upper, lower in zip(string.asci i_uppercase, string.ascii_lo wercase): .... foldcase[ord(upper)] = lower
.... foldcase = "".join(foldcas e)
s 'A man, a plan, a canal -- Panama!' s.translate(fol dcase, punctuation) 'amanaplanacana lpanama'
3) instead of comparing the string to itself, make a
new string which is a reverse of the old one and compare
the strings to each other

In newer Pythons (2.3) you can use [::-1] as a way
to slice the string backwards. Here's some examples
s 'A man, a plan, a canal -- Panama!' s[::-1] '!amanaP -- lanac a ,nalp a ,nam A' t = s.translate(fol dcase, punctuation)
t 'amanaplanacana lpanama' t[::-1] 'amanaplanacana lpanama'
Since t == t[::-1] you know they are palindromes.

For older Pythons you'll need to turn the string
into a list of characters, reverse the list, and turn
it back into a string, as in
chars = list(s)
chars ['A', ' ', 'm', 'a', 'n', ',', ' ', 'a', ' ', 'p', 'l', 'a', 'n', ',', ' ',
'a', ' ', 'c', 'a', 'n',
'a', 'l', ' ', '-', '-', ' ', 'P', 'a', 'n', 'a', 'm', 'a', '!'] chars.reverse()
chars ['!', 'a', 'm', 'a', 'n', 'a', 'P', ' ', '-', '-', ' ', 'l', 'a', 'n', 'a',
'c', ' ', 'a', ' ', ',',
'n', 'a', 'l', 'p', ' ', 'a', ' ', ',', 'n', 'a', 'm', ' ', 'A'] "".join(cha rs) '!amanaP -- lanac a ,nalp a ,nam A'


This should be enough information for you to make a
very nice palindrome function.

Andrew
da***@dalkescie ntific.com
Jul 18 '05 #5
Runic911 wrote:
Does anyone know how i can fix my Palindrome program?

s = raw_input('Ente r a String: ')
punctuation = '%$!*.,-:? ;()\'\"\\'
i = 0
h = 0
t = 0
p = ''
z = 0
while s!= ' ':
while i <= len(s) - 1:
punct = s[i]
if punctuation.fin d(punct) == -1:
p = p + punct
i = i + 1
t = p.lower()
t[h] == t[len(t)-1-h]

I´m not very experienced with Python but I think you could do it in a
more simple way.
inp = raw_input('Ente r a string: ')

pal = []
rev = []
for c in inp:
if c.isalnum():
pal.append(c.up per())
rev.append(c.up per())
rev.reverse()
if pal == rev:
print '"' + inp + '" ' + 'is a palindrome.'
else:
print '"' + inp + '" ' + 'is no palindrome.'

--
-- Ulli
www.u-schramme.de

Jul 18 '05 #6
Ulrich Schramme:
I´m not very experienced with Python but I think you could do it in a
more simple way.


Looks good to me. And it shows that I'm no longer able to help out
beginning programmers since my solution is along the lines of

inp = raw_input('Ente r a string: ')

punctuation = '%$!*.,-:? ;()\'\"\\'
foldcase = [chr(i) for i in range(256)]
for upper, lower in zip(string.asci i_uppercase, string.ascii_lo wercase):
foldcase[ord(upper)] = lower
foldcase = "".join(foldcas e)

t = inp.translate(f oldcase, punctuation)
if t != t[::-1]:
print '"' + inp + '" ' + 'is a palindrome.'
else:
print '"' + inp + '" ' + 'is not a palindrome.'

Faster, but with a startup cost and a high learning curve.
It's what I would use for my own code.

A slightly easier to understand and slower version is

inp = raw_input('Ente r a string: ')
punctuation = '%$!*.,-:? ;()\'\"\\'
identity = "".join([chr(i) for i in range(256)])

t = inp.translate(i dentity, punctuation).lo wer()
if t != t[::-1]:
...

Yours is definitely easiest to understand so best for
the OP.

Cheers,
Andrew
da***@dalkescie ntific.com
Jul 18 '05 #7
Andrew Dalke wrote:
Ulrich Schramme:
I´m not very experienced with Python but I think you could do it in a
more simple way.

Looks good to me. And it shows that I'm no longer able to help out
beginning programmers since my solution is along the lines of

inp = raw_input('Ente r a string: ')

punctuation = '%$!*.,-:? ;()\'\"\\'
foldcase = [chr(i) for i in range(256)]
for upper, lower in zip(string.asci i_uppercase, string.ascii_lo wercase):
foldcase[ord(upper)] = lower
foldcase = "".join(foldcas e)

t = inp.translate(f oldcase, punctuation)
if t != t[::-1]:
print '"' + inp + '" ' + 'is a palindrome.'
else:
print '"' + inp + '" ' + 'is not a palindrome.'

Faster, but with a startup cost and a high learning curve.
It's what I would use for my own code.

A slightly easier to understand and slower version is

inp = raw_input('Ente r a string: ')
punctuation = '%$!*.,-:? ;()\'\"\\'
identity = "".join([chr(i) for i in range(256)])

t = inp.translate(i dentity, punctuation).lo wer()
if t != t[::-1]:
...

Yours is definitely easiest to understand so best for
the OP.

Cheers,
Andrew
da***@dalkescie ntific.com

Thanks Andrew,

there might be a million ways to solve the palindrome problem. I think
that another good way would be the use of regular expressions. I´m a
software developer by profession but quite new to Python. So I tried to
find an easy way that fits my limited knowledge of the Python syntax.

My first impression of Python is that it is a well - designed and
interesting language. I also like this newsgroup. People here seem to be
more helpful than in some other groups I know...

Hopefully taking part in discussions here will improve my English as
well as my Python :-)

--
-- Ulli
www.u-schramme.de

Jul 18 '05 #8

"Ulrich Schramme" <ne**@u-schramme.de> wrote in message news:bo******** **@online.de...
| Georgy Pruss wrote:
| > Knowing what your program should do, could also help.
| > G-:
| >
|
| As far as I know is a palindrome a word that you can read from both
| sides. Sorry, but English is not my native language. So I don´t have an
| English example handy. But the German name 'OTTO' is a palindrome.

I know what is a palindrome, but I can make up dozen things
the program could do with the palindrom.
G-:
|
|
| --
| -- Ulli
| www.u-schramme.de
|
Jul 18 '05 #9
Georgy Pruss wrote:
I know what is a palindrome, but I can make up dozen things
the program could do with the palindrom.
G-:


Sorry, it seems that I misunderstood your previous posting.

--
-- Ulli
www.u-schramme.de

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
13870
by: Lorin Leone | last post by:
Can anyone help me modify the program so that it recognizes strings like "Anna" as palindromes. To make the program "case-insensitive." using the built-in C++ function "toupper". and so that it recognizes strings like "race car" as palindromes, have the program ignore spaces in the input string. Here is my code:
23
3210
by: Amar Prakash Tripaithi | last post by:
Dan Hoey, who had recently graduated, wrote a C program to look for and construct the following beauty: A man, a plan, a caret, a ban, a myriad, a sum, a lac, a liar, a hoop, a pint, a catalpa, a gas, an oil, a bird, a yell, a vat, a caw, a pax, a wag, a tax, a nay, a ram, a cap, a yam, a gay, a tsar, a wall, a car, a luger, a ward, a bin, a woman, a vassal, a wolf, a tuna, a nit, a pall, a fret, a watt, a bay, a daub, a tan, a cab, a...
32
11449
by: ramakrishnadeepak | last post by:
HI Everybody, I 've to submit a program on c.Can any one help me plz.........The problem is like this:: Write a program which computes the largest palindrome substring of a string. Input: The input is the string whose largest palindrome substring should be
4
4604
by: outofmymind | last post by:
hi, im trying to solve the following question: Create a class responsible for determining whether a string is a palindrome. Show your test cases. Palindome mypal("bob"); mypal.Ispalindrome(); // should return true i tried to do the code, but im having problems in comlpeting it, I hope that some one can help me know how im supposed to finish it off this is the code that i did: #include <iostream>
3
6134
by: colinNeedsJavaHelp | last post by:
I am still having an exceptional amount of trouble with java. This is my new assignment, if anyone can help I would greatly appreciate it. I don't even know where to start. A word or phrase in which the letters spell the same message when written forward and backward (with whitespaces and punctuations not considered) is called a palindrome. Write a simple Java program that detects palindromes. Your program should be named...
2
2796
by: Synapse | last post by:
aloha people! I need help in my java palindrome program. It's a 5-digit palindrome checker. The code below is running good but i got a few problems on it. If I enter 33633, 11211, 45554, it will return It's a Palindrome! and if I enter 33636 or 11214, it returns It's not a Palindrome!
20
13413
by: Wabz | last post by:
Hello mates, Does anyone know how to write a function that tests if an integer is a palindrome in C language?
4
5265
by: vicestner | last post by:
Write a Java program that prints the longest palindrome in an input file to standard output. A palindrome is a string whose reverse is the same as the original. Ignore case, whitespace, and punctuation in the input. If there are more than one palindrome of the maximum length, print the first one. Remove all space and punctuation and convert upper case to lower case in the output. If the input file contains: Was it a rat I saw? Your program...
5
3510
by: rubyhuang | last post by:
i'm a new perl learner, this is the first perl task i will do. please help me. The user can input a string, and then a script will check to see if the string is a palindrome or not, displaying the result to the user on another page (include the original string that they input in the displayed output). Disregard the case of letters, as well as spaces and any punctuation symbols in the sentence (use Perl string routines to deal with these...
2
4144
by: bigtd08 | last post by:
help writing this palindrome program for my c++ class. HERE WHAT THE CODE SHOULD BE LIKE. Write a program that takes a line of input from the keyboard and check to see if that line is a palindrome. Your program should ignore blanks, punctuation, and lettercase Your program should output what the user entered as well as the reversed line. Sample output: Please enter a phrase, and I will tell you if it is a palindrome. >> Madam I'm Adam
0
10952
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10618
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10683
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10320
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9459
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7862
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7045
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5699
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.