Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印m个数为-1和n-m个数为1的所有数组_Python_Algorithm - Fatal编程技术网

Python 打印m个数为-1和n-m个数为1的所有数组

Python 打印m个数为-1和n-m个数为1的所有数组,python,algorithm,Python,Algorithm,给定元素n和m的数量,我必须打印所有不同的数组,其中m个值为-1,n-m个值为1。您必须使用递归,但我希望它能有所帮助。你要确保你降低了n级,并且在每一级你都向你的数组中添加一个+1,或者如果你还没有使用所有的m-1,则添加-1 最后,你打印你得到的数组(向量),如果数组中有n个数字,并且你使用了m-1。left overall显示剩余元素的总数。左边的负片显示还有多少-1可以添加 def rec(left_overall, left_negative, v = []): if left

给定元素n和m的数量,我必须打印所有不同的数组,其中m个值为-1,n-m个值为1。

您必须使用递归,但我希望它能有所帮助。你要确保你降低了n级,并且在每一级你都向你的数组中添加一个+1,或者如果你还没有使用所有的m-1,则添加-1

最后,你打印你得到的数组(向量),如果数组中有n个数字,并且你使用了m-1。left overall显示剩余元素的总数。左边的负片显示还有多少-1可以添加

def rec(left_overall, left_negative, v = []):
    if left_overall == 0 and left_negative == 0:
        for i in range(0, len(v)):
            print(v[i], end=" ")

        print()
        return

    if left_overall == 0:
        return

    v.append(1)
    rec(left_overall - 1, left_negative, v)
    v.pop()

    if left_negative > 0:
        v.append(-1)
        rec(left_overall - 1, left_negative - 1, v)
        v.pop()
    return

n = 5
m = 2

arr = []
rec(n, m, arr)

你应该看看:你能告诉我们你尝试了什么吗?不要在回答Python问题时使用C++代码,我把代码改为Python。我真的不知道:)