[英]how to define a function in Python 3 that sort an array and return the number that exists only once rather than twice
in this code I want to do the following 1- sort the array 2- Iterate over it to find an element that exists only once while every other element exist twice.在这段代码中,我想执行以下操作 1- 对数组进行排序 2- 迭代它以查找仅存在一次而其他每个元素都存在两次的元素。 e,g [2,1,3,2,3], answer is 1 3- In iteration I do the following ->If reached last element , then last element is the wanted ->If an element i is not equal to element i+1, then element i is the wanted 4- at the end return -1 if not found e,g [2,1,3,2,3], 答案是 1 3- 在迭代中,我执行以下操作 ->如果到达最后一个元素,则最后一个元素是想要的 ->如果元素 i 不等于元素i+1,然后元素 i 是想要的 4- 如果没有找到,最后返回 -1
this is my code, please help me, I am new in Python这是我的代码,请帮助我,我是 Python 新手
class Main:
def singleNumber(self, nums: List[int]) -> int:
sorted(nums)
l =len(nums)
while i<l:
if i+1==l:
re=nums(i)
if nums(i)!=nums(i+1):
re=nums(i)
else:
i+=1
re=-1
return re
you can use collections.Counter
with the built-in function sorted
:您可以使用带有内置函数sorted
collections.Counter
:
from collections import Counter
nums = [2,1,3,2,3]
sorted(k for k, v in Counter(nums).items() if v == 1)
output:输出:
[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.