数字分组求偶数和| 豆包MarsCode AI刷题

112 阅读2分钟

首先我们来读题:
小M面对一组从 1 到 9 的数字,这些数字被分成多个小组,
并从每个小组中选择一个数字组成一个新的数。
目标是使得这个新数的各位数字之和为偶数。
任务是计算出有多少种不同的分组和选择方法可以达到这一目标。

  • numbers: 一个由多个整数字符串组成的列表,每个字符串可以视为一个数字组。小M需要从每个数字组中选择一个数字。

例如对于[123, 456, 789],14个符合条件的数为:147 149 158 167 169 248 257 259 268 347 349 358 367 369
-----------------------------读题完毕-----------------------------

思路:
挑选包含偶数(含0)个奇数的组合,计算总方法就可以得到最终答案
为了挑选符合条件的组合,需要使用组合的代码

这道题如果用python写会比较容易
因为python有自带库itertools
其中有排列函数permutations(iterable, r)与组合函数combinations(iterable, r)
其中,
iterable表示要生成组合的可迭代对象,例如列表、元组等。
r表示每个组合中元素的数量。

这两个函数分别可以返回排列类型或组合类型迭代器
可以通过循环依次遍历其中的排列或组合元素

本题用到的是combinations(iterable, r)
它可以创建一个迭代器,返回iterable中所有长度为r的子序列,
返回的子序列中的项按输入iterable中的顺序排序。

通过本题可以看到,排列组合使用python自带库itertools中的
permutations(iterable, r)和combinations(iterable, r)会非常方便,
不需要自己写排列或组合算法就可以实现全排列、组合类型问题。

下面是参考代码~

from itertools import *

def solution(numbers):
    l=len(numbers)
    x=[[0]*2 for i in range(l)]
    for i in range(len(numbers)):
        for j in str(numbers[i]):
            j=int(j)
            if j%2==0:
                x[i][0]+=1#偶数
            else:
                x[i][1]+=1
    print(x)
    ans=0
    ou=[]
    ji=[]
    for i in range(len(numbers)):
        #ans*=x[i][0]
        if x[i][0]>0:
            ou.append(i)
        if x[i][1]>0:
            ji.append(i)
    print(ou,ji)
    for i in range(0,len(ji)+1,2):
        for k1 in combinations(ji,i):
            print('k1',k1)
            ounew=ou[::]
            temp1=1
            for j in k1:
                temp1*=x[j][1]
                if j in ounew:
                    ounew.remove(j)
            for k2 in combinations(ounew,l-i):
                print('k2',k2)
                temp2=1
                for q in k2:
                    temp2*=x[q][0]
                ans+=temp1*temp2
                print('ans',ans)
    print(ans)
    return ans
    


if __name__ == "__main__":
    #  You can add more test cases here
    print(solution([123, 456, 789]) == 14)
    print(solution([123456789]) == 4)
    print(solution([14329, 7568]) == 10)