Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save IssamLL/d8a974690867207fe07624bdcc7f3778 to your computer and use it in GitHub Desktop.
Save IssamLL/d8a974690867207fe07624bdcc7f3778 to your computer and use it in GitHub Desktop.
Python - Competitive Programming Tricks
Python - Competitive Programming Tricks
# Initialising a list filled with value
arr = [0]*10
print(arr)
x = 1
arr = [x] * 10
print(arr)
# Reverse
arr = [1, 2, 3, 4, 5]
print(arr, '<>', arr[::-1])
s = 'Hello world!'
print(s, '<>', s[::-1])
# Get dictionary
dictionary = {'a': 1, 'b':2}
print(dictionary['a'])
try:
print(dictionary['c'])
except Exception as e:
print('Error:', e)
print(dictionary.get('c', 0)) # Default value is 0
# For Else
arr = []
for x in arr:
print(x)
else:
print('Empty array')
# Copy
arr = [1, 2, 3]
print(arr)
arr2 = arr.copy()
arr[0] = 0
print(arr)
print(arr2)
# Read an integer from standard input:
n = int(input())
# Read an integer array from standard input:
arr = list(map(int, input().split()))
# Change input from standard input to file:
import sys
sys.stdin = open('in.txt', 'r')
# Floor div
x = 6 // 4
print(x)
# Elvis
x = 'true' if True else 'false'
print(x)
x = ('false', 'true')[2>1] # (falseValue, trueValue)[bool(<expression>)]
print(x)
# Swap
a = 1
b = 2
print(a, b)
a, b = b, a
print(a, b)
# Chained Comparison
a = 100
print(9>a<1001)
print(9<a<1001)
print(9<=a==100)
# Print variable to Standard output:
x = 5
print(x)
print(x, end="") # Print without break line
print() # Print break line
s = "Hello world"
print(s)
print(s, x)
arr = [1, 2, 3]
print(arr)
print(*arr)
dictionary = {'x': 1, 'y': 2, 'z': 3}
print(dictionary)
print(*dictionary)
# Change output from standard output to file:
import sys
sys.stdout = open('out.txt', 'w')
# String Interpolation
result = 100
s = 'result is {}'.format(result)
print(s)
s = f'result is {result}' # From Python 3.6
print(s)
s = 'result is %s' % (result)
print(s)
# String join
arr = [1, 2, 3]
s = ''.join(map(str, arr)) # Convert list integer to string
print(s)
s = '\n'.join(map(str, arr))
print(s)
# String to array of character
s = 'abcdef'
arr = list(s)
print(arr)
# String split
s = '1 2 3'
arr = list(map(int, s.split())) # Default split parameter is space
print(arr)
from time import perf_counter
# Start the stopwatch / counter
t1_start = perf_counter()
# Your code
# Stop the stopwatch / counter
t1_stop = perf_counter()
print("Elapsed time during the whole program in seconds:", t1_stop-t1_start)
# To run all tests: python3 unittest_run.py
# To run single test: python3 unittest_run.py {test_function_name}, ex: python3 unittest_run.py testInOut
import sys
import os
if __name__ == '__main__':
args = " ".join(map(lambda x: f'Test.{x}', sys.argv[1:]))
cmd = f'python3 -m unittest -v unittest_test.py {args}'
os.system(cmd)
# This program read two integer from Standard Input and print sum
def compute(a, b):
return a+b
def main():
a, b = map(int, input().split())
result = compute(a, b)
print(result)
if __name__ == '__main__':
main()
# This program test unittest_solution.py
import sys
sys.dont_write_bytecode = True
import unittest
import unittest_solution as solution
class Test(unittest.TestCase):
def tearDown(self):
try:
import os
os.remove('in.txt')
os.remove('out.txt')
os.remove('result.txt')
except:
pass
# Test direct sample
def testSample(self):
self.assertEqual(solution.compute(1, 2), 3)
self.assertEqual(solution.compute(2, 2), 4)
self.assertEqual(solution.compute(1, 1), 2)
# Test input, output
def testInOut(self):
with open('in.txt', 'w') as fi:
print('1 2', file=fi)
with open('out.txt', 'w') as fo:
print('3', file=fo)
sys.stdin = open('in.txt', 'r')
sys.stdout = open('result.txt', 'w')
solution.main()
sys.stdin.close()
sys.stdout.close()
import filecmp
self.assertTrue(filecmp.cmp('result.txt', 'out.txt'))
if __name__ == '__main__':
unittest.main()
# Print 2d array pretty
def printPretty2dArray(arr):
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in arr]))
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix)
printPretty2dArray(matrix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment