The problem is indexing. I've tried this code snippet:
for i in range(2,len(the_list_im_getting_values_from)):
for j in range(0,i+1):
index[j] = j
for k in range(0,len(index)):
the_output_list.append(the_list_im_getting_values_from[index[k]]*the_list_im_getting_values_from[index[k+1]])
k += 1
, but it totally didn't work.
How to solve this problem?
Example input: array of 3, 4 and 7
Example output: [12,21,28,84]
Processing stages:
3*4=12
3*7=21
4*7=28
3*4*7=84
[12,21,28,84]
You can play around with itertools multiset-receipt . It will generate somewhat more of the needed tuples, you would have to filter them out:
from itertools import chain, combinations
# see link above for credits
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
def mult(iterab):
"""Multiply all numbers in the iterable and return result"""
rv = 1
for k in iterab:
rv = rv * k
return rv
d = [3,4,7]
k = powerset(d) # (), (3,), (4,), (7,), (3, 4), (3, 7), (4, 7), (3, 4, 7)
result = []
# we filter out anything from k thats shorter then 2
result.extend(map(mult, (x for x in k if len(x)>1)))
print(result)
Output:
[12, 21, 28, 84]
So you're trying to get all products using every possible combination of numbers in your list.
from itertools import chain, combinations
from functools import reduce
def powerset(iterable, min_subset_size=1):
'Returns all subsets of the iterable larger than the given size.'
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(min_subset_size, len(s)+1))
def product(iterable):
'Returns the product of all the numbers in the iterable.'
return reduce((lambda x, y: x * y), iterable)
numbers = 3, 4, 7
If eg 3 counts as a product of a single number:
result = {product(subset) for subset in powerset(numbers)}
print(result)
Out: {3, 4, 7, 12, 84, 21, 28}
If a product must be of 2 or more numbers eg 3*4, 3*4*7:
result = {product(subset) for subset in powerset(numbers, 2)}
print(result)
Out: {28, 12, 21, 84}
I think what you want is the result of each number multiplied by the other ints in the list? Thus for list[3,4,7] you would want 9,16,49,12,21,28. You can try this.
l = [3,4,7]
s = set()
for count, num in enumerate(l):
for each in l:
s.add(each * l[count])
s
{9, 12, 16, 49, 21, 28}
if you dont want the squares (9,49,16) add
if list[count] == each:
countinue
underneath the second for loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.