Python实现互联网笔试题-百度-关于排序sorted()函数
来源:互联网 发布:阿里云香港主机建立ss 编辑:程序博客网 时间:2024/06/05 23:59
1.
时间限制:1秒
空间限制:32768K
度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同。度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少?
输入描述:
首先输入一个正整数N(N <= 50),接下来输入N个数表示每顶帽子的价格(价格均是正整数,且小于等于1000)
输出描述:
如果存在第三便宜的帽子,请输出这个价格是多少,否则输出-1
输入例子:
1010 10 10 10 20 20 30 30 40 40
输出例子:
30
自己编写的代码如下:
import sysn = int(sys.stdin.readline())price = sys.stdin.readline().strip().split()print pricepriceOrder = sorted(price)print priceOrderi=j=0while i<len(priceOrder)-1 and j<3: if priceOrder[i] == priceOrder[i+1]: i+=1 else: j+=1 if j==1: i+=1if j<2: print -1else: print priceOrder[i+1]
运行测试时,有一个测试用例未通过:
测试用例:
40
1 1 1 1 1 1 1 1000 1 1 1 1 1 2 1 1 1 999 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1
对应输出应该为: 999
你的输出为: 2
40
1 1 1 1 1 1 1 1000 1 1 1 1 1 2 1 1 1 999 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1
对应输出应该为: 999
你的输出为: 2
然后打印出了用sorted()排序好后的List:
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1000', '2', '2', '999']
发现1000排在了2前面。程序是输出排序完后第三个不同于前两个的值,因为是已排序所以我没考虑大小,所以输出了2。
为什么会导致这样的情况呢?
思考了一下,发现问题所在:这里的priceOrder的类型是string,所以sorted()按照第一个字符大小排序。把它转成int再排序,修改程序如下:
import sysn = int(sys.stdin.readline())price = sys.stdin.readline().strip().split()priceInt=[int(i) for i in price]priceOrder = sorted(priceInt)i=j=0while i<len(priceOrder)-1 and j<3: if priceOrder[i] == priceOrder[i+1]: i+=1 else: j+=1 if j==1: i+=1if j<2: print -1else: print priceOrder[i+1]
2.
度度熊有一个N个数的数组,他想将数组从小到大排好序,但是萌萌的度度熊只会下面这个操作:
任取数组中的一个数然后将它放置在数组的最后一个位置。
问最少操作多少次可以使得数组从小到大有序?
输入例子:
4
19 7 8 25
输出例子:
2
(这题思考主要是统计出相对位置正确的个数。上例中,7 8 就是相对位置正确的。)
程序参考,来自牛客网用户“周昆”:
n = int(raw_input())nums = map(int, raw_input().split())index = sorted(range(n), key = lambda i:nums[i])count = 1for i in range(1, len(index)): if index[i] > index[i-1]: count += 1 else: breakprint len(index) - count学习了sorted的高级用法,key为关键字参数,lambda为临时函数,隐函数。
index输出的为按升序排列的 nums 实际处于原数列的位置。输入例子即 index = [1, 2, 0, 3]
0 0
- Python实现互联网笔试题-百度-关于排序sorted()函数
- Python实现互联网笔试题-百度1、2
- Python 排序函数sorted
- 关于互联网笔试题
- python的sorted 函数、python列表排序
- Python的排序:关于sort()与sorted()
- python内置函数sorted排序用法
- python内置函数sorted排序用法
- python内置函数sorted排序用法
- python排序函数sort()与sorted()区别
- python字典排序及sorted函数
- python的排序函数sort,sorted
- python排序函数sort()、sorted()、argsort()
- Python学习(五)—sorted排序函数
- python排序函数sort()与sorted()区别
- Python中的排序函数argsort,sort,sorted
- Python的排序函数Sort,Sorted
- Python排序函数sort()和sorted()详解
- GDOI2017游记
- java复习——二维数组
- Angular系列——MVC模式和MVVC模式
- JavaScript之原型
- LeetCode_3、5两题(substring问题)
- Python实现互联网笔试题-百度-关于排序sorted()函数
- 二叉树三种遍历方式的六种实现方法
- 论文阅读计划
- 解决Finetune时 Aborted at 1493299396 (unix time) try "date -d" if you are using GNU date
- 最近面试的一些感悟
- 第九周
- 用栅栏(CyclicBarrier)实现高并发测试
- 好好学习,天天向上
- cURL开源库中的发送邮件示例代码(smtp-multi.c)