Skip to content

Commit 6e69208

Browse files
Hyftarcclauss
authored andcommitted
Add problem 32 solution (TheAlgorithms#1257)
1 parent d28fc71 commit 6e69208

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

project_euler/problem_32/solution.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
We shall say that an n-digit number is pandigital if it makes use of all the
3+
digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through
4+
5 pandigital.
5+
6+
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing
7+
multiplicand, multiplier, and product is 1 through 9 pandigital.
8+
9+
Find the sum of all products whose multiplicand/multiplier/product identity can
10+
be written as a 1 through 9 pandigital.
11+
12+
HINT: Some products can be obtained in more than one way so be sure to only
13+
include it once in your sum.
14+
"""
15+
import itertools
16+
17+
18+
def isCombinationValid(combination):
19+
"""
20+
Checks if a combination (a tuple of 9 digits)
21+
is a valid product equation.
22+
23+
>>> isCombinationValid(('3', '9', '1', '8', '6', '7', '2', '5', '4'))
24+
True
25+
26+
>>> isCombinationValid(('1', '2', '3', '4', '5', '6', '7', '8', '9'))
27+
False
28+
29+
"""
30+
return (
31+
int(''.join(combination[0:2])) *
32+
int(''.join(combination[2:5])) ==
33+
int(''.join(combination[5:9]))
34+
) or (
35+
int(''.join(combination[0])) *
36+
int(''.join(combination[1:5])) ==
37+
int(''.join(combination[5:9]))
38+
)
39+
40+
41+
def solution():
42+
"""
43+
Finds the sum of all products whose multiplicand/multiplier/product identity
44+
can be written as a 1 through 9 pandigital
45+
46+
>>> solution()
47+
45228
48+
"""
49+
50+
return sum(
51+
set(
52+
[
53+
int(''.join(pandigital[5:9]))
54+
for pandigital
55+
in itertools.permutations('123456789')
56+
if isCombinationValid(pandigital)
57+
]
58+
)
59+
)
60+
61+
if __name__ == "__main__":
62+
print(solution())

0 commit comments

Comments
 (0)