Skip to content

Instantly share code, notes, and snippets.

@mythical-programmer
Last active September 20, 2015 09:43
Show Gist options
  • Save mythical-programmer/874d79ecc7294aabf7d1 to your computer and use it in GitHub Desktop.
Save mythical-programmer/874d79ecc7294aabf7d1 to your computer and use it in GitHub Desktop.
python: better completions
{
// coding genie
"scope": "source.python - string",
"completions":
[
////////////////////////////////////////////////////////////////////////
////////////////////// BEGIN ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
["a arr ___", "a[$1]$2"],
["abcdefghijklmnopqrstuvwxyz ___", "abcdefghijklmnopqrstuvwxyz"],
["m matrix ___", "${1:m}[$2][$3]$4"],
["g ___", "g[$1]$2"],
["b square bs [] ___", "[$1]$2"],
["b brace bb {} ___", "{$1}$2"],
["n = int(sys.argv) ___", "${1:n} = int(sys.argv[${2:1}])$3"],
["c ___", "'''\n$1\n'''"],
["f ___", "False"],
["F ___", "False"],
["t ___", "True"],
["T ___", "True"],
["integer.bit_length() __ int", "${1:integer}.bit_length()"],
//#@
["import ___", "import ${1:sys}"],
["import sys ___", "import sys"],
["import math ___", "import math"],
["import random ___", "import random"],
["assert ___", "assert ${1:x > 0}, '${2:Negative value detected!}'$3"],
["class ___", "class ${1:Student}:\n ''' Class doc '''\n def __init__(self):\n ''' Class initialiser '''\n pass\n\n def __repr__(self):\n ''' String 'repr'esentation '''\n pass"],
["dict ___", "${1:a}={$2}$3"],
["filter ___", "filter(${1:boolean_func}, ${2:seq})$3"],
["fopen ___", "f=open('${1:fname}','${2:r}')$3"],
["for_ ___", "for _ in range(input()):\n\t"],
["fori ___", "for i in range(${1:0, n}):\n $2"],
["forii ___", "for ii in range(${1:t}):\n\t$2"],
["forj ___", "for j in range(${1:0, n}):\n\t$2"],
["fork ___", "for k in range(${1:0, n}):\n\t$2"],
["forrev ___", "for i in reversed(range(${1:0,5,2})):\n\t$2"],
["isFloat ___", "def isfloat(${1:value}):\n\ttry:\n\t\tfloat(value)\n\t\treturn True\n\texcept ValueError:\n\t\treturn False"],
["join ___", "''.join(${1:list})$2"],
["lambda ___", "summ=lambda a, b: a + b"],
["list [] ___", "${1:a}=[$2]$3"],
["if __name__ == '__main__' ___", "if __name__ == '__main__':\n\t"],
["map lambda ___", "map(lambda a:a*a*a, range(1,11)) #cube of 10 numbers"],
["map ___", "map($1)$2"],
["map int ___", "map(${1:int}, ${2:iterable})$3"],
["map input ___", "map(${1:int}, input().split())$2"],
["input ___", "input()"],
["input.split ___", "input().split($1)$2"],
["map line ___ use inside for line in fileinput.input()", "map(${1:int}, line.split())$2"],
["list map ___", "list(map(${1:int}, ${2:lst}))$3"],
["strip trim ___", "strip()"],
["list map read stdin array ___", "list(map(${1:float}, input().split()))$2"],
["list map read stdin matrix ___", "[list(map(${1:float}, input().split())) for x in range(${2:n})]$3"],
["read all lines from stdin input redirection ___", "''.join([line for line in sys.stdin])"],
["next permutation ___", "def next_permutation(a, start, end):\n\t# 1. finds the largest k, that c[k] < c[k+1]\n\tlo=end-2\n\twhile lo>=start and a[lo]>=a[lo+1]: lo-=1\n\t# 2. find last index toSwap, that c[k] < c[toSwap]\n\tif lo==-1: return False\n\thi=end-1\n\twhile lo<hi and a[lo]>=a[hi]: hi-=1\n\t# 3. swap elements with indexes lo and hi\n\ta[lo],a[hi]=a[hi],a[lo]\n\t# 4. reverse sequence from k+1 to n (inclusive)\n\tlo+=1;hi=end-1\n\twhile lo<hi:\n\t\ta[lo],a[hi]=a[hi],a[lo]\n\t\tlo+=1;hi-=1\n\treturn True"],
["printf pf ___", "print('%s$1' % ($2))$3"],
["format string ___", "'%s$1' % ($2)$3"],
["string.upper() ___", "${1:string}.upper()$2"],
["string.lower() ___", "${1:string}.lower()$2"],
["string.startswith(t) ___", "${1:s}.startswith($2)$3"],
["string.endswith(t) ___", "${1:s}.endswith($2)$3"],
["string.strip() ___", "${1:s}.strip()$2"],
["string.count(t) ___", "${1:s}.count(${2:t})$3"],
["string.find(t, start) ___", "${1:s}.find(${2:t}, ${3:startingIndex})$4"],
["string.replace(old, new) ___", "${1:s}.replace(${2:old}, ${3:new})$4"],
["string.split(delimiter) ___ list", "${1:s}.split(${2:delimiter})$3"],
["delimiter.join(list) ___ str", "${1:delimiter}.join(${2:list})$3"],
["printf pf pfe end ___", "print('%s' % ($1), end='$2')$3"],
["print pr ___", "print($1)$2"],
["print end pe pre ___", "print($1, end='$2')$3"],
["end='' ___", "end=''"],
["prime seive ___", "def prime_seive(n):\n\t'''\n\tseive of Eratosthenes\n\t'''\n\tisPrime = [True] * (n+1)\n\tfor i in range(2, n):\n\t\tif isPrime[i]:\n\t\t\tfor j in range(2, n//i + 1):\n\t\t\t\tisPrime[i*j] = False\n\treturn (i for i, x in enumerate(isPrime) if isPrime[i] and i > 1)\nprint([x for x in prime_seive(n)])"],
["range ___", "range($1)$2"],
["raw input (only input in python3)___", "input()"],
["reduce ___", "reduce(lambda a, b: a + b, ${1:rangeOrList}, ${2:0_initValue})$3"],
["repr ___", "repr($1)$2"],
["ret ___", "return $1"],
["set ___", "set($1)$2"],
["split ___", "split($1)$2"],
["sum ___", "sum(${1:seq})$2"],
["transpose ___", "zip(*matrix) #* used to upzip"],
["matrix generator ___", "[[${1:c} for c in range($2)] for r in range($3)]$4"],
["tuple ___", "${1:a}=($2)$3"],
["sys.stdout.write ___", "sys.stdout.write($1)"],
["xrange ___", "xrange($1)"],
["zip ___", "zip(x, y)"],
["reverse sort arg ___", "reverse=True"],
["raw string ___", "r'\/\/' #backslash not treated as escape in raw string; useful in regex"],
["swap idiom ___", "${1:a}, ${2:b} = ${2:b}, ${1:a}"],
["join array___", "''.join(_array)"],
["concat array ___", "''.join(_array)"],
["string concat ___", "''.join(_array)"],
["dict mutate ___", "for ${1:key} in d.keys():\n\td[str(${1:key})] = d[${1:key}]"],
["dict iterate ___", "for ${1:key} in ${2:d}:\n\tprint ${1:key}"],
["dict key in ___", "if key in d:\n\t#do something"],
["dict get ___", "d.get(key, default_val) # for w in graph.get(v,''): ..."],
["dict set default (d[None] access) ___", "d.setdefault(key, val)"],
["from collections import defaultdict ___", "from collections import defaultdict\nd = defaultdict(int)"],
["enumerate ___", "enumerate(${1:_list})"],
["enumerate loop ___", "for (${1:index}, ${2:item}) in enumerate(items):\n\tprint ${1:index}, ${2:item}"],
["sys.argv[] ___", "sys.argv[${1:1}]"],
["generator user defined ___", "def my_range_generator(stop):\n\t''' generator for '''\n\tvalue = 0\n\twhile value < stop:\n\t\tyield value\n\t\tvalue += 1\nfor i in my_range_generator(10):\n\tdo_something(i)"],
["for else idiom ___", "for item in sequence:\n\tif condition(item):\n\t\tbreak\nelse:\n\traise Exception('Condition not satisfied.')"],
["css reader ___", "def filter_rows(row_iterator):\n\tfor row in row_iterator:\n\t\tif row:\n\t\t\tyield row\n\ndata_file = open(path, 'rb')\nirows = filter_rows(csv.reader(data_file))"],
["file reader ___", "datafile = open('datafile')\nfor line in datafile:\n\tdo_something(line)"],
["file.readlines() ___ return list", "${1:fileObject}.readlines()$2"],
["module struct ___", "'''module docstring'''\n# imports\n# constants\n# exception classes\n# interface functions\n# classes\n# internal functions & classes\n\ndef main(...):\n\t...\n\nif __name__ == '__main__':\n\tstatus = main()\n\tsys.exit(status)"],
["lambda if else ___", "f = lambda x: x > 100 and 'big' or 'small'\nfor i in (1,10,101,2,200):\n\tprint(i, f(i))"],
["try except ___", "try:\n\treturn int(str)\nexcept (TypeError, ValueError, OverflowError): #int conversion failed\n\treturn None"],
["string concat fast low memory ___", "from cStringIO import StringIO\nfile_str = StringIO()\nfor num in xrange(loop_count):\n\tfile_str.write(`num`)\nfile_str.getvalue()"],
["def function ___", "def ${1:functionName}($2):\n $3"],
// fileinput, stdin
["import fileinput", ""],
["for fileinput ___ read from stdin or multiple files", "for line in fileinput.input():\n ${1:pass}"],
["fileinput.lineno nLines___", "${1:nLines}=fileinput.lineno()$2"],
["fileinput.isstdin()", ""],
["for line in sys.stdin ___ read from stdin", "for line in sys.stdin:\n\t$1"],
// math
["import math", ""],
["abs ___", "abs(${1:x})$2"],
["math.sqrt ___", "math.sqrt(${1:x})$2"],
["math.ceil ___", "math.ceil(${1:x})$2"],
["math.floor ___", "math.floor(${1:x})$2"],
["math.exp ___", "math.exp(${1:x})$2"],
["math.pow ___", "math.exp(${1:x},${2:y})$3"],
["math.fact ___", "math.factorial(${1:x})$2"],
["math.isnan ___", "math.isnan(${1:x})$2"],
["math.log ___", "math.log(${1:x},${2:base})$3"],
["math.pi ___", "math.pi"],
["math.e ___", "math.e"],
["issubclass ___", "issubclass(int, object)"],
["ord ___", "ord($1)$2"],
// math, algorithmic completions
["bernoulli 0.5 ___", "random.random() < 0.5"],
["binomial 0.5 ___", "sum(1 for x in range(${1:n}) if random.random() < 0.5$2)$3"],
["binarySearch(a, key) ___ algo", "def binarySearch(${1:a}, key):\n '''\n binary search, non recursive implementation\n '''\n lo = 0\n hi = len(${1:a})\n while lo < hi:\n mid = (lo + hi) // 2 # no overflow problem in python\n if ${1:a}[mid] > key:\n hi = mid - 1\n elif ${1:a}[mid] < key:\n lo = mid + 1\n else:\n return mid\n return -1$2"],
// random
["import random", "import random"],
["random.seed(None/i) ___", " random.seed($1)$2"],
["random.random() ___ float", "random.random($1)$2"],
["random.uniform ___ float", "random.uniform($1, $2)$3"],
["random.uniform ___ int", "int(random.uniform(${1:0}, ${2:1}))$3"],
["random.randrange knuth shuffle ___", "r = random.randrange(i, ${1:n})"],
["random.randrange ___ int", "random.randrange(${1:0}, ${2:2}"],
["random shuffled array ___", "def shuffle(a):\n '''\n shuffle array using knuth shuffle\n '''\n for i in range(0, len(a)):\n r = random.randrange(i, len(a))\n a[i], a[r] = a[r], a[i]"],
// calendar
["calendar.setfirstweekday(calendar.SUNDAY) ___", "calendar.setfirstweekday(calendar.${1:SUNDAY})"],
["calendar.monthcalendar(year, month) ___ return matrix", "calendar.monthcalendar(${1:year}, ${2:month})$3"],
["calendar.weekheader(2) ___", "calendar.weekheader(${1:nChars})$2"],
// stddraw
["import stddraw ___", "import stddraw"],
["import stddraw, stdstats plot ___", "import stddraw\nimport stdstats"],
["stddraw.setXscale(x0, x1) ___", "stddraw.setXscale(${1:x0}, ${2:x1})$3"],
["stddraw.setYscale(y0, y1) ___", "stddraw.setYscale(${1:y0}, ${2:y1})$3"],
["stddraw.setPenRadius(0.001) ___", "stddraw.setPenRadius($1)$2"],
["stddraw.point(x, y) ___", "stddraw.point(${1:x}, ${2:y})$3"],
["stddraw.show() ___", "stddraw.show()"],
["stddraw.clear() ___", "stddraw.clear()"],
["stddraw.setCanvasSize() ___", "stddraw.setCanvasSize(${1:xMax}, ${2:yMax})$3"],
["stddraw.plotBars ___", "stddraw.setYscale(0, max(${1:list}))\nstdstats.plotBars(${1:list})$2"],
//# just adding brackets
["str ___", "str($1)$2"],
["int ___", "int($1)$2"],
["float ___", "float($1)$2"],
["round ___", "round($1)$2"],
["list ___", "list($1)$2"],
["len ___", "len($1)$2"],
["len(sys.argv) nargs args length ___", "len(sys.argv)"],
["int sys argv ___", "int(sys.argv[${1:1}])$2"],
//####### regex
["search ___", "mat=re.search(${1:pat}, ${2:S})$3"],
["findall ___", "mat=re.findall(${1:pat}, ${2:S})\nif mat: print mat.group(1)"],
["sub ___", "re.sub(pat, s1, ${1:s2})"],
//#xml
["tree ___", "tree=etree.ElementTree(etree.fromstring(xml))"],
["root ___", "root=tree.getroot()"],
//#graphviz plot
["graphviz ___", "def plot(g):\n\t''' static visualization of the graph using graphviz '''\n\twith open('graph.dot','w') as f:\n\t\tf.write('digraph G {\n')\n\t\tfor v in g:\n\t\t\tif not g[v]:\n\t\t\t\tf.write('{%s} -> {};\n' % (v))\t# isolated node\n\t\t\tfor w in g[v]:\n\t\t\t\tf.write('{%s} -> {%s};\n' % (v, w))\n\t\tf.write('}\n')\n\timport os\n\tos.popen('dot -Tpng -O graph.dot')\n\tos.popen('gnome-open graph.dot.png')\nplot(g)"],
["timer profile timing ___", "import time\nstart = time.clock()$1\nend = time.clock()\nprint(end-start)"],
//################# for hacker code ######################################
["tt ___", "t=int(input())"],
["mm ___", "m=int(input())"],
["nn ___", "n=int(input())"],
["ss ___", "s=input()"],
["init ___", "#coding:utf-8\n'''\n${1:n}\n'''"],
// Own API
["import sorthelper ___", "import sorthelper"],
["sorthelper.isSorted(a) ___", ""],
["sorthelper.timingTest ___", ""],
//# notes or references
["scope of i outside loop doc___", "Unlike analogous loops in many other programming languages, when the first for loop terminates, the variable i is 4 and it remains in scope."],
["division operator doc___", "In Python 3, the / operator has the same behavior as the floating-point division operator when both its operands are integers. In Python 2, the / operator has the same behavior as the floored division operator // when both its operands are integers. For example, 17 / 2 evaluates to 8.5 in Python 3 and to 8 in Python 2. For compatibility among Python versions, we do not use the / operator with two int operands in this booksite."],
["functions with same name overwritten doc___", "no function overloading here, its overwritten. You can often achieve the same effect by using default arguments. "],
["reserved keywords doc___", "False class finally is return\nNone continue for lambda try\nTrue def from nonlocal while\nand del global not with\nas elif if or yield\nassert else import pass\nbreak except in raise"],
["keywords doc___", "False class finally is return\nNone continue for lambda try\nTrue def from nonlocal while\nand del global not with\nas elif if or yield\nassert else import pass\nbreak except in raise"],
["falsy values doc___", "False (== 0)\n\"\" (empty string)\n0, 0.0\n[], (), {}, set()\nNone"],
["truthy values doc___", "True (== 1)\nany string but \"\" (\" \", \"anything\")\nany number but 0 (1, 0.1, -1, 3.14)\nany non-empty container ([0], (None,), [''])\nalmost any object that's not explicitly False"],
["mutable immutable doc___", "immutable : (int, float, str, bool, tuple)\nmutable : (arrays/lists, dict, )"],
["call by object reference doc___", "The only difference between a parameter variable and a local variable is that Python initializes the parameter variable with the corresponding argument provided by the calling code. We refer to this approach as call by object reference. One consequence of this approach is that if a parameter variable refers to a mutable object and you change that object's value within a function, then this also changes the object's value in the calling code (because it is the same object). Next, we explore the ramifications of this approach."],
["function return None doc___", "Functions with no specified return value actually return the special value None, which is usually ignored."],
["function default arguments doc___", "Python function may designate an argument to be optional by specifying a default value for that argument."],
["function and global variable doc___", "While code in a function can refer to global variables, it should not do so: all communication from a caller to a function should take place via the function's parameter variables, and all communication from a function to its caller should take place via the function's return value."],
["immutability and aliasing int increment doc___", "j += 1 results in j referencing an object with value 100, but it does not do so by changing the value of the existing integer from 99 to 100! Indeed, since int objects are immutable, no statement can change the value of that existing integer. Instead, that statement creates a new integer 1, adds it to the integer 99 to create another new integer 100, and assigns to j a reference to that integer."],
["function, mutable object as a default arg doc___", "may lead to unexpected behavior. Python evaluates a default value only once. next call would use modified value (not default value)"],
["defensive copy of arrays as args to functions doc___", "self._coords = a[:] #defensive copy of array argument passed. Now even if a is changed in client code, it will not affect the class code or logic"],
//####################### stdlib of Intro to programming in python #######
["w ___", "stdio.write($1)"],
["wl ___", "stdio.writeln($1)"],
["wf ___", "stdio.writef('%s' % ($1))"],
["stdio ___", "import stdio"]
////////////////////////////////////////////////////////////////////////
////////////////////// END /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment