为什么我的代码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)发布于 2017-01-06 10:02:56
我不认为是在你的方法try_at_random(
“,您是指”
”(return instance.try_at_random(S,n-1,t)或instance.try_at_random(S,n-1,t-Sn-1))时,你想要什么?如果您在返回之前执行一条print语句,看看它的值是什么,会得到什么结果。我知道您试图递归地调用它,但是在不使用"self.try_at_random“和返回"or”语句之间,我不确定这是在做什么。
祝好运!
https://stackoverflow.com/questions/41497332
复制相似问题