This question already has answers here:
Understanding slicing
(38 answers)
Closed 3 years ago.
What does this kind of indexing refer to in case of recursion.
def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
print("String is a palindrome!")
else:
print("String isn't a palindrome!")
If you look in the documentation, this expression is called slicing : Python: Slicing
You can add three arguments in this syntax.
The first is the start of the sequence, the second is the end (not included) and the third is the step.
When you put a negativ arguments it means that you count from the end of your array.
So for :
s = "Hello World"
s = s[1:-1]
You would have :
s = "ello Worl"
For your case it is recursive to go step by step to the center of the string and each time you check if the string is still a palindrome. When you have only one character or less it returns True because everything before was OK to say that your string is a palindrome
Related
This question already has answers here:
What is a None value?
(9 answers)
Closed 28 days ago.
I am attempting a practice question on Coursera where the code seems to be throwing me off even though the logic seems fine to me. I am a beginner trying to get my hand on the language but I am running into logical errors.
def is_positive(number):
if number > 0:
return "True"
else:
return "None"
number=-1
print(is_positive(number))
From your comment, I assume that you want to return the values True and None, rather than the strings "True", and "None". To do this, simply remove the quotation marks surrounding the string.
def is_positive(number):
if number > 0:
return True
else:
return None
number=-1
print(is_positive(number))
n = int(input())
print( True if n > 0 else False)
I think this is what you're looking for
This question already has an answer here:
Identifying straight, flush and other categories (from Poker) using Python
(1 answer)
Closed 3 years ago.
If there is a string = '99888' it should print 'True'. How can you check pairs and threes of a character in a string
I tried using the count function but it only identifies a pair
string = '99888'
for c in '123456789':
if string.count(c) == 2 and string.count(c) == 3 :
print('True')
Edit:
The string is a always 5 character string and if there is a pair and three of a kind it prints True
For example '89899' and '75757' print True. '98726' prints False
Use the Counter class from the collections module
from collections import Counter
def check(inputString):
x = Counter(inputString)
list_of_counts = [x[i] for i in x.elements()]
if (2 in list_of_counts) and (3 in list_of_counts):
return(True)
else:
return(False)
print(check("99888"))
print(check("999888"))
This question already has answers here:
How to check for palindrome using Python logic
(35 answers)
Closed 7 years ago.
very new to programming and I am trying to solve a few Project Euler problems. I would like to know for a python code which identifies palindrome and non-palindrome. What is the most efficient way to do this? could you please show the code you find most efficient for this problem.
You can do this very simply by just checking if the string that you input is equal to itself reversed (that's what a palindrome is).
def check_palindrome(s):
return s == s[::-1]
[::-1] reverses the string because the -1 tells how many steps to go by and negative will go through the string in reverse.
If you will need to check if integers are palindromes, you can do:
def check_palindrome(s):
return str(s) == str(s)[::-1]
I'm a big fan of simplicity over (potentially false) optimizations. Start with something straight forward, and move on from there:
def is_palindrom(s):
length = len(s)
for i in range(length / 2):
if s[i] != s[length - i - 1]:
return False
return True
This question already has answers here:
is_alpha coding that works like isalpha() in python
(4 answers)
Closed 9 years ago.
ASCII_LOWERCASE='abcdefghijklmnopqrstuvwxyz'
ASCII_UPPERCASE='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ASCII_ALL=ASCII_LOWERCASE+ASCII_UPPERCASE
def is_alpha(x):
for ch in x:
if ch not in ASCII_ALL:
return False
return True
This was my original code and it is still not returning False in cases like "". When the real isalpha() returns False in the case of '' or "". How to exclude all these cases?
Your loop
for ch in x:
Will never run if len(x) == 0, you go straight to
return True
Also, if you
import string
You can use string.ascii_uppercase and string.ascii_lowercase.
Empty strings will not trigger any code in the for loop, since for ch in '' is essentially a no-op here (there's nothing to iterate), so your is_alpha returns True for empty strings. You should add something like
if not x:
return False
to the beginning of your function.
(As a side note, your break statement is unnecessary since return False will exit the function.
First off, this IS homework, so I am not expecting any direct answers. I need to take two strings defined by a function (semordnilap(str1, str2)) and I need to see if they are equal when one is reversed. I was wondering if I can call these separately out of the function with semordnilap(str1[0:1) == semordnilap(str2[-1]) I tried this a few ways and I must not be thinking about it correctly, plus of course there is the kicker of trying to do this recursively. Any advise or direction would be helpful.
def semordnilap(str1, str2):
'''
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap
False otherwise.
'''
if len(str1) != len(str2):
return False
if len(str1) <= 1 or len(str2) <= 1:
return False
if semordnilap(str1[0]) != semordnilap(str2[-1]):
return False
else:
return True
This is what I have so far, getting error of TypeError: semordnilap() takes exactly 2 arguments (1 given)
Given two strings str1 and str2, the easiest way to compare if one is equal to the reverse of the other is by using slicing:
str1 = 'racecar'
str2 = 'racecar'
str1 == str2[::-1]
Out[57]: True
Which is really just checking if str1 is a palindrome (i.e. a reverse of itself).
If you really want to use recursion, you also want to be using slicing: check if str1[0] == str2[-1], and then recursively call your function on str1[1:] and str2[:-1].
The [::-1] syntax is extended slicing syntax, which is valid for strings as well as lists and other sequences.
To reverse a string you use 'this is a string'[::-1].
[::-1] Is slice notation which says include everything from the start to the end of the string but do it in reverse.
'abcdefghijk'[6:1:-2] outputs 'gec' because it goes from the 6th index (starting with 0) up to but not including the first index, in reverse steps of 2.
Read up more on slice notation:Explain Python's slice notation, http://docs.python.org/2.3/whatsnew/section-slices.html
def semordnilap(str1, str2):
if str1 == str2[::-1]: return True
else: return False
One way to do it recursively:
def semordnilap(str1, str2):
if not (len(str1) or len(str2)): return True
if not (len(str1) and len(str2)): return False
if str1[0] != str2[-1]: return False
return semordnilap(str1[1:], str2[:-1])
The first line checks if both strings are empty (0 evaluates to False, any other number is True). len(str1) returns the length as an integer.
Then it checks if only one of the strings is empty in which case they are not equal.
Then it checks if the first letter is the same as the last letter.
Then it repeats the process with the each string (minus the first letter of str1 and minus the last letter of str2). It goes until one of the base cases is reached. The base case is what is returned. So it will only return True when then first letter was equal to the last letter each round until both strings ran out of characters at the same time.