如何创建包含 3 位数字的列表,其中第一个数字 + 第二个数字 = 第三个数字
How to create list with 3- digit numbers which first digit + second digit = third digit
我是 Python 的新手,一直在努力解决这个问题。
我想创建 3 位数字的列表,其中 first digit + second digit = third digit
并且如果前两位数字的总和大于 9,我希望该数字的第三位数字是总和的第二位数字。例如。 583 其中 5+8=13 所以最后一位数字是 3。我想要 50 个这样的 3 位数字
这就是我到目前为止所得到的。
import random as rd
N=50
ar1 = [rd.randint(100, 999) for i in range(N)]
关注
只有 45 个不同的 3 位数 abc
你有 a!=0
和 a+b=c
.
以下解决方案使用 limit fo 试图避免无限循环,以防你问得太多
要生成一个符合您规则的数字,您需要生成 2 位数字,然后检查它们的总和是否小于 10(为一位数)
a, b = randrange(1, 10), randrange(10)
if a + b < 10:
# you have the tuple (a, b, a + b)
然后循环使用直到达到你的极限
def generate(N=50, tries=1000):
result = set()
while len(result) != N and tries > 0:
tries -= 1
a, b = randrange(1, 10), randrange(10)
if a + b < 10:
result.add(int("".join(map(str, (a, b, a + b)))))
return result
您将获得一个列表
{257, 516, 134, 268, 909, 527, 145, 404, 279, 538, 156, 415, 549, 167, 808, 426, 303,
178, 819, 437, 314, 189, 448, 707, 325, 202, 459, 718, 336, 213, 729, 347, 606, 224,
101, 358, 617, 235, 112, 369, 628, 246, 505, 123, 639}
我是 Python 的新手,一直在努力解决这个问题。
我想创建 3 位数字的列表,其中 first digit + second digit = third digit
并且如果前两位数字的总和大于 9,我希望该数字的第三位数字是总和的第二位数字。例如。 583 其中 5+8=13 所以最后一位数字是 3。我想要 50 个这样的 3 位数字
这就是我到目前为止所得到的。
import random as rd
N=50
ar1 = [rd.randint(100, 999) for i in range(N)]
关注
只有 45 个不同的 3 位数 abc
你有 a!=0
和 a+b=c
.
以下解决方案使用 limit fo 试图避免无限循环,以防你问得太多
要生成一个符合您规则的数字,您需要生成 2 位数字,然后检查它们的总和是否小于 10(为一位数)
a, b = randrange(1, 10), randrange(10)
if a + b < 10:
# you have the tuple (a, b, a + b)
然后循环使用直到达到你的极限
def generate(N=50, tries=1000):
result = set()
while len(result) != N and tries > 0:
tries -= 1
a, b = randrange(1, 10), randrange(10)
if a + b < 10:
result.add(int("".join(map(str, (a, b, a + b)))))
return result
您将获得一个列表
{257, 516, 134, 268, 909, 527, 145, 404, 279, 538, 156, 415, 549, 167, 808, 426, 303,
178, 819, 437, 314, 189, 448, 707, 325, 202, 459, 718, 336, 213, 729, 347, 606, 224,
101, 358, 617, 235, 112, 369, 628, 246, 505, 123, 639}