How can I print a list of lists backwards in Python 3.x?
I have created an adjacency list by writing a list of lists as following:
adjazenzListe = [[1], #0
[1, 3], #1
[1], #2
[4, 5],#3
[3], #4
[3, 6, 7],#5
[5], #6
[8, 10],#7
[9, 10], #8
[8], #9
[7, 8, 11],#10
[10, 12, 13], #11
[11], #12
[14, 15],#13
[13], #14
[13]]#15
Now I want to print that but not in order 0, 1, 2, 3... but backwards (15, 14, 13...).
My current way of printing works via for-loop:
n = len(adjazenzListe)
for k in range(0,n):
print(k, ": ", adjazenzListe[k])
Now I looked a bit through Google and found stuff like using index [::-1] or the built-in reversed function. But these don't work with list as indices.
You must not have been using the indices correctly.
Try the following:
adjazenzListe = [[1], #0
[1, 3], #1
[1], #2
[4, 5],#3
[3], #4
[3, 6, 7],#5
[5], #6
[8, 10],#7
[9, 10], #8
[8], #9
[7, 8, 11],#10
[10, 12, 13], #11
[11], #12
[14, 15],#13
[13], #14
[13]]#15
for i, k in enumerate(adjazenzListe[::-1]):
print(len(adjazenzListe) - i - 1, k)
With reverse:
adjazenzListe = [[1], #0
[1, 3], #1
[1], #2
[4, 5],#3
[3], #4
[3, 6, 7],#5
[5], #6
[8, 10],#7
[9, 10], #8
[8], #9
[7, 8, 11],#10
[10, 12, 13], #11
[11], #12
[14, 15],#13
[13], #14
[13]]#15
adjazenzListe.reverse()
for i, k in enumerate(adjazenzListe):
print(len(adjazenzListe) - i - 1, k)
>>> n = len(adjazenzListe)-1
>>> for k in range(n,-1,-1):
... print(k, ": ", adjazenzListe[k])
Martijn Pieters was spot on, as usual
Hmmm I am not sure why you had problems using the alternative techniques stated. Though there have already been great answers of using range() and list slicing, I am just going to showcase another technique for future visitors to this page:
Approach 1: The reversed() function
adjazenzListe = [[1], #0
[1, 3], #1
[1], #2
[4, 5],#3
[3], #4
[3, 6, 7],#5
[5], #6
[8, 10],#7
[9, 10], #8
[8], #9
[7, 8, 11],#10
[10, 12, 13], #11
[11], #12
[14, 15],#13
[13], #14
[13]]#15
for row in reversed(adjazenzListe):
print(row)
reversed() will simply reverse the order of a sequential object or structure when evaluated against a loop variable. Please note that this function is best used in loop statements, with range() or conditional statements if used by itself. If you wish to use it for variable assignment, you will need to accompany it with a formatting function such as list() to see your results if output. See example below:
adjazenzListe = [[1], #0
[1, 3], #1
[1], #2
[4, 5],#3
[3], #4
[3, 6, 7],#5
[5], #6
[8, 10],#7
[9, 10], #8
[8], #9
[7, 8, 11],#10
[10, 12, 13], #11
[11], #12
[14, 15],#13
[13], #14
[13]]#15
reversed_list = list(reversed(adjazenzListe))
for row in reversed_list:
print(row)
As previously stated: It can also be used with range():
adjazenzListe = [[1], #0
[1, 3], #1
[1], #2
[4, 5],#3
[3], #4
[3, 6, 7],#5
[5], #6
[8, 10],#7
[9, 10], #8
[8], #9
[7, 8, 11],#10
[10, 12, 13], #11
[11], #12
[14, 15],#13
[13], #14
[13]]#15
for i in reversed(range(len(adjazenzListe))):
print(adjazenzListe[i])
Here is a reference for further learning: https://www.geeksforgeeks.org/python-reversed-function/
Related
I would like to achieve the following in an efficient way in numpy. Suppose I have a matrix
A = np.asarray([[1, 2], [3, 4]])
and a vector of the following form
B = np.asarray([7, 8, 9])
What I would like to achieve is the following: Take the first element in B and add it to all elements in A. Then we take the second element of B and so on. At the end I would like to get a matrix of the form (A.shape[0]*B.shape[0],A.shape[1]). The result in this case should be (hopefully on typo):
np.asarray([[8, 9], [10, 11], [9, 10], [11, 12], [10, 11], [12, 13]])
Out[142]:
array([[ 8, 9],
[10, 11],
[ 9, 10],
[11, 12],
[10, 11],
[12, 13]])
Add two new axes to B to its end and then perform addition, thus leveraging broadcasting and finally a reshape for 2D output such that the number of columns is same as in A -
In [396]: (A + B[:,None,None]).reshape(-1,A.shape[-1])
Out[396]:
array([[ 8, 9],
[10, 11],
[ 9, 10],
[11, 12],
[10, 11],
[12, 13]])
Also, this is basically outer addition, so with the builtin -
In [399]: np.add.outer(B,A).reshape(-1,A.shape[-1])
Out[399]:
array([[ 8, 9],
[10, 11],
[ 9, 10],
[11, 12],
[10, 11],
[12, 13]])
You can also achieve this with np.tile:
In [42]: (A + np.tile(B[:, None, None], A.shape)).reshape(
A.shape[0] * B.shape[0], A.shape[1]
)
Out[42]:
array([[ 8, 9],
[10, 11],
[ 9, 10],
[11, 12],
[10, 11],
[12, 13]])
For summation purposes, I created a list of tuples, where multiple items in the list have the same first variable.
for example:
x = [('m32',[1,2,3]),('m32',[2,3,4]),('m32',[4,5,6]),('m33',[1,2,3]),('m33',[2,3,4]),('m33',[4,5,6]),('m34',[1,2,3]),('m34',[2,3,4]),('m34',[4,5,6])....]
I want to add the individual values of the second items in the tuples (i.e 1+2+4, 2+3+5, 3+4+6) for all values that have the same first item (i.e. 'm32').
In other words, for all items labeled 'm32', I want to be able to add the other values.
How can I slice/index this to loop through and perform the summation?
Some tricky zip magic, along with itertools.groupby to group the matching first items together:
>>> x = [('m32',[1,2,3]),('m32',[2,3,4]),('m32',[4,5,6]),('m33',[1,2,3]),('m33',[2,3,4]),('m33',[4,5,6]),('m34',[1,2,3]),('m34',[2,3,4]),('m34',[4,5,6])]
>>> from itertools import groupby
>>> from operator import itemgetter
>>> for k,g in groupby(x,key=itemgetter(0)):
... print (k,[sum(i) for i in zip(*zip(*g)[1])])
...
('m32', [7, 10, 13])
('m33', [7, 10, 13])
('m34', [7, 10, 13])
A breakdown of how it works:
g is the group of items with matching keys. zip(*g) transposes the matrix, bringing the keys and values together:
>>> for k,g in groupby(x,key=itemgetter(0)):
... print zip(*g)
...
[('m32', 'm32', 'm32'), ([1, 2, 3], [2, 3, 4], [4, 5, 6])]
[('m33', 'm33', 'm33'), ([1, 2, 3], [2, 3, 4], [4, 5, 6])]
[('m34', 'm34', 'm34'), ([1, 2, 3], [2, 3, 4], [4, 5, 6])]
Getting the 2nd items:
>>> for k,g in groupby(x,key=itemgetter(0)):
... print zip(*g)[1]
...
([1, 2, 3], [2, 3, 4], [4, 5, 6])
([1, 2, 3], [2, 3, 4], [4, 5, 6])
([1, 2, 3], [2, 3, 4], [4, 5, 6])
Transposing again to match up the items to sum:
>>> for k,g in groupby(x,key=itemgetter(0)):
... print zip(*zip(*g)[1])
...
[(1, 2, 4), (2, 3, 5), (3, 4, 6)]
[(1, 2, 4), (2, 3, 5), (3, 4, 6)]
[(1, 2, 4), (2, 3, 5), (3, 4, 6)]
And adding them up:
>>> for k,g in groupby(x,key=itemgetter(0)):
... print [sum(i) for i in zip(*zip(*g)[1])]
...
[7, 10, 13]
[7, 10, 13]
[7, 10, 13]
The answer given by Mark is great, and probably much more efficient that the one I'll post you. But I still want to post my answer because you are probably new to python and it will be easy for you to understand it.
For this kind of scripts you only need some imagination and basic python notions:
dictionary={}
for name, numbers in x:
if name in dictionary:
current_list=dictionary[name]
for i in range(3):
current_list[i]+=numbers[i]
else:
dictionary[name]=numbers
print(dictionary)
Note that the output is a dictionary:
{'m32': [7, 10, 13], 'm33': [7, 10, 13]}..
I hope it help you!
I have python lists like follows
>>>[[2, 0, 10], [2, 0, 11], [2, 1, 12], [2, 1, 13], [4, 3, 5], [4, 3, 7], [7, 6, 8], [7, 6, 10], [10, 9, 2], [10, 9, 11], [13, 14, 15]]
>>>[[0, 1, 3], [0, 1, 6], [3, 2, 0], [3, 2, 6], [3, 4, 5]]
I want to extract largest list set containing uncommon values. For example, for latter list, the largest independent set should be [[0, 1, 6], [3, 4, 5]], whereas for the former, it should be [[2, 0, 12], [4, 3, 5], [7, 6, 8], [10, 9, 11], [13, 14, 15]]. It may be similar with maximum independent set problem, but I have no idea about this as I know nothing about graphs. So any suggestion to solve this problem? Thanks in advance.
I have a large graph made in networkx, and I used the clique function to find the largest clique for each node:
thecliques = nx.node_clique_number(mygraph)
However, no matter how much I search, I am unable to find the members of the maximal clique for each node. Does anyone know how to do this?
May not be computationally optimal as it enumerates all cliques, but you can use:
G= nx.barabasi_albert_graph(20, 2, seed=1234)
dict_of_cliques=nx.cliques_containing_node(G,nodes=None,cliques=None)
print dict_of_cliques
Output is a dictionary {node:list of lists of nodes in clique, including node}. IE:
{0: [[0, 3, 2], [0, 3, 7], [0, 4, 8], [0, 5], [0, 9, 13], [0, 15], [0, 17], [0, 19]], 1: [[1, 2, 11], [1, 4], [1, 5]], 2: [[0, 3, 2], [1, 2, 11], [6, 2], [18, 2]], 3: [[0, 3, 2], [0, 3, 7], [12, 3]], 4: [[0, 4, 8], [1, 4], [6, 4], [12, 4], [18, 4]], 5: [[0, 5], [1, 5], [14, 5]], 6: [[6, 2], [6, 10, 16], [6, 10, 9], [6, 4]], 7: [[0, 3, 7]], 8: [[0, 4, 8]], 9: [[0, 9, 13], [6, 10, 9], [14, 9]], 10: [[6, 10, 16], [6, 10, 9], [10, 19]], 11: [[1, 2, 11], [11, 17]], 12: [[12, 3], [12, 4], [12, 15]], 13: [[0, 9, 13]], 14: [[14, 9], [14, 5]], 15: [[0, 15], [12, 15]], 16: [[6, 10, 16]], 17: [[0, 17], [11, 17]], 18: [[18, 2], [18, 4]], 19: [[0, 19], [10, 19]]}
Crucially you can see here that the maximal cliques may not be unique, so it is up to you how you will select the largest clique.
I have a number, x, and I wish to find all unique ways to write a*b*c. By unique I mean 2*3*5 is the same as 3*2*5 or 5*3*2.
I've got a working algorithm that takes the prime factorization of x and then divvies up factors into three bins but it's quite slow and brute and I have to remove duplicates later, so I am curious if there is a faster way to generate unique combinations here directly.
Consider the number 720.
[3, 5, 48]
[5, 9, 16]
[3, 15, 16]
[3, 3, 80]
[2, 5, 72]
[5, 6, 24]
[5, 8, 18]
[2, 15, 24]
[2, 3, 120]
[3, 10, 24]
[6, 8, 15]
[3, 8, 30]
[3, 6, 40]
[2, 8, 45]
[2, 9, 40]
[8, 9, 10]
[4, 5, 36]
[5, 12, 12]
[4, 12, 15]
[3, 4, 60]
[3, 12, 20]
[4, 4, 45]
[4, 9, 20]
[2, 2, 180]
[2, 10, 36]
[2, 12, 30]
[2, 6, 60]
[6, 10, 12]
[2, 4, 90]
[2, 18, 20]
[4, 10, 18]
[4, 6, 30]
[6, 6, 20]
In Python:
def trifactorgenerator(n):
return (((i,j,n/(i*j))
for i in range(1, int(n**.5)+1) if n%i==0
for j in range(i, int( (n/i)**.5)+1) if n%(i*j) == 0))
This function has the interesting effects:
It is a true generator -- the entire list is never in memory unless the caller creates such a list
Each tuple is sorted (e.g., (2,3,4) never (2,4,3)
It returns no duplicates
The tuples are returned in lexicographic order.
Ref: https://stackoverflow.com/a/6800214/8747