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
Related
I know it can be simply done through string slicing but i want to know where is my logic or code is going wrong. Please Help!
S=input()
string=""
string2=""
list1=[]
list1[:0]=S
for i in list1:
if(i%2==0):
string=string+list1[i]
else:
string2=string2+list1[i]
print(string," ",string2)
Here's my code. Firstly i stored each character of string in the list and went by accessing the odd even index of the list.
But i'm getting this error
if(i%2==0):
TypeError: not all arguments converted during string formatting
You are iterating over characters, not indices, so your modulo is incorrect, equivalent to:
i = "a"
"a" % 2 == 0
You want to use enumerate
for idx, letter in enumerate(list1):
if(idx%2 == 0)
string += letter
You don't need to use an intermediate list: just iterate over the input string directly. You also need to use for i in range(len(original)) rather than for i in original, because you need to keep track of whether a given character is at an odd or an even index. (I've gone ahead and renamed some of the variables for readability.)
S = input()
even_index_characters = ""
odd_index_characters = ""
for i in range(len(S)):
if i % 2 == 0:
even_index_characters += S[i]
else:
odd_index_characters += S[i]
print(f"{even_index_characters} {odd_index_characters}")
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())
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 = ""
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.
My question can be understood below:
goodvalue=False
while (goodvalue==False):
try:
word=str(input("Please enter a word: "))
except ValueError:
print ("Wrong Input...")
else:
goodvalue=True
word=word.lower()
List=list(map(str,word))
lenList=len(list(map(str,word)))
listofans=[]
x=0
while (lenList-1==x):
if List[x]==str("a"):
listofans[x]=str("1")
x=x+1
elif List[x]==str("b"):
listofans[x]=str("2")
x=x+1
elif List[x]==str("c"):
listofans[x]=str("3")
x=x+1
It continues like that for all alphabets for a while... And then:
sumofnums=listofans[0]
y=1
while (lenList-2==y):
sumofnums+=listofans[y]
print ("The number is: ", sumofnums)
So basically, if I give hello, it should return 8 5 12 12 15. Any help is truly appreciated!
Your code is very messy, and some of it isn't even needed (all those uses of map is not needed. Nor is the try/except structure)
Why not simplify it a bit ;).
>>> import string
>>> d = {j:i for i, j in enumerate(string.lowercase, 1)}
>>> for i in 'hello':
... print d[i],
...
8 5 12 12 15
Some problems with your code:
Don't compare booleans like that. Just do while goodvalue.
List=list(map(str,word)) is excessive. A simple List = list(word) is needed, but you probably won't even need this as you can iterate through strings (as I have shown above)
str("a") is pointless. "a" is already a string, thus str() does nothing here.
As I said before, the try/except is not needed. No input could cause a ValueError. (unless you meant int())
Are looking for something like this?
[ord(letter)-ord('a')+1 for letter in word]
For "hello" this outputs:
[8, 5, 12, 12, 15]
The ord function returns the ascii ordinal value for the letter. Subtracting ord('a') rebases that to 0, but you have 'a' mapping to 1, so it has to be adjusted by 1.
Try this:
goodvalue=False
while (goodvalue==False):
try:
word=str(input("Please enter a word: "))
except ValueError:
print ("Wrong Input...")
else:
goodvalue=True
word=word.lower()
wordtofans=[]
for c in word:
if c >= 'a' and c <= 'z':
wordtofans.append( int(ord(c)-ord('a')+1) )
print wordtofans
You can directly iterate a string in a for loop, you don't have to convert your string to a list.
You have a control check here to ensure that only letters a..z and A..Z are converted into numbers.
Conversion from a string letter to a number is done using int(ord(c)-ord('a')+1) which uses ord function that will return a ASCII value for a supplied character.
First of all just for make your code smaller you have to look on a small stuff like, instead of print =="a" you print ==str("a"). That's wrong.
So here is your old while loop:
while (lenList-1==x):
if List[x]==str("a"):
listofans[x]=str("1")
x=x+1
elif List[x]==str("b"):
listofans[x]=str("2")
x=x+1
elif List[x]==str("c"):
listofans[x]=str("3")
x=x+1
And here is new:
while (lenList-1==x):
if List[x]=="a":
listofans[x]="1"
x=x+1
elif List[x]=="b":
listofans[x]="2"
x=x+1
elif List[x]=="c":
listofans[x]="3"
x=x+1
And about your question, here is a solution:
[ord(string)-ord('a')+1 for string in word]
If you print "hello" this will returns you:
[8, 5, 12, 12, 15]