PE SWE Coding
16 flashcards · Computer Science · by tosus
Order a dict by the length of its value, descending
{key: value for key, value in sorted(dict.items(), reverse=True, key=lambda item: len(item[1]))}
Open a csv file as a dictionary
with open('dataset.csv') as datafile: data = csv.DictReader(datafile)
Create a dict with a default value of a dict with a default value of 0
defaultdict(lambda: defaultdict(int))
Generate a boolean that has a 20% chance to be True
random.random()<1/5
Get the second and third commandline argument
sys.argv[1:3]
Choose 20 unique, even integers between 100 and 200 inclusive
random.sample(range(100, 201, 2), k=20)
Given coordinates (x, y) in a n by m grid, generate all neighbours of the point that are not out of bounds
[(x+vertical, y+horizontal) for vertical in [-1, 0, 1] for horizontal in [-1, 0, 1] if 0 <= x+vertical < n and 0 <= y+horizontal < m and not vertical == horizontal == 0]
Check if last character of a string is alphanumerical
str[-1].isalnum()
Create a list of length 10 initialized with 0s
[0]*10
Process inputs from standard input
for line in sys.stdin:
Read a csv file line by line
with open('dataset.csv') as datafile: datareader = csv.reader(datafile, delimiter=',') for line in datareader:
Given a list with duplicates, create a list with no duplicates, with items sorted by how common they were in the original list
[key for key, _ in Counter(list).most_common()]
Get last item of a list
list[-1]
Get last 3 items of a list
list[-3:]
Get all items of a list, except the first 2 and last 3
list[2:-3]
Get items 2 to 6 of a list, inclusive, in reverse
list[5:1:-1]