defselect_activities(activities, n): activities = sorted(activities, key=lambda x: x[2]) result = [] end = -1 i = 0 while i != n: begin = activities[i][1] if begin >= end: result.append(activities[i][0]) end = activities[i][2] print(f"choose activity {activities[i][0]} which begins at {activities[i][1]} and ends at {activities[i][2]}") i += 1 return result
defpartial_knapsack(items, capacity, n): # items(名称,价值,重量),计算得到性价比(名称,性价比,重量) v_per_w = [[0, 0, 0] for _ inrange(n)] for i inrange(n): v_per_w[i][0] = items[i][0] v_per_w[i][1] = float(items[i][1] / items[i][2]) v_per_w[i][2] = items[i][2] # 按照性价比降序排序 v_per_w.sort(key=lambda x: x[1], reverse=True) total = 0 # 一直拿整份性价比最高的,直到背包容量不够只能拿部分 for i inrange(n): if v_per_w[i][2] <= capacity: value = v_per_w[i][1] * v_per_w[i][2] total += value capacity -= v_per_w[i][2] print(f"Take full {v_per_w[i][0]}: weight = {v_per_w[i][2]}, value per weight = {v_per_w[i][1]:.2f}, value = {value}") else: value = v_per_w[i][1] * capacity total += value print(f"Take partial {v_per_w[i][0]}: weight = {capacity}, value per weight = {v_per_w[i][1]:.2f}, value = {value}") break print(f"Total value in knapsack: {total:.2f}") return total