Skip to content

Instantly share code, notes, and snippets.

@aausch
Last active December 22, 2016 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aausch/6750121 to your computer and use it in GitHub Desktop.
Save aausch/6750121 to your computer and use it in GitHub Desktop.
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