Iterating through functions using for loop - python

I currently have multiple functions as below:
vect_1 = CountVectorizer(parameters)
vect_2 = CountVectorizer(parameters)
vect_3 = CountVectorizer(parameters)
vect_3 = CountVectorizer(parameters)
which I am trying to iterate each one of them. I've tried:
for i in range(4):
vect = vect_[i]
print vect
And I am struggling to correctly defining 'vect' part as it just becomes a string. Any ideas please?
Thanks

This is the pythonic way to do it, using a list:
vects = [
CountVectorizer(parameters),
CountVectorizer(parameters),
CountVectorizer(parameters),
CountVectorizer(parameters)
]
for v in vects:
print(v)
Whenever you see that variable names are being generated dynamically from strings, that's a warning that you need a better data structure to represent your data. Like a list, or a dictionary.

Of course not this, but try globals (in def use locals):
for i in range(1,5):
vect = globals()['vect_%s'%i]
print(vect)
Although still the most pythonic way is using #Oscar's solution

You can just loop through all your parameters.
vectors = []
parameters = []
#Put code for adding parameters here
for parameter in parameters:
vectors.append(CountVectorizer(parameter))
This loops through the parameters you have set and runs the function with each parameter. You can now access all the outputs from the vectors list.

I prefer using list or dict
def func_a(a):
print(a)
def func_b(b):
print(b, b)
def func_c(c):
print(c, c, c)
def func_d(d):
print(d, d, d, d)
# use list
func_list = [func_a, func_b, func_c, func_d]
for i in range(4):
func_list[i](i)
# use dict
func_dict = {"vect_1": func_a,
"vect_2": func_b,
"vect_3": func_c,
"vect_4": func_d}
for i in range(1, 5):
func_dict["vect_" + str(i)](i)
which will print
0
1 1
2 2 2
3 3 3 3
1
2 2
3 3 3
4 4 4 4

Related

Assignments in for loops

This is something I wish to ask on top of the question that is already discussed:
Assigning values to variables in a list using a loop
So the link above says it is not recommended to perform assignments in a for loop because doing so changes only the reference of those values and doesn't change the original variable.
For example, if I wish to add 1 to each variable:
p = 1
q = 2
r = 3
a = [p,q,r]
for i in a:
i += 1
print(p, q, r)
# returns 1 2 3
So this doesn't change p, q, and r, since the values added by one are assigned to 'i'. I inquired some people about a possible solution to this issue, and one suggested that I try the 'enumerate' function. So I did:
p = 1
q = 2
r = 3
a = [p,q,r]
for idx, val in enumerate(a):
a[idx] = val + 1
print(p, q, r)
# returns 1 2 3
So it still doesn't work. Printing the list 'a' does return the list of values added by 1, but it still doesn't change the values assigned to p, q, and r, which is what I want.
So the only solution I currently have is to do the assignment for each variable manually:
p = 1
q = 2
r = 3
p += 1
q += 1
r += 1
print(p, q, r)
# returns 2 3 4
However, in a hypothetical setting where there are more variables involved than 3, such as 50 variables where I wish to add 1 to each value assigned, doing it manually is going to be very demanding.
So my question is, is there a solution to this without doing it manually? How do we accomplish this using the for loop? Or, if the for loop doesn't work for this case, is there another way?
You can maintain a dictionary, where the keys are strings (the names variables that you originally had) and the values are the integers that they're assigned to.
Then, you can do the following:
data = {
"p": 1,
"q": 2,
"r": 3
}
for item in data:
data[item] += 1
print(data)
This outputs:
{'p': 2, 'q': 3, 'r': 4}

how to do deletion of an element from array in python without using builtin functions

How to delete element in an array without using python builtin functions
I have tried this program with builtin functions, but I do not know how to do it without them
c = [6,7,8,9]
c.remove(c[0])
print(c)
I am getting expected result but I want it without using the built-in function in python.
This should do it, but this method creates a new array
c=[6,7,8,9]
d=[]
a=0
for x in c:
if x!=c[a]: #or you write c[0] and remove the a=0
d.append(x)
print(d)
you could use a list comprehension:
c = [ e for e in c if e != c[0] ]
However, if you have multiple instances of the c[0] value, they will all be removed.
removing by index can also be done using a list comprehension:
c = [ e for i,e in enumerate(c) if i != 0 ]
if you know the index of the element that you want to remove:
1) you can concatenate 2 slices of your list that has all the elements except the one you want to remove:
index_to_remove = 0
c = c[0:index_to_remove] + c[index_to_remove + 1:]
2) or by filtering using list comprehension:
c = [e for i, e in enumerate(c) if i != index_to_remove]
if you just want to delete the first element that has a certain value you can use the same methods, you just set:
index_to_remove = c.index(my_value)
from array import *
arr = array("i",[2,4,6,8,9])
del arr[2]
print(arr)
output-array("i",[2,4,8,9])

Are there any shorter way for this way?

Lets say i have variables a,b,c,d,e,f.. every time 2 of the 6 variables will have value = 0 randomly. So my code is like this
if(a == 0 and b == 0):
run c,d,e,f
elif(a == 0 and c == 0):
run b,d,e,f
...
...
continue until end of all combination
So the coding will be very long, are there any other approach ?
You can put all numbers into a list and then feed a list comp of that list into the run function - ignoring elements that are 0:
def run(p1,p2,p3,p4):
print(p1,p2,p3,p4)
# 3 test cases
for d in [ [ 1,2,0,3,4,0], [0,0,2,3,4,1], [4,3,0,2,1,0]]:
run(*[x for x in d if x]) # *[1,2,3] makes python provide the elements as params
Output:
1 2 3 4
2 3 4 1
4 3 2 1
run( *[1,2,3]) is the same as run(1,2,3)
0 is Falsy - so *[x for x in d if x] for a d=[0,1,2,3,0] does only use non falsy values of x in d: *[1,2,3]
truth value testing
you can exchange the list comp run(*[x for x in d if x]) against a generator comp if you like run(*(x for x in d if x)) to avoid the list creation (not that it matters here ;) )
#Mehrdad Dowlatabadi raised an interesting side question - if any other of the params is 0 you get an error due to a mismatch between function parameters and provided parameters from the list comprehension - you can negate that by defining defaults:
def run(p1=0, p2=0, p3=0, p4=0):
print(p1,p2,p3,p4)
So if you feed [0,1,2,0,0,0] into it it will still run.
If you want to run a function with the variables that aren't set to 0 you can first make a list of elements that are'nt 0
elements = [element for element in a, b, c, d, e if element !=0]
then call the function with elements list as arguments
run(*elements)
As a one liner :
run(*[element for element in a, b, c, d, e if element !=0])
Make run take a list:
def run(lst):
...
then use the filter function:
run(filter(None, [a, b, c, d, e, f]))
filter(None, lst) removes all fals-y elements.

Passing multiple arguments to scipy stats functions in python

I am trying to pass multiple arguments to some scipy stats functions in python eg. stats.kruskal but the problem is sometimes I got only three arguments sometimes i got many more and I do not know how to pass it dynamically. Here is what I got so far:
dependent_variable = dataset[attributes[0]]
independent_variable = dataset[attributes[1]]
dependent_variable_values = dataset[attributes[0]].unique()
i = 0
stre = ''
temp = []
for item in dependent_variable_values:
temp.append(dataset.loc[dataset[attributes[0]] == dependent_variable_values[i]])
i += 1
for i in range(i):
stre = temp[i]['Oceny']
i = i - 1
My first idea was to create string with these arrays but it does not work that way.
Here is example of the same code but less automatic which works fine but as I said before I will not get always only three arguments and know data so well. I want this code below more automatic to work with every data.
a = dataset['Group']
b = dataset['Mark']
c = dataset.loc[dataset['Group'] == '1'] #here I know that group contains only 3 possibly values 1, 2, 3 but I will know that in every case
d = dataset.loc[dataset['Group'] == '2']
e = dataset.loc[dataset['Group'] == '3']
testy = [c['Mark'], d['Mark'], e['Mark']] #marks for group 1, 2, 3
Use func(*args) or func(*position_args, **keyword_args)
https://docs.python.org/3/faq/programming.html#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another

Problems with the zip function: lists that seem not iterable

I'm having some troubles trying to use four lists with the zip function.
In particular, I'm getting the following error at line 36:
TypeError: zip argument #3 must support iteration
I've already read that it happens with not iterable objects, but I'm using it on two lists! And if I try use the zip only on the first 2 lists it works perfectly: I have problems only with the last two.
Someone has ideas on how to solve that? Many thanks!
import numpy
#setting initial values
R = 330
C = 0.1
f_T = 1/(2*numpy.pi*R*C)
w_T = 2*numpy.pi*f_T
n = 10
T = 1
w = (2*numpy.pi)/T
t = numpy.linspace(-2, 2, 100)
#making the lists c_k, w_k, a_k, phi_k
c_karray = []
w_karray = []
A_karray = []
phi_karray = []
#populating the lists
for k in range(1, n, 2):
c_k = 2/(k*numpy.pi)
w_k = k*w
A_k = 1/(numpy.sqrt(1+(w_k)**2))
phi_k = numpy.arctan(-w_k)
c_karray.append(c_k)
w_karray.append(w_k)
A_karray.append(A_k)
phi_karray.append(phi_k)
#making the function w(t)
w = []
#doing the sum for each t and populate w(t)
for i in t:
w_i = ([(A_k*c_k*numpy.sin(w_k*i+phi_k)) for c_k, w_k, A_k, phi_k in zip(c_karray, w_karray, A_k, phi_k)])
w.append(sum(w_i)
Probably you mistyped the last 2 elements in zip. They should be A_karray and phi_karray, because phi_k and A_k are single values.
My result for w is:
[-0.11741034896740517,
-0.099189027720991918,
-0.073206290274556718,
...
-0.089754003567358978,
-0.10828235682188027,
-0.1174103489674052]
HTH,
Germán.
I believe you want zip(c_karray, w_karray, A_karray, phi_karray). Additionally, you should produce this once, not each iteration of the for the loop.
Furthermore, you are not really making use of numpy. Try this instead of your loops.
d = numpy.arange(1, n, 2)
c_karray = 2/(d*numpy.pi)
w_karray = d*w
A_karray = 1/(numpy.sqrt(1+(w_karray)**2))
phi_karray = numpy.arctan(-w_karray)
w = (A_karray*c_karray*numpy.sin(w_karray*t[:,None]+phi_karray)).sum(axis=-1)

Categories

Resources