Python Array Intersection - python-3.x

This is my code to find values common between 2 arrays.
li1 = [int(x) for x in input().split()]
li2 = [int(h) for h in input().split()]
for m in li1 :
for j in li2 :
if m == j :
print(m, end=" ")
j = float("-inf")
break
When I do li1 = [5, 5, 5] and li2 = [5, 5], it returns 5 5 5. I want this to be 5 as li2 only has two 5. How can I do this.

You can do the same more simply by using sets and intersection:
li1 = [1, 2, 3]
li2 = [2, 3, 4]
shared = list(set(li1).intersection(set(li2))
print(shared) # prints [2, 3]

Related

I want an efficient way of comparing columns of data to make a decision

I have a CSV file that I read using pandas. I would like to make a comparison between some of the columns and then use the outcome of the comparison to make a decision. An example of the data is shown below.
A
B
C
D
6
[5, 3, 4, 1]
-4.2974843
[-5.2324843, -5.2974843, -6.2074043, -6.6974803]
2
[3, 6,4, 7]
-6.4528433
[-6.2324843, -7.0974845, -7.2034041, -7.6974804]
3
[6, 2, 4, 5]
-3.5322451
[-4.3124440, -4.9073840, -5.2147042, -6.1904800]
1
[4, 3, 6,2]
-5.9752843
[-5.2324843, -5.2974843, -6.2074043, -6.6974803]
7
[2, 3, 4, 1]
-1.2974652
[-3.1232843, -4.2474643, -5.2074043, -6.1994802]
5
[1, 3, 7, 2]
-9.884843
[-8.0032843, -8.0974843, -9.2074043, -9.6904603]
4
[7, 3, 1, 4]
-2.3984843
[-7.2324843, -8.2094845, -9.2044013, -9.7914001]
Here is the code I am using:
n_A = data['A']
n_B = data['B']
n_C = data['C']
n_D = data['D']
result_compare = []
for w, e in enumerate(n_A):
for ro, ver in enumerate(n_B):
for row, m in enumerate(n_C):
for r, t in enumerate(n_D):
if ro==w:
if r ==row:
if row==ro:
if r==0:
if t[r]>m:
b = ver[r]
result_compare.append(b)
else:
b = e
result_compare.append(b)
elif r>=0:
q = r-r
if t[q]>m:
b = ver[q]
result_compare.append(b)
else:
b = e
result_compare.append(b)
I had to select only the columns required for the comparison and that was why I did the following.
n_A = data['A']
n_B = data['B']
n_C = data['C']
n_D = data['D']
Results could be as:
result_compare = [6, 3 , 3, 4, 7 , 1, 4 ]
The values in D are arranged in descending order which is why the first element of the list is selected in this case. So when the first element in the row of the list D is greater than the one of C, we choose the first element of the list B, otherwise A. I would like an efficient way since my code takes lots of time to provide results most especially in the case of large data.
I would do this in your case
data['newRow']=data.apply(lambda row: row["B"][0] if row["D"][0] > row["C"] else row['A'], axis=1)
And if you need it as a list by the end:
list(data['newRow'])

Random change of rows of two matrices using indices

Any idea or clue about writing below problem code in python 3.6?
Imagine I have matrix A and B as below:
A = [1 2, 3 4, 5 6] with the dimension of 3*2
B = [1, 3, 5] with the dimension of 3*1
Now I want to change the rows randomly using indices.
for instance index 1 related to [1 2] from A and [1] from B, index 2 related to [3 4] from A and [3] from B, index 3 related to [5 6] from A and [5] from B.
Imagine randomly I order the indices as 2, 3, 1, now my output will be:
A=[3 4, 5 6, 1 2]
B=[3, 5, 1]
import numpy as np
A = [[1, 2],[3, 4], [5, 6]]
A = np.array(A)
B = [[1], [3], [5]]
B = np.array(B)
import random
def rand(n):
l = list(range(n))
random.shuffle(l)
l = np.reshape(l, (n,1)) return l l = rand(3)
print(l)
AF = []
AFF = []
BF = []
BFF = []
for i in range (0, len(A)):
AF = A[l[i]]
AFF.extend(AF)
BF = B[l[i]]
BFF.extend(BF)
B = np.array(BFF)
A = np.array(AFF)
print(B)
print(A)

Please explain me this code?

rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
I am not able to understand how it will print the transpose when we use it in for loop . Can someone explain the working thoroughly ?
#Parakh, you did not specify what m is, so I made it a 2d array:
m = [[6, 2],
[3, 4]]
rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
print(rez)
[[6, 3], [2, 4]]
This is the same as:
```
m = [[6, 2],
[3, 4]]
rez = []
for i in range(len(m[0])):
temp = []
for j in range(len(m)):
temp.append(m[j][i])
rez.append(temp)
print(rez)
```
This is producing column 0, row 0 (6) and column 0, row 1 (3) as the first new list,
then column 1, row 0 (2) and column 1, row 1 (4) as the second new list.
j is the row index, i is the column index.
i[0], j[0] = 6
i[0], j[1] = 3
i[1], j[0] = 2
i[1], j[1] = 4

Compute distance metric in a complete graph

Suppose I have an array, namely Map. Map[i][j] means the distance between area i and area j. Under this definition, we get:
a) Map[i][i] always equals 0.
b) Map[i][k] <= Map[i][j] + Map[j][k] for all i,j,k
I want to build a function func(Map,k) returning a metric D, while D[i][j] is the shortest distance of a route from area i to area j, and this route should pass through at least k different area.
This is my python code to do so:
def func(Map,k):
n=len(Map)
D_temp = [list(x) for x in Map]
D = [list(x) for x in Map]
for m in range(k - 1):
for i in range(n):
for j in range(n):
tmp = [D[i][x] + Map[x][j] for x in range(n) if x != i and x != j]
D_temp[i][j] = min(tmp)
D = [list(x) for x in D_temp]
return D
func([[0, 2, 3], [2, 0, 1], [3, 1, 0]],2)
return a distance metric D which equals [[4, 4, 3], [4, 2, 5], [3, 5, 2]]
D[0][0] equals 4, because the shortest route from area0 to area0 which pass through at least 2 area is {area0-->area1-->area0}, and the distance of the route is Map[0][1]+Map[1][0]=2+2=4
Wanted to know what would be the best way to do that?
You can use the A* algorithm for this, using Map[i][j] as the heuristic for the minimum remaining distance to the target node (assuming that, as you said, Map[i][j] <= Map[i][x] + Map[x][j] for all i,j,x). The only difference to a regular A* would be that you only accept paths if they have a minimum length of k.
import heapq
def min_path(Map, k, i, j):
heap = [(0, 0, i, [])]
while heap:
_, cost, cur, path = heapq.heappop(heap)
if cur == j and len(path) >= k:
return cost
for other in range(len(Map)):
if other != cur:
c = cost + Map[cur][other]
heapq.heappush(heap, (c + Map[other][j], c, other, path + [other]))
Change your func to return a list comprehension using this min_path accordingly.
def func(Map, k):
n = len(Map)
return [[min_path(Map, k, i, j) for i in range(n)] for j in range(n)]
res = func([[0, 2, 3], [2, 0, 1], [3, 1, 0]], 2)
This gives me the result [[4, 4, 3], [4, 2, 3], [3, 3, 2]] for len(path) >= k, or [[4, 4, 3], [4, 2, 5], [3, 5, 2]] for len(path) == k.

Why does swapping fail in python?

I was trying to write a program that would reverse a list in python3. I first tried:
def reverse(lst):
""" Reverses lst in place.
>>> x = [3, 2, 4, 5, 1]
>>> reverse(x)
>>> x
[1, 5, 4, 2, 3]
"""
n = len(lst)
for i in range(n//2):
lst[i], lst[n-i-1] = lst[n-i-1], lst[i]
It failed and the x I got was the original value. However, when I changed my code to this, it worked:
def reverse(lst):
""" Reverses lst in place.
>>> x = [3, 2, 4, 5, 1]
>>> reverse(x)
>>> x
[1, 5, 4, 2, 3]
"""
n = len(lst)
for i in range(n//2):
temp = lst[i]
lst[i] = lst[n-i-1]
lst[n-i-1] = temp
It works as expected:
>>> def reverse(lst):
... n = len(lst)
... for i in range(n//2):
... lst[i], lst[n-i-1] = lst[n-i-1], lst[i]
...
>>> lst = [1,2,3,4,5]
>>> reverse(lst)
>>> print(lst)
[5, 4, 3, 2, 1]
BTW, why don't you use list.reverse?
>>> lst = [1,2,3]
>>> lst.reverse()
>>> lst
[3, 2, 1]

Resources