Generate random numbers and add them up

Asked

Viewed 1,471 times

0

I wish I could make the script generate "n" numbers(so far everything is done as you can see in the code below) and add them up.

import random

n = 2

total = (random.randint(1, 100), n)

print total

Now all that remains is to add up these "n" numbers.

4 answers

3

To generate n random numbers, use generators:

numbers = (random.randint(1, 100) for _ in range(n))

Note: If the number list is used for more than just calculating the sum, do not use generator, but yes comprehensilist on (just change of () for []):

numbers = [random.randint(1, 100) for _ in range(n)]

Where n is the amount of numbers to be generated. Note that print(numbers), the exit will be:

<generator object <genexpr> at ...>

That is, the list itself has not yet been generated. Even so, to get the sum of the values, just use the native function sum:

total = sum(numbers)

Making print(total), an integer value referring to the sum of all numbers is displayed. In my case, the total was 300.

See working on Ideone.

  • random.sample(range(x), x-y) also serves if you don’t want duplicates

1


That’s what you need?

import random

n = 2

total = random.randint(1, 100) + n

print total

If you need to randomize more than 1 number and add up all the generated numbers, you can do so:

import random

total = 0;

for i in xrange(0, 2):
    numeroGerado = random.randint(1, 100)
    print numeroGerado
    total += numeroGerado

print total
  • 3

    What is the logic in adding up the value of n with the random number in the first code?

0

If you wish only somar the numbers that were generated randomly, you can use the following algorithm...

from random import randint

n = int(input('Desejas gerar quantos números aleatórios? '))
numeros = [randint(1, 100) for _ in range(n)]
soma = sum(numeros)
print(f'\033[32mA soma dos {n} números aleatórios gerados é: {soma}\033[m')

See how the algorithm works on repl it..

Now, if you want to perform the sum of values generated randomly and without repetições you can use the following algorithm...

from random import sample

n = int(input('Desejas gerar quantos números aleatórios? '))
numeros = sample(range(1, 100), n)
soma = sum(numeros)
print(f'\033[32mA soma dos {n} números aleatórios gerados é: {soma}\033[m')

See how the algorithm works on repl it..

Note that the method sample class random, draws without repetitions.

-1

import random

n = 2

total = (random.randint(1, 100), n)

a=str(total).split(",")[0].split("(")[1]
b=str(total).split(",")[1].split(")")[0]

soma=int(a) + int(b)

print soma

Browser other questions tagged

You are not signed in. Login or sign up in order to post.