我如何找到这道数学题的答案?

2024-04-27 16:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一道关于排列的数学题的帮助。任务是:

How many four-digit even numbers are there where no digit appears more than once.

我走了这么远:

   gerade = set()
   for c in range(1000,9999):
       for d in str(c):
           if int(d) %2 !=0:
               gerade.add(c)
           if 
               break
        print (c)

Tags: noinforifwherearemanyhow
2条回答
  1. 要只生成偶数,只需使用2步骤

    for c in range(1000, 9999, 2)
    
  2. 然后到count unique digits您可以使用set并检查长度,如果它们相同,则保留值

    gerade = set()
    for c in range(1000, 9999, 2):
        if len(str(c)) == len(set(str(c))):
            gerade.add(c)
    

我们也可以用数学来解决这个问题,而不用检查所有可能的数字(一种蛮力,不适用于更大范围)

我们可以从5个变体(偶数)中选择第四个数字
我们可以从9个变体中选择第三个数字(不包括使用过的数字)
我们可以从8个变体中选择第二个数字(不包括使用过的数字)
我们可以从7个变体中选择第一个数字(不包括使用过的数字)

所以我们有5*9*8*7 = 2520不同数字的变体。
但有些是三位数,因为第一位是零。我们必须排除他们。
4*8*7 = 224这样的数字,最终结果是:

  2296 variants = 2520 - 224

相关问题 更多 >