Skip to content

Instantly share code, notes, and snippets.

@ksylvan
Last active March 18, 2020 06:27
Show Gist options
  • Save ksylvan/a105f65fb6797629ba123dcad5f17e43 to your computer and use it in GitHub Desktop.
Save ksylvan/a105f65fb6797629ba123dcad5f17e43 to your computer and use it in GitHub Desktop.
OurString and hasNext and getNext
#
#
# _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
# |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|
# | | | |
# |H| |L| |W| |D|
# |E| |O| |O| |!|
# |L| |R|
# |L|
#
# 1) var def
# 2) print
# 3) hasNext, getNext
#
#
#
class OurString:
def __init__(self, arr):
self.__a = arr
self.__it = iter(self)
self.__peek = None
def __iterator(self):
i, j = 0, 0
arr = self.__a
n = len(arr)
while i < n:
if arr[i] is None:
i += 1
continue
s = arr[i]
if j == len(s):
j = 0
i += 1
continue
yield s[j]
j += 1
def __iter__(self):
return self.__iterator()
def __str__(self):
# We can use the object as an iterable,
# since we defined __iter__() to return
# the iterator (generator above).
return "".join([x for x in self])
def hasNext(self):
if self.__peek:
return True
try:
self.__peek = next(self.__it)
except StopIteration:
return False
return True
def getNext(self):
# return next character, or None
c = None
if self.hasNext():
c = self.__peek
self.__peek = None
return c
s1 = OurString([None, None, "HEL", "LO", None, None, None, "WORL", None, "D!"])
# print() uses str() under the hood,
# which uses the __str__() method.
print(s1)
s2 = OurString([None, "Hi", None, None, "There!"])
while s2.hasNext():
print(s2.getNext())
# Demo use of OurString as an iterable.
for c in s2:
print(c, end="")
print("")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment