breadth first search

Tim Chase python.list at tim.thechases.com
Wed Feb 8 12:17:42 EST 2006


> Anyone know how to implement breadth first search using Python? 

Yes.  Granted, for more details, you'd have to describe the data 
structure you're trying to navigate breadth-first.

 > Can Python create list dynamically

Is Perl write-only?
Does Lisp use too many parens?
Of course! :)

Not only can Python create lists dynamically, but it's one of 
Python's strong points.

     x = []
     x.append(42)
     x.append("hello")
     h = x.pop()
     ft = x.pop()

> I want to implement a program which will read data
> from a file and store each line into a list, is this possible?

     x = [line[:-1] for line in open("file.txt", "r").readlines()]

will assign the contents of the file "file.txt" to the list "x", 
making x[0] the first line in the file and x[-1] is the last line 
in the file.

If you want to make other use of the file, you can open a file 
object first:

     fileObject = open("file.txt", "r")
     x = [line[:-1] for line in fileObject.readlines()]
     # use fileObject elsehow here
     fileObject.close()

The convention of using the "line[:-1]" strips off the newline at 
the end of each line.  Otherwise, you can just use "line" instead 
of "line[:-1]"

-tkc








More information about the Python-list mailing list