python:数组分组(★深度递归★)

(题目来自牛客网)

描述:
输入int型数组,询问该数组能否分成两组,使得两组中各元素加起来的和相等,并且,所有5的倍数必须在其中一个组中,所有3的倍数在另一个组中(不包括5的倍数),不是5的倍数也不是3的倍数能放在任意一组,可以将数组分为空数组,能满足以上条件,输出true;不满足时输出false。

输入描述:
第一行是数据个数,第二行是输入的数据

输出描述:
返回true或者false

示例:
输入:
4
1 5 -5 1
输出:
true

代码:

import math
def ad(five,three,other):
    if not other:
        if sum(five)==sum(three):
            return True
        else:
            return False
    else:
        return ad(five+other[:1],three,other[1:]) or ad(five,three+other[:1],other[1:])   #深度递归

while True:
    try:
        n,num=int(input()),list(map(int,input().split()))
        five,three,other=[],[],[]
        for i in num:
            if i%5==0 and math.fabs(i)>=5:
                five.append(i)
            elif i%3==0 and math.fabs(i)>=3:
                three.append(i)
            else:
                other.append(i)
        if ad(five,three,other):
            print('true')
        else:
            print('false')
    except:
        break          
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CHNfisher

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值