PE SWE Coding

16 flashcards · Computer Science · by tosus

  1. 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]))}

  2. Open a csv file as a dictionary

    with open('dataset.csv') as datafile: data = csv.DictReader(datafile)

  3. Create a dict with a default value of a dict with a default value of 0

    defaultdict(lambda: defaultdict(int))

  4. Generate a boolean that has a 20% chance to be True

    random.random()<1/5

  5. Get the second and third commandline argument

    sys.argv[1:3]

  6. Choose 20 unique, even integers between 100 and 200 inclusive

    random.sample(range(100, 201, 2), k=20)

  7. 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]

  8. Check if last character of a string is alphanumerical

    str[-1].isalnum()

  9. Create a list of length 10 initialized with 0s

    [0]*10

  10. Process inputs from standard input

    for line in sys.stdin:

  11. Read a csv file line by line

    with open('dataset.csv') as datafile: datareader = csv.reader(datafile, delimiter=',') for line in datareader:

  12. 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()]

  13. Get last item of a list

    list[-1]

  14. Get last 3 items of a list

    list[-3:]

  15. Get all items of a list, except the first 2 and last 3

    list[2:-3]

  16. Get items 2 to 6 of a list, inclusive, in reverse

    list[5:1:-1]