Python输出模糊性

2024-03-29 08:38:54 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我编写了以下代码来生成combinations (n choose k)

#!/usr/bin/env python3

combinations = []
used = []

def init(num):
    for i in range(0, num+1):
        combinations.append(0)
        used.append(0)

def printSolution(coef):
    for i in range(1, coef+1):
        print(combinations[i], " ", end=' ')
    print("\n")

def generateCombinations(which, what, num, coef):
    combinations[which] = what
    used[what] = 1

    if which == coef:
        printSolution(coef)
    else:
        for next in range(what+1, num+1):
            if not used[next]:
                generateCombinations(which+1, next, num, coef)

    used[what] = 0

n = int(input("Give n:"))
k = int(input("Give k:"))

if k <= n:
    init(n)
    for i in range(1, n+1):
        generateCombinations(1, i, n, k)

input()

问题是当它输出文本时,不是像这样一行接一行地写:

Give n:4
Give k:3
1 2 3
1 2 4
1 3 4
2 3 4

它实际上是这样输出的:

Give n:4
Give k:3
1 2 3

1 2 4

1 3 4

2 3 4

我的问题是,为什么会发生这种情况,以及如何解决它?我必须说我是python新手,所以不要对我苛刻。先谢谢你。你知道吗


Tags: inwhichforinputifdefrangewhat