I am trying to check if a string that is passed in to a function is a palindrome of the second string that is passed in. Google defines a palindrome to be a word that is the same spelled forwards or backwards.
def palindrome(strA, strB):
if (strA == strB and strA[::1] == strB):
print "true"
else:
print "false"
if __name__ == '__main__':
palindrome("sirap", "paris")
In the code above, I am attempting to check if the given string is equal to the second string both forwards and backwards yet the test i give it in main returns false. Any ideas on what im missing?
You check if 'sirap' is the same as 'paris' as well as checking if reversed 'sirap' is the same as 'paris'. You just have too many things in your if:
if strA[::-1] == strB:
print "true"
else:
print "false"
What you had would work if you passed in a palindrome as well as its reverse, the same thing. For example, palindrome("stats", "stats") would print "true", but I don't think that's what you had in mind. You will also notice that I used strA[::-1] instead of strA[::1]. That is because strA[::1] starts at the beginning and goes to the end, but you want to go backwards, so you should use -1.
You could even do it in one line:
print ("false", "true")[str[::-1] == strB]
I did a similar test using the "100 projects" to learn python (useful for learning any language)
You could do something like this, and just run the script. For this I just made some changes to the original palindrome script I wrote.
print "This will check if its a palindrome"
inputstring = raw_input("String1: ")
inputstring2 = raw_input("String2: ")
inputstring = inputstring.lower()
inputstring2 = inputstring.lower()
revstring = inputstring[::-1] #Reverses the string
if revstring == inputstring2:
print "Yes: " + revstring
else:
print "No: " + revstring
Related
The use of parentheses for 'if' loop results in two different output for a palindrome program!
1.) () this gives the accurate result
2.) [] this only gives you the result of 'if' statement even if the "String" is not a palindrome
def isapalindrome(String):
if(String == String[::-1]):
return("is a palindrome!")
else:
return("is not a palindrome!")
String = input("Enter the String of your choice: ")
isapalindrome(String)
this code executes properly!
def isapalindrome(String):
if[String == String[::-1]]:
return("is a palindrome!")
else:
return("is not a palindrome!")
String = input("Enter the String of your choice: ")
isapalindrome(String)
this code executes only the 'if' statement!
() and [] are nothing alike.
() does what you expect it to, but wouldn't even be necessary since there is only one operator.
[] will create a list with a single element that equals the truth value of String == String[::-1], so either [True] or [False]. Independently of what the list contains, non-empty list in python are truthy. This means that your if condition will always evaluate to True
As other comments suggest, the correct structure of an if statement is:
if condition:
print("Do something")
else:
print("Do nothing")
Parenthesis are useful when using boolean expressions:
if (A==B) == C:
print("Do")
Point being, the brackets '[ ]' do not really belong there. As they are used to select a memory space within a given memory slot. Just like we would do with arrays.
I think is good that you are exploring different things, it is always good to know why things are the way they are.
Please help...
So the instruction says to program the computer to check whether a word is a palindrome or not. I inputted this code:
def is_palindrome(word):
counter_from_first_letter=0
counter_from_last_letter=-1
from_first_letter = word[counter_from_first_letter]
from_last_letter = word[counter_from_last_letter]
max_index_from_first= len(word)
max_index_from_last= (len(word))*-1
while from_first_letter == from_last_letter:
from_first_letter = word[counter_from_first_letter]
from_last_letter = word[counter_from_last_letter]
counter_from_first_letter += 1
counter_from_last_letter -= 1
return True
The problem is the computer only checks whether the first and last letters are the same, and if they are, it just returns true. How do I make sure the computer checks every single letter? Thanks
Maybe something like this:
def is_palindrome(word):
if word == word[::-1]:
return True
else:
return False
in python-3
name = 'madam'
print(name.find(name[::-1]) == 0)
Maybe you can try this: first convert your string into a list, then reverse the list and convert it back into a string. compare both the strings and if they match? they are palindromes, if not, they aren't.
'''checking whether a word is a palindrome
we first convert the word into a list then join it;
use an if statement to compare the two strings'''
def palindrome(string):#you need the input(string)
palindrome_check=[]#create an empty list
for character in string [::-1]:#create a list from the input
#(use a for loop because you now know the range)
#the [::-1] analyzes the characters in reverse
palindrome_check.append(character)#add each character to the new empty list
#print(palindrome_check)
rev_string= ''.join(palindrome_check)#.join -creates a string from the created list
print(rev_string)
#REMOVE SPECIAL CHARACTERS- IM THINKING OF A LOOPING THROUGH, BUT NOT SURE HOW TO IMPLEMENT IT
string=string.replace(' ', '')
rev_string=rev_string.replace(' ', '')
string=string.replace(',', '')
rev_string=rev_string.replace(',', '')
string=string.replace('.', '')
rev_string=rev_string.replace('.', '')
#THIS IS THE LOGIC: IT CHECKS BOTH STRINGS, if they are equal, it is a palindrome;
if string.lower()==rev_string.lower():
return True, print('It is a Palindrome')
else:
return False, print('It isnt a palindrome')
#call the function; key in the parameters-
palindrome= palindrome("No, Mel Gibson Is A Casinos Big Lemon")
#maybe we can try having a user key in the parameter? lets try
#palindrome=palindrome(input('kindly enter your word/phrase '))-wrong
#print('Kindly enter your word or phrase')
#user_palindrome=input('')
#palindrome=palindrome(user_palindrome)
#it wont work this way either
If you can have the user define the parameter(string), the better, if you know how to do this, kindly share.
To check whether a word or phrase is a palindrome, it be necessary to check if the original sentence is equal to the original sentence reversed.
word = "Eva can I see bees in a cave"
word_lower = word.lower().replace(" ", "")
if word_lower == word_lower[::-1]:
print("It's a palindrome")
else:
print("This is not a palindrome")
Here is a dictionary:
Vocab ={'Adherent' : " supporter; follower.",
'Incoherent' : "without logical or meaningful connection; disjointed; rambling",
'Inherent' : "existing in someone or something as a permanent and inseparable element, quality, or attribute"}
I've created a simple set of if statements in a loop:
while 1:
x = Vocab[random.choice(Vocab.keys())]
print x
t1=raw_input("What word matches this definition?: ")
if t1 in Vocab == True:
if Vocab[t1] == x:
print "That's correct!"
elif Vocab[t1] != x:
print "That's wrong!"
else:
print "That's not a word!"
raw_input("Hit 'enter': ")
For some strange reason, when the user inputs a key that is in the dictionary, the code outputs:
"That's not a word"
Why isn't the if statement with the '== True' working?
You don't need to use if t1 in Vocab == True, simply use if t1 in Vocab.
The problem is the operand precedence. The == has priority over in, so when you write if t1 in Vocab == True python interprets as if t1 in (Vocab == True).
To fix the precedence issue, you can write like this: if (t1 in Vocab) == True:, but again there is no need to compare if the result of t1 in Vocab is True, simple use this:
if t1 in Vocab:
You shouldn't need to use the "== True." Python should evaluate the if statement when you use this syntax without that.
A couple of things. First, if you're on Windows, there is the possibility that it might not be stripping the '\r' at the end of the input line, or you might have extra whitespace in general from your input. But also, you can simplify your code significantly, as so:
t1=raw_input("What word matches this definition?: ")
try:
if Vocab[t1.strip()] == x: # This should fix your 'not a word' problem
print "That's Correct"!
else:
print "That's Wrong!"!
except KeyError:
print "That's not a word!"
There's no need to test if a key is in a dictionary before using it. Simply try and use it and then catch the resulting KeyError.
edit
#MagnunLeno is also totally correct about the precedence problem, although simplifying your code as I have recommended makes it a moot point.
I have been learning python through code academy. It asked me to create a if else statement that prints the users input, but if there is no input print "empty". I did pass the tutorial but when there is a user input it prints both the users input and "empty".
here is my code:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len("original")
if length > 0:
print original
else: length < 0
print "empty"
Notice that print under else is not indented. I thought you had to indented it, but when i do it gives me an error.
You seem to have a couple issues with your code. First I believe you should change your assignment of length to:
length = len(original)
That way you get the correct length of the string you binded to the name original. If you use len("original"), you will pass the string "original" to the len() function, and it will just count the characters in that string. Regardless of what the user of your program inputted, your length will always be 8, since that's how many characters are in the string "original"
Also keep in mind that the len() function will never return a negative value. So testing if length < 0 doesn't make sense. You probably wanted to test if it equals 0. It seems as if you were trying to use an elif statement.
Try:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
elif length == 0:
print "empty"
elif statements let you test conditions just like if statements. elif is short for "else if".
Furthermore, as #chepner pointed out in the comments, there is no need to even test the second condition at all. You can just as easily go with:
else:
print "empty"
The else syntax is not followed by any condition. It automatically enters the indented block of code if the other conditions evaluate to False.
Was the length < 0 intended to be a comment? You need the comment character #.
else: # length < 0
print "empty"
It's wrong anyway, it should be length <= 0.
Without a comment character it was being interpreted as the statement to use as the else clause. It didn't create an error since length < 0 just generates a boolean result that you didn't do anything with, but it prevented you from having another statement as part of the else.
else: length < 0
print "empty"
should be
elif length == 0:
print "empty"
Python has significant whitespace, things that are indented the same are in the same scope.
First off, it is not len("original") it is len(original). If you use quotes you are making it a constant value, "original", rather than a variable named original.
Second, instead of checking the length of the string you should use this
if original:
# Type here what happens if the string is not empty
else:
# Here what happens if the string is empty
By Python standard any collection, including strings, equals false if it is empty(aka contains no elements) and true if it contains any elements.
There is a a statement after else.
else: length < 0
print "empty"
Maybe you are looking for an (elif is another way to check another condition after the if if the previous if fails.)
elif length <= 0:
or just a plain
else:
print "empty"
it will never go past zero anyways you could have a == conditional for zero and it would work.
elif length == 0:
this is probably the best way there is no need to check another condition.
if length > 0:
print original
else:
print "empty"
also just a side note length = len("original")
there is not suppose to be quotation marks around original because its a variable :). You will just be getting the string "original" not the actual stuff inside of the variable.
The end result ..
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
else:
print "empty"
To check if there is an item in a list, simply do this:
if List_name:
{code here}
...
So, your code should very simply look like this:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
if original:
print original
else:
print "Empty"
It's that easy :D
Hello guys with the code below, after inputting a number and then a char, it returns None. I've got no clue about this one. Any help is welcome.
I've tried printing the values but it changes just on returning!
import string
def get_input_char(char):
char = str.lower(input("Input a letter: "))
if not char in string.ascii_letters or char == "" or char == None:
print("Character " + char + " not valid. Try again.\n")
char = str(get_input_char(char))
else:
return char
print (char)
word_frag = ""
while True:
word_frag += get_input_char("")
print("\nThe current word fragment is " + word_frag)
If your function falls through to the end, after the print statement, it doesn't return anything. The default value returned from a function is None.
As Mark pointed out, the problem is that no value is returned if the first entered value is not valid. There are also a few other things not quite right in your code:
You're using recursion to test for valid values when a loop would be better. This is mainly because of the large overheads involved in calling a function compared to a loop. If you use a loop, you don't need to give the function an argument.
It is better practice to check char is None instead of char == None. Checking for equality may give unexpected results if the object you're testing has been customised to compare equal to None. Checking identity (using is) is much more robust.
However, it is not necessary to check for None at all, since char will always be a string.
Your code implies that only one character is expected, but actually any string contained in ascii_letters would be accepted, e.g. "efgh".
I'd suggest rewriting the function something like this:
def get_input_char():
while True:
char = str.lower(input("Input a letter: "))
if len(char) == 1 and char in string.ascii_letters:
break
else:
print("Character '%s' not valid. Try again.\n" % char)
return char