简体   繁体   中英

2D List being returned as 1D

When given an input

Example: runGenerations2d([[0, 0, 1, 0], [0, 0, 1, 1], [1, 1, 1, 0], [1, 0, 0, 1]])

With a click on any box the program will convert the number from 1 to 0 else 0 to 1. The problem arises after a click the information passed back to runGenerations2d is coming in a 1D list rather than the original 2D list. I believe the function causing the problem is evolve2d

Any advice on where i'm going wrong here?

import time # provides time.sleep(0.5)
from csplot import * # provides the visual board
from random import * # provides choice( [0,1] ), etc.
import sys  # larger recursive stack
sys.setrecursionlimit(100000) # 100,000 deep


def runGenerations2d(L , x=0 ,y=0 ):
    show(L)
    print( L )           # display the list, L
    time.sleep(5)      # pause a bit
    newL = evolve2d( L )   # evolve L into newL
    print(newL)
    if min(L) == 1:
        #I like read outs to be explained so I added an extra print command.
        if x<=1: # Takes into account the possibility of a 1 click completition.
            print ('BaseCase Reached!... it took %i click to complete' % (x))
            print (x)
            done()#removes the need to input done() into the shell
        else:
            print ('BaseCase Reached!... it took %i clicks to complete' % (x))
            print (x)
            done()#removes the need to input done() into the shell
        return   
    x = x+1 # add 1 to x before every recusion
    runGenerations2d( newL , x,y )  # recurse

def evolve2d( L ):
    N = len(L)
    x,y = sqinput2()
    print(x,y)
    show(L)
    print("Two")
    time.sleep(5)
    return [setNewElement2d(L, xx, yy, x, y) for xx in range(N) for yy in range(N)]


def setNewElement2d( L, xx, yy, x=0,y=0 ):
    show(L)
    print(L)
    print("Three")
    #time.sleep(5)    
    if (xx,yy) == (x,y): # if it's the user's chosen row and column
        if L[xx][yy]==1:
            return 0 
        else:
            return 1 # If it's already 1 return 0 else return 1
    else: # otherwise
        print("Lastly")
        return L[xx][yy] # return the original  

Error given:

[[0, 0, 1, 0], [0, 0, 1, 1], [1, 1, 1, 0], [1, 0, 0, 1]]
Three
Lastly
[0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1]
[0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1]
The data does not seem 2d.
Try using sqinput instead.

As mentioned by Brian, create a 2D list comprehension:

[[... for ... in ...] for ... in ...] 

instead of a 1D list comprehension:

[... for ... in ... for ... in ...] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM