如何维护列表中的唯一项,从而解决此问题?

时间:2019-07-19 05:28:54

标签: python python-3.x jupyter-notebook jupyter-lab azure-notebooks

我需要创建一个提供解决方案的程序:

  

1
3 2
6 5 4
10 9 8 7

使用python。

三个多星期以来,我一直在尝试不同的想法,但找不到解决方案。 在以下尝试中,已经使用了我允许使用的所有代码功能/命令。

各种尝试包括:

第一段代码显示了一些希望,但是它不断在x列表中获得重复项。

    #Attempt 1
    n=4
    l = [0, 1, 2, 3, 4]
    x = [0]
    for i in range (0, n+1):
        k = 0
        j = i
        while k <= i and j != x[j-1]:
            j += l[k]
            print (j, end = " ")
            x.append(j)
            while j != i and j != x[j-1]:
                j -= 1
                if j > i:
                    print (j, end = " ")
                    x.append(j)
            print (x)
            k+=1

    #Attempt 2
    n = 4 
    print (1)
    for a in range (2, n):
        for i in range (2, n*2, a):
            j = i 
            j+=i-1
            print (j, end =" ")
            while j>i:
                j-=1
                print (j, end= " ")
            print ()

    #Attempt 3
    n = 4
    l = [1, 2, 3, 4]
    for i in range (0, n):
        for j in range (0, n*3, l[i]):
            while j >= i:
                print (j, end = " ")
                j-=1
            print ()

输出应为

  

1
3 2
6 5 4
10 9 8 7

某种形式或其他形式,但我从来没有得到。

3 个答案:

答案 0 :(得分:3)

如果您只是想获取特定输出,而只知道 $stmt = $conn->prepare( ' INSERT INTO `Table2` (`name`) VALUES (:name ) ' ); $stmt->execute([ 'name' => $_POST['name'] ]) $last_id = $conn->lastInsertId(); 的值,则可以执行以下操作:

n

输出

n = 8

numbers = range(1, n * (n + 1) // 2 + 1)

for i in range(1, n + 1):
    head, numbers = numbers[:i], numbers[i:]
    print(*reversed(head))

还是这个我没有得到的问题?

答案 1 :(得分:1)

cdlane给出的答案更具有Python风格。这是简化的(学校项目)版本。

n = 4

for i in range(1, n+1):
  max_num_in_line = i * (i+1)// 2  # this gives max number to be printed in line i
  for j in range(i): # here i is the total numbers to be printed in a line.
    print(max_num_in_line, end=' ')
    max_num_in_line -= 1
  print()

答案 2 :(得分:0)

如果您不希望重复的值,则应在变量set()上使用list()而不是x