学习python,看到一个有趣的题目,就练习了一下

0到9的10个数,要求组成两个5位数a和b,构成a和b中的数字不重复,并且 a + 20085 = b

代码实现,随手写的不是很规范

n = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 20085


def validate(num: int):
    total = num + k

    if total > 99999:
        return False

    s = list(str(total)+str(num))

    for i in range(0, 5):
        a = s[i]

        if s.count(a) > 1:
            return False

    return True


def cal(base: int, num_list: list, digit: int):

    for t in range(0, len(num_list)):
        result = base
        num_list_copy = num_list.copy()
        num = num_list_copy[t]

        if (num == 0 or num*math.pow(10, digit) + k > 99999) and digit == 4:
            continue

        num_list_copy.remove(num)

        result += num * int(math.pow(10, digit))

        if digit == 0:
            if validate(result):
                print(result + k, result)
        else:
            cal(result, num_list_copy, digit - 1)

cal(0, n, 4)

运行的结果是:

35067,14982
48036,27951
58026,37941
62058,41973
72048,51963
85017,64932

你可能感兴趣的:(Python)