Reputation: 256
The problem I'm trying to solve is rather simple: write a function q2(n)
that would return n
odd positive integers. For example, q2(3)
should return [1,3,5]
.
I have solved it, as you can see in the code below, using a for
loop. However, there was a note to the problem that said 'try to not use loops'. So the question is: how do I do that without using loops?
Here's my version:
def q2(n):
num100 = list(range(100))
odd = []
for i in num100:
if (i%2) != 0:
odd.append(i)
result = odd[0:n]
return result
Upvotes: 2
Views: 804
Reputation: 42143
You can use the range function:
def q2(N): return list(range(1,N*2,2))
or recursion:
def q2(N,r=1): return [r] if N == 1 else [r] + q2(N-1,r+2)
or a list comprehension (but that may be considered a loop):
def q2(N): return [2*n+1 for n in range(N)]
Upvotes: 1
Reputation: 1328
You can also use the python built-in filter
function.
>>> list(filter(lambda x: x%2 != 0, range(10*2)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Upvotes: 1
Reputation: 7852
You can use numpy's arange:
import numpy as np
def no_loop_odd_integers(n):
return np.arange(1,2*n,2).tolist() #.tolist() in the end if want list not np array
Or without numpy, use the built-in range as suggested in the comments:
def no_loop_odd_integers2(n):
return list(range(1,2*n,2))
Or, if you are into tensorflow, can use its range:
import tensorflow as tf
def no_loop_odd_integers3(n):
# create a tensor, convert it to numpy array, then to list:
return tf.range(1,2*n,2).numpy().tolist()
no_loop_odd_integers(4)
, no_loop_odd_integers2(4)
, no_loop_odd_integers3(4)
all return:
[1, 3, 5, 7]
All of the above methods work in the same spirit: you specify from where you want to start your array (ie 1), then you say up to (not including) which number you want to be the upper limit (you want n odd numbers, so the nth odd number is 2n-1, so you say 2n, so all your numbers will be lower than this), then you specify what steps you want to make between these two limits. You want to make steps of 2 (1,3,5,...), so that is the third argument in the range functions in all namespaces.
Upvotes: 0
Reputation: 5414
You can use recursion
,
def q2(n):
result = []
if n:
result = result + q2(n - 1)
result.append(n * 2 - 1)
return result
result = q2(3)
print(result) # output : [1, 3, 5]
This is a good resource to start learning recursion.
Upvotes: 1
Reputation: 170
You should use a list comprehension, but it is also a kind of loop
def q2(n):
return [number for number in range(n) if number%2!=0]
Upvotes: 1