笔试编程题汇总(2)
程序员文章站
2024-03-19 22:06:46
...
"""
描述:给一个整数数组num, 和一个镇整数k, 能否把数组num切成k个子集,且各个子集的和相等,返回布尔类型
输入输出:
输入:一个整数数组num和一个正整数k
输出:返回true或者false,bool类型
样例:
输入:
[4,3,2,3,5,2,1];4
输出:
True
解释:可以分解为4个子集,他们的和都是5
"""
import sys
def find_value(num, value):
for idx, data in enumerate(num):
if data<=value:
num = num[:idx] + num[idx+1:]
return value-data, num, True
return value, num, False
def check_num(num, k):
if k==1:
return True
num_sum = int(sum(num))
mean_value = int(num_sum/k)
if not (mean_value*k % num_sum == 0):
return False
value = mean_value
while len(num)>0:
value, num,rtn = find_value(num, value)
#rtn, num = sub_list(num, mean_value)
if not rtn:
return False
if value == 0:
value = mean_value
return True
if __name__=="__main__":
line = sys.stdin.readline().strip()
num_str, k = line.split(";")
num = eval(num_str)
num = [int(data) for data in num]
k = int(k)
print(check_num(num, k))