扫码关注官方订阅号
面试题,求解答
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...
都确定是3个整数了……直接三重循环枚举啊…………
如同 @xiaoboost 說的, 使用簡單的暴力法就可以做出來:
import itertools def nsum(lst, n, target): count = 0 for c in itertools.combinations(lst, n): if sum(c) == target: count += 1 return count if __name__ == '__main__': lst = [-1, 3, -2, 7, -4, -3, 6, 9, -2, -2, 1, 1, 0, 10, -1, 9, 8, -12] print(nsum(lst, 3, 0))
結果:
22
我回答過的問題: Python-QA
from itertools import combinations def sum_is_sth(lst, sth=0, cnt=3): return sum([1 for sub_lst in combinations(lst, cnt) if sum(sub_lst) == sth])
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
都确定是3个整数了……直接三重循环枚举啊…………
如同 @xiaoboost 說的, 使用簡單的暴力法就可以做出來:
結果:
我回答過的問題: Python-QA