Home > Mobile >  "ValueError: too many values to unpack (expected 2)" should not happen here
"ValueError: too many values to unpack (expected 2)" should not happen here

Time:10-25

I'm currently trying to create a Sudoku without help but i'm stuck on one issue.

def play():
    global myinput
    global column_rdm
    sudoku_col = [[] for _ in range(9)]
    for i in range(9):
        sudoku_col[i].append(0)
    h = 1
    try:
        while h < 10:
            rdm_list = random.sample(range(1, 10), 9)
            test_var = 0
            for j in range(9):
                if rdm_list[j] not in sudoku_col[j]:
                    test_var  = 1
            if test_var == 9:
                for rdm_number, g in rdm_list, range(9):
                    sudoku_col[g].append(rdm_number)
                    # Input the values found in the sudoku
                    column_rdm = f"{rdm_number}"
                    myinput = Input(h, g 1)
                    myinput.value_def(column_rdm)  # end
            h  = 1
        update()
    # except Exception as e:
    #     print("Erreur dans la création du Sudoku")
    finally:
        print(h)

Here the function that should create my Sudoku. I create random lists of 9 numbers which will be my sudoku raws, and i check if each item of those lists is already present in its column with my "sudoku_col". If the test is OK (that is, test_var == 9), then I add this raw to my template. If not, I create a new random list and let it complete the test again. I do that until I have 9 raws (h < 10).

However, the code stops at line "for rdm_number, g in rdm_list, range(9):" due to a ValueError. That should not happen, because rdm_list and range(9) have the same lenght and each item in both lists should be iterated correctly. What am I missing here ?

Thank you for your time

CodePudding user response:

It should be

for rdm_number, g in zip(rdm_list, range(9)):

what you are doing is the same as

for rdm_number, g in (rdm_list, range(9)):

which creates a tuple with two items that you iterate over, you can see that happen if you do this (it will print out whatever is the rdm_list and range(0, 9)):

for sth in rdm_list, range(9):
    print(sth)

also while h < 10 can just be replaced with for h in range(9): and you don't need to increase any variables and for loops are faster.

Another improvement would be to do this (instead of using the range and accessing values by index):

for rdm, s_col in zip(rdm_list, sudoku_col):
    if rdm not in s_col:
        test_var  = 1

Also this:

sudoku_col = [[] for _ in range(9)]
for i in range(9):
    sudoku_col[i].append(0)

can easily be reduced to

sudoku_col = [[0] for _ in range(9)]

Again you shouldn't use range to access values by using index, you should iterate over the values like this: for value in iterable:, instead of for index in range(len(iterable)), if you also need the index then use this: for index, value in enumerate(iterable):

  • Related