How can I make a Python function examine every element of a list? -


i ordered build bulean function takes list of numbers , execute "true" if list proper grade list(i.e every number between 0 100) , "false" otherwise. encounter error, caused, believe not thorough acquaintance program. reason why ask here learn doing.

i tried few scripts. 1 of them:

 def isvalidgradelist(i):     x in range(0,len(i)+1):         if i[x] not in range (0,101):             return false         else: continue         return true 

as see, code won't way in scripter. how can attend it? appreciate help.

thank help. unfortunately, not use "all" built-in function yet, we've not learned how use it. is, however, i've done far. seems working.

def areintegers(i):     x=0     x in range(0,len(i)):         if type(i[x])==int:             x=x+1         else:                 return false     return true  def isbounded(i):     x=0     x in range(0,len(i)):         if i[x] in range(0,101):             x=x+1         else:                 return false     return true  def isvalidgradelist(i):     if isbounded(i)==true:         if areintegers(i)==true:             return true         else:             return false     else:         return false 

the code needs go through list , if catches grade outside range 0-100, return false. if not catch such grade continues until reaches end of list. @ point know none of grades outside of range can return true. so, unindenting return true executed after loop has finished make code work.

def isvalidgradelist(i):     x in range(0,len(i)+1):         if i[x] not in range (0,101):             return false         else: continue     return true    # needs *outside* of loop 

this can simplified bit: continue statement doesn't anything; can loop through elements of list rather using index; , can check grades within range using form a <= x <= b rather range.

def is_valid_grade_list(l):     grade in l:         if not 0 <= grade <= 100:             return false     return true 

and all provides shortcut type of function:

def is_valid_grade_list(l):     return all(0 <= grade <= 100 grade in l) 

if need check each grade integer checking within range, can add isinstance(grade, int) condition:

def is_valid_grade_list(l):     grade in l:         if not (isinstance(grade, int) , 0 <= grade <= 100):             return false     return true 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -