I have a list, lst
, that contains only 0's and 1's of length n .
The list represents either a cut vector or a path vector, from reliability analysis, which may or may not be minimal cut/path vectors themselves.
The elements within the list represent separate variables, say x1 , x2 , and x3 and the length of the list, n , represents the number of variables being represented.
For example, the list [0, 1, 1]
represents 3 variables, x1 , x2 , and x3 .
Given the input, lst
, I want to return a list or string that is guided by the following rules.
If x i = 1:
a. return (x i )
else if x i = 0:
b. return: (1 - x i )
[0, 1] => [1-X1, X2]
or "1-X1, X2"
[1, 0] => [X1, 1-X2]
or "X1, 1-X2"
[0, 1, 1] => [1-X1, X2, X3]
or "1-X1, X2, X3"
[1, 1, 1] => [X1, X2, X3]
or "X1, X2, X3"
def get_function(path_vector):
lst = []
for item in path_vector:
if "0" in item:
print("1-", item, sep="")
lst.extend(["1-", item])
else:
print(item)
lst.append(item)
print(lst)
expr = "*".join(lst)
return expr
The eventual goal is to join the items in the new list - separated by a *
- and input them into a function from the sympy library.
Any tips are appreciated.
item
has values 0
or 1
but you need its position on list to create string 1-X{position}
or X{position}
You may use enumarate(..., 1)
to get its position on list.
Because you have integer values then you should compare integers if item == 0:
Minimal working code which use list examples
to generate string and compare with expected result
def get_function(path_vector):
lst = []
for position, item in enumerate(path_vector, 1):
if item == 0:
text = f"1-X{position}"
else:
text = f"X{position}"
lst.append(text)
print('text:', text)
print('lst:', lst)
expr = "*".join(lst)
return expr
# --- main ---
examples = [
([0, 1], "1-X1*X2"),
([1, 0], "X1*1-X2"),
([0, 1, 1], "1-X1*X2*X3"),
([1, 1, 1], "X1*X2*X3"),
]
for data, expected_result in examples:
result = get_function(data)
print(data, expected_result, result, expected_result==result)
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.