继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

python基础学习笔记(实用的内建函数和经典题目收集)

quantumcheese
关注TA
已关注
手记 6
粉丝 179
获赞 722

说明:本手记大部分知识点摘自菜鸟教程,包括代码示例。(菜鸟教程的学习资源真心很好用,把它当查询工具书灰常给力)

1. 字符串方法中的string模块
  • maketrans ( ) 和translate( ) 方法
    1 .maketrans( )
    用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。(两个字符串的长度必须相同,为一一对应的关系)

语法:
str.maketrans(intab, outtab)
intab -- 字符串中要替代的字符组成的字符串
outtab -- 相应的映射字符的字符串

2. translate( )
根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中。

translate()方法语法:
str.translate(table[, deletechars]);
table -- 翻译表,翻译表是通过maketrans方法转换而来。
deletechars -- 字符串中要过滤的字符列表。

使用示例:translate()和maketrans()连用实现字符串翻译:

from string import maketrans   # 引用 maketrans 函数。

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab);
>>>以上实例输出结果如下:
th3s 3s str3ng 2x1mpl2....w4w!!!
  • jion( )方法
    join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

join()方法语法:
str.join(sequence)
sequence -- 要连接的元素序列。
返回通过指定字符连接序列中元素后生成的新字符串。
使用示例:

str = "-";
seq = ("a", "b", "c"); # 字符串序列
print str.join( seq );
以上实例输出结果如下:
a-b-c
2.list列表方法
  • **列表排序
    1. sort( ) 方法**

语法:
list.sort([func])
func -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
默认为正序排列(升序),如果想倒序(降序)可制定参数为:
list.sort(reverse=True)

注意:sort( )方法没有返回值!!
用法示例:

aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print "List : ", aList;
以上实例输出结果如下:
List :  [123, 'abc', 'xyz', 'xyz', 'zara']

2. sorted()方法:

参考:sort()和sorted()用法详解:http://www.cnblogs.com/sysu-blackbear/p/3283993.html


经典题目1:DNA解码
描述:

Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.
In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).
样例输出:
DNA_strand ("ATTGC") # return "TAACG"
DNA_strand ("GTAT") # return "CATA"

解法1:

import string
def DNA_strand(dna):
    return dna.translate(string.maketrans("ATCG","TAGC"))
    # Python 3.4 solution || you don't need to import anything :)
    # return dna.translate(str.maketrans("ATCG","TAGC"))

解法2:

pairs = {'A':'T','T':'A','C':'G','G':'C'}
def DNA_strand(dna):
    return ''.join([pairs[x] for x in dna])

经典题目2:

接收一串字符串,把字母转换成字母表中对应的位置,a-1,b-2....z-26。
输出结果也要是字符串,而且数字之间以空格间隔
样例:
alphabet_position("The sunset sets at twelve o' clock.")
输出结果: "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5
15 3 12 15 3 11"

解法:

def alphabet_position(text):
    return ' '.join(str(ord(c) - 96) for c in text.lower() if c.isalpha())

经典题目3:

You probably know the "like" system from Facebook and other pages.
People can "like" blog posts, pictures or other items. We want to
create the text that should be displayed next to such an item.
Implement a function likes :: [String] -> String, which must take in
input array, containing the names of people who like an item. It must
return the display
样例如下:
likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like
this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2
others like this"
For more than 4 names, the number in and 2 others simply increases.

最佳解法:

def likes(names):
    n = len(names)
    return {
        0: 'no one likes this',
        1: '{} likes this', 
        2: '{} and {} like this', 
        3: '{}, {} and {} like this', 
        4: '{}, {} and {others} others like this'
    }[min(4, n)].format(*names[:3], others=n-2)
 解析:format( )前置{}中为规定好的字符串格式,后面()中的参数为传入的数据,把names的前四个元素分别匹配到{}中的对应位置。
函数返回值为一个字典,分别对应n(names列表长度)为不同值时选择的标准格式(key:n对应的value)

经典题目4:

描述:接收一个整数,输出整数以其中每一位数字降序排列的结果,结果也是整数,样例如下:
Input: 145263 Output: 654321
Input: 1254859723 Output: 9875543221

最佳解法:

def Descending_Order(num):
   return int(''.join(sorted(str(num), reverse = True)))

经典题目5:

描述:接收一个字符串,计算出其中元音字母(a,e,i,o,u)的个数。

解法1:

def getCount(inputStr):
    count_l=[let for let in inputStr if let in "aeiou"] 
   #遍历inputStr,遇到“aeiou”中的任何一个字母,就放入新列表 count_l
    return len(count_l)
   #返回 count_l的长度,即元音字母的个数

解法2(最佳解法):

def getCount(inputStr):
    return sum(1 for let in inputStr if let in "aeiou" )
    # 直接用sum函数,()中的参数是一个sequence,这里参数就是n个数字1组成的列表,数字1的个数取决于后面的条件for let in inputStr if let in "aeiou"
   #遍历inputStr,遇到“aeiou”中的任何一个字母,sum+1

经典题目6:

描述:接收一个字符串,对于其中的每个字母,如果只出现过一次,把它替换为“(”,如果出现过不止一次,则替换为“)”。
样例:
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("

最佳解法:

def duplicate_encode(word):
    return "".join(["(" if word.lower().count(c) == 1 else ")" for c in word.lower()])
   # 复杂表达式参数里可以直接写if...else条件语句
打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP