How to make string characters lower case and uppercase match in python - 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()

Related

How to make letters in a string match

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

For loop terminating early in nested ifs and function due to return

I am trying to solve the following practice question:
"Imagine you're writing the software for an inventory system for
a store. Part of the software needs to check to see if inputted
product codes are valid.
A product code is valid if all of the following conditions are
true:
The length of the product code is a multiple of 4. It could
be 4, 8, 12, 16, 20, etc. characters long.
Every character in the product code is either an uppercase
character or a numeral. No lowercase letters or punctuation
marks are permitted.
The character sequence "A1" appears somewhere in the
product code.
Write a function called valid_product_code. valid_product_code
should have one parameter, a string. It should return True if
the string is a valid product code, and False if it is not."
def valid_product_code(code):
if len(code)%4 == 0:
if "A1" in code:
if code.isalnum():
for character in code:
#print(character)
#print statement above when uncommented used to
#check if the loop is actually running as intended
if character.isupper() or character.isdigit():
return True
else:
return False
else:
return False
else:
return False
else:
return False
The practice question had several test strings, of which they included the following:
print(valid_product_code("A12B44BP"))
print(valid_product_code("BFDSAUSA98932RWEFOEWA9FEAA1DSFSF"))
print(valid_product_code("A1BBD5"))
print(valid_product_code("BDD5664S"))
print(valid_product_code("66aBSaA1fdsv"))
My code worked for the first four examples, resulting in True, True, False, False but while the last one should be False, I got True. After attempting some debugging (hence the print(character) in the for loop and changing the return True and return False to print(True) and print(False) statements respectively), the print statements I used to check indicated that lowercase letters all had False values whereas numbers and uppercase letters had True values as intended.
I had no problems with the 3 outer if statements, but once I needed to isolate lowercase characters I thought a for-each loop would suffice but the fact that this is a function means return is terminating my function prematurely and not allowing me to actually indicate that the presence of even a single lowercase letter in the whole string should render the value of the whole string as False. I feel something is missing, like maybe that I am putting my return statements in the wrong place, or have I simply approached this question the wrong way?
Please help and thanks in advance!
Your innermost loop is not implemented correctly. At the moment, if character.isupper() or character.isdigit(): will return True as soon as it detects the first 6.
You need to check for each element. This can be done in the following way. I am highlighting the modified lines by a comment #
def valid_product_code(code):
if len(code)%4 == 0:
if "A1" in code:
if code.isalnum():
for character in code:
if not (character.isupper() or character.isdigit()): # <---
return False # <----
return True # <---
else:
return False
else:
return False
else:
return False
print(valid_product_code("A12B44BP"))
print(valid_product_code("BFDSAUSA98932RWEFOEWA9FEAA1DSFSF"))
print(valid_product_code("A1BBD5"))
print(valid_product_code("BDD5664S"))
print(valid_product_code("66aBSaA1fdsv"))
True
True
False
False
False
Alternatively, you can combine your if statements to make the code more compact as
def valid_product_code(code):
if len(code)%4 == 0 and "A1" in code and code.isalnum():
for character in code:
if not (character.isupper() or character.isdigit()):
return False
return True
else:
return False

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

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