Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function that takes in a list of integers and returns a list containing

ID: 3848263 • Letter: W

Question

Write a function that takes in a list of integers and returns a list containing either all the odd numbers or all the even numbers in the list. The function should have two parameters: the list of integers, and a string (either ‘odd’ or ‘even’) that determines if the function should return all the odds or all the evens. If a user does not pass in a second argument (the string ‘even’ or ‘odd’), the function should default to returning all evens.

If there is something in the list that is not an integer, raise a ValueError and tell the user that this function can only take in lists of integers.

Make sure to give your function a descriptive name and a good docstring.

Explanation / Answer

Python 2.7 code:

def IsInt(s):
try:
int(s)
return True
except ValueError:
return False

def select(l,property):
   if(property == "odd"):
       out = []
       for i in range(0,len(l)):
           if(IsInt(l[i])):
               if(l[i]%2 == 1):
                   out.append(l[i])
           else:
               print l[i], "is not integer!"
       return out
   else:
       out = []
       for i in range(0,len(l)):
           if(IsInt(l[i])):
               if(l[i]%2 == 0):
                   out.append(l[i])
           else:
               print l[i], "is not integer!"
       return out
print "Even Numbers are",
print select([1,2,3,4,5], "even")
print "Odd Numbers are",
print select([1,2,3,4,5], "odd")

Sample Output:

Even Numbers are [2, 4]
Odd Numbers are [1, 3, 5]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote