帮我用python翻译如下代码:#include<stdio.h> int max(double* a,int n) { int rmax=0; for(int i=1;i<n;i++) { if(a[i]>a[rmax]) { rmax=i; } } return rmax; } int main() { int M,n; scanf("%d",&M); scanf("%d",&n); int w[100000];//商品重量 int p[100000];//商品效益 double a[100000]; //单位重量的商品效益 double answer[100000]; float cost=0; for(int i=0;i<n;i++) { scanf("%d",&w[i]); } for(int i=0;i<n;i++) { scanf("%d",&p[i]); } for(int i=0;i<n;i++) { a[i]=(double)p[i]/w[i]; } int j; for(int i=0;i<n;i++) { j=max(a,n); if(w[j]<=M) { answer[j]=1; cost+=p[j]; a[j]=0; M=M-w[j]; } else break; } answer[j]=(double)M/w[j]; cost+=answer[j]*p[j]; printf("%g\n",cost); for(int i=0;i<n-1;i++) { printf("%.2lf ",answer[i]); } printf("%.2lf",answer[n-1]); return 0; }
时间: 2024-03-07 18:50:46 浏览: 69
用python实现百度翻译的示例代码
这是一段C语言代码,主要实现了一个背包问题的解决方案。下面是Python代码的翻译:
```python
def find_max(a, n):
rmax = 0
for i in range(1, n):
if a[i] > a[rmax]:
rmax = i
return rmax
M = int(input()) # 背包容量
n = int(input()) # 商品数量
w = [] # 商品重量
p = [] # 商品效益
a = [] # 单位重量的商品效益
answer = [0] * n # 商品选择情况
cost = 0 # 花费
for i in range(n):
w.append(int(input()))
for i in range(n):
p.append(int(input()))
for i in range(n):
a.append(p[i] / w[i])
j = 0
for i in range(n):
j = find_max(a, n)
if w[j] <= M:
answer[j] = 1
cost += p[j]
a[j] = 0
M = M - w[j]
else:
break
answer[j] = M / w[j]
cost += answer[j] * p[j]
print(cost)
print(" ".join([str("%.2f" % answer[i]) for i in range(n)]))
```
阅读全文