Skip to content

Instantly share code, notes, and snippets.

@adeleinr
Last active May 5, 2024 10:39
Show Gist options
  • Save adeleinr/7669301 to your computer and use it in GitHub Desktop.
Save adeleinr/7669301 to your computer and use it in GitHub Desktop.
Python Cheetcheat
SORTING
=======
Returns a sorted list => sorted(l)
Sort in place ==> l.sort([2,3,7])
# Reverse sorting by y in an (x,y) tuple list in
sorted([(1,2),(2,3)], key=lambda tup: tup[0],reverse=True))
sample = [('Jack', 76), ('Beneth', 78), ('Cirus', 77), ('Faiz', 79)]
sample.sort(key=lambda a: a[1])
# Sorting list of tuples of of a Counter obj
sorted(c.most_common(3), key=lambda tup: tup[0]))
Set
===
tag_counter = set()
tag_counter.update(["hello"])
print(s) --> {"hello"}
tag_counter.update("hello")
print(s) --> {"h", "e", "l", "l", "o"}
Counters:
-------
from collections import Counter
c = Counter("abca")
{'a':2, 'b':1, 'c':1}
sales = Counter(banana=15, tomato=4, apple=39, orange=30)
sales.update(["pineapple"])
# Counter(banana=15, tomato=4, apple=39, orange=30, pineapple=1)
sales.most_common()
Counter(elem[0] for elem in list1)
Strings
=======
"\n".join([])
str.find("some string") return index
LIST COMPREHENSIONS
===================
x if a > b else y
(a > b) and x or y
OPERATIONS ON LISTS
===================
l = [1,2,3]
sum(l) # 6
LOOPS
=====
for i, entry in enumerate(l):
# Start from the end
for i, entry in enumerate(l):
VARIABLE SIZE ARGS *args and **kargs
====================================
# Instead of args it could be any name
# args is a tuple of parameters
def test1 (*args):
print args # (1, 2, 3)
for args in args:
print arg
test1 (1,2,3)
def test2 (**kwargs):
print kwargs # {key1='val1', key2='val2')
for key, value in kwargs.items():
print "%s:%s" % (key, value)
test2( 'key1':'value1', 'key2':'value2')
MD5
====
def GenerateCacheKey(self, prefix, *args, **kwargs):
"""Generates a cache key based on args and kwargs provided."""
md5 = hashlib.md5()
for arg in args:
md5.update(arg)
for key, val in kwargs.iteritems():
md5.update('%s=%s' % (key, val))
md5hash = md5.hexdigest()
return prefix + md5hash
NUMPY
=====
# https://www.hackerrank.com/challenges/np-min-and-max
import numpy
def findMinMax():
num = int(input().split(" ")[0])
npInput = []
for n in range(num):
inp = input().split(" ")
npInput.append ( [int(inp[0]),int(inp[1])])
print(max(numpy.array(npInput).min( axis = 1)))
Convert a Dict into an object
=============================
from collections import namedtuple
d = {"name": "joe", "age": 20}
d
{'age': 20, 'name': 'joe'}
d_named = namedtuple("Employee", d.keys())(*d.values())
d_named
Employee(name='joe', age=20)
d_named.name
'joe'
Random Numbers
==============
import random
random.seed(320
)
random.rand(1,100) # includes 100
l = [ 1,2,3,4]
random.choice(l) # Generates a single choice, could return duplicates, it is like putting 2 back in the list
2
random.choices(l, k=15) # Generates 15 choices, but can still return duplicatess
random.sample(l, k=15) # Generates 15 choices but no duplicates.
random.shuffle(l)
Misc
====
ord("a") gives charset value
3 // 5 returns an int instead of float
a,b=b,a # Swapping values
char_list = "a" * 3 returns "aaa"
l = [0] * 10 creates a list of 10 elements with 0 as the initial value
Initializing a grid ==> grid = [[False]*5]*5
Data structures
===============
defaultdict
-----------
self.price_items_map = defaultdict(list)
for item in inventory_data:
self.price_items_map[item["price"]].append(item)
lamda (anonymous) functions
---------------------------
l = lambda x,y : x*y
conditionals
-------------
any(a>b, c==d, e)
dict of choices
---------------
"""
[] --> "no one likes this"
["Peter"] --> "Peter likes this"
["Jacob", "Alex"] --> "Jacob and Alex like this"
["Max", "John", "Mark"] --> "Max, John and Mark like this"
["Alex", "Jacob", "Mark", "Max"] --> "Alex, Jacob and 2 others like this"
"""
def likes(names):
# make a dictionary d of all the possible answers. Keys are the respective number
# of people who liked it.
# {} indicate placeholders. They do not need any numbers but are simply replaced/formatted
# in the order the arguments in names are given to format
# {others} can be replaced by its name; below the argument "others = length - 2"
# is passed to str.format()
d = {
0: "no one likes this",
1: "{} likes this",
2: "{} and {} like this",
3: "{}, {} and {} like this",
4: "{}, {} and {others} others like this"
}
length = len(names)
# d[min(4, length)] insures that the appropriate string is called from the dictionary
# and subsequently returned. Min is necessary as len(names) may be > 4
# The * in *names ensures that the list names is blown up and that format is called
# as if each item in names was passed to format individually, i. e.
# format(names[0], names[1], .... , names[n], others = length - 2
return d[min(4, length)].format(*names, others = length - 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment