Last active
August 29, 2015 14:03
-
-
Save gchiam/9d1938483b174806c2d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Sequence generator | |
$ python sequence.py 3 | |
[3] | |
[2, 1] | |
[1, 1, 1] | |
$python sequence.py 6 | |
[6] | |
[5, 1] | |
[4, 2] | |
[4, 1, 1] | |
[3, 3] | |
[3, 2, 1] | |
[3, 1, 1, 1] | |
[2, 2, 2] | |
[2, 2, 1, 1] | |
[2, 1, 1, 1, 1] | |
[1, 1, 1, 1, 1, 1] | |
""" | |
import argparse | |
def gen_sequence(sequence, previous_first=None): | |
first = sequence[0] | |
start = first - 1 | |
if previous_first is None: # first entry | |
yield sequence | |
for new_number in xrange(start, 0, -1): | |
second = first - new_number | |
new_sequence = [new_number, second] + sequence[1:] | |
if new_number >= second: | |
yield new_sequence | |
new_first = new_sequence[0] | |
if len(new_sequence) > 1 and new_sequence[1] > 1: | |
sub_sequence = new_sequence[1:] | |
sub_first = new_first | |
for sub_sequence in gen_sequence(sub_sequence, sub_first): | |
if new_first >= sub_sequence[0]: | |
if previous_first is None or previous_first >= new_first: | |
yield [new_first] + sub_sequence | |
def main(): | |
"""Main function""" | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
'number', | |
metavar='N', | |
type=int, | |
help='Size') | |
args = parser.parse_args() | |
initial_sequence = [args.number] | |
for element in gen_sequence(initial_sequence): | |
print element | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment