【问题标题】:Sudoku - checking if there are duplicates in rows&columns数独 - 检查行列中是否有重复项
【发布时间】:2021-03-05 10:48:44
【问题描述】:

所以我的目标是编写一个程序,从每一行和每一列中提取非零整数并检查是否有任何重复值,如果存在重复则返回 False,否则返回 True。 它适用于行,但我正在努力获取每列中的非零条目。我只能从一个特定列中获取非零条目,但我不知道如何遍历所有列并检查重复项。 我尝试过使用嵌套的 for 循环,但它似乎不起作用,因为它只会从 L 中的每个列表中返回所有非零整数的列表。

    def sudoku(L):
    #checks the rows
    
    for i in L:
        row=[x for x in i if x != 0]
        for j in row:
            if row.count(j)!=1:
                return False

    #checks the columns
    col=list()
    for x in range(9):
        if L[x][0]!=0:
            col.append(L[x][0])
    print(col)

L = [[5,3,0,0,7,0,0,0,0],
     [6,0,0,1,9,5,0,0,0],
     [0,9,8,0,0,0,0,6,0],
     [8,0,0,0,6,0,0,0,3],
     [4,0,0,8,0,3,0,0,1],
     [7,0,0,0,2,0,0,0,6],
     [0,6,0,0,0,0,2,8,0],
     [0,0,0,4,1,9,0,0,5],
     [0,0,0,0,8,0,0,7,9]]

print(sudoku(L))

【问题讨论】:

    标签: python python-3.x loops for-loop nested-loops


    【解决方案1】:

    我的方法是将每一列的相同索引转换为一行,并重用行的代码

    L = [[5,3,0,0,7,0,0,0,0],
         [6,0,0,1,9,5,0,0,0],
         [0,9,8,0,0,0,0,6,0],
         [8,0,0,0,6,0,0,0,3],
         [4,0,0,8,0,3,0,0,1],
         [7,0,0,0,2,0,0,0,6],
         [0,6,0,0,0,0,2,8,0],
         [0,0,0,4,1,9,0,0,5],
         [0,0,0,0,8,0,0,7,9]]
    
    columns = []
    
    for i in range(len(L)):
      columns.append([])
      for row in L:
        if row[i] != 0:
          columns[i].append(row[i])
    
    print(columns) #List of columns with no 0’s
    

    【讨论】:

      【解决方案2】:
          column = [[x[count] for x in L if x[count] != 0] for count in range(9) ]
          for c in column:
              if len(set(c)) != len(c):
                  return False
              else:
                  return True
      
      

      set() 删除所有重复项

      代码可以缩短为

          column = [[x[count] for x in L if x[count] != 0] for count in range(9) ]
          return False not in [True if len(set(c)) == len(c) else False for c in column]
      

      【讨论】:

      • 嗯,我认为有一个问题 - len(set(c))==len(c) 必须满足列中的所有 c,我认为更改为这样会起作用:if all(len (set(c)) == len(c) for c in col): return True else: return False
      • 什么意思?
      • 你想要每列分别的条件吗?我最初虽然你希望它是如果一列有重复然后为所有内容返回 false
      • 哦,如果所有非零列都没有重复项,我希望代码返回 True,所以我认为我们需要使用 all() 函数来检查所有列。我认为代码中的 for 循环将在找到 len(set())==len() 的 ONE 列后终止。但无论如何,你帮了我很多谢谢!
      • 会调整我的答案
      猜你喜欢
      • 2011-03-09
      • 2020-07-20
      • 2010-12-05
      • 2012-01-10
      • 1970-01-01
      • 2022-08-07
      • 2017-06-08
      相关资源
      最近更新 更多