Exemplo n.º 1
0
def test_collatz():
    assert collatz(1) == "1"
    assert collatz(2) == "2->1"
    assert collatz(3) == "3->10->5->16->8->4->2->1"
    assert collatz(4) == "4->2->1"

    result = "27->82->41->124->62->31->94->47->142->71->214->107->322->" + \
             "161->484->242->121->364->182->91->274->137->412->206->103->" + \
             "310->155->466->233->700->350->175->526->263->790->395->" + \
             "1186->593->1780->890->445->1336->668->334->167->502->251->" + \
             "754->377->1132->566->283->850->425->1276->638->319->958->" + \
             "479->1438->719->2158->1079->3238->1619->4858->2429->7288->" + \
             "3644->1822->911->2734->1367->4102->2051->6154->3077->9232->" + \
             "4616->2308->1154->577->1732->866->433->1300->650->325->976->" + \
             "488->244->122->61->184->92->46->23->70->35->106->53->160->" + \
             "80->40->20->10->5->16->8->4->2->1"
    assert collatz(27) == result
Exemplo n.º 2
0
 def test_collatz(self):
     self.assertEquals(5, collatz.collatz(10))
     self.assertEquals(16, collatz.collatz(5))
     self.assertEquals(8, collatz.collatz(16))
     self.assertEquals(4, collatz.collatz(8))
     self.assertEquals(2, collatz.collatz(4))
     self.assertEquals(1, collatz.collatz(2))
def collatzpage():
    form = UserInput(request.form)
    print(form.errors)
    clist = []
    if request.method == 'POST':
        try:
            number = int(request.form['number'])
        except ValueError:
            number = 2

        if form.validate():
            clist = list(collatz(number))

    return render_template('collatz.html', form=form, clist=clist)
 def test_return_value_for_8(self):
     self.assertEqual(collatz(8), 4)
 def test_input_value_16(self):
     self.assertEqual(collatz(5), 16)
 def test_8(self):
     self.assertEqual(collatz(8), 4)
 def test_5(self):
     self.assertEqual(collatz(5), 16)
Exemplo n.º 8
0
	def spec_collatz_dez(self):
		collatz(10) |should| equal_to([10, 5, 16, 8, 4, 2, 1])	
Exemplo n.º 9
0
def test_answer():
    assert collatz.collatz(2) == 1
Exemplo n.º 10
0
#!/usr/bin/env python3

if __name__ == "__main__":
    from collatz import collatz
    import argparse

    desc = "Find the number with the longest Collatz sequence under a given ceiling."
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument("ceiling", type=int, default=13, nargs="?")
    args = parser.parse_args()

    ceiling = args.ceiling
    results = {}

    for x in range(ceiling - 1, 1, -2):
        results[collatz(x)] = x

    longest = max(iter(results))
    answer = results[longest]
    print("Longest: C{0} for {1}".format(longest, answer))

    print_all = False
    if print_all:
        for i in range(0, len(results)):
            print("{0}: {1}".format(i + 1, results[i]), end="\t")
        print("")
Exemplo n.º 11
0
import matplotlib.pyplot as plt

from collatz import collatz

x = []
y = []
for n in range(1, 5000 ):
    x.append(n)
    y.append(max(collatz(n)))

fig, ax = plt.subplots()
ax.plot(x, y, 'o', markersize=1)
ax.set(xlabel='n', ylabel='max', title='Maximum value of Collatz sequence')
plt.show()
Exemplo n.º 12
0
def _collatz_finder(value):
    res = collatz(value)
    return (value, res[0])
Exemplo n.º 13
0
 def test_2_retorna_2_1(self):
     self.assertEqual(collatz(2), [2, 1])
Exemplo n.º 14
0
 def test_1_retorna_1(self):
     self.assertEqual(collatz(1), [1])
Exemplo n.º 15
0
 def test_13_retorna_13_40_20_10_5_16_8_4_2_1(self):
     self.assertEqual(collatz(13), [13, 40, 20, 10, 5, 16, 8, 4, 2, 1])
Exemplo n.º 16
0
 def test_3_retorna_3_10_5_16_8_4_2_1(self):
     self.assertEqual(collatz(3), [3, 10, 5, 16, 8, 4, 2, 1])
Exemplo n.º 17
0
 def test_5_retorna_5_16_8_4_2_1(self):
     self.assertEqual(collatz(5), [5, 16, 8, 4, 2, 1])
Exemplo n.º 18
0
 def test_4_retorna_4_2_1(self):
     self.assertEqual(collatz(4), [4, 2, 1])
Exemplo n.º 19
0
def test_collatz(num, result):
    """Test for collatz."""
    from collatz import collatz
    assert collatz(num) == result
Exemplo n.º 20
0
def test_collatz_general():
    lengths = [0, 0, 1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9, 17, 17, 4, 12, 20, 20,
               7, 7, 15, 15, 10, 23, 10, 111, 18, 18, 18, 106, 5, 26, 13, 13,
               21, 21, 21, 34, 8, 109, 8, 29, 16, 16, 16, 104, 11, 24, 24]
    for i, l in zip(range(len(lengths) + 1), lengths):
        assert collatz(i) == l
Exemplo n.º 21
0
 def collatz(self, n):
     return collatz.collatz(n)
Exemplo n.º 22
0
def test_collatz_63728127():
    assert collatz(63728127) == 949
Exemplo n.º 23
0
            8. Magic Eight Ball
            9. The Collatz Sequence
            """)

    game = int(input("Input the number of the game we're playing: "))
    print("-" * 65)
    
    if game == 1:
        rand.guess()
    elif game == 2:
        hang.hangman()
    elif game == 3:
        rps.rps()
    elif game == 4:
        mad.madlib()
    elif game == 5:
        caps.caps_game()
    elif game == 6:
        aliens.a_game.play()
    elif game == 7:
        yourname.yourname()
    elif game == 8:
        magic.magic()
    elif game == 9:
        collatz.collatz()
    elif game == 0:
        print("Bye!")
        over = False
    else:
        print("There isnt a game like that")
Exemplo n.º 24
0
def test_collatz_0():
    assert collatz(0) == 0
Exemplo n.º 25
0
	def spec_collatz_cinco(self):
		collatz(5) |should|	equal_to([5, 16, 8, 4, 2, 1])
Exemplo n.º 26
0
def test_collatz_0bad():
    assert collatz(0) != 1
Exemplo n.º 27
0
	def spec_collatz_treze(self):
		collatz(13) |should| equal_to([13, 40, 20, 10, 5, 16, 8, 4, 2, 1])
Exemplo n.º 28
0
 def test_checkvalue1(self):
     self.assertEqual(collatz.collatz(8), 4)
 def test_type_error(self):
     with self.assertRaises(TypeError):
         collatz('aoeu')
Exemplo n.º 30
0
 def test_checkvalue2(self):
     self.assertEqual(collatz.collatz(5), 16)
 def test_input_value_4(self):
     self.assertEqual(collatz(8), 4)
Exemplo n.º 32
0
 def test_checkstring(self):
     self.assertRaises(TypeError, collatz.collatz('aoeu'))
 def test_wrong_type_of_input(self):
     with self.assertRaises(TypeError):
         collatz('string_value')
 def test_collatz_1(self):
     with self.assertRaises(TypeError):
         collatz('aoue')
 def test_return_value_for_5(self):
     self.assertEqual(collatz(5), 16)
Exemplo n.º 36
0
def test_answer():
    assert collatz.collatz(2) == 1
Exemplo n.º 37
0
def _main():
    # Parse the arguments
    arg_len = len(sys.argv)
    _START = 1
    _END = 100000
    _STEP = 1
    if arg_len == 2:
        _END = _parse_positive_int(sys.argv[1], 1)
    elif arg_len == 3:
        _START = _parse_positive_int(sys.argv[1], 1)
        _END = _parse_positive_int(sys.argv[2], 2)
    elif arg_len >= 4:
        _START = _parse_positive_int(sys.argv[1], 1)
        _END = _parse_positive_int(sys.argv[2], 2)
        _STEP = _parse_positive_int(sys.argv[3], 3)
    if _END < _START:
        print('Cannot have the end of the range before the start of the range')
        sys.exit(-1)
    _COUNT = int((_END - _START) // _STEP + 1)
    print('Using range ({}, {}), step {}, total {}'.format(
        _START, _END, _STEP, _COUNT))

    # Figure out multiprocessing
    _MULTIPROC = _COUNT >= 50_000 and mproc.cpu_count() > 1
    if _MULTIPROC:
        print('Using multiprocessing on {} cores'.format(mproc.cpu_count()))

    # Calculate the sequences
    inputs = range(_START, _END + 1, _STEP)
    outputs = np.zeros((_COUNT, 2), dtype=int)
    start_time = 0.
    end_time = 0.
    if _MULTIPROC:
        calc_pool = mproc.Pool(mproc.cpu_count())
        start_time = timer_f()
        res = calc_pool.map(_collatz_finder, inputs)
        end_time = timer_f()
        calc_pool.close()
        for ii, val in enumerate(res):
            outputs[ii] = val
    else:
        start_time = timer_f()
        for i, coll_in in enumerate(inputs):
            outputs[i][0] = coll_in
            outputs[i][1] = collatz(coll_in)[0]
        end_time = timer_f()
    print('Finished calculating in {:.3f} seconds'.format(end_time -
                                                          start_time))

    # Generate info about the numbers
    min_coll = outputs[np.argmin(outputs[:, 1])]
    max_coll = outputs[np.argmax(outputs[:, 1])]
    x_range = _END - _START
    y_range = max_coll[1] - min_coll[1]
    y_min = min_coll[1]
    shift_size = (0.004 * x_range, 0.004 * y_range)

    # Get the graph type
    gtype = 0
    while True:
        gtype = input(
            'Enter the plot type to use (0=linear [default], 1=log) > ').strip(
            )
        if len(gtype) == 0:
            break
        try:
            gtype = int(gtype)
            if gtype == 0 or gtype == 1:
                break
            print('Please enter a valid number')
        except:
            print('Please enter a valid number')
            continue

    # Generate the graph
    print('Generating and saving graph...')
    start_time = timer_f()
    plt.style.use('ggplot')
    fig, axs = plt.subplots(1, 1, figsize=(11, 8.5))
    fig.suptitle('Collatz Stopping Numbers', fontsize=18)
    axs.set_title('Start: {}  End: {}  Step: {}'.format(_START, _END, _STEP),
                  fontsize=10)
    axs.set_xlabel('Input [n]')
    axs.set_ylabel('Collatz(n)')
    axs.scatter(outputs[:, 0], outputs[:, 1], s=6)
    if gtype == 1:
        axs.set_xscale('log')
    axs.text(max_coll[0] + shift_size[0], max_coll[1] + shift_size[1],
             'Max: ({}, {})'.format(*max_coll))
    axs.text(min_coll[0] + shift_size[0],
             min_coll[1] - shift_size[1],
             'Min: ({}, {})'.format(*min_coll),
             verticalalignment='top')
    if not os.path.isdir('./img/stop'):
        os.makedirs('./img/stop')
    fig.savefig('./img/stop/{}.{}.{}.png'.format(_START, _END, _STEP))
    end_time = timer_f()
    print('Complete ({:.1f} ms)'.format((end_time - start_time) * 1000))
def collatz_range(start, end):
    stepsTaken = [];
    for n in range(start,end):
        stepsTaken.append(collatz(n))
    print(stepsTaken)
    return stepsTaken
Exemplo n.º 39
0
import collatz

# Start of program
print("Enter number to see Collatz Sequence:")
try:
    number = int(input())
    collatz.collatz(number)
except ValueError:
    print("ERROR: Input is not a number, please enter a valid integer")
Exemplo n.º 40
0
# -*- coding: utf-8 -*-
"""
Created on Sat May 26 21:49:27 2018

@author: Administrator
"""
import collatz

print("请输入一个整数:")
try:
    num = int(input())

    while (num != 1):
        num = collatz.collatz(num)
except ValueError:
    print("警告,输入的必须为一个整数!")
Exemplo n.º 41
0
 def test_collatz(self):
     self.assertEqual(collatz.collatz(1), 4)
     self.assertEqual(collatz.collatz(2), 1)
     self.assertEqual(collatz.collatz(3), 10)
     self.assertEqual(collatz.collatz(4), 2)
     self.assertEqual(collatz.collatz(5), 16)
     self.assertEqual(collatz.collatz(6), 3)
     self.assertEqual(collatz.collatz(7), 22)
     self.assertEqual(collatz.collatz(8), 4)
     self.assertEqual(collatz.collatz(9), 28)
     self.assertEqual(collatz.collatz(10), 5)
     self.assertEqual(collatz.collatz(11), 34)
     self.assertEqual(collatz.collatz(12), 6)
     self.assertEqual(collatz.collatz(13), 40)
     self.assertEqual(collatz.collatz(14), 7)
     self.assertEqual(collatz.collatz(15), 46)
     self.assertEqual(collatz.collatz(16), 8)
     self.assertEqual(collatz.collatz(17), 52)
     self.assertEqual(collatz.collatz(18), 9)
     self.assertEqual(collatz.collatz(19), 58)
     self.assertEqual(collatz.collatz(20), 10)
Exemplo n.º 42
0
 def test_collatz_on_five_returns_sixteen(self):
     self.assertEqual(collatz(5), 16)
Exemplo n.º 43
0
 def assert_collatz(self, n, i):
     self.assertEqual(collatz(n), i)
Exemplo n.º 44
0
 def test_collatz_on_eight_returns_four(self):
     self.assertEqual(collatz(8), 4)
Exemplo n.º 45
0
 def test_collatz(self):
     """unittest prime_factorisation.is_prime()"""
     self.assertEqual(collatz(6), [6, 3, 10, 5, 16, 8, 4, 2, 1])
     self.assertEqual(collatz(19),
                      [19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13,
                       40, 20, 10, 5, 16, 8, 4, 2, 1])
 def test_values(self):
     self.assertEqual(collatz.collatz(3), 10)
Exemplo n.º 47
0
import collatz

foo = collatz.collatz(6)

Exemplo n.º 48
0
from collatz import collatz

steps = collatz(int(input()))
print(steps)