如何让这个用于查找彩色数字的 Python 函数对任意数字进行运算?

问题描述 投票:0回答:1

彩色数字是指它的数字列表中没有重复的数字+它的数字子集的乘积。例如,263 的乘积为 [2, 6, 3, 2x6, 6x3, 2x6x3]。这些都是不同的数字,所以 263 是彩色的。

我编写了一些代码以允许最大长度为 3 的整数。它确实有效。它制作数字和子集的列表,然后将该列表转换为一个集合以删除重复项,然后将列表与集合进行比较。如果没有重复,长度将相同。

但是它应该针对任何长度的 int 进行缩放。它也远非简洁。我应该如何使其缩放并使其可读?

这是我的功能。它适用于长度不超过 3 的值。

def is_colorful(num):

    str_num = str(num)
    combos = []

    if len(str_num) == 1:

        x = int(str_num[0])

        combos.append(x)

    if len(str_num) == 2:

        x = int(str_num[0])
        y = int(str_num[1])

        combos.append(x)
        combos.append(y)
        combos.append(x*y)

    if len(str_num) == 3:

        x = int(str_num[0])
        y = int(str_num[1])
        z = int(str_num[2])
        
        combos.append(x)
        combos.append(y)
        combos.append(z)
        combos.append(x*y)
        combos.append(y*z)
        combos.append(x*y*z)

    set_combos = set(combos)
    print(set_combos)
    
    return True if len(set_combos) == len(combos) else False
python duplicates set append readability
1个回答
0
投票

这是一种扩展它的方法:

def is_colorful(num):
    # disqualify as colorful if:
    #    - there are multiple digits and one of them is 0 or 1
    #    - any digit is a duplicate
    n, prods = num, set()
    while n:
        digit = n % 10
        if prods and digit in (0,1) or digit in prods:
            return False
        n, prods = n // 10, prods | {digit}
    
    # disqualify as colorful if:
    #    - the product of the digits in any subset is a duplicate
    n, prods = num, set()
    while n:
        digit, curProds = n % 10, set()
        for prd in (p * digit for p in (f for group in (prods, [1]) for f in group)):
            if prd in prods:
                return False
            curProds.add(prd)
        n, prods = n // 10, prods | curProds
    return True

top = 1
while top <= 10_000_000:
    colorful = []
    for i in range(top):
        if is_colorful(i):
            colorful.append(i)
    print(f'for 0 to {top}, ', 
        f'the count of colorful numbers is {len(colorful)}), ',
        f'percent = {100 * len(colorful) / top}%')
    top *= 10

输出:

for 0 to 1, the count of colorful numbers is 1, percent = 100.0%
for 0 to 10, the count of colorful numbers is 10, percent = 100.0%
for 0 to 100, the count of colorful numbers is 74, percent = 74.0%
for 0 to 1000, the count of colorful numbers is 454, percent = 45.4%
for 0 to 10000, the count of colorful numbers is 2194, percent = 21.94%
for 0 to 100000, the count of colorful numbers is 7690, percent = 7.69%
for 0 to 1000000, the count of colorful numbers is 17530, percent = 1.753%
for 0 to 10000000, the count of colorful numbers is 23290, percent = 0.2329%
© www.soinside.com 2019 - 2024. All rights reserved.