【发布时间】:2018-08-20 16:24:38
【问题描述】:
除了一些函数式编程和数学算法实现外,我是编程方面的新手。无论如何,我开始了在线编程课程并提出了这个问题。给定整数 A 和 B 按字母顺序返回数组 [1,..,A] 中 B 元素的所有可能组合 (ie [[1,...,B] , [1,...B-1, B+1], [1,..,B-1,A],...]))。现在我知道库 itertools 并且我已经看到了一些解决方案,但是我想自己解决它,因为一位朋友告诉我它是通过递归完成的。
def combinations(A,B):
# Three ideas:
# Combination using recursion should look as follows:
# combinations[1,2,3,4,5]
# = [[[1] + combinations[2,3,4,5]],
# [[2] + combinations[3,4,5]]...].
# Terminating condition combination[x] = [x]
# Another idea: print all binary permutations
# with fixed B numbers of ones. Binary combin-
# ations (1,0,0) for A = 3, B = 1 are [(1,0,0),
# (0,1,0), (0,0,1)] Cartesian product of these
# with [1,2,3] would give [1] [2] [3] after rem-
# oving zeroes. In this cas the recursion should
# look as follows: perm([1,0,0]) = [[1, perm([0,
# 0])], [0, perm([1,0])]] In this case terminat-
# ing condition should looks as : perm(x) = x.
# Simplest idea: for element A, either add to
# some array in helper or not. helper(A,B) if value is A appended
# helper(A-1,B-1) and append B-1 values, if A value is not appended
# helper(A-1,B) until now append A or when A==B
# append A and B till array filled. B == 0 helper.append([])
array = [[]]
def helper(array,A,B):
if not B:
array.append([])
# return ??
for i in range(0,1):
if i or A == B: # A == B means add elements until B empty.
array[-1].append(A)
#something helper(A-1,B-1)
return # ?? return
else:
#something helper(A-1,B)
return # ?? return #don't append value A to array
return array
array = helper(array,A,B)
至少有人可以解释如何实施“简单”的解决方案吗?我真的很喜欢这个想法,并且想了解如何实现我自己的递归。谢谢!
【问题讨论】:
-
错误的论坛 - 我们关心带有特定问题和特定答案的损坏代码。不是提供教程或解释基本代码。阅读How to debug small programs (#1) 并调试代码,直到你摸索为止。请再次查看how to ask 和on-topic,如果您有任何问题,请将您的代码提供为mvce。
-
值得注意的是,
itertools.combinations的文档包含做同样事情的 python 代码。
标签: python-3.x recursion combinations permutation