[python-users] Schönes Muster

Klaus Bremer klaus.bremer at bmcct.de
Do Feb 18 10:48:30 CET 2010


Kurze Pause, Zeit mal eine lange Liste zu nehmen. [] und () sind praktisch gleich schnell, aber Set schlägt alles:

    Python 2.6.2 (r262:71600, Aug 18 2009, 11:29:27) 
    [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import random
    >>> def get_randoms(n=100000):
    ...     s = [x for x in range(n)]
    ...     random.shuffle(s)
    ...     return s
    >>>
    >>> def timer(n):
    ...     t = time.time()
    ...     for x in range(n):
    ...             dummy = x in s
    ...     print time.time() - t
    ... 
    >>> import time
    >>> s = get_randoms()
    >>> timer(1000)
    1.63445401192
    >>> timer(1000)
    1.62705278397
    >>> s = tuple(s)
    >>> timer(1000)
    1.64976906776
    >>> timer(1000)
    1.63925099373
    >>> s = set(s)
    >>> timer(1000)
    0.000164985656738
    >>> timer(1000)
    0.000165939331055
    >>> 


Gruß
Klaus


Am 18.02.2010 um 08:58 schrieb Rex Turnbull:

> Mir gefällt die leichtigkeit und klarheit in einer Abfrage wie unten, 
> selbst wenn auf simple zahlen verglichen wird. Ich mache oft:
> 
> if wert in [1, 3, 4, 5, 7, 13]:
> 
> Dabei frage ich mich nun, ob es rechnerisch schneller ist mit [] oder () ...
> 
> Grüße, Rex
> 
> Klaus Blindert wrote:
>> Hallo,
>> 
>> ich bin letztens über ein schönes Muster (Pattern)
>> gestolpert. Vergleicht mal die beiden if-Bedingungen.
>> 
>> def save(self, *args, **kwargs):
>>    # Crop the image, provided x/y/w/h are available
>>    if self.x is not None and self.y is not None \
>>            and self.w is not None and self.h is not None:
>>        original = PIL.open(self.source.image)
>> 
>> def save(self, *args, **kwargs):
>>    # Crop the image, provided x/y/w/h are available
>>    if None not in (self.x, self.y, self.w, self.h):
>>        original = PIL.open(self.source.image)
>> 
>> Ist mir so noch nicht aufgefallen und hab mich doch sehr
>> gefreut =).
>> 
>> -klaus
>> 
>> ________________________________________
>> Diese Mail erhalten Sie ueber die Mailingliste Python-users der Universitaet zu Koeln
>> Python-users at uni-koeln.de
>> https://lists.uni-koeln.de/mailman/listinfo/python-users
>> 
> 
> ________________________________________
> Diese Mail erhalten Sie ueber die Mailingliste Python-users der Universitaet zu Koeln
> Python-users at uni-koeln.de
> https://lists.uni-koeln.de/mailman/listinfo/python-users





Mehr Informationen über die Mailingliste python-users