Skip to content

Latest commit

 

History

History
59 lines (46 loc) · 1.92 KB

python.md

File metadata and controls

59 lines (46 loc) · 1.92 KB
  • class definition
class Blah:
     def __init__(self, x):
         self.val = x
         self.something = None
         self.something_else = None
for i, x in collection:
  element = collection[i]
  x == element # returns true
  • deep copy
import copy

copy.deepcopy(thing)
  • random

    • import: import random
    • random.randint(a, b) for a random integer in [a, b]
    • random.choice(seq) to pick a random element in the sequence
    • random.random() to get a random floating point number in [0.0, 1.0)
    • docs
  • sets: create using set(), use frozensets if you want immutable sets (useful if you want sets of sets because sets cannot contain mutable objects)

  • random string stuff: lower(), isalnum(), len() etc

  • sorting tuples: merged = sorted(some_collection_of_tuples, key = lambda x: x[0])

  • dictionaries: dict.get(key, default_value) -> returns default_value if key not in dict

  • this * thing:

    • say m = [[1, 2], [3, 4], [5, 6]]. Then zip(*m) is equivalent to zip([1, 2], [3, 4], [5, 6]) so * allows us to specify multiple arguments (lists) as one (list of lists).
    >>> zip([1, 2], [3, 4], [5, 6])
    [(1, 3, 5), (2, 4, 6)]
  • reversing a list: either do list(reversed(the_list)) or the_list[::-1]

    • traversing a reversed range: for i in reversed(range(10)) # 9, 8, ..., 0
  • list functions: pop() deletes the last element of the list, or if specified, the element at an index

infinity

positive_inf = float("inf")
negative_inf = float("-inf")

# can be compared to other numbers (ints, floats, doubles)

collections (ordered dict, deques) | docs

sockets | docs