New*_*bie 0 python arrays random
我有一个清单:
> S = [1,8,93,3,8]
Run Code Online (Sandbox Code Playgroud)
我需要选择一个不在列表中但在最大值范围内的随机数。我更关心时间复杂度 O(n)。S 可能是一个相当大的列表。
import random
S=[1,8,93,3,8]
m = max(S)
for x in xrange(m):
rand = random.randint(1,m)
if rand not in S:
print rand
else:
print "Number - %d found in the array" % rand
break
Run Code Online (Sandbox Code Playgroud)
我没有尝试列表理解
这是我能想到的最简单的事情:
import random
S=[1,8,93,3,8]
m = max(S)
not_in_S = random.choice([x for x in range(m) if x not in S])
Run Code Online (Sandbox Code Playgroud)
如果list由整数组成并且可以接受任何数字:
S = [1,8,93,3,8]
number = 0.5
Run Code Online (Sandbox Code Playgroud)
如果数字必须是整数:
S = [1,8,93,3,8]
number = max(S) + 1
Run Code Online (Sandbox Code Playgroud)
如果数字必须是 中最大和最小元素之间的任意整数list:
S = [1,8,93,3,8]
number = next(iter(set(range(min(S)+1, max(S))) - set(S)))
Run Code Online (Sandbox Code Playgroud)
如果数字必须是 中最大和最小元素之间的伪随机整数list:
import random
S = [1,8,93,3,8]
number = random.choice(list(set(range(min(S)+1, max(S)))-set(S)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6336 次 |
| 最近记录: |