Sunday, April 14, 2024
HomeSoftware EngineeringThe right way to Fill an Array in Python

The right way to Fill an Array in Python


The problem

We would like an array, however not simply any previous array, an array with contents!

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

For instance, the next code will end in an array containing the numbers “ to 4:

arr(5) # => [0,1,2,3,4]

Word: The parameter is non-obligatory. So it’s important to give it a default worth.

The answer in Python code

Possibility 1:

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

Possibility 2:

def arr(n=0): 
    return record(vary(n))

Possibility 3:

def arr(n=0):
    aux = []
    for x in vary(n):
        aux.append(x)
    return aux

Take a look at instances to validate our answer

import check
from answer import arr

@check.it("Fundamental Checks")
def basic_tests():
    @check.it('Fundamental Take a look at Instances')
    def basic_test_cases():
        check.assert_equals(arr(4), [0,1,2,3])
        check.assert_equals(arr(0), [])
        check.assert_equals(arr(), [])
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments