[codewars][Python] Find the unique number

这是一篇关于如何在Python中找到数组中唯一不重复元素的博客。题目描述要求从包含多个重复数字的数组中找出那个独特的数字,且考虑到性能优化,因为测试用例可能包含大型数组。解决方案包括使用集合的去重特性以及利用count()方法来找出不重复的元素。
摘要由CSDN通过智能技术生成

题目:找出列表中唯一一个不重复的元素

There is an array with some numbers. All numbers are equal except for one. Try to find it!

find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55

It’s guaranteed that array contains more than 3 numbers.

The tests contain some very huge arrays, so think about performance.

My code:

def find_uniq(arr):
    # your code here
    length = len(arr)
    for i in range(1,length-1):
        if arr[i] != arr[i-1] and arr[i] != arr[i+1]:   #将元素与相邻的两个元素比较,是否相同
            return arr[i]
        elif arr[i] != arr[i-1] and arr[i] == arr[i+1]:  #不同的元素在列表开头
            return arr[i-1]
        elif arr[i] == arr[i-1] and arr[i] != arr[i+1]:   #不同的元素在列表结尾
            return arr[i+1]
        else:
            pass
python实现以下需求,并输出代码。a) Read “train.csv” data to your Python session. b) Check the dimension of the dataframe that you created in a). (How many number of rows and columns do you observe in the dataframe?) And print the column names of the dataframe. c) We want to find out the most common word in articles of class 2 (articles on stock price movement). Please do the following to solve this question. • Step 1. Create a variable named “combinedText” having an empty string (“”) value • Step 2. Define a variable “news” in a for loop to iterate over the articles of class 2 (df.news[df.label==2]) – Step 3. Add “combinedText” to “news” (we need to place an empty space (“ ”) in between them) and assign the resultant string back to “combinedText” • Step 4. Split “news” into words (you can use combinedText.split()) and assign the resultant list to “words” • Step 5. Find the unique words in “words” and assign the resultant list to “unique_words” • Step 6. Create an empty list named “word_freqs” • Step 7. Define a variable “word” in a for loop to iterate over “unique_words” – Step 8. Count the number of times “word” appears in “words” (you can use words.count(word)) and append the count to “word_freqs” • Step 9. Find the index of maximum value of “word_freqs”. (I suggest you to use numpy.argmax(word_freqs) where numpy is an external library that needs to be imported to your Python session.) And provide this index to “unique_words” to find the most common word.
04-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值