pangram - Need help on Python -
q: pangram sentence contains letters of english alphabet @ least once, example: quick brown fox jumps on lazy dog. task here write function check sentence see if pangram or not.
what have is:
def ispangram(s): alphabetlist = 'abcdefghijklmnopqrstuvwxyz' alphabetcount = 0 if len(s) < 26: return false else: s = re.sub('[^a-za-z]','',s).lower() in range(len(alphabetlist)): if alphabetlist[i] in s: alphabetcount = alphabetcount + 1 if alphabetcount == 26: return true else: return false
however, when try example s=["the quick brown fox jumps on lazy dog"], result false, wrong. should true b/c has contained 26 letters. can me fix code? many thanks!!!
the problem you're passing in list of strings instead of list. pass in "the quick brown fox jumps on lazy dog"
without brackets , code work.
your code unnecessarily complex (and mis-indented boot):
if alphabetcount == 26: return true else: return false
is way complicated - alphabetcount == 26
true or false! can write
return alphabetcount == 26
additionally, iterate on input string index variable. unnecessary, iterate on input string, this:
for c in alphabetlist: if c in s: alphabetcount += + 1
on top - , has caused error now, since code have failed otherwise - check len(s) < 26
superfluous, remove it.
the alphabet built-in python, it's called string.ascii_lowercase
. don't need write yourself!
that being said, algorithm still slow - iterate on s 26 times! why not write
import string def ispangram(s): return set(s.lower()) >= set(string.ascii_lowercase)
Comments
Post a Comment