K
K
Kirill2021-05-25 13:38:03
Python
Kirill, 2021-05-25 13:38:03

Is it possible to shorten code with numpy?

monitors = []
pairs = 0

for i in range(int(input())):
    wh = input().split()
    for monitor in monitors:
        if len(set(wh) & set(monitor)) > 0:
            pairs += 1
    monitors.append(wh)

print(pairs)


There is such a code. The number of elements is entered, after which the elements themselves from 2 numbers separated by a space. We need to find the number of possible pairs. Condition - the elements of this pair must have one common number.

Work example:
4
4 5
2 4
6 4
2 3

Answer - 4
Pairs - 4 5 and 2 4, 4 5 and 6 4, 2 4 and 6 4, 2 4 and 2 3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-05-25
@Vindicar

What numbers can be in pairs? If any, then the matter becomes more complicated.
If small integers are positive, then we can calculate like this.
You build a two-dimensional array, where the first index is the first number of the pair, the second is the second.
You fill with zeros, then you increase the element by one each time such a pair is encountered.
If two pairs have a common number, they will lie on the same row or on the same column.
Then if a pair has no common numbers with others, then the sum of the values ​​on its row and its column will be 1.
If two pairs have a common number, then the sum of the values ​​on their common row/column will be 2. And so on.
Hence the conclusion: for each row and each column, calculate the sum of the values ​​minus 1 (but limit from below to zero!). Add up the numbers you get and you'll get your answer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question