Home > OS >  List elements as argument in decorator (Python)
List elements as argument in decorator (Python)

Time:10-06

I am trying to solve this task: Create a function generating an array of random numbers and use decorator to square each element in the array. I do not know how can I have the array elements as the arguments in decorator.

import random


def square_them(function):
    def case(*args, **kwargs):
        numbers = function(*args, **kwargs)
        return numbers ** 2

    return case


@square_them
def array_creator():
    randomlist = []
    for i in range(1, 10):
        numbers = random.randint(1, 100)
        randomlist.append(numbers)
    print(randomlist)


array_creator()

I am getting an error:

line 7, in case return numbers ** 2 TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'

Any idea please? Thank you.

CodePudding user response:

Use a list comprehension:

import random

def square_them(function):
    def case(*args, **kwargs):
        numbers = function(*args, **kwargs)
        return [i ** 2 for i in numbers]
    return case


@square_them
def array_creator():
    randomlist = []
    for i in range(1, 10):
        numbers = random.randint(1, 100)
        randomlist.append(numbers)
    return randomlist


print(array_creator())

Output:

[2809, 3364, 400, 8100, 3025, 4096, 4, 2601, 144]

CodePudding user response:

import random
print([i*2 for i in random.sample(range(10), 5)])
  • Related