Moved 1 to 5 to Python and learned a ton.
This commit is contained in:
78
python/lib_misc.py
Normal file
78
python/lib_misc.py
Normal file
@@ -0,0 +1,78 @@
|
||||
def get_digits_reversed(n):
|
||||
"""
|
||||
Returns a list of digits for n.
|
||||
"""
|
||||
digits, rest = [], n
|
||||
while rest != 0:
|
||||
digits.append(rest % 10)
|
||||
rest //= 10
|
||||
return digits
|
||||
|
||||
|
||||
def is_palindrome_string(n):
|
||||
"""
|
||||
Checks whether n is a palindrome number
|
||||
with a string based algorithm.
|
||||
|
||||
:param n: number to check
|
||||
:returns: boolean
|
||||
|
||||
"""
|
||||
s = str(n)
|
||||
return s == s[::-1]
|
||||
|
||||
|
||||
def is_palindrome_integer(n):
|
||||
"""
|
||||
Checks whether n is a palindrome number
|
||||
with an integer based algorithm.
|
||||
|
||||
:param n: number to check
|
||||
:returns: boolean
|
||||
"""
|
||||
digits = get_digits_reversed(n)
|
||||
digits_count = len(digits)
|
||||
for i in range(digits_count // 2):
|
||||
if digits[i] != digits[digits_count - i - 1]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def time_is_palindrom():
|
||||
""" I just want to check which option is faster. """
|
||||
from timeit import timeit
|
||||
print(timeit(lambda: is_palindrome_integer(82445254428), number=100000))
|
||||
print(timeit(lambda: is_palindrome_string(82445254428), number=100000))
|
||||
# > 0.42330633100027626
|
||||
# > 0.07605635199979588
|
||||
|
||||
|
||||
is_palindrome = is_palindrome_string
|
||||
|
||||
|
||||
def get_item_counts(l):
|
||||
"""
|
||||
Counts how often each element is part of the list.
|
||||
|
||||
:param l: a list
|
||||
:returns: a dictionary
|
||||
"""
|
||||
d = {}
|
||||
for e in l:
|
||||
try:
|
||||
d[e] += 1
|
||||
except KeyError:
|
||||
d[e] = 1
|
||||
return d
|
||||
|
||||
|
||||
def product(l):
|
||||
"""
|
||||
Calculates the product of all items in the list.
|
||||
|
||||
:param l: a list
|
||||
:returns: a number that is the product of all elements in the list
|
||||
"""
|
||||
from functools import reduce
|
||||
import operator
|
||||
return reduce(operator.mul, l, 1)
|
||||
Reference in New Issue
Block a user