Skip to content

Instantly share code, notes, and snippets.

@SteadBytes
SteadBytes / int_to_bin.py
Created November 8, 2017 07:31
algorithm for converting integer to binary string (python3)
def int_to_bin(x):
if x == 0: return "0"
s = ''
while x:
if x & 1 == 1:
s = "1" + s
else:
s = "0" + s
x //= 2
return s
@SteadBytes
SteadBytes / reverse_int.py
Last active October 19, 2017 16:30
Mathematical and String-based methods for reversing the digits of an integer
import timeit
# reverse the digits of an integer i.e 1234 -> 4321
# String method turns out to be faster! (timer code if if __name__=='main' section)
def reverse_int_math(x):
"""Reverses the digits of an integer mathematically
Args:
x (int): integer to reverse
Returns:
@SteadBytes
SteadBytes / binary_search_insert.py
Created October 17, 2017 10:32
Binary Search Insert
def binary_search_insert(target, seq):
"""Finds position to insert an item into a **descending** sorted list
Args:
target : value to find insert position of
seq : descending sorted list
Returns:
int: Index of position to insert target to maintain sort
"""
l_index = 0
def split_power_2(x):
""" Splits a number up into powers of 2, returning a list of powers.
"""
split_powers = []
i = 1
while i <= x:
if i & x: # 1 or 0 -> evaluate as True/False
split_powers.append(i)
i <<= 1
return split_powers

Symmetric Matrix

A matrix is symmetric if the first row is the same as the first column, the second row is the same as the second column etc… Write a function to determine whether a matrix is symmetric.

Example input and output:

print symmetric([[1, 2, 3],
                [2, 3, 4],
                [3, 4, 1]])
&gt;&gt;&gt; True