the function takes user's input (a string). It should return True if the last character appears more than once in the string, regardless if it's upper or lower case, otherwise it returns False.
What is wrong with the code?
def last_early(word):
word.lower()
if word.count(word[-1]) > 1:
print("True")
else:
print("False")
This is what I expect:
>>> last_early("happy birthday")
True
>>> last_early("best of luck")
False
>>> last_early("Wow")
True
>>> last_early("X")
False
Try:
def last_early(word):
lower_word = word.lower() # word.lower won't change word itself
if lower_word.count(lower_word[-1]) > 1:
return True
else:
return False
you can test by running:
def testLastEarly():
print("testing last_early()...",end="")
assert(last_early("happy birthday") == True)
assert(last_early("best of luck") == False)
assert(last_early("Wow") == True)
assert(last_early("X") == False)
print("pass")
testLastEarly()
if you want to try more exercise, check out here
Related
Looking for some help on a tick tac toe exercise:
I have the bellow:
test_board = ['#','X','O','X','O','X','O','','O','X']
def space_check(board,position):
free_space = ""
if free_space in board[position]:
return True
else:
return False
When running the function I cannot see the False return, only True:
space_check(test_board,7)
Output: True
space_check(test_board,9)
Output: True
If free_space in board[position]
You are search a "" in a string not in a list of string,so the results always true because "" always exist in any string.
You just Use equal operation == instead of in.
Change your function with this:
def space_check(board,position):
free_space = ""
return free_space == board[position]
test_board = ['#','X','O','X','O','X','O','','O','X']
space_check(test_board, 7)
Output : True
space_check(test_board, 9)
Output: False
My code is here:
def isIn(char, aStr):
mid = len(aStr)//2
if len(aStr)==0:
return False
elif len(aStr)==1:
if char == aStr:
return True
elif aStr[mid] == char:
return True
if mid == 0 and len(aStr) != 1:
return False
else:
if char > aStr[mid]:
return isIn(char,aStr[mid:] )
else:
return isIn(char,aStr[0:mid])
my code works for when the character is present in the string, if the test case is such that if the character that I want to search in the string is not actually present in the string, then the code goes into an infinite loop.
For example in the test case isIn('m','iloruuyz') the code goes into an infinite loop.
On the if len(aStr) == 1: condition, you only return True if the condition is met, but not False if the condition is not, that is where the infinite loop is occuring :)
def isIn(char, aStr):
mid = len(aStr)//2
if len(aStr)==0:
return False
elif len(aStr)==1:
if char == aStr:
return True
else: # Else return false to stop the infinite loop
return False
elif aStr[mid] == char:
return True
if mid == 0 and len(aStr) != 1:
return False
else:
if char > aStr[mid]:
return isIn(char,aStr[mid:] )
else:
return isIn(char,aStr[0:mid])
def first_and_last(message):
if (message[0] == message[3]):
return True
elif (message[0] != message[3]):
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
I want to return True if string is empty, True if 1st and last letter of string match and False otherwise.
How can I get a True result for an empty string?
You wrote that you want to compare the first character to the last,
so you have to use [-1] and not [3]. Otherwise you are comparing
the first and the fourth characters.
You can use if not message to check if it's an empty string
Since you are returning, you don't need to check if they do not match.
def first_and_last(message):
if not message:
return True
return message[0] == message[-1]
As noted in the comments this can be pushed a bit more into a single line:
def first_and_last(message):
return not message or message[0] == message[-1]
You can use if not
def first_and_last(message):
if not message:
return False
else: return True
print(first_and_last("else")) #True
print(first_and_last("tree")) #True
print(first_and_last("")) #False
# defines, name and establishes the arguments for the function
def first_and_last(message):
# "if not message" checks if the parameter is empty
# message[0] gets the first character in the parameter
# message[-1] gets the last character in the parameter
# "==" checks if the first and last character are the same in the
# parameter
# the "or" comparator checks if the statements on either side or
# the comparator is true
if not message or message[0] == message[-1]:
# if either one or both of the above statements are true the
# function returns True
return True
# otherwise returns False
return False
You can use if not message: to check if the message variable is empty.
You could, for example, do as follow :
def first_and_last(message):
if not message:
return True
elif (message[0] == message[3]):
return True
elif (message[0] != message[3]):
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
You can check if the string is empty with bool(message). And check the last item with message[-1]:
def first_and_last(message):
if not message:
return True
elif (message[0] == message[-1]):
return True
else:
return False
print(first_and_last("else")) # Returns True
print(first_and_last("tree")) # Returns False
print(first_and_last("")) # Returns True
Use:
if not message:
This will return true if the string is empty:
def first_and_last(message):
if not message:
return True
if (message[0] == message[3]):
return True
elif (message[0] != message[3]):
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
def first_and_last(message):
if not message:
return True
elif (message[0] == message[-1]):
return True
elif (message[0] != message[-1]):
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
def first_and_last(message):
if message=="" or message[0]==message[-1]:
return True
return False
Here, message == "" checks for empty string and after "or" it checks for first and last letter of word.
Just to make it more readable since you are learning and haven't used "if not"
def first_and_last(message):
if message == "":
return True
elif message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
output would be below
True
False
True
def first_and_last(message):
if message == "" or message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))`enter code here`
print(first_and_last(""))
# could it work like this as well? if not why? thanks :)
def first_and_last(message):
while bool(message) == True:
first_letter = str(message[0])
last_letter = str(message[-1])
if first_letter == last_letter:
return True
else :
return False
return True
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
# Output (True, False, True)
So I have this two scripts with same content, but different if statements inside the loop:
Based on my understanding and if, if tests both conditions while if, elif testes up to the first condition that is True and ignores the next ones.
Why my instructor tells me that if, elif is the right answer? shouldn't both of them be valid answers?
def has_letter_cases(s: str) -> bool:
"""Return True if and only if s contains at least one lowercase letter
and an uppercase letter
>>>has_letter_cases('abcABC')
True
>>>has_letter_cases('abc123')
False
>>>has_letter_cases('ABCXYZ')
False
"""
upper = False
lower = False
for ch in s:
if ch.islower():
lower = True
if ch.isupper():
upper = True
return bool(upper and lower)
def has_letter_cases(s: str) -> bool:
"""Return True if and only if s contains at least one lowercase letter
and an uppercase letter
>>>has_letter_cases('abcABC')
True
>>>has_letter_cases('abc123')
False
>>>has_letter_cases('ABCXYZ')
False
"""
upper = False
lower = False
for ch in s:
if ch.islower():
lower = True
elif ch.isupper():
upper = True
return bool(upper and lower)
I have a CSV file with data in it that should be either a float or an integer, but if its not, the row is marked as corrupt.
I have this if statement that checks several of the columns in each row to see if they are not empty, and if they are a float or integer. Currently, the program marks every row in the CSV file as corrupt. How do I fix this?
def check_if_number(num) :
for i in num:
if i == "." or i == "":
pass
else:
try:
float(i)
except (ValueError, TypeError):
return False
return True
def check_if_empty(item) :
if item == "" :
return True
else:
return False
if (check_if_empty(row[5]) == False
and check_if_number(row[5]) == False
or check_if_empty(row[6]) == False
and check_if_number(row[6]) == False
or check_if_empty(row[8]) == False
and check_if_number(row[8]) == False
or check_if_empty(row[9]) == False
and check_if_number(row[9]) == False
or check_if_empty(row[10]) == False
and check_if_number(row[10]) == False):
corrupt = True
I think your second function is returning True when you want it to return False?
def check_if_empty(item) :
if item == "" :
return False
else:
return True
EDIT:
I have simplified and attached an updated working code that yields what you are looking for just to help substantiate my thought.
def check_if_number(num):
float(num)
for i in num:
if i == "." or i == "":
pass
else:
try:
float(i)
except (ValueError, TypeError):
return False
return True
def check_if_empty(item):
if item == "" :
return False
else:
return True
if check_if_empty('.4') == True and check_if_number('.4') == True:
corrupt = False
else:
corrupt = True
print(corrupt)
... False