如何使用递归将两个函数合并为一个?我知道它是“move_zeros”的答案,但是这里我发布的只是想学习如何使用递归和解决递归问题。
func 1
def move_zeross(array):
for i in range(len(array)):
if array[i] is not False and array[i] == 0:
array.pop(i)
array.append(0)
return array
func 2
def move_zeros(array):
for i in range(len(array)):
if array[i] is not False and array[i] == 0:
move_zeross(array)
return array
我试过如下,但RuntimeError
发生了:
RuntimeError: maximum recursion depth exceeded in cmp
以下是组合代码:
def move_zeros(array):
for i in range(len(array)):
if array[i] is not False and array[i] == 0:
array.pop(i)
array.append(0)
move_zeros(array)
return array
答案 0 :(得分:1)
如果您只想将列表中的所有零移到最后,请尝试:
def move_zeros(array):
result = [x for x in array if x is not 0]
return result + [0]*(len(array)-len(result))
使用递归:
def move_zeros(array, n=None):
if n is None:
n = len(array) - 1
if n < 0:
# no more to process
return array
if array[n] is 0:
# move this zero to the end
array.append(array.pop(n))
return move_zeros(array, n-1)
答案 1 :(得分:1)
一种不同的递归方法:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div id="cube">
<figure class="front"></figure>
<div class="spot" id="front-1"></div>
<div class="spot" id="front-2"></div>
<div class="spot" id="front-3"></div>
<div class="spot" id="front-4"></div>
<div class="spot" id="front-5"></div>
<div class="spot" id="front-6"></div>
<figure class="back"></figure>
<div class="spot" id="back-1"></div>
<figure class="right"></figure>
<div class="spot" id="right-1"></div>
<div class="spot" id="right-2"></div>
<div class="spot" id="right-3"></div>
<div class="spot" id="right-4"></div>
<div class="spot" id="right-5"></div>
<figure class="left"></figure>
<!-- <div class="spot"></div>
<div class="spot"></div> -->
<figure class="top"></figure>
<!-- <div class="spot"></div>
<div class="spot"></div>
<div class="spot"></div> -->
<figure class="bottom"></figure>
<!-- <div class="spot"></div>
<div class="spot"></div>
<div class="spot"></div>
<div class="spot"></div> -->
</div>
</div>
<div class="roll">
<p>Roll the Dice</p>
</div>
</body>
</html>
比acw1668的解决方案更多地列出操作,但是不那么面向索引。