How to Fill an Array in Python

The challenge

We want an array, but not just any old array, an array with contents!

Write a function that produces an array with the numbers 0 to N-1 in it.

For example, the following code will result in an array containing the numbers 0 to 4:

arr(5) # => [0,1,2,3,4]
Code language: Python (python)

Note: The parameter is optional. So you have to give it a default value.

The solution in Python code

Option 1:

def arr(n=0): return [x for x in range(n) if n>0]
Code language: Python (python)

Option 2:

def arr(n=0): return list(range(n))
Code language: Python (python)

Option 3:

def arr(n=0): aux = [] for x in range(n): aux.append(x) return aux
Code language: Python (python)

Test cases to validate our solution

import test from solution import arr @test.it("Basic Tests") def basic_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(arr(4), [0,1,2,3]) test.assert_equals(arr(0), []) test.assert_equals(arr(), [])
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments