COMP9021 Principles of Programming Midterm exam 16s2

0 做题感受

mid-term的题目本身复杂度适中,在读题的时候建议结合例子理解,许多题目过于复杂,难以用英语的从句限定完全理解。注意:
(1)list的排序
(2)print的输出要使用%format格式,而不能使用f{}format格式
(3)及时test,不要一次性写很多逻辑
(4)python自带的IDLE没有自动补全代码的功能,coding时variable name建议尽量简单,如果过长,尽量复制黏贴,而不是每次手打
(5)虽然Eric之前课程材料中有非常多excellent的解题逻辑,可是如果无法完全掌握,在限时考试中还是建议用自己的逻辑
(6)coding时优先完成task,而不要想太多代码优化的问题

1 Longest sequence of deficient numbers

A number is said to be deficient if the sum of its proper divisors is strictly smaller than itself. For instance, the proper divisors of 10 are 1, 2 and 5, which add up to 8, which is strictly smaller than 10, hence 10 is deficient, whereas the proper divisors of 12 are 1, 2, 3, 4 and 6, which add up to 16, which is greater than or equal to 12, hence 12 is not deficient. Here is the list of all deficient numbers up to 50:
1,2,3,4,5,7,8,9,10,11,13,14,15,16,17,19,21,22,23,25,26,27,29,31,32,33,34,35,37,38,39,41,43,44,45,46,47,49,50
Write a program that prompts the user to input two strictly positive integers a and b and finds out the range of the longest sequence of deficient numbers between a and b. When that sequence is not unique, the range should be that of the sequence closest to a. If a is smaller than b then that sequence is increasing, whereas if a is greater than b then that sequence is decreasing.
Here is a typical interaction:

$ python3 deficient.py
Enter two strictly positive numbers: 10 twenty
Incorrect input, giving up.
$ python3 deficient.py
Enter two strictly positive numbers: 10 20 30
Incorrect input, giving up.
$ python3 deficient.py
Enter two strictly positive numbers: 0 10
Incorrect input, giving up.
$ python3 deficient.py
Enter two strictly positive numbers: 10 10
The longest sequence of deficient numbers between 10 and 10 ranges between 10 and 10.
$ python3 deficient.py
Enter two strictly positive numbers: 12 12
There is no deficient number between 12 and 12.
$ python3 deficient.py
Enter two strictly positive numbers: 10 20
The longest sequence of deficient numbers between 10 and 20 ranges between 13 and 17.
$ python3 deficient.py
Enter two strictly positive numbers: 20 10
The longest sequence of deficient numbers between 20 and 10 ranges between 17 and 13.
$ python3 deficient.py
Enter two strictly positive numbers: 3 20
The longest sequence of deficient numbers between 3 and 20 ranges between 7 and 11.
$ python3 deficient.py
Enter two strictly positive numbers: 20 3
The longest sequence of deficient numbers between 20 and 3 ranges between 17 and 13.

解答:

import sys

try:
    temp = input("Enter two strictly positive numbers: ").split()
    if len(temp) != 2:
        raise ValueError
    a, b = int(temp[0]), int(temp[1])
    if a <= 0 or b <= 0:
        raise ValueError
except ValueError:
    print("Incorrect input, giving up.")
    sys.exit()

def deficient(n):
    if n == 1:
        return True
    total = 1
    for i in range(2, n):
        if n % i == 0:
            total += i
    if total < n:
        return True
    else:
        return False

def longest_deficient(m, n):
    sequence = []
    flag = 0
    if m > n:
        flag = 1
        m, n = n, m
    for i in range(m, n + 1):
        if deficient(i):
            start, end = i, i
            for j in range(i + 1, n + 1):
                if deficient(j):
                    end = j
                else:
                    break
            sequence.append((start, end, end - start))
    if flag == 1:
        sequence.sort(key = lambda x: (-x[2], -x[1]))
    else:
        sequence.sort(key = lambda x: (-x[2], x[0]))
    return sequence[0]
    
result = longest_deficient(a, b)
start, end = result[0], result[1]
if a > b:
    start, end = end, start

print("The longest sequence of deficient numbers between %d and %d ranges between %d and %d." % (a, b, start, end))

2 Solving a multiplication

Write a program that solves a multiplication
OEE
x EE
-----
EOEE
EOE
-------
OOEE

where E stands for an even digit and O stands for an odd digit. Of course the leading digit of any of the 5 numbers cannot be 0. Two occurrences of E can refer to the same even digit or to two distinct even digits, and two occurrences of O can refer to the same odd digit or to two distinct odd digits.
The output of your program should be of the form above, with of course the Es and the Os being replaced by appropriate digits. Still spaces are irrelevant; in particular, it is irrelevant whether digits are separated by spaces, whether x (the multiplication sign) is followed by spaces, whether there are leading spaces at the beginning of the last line. The number of - on the separating lines is also irrelevant.
Your program should not make any assumption on the actual solution (which is unique), except obvious ones on the ranges of some values.
解答:

odd = [1, 3, 5, 7, 9]
even = [0, 2, 4, 6, 8]

for i in range(100, 1000):
    if (i % 10) not in even:
        continue
    if (i // 10 % 10) not in even:
        continue
    if (i // 100) not in odd:
        continue
    for j in range(10, 100):
        if (j % 10) not in even:
            continue
        if (j // 10) not in even:
            continue
        
        middle_1 = i * (j % 10)
        if len(str(middle_1)) != 4:
            continue
        if (middle_1 % 10) not in even:
            continue
        if (middle_1 //10 % 10) not in even:
            continue
        if (middle_1 //100 % 10) not in odd:
            continue
        if (middle_1 //1000) not in even:
            continue

        middle_2 = i * (j // 10)
        if len(str(middle_2)) != 3:
            continue
        if (middle_2 % 10) not in even:
            continue
        if (middle_2 // 10 % 10) not in odd:
            continue
        if (middle_2 // 100) not in even:
            continue

        result = i * j
        if len(str(result)) != 4:
            continue
        if (result % 10) not in even:
            continue
        if (result // 10 % 10) not in even:
            continue
        if (result // 100 % 10) not in odd:
            continue
        if (result // 1000) not in odd:
            continue

        print(' ', str(i), sep = '')
        print('x ', str(j), sep = '')
        print('----')
        print(str(middle_1))
        print(str(middle_2), ' ', sep = '')
        print('----')
        print(str(result))

3 Decoding a number

Write a program that implements a function named decode, called as decode(base, number) where base is any number b between 1 and 9, and number is any nonnegative integer n, seen as encoding a set S of nonnegative integers such that for all nonnegative integers i, i belongs to S i the ith digit of n written in base b is not equal to 0 (counting the digits from 0 and starting from the right). For instance, in base 3, 586 reads as 210201 because
586=2*3^5 +1*3^4 +0*3^3 +2*3^2 +0*3^1 +1*3^0
and so, with base equal to 3, 586 encodes {5, 4, 2, 0}.
解答:

def max_power(base, number):
    max_power = 0
    while (base ** max_power) <= number:
        max_power += 1
    if max_power != 0:
        max_power -= 1
    return max_power

def decode(base, number):
    upper = max_power(base, number)
    candidate = [0] * (upper) + [upper]
    number -= (number // (base ** upper)) * (base ** upper)

    while number != 0:
        power = max_power(base, number)
        a = base ** power
        b = number // a
        candidate[power] = power
        if power == 0:
            candidate[0] = -1
        number -= a * b

    code = []
    for i in candidate:
        if i == -1:
            code.append(0)       
        if i != 0 and i != -1:
            code.append(i)
    code.sort(reverse= True)

    if not code:
        print('{}')
    else:
        print('{', sep = '', end = '')
        for j in range(len(code)):
            if j == len(code) - 1:
                print(code[j], '}', sep = '', end = '')
            else:
                print(code[j], ', ', sep= '', end = '')
        print()

decode(2, 11)
decode(3, 586)
decode(8, 4223296)
decode(9, 0)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,125评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,293评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,054评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,077评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,096评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,062评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,988评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,817评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,266评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,486评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,646评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,375评论 5 342
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,974评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,621评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,796评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,642评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,538评论 2 352

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,467评论 0 23
  • 我的爱情观就是共同进步,相信彼此,并且为了彼此一起变得优秀,我不是要成为某个人的妻子或者某个小孩子的母亲,而是成为...
    mywaycover阅读 336评论 1 0
  • 文 | 水清心宁 我不是一个擅长写字的人。不是谦虚,更非矫情。 记忆中读书时作文从没有被老师表扬过。后来教书时,参...
    水清心宁阅读 3,174评论 67 118
  • 不知道为什么突然去成都。做决定到买票也只有五分钟的时间,反正也不想跟人商量去处不是么。 大概是想着把存款花光就能安...
    取一个帅气的昵称呵阅读 177评论 0 0
  • 突然想起一句话,这城市所有的喧嚣都与你无关,而你已经习惯于这喧嚣。 踏着夜色下了公车,没有月光竟然也没有星星,能感...
    凉风一梦是归途阅读 452评论 0 0