2 つの入力が与えられ、重複が存在しないという条件でリストを作成したいと考えています。リストには、ランダムな一連の数字が含まれている必要があります。リスト内の数値は正の整数です。
入力 1: リストの長さ (var
samples
)入力 2: リストの最大数 (var
end
)
これを行う方法はわかっていますが、リストに膨大な数、100 万個、またはそれ以上の数を含めたいと考えています。私はこの問題を自分で解決する 2 つの方法を作成しました。どちらにも問題があり、そのうちslow
の 1 つはMemoryError
.
方法 1 MemoryError
、:
import random
def create_lst_rand_int(end, samples):
if samples > end:
print('You cannot create this list')
else:
lst = []
lst_possible_values = range(0, end)
for item in range(0, samples):
random_choice = random.choice(lst_possible_values)
lst_possible_values.remove(random_choice)
lst.append(random_choice)
return lst
print create_lst_rand_int(1000000000000, 100000000001)
方法 2 slow
、:
import random
def lst_rand_int(end, samples):
lst = []
# lst cannot exist under these conditions
if samples > end:
print('List must be longer or equal to the highest value')
else:
while len(lst) < samples:
random_int = random.randint(0, end)
if not random_int in lst:
lst.append(random_int)
return lst
print lst_rand_int(1000000000000, 100000000001)
私の方法はどちらもうまく機能しないため (方法 1 は方法 2 よりもうまく機能します)、私の要件をより適切に満たすリストを作成する方法を知りたいです。