代做CSC 108 H1F Final Examination December 2018代做Python程序

DECEMBER 2018 EXAMINATIONS

CSC 108 H1F

Question 1. [6 marks]

Part 1: Select the option on the right that best describes what happens when the code on the left is run.

L = [1, 1, 2, 2, 3, 4]

for item in L:

if item % 2 == 1:

item = item + 1

print(L)

(A) [1, 1, 2, 2, 3, 4] is printed

(B) [2, 2, 2, 2, 4, 4] is printed

(C) A different list is printed

(D) An error occurs when the code is run

Part 2: Select the option on the right that best describes what happens when the code on the left is run.

L=['cat', 5, 'dog', 4]

f = open('output.txt', 'w')

for item in L:

f.write(str(item))

f.close()

f = open('output.txt', 'r')

print(f.readlines())

f.close()

(A) ['cat\n', '5\n', 'dog\n', '4\n'] is printed

(B) ['cat, '5', 'dog', '4'] is printed

(C) ['cat5dog4'] is printed

(D) A different list is printed

(E) An error occurs when the code is run

Part 3: Select the option on the right that best describes what happens when the code on the left is run.

s = 'big orange cats are best'

result = False

for each in s.split():

if each == 'cats':

result = True

else:

result = False

if result:

print('cats found')

else:

print('no cats found')

(A) cats found is printed

(B) no cats found is printed

(C) Something else is printed

(D) An error occurs when the code is run

Part 4: Select the option below that best describes what happens when this code is run.

shoes = ['Saucony', 'Asics', 'Asics', 'NB', 'Saucony', 'Nike', 'Asics', 'Adidas', 'Saucony', 'Asics']

shoes_to_places = {}

for i in range(len(shoes)):

shoes_to_places[shoes[i]].append(i + 1)

print(shoes_to_places)

(A) {'Saucony': [1, 5, 9], 'Asics': [2, 3, 7, 10], 'NB': [4], 'Nike': [6], 'Adidas': [8]} is printed

(B) {'Saucony': [0, 4, 8], 'Asics': [1, 2, 6, 9], 'NB': [3], 'Nike': [5], 'Adidas': [7]} is printed

(C) {'Saucony': [9], 'Asics': [10], 'NB': [4], 'Nike': [6], 'Adidas': [8]} is printed

(D) {'Saucony': [1], 'Asics': [2], 'NB': [4], 'Nike': [6], 'Adidas': [8]} is printed

(E) Something else is printed

(F) An error occurs when the code is run

Part 5:

Consider the following code.

D={'cat': 5}

x = VALUE1

D[x] = VALUE2

Circle ALL of the options below that could used be in place of VALUE1 so the code would run without error.

(A) 'dog'

(B) 'cat'

(C) x

(D) ['a', 'b']

(E) ('a', 'b')

(F) {'a': 'b'}

(G) D['cat']

(H) None of the above

Circle ALL of the options below that could used be in place of VALUE2 so the code would run without error.

(A) 'dog'

(B) 'cat'

(C) x

(D) ['a', 'b']

(E) ('a', 'b')

(F) {'a': 'b'}

(G) D['cat']

(H) None of the above

Question 2. [6 marks]

A board is a list of lists of length 1 strings, where each inner list has the same length. Precondition for all three functions below: the first parameter represents a board with at least one row and column.

Part (a) [1 mark] Complete the following function according to its docstring.

def get_row(board: List[List[str]], row_num: int) -> List[str]:

"""Return row row_num of board.

>>> b = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

>>> get_row(b, 0)

['a', 'b', 'c']

>>> get_row(b, 2)

['g', 'h', 'i']

"""

Part (b) [2 marks] Complete the following function according to its docstring.

def get_column(board: List[List[str]], column_num: int) -> List[str]:

"""Return column column_num of board.

>>> b = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

>>> get_column(b, 0)

['a', 'd', 'g']

>>> get_column(b, 2)

['c', 'f', 'i']

"""

Part (c) [3 marks] Complete the following function according to its docstring. Call at least one of the functions from Part (a) or Part (b) as a helper function.

def get_rotated_board(original: List[List[str]]) -> List[List[str]]:

"""Return a new board that is the same as board original but with its rows and columns swapped.

(Row 0 is swapped with column 0, row 1 is swapped with column 1, and so on.)

>>> b = [['a', 'a', 'a', 'a'], ['b', 'b', 'b', 'b'], ['c', 'c', 'c', 'c']]

>>> get_rotated_board(b)

[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

"""

Question 3. [5 marks]

A palindrome is a string that is read the same from front-to-back and back-to-front. For example, noon and racecar are both palindromes.

There are several ways to check whether a string is a palindrome. One algorithm compares the first letter to the last letter, the second letter to the second last letter, and so on, stopping when the middle of the string is reached or when a mismatch is found.

Part (a) [3 marks] Complete the function below using the algorithm described above. Do not modify code that is given outside of a box and do not add code outside of a box.

def is_palindrome(s: str) -> bool:

"""Return True if and only if s is a palindrome.

>>> is_palindrome('noon')

True

>>> is_palindrome('racecar')

True

>>> is_palindrome('dented')

False

"""

i=0

# In the box below, declare any additional variable(s), if needed

# In the box below, write the while loop condition

while                   :

# In the box below, write the while loop body

return i == len(s) // 2

Part (b) [1 mark] For a string s of length n, where n is divisible by 2, how many times will the while loop in is_palindrome iterate in the worst case?

Part (c) [1 mark] Circle the term below that best describes the worst case running time of the is_palindrome function.

constant                               linear                            quadratic                        something else

Question 4. [6 marks]

Complete the function below to according to its docstring.

def update_messages(msgs: List[str], lens: List[int]) -> None:

"""Update the list of the strings in msgs so their lengths are adjusted to

match the value at the corresponding position in lens. Strings that are too

long should be shortened by leaving off characters at the end and strings

that are too short should be lengthened by adding underscores to the end.

Precondition: len(msgs) == len(lens) and all values in lens are >= 0

>>> messages = ['aardvark', 'bear', 'cat', 'dog']

>>> update_messages(messages, [6, 5, 5, 3])

>>> messages

['aardva', 'bear_', 'cat__', 'dog']

>>> messages = ['', 'cat']

>>> update_messages(messages, [3, 0])

>>> messages

['___', '']

"""

Question 5. [6 marks]

Each of the functions below has a correct docstring, but one or more bugs in the code. In the table below each function, write two test cases. The first test case should not indicate a bug in the function (the test case would pass), while the second test case should indicate a bug (the test case would fail or an error would occur). If the code would stop due to an error on the second test case, write ‘Error’ in the Actual Return Value column for that test. Both test cases should pass on a correct implementation of the function.

def find_a_digit(s: str) -> int:

"""Return the index of the first digit in s, or the length of s if there are no digits.

"""

i=0

while not s[i].isdigit():

i=i+1

return i

Argument for s                         Actual Return Value                     Expected Return Value

Does not indicate bug (pass)

Indicates bug (fail/error)

def has_a_fluffy(s: str) -> bool:

"""Return True if and only if s contains at least one character that is in 'fluffy'.

"""

for ch in s:

if ch in 'fluffy':

return True

else:

return False

Argument for s                      Actual Return Value                   Expected Return Value

Does not indicate bug (pass)

Indicates bug (fail/error)

def get_year_of_study(num_credits: float) -> int:

"""Return the year of study at UofT given the number of credits num_credits, using these rules:

14.0 credits or more 4th year

9.0 to 13.5 credits 3rd year

4.0 to 8.5 credits 2nd year

< 4.0 credits 1st year

"""

if num_credits >= 4.0:

return 2

elif num_credits >= 9.0:

return 3

elif num_credits < 4.0:

return 1

else:

return 4

Argument for num_credits                  Actual Return Value                 Expected Return Value

Does not indicate bug (pass)

Indicates bug (fail/error)

Question 6. [6 marks]

Consider this function:

def mystery(s: str) -> str:

""" """

i=0

result = ''

while i < len(s) and not s[i] == '.':

result = result + s[i]

i=i+1

return result

Part (a) [1 mark]

Give an example of an argument of length 4 that would produce the best case behaviour of this function.

Part (b) [1 mark]

How many assignment statements would be executed on one call to this function with an argument of length 4 that produces the best case?

Part (c) [1 mark]

Circle the term below that best describes the best case running time of this function on a length n string.

constant                 linear               quadratic                  something else

Part (d) [1 mark]

Give an example of an argument of length 4 that would produce the worst case behaviour of this function.

Part (e) [1 mark]

How many assignment statements would be executed on one call to this function with an argument of length 4 that produces the worst case?

Part (f) [1 mark]

Circle the term below that best describes the worst case running time of this function on a length n string.

constant                     linear                          quadratic                         something else

Question 7. [12 marks]

Emotion analysis categorizes text as positive, negative, or neutral. For example, an emotion analysis program might categorize the text "happy birthday" as positive, and the text "it was disastrous" as negative.

Part (a) [4 marks]

Words are scored from -5 (most negative) to 5 (most positive). Word scoring data is stored in a comma separated values (CSV) file with a word, followed by its score, on each line.

Here is an example word scoring CSV file:

amazing,4

happy,3

anxious,-2

disastrous,-3

awesome,4

outstanding,5

woohoo,3

Each line in the file contains one word that contains only lowercase letters (no punctuation), followed by one comma, and then a valid score. There are no blank lines in the file. Each word has at least one character.

Neutral words, which would have a score of 0, are not included in the CSV file.

Given the example CSV file opened for reading, function read_word_scores should return:

{'amazing': 4, 'happy': 3, 'anxious': -2, 'disastrous': -3, 'awesome': 4, 'outstanding': 5, 'woohoo': 3}

Complete the function read_word_scores according to the example above and the docstring below. You may assume the argument file has the correct format.

def read_word_scores(f: TextIO) -> Dict[str, int]:

"""Return a dictionary that has words from f as keys and their

corresponding scores as values.

Precondition: words in f are unique

"""

Part (b) [4 marks] Complete the function below according to its docstring:

def score_document(text: str, word_to_score: Dict[str, int]) -> float:

"""Return the emotion analysis score for text. The score is the average of the score for

each word in text using word_to_score. If a word from text does not appear in word_to_score, its score is 0.

Precondition: text contains only words made up of only lowercase alphabetic characters

(no punctuation), and each word is separated by a space. text contains at least one word.

>>> word_to_score = {'amazing': 4, 'happy': 3, 'anxious': -2, \

'disastrous': -3, 'awesome': 4, 'outstanding': 5, 'woohoo': 3}

>>> score_document('everything is awesome', word_to_score)

1.3333333333333333

>>> score_document('outstanding and amazing', word_to_score)

3.0

>>> score_document('it is', word_to_score)

0.0

>>> score_document('i am happy but anxious', word_to_score)

0.2

"""

Part (c) [4 marks] Complete the function below according to its docstring:

def find_similar_words(word: str, word_to_score: Dict[str, int]) -> List[str]:

"""Return a list of words from word_to_score that are similar to word. Two words

are considered similar if they start with the same letter, have the same length,

and have the same score in word_to_scores. A word cannot be similar to itself.

Precondition: word is lowercase and word is in word_to_score

>>> word_to_score = {'amazing': 4, 'happy': 3, 'anxious': -2, \

'disastrous': -3, 'awesome': 4, 'outstanding': 5, 'woohoo': 3}

>>> find_similar_words('amazing', word_to_score)

['awesome']

>>> find_similar_words('happy', word_to_score)

[]

"""

Question 8. [6 marks]

Complete the function below to according to its docstring.

To receive full marks on this function, your solution must not remove any keys from the parameter card_to_total, even temporarily, such as by using the method dict.clear().

def update_amounts(card_to_total: Dict[str, int], amts: List[Tuple[str, int]]) -> None:

"""Update card_to_total with the amounts for each card from amts.

>>> D = {}

>>> update_amounts(D, [('visa', 1000), ('amex', 50), ('visa', 500)])

>>> D

{'visa': 1500, 'amex': 50}

>>> update_amounts(D, [('amex', 50), ('visa', 1000), ('mc', 100)])

>>> D

{'visa': 2500, 'amex': 100, 'mc': 100}

>>> update_amounts(D, [('paypal', 25), ('amex', -100)])

>>> D

{'visa': 2500, 'amex': 0, 'mc': 100, 'paypal': 25}

"""

Question 9. [7 marks]

Recall the algorithms insertion sort, selection sort, and bubble sort. Throughout this question, lists are to be sorted into ascending (increasing) order.

Part (a) [1 mark]

Consider the following lists:

L1 = [1, 3, 4, 5, 2, 6, 7, 8, 9]

L2 = [9, 8, 7, 6, 5, 4, 3, 2, 1]

Which list would cause Selection Sort to do more comparisons? Circle one of the following.

L1                      L2                       they would require an equal number

Part (b) [1 mark]

Consider the following lists:

L1 = [1, 3, 4, 5, 2, 6, 7, 8, 9]

L2 = [9, 8, 7, 6, 5, 4, 3, 2, 1]

Which list would cause Insertion Sort to do more comparisons? Circle one of the following.

L1                      L2                            they would require an equal number

Part (c) [5 marks] Consider the following lists. For each list, and each algorithm, consider whether at least two passes of the algorithm could have been completed on the list. If at least two passes could have been completed, check the box corresponding to that list and algorithm.

Insertion?              Selection?             Bubble?

[1, 2, 4, 6, 5, 7, 3]

[1, 3, 4, 6, 5, 7, 2]

[1, 3, 4, 5, 2, 6, 7]

[5, 4, 3, 2, 1, 6, 7]

[1, 2, 4, 5, 6, 7, 8]





热门主题

课程名

mktg2509 csci 2600 38170 lng302 csse3010 phas3226 77938 arch1162 engn4536/engn6536 acx5903 comp151101 phl245 cse12 comp9312 stat3016/6016 phas0038 comp2140 6qqmb312 xjco3011 rest0005 ematm0051 5qqmn219 lubs5062m eee8155 cege0100 eap033 artd1109 mat246 etc3430 ecmm462 mis102 inft6800 ddes9903 comp6521 comp9517 comp3331/9331 comp4337 comp6008 comp9414 bu.231.790.81 man00150m csb352h math1041 eengm4100 isys1002 08 6057cem mktg3504 mthm036 mtrx1701 mth3241 eeee3086 cmp-7038b cmp-7000a ints4010 econ2151 infs5710 fins5516 fin3309 fins5510 gsoe9340 math2007 math2036 soee5010 mark3088 infs3605 elec9714 comp2271 ma214 comp2211 infs3604 600426 sit254 acct3091 bbt405 msin0116 com107/com113 mark5826 sit120 comp9021 eco2101 eeen40700 cs253 ece3114 ecmm447 chns3000 math377 itd102 comp9444 comp(2041|9044) econ0060 econ7230 mgt001371 ecs-323 cs6250 mgdi60012 mdia2012 comm221001 comm5000 ma1008 engl642 econ241 com333 math367 mis201 nbs-7041x meek16104 econ2003 comm1190 mbas902 comp-1027 dpst1091 comp7315 eppd1033 m06 ee3025 msci231 bb113/bbs1063 fc709 comp3425 comp9417 econ42915 cb9101 math1102e chme0017 fc307 mkt60104 5522usst litr1-uc6201.200 ee1102 cosc2803 math39512 omp9727 int2067/int5051 bsb151 mgt253 fc021 babs2202 mis2002s phya21 18-213 cege0012 mdia1002 math38032 mech5125 07 cisc102 mgx3110 cs240 11175 fin3020s eco3420 ictten622 comp9727 cpt111 de114102d mgm320h5s bafi1019 math21112 efim20036 mn-3503 fins5568 110.807 bcpm000028 info6030 bma0092 bcpm0054 math20212 ce335 cs365 cenv6141 ftec5580 math2010 ec3450 comm1170 ecmt1010 csci-ua.0480-003 econ12-200 ib3960 ectb60h3f cs247—assignment tk3163 ics3u ib3j80 comp20008 comp9334 eppd1063 acct2343 cct109 isys1055/3412 math350-real math2014 eec180 stat141b econ2101 msinm014/msing014/msing014b fit2004 comp643 bu1002 cm2030
联系我们
EMail: 99515681@qq.com
QQ: 99515681
留学生作业帮-留学生的知心伴侣!
工作时间:08:00-21:00
python代写
微信客服:codinghelp
站长地图