0

The odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1.

def odd_numbers(n):
    return [x for x in ___ if ___]

print(odd_numbers(5))  
# Should print [1, 3, 5]
print(odd_numbers(10)) 
# Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) 
# Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1))  
# Should print [1]
print(odd_numbers(-1)) 
# Should print []

Answer:

def odd_numbers(n):
  return [x for x in range(n + 1) if x % 2 == 1]

print(odd_numbers(5))  
# Should print [1, 3, 5]
print(odd_numbers(10)) 
# Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) 
# Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1))  
# Should print [1]
print(odd_numbers(-1)) 
# Should print []
  • Most simplest way in my opinion to complete this – Tanner Boviall Sep 03 '22 at 06:54
  • 1
    Looks ok, but since range takes a step parameter you can just do `list(range(1, n + 1, 2))` (no need for the if condition), implying that the question setup is somewhat odd. – mcsoini Sep 03 '22 at 07:06
  • What is the problem here? The code shown in the "Answer" fulfils the fill-in-the-gaps requirement and provides the required output. It's not the best way to get a list of odd numbers (as has been pointed out elsewhere) but there's nothing functionally wrong with the code shown in the question – DarkKnight Sep 03 '22 at 07:41

0 Answers0