Moved more problems to Python.
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
def get_digits_reversed(n):
|
||||
"""
|
||||
Returns a list of digits for n.
|
||||
@@ -76,3 +79,59 @@ def product(l):
|
||||
from functools import reduce
|
||||
import operator
|
||||
return reduce(operator.mul, l, 1)
|
||||
|
||||
|
||||
def triangle_numbers():
|
||||
c = 0
|
||||
i = 1
|
||||
while True:
|
||||
c += i
|
||||
yield c
|
||||
i += 1
|
||||
|
||||
|
||||
def even(n):
|
||||
"""
|
||||
Returns true if a number is even.
|
||||
"""
|
||||
return n % 2 == 0
|
||||
|
||||
|
||||
def odd(n):
|
||||
"""
|
||||
Returns true if a number is odd.
|
||||
"""
|
||||
return n % 2 != 0
|
||||
|
||||
|
||||
def collatz_sequence(n):
|
||||
"""
|
||||
Returns collatz sequence for n.
|
||||
|
||||
:param n: collatz sequence
|
||||
"""
|
||||
cs = []
|
||||
while n != 1:
|
||||
cs.append(n)
|
||||
n = n // 2 if n % 2 == 0 else 3 * n + 1
|
||||
cs.append(n)
|
||||
return cs
|
||||
|
||||
|
||||
@lru_cache(maxsize=1000000)
|
||||
def collatz_sequence_length(n):
|
||||
"""
|
||||
Returns length of collatz sequence for n.
|
||||
|
||||
:param n: collatz sequence
|
||||
"""
|
||||
if n == 1:
|
||||
return 1
|
||||
length = 1
|
||||
while odd(n):
|
||||
n = 3 * n + 1
|
||||
length += 1
|
||||
return length + collatz_sequence_length(n // 2)
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user