奥克兰大学CS110(Auckland University Computer Science 110)的一些算法(2022)

免责声明:课余时间写的,仅仅是为了应对考试的时候手算的太慢,不能保证完全应对每种情况,请自行判断和使用,如果有任何bug可以向我反馈,我会尝试修复

代码功能一览
1.凯撒密码加密以及破解
2.块密码加密以及破解(DES)
3.DIFFIE-HELLMAN协议
4.RSA KEY
5.turing(图灵机)
6.transform 16-float point(hex, binary)
7.packets计算
8.switches and routers问题计算
9.查找ASCII值
10.计算substring, prefix, suffix

使用本程序请确保您有一定的python基础

# 1.凯撒密码加密以及破解
"""
string输入:ABCDE
displacement输入:数字
initial输入原字符串
decode输入加密后的字符串
mode4: KEEP CALM/PJJU HFQR or PJJU HFQR/KEEP CALM
"""
import string
A_list = list(string.ascii_uppercase)    # 大写
mode_info = int(input(f'choose 1.加密 2.解密 3.找key 4.判断加密前后是否正确: '))
if mode_info == 1:
    str1 = input(f'pls enter the string: ')
    displacement = int(input(f'shift num: '))
    str2 = ''
    for i in str1:
        if i != ' ':
            str2 += A_list[(A_list.index(i)+displacement) % 26]
        else:
            str2 += ' '
    print(str2)

elif mode_info == 2:
    str1 = input(f'pls enter the string: ')
    displacement = int(input(f'shift num: '))
    str2 = ''
    for i in str1:
        if i != ' ':
            str2 += A_list[(A_list.index(i)-displacement) % 26]
        else:
            str2 += ' '
    print(str2)

elif mode_info == 3:
    initial = input(f'请输入加密前的字符串: ')
    decode = input(f'请输入加密后的字符串: ')
    init_index = A_list.index(initial[0])
    decode_index = A_list.index(decode[0])
    if init_index > decode_index:
        key = (26 - init_index) + decode_index
        print(key)
    elif init_index < decode_index:
        key = decode_index - init_index
        print(key)

elif mode_info == 4:
    initial = input(f'请输入加密前/加密后的字符串: ').replace(' ', '')
    decode = input(f'请输入加密前/加密后的字符串: ').replace(' ', '')
    key_now = 0
    init_index = A_list.index(initial[0])
    decode_index = A_list.index(decode[0])
    judge = True
    if init_index > decode_index:
        key_now = (26 - init_index) + decode_index
    elif init_index < decode_index:
        key_now = decode_index - init_index
    for i in range(1, len(initial)):
        if A_list[(A_list.index(initial[i])+key_now) % 26] != decode[i]:
            judge = False
            break
    if judge:
        print("加密解密正确")
    else:
        print("error")


# 2.块密码加密以及破解
"""
info_string输入例如:GO
encode_list例子:
3 516 3 10 4 6 3 11 0 2
2 3
那么就输入:3 2 5 3
请注意! 一定看清题目使用的index是什么,有的时候是从A为0开始,有的时候是从A为1开始
本程序默认使用A从0开始,如需A从1开始,请将A_list = list(string.ascii_uppercase)注释掉,使用下面被注释的A_list
"""
import string
A_list = list(string.ascii_uppercase)    # 大写
# A_list = ['Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']
mode_choose = int(input(f'1.加密/解密: '))
if mode_choose == 1:
    info_string = input(f'pls enter the info_string: ')
    code_list = input(f'pls enter the encode_list: ').split(' ')
    mod_num = int(input(f'pls enter the mod_num: '))
    code_list = [[int(code_list[i+j]) for j in range(0, int(len(code_list)**0.5))] for i in
                   range(0, len(code_list), int(len(code_list)**0.5))]
    list1 = [A_list.index(i) for i in info_string]
    list1 = [[list1[i+j] for j in range(0, len(code_list))] for i in range(0, len(list1), len(code_list))]
    final_list = []
    for i in list1:
        for j in code_list:
            final_list.append(sum([a * b for a, b in zip(j, i)]))
    final_list = [A_list[i % mod_num] for i in final_list]
    print(''.join(final_list))

# if mode_choose == 2:


# 3.DIFFIE-HELLMAN协议
"""
example:
They have agreed to use p = 31 and g = 11 for the exchange. 
Also, Alice uses her private key a = 4 and Bob uses his private key b = 2.
mod_number = 31
base_number = 11
a_private_key = 4
b_private_key = 2
"""
mod_number = int(input('pls enter the mod_number: '))
base_number = int(input('pls enter the base_number: '))
a_private_key = int(input('pls enter the a_private_key: '))
b_private_key = int(input('pls enter the b_private_key: '))
print('-'*15)
base_number_for_a = base_number
base_number_for_b = base_number
a_value = 0
b_value = 0
times = 1
while True:
    a_value = (base_number_for_a ** a_private_key) % mod_number
    b_value = (base_number_for_b ** b_private_key) % mod_number
    if a_value == b_value:
        print(f'final secret key for both is {a_value}')
        break
    else:
        print(f'after {times} times calculate, a is {a_value}, b is {b_value}')
        base_number_for_a = b_value
        base_number_for_b = a_value
        print('-'*15)
    times += 1


# 4.RSA KEY
"""
p and q is key
Public key = (p, e); Private key = d
P is message P(text mapped from char to numbers somehow)
"""
import random
def Oula(sushu1 , sushu2):
    return (sushu1-1)*(sushu2-1)
def Is_Huzhi(int_min, int_max):
    for i in range(2, int_min+1):
        if int_min % i == 0 and int_max % i == 0:
            return False
    return True
def Creat_E(oula):
    top = oula
    while True:
        i = random.randint(2, top)
        for e in range(i, top):
            if Is_Huzhi(e, oula):
                return e
        top = i
def Compute_D(oula, e):
    k = 1
    while (k*oula+1) % e != 0:
        k += 1
    return int((k*oula+1)/e)


mode_info = int(input('1.计算Private key(d) 2.计算n/m 3.RSA encryption 4.RSA decryption: '))
if mode_info == 1:
    p = int(input('pls enter the p: '))
    q = int(input('pls enter the q: '))
    e = int(input('pls enter the e: '))
    oula = Oula(p, q)
    d = Compute_D(oula, e)
    print(f'Public key(p, e) = {p, e}; Private key(d) = {d}')

elif mode_info == 2:
    p = int(input('pls enter the p: '))
    q = int(input('pls enter the q: '))
    print(f'n is {p * q}')
    print(f'm is {(p - 1) * (q - 1)}')

elif mode_info == 3:
    P = int(input('pls enter the message P(text mapped from char to numbers somehow): '))
    p = int(input('pls enter the p: '))
    e = int(input('pls enter the e: '))
    C = (P ** e) % p
    print(f'C is {C}')

elif mode_info == 4:
    C = int(input('pls enter the C: '))
    d = int(input('pls enter the d: '))
    p = int(input('pls enter the p: '))
    P = (C ** d) % p
    print(f'P is {P}')


# 5.turing(图灵机)
"""
e.g.
# instruction_list = (1,0,1,2,R)(1,1,1,4,R)(2,0,0,4,R)(2,1,0,3,R)(3,0,1,5,R)(3,1,1,1,R)(4,0,0,2,R)(4,1,0,4,R)(5,0,0,2,R)(5,1,1,5,R)
# instruction_list = (1, 0, 1, 1, R)(1, 1, 0, 1, R)
# init_list = 111100

PARITY BIT MACHINE(判断数字是even还是odd): 
instruction_list = (1,0,0,1,R)(1,1,1,2,R)(2,0,0,2,R)(2,1,1,1,R)(1,b,1,3,R)(2,b,0,3,R)
如果最后输出的最后三个b的第一个b被改变为1,数字是even,如果是0,数字是odd(init_list输入二进制)

UNARY INCREMENTING(输入n,得到n+1):
instruction_list = (1, 1, 1, 1, R)(1, b, 1, 2, R) or (1, 1, 1, 1, L)(1, b, 1, 2, L)
init list = 111....

UNARY ADDITION(两个数相加)
instruction_list = (1, 1, b, 2, R) (2, 1, b, 3, R) (3, 1, 1, 3, R)(3, b, 1, 4, R)(3, b, 1, 6, R)
init list = 111b1111

切记一点,这个程序的mode2可能无法判断machine halt!请自行判断
如果程序运行超出7-8次,说明大概率是无法halt,考试题目一般运算次数在6次以下
"""
import re
mode_choose = int(input("请选择模式 1.判断turing是否能够运行 2.运行turing: "))
instruction_list = input('pls enter the instruction_list: ').replace(' ', '')
instruction_list = instruction_list.replace(' ', '')
re_match_content = re.compile(r'[(](.*?)[)]')
after_spilt_list = re.findall(re_match_content, instruction_list)
if mode_choose == 1:
    judge = True
    new_judge_list = [f"{after_spilt_list[i][0]},{after_spilt_list[i][2]}" for i in range(len(after_spilt_list))]
    if len(after_spilt_list) != len(set(after_spilt_list)) or len(after_spilt_list) != len(set(new_judge_list)):
        print("turing有重复,不能运行")
        judge = False

    for i in after_spilt_list:
        if i[0].isdigit() is False or i[6].isdigit() is False:
            print(f"({i})这个地方有错误,turing码的1, 4位只能为数字,不能运行")
            judge = False
            break

        elif i[2] not in ['0', '1', 'b'] or i[4] not in ['0', '1', 'b']:
            print(f"({i})这个地方有错误,turing码的第2, 3位只能为0, 1或者是'b',不能运行")
            judge = False
            break

        elif i[-1] not in ['R', "L"]:
            print(f"({i})这个地方有错误,turing码的第5位只能为'R'或者'L',不能运行")
            judge = False
            break

    if judge is True:
        print('可以运行, valid')

if mode_choose == 2:
    init_list = input("pls enter the init_list: ")   # [0, 1, 1]  011
    init_list = 'bbb' + init_list + 'bbb'
    init_list = [i for i in init_list]
    mode_setting = 1
    position_now = 3
    times = 0
    print(f"start_value: init = {init_list}, position = {position_now}, mode_setting = {mode_setting}")
    while True:
        judge = False
        for i in after_spilt_list:
            if int(i[0]) == mode_setting:
                if i[2] == init_list[position_now]:
                    init_list[position_now] = i[4]
                    mode_setting = int(i[6])
                    if i[-1] == "R":
                        position_now += 1
                    elif i[-1] == "L":
                        position_now -= 1
                    print(f"init = {''.join(init_list)}, position = {position_now}, mode_setting = {mode_setting}")
                    times += 1
                    judge = True

        if judge is False:
            print(f'times: {times}')
            break


# 6.transform 16-float point(hex, binary)
"""
# 6004
# C102
"""
mode = int(input(f"select 1.16进制(例:ECC8) 2.判断10进制能否转换为16-float: "))
if mode == 1:
    point_float = input("pls enter the 16 bits hexmode(ECC8 or 0000000000000000格式): ")
    final_string = ''
    if len(point_float) == 4:
        # point_float = "6004"
        hex_list = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
        for i in point_float:
            new_element = f'{bin(hex_list.index(i))[2:]}'
            while len(new_element) < 4:
                new_element = '0' + new_element
            final_string += new_element
    else:
        final_string = point_float
    final_string = f"{final_string[0]} {final_string[1:10]} {final_string[10]} {final_string[11:]}".split(' ')
    number = ""
    power_dict = {"0": 16, "1": 8, "2": 4, "3": 2, "4": 1}
    # print(final_string)
    for i in range(len(final_string)):
        if i == 0 and final_string[i] == "1":
            number += "-"
        elif i == 1:
            number += f"0.{final_string[1]}"
        elif i == 3:
            power = sum([power_dict[str(j)] for j in range(len(final_string[i])) if final_string[i][j] != "0"])
            if final_string[2] == "1":
                power *= -1
            number = float(number) * (10 ** power)
    print(f'二进制结果为:{number}')
    print(f"不计算二进制小数部分,10进制表示为:{int(str(int(number)), 2)}")
if mode == 2:
    point = input("请输入十进制:")
    if "-" in point:
        binary = bin(int(float(point)))[3:]
    else:
        binary = bin(int(float(point)))[2:]
    binary = binary.rstrip('0')
    if '.' in point:
        binary += '小'
    print(binary)
    if len(binary) > 9:
        print("超出位数")
    else:
        print("可以转换")


# 7.packets计算
"""
1500 28 27000000
"""
mode = int(input("模式选择 1.计算IP packets 2.计算bytes(network layer) 3.计算bytes(data layer): "))
atu = int(input("pls enter the ATU(bytes): "))
header = int(input("pls enter the header(IPV4/UDP/TCP): "))
file_size = int(input("pls enter the file size(bytes): "))
real_packets = (file_size/(atu-header))
packets = round(real_packets)
if mode == 1:
    print(f'number of packets is: {real_packets}({packets})')
elif mode == 2:
    total_bytes = (packets * header) + file_size
    print(f'the total bytes is: {total_bytes}')
elif mode == 3:
    etr_header = int(input("pls enter the header(frame checksum): "))
    real_bytes = file_size + (packets * (etr_header + header))
    print(f'the total bytes is: {real_bytes}')


# 8.switches and routers问题计算
"""
2 5
"""
mode = int(input("模式选择 1.switches and routers问题计算 2.计算有关距离延迟问题: "))
switches = int(input("pls enter switches number: "))
routers = int(input("pls enter routers number: "))
if mode == 1:
    print(f'often by the transport layer: 2')
    print(f'often by the Network layer: {2+routers}')
    print(f'often by the Link/data layer: {2 + routers*2 + switches}')
elif mode == 2:
    length = int()


# 9.查找ASCII值
"""
word_list = str("sec89ure")
d, e, j, l, y, z
"""
mode = int(input("模式选择 1.字符转为ascii 2.ascii转为字符: "))
if mode == 1:
    word_list = input("pls enter the word string(单个字母或字符串): ").replace(' ', '').replace(',', '')
    ascii_list = [ord(i) for i in word_list]
    print(f'list: {ascii_list}')
    print(f'sum of list: {sum(ascii_list)}')
elif mode == 2:
    word = int(input("pls enter the ascii(数字): "))
    print(f'result: {chr(word)}')


# 10.计算substring, prefix, suffix
"""
abc, bbb
"""
string = input("pls enter the String: ")
substring = ["lambda"]
# substring
for x in range(len(string)):
    for i in range(len(string) - x):
        substring.append(string[i:i + x + 1])
print(f"the substring list is: {sorted(list(set(substring)))}")
print(f"number of substring is: {len(list(set(substring)))}")
print(f"number of prefix is: {len(string)+1}")
print(f"number of suffix is: {len(string)+1}")
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值