1

I'm new to Python and been trying to solve this problem. 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. 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.

import random as rd

N=50

ar1 = [rd.randint(100, 999) for i in range(N)]
ddnn5
  • 21
  • 3
  • 1
    Judging by the answers, I don't think you've made the question very clear. It would help if you showed the result you are hoping for. – Mark Oct 12 '20 at 17:13
  • 1
    There is only 45 values where in `abc` you have `a!=0` and `a+b=c` – azro Oct 12 '20 at 17:16

1 Answers1

0

Attention

There is only 45 different 3-digits numbers abc you have a!=0 and a+b=c.

The following solution uses a limit fo tries to avoid infinite loop in case you ask too many


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)

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}
azro
  • 53,056
  • 7
  • 34
  • 70
  • your explanation was very helpful but I want the result to be as numbers and not as sets – ddnn5 Oct 12 '20 at 17:21
  • @ddnn5 read again at the top, there is only 45 different values – azro Oct 12 '20 at 17:21
  • @ddnn5 Sidenote: they're tuples, not sets. Sets are unordered. – wjandrea Oct 12 '20 at 17:23
  • I think i'm not explaining well. result that you've got is what I was looking for. I just want them to be outputed as 3-digit numbers in a list – ddnn5 Oct 12 '20 at 17:29
  • @ddnn5 that's what you have, you have not a list, but not a set, that's the same use, or just do `return list(result)` in the method – azro Oct 12 '20 at 17:30
  • @ddnn5 If the answer satistifies you, you can [accept an answer](https://stackoverflow.com/help/someone-answers) – azro Oct 12 '20 at 17:57