Как найти произведение всех элементов списка python

Я приведу не очень практичное, но красивое решение в одну строку. Оно не использует eval, побочные эффекты при работе со списком или именованные функции.

Если именованные функции разрешены, то решение может выглядеть так:

def p(a):
    if a:
        return a[0] * p(a[1:])
    return 1

print(p([1, 2, 3, 4, 5]))

Нам оно не подходит, так именованная функция требует минимум две строки для определения и вызова. Лямбду можно определить и вызвать в одной строке, но есть трудность в создании рекурсивной лямбды. Синтаксис Python разрешает такой трюк:

p = (lambda a: a[0] * p(a[1:]) if a else 1); print(p([1, 2, 3, 4, 5]))

Это именно трюк с глобальной переменной и двумя операторами в одной строке. А можно обойтись без глобальной переменной вообще. На первый взгляд этого не может быть так как имя нужно чтобы сделать рекурсивный вызов. Но функцию можно передать как аргумент в саму себя:

p = lambda f, a: a[0] * f(f, a[1:]) if a else 1
print(p(p, [1, 2, 3, 4, 5]))

Кажется мы ничего не выиграли: всё равно два оператора и глобальная переменная p. Однако сделан очень важный шаг — тело лямбды не использует глобальные переменные. Глобальная переменная используется в операторе print. Избавимся от неё:

p = lambda f, a: a[0] * f(f, a[1:]) if a else 1
y = lambda f, a: f(f, a)
print(y(p, [1, 2, 3, 4, 5]))

Стало только хуже: три строки и две глобальные переменные. Зато каждая глобальная переменная задействована только один раз. Делаем подстановку:

print((lambda f, a: f(f, a))(lambda f, a: a[0] * f(f, a[1:]) if a else 1, [1, 2, 3, 4, 5]))

Читается тяжело, но задача решена в одну строку без глобальных имён и волшебных вызовов eval.

P.S. Читайте Fixed-point combinator чтобы узнать откуда пошло это решение.

P.P.S. Красивое утверждение: программу любой сложности можно записать в функциональном стиле не определив ни одной глобальной переменной, включая имена функций.

P.P.P.S. Не пытайтесь повторить это дома.

Given a list, print the value obtained after multiplying all numbers in a list. 

Examples: 

Input :  list1 = [1, 2, 3] 
Output :
Explanation: 1*2*3=6 

Input : list1 = [3, 2, 4] 
Output : 24 

Method 1: Traversal

Initialize the value of the product to 1(not 0 as 0 multiplied with anything returns zero). Traverse till the end of the list, multiply every number with the product. The value stored in the product at the end will give you your final answer.

Below is the Python implementation of the above approach:  

Python

def multiplyList(myList):

    result = 1

    for x in myList:

        result = result * x

    return result

list1 = [1, 2, 3]

list2 = [3, 2, 4]

print(multiplyList(list1))

print(multiplyList(list2))

Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(1),

Method 2: Using numpy.prod()

We can use numpy.prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.

Below is the Python3 implementation of the above approach:  

Python3

import numpy

list1 = [1, 2, 3]

list2 = [3, 2, 4]

result1 = numpy.prod(list1)

result2 = numpy.prod(list2)

print(result1)

print(result2)

Output: 
 

6
24 

Time complexity: O(n), where n is the length of the input lists. 
Auxiliary space: O(1). 

Method 3 Using lambda function: Using numpy.array

Lambda’s definition does not include a “return” statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list.

Below is the Python3 implementation of the above approach:  

Python3

from functools import reduce

list1 = [1, 2, 3]

list2 = [3, 2, 4]

result1 = reduce((lambda x, y: x * y), list1)

result2 = reduce((lambda x, y: x * y), list2)

print(result1)

print(result2)

Time complexity: O(n) – where n is the length of the longer list.
Auxiliary space: O(1) – the memory used is constant, as no extra data structures are create.

Method 4 Using prod function of math library: Using math.prod

Starting Python 3.8, a prod function has been included in the math module in the standard library, thus no need to install external libraries.

Below is the Python3 implementation of the above approach:  

Python3

import math

list1 = [1, 2, 3]

list2 = [3, 2, 4]

result1 = math.prod(list1)

result2 = math.prod(list2)

print(result1)

print(result2)

Output: 
 

6
24 

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(1), as the program only uses a fixed amount of memory to store the input lists and the output variables.

Method 5: Using mul() function of operator module. 

First we have to import the operator module then using the mul() function of operator module multiplying the all values in the list. 

Python3

from operator import*

list1 = [1, 2, 3]

m = 1

for i in list1:

    m = mul(i, m)

print(m)

Time complexity:

The program contains a single for loop that iterates through each element in the input list. Therefore, the time complexity of the program is O(n), where n is the length of the input list.
 

Auxiliary space:

The program uses a constant amount of auxiliary space throughout its execution. Specifically, it only creates four variables: list1, m, i, and the imported mul function from the operator module. The space required to store these variables does not depend on the size of the input list, and therefore the auxiliary space complexity of the program is O(1), which is constant.
 

Method 6: Using traversal by index

Python3

def multiplyList(myList) :

    result = 1

    for i in range(0,len(myList)):

        result = result * myList[i]

    return result

list1 = [1, 2, 3]

list2 = [3, 2, 4]

print(multiplyList(list1))

print(multiplyList(list2))

Time complexity: O(n), where n is the length of the input list. 

Auxiliary space: O(1), as the program uses a single variable to store the result and does not use any additional data structure. 

Method 7: Using itertools.accumulate

Python

from itertools import accumulate

list1 = [1, 2, 3]

list2 = [3, 2, 4]

result1 = list(accumulate(list1, (lambda x, y: x * y)))

result2 = list(accumulate(list2, (lambda x, y: x * y)))

print(result1[-1])

print(result2[-1])

Output:

6
24

The time complexity is O(n), where n is the length of the input list.

The auxiliary space is also O(n) 

Method 8: Using the recursive function 

The function product_recursive() takes a list of numbers as input and returns the product of all the numbers in the list, using a recursive approach.

The steps for this function are:

  1. Check if the list is empty. If it is, return 1 (the product of an empty list is defined as 1).
  2. If the list is not empty, recursively call the product_recursive() function on the rest of the list (i.e., all the elements except for the first one) and multiply the result by the first element of the list.
  3. Return the product obtained from step 2.
     

Python3

def product_recursive(numbers):

    if not numbers:

        return 1

    return numbers[0] * product_recursive(numbers[1:])

list1 = [1, 2, 3]

product = product_recursive(list1)

print(product) 

list2 = [3, 2, 4]

product = product_recursive(list2)

print(product) 

The time complexity of this function is O(n), where n is the number of elements in the list. This is because the function needs to perform n recursive calls, one for each element in the list. 
The space complexity is also O(n) because the function creates n recursive calls on the call stack. This means that for large lists, the function can quickly use up a lot of memory, which can cause the program to crash or slow down significantly.

Method: Using  reduce() and the mul() function’s

One approach to solve this problem is to use the built-in reduce() function from the functools module, which can apply a function to an iterable in a cumulative way. We can use the operator.mul() function to multiply the elements together.

Here are the steps and code:

  1. Import the reduce() function and mul() function from the functools and operator modules, respectively.
  2. Define the input list.
  3. Apply the reduce() function to the list, using mul() as the function to apply.
  4. Print the result.

Python3

from functools import reduce

from operator import mul

list1 = [1, 2, 3]

result = reduce(mul, list1)

print(result)

Time complexity: O(n)
Auxiliary space: O(1)

Last Updated :
25 Apr, 2023

Like Article

Save Article

Вопрос:

Мне нужно написать функцию, которая принимает
a список чисел и умножает их вместе. Пример:
[1,2,3,4,5,6] даст мне 1*2*3*4*5*6. Я действительно могу использовать вашу помощь.

Ответ №1

Python 3: используйте functools.reduce:

>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

Python 2: используйте reduce:

>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

Для совместимости с 2 и 3 используйте pip install six, затем:

>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

Ответ №2

Вы можете использовать:

import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)

Смотрите reduce и operator.mul документация для объяснения.

Вам нужна строка import functools в Python 3 +.

Ответ №3

Я бы использовал numpy.prod для выполнения задачи. См. Ниже.

import numpy as np
mylist = [1, 2, 3, 4, 5, 6]
result = np.prod(np.array(mylist))

Ответ №4

Если вы хотите избежать импорта чего-либо и избежать более сложных областей Python, вы можете использовать простой цикл

product = 1  # Don't use 0 here, otherwise, you'll get zero
# because anything times zero will be zero.
list = [1, 2, 3]
for x in list:
product *= x

Ответ №5

Мне лично это нравится для функции, которая объединяет все элементы общего списка:

def multiply(n):
total = 1
for i in range(0, len(n)):
total *= n[i]
print total

Он компактный, использует простые вещи (переменную и цикл for) и чувствует себя интуитивно понятным для меня (похоже, как я думаю об этой проблеме, просто возьмите ее, умножьте ее, затем умножьте на следующую и и так далее!)

Ответ №6

Вот некоторые измерения производительности от моей машины. Относится к случаю, если это выполняется для небольших входов в длительном цикле:

import functools, operator, timeit
import numpy as np

def multiply_numpy(iterable):
return np.prod(np.array(iterable))

def multiply_functools(iterable):
return functools.reduce(operator.mul, iterable)

def multiply_manual(iterable):
prod = 1
for x in iterable:
prod *= x

return prod

sizesToTest = [5, 10, 100, 1000, 10000, 100000]

for size in sizesToTest:
data = [1] * size

timerNumpy = timeit.Timer(lambda: multiply_numpy(data))
timerFunctools = timeit.Timer(lambda: multiply_functools(data))
timerManual = timeit.Timer(lambda: multiply_manual(data))

repeats = int(5e6 / size)
resultNumpy = timerNumpy.timeit(repeats)
resultFunctools = timerFunctools.timeit(repeats)
resultManual = timerManual.timeit(repeats)
print(f'Input size: {size:>7d} Repeats: {repeats:>8d}    Numpy: {resultNumpy:.3f}, Functools: {resultFunctools:.3f}, Manual: {resultManual:.3f}')

Результаты:

Input size:       5 Repeats:  1000000    Numpy: 4.670, Functools: 0.586, Manual: 0.459
Input size:      10 Repeats:   500000    Numpy: 2.443, Functools: 0.401, Manual: 0.321
Input size:     100 Repeats:    50000    Numpy: 0.505, Functools: 0.220, Manual: 0.197
Input size:    1000 Repeats:     5000    Numpy: 0.303, Functools: 0.207, Manual: 0.185
Input size:   10000 Repeats:      500    Numpy: 0.265, Functools: 0.194, Manual: 0.187
Input size:  100000 Repeats:       50    Numpy: 0.266, Functools: 0.198, Manual: 0.185

Вы можете видеть, что Numpy немного медленнее при меньших входах, поскольку он выделяет массив перед выполнением умножения. Также следите за переполнением в Numpy.

Ответ №7

Простой способ:

import numpy as np
np.exp(np.log(your_array).sum())

Ответ №8

Начиная с Python 3.8, функция prod была включена в модуль math в стандартной библиотеке:

math.prod(iterable, *, start=1)

который возвращает произведение значения start (по умолчанию: 1), умноженное на итерируемое число:

import math

math.prod([1, 2, 3, 4, 5, 6]) # 720

Обратите внимание, что если итерация пуста, будет получено значение 1 (или значение start, если оно предусмотрено).

Ответ №9

Нашел этот вопрос сегодня, но я заметил, что он не имеет случая, когда в списке есть None. Таким образом, полным решением будет:

from functools import reduce

a = [None, 1, 2, 3, None, 4]
print(reduce(lambda x, y: (x if x else 1) * (y if y else 1), a))

В случае сложения мы имеем:

print(reduce(lambda x, y: (x if x else 0) + (y if y else 0), a))

Ответ №10

nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))

Ответ №11

Я хотел бы это следующим образом:

    def product_list(p):
total =1 #critical step works for all list
for i in p:
total=total*i # this will ensure that each elements are multiplied by itself
return total
print product_list([2,3,4,2]) #should print 48

Ответ №12

Это мой код:

def product_list(list_of_numbers):
xxx = 1
for x in list_of_numbers:
xxx = xxx*x
return xxx

print(product_list([1,2,3,4]))

результат: (‘1 * 1 * 2 * 3 * 4’, 24)

Ответ №13

var=1
def productlist(number):
global var
var*=number
list(map(productlist,[1,2,4]))
print(var)

Вы можете сделать это с помощью карты

Ответ №14

Мое решение для умножения элементов в кортеже или списке

a = 140,10
val = 1
for i in a:
val *= i
print(val)

[ВЫХОД]:

1400

Ответ №15

Мое решение:

def multiply(numbers):
a = 1
for num in numbers:
a *= num
return a

pass

Ответ №16

Numpy имеет функцию prod, которая возвращает произведение списка, или, в данном случае, так как это numpy, технически это произведение массива по заданной оси.

в одну сторону:

import numpy
a = [1,2,3,4,5,6]
b = numpy.prod(a)

другой просто играет на том, как вы импортируете:

from numpy import prod
a = [1,2,3,4,5,6]
b = prod(a)

Ответ №17

def multiply(numbers):
total = numbers[0]
for num in numbers:
total *= num
return total

Ответ №18

Как насчет использования рекурсии?

def multiply(lst):
if len(lst) > 1:
return multiply(lst[:-1])* lst[-1]
else:
return lst[0]

Ответ №19

Это очень просто, ничего не импортировать. Это мой код Это определит функцию, которая умножает все элементы в списке и возвращает их продукт.

def myfunc(lst):
multi=1
for product in lst:
multi*=product
return product

Я приведу не очень практичное но красивое решение в одну строку. Оно не использует eval, побочные эффекты при работе со списком или именованные функции.

Если именованные функции разрешены, то решение может выглядеть так:

def p(a):
    if a:
        return a[0] * p(a[1:])
    return 1

print(p([1, 2, 3, 4, 5]))

Нам оно не подходит, так именованная функция требует минимум две строки для определения и вызова. Лямбду можно определить и вызвать в одной строке, но есть трудность в создании рекурсивной лямбды. Синтаксис Python разрешает такой трюк:

p = (lambda a: a[0] * p(a[1:]) if a else 1); print(p([1, 2, 3, 4, 5]))

Это именно трюк с глобальной переменной и двумя операторами в одной строке. А можно обойтись без глобальной переменной вообще. На первый взгляд этого не может быть так как имя нужно чтобы сделать рекурсивный вызов. Но функцию можно передать как аргумент в саму себя:

p = lambda f, a: a[0] * f(f, a[1:]) if a else 1
print(p(p, [1, 2, 3, 4, 5]))

Кажется мы ничего не выиграли: всё равно два оператора и глобальная переменная p. Однако сделан очень важный шаг — тело лямбды не использует глобальные переменные. Глобальная переменная используется в операторе print. Избавимся от неё:

p = lambda f, a: a[0] * f(f, a[1:]) if a else 1
y = lambda f, a: f(f, a)
print(y(p, [1, 2, 3, 4, 5]))

Стало только хуже: три строки и две глобальные переменные. Зато каждая глобальная переменная задействована только один раз. Делаем подстановку:

print((lambda f, a: f(f, a))(lambda f, a: a[0] * f(f, a[1:]) if a else 1, [1, 2, 3, 4, 5]))

Читается тяжело, но задача решена в одну строку без глобальных имён и волшебных вызовов eval.

P.S. Читайте Fixed-point combinator чтобы узнать откуда пошло это решение.

P.P.S. И есть очаровательное утверждение: программу любой сложность можно записать в функциональном стиле не определив ни одной глобальной переменной, включая имена функций.

P.P.P.S. Не пытайтесь повторить это дома.

Понравилась статья? Поделить с друзьями:
  • Как нужно найти плотность
  • Как найти баннер на браузере
  • Флешка стала локальным диском как исправить windows 10
  • Как найти площадь треугольника по координатным точкам
  • Как найти высоту полуокружности формула