For some reason it works great but on some sentences that are palindrome it says they are not
palindrome = input("Enter a word: ")
palindrome = palindrome.lower()
palindrome.replace(" ", "")
if palindrome == palindrome[::-1]:
print("OK")
else:
print("NOT")
An example:"Mr Owl ate my metal worm"
but on other sentences it works good and i don't understand whats different
please help me btw the level of the code needs to be at this level
instead of using replace whitespace ( if they are not require much ) then, you can convert the word to list of words sperated on whitespace and then create a new word joining all word inside the list and reverse it to check if the sentence is palindrome or not
here is code
palindrome = input("enter the word ")
palindrome = ''.join(palindrome.split()).lower()
if palindrome == palindrome[::-1]:
print("OK")
else:
print("NOT")
without using join
palindrome = input("enter the word ")
new_palin = ''
for chars in palindrome:
if chars != ' ' :
new_palin+=chars
new_palin = new_palin.lower()
if new_palin == new_palin[::-1]:
print("OK")
else:
print("NOT")
Related
So I am stuck with the part of checking if the letter is present in the word or not. The game needs to let a person guess a letter in the word, and tell if this letter is present in word or not(5 attempts only)
import random
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
inp = input("What's your guess for a letter in the word?\n")
for j in range(0,len(word)):
if inp == word[j]:
print("Yes, we have this letter.")
else:
print("No, we don't have this letter.")
i=i+1
The expected output would be one sentence, either confirming that the letter is present in word, or disproving. However, the actual output is that is prints one sentence per each of letters in the given word, like this:
What's your guess for a letter in the word?
p
Yes, we have this letter.
No, we don't have this letter.
Instead of checking against each letter of the word (and thereby printing it each time), just check whether the letter is in the word:
while i<5:
inp = input("What's your guess for a letter in the word?\n")
if inp in word:
print("Yes, we have this letter.")
You can try regular expression:
import random
import re
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
inp = input("What's your guess for a letter in the word?\n")
res = re.findall(inp, word)
length = len(res)
if length == 0:
print("Your guess is wrong :( ")
else:
print(f"You guess is right :) ")
i +=1
here the output of regular expression is a list so you can do whatever you want with it, e.g. hangman game or ...
I have been looking around to see if I could find something that could help, but nowhere has an answer for what I'm looking for. I have a Hangman game I'm doing for a final project in one of my classes, and all I need is to make it so if a word has a capital letter, you can input a lowercase letter for it. This is the code.
import random
import urllib.request
wp = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-
type=text/plain"
response = urllib.request.urlopen(wp)
long_txt = response.read().decode()
words = long_txt.splitlines()
###########
# Methods #
###########
def Run():
dashes1 = "-" * len(word)
dashes2 = "-" * len(word2)
used_letter = []
dashes = dashes1 + " " + dashes2
#dashes ="-" * len(secretWord)
guessesLeft = 6
while guessesLeft > -1 and not dashes == secretWord:
print(used_letter)
print(dashes)
print (str(guessesLeft))
guess = input("Guess:")
used_letter.append(guess)
if len(guess) != 1:
print ("Your guess must have exactly one character!")
elif guess in secretWord:
print ("That letter is in the secret word!")
dashes = updateDashes(secretWord, dashes, guess)
else:
print ("That letter is not in the secret word!")
guessesLeft -= 1
if guessesLeft < 0:
print ("You lose. The word was: " + str(secretWord))
print(dashes)
else:
print ("Congrats! You win! The word was: " + str(secretWord))
print(dashes)
def updateDashes(secret, cur_dash, rec_guess):
result = ""
for i in range(len(secret)):
if secret[i] == rec_guess:
result = result + rec_guess
else:
result = result + cur_dash[i]
return result
########
# Main #
########
word = random.choice(words)
word2 = random.choice(words)
#print(word)
#print(word2)
secretWord = word + " " + word2 # can comment out the + word2 to do one
word or add more above to create and combine more words will have to adjust
abouve in Run()
splitw = ([secretWord[i:i+1] for i in range(0, len(secretWord), 1)])
print (splitw)
Run()
any bit of help is appreciated. The website I'm using has a bunch of words that are being used for the words randomly generated. Some are capitalized, and I need to figure out how to let the input of a letter, say a capital A, accept a lowercase a and count for it.
you could compare after you converted everything to lowercase.
e.g. you could do
secretWord = word.lower() + " " + word2.lower() # that should make your secret all lowercase
for the input you should do the same:
guess = input("Guess:").lower()
after that it should not matter if it is upper or lower case. it should always match if the letter is the correct one.
hope that helps
Simply check everything in lowercase:
[...]
elif guess.lower() in secretWord.lower():
[...]
and so on.
I would just change this line:
while guessesLeft > -1 and not dashes == secretWord:
to:
while guessesLeft > -1 and not dashes.lower() == secretWord.lower():
This way you are always comparing lower-case representations of the user's input to the lower-case representation of your secretWord. Since this is the main loop for your game, you want to break out of this as soon as the user's guess matches your word regardless of case. Then later in your code, you will still check whether they had any guesses left, and print out their answer and the secret word as before.
No other changes required, I think.
You could just force all comparisons to be made in the same Case, such as lowercase.
Let’s say that your word is "Bacon". and someone enters "o".
That will be a match because quite obviously “o” equals “o” so you can cross that letter off the list of letters left to guess.
But in the case that someone enters “b” then b is NOT equal to “B”.
So why not just force all letters to be compared using the same case?
So your comparison will be like
elif guess.Lower() in secretWord.Lower()
My python is rusty as hell, but the idea here should do what you want to do
For an assignment, I need code that asks the user for a word and a letter. Then, it edits the word to not include the specific letter. It needs in include a "for i in range" statement. The code before works but doesn't use a for loop and uses a python command.
word1 = raw_input ("Give me a word! ")
letter1 = raw_input ("Give me a letter! ")
modify = word1.replace(letter1,"")
check = word1.find(letter1)
if check == -1:
print "There is no letters to replace in", word1
check = 0
if check >= 1:
print modify
How about:
word = raw_input('Give me a word! ')
letter = raw_input('Give me a letter! ')
cleaned = ''
for i in range(len(word)):
if word[i] != letter:
cleaned += word[i]
if cleaned:
print cleaned
else:
print 'There is no letters to replace in', word
You can iterate through a string letter by letter like you would a list or dict
word='someword'
for letter in word:
print(letter)
Problem 1.
This problem provides practice using a while True loop. Write a function named
twoWords that gets and returns two words from a user. The first word is of a
specified length, and the second word begins with a specified letter.
The function twoWords takes two parameters:
an integer, length, that is the length of the first word and
a character, firstLetter, that is the first letter of the second word.
The second word may begin with either an upper or lower case instance of
firstLetter. The function twoWords should return the two words in a list. Use
a while True loop and a break statement in the implementation of twoWords. The
following is an example of the execution of twoWords:
print(twoWords(4, 'B')):
A 4-letter word please two
A 4-letter word please one
A 4-letter word please four
A word beginning with B please apple
A word beginning with B please pear
A word beginning with B please banana
['four', 'banana']
This is what I have so far, but it keeps asking me the first question over again
even if I have the right word length. What am I doing wrong?
def twoWords(length, firstLetter):
wordLen = input('A 4-letter word please ')
while len(wordLen) != int(length):
wordlen = input('A 4-letter word please ')
word = input('A word beginning with ' + firstLetter + ' please ')
while word[0] != firstLetter:
word = input('A word beginning with ' + firstLetter + ' please ')
return[wordLen, word]
def twoWords(length,firstLetter):
firstWord = ""
secondWord= ""
while True:
firstWord = input('A ' + str(length) + '-letter word please.')
if length == len(firstWord):
break
while True:
secondWord = input('A word beginning with ' + firstLetter+ ' please')
if secondWord[0] == firstLetter.upper() or secondWord[0] == firstLetter.lower():
break
return [firstWord,secondWord]
print(twoWords(4,'B'))
def twoWord(length, firstLetter):
while True:
word1=(input("Enter a "+ str(length)+"-letter word please:"))
if len(word1)==int(length):
break
while True:
word2=input("Please enter the word beginning with "+firstLetter+" please:")
if word2[0].upper()==firstLetter or word2[0].lower()==firstLetter:
break
return word1, word2
print(twoWord(5, 'b'))
I'm trying to write a function that will tell me if the inputted word or phrase is a palindrome. So far my code works but only for single words. How would I make it so that if I enter something with a space in it like 'race car' or 'live not on evil' the function will return true? Other questions on this page explain how to do it with one words but not with multiple words and spaces. Here what I have so far...
def isPalindrome(inString):
if inString[::-1] == inString:
return True
else:
return False
print 'Enter a word or phrase and this program will determine if it is a palindrome or not.'
inString = raw_input()
print isPalindrome(inString)
You could add the characters of the string to a list if the character is not a space. Here is the code:
def isPalindrome(inString):
if inString[::-1] == inString:
return True
else:
return False
print 'Enter a word or phrase and this program will determine if it is a palindrome or not.'
inString = raw_input()
inList = [x.lower() for x in inString if x != " "] #if the character in inString is not a space add it to inList, this also make the letters all lower case to accept multiple case strings.
print isPalindrome(inList)
Output of the famous palindrome "A man a plan a canal panama" is True. Hope this helps!
You just need to split it by the spaces and join again:
def isPalindrome(inString):
inString = "".join(inString.split())
return inString[::-1] == inString
Slightly different approach. Just remove spaces:
def isPalindrome(inString):
inString = inString.replace(" ", "")
return inString == inString[::-1]