蛮力法算法python

时间:2019-10-02 08:12:29

标签: python

我想使用蛮力法获得所有可能组合的集合的加法,并获得给定数的最高模量值。

找到模数的给定数字为n:7

例如:

I / P:

[[1,2,3,4],[3,4],[1,3,8,4,9]]

O / P:

1+3+1 = 5
1+3+3 = 8
1+3+8 = 12
.
.
1+4+1 = 6
1+4+3 = 8
.
.
2+3+1 = 6
2+3+3 = 8
.
.

所有可能的组合

预期的O / P:

1+4+1 = 6
6%7 = 6

该集合中可以达到的最高模数为6(n-1)

3 个答案:

答案 0 :(得分:1)

简单的暴力破解:

my_list = [[1,2,3,4],[3,4],[1,3,8,4,9]]

highest_modulus = 0
for i in my_list[0]:
    for j in my_list[1]:
        for k in my_list[2]:
            res = i + j + k
            print(f"{i}+{j}+{k} = {res}")
            if res % 7 > highest_modulus:
                highest_modulus = res

print(f"{highest_modulus}%7 = {highest_modulus % 7}")

输出:

1+3+1 = 5
1+3+3 = 7
1+3+8 = 12
1+3+4 = 8
1+3+9 = 13
1+4+1 = 6
1+4+3 = 8
1+4+8 = 13
1+4+4 = 9
1+4+9 = 14
2+3+1 = 6
2+3+3 = 8
2+3+8 = 13
2+3+4 = 9
2+3+9 = 14
2+4+1 = 7
2+4+3 = 9
2+4+8 = 14
2+4+4 = 10
2+4+9 = 15
3+3+1 = 7
3+3+3 = 9
3+3+8 = 14
3+3+4 = 10
3+3+9 = 15
3+4+1 = 8
3+4+3 = 10
3+4+8 = 15
3+4+4 = 11
3+4+9 = 16
4+3+1 = 8
4+3+3 = 10
4+3+8 = 15
4+3+4 = 11
4+3+9 = 16
4+4+1 = 9
4+4+3 = 11
4+4+8 = 16
4+4+4 = 12
4+4+9 = 17
13%7 = 6

答案 1 :(得分:0)

在获得每个列表的长度并将其用作计数之后,可以通过for循环来完成。

list1 = [[1,2,3,4],[3,4],[1,3,4,8,9]]
length1 = len(list1[0])
length2 = len(list1[1])
length3 = len(list1[2])

for a in range(0,length1):
    for b in range(0,length2):
        for c in range(0,length3):
            print(list1[0][a] + list1[1][b] + list1[2][c])

这是每个子列表的长度,然后遍历该长度并打印结果。

然后要对答案取模并找到最大模数,您需要将其放在第三个for循环内,又名:

max = 0 #this should be outside all of the for loops

        for c in range(0,length3):
            result = list1[0][a] + list1[1][b] + list1[2][c]
            if result % 7 > max:
                max = result % 7

答案 2 :(得分:0)

您可以从itertools软件包中使用product

from itertools import product

z = [[1,2,3,4],[3,4],[1,3,8,4,9]]

list(map(lambda x: '{}+{}+{} = {}'.format(*x, sum(x)), product(*z)))
# returns:
['1+3+1 = 5',
 '1+3+3 = 7',
 '1+3+8 = 12',
 '1+3+4 = 8',
 '1+3+9 = 13',
 '1+4+1 = 6',
 '1+4+3 = 8',
 '1+4+8 = 13',
 '1+4+4 = 9',
 '1+4+9 = 14',
 '2+3+1 = 6',
 '2+3+3 = 8',
 '2+3+8 = 13',
 '2+3+4 = 9',
 '2+3+9 = 14',
 '2+4+1 = 7',
 '2+4+3 = 9',
 '2+4+8 = 14',
 '2+4+4 = 10',
 '2+4+9 = 15',
 '3+3+1 = 7',
 '3+3+3 = 9',
 '3+3+8 = 14',
 '3+3+4 = 10',
 '3+3+9 = 15',
 '3+4+1 = 8',
 '3+4+3 = 10',
 '3+4+8 = 15',
 '3+4+4 = 11',
 '3+4+9 = 16',
 '4+3+1 = 8',
 '4+3+3 = 10',
 '4+3+8 = 15',
 '4+3+4 = 11',
 '4+3+9 = 16',
 '4+4+1 = 9',
 '4+4+3 = 11',
 '4+4+8 = 16',
 '4+4+4 = 12',
 '4+4+9 = 17']
相关问题