设S是由
递归定义的有序整数对的子集基础步骤:(0,0)∈S。
递归步骤:如果(a,b)∈S,
然后(a,b + 1)∈S,(a + 1,b + 1)∈S,和(a + 2,b + 1)∈S。
列出前四个应用程序生成的S元素
<dataSource>
输出
(0,0) (0,1) (0,2) (0,3) (0,4) (1,0) (1,1) (1,2) (1,3) (1,4) (2,0) (2,1) (2,2) (2,3) (2,4) (3,0) (3,1) (3,2) (3,3) (3,4) (4,0) (4,1) (4,2) (4,3) (4,4)
但正确的答案不仅仅是我得到的答案。
(0,1),(1,1)和(2,1)都在S中。如果我们将递归步骤应用于这些,我们添加(0,2),(1,2),(2) ,2),(3,2)和(4,2)。下一轮给出了我们(0,3),(1,3),(2,3),(3,3),(4,3),(5,3)和(6,3)。第四组申请增加(0,4),(1,4),(2,4),(3,4),(4,4),(5,4),(6,4),( 7,4)和(8,4)。
我的代码出了什么问题?
答案 0 :(得分:1)
def subset(a):
#Returns a list that contains all (i, a + 1) from i = 0 to i = (a + 1) * 2 + 1
return [(i, a + 1) for i in range((a + 1) * 2 + 1)]
setList = []
for i in range(4):
setList += subset(i) #Fill a list with subset result from i = 0 -> 3
print(setList)
如果你想使用递归函数,你也可以这样做:
def subset(a, b):
if a < b * 2:
#Returns a list that contains (a, b) and unzipped result of subset(a + 1, b)
#Otherwise it would add a list in the list
return [(a, b), *subset(a + 1, b)]
else:
return [(a, b)] #If deepest element of recursion, just return [(a, b)]
setList = []
for i in range(5):
setList += subset(0, i)
print(setList)