I am writing a function to check if a word is a palindrome
def palidrome(b):
word = ''.join(reversed(b))
if b == word:
return True
return False
def main():
so = input("Please enter a matching word")
come = palidrome(so)
print(come)
main()
Whatever I put, e.g., 'mom,' 'dad' or 'racecar,' it always outputs False but it should be True.
def checkPalindrome(word):
wordCopy = word[::-1]
if word == wordCopy:
return True
else:
return False
def main():
s = 'oro'
print(checkPalindrome(s))
main()
According to this demo, your code is running fine - however, I noticed your input statement doesn't have a space after it. Are you typing a space before you put your word in? If so, consider the strip() function, which will remove leading and trailing spaces - or just add a space to your input prompt!
Related
I am facing difficulty while writing a code for testing for a pangram (a string that contains all 26 alphabets at least once).
When executed based on first part as follows:
def ispangram(x):
alphabet="abcdefghijklmnopqrstuvwxyz"
for i in alphabet:
if i in x.lower():
return True
The code works fine.
But if I add the else condition:
def ispangram(x):
alphabet="abcdefghijklmnopqrstuvwxyz"
for i in alphabet:
if i in x.lower():
return True
else i not in x.lower():
return False
The code returns every input as a valid pangram.
Could someone please help me understand what is going wrong here?
You aren't checking every letter in the alphabet. You are only checking if the word contains the letter a. Let's examine the control flow
def is_pangram(x):
x = x.lower()
alphabet="abcdefghijklmnopqrstuvwxyz"
# we begin iteration here
for i in alphabet:
# we check if the letter is in the word
if i in x:
# we return! This will stop execution at the first True
# which isn't always the case
return True
else:
# we return again! since we've covered all cases, you will
# only be checking for a
return False
To fix this, you can do one of two things. Using a loop, you can just check if letters are not in x, returning False if they are not, and returning True at the end:
def is_pangram(x):
x = x.lower()
alphabet="abcdefghijklmnopqrstuvwxyz"
for i in alphabet:
if i not in x:
return False
# this means we made it through the loop with no breaks
return True
Alternatively, you can use the all operator to check if all of the letters in the alphabet are in the word, which returns True, otherwise it returns False
def is_pangram(x):
x = x.lower()
alphabet="abcdefghijklmnopqrstuvwxyz"
return all(i in x for i in alphabet)
Your first function will return true for any string that contains any letter. You need to verify that each letter is in your input string:
import string
def ispangram(x):
x = x.lower()
for c in string.ascii_lowercase:
if c not in x:
# a letter is not in the input string, so the input string is not a pangram
return False
# if we got here, each letter is in the input string
return True
Hello guys I hope you will help me with a small problem that I did not figured out yet.
Here is the description of the homework to have an idea first about what I am working on.
" In this part of the homework, you will write a program that inputs two different
characters in the form of "c1-c2", where c1
is the first character and c2
is the second
character. You need to check the validity of this input. That is, the input should
start with a letter, followed by a dash (-), and it should end with another letter case
insensitively (it means that "a" and "A" are the same characters). Please note that
the characters to be obtained from the user must be different from each other. In
case that the user enters an invalid input, your program should continuously
prompt for the required value until (s)he enters a valid one."
Here is some sample runs:
Please enter two different characters in the form c1-c2: a-A
Invalid input!
Please enter two different characters in the form c1-c2: a-B
(The program should stop if it is correct.)
Here is what I tried so far:
ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def process(Z):
if Z[0] in ascii_letters:
return True
if Z[1] == '-':
return True
if Z[2] in ascii_letters:
return True
if Z[0] != Z[2]:
return True
if Z[0] != Z[2].upper():
return True
if Z[0] != Z[2].lower():
return True
X = False
while X == False:
ask = input("Please enter two different characters in the form c1-c2: ")
if process(ask) == False :
print("Invalid input!")
else:
break
Here your process almost always terminate at the first check:
def process(Z):
if Z[0] in ascii_letters:
return True
You need to nest your condition, and 'return' only when all the conditions are filled, a fast example:
def process(Z):
if Z[0] in ascii_letters:
if Z[1] == '-':
if Z[2] in ascii_letters:
return True
return False
Note you will want to check for that Z is the right size before accessing Z[2]. And you need as well to add the check about same-letter. So a solution for your problem would be:
def process(Z):
if len(Z) == 3
and Z[0] in ascii_letters
and Z[1] == '-'
and Z[2] in ascii_letters
and Z[0].upper() != Z[2].upper():
return True
return False
Strings have methods you can use to validate the input. Use them! You can split on '-' and verify you have 2 characters of length 1, check whether they are alphabetic and compare the upper case version of each.
def process(Z):
parts = Z.split("-")
return (len(parts)==2 and len(parts[0])==1 and len(parts[1])==1
and parts[0].isalpha()
and parts[0].upper() == parts[1].upper())
isalpha works for all unicode characters so you don't have to worry whether the user entered text in some strange language.
The inbuilt function -isalpha() will be helpful for your homework.
while True:
ask=input('Please enter two different characters in the form c1-c2: ')
if len(ask)!=3:
continue
if ask[1] == '-' and ask[0].isalpha() and ask[2].isalpha() and ask[0]!=ask[2]:
break
The isalpha() function returns True if the given string has all alphabets.
The correct way to handle this is with regular expressions. Their is a regex library as part of the standard python library.
import re
u_input = 'your string'
def validate(input):
# chars must be different
if input[0] == input[-1:]:
return False
# begin and end with upper or lower a-z with dash in middle
pattern = '[a-zA-Z]{1}-[a-zA-Z]{1}'
result = re.match(pattern, input)
# re.match returns None if no match
if not result:
return False:
else:
return True
I tried to make it as similar to your code as possible and it's quite simple to understand. I think I considered all required conditions. If not, tell me.
from string import ascii_letters
def validity_check(input_chars):
try:
# if cant be splitted raises Exception which results in restart
char_1, char_2 = input_chars.split("-")
# if characters not in alphabet restarts
chars_in_alphabet = char_1 in ascii_letters and char_2 in ascii_letters
if not chars_in_alphabet:
return False
# if characters are the same letter restarts
same_latter = char_1.lower() == char_2.lower()
if same_latter:
return False
# I'm not sure if you want to check if the first letter
# is small and the second one is capital
# if so add this block
# chars_letter_size = char_1 in ascii_letters.lower() and char_2 in ascii_letters.upper()
# if not chars_letter_size:
# return False
return True
except:
return False
while True:
ask = input("Please enter two different characters in the form c1-c2: ")
if validity_check(ask):
break
#Function takes a character and a string and returns a boolean reflecting if
#the character is found in the string.
def isItThereS(letter, word):
letInWord = 0
for l in word:
if l == letter:
letInWord += 1
return letInWord == True
When I put it in the operator like
isItThereS("h","hello world")
True
but when I go to find a character that repeats like "l" or "o" it returns false.
isItThereS("l","hello world")
False
How would I go about getting that to not return false, but instead return True since the character is technically in the string?
you can simply use the in operator
def isItThereS(letter, word):
return letter in word
If you really want to use a custom function for that, change your return to return letInWord >= 1. As everything but 1 == True will evaluate to False. (So a more appropriate name for the function as is would be is_it_there_only_once).
Otherwise please use the solution provided by armak.
So I am trying to create a function that calls two functions within the function where one function called "encode" checks if the first letter of a word is a vowel and if yes it will add "way" to the end of the word and if the word starts with a consonant it will move the first letter to the third position in the word and adds gar.
my problem is creating that function that calls from the encode function to read a sentence and change each word accordingly based on the first letter.
So here are some text cases for the function:
encode() function:
The output will look like this:
Please enter your message: python is fun
The secret message is: ythonpar isway unfar
translation is correct when words are separated by more than one space character.
Please enter your message: simple is better than complex
The secret message is: implesar isway etterbar hantar omplexcar
Here is my script. They are suppose to be connected.
def get_input():
user_input = input('Please enter a message: ')
more_message = True
while more_message:
user_input = input('Please enter a message: ')
if not user_input==' ':
more_grades = False
return
def starts_with_vowel(word):
while True:
data = word
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
print ('true')
else:
print ('false')
return
def encode(word):
while True:
data = starts_with_vowel(word)
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
new_word=word+'way'
print ('The secret word is:',new_word)
else:
new_word2=word+'ar'
scrambled_word=new_word2[1:-2]+new_word2[0]+new_word2[3]+new_word2[4]
print (scrambled_word)
print ('The secret word is:',new_word2)
return
def translate(text):
secret_message= encode(text)
return (secret_message)
translate('gin is a boy')
A better approach would be to use split on the sentence (input) and loop over the words:
vowels = 'aeiou'
sentence = 'python is fun'
new_words = []
for word in sentence.split():
if word[0].lower() in vowels:
new_words.append(word+'way')
else:
new_words.append(word[1:3]+word[0]+word[3:]+'gar')
' '.join(new_words)
'ytphongar isway unfgar'
I think in the first part of the code you will need to change the more_grades section with more_message, because first off more_grades has not been initialized and more_messages is controlling your loop so i think that's what you meant to do. Don't worry I believe that's only one error I have caught I will check the rest of the code and get back to you. Don't stress it.Happy coding :-)
Right now, what I have is a code that I can test a single word whether it is a Palindrome or not. I have to input the word, and it will tell me whether it is a Palindrome (True) or if it is not (False)
I need to create one that Asks for a single word, then provides a True of False based on the word that is typed. This is what i have so far.
I really have no idea how to do this, any help would be greatly appreciated.
def isPalindrome(s):
if len(s) <= 1:
return True
else:
if s[0] != s[len(s)-1]:
return False
else:
return isPalindrome(s[1:len(s)-1])
print(isPalindrome("poop"))
Simply create a reversed string and check if both are equal.
def isPalindrome(s):
return s == s[::-1]
print(isPalindrome('poop'))
Also using a reversed string, but can be used in-line, as well (i.e., doesn't require a function).
def is_palindrome(word):
return word == ''.join(reversed(word))
print is_palindrome('hello') #False
print is_palindrome('racecar') #True
If you are asking how to get Python to take user input, then there are a couple options available to you. One option is to make your script run from the command line and use a command line argument and the other is to use the raw_input function. Both are implemented in the following code.
import sys
def isPalindrome(word):
...
if __name__ == '__main__':
if len(sys.argv) > 1:
inp = sys.argv[1]
else:
inp = raw_input("Type a word: ") # Which you might want to strip for white space
if isPalindrome(inp):
print inp,"is a palindrome"
else:
print inp,"is not a palindrome"
Several other people have suggested alternative implementations for isPalindrome that are probably better, but if you are doing this as an assignment and are supposed to use recursion, then keep using yours. Also, the raw_input function can be called anywhere that is convenient in your script and doesn't have to be used when called from the command line.
You might try this function:
def is_palindrome(text):
return text[:len(text)//2] == text[:(len(text)-1)//2:-1]
Here is example usage for reference:
>>> is_palindrome('')
True
>>> is_palindrome('a')
True
>>> is_palindrome('b')
True
>>> is_palindrome('aa')
True
>>> is_palindrome('ab')
False
>>> is_palindrome('ba')
False
>>> is_palindrome('bb')
True
>>> is_palindrome('aaa')
True
>>> is_palindrome('aab')
False
>>> is_palindrome('aba')
True
here is mine:
def isPalindrome(word):
word=str(word)
a=word[::-1]
if a!=word:
return False
elif word=='':
return False
else: return True
Using string subscripting
def is_palindrome(string):
return all(char == string[-i - 1] for i, char in enumerate(string))
Using list reversing
def is_palindrome(string):
to_list = list(string)
# reverse to_list now
to_list.reverse()
# our reversed list should be equal string as a list
# if string is a palindrome
return to_list == list(string)
This is mine:
def palindrome_checker(word):
return True if len(word) < 2 else (word[0] == word[-1]) and palindrome_checker(word[1:-1])
This should work.
return (s[:1+len(s)//2]==s[len(s)//2:][::-1])
For the people doing the palindrome test from testdome.com that takes into account casing, here is my solution:
def is_palindrome(word):
wordoriginal = []
wordreversed = []
for i in reversed(word):
i = i.lower()
wordreversed.append(i)
for i in word:
i = i.lower()
wordoriginal.append(i)
return wordoriginal == wordreversed
This is what I came up with, hope it works for you:
def palindrome_(word):
word = input("enter your word Here ")
return word == word[::-1]
print palindrome_("word")