Determining whether a string is a Palindrome - python

I wrote the following program to determine whether a string s a palindrome using recursion. My problem is that I am not sure how to add a print statement that tells me whether the string is a palindrome or not. I realize that there are other codes which do the same thing, but I am trying to understand if my reasoning is correct.
import re
s= raw_input( " Enter a string to check if it is a palindrome ")
newstring = re.sub('\W', '', s)
newstring =newstring.lower()
def Palind(newstring):
if newstring[0] != newstring[-1]:
#print 'The given string is not a palindrome'
return False
else:
s_remain = newstring[1:-1]
if s_remain == '':
return True
elif len(s_remain) == 1 :
return True
else:
return Palind(s_remain)
if Palind(newstring):
print 'Yes'
else:
print 'No'

First, correctly indent your code, and properly lowercase the input:
import re
s= raw_input( " Enter a string to check if it is a palindrome ")
newstring = re.sub('\W', '', s)
newstring = newstring.lower()
def Palind(newstring):
if newstring[1] != newstring[-1]:
#print 'The given string is not a palindrome'
return False
else:
s_remain = newstring[1:-1]
return Palind(s_remain)
Then actually call your function and deal with the result:
if Palind(newstring):
print ('Yes')
else:
print ('No')
That's how you print the result of your function..
You will have problems when you enter a palindrome though, because you never actually return true. You'll need to fix that by checking if you've gotten to the end of the string without returning false.

Your logic is roughly right, but you are missing some things.
The first character in a string is string[0] not string[1], so you are comparing the wrong characters.
You need to call Palind() as well as defining it.
If you correct those problems, you are taking one letter off each side of the string each time, it gets shorter and shorter - the next interesting thing that happens is you either get down to a single character or you run out of characters. You should be looking for that state.

Related

String exercise in Python which detects certain letters

I am trying to create a function in Python which allows me to know if a string contains a letter "y" which appears in the beginning of a word and before a consonant. For example, the sentence "The word yes is correct but the word yntelligent is incorrect" contains the "y" of the word "yncorrect", so the function has to return True. In addition, it has to return true if the "y" is in capital letters and verifies those same conditions.
I have done it in the following way and it appears as if the program works but I was asked to use the method for strings in Python find and I havent't been able to include it. Any hint about how to do it using the method find? Thank you very much.
def function(string):
resultado=False
consonants1="bcdfghjklmnñpqrstvwxyz"
consonants2="BCDFGHJKLMNÑPQRSTVWXYZ"
for i in range(0,len(string)):
if string[i]=="y" and string[i-1]==" " and string[i+1] in consonants1:
resultado=True
break
if string[i]=="Y" and string[i-1]==" " and string[i+1] in consonants2:
resultado=True
break
return resultado
print(function("The word yes is correct but the word yntelligent is incorrect"))
Basically it is better to use re
consonants1="BCDFGHJKLMNÑPQRSTVWXYZ"
for i in consonants1:
if (a:= string.upper().find(f' Y{i}')) != -1:
print(...)
break
I think the function you want isn't find, but finditer from the package 're' (find will only give you the first instance of y, while finditer will return all instances of y)
import re
import string
consonants = string.ascii_lowercase
vowels = ['a', 'e', 'i', 'o', 'u']
for vowel in vowels:
consonants.remove(vowel)
def func(string):
for x in re.finditer('y', string.lower()):
if string[x.start() + 1] in consonants:
return True
return False
The function find returns the index at which the string first begins or is found. So, it returns the first index, else -1. This won't work for your use cases, unless you make it a bit more complicated.
Method One: Check every combination with find.
You have to two results, one to check if its the first word, or if its in any other word. Then return True if they hit. Otherwise return false
def function(string):
consonants1="bcdfghjklmnñpqrstvwxyz"
string = string.lower()
for c in consonants1:
result1 = string.find(" y" + c)
result2 = string.find("y" + c)
if result1 != 1 or result2 == 0:
return True
return False
Method Two: loop through find results.
You can use .find but it will be counter-intuitive. You can use .find and loop through each new substring excluding the past "y/Y", and do a check each time you find one. I would also convert the string to .lower() (convert to lowercase) so that you don't have to worry about case sensitivity.
def function(string):
consonants1="bcdfghjklmnñpqrstvwxyz"
string = string.lower()
start_index = 0
while start_index < len(string):
temp_string = string[start_index+1:end] ## add the 1 so that you don't include the past y
found_index = temp_string.find("y")
if found_index == -1: return False
og_index = start_index + found_index
## check to see if theres a " yConsonants1" combo or its the first word without space
if (string[og_index - 1] == " " and string[og_index+1] in consonants1) or (string[og_index+1] in consonants1 and og_index == 0):
return True
else:
start_index = og_index
return False
Here's how I would go about solving it:
Look up what the find function does. I found this resource online which says that find will return the index of the first occurrence of value (what's passed into the function. If one doesn't exist, it returns -1.
Since we're looking for combinations of y and any consonant, I'd just change the arrays of your consonants to be a list of all the combinations that I'm looking for:
# Note that each one of the strings has a space in the beginning so that
# it always appears in the start of the word
incorrect_strings = [" yb", " yc", ...]
But this won't quite work because it doesn't take into account all the permutations of lowercase and uppercase letters. However, there is a handy trick for handling lowercase vs. uppercase (making the entire string lowercase).
string = string.lower()
Now we just have to see if any of the incorrect strings appear in the string:
string = string.lower()
incorrect_strings = [" yb", " yc", ...]
for incorrect_string in incorrect_strings:
if string.find(incorrect_string) >= 0:
# We can early return here since it contains at least one incorrect string
return True
return False
To be honest, since you're only returning a True/False value, I'm not too sure why you need to use the find function. Doing if incorrect_string in string: would work better in this case.
EDIT
#Barmar mentioned that this wouldn't correctly check for the first word in the string. One way to get around this is to remove the " " from all the incorrect_strings. And then have the if case check for both incorrrect_string and f" {incorrect_string}"
string = string.lower()
incorrect_strings = ["yb", "yc", ...]
for incorrect_string in incorrect_strings:
if string.find(incorrect_string) >= 0 or string.find(f" {incorrect_string}"):
# We can early return here since it contains at least one incorrect string
return True
return False

How do I alternate the cases of letters/words in a list?

I need to convert the "letter_guessed" input to lower case, if it's uppercase and if an uppercase letter already exists inside the list as a lower case it will return false but I can't get it to work.
I have tried using isupper(), upper ,islower(), lower() in many ways. I am pretty sure that I am doing something wrong with "if" but can't get it right.
def check_valid_input(letter_guessed, old_letters_guessed):
while True:
""" will work only if you enter one letter and do not contain special letters other then the abc
and if its all ready been entered it will show false """
if len(letter_guessed) == 1 and letter_guessed not in old_letters_guessed :
"""if the letter is one letter and not already inside old_letter_guessed only then continue """
old_letters_guessed.append(letter_guessed)
print("True")
letter_guessed = input(" : ")
else:
""" if its wrong input will print False Try again and if the input is correct it will go back to " if " """
#old_letters_guessed.append(letter_guessed)
print(False, 'Try again')
old_letters_guessed.sort()
print('->'.join(old_letters_guessed))
letter_guessed = input(" : ")
#if letter_guessed is letter_guessed.isupper()
new = input()
old = []
check_valid_input(new,old)
Everything sting has a method called swapcase which swaps between upper and lower case. So:
"TEST".swapcase()
Would become
"test"
I'd suggest using that instead of your if statements.
use a for loop to iterate over all elements in the list with the .swapcase() function common to all strings
list = ['some', 'words', 'in a list']
for word in list:
print(word.swapcase())

How do you find a substring of a string in python using no built-in function or slicing

I'm trying to work on a basic python program that is to find a substring of a string in python but the challenge was I can't use built functions or slicing.
MAINSTRING = raw_input('Enter a string : ')
print 'You entered %s' %MAINSTRING
isSubString = raw_input('Enter the substring : ')
print 'You entered %s' %isSubString
if isSubString in MAINSTRING:
print isSubString + " is a substring of " + MAINSTRING
It works but I can't use in syntax which is the frustrating part. I also know to use the slicing method in python but my challenge was to break it to the basics.
Sorry for being so vague, but I just got a hint.
The complete code consist of two 'for' loops, one for the string and one for the substring
To avoid anything other than for loops and a function you could do it like this although I have no idea why. Also you will have to use in which is pointed out in the comments. If a letter in the mainstring matches the first letter in the substring then add it to the temp string t, then go to the next letters in each and see if they match. If the temp string equals the substring then it exists and it will return.
def substring(ss, s):
x = 0
t = ""
for i in range(len(s)):
if s[i] == ss[x]:
t += ss[x]
if t == ss:
return s
x+=1
else:
x = 0
t = ""

How can I replace a substring in a string?

I am trying to write a program to change character if ch is found inside the string called st i will replace it with '!'
I wrote a program but for some reason this code can't replace one letter for example if i enter:
st = a
ch = a
I dont get an output of '!' instead i get 'a' but i dont want that i want it to be '!'
my code is
st = raw_input("String: ")
ch = raw_input("character: ")
def replace_char(st,ch):
if st.find(ch):
new = st.replace(ch,'!')
print new
return new
elif len(st)==len(ch):
if ch==st:
print"!"
else:
print st
else:
print st
return st
replace_char(st,ch)
Please help i dont get what i'm doing wrong or missing from my code
From the Python documentation:
find(s, sub[, start[, end]])¶
Return the lowest index in s where the substring sub is found such
that sub is wholly contained in s[start:end]. Return -1 on failure.
Defaults for start and end and interpretation of negative values is
the same as for slices.
It does not say anything about find() returning True or False. This is your problem.
For a substring search better use
if some_string in some_otherstring:
do_something()
st.find(ch) returns position where ch is in st not True/False. Because if == True is True in Python your program works in some cases... :)
Consider str == 'a' and ch == 'a', first condition fails, but second condition works only if str and ch has same length. I guess u have something else in your st or ch.
In my PC your program works except the case if searching ch is first in st, like following: st = 'afsdf' ch = 'a'.
Better solution is like follows:
st.replace(ch, '!')
It will work in all cases.

Palindrome in Python

fno = input()
myList = list(fno)
sum = 0
for i in range(len(fno)):
if myList[0:] == myList[:0]:
continue
print (myList)
I want to make a number palindrome.
eg:
input(123)
print(You are wrong)
input(12121)
print(you are right)
Please Guide me how to make a palindrome in python.Its not complete code please suggest me what the next step.
Thanks
I presume, given your code, you want to check for a palindrome, not make one.
There are a number of issues with your code, but in short, it can be reduced down to
word = input()
if word == "".join(reversed(word)):
print("Palidrome")
Let's talk about your code, which doesn't make much sense:
fno = input()
myList = list(fno) #fno will be a string, which is already a sequence, there is no need to make a list.
sum = 0 #This goes unused. What is it for?
for i in range(len(fno)): #You should never loop over a range of a length, just loop over the object itself.
if myList[0:] == myList[:0]: #This checks if the slice from beginning to the end is equal to the slice from the beginning to the beginning (nothing) - this will only be true for an empty string.
continue #And then it does nothing anyway. (I am presuming this was meant to be indented)
print (myList) #This will print the list of the characters from the string.
Slice notation is useful here:
>>> "malayalam"[::-1]
'malayalam'
>>> "hello"[::-1]
'olleh'
See Explain Python's slice notation for a good introduction.
str=input('Enter a String')
print('Original string is : ',str)
rev=str[::-1]
print('the reversed string is : ',rev)
if(str==rev):
print('its palindrome')
else:
print('its not palindrome')
x=raw_input("enter the string")
while True:
if x[0: ]==x[::-1]:
print 'string is palindrome'
break
else:
print 'string is not palindrome'
break

Categories

Resources