Double for loop in a dictionary in python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a dictionary with keys from 1 to N. I would like to go through this dictionary with a double for loop so that I don't take two elements at the same time (k goes from 1 to N-1 and j from k+1 to N). I need to this efficiently as I will have to repeat this operation. Is there anyway to do a dictionary comprehension so as to go through the keys as: k goes from 1 to N-1 and j from k+1 to N?

If the order of the keys don't matter, you can do it like this
my_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
from itertools import combinations
for key1, key2 in combinations(my_dict.keys(), r = 2):
print key1, key2
Output
a c
a b
a d
c b
c d
b d

By your description, it sounds like you're trying to access the upper triangle of (what should be) an array, so you can use numpy's triu(http://docs.scipy.org/doc/numpy/reference/generated/numpy.triu.html).
As others have said, using a dictionary is probably not the best choice.

On "What I want to do is go through all the couples of objects in the dictionary and compute the distance between them"
You can use numpy broadcasting to calculate the distances, it's fast:
In [175]: locs=np.array([1,2,4,6])
In [176]: np.abs(locs[:, None]-locs)
Out[176]:
array([[0, 1, 3, 5],
[1, 0, 2, 4],
[3, 2, 0, 2],
[5, 4, 2, 0]])
and you can use the index e.g., locs[0][3] to get distance between element 0 and element 3 directly.

Related

How to find the count of numbers that are less than each element of a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I have a list [1,2,3,4,5,6,7], for each element in the list, I need to find the count of a number of elements that are less than the number. For example, the first element is 1 and there are 0 elements in the list that are less than 1, the second number is 2 and there is 1 element less than 2. So basically the output should be [0,1,2,3,4,5,6]. Need to do this in Python. Any help would be appreciated. Below is the code I've tried,
lst = [1,2,3,4,5,6,7]
count = 0
final = []
for i in range(len(lst)):
for j in range(i+1,len(lst)):
if lst[i] < lst[j]:
count = count + 1
final.append(count)
print (final)
Below is the output I got,
[6, 11, 15, 18, 20, 21, 21]
Try:
lst = [1, 2, 3, 4, 5, 6, 7]
out = [sum(vv < v for vv in lst[:i]) for i, v in enumerate(lst)]
print(out)
Prints:
[0, 1, 2, 3, 4, 5, 6]

matching and joining key/val of dictionaries in list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
this is a list, I got lists like this :
k = [{a:1}, {b:2}, {c:3}, {d:4}, {a: 5}] and t = [{a:6}, {b:7}, {c:8}, {d:9}, {a: 10}]
if a's dictionary key in k is matching with t's dictionary key in t, then extract value and key in dictionary
and then I want to reorganize like below:
newlist = [a is 1 and 6, b is 2 and 7, c is 3 and 8, d is 4 and 9, a is 5 and 10]
From your description, it is little hard to understand what you require exactly, but I have done my best to obtain what I think you need! :-)
k = [{'a':1}, {'b':2}, {'c':3}, {'d':4}, {'a': 5}]
t = [{'a':6}, {'b':7}, {'c':8}, {'d':9}, {'a': 10}]
newlist = []
for i in range(min(len(k), len(t))):
letter_k, value_k = [*k[i].items()][0]
letter_t, value_t = [*t[i].items()][0]
if letter_k == letter_t:
newlist.append({letter_k: [value_k, value_t]})
This will yield:
newlist = [{'a': [1, 6]}, {'b': [2, 7]}, {'c': [3, 8]}, {'d': [4, 9]}, {'a': [5, 10]}]
Note that I did not combine the dictionaries due to duplicate keys!

How to Transfer a number in an array from one position to another

I would like to know how to transfer a number.
For example: [1,0,2,3,4]
Remove the one and transfer the one to two's position
Result: [0,0,1,3,4]
If your manipulations are purely index-based, you can do this:
lst = [1,0,2,3,4]
lst[2] = lst[0]
lst[0] = 0
# [0, 0, 1, 3, 4]
Alternatively, if you need to work out the index of 2:
lst[lst.index(2)] = lst[0]
lst[0] = 0
Since you have not described your question with clear instructions, There is case when there will be more than one 2 or 1 in vector then what you want to do ?
My solution is only for that condition when there is single 1 and 2 in vector because when you use .index method it always returns first value index no matter there are other values too.
Since in your dataset there is always 1 times 1 and 2 in all vector so here is the solution for that
data=[[1, 2, 3, 4, 0], [1, 3, 2, 4, 0], [2, 1, 3, 4, 0] ]
def replace_ (vector_ , replace_value, replace_with):
memory=vector_.index(replace_with)
vector_[vector_.index(replace_value)]=vector_[vector_.index(replace_with)]
vector_[memory]=0
return vector_
for i in data:
print(replace_(i,1,2))
If there are more than one 1 or 2 in vector like [1,0,1,1,2,2] then describe your logic and edit your question for that.

Count number of complementary pairs in array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am rookie with python and have question about counting pairs in array that complement to some certain number.
Example
Given an integer array A find all the complementary pairs in A that sums up to a provided value K, so for example given the array [2, 45, 7, 3, 5, 1,8,9] and an integer K = 10 the result must be 3 because the input array contains [9, 1] [7, 3] [8, 2]
Here is the code finding complementary pairs
def find_pairs(x, sum):
s = set(L)
for i in L:
diff = 10-i
s.remove(i)
if diff in s:
print i, diff
L = [2, 45, 7, 3, 5, 1, 8, 9]
sum = 10
find_pairs(L, sum)
How can I add count command at the end?
Use a simple counter variable
def find_pairs(list_, sum_):
s = set(list_)
pairs = 0
for i in list_:
diff = sum_ - i
s.remove(i)
if diff in s:
pairs += 1
return pairs
Or you can use a helper list for storing pairs if you also want to know the pairs
def find_pairs(list_, sum_):
s = set(list_)
pairs = []
for i in list_:
diff = sum_ - i
s.remove(i)
if diff in s:
pairs.append([i, diff])
return pairs
L = [2, 45, 7, 3, 5, 1, 8, 9]
pairs = find_pairs(L, 10)
print pairs
>>> [[2, 8], [7, 3], [1, 9]]
print len(pairs)
>>> 3
Using numpy:
A = np.asarray(A)
np.count_nonzero((A[None, :] + A[:, None]) == K) // 2

Generating repetitive data in numpy / pandas in a fast vectorized way [duplicate]

This question already has answers here:
Retrieving array elements with an array of frequencies in NumPy
(3 answers)
Closed 8 years ago.
Suppose I want to generate a 1D array like this:
1 1 1 1 2 2 2 3 3 4
In general I am looking for something with this form:
Element N-repetition
1 n-0
2 n-1
3 n-2
4 n-3
. .
. .
. .
n n-(n-1)=1
This is of course possible by combining arrays of
sizes n, n-1, n-2, ..., but I am wondering if there is
a better, vectorized way of doing this?
Its very simple with Numpy's repeat:
n = 4
a = np.arange(1,n+1)
The array a looks like:
array([1, 2, 3, 4])
And you basically want to repeat it with the reverse of a, so:
np.repeat(a, a[::-1])
Gives:
array([1, 1, 1, 1, 2, 2, 2, 3, 3, 4])
I came up with something myself, but it's a little complicated:
def makegenarr(n):
def genarr(x):
return np.repeat(x, n-(x-1))
return(genarr)
x = np.arange(1, 5)
mapfunc = makegenarr(x.shape[0])
np.apply_along_axis(genarr, 0, x)

Categories