0

I am solving a Sudoku kata on Codewars and here is my code:

def valid_solution(S):
    s=[];L=[];l=[];S1=S[:3];S2=S[3:6];S3=S[6:]
    def verif(S):
        for i in S:
            if len(set(i))!=9 or 0 in set(i): return False
    for z in range(0,9):
        for i in range(len(S)): s.append(S[i][z])
        L.append(s);s=[]
    def loop(h):
        x=3;y=0;s=[];l=[]
        for z in range(len(h)):
            for i in range(3): s.append(h[i][y:x])
            y+=3;x+=3;l.append(s);s=[]
        return l
    l=loop(S1)+loop(S2)+loop(S3)
    for i in range(len(l)):
        for z in range(len(l[i])): l[i][z]=''.join(list(map(str,l[i][z])))
        l[i]=''.join(l[i])
    return False if verif(L)==False or verif(S)==False or verif(l)==False else True

I was wondering if there were a way to make it shorter, not by using matrix etc., but by making 'for in' loops shorter.

Exemple:

for z in range(0,9):
        for i in range(len(S)): s.append(S[i][z])
        L.append(s);s=[]

-->

[(L.append(s),s=[]) [s.append(S[i][z] for z in range(0,9)] for i in range(len(S))]

Thanks in advance.

  • What you're doing with `s.clear` will not have the effect you want. Each time you `L.append(s)` it will append *the same object* and thus you will see the same values in each row. You need to create an actual new list each time - which is also simpler. – Karl Knechtel Nov 11 '20 at 17:39
  • modified it thanks! –  Nov 11 '20 at 17:47
  • Anyway, the first thing I would do is stop using `;` and same-line blocks all over the place - write the code neatly, and give things names that make sense and tell you what's going on. The next thing I recommend is to read https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ . – Karl Knechtel Nov 11 '20 at 17:51

0 Answers0