# 2021年6月22日,vivo 2022届提前批 数据挖掘 一面

·  阅读 85

## 1.输入一个数组，统计数组中有多少个数是7的倍数或者含有数字7

``````def get_num_1(nums):
res = 0
for i in nums:
if i % 7 ==0 or str(i).find('7') != -1:
res +=1
return res
nums = [7,21,34,777,666,888,63]
print(get_num_1(nums))

def get_num_2(nums):
res = 0
for i in nums:
if i % 7 ==0 or '7' in str(i):
res +=1
return res
nums = [7,21,34,777,666,888,63]
print(get_num_2(nums))

2.背包问题

## 2.0-1背包问题

c(i, w) 表示包容量为w时，考虑前i个物品所能获得的最大价值。。 i表示第i个物品，w表示包容量

``````#  01 背包问题
def bag_01(weights, values, capicity):

# [*, *, *, *, *, *, *, *, *, *, *, *]
# [*, *, *, *, *, *, *, *, *, *, *, *]
# [*, *, *, *, *, *, *, *, *, *, *, *]
# [*, *, *, *, *, *, *, *, *, *, *, *]
# [*, *, *, *, *, *, *, *, *, *, *, *]
# [*, *, *, *, *, *, *, *, *, *, *, *]
n = len(values)
f = [[0 for j in range(capicity+1)] for i in range(n+1)]
for i in range(1, n+1):
for j in range(1, capicity+1):
f[i][j] = f[i-1][j]
if j >= weights[i-1] and f[i][j] < f[i-1][j-weights[i-1]] + values[i-1]:
f[i][j] = f[i-1][j-weights[i-1]] + values[i-1]
return f

def show(capicity, weights, f):
n = len(weights)
print("最大价值:", f[n][capicity])
x = [False for i in range(n)]
j = capicity
for i in range(n, 0, -1):
if f[i][j] > f[i-1][j]:
x[i-1] = True
j -= weights[i-1]
print("背包中所装物品为:")
for i in range(n):
if x[i]:
print("第{}个".format(i+1))

if __name__ == '__main__':
# weights 指的是物品的重量
# values 指的是物品的价值
# capicity 指的是袋子能装的重量
n = 5
weights = [1, 2, 5, 6, 7]
values = [1, 6, 18, 22, 28]
capicity = 11
m = bag_01(weights, values, capicity)
# 打印矩阵
for i in range(len(m)):
print(m[i])

# 接下来输出要装的物品
show(capicity, weights, m)