Skip to content

Instantly share code, notes, and snippets.

@aausch
Last active Dec 22, 2016
Embed
What would you like to do?
Generates a sequence of triangle numbers
# Copyright 2013, Alex Ausch
# Free to use under attribution license: http://creativecommons.org/licenses/by/2.0/ca/
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
class TriangleDictionary(Mapping):
"""A TriangleDictionary maps triangle numbers to their place in their generation sequence:
>>> p = TriangleDictionary()
>>> p[1]
1
>>> p[3]
6
>>> p[7]
28
>>> 4 in p
10
The object generates triangle numbers as needed. When iterated over, it
yields the numbers generated so far:
>>> 11 in p
True
>>> list(p)
[1,3,6,10,15,21,28,36,45,55,66]
"""
instance = None
def __new__(cls):
if cls.instance is None:
cls.instance = super(TriangleDictionary, cls).__new__(cls)
return cls.instance
def __init__(self):
super(TriangleDictionary, self).__init__()
self.inner_dict = {}
self.inner_dict[1] = 1
def __iter__(self):
return iter(self.inner_dict.values())
def __len__(self):
return len(self.inner_dict)
def __contains__(self, key):
try:
key = int(key)
except ValueError:
return False
if key < 1: return False
if not key in self.inner_dict:
self[key]
return True
def __setitem__(self, key, value):
raise TypeError("'TriangleDictionary' object doesn't support item assignment")
def __delitem__(self, key):
raise TypeError("'TriangleDictionary' object doesn't support item removal")
def __getitem__(self,key):
try:
key = int(key)
except:
return False
if key > len (self):
self.inner_dict[key] = key + self[key - 1] #more useful than 1/2key(key+1), depending on application
return self.inner_dict[key]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment