You are on page 1of 9

1

EEA216 資料結構
Data Structure
Lecture 6
Yu-Hui Huang, Data Structure

Yu-Hui Huang
Oot. 3, 2022
L4: Exercise 1: Dictionary
Write a python function to map two given
lists into a dictionary. #Test case:
Input: [“a”,”b”,”c”], [35, 20, 10]
Output: {'a': 35, 'c': 20, 'b': 10}
def toDict(key,val):
return dict(zip(key,val))

k = [“a”, “b”, “c”]


v = [35, 20 ,10] Hint:
1. zip()
print(toDict(k, v))
2. dict()

Yu-Hui Huang, Data Structure 2


L4: Exercise 2: map
Write a program to square the elements
from a given list using map() function.

def squared(num): #Test case:


return num*num Input: [1,2,3,4]
Output: [1,4,9,16]
nums = [1,2,3,4]
out = map(squared, nums)
print(list(out))

Yu-Hui Huang, Data Structure 3


L4: Exercise 3
Write a program with the following class definition
and test it with the following expressions.
>>>cir = Circle(6)
Polygon
>>>print(cir.area())
(num_sides)
113.097335529
area
>>>print(cir.perimeter())
perimeter
37.6991118430
inherit inherit
>>>rec = rectangle(6,6)
>>>print(rec.area())
Circle Rectangle
36
(num_sides, radius) (num_sides, length,
>>>print(rec.perimeter())
area breadth)
24
perimeter area
perimeter

Yu-Hui Huang, Data Structure 4


import math
L4: Exercise 3 pi = math.pi
class Polygon:
def __init__(self, n_s):
self.num_sides = n_s
def area(self):
pass
def perimeter(self):
Polygon
pass
(num_sides)
class Circle(Polygon):
area
def __init__(self, r):
perimeter
Polygon.__init__(self,0)
inherit inherit self.radius = r
def area(self):
Circle Rectangle return pi*(self.radius)**2
(num_sides, radius) (num_sides, length,def perimeter(self):
area breadth) return pi*2*self.radius
perimeter area
perimeter …

Yu-Hui Huang, Data Structure 5


L4: Exercise 4: lambda function

Write a program to add the numbers from two lists


using lambda function.
Syntax: lambda arguments : expression

a = [1,3,5] #Test case:


b = [2,4,6] Input: [1,3,5], [2,4,6]
Output: [3,7,11]

1. print(list(map(lambda x,y: x+y, a,b))


2. print(list(map(lambda x:x[0]+x[1], zip(a,b))))

Yu-Hui Huang, Data Structure 6


Exercise 0: Register on OJ

1. Create a new account with your student ID


number as “username”
2. Try with the problem #1 and #1000
Hint:
input(): take the user input from standard IO
(data type: string)

Yu-Hui Huang, Data Structure 7


Exercise 1: file I/O (#100301)

Write a program to read a file (input.txt), and print


out the longest word on the screen.
#Test case:
Input(input.txt)
--
Lorem ipsum dolor sit amet
consectetuer adipiscing elit
--
Output: (stdio)
consectetuer

Yu-Hui Huang, Data Structure 8


Exercise 2: string (#100302)

Write a program to count the occurrence of each


alphabet. (standard I/O)
#Test case: Hint:
Input: upper()
2 isalpha()
To be or not to be.
True.

Output:
T 3
O 4
B 2
E 3
R 2
N 1
Yu-Hui Huang, Data Structure 9

You might also like