Diccionarios Python vs C#

I've been coding in Python for a while now and I got used to thinking that dictionaries have worst case O(n) time complexity (fuente). However, at work I have to use C# and I've just recently find out that dictionaries in C# have much better time complexity (fuente). Why is that? What advantages do python dictionaries have over C# ones?

By the way, which implementation is more common? If I ever have to use dictionaries from another language's standard library what time complexity will they most probably have?


preguntado el 28 de mayo de 14 a las 14:05

Here's an older SO about python's built in dictionary - stackoverflow.com/questions/327311/…. -

2 Respuestas

MSDN documentation speaks about average case time complexity (more particularly, they say that the complexity "approaches" the given function), and these are the same as presented in Python documentation. Python additionally provides worst case complexities. For some operations MSDN also provides worst case estimations (example: http://msdn.microsoft.com/en-us/library/k7z0zy8k%28v=vs.110%29.aspx ).

It does not make sense to compare average case with worst case.

Skipping the theory, in practice: average case describes what you should expect in general when performing an operation. Worst case informs you that sometimes, in some particular conditions and/or for some particular data, the operation may perform slower.

Also, it's best to focus on one particular operation. Discussing "complexity of a dictionary" in general also doesn't make much sense.

contestado el 28 de mayo de 14 a las 14:05

I assume that dictionaries in Python and C# use much the same implementation: a hashed lookup.

The time order of a hashed lookup is slightly great than O(1). On average, once the key has been hashed, it can be found in one access or slightly longer (for hash collisions).

The worst case performance of a hashed lookup is O(n). If all the keys in the dictionary have the same hash value then the search becomes (usually) equivalent to linear brute force.

So yes, Python has worst case O(n) and C# has average time complexity of O(1+). On the other hand, Python has average time complexity of O(1+) and C# has worst case of O(n).

In other words, they're the same (to a first order approximate). And so are all the others you're likely to run into.

But watch out for anything that is a sorted dictionary. They're very different.

contestado el 29 de mayo de 14 a las 00:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.