猿问

如何生成一个不是2的幂的随机数?输出需要是 8 个随机数的列表

在python中,如何生成一个不是2的幂的随机数?输出需要是 8 个随机数的列表。这应该在 python 中的单个语句(理解风格)中完成。



绝地无双
浏览 125回答 2
2回答

MMMHUHU

试试下面的代码,def is_power_of_two (x):     return (x and (not(x & (x - 1))) )def get_random(start, stop):    while True:        value = random.randint(start, stop)        if not is_power_of_two(value):            return value    return [i for i in range(limit) if not is_power_of_two(i)]result = [get_random(0, 10000000000) for _ in range(8)]

慕仙森

在这种情况下,生成器会派上用场。编写一个带有无限循环的函数,该函数返回满足您条件的随机数,然后yield在调用该函数时使用语句一次返回一个这些值。这是一个例子。我添加了一些代码来检查输入参数,以确保在给定范围内有有效的结果。def random_not_power_of_2(rmin, rmax):&nbsp; &nbsp; # Returns a random number r such that rmin <= r < rmax,&nbsp; &nbsp; # and r is not a power of 2&nbsp; &nbsp; from random import randint&nbsp; &nbsp; # Sanity check&nbsp; &nbsp; if rmin < 0:&nbsp; &nbsp; &nbsp; &nbsp; raise ValueError("rmin must be non-negative")&nbsp; &nbsp; if rmax <= rmin:&nbsp; &nbsp; &nbsp; &nbsp; raise ValueError("rmax must be greater than rmin")&nbsp; &nbsp; # Abort if the given range contains no valid numbers&nbsp; &nbsp; r = rmin&nbsp; &nbsp; isValid = False&nbsp; &nbsp; while r < rmax:&nbsp; &nbsp; &nbsp; &nbsp; if r == 0 or (r & (r-1) > 0):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isValid = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; r += 1&nbsp; &nbsp; if not isValid:&nbsp; &nbsp; &nbsp; &nbsp; raise ValueError("no valid numbers in this range")&nbsp; &nbsp; while True:&nbsp; &nbsp; &nbsp; &nbsp; r = randint(rmin, rmax)&nbsp; &nbsp; &nbsp; &nbsp; if r == 0 or (r & (r-1) > 0):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield rdef get_random_list(rmin, rmax, n):&nbsp; &nbsp; # Returns a list of n random numbers in the given range&nbsp; &nbsp; gen = random_not_power_of_2(rmin, rmax)&nbsp; &nbsp; return [next(gen) for i in range(n)]get_random_list(0,17,10)
随时随地看视频慕课网APP

相关分类

Python
我要回答