赞
踩
1.计算整数列表的最小公倍数
例如,给定列表d=[2,3,4,5,6]
,函数的输出为leastCommonDenominator() = 60
用到了python
的fraction
模块,代码示例:
from fractions import gcd
def leastCommonDenominator(denominators):
return reduce(lambda x,y:(x*y)//gcd(x,y),denominators)
2.python 字典的键值类型
判断下列对象中哪些可以用做python
中dict
的键值:
1.set
2.frozenset
3.tuple of mutable objects
4.tuple of immutable objects
5.list of mutable objects
6.list of immutable objects
3.python 中的排序函数sort和sorted
给一个字符串,找出组成这个字符串的字符并按ASCII
码值进行排序,例:
document = "Todd told Tom to trot to the timber"
则函数的输出为:
uniqueCharacters(document) = [' ', 'T', 'b', 'd', 'e', 'h', 'i', 'l', 'm', 'o', 'r', 't']
示例代码如下:
def uniqueCharacters(document):
return sorted(set(document),key=lambda x:ord(x))
参考python
中的Sorting HOW TO
4.判断一个集合关系
判断a
是否是b
的子集。例如,a=[1,2],b=[1,2,3]
则subSetOrNot(a,b)=True
代码示例:
def subSetOrNot(a,b):
return set(a)<=set(b)
主要考察set
的应用,参考3.当然还有别的解法。
5.给定一个列表变成指定形式
给定一个list
,譬如lis=[1,2,3,4,2]
生成的列表形式为:
dooledPassword(lis)=[[1,2,3,4,2]
[2,3,4,2,1]
[3,4,2,1,2]
[4,2,1,2,3]
[2,1,2,3,4]]
示例代码如下:
from collections import deque
def doodledPassword(digits):
n = len(digits)
res = [deque(digits) for _ in range(n)]
map(lambda x,y:x.rotate(-y),res,range(n))
return [list(d) for d in res]
6.根据字典的值对字典排序
给一个编程语言文件名的字典,其值是文件扩展名,根据字典值的字母表顺序对字典进行排序,并转置生成二维列表,例如:
scriptByExtension = {
"validate": "py",
"getLimits": "md",
"generateOutputs": "json"
}
其对应的结果为:
transposeDictionary(scriptByExtension) = [["json", "generateOutputs"],
["md", "getLimits"],
["py", "validate"]]
示例代码如下:
def transposeDictionary(scriptByExtension):
return list(zip(map(lambda y:y[1],sorted(scriptByExtension.items(),key=lambda x:x[1])),map(lambda y:y[0],sorted(scriptByExtension.items(),key=lambda x:x[1]))))
refer:
1 http://www.runoob.com/python/python-dictionary.html
2 https://wiki.python.org/moin/DictionaryKeys
3 http://blog.csdn.net/business122/article/details/7541486
4 https://docs.python.org/2/library/collections.html#collections.deque
5 http://www.runoob.com/python/python-func-map.html
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。