473,403 Members | 2,366 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,403 software developers and data experts.

Cannot understand the detailedly the following code

Hi,

At the url http://www.python.org/doc/essays/graphs.html there is some
code by Guido Van Rossum for computing paths through a graph - I have
pasted it below for reference -

Let's write a simple function to determine a path between two nodes.
It takes a graph and the start and end nodes as arguments. It will
return a list of nodes (including the start and end nodes) comprising
the path. When no path can be found, it returns None. The same node
will not occur more than once on the path returned (i.e. it won't
contain cycles). The algorithm uses an important technique called
backtracking: it tries each possibility in turn until it finds a
solution.
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None

*** He then says------------------------

It is simple to change this function to return a list of all paths
(without cycles) instead of the first path it finds:

def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
*** I couldn't understand how it was simple to change the function
find paths to find all paths. How would you think about writing this
second function recursively. Especially the part about if start==end:
return [path]. I feel you would give square brackets around path here
after first writing the inductive part ... for node in
graph[start] ....
and then by trial and error put square brackets around path in the
Basis part. Can someone please explain how to write this code. Thanks!
Apr 8 '08 #1
9 1842
On 2008-04-08, re******@hotmail.com <re******@hotmail.comwrote:

[deleted a long piece of text by our BDFL about recursive graph path-finding algorithm]
after first writing the inductive part ... for node in
graph[start] ....
and then by trial and error put square brackets around path in the
Basis part. Can someone please explain how to write this code. Thanks!
The same as any other function.
(the trick with recursive functions is not to think about recursion. Instead,
pretend you are calling another function that happens to have the same name.)

As for the actual procedure of writing a function:

First define the input and output parameters/values of the function.
(ie what goes in, and what comes out)

For recursive functions, there are always two cases, a terminating case, and a
reduction case. In the first case, you may not use the recursive function, in
the latter function you should.
Both cases should use the information available from the input parameters, and
provide a result that matches with the output requirements of the function. Add
a if/then/else that distinguishes between what case you have, and you're done.
Sincerely,
Albert
Apr 8 '08 #2
En Tue, 08 Apr 2008 09:45:35 -0300, A.T.Hofkamp <ha*@se-162.se.wtb.tue.nl>
escribió:
On 2008-04-08, re******@hotmail.com <re******@hotmail.comwrote:

[deleted a long piece of text by our BDFL about recursive graph
path-finding algorithm]
>after first writing the inductive part ... for node in
graph[start] ....
and then by trial and error put square brackets around path in the
Basis part. Can someone please explain how to write this code. Thanks!

The same as any other function.
(the trick with recursive functions is not to think about recursion.
Instead,
pretend you are calling another function that happens to have the same
name.)
But our BDFL played some tricks to make both functions look more similar
than they would instead. Take the "single path" variant:

def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None

Why are those "return None" there, if not to be replaced by "return []"?
Nobody writes that final one at least. Anyway, using the current Python
version, it's easier to mutate the above function into a generator of all
posible solutions; I hope the OP finds the mutation easier to follow:

def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
yield path
return
if start not in graph:
return
for node in graph[start]:
if node not in path:
for newpath in find_all_paths(graph, node, end, path):
yield newpath

The last two lines might be replaced in Python 3 by:
yield *find_all_paths
if this patch is accepted: http://bugs.python.org/issue2292

--
Gabriel Genellina

Apr 9 '08 #3
On Apr 8, 5:45*pm, "A.T.Hofkamp" <h...@se-162.se.wtb.tue.nlwrote:
On 2008-04-08, reach...@hotmail.com <reach...@hotmail.comwrote:

[deleted a long piece of text by our BDFL about recursive graph path-finding algorithm]
after first writing the inductive part ... for node in
graph[start] ....
and then by trial and error put square brackets around path in the
Basis part. Can someone please explain how to write this code. Thanks!

The same as any other function.
(the trick with recursive functions is not to think about recursion. Instead,
pretend you are calling another function that happens to have the same name.)

As for the actual procedure of writing a function:

First define the input and output parameters/values of the function.
(ie what goes in, and what comes out)

For recursive functions, there are always two cases, a terminating case, and a
reduction case. In the first case, you may not use the recursive function,in
the latter function you should.
Both cases should use the information available from the input parameters,and
provide a result that matches with the output requirements of the function.. Add
a if/then/else that distinguishes between what case you have, and you're done.

Sincerely,
Albert

OK so trying to follow your instructions I have-
def find_all_paths(graph, start, end, path=[]):
for node in graph[start]:

Apr 9 '08 #4
On Apr 8, 5:45*pm, "A.T.Hofkamp" <h...@se-162.se.wtb.tue.nlwrote:
On 2008-04-08, reach...@hotmail.com <reach...@hotmail.comwrote:

[deleted a long piece of text by our BDFL about recursive graph path-finding algorithm]
after first writing the inductive part ... for node in
graph[start] ....
and then by trial and error put square brackets around path in the
Basis part. Can someone please explain how to write this code. Thanks!

The same as any other function.
(the trick with recursive functions is not to think about recursion. Instead,
pretend you are calling another function that happens to have the same name.)

As for the actual procedure of writing a function:

First define the input and output parameters/values of the function.
(ie what goes in, and what comes out)

For recursive functions, there are always two cases, a terminating case, and a
reduction case. In the first case, you may not use the recursive function,in
the latter function you should.
Both cases should use the information available from the input parameters,and
provide a result that matches with the output requirements of the function.. Add
a if/then/else that distinguishes between what case you have, and you're done.

Sincerely,
Albert

Ok following these instructions one gets

def find_all_paths(graph, start, end, path=[]):
path= path+ [start]

for node in graph[start]:

find_all_paths(graph, node, end, path)

Now >
First define the input and output parameters/values of the function.
(ie what goes in, and what comes out)
Now what will be the output parameters - there is a Return statement.
Input parameters are graph, vertexes start, node, end and path. Also
how would you write the terminating and reduction cases after this.
Actually i'm not clear how to proceed writing this recursive function.
Thanks!
Apr 9 '08 #5
On 2008-04-09, re******@hotmail.com <re******@hotmail.comwrote:
On Apr 8, 5:45*pm, "A.T.Hofkamp" <h...@se-162.se.wtb.tue.nlwrote:
Ok following these instructions one gets

def find_all_paths(graph, start, end, path=[]):
path= path+ [start]

for node in graph[start]:

find_all_paths(graph, node, end, path)
>First define the input and output parameters/values of the function.
(ie what goes in, and what comes out)

Now what will be the output parameters - there is a Return statement.
Input parameters are graph, vertexes start, node, end and path. Also
how would you write the terminating and reduction cases after this.
Actually i'm not clear how to proceed writing this recursive function.
Thanks!

Don't look at code, don't even think about it (it gives you too much confusing
details).

Instead, have a beer, sit down in a sunny spot, and do mothing for a while.

Think about the function as a (black) box. You don't know what is in it (it is
not important yet). That box is the function (many people prefer to draw a
rectangular shape on a sheet of paper, and consider that to be the function).
What data does the box need to do its work, and what does it produce after
it has done its work?

(suppose you are given the task of 'finding all paths'. What information do you
need to acomplish this task, and what information do you write down as result?)
A simple example of a multiplication task: One needs 2 numbers to do the task,
and the result is another number. Note that at this stage, you don't worry
about HOW you do the task, only WHAT GOES IN AND WHAT COMES OUT.
(actually, HOW depends on INPUT. Multiplication of 2 and 5 can be done
differently from multiplication of
23069876208526945906838863907890387038579036870387 9038285790 and
59380637860938956826829683907893808346873876897628 97. For this reason, deciding
the strategy of solving the problem comes after establishing input and output).
Sincerely,
Albert
PS email will give you shorter response times.
Apr 9 '08 #6
On Apr 9, 8:12*pm, "A.T.Hofkamp" <h...@se-162.se.wtb.tue.nlwrote:
On 2008-04-09, reach...@hotmail.com <reach...@hotmail.comwrote:


On Apr 8, 5:45*pm, "A.T.Hofkamp" <h...@se-162.se.wtb.tue.nlwrote:
Ok following these instructions one gets
def find_all_paths(graph, start, end, path=[]):
*path= path+ [start]
*for node in graph[start]:
* *find_all_paths(graph, node, end, path)
First define the input and output parameters/values of the function.
(ie what goes in, and what comes out)
Now what will be the output parameters - there is a Return statement.
Input parameters are graph, vertexes start, node, end and path. Also
how would you write the terminating and reduction cases after this.
Actually i'm not clear how to proceed writing this recursive function.
Thanks!

Don't look at code, don't even think about it (it gives you too much confusing
details).

Instead, have a beer, sit down in a sunny spot, and do mothing for a while..

Think about the function as a (black) box. You don't know what is in it (it is
not important yet). That box is the function (many people prefer to draw a
rectangular shape on a sheet of paper, and consider that to be the function).
What data does the box need to do its work, and what does it produce after
it has done its work?

(suppose you are given the task of 'finding all paths'. What information do you
need to acomplish this task, and what information do you write down as result?)

A simple example of a multiplication task: One needs 2 numbers to do the task,
and the result is another number. Note that at this stage, you don't worry
about HOW you do the task, only WHAT GOES IN AND WHAT COMES OUT.
(actually, HOW depends on INPUT. Multiplication of 2 and 5 can be done
differently from multiplication of
23069876208526945906838863907890387038579036870387 9038285790 and
59380637860938956826829683907893808346873876897628 97. For this reason, deciding
the strategy of solving the problem comes after establishing input and output).

Sincerely,
Albert
PS email will give you shorter response times.- Hide quoted text -

- Show quoted text -
Hello,

Thank you for the suggestion of relaxing!

After that the black box function you mentioned looks like this-

Output- path1

path 2

| ... path n

|

|

|

----------------------

| |

| |

| function -find_ |

| _all_paths() |

| |

----------------------

|

|

|

|

Input - graph, start, end

i.e. you give, the graph, the start and end vertices as inputs and you
get the output as a listing of all the paths. This is where I got to.
It would be very nice if you could kindly hint on how to proceed
further. Thank you so much for your time!

Thanks & Regards,

Anshu
Apr 11 '08 #7
En Thu, 10 Apr 2008 23:57:29 -0300, <re******@hotmail.comescribió:
i.e. you give, the graph, the start and end vertices as inputs and you
get the output as a listing of all the paths. This is where I got to.
It would be very nice if you could kindly hint on how to proceed
further. Thank you so much for your time!
If you want to understand how recursion works, or how you can actually
construct a recursive function step by step, see this excellent post by
Neil Cerutti:

http://groups.google.com/group/comp....0b10631fd47886

--
Gabriel Genellina

Apr 11 '08 #8
On Apr 11, 10:27*am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
En Thu, 10 Apr 2008 23:57:29 -0300, <reach...@hotmail.comescribió:
i.e. you give, the graph, the start and end vertices as inputs and you
get the output as a listing of all the paths. This is where I got to.
It would be very nice if you could kindly hint on how to proceed
further. Thank you so much for your time!

If you want to understand how recursion works, or how you can actually *
construct a recursive function step by step, see this excellent post by *
Neil Cerutti:

http://groups.google.com/group/comp....0b10631fd47886

--
Gabriel Genellina
Hi,

I did read the post by Neil Cerutti, but I still am unable to write
this recursive function. I will appreciate it if someone can kindly
guide me.

Thanks,
Anshu
Jun 27 '08 #9
On Apr 11, 10:27*am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
>
If you want to understand how recursion works, or how you can actually *
construct a recursive function step by step, see this excellent post by *
Neil Cerutti:

http://groups.google.com/group/comp....0b10631fd47886
Hi,

I did read the above post by Cerutti but I'm still having trouble
writing this recursive function. I will be grateful if someone can
kindly guide me.

Regards,
Anshu

Jun 27 '08 #10

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

Similar topics

8
by: Alex Ang | last post by:
I have written the following VBScript program. It is stored into a file "map_drive.vbs". It successfully mapped to a network drive \\server1\data. Dim WshNetwork Set WshNetwork =...
5
by: Brad Moore | last post by:
Hey all, I'm getting the following compiler error from my code. I was wondering if anyone could help me understand the concept behind it (I actually did try and compile this degenerate...
8
by: baustin75 | last post by:
Posted: Mon Oct 03, 2005 1:41 pm Post subject: cannot mail() in ie only when debugging in php designer 2005 -------------------------------------------------------------------------------- ...
1
by: Andreas Poller | last post by:
Hello, I have the following problem: I have a class deriving from ICustomTypeDescriptor: public __gc class TPropertyBag : public ICustomTypeDescriptor { private: ...
6
by: Chad Crowder | last post by:
Getting the following error on my production server whether the file exists or not: "System.IO.IOException: Cannot create a file when that file already exists." Here's the code generating the...
17
by: Gladiator | last post by:
When I am trying to execute a program from "The C Programming Language" by Dennis Ritchie, I tried to run the following program.I am using Dev++ as a compiler software. The Program is presented...
1
by: rveloso | last post by:
Hi all, i'm having a really nasty problem with popen. I have the following code : --------------------- .... FILE *PD; .... sprintf(fname,"/usr/bin/gzip -dc %s/%s",dirname,dp->d_name); .......
8
by: blisspikle | last post by:
Can any Public class be inherited from? I installed some software on my pc and I can use it in my code, but I cannot seem to inherit from it. It was an executable that installed on my pc, I do not...
4
by: =?Utf-8?B?VG9yZW4gVmFsb25l?= | last post by:
Was editing code, am getting the following errors } expected Type or namespace definition, or end-of-file expected Eyes crossed cannot find code below! using System; using...
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: 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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...

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.