【发布时间】:2017-01-06 01:01:05
【问题描述】:
为什么我的代码 100% 成功?我想为此代码的输出生成 100 个随机样本来测量速度,但每次运行时,我都会收到 100 个真实结果和 0 个错误结果。有人可以给我一些建议吗?
import random
from random import randint, sample
from itertools import chain, combinations
import time
class SSP():
def __init__(self, S=[], t=0):
self.S = S
self.t = t
self.n = len(S)
#
self.decision = False
self.total = 0
self.selected = []
def __repr__(self):
return "SSP instance: S="+str(self.S)+"\tt="+str(self.t)
def random_instance(self, n, bitlength=10):
max_n_bit_number = 2**bitlength-1
self.S = sorted([randint(0,max_n_bit_number) for i in range(n)], reverse=True)
self.t = randint(0,n*max_n_bit_number)
self.n = len(self.S)
def random_yes_instance(self, n, bitlength=10):
max_n_bit_number = 2**bitlength-1
self.S = sorted([randint(0,max_n_bit_number) for i in range(n)], reverse=True)
self.t = sum(sample(self.S, randint(0,n)))
self.n = len(self.S)
def try_at_random(self, S, n, t):
#if sum is 0, use empty set as our solution
if (t == 0):
return True
print("Found a subset with given sum")
#if n is 0 and sum is not 0, no solution possible
if (n == 0 and t != 0):
return False
print("No subset within given sum")
if (S[n-1] > sum):
return instance.try_at_random(S, n-1, t)
else:
return instance.try_at_random(S, n-1, t) or instance.try_at_random(S, n-1, t-S[n-1])
i=0
tr = 0
fa = 0
instance = SSP()
for i in range (0, 100):
instance.random_yes_instance(4)
print(instance)
start_time = time.time()
if (instance.try_at_random(instance.S, instance.n, instance.t) == True):
print("Found a subset with given sum")
tr += 1
else:
print("No subset within given sum")
fa += 1
time_after = time.time() - start_time
print ("Time taken: " +str(time_after)+"s")
i+=1
print ("Times succeeded: ", tr)
print ("Times failed: ", fa)
这是一个示例输出:
SSP instance: S=[754, 429, 232, 131] t=131
Found a subset with given sum
Time taken: 0.0s
SSP instance: S=[954, 903, 768, 184] t=0
Found a subset with given sum
Time taken: 0.0s
SSP instance: S=[871, 532, 495, 337] t=0
Found a subset with given sum
Time taken: 0.0s
SSP instance: S=[1011, 837, 599, 559] t=599
Found a subset with given sum
Time taken: 0.0s
SSP instance: S=[571, 306, 181, 121] t=0
Found a subset with given sum
Time taken: 0.0s
SSP instance: S=[807, 284, 220, 71] t=1162
Found a subset with given sum
Time taken: 0.0s
('Times succeeded: ', 100)
('Times failed: ', 0)
【问题讨论】:
-
我的第一印象是,由于 SSP.__init__() 中存在默认值,因此出现了问题。但是,当我粘贴您的示例代码时,它会在 try_at_random if (S[n-1] > sum): TypeError: unorderable types: int() > builtin_function_or_method() 中抛出异常第 41 行,我猜“总和”应该是是总和(某事)?
标签: python dynamic-programming subset-sum