CCF-CSP 201403-1 Opposite number (python)

Question name

201403-1 Opposite number

Problem Description

There are N non-zero and different integers. Please make a program to find out how many pairs of opposite numbers are in them (a and -a are a pair of opposite numbers).

Input format

The first line contains a positive integer N. (1 ≤ N ≤ 500).
The second line is N non-zero integers separated by a single space, and the absolute value of each number does not exceed 1000, to ensure that these integers are different.

Output format

Only output an integer, that is, how many pairs of opposite numbers are contained in these N numbers.

Sample input

5
1 2 3 -1 -2

Sample output

2

solution

n = int(input())
# 输入N 个用单个空格隔开的非零整数, .split() 会使用空格作为分隔符将数据存入l中
l = input().split()
# map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
# Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。
l = list(map(int, l))
l_length = len(l)
sum = 0
for i in range(l_length):
    if i == l_length - 1:
        break
    for j in range(i + 1, l_length):
        if l[i] == -l[j]:
            sum += 1
print(sum)

Guess you like

Origin blog.csdn.net/qq_43503670/article/details/115034867