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
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 answers here:
Why does python use 'else' after for and while loops?
(24 answers)
Closed 1 year ago.
I would like to understand why the following python code to find all prime numbers less than n works:
def prime(n):
for q in range(2,n):
for i in range(2,q):
if q%i==0:
print(q, "is not a prime")
break
else:
print(q, "is a prime")
My problem is that I thought the else: should be aligned under the if: but it isn't in this code. I think the problem is that I do not understand well enough what the "break" does.
In Python, for loops can also have an else: block (see for_stmt in the parser grammar). The else block of a for loop is entered if the loop runs to completion without hitting any break statement.
In your case, the break is conditional upon q % i == 0, so the else block here means that no number in range(2, q) has satisfied this condition, i.e. that q has no divisors besides 1 and itself.
Note: this primality test is very similar to a code snippet from the tutorial.
This question already has an answer here:
Why Python recursive function returns None [duplicate]
(1 answer)
Closed 2 years ago.
I'm trying to create a recursive function in Python (as part of an online course) which takes two numbers and returns the highest common denominator between them, however, the function won't return the value.
My code is:
def gcdRecur(a, b):
x = min(a,b)
y = max(a, b)
if x == 0:
return y
else:
gcdRecur(x, y%x)
When I test the function with
gcdRecur(2,12)
or
gcdRecur(6,12)
nothing is returned. I know the function works because if I print y before I return it then the correct denominator is printed to the console, I'm just not sure why the function doesn't output y.
It's probably something obvious but as I'm new to Python I'm not sure what I'm doing wrong.
Any help would be much appreciated.
You need to return something in both branches:
else:
return gcdRecur(x, y%x)
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
This question already has answers here:
How to test if one string is a subsequence of another?
(4 answers)
Python list filtering: remove subsets from list of lists
(10 answers)
Closed 4 years ago.
I know many similar questions has been asked before with answers but my concern is related to builtin functionality rather than my own logic of loops and indexes etc.
In my python app, I need to check if listA is subset of listB. I've done this with the help of sets like this
set(listA) < set(listB)
It works fine overall but I also need to check order of objects in list. e.g.
x = ['a','b','c','d']
xx = ['a', 'c']
xxx = ['c' , 'a']
so according to sets definition;
set(xx) < set(x) returns true and set(xxx) < set(x) also returns true...
But I need something that returns false for 2nd case.
Is there any builtin functionality in python or I need to implement my own logic to get required result?
I think a better word for this operation is a subsequence.
You need to write this yourself, but you can do it fairly easily by walking both lists together:
def is_subsequence(a, b):
b_it = iter(b)
try:
for a_val in a:
while next(b_it) != a_val:
pass
except StopIteration:
return False
else:
return True
used as:
>>> is_subsequence(xx, x)
True
>>> is_subsequence(xxx, x)
False
Edit: Searching for "subsequence" finds this great answer.