coding基本功实践
作为一名程序员,除了需要具备解决问题的思路以外,代码的质量和简洁性也很关键。因为从一个人的代码可以直接看出你的基本功。对于Python而言,这就意味着你需要对Python的内置功能和库有很深入的了解。
一 选择正确的内置功能
01.题目
在FizzBuzz中,你将获得一个整数列表,任务是执行以下操作: 用“fizz”替换所有可被3整除的整数 用“buzz”替换所有可被5整除的整数 将所有可被3和5整除的整数替换为“fizzbuzz”
1 numbers = [45, 22, 14, 65, 97, 72] 2 for i, num in enumerate(numbers): 3 if num % 3 == 0 and num % 5 == 0: 4 numbers[i] = 'fizzbuzz' 5 elif num % 3 == 0: 6 numbers[i] = 'fizz' 7 elif num % 5 == 0: 8 numbers[i] = 'buzz'
02.使用断点breakpoint()调试而不是print()
你可能通过在代码中添加print并查看打印出的内容来调试一个小问题。这种方法起初效果很好,但很多就变得很麻烦。 如果你使用的是Python 3.7,则无需导入任何内容,只需在代码中要放入调试器的位置调用breakpoint():
调用breakpoint()会将你带入pdb,这是默认的Python调试器。在Python 3.6及更早版本中,你可以通过显式导入pdb来执行相同的操作:
像breakpoint()一样,pdb.set_trace()会将你带入pdb调试器。它不是那么简洁,而且需要记住的多一点。你可能想要尝试其他调试器,但pdb是标准库的一部分,
因此它始终可用。无论你喜欢哪种调试器,在进行编码面试设置之前,都值得尝试使用它们来适应工作流程。
import pdb; pdb.set_trace()
03.使用f-Strings格式化字符串 在coding中,如果使用Python 3.6+,建议的格式化方法是Python的f-strings。 f-string允许你将Maria放入字符串中,并在一个简洁的操作中添加具有所需格式的年龄。需要注意的一个风险是,如果你输出用户生成的值,那么可能会带来安全风险,
在这种情况下,模板字符串可能是更安全的选择。
def get_name_and_decades(name, age): return f"My name is {name} and I'm {age / 10:.5f} decades old." get_name_and_decades("Maria", 31) # My name is Maria and I'm 3.10000 decades old.
二 有效利用基本的数据结构和方法
1 import random 2 all_words = "all the words in the world".split() 3 def get_random_word(): 4 return random.choice(all_words) 5 6 def get_unique_words(): 7 words = set() 8 for _ in range(200): 9 words.add(get_random_word()) 10 return words 11 12 print(get_unique_words())
1 sum((i * i for i in range(1, 1001))) 2 3 """ 4 换出括号会将列表推导更改为生成器表达式。当你知道要从序列中检索数据,但不需要同时访问所有数据的时候,生成器表达式非常适合。 5 当sum通过重复调用.__ next __()来迭代生成器对象时,生成器检查i等于多少,计算i * i,在内部递增i,并将正确的值返回到sum。 6 该设计允许生成器用于大量数据序列,因为一次只有一个元素存在于内存中。 7 """
1 cowboy = {'age': 32, 'horse': 'mustang', 'hat_size': 'large'} 2 name = cowboy.setdefault('name', 'The Man with No Name') 3 4 """ 5 等价于: 6 if 'name' not in cowboy: 7 cowboy['name'] = 'The Man with No Name' 8 """
三 利用Python的标准库
1 from collections import defaultdict 2 3 grades = [ 4 ('elliot', 91), 5 ('neelam', 98), 6 ('bianca', 81), 7 ('elliot', 88) 8 ] 9 10 """ 11 你将创建一个defaultdict,它使用不带参数的list构造函数作为默认方法, 12 没有参数的list返回一个空列表你也可以使用lambda函数作为值来返回任意常量。 13 """ 14 student_grades = defaultdict(list) 15 for name, grade in grades: 16 student_grades[name].append(grade)
1 # 一长串没有标点符号或大写字母的单词,你想要计算每个单词出现的次数。 2 from collections import Counter 3 words = "if there was there was but if there was not there was not".split() 4 counts = Counter(words) 5 print(counts) # Counter({'there': 4, 'was': 4, 'if': 2, 'not': 2, 'but': 1}) 6 print(counts.most_common(2)) # 返回n个最频繁的输入 7 """ 8 collections.Counter是dict的子类,它使用0作为任何缺失元素的默认值,并且更容易计算对象的出现次数: 9 """
1 import string 2 def is_upper(word): 3 for letter in word: 4 if letter not in string.ascii_uppercase: 5 return False 6 return True 7 8 print(is_upper('T')) 9 10 11 """ 12 所有字符串常量都只是经常引用的字符串值的字符串。其中包括以下内容: 13 string.ascii_letters 14 string.ascii_uppercase 15 string.ascii_lowercase 16 string.digits 17 string.hexdigits 18 string.octdigits 19 string.punctuation 20 string.printable 21 string.whitespace 22 """
1 """ 2 itertools有多个工具来生成可重复输入数据序列,但现在我们只关注两个常见函数: 3 itertools.permutations() 排列 区分顺序 4 itertools.combinations()。组合 不区分顺序 5 6 """ 7 import itertools 8 a = ['a','b','c'] 9 list(itertools.permutations(a,r=2)) # [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] 10 11 import itertools 12 a = ['a','b','c'] 13 list(itertools.combinations(a,r=2)) # [('a', 'b'), ('a', 'c'), ('b', 'c')]