user14948921
user14948921

Reputation: 21

Print the odd number using list comprehension

The question is :

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 []

And this is my code :

def odd_numbers(n):
    return [x for x in range(0, n) if x%2 != 0]

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 []

The output of my code said :

Here is your output: [1, 3] [1, 3, 5, 7, 9] [1, 3, 5, 7, 9] [] []

Not quite, odd_numbers(5) returned [1, 3] instead of [1, 3, 5]. Remember that list comprehensions let us use a conditional clause. What's the condition to determine whether a number is odd or even?

i dont know which part i should add in my code, this python is new for me, can you help me?

Upvotes: 1

Views: 17242

Answers (7)

Dave
Dave

Reputation: 1

this also works

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

Upvotes: 0

ADigraj
ADigraj

Reputation: 1

def odd_numbers(n):
    return [x for x in range(1,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 []

Upvotes: 0

Instead of losing one iteration as proposed previously by starting from 0 as in:

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

start from 1 to speed up:

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

Upvotes: 0

That Guy Eli
That Guy Eli

Reputation: 1

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

This worked for me as well but I'm not sure which is best practice when testing for an odd value (!= 0 or > 0). So which option is best practice?

Upvotes: 0

cynosure1
cynosure1

Reputation: 19

This is correct, too, specifying a step to the range:

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

Upvotes: 1

papi.chulo69999
papi.chulo69999

Reputation: 1

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

Upvotes: 0

Sivaram Rasathurai
Sivaram Rasathurai

Reputation: 6333

you need to change the range to take the n also.

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

Upvotes: 2

Related Questions