Assign comparison operator to variable? - python

Is it possible to assign < to a variable, let's say b ?
For example:
b = < .
Edit:
My plan is the following:
a < b < c < d .
I want add the "compares" to a permutation. I know that I can add a b c d to a permutation but I have to change the < too. Please believe me that this is important for my plan. I have to find all possibilities.

You can do it like so
b = '<'
c = '+'
When you want to use it, you have to use the eval function.
eval('5' + b + '10') # '5<10'
>>> True
eval('5' + c + '10') # '5+10'
>>> 15

Related

Is this possible to use += to add a single value into two variables at the same time?

Following this logic :
a,b = 0,0
I was expecting this to work :
a,b += 1,1
SyntaxError: illegal expression for augmented assignment
so here i am.
Is there anyway to achieve this in one line ?
Think of it like a list of "how to update each variable" (variables to the left, formulas to the right).
a, b = a+1, b+1
As already mentioned by others, you could combine two statements into one line as a += 1; b += 1.
But, if you prefer a single statement in the same "spirit" as a, b = 0, 0 then try this:
a, b = a + 1, b + 1
The way these assignments work is that a list of variables is assigned a list of values:
variable
value
a
0
b
0
→ a = 0; b = 0 → a, b = 0, 0
variable
value
a
a + 1
b
b + 1
→ a = a + 1; b = b + 1 → a, b = a + 1, b + 1
You can either use multiple statements, one per table row, or a single statement where all the values in the left column go on one side of the = and all the values in the right column go on the other side.
This works only for = though. Your idea a, b += 1 firstly wouldn't work for the same reason a, b = 0 doesn't (there is only one right-hand side value), but a, b += 1, 1 unfortunately also doesn't work, just because Python doesn't support this concept. + with tuples would concatenate them into a larger tuple, not add each of their elements ((1, 2) + (3, 4) is (1, 2, 3, 4) and not (4, 6)).
If you want it in 1 line here is what you can do.. a,b=0 is not the right way , it should have been a=b=0 or a,b=0,0
a=b=0
a+=1;b+=1
You can use map to apply your increment or other operation
a,b=0,0
a, b = map( lambda x : x+1, [a,b])
output
1,1

pathlib get base path, given the absolute and relative paths

I have:
A = Path('/a/b/.../m/n/.../z.txt')
B = Path('n/.../z.txt')
I want:
C = Path('/a/b/.../m')
We have well defined, reliable functions for two of the three relationships between these paths:
B == A.relative_to(C)
A == C / B
C == A.unknown_operator(B)
Is there a clean, exact way to compute C given A and B? Or: What's the third, missing operation? Or must I resort to string manipulation?
What about path as string manipulation using str.removesuffix (since py3.9)
A = Path('/a/b/.../m/n/.../z.txt')
B = Path('n/.../z.txt')
C = Path(A.as_posix().removesuffix(B.as_posix()))
print(C) # /a/b/.../m
Or remove part from the end of A until A == C/B
C = Path(A.as_posix())
while C != Path("/") and not B == A.relative_to(C):
C = C.parent
You can use parents field of pathlib.Path:
C = (A.parents[len(B.parents)-1]
if 1 <= len(B.parents) <= len(A.parents) else None)
if C is None or A != C.joinpath(B):
# B is not a suffix of A, proceed accordingly

How to enter a Googol in Python?

I've heard that Python does not have any upper limit with integers. So I wanted to give a try:
a = 1e100
b = 1
c = a + b + a
c - 2 * a
> 0.0
Unfortunately I realized that writing 1e2 returns a float while 100 returns an int.
I've then tested with long('1' + '0' * 100) which works.
a = long('1' + '0' * 100)
b = 1
c = a + b + a
c - 2 * a
> 1L
Is this solution the only way to affect a Googol to a variable?
Subsequent question:
How to avoid confusion between floating point and fixed point during computations?
You can get a Googol like so:
10**100
I dont really understand your question but i think you are asking is there only this way to manipulate googol variable .
i just tried this on my python idle and got this
>>> a = 10 ** 100
>>> b = 1
>>> c = a + b + a
>>> c - 2 *a
1
>>>
You could use the power operator:
base**times
so 123 googols would be 123*10**100

python generators/ variable [duplicate]

This question already has answers here:
Multiple assignment and evaluation order in Python
(11 answers)
Closed 9 years ago.
2 questions...
1) I am trying to wrap my brain around this...
I am to understand that variables can take values using such code syntax as this:
a ,b = 2, 3
and that this would be the same as coding:
a = 2
b = 3
I hope this is correct.
So here is my puzzlement. I have the following code using a generator:
def fibonacci_generator() :
a = b = 1
while True :
yield a
a , b = b , a + b
fib = fibonacci_generator()
for i in fib :
if i > 100 :
break
else :
print ('Generated: ', i)
print (next(fib))
(yes this is code from a python learning book)
If I were to rewrite this code and instead assign my a and b variables like so:
yield a
a = b
b = a + b
then I get different returns for a.
I am not understanding why this is??? Super frustrated about it!
2) When I run the code as written the first time above, I get the number 233 printed at the end. I also cannot figure out why??!!
In this code:
a, b = b, a + b
a is set to b, and b is set to a+b.
In this code:
a = b
b = a + b
a is set to b, and b is afterwards set to a+b. But since a is already set to b, then b is in fact set to b+b.
a , b = b , a + b
is not the same as
a = b
b = a + b
Because, when you say
a, b = b, a + b
It will first prepare the values on the right side b, a + b and assign them to the variables on the left.
Python computes the right hand side first and then assigns the value (or unpacks it) on the left hand side. So, in the example:
a, b = b, a+b
compared to:
a = b
b = a + b
You have different values for a when you go to compute a + b. In the second example, when you compute a + b it is equivalent to computing b + b!
You are probably missing the flow of data.
a = b ...eqI
b = a+b ...eqII
here, before executing b eqII, a has already stored bas a value of itself. Now when yow try execute b of eqII it comes like b=b+b. Because after executing eqI when it comes to eqII, a is bnow.
But in python you can avoid this conflict if you try a, b = b, a+b.
For your second question:
I am not sure about your code but this one will work fine in the sense of your code...
a = b = 1
while True :
a , b = b , a + b
if a and b > 100:
break
else: print a, b
try it !!
In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables. Because that you get different results
a, b = b, a+b
This line computes b and a+b before performing any assignment. Strictly speaking, it computes a tuple (b, a+b) and then unpacks the elements of the tuple to assign them to a and b.
a = b
b = a+b
This assigns a, then computes a+b using the new value of a.

Python: Altering code between iterations

I have a bit of code that I want to run multiple times. That seams trivial but there is a twist: I want to change the code in a specific way between iterations. For example:
A = 1
B = ['+','-','/'.'*','**']
C = []
for x in range(len(B)):
C.append(A{B[x]}100)
print(C)
Now, I know this code doesn't work and it's not a proper Python syntax, but i't just an example of what I'd like the code to do.
Ideally I'd get C as a list where 0th element is 1 + 100, 1st element is 1 - 100, 2nd element is 1 / 100 etc. (N.b.: NOT '1 + 100' string. A result of 1 + 100 calculation - 101). Basically I want the code to change itself between iterations of loop in a defined way.
I do not want to define some lengthy if/elif statement since list B is very, very long.
Edit:
Let me give another example. This one is more relevant to my problem.
A = ['mom','dad','me','you','c']
B = ['a','b','something','nothing','cat']
for x in range(len(A)):
C_{A[x]} = B[x]
I want to end up with 5 new variables so that:
Print(C_mom)
a
Print(C_dad)
b
Print(C_c)
cat
Again, I recognize this is not a proper python syntax and this code doesn't work.
First create a dict where each string '+','*' etc point to it's corresponding method imported from operator module.
Now loop over B and fetch the corresponding method from the ops dict and pass the operands to the method.
>>> from operator import add,sub,mul,div,pow
>>> ops = {'+':add,'-':sub,'/':div, '*':mul,'**':pow}
>>> B = ['+','-','/','*','**']
>>> A = 1
>>> [ops[item](A,100) for item in B]
[101, -99, 0, 100, 1]
Use '/': operator.truediv if you want ops['/'](1,100) to return 0.01 instead of 0.
Update:
Creating dynamic variables in python is not a good idea, you should better use a dict here:
>>> A = [1,2,3,4,5]
>>> B = ['a','b','something','nothing','cat']
>>> c = {x:y for x,y in zip(A,B)}
>>> c[1]
'a'
>>> c[2]
'b'
>>> c[5]
'cat
Use globals() to create dynamic variables(don't use this method):
for x,y in zip(A,B):
globals()['C'+str(x)] =y
...
>>> C1
'a'
>>> C2
'b'

Categories

Resources