• Source
    1. Module 3
    2. In this assignment, you will implement some functions related to strings, lists, sets and tuples. Each function has been defined for you, but without the code. See the docstring in each function for instructions on what the function is supposed to do and how to write the code. It should be clear enough. In some cases, we have provided hints to help you get started.
    3.  
    4. ###########################################################
    5. ### EXECUTE THIS CELL BEFORE YOU TO TEST YOUR SOLUTIONS ###
    6. ###########################################################
    7. ​
    8. import unittest
    9. from nose.tools import assert_equal, assert_true
    10. import nose.tools
    11. def concatenate(strings):
    12. """
    13. Concatenates the given list of strings into a single string.
    14. Returns the single string.
    15. If the given list is empty, returns an empty string.
    16. ​
    17. For example:
    18. - If we call concatenate(["a","b","c"]), we'll get "abc" in return
    19. - If we call concatenate([]), we'll get "" in return
    20. ​
    21. Hint(s):
    22. - Remember, you can create a single string from a list of multiple strings by using the join() function
    23. """
    24. l=""
    25. for a in strings:
    26. l+=a
    27. return l
    28.  
    29. ##########################
    30. ### TEST YOUR SOLUTION ###
    31. ##########################
    32. ​
    33. lst = ["a","b","c"]
    34. assert_equal("abc",concatenate(lst))
    35. lst = []
    36. assert_equal("",concatenate(lst))
    37. print("Success!")
    38. Success!
    39. def all_but_last(seq):
    40. """
    41. Returns a new list containing all but the last element in the given list.
    42. If the list is empty, returns None.
    43. ​
    44. For example:
    45. - If we call all_but_last([1,2,3,4,5]), we'll get [1,2,3,4] in return
    46. - If we call all_but_last(["a","d",1,3,4,None]), we'll get ["a","d",1,3,4] in return
    47. - If we call all_but_last([]), we'll get None in return
    48. """
    49. if seq==[]:
    50. return None
    51. else:
    52. return seq[:-1]
    53.  
    54. ##########################
    55. ### TEST YOUR SOLUTION ###
    56. ##########################
    57. ​
    58. lst = []
    59. assert_equal(None,all_but_last(lst))
    60. lst = [1,2,3,4,5]
    61. nose.tools.assert_list_equal([1,2,3,4],all_but_last(lst))
    62. lst = ["a","d",1,3,4,None]
    63. nose.tools.assert_list_equal(["a","d",1,3,4],all_but_last(lst))
    64. print("Success!")
    65. Success!
    66. def remove_duplicates(lst):
    67. """
    68. Returns the given list without duplicates.
    69. The order of the returned list doesn't matter.
    70. ​
    71. For example:
    72. - If we call remove_duplicates([1,2,1,3,4]), we'll get [1,2,3,4] in return
    73. - If we call remove_duplicates([]), we'll get [] in return
    74. ​
    75. Hint(s):
    76. - Remember, you can create a set from a string, which will remove the duplicate elements
    77. """
    78.  
    79. o = []
    80. for x in lst:
    81. if x not in o:
    82. o.append(x)
    83. return o
    84.  
    85. ##########################
    86. ### TEST YOUR SOLUTION ###
    87. ##########################
    88. ​
    89. lst = [1,3,4,3,4,5,2]
    90. nose.tools.assert_count_equal([1,3,4,5,2],remove_duplicates(lst))
    91. lst = []
    92. nose.tools.assert_count_equal([],remove_duplicates(lst))
    93. print("Success!")
    94. Success!
    95. def reverse_word(word):
    96. """
    97. Reverses the order of the characters in the given word.
    98. ​
    99. For example:
    100. - If we call reverse_word("abcde"), we'll get "edcba" in return
    101. - If we call reverse_word("a b c d e"), we'll get "e d c b a" in return
    102. - If we call reverse_word("a b"), we'll get "b a" in return
    103. - If we call reverse_word(""), we'll get "" in return
    104. ​
    105. Hint(s):
    106. - You can iterate over a word in reverse and access each character
    107. """
    108.  
    109. return word[::-1]
    110.  
    111. ##########################
    112. ### TEST YOUR SOLUTION ###
    113. ##########################
    114. ​
    115. word = "abcdefg"
    116. assert_equal("gfedcba",reverse_word(word))
    117. ​
    118. word = "a b c d e f g"
    119. assert_equal("g f e d c b a",reverse_word(word))
    120. ​
    121. word = "a b"
    122. assert_equal("b a",reverse_word(word))
    123. ​
    124. word = ""
    125. assert_equal("",reverse_word(word))
    126. print("Success!")
    127. Success!
    128. def divisors(n):
    129. """
    130. Returns a list with all divisors of the given number n.
    131. As a reminder, a divisor is a number that evenly divides another number.
    132. The returned list should include 1 and the given number n itself.
    133. The order of the returned list doesn't matter.
    134. ​
    135. For example:
    136. - If we call divisors(10), we'll get [1,2,5,10] in return
    137. - If we call divisors(1), we'll get [1] in return
    138. """
    139. out=[]
    140. for i in range(1,n+1):
    141. if(n % i == 0):
    142. out.append(i)
    143. return out
    144.  
    145. ##########################
    146. ### TEST YOUR SOLUTION ###
    147. ##########################
    148. ​
    149. number = 10
    150. nose.tools.assert_count_equal([1,2,5,10],divisors(number))
    151. ​
    152. number = 1
    153. nose.tools.assert_count_equal([1],divisors(number))
    154. ​
    155. number = 7
    156. nose.tools.assert_count_equal([1,7],divisors(number))
    157. print("Success!")
    158. Success!
    159. def capitalize_or_join_words(sentence):
    160. """
    161. If the given sentence starts with *, capitalizes the first and last letters of each word in the sentence,
    162. and returns the sentence without *.
    163. Else, joins all the words in the given sentence, separating them with a comma, and returns the result.
    164. ​
    165. For example:
    166. - If we call capitalize_or_join_words("*i love python"), we'll get "I LovE PythoN" in return.
    167. - If we call capitalize_or_join_words("i love python"), we'll get "i,love,python" in return.
    168. - If we call capitalize_or_join_words("i love python "), we'll get "i,love,python" in return.
    169. ​
    170. Hint(s):
    171. - The startswith() function checks whether a string starts with a particualr character
    172. - The capitalize() function capitalizes the first letter of a string
    173. - The upper() function converts all lowercase characters in a string to uppercase
    174. - The join() function creates a single string from a list of multiple strings
    175. """
    176. if sentence.startswith('*'):
    177. sentence=sentence.title()
    178. words = sentence.replace('*', '').split()
    179. ans=""
    180. for word in words:
    181. ans+=word[:-1] + word[-1].upper() + " "
    182. return ans.strip()
    183. ​
    184. words = sentence.split()
    185. return ','.join(words)
    186.  
    187. ##########################
    188. ### TEST YOUR SOLUTION ###
    189. ##########################
    190. ​
    191. string = "*i love python"
    192. assert_equal("I LovE PythoN",capitalize_or_join_words(string))
    193. ​
    194. string = "i love python"
    195. assert_equal("i,love,python",capitalize_or_join_words(string))
    196. ​
    197. string = "i love python "
    198. assert_equal("i,love,python",capitalize_or_join_words(string))
    199. print("Success!")
    200. Success!
    201. def move_zero(lst):
    202. """
    203. Given a list of integers, moves all non-zero numbers to the beginning of the list and
    204. moves all zeros to the end of the list. This function returns nothing and changes the given list itself.
    205. ​
    206. For example:
    207. - After calling move_zero([0,1,0,2,0,3,0,4]), the given list should be [1,2,3,4,0,0,0,0] and the function returns nothing
    208. - After calling move_zero([0,1,2,0,1]), the given list should be [1,2,1,0,0] and the function returns nothing
    209. - After calling move_zero([1,2,3,4,5,6,7,8]), the given list should be [1,2,3,4,5,6,7,8] and the function returns nothing
    210. - After calling move_zero([]), the given list should be [] and the function returns nothing
    211. """
    212. no_zero = list()
    213. only_zero = list()
    214. for i in lst:
    215. if i != 0:
    216. no_zero.append(i)
    217. else:
    218. only_zero.append(i)
    219. ​
    220. temp = no_zero + only_zero
    221. i = 0
    222. for e in temp:
    223. lst[i] = e
    224. i += 1
    225.  
    226. ##########################
    227. ### TEST YOUR SOLUTION ###
    228. ##########################
    229. ​
    230. lst = [0,1,0,2,0,3,0,4]
    231. assert_equal(None,move_zero(lst))
    232. nose.tools.assert_list_equal([1,2,3,4,0,0,0,0],lst)
    233. ​
    234. lst = []
    235. move_zero(lst)
    236. nose.tools.assert_list_equal([],lst)
    237. ​
    238. lst = [0,0,0,0,0,0,0,0,0]
    239. move_zero(lst)
    240. nose.tools.assert_list_equal([0,0,0,0,0,0,0,0,0],lst)
    241. ​
    242. lst = [1,2,3,4,5,6,7,8]
    243. move_zero(lst)
    244. nose.tools.assert_list_equal([1,2,3,4,5,6,7,8],lst)
    245. print("Success!")
    246. Success!
    247. def main():
    248. """
    249. Calls all the functions above to see whether they've been implemented correctly.
    250. """
    251. ​
    252. # test concatenate
    253. print("test concatenate")
    254. word = concatenate(["b", "e", "a", "t", "l", "e", "s"])
    255. print(word == "beatles")
    256. print("=" * 50)
    257. ​
    258. # test all_but_last
    259. print("test all_but_last")
    260. seq = all_but_last(["john", "paul", "george", "ringo", "tommy"])
    261. print(seq == ["john", "paul", "george", "ringo"])
    262. print("=" * 50)
    263. ​
    264. # test remove_duplicates
    265. print("test remove_duplicates")
    266. res = remove_duplicates([1, 3, 4, 2, 1])
    267. print(res == [1, 3, 4, 2])
    268. print("=" * 50)
    269. ​
    270. # test reverse_word
    271. print("test reverse_word")
    272. res = reverse_word("alphabet")
    273. print(res == "tebahpla")
    274. print("=" * 50)
    275. ​
    276. # test divisors
    277. print("test divisors")
    278. res = divisors(120)
    279. print(set(res) == set([1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120]))
    280. print("=" * 50)
    281. ​
    282. # test capitalize_or_join_words
    283. print("test capitalize_or_join_words")
    284. print("Result for String Start With *: ")
    285. # Should return "I LovE CodinG AnD I'M HavinG FuN"
    286. res = capitalize_or_join_words("*i love coding and i'm having fun")
    287. print(res == "I LovE CodinG AnD I'M HavinG FuN")
    288. ​
    289. print("Result for Other String: ")
    290. # Should print "I,love,coding,and,I'm,having,fun"
    291. res = capitalize_or_join_words("I love coding and I'm having fun")
    292. print(res == "I,love,coding,and,I'm,having,fun")
    293. print("=" * 50)
    294. ​
    295. # test move_zero
    296. print("test move_zero")
    297. lst = [0, 1, 0, 2, 0, 3, 4, 0]
    298. print("Before move,the list looks like\n", lst)
    299. move_zero(lst)
    300. print("After move,the list looks like\n", lst)
    301. print("=" * 50)
    302. ​
    303. #This will automatically run the main function in your program
    304. #Don't change this
    305. if __name__ == '__main__':
    306. main()