python - 整数的元组表示
问题描述
我正在做我的 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
但这无济于事,因为元组应像集合论一样表示
((), ((),))
。
解决方案
这个怎么样?
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 [[], [[]], [[], [[]]], [[], [[]], [[], [[]]]]]
推荐阅读
- apache-spark - 启用书签的 AWS Glue 作业失败并显示“数据源不支持编写空或嵌套的空模式”
- ajax - Rails 6 Ajax 请求不起作用,SyntaxError: expected expression, got '<' cars:1 AJAX 在 Rails 6 中被破坏了吗?
- python - boto3 textract start_document_text_detection 不接受用于 s3 上的输入文件的文件夹
- java - Map 为两个等效键返回不同的值
- python - 将 Selenium 与 PyCharm CE 一起使用时的弃用问题
- python - TypeError:在 Python 中过滤 JSON 中的值时,字符串索引必须是整数
- python - Python程序抛出错误,因为它说它找不到pygame,即使我已经在程序中导入了它
- python - selenium.common.exceptions.WebDriverException:消息:“chromedriver”可执行文件需要在 PATH 中。我该如何解决
- linux-kernel - LLVM 在生成 .o 文件时是否有任何可能的方法来生成 .bc 文件?
- reactjs - 是否可以在不使用 JSX 的情况下使用 React Hooks API(在打字稿中)