[Python-de] Noch eine Denksportaufgabe

Gregor Lingl glingl at aon.at
Fri Oct 11 02:57:34 EDT 2002


Martin v. Loewis schrieb:

>Gerhard Häring <gerhard.haering at opus-gmbh.net> writes:
>
>  
>
>>    Schreibe eine Prozedur, die die Elemente eines Arrays mit M
>>    Elementen um n rotiert. -M < n < M
>>    
>>
>
>class ShiftableArray:
>    def __init__(self, elems):
>        self.offset = 0
>        self.elems = elems
>
>    def shift(self, n):
>        self.offset += n
>
>    def __getitem__(self, index):
>        return self.elems[(index-self.offset)%len(self.elems)]
>
>    def __setitem__(self, index, value):
>        self.elems[(index-self.offset)%len(self.elems)] = value
>
>s = ShiftableArray([1, 2, 3, 4, 5, 6])
>print s[0]
>s.shift(2)
>print s[0]
>  
>
1
5

 >>>
Wunderschöne Idee!
Jedoch:
 >>> s
<__main__.ShiftableArray instance at 0x0093EF58>
 >>> len(s)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in ?
    len(s)
AttributeError: ShiftableArray instance has no attribute '__len__'
 >>>

Dagegen:

class ShiftableList(list):
    def __init__(self, elems):
        self.offset = 0
        list.__init__(self,elems)

    def shift(self, n):
        self.offset += n

    def __getitem__(self, index):
        return list.__getitem__(self,(index-self.offset)%len(self))

    def __setitem__(self, index, value):
        return list.__setitem__(self,(index-self.offset)%len(self), value)

    def __repr__(self):
        s = "["+str(self[0])
        for i in range(1,len(self)):
            s += (", "+str(self[i]))
        return s+"]"                    # vielleicht etwas unbeholfen
       

s = ShiftableList([1, 2, 3, 4, 5, 6])
print s[0]
s.shift(2)
print s[0]

1
5

 >>> s
[5, 6, 1, 2, 3, 4]
 >>> len(s)
6
 >>> s[3] = 1001
 >>> s
[5, 6, 1, 1001, 3, 4]
 >>> s.shift(-3)
 >>> s
[1001, 3, 4, 5, 6, 1]

Schöne Grüße, Gregor

P.S.: natürlich bleibt viel zu tun, z.B.
 >>> s+[100,101]
[1, 1001, 3, 4, 5, 6, 100, 101]
 >>>
Urrrgh!
(aber das war ohnehin nicht gewünscht ...)







>Ciao,
>Martn
>
>_______________________________________________
>Python-de maillist  -  Python-de at starship.python.net
>http://starship.python.net/mailman/listinfo/python-de
>
>
>  
>








More information about the Python-de mailing list