Easiest way to initialize a large number of variables - python

Assume you are given a large number of variables that need to be initialized to None. A naive way to do this would be to count the number of variables on the left, and create a list of the same size on the right:
a, b, c, d, e, f, g, h, i, j = [None]*10
Is there a way to do this without having to count the variables? If one uses this pattern often, it could become tedious to have to count the number of variables.

a = b = c = d = e = f = g = h = i = j = None
Note: don't use this for mutable types. If you're curious why, this demonstrates:
>>> a = b = []
>>> a.append(1)
>>> a
[1]
>>> b
[1]

Is there a reason you're not doing this?
a = b = c = d = e = f = g = h = i = j = None
I'm not too familiar with the intricacies of Python's syntax so please correct me if I'm wrong.

Related

How to iterate through a list to create combinations of n successive values and use them independently in Python?

from PIL import Image
imagen_base = Image.open(imagen_base)
a = Image.open(a)
b = Image.open(b)
c = Image.open(c)
d = Image.open(d)
e = Image.open(e)
f = Image.open(f)
lista=[a,b,c,d,e,f]
First, you would have a base image:
image_base = Image.open (image_base)
Second, you would have a list of images:
a = Image.open(a)
b = Image.open(b)
c = Image.open(c)
d = Image.open(d)
e = Image.open(e)
f = Image.open(f)
list = [a, b, c, d, e, f]
The objective would be to obtain three new images; place the ab, cd and ef combinations above the base image thanks to the paste function inside the module.
If i'm understanding your question correctly, you just to find a way to group items N successive items in a list? If so, you could try:
combined = []
for idx, val in enumerate(_list):
if (_list[idx] == 0) | (idx % 2 == 0):
combined.append((_list[idx], _list[idx + 1]))
Which will return:
combined = [(a, b), (c, d), (e, f)]
Now, in this example I am using .append() method to put them back into a list for clarity, but you can replace that with whatever functions you require in your task.

sympy .subs() built-in function doesn't work

I'm trying to implement the multivariate chain rule using python, when I try to substitute one of the elements using the built-in sympy function expr.subs() I won't get an answer.
The exercise goes as follows:
Compute df/dx of the following function using the chain rule:
a = x^2
b = exp(a)
c = a + b
d = log(c)
e = sin(c)
f = d + e
⁡
And this is the code:
a, b, c, d, e, f = sym.symbols('a b c d e f')
f = d + e
dfd = sym.diff(f, d)
dfe = sym.diff(f, e)
df = sym.Matrix([[dfd, dfe]])
d = sym.log(c)
e = sym.sin(c)
ddc = sym.diff(d)
dde = sym.diff(e)
dd = sym.Matrix([[ddc],[dde]])
dfdd = df#dd
c = a + b
dca = sym.diff(c, a)
dcb = sym.diff(c, b)
dc = sym. Matrix([[dca, dcb]])
dfdc = dfdd#dc
a = x**2
b = sym.exp(a)
result = dfdc.subs(c, (a + b))
result
The result the function .subs() doesn't substitute anything and I don't know why, I tried substituting it using other ways to write the function, like:
dfdc.subs({c : (a + b)})
dfdc.subs(c, a + b)
And even tried to just substitute it for an integer to see it that would work and neither does it.
What am I doing wrong?
The c in your dfdc expression was created before you set c=a+b. So it still appears as c in dfdc. However, by the time you want to do your subs, the c symbol is declared as c=a+b, and so your substitute really reads
dfdc.subs(a+b, a+b)
And that does nothing.
In order to really use c there, do
dfdc.subs(sym.Symbol('c'), a+b)

How to concatenate over 2 ndarray(variable) in loop (one of these is EMPTY in first loop )

I want to achieve this function in Python like Matlab
in matlab, the code is
A = [];
for ii = 0:9
B = [ii, ii+1, ii**2];
C = [ii+ii**2, ii-5];
A = [A, B, C];
end
but in Python, use np.hstack or np.concatenate, the ndarray must have same number of dimensions
if the A in first loop is empty, the code will make mistake as following:
for ii in range(10):
B = np.array([ii, ii+1, ii**2])
C = np.array([ii+ii**2, ii-5])
if ii == 0:
A = np.hstack([B, C])
else:
A = np.hstack([A, B, C])
and, that is my Python code, B and C are variable, not repeat the ndarray, plz don't close my question!
for ii in range(10):
B = np.array([ii, ii+1, ii**2])
C = np.array([ii+ii**2, ii-5])
if ii == 0:
A = np.hstack([B, C])
else:
A = np.hstack([A, B, C])
but, i think it a little troublesome and unreadable.
how can i rewrite it?(It's better to use only one line of code)
Without knowing what the result Should be - I think this is close
import numpy as np
q = np.arange(10)
bs = np.vstack((q,q+1,q**2)).T
cs = np.vstack((q,q**2,q-5)).T
a = np.hstack((bs,cs))
Or maybe:
a = np.hstack((bs,cs)).ravel()

Dask delayed: pass combination of two lists

I have a feeling this should be easily possible, but I fail to pass combinations of (lazy) lists to a delayed function:
def test(a,b):
return(str(a)+','+str(b))
a = [1,2] #not lazy for example
b = [3,4] #not lazy
c = dask.delayed(test)(a,b)
c = c.compute()
out:
'[1,2][3,4]'
desired output:
['1,3','1,4','2,3','2,4']
Also tried:
def test(c):
a = c[0]
b = c[1]
return(str(a)+','+str(b))
def combine_a_b(a,b):
return([(i,j) for i in a for j in b])
c = dask.delayed(combine_a_b)(a,b)
c = dask.delayed(test)(c)
c = c.compute()
out:
'(1,3)(1,4)'
What am I doing wrong here?

How to test all possible values ​for all variables to get the maximum result for the function

I have three variables called a, b and c, each of these can assume a different value defined in a range. I'd like to create a function that tests every possible variable value and gives me their best combination for the output 'f'.
a = list(range(1, 10, 2))
b = list(range(5, 8, 1))
c = list(range(1, 3, 1))
def all_combinations (a, b, c):
#something
f = a + (b * a) - (c*(a ^ b))
return BEST a, b, c for my f
it's possible to do it ? what is the best way to do it?
You can use itertools.product() to get all the possible combinations of a, b, and c.
Then calculate your formula for each unique combination of a b c, keep track of the result, and if the result is better than the previous best, save the current values of a b c.
import itertools
def all_combinations (alist, blist, clist):
best_a = 0
best_b = 0
best_c = 0
best_f = 0
for a,b,c in itertools.product(alist, blist, clist):
f = a + (b * a) - (c*(a ^ b))
if f > best_f: # use your own definition of "better"
best_a = a
best_b = b
best_c = c
best_f = f
return best_a, best_b, best_c
First of all, you said I have three variables called a, b and c, each of these can assume a different value defined in a range. Note that the variables in your code are actually equal to three lists of integers, not three integers.
The naive algorithm to test all possible combinations is 3 nested for loops. Here I assume that by "best" you mean "maximum value":
def all_combinations (list1, list2, list3):
best_f, best_a, best_b, best_c = None, None, None, None
for a in list1:
for b in list2:
for c in list3:
f = a + (b * a) - (c*(a ^ b))
# here you have to define what f being "better" than best_f means:
if not f or f > best_f:
best_f = f
best_a = a
best_b = b
best_c = c
return best_a, best_b, best_c
If you're sure those are the only values you want to test, then the following will work. Otherwise you might want to look into scipy.optimize.
from itertools import product
import numpy as np
parameters = list(product(a, b, c))
results = [my_fun(*x) for x in parameters]
print(parameters[np.argmax(results)])
obviously replace np.argmax with np.argmin if you want to minimize the function

Categories

Resources