Nguyenkhachungit.files.wordpress.com



REPORT PH?T TRI?N H? TH?NG ?A PH??NG TI?NMSSV: 16049611H? và Tên: Nguy?n Kh?c HùngM?n: Phát tri?n h? th?ng ?a ph??ng ti?n.Bài 1: Python data type String1. Write a Python program to calculate the length of a stringa=?"Hello,World!"print(len(a)) #In ra ?? dài bi?n a.center635Ch?y:center6352. Write a Python program to count the number of characters (character frequency) in a string.Code:def char_frequency(str1): dict = {} for n in str1: #Vòng l?p ??n h?t chu?i str1 keys = dict.keys() #Khai báo bi?n key if n in keys: #?i?u ki?n n trong bi?n key dict[n] += 1 #t?ng s? l??ng ph?n t? dict lên 1 else: # Ng??c l?i s? ph?n t? c?a dict là 1. dict[n] = 1 return dict # tr? v? giá tr? c?a dict.print(char_frequency('')) G?i hàm char_frequency v?i giá tr? ??u vào là center635Ch?y:center6353. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty stringcode:def string_both_ends(str): #Tên Hàm String_both_ends v?i giá tr? vào là 1 chu?i str. if len(str) < 2: #?i?u ki?n n?u ?? dài chu?i nh? h?n 2. return '' #Tr? v? null return str[0:2] + str[-2:] Tr? v? ch?i str[0:2] thêm vào str giá tr? -2print(string_both_ends('w3resource')) #G?i hàm v?i các giá tr? ??u vào khác nhau.print(string_both_ends('w3'))print(string_both_ends('w'))center635Ch?y:center6354. Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itselfcode:def change_char(str1): #Khai báo tên Hàm char = str1[0] # Khai báo bi?n str1 str1 = str1.replace(char, '$') #thay th? giá tr? c?a bi?n str1. str1 = char + str1[1:] return str1print(change_char('restart')) G?i hàmdef change_char(str1): char = str1[0] str1 = str1.replace(char, '$') str1 = char + str1[1:] return str1print(change_char('restart'))Ch?y:center6355. Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each stringcode:def chars_mix_up(a, b): new_a = b[:2] + a[2:] #Khai báo 2 chu?i new_a và new_b new_b = a[:2] + b[2:] return new_a + ' ' + new_b #N?i hai chu?i l?i v?i nhau cách nhau 1 kho?ng tr?ng.print(chars_mix_up('abc', 'xyz')) #G?i Hàmcenter635Ch?y:center635Bài 2: Python data type JSON1. Write a Python program to convert JSON data to Python objectcode:import json #N?p th? vi?n jsonjson_obj = '{ "Name":"David", "Class":"I", "Age":6 }' #Khai báo m?ng ??i t??ngpython_obj = json.loads(json_obj) # Kh?i ch?y mangr ??i t??ng ?ó.print("\nJSON data:")print(python_obj) #In d? li?u ra màn hình theo d? li?u c?a print("\nName: ",python_obj["Name"]) t?ng ??i t??ngjprint("Class: ",python_obj["Class"])print("Age: ",python_obj["Age"]) center635Ch?y:center6352. ?Write a Python program to convert Python object to JSON datacode:import json# a Python object (dict):python_obj = { "name": "David", "class":"I", "age": 6 }print(type(python_obj))# convert into JSON:j_data = json.dumps(python_obj) #chuy?n ??i t? ki?u ??i t??ng sang data trong python.# result is a JSON string:print(j_data) #in ra k?t qu? v?a chuyênr ??icenter635Ch?y:center6353. Write a Python program to convert Python objects into JSON strings. Print all the values.Code:import jsonpython_dict = {"name": "David", "age": 6, "class":"I"}python_list = ["Red", "Green", "Black"]python_str = "Python Json"380238069215Khai báo các bi?nKhai báo các bi?npython_int = (1234)python_float = (21.34)python_T = (True)python_F = (False)python_N = (None)3830955132080Th?c hi?n chuy?n ??i các bi?n ??i t??ng sang d? li?u ?? bài yêu c?u ( int, float, ...)Th?c hi?n chuy?n ??i các bi?n ??i t??ng sang d? li?u ?? bài yêu c?u ( int, float, ...)json_dict = json.dumps(python_dict)json_list = json.dumps(python_list)json_str = json.dumps(python_str)json_num1 = json.dumps(python_int)json_num2 = json.dumps(python_float)json_t = json.dumps(python_T)json_f = json.dumps(python_F)json_n = json.dumps(python_N)3707130113665In k?t qu? ?? converrt ra màn hìnhIn k?t qu? ?? converrt ra màn hìnhprint("json dict : ", json_dict)print("jason list : ", json_list)print("json string : ", json_str)print("json number1 : ", json_num1)print("json number2 : ", json_num2)print("json true : ", json_t)print("json false : ", json_f)print("json null ; ", json_n)center635Ch?y:center6354. Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4code:import jsonj_str = {'4': 5, '6': 7, '1': 3, '2': 4}print("Original String:")print(j_str)print("\nJSON data:")print(json.dumps(j_str, sort_keys=True, indent=4)) #S?p x?p giá tr? bi?n j_str theo t? t? t?ng d?nCh?y:center6355. Write a Python program to convert JSON encoded data into Python objectscode:import jsonjobj_dict = &apos;{"name": "David", "age": 6, "class": "I"}&apos;jobj_list = &apos;["Red", "Green", "Black"]&apos;jobj_string = &apos;"Python Json"&apos;jobj_int = &apos;1234&apos;jobj_float = &apos;21.34&apos;python_dict = json.loads(jobj_dict)python_list = json.loads(jobj_list)python_str = json.loads(jobj_string)python_int = json.loads(jobj_int)python_float = json.loads(jobj_float)print("Python dictionary: ", python_dict)print("Python list: ", python_list)print("Python string: ", python_str)print("Python integer: ", python_int)print("Python float: ", python_float)Ch?y:center635Bài 3: Python data type List1. Write a Python program to sum all the items in a list.Code:def sum_list(items): sum_numbers = 0 for x in items: #vào vòng l?p ds. sum_numbers += x #Th?c hi?n c?ng các giá rt? trong ds return sum_numbers #Tr? v? giá tr? sun_numbersprint(sum_list([1,2,-8])) #In ra iá tr? t?ng các ph?n t? trong ds tr? v? trong hàm sum_list. Ch?y:center6352. Write a Python program to multiplies all the items in a list.Code:def multiply_list(items): tot = 1 for x in items:226885533655Gi?i thích t??ng t? bài m?t, nh?n các giá tr? c?a ds và tr? v?Gi?i thích t??ng t? bài m?t, nh?n các giá tr? c?a ds và tr? v? tot *= x return totprint(multiply_list([1,2,-8]))Ch?y:center6353. Write a Python program to get the largest number from a listcode:def max_num_in_list( list ): max = list[ 0 ] Khai báo ds for a in list: Vòng l?p ??n cu?i ds if a > max: N?u a> max → Gán max = a max = a Tr? v? giá tr? max return maxprint(max_num_in_list([1, 2, -8, 0])) G?i hàm v?i giá tr? ??u vào.Ch?y:center6354. Write a Python program to get the smallest number from a listcode:def smallest_num_in_list( list ):2887980145415Gi?i thíc t??ng t? bài 3 tìm minGi?i thíc t??ng t? bài 3 tìm min min = list[ 0 ] for a in list: if a < min: min = a return minprint(smallest_num_in_list([1, 2, -8, 0])) Ch?y:center6355. ?Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of stringscode:def match_words(words): Kh?i t?o hàm ??m ctr = 0 for word in words: if len(word) > 1 and word[0] == word[-1]: #So sánh n?u chu?i có kí t? ??u và kí t? cu?i gi?ng nhau ctr += 1 return ctr #Tr? v? k?t qu?.print(match_words(['abc', 'xyz', 'aba', '1221'])) #G?i hàm và xu?t ra màn hìnhCh?y:center635Bài 4: Python data type Dictionary1. Write a Python script to sort (ascending and descending) a dictionary by valuecode:import operator #Khai báo th? vi?nd = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}print('Original dictionary : ',d) #In ra danh sách d.sorted_d = sorted(d.items(), key=operator.itemgetter(0)) #S?p x?p danh sách theo th? t? t?ng d?nprint('Dictionary in ascending order by value : ',sorted_d) #In ra màn hìnhsorted_d = dict( sorted(d.items(), key=operator.itemgetter(0),reverse=True))print('Dictionary in descending order by value : ',sorted_d)Ch?y:center6352. Write a Python script to add a key to a dictionary.Code:d = {0:10, 1:20}print(d) #in ds dd.update({2:30}) #L?nh thêm m?t giá tr? vào dprint(d) In ds d ?? thêmCh?y:center6353. ?Write a Python script to concatenate following dictionaries to create a new onecode:dic1={1:10, 2:20}dic2={3:30, 4:40}dic3={5:50,6:60}dic4 = {}for d in (dic1, dic2, dic3): dic4.update(d) #dic4= dic1+dic2+dic3 Caapk nh?t l?i giá tr? dic4print(dic4)Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60}Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}Ch?y:center6354. Write a Python script to check if a given key already exists in a dictionarycode:d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} #Kh?i t?o 1 ds ch?a các keydef is_key_present(x): #Kh?i t?o hàm tìm key if x in d: print('Key is present in the dictionary') else: print('Key is not present in the dictionary')is_key_present(5) #Các giá tr? c?n tìmis_key_present(9)Ch?y:center6355. Write a Python program to iterate over dictionaries using for loops code:d = {'x': 10, 'y': 20, 'z': 30} for dict_key, dict_value in d.items(): #Vòng l?p for chuy?n các kí t? n?i key và value print(dict_key,'->',dict_value) #In ra k?t qu?Ch?y:center635Bài 5: Python data type tuple1. Write a Python program to create a tuple.?Code:x = () #T?o 1 ??i t??ng tr?ngsprint(x)#T?o 1 ??i t??ng tuple tr?ng dungf hàm tuple()tuplex = tuple()print(tuplex)Ch?y:center6352.Write a Python program to create a tuple with different data typescode:#T?o 1 tupe v?i ki?u d? li?u khác nhautuplex = ("tuple", False, 3.2, 1)print(tuplex)Ch?y:center6353. Write a Python program to create a tuple with numbers and print one item.Code:T?o 1 tuple v?i các s? nguyêntuplex = 5, 10, 15, 20, 25print(tuplex)#T?o các ch? m?c tupletuplex = 5,print(tuplex) Ch?y:center6354. Write a Python program to unpack a tuple in several variables.Code:#T?o m?i 1 tupletuplex = 4, 8, 3 print(tuplex)n1, n2, n3 = tuplex#m? 1 tupleprint(n1 + n2 + n3) #S? l??ng bi?n ph?i b?ng s? l??ng ch? m?c trong tuplen1, n2, n3, n4= tuplex Ch?y:center6355. Write a Python program to add an item in a tuple.?Code:#T?o 1 tupletuplex = (4, 6, 2, 8, 3, 1) print(tuplex)#tuple là kh?ng ??i cho nên kh?ng th? thêm 1 thành ph?n m?i #S? dung tuple h?p nh?t v?i toán t? + ?? thêm và nó s? t?o ra 1 tuple tuplex = tuplex + (9,)print(tuplex)#Thêm m?t ph?n t?tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]print(tuplex)#Chuy?n tuple thành dslistx = list(tuplex) #S? dungj cách khác ?? thêm vào ds.listx.append(30)tuplex = tuple(listx)print(tuplex)Ch?y:center635Bài 6: Python data type Array1. Write a Python program to create an array of 5 integers and display the array items. Access individual element through indexes.?Code:from array import *array_num = array('i', [1,3,5,7,9])for i in array_num: print(i)print("Access first three items individually")print(array_num[0])print(array_num[1])print(array_num[2])Ch?y:center6352. Write a Python program to append a new item to the end of the array.?Code:from array import *array_num = array('i', [1, 3, 5, 7, 9])print("Original array: "+str(array_num))print("Append 11 at the end of the array:")array_num.append(11)print("New array: "+str(array_num))Ch?y:center6353. Write a Python program to reverse the order of the items in the array.Code:from array import *array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3])print("Original array: "+str(array_num))array_num.reverse()print("Reverse the order of the items:")print(str(array_num))Ch?y:center6354. Write a Python program to get the length in bytes of one array item in the internal representation.Code:from array import *array_num = array('i', [1, 3, 5, 7, 9])print("Original array: "+str(array_num))print("Length in bytes of one array item: "+str(array_num.itemsize))Ch?y:center6355. Write a Python program to get the current memory address and the length in elements of the buffer used to hold an array?s contents and also find the size of the memory buffer in bytes.Code:from array import *array_num = array('i', [1, 3, 5, 7, 9])print("Original array: "+str(array_num))print("Current memory address and the length in elements of the buffer: "+str(a$print("The size of the memory buffer in bytes: "+str(array_num.buffer_info()[1]$Ch?y:center635Bài 7: Python File Input/Output1. Write a Python program to read an entire text filecode:def file_read(fname): #Kh?i t?o hàm ??c file txt = open(fname) #M? file fname print(txt.read()) #??c filefile_read('test.txt') #G?i hàmCh?y:T?o file test.txt trong cùng th? m?ccenter6352. Write a Python program to read first n lines of a file.Code:def file_read_from_head(fname, nlines): #kh?i t?o hàm ??c file from itertools import islice #G?i th? vi?n slice with open(fname) as f: #M? file for line in islice(f, nlines): #Vòng l?p ?? ??c file print(line)file_read_from_head('test.txt',2) #G?i hàmCh?y:center6353. Write a Python program to append text to a file and display the textcode:def file_read(fname): #Kh?i t?o hàm ??c file from itertools import islice #G?i th? vi?n slice with open(fname, "w") as myfile: #M? file myfile.write("Python Exercises\n") #Ghi các kí t? vào file myfile.write("Java Exercises") txt = open(fname) #M? file print(txt.read()) #?ocj filefile_read('abc.txt') #g?i hàmCh?y:center6354. Write a Python program to read last n lines of a fileCode:#Import các th? vi?nimport sysimport osdef file_read_from_tail(fname,lines): #Kh?i t?o hàm ??c file bufsize = 8192 fsize = os.stat(fname).st_size #?? l?n c?a file iter = 0 with open(fname) as f: #M? file if bufsize > fsize: #So sánh n?u bufile > fsize bufsize = fsize-1 data = [] while True: iter +=1 f.seek(fsize-bufsize*iter) data.extend(f.readlines()) #??c các hàng c?a file if len(data) >= lines or f.tell() == 0: print(''.join(data[-lines:])) breakfile_read_from_tail('test.txt',2)Ch?y:center6355.Write a Python program to read a file line by line and store it into a list.Code:import sysimport osdef file_read_from_tail(fname,lines): bufsize = 8192 fsize = os.stat(fname).st_size iter = 0 with open(fname) as f: if bufsize > fsize: bufsize = fsize-1 data = [] while True: iter +=1 f.seek(fsize-bufsize*iter) data.extend(f.readlines()) if len(data) >= lines or f.tell() == 0: print(''.join(data[-lines:])) breakfile_read_from_tail('test.txt',2)Ch?y:center635 ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download