"""
k-best解決的問題:
n個珠寶價值vi和重量wi;求保留k個珠寶的單位價值最大化
n,vi,wi 值域。。。
"""def
k_best
(v_ls,w_ls,k)
: l,r =
0.0,
1e5#maximun 10,0000
while
abs(r-l)
>1e-
6:mid =
(l + r)
/2.0
vw_ls =
[v - mid * w for v,w in
zip(v_ls, w_ls)
] choose =
list
(range
(len
(v_ls)))
for jj in
range
(k):
#乙個bug,序號會亂,因為排序後不;
for i in
range
(jj+1,
len(v_ls)):
if vw_ls[jj]
< vw_ls[i]
: vw_ls[jj]
, vw_ls[i]
= vw_ls[i]
, vw_ls[jj]
choose[jj]
, choose[i]
= choose[i]
, choose[jj]
sk =
sum(vw_ls[
0:k]
)if sk <0:
r = mid
else
: l = mid
return choose, mid
""" choose =
for jj in range(k): #乙個bug,不應該設定為前幾個的;
c = 0
for i in range(jj+1,len(v_ls)):
if vw_ls[jj] < vw_ls[i]:
vw_ls[jj], vw_ls[i] = vw_ls[i], vw_ls[jj]
c = i
"""if __name__ ==
"__main__"
:# n,k = input("輸入珠寶數目n,待選數目k:")
# v_ls =
# w_ls =
# for i in range(int(n)):
# v,w = input("輸入珠寶價值,重量" ).split(',')#, input()
v_ls =[3
,40,1.5,10
,8] w_ls =[1
,20,1
,5,4
] k =
3print
("list : "
, v_ls, w_ls)
chose, mid = k_best(v_ls,w_ls, k)
print
(chose,
" value: "
, mid)
print
("\nchoose k: "
)for i in
range
(k):
print
(v_ls[chose[i]
], w_ls[chose[i]
])
list : [3, 40, 1.5, 10, 8] [1, 20, 1, 5, 4]
[0, 4, 3, 1, 2] value: 2.1000007109250873
choose k:
3 18 4
10 5
python 演算法 小試牛刀
1.列印從1到100,碰到3倍數用fizz代替,碰到5倍數,用buzz代替,3和5的倍數,fizzbuzz代替 def func for i in range 1,101 if i 3 0 i 5 0 print fizzbuzz elif i 3 0 print fizz elif i 5 0 p...
Python小試牛刀 迴圈
斐波那契數列,數列前兩項為1,之後每一項都是前兩項之和。usr bin env python3 a,b 0,1 while b 100 print b a,b b,a b預設print輸出結果後會自動換行,如果不希望換行,只做間隔的話,就通過另乙個引數end來替換這個換行符 print a,end ...
boost graph lib 小試牛刀
最近要做社會網路的社群發現,發現用bgl能減少不少 量。經過一番調研發現bgl封裝的很牛叉,dijkstra等演算法統統具備,奈何自己對泛型程式設計不太熟,遇到問題還是很糾結。primer泛型程式設計 演算法部分和stl原始碼分析接下來有時間一定要讀下。下面僅以鄰接鍊錶和自定義節點為例 typede...