Derpyninja
Derpyninja

Reputation: 35

Multiplying random numbers in list in python

Ok so i need to multiple 50 numbers that were randomly generated, between 5 and 70, and put in a list. I am able to create the list of numbers but dont know how to.

Example-If the list generates the numbers [10, 12, 3] the answer would be 360 as 10*12*3 = 360

This is the code i am working with.

 import random
 talnalisti = []
 for x in range(50):
     tala = random.randint(5, 70)
     talnalisti.append(tala)
 print(talnalisti)
 print("Stærsta talan er", max(talnalisti))
 print("Minsta talan er", min(talnalisti))

Upvotes: 0

Views: 1946

Answers (4)

Abdirahman
Abdirahman

Reputation: 180

No complex code needed to get the product of list elements, try this:

    product = 1 # to get first element unchanged

    for element in talnalisti:
        product = product*element

    print(product)

Tested, printed something like: 98135262633757341182160114591148916792761926172600487116800000000000000000

Upvotes: 0

ashemag
ashemag

Reputation: 86

You can keep track of the product of each number you add to the list.

import random
talnalisti = []
result = 1
for x in range(50):
    tala = random.randint(5, 70)
    result *= tala
    talnalisti.append(tala)
print(talnalisti)
print("Product of list is ", result)
print("Stærsta talan er", max(talnalisti))
print("Minsta talan er", min(talnalisti))

Upvotes: 0

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6920

Try this:

import random
from functools import reduce
talnalisti = []
for x in range(50):
    tala = random.randint(5, 70)
    talnalisti.append(tala)
product_ = reduce((lambda x, y: x * y), talnalisti)
print(f"Multiplying all of {talnalisti}, we get {product_}")

Output :

Multiplying all of [20, 35, 19, 34, 10, 15, 33, 60, 22, 35, 12, 66, 14, 48, 5, 59, 9, 5, 8, 22, 65, 32, 17, 24, 58, 47, 8, 14, 24, 44, 62, 58, 29, 9, 53, 59, 6, 35, 49, 29, 51, 6, 15, 37, 43, 31, 64, 65, 35, 9], we get 9141144262078455405304024709785603282981464013901848903680000000000000

Upvotes: 0

Ruben
Ruben

Reputation: 38

You could declare a variable beforehand and directly multiply the newly generated random number to it.

import random
talnalisti = []
res = 1
for x in range(50):
    tala = random.randint(5, 70)
    talnalisti.append(tala)
    res *= tala

Or you could use a normal for-loop to loop over the elements afterwards.

res = 1
for x in talnalisti:
    res *= x

Keep in mind that there are many other and more sophisticated solutions.

Upvotes: 1

Related Questions