Skip to content

Instantly share code, notes, and snippets.

@ihavenonickname
Last active January 23, 2018 12:16
Show Gist options
  • Save ihavenonickname/5b0c3128c16b8a4e9ecc13e8968711d0 to your computer and use it in GitHub Desktop.
Save ihavenonickname/5b0c3128c16b8a4e9ecc13e8968711d0 to your computer and use it in GitHub Desktop.
r/learnpython 23-01-2018
def none_slice_gabriel(lst, start, stop):
i = start
while i < 0 and i < stop:
yield None
i += 1
while i < len(lst) and i < stop:
yield lst[i]
i += 1
while i < stop:
yield None
i += 1
def none_slice_elbiot(mylist, start, stop):
length = len(mylist)
if stop < start:
raise ValueError('{} is not less than {}'.format(start, stop))
elif (stop < 0) or (start > length-1):
return [None] * (stop - start)
else:
part1 = [None] * (0 - min(start, 0))
part2 = mylist[max(start, 0):stop] # negative start causes empty
part3 = [None] * max(0, stop-length)
return part1 + part2 + part3
def main():
test_cases = [
(-5, -5, []),
(-5, 0, [None] * 5),
(-2, 2, [None, None, 0, 1]),
(0, 0, []),
(0, 5, list(range(5))),
(3, 7, list(range(3, 7))),
(9, 11, [9, None]),
(10, 11, [None]),
(11, 11, [])
]
mylist = [i for i in range(23) if i % 2 == 0]
for start, stop, _ in test_cases:
x = list(none_slice_gabriel(mylist, start, stop))
y = none_slice_elbiot(mylist, start, stop)
assert x == y
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment