Returning the product of a list
Without using lambda:
from operator import mul
# from functools import reduce # python3 compatibility
reduce(mul, list, 1)
it is better and faster. With python 2.7.5
from operator import mul
import numpy as np
import numexpr as ne
# from functools import reduce # python3 compatibility
a = range(1, 101)
%timeit reduce(lambda x, y: x * y, a) # (1)
%timeit reduce(mul, a) # (2)
%timeit np.prod(a) # (3)
%timeit ne.evaluate("prod(a)") # (4)
In the following configuration:
a = range(1, 101) # A
a = np.array(a) # B
a = np.arange(1, 1e4, dtype=int) #C
a = np.arange(1, 1e5, dtype=float) #D
Results with python 2.7.5
| 1 | 2 | 3 | 4 |
-------+-----------+-----------+-----------+-----------+
A 20.8 µs 13.3 µs 22.6 µs 39.6 µs
B 106 µs 95.3 µs 5.92 µs 26.1 µs
C 4.34 ms 3.51 ms 16.7 µs 38.9 µs
D 46.6 ms 38.5 ms 180 µs 216 µs
Result: np.prod
is the fastest one, if you use np.array
as data structure (18x for small array, 250x for large array)
with python 3.3.2:
| 1 | 2 | 3 | 4 |
-------+-----------+-----------+-----------+-----------+
A 23.6 µs 12.3 µs 68.6 µs 84.9 µs
B 133 µs 107 µs 7.42 µs 27.5 µs
C 4.79 ms 3.74 ms 18.6 µs 40.9 µs
D 48.4 ms 36.8 ms 187 µs 214 µs
Is python 3 slower?
Multiply items in list
Or something similar with one of the answer which first flattned the nested list using the flatten
and using numpy prod
to calculate the cross multiplication.
import numpy as np
def flatten(li):
try:
for item in li:
yield from flatten(item)
except TypeError:
yield li
li = [6,[1, 2, 3]]
list1 = [fi for fi in flatten(li)]
result1 = np.prod(list1)
Initially, the OP accept the suggestion per the code below
Extract the nested list
num, val_list = [6 , [1, 2, 3]]
multiply and add all the value in the list
expected_output=sum([value * num for value in val_list])
As a function:
def grow(arr):
num, val_list = arr
return sum([value * num for value in val_list])
my_arr= [6 , [1, 2, 3]]
data=grow(my_arr)
max possible product of a list with any elements
Post request corner cases where the posted code doesn't work.
Code provides incorrect answers for single negative numbers.
Examples:
print(max_prod([0]))
# Output: 1
The answer should be 0
Simple fix would be to add condition:
if xs == [0]:
return 0
Simpler Code
from math import prod
def max_prod(xs):
pos = [i for i in xs if i > 0]
neg = [i for i in xs if i < 0]
if len(neg) % 2:
neg.remove(max(neg))
if len(pos) > 0 or len(neg) > 0:
return str(prod(pos) * prod(neg))
return "0"
Tests
for xs in [[], [0], [2], [-2], [2, 3], [0, 2, 3],
[-2, -3], [-2, -3, -4], [2, 0, -2, -3],
[2, 0, -2, -3, -1]]:
print(f'{xs} max-> {max_prod(xs)}')
Output
[] max-> 0
[0] max-> 0
[2] max-> 2
[-2] max-> 0
[2, 3] max-> 6
[0, 2, 3] max-> 6
[-2, -3] max-> 6
[-2, -3, -4] max-> 12
[2, 0, -2, -3] max-> 12
[2, 0, -2, -3, -1] max-> 12
Product of a list python
Using reduce(f, iterable[, initializer])
:
>>> from operator import mul
>>> reduce(mul, [1, 2, 3], 1)
6
reduce()
abstracts over the following pattern:a ⊗ b ⊗ c ⊗ d ⊗ e ...
where ⊗
is a binary (left associative) operator, i.e. a function accepting two parameters.
Returning items in a list
You are losing the information about insertion order because you are using Unordered collection Set
. Insertion order is preserved in data structures like LinkedList (and its set variant LinkedHashSet or its map variant LinkedHashMap).
The advantage of using a LinkedHashSet or LinkedHashMap over LinkedList is that while insertion, when check is performed for duplicate, in LinkedHashSet or LinkedHashMap it is O(1) where as for LinkedList it is O(n).
You can achieve same thing using Java 8 stream.distinct()
also.
Here are few options:
public class MyApp {
public static void main(String[] args) {
List myList = Arrays.asList("red", "yellow", "green", "yellow", "blue", "green", "purple");
distinctValuesUsingStreamDistinct(myList).forEach(System.out::println);
System.out.println("==============");
distinctValuesUsingLinkedHashSet(myList).forEach(System.out::println);
}
public static List<String> distinctValuesUsingStreamDistinct(List<String> stringList) {
return stringList.stream().distinct().collect(Collectors.toList());
}
public static List<String> distinctValuesUsingLinkedHashSet(List<String> stringList) {
LinkedHashSet<String> setSortedByInsertionOrder = new LinkedHashSet<String>();
stringList.forEach(str -> setSortedByInsertionOrder.add(str));
return new ArrayList<>(setSortedByInsertionOrder);
}
}
python multiply all elements except ith element in list and return list
A simple solution using two for loops:
l=[1,2,3,4]
out=[]
for i in range(len(l)):
prod=1
for j in range(len(l)):
if(j!=i): #Iterate through list once more and compare the indices
prod=prod*l[j]
out.append(prod)
print(out)
Output is: [24, 12, 8, 6]
Related Topics
Python Unexpected Eof While Parsing
How to Append One String to Another in Python
How to Access Outer Class from an Inner Class
Differencebetween Slice Assignment That Slices the Whole List and Direct Assignment
Ignore Python Multiple Return Value
How to Read the Rgb Value of a Given Pixel in Python
Zip Variable Empty After First Use
How to Uninstall Anaconda Completely from MACos
Scraping Dynamic Content Using Python-Scrapy
How to Use Angularjs with the Jinja2 Template Engine
How to Scroll the Background Surface in Pygame
How to Split a Dos Path into Its Components in Python
Repeating Elements of a List N Times