Suppose we have a variable sets and suppose each variable gets few values from sets . So . Now there is a function . How can I sum up on all possible values of to on ?
For example if and and and then I am looking for:
*The size of can change. So the size of it is also changing. I didn't want to write in a complex form but actually I am adding up multiple functions which each has their own variable set.
You can use itertools.product
>>> from itertools import product
>>> V = [[1,2],[3,4,5]]
>>> summ = 0
>>> for x in product(*V):
print x
# or call some function : summ += func(*x)
...
(1, 3)
(1, 4)
(1, 5)
(2, 3)
(2, 4)
(2, 5)
You can use a list to represent the sets. So V is a list of lists.
V = [[1,2],[3,4,5]]
r = [[]]
for v in V:
r = [ i + [y] for y in v for i in r ]
# at this point, r contains the inputs for your functions
sum = 0
for domain in r:
sum += function(domain)
All you have to do is define your function to accept a list. In your example, it would be this:
def function(l):
return l[0] * l[1]
Related
We have to accept a list and find the subsequent from the list such that number in subsequence are in increasing order.
Find sum of each subsequence
return maximum sum
For example
Input=[1, 4,2]
Possible subsequence will be [1][4][2][1,4][1,2]
Here [4,2] will not come as 4 is greater. And order should not change. Means first position elements if it comes in sublist it should be first
Sum of each subsequence will be 1,4,2,5,3
Output will be 5.
What will be your logic to solve it?
You can use itertools.combinations and itertools.chain to do this easily
>>> from itertools import combinations, chain
>>> Input=[1, 4,2]
>>> max(map(sum, (filter(lambda x: sorted(x) == list(x), chain(*[combinations(Input, i) for i in range(1, len(Input)+1)])))))
5
Explanation
>>> possibilities = chain(*[combinations(Input, i) for i in range(1, len(Input)+1)])
>>> filtered_possibilities = filter(lambda x: sorted(x) == list(x), possibilities)
>>> sum_of_each_possibility = map(sum, filtered_possibilities)
>>> max_sum = max(sum_of_each_possibility)
>>> print (max_sum)
5
You can break down the question into three steps:
1) Find the power_set(all sub lists) of list.
2) Filter out unwanted list (list with decreasing order).
3) Find the max sum.
Step1:
def powerset(s):
x = len(s)
res=[]
for i in range(1 << x):
res.append([s[j] for j in range(x) if (i & (1 << j))])
return res
lst=[1,4,2]
res=powerset(lst)
Step 2&3:
def max_sub(lsts):
max_out=0
def helper(lsts): #Step2: to filter out decreasing lists.
if lsts==[]:
return False
else:
for i in range(len(lsts)-1):
if lsts[i]>lsts[i+1]:
return False
return True
filtered_lst=list(filter(lambda x:helper(x),lsts))
for lst in filtered_lst:
max_out=max(max_out,sum(lst)) #step3: Find out the max sub list sum.
return max_out
print(max_sub(res))
Result:
5
Drako already mentioned, that this is not free coding service. Show some effort yourself and tell us, what you already tried and how it didn't work. also provide output to help us analyze the problem. I'll help anyway; also welcome to StackOverflow.
What you are looking for is a "power set". An exhaustive set M of sets s, where each s is a subset of M and there is in fact no subset of M which is not already contained in a s. As sets are unordered by definition, you don't have to care about duplicates because of different ordering. Looking at this question
There is a nice answer to get the power set of a given set. Assuming your input list/set/iterable is i, you can use the following code to get the power set list.
from itertools import chain, combinations
def get_power_set(i):
i.sort() # Sorted input --> sorted output
ps_iterable = chain.from_iterable(combinations(i, r) for r in range(len(i)+1))
return list(ps_iterable)
def get_highest_sum(input_list):
maximum = 0
for s in input_list:
sum_of_set = sum(s)
if sum_of_set > maximum:
maximum = sum_of_set
return maximum
i = [1,2,3] # Assign your input list here
power_set = get_power_set(i)
highest_sum = get_highest_sum(power_set)
print(power_set)
# >>> [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
print("Highest sum is {}".format(highest_sum))
# >>> 6
I have a problem to find the max of sum of count of set bits in any k-elements from the given list.
Given :
n = 4 # length of list
k = 2 # choose only k elements of list whose count(sum(set bits)) is max
list l= 6 2 1 0
so If I choose numbers 6 (110) and 1 (001) with 2 and 1 set bits respectively, adding them gives me max count of set bits i.e . 3
What I tried is :
from itertools import combinations
s = list(map(int,raw_input().split()))
n = s[0]
k = s[1]
l = list(map(int,raw_input().split()))
comb = list(combinations(l, k))
# print comb
ad = []
for i in comb:
x = bin(i[0])[2:].count('1')+bin(i[1])[2:].count('1')
ad.append(x)
# print ad
print max(ad)
My problem is with line :
x = bin(i[0])[2:].count('1')+bin(i[1])[2:].count('1')
As k = 2, I took this manually i[0] and i[1].
But how to do this dynamically.
Also I am looking for a answer without using list comprehension,as my list size may vary to 2 to 10^18 which cause memory exceeding.
If you can suggest any other logic,that will be much useful.
I would expect that there is a sort in there. I really think that combinations isn't needed because only the the items with the most bits set can make up the result. Consider the following:
Given your input, the following I think computes the result:
n = 4 # length of list
k = 2 # choose only k elements of list whose count(sum(set bits)) is max
l = [6, 2, 1, 0]
like this:
>>> sorted(l, key=lambda v: bin(v)[2:].count('1'), reverse=True)[:2]
[6, 2]
This can be made to stream over the input by using a heapq of size k and inserting (bin(v)[2:].count('1'), v) then the result can be product by extracting the numbers. The heapq function nlargest will work nicely
>>> import heapq
>>> heapq.nlargest(k, l, key=lambda v: bin(v)[2:].count('1'))
[6, 2]
Note that l can be a iterator. This operates in constant space. The memory usage depends on k not on the length of the iterator.
Then you can compute the sum of the bits set as in the other answers:
>>> sum(bin(v)[2:].count('1') for v in [6,2])
3
I think
x = sum([bin(i[kk])[2:].count('1') for kk in range(k)])
could work
This question already has answers here:
How do I generate all permutations of a list?
(40 answers)
Closed 8 years ago.
I have a dictionary
Example: dict = {'one':1 ,'two':2 , 'three':3}
I want to use/have two values within single iteration of for loop. End result should be like this
# 1 2 (First iteration)
# 1 3 (Second iteration)
# 2 1
# 2 3
# 3 1
# 3 2
Can someone please tell how I can achieve this in python dictionary.
for i in dict.values():
# how do i Access two values in single iteration and to have result like mentioned above
Thanks
import itertools
d = {'one':1 ,'two':2 , 'three':3}
l = list(itertools.permutations(d.values(),2))
>>> l
[(3, 2),
(3, 1),
(2, 3),
(2, 1),
(1, 3),
(1, 2)]
for x, y in l:
# do stuff with x and y
You can get the desired output order by ordering the permutations of the dicts values, eg:
from itertools import permutations
dct = {'one':1 ,'two':2 , 'three':3}
for fst, snd in sorted(permutations(dct.itervalues(), 2)):
print fst, snd # or whatever
Actually i want to access the values only so i am using this function dict.values() Example it should be like this x = 1 , y =2 these values will be used as an arguments to another function self.funct(x,y)
In your comment it seemed like you just wanted both numbers for another function. If you don't mind nested loops, this should suffice:
d = {'one':1 ,'two':2 , 'three':3}
dvals = sorted(d.values()
for x in dvals:
for y in dvals:
if x != y:
self.funct(x,y)
My actual output looks like this:
target = [([('Kid', '200-5'), (u'Rock', '200-6')], u's725')]
How can I modify data in the tuple such that I can return, at the end, the modified list which has the same format as target?
For example: I'd like to change 'kid' in 'adult', such that the rest stays, i.e. I receive: newTarget = [([('adult', '200-5'), (u'Rock', '200-6')], u's725')]
My idea: Copy all the data of target in a temporary list, modify things and create the same format as in target.
BUT: How can I achieve this concretely?
Until now, I could Change and modify things, but I didn't get the same format again...
Have you tried this?
l = list(target[0][0][0])
l[0] = 'Adult'
target[0][0][0] = tuple(l)
Since tuples are immutable, you cannot modify their elements—you must replace them with new tuples. Lists are mutable, so you can replace individual parts as needed:
>>> x = [(1, 2), (3, 4), 5]
>>> x[0] = (x[0][0], 0)
>>> x
[(1, 0), (3, 4), 5]
In the above example, I create a list x containing tuples as its first and second elements and an int as its third. On the second line, I construct a new tuple to swap in to the first position of x, containing the first element of the old tuple, and a new element 0 to replace the 2.
You will need recursion if you need to be more flexible
target = [([('Kid', '200-5'), (u'Rock', '200-6')], u's725')]
def search_and_replace(inlist):
res = []
for t in inlist:
if isinstance(t, list):
res.append(search_and_replace(t))
elif isinstance(t, tuple):
t1, t2 = t
if t1 == 'Kid':
t1 = 'adult'
elif isinstance(t1, list):
t1 = search_and_replace(t1)
res.append((t1, t2))
else:
res.append(t)
return res
print search_and_replace(target)
I'm making a function called different(). It needs to take a two-dimensional table as input and return the number of distinct entries in the table. I'm not sure how to start it,m I would really appreciate some suggestions. When used, it should look like this in the shell:
t = [[1,0,1], [0,1,0]]
different(t)
>>2
This is what I have so far:
def different()-> int
''' takes a two-dimensional table and returns number of distinct entries'''
t = []
while
#use set method?
I think there are two possible interpretations
>>> set(j for i in t for j in i)
set([0, 1])
and
>>> set(tuple(i) for i in t) # equivalent to set(map(tuple, t))
set([(0, 1, 0), (1, 0, 1)])
Either way, different should return the len of the set
def different(t):
return len(set(...))
If you like itertools, you can do the following
from itertools import chain
def different(t):
return len(set(chain.from_iterable(t)))
def different(t):
return len(set(tuple(item) for item in t))
From basic knowledge of python you can solve the above problem
t = [[1,0,1], [0,1,0], [1,2,3], [1,0,1]]
a = []
for i in t:
if i not in a:
a.append(i)
print len(a)
you have created a new list name 'a' and you have inserted all those element in the list which are unique. And afetrwards you can get the length of the new list a.