COMP9021 Principles of Programmi

2017-08-23  本文已影响0人  Sisyphus235

1. Q1

Write a program characters_triangle.py that gets a strictly positive integer N as input and outputs a triangle of height N, following this kind of interaction:

Q1
def running_time(f):
    def g(*args):      
        from time import time
        before = time()
        f(*args)
        after = time()
        print(f'It took {after - before} seconds to execute the function.')
    return g

while True:
    try:
        N = int(input('Enter strictly positive number: '))
        if N < 1:
            raise ValueError
        break
    except ValueError:
        print('The input is illegal. Please input again.')

array = [[0] * (N * 2 - 1) for _ in range(N)]
#根据输入的N创建所有element为0的矩阵

@running_time
def characters_triangle(N):
    center = N - 1
    #所有row的center不变
    array[0][center] = 65
    #初始化第一行的center值,是字母A的ord值
    if N != 1:
        for i in range(1, N):
            last_center = array[i - 1][center]
            array[i][center] = last_center + i + 1
            #新一行的中心值等于上一行的中心值 + 行号 + 1
            end = array[i][center] - 1
            #从中心值向两侧赋值
            move = 1
            #每次移动1位
            while end > last_center:
            #移动到ord值刚好比上一行中心值大1为止
                array[i][center - move] = end
                array[i][center + move] = end
                #中心值两侧对称赋值
                end -= 1
                move += 1
            for j in range(2 * N - 1):
            #如果有element的值大于90(Z的ord值),则减去26,重新回到A-Z的ord范围中
                while array[i][j] > 90:
                #注意要使用循环减去26,一旦N很大,可能超出多个26
                    array[i][j] -= 26
    return array

def print_characters():
    for i in range(N):
        for j in range(2 * N - 1):
            if array[i][j] == 0:
                print(' ', end = '')
            else:
                print(chr(array[i][j]), end = '')
        print()

        
characters_triangle(N)  
print_characters()

2. Q2

Write a program pascal_triangle.py that prompts the user for a number N and prints out the first N + 1 lines of Pascal triangle, making sure the numbers are nicely aligned, following this kind of interaction.

Q2
def running_time(f):
    def g(*args):      
        from time import time
        before = time()
        f(*args)
        after = time()
        print(f'It took {after - before} seconds to execute the function.')
    return g

while True:
    try:
        N = int(input('Enter a nonnegative integer: '))
        if N < 0:
            raise ValueError
        break
    except ValueError:
        print('The input is illegal. Please input again.')

array = [[0] * (N * 2 + 3) for _ in range(N + 1)]
#根据输入的N创建所有element为0的矩阵,在原矩阵两侧各加一列0,便于boundary计算

array[0][N + 1] = 1
#确定初始值,第一行中间值为1
@running_time
def pascal():
    if N > 0:
        for i in range(1, N + 1):
            for j in range(1, N * 2 + 2):
                array[i][j] = array[i - 1][j - 1] + array[i - 1][j + 1]
                #新的一行每个元素等于上一行左上和右上两个数字的加和        

def print_characters():
    space = len(str(max(array[-1])))
    #为了保持输出格式,确定最长数字的长度
    for i in range(N + 1):
        for j in range(1, 2 * N + 3):
            e = array[i][j]
            if e == 0:
                print(' ' * space, sep = '', end = '')
            else:
                print(' ' * (space - len(str(e))), e, sep = '', end = '')
        print()

pascal()
print_characters()

3. Q3

Write a program plane_encoding.py that implements a function encode(a, b) and a function decode(n) for the one-to-one mapping from the set of pairs of integers onto the set of natural numbers, that can be graphically described as follows:

Q3
def encode(x, y):
#每一层x开始的数都是(level * 2 - 1) ** 2,坐标都是[level, 1 - level]
#再根据x, y坐标的情况判断处于该层正方形不同边上位置的数字是多少
    level = max(abs(x), abs(y))
    start = (level * 2 - 1) ** 2
    start_position = [level, 1 - level]
    if x == level and y != -level:
    #该层正方形右边
        return start + (y - start_position[1])
    elif y == level:
    #该层正方形上边
        return start + (2 * level - 1) + (level - x)
    elif x == -level:
    #该层正方形左边
        return start + (2 * level - 1) + (2 * level) + (level - y)
    elif y == -level:
    #该层正方形下边
        return start + (2 * level - 1) + (2 * level) + (2 * level) + (x + level)

def decode(n):
    if n == 0:
        return (0, 0)
    level = 1
    while (2 * level - 1) ** 2 <= n: 
        level += 1
    level -= 1
    start = (level * 2 - 1) ** 2
    start_position = [level, 1 - level]

    if n <= (start + level * 2 - 1):
    #该层正方形右边
        return (level, n - start + start_position[1])
    elif n <= (start + level * 2 - 1) + level * 2:
    #该层正方形上边    
        return (level - (n - (start + 2 * level - 1)), level)
    elif n <= (start + level * 2 - 1) + level * 2 + level * 2:
    #该层正方形左边  
        return (-level, level - (n - (start + 2 * level - 1 + 2 * level)))
    else:
        return (-level + (n - (start + 2 * level - 1 + 2 * level + 2 * level)), -level)

4. Q4

Given a positive integer n, a magic square of order n is a matrix of size n×n that stores all numbers from1 up to n2 and such that the sum of the n rows, the sum of the n columns, and the sum of the two diagonals is constant, hence equal to n(n2 + 1)/2. The function print_square(square) prints a list of lists that represents a square, and the function is_magic_square(square) checks whether a list of lists is a magic square. For instance:

def print_square(square):
    length = len(str(max(max(square))))
    for row in square:
        for i in range(len(row)):
            if i < len(row) - 1:
                print(' ' * (length - len(str(row[i]))), row[i], end = ' ')
            else:
                print(' ' * (length - len(str(row[i]))), row[i])

def is_magic_square(square):
    n = len(square)
    total = int(n * (n ** 2 + 1) / 2)
    for row in square:
        if sum(row) != total:
            return False
    #每一行的和是否成立
    total_column = [0] * n
    total_diagnal = [0] * 2
    for i in range(n):
        for j in range(n):
            total_column[j] += square[i][j]
            #每一列的和
            if i == j:
                total_diagnal[0] += square[i][j]
                #左上右下对角线的和
            if i + j == n - 1:
                total_diagnal[1] += square[i][j]
                #左下右上对角线的和
    for e in total_column:
        if e != total:
            return False
    for e in total_diagnal:
        if e!= total:
            return False
    return True
上一篇下一篇

猜你喜欢

热点阅读