Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Asking a favour
#4
A small training session in my favorite language
#!/usr/bin/env python3
import itertools as itt
import os

def iranduint():
    yield from itt.chain.from_iterable(os.urandom(1024) for k in itt.count())
iranduint = iranduint()

def irandrange(n):
    sz = n.bit_length()
    if sz > 8:
        raise ValueError('Expected value < 256, got', n)
    m = 2 ** sz
    assert((m/2) <= n < m)
    for x in iranduint:
        x %= m
        if x < n:
            yield x
            
def irandchoice(n):
    s = set()
    while True:
        x = next(irandrange(n))
        if x in s:
            continue
        s.add(x)
        yield x

def make_key():
    rotor = [x for x in range(1, 9)]
    alpha = [x for x in "ABCDEFGHIJKL"]
    chx = irandchoice(len(alpha))
    core = [alpha[next(chx)] for i in range(8)]
    g36 = irandrange(36)
    ring = [1 + next(g36) for i in range(8)]
    g11 = irandchoice(11)
    notchring = [1 + next(g11) for i in range(7)]
    notchring.insert(3, '')
    beta = ("A, B, B+, C, D, E, E+, F, G, G+, "
            "H, I, J, J+, K, L, M, M+ N, O, O+, "
            "P, Q, R, R+, S, T, T+, U, V, W, W+, "
            "X, Y, Z, Z+").replace(",", "").split()
    val = irandrange(len(beta))
    ringset = [beta[next(val)] for i in range(7)]
    ringset.insert(3, '')
    return rotor, core, ring, notchring, ringset

if __name__ == '__main__':
    for row in make_key():
        print(''.join('{:<3}'.format(x) for x in row))
Output:
1 2 3 4 5 6 7 8 G D A F J L H E 34 31 36 29 4 19 11 3 6 9 7 1 8 5 10 S B+ D X Z+ A M
Starting with 3.6, one can use the secrets module instead of os.urandom
Reply


Messages In This Thread
Asking a favour - by kityatyi - Dec-14-2018, 04:51 PM
RE: Asking a favour - by Larz60+ - Dec-14-2018, 05:55 PM
RE: Asking a favour - by kityatyi - Dec-14-2018, 06:02 PM
RE: Asking a favour - by Gribouillis - Dec-14-2018, 07:23 PM
RE: Asking a favour - by kityatyi - Dec-14-2018, 07:24 PM
RE: Asking a favour - by kityatyi - Dec-14-2018, 08:47 PM
RE: Asking a favour - by Gribouillis - Dec-14-2018, 09:23 PM
RE: Asking a favour - by kityatyi - Dec-14-2018, 09:25 PM
RE: Asking a favour - by Gribouillis - Dec-14-2018, 09:34 PM
RE: Asking a favour - by kityatyi - Dec-14-2018, 09:36 PM
RE: Asking a favour - by Gribouillis - Dec-14-2018, 09:53 PM
RE: Asking a favour - by kityatyi - Dec-14-2018, 10:35 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020