Beispiel #1
0
def main():
    max = 1000000 # one million

    C = Collatz()
    for i in range(1, max): # 1 <= i < max
        this_collatz_seq = C.get_collatz_sequence(i)
        C.store_collatz_lengths(this_collatz_seq)

    # C.collatz_lengths_stored を value で整列して出力
    for start_num, collatz_length in sorted(C._collatz_lengths_stored.items(), key=lambda x:x[1]):
        sys.stdout.write("start number: %s, collatz sequence length: %s\n" %(start_num, collatz_length))
def plot_comparison(sequences, scale='linear'):
    '''Plot each sequence in sequences on the same plot.'''
    linear = scale == 'linear'
    plt.style.use('ggplot')
    plotted_sequences = 0
    for sequence in sequences:
        if len(sequence) == 1:
            print(
                f'Sequence {sequence!r} not plotted as only contains one element'
            )
            continue
        x_values = range(len(sequence))
        sequence_label = Collatz.convert_to_scientific_form(sequence[0])
        try:
            plt.plot(x_values, sequence, label=sequence_label)
            plotted_sequences += 1
        except OverflowError:
            print(f'ERROR: Sequence {sequence!r} too large to plot')
            continue
    # Axis limits
    plt.xlim(0)
    y_min = 0 if linear else 1
    plt.ylim(y_min)
    # Labels
    plt.title(f'Comparison plot of {plotted_sequences} Collatz sequences')
    plt.xlabel('Step')
    plt.ylabel(fr'Value - $\it{{{scale}\ scale}}$')
    # Scale
    scale = 'linear' if linear else 'log'
    plt.yscale(scale)
    if len(sequences) <= 10:
        plt.legend(title='First term', facecolor='#fdf6e3', framealpha=1)
    plt.show()
Beispiel #3
0
def test_convert_to_scientific_form(input_number, decimal_places, threshold,
                                    expected_output):
    '''Test method converts to scientific form.'''
    # Act, assert
    actual_output = Collatz.convert_to_scientific_form(
        input_number, decimal_places=decimal_places, threshold=threshold)
    assert expected_output == actual_output
Beispiel #4
0
class CollatzTest(unittest.TestCase):
    def setUp(self):
        self.c = Collatz()

    def test_one(self):
        expected = [1]
        result = self.c.chain(1)
        self.assertEquals(expected, result)

    def test_two(self):
        expected = [2, 1]
        result = self.c.chain(2)
        self.assertEquals(expected, result)

    def test_13(self):
        expected = [13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
        result = self.c.chain(13)
        self.assertEquals(expected, result)

    def test_len_chain(self):
        expected = 10
        result = self.c.len_chain(13)
        self.assertEquals(expected, result)

    def test_find_greatest_chain(self):
        expected = 2
        result = self.c.find_greatest_chain(1, 2)
        self.assertEquals(expected, result)

    def test_find_greatest_chain100(self):  # ~38s
        expected = 525
        result = self.c.find_greatest_chain(1, 1000000)
        self.assertEquals(expected, result)
Beispiel #5
0
def collatz_complete():
    if request.method == 'POST':
        num1 = request.form['num1']
        try:
            val = int(num1)
        except ValueError:
            return render_template(
                'appInitial.html',
                message="Please input an Integer and try again")

        thisCollatz = Collatz(num1)
        thisCollatz.collatz()
        initialNumberString = str(thisCollatz.getInitialNumber())
        numNowListString = thisCollatz.getNumberNowList()
        loopCountString = str(thisCollatz.getLoopCount())
        finalNumString = str(thisCollatz.getFinalNumber())
        return render_template('appComplete.html',
                               collatzNumInitial=initialNumberString,
                               collatzList=numNowListString,
                               collatzLoop=loopCountString,
                               collatzNumFinal=finalNumString)
Beispiel #6
0
 def test_dezesseis_retorna_dezesseis_oito_quatro_dois_um(self):
     self.assertEqual(Collatz(16).retorna_sequencia(), (16,8,4,2,1))
Beispiel #7
0
 def test_oito_retorna_oito_quatro_dois_um(self):
     self.assertEqual(Collatz(8).retorna_sequencia(), (8,4,2,1))
Beispiel #8
0
 def test_quatro_retorna_quatro_dois_um(self):
     self.assertEqual(Collatz(4).retorna_sequencia(), (4,2,1))
Beispiel #9
0
 def test_dois_deve_retornar_dois_um(self):
     self.assertEqual(Collatz(2).retorna_sequencia(), (2,1))
Beispiel #10
0
def test_ordering(number_1, number_2, ordering):
    '''Test comparison ordering as for tuples.'''
    assert ordering(Collatz(number_1), Collatz(number_2))
Beispiel #11
0
 def __init__(self):
     self.queue = queue.Queue()
     self.collatz = Collatz()
     threading.Thread(target=self.await_submission).start()
Beispiel #12
0
 def test_inic_classe(self):
     self.assertTrue(isinstance(Collatz(5), int))
Beispiel #13
0
def test_generate_sequences(example_sequence):
    '''Test generated collatz sequences are correct for a few first terms.'''
    first_term = example_sequence[0]
    assert Collatz(first_term) == example_sequence
Beispiel #14
0
 def setUp(self):
     self.c = Collatz()
Beispiel #15
0
    def elaborate(self, platform):
        m = Module()
        m.domains.sync = ClockDomain()

        if not self.sim:
            clk12 = platform.request("clk12")
            m.d.comb += ClockSignal().eq(clk12.i)
            board_uart = platform.request("uart")
        else:
            clk12 = None
            board_uart = None

        self.uartfifo = uartfifo = UART_FIFO(sim=self.sim,
                                             sim_tx_cycle_accurate=self.sim_tx_cycle_accurate,
                                             width=8,
                                             depth=1024,
                                             clk=clk12,
                                             board_uart=board_uart)
        self.collatz = collatz = Collatz(xwidth, nwidth)
        self.uart_printer = uart_printer = UART_Printer(uartfifo.w_fifo)
        m.submodules.uartfifo = uartfifo
        m.submodules.collatz = collatz
        m.submodules.uart_printer = uart_printer

        m.d.comb += [
            self.tx.eq(uartfifo.tx),
            self.rx.eq(uartfifo.rx)
        ]

        m.d.comb += [
            self.collatz.ld_x.eq(self.x),
        ]
        with m.FSM(reset='AWAIT_START') as fsm:
            with m.State('AWAIT_START'):
                with m.If(uartfifo.r_fifo.r_rdy):
                    with m.If(uartfifo.r_fifo.r_data == 65):
                        # A is the start character
                        m.d.comb += [
                            uartfifo.r_fifo.r_en.eq(1),
                        ]
                        m.next = 'INC'
                    with m.Else():
                        # swallow and ignore
                        m.d.comb += [
                            uartfifo.r_fifo.r_en.eq(1)
                        ]
                        m.next = 'AWAIT_START'
            with m.State('INC'):
                m.d.sync += [
                    self.x.eq(self.x + 1)
                ]
                m.next = 'CALC_START'
            with m.State('CALC_START'):
                m.d.comb += [
                    self.collatz.start.eq(1)
                ]
                m.next = 'CALC'
            with m.State('CALC'):
                with m.If(self.collatz.done):
                    with m.If(self.collatz.out > self.nmax):
                        m.d.sync += [
                            self.nmax.eq(self.collatz.out),
                            self.nmaxcnt.eq(self.nmaxcnt+1),
                            self.xmax.eq(self.x),
                        ]
                        # was a new record, print to terminal
                        m.next = 'R_1'
                    with m.Elif(self.collatz.err_n):
                        m.next = 'ERR_N_1'
                    with m.Elif(self.collatz.err_x):
                        m.next = 'ERR_X_1'
                    with m.Else():
                        # not a new record sequence length, and neither an error
                        m.next = 'INC'

            with m.State('R_1'):
                with m.If(uart_printer.writable):
                    m.d.comb += [
                        uart_printer.din.eq( Cat(self.nmaxcnt, Signal(34-nwidth), Const(0x5)) ),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'N_1'

            with m.State('N_1'):
                with m.If(uart_printer.writable):
                    m.d.comb += [
                        uart_printer.din.eq( Cat(self.nmax, Signal(34-nwidth), Const(0x5)) ),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'X_1'

            with m.State('X_1'):
                with m.If(uart_printer.writable):
                    m.d.comb += [
                        uart_printer.din.eq( Cat(self.xmax, Const(0x5)) ),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'END'
            #        m.next = 'SUFFIX_1'

            #with m.State('SUFFIX_1'):
            #    with m.If(uart_printer.writable):
            #        m.d.comb += [
            #            uart_printer.din.eq( Cat(Signal(32, reset=0x123456AB), Signal(2), Const(0x7)) ),
            #            uart_printer.we.eq(1)
            #        ]
            #        m.next = 'END'

            with m.State('ERR_N_1'):
                with m.If(uart_printer.writable):
                    # padding needed to get to 34 bits data
                    # CR, LF, BELL, 0<ignored>, pad(2bit), cmd(3bit)
                    p = Cat(Signal(8,reset=ord('N')), Signal(8,reset=ord(' ')), Signal(8), Signal(8), Signal(2), Const(4))
                    m.d.comb += [
                        uart_printer.din.eq(p),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'ERR_N_2'
            with m.State('ERR_N_2'):
                with m.If(uart_printer.writable):
                    m.d.comb += [
                        uart_printer.din.eq( Cat(self.collatz.out, Signal(34-nwidth), Const(0x5)) ),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'ERR_N_3'
            with m.State('ERR_N_3'):
                with m.If(uart_printer.writable):
                    m.d.comb += [
                        uart_printer.din.eq( Cat(self.x, Const(0x5)) ),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'END'

            with m.State('ERR_X_1'):
                with m.If(uart_printer.writable):
                    # padding needed to get to 34 bits data
                    # CR, LF, BELL, 0<ignored>, pad(2bit), cmd(3bit)
                    p = Cat(Signal(8,reset=ord('X')), Signal(8,reset=ord(' ')), Signal(8), Signal(8), Signal(2), Const(4))
                    m.d.comb += [
                        uart_printer.din.eq(p),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'ERR_X_2'
            with m.State('ERR_X_2'):
                with m.If(uart_printer.writable):
                    m.d.comb += [
                        uart_printer.din.eq( Cat(self.collatz.out, Signal(34-nwidth), Const(0x5)) ),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'ERR_X_3'
            with m.State('ERR_X_3'):
                with m.If(uart_printer.writable):
                    m.d.comb += [
                        uart_printer.din.eq( Cat(self.x, Const(0x5)) ),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'END'

            with m.State('END'):
                with m.If(uart_printer.writable):
                    # padding needed to get to 34 bits data
                    # CR, LF, BELL, 0<ignored>, pad(2bit), cmd(3bit)
                    p = Cat(Signal(8,reset=13), Signal(8,reset=10), Signal(8,reset=7), Signal(8), Signal(2), Const(4))
                    m.d.comb += [
                        uart_printer.din.eq(p),
                        uart_printer.we.eq(1)
                    ]
                    m.next = 'INC'
        return m
Beispiel #16
0
 def test_impar(self):
     self.assertEqual(Collatz(5).retorna_sequencia(), (5,16,8,4,2,1))
Beispiel #17
0
from collatz import CollatzFunction as Collatz
from utils import ffs

C = Collatz()


def print_sequence(n):
    for k in C.orbit(n):
        print(k)


def print_ffs_after_increase(n):
    assert n > 0
    i = 1  # Count which iteration we're on
    print("1: {}".format(n))
    while n > 1:
        i += 1
        m = C(n)
        if m > n:  # We increased w/ m = 3n + 1
            print("{}: {} {}".format(i, m, ffs(m)))
        else:
            print("{}: {}".format(i, m))
        n = m


if __name__ == '__main__':
    while True:
        selection = input('''(1) print orbit
(2) print orbit with trailing zeros info
''')
        try:
Beispiel #18
0
 def test_maior_sequencia(self):
     self.assertEqual(Collatz(5).maior_sequencia(), (3,10,5,16,8,4,2,1))
Beispiel #19
0
def test_raise_value_error(wrong_input_value):
    '''Check ValueError raised for negative numbers, 0, and non-integer floats.
    '''
    with pytest.raises(ValueError):
        Collatz(wrong_input_value)
Beispiel #20
0
def test_raise_type_error(wrong_input_type):
    '''Check TypeError raised when input is not a float or integer.'''
    with pytest.raises(TypeError):
        Collatz(wrong_input_type)
Beispiel #21
0
class Judge:

    docker_name = 'sandbox'
    runtime = 'python3'
    timeout = 30

    def __init__(self):
        self.queue = queue.Queue()
        self.collatz = Collatz()
        threading.Thread(target=self.await_submission).start()

    """
    Busy wait until we get a submission. Once we get a submission, run the
    judge
    """
    def await_submission(self):
        while True:
            try:
                submission = self.queue.get(timeout=1)
                self.run_judge(submission)
            except queue.Empty:
                continue

    """
    Submit a submission to the judge for grading
    """
    def submit(self, submission):
        self.queue.put(submission)

    """
    Run a given submission on docker
    """
    def run_judge(self, submission):
        f = self.prepare_submission(submission)
        file_path = os.path.dirname(f.name)
        file_name = os.path.basename(f.name)

        # The judge now has the submission
        submission.status = Submission.RUNNING
        submission.save()

        # Setup the docker command we're going to run to test the submission
        docker_name = str(uuid.uuid4())
        docker_cmd = [
            'docker',
            'run',
            '--name="%s"' % docker_name,
            '-v',
            '%s:/judging_dir:ro' % os.getcwd(),
            '-w',
            '/judging_dir',
            '-a',
            'stdin',
            '-a',
            'stdout',
            '-i',
            self.docker_name,
            self.runtime,
            f.name
        ]

        # Generate a test
        test_in, test_out = self.collatz.generate_tests()
        test_in_file = tempfile.TemporaryFile()
        test_in_file.write(test_in.encode("UTF-8"))
        test_in_file.seek(0)

        ran_to_completion = [True]

        # Create a timer to watch for timeouts
        def timeout_func():
            ran_to_completion[0] = False
            try:
                subprocess.call(['docker', 'rm', '-f', docker_name])
            except:
                pass
        timer = threading.Timer(self.timeout, timeout_func)
        timer.start()

        # Run the docker test command in a new process
        runner = subprocess.Popen(
            shlex.split(' '.join(docker_cmd)),
            stdin=test_in_file,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        stdout, stderr = runner.communicate()

        # We're done with everything, stop the timer
        timer.cancel()
        f.close()
        os.remove(f.name)

        # Verify the program's output if it completed
        if ran_to_completion[0]:
            self.verify_output(submission, stdout.decode('ascii'), test_out)
        else:
            submission.status = Submission.TIMEOUT
            submission.save()

    """
    Take a submission and turn the submission text into a file we can run
    against docker
    """
    def prepare_submission(self, submission):
        fp = open('tmp.py', 'w+')
        fp.write(submission.submission_text)
        fp.seek(0)
        return fp

    """
    Verify the output of the program and update the submission with the status
    """
    def verify_output(self, submission, actual, expected):
        if actual == expected:
            submission.status = Submission.PASSED
        else:
            submission.status = Submission.FAILED
            submission.actual_out = actual
            submission.expected_out = expected

        submission.save()