为什么python randint(0,N)返回N?

时间:2017-11-02 00:46:03

标签: python-2.7

考虑MWE:

(主要思想是从列表中选择一个随机点并确定距离最远的一个点):

import numpy as np
import matplotlib.pyplot as plt
from random import randint
from scipy.spatial.distance import euclidean    

N = 5 # number of points
print( 'N = %d' % N)
x=[ randint(1,N) for p in range(0,N)]
y=[ randint(1,N) for p in range(0,N)]

pts = [[x[i],y[i]] for i in range(0,N)]
print pts

def dist_ponto_lista(ponto,lista):
    return [ euclidean(ponto,lista[j]) for j in range(len(lista)) ]

def ponto_mais_longe(lista_ds):
    ds_max = max(lista_ds)
    idx = lista_ds.index(ds_max)
    return pts[idx]

r=randint(0,N)
print r
P0 = pts[r]  # choose a random pt from pts 
ds = dist_ponto_lista(P0,pts)
PML = ponto_mais_longe(ds)
print P0
print ds
print PML

quit()

它似乎运作良好,但有时,它会出现错误,如下所示:

N = 5
[[5, 4], [3, 2], [5, 3], [4, 2], [1, 1]]
5
Traceback (most recent call last):
  File "farthest-pts.py", line 25, in <module>
    P0 = pts[r]
IndexError: list index out of range


------------------
(program exited with code: 1)
Press return to continue

我真的不明白。在这种情况下,r=5因此pts索引后的错误应该从04(请记住N=5)。

但为什么选择r=5,因为它被定义为r=randint(0,N)

2 个答案:

答案 0 :(得分:1)

寻找at the manual

random.randint(a, b)
    Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

您可能想要使用的是numpy.random.randint

numpy.random.randint(low, high=None, size=None, dtype='l')
[...]
    high : int, optional
      If provided, one above the largest (signed) integer to be drawn from the
      distribution (see above for behavior if high=None).

这将为您提供预期的行为。

答案 1 :(得分:0)

你应该替换

P0 = pts[r]

通过

P0 = pts[r-1]

因为列表从0索引到size-1! 或者您也可以调整randint的范围

r=randint(0,N-1)

根据您的喜好。

最后但并非最不重要的是,错误意味着您正在尝试访问超出范围的数组的单元格:

IndexError: list index out of range

希望它可以帮到你!