【问题标题】:ValueError: number of bits must be greater than zeroValueError:位数必须大于零
【发布时间】:2015-12-10 21:20:02
【问题描述】:

我正在尝试写一个关于 pagerank 的脚本。下面是我的脚本:

from scipy import *
from numpy import linalg as LA
import pickle
import random
import operator

def new_pagerank_step(current_page, N, d, links):

    if random.random() < 1 - d:
        next_page = random.randint(0, N)

    else:
        next_page = random.choice(links[current_page])

    return next_page




def pagerank_wikipedia_demo():
    with open("wikilinks.pickle", "rb") as f:
        titles, links = pickle.load(f)
    current_page = 2
    T = 100000
    N = len(titles)
    d = 0.4
    Result = {}
    result = []
    for i in range(T):

        result.append(current_page)

        current_page = new_pagerank_step(current_page, N, d, links)

pagerank_wikipedia_demo()

但是,当我运行此脚本时,我会收到以下消息:

Traceback (most recent call last):
  File "/usr/lib/python3.2/random.py", line 249, in choice
    i = self._randbelow(len(seq))
  File "/usr/lib/python3.2/random.py", line 225, in _randbelow
    r = getrandbits(k)          # 0 <= r < 2**k
ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "markov1.py", line 141, in <module>
    pagerank_wikipedia_demo()
  File "markov1.py", line 135, in pagerank_wikipedia_demo
    current_page = new_pagerank_step(current_page, N, d, links)
  File "markov1.py", line 113, in new_pagerank_step
    next_page = random.choice(links[current_page])
  File "/usr/lib/python3.2/random.py", line 251, in choice
    raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence

我不明白 ValueError 的含义。对于 IndexError,我知道这意味着 links[current_page] 是空的,但是从我的代码中,我看不出为什么 links[current_page] 可以是一个空列表。

【问题讨论】:

    标签: python-3.x random


    【解决方案1】:

    抛出此错误是因为您以某种方式向 random.choices 提供了空列表。试试:

    random.choice([])
    

    你会看到同样的错误。

    我不知道您的初始数据。但我会看看你那里是否有空的链接列表,如果有,在代码中测试它并设计在这种情况下你需要做什么。

    【讨论】:

      【解决方案2】:

      请注意 random.randint(0, N) 返回一些 x 使得 0 &lt;= x &lt;= N

      【讨论】:

      • 也许你可以打印更多的调试信息来定位异常发生的位置,看看周围是否有变量值不期望。
      猜你喜欢
      • 2016-03-16
      • 2017-01-30
      • 2018-05-24
      • 2017-04-08
      • 2021-12-10
      • 2018-03-30
      • 2020-04-01
      • 2017-08-17
      • 2016-07-02
      相关资源
      最近更新 更多