蓝桥杯-2023(python)

1.问题描述

请求出在 12345678 至 98765432 中,有多少个数中完全不包含 2023 。 完全不包含 2023 是指无论将这个数的哪些数位移除都不能得到 2023 。 例如 20322175,33220022 都完全不包含 2023,而 20230415,20193213 则 含有 2023 (后者取第 1, 2, 6, 8 个数位) 。

2.python实现

        直接暴力枚举即可,可以先得出完全包含‘2023’的个数,再相减得出完全不包含‘2023’的个数(完全包含和完全不包含属于对立事件)。主要利用combinations函数实现,为了缩短运行时间,利用if语句先进行判断其数字是否包含‘2’,‘0’,‘3’这三个数字(其中数字‘2’至少出现两次)。

答案:85959030

from itertools import combinations

ans=0
for i in range(12345678,98765433):
    if str(i).count('2')>=2 and str(i).count('0')!=0 and str(i).count('3')!=0:
        for j in combinations(str(i),4):
            if ''.join(j)=='2023':
                ans+=1
                break
print(98765433-12345678-ans)

猜你喜欢

转载自blog.csdn.net/m0_62428181/article/details/130448708