Implement "All You Need Is Kill" in Python

A live-action movie version of "All You Need Is Kill" has been released released throughout Japan on July 4, 2014 .co.jp/edgeoftomorrow/) To commemorate that, I wrote the ʻAllYouNeedIsKill` class in Python.

aynik.py


#!/usr/bin/env python3
# vim:fileencoding=utf-8

# Copyright (c) 2014 Masami HIRATA <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     1. Redistributions of source code must retain the above copyright notice,
#        this list of conditions and the following disclaimer.
#
#     2. Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

__all__ = ['AllYouNeedIsKill']


class AllYouNeedIsKill:
    def __init__(self, iterable):
        self._iter_source = iter(iterable)
        self._buffer = []
        self._iter_buffer = None

    def __iter__(self):
        return self

    def __next__(self):
        if self._iter_buffer is not None:
            try:
                return next(self._iter_buffer)
            except StopIteration:
                self._iter_buffer = None
        value = next(self._iter_source)
        self._buffer.append(value)
        return value

    def rewind(self):
        if self._buffer:
            self._iter_buffer = iter(self._buffer)
        else:
            self._iter_buffer = None

    def reset(self):
        if self._iter_buffer is not None:
            self._buffer = list(self._iter_buffer)
            self.rewind()
        else:
            self._buffer = []

ʻThe instance of the AllYouNeedIsKillclass behaves as an iterator with therewind ()method for rewinding and thereset ()` method for starting from the state at the time of execution added to the iterator of the argument object. ..

The sample is below.

>>> from itertools import count  # count()Is an iterator that just keeps counting up
>>> from aynik import AllYouNeedIsKill
>>> counter = AllYouNeedIsKill(count(1))
>>> next(counter)
1
>>> next(counter)
2
>>> counter.rewind()  #Perform rewind
>>> next(counter)  #Rewound so it becomes 1
1
>>> next(counter)
2
>>> counter.reset()  #Starting from the current state
>>> next(counter)
3
>>> counter.rewind()  #Perform rewind
>>> next(counter)  #The return value will be 3 instead of 1
3
>>> 

The ʻAllYouNeedIsKill class allows me to handle infinite iterators as well, but it's implemented in a class rather than a function, and it's typed like some tools in the standard library ʻitertools. Please note that the performance is poor due to not deploying iterators to tuples and the code is not Python-like.

ʻAynik.py` will be released under a two-clause BSD license, so feel free to use it.

Recommended Posts

Implement "All You Need Is Kill" in Python
Implement recommendations in Python
Implement XENO in python
Implement sum in Python
About __all__ in python
Implement Traceroute in Python 3
Implement naive bayes in Python 3.3
Implement ancient ciphers in python
Implement Redis Mutex in Python
Implement extension field in Python
Implement fast RPC in Python
Implement method chain in Python
Implement Dijkstra's Algorithm in python
Implement Slack chatbot in Python
(Maybe) This is all you need to pass the Python 3 Engineer Certification Data Analysis Exam
Implement stacking learning in Python [Kaggle]
Implement R's power.prop.test function in python
Difference between == and is in python
Use fabric as is in python (fabric3)
Python is UnicodeEncodeError in CodeBox docker
Do you need a Python re.compile?
Until you put Python in Docker
There is no switch in python
Quickly implement REST API in Python
Python in is also an operator
How to use the asterisk (*) in Python. Maybe this is all? ..
[Python] When you want to use all variables in another file
Implement __eq__ etc. generically in Python class
"<" In python> pack ("<L", ...) is little endian
I tried to implement permutation in Python
Inject is recommended for DDD in Python
Implement FIR filters in Python and C
I tried to implement PLSA in Python 2
What is "mahjong" in the Python library? ??
Hash in Perl is a dictionary in Python
I tried to implement ADALINE in Python
How to use is and == in Python
[Python] Combine all the elements in the array
Try to implement Oni Maitsuji Miserable in python
What is "functional programming" and "object-oriented" in Python?
How to implement Discord Slash Command in Python
What is wheezy in the Docker Python image?
How to implement shared memory in Python (mmap.mmap)
About the difference between "==" and "is" in python
I tried to implement TOPIC MODEL in Python
[Implementation for learning] Implement Stratified Sampling in Python (1)
Why you are interested in motor control in Python
I tried to implement selection sort in python
Implement PRML algorithm in Python (almost Numpy only)
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Python is easy
Implement a circular expression binary search in Python. There is a comparison with a simple full search.
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python