Week 1

Week 1

这周我们 ed 系统上有一个 Quiz 和四个 Challenges。

[TOC]

Quiz 1

这个 Quiz 写好了输入输出的代码,让你补充其中对于其 mapping 相关一些操作的运算和判断过程。

题目要求

See pdf and stub.

0.5 mark for print statement

0.5 mark for list of integers that are not keys of the mapping

0.5 mark for mapping as a list

1 mark for one-to-one part of the mapping

然后 pdf 文档中给出了 test cases 和希望的输出结果。限于篇幅,这里我只放其中一个。详情请见 Quiz 1 要求 -- OneDrive 分享

在 shell 中输入:

(根据个人习惯,shell 可以为 terminal、iterm、powershell等。在 unix (MacOS included) 和 linux 下,个人推荐直接用 terminal(终端)就很好了)

$ python3 quiz_1.py
Enter two integers: 0 8

期望得到的输出:

The generated mapping is:
{2: 4, 3: 8, 4: 7, 5: 7}

The mappings's so-called "keys" make up a set whose number of elements is 4.

The list of integers between 1 and 8 that are not keys of the mapping is:
[1, 6, 7, 8]

Represented as a list, the mapping is:
[None, None, 4, 8, 7, 7, None, None, None]

The one-to-one part of the mapping is:
{2: 4, 3: 8}

你需要做

  • 数一下 keys of mapping 有几个。
  • 列出非 keys of mapping 的数。
  • 将 mapping 列表输出,其中没有 mapping 的用 None 填充。
  • 寻找唯一的 mapping 并输出。

代码实现

(by Harriet and Eric Martin, All Right Reserved)

Anyone who is plagiarisming, which include copying, Inappropriate paraphrasing, Collusion, Inappropriate citation, Self-plagiarism will undermine academic integrity and is not tolerated at UNSW.

# Written by Harriet and Eric Martin for COMP9021

import sys
from random import seed, randrange

try:
    arg_for_seed, upper_bound = (abs(int(x)) + 1 for x in input('Enter two integers: ').split())
except ValueError:
    print('Incorrect input, giving up.')
    sys.exit()

seed(arg_for_seed)
mapping = {}
num_map = 0

# Generate Mapping
for i in range(1, upper_bound):
    r = randrange(-upper_bound // 2, upper_bound)
    if r > 0:
        mapping[i] = r;
        num_map += 1;
print('\nThe generated mapping is:')
print('  ', mapping)

mapping_as_a_list = []
one_to_one_part_of_mapping = {}
nonkeys = []

# Calculate the value of keys

for i in range (1, upper_bound):
    if i not in mapping.keys():
        nonkeys.append (i);

# Generate mapping as a list
for i in range (0, upper_bound):
    if i in mapping:
        mapping_as_a_list.append(mapping[i]);
    else:
        mapping_as_a_list.append(None);

# Generate one by one mapping
mapping_value = []
for key, value in mapping.items():
    mapping_value.append(value);
    num_mpvl = 0;
    for key_another, value_another in mapping.items():
        if value == value_another:
            num_mpvl += 1;
    # Only output values that its number of mapping values equals to 1
    if num_mpvl == 1:
        one_to_one_part_of_mapping[key] = value;

# Output
print()
print(f'The mappings\'s so-called "keys" make up a set whose number of elements is {num_map}.');
print('\nThe list of integers between 1 and', upper_bound - 1, 'that are not keys of the mapping is:')
print('  ', nonkeys)
print('\nRepresented as a list, the mapping is:')
print('  ', mapping_as_a_list)
# Recreating the dictionary, inserting keys from smallest to largest,
# to make sure the dictionary is printed out with keys from smallest to largest. 
one_to_one_part_of_mapping = {key: one_to_one_part_of_mapping[key]
for key in sorted(one_to_one_part_of_mapping)
    }
print('\nThe one-to-one part of the mapping is:')
print('  ', one_to_one_part_of_mapping)


Challenge 1: Temperature conversion tables

题目要求

Study the program fahrenheit_to_celsius.py and run it in the Terminal window, executing "python3 fahrenheit_to_celsius.py". Then complete the program celsius_to_fahrenheit.py that displays a conversion table from Celsius degrees to Fahrenheit degrees, with the former ranging from 0 to 100 in steps of 10; run it and check your solution with the Run and Submit buttons, respectively.

See commands_and_expected_outputs.txt for expected output.

其中提到的两个文件:

  1. fahrenheit_to_celsius.py
# Written by Eric Martin for COMP9021

'''
Prints out a conversion table of temperatures from Fahrenheit to Celsius degrees,
with the former ranging from 0 to 300 in steps of 20.
'''

min_temperature = 0
max_temperature = 300
step = 20
# \t: A tab
print('Fahrenheit\tCelsius')
# We let fahrenheit take the values
# - min_temperature
# - min_temperature + step
# - min_temperature + 2 * step
# - min_temperature + 3 * step
# ...
# up to the largest value smaller than max_temperature + step
for fahrenheit in range(min_temperature, max_temperature + step, step):
    celsius = 5 * (fahrenheit - 32) / 9
    # {:10d} or {:10}:  fahrenheit as a decimal number in a field of width 10
    # {:7.1f}: celsius as a floating point number in a field of width 7
    #          with 1 digit after the decimal point
    print(f'{celsius:10}\t{fahrenheit:7.1f}')
  1. commands_and_expected_outputs.txt
TEST 1 BEGIN
$ python3 celsius_to_fahrenheit.py�
Celsius Fahrenheit
      0         32
     10         50
     20         68
     30         86
     40        104
     50        122
     60        140
     70        158
     80        176
     90        194
    100        212
TEST 1 END

直接在 shell 中运行第一个文件 "fahrenheit_to_celsius.py" 的结果是:

$ python3 fahrenheit_to_celsius.py 
Fahrenheit  Celsius
         0    -17.8
        20     -6.7
        40      4.4
        60     15.6
        80     26.7
       100     37.8
       120     48.9
       140     60.0
       160     71.1
       180     82.2
       200     93.3
       220    104.4
       240    115.6
       260    126.7
       280    137.8
       300    148.9

你需要做

  • 研究老师给的 "fahrenheit_to_celsius.py" 如何输出华氏度到摄氏度的转换表
  • 写一个 "celsius_to_fahrenheit.py" 逆向输出摄氏度到华氏度的转换表

代码实现

(by Harriet and Eric Martin, All Right Reserved)

Anyone who is plagiarisming, which include copying, Inappropriate paraphrasing, Collusion, Inappropriate citation, Self-plagiarism will undermine academic integrity and is not tolerated at UNSW.

'''
Prints out a conversion table of temperatures from Celsius to Fahrenheit degrees,
the former ranging from 0 to 100 in steps of 10.
'''
# Written by Harriet for COMP9021

min_temperature = 0
max_temperature = 100
step = 10
print('Celsius\tFahrenheit')
for celsius in range(min_temperature, max_temperature + step, step):
    fahreheit = 9 * celsius / 5 + 32;
    fahreheit = int(fahreheit);
    print(f'{celsius:7d}\t{fahreheit:10d}');

Challenge 2: Max element and span in a list

题目要求

Study the program max_in_list.py and run it in the Terminal window, executing "python3 max_in_list.py". Then complete the program span.py that prompts the user for a seed for the random number generator, and for a strictly positive number, nb_of_elements, generates a list of nb_of_elements random integers between 0 and 99, prints out the list, computes the difference between the largest and smallest values in the list without using the builtins min() and max(), prints it out, and check that the result is correct using the builtins; run it and check your solution with the Run and Submit buttons, respectively.

See commands_and_expected_outputs.txt for expected outputs and sample inputs.

你需要做

代码实现

(by Harriet and Eric Martin, All Right Reserved)

Anyone who is plagiarisming, which include copying, Inappropriate paraphrasing, Collusion, Inappropriate citation, Self-plagiarism will undermine academic integrity and is not tolerated at UNSW.

# Written by Harriet for COMP9021

'''
Prompts the user for a seed for the random number generator,
and for a strictly positive number, nb_of_elements.
Generates a list of nb_of_elements random integers between 0 and 99, prints out the list,
computes the difference between the largest and smallest values in the list without using
the builtins min() and max(), prints it out, and check that the result is correct using
the builtins.
'''

from random import seed, randint
import sys
try:
    arg_for_seed = int(input('Input a seed for the random number generator: '))
except ValueError:
    print('Input is not an integer, giving up.')
    sys.exit()   
try:
    nb_of_elements = int(input('How many elements do you want to generate? '))
except ValueError:
    print('Input is not an integer, giving up.')
    sys.exit()
if nb_of_elements <= 0:
    print('Input should be strictly positive, giving up.')
    sys.exit()
seed(arg_for_seed)
L = [randint(0, 99) for _ in range(nb_of_elements)]
print('\nThe list is:', L)
max_element = 0
min_element = 99
for e in L:
    if e > max_element:
        max_element = e
    if e < min_element:
        min_element = e
print('\nThe maximum difference between largest and smallest values in this list is:', max_element-min_element)
print('Confirming with builtin operations:', max(L)-min(L))

Challenge 3: Classifying elements in a list

题目要求

The operators /, // and % are used for floating point division, integer division, and remainder, respectively. Study the program modulo_4.py and run it in the Terminal window, executing "python3 modulo_4.py". Then complete program intervals.py that prompts the user for a strictly positive integer, nb_of_elements, generates a list of nb_of_elements random integers between 0 and 19, prints out the list, computes the number of elements strictly less than 5, 10, 15 and 20, and prints those out; run it and check your solution with the Run and Submit buttons, respectively.

See commands_and_expected_outputs.txt for expected outputs and sample inputs.

你需要做

代码实现

(by Harriet and Eric Martin, All Right Reserved)

Anyone who is plagiarisming, which include copying, Inappropriate paraphrasing, Collusion, Inappropriate citation, Self-plagiarism will undermine academic integrity and is not tolerated at UNSW.


Challenge 4: Statistics on numbers in a list

题目要求

Complete the program mean_median_standard_deviation.py that prompts the user for a strictly positive integer, nb_of_elements, generates a list of nb_of_elements random integers between - 50 and 50, prints out the list, computes the mean, the median and the standard deviation in two ways, that is, using or not the functions from the statistics module, and prints them out.

To compute the median, the easiest way is to first sort the list with the builtin sort() method.

See commands_and_expected_outputs.txt for expected outputs and sample inputs.

你需要做

代码实现

(by Harriet and Eric Martin, All Right Reserved)

Anyone who is plagiarisming, which include copying, Inappropriate paraphrasing, Collusion, Inappropriate citation, Self-plagiarism will undermine academic integrity and is not tolerated at UNSW.

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