473,614 Members | 2,082 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Another Python rookie trying to port to C/C++ question.


A week or two ago, I asked here about porting Python to C. Got some good
answers (Note 1) but now I've got another question. Actually, more a
request for clarification of a topic that both the Python tutorial and
docs leave a touch murky to my understanding.

Dictionaries/"dict" types...

Am I understanding/interpreting correctly when I go with the idea that a
"dict" variable can be looked at as (effectively) two parallel arrays?
Something like this C construct:

struct DictStruct
{
char *KeyArray[<somenumber>];
ValType ValArray[<somenumber>];
}

Where "ValType" would be likely be a union, to allow
assigning/retrieving the actual values correctly depending on what their
individiual types were, and "<somenumbe r>" is just that: Some
more-or-less arbitrarily selected value that provides enough space to
handle all expected numbers of key/value pairs?

Similarly, would something like:

struct DictStruct
{
char Key[25];
ValType Value;
DictStruct *PrevDictEntry;
DictStruct *NextDictEntry;
}

(again, ValType would probably be a union to cover each type of value
that might be wanted in the dictionary - but in this case, Key directly
contains the Key's name) then building a double-linked list of struct
DictStructs end up behaving at least reasonably like a Python "dict"?

I expect that either will be a reasonable facsimile of how Python
handles dicts, with, of course, the corresponding overhead (which may be
surprisingly little, I'm thinking... but I have yet to code that part,
so I may find out it's going to be a nightmare) of "We want the value
that goes with key, so we've got to walk the KeyArray[] until we find a
match, then extract the value from the other array", or a similar
procedure for the doubly-linked list.

Or am I way out in left field with the way I'm RTFM?

(Note 1)
Along with quite a bit of entirely unwelcome "Python evangelism" --
Which part of "I don't care how good, bad, or indifferent Python is
compared to C/C++, or any other language. I want this Python code to be
written in C/C++, end of discussion." wasn't clear enough for those of
you who took it upon yourselves to preach (including the idiot who
decided to spew a relatively impressive (as such things go) string of
insults about how stupid I am, how far up my ass my head is, and how
pathetic my family all the way back to Adam must be for producing such a
throwback because I've got no interest in adopting "the perfect
language...") at me on the merits of Python, both on group and
in-mailbox?

--
Don Bruder - da****@sonic.ne t <--- Preferred Email - SpamAssassinate d.
Hate SPAM? See <http://www.spamassassi n.org> for some seriously great info.
I will choose a path that's clear: I will choose Free Will! - N. Peart
Fly trap info pages: <http://www.sonic.net/~dakidd/Horses/FlyTrap/index.html>
Jul 18 '05
12 2828
On Thu, 25 Sep 2003, Don Bruder wrote:
In article <8y**********@p ython.net>,
Thomas Heller <th*****@python .net> wrote:
Don Bruder <da****@sonic.n et> writes:

[rewriting a Python program in C/C++]
Something like this C construct:

struct DictStruct
{
char *KeyArray[<somenumber>];
ValType ValArray[<somenumber>];
}
[...]
Similarly, would something like:

struct DictStruct
{
char Key[25];
ValType Value;
DictStruct *PrevDictEntry;
DictStruct *NextDictEntry;
}

[...] end up behaving at least reasonably like a Python "dict"?


Yes.

Except that it would be less flexible, *much* slower, and
probably much more buggy.


Well, since I'm not worried about "flexible", have my doubts about the
"much slower" part,


think again. python's dictionaries use an efficient implementation, are
written in C, and have been tuned over the course of several years. your
sketched design uses a very slow implementation, and is brand new.
and have no reason to believe that choice of language automatically
makes a routine buggy,


it's maturity that matters in this case; you will make mistakes, just like
the python (and STL) implementers did, but they've already had years to
find and fix them.

if you don't fancy using STL (which will be the case if you're steering
clear of C++ - and might well be even if you weren't!), at least go and
read up on how to implement dictionaries; they're a very well-studied
abstract type. hashtables are simple and efficient, and binary trees are
good too. there are more complicated things like ternary trees, red-black
trees, Patricia trees (my personal favourite :) ) and skip lists, but
you'll probably be fine with hashtables. if you can lay your hands on a
good data structures and algorithms textbook, you'll be fine (Sedgewick's
'Algorithms in C' is where i learnt my craft).

tom

--
Things fall apart - it's scientific

Jul 18 '05 #11
On Fri, 26 Sep 2003 00:33:46 +0100, Tom Anderson
<tw**@urchin.ea rth.li> wrote:
Patricia trees (my personal favourite :)


Oh goody - Something new to look up!
--
Steve Horne

steve at ninereeds dot fsnet dot co dot uk
Jul 18 '05 #12
Stephen Horne <$$$$$$$$$$$$$$ $$$@$$$$$$$$$$$ $$$$$$$$$.co.uk > wrote in
news:79******** *************** *********@4ax.c om:
On Thu, 25 Sep 2003 15:19:00 -0700, Brian Quinlan <br***@sweetapp .com>
wrote:
Well, since I'm not worried about "flexible", have my doubts about the
"much slower" part,


Your implementation is O(n) with the number of entries while the Python
implementatio n is O(log(n)). If n is small then your implementation
might be acceptably fast. Can't you just use the STL hash_map template
class?


Are you sure Python dictionaries are O(log n)? - Remember, they are
based on hashing.

Simple hashing is O(1). Handling of collisions and stuff will affect
that (and I'm no expert on hashing techniques) but I can't help
wondering if you're confusing Pythons hashing with tree-based
techniques.


Python dictionaries are effectively O(1). Dictionaries are never more than
2/3rds full, so on average a dictionary lookup only needs a couple of
probes. Python's collision resolution is designed such that in most cases
lookups that collide on the first attempt will diverge for the next
attempt.

As some of the other posters have said dictionaries in Python have been
tuned over many years, and since the whole of Python is based on fast
dictionary lookups it is very unlikely that the OP will get close to the
same efficiency. That may not matter though as Python dictionaries are
tuned for general use, so a specific application might be able to do better
by losing some of the generality.

Some of the tuning extends beyond dictionaries, for example strings are
commonly used as dictionary keys, and Python avoids recalculating hash
values more than once for each string. It is unlikely that a C or C++
programmer would go to the effort of using a string type that cached hash
values throughout their application, so for many uses, string lookups in
dictionaries will almost certainly be slower (although there could be gains
elsewhere).

--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #13

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

Similar topics

1
1519
by: Don Bruder | last post by:
Greetings, oh scaly ones... :) I'm a Mac user with a fairly high level of computer literacy, including reasonable programming skills in BASIC, C, Pascal, and several flavors of ML, just trying to run a "canned" Python... Uhhh... Program? Script? Module? - Yeesh... I'm such a rookie at Python I'm not even sure of the right terminology to use here... At this point in the game, I'm not actually trying to *DO* anything in Python, I just...
3
2277
by: Michael Sparks | last post by:
Hi, I'm posting a link to this since I hope it's of interest to people here :) I've written up the talk I gave at ACCU Python UK on the Kamaelia Framework, and it's been published as a BBC R&D White Paper and is available here: * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml
8
1306
by: Daniel Bickett | last post by:
This post started as an incredibly long winded essay, but halfway through I decided that was a terribly bad idea, so I've trimmed it down dramatically, and put it in the third person (for humor's sake). Once upon a time a boy named Hypothetical programmed in PHP and made many a web application. It would be a long while before he would find Python, and since that time he would have no desire to ever touch PHP again.
7
1715
by: clintonG | last post by:
I'm puzzled and don't think this is possible but if an application that is running on websiteA generates a file can FTP be used from websiteA to transfer that file to websiteB which would be located on another server? -- <%= Clinton Gallagher NET csgallagher AT metromilwaukee.com URL http://www.metromilwaukee.com/clintongallagher/
12
6994
by: Arash Partow | last post by:
Hi all, I've ported various hash functions to python if anyone is interested: def RSHash(key): a = 378551 b = 63689 hash = 0
206
8270
by: WaterWalk | last post by:
I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a footprint which says: "Indeed, one often hears arguments against building exibility into an engineered sys- tem. For example, in the philosophy of the computer language Python it is claimed: \There should be one|and preferably only one|obvious...
3
1875
by: chernevik | last post by:
Here is a newbie question: how do I get the server examples in the Preview chapter of "Progamming Python" (Lutz) to run? The code is supposed to be a little webserver on which to run examples, but when I run it it I get "permission denied". Running it as root gets "address already in use". Here is the code (it's example 2.32); comments are from Lutz, not me: webdir = '.' # where your html files and cgi-bin script directory live
15
3203
by: kyosohma | last post by:
Hi, I am trying to get a small group of volunteers together to create Windows binaries for any Python extension developer that needs them, much like the package/extension builders who volunteer their time to create Linux RPMs. The main thing I need are people willing to test the binaries to make sure the extension is stable. This would require installing the binary and probably downloading the source too to get the developer's test
31
1778
by: raylopez99 | last post by:
I went through a bunch of Regex examples, and indeed it's quite powerful, including 'groups' using 'matches', word boundaries, lookahead matches, replacing and splitting text,etc--apparently there's a whole book on it, though I just used the chapter in Albahari et al C#3 in a Nutshell (a great book). You can indeed 'massage' a string into a number of ways, but, at the end of the process I found that you still have to go through the...
0
8177
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8121
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8620
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8268
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7048
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6085
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5537
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4118
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1420
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.