473,378 Members | 1,507 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

breadth first search

I am new in using Python

Anyone know how to implement breadth first search using Python? Can Python
create list dynamically, I want to implement a program which will read data
from a file and store each line into a list, is this possible?

Please send mail to me at ni******@yahoo.com.hk or reply this mail

Thanks a lot!
Feb 8 '06 #1
9 5305
News wrote:
I am new in using Python

Anyone know how to implement breadth first search using Python?
Breadth-first search of what? It depends what kind of tree you're
searching, but here's a page with a few implementations:

http://aspn.activestate.com/ASPN/Coo.../Recipe/231503

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


L = []
[L.append(line) for line in (open('filename.txt')]

- C
Feb 8 '06 #2
Chris McDonough wrote:
Can*Python
create list dynamically, I want to implement a program which will read
data from a file and store each line into a list, is this possible?


L = []
[L.append(line) for line in (open('filename.txt')]


Why would you create two lists, one filled only with None entries just to
throw it away immediately? Don't use list comprehensions just because you
can.

Here are two sane approaches:

lines = open(filename).readlines()
lines = list(open(filename)) # a bit more generic

Finally, if you want to strip off the trailing newlines, a list
comprehension is in order:

lines = [line[:-1] for line in open(filename, "U")]

Peter

Feb 8 '06 #3
Chris McDonough wrote:
L = []
[L.append(line) for line in (open('filename.txt')]


Ouch.

Did you perhaps mean:

L = [ line for line in open('filename.txt') ]

Or, with better error handling:

try:
f = open('filename.txt')
except IOError:
# handle error here
else:
L = [ line for line in f ]

Feb 8 '06 #4
> 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

Feb 8 '06 #5
Chris McDonough wrote:
News wrote:
... Can Python
create list dynamically, I want to implement a program which will read
data
from a file and store each line into a list, is this possible?


L = []
[L.append(line) for line in (open('filename.txt')]

- C

Woops, crossed wires there:
after:
somefile = open('filename.txt')

You can do:
L = somefile.readlines()
or
L = [line for line in somefile]
or
L = []
for line for line in somefile:
L.append(line)
to put all lines of somefile into L,

but
L = []
K = [L.append(line) for line in somefile]
builds a list K that has a None for each line in
somefile, while filling up L with the lines as a side-effect.
It is a style to avoid. Dropping the "K = " part simply says
"build the list of Nones and then discard it." -- not good style.

Also, it is good style to then call somefile.close() after
you are done with the file.

--Scott David Daniels
sc***********@acm.org
Feb 8 '06 #6
Peter Otten wrote:
Chris McDonough wrote:
Can Python
create list dynamically, I want to implement a program which will read
data from a file and store each line into a list, is this possible?

L = []
[L.append(line) for line in (open('filename.txt')]


Why would you create two lists, one filled only with None entries just to
throw it away immediately? Don't use list comprehensions just because you
can.


Yes, of course. Thank you. I didn't mean to offend your sensibilities.
I'm not retarded *every* day, just today. ;-)

- C
Feb 8 '06 #7
Chris McDonough wrote:
I*didn't*mean*to*offend*your*sensibilities.


Me neither :-)

Peter
Feb 8 '06 #8
> Thanks for your reply and the structure of the file structure going to be
read is

<total number of nodes>
<first node><second node><distance from first node to second node>
...
<end of file represented by -1>

The aims is to find out the shortest path(s) for the leaf node(s)

Example:
9
0 1 1
0 4 2
1 2 3
1 3 4
4 3 2
4 5 1
4 8 2
5 6 2
5 7 2
-1

Output:
Possible solutions:
Path=0,1,2 length=4
Path=0,4,3 length=4


Well, I notice several items here:

1) the number of records is obvious, as you have newlines
2) the end-of-file is obvious to Python
3) you don't explicitly spell out which nodes are availble
leaf-nodes

To build a tree like your data provides, you might have some code
like

data = open("data.txt","r")
lines = [line[:-1] for line in data.readlines()[1:-1]]
data.close()
graph = {}
for line in lines:
a,b,weight = line.split(" ",2)
weight = int(weight)
if a in graph:
graph[a][b] =(weight)
else:
graph[a] = {b:weight}

print repr(graph)

You can then navigate this graph/tree. Starting at the root node:

root = graph("0")

root now contains a dictionary. The keys in this dictionary
specify which nodes can be reached from the current location, and
the values of the dictionary represent the weight/cost associated
with traversing to this node.

You can then do a breadth-first search of this data structure
just as you would in any other language. It doesn't look like it
would be a straight-forward breadth-first search, as it looks
like you want to take the weight into account as well as the
number of steps from the root.

-tkc

PS: you should CC the list when you reply, as I certainly don't
have all the answers, and there are others on the mailing list
that can point out better ways to do things, have other ideas, or
be there more predictable than I am (otherwise, you may mail
something and I might not get it for a week)



Feb 8 '06 #9
On 2006-02-08, News <ni******@yahoo.com.hk> wrote:
I am new in using Python

Anyone know how to implement breadth first search using Python? Can Python
create list dynamically, I want to implement a program which will read data
from a file and store each line into a list, is this possible?

Please send mail to me at ni******@yahoo.com.hk or reply this mail

Thanks a lot!


Yes. List has methods that support a stack, in case you find it useful
in this context.

Yes. List has methods that allow dynamic creation, such as might be
useful when implementing a stack, in case you find it useful in this
context.

And Yes. File has methods that will populate a list from a file.
Examples are in the tutorials.

You're welcome.

You can find numerous examples of the breadth-first algorithm on the
web. You can then take the individual steps and translate them into
Python. You'll likely find one or two sticking points, but the
implementation is straightforward from pseudocode or from a GOOD
statement of the algorithm.

Feb 8 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: slickn_sly | last post by:
Why am i getting an error? public void breadthFirst( TreeNode tNode) { Queue q = new Queue( ); if( q.isEmpty() ) { q.enqueue( this ); }
7
by: Matt L. | last post by:
In summary, I don't know how/why the following code works and would like to know. I'm trying to match the first 3 characters of a variable (filename). The code below crudely works, but only if I...
6
by: cameron | last post by:
I have always been under the impression that LDAP was optimized for speed. Fast queries, fast access, slower writes. I have a block of data in LDAP and in SQL. Exact same data. The query is fast...
2
by: xandra | last post by:
i have 2 question in breadth-first traversal.your help will be appreciated. 1. what is the purpose of the queue in breath-first traversal? 2 suppose you had a function call displayAtDepthN which...
3
by: alaa123 | last post by:
hi plz do not ignore me I really neeed ur help I am working on a progarmme to implement First Search and Breadth Search I did the first search algorithm but I need help with implementing the...
1
by: Lord Raiden | last post by:
Hello lads i have a problem about the Breadth First Search . I need to do an implementation of a checking algorith that check from a Game Graph that i have create if every non-object node appears...
0
by: varun aggarwal | last post by:
Hi i am doing the data structures in C++. I have seen the adjacency list implementation of depth first search/traversal that is using some recursive function to traverse the whole graph. but not...
3
by: javaboyjavaboy | last post by:
i need the coding of Breadth First Search program
11
by: tokcy | last post by:
Hi everyone, I am new in php and ajax, i am facing the prob while i click on element of first drop down then in second dropdown all element showl come from database. I mean i have three dropdown 1....
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.