Python - Check if a word "Is Isogram" - python

I could look up the right answer, but I am just so certain I am correct as I get this to pass all my tests in IDLE, but on my online course it only partially passes - any reason why?
def is_isogram(txt):
if len(list(txt)) == len(set(txt)):
return True
else:
return False

It might be that you aren't accounting for a string with upper and lowercase letters. Using either str.upper or str.lower might be the solution. If that is the case, something like this could do it in one pass.
def is_isogram(txt):
seen = set()
for char in txt.lower():
if char in seen:
return False
seen.add(char)
return True

Mostly it is failing due to case sensitive issue. Why don't you add lower() to your code and try it:
def is_isogram(txt):
if len(list(txt.lower())) == len(set(txt.lower())):
return True
else:
return False

the below made me pass my quiz, I did need to account for lower/upper!
def is_isogram(txt):
txt = txt.lower()
if len(list(txt)) == len(set(txt)):
return True
else:
return False

Related

How to check the given number is digit or not?

How can I check if a number is composed by a single digit?
Here is what I have tried so far:
n=5
def digit(n):
for i in [0,1,2,3,4,5,6,7,8,9]:
if ???
return True
else:
return False
The output in this case should be `True
`
I'm not saying it's the best way to do it, but it's probably what you meant to do:
def digit(n):
for i in [0,1,2,3,4,5,6,7,8,9]:
if n == i:
return True
else:
return False
digit(5)
Output:
True
Please pay attention that the else clause is not part of the if, but part of the for, which means that it will be executed only if the loop ended without any return or break during the iterations. You can also not use the else at all, and just return False after the loop.
You can simply do
def isdigit(n):
return n in range(10)

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

a bug in my Palindrome code . My function runs fine except when i call ('abba') returns false instead of True . Why

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction. Write a function that determines whether the given word or number is a palindrome.
def isPalindrome(word1):
c=''
for l in reversed(str(word1)):
c+=l #reversed word
if (str(c).lower()==str(word1).lower())&len(str(word1))<>0:
return True
else :
return False
def isPalindrome(word1):
c=''
for l in reversed(str(word1)):
c+=l #reversed word
if (str(c).lower()==str(word1).lower()) and len(str(word1))!=0:
return True
else :
return False
Just some syntax errors:
In Python, the syntax for "and" is simply and, not &.
In Python 3, the syntax for "not equal" is !=, not <>. However, in Python 2, this is valid syntax. It is still better to use != to maintain compatibility across versions.
Maybe this is cheating a little, but why do you not use something like:
def isPalindrome(word):
if word.lower() == word[::-1].lower():
return True
return False
where word[::-1] is simply your input reversed.
def isPalindrom(word):
for (c1,c2) in zip(word,reversed(word)):
if c1.lower()!=c2.lower():
return False
return True
Could you use the following logic
def isPalindrome(word1):
c=0
for l in reversed(str(word1)):
if (str(word1[c]).lower()==l.lower()):
c+=1
continue
else :
return False
return True
print(isPalindrome('12311'))

Why isn't my for loop working for my expression?

I want this function to read a password, and check to see if it has at least 1 number in it. If not, it needs to return False. I need to use a for loop with the range function and this is what I have:
def hasNum(password):
for i in range(0,len(password),1):
if password == str('0123456789'):
return True
else:
return False
I've tried different variations and it's driving me crazy. Can someone possibly explain to a rookie what they're doing wrong?
The loop tests once if the password is 0123456789; if it matches that string, True is returned, otherwise False is returned outright. The range(0, len(password), 1) is a complicated way to write range(len(password)); likewise str('0123456789') is a complicated way of writing '0123456789'.
What you need is to iterate over each character, and if it is a digit, then return True; if none is, then return False:
def has_digit(password):
for character in password:
if character.isdigit():
return True
return False
The final return False is outside the loop - we must check each and every character in the password before returning False.
This can be simplified with any:
def has_digit(password):
return any(ch.isdigit() for ch in password)

How can this behavior be acomplished? Python "short circuting" test

I have the following code:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
else:
pass
return False
What i need to know the following: in case the if condition evaluates to true, will the function stop looking in the list and never return False? Or do i need a break statement?
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
break
else:
pass
return False
If the following code does not solve my problem, what can i use to do simulate that behavior?
Thanks
return is the end of the line, and nothing else will happen in that function afterwards. On the other hand, you could rewrite your function as
def testGeodatabase(self):
return self.outputGeodatabase in self.gp.ListWorkspaces("*","ALL")
You don't need the break keyword in the code above. Actually, you don't need the
else:
pass
either. The
return True
will exit the function.
The return statement will indeed cause the function to be exited at that point. No further code is executed in the function.
Here is a simple test which you could run to prove the point:
def someFunction(nums):
for i in nums:
if i == 1:
return "Found 1!"
return "Never found 1"
And running it:
>>> someFunction([2])
'Never found 1'
>>> someFunction([2,1,3])
'Found 1!'
I think that using any() is the best choice:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
return any(x == self.outputGeodatabase for x in geodatabaseList)

Categories

Resources