尝试用不同语言写简单题的过程中的一些小发现

Python:

python2中的sort函数是允许传入cmp函数的

1 def comp(x, y):
2     return x - y
3 a = [3, 2, 1]
4 a.sort(comp)

与我们常用的c++的cmp函数类似

但是python3中取消了cmp函数的支持,sort如下

sorted(iterable,key=None, reverse=False)

key指定一个接收一个参数的函数,这个函数用于从每个元素中提取一个用于比较的关键字。默认值为None 。 

1 def comp(x):
2     return x
3 a = [3, 2, 1]
4 a.sort(comp)

所以python3中用这种写法实现和上面代码一样的功能

 

Java:

HashMap<K, V>中K和V必须是具有hashCode方法的类,所以

HashMap<int, int> hMap = new HashMap<int, int>();

这种写法是会报错的,int没有hash方法,改为

HashMap<Integer, Integer> hMap = new HashMap<Integer, Integer>();

即可。int类型是可以直接隐式转换成Integer类型的

 

Scala(吐槽cnblog的插入代码都还不支持scala):

之前没有深入了解....帮人写完作业就没有继续探究这门语言了...

for循环是不能直接支持break和continue语句的,需要借助breakable

输出0-4可以用以下方式实现

1 breakable {
2   for (i <- 0 to 9) {
3     println(i)
4     if (i == 4) break
5   }
6 }

输出小于10的非负偶数

1 for (i <- 0 to 9) {
2   breakable {
3     if (i % 2 == 1) break
4     println(i)
5   }
6 }

 

posted @ 2018-06-03 16:19  ztztyyy  阅读(165)  评论(0编辑  收藏  举报