Codewars--Prefill an Array

Prefill an Array

Problem Description:

在這裏插入圖片描述
Create the function prefill that returns an array of n elements that all have the same value v. See if you can do this without using a loop.

You have to validate input:

v can be anything (primitive or otherwise)
if v is ommited, fill the array with undefined
if n is 0, return an empty array
if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError

When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.

Code Examples
prefill(3,1) --> [1,1,1]

prefill(2,"abc") --> ['abc','abc']

prefill("1", 1) --> [1]

prefill(3, prefill(2,'2d'))
  --> [['2d','2d'],['2d','2d'],['2d','2d']]

prefill("xyz", 1)
  --> throws TypeError with message "xyz is invalid"

Sample Tests:

Test.assert_equals(prefill(3,1), [1,1,1])
Test.assert_equals(prefill(2,'abc'), ['abc','abc'])
Test.assert_equals(prefill('1',1), [1])
Test.assert_equals(prefill(3, prefill(2,'2d')), [['2d','2d'],['2d','2d'],['2d','2d']])
try:
    prefill('xyz', 1)
except TypeError as err:
    Test.assert_equals(str(err), "xyz is invalid")

Version of Python:

在這裏插入圖片描述

Solutions:

Method1:

def prefill(n,v="undefined"):
    n=str(n)
    if n.isdigit():
            return int(n)*[v]
    else:
            return n+" is invalid"

Method2:

def prefill(n,v="undefined"):
    if not isinstance(n, int):
        n=str(n)
        if n.isdigit():
            return int(n)*[v]
        else:
            return n+" is invalid"
    list=[]
    if isinstance(n,int):
        list=n*[v]
    else:
        list=int(n)*[v]
    return list

Method3:

def prefill(n=0,v=None):
    try:
        return [v] * int(n)
    except:
        raise TypeError(str(n) + ' is invalid')

Explanations:

  • v="undefined"
    if v==None,then save v as “undefined”

  • n=str(n)
    During method2,When n is not an integer, n may be floating point data,

    n="10.5"
    n=str(n)
    if n.isdigit():
        print(int(n)*[v])
    else:
        print(n+" is invalid")
    

    在這裏插入圖片描述

  • n.isdigit()
    The Python isdigit() function checks whether a string consists of just numbers.The output is boolean.

  • isinstance(n,int)
    The Python isinstance(object, datatype) function checks whether a object’s datatype is datatype.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章