473,385 Members | 2,044 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

RRArray for Python?


I was wondering if there is already some 'official' module for round robin
arrays. Of course, it is relatively easy to implement your own if you need it,
but IMHO it feels like there should be one, because they are so
general-purpose.

Here's my implementation, if someone needs one. If there are enough people
supporting it's release, I could add it to some static web address.

"""
Round-robin array module

This module contains class for a round-robin array and associated round-robin
array database to contain long-time spanning sample values (cf. rrdtool).

Arrays can be arbitrary length, and default slot values can be defined by the
user.

Edvard Majakari <ed****@majakari.net>
"""

class RRArrayError(Exception): pass

class RRArray:
"""Simple round-robin class for arbitrary items"""

def __init__(self, slots, default=None):
"""Instantiate RRArray object

@param default: value to fill empty slots with
r = RRArray(10) # creates a round-robin array of length 10
len(r) 10
"""

self.default = default
self._slots = slots

self._array = [default]*slots

self._next = 0 # points to next free index in array
self._array_full = False

def clear(self):
"""Erase array by setting all values to default fill value"""

self._array = [self.default]*self._slots
self._next = 0
self._array_full = False

def contents(self):
"""Return contents of RRArray object as a list

so that most recent item is the last position.
r = RRArray(3, 0)
r.contents() [0, 0, 0] r.insert(2)
r.contents() [0, 0, 2]
"""

retval = self.latest(self._slots)
retval.reverse()

return retval

def insert(self, item):
"""Insert an item to object
r = RRArray(3)
r.insert(42)
r.most_recent() == 42 and r.used_slots() == 1 True
"""

self._array[self._next % self._slots] = item

if self._next == self._slots - 1:
self._array_full = True
self._next = 0 # wrap-around

else:
self._next += 1

def latest(self, count):
"""Return count most recent items

Note that it is possible to receive default values which were never
inserted, eg.

r = RRArray(5)
r.insert(2), r.latest(3) # would return [2, None, None]
r = RRArray(3)
r.insert(42)
r.insert(5)
r.insert(7)
r.insert(11)
r.latest(2) [11, 7] r.contents()

[5, 7, 11]
"""

if count > self._slots:
err = "attempted to get %d items from rra of size %d"
raise RRArrayError(err % (count, self._slots))

latest_idx = self._latest_index()

head = self._array[0:latest_idx+1]
head.reverse()

if count >= len(head):
tail = self._array[latest_idx+1:self._slots]
tail.reverse()
head.extend(tail)

return head[0:count]

def most_recent(self):
"""Return most recent item inserted.

An IndexError is raised if no items have been inserted yet.
"""

if self._next == 0 and not self._array_full:
raise IndexError("no items inserted yet")

return self._array[(self._next - 1) % self._slots]

def used_slots(self):
"""Return number of used slots."""

if self._next < self._slots and not self._array_full:
return self._next
else:
return self._slots

### private and special methods

def __len__(self):
"""Return number of slots in the object."""

return self._slots

def _latest_index(self):
return (self._next - 1) % self._slots

def _test():
import doctest, rrarray
doctest.testmod(rrarray)

if __name__ == '__main__':
_test()

--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli Deo Gloria!

"Debugging is twice as hard as writing the code in the firstplace. Therefore,
if you write the code as cleverly as possible, you are, by definition,
not smart enough to debug it." -- Brian W. Kernighan
Jul 19 '05 #1
0 927

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

Similar topics

1
by: Emile van Sebille | last post by:
QOTW: "If we get 2.3.3c1 out in early December, we could release 2.3.3 final before the end of the year, and start 2004 with a 100% bug-free codebase <wink>." -- Tim Peters "cjOr proWe vbCould...
0
by: Emile van Sebille | last post by:
QOTW: "Have you ever used the copy module? I am *not* a beginner, and have used it *once* (and I can't remember what for, either)." -- Michael Hudson "It will likely take a little practice...
0
by: Emile van Sebille | last post by:
QOTW (in the OS agnostic category): "There is a (very popular) Python package out there which exposes the win32 api. I'm not sure what it's called. (win32api? pythonwin? win32all?)" -- Francis...
0
by: Emile van Sebille | last post by:
QOTW (advanced interfaces track): "I'm firmly in favour of any language that can DWIMNWIS." -- Tim Delaney QOTW (MS roadkill track): "Underestimate MS at your own risk. It is one thing to not...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...

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.