Python 2.7
Pendekatan ini mengambil keuntungan dari pertimbangan berikut:
Setiap bilangan bulat dapat direpresentasikan sebagai jumlah dari kekuatan dua. Eksponen dalam kekuatan dua juga dapat direpresentasikan sebagai kekuatan dua. Sebagai contoh:
8 = 2^3 = 2^(2^1 + 2^0) = 2^(2^(2^0) + 2^0)
Ekspresi ini yang kita hasilkan dapat direpresentasikan sebagai set set (dengan Python, saya menggunakan built-in frozenset
):
0
menjadi set kosong {}
.
2^a
menjadi himpunan yang berisi himpunan yang mewakili a
. Misalnya: 1 = 2^0 -> {{}}
dan 2 = 2^(2^0) -> {{{}}}
.
a+b
menjadi gabungan dari set yang mewakili a
dan b
. Misalnya,3 = 2^(2^0) + 2^0 -> {{{}},{}}
Ternyata ekspresi formulir 2^2^...^2
dapat dengan mudah diubah menjadi representasi himpunan unik mereka, bahkan ketika nilai numeriknya terlalu besar untuk disimpan sebagai integer.
Sebab n=20
, ini berjalan dalam 8.7s pada CPython 2.7.5 di komputer saya (sedikit lebih lambat di Python 3 dan jauh lebih lambat di PyPy):
"""Analyze the expressions given by parenthesizations of 2^2^...^2.
Set representation: s is a set of sets which represents an integer n. n is
given by the sum of all 2^m for the numbers m represented by the sets
contained in s. The empty set stands for the value 0. Each number has
exactly one set representation.
In Python, frozensets are used for set representation.
Definition in Python code:
def numeric_value(s):
n = sum(2**numeric_value(t) for t in s)
return n"""
import itertools
def single_arg_memoize(func):
"""Fast memoization decorator for a function taking a single argument.
The metadata of <func> is *not* preserved."""
class Cache(dict):
def __missing__(self, key):
self[key] = result = func(key)
return result
return Cache().__getitem__
def count_results(num_exponentiations):
"""Return the number of results given by parenthesizations of 2^2^...^2."""
return len(get_results(num_exponentiations))
@single_arg_memoize
def get_results(num_exponentiations):
"""Return a set of all results given by parenthesizations of 2^2^...^2.
<num_exponentiations> is the number of exponentiation operators in the
parenthesized expressions.
The result of each parenthesized expression is given as a set. The
expression evaluates to 2^(2^n), where n is the number represented by the
given set in set representation."""
# The result of the expression "2" (0 exponentiations) is represented by
# the empty set, since 2 = 2^(2^0).
if num_exponentiations == 0:
return {frozenset()}
# Split the expression 2^2^...^2 at each of the first half of
# exponentiation operators and parenthesize each side of the expession.
split_points = xrange(num_exponentiations)
splits = itertools.izip(split_points, reversed(split_points))
splits_half = ((left_part, right_part) for left_part, right_part in splits
if left_part <= right_part)
results = set()
results_add = results.add
for left_part, right_part in splits_half:
for left in get_results(left_part):
for right in get_results(right_part):
results_add(exponentiate(left, right))
results_add(exponentiate(right, left))
return results
def exponentiate(base, exponent):
"""Return the result of the exponentiation of <operands>.
<operands> is a tuple of <base> and <exponent>. The operators are each
given as the set representation of n, where 2^(2^n) is the value the
operator stands for.
The return value is the set representation of r, where 2^(2^r) is the
result of the exponentiation."""
# Where b is the number represented by <base>, e is the number represented
# by <exponent> and r is the number represented by the return value:
# 2^(2^r) = (2^(2^b)) ^ (2^(2^e))
# 2^(2^r) = 2^(2^b * 2^(2^e))
# 2^(2^r) = 2^(2^(b + 2^e))
# r = b + 2^e
# If <exponent> is not in <base>, insert it to arrive at the set with the
# value: b + 2^e. If <exponent> is already in <base>, take it out,
# increment e by 1 and repeat from the start to eventually arrive at:
# b - 2^e + 2^(e+1) =
# b + 2^e
while exponent in base:
base -= {exponent}
exponent = successor(exponent)
return base | {exponent}
@single_arg_memoize
def successor(value):
"""Return the successor of <value> in set representation."""
# Call exponentiate() with <value> as base and the empty set as exponent to
# get the set representing (n being the number represented by <value>):
# n + 2^0
# n + 1
return exponentiate(value, frozenset())
def main():
import timeit
print timeit.timeit(lambda: count_results(20), number=1)
for i in xrange(21):
print '{:.<2}..{:.>9}'.format(i, count_results(i))
if __name__ == '__main__':
main()
(Konsep dekorator memoisasi disalin dari http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/ .)
Keluaran:
8.667753234
0...........1
1...........1
2...........1
3...........2
4...........4
5...........8
6..........17
[...]
19.....688366
20....1619087
Pengaturan waktu untuk berbeda n
:
n time
16 0.240
17 0.592
18 1.426
19 3.559
20 8.668
21 21.402
Setiap n
21 di atas menghasilkan kesalahan memori pada mesin saya.
Saya tertarik jika ada yang bisa membuat ini lebih cepat dengan menerjemahkannya ke bahasa yang berbeda.
Sunting: Mengoptimalkan get_results
fungsi. Juga, menggunakan Python 2.7.5 bukannya 2.7.2 membuatnya berjalan sedikit lebih cepat.
2^n
, dan karena itu tidak perlu untuk melacak apa pun kecualin
. Yaitu, hanya menggunakan aturan eksponensial tampaknya bijaksana. Namun, pasti ada cara yang lebih cerdas dan sepenuhnya aljabar untuk melakukan ini.