# HG changeset patch # User Paul Boddie # Date 1480636545 -3600 # Node ID 503985ccf89356b025d382e8ed45f958ccf9fb90 # Parent 6cfa2f4aaca2ae06d5057cc392cf72910b0f79c1 Added a simple hash function for strings; expanded string and dictionary tests. diff -r 6cfa2f4aaca2 -r 503985ccf893 lib/__builtins__/str.py --- a/lib/__builtins__/str.py Fri Dec 02 00:54:32 2016 +0100 +++ b/lib/__builtins__/str.py Fri Dec 02 00:55:45 2016 +0100 @@ -27,6 +27,9 @@ "The base class for all strings." + _p = 0x03ffffff + _a = 31 + def __init__(self): "Initialise the string." @@ -37,6 +40,20 @@ self.__data__ = None + def __hash__(self): + + "Return a value for hashing purposes." + + result = 0 + l = self.__len__() + i = 0 + + while i < l: + result = (result * self._a + ord(self.__get_single_item__(i))) % self._p + i += 1 + + return result + def __iadd__(self, other): "Return a new string for the operation." diff -r 6cfa2f4aaca2 -r 503985ccf893 tests/dict.py --- a/tests/dict.py Fri Dec 02 00:54:32 2016 +0100 +++ b/tests/dict.py Fri Dec 02 00:55:45 2016 +0100 @@ -5,9 +5,11 @@ for key, value in d.items(): return value -d = {10 : "a", 20 : "b"} +d = {10 : "a", 20 : "b", "c" : 30} +print d print d[10] # a print d[20] # b +print d["c"] # 30 try: print d[30] # should fail with an exception except KeyError, exc: @@ -17,20 +19,23 @@ print l print 10 in l # True print 20 in l # True +print "c" in l # True print 30 in l # False l = d.values() print l print "a" in l # True print "b" in l # True +print 30 in l # True print "c" in l # False -v = g(d) # either "a" or "b" +v = g(d) # either "a" or "b" or 30 print v -print v == "a" or v == "b" # True -print v == 10 or v == 20 # False +print v == "a" or v == "b" or v == 30 # True +print v == 10 or v == 20 or v == "c" # False l = d.items() print l print (10, "a") in l # True +print ("c", 30) in l # True print (10, "b") in l # False diff -r 6cfa2f4aaca2 -r 503985ccf893 tests/string.py --- a/tests/string.py Fri Dec 02 00:54:32 2016 +0100 +++ b/tests/string.py Fri Dec 02 00:55:45 2016 +0100 @@ -20,3 +20,5 @@ print ord(s) # should raise an exception except ValueError, exc: print "ord(s): value is not appropriate", exc.value + +print hash(s)