Python输出歧义

时间:2014-05-07 20:06:51

标签: python output newline ambiguity

所以我编写了以下代码来生成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的新手,所以不要对我很苛刻。提前谢谢。

1 个答案:

答案 0 :(得分:3)

print("\n")

打印换行符,并以换行符结束。因此有两个换行符

删除其中一个的两个选项:

print()

print("\n", end="")