I write a simple lambda function to generate a random list of booleans with the following code:
randBinList = lambda n: [random()<0.5 for _ in range(n)]
This function works perfect, for example:
>>> randBinList(100)
[False, False, True, False, False, True, True, False, True, False, False, False, False, True, False, True, False, False, False, False, False, False, True, False, True, True, True, False, False, True, True, False, False, False, False, True, False, True, False, True, False, False, True, False, False, False, True, False, True, False, False, False, False, True, True, True, True, False, True, True, True, True, False, True, True, True, True, False, False, True, True, False, True, False, True, False, True, True, False, False, False, False, True, True, False, False, False, False, True, False, False, True, True, True, False, True, False, True, False, False]
However, when I tried to add this function to a new class I'm working on I received the following error:
return self.randBinList(num_of_features)
TypeError: <lambda>() takes 1 positional argument but 2 were given
I do not know why it says that tow arguments were given? Here is the code of my class. Thanks for your help.
import sys, csv, os, subprocess, time
from collections import deque, defaultdict
import random
from typing import List
class ScriptFeatures():
randBinList = lambda n: [random()<0.5 for _ in range(n)]
def get_random_individual (self):
num_of_features = len(self.d)
return self.randBinList(100)
This example reproduces your error.
import numpy as np
class A(object):
rand_bin_list = lambda n: [np.random.random() < 0.5 for _ in range(n)]
def __init__(self):
print(self.rand_bin_list(5))
The problem here is that when you construct a function within a class, and call it prefixed with self.
you need to include self as the first argument. So you can either add self
as an argument, or you can define the function in the __init__
. So either
class A(object):
rand_bin_list = lambda self, n: [np.random.random() < 0.5 for _ in range(n)]
def __init__(self):
print(self.rand_bin_list(5))
or
class A(object):
def __init__(self):
self.rand_bin_list = lambda n: [np.random.random() < 0.5 for _ in range(n)]
print(self.rand_bin_list(5))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With