Langzzx / Design-of-Computer-Programs

EX FOR UDACITY CS212
0 stars 0 forks source link

Python tips, tricks and pitfalls #1

Open Langzzx opened 6 years ago

Langzzx commented 6 years ago

ref to: https://www.udacity.com/wiki/python-tips-and-tricks

  1. Build strings using str.join not +

    '--'.join(map(str,range(5))) map(str, range(5))

  2. map(int, ['1', '2', '3']) [x**2 for x in range(5)]

Langzzx commented 6 years ago

Pitfalls

Beware Default Parameters of Mutable Types

in Python 3 and above, all numbers are treated as floats in division operations. But this also can lead to unexpected results, when the result of a division is used as an index in an iterable.

a = [1,2,3,4] a[4/2] Traceback (most recent call last): File "", line 1, in TypeError: list indices must be integers, not float

ref to: https://www.udacity.com/wiki/common-python-pitfalls

Langzzx commented 6 years ago

One of the most important ways to manage complexity is to leave it out completely, just go for the simple solution.

The question was designed so that you had a choice: you could do it "in your head", if that's the kind of head you have, but if you don't, that's also fine. You can easily "run some code.

DRY: Don't Repeat Yourself.