【问题标题】:How can i work around the ValueError from random.sample in Python?如何解决 Python 中 random.sample 中的 ValueError?
【发布时间】:2015-02-24 23:32:45
【问题描述】:

我正在尝试为背包问题编写代码。如果有一个具有承重能力的背包,您可以选择一定的物品组合以找到最佳解决方案。但是,我正在尝试随机生成可能的解决方案。所以我的代码会选择随机数量的随机项目(生成一个随机大小的列表)并测试解决方案是可行的(小于容量)还是不可行的(大于容量)。但是我遇到了 random.sample() 的问题。为了获得一个随机大小的列表,我将 k 设置为 leng(一个随机整数),并且总体是从给定项目范围内挑选的项目的随机列表。但我知道如果 leng 大于人口,那么就会有一个 ValueError。我想使用 random.sample() 所以我可以有一个唯一数字列表,但我需要以某种方式解决 ValueError 。我试过尝试:除了ValueError:但我不确定如何真正执行它。这是我目前所拥有的:

def genSoln(cap, items)
    g = input("Would you like to generate random potential solutions? [y/n] ")
    if g == 'y':
        gen = int(input("Number of times to generate/check random potential solutions? "))
        totalwt = 0
        totalval = 0
        for i in range(1,gen+1):
            try:
                pop = range(1,items)
                leng = random.randint(1,8)
                ran = random.sample(pop, leng)
            except ValueError:
                pass
            for i in ran:
                totalwt += int(wts[i])
                totalval += int(vals[i])
                if i == len(ran):
                    if totalwt < int(cap):
                        print("Items picked: ", ran)
                        print("Feasible: ", "Total Wt = ", totalwt, "Total Val = ", totalval)
                    else:
                        print("Items picked: ", ran)
                        print("Infeasible: ", "Total Wt = ", totalwt, "Total Val = ", totalval)
                    totalwt = 0
                    totalval = 0

【问题讨论】:

  • 不硬编码leng的上限,为什么不用pop的大小作为上限呢?
  • 所以...ran = random.sample(pop, len(pop))?
  • 是的,甚至只是:ran = random.sample(pop, items),假设 items 是一个整数
  • 哦...我才意识到。这样做的原因是它产生了相同大小的列表。我做了leng = random.randint(1,8),因为代码将产生多个随机生成,并且随机生成需要......嗯..随机大小。
  • 对不起你的权利,这就是为什么我一开始说改变leng的上限,即leng = random.randint(1,len(pop))

标签: python-3.x random-sample knapsack-problem


【解决方案1】:

应该这样做。

leng = random.randint(1, items)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多