Can't exclude some strings [duplicate] - python

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.

Related

How to determine unique characters in a string

I have a solution in python to find the string having unique characters.
def is_unique_with_ascii(string):
if len(string) > 128:
return False
char_set = [False] * 128
for char in string:
val = ord(char)
if char_set[val]:
print(char_set[val])
return False
char_set[val] = True
return True
In this code, the char_set has been initialized with false values. But in if statement when the same character that has already in string caught the statement become true means the char_set[val] got true value.My question is in python how to if char_set[val]: statement works to get the same value. Please help me out.
Looking at the documentation for if, it evaluates the condition, which is char_set[val] in this case. Since it already returns a Bool, the if statement evaluates it right away, to give the impression that "if char_set[val] statement works to get the same value"

return True for recursive function in python [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 1 year ago.
could someone please indicate to me what's wrong with the logic of the simple recursive function, below:
def palindrome (string):
if len(string)<=1:
return True
elif string[0]== string[-1]:
palindrome(string[1:-1])
else:
return False
the False part, works ok, for example :
palindrome('good') the function returns correctly False.
but if it's fed a palindrome like :
palindrome('level') the function returns nothing.
As mentioned in the comments, you don't return the function when calling it recursively, but you should, or the original function call will return None.
Solution:
def palindrome (string):
if len(string)<=1:
return True
elif string[0].lower() == string[-1].lower():
return palindrome(string[1:-1])
else:
return False
I would also add "lower" as capitalization isn't relevant

if decision with list variable [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 3 years ago.
In C/C++, true is standardized as 1, and false as 0. Although not a good practice,
if variable:
#do something
kind of decision making seems ok in python and it seems makes decision based on whether variable is None or is zero - if it is a number. Followings are reasonable.
a = 123123
if a:
print "if condition is true" # this prints
a = "a string"
if a:
print "if condition is true" # this prints
a = None
if a:
print "if condition is true" # this does not print
However, I wonder why it evaluates to false with an empty list, which is neither None, nor zero. What is the exact implementation of python if statement?
a = [] # a is not None
if a:
print "true" # this does not print
An if statement requires a bool. That means the the expression following the if is analyzed is a boolean context. Said differently it is converted to bool.
If a bool context, the following items evaluate to False (non exhaustive list):
None
numeric 0
empty list
empty string
empty dict
Non null numerics and non empty iterables eveluate to True
Lists are empty, so they're False, that's how python reacts, to know whether something is False so doesn't go trough, do:
>>> bool([])
False
>>>
So it is False.

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

if statement to one line with return [duplicate]

This question already has answers here:
Is it possible to write single line return statement with if statement?
(4 answers)
Closed 6 years ago.
I know that the 'one line if statement' question has been asked multiple times already but I couldn't figure out what's wrong with my code. I want to convert
def has_no_e(word):
if 'e' not in word:
return True
to a one line function like:
def hasNoE(word):
return True if 'e' not in word
but I get a Syntax Error if I do so -why?
I think because you do not specify the else part. You should write it as:
return True if 'e' not in word else None
This is because Python sees it as:
return <expr>
and you specify a ternary condition operator as <expr> which has syntax:
<expr1> if <condition> else <expr2>
So Python is looking for your else part.
Return False?
Perhaps you want to return False in case the test fails. In that case you could thus write it like:
return True if 'e' not in word else False
but this can be shortened in:
return 'e' not in word
Ternary conditional statements require you to have an else in them as well. Thus, you must have:
def hasNoE(word):
return True if 'e' not in word else False

Categories

Resources