0

I've been reading an article but the code is written in C language which I don't get at all...

The code is:

void traverse(Tptr p) 
{    if (!p) return; 
     traverse(p->lokid); 
     if (p->splitchar) 
         traverse(p->eqkid); 
     else 
         printf("%s/n", (char *) p->eqkid); 
     traverse(p->hikid);

Someone please translate it to python...

5
Contributors
8
Replies
11
Views
9 Years
Discussion Span
Last Post by tyincali
1

Oh sweet Jesus! Years ago they used to pester us with stuff like this. C syntax can be real ugly, and your example is one of the best examples of ugly C syntax.

Votes + Comments
I concur
0
def traverse(p):
	try:
		p
	except NameError:
		traverse(p=lokid)
	if (p==splitchar):
		traverse(p=eqkid)
	else:
		print p
		traverse(p=hikid)

I think this is what you would want... someone correct me though... I thought it was good, but then I reread it and I'm a little drunk...

What I am confused about is, two lines into the function, it says restart the function...

0

I've been reading an article but the code is written in C language which I don't get at all...

The code is:

void traverse(Tptr p) 
{    if (!p) return; 
     traverse(p->lokid); 
     if (p->splitchar) 
         traverse(p->eqkid); 
     else 
         printf("%s/n", (char *) p->eqkid); 
     traverse(p->hikid);

Someone please translate it to python...

A word to word translation would go like this

def traverse(p):
    if not p:
        return
    traverse(p.lokid)
    if p.splitchar:
        traverse(p.eqkid)
    else:
        print(p.eqkid)
    traverse(p.hikid)
0

So, looking at your translation, would you agree with me when I say this code is broken?

This code isn't broken it's a recursive function

0

This code isn't broken it's a recursive function

yes, but because of the traverse(p->lokid); two lines into the function, it restarts itself over and over until the end when the fact that p is not defined forces a return. There is no way for it to get to the code after the second line, because it always restarts itself.

0

You must think recursively! These calls are all stacked so once it traverses to the outer-most or lower-most children, p becomes none, so it returns. When it returns, the function that called it can then proceed past that traverse(p->lokid) call.

You see this thing travels to all of the children, and then starts doing what it needs to do. And it looks like it's a tertiary (triary? I'm not sure which word is correct) search as opposed to binary search.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.