How do I create a grid in python with different values? - python-2.7

I'm trying to write a 4X4 grid in python where the last two rows contain the same numbers as the first two rows.
The end result should be exactly this:
0 1 2 3
4 5 6 7
0 1 2 3
4 5 6 7
The goal is to make a game where the above grid is traversable. I've tried list comprehensions and concatenating two lists and it's not producing the right answers.

Concatenating two lists should work. The code for concatenating two lists
l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
l3 = [l1 , l2];
l4 = l3+l3
print l4
should yield [[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4], [5, 6, 7, 8]]

Related

Can someone help me understand how this piece of code to sort elements of a list in descending order works?

I just would like to understand the passages of how this piece of code operates:
llist = [5, 2, 1, 4, 3]
for i in range(len(llist)):
for j in range(i+1):
if llist[j] < llist[i]:
temp = llist[i]
llist[i] = llist[j]
llist[j] = temp
print(llist)
I tried to meticulously go through every passage of the nested loop, but I can't understand how at the end of all that new-variable-assigning the elements of the list get sorted from highest to lowest.
Thank you very much to anyone who can help
With a bit of printing:
llist = [5, 2, 1, 4, 3]
for i in range(len(llist)):
print()
print(f'current pivot is {llist[i]} on position {i}')
for j in range(i+1):
if llist[j] < llist[i]:
print('-----------------------------------------------------------------')
print((f'\t {llist[j]} in position {j} and {llist[i]} on position {i} are in'
' the wrong order'))
print(f'\t before swapping our list is : {llist}')
temp = llist[i]
llist[i] = llist[j]
llist[j] = temp
print(f'\t after swapping we have {llist}')
print('-----------------------------------------------------------------')
print(f'list at the end of iteration: {llist}')
You get:
current pivot is 5 on position 0
list at the end of iteration: [5, 2, 1, 4, 3]
current pivot is 2 on position 1
list at the end of iteration: [5, 2, 1, 4, 3]
current pivot is 1 on position 2
list at the end of iteration: [5, 2, 1, 4, 3]
current pivot is 4 on position 3
-----------------------------------------------------------------
2 in position 1 and 4 on position 3 are in the wrong order
before swapping our list is : [5, 2, 1, 4, 3]
after swapping we have [5, 4, 1, 2, 3]
-----------------------------------------------------------------
-----------------------------------------------------------------
1 in position 2 and 2 on position 3 are in the wrong order
before swapping our list is : [5, 4, 1, 2, 3]
after swapping we have [5, 4, 2, 1, 3]
-----------------------------------------------------------------
list at the end of iteration: [5, 4, 2, 1, 3]
current pivot is 3 on position 4
-----------------------------------------------------------------
2 in position 2 and 3 on position 4 are in the wrong order
before swapping our list is : [5, 4, 2, 1, 3]
after swapping we have [5, 4, 3, 1, 2]
-----------------------------------------------------------------
-----------------------------------------------------------------
1 in position 3 and 2 on position 4 are in the wrong order
before swapping our list is : [5, 4, 3, 1, 2]
after swapping we have [5, 4, 3, 2, 1]
-----------------------------------------------------------------
list at the end of iteration: [5, 4, 3, 2, 1]
So we you can see, every time it finds that a number on the list has another number to its left that is smaller than the number at hand, then it swaps them.
For 5, it does nothing as there are no numbers to its left.
For 2, it does nothing as 5 is the only number to the left and it's > 2.
For 1, it does nothing as 5 and 2 are the only numbers to the left and they are both > 1.
For 4, it finds 2 as a number to its left, so we swap them and have:
[5,2,1,4,3] -> [5,4,1,2,3]
So now we continue and find 1 to the left of 2 (since now 2 is in the 3rd position), so we swap again
[5,4,1,2,3] -> [5,4,2,1,3]
Does that help?

How to put in variable as list

I'm trying to make a program that for a sublist of numbers, uses index as a variable and selects each number from the list of lists
so if my numbest = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 5, 7, 9, 11]]
I want to be able to call the function like this
column_sum(2, [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 5, 7, 9, 11]]) will add the numbers at index 2 in each sublist (3, 6, and 7) and will return the number 16."
I can't for the life of me figure out how to print
for i in numlist:
print numbest[index]
Looks like Python, so imma say that all you need to do is have a variable that is a running total, add up all the numbers that are the values at the index you specify, and then return that value.
Alexander is also right and if his way is easier for you, you can find resources https://www.w3schools.com/python/ref_func_sum.asp and https://www.w3schools.com/python/python_lists_comprehension.asp

Writting in sub-ndarray of a ndarray in the most pythonian way. Python 2

I have a ndarray like this one:
number_of_rows = 3
number_of_columns = 3
a = np.arange(number_of_rows*number_of_columns).reshape(number_of_rows,number_of_columns)
a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
But I want something like this:
array([[0, 100, 101],
[3, 102, 103],
[6, 7, 8]])
To do that I want to avoid to do it one by one, I rather prefer to do it in arrays or matrices, because later I want to extend the code.
Nothe I have change a submatrix of the initial matrix (in mathematical terms, in terms of this example ndarray). In the example the columns considered are [1,2] and the rows [0,1].
columns_to_keep = [1,2]
rows_to_keep = [0,1]
My first try was to do:
a[rows_to_keep,:][:,columns_to_keep] = np.asarray([[100,101],[102,103]])
However this doesn't modify the initial a, I am not having any error, so a=
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
So I have implemented a piece of code that goes do the job:
b = [[100, 101],[102, 103]]
for i in range(len(rows_to_keep)):
a[i,columns_to_keep] = b[i]
Al thought the previous lines do the job I am wondering how to do it slicing and in a faster fashion. Also in a way that with:
columns_to_keep = [0,2]
rows_to_keep = [0,2]
the desired output is
array([[100, 1, 101],
[3, 4, 5],
[102, 7, 103]]).
Many thanks!
Indexing with lists like [1,2] is called advanced indexing. By itself it produces a copy, not a view. You have to use one indexing expression, not two to assign or change values. That is a[[1,2],:] is a copy, a[[1,2],:][:,[1,2]] += 100 modifies that copy, not the original a.
In [68]: arr = np.arange(12).reshape(3,4)
Indexing with slices; this is basic indexing:
In [69]: arr[1:,2:]
Out[69]:
array([[ 6, 7],
[10, 11]])
In [70]: arr[1:,2:] += 100
In [71]: arr
Out[71]:
array([[ 0, 1, 2, 3],
[ 4, 5, 106, 107],
[ 8, 9, 110, 111]])
Doing the same indexing with lists requires arrays that 'broadcast' against each other. ix_ is a handy way of generating these:
In [73]: arr[np.ix_([1,2],[2,3])]
Out[73]:
array([[106, 107],
[110, 111]])
In [74]: arr[np.ix_([1,2],[2,3])] -= 100
In [75]: arr
Out[75]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
Here's what ix_ produces - a tuple of arrays, one is (2,1) in shape, the other (1,2). Together they index a (2,2) block:
In [76]: np.ix_([1,2],[2,3])
Out[76]:
(array([[1],
[2]]), array([[2, 3]]))
For the continuous rows and columns case, you can use basic slicing like this:
In [634]: a
Out[634]:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [635]: b = np.asarray([[100, 101],[102, 103]])
In [636]: a[:rows_to_keep[1]+1, columns_to_keep[0]:] = b
In [637]: a
Out[637]:
array([[ 0, 100, 101],
[ 3, 102, 103],
[ 6, 7, 8]])

Select the value in the matrix/ array/ list

I was a beginner in python programming. What is the difference:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
with
a = [0 1 2 3 4 5 6 7 8 9]
I have
a = [0 1 2 3 4 5 6 7 8 9]
I want to form a matrix / array / list with values <= 6, in order to obtain:
a1 = [0 1 2 3 4 5 6]
How do I get the a1?
Sorry if my question has been asked before.
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
is a valid list,
a = [0 1 2 3 4 5 6 7 8 9]
is not a valid list
Assuming you want to turn:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
into
a = [0, 1, 2, 3, 4, 5, 6]
you could use list comprehension:
a1 = [x for x in a if x <= 6]
or a for loop:
a1 = []
for x in a:
if x <= 6:
a1.append(x)
The list comprehension solution is more pythonic though.

When changing data inside a list using a for loop, how do you append the list to a dictionary each time the loop iterates?

Basically, wanted to iterate over a list of numerical data to change it's contents, where the numerical at the start of the list is moved to the last, and then the data is shifted to the left. Whilst I have achieved this, as the printed contents of the loop gives the desired results, when trying to append the contents of said loop to said dictionary, it only does this for the final iteration. Here's my code:
minor=[1,2,3,4,5,6]
MNP = {'scale degree' : []
}
def patterns(scale):
for i in scale:
print (scale)
scale.insert(len(scale),scale[0])
del(scale[0])
MNP['scale degree'].append(scale)
using the function patterns, this is the output:
>>> patterns(minor)
the list, minor, is at the top of the page by the way.
output:
[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 1]
[3, 4, 5, 6, 1, 2]
[4, 5, 6, 1, 2, 3]
[5, 6, 1, 2, 3, 4]
[6, 1, 2, 3, 4, 5]
Yet when I try to print the contents of the list, scale degree, in the MNP dict, the result is:
MNP['scale degree']
[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]
I am very perplexed by this result, it's as if the output changes depending on the operation called upon it?
Thank you for any help in advance. It's also worth noting that I've been stuck with this for a good amount of time, so if there's any resources out there that may help me understand similar occurrences i certainly wouldn't pass that up.
The reason this happens is because what you store in MNP['scale degree'] is only a reference to scale. So when you change scale, so do the entries in MNP['scale degree']. What you need to do to avoid this is copying scale each time you append it (i.e. creating a new list instead of adding a reference). You can do this with the copy module:
import copy
minor=[1,2,3,4,5,6]
MNP = {'scale degree' : []
}
def patterns(scale):
for i in scale:
print (scale)
scale.insert(len(scale),scale[0])
del(scale[0])
MNP['scale degree'].append(copy.copy(scale))
patterns(minor)
print(MNP['scale degree'])