How can I print variables from the following for loop? - python

import numpy as np
def initialize_parameters(n, L):
for i in range(0, L):
globals()['W%s' % i] = np.random.randn(n[i], n[i-1]) * 0.01
n = [2, 3, 1]
L = 3
initialize_parameters(n, L)
print(W0, '\n', W1, '\n', W2)
Instead of writing W0, W1, etc. in the last print function, I want a print function to print all Ws

Since you asked how to turn this into a list I will go through it step by step.
In python a list is a set of objects surrounded with square brackets (e.g. n in your code is a list). Knowing this we can simply change your function like this to create a list and then add new values to it with the append function:
def initialize_parameters(n, L):
a_list = []
for i in range(0, L):
a_list.append(np.random.randn(n[i], n[i-1]) * 0.01)
However as we are no longer using global variables there are a couple of other things we have to do to make this list accessible.
Firstly we need to tell the function to return the list:
def initialize_parameters(n, L):
a_list = []
for i in range(0, L):
a_list.append(np.random.randn(n[i], n[i-1]) * 0.01)
return a_list
Secondly when we call this function we have to assign it to a new variable:
list_of_Ws = initialize_parameters(n, L)
Now all you have to do is print(list_of_Ws) and you will see all of the values or print(list_of_Ws[0]) for the first value, etc. for the rest of the values.

You could theoretically iterate over globals() and output the value:
for g in list(globals()):
if g.startswith("W"):
print(globals()[g])
But as #MisterMiyagi wrote in the comment, I would store the values in a list, not in globals().

Related

How can I use zip function for this?

for i in range(2200):
calculate_path(r_mercury, mercury_track, i)
calculate_path(r_venus, venus_track, i)
calculate_path(r_earth, earth_track, i)
calculate_path(r_mars, mars_track, i)
calculate_path(r_jupiter, jupiter_track, i)
calculate_path(r_saturn, saturn_track, i)
calculate_path(r_uranus, uranus_track, i)
calculate_path(r_neptune, neptune_track, i)
This is the code, I would like to optimize it using zip, is there any way I can do that?
And the first And the first parameter of calculate_path is an int, second one is empty list, but I am appending values in function.
I would not call this optimizing since it doesn't improve anything, but here is a shorter implementation:
r_planets = [r_mercury, r_venus, r_earth]
planets_tracks = [mercury_track, venus_track, earth_track]
for i in range(2200):
for r_planet, planets_track in zip(r_planets, planets_tracks):
calculate_path(r_planet, planets_track, i)
Alternatively, with one less for loop (but still the same number of iteration anyway):
import itertools
r_planets = [r_mercury, r_venus, r_earth]
planets_tracks = [mercury_track, venus_track, earth_track]
for p, i in itertools.product(zip(r_planets, planets_tracks), range(2200)):
r_planet = p[0] # can be remove
planets_track = p[1] # can be remove
calculate_path(r_planet, planets_track, i) # can be replace with calculate_path(p[0], p[1], i)

Python Function is returning none although there is the original Value instead of copy

I have a code where I zero a column or row if it contains zero , I have my own function but when I use it it returns None , I made a copy of my matrix and performed changes on it and then I converted the values to the original one and yet I still get no return . my function shouldn't return values only update the matrix values. here's the code:
def ConvertMatrix(NumOfRows,M):
for i in range(numOfRows):
Col=len(M[i])
M1=[[M[i][j] for j in range(Col)] for i in range(numOfRows)]
for i in range(numOfRows):
for j in range(Col):
if M[i][j]==0:
for n in range(Col):
M1[i][n]=0
for k in range(numOfRows):
M1[k][j]=0
M=[[M1[i][j] for j in range(Col)] for i in range(numOfRows)]
numOfRows = int(input())
M = [[int(item) for item in input().split(' ')] for i in range(numOfRows)]
M=ConvertMatrix(numOfRows,M)
print(M)
ConvertMatrix(numOfRows, M) does not return anything which means it implicitly returns None. Hence
M = ConvertMatrix(numOfRows, M)
turns M into None. There are two changes you should apply in order to make this mutation function approach work:
Change the last line in the function to:
M[:] = [[M1[i][j] for ...]
# slice assignment mutates the passed list object ...
# otherwise you are just rebinding a local variable
Do not assign the function result:
# ...
ConvertMatrix(numOfRows, M)
print(M)

Adding matrix elements as the nested lists by list comprehension (and zip) in Python

I've tried to proceed with adding the matrix elements of 2 matrices by
using list comprehension and zip, as I thought it would be so simple to perform. Unfortunately, and I've tried to do this in the proverbial "overly clever" way and I failed. I still don't understand where I've made a mistake and exercising my brain in complex comprehension structures is the piece of training I miss.
The code by which I tried to perform adding of 2 matrices in the form of nested lists:
Example input at the def main():
It looks like this fragment produces major error:
new_matrix[index] = zip(row, other[index])
IndexError: list assignment index out of range
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
def add(self,number_of_rows, number_of_columns, other):
new_matrix = [[] * len(self.matrix)]
if len(self.matrix) == len(other) and len(self.matrix[0]) == len(other[0]):
for index, row in enumerate(self.matrix):
new_matrix[index] = zip(row, other[index])
return [[x + y for (x, y) in new_matrix[index]] for index in range(0, len(new_matrix))]
def main():
matrix1 = Matrix([[1,2,3], [2,3,4],[4,5,6]])
matrix2 = matrix1.add([[1,2,3],[2,3,4],[4,5,6]])
print(matrix2)
if __name__ == '__main__':
main()
The problem is new_matrix = [[] * len(self.matrix)]
I assume you expect is that [[] * 3] will give:
[[], [], []] but it is not.
[]*N is just [] for every N
so your new_matrix is list with only ONE element which is [] and when you try to assign to new_matrix[1] you get your error.
Instead perform:
new_matrix = [[]] * len(self.matrix)
I haven't tested the rest of your code
update - checked your example with my fix and it is working

Python List/Tuple

Hi i want to modify my list so it shows an (x) at the given coordinate via tuple.
Here is my code so far
#w=width
#h=height
#c=coordinates
new_grid = []
def coordinates(w,h,c):
'''
>>> coordinates(2, 4, (0, 1))
>>> print(new_grid)
[['(_)', '(x)'], ['(_)','(_)'], ['(_)', '(_)'], ['(_)', '(_)']]
'''
b=[]
for i in range(h):
new_grid.append(b)
for j in range(w):
c=('(_)')
b.append(c)
i am not sure how to implement (x) at the given coordinates, any help is appreciated
thanks.
There are multiple errors in your approach:
You declare the global variable new_grid, but later you have grid.append(b)
Globals are usually not needed, you could create the grid in the function and update the global using the function's return value
The two for-loops are separate. Remember that indentation matters in Python
b is declared outside of the loops, and so you append to the same instance all the time
You overwrite your original coordinate tuple c with the string '(_)'
Here's a version that I think does what you were originally after:
def coordiantes(w,h,c):
'''
>>> print(coordiantes(2, 4, (0, 1)))
[['(_)', '(x)'], ['(_)','(_)'], ['(_)', '(_)'], ['(_)', '(_)']]
'''
grid = []
for i in range(h):
b = []
grid.append(b)
for j in range(w):
if (i, j) == c:
b.append('(x)')
else:
b.append('(_)')
return grid
You could also implement the whole thing as a list comprehension:
def coordiantes(w, h, c):
return [['(x)' if c == (y, x) else '(_)' for x in range(w)]
for y in range(h)]

Largest even number in a list using fold

I want to accomplish this:
Construct a function that takes in a list as a parameter and returns the biggest even number in that list.
Do this by using the "fold" function in Python
I thought it might be something along the lines of:
def fold(f, v, l):
for x in l:
v = f(v, x)
return v
def biggest_even_number(xs):
l = [i for i in xs if i % 2 == 0]
return fold(l)
I know this is wrong but I just don't know how to set this up. How would I accomplish the above task using the "fold" function?
fold function looks good. You just need to call it with correct arguments:
def biggest_even_number(xs):
l = [i for i in xs if i % 2 == 0]
return fold(max, float("-inf"), l)
If it is not a homework, you can use builtin reduce() which basically does the same thing:
def biggest_even_number(xs):
l = [i for i in xs if i % 2 == 0]
return reduce(max, l, float("-inf"))
Thanks to #Steven Rumbalski, for anyone trying to find the maximum value of a sequence, you don't even need reduce:
def biggest_even_number(xs):
return max(i for i in xs if i % 2 == 0)
Do something like the following:
def fold(l):
biggest = float("-inf")
for i in l:
biggest = max(i, biggest)
return biggest
def biggest_even_number(xs):
l = [i for i in xs if i % 2 == 0]
return fold(l)

Categories

Resources