UNSW COMP9021 2019T2

Week 2

2019-06-24  本文已影响0人  璇冰酱是个麻瓜

Week 2

这周我们 ed 系统上有1个 Quiz 和5个 Challenges。

[TOC]

Quiz 2

这个 Quiz 依旧写好了输入输出的代码。

题目要求

See pdf and stub.

1.5 mark for cycles

1 mark for reversed dictionary

依旧,pdf 文档中给出了 test cases 和希望的输出结果。详情请见 Quiz 2 要求 -- OneDrive 分享

在 shell 中输入:

$ python3 quiz_2.py
Enter two integers: 20 11

期望得到的输出:

The generated mapping is:
   {2: 4, 3: 9, 4: 4, 5: 8, 6: 2, 7: 5, 8: 11, 9: 1, 10: 10, 11: 5}

The keys are, from smallest to largest: 
   [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Properly ordered, the cycles given by the mapping are: 
   [[4], [5, 8, 11], [10]]

The (triply ordered) reversed dictionary per lengths is: 
{1: {1: [9], 2: [6], 8: [5], 9: [3], 10: [10], 11: [8]},
 2: {4: [2, 4], 5: [7, 11]}}

你需要做

代码实现

(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
from pprint import pprint

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 = {}
for i in range(1, upper_bound):
    r = randrange(-upper_bound // 8, upper_bound)
    if r > 0:
        mapping[i] = r
print('\nThe generated mapping is:')
print('  ', mapping)
# sorted() can take as argument a list, a dictionary, a set...
keys = sorted(mapping.keys())
print('\nThe keys are, from smallest to largest: ')
print('  ', keys)

cycles = []
reversed_dict_per_length = {}

# INSERT YOUR CODE HERE

#############################################################################
# Section 1
# This section is for cycles
#############################################################################
used_in_cycle = []

# Loop and try all elements in `mapping`
for i in keys:
    tracking = i
    used = []
    flag = 0
    used.append(i)
    # If is a same cycle listed before, then jump to next `i`
    # If not, do other things.
    if i in used_in_cycle:
        continue
    else:
        # Loop for cycles
        while 1:
            # If tracking can not move to next loop, 
            # this is not a cycle
            # Record this in `flag` as wrong and break the while loop
            if mapping[tracking] not in mapping:
                flag = 0
                break

            # Move to next tracking
            tracking = mapping[tracking]

            # Getting into a wrong cycle
            # Record this in `flag` as wrong and break while loop
            if (tracking in used) and (tracking != i):
                flag = 0
                break

            # If tracking equals to the original number `i`,
            # this is a cycle.
            # Record this in `flag` and break while loop
            if tracking == i:
                flag = 1
                break

            # If not correct and not recorded in used
            # Record this `used` and continue finding
            used.append(tracking)

        # Check if this i is a correct valur for cycle
        # If true, then append this in cycle
        if flag:
            cycles.append(used)

            # And record all elements in this cycle 
            # into `used_in_cycle`.
            # This is for avoiding outputing a same cycle
            # for multiplied times.
            for j in used:
                if j not in used_in_cycle:
                    used_in_cycle.append(j)
        else:
            continue

#############################################################################
# Section 2
# This section is for reversed dictionary.
#############################################################################

value_key = {}
value_count = {}

# Take out the `keys` and `values` in original `mapping`.
# Then put `values:keys` into value_key
# also do counting for each `value` in original `mapping`.

for j, i in mapping.items():
        # If this is a key-value pair in mapping
        if mapping[j] == i:
            # Also, if this value is a new value
            if i not in value_key.keys():
                value_key[i] = []
                value_key[i].append(j)
                value_count[i] = []
                value_count[i] = 1
            # if this value has appeared as `value_key.keys()`
            else:
                value_key[i].append(j)
                value_count[i] += 1

# Collect all `values:keys` with same `value_count` 
# into a same `value_count:{values:keys}`

# List all counting values in sorted way.
counting_used = sorted(value_count.values())

# Take out all values and its countings
for i, j in value_count.items():
    # If this counting has not been appeared in `reversed_dict_per_length`
    # Then we should add a new element.
    if (value_count[i] == j) and (j not in reversed_dict_per_length.keys()):
        reversed_dict_per_length[j] = {}
    # In final result `reversed_dict_per_length`, for counting `j`,
    # The `i`th subelement should be `value_key[i]`
    reversed_dict_per_length[j][i] = value_key[i]

print('\nProperly ordered, the cycles given by the mapping are: ')
print('  ', cycles)
print('\nThe (triply ordered) reversed dictionary per lengths is: ')
pprint(reversed_dict_per_length)
上一篇下一篇

猜你喜欢

热点阅读