7-2 Finding Wonders (20 points) Python

In a sequence of positive integers of length n, all odd numbers appear even times, and only one odd odd number appears odd times. Your task is to find this strange flower.

Input format:
Input firstly give a positive integer n (≤10 ​4 ) in the first line , and then give n positive integers that meet the description of the title in the following line. Each value does not exceed 10 ​5 , and the numbers are separated by spaces.

Output format:
output the odd number in one line. The title guarantees that this weird thing exists.

Input sample:

12
23 16 87 233 87 16 87 233 23 87 233 16

Sample output:

233
Author unit Code length limit time limit Memory limit
Chen Yue Zhejiang University 16 KB 400 ms 64 MB

Problem-solving ideas:

There are three key judgment points in this question:

  1. Is this number odd? Only odd numbers satisfy the characteristics of strange numbers
  2. This number has appeared several times, how to count
  3. How to judge whether this number appears odd or even times

Corresponding ideas:

  1. Only odd numbers meet the characteristics of odd numbers, so the result of %2 can be judged and even numbers can be filtered out.
  2. Declare one dictto store the number of occurrences of each number. First, by indetermining this number is absent dict, if the direct value+1, if not, add to this a number key, valuefor the 1value pairs
  3. Because the condition of the question is known, only one odd number appears once. So you only need dict.keys()to traverse in to get the keycorresponding valuejudgment valuewhether it can be divisible by 2. If not, then this is the answer, output it keyand exit the program.

AC code:

n = input()		#对应题目给的输入格式,作为占位符,不做他用
ques = list(map(int, input().split()))		#获取输入的数字并存入列表中
temp = {
    
    }		#声明一个字典
for i in ques:		#遍历需要求解的列表
    if i % 2 == 1:		#如果这个数是个奇数(偶数直接忽略):
        if i in temp:		#再判断这个数是否存在于字典中
            temp[i] = temp[i] + 1		#如果存在,值+1
        else:
            temp[i] = 1		#如果不存在,即本次是第一次出现,新增且值为1
for i in temp.keys():	#遍历字典
    if temp[i] % 2 == 1:	#判断出现次数是否为奇数
        print(i)	#打印结果
        exit(0)		#退出程序

Edit, add another solution, thanks to the idea provided by @C^super .

Problem-solving ideas:

XOR operation, the same results as 0, and the result of XOR operation with any number that is not 0 is itself. Therefore, you can use this feature to do XOR operations to remove even-numbered numbers, and the final result is the "exotic number" you need.

AC code:

n = input()  # 同上,占位符
ques = [i for i in list(map(int, input().split())) if i % 2 == 1]  # 列表生成式获取输入的奇数集合
ans = 0  # 初始化ans
for i in ques:
    ans ^= i  # 与列表中每个元素做异或运算
print(ans)  # 输出结果

XOR learning reference:

Knowing the column: Talking about the Xor of the Python logical operator xor https://zhuanlan.zhihu.com/p/96147159

Guess you like

Origin blog.csdn.net/weixin_44289959/article/details/111058253