Reputation: 13
Shown below is the code to print the odd numbers in a given range of integers.
When I'm using the return
keyword, it's checking the 3
and returning the num
, so the output is 3
, but this is not the required output I'm looking for. The required output is 3,5
.
In another case when I'm using the print
function instead of return
, the program checks 3,4,5 and returns '3 & 5' as the output.
Could help me to get the right output
def oddNumbers(l, r):
# iterating each number in list
for num in range(l, r + 1):
# checking condition
if num % 2 != 0:
return num
Upvotes: 1
Views: 16471
Reputation: 131
Simple solution using list comprehension:
def odd(l,u):
return([a for a in range(l,u) if a%2 != 0])
Upvotes: 0
Reputation: 57033
There is no need to go through the range. Take a look at the first number: if it is odd, build a new range with the step of 2 that starts at that number. If it is even, then start at the next number.
def oddNumbers(l, r):
if l % 2 == 1:
return list(range(l, r + 1, 2))
else:
return list(range(l + 1, r + 1, 2))
Or, in a more Pythonic way:
def oddNumbers(l, r):
return list(range(l if l % 2 else l + 1, r + 1, 2))
Upvotes: 4
Reputation: 16640
You can use the following approach which stores the interim values in a list named odd
and returns the list after going through the range of numbers between l
and r
:
def oddNumbers(l, r):
odd = []
# iterating each number in list
for num in range(l, r + 1):
# checking condition
if num % 2 != 0:
odd.append(num)
return odd
Upvotes: 1