Python 在发现匹配之前计算迭代次数不正确

Python 在发现匹配之前计算迭代次数不正确,python,list,Python,List,我有以下代码: def numbers(): '''returns 2 random numbers between 1 and 10 that are not the same ''' b = random.randrange(1, 11, 1) res = [] count = 0 while len(res) < 2: if b not in res: res.append(b)

我有以下代码:

def numbers():
    '''returns 2 random numbers between 1 and 10 that are not the same
    '''
    b = random.randrange(1, 11, 1)
    res = []
    count = 0
    while len(res) < 2:
        if b not in res:
            res.append(b)
            b = random.randrange(1, 11, 1)
    return res


def match_count():
    '''counts how many times numbers must be ran before a match is found.
    '''
    count = 0
    a = sorted(numbers())
    b = sorted(numbers())
    while b != a:
        b = sorted(numbers())
        count += 1
        print a, b
    return count
def numbers():
''返回2个介于1和10之间的不相同的随机数
'''
b=随机随机随机范围(1,11,1)
res=[]
计数=0
而len(res)<2:
如果b不在res中:
决议草案(b)
b=随机随机随机范围(1,11,1)
返回res
def match_count():
''计算在找到匹配项之前必须运行数字的次数。
'''
计数=0
a=已排序(数字())
b=已排序(数字())
而b!=a:
b=已排序(数字())
计数+=1
打印a、b
返回计数
当我运行这段代码时,有时会返回count,但大多数时候程序似乎没有匹配项而挂起,我不得不中断它。比如说

>>> match_count()
[3, 8] [3, 5]
[3, 8] [1, 9]
[3, 8] [1, 4]
[3, 8] [5, 10]
[3, 8] [3, 8]
5
>>> match_count()
[2, 8] [4, 6]
[2, 8] [4, 10]
[2, 8] [1, 3]

Traceback (most recent call last):
  File "<pyshell#252>", line 1, in <module>
    match_count()
  File "C:\Python27\match_count.py", line 24, in match_count
   b = sorted(numbers())
  File "C:\Python27\match_count.py", line 10, in numbers
    while len(res) < 1:
 KeyboardInterrupt
>>匹配\u计数()
[3, 8] [3, 5]
[3, 8] [1, 9]
[3, 8] [1, 4]
[3, 8] [5, 10]
[3, 8] [3, 8]
5.
>>>匹配计数()
[2, 8] [4, 6]
[2, 8] [4, 10]
[2, 8] [1, 3]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
匹配计数()
文件“C:\Python27\match\u count.py”,第24行,在match\u count中
b=已排序(数字())
文件“C:\Python27\match\u count.py”,第10行,以数字表示
而len(res)<1:
键盘中断

如果我将len(res)<2时的
更改为len(res)<1时的
,程序每次都会工作。有人能告诉我我做错了什么吗。任何关于使此代码更高效的建议都值得赞赏。

这里有一个可能的问题:当len(res)<2:
循环第一次通过时,新的b值可能与旧的b值相同。然后此代码将永远循环:

while len(res) < 2:
    if b not in res:
        res.append(b)
        b = random.randrange(1, 11, 1)
而len(res)<2:
如果b不在res中:
决议草案(b)
b=随机随机随机范围(1,11,1)
因为
len(res)
将始终为1,如果b不在res中,则测试将始终失败。

代码行

while len(res) < 2:
    if b not in res:
        res.append(b)
        b = random.randrange(1, 11, 1)
而len(res)<2:
如果b不在res中:
决议草案(b)
b=随机随机随机范围(1,11,1)
如果第一个和第二个数字相同,则在无限循环中运行(b仅在其不同的情况下变化,否则它是无限循环)。将缩进更正为

while len(res) < 2:
    if b not in res:
        res.append(b)
    b = random.randrange(1, 11, 1)
而len(res)<2:
如果b不在res中:
决议草案(b)
b=随机随机随机范围(1,11,1)

一切都应该正常运行。

这是有道理的,但是有什么解决方案可以防止它进入不可能的循环呢?最后,我想增加列表中的项目数。如果测试失败,则分配一个新的b。这样,下一次循环将尝试不同的b。只需移动
b=random.randrange(1,11,1)
一个制表位到左侧。嘿。。。这是绝对正确的,但我有一个疑问,那就是我们不可能直接从python中的不连续范围生成随机数吗?从1-4和5-9中选择?我们可以使用您提供的功能,但是否有相同的默认功能。。