dependent = ["R", "S"]
L = {"R": [0.8, 0.2], "S": [0.5, 0.5], "K": [0.1, 0.1]}
sequence = [[0,0], [0, 1], [1, 0], [1,1]]
I wish to generalize a certain approach without imports.
Given these three list and dictionaries output the sequence. so for R and S the first element implies R = 0, S = 0. What I want is:
0.8 x 0.5 + 0.8 x 0.5 + 0.2 x 0.5 + 0.2 x 0.5
basically
(R = 0 x S = 0) + (R = 0 x S = 1) + (R = 1 x S = 0) + (R = 1 x S = 1) as given by the sequence list.
I know I iterate from the sequence but after that I'm not sure how to use dependent and L concurrently.
Given that you don't want to use imports, I think the best approach is to define a function such as:
def cartesian(items):
if len(items) == 0:
return [[]]
else:
return [
[x] + c
for x in items[0]
for c in cartesian(items[1:])
]
to get the cartesian product of given iterables.
We want to apply this function just to your dependent items, so first:
dep_items = [v for k, v in L.items() if k in dependent]
and then calculate the product:
>>> sum([eval("*".join(map(str, c))) for c in cartesian(dep_items)])
1.0
Update
After reading one of your comments and I believe I misunderstood the role of sequence
in your question, ie sequence
is always available and not made of all combinations, so you don't need the cartesian
function. In that case, I believe sequence
and dependent
should keep the same order, so first:
items = [L[k] for k in dependent]
then I get combinations according to sequence
:
combos = [[items[i][ind] for i, ind in enumerate(s)] for s in sequence]
and finally calculate the sum of the products.
I'll show an example with a particular dependent
and sequence
you requested in a comment:
>>> dependent = ["R", "S", "K"]
>>> sequence = [[0, 0, 0], [0, 1, 0], [1, 0, 1]]
>>> items = [L[k] for k in dependent]
>>> combos = [[items[i][ind] for i, ind in enumerate(s)] for s in sequence]
>>> sum([eval("*".join(map(str, c))) for c in combos])
0.09000000000000002
I have to leave so I can't finish this, but this is where I'm at. Maybe it will help set you on a path to solve it!
dependent = ["R", "S"]
L = {"R": [0.8, 0.2], "S": [0.5, 0.5], "K": [0.1, 0.1]}
sequence = [[0, 0], [0, 1], [1, 0], [1, 1]]
my_list = []
for item in sequence:
item_total = 1
for index in range(len(item) - 1):
print(L[dependent[index]][item[index]])
item_total = item_total * L[dependent[index]][item[index]]
# print(item_total)
my_list.append(item_total)
print(my_list)
total = sum(my_list)
print(total)
Right now I'm getting
0.8
0.8
0.2
0.2
[0.8, 0.8, 0.2, 0.2]
2.0
Which is obviously not correct, but close. There's just an indexing error somewhere D:
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.