柴柴柴拆柴柴 edited 5 年,4 月前
题目要求:编写一个程序,输入任意一个自然数$n$,输出$P(\lbrace 1,2,…,n \rbrace )$的所有元素!
使用了例1.2.4中提及的递归算法
def add_to_list(mylist,myset):
"""直接调用append方法会导致集合重复出现,因此编写此函数在添加前检查是否重复"""
if myset not in mylist:
mylist.append(myset)
def make_set(a,B):
"""进行集合运算new_set(a,B)={{a} union x|x belongs to P(B)}"""
mylist=[]
add_to_list(mylist,a)
for element in B:
newset=a|element
add_to_list(mylist,newset)
return mylist
def power_set(myset):
"""递归函数"""
mylist=[]
if not myset:
mylist.append(set())
return mylist
else:
for element in myset:
a = set((element,))
B = myset - a
newset = power_set(B)
for element1 in newset:
add_to_list(mylist, element1)
for element1 in make_set(a, newset):
add_to_list(mylist, element1)
return mylist
num = int(input("Input a number:"))
myset = set(range(1, num + 1))
for element in power_set(myset):
if element == set():
print("Ø")
else:
print(element)
偷偷承包柴柴
巨佬
其实有更好的办法,Python的标准库itertools里有combinations和permutations可以直接实现排列组合