This challenge took me forever. I spent a lot of time messing with regular expressions, but couldn't get it to work. I ended up coming up with this abomination. If anybody wants to take the time I'm interested in simpler ways to accomplish this task. (I'm a brand new pythoner)
def is_stressful(subj):
"""
recognise a stressful email subject
we are looking for any of: all uppercase, or ending in 3 !!!, or
containing 'help', 'asap', or 'urgent' despite have extraneous spellings
"""
import string
flagged_words = ['help', 'asap', 'urgent']
if subj[-3:] == '!!!': # check for ending in at least 3 !!!
return True
if subj.isupper(): # check for uppercase
return True
stripped = "".join(c for c in subj if c not in string.punctuation) # get rid of confusing characters
wordlist = stripped.lower().split(' ') # make the list to check
for word in wordlist: # first easy check, everything is spelled correctly
if word in flagged_words:
return True
for word in wordlist: # start the annoying check, getting rid of extra letters in flagged words
r = 0 # our word list counter
getgood = []
badletters = []
while r < len(flagged_words): # start the loop
for i, l in enumerate(word): # going through each character
if l in flagged_words[r]: # checking for good letters
if l not in getgood:
getgood.append(l) # no repeats except for 'a' in asap (don't know a good way for this)
elif l == 'a' and getgood.count('a') < 2:
getgood.append(l)
else:
badletters.append(False) # make sure we don't spell flagged words accidentally
r += 1 # go to the next word in list
i = 0 # reset letter counter
if ''.join(getgood) in flagged_words and all(badletters): # our final check
return True
getgood = [] # reset the loop
badletters = [] # reset the loop
return False
My tests:
print(is_stressful("H!E!L!P! its urGent asAP"))
print(is_stressful("asaaap"))
print(is_stressful("Headlamp, wastepaper bin and supermagnificently"))
print(is_stressful("I neeed advice!!!!"))
Thanks for any tips!