Python List/Tuple - python

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)]

Related

Is it possible to use slice in Python in list of complex objects with field of the object

I am new in Python and using python3.
I have list og objects of type points
class Po:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
C = [Po(0, j) for j in range(10)]
and 2 dimensional array
m = [[j for i in range(2)] for j in range(10)]
I want to assign all fields x of C to values with index 0 from m like
C[:].x = m[:][0]
but python says list doesn't have field x.
how can I do this and why I can' access x this way
There's no specific syntax for this in Python. You'll just need to use a regular for loop.
for ci, mi in zip(C, m):
ci.x = mi[0]
Your "C" instance is itself a list, so in order to access it's x or y values, you need to call the index first. So this way you can access them:
for i in range(10):
print(C[i].x)
print(C[i].y)

creating multible variable lists in a loop in python

I'm trying to make a loop that finds distances of values of one list, to the values of another list.
The data itself is of varying dimensions in a coordinates layout. Here is an example
x = ['1.23568 1.589887', '1.989 1.689']
y = ['2.5689 1.5789', '2.898 2.656']
I would like to be able to make a separate list for each y value and its distance from each x value.
There are always more x values than y values.
This is what I have so far:
def distances_y(x,y):
for i in y:
ix = [i.split(' ',)[0] for i in y]
for z in x:
zx = [z.split('',1)[0] for z in x]
distances_1 = [zx - ix for z in x]
return distances_1
print(i +"_"+"list") = [distance_1]
But I'm stuck on how to create individual lists for each y value.
Each distance also needs to be a list in itself, a list in a list so to speak.
The largest problem is that I am unable to use packages besides tkinter for this.
Try using a dictionary instead:
def distances_y(x,y):
dct = {}
for i in y:
ix = [i.split(' ',)[0] for i in y]
for z in x:
zx = [z.split('',1)[0] for z in x]
distances_1 = [zx - ix for z in x]
return distances_1
dct[i +"_"+"list"] = [distance_1]
And to get the values, do:
print(dct)
And if you want to get a specific key name, try:
print(dct[<key name over here>])
And if you want a 2-d array:
for each x you would add
my2d.append([])
and for each y
my2d[i].append(x[i] - y[j])

How can I print variables from the following for loop?

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().

How do you swap integers in a list when those integers may repeat

My list contains random integers in no order. I want to swap elements while keeping the order of the list intact.
ran=[1,1,2,1]
And I want to swap say 1 and 2:
swap(ran,1,2)
output:
2212
or
ran=[3,3,1,2]
swap(ran,1,3)
output:
1132
I tried a swap function, but I know my iteration logic isn't very good.
def swap(c,x,y):
arr=[]
for i, v in enumerate(c):
if v==x or v==y:
for j,v2 in enumerate(c):
if v2==y or v2==x:
arr[i], arr[j] = arr[j], arr[i]
This just changes one of the values.
The problem is not knowing which index has been changed already.
The examples you gave suggest the process you want isn't really a "swap" of individual elements as such, but more like a bi-directional "search and replace". If that's what's needed, a much simpler loop would work:
def swap(c, x, y):
for i, v in enumerate(c):
if v == x:
c[i] = y
elif v == y:
c[i] = x
Use a dict to encode the swapping logic and index into it with get(e, e). Any non-swappable elements that aren't in the dict will be left alone.
>>> def swap(lst, x, y):
... swaps = {x: y, y: x}
... return [swaps.get(e, e) for e in lst]
...
>>> swap([1, 1, 2, 1], 1, 2)
[2, 2, 1, 2]
You can generalize this by letting the caller pass in a dictionary to specify the swaps. Here's a closely related question.
I think you could use something like this:
def swap(lst,x,y):
ret = lst
for e in range(0,length(lst)):
if x == lst[e]:
ret[e] = y
if y == lst[e]:
ret[e] = x
return ret

A Python numpy array is being rewritten in a loop - shouldn't be doing this

Using Anaconda, I have written a simple code and I am at wit's end trying to figure out how an array keeps getting rewritten in a for loop after it's defined. I write the array (random 0 or 1s) named box and define a new array holder as a "copy" of the array I want to leave alone. However, box keeps getting rewritten and I just don't see how it should be doing this.
#FUNCTIONS
def initialize():
config = np.zeros([n, n])
for x in range(n):
for y in range(n):
if np.random.rand() < p:
config[x, y] = 1
return config
def roller(x):
test1 = np.roll(x,1,axis=0)
test2 = np.roll(x,1,axis=1)
test3 = np.roll(x,-1,axis=1)
test4 = np.roll(x,-1,axis=0)
hold = np.sum([test1,test2,test3,test4],axis=0)
return hold
def loop(steps,holder,store_config):
for t in range(steps):
tot = roller(holder)
for x in range(n):
for y in range(n):
if tot[x,y] >= 4:
holder[x,y] = 1
else:
holder[x,y] = 0
store_config[:,:,t] = holder
def func():
start = time.time()
time_steps = 20
store_config = np.zeros([n,n,time_steps])
loop(time_steps,holder,store_config)
end = time.time()
print(end - start, np.sum(store_config))
#CONSTANTS
n = 100
p = .2
box = initialize() #Array to leave ALONE
print(np.sum(box))
#Action
holder = box #Array to manipulate and redefine as box
func()
print(np.sum(box))
If you the value from the output of np.sum(box) should match before and after func() is ran , but they never do. The intention was that when I rerun func(), it spits out a value, but just iterates over the same defined "box" array but it keeps getting rewritten. I don't see how its possible. I thought arrays were treated like variables inside a function where they're not global? Each of the three sections #Functions, #Constants, and #Action would be in their own cells in a Conda Notebook.
I think the issue you are having is that arrays, just as lists and dicts, are assigned by reference. This happens no matter if it's a variable assignment or as an argument being passed to a function.
def f(x):
x[0] = 0
return x
a = array([1, 1])
b = f(a)
WILL result in a and b being equal, since x is being manipulated and then returned. If you want to retain a, you must copy the array first:
def f(x):
x_ = x.copy()
x_[0] = 0
return x_
I hope this clarifies things a bit. :-)
The line holder = box doesn't create a new copy of the array, it causes holder to point to the same array as box. Since your code modifies holder, you want to make holder point to a copy of box so that it doesn't get overwritten. You can do this using np.copy() as in:
holder = np.copy(box)

Categories

Resources