How to make letters in a string match - python

I wasn't sure what to title it, but I'm writing a function that checks if a phrase is a palindrome or not. If something is capitalized or not doesn't matter and if there are other characters it will remove them. If the string is the same forwards and backwards (that's what a palindrome is) then it will be a Boolean True, and a Boolean False if it isn't. For example:
is_palindrome('ta.cocat')
#It would return
True
is_palidrome('Tacocat')
#It would return
True
is_palindrome('tacodog')
#It would return
False
I've written code that will take out extra characters, but I can't figure out how to make it that capitalization doesn't matter.
#Strip non-alpha
def to_alphanum(str):
return ''.join([char for char in str if char.isalnum()])
#Palindromes
def is_palindrome(str):
str = to_alphanum(str)
if(str==str[::-1]):
return True
else:
return False
#Here's examples about what it returns
is_palindrome('taco.cat')
True
is_palindrome('Tacocat')
>>> False

just use the lower function on your input string, so that case doesnt matters in your function
str = to_alphanum(str).lower()

You can simply use:
def isPalindrome(s):
s = to_alphanum(s).lower()
rev = s[::-1]
# Checking if both string are equal or not
if (s == rev):
return True
return False
s1 = "malayalam"
>>> isPalindrome(s1)
True

Related

How to make string characters lower case and uppercase match in python

I wasn't sure what to title it, but I'm writing a function that checks if a phrase is a palindrome or not. If something is capitalized or not doesn't matter and if there are other characters it will remove them.
If the string is the same forwards and backwards (that's what a palindrome is) then it will be a Boolean True, and a Boolean False if it isn't.
For example:
is_palindrome('ta.cocat')
#It would return
True
is_palidrome('Tacocat')
#It would return
True
is_palindrome('tacodog')
#It would return
False
I've written code that will take out extra characters, but I can't figure out how to make it that capitalization doesn't matter.
#Strip non-alpha
def to_alphanum(str):
return ''.join([char for char in str if char.isalnum()])
#Palindromes
def is_palindrome(str):
str = to_alphanum(str)
if(str==str[::-1]):
return True
else:
return False
#Here's examples about what it returns
is_palindrome('taco.cat')
True
is_palindrome('Tacocat')
>>> False
just use the lower function on your input string, so that case doesnt matters in your function
str = to_alphanum(str).lower()

In Python, how do I check if a string has only alphabets without the built in functions(.islower etc)?

This is my code. it seems to be checking only the first character. I'd like to know how to fix it.
import string
ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DECIMAL_DIGITS = "0123456789"
ALPHABETS = ASCII_LOWERCASE + ASCII_UPPERCASE
def is_alpha(string):
for c in "string":
if c in ALPHABETS:
return False
else:
return True
Do not return in every iteration, only return False when you find something that is not in ALPHABET. What about this?
def is_alpha(your_string):
for c in your_string:
if c not in ALPHABETS:
return False
return True
actually its almost half right:
def is_alpha(string):
for c in string:
if not c in ALPHABETS:
return False
return True
short circuiting on False is ok but you need to finish the loop to determine True
There's several issues with your code here.
In your function definition you say
for c in "string"
which means you're checking the characters in the string literal "string".
You'll need to remove the quotes to have it refer to your parameter and actually check the string you're looking at. Further, you should change the name of your parameter and variable to something less ambiguous than string.
As Two-Bit Alchemist points out, you're returning from inside the loop so if the first character is in ALPHABETS then it returns and doesn't execute any more.
Which goes to the final issue. You're returning False if it is an alpha character instead of true. If you change
if c in ALPHABETS:
return False
to
if c not in ALPHABETS:
return False
then delete the else branch and put the return True after the loop it will work as you intend.
Change your function like this:
def is_alpha(string):
for c in string:
if c not in ALPHABETS:
return False
return True
First of all, you had for c in "string": in your code. There you are creating a new string ("string") and looping through the characters in it. Instead, you want to loop through the parameter passed to your function. So remove the double quotes.
Your function returns after first character because you are returning in both cases. Return true only when all characters are in ALPHABETS

See if string contains substring

I was looking for a way to write code that checks whether a certain string is a part of another string. I understand that it is easy to do when we have numbers, but I don't know how to do it with strings.
For example, I have this function
a = is_part("motherland", "land")
I need to know that "land" is a part of the word "motherland" (return True or False). Is it possible to check this?
UPDATE: How can I create a restriction when the second word always has to be in the end of the first one. For example, in case when I check whether "eight" is a part of "eighteen" it returns False because "eight" is not at the end of the first word
This should help:
>>> "land" in "motherland"
True
>>> "banana" in "motherland"
False
Here is a function that determines whether a string target is contained within another string some_string.
def is_part(some_string, target):
return target in some_string
>>> is_part('motherland', 'land')
True
>>> is_part('motherland', 'father')
False
>>> is_part('motherland', '')
True
If you don't like an empty string returning true, change the return statement to
return (target in some_string) if target else False
If, on the other hand, you need to implement it yourself:
def is_part(some_string, target):
if target:
target_len = len(target)
for i in range(len(some_string)):
if some_string[i:i+target_len] == target:
return True
return False

How to check if the string has digits without a try/except or str.isdigit?

NUMBERS = "123456789"
def digit_checker(x):
for t in x:
if t in NUMBERS:
y = True
else:
y = False
return y
sentence = input("Enter a string to check if its all digits: ")
checker = digit_checker(sentence)
print(checker)
As the title states, how would I find if the string has all digits without using the str.isdigit or a try/except. The code keeps checking the first character and not all. How do I fix that?
NUMBERS = "123456789"
def digit_checker(x):
y = True
for t in x:
if t not in NUMBERS:
y = False
return y
You can use all and a generator expression:
NUMBERS = "1234567890"
def digit_checker(x):
return all(t in NUMBERS for t in x)
This will go through each character in x and see if it is in NUMBERS. If not, all will immediately stop checking and return False. Otherwise, it will return True after it has confirmed that every character is a digit. Below is a demonstration:
>>> NUMBERS = "1234567890"
>>> def digit_checker(x):
... return all(t in NUMBERS for t in x)
...
>>> digit_checker('12345')
True
>>> digit_checker('12345a')
False
>>>
Note too that it would be more efficient if you made NUMBERS a set:
NUMBERS = set("1234567890")
That way, t in NUMBERS will perform an O(1) (constant) hash lookup rather than an O(n) (linear) search through the string. Granted, on strings this small, the performance impact of the linear search is not too worrisome. However, that will quickly change whenever you are working with larger strings.
Actually, it looks like it is checking every character, but because it sets y for every character, it is the "numberless" of the last character that determines the value returned, regardless of what the other characters are.
Instead, you should initialize y to True, and only set it to False if you ever find a non-number. In fact, when that happens, you can immediately return.
If you are chefcking for the fact that all the letters are numbers, you can try the following expression:
def digit_checker(x):
return all( t in NUMBERS for t in x )
It is exactly the same as your code except it will also check whether all the characters within x are numbers. This is what has been missing in your code. The return value is always overwritten by the last check. Of course, using a loop and breaking out might be more efficient unless all does that internally for the generator expression, in which case the two are exactly equivalent.
NUMBERS = "1234567890" # Did you miss the 0?
def digit_checker(x):
all_digits = True
for t in x:
if t not in NUMBERS:
all_digits = False
break
return all_digits
A different approach would be to check them as sets:
def digit_checker(x):
return True if set(x).difference(set(NUMBERS)) == set() else False
Perhaps if you clear up the variable names the problem will be more clear:
def digit_checker(sentence):
is_number = True
for character in sentence:
if character in NUMBERS:
is_number = True
else:
is_number = False
return is_number
As you can see, you are evaluating if it is a number for each character, and changing the is_number variable each time. So, only the last character will result in proper evaluation.
You probably want to just return False when a non-digit is first detected. Try if character not in NUMBERS set is_number to False and break the loop.
There are some good answers to do that. Here's another way to do it. You can count the number of characters that are not digits, by storing them in a list, the length of this list should be zero.
NUMBERS = "1234567890"
def digit_checker(x):
return len([t for t in x if t not in NUMBERS]) == 0
print digit_checker('123') #True

Unsure of for loop

Not sure what I'm doing wrong here. Any help would be appreciated. When I enter a DNA sequence that contains a bad variable (like Z) I keep getting a return True. Can someone point out why?
Thanks
def is_valid_sequence(dna):
""" (str) -> bool
>>> is_valid_sequence('ATCG')
True
>>> is_valid_sequence('AZT')
False
>>> is_valid_sequence('atcg')
False
Returns a boolean result based on whether dna is a valid
dna sequence.
"""
for char in dna:
if char in "TCGA":
return True
else:
return False
You're returning on the first iteration of the loop: return ends the function, and all paths in the body of your loop contain a return. You probably want
for char in dna:
if char not in 'TCGA':
return False
return True
Or, more Pythonically:
return all(char in 'TCGA' for char in dna)
In your code you take char one by one and return True if it is in "TCGA". So if the first char is in "TCGA" it would return True and will stop execution. You should do something like this:
for char in dna:
if char not in "TCGA":
return False
You're always returning after testing the first character. Keep testing until you reach a bad character, don't return True until you've tested the whole string.

Categories

Resources