选择一个不在列表中的随机数 [英] pick a random number not in a list

查看:74
本文介绍了选择一个不在列表中的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

> S = [1,8,93,3,8]

我需要选择一个随机数不在列表中,但在值的最大范围内。我更关心时间复杂度O(n)。 S可能是一个很大的列表。

I need to pick a random number that is not in the list but within the max range of value. I am more concerned about time complexity O(n). The S could be a pretty big list.

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

我没有尝试列表理解

推荐答案

如果 list 由整数组成,可以接受任何数字:

If the list consists of integers and any number is acceptable:

S = [1,8,93,3,8]
number = 0.5

如果数字必须是整数:

S = [1,8,93,3,8]
number = max(S) + 1

如果数字必须是列表:

S = [1,8,93,3,8]
number = next(iter(set(range(min(S)+1, max(S))) - set(S)))

如果数字mu st是列表中的最大元素和最小元素之间的伪随机整数:

If the number must be a psuedorandom integer between the largest and smallest elements in the list:

import random
S = [1,8,93,3,8]
number = random.choice(list(set(range(min(S)+1, max(S)))-set(S)))

这篇关于选择一个不在列表中的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆