0

Reading a text maze from a file, consists of a large series of walls (#) and openings ( ).

The maze needs to be read into a 2-dimensional array.

I can't figure out how to split each '#' and ' ' so that they are separate.

1
  • what language, python? Commented Mar 20, 2014 at 2:45

3 Answers 3

1

Just calling list() should split each character individually as an element in a list

from pprint import pprint as pp

def loadMaze(mazeName):
    global grandList
    grandList = []
    with open(mazeName) as sourceList:
        for line in sourceList:
            eachList = list(line)
            grandList.append(eachList)
        pp(grandList)
Sign up to request clarification or add additional context in comments.

Comments

0

Don't call .split().

eachList = list(line.strip('\n'))

because string.split() is for separating a string by whitespace, into a list of sub-strings:

>>> "a bb ccc".split()
['a', 'bb', 'ccc']

or separating by a character:

>>> "a/bb/ccc".split('/')
['a', 'bb', 'ccc']

list(some_string) will make a list of the characters in the string:

>>> list("a, bb, ccc")
['a', ',', ' ', 'b', 'b', ',', ' ', 'c', 'c', 'c']

3 Comments

@Liam That's because your maze is 36 characters wide, and when you turn it into a list of characters, they each get wrapped in quotes, and commas and show as '#', - 5 characters each. A maze line is 180 characters in list form. PrettyPrint will try to keep lines to 80 characters, but that now doesn't fit, and is printing one item per line. You can make it do it with import pprint; pp = pprint.PrettyPrinter(width=200).pprint at the top instead, but the lines are wide. It's just not a great way to show the maze.
I am testing in PythonWin editor on Windows, and it prints how I expect ( i.imgur.com/Gm6IbfA.png ). PythonWin wraps if I have the window too narrow, but if it's wide enough it shows one one line. So I can only guess it's your terminal/shell/IDE doing the wrapping now.
@Liam That's also an interaction between Python and the surrounding shell/interpreter. Try adding the line print "" before the pp(grandList) line to just print an empty space and get away from the prompt.
0

Yeap! You almost made it, just don't split the strings.

You can do it the easy way,

with open(mazeName) as sourceList:
    for line in sourceList:
        grandList.append(list(line))
    pp(grandList)

or your own way:

with open(mazeName) as sourceList:
    for line in sourceList:
        grandList.append([c for c in line])
    pp(grandList)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.