SpS__79's blog

By SpS__79, history, 19 months ago, In English
  1. Fast I/O — Python's default input() is too slow for massive test cases. You can override it with sys.stdin.readline to prevent Time Limit Exceeded (TLE) errors. import sys input = sys.stdin.readline
  2. Map function — While taking an integer array input in python we can easily take it through the map function and using the code mentioned below we can directly change it into a list. var = list(map(int,input().split())) n, k = map(int, input().split())
  3. Max-Min-Sum function — To get the maximum, minimum, or total sum value from a list without writing manual loops. val = max(var) total = sum(var)
  4. Sort — For sorting an array [Remember the sort() method doesn't return the sorted list. Rather it sorts the list in place and returns None. Therefore, assigning var.sort() in a variable will make it equal to None]. var.sort() print(var)
  5. List Comprehension — You can directly perform loops inside a list to initialize arrays in one clean line. lis = [i for i in range(10)] zeros = [0] * 10
  6. Array Output — For array output you can use two methods. 1. print((" ").join(map(str,array))) or simply print(*array)
  7. Recursion Limit — Python has a low default recursion depth limit. You must increase it to avoid a RecursionError when writing Depth First Search (DFS). import sys sys.setrecursionlimit(10*6)*
  8. Collections Module — Never use list.pop(0) as it takes $$$O(N)$$$ time. Use deque for fast appends and pops from both ends, or Counter for instant frequency counting. from collections import deque, Counter q = deque([1, 2, 3]) freq = Counter(var)
  9. Math Module — Don't write your own functions for basic math. Python has highly optimized built-in functions for GCD, LCM, ceilings, and floors. import math g = math.gcd(12, 18)
  10. Strings and Characters — Strings are immutable, so you cannot change characters directly. Use ord() and chr() to convert between characters and their ASCII integer values. pos = ord('d') — ord('a') rev_s = s[::-1]
  11. Bisect Module — Python's built-in module for performing Binary Search on sorted arrays instantly without writing manual loops. import bisect idx = bisect.bisect_left(var, 3)

Full text and comments »

  • Vote: I like it
  • +6
  • Vote: I do not like it