简体   繁体   English

如何使用三位数字创建列表,其中第一位数字+第二位数字=第三位数字

[英]How to create list with 3- digit numbers which first digit + second digit = third digit

I'm new to Python and been trying to solve this problem.我是 Python 新手,一直在努力解决这个问题。 I want to create list of 3 - digit numbers in which first digit + second digit = third digit and if sum of first two digits is greater than 9 I want the third digit of that number to be second digit of the sum.我想创建三位数字列表,其中first digit + second digit = third digit ,如果前两位数字的总和大于 9,我希望该数字的第三位数字是总和的第二位数字。 eg.例如。 583 where 5+8=13 so the last digit will be 3. I want to have 50 3-digit numbers like that this is what I've got so far. 583 其中 5+8=13 所以最后一位数字是 3。我想要 50 个这样的 3 位数字,这就是我到目前为止所得到的。

import random as rd

N=50

ar1 = [rd.randint(100, 999) for i in range(N)]

Attention注意力

There is only 45 different 3-digits numbers abc you have a!=0 and a+b=c .只有45 个不同的 3 位数字abc你有a!=0a+b=c

The following solution uses a limit fo tries to avoid infinite loop in case you ask too many以下解决方案使用限制fo 尝试避免无限循环,以防您问太多


To generate one number that follows your rule, you need to generate 2 digits, then check if their sum is lower than 10 (to be one digit)要生成一个符合您规则的数字,您需要生成 2 位数字,然后检查它们的总和是否小于 10(为一位数)

a, b = randrange(1, 10), randrange(10)
if a + b < 10:
    # you have the tuple (a, b, a + b)

Then use a loop to go until you reach your limit然后循环使用直到达到极限

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

You'll obtain a list您将获得一份清单

{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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM