Python itertools.product

digits = [str(i) for i in range(10)]
class Solution:
def convert_baseK_to_base10(self, s, k):
convert a base k number to base 10 number
ret = 0
for c in s:
ret *= k
ret += int(c)
return ret

def is_mirror_base10_number(self, s):
check whether this base 10 number in string is a mirror number
k = len(s) // 2
return len(s) == 1 or s[:k] == s[-k:][::-1]

def get_this_length_ret(self, length_, k):
Get the base k number with lenght of length_
if length_ == 1:return list(range(1, k))
# construct all possible candidates for left mirror, then the right will be the reverse of the candidate.
left = ("".join(candidate) for candidate in list(itertools.product(digits[:k], repeat = length_ // 2)))

if length_ % 2 == 0:
ret = [element + element[::-1] for element in left]
ret = [element + str(i) + element[::-1] for element in left
for i in range(k)]
# check whether base k is valid
ret = [self.convert_baseK_to_base10(element, k) for element in ret
if element[0] != "0"]
# check whether base 10 is valid
ret = [element for element in ret
if self.is_mirror_base10_number(str(element))]
return ret

def kMirror(self, k: int, n: int) -> int:
ret = []
# construct number with a specified length.
for length_ in range(1, 1000000):
ret += self.get_this_length_ret(length_, k)
if len(ret) >= n:
return sum(sorted(ret)[:n])




Data Scientist/MLE/SWE @takemobi

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Automate Excel tasks with Openpyxl and Python

Into Game Mechanics: Production Player Setup

AWS S3 MultiPart Upload with Python and Boto3

Internals Of Java Parallel Streams

Convert Multiple Line Python Code To a Single Line in 3 Seconds

Java Developer Job Description: Role and Duties

Implementing SSH tunnels in Elixir

Postmortem[Incident Report]

I dont use debuggers.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jimmy Shen

Jimmy Shen

Data Scientist/MLE/SWE @takemobi

More from Medium

Python: Arithmetic operations

Top 6 - PYTHON libraries You must know

Python Morsel — count_calls

5 Useful Python Libraries