2 回答

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
試試下面的代碼,
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)]

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
在這種情況下,生成器會(huì)派上用場。編寫一個(gè)帶有無限循環(huán)的函數(shù),該函數(shù)返回滿足您條件的隨機(jī)數(shù),然后yield在調(diào)用該函數(shù)時(shí)使用語句一次返回一個(gè)這些值。
這是一個(gè)例子。我添加了一些代碼來檢查輸入?yún)?shù),以確保在給定范圍內(nèi)有有效的結(jié)果。
def random_not_power_of_2(rmin, rmax):
# Returns a random number r such that rmin <= r < rmax,
# and r is not a power of 2
from random import randint
# Sanity check
if rmin < 0:
raise ValueError("rmin must be non-negative")
if rmax <= rmin:
raise ValueError("rmax must be greater than rmin")
# Abort if the given range contains no valid numbers
r = rmin
isValid = False
while r < rmax:
if r == 0 or (r & (r-1) > 0):
isValid = True
break
r += 1
if not isValid:
raise ValueError("no valid numbers in this range")
while True:
r = randint(rmin, rmax)
if r == 0 or (r & (r-1) > 0):
yield r
def get_random_list(rmin, rmax, n):
# Returns a list of n random numbers in the given range
gen = random_not_power_of_2(rmin, rmax)
return [next(gen) for i in range(n)]
get_random_list(0,17,10)
添加回答
舉報(bào)