安全代码
Safe Codes
题目详情
电子保险箱有一个三位数代码。关于保险箱密码,你会收到两个提示:
- 所有数字都不为零
- 各位数字之和不超过十
有多少可能的三位数条目满足这两个要求?
An electronic safe has a three digit code. You are given two hints regarding the code to the safe:
- None of the digits are zero
- The sum of the digits does not exceed ten
How many possible three digit entries satisfy these two requirements?
解析
让我们以第一位数字为条件来确定代码的数量。
如果我们的第一个数字是 ,则有 可能的代码(因为总和将超过非零数字的 )
如果我们的第一位数字是,那么剩下的数字之和只能是。完成此操作的唯一方法是剩余数字为 。
如果第一位数字是 ,则剩余的和可以是 或 。 与 的求和方式有多种(1+2 或 2+1),并且我们已经统计了与 求和的方式,如果我们的第一个数字是 ,则总共有 不同的组合
如果第一个数字是 ,我们只需要找到与 相加的有多少种方法,并将其与我们之前看到的 和 的组合相加。 有多种方法可以与 求和。现在,我们应该注意到一个模式。
如果我们的第一个数字是,就会有不同的组合。本质上,我们只是对前一个 三角数求和。
codes = []
for i in range(1, 10):
for j in range(1, 10):
for k in range(1, 10):
codes.append([i, j, k])
valid_codes = [code for code in codes if sum(code) <= 10]
print(len(valid_codes))Original Explanation
Let's condition the number of codes on the first digit.
If our first digit is , there are possible codes (as sum will exceed with non-zero digits)
If our first digit is , the remaining digits can only sum to . The only way to accomplish this is if the remaining digits are .
If the first digit is , the remaining sum can be or . There are ways to sum to (1+2 or 2+1) and we have already counted the ways to sum to , resulting in a total of different combinations if our first digit is
If the first digit is we only need to find how many ways to sum to and add that with the combinations for and we've seen previously. There are ways to sum to . By now, we should notice a pattern.
If our first digit is , there will be different combinations. Essentially, we are just summing the first triangular numbers.
codes = []
for i in range(1, 10):
for j in range(1, 10):
for k in range(1, 10):
codes.append([i, j, k])
valid_codes = [code for code in codes if sum(code) <= 10]
print(len(valid_codes))