首页 > 解决方案 > 整数的元组表示

问题描述

我正在做我的 CS 作业,问题是:

n_to_tuple
    Args:
      n (int): an integer.
    Returns:
      t (tuple): tuple representation of the integer.
                 None if integer cannot be represented.

它应该返回如下内容:

>>> n_to_tuple(2)
((), ((),))
>>> n_to_tuple(0)
()
>>> n_to_tuple(1)
((),)

我已经尝试过多次,但我被困在元组的形成上。

我的尝试包括:

def tuple_to_n(t):
    lst = list(t)
    print(lst)
    count = 0
    for x in lst:
        print(x)
        if(x == "()"):
            count += 1

    if(count == 0):
        return -1
    else:
        return count

但这无济于事,因为元组应像集合论一样表示 ((), ((),))

标签: pythontuples

解决方案


这个怎么样?

def n_to_tuple(n):
    if n < 0: return None
    if n == 0: return ()
    t = list(n_to_tuple(n-1))
    t.append(tuple(t))
    return tuple(t)

for n in range(-2, 5):
    print(n, n_to_tuple(n))

结果如下:

-2 None
-1 None
0 ()
1 ((),)
2 ((), ((),))
3 ((), ((),), ((), ((),)))
4 ((), ((),), ((), ((),)), ((), ((),), ((), ((),))))

非负整数 n 的集合表示 S(n) 递归定义如下:

S(0) = {}
S(n+1) = S(n) union {S(n)}

例如,我们有

S(0) = {}
S(1) = S(0) union {S(n)} = {} union {{}} = {{}}
S(2) = S(1) union {S(1)} = {{}} union {{{}}} = {{}, {{}}}

由于 Python 中不可能有一组集合,因此问题要求 S(n) 的元组版本 T(n)。例如,

T(0) = ()
T(1) = ((),)
T(2) = ((), ((),))

这有点棘手,因为元组是不可变的。如果要求非负整数 n 的列表表示,事情会稍微容易一些:

def n_to_list(n):
    if n < 0: return None
    if n == 0: return []
    l = n_to_list(n-1)
    l.append(l.copy())
    return l

for n in range(-2, 5):
    print(n, n_to_list(n))

结果如下:

-2 None
-1 None
0 []
1 [[]]
2 [[], [[]]]
3 [[], [[]], [[], [[]]]]
4 [[], [[]], [[], [[]]], [[], [[]], [[], [[]]]]]

推荐阅读