How to call comparison operators from list [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Hi I want to install some kind of adjustable comparer where an element from a list a is compared to an element of a list Values with an operator which is read from a list Operators
a = [1,2,3,4] # This should be variable
Val = [0.5,1,10,7] # This should have the same length as a
Op = ['<','>','<>','<']
for i in range(len(a)):
print(a[i]Op[i]Val[i])

Instead of comparison symbols, use the function from operators.
May be this can help!
from operator import lt, gt, ne, le,eq
a = [1,2,3,4] # This should be variable
val = [0.5,1,10,7] # This should have the same length as a
operation = {'<': lt, '>': gt, '<>': ne, '=': eq}
op = ['<','>','<>','<']
for i,o,j in zip(a,op,val):
print(operation[o](i,j))
False
True
True
True

Using eval even in some situation it is unstable, but if only consider your case , it work as expected and better solution is sympy
a = [1,2,3,4] # This should be variable
Val = [0.5,1,10,7] # This should have the same length as a
Op = ['<','>','!=','<']
for i in range(len(a)):
parse_expr(str(a[i])+Op[i]+str(Val[i]))# or change to eval(str(a[i])+Op[i]+str(Val[i]))
False
True
True
True

Seems that you need programmatic way to call comparison operators, operator module will do the work. Either construct list of operator functions or make signs to operator mapping via dict

a = [1,2,3,4] # This should be variable
b = [0.5,1,10,7] # This should have the same length as a
c = ['<','>','<>','<']
use
for i in range(len(a)):
eval(str(a[i])+b[i]+str(c[i]))

Related

Struggling with python Comparison question [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Am learning python and one of the questions in our study guide asks to evaluate RNA sequences. I do not get the expected outputs as suggested by the question, I get 17.
Here is the code:
####START FUNCTION
def rna_length(mrna);
start_rna = 'AUG';
end_rna1 = 'UGA';
end_rna2 = 'UAA';
end_rna3 = 'UAG';
if (mrna[0:3]==start_rna) and (mrna [-3:]==end_rna1 or end_rna2 or end_rna3):
length = len(mrna[3:-3])
return length
else: ((mrna[0:3]!=start_rna) or (mrna [-3:]!=end_rna1 or end_rna2 or end_rna3))
return "Not readable RNA code"
####END FUNCTION
A link to a screenshot of the question here
The issue is you using the boolean operator or to compare strings. You can think of the comparisons like this:
(mrna [-3:]==end_rna1 or end_rna2 or end_rna3)
(((mrna [-3:]==end_rna1) or end_rna2) or end_rna3)
Because or is a boolean operator, it needs to work on booleans. You can convert strings to booleans using bool(<str>)
(((mrna [-3:]==end_rna1) or bool(end_rna2)) or bool(end_rna3))
Any string that is not empty (ie. any string that is not "") is "truthy." What that means is that bool(non_empty_str) == True and bool('') == False.
(((mrna [-3:]==end_rna1) or True) or True)
((True) or True)
(True or True)
True
Now, how should you fix it? There are a few approaches to this.
Properly use or.
if (mrna[0:3]==start_rna) and (mrna[-3:]==end_rna1 or mrna[-3:]==end_rna2 or mrna[-3:]==end_rna3):
length = len(mrna[3:-3])
return length
else:
((mrna[0:3]!=start_rna) or (mrna[-3:]!=end_rna1 or mrna[-3:]!=end_rna2 or mrna[-3:]!=end_rna3))
return "Not readable RNA code"
Use a collection. Note that it is standard to use tuples instead of lists whenever you don't want to modify the collection. I used lists here because the brackets look different. You can also use sets for quicker in, but that's overkill for 3.
if mrna[0:3] == start_rna and mrna[-3:] in [end_rna1, end_rna2, end_rna3]:
length = len(mrna[3:-3])
return length
else:
(mrna[0:3] != start_rna or mrna[-3:] not in [end_rna1, end_rna2, end_rna3])
return "Not readable RNA code"
Heck, you can even use the string methods str.startswith and str.endswith.
if mrna.startswith(start_rna) and mrna.endswith([end_rna1, end_rna2, end_rna3]):
length = len(mrna[3:-3])
return length
else:
...

What does this Python syntax do? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
New to python and trying to understand what does following syntax doing ?
def testMissingConfig(self):
""" if config is missing, the config is valid """
input_args = self.buildmock()
validation_errors = [
x
for x in self.validator.validate(
ValidatorArguments(input_args=input_args)
)
if x
]
validation_keys = {x.key for x in validation_errors}
self.assertEmpty(validation_keys)
Especially the array initialization for "validation_errors"
It is called List comprehension. Here you can combine assignments, loops, functions all in one block.
One of the big advantages of list comprehension is that they allow developers to write less
code that is often easier to understand.
Syntax:
[expression for item in list]
Example:
number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)
Here the numberlist loops over 0 to 20 and gives even numbers 0,2,4...20 as result.
Similarly in your code, validation_errors will store x if x exists(not null)
Lambda functions can also be used to create and modify lists in less lines of code.
Reference:
https://www.programiz.com/python-programming/list-comprehension

Python - how to restore original string after replace? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Let's say, the original string is:
a = 'DA115792C339A5E674416AB0559BF5CB8D38E88B1E71F4DFAE896EBD2D13ABB13FFB1DC687DCF0C270A8BF4861D2E6D26E74DC81C18EB53FD5C52AA691A8F16BDA4E1EB8009B00DCD61457E34C438F23EF3D1FD905CF689793CC1E02E1ECB6778A1E2720D416AC432959A8A3B20B43525A856C97E4D404065D1D30ADC74D012B27D00B0029AD3940CB2C9F2AB6C01D430F3A58584C5DB6C98839579AF2A8F90A5D80B5097D547105DF2D9F9485E9F2CCFD6F9ECDDBD562FE09EA81C19B18482BD483AEBAB8481EE208887909DDAE826629538F36E6A50CEECBF3462E9FFBDAC6363F3A9A56F31081EBF28AD0FCF288B0DB8CB44735B9D7E6D193D55C90767E83'
Now, all the instances of 'D6' were replaced with '9F' in above string by doing:
b = a.replace('D6','9F')
b = 'DA115792C339A5E674416AB0559BF5CB8D38E88B1E71F4DFAE896EBD2D13ABB13FFB1DC687DCF0C270A8BF4861D2E6D26E74DC81C18EB53FD5C52AA691A8F16BDA4E1EB8009B00DC9F1457E34C438F23EF3D1FD905CF689793CC1E02E1ECB6778A1E2720D416AC432959A8A3B20B43525A856C97E4D404065D1D30ADC74D012B27D00B0029AD3940CB2C9F2AB6C01D430F3A58584C5DB6C98839579AF2A8F90A5D80B5097D547105DF2D9F9485E9F2CCF9FF9ECDDBD562FE09EA81C19B18482BD483AEBAB8481EE208887909DDAE826629538F36E6A50CEECBF3462E9FFBDAC6363F3A9A56F31081EBF28AD0FCF288B0DB8CB44735B9D7E6D193D55C90767E83'
Now, let's say, we only have the value of b and not a. We need to perform some operations on b to retrieve the original value of a.
Also, we know that the value of 'a' should satisfy a certain mathematical condition.
The mathematical condition is:
number z should be divisible by a (z % a == 0)
z = 55057004365075793824891923502198296150348187500859129529014955509148421282041969078213265169463529503768779794209446773790749529176461595867792548236095966024387560672845152234957439383409540755826755640123124159246487058454615922008741879614211920551517049373314503998980825185719370304183623398662036133862488876163410866971729000216470924616148028986990798495248878127793311548452974671645100371499570058070179424193067736979204502413302335974105838586819414807952974885796840178274113497125765593996690493177955553456655538977929256055738007112424150644005452979891672942537126552535517394691741201589304958975238
We need to leverage this mathematical property of 'a' to restore it from b.
I understand that we cannot use the replace() function on b to get back 'a' because some of the original instances of '9F' might get replaced.
I think we need to perform replace operation in different positions till we satisfy that condition.
For the given string we have:
b.count('9F')
6
So, we would have to replace '9F' with 'D6' in different combinations of positions till we get back 'a' satisfying the mathematical condition, 'C'.
I did something like:
count = b.count('9F')
for i in range(1,count+1):
print "trying: %d" %(i)
tmp = b.replace('9F','D6',i)
num = int(tmp, 16)
if z % num == True:
print num
This seems to be a problem related to permutations and combinations.
You already have 4 instances of 9F in your original string. Those are causing the wierd behaviour
a = 'DA115792C339A5E674416AB0559BF5CB8D38E88B1E71F4DFAE896EBD2D13ABB13FFB1DC687DCF0C270A8BF4861D2E6D26E74DC81C18EB53FD5C52AA691A8F16BDA4E1EB8009B00DCD61457E34C438F23EF3D1FD905CF689793CC1E02E1ECB6778A1E2720D416AC432959A8A3B20B43525A856C97E4D404065D1D30ADC74D012B27D00B0029AD3940CB2C9F2AB6C01D430F3A58584C5DB6C98839579AF2A8F90A5D80B5097D547105DF2D9F9485E9F2CCFD6F9ECDDBD562FE09EA81C19B18482BD483AEBAB8481EE208887909DDAE826629538F36E6A50CEECBF3462E9FFBDAC6363F3A9A56F31081EBF28AD0FCF288B0DB8CB44735B9D7E6D193D55C90767E83'
print(a.count('9F'))
#4
Otherwise the string.replace works perfectly
a = 'hello'
b = a.replace('l','a')
print(b)
#heaao
c = b.replace('a','l')
print(c)
#hello
print( a == c)
#True
Gives you True (Convert l to a, and then a to l)
Possible solution, replace existing 9F to something not present in the string,say XY, then use it in replacing back as well
a = 'DA115792C339A5E674416AB0559BF5CB8D38E88B1E71F4DFAE896EBD2D13ABB13FFB1DC687DCF0C270A8BF4861D2E6D26E74DC81C18EB53FD5C52AA691A8F16BDA4E1EB8009B00DCD61457E34C438F23EF3D1FD905CF689793CC1E02E1ECB6778A1E2720D416AC432959A8A3B20B43525A856C97E4D404065D1D30ADC74D012B27D00B0029AD3940CB2C9F2AB6C01D430F3A58584C5DB6C98839579AF2A8F90A5D80B5097D547105DF2D9F9485E9F2CCFD6F9ECDDBD562FE09EA81C19B18482BD483AEBAB8481EE208887909DDAE826629538F36E6A50CEECBF3462E9FFBDAC6363F3A9A56F31081EBF28AD0FCF288B0DB8CB44735B9D7E6D193D55C90767E83'
#Replace 9F to XY, then D6 to 9F
b = a.replace('9F','XY').replace('D6','9F')
#Replace 9F to D6, then XY to 9F
c = b.replace('9F', 'D6').replace('XY', '9F')
print(a == c)
#True
You won't retrieve your original string back after these two operations, because you probably have "9F" in your original string, too:
test = "D69F"
changed = test.replace("D6", "9F")
print(changed)
# 9F9F
undo_change = changed.replace("9F", "D6")
print(undo_change)
# D6D6
If it don't interfere with your intermediate step you can mask your replacement, e.g. with test.replace("D6", "ยง9F").

Separating strings in CamelCase to individual strings [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
The question is as follows:
"A string exists in CamelCase format. For example: "ThisIsACamelCaseString".
A procedure/function is required that will:
1) prompt for the original entry
2) separate each word of the string
3) store each word in a separate array/list element
4) fill unused array/list elements with a rogue string such as "(Empty)".
After processing the preceding example, the array contents will look like this:
This
Is
A
Camel
Case
String
(Empty)
(Empty)
(Empty)
(Empty)
You may assume that the original string will contain no more than 10 separate words. Write program code in Python for this design."
This is what I tried:
a = input("Enter: ")
lists = list(a)
len = len(a)
alpha = ["Empty"]*10
alpha[0] = lists[0]
for i in range(len):
for j in range(len):
if lists[j + 1].isupper():
break
alpha[i] = alpha[i] + lists[j + 1]
for i in range(10):
print(alpha[i])
How do I find suitable code?
This is one way to do it:
a = 'ThisIsACamelCaseString'
b = [i for i, e in enumerate(a) if e.isupper()] + [len(a)]
c = [a[x: y] for x, y in zip(b, b[1:])]
final = ['(Empty)']*10
for i, case in enumerate(c):
final[i] = case
Use regular expressions to split camel case How to do CamelCase split in python .
Or just iterate over the string in a loop.

How to autodefine elements from a list in Python 2.7? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to create a list of both strings and integers, and make the strings work as variables whose value is the integers number.
list = ("y","1","x","3")
str(list[0]) == int(list[1])
str(list[2]) == int(list[3])
z = x + y
print(z)
I tried this, but it does't work anyway. Anybody knows a possible solution for that?
Use a dictionary:
data = {"y": 1, "x": 3}
z = data["y"] + data["x"]
print(z) # 4
Also:
list = ("x", "1", "y", "3")
Does not create a list, that creates a tuple. Also, don't use names like list as it is using the same name as the built-in list.
In [1]: exec 'y=1+1'
In [2]: y
Out[2]: 2
Needless to say that a dictionary is way better and that you should not trust user-provided input, personally I highly discourage you to pursue this path.
You can use zip() function to get the pairs and then use exec() to assign the integers to names:
>>> items = ("y","1","x","3")
>>> for i,j in zip(items[0::2], items[1::2]):
... exec("{}={}".format(i,j))
...
>>> x+y
4
But note that you need to be sure about the identity of your items, because using exec() might harm your machine.
Or as a more pythonic approach you can use a dict:
>>> items = ("y","1","x","3")
>>> the_dict = {i:int(j) for i, j in zip(items[0::2], items[1::2])}
>>>
>>> the_dict['x'] + the_dict['y']
4
Again in this case you need be sure of the type of items because converting the digits might raise an exception if they are not valid digits.

Categories