100 câu hỏi viết mã python hàng đầu năm 2022

Bài viết này mang đến cho bạn 50 câu phỏng vấn về ngôn ngữ lập trình Python. Đây không phải tất cả các câu hỏi bạn có thể gặp nhưng có thể mang đến cho bạn những ý tưởng để chuẩn bị tốt nhất khi đi phỏng vấn. Các câu trả lời là các thông tin gợi ý cùng một số nguồn bạn có thể tham khảo. Bạn nên tìm hiểu thêm để có thể có câu trả lời phù hợp nhất cho các câu hỏi phòng vấn về Python.

Show

Nội dung

  • 1/ Sự khác nhau giữa Danh sách (List) và Bộ dữ liệu (Tuple) là gì?
  • 2/ Làm thế nào để convert List thành Tuple?
  • 3/ Khác nhau giữa dãy (Array) và Danh sách (List)?
  • 4/ Làm thế nào để convert một List thành một Array
  • 5/ Bộ nhớ được quản lý như thế nào trong Python?
  • 6/ Đa luồng (multithreading) trong Python được xử lý thế nào?
  • 7/ Monkey patching là gì trong Python?
  • 8/Hàm lambda trong Python là gì?
  • 9/  Pickling và unpickling là gì?
  • 10/ NumPy arrays là gì và có lợi thế gì so với nested lists trong Python?
  • 11/ Giải thích về kế thừa (inheritance) trong Python. Có những loại kế thừa nào?
  • 12/ Đa hình (polymorphism) trong Python là gì?
  • 13/ Sự khác nhau giữa hàm range() và xrange()
  • 14/ Giải thích sự khác nhau giữa Flask và Django
  • 15/ PYTHONPATH là gì và sử dụng khi nào?
  • 16/ PEP 8 là gì?
  • 17/ Python decorators là gì?
  • 18/ Init là gì?
  • 19/Toán tử ternary  là gì?
  • 20/Local và global variables trong Python là gì?
  • 21/ Trong Python @property là gì?
  • 22/ Try/except được sử dụng thế nào trong Python?
  • 23/ Python 2.7.x và Python 3.x khác nhau thế nào?
  • 24/ Join method trong Python là gì và method này hoạt động thế nào?
  • 26/ Dictionary comprehension là gì?
  • 27/ Deep copy là gì trong Python?
  • 28/ Làm thế nào để kiểm tra xem một key đã có trong một dictionary hay chưa?
  • 29/Làm thế nào để thực hiện tối ưu hóa (memoization) trong Python?
  • 30/ Làm thế nào để sort một dictionary trong Python?
  • 31/ Khi nào và làm thể nào để dùng hàm any() và hàm all () trong Python?
  • 32/ Python Docstring là gì?
  • 33/ Giải thích sự khác nhau giữa Generator và Iterator trong Python
  • 34/ Defaultdict trong Python là gì?
  • 35/ Python Module là gì?
  • 36/ Sự khác nhau giữa “is” và “==”?
  • 37/ Giải thích sự khác nhau giữa instance, static và class methods trong python?
  • 38/Sự khác nhau giữa “func” và “func()” trong Python?
  • 39/Hàm map hoạt động thế nào trong Python?
  • 40/ Hàm reduce trong Python hoạt động thế nào?
  • 41/ Giải thích cách hoạt động của hàm Filter trong Python
  • 42/ Lookup một giá trị trong dictionary và list cái nào nhanh hơn?
  • 43/ Hiệu ứng Dogpile là gì? Làm thế nào để ngăn ngừa?
  • 44/ Đóng gói (Encapsulation) là gì trong Python?
  • 45/ Index âm (negative indexes) là gì và tại sao chúng được dùng?
  • 46/ Bạn biết gì về Palindrome và làm thế nào để kiểm tra chuỗi nhập vào có phải làm một Palindrome trong Python?
  • 47/ Namespace là gì? Cách sử dụng namespace trong Python?
  • 48/ Phạm vi (scope) trong Python là gì?
  • 49/ Kiểm tra mức đơn vị (Unittest) là gì trong Python? 
  • 50/ Hàm help() và dir() được dùng làm gì trong Python?
  • Kết luận

1/ Sự khác nhau giữa Danh sách (List) và Bộ dữ liệu (Tuple) là gì?

Đây là một câu hỏi hầu như buổi phỏng vấn Python nào cũng có thể gặp. Bạn cần biết:

  • List có thể thay đổi sau khi tạo (mutable)
  • Tuples là bất biến (immutable), không thể thay đổi sau khi tạo. Bạn không thể sử dụng  append()extend() , remove() , pop() method đối với tuples
  • List được đặt trong ngoặc vuông [] còn tuple trong ngoặc tròn ()

Tìm hiểu thêm về khác nhau giữa List và Tuple

2/ Làm thế nào để convert List thành Tuple?

Có nhiều cách để thực hiện việc này. Cách đơn giản nhất là dùng hàm tuple(list_name)

Ví dụ đoạn code sau:

# Create a list
list_1 = [1, 2, 3, 4, 5]

# Convert a list to a tuple
t = tuple(list_1)

# Print the result
print(t)

Sẽ cho ra kết quả:

(1, 2, 3, 4, 5)

3/ Khác nhau giữa dãy (Array) và Danh sách (List)?

List và Array trong Python có thể lưu bất kỳ kiểu dữ liệu nào (string, integer…), cả hai đều có thể indexed & iterated. Tuy nhiên có những điểm khác biệt:

  • List có sẵn trong thư viện, array được định nghĩa bởi Numpy
  • List có thể có nhiều kiểu dữ liệu trong khi array đòi hỏi các phần tử là đồng nhất.
  • Array dùng ít bộ nhớ hơn

4/ Làm thế nào để convert một List thành một Array

Khi lập trình, có những lúc bạn cần phải chuyển từ list sang array để có thể thực hiện một số toán tử mà trong list không thể làm được. Hàm numpy.array(). được sử dụng cho mục đích đó. Hàm này sử dụng một list như một argument và trả về một array có chứa tất cả các element của danh sách đó.

5/ Bộ nhớ được quản lý như thế nào trong Python?

  • Với Python, việc quản lý bộ nhớ do Python Memory Manager xử lý.
  • Việc quản lý bộ nhớ trong Python được xử lý trong vùng private heap. Tất cả các objects và cấu trúc dữ liệu được định vị trong vùng private heap và Python interpreter quản lý việc này và lập trình viên không cần can thiệp.
  • Python có built-in garbage collector và việc quản lý bộ nhớ được thực hiện một cách tự động

Xem thêm chi tiết về quản lý bộ nhớ trong Python tại đây

6/ Đa luồng (multithreading) trong Python được xử lý thế nào?

Python sử dụng Global Interpreter Lock (GIL) để quản lý luồng (thread), đảm bảo mỗi thời điểm chỉ có một thread được thực thi.

Tham khảo thêm về GIL và Multithreading trong Python

7/ Monkey patching là gì trong Python?

Trong Python, thuật ngữ monkey patch đề cập tới việc thay đổi các class hay module trong thời gian thực thi (run-time).

8/Hàm lambda trong Python là gì?

  • Hàm Lambda là một hàm ẩn danh (anonymous function) (hàm ẩn danh). Lambda có thể khai báo, định nghĩa ở bất kỳ đâu và không có khả năng tái sử dụng.
  • Hàm Lambda chỉ tồn tại trong phạm vi của biến mà nó được định nghĩa, vì vậy nếu như biến đó vượt ra ngoài phạm vi thì hàm này cũng không còn tác dụng nữa.
  • Hàm Lambda thường được dùng để gán vào biến, hay được gán vào hàm, class như một tham số.
100 câu hỏi viết mã python hàng đầu năm 2022
Cấu trúc hàm Lambda trong Python

9/  Pickling và unpickling là gì?

Python Pickle module dùng để biến bất kỳ Python object nào thành các chuỗi đại diện (string representation) và dump vào một file dùng hàm dump. Quy trình này gọi là pickling.  Quy trình ngược lại biến các chuỗi thành objects gọi là unpickling.

10/ NumPy arrays là gì và có lợi thế gì so với nested lists trong Python?

  • Numpy array là một đối tượng mảng N chiều ở dạng hàng và cột. Chúng ta có thể khởi tạo các numpy arrays từ nested Python lists và truy cập các phần tử trong đó.
  • Numpy hiệu quả hơn List ở chỗ nó cho phép nhiều tác vụ về vector và matrix, giúp giảm thiểu một số xử lý không cần thiết khi phải làm việc với list.

11/ Giải thích về kế thừa (inheritance) trong Python. Có những loại kế thừa nào?

Kế thừa (Inheritance) cho phép một lớp (class) có thể kế thừa các thuộc tính và phương thức từ các lớp khác đã được định nghĩa. Lớp được kế thừa gọi là lớp cha (base class hoặc parent class), lớp mới phát sinh gọi là lớp con (child class hoặc derived class). Lớp con kế thừa tất cả thành phần của lớp cha, có thể mở rộng các thành phần kế thừa và bổ sung thêm các thành phần mới.

Có những loại kế thừa sau trong Python:

  • Single inhetitance: lớp con có tất cả các member của lớp cha
  • Multi-level inheristance: lóp con d1 kế thừa từ lớp cha b1, và d2 kế thừa từ lớp cha b2
  • Hierarchical inheritance: khi nhiều lớp con được định nghĩa từ một lớp cha
  • Multiple inheritance: lớp con được định nghĩa từ nhiều lớp cha.

12/ Đa hình (polymorphism) trong Python là gì?

Tính đa hình (polymorphism) là khái niệm mà hai hoặc nhiều lớp có những phương thức giống nhau nhưng có thể thực thi theo những cách thức khác nhau.

13/ Sự khác nhau giữa hàm range() và xrange()

Hàm Range() và Xrange() là hai hàm gần như tương tự nhau về chức năng. Chúng đều được dùng để tạo danh sách các số nguyên. Điều khác biệt là hàm rang() trả về một Python list object trong khi đó xrange() trả về xrange object. Điều đó có nghĩa hàm xrange() không tạo ra danh sách tĩnh trong quá trình thực thi như hàm range. Thay vào đó xrange tạo ra các giá trị với kỹ thuật gọi là yielding. Kỹ thuật này được dùng với một kiểu object gọi là generator.

14/ Giải thích sự khác nhau giữa Flask và Django

Django là một mã nguồn mở Python web framework, cho phép phát triển nhanh và hiệu quả. Nó chạy nhanh, bảo mật và có thể mở rộng. Django có được sự hỗ trợ mạnh mẽ từ cộng đồng và nhiều tài liệu tham khảo. Một số công ty như Instagram, Dropbox, Pinterest, Spotify… sử dụng Django để phát triển các sản phẩm của họ.

Flask được xem là một microframework, là một web framework ở mức tối thiểu. Flask thiếu nhiều chức năng so với Django như temple engine, account authorization, and authentication

Xem thêm chi tiết về sự khác nhau giữa Django và Flask framework

15/ PYTHONPATH là gì và sử dụng khi nào?

PYTHONPATH là biến môi trường và được sử dụng khi một module được import.

16/ PEP 8 là gì?

PEP viết tắt của Python Enhancement Proposal, là quy tắt coding (coding convention). Đây là một tập hợp các quy tắt được đặt ra giúp định dạng Python code một cách dễ đọc nhất

17/ Python decorators là gì?

Một decorator là một design pattern trong Python cho phép lập trình viên Python thêm các tính năng vào các object đang có mà không làm thay đổi cấu trúc. Decorator thường được gọi trước một hàm mà bạn muốn mở rộng hay thay đổi (decorate). 

18/ Init là gì?

_init_ là một method hay constructor trong Python. Method này được gọi một cách tự động để cấp bộ nhớ khi một object/instance của một lớp được tạo. Tất cả các lớp (class) đềi có _init_ method.

19/Toán tử ternary  là gì?

Toán tử ternary (ternary operator) là cách viết các lệnh có điều kiện trong Python. Nói một cách đơn giản, ternary operator là một phiên bản đơn giản của câu lệnh if-else.  Toán tử Python này bao gồm 3 toán hạng (operand):

[on true] if [expression] else [on false]

Nếu expression là True, câu lệnh trong [on true] được thực thi. Ngược lại  [on false] sẽ được thực thi.

Ví dụ dưới đây cho thấy sự khác nhau khi dùng If-else và khi dùng toán tử Ternary

# USING TERNARY OPERATOR
to_check = 6
msg = "Even" if to_check%2 == 0 else "Odd"
print(msg)
# USING USUAL IF-ELSE
msg = ""
if(to_check%2 == 0):
msg = "Even"
else:
msg = "Odd"
print(msg)

20/Local và global variables trong Python là gì?

Global variables: Các biến được khai báo bên ngoài hàm hoặc trong vùng global. Các biến này được truy cập bởi tất cả các hàm trong chương trình

Local variables: Các biến được khai báo bên trong một hàm. Biến này chỉ hiện diện trong khu vực cục bộ (local space).

21/ Trong Python @property là gì?

Trong Python, @property là một decorator. Mục đích chính của các decorator là thay đổi các phương thức, thuộc tính class sao cho không cần thực hiện bất kỳ thay đổi nào trong code. Để hiểu chi tiết về syntax, cách sử dụng bạn có thể xem tại đây

22/ Try/except được sử dụng thế nào trong Python?

Một ngoại lệ (exception) là một error xảy ra khi chương trình được thực thi. Khi lỗi xuất hiện, chương trình sẽ ngưng và tạo ra một ngoại lệ để ngăn không cho toàn bộ chương trình bị hỏng (crash)

Các ngoại lệ được tạo ra bởi chương trình được giữ trong try block và được xử lý trong except block.

Bạn có thể xem đầy đủ về Try và Except tại link này

23/ Python 2.7.x và Python 3.x khác nhau thế nào?

Bạn có thể tìm thấy sự khác nhau giữa Python 2.7.x và 3.x trên blog của Sebastian Raschka, một machine learning researcher, người đã viết cuốn Python Machine Learning bán chạy nhất trên Amazon.

24/ Join method trong Python là gì và method này hoạt động thế nào?

Pythonvmethod là một string method. Method này nối các chuỗi hay các thành phần lại với nhau dùng một giá trị kết nối.

100 câu hỏi viết mã python hàng đầu năm 2022

Một ví dụ về Python join() method:

list = [“my”, “name”, “is”, “Python”]
” “.join(list)

trong đó ” ” (khoảng trắng) là giá trị kết nối (connector value)

Out put sẽ là:

‘my name is Python’

26/ Dictionary comprehension là gì?

Dict (Dictionary)  là một container như List, Tuple. Tuy nhiên có điều khác biệt là những container như List, Tuple có các index để phân biệt các phần tử thì Dict dùng các key để phân biệt.

Dictionary comprehension là một cách để tạo dictionary trong Python. Nó tạo ra một dictionary bằng cách hợp nhất hai tập dữ liệu dưới định dạng list hay arrays.

Dữ liệu trong một trong hai danh sách hoặc dãy sẽ đóng vai trò là các key của dictionary trong khi dữ liệu của danh sách hay dãy còn lại sẽ là các giá trị. Như vậy kích thước của cả hai list hay array phải bằng nhau.

Ở đây chúng ta đang đề cập đến việc hợp nhất đơn giản, tức việc hợp nhất hai danh sách mà không có giới hạn nào. Nói một cách khác, đây là sự hợp nhất không có điều kiện (unconditional merging)

Cú pháp sử dụng như sau:

100 câu hỏi viết mã python hàng đầu năm 2022

Ví dụ về cách sử dụng Dictionary comprehension.

Hãy xem một CSDL của một trường có chứa rất nhiều data về các sinh viên: địa chỉ, tên, mã số SV, học phí.. Việc của chúng ta là xác định từng sinh viên cụ thể và tạo một dictionary lưu trữ duy nhất tên các sinh viên. Để thực hiện được việc này cần xác định đâu là key và đâu là value.

Trong trường hợp này chọ Mã số SV là key và tên là value vì mã số SV không trùng lắp. Đoạn code sẽ như sau:

MasoSV =[122,233,353,456]

Ten = [‘Minh’,’Toan’,’My’, ‘Viet’]

NewDictionary={ i:j for (i,j) in zip (MasoSV,ten)}

print(NewDictionary)

Output:

{356: ‘viet’, 234: ‘toan’, 124: ‘minh’, 253: ‘my’}

27/ Deep copy là gì trong Python?

Deep copy khi được sử dụng sẽ tạo ra object mới với độc lập với object gốc. Mọi thay đổi object chứa trong sẽ không ảnh hưởng đến nhau. Nó khác với việc chúng ta dùng  toán tử “=” vì toán tử này chỉ tạo ra một biến mới chia sẻ tham chiếu của object ban đầu.

Cú pháp deepcopy():

100 câu hỏi viết mã python hàng đầu năm 2022

28/ Làm thế nào để kiểm tra xem một key đã có trong một dictionary hay chưa?

Bạn có thể kiểm tra xem key đã có trong dictionary chưa trước khi trích xuất giá trị (value) của key đó. Python chung cấp cho bạn 2 chức năng để thực hiện việc này:

  • Hàm has_key()

Hàm has_key trả về true nếu key đã có trong dictionary. Ngược lại kết quả là false. Ví dụ:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
key_to_lookup = 'a'
if Fruits.has_key(key_to_lookup):
print "Key exists"
else:
print "Key does not exist"

Output: Key đã có

  • Câu lệnh if-in

Cách này sử dụng câu lệnh if-in để kiểm tra xem key đã có hay chưa trong dictionary:

This approach uses the if-in statement to check whether or not a given key exists in the dictionary.

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
key_to_lookup = 'a'
if key_to_lookup in Fruits:
print "Key exists"
else:
print "Key does not exist"

Output: Key đã có

29/Làm thế nào để thực hiện tối ưu hóa (memoization) trong Python?

Memoization là cách caching kết quả khi một hàm được gọi.  Để trả lời tốt câu hỏi này, bạn có thể tham khảo đến một bài viết về memoization trong Python với ví dụ về tính đệ quy (recursion). Ví dụ này rất rõ ràng về cách mà Python memoization hoạt động.

30/ Làm thế nào để sort một dictionary trong Python?

Để sort một dictionary theo giá trị (value) trong Python bạn có thể dùng chức năng sorted() . Chức năng này cũng có thể dùng để sort các list, tuple và dictionary. sorted() dùng 3 arguments (đối số): object, key và reverse.

31/ Khi nào và làm thể nào để dùng hàm any() và hàm all () trong Python?

Hàm any()  là hàm có thể kiểm tra các itetable (như list, tuple, set..) và trả về True nếu có bất kỳ phần tử nào là True, ngược lại sẽ trả về False. Nếu bạn chưa hiểu iterable là gì thì Iterable object là 1 object mà bạn có thể dùng for loop để access từng element của nó. Object có thể là indexable (sequence) hoặc non-indexable (dict, set, etc.)… Tham số hàm any() chính là các iterable.

Hàm all() là một hàm khác của Python kiểm tra các iterable và trả về True nếu tất cả các phần tử là True, ngược lại sẽ trả về False. Tương tự như any(), hàm all() có tham số là bất lỳ iterable (set, list, dictionary…)

32/ Python Docstring là gì?

Để hiểu docstring và trả lời đúng câu hỏi này trong các buổi phỏng vấn hãy tìm hiểu về cú pháp của một hàm trong Python:

def function_name(parameters):
	"""docstring"""
	statement(s)

Trong đó:

  • Từ khóa def đánh dấu sự bắt đầu của tiêu đề hàm.
  • function_name: Là định danh duy nhất dành cho hàm. Việc đặt tên hàm phải tuân thủ theo quy tắc viết tên và định danh trong Python.
  • Các tham số/đối số: truyền giá trị cho hàm thông qua các tham số này. Đây là các tùy chọn.
  • Dấu hai chấm (:) đánh dấu sự kết thúc của tiêu đề hàm.
  • docstring: Chuỗi văn bản tùy chọn để mô tả chức năng của hàm.
  • Các câu lệnh: Một hoặc nhiều lệnh Python hợp lệ tạo thành khối lệnh. Các lệnh này phải có cùng một mức thụt đầu dòng (thường là 4 khoảng trắng).
  • Lệnh return: Lệnh này là tùy chọn, dùng khi cần trả về giá trị từ hàm.

Như vậy cú pháp trên ta đã hiểu được ý nghĩa của docstring. docstring là không bắt buộc, nhưng việc bạn giải thích ngắn gọn về chức năng của hàm sẽ giúp người khác, thậm chí là bạn, khi gọi hàm có thể hiểu ngay hàm sẽ làm gì mà không cần phải tìm lại định nghĩa hàm để xem xét. Docstring được dùng để mô tả hàm dùng để làm gì chứ không phải hàm hoạt động thế nào. 

Bạn có thể xem thêm về hàm và cách sử dụng docstring tại đây

33/ Giải thích sự khác nhau giữa Generator và Iterator trong Python

Để hiểu tường tận bạn có thể tìm hiểu trong bài viết được đăng trên Medium. Bài viết giải thích khá chi tiết về Generator và Iterator cùng sự khác nhau giữa chúng

34/ Defaultdict trong Python là gì?

Trong Python dictionary, dict, chứa các cặp key-value của các kiểu dữ liệu. Vậy sự khác biệt giữa dict và defaultdict là gì?

Defaultdict là một  phân khu (subdivision) của dict class. Defaultdict cho phép key được gán một giá trị mặc định dựa trên kiểu dictionary được tạo. Một defaultdict được tạo bằng cách khai báo cho nó một argument có một trong 3 giá trị: list, set hoặc int. Dictionary được tạo tùy thuộc vào kiểu dữ liệu được đặc tả. Khi bất kỳ một key không hiện hữu trong defaultdict được thêm vào hoặc truy cập nó sẽ được gán một giá trị mặc định thay vì trả về KeyError.

Ví dụ đoạn code sau sẽ trả về error khi một key không tồn tại trong dict khi được truy cập:

dict_demo = dict()
print(dict_demo[3])

Bây giờ hãy xem một defaultdict và xem chuyện gì sẽ xãy ra

from collections import defaultdict
defaultdict_demo = defaultdict(int)
print(defaultdict_demo[3])

Kết quả: 0

Trong trường hợp này ta đã truyền kiểu dữ liệu int vào defaultdict. Khi có bất kỳ key nào không tồn tại trong defaultdict_demo nó sẽ được gán một giá trị là 0 trừ khi một giá trị khác được gán cho nó.

Bạn có thể tìm hiểu thêm về Defaultdict trên blog này

35/ Python Module là gì?

Một Python module là một file chứa các lớp, hàm và biến được sử dụng cho các ứng dụng. Biến có thể là arrays, dictionary, object… Module có thể có sẵn (built-in) hoặc do người dùng định nghĩa. Một số lợi ích của module trong Python:

  • Khả năng tái sử dụng: Module có thể được sử dụng ở trong phần Python code khác, do đó làm tăng tính tái sử dụng code.

  • Khả năng phân loại: Các kiểu thuộc tính tương tự nhau có thể được đặt trong một Module.

36/ Sự khác nhau giữa “is” và “==”?

Có nhiều người nhầm lẫn cho rằng “is” và “==” là một. Tuy nhiên hai toán tử này là khác nhau. is dùng để kiểm tra tính đồng nhất (identity) và == checks trạng thái bằng nhau (equality)

Lấy ví dụ bằng cách tạo các danh sách và gán tên:

a = [1,2,3]
b = a
c = [1,2,3]

Kiểm tra và chú ý là cả 3 đều bằng nhau:

print(a == b)
print(a == c)
#=> True
#=> True

Tuy nhiên các danh sách này là không đồng nhất:

print(a is b)
print(a is c)
#=> True
#=> False

Có thể kiểm tra bằng cách in các object id:

print(id(a))
print(id(b))
print(id(c))
#=> 4369567560
#=> 4369567560
#=> 4369567624

cid khác ab.

37/ Giải thích sự khác nhau giữa instance, static và class methods trong python?

Instace method, class method, static method là những khái niệm rất cơ bản trong lập trình hướng đối tượng với Python. Hiểu rõ những method này không chỉ giúp bạn trả lời tốt trong các buổi phỏng vấn Python mà còn giúp bạn code tốt hơn trong thực tế.

Bạn có thể xem bài viết về instance, static và class methods trên Medium hoặc một bài viết khác trên blog này

38/Sự khác nhau giữa “func” và “func()” trong Python?

Mục đích của câu hỏi này trong các buổi phỏng vấn Python là để xem bạn có hiểu về các hàm và đối tượng (objects) trong Python hay không

def func():
print('Im a function')

func
#=> function __main__.func>

func()
#=> Im a function

Trong đoạn code trên, func là object đại diện cho hàm và có thể gán một biến hoặc có thể truyền qua một hàm khác. Func() với dấu ngoặc gọi các hàm và trả về các kết quả

39/Hàm map hoạt động thế nào trong Python?

Hàm map có tác dụng duyệt qua tất cả các phần tử của một hoặc nhiều list, dictionary hoặc tương tự , sử dụng đơn giản với cú pháp như sau:

map(function, iterable1, iterable2 ,…)

  • function là hàm xử lý logic qua mỗi lần lặp giá trị trong interable1, ……
  • interable1, interable2 là các list, dict ,…  cần lặp.

Hàm map sẽ trả về một map object chứa các kết quả sau khi thực thi.

40/ Hàm reduce trong Python hoạt động thế nào?

Câu hỏi này có thể khiến bạn bị nhầm lẫn trong các buổi phỏng vấn về Python nếu chưa bao giờ dùng hàm reduce này.

Hàm reduce() chấp nhận một hàm và một chuỗi, trả về một giá trị được tính toán như sau:

  • Đầu tiên hàm sẽ được gọi với 2 phần tử đầu tiên trong chuỗi và trả về kết quả xử lý
  • Hàm tiếp tục được gọi với kết quả lần gọi trước đó và giá trị tiếp theo trong chuỗi. Quy trình này được tiếp tục cho đến khi tất cả các phần tử trong chuổi được xử lý.

Cú pháp của hàm reduce():

reduce(function, sequence[, initial]) -> value

Trong trường hợp giá trị initial được cung cấp, hàm sẽ được gọi với giá trị này cùng với phần tử đầu tiên trong sequence.

41/ Giải thích cách hoạt động của hàm Filter trong Python

Hàm này khá đơn giản và dễ hiểu nhưng thường nằm trong danh sách các câu hỏi phỏng vấn Python. Tên của hàm đã giải thích cách hoạt động của nó. Hàm sẽ lọc ra các phần tử trong chuỗi. Mỗi phần tử sẽ được truyền qua một hàm và sẽ đưa vào một chuổi kết quả nếu hàm trả về là True. Ngược lại sẽ bỏ qua nếu kết quả trả về là False

def add_three(x):
if x % 2 == 0:
return True
else:
return False
li = [1,2,3,4,5,6,7,8][i for i in filter(add_three, li)]
#=> [2, 4, 6, 8]

Trong ví dụ trên, chuỗi kết quả trả về là những số chia hết cho 2. Các số còn lại đã bị loại bỏ.

42/ Lookup một giá trị trong dictionary và list cái nào nhanh hơn?

Lookup một giá trị trong danh sách cần thời gian O(n) vì toàn bộ danh sách sẽ được duyệt cho đến khi tìm ra giá trị

Lookup một khóa trong dictionary cần O(1) vì đó là một bảng hash.

Như vậy thời gian lookup có thể rất khác nhau nếu có nhiều giá trị và dictionary thường được sử dụng để tăng tốc độ. Tuy nhiên dictionary cũng có các giới hạn như cần các khóa duy nhất.

43/ Hiệu ứng Dogpile là gì? Làm thế nào để ngăn ngừa?

Hiệu ứng Dogpile là một sự kiện (event) xảy ra khi bộ nhớ đệm (cache) đã hết hiệu lực (expire) và các website có rất nhiều yêu cầu truy cập đồng thời từ các client. Điều này có thể gây ra nhiều vấn đề khác nhau, từ độ trễ đột ngột đến xảy ra sự cố hoàn toàn. Hiệu ứng này có thể ngăn ngừa bằng cách dùng khóa semaphore. Trong hệ thống này khi một giá trị hết hiệu lực, process đầu tiên giữ khoa và tạo ra giá trị mới

44/ Đóng gói (Encapsulation) là gì trong Python?

Tính đóng gói (encapsulation) là một trong những nguyên lý cơ bản trong lập trình hướng đối tượng (Object-oriented programming) trong Python. Với encapsulation, trạng thái bên trong của một đối tượng được bảo vệ khỏi sự truy cập được từ  bên ngoài. Điều đó có nghĩa code bên ngoài không thể trực tiếp nhìn thấy và thay đổi trạng thái của đối tượng.

45/ Index âm (negative indexes) là gì và tại sao chúng được dùng?

Đây là một câu hỏi bạn có thể nghĩ là đơn giản trong phỏng vấn Python, tuy nhiên không phải ai cũng trả lời đúng

Chúng ta đều biết index (chỉ mục) được dùng trong các mảng (arrays) trong tất cả các ngôn ngữ lập trình. Tuy nhiên, chỉ có Python là cho phép sử dụng index âm trong arrays.

Để truy cập một phần tử trong chuỗi , chúng ta chỉ đơn giản là dùng index của phần tử, là số dương. Thông thường một index bắt đầu bằng 0 tức phần tử đầu tiên có index là 0, phần tử thứ hai có index là …

Khi bạn dùng index để truy xuất các phần tử từ cuối danh sách, nó được gọi là reverse indexing (chỉ mục đảo). Trong chỉ mục đảo, các chỉ mục của các phần tử sẽ bắt đầu từ phần tử cuối cùng với số index là ‘-1’. Phần tử kế cuối sẽ là -2 và cứ thế tiếp tục. Các index dùng trong reverse indexing được gọi lá các index âm.

46/ Bạn biết gì về Palindrome và làm thế nào để kiểm tra chuỗi nhập vào có phải làm một Palindrome trong Python?

Palindrome là một số nguyên tố mà bạn viết xuôi hay viết ngược đều chi cho ra một số. Ví dụ số 131.

Để kiểm tra chuỗi nhập vào có phải là một Palindrome trong Python ta có thể dùng đoạn code dơn giản sau:

my_string=input("Enter string:")
if(my_string==my_string[::-1]):
   print("The string is a palindrome")
else:
   print("The string isn't a palindrome")

Giải thích:

  • Bước 1: nhập chuỗi, ví dụ 131
  • Bước 2: Dùng string slicing đảo ngược chuỗi và so sánh với chuỗi nguyên thủy
  • Bước 3: Hiển thị kết quả

47/ Namespace là gì? Cách sử dụng namespace trong Python?

Một namspace (không gian tên) là một từ khóa trong Python được dùng để đảm bảo tên của các object là duy nhất và có thể dùng mà không bị đụng độ. Trong Python, các namspace được duy trì dưới dạng các tự điển Python với tên là key được map các giá trị chính là các object. Điều này cho phép có nhiều namspace được phép trùng tên và map vào các object khác nhau. Có các loại namesapce:

  • Namespace cục bộ (local) là các tên bên trong một hàm. Namespace này được tạo một cách tạm thời phục vụ cho việc gọi hàm và sẽ bị loại bỏ khi kết quả được trả về
  • Namespace toàn cục (global) là các tên trong các gói hay module được tạo khi gói được tạo trong script và sẽ kết thúc khi thực thi script đó
  • Namespace tích hợp (built-in) bao gồm các hàm được tích hợp sẵn trong Python và các tên có sẵn trong các kiểu exception khác nhau

Vòng đời của namespace (Lifecycle of a namespace) phụ thuộc vào phạm vi của đối tượng mà nó được map vào. Nếu phạm vi của đối tượng kết thúc thì thời gian tồn tại của namespace đó cũng kết thúc. Do đó, không thể truy cập các đối tượng bên trong namespace (inner namespace) từ một namespace bên ngoài (outer namespace).

100 câu hỏi viết mã python hàng đầu năm 2022
Các loại namespace trong Python

48/ Phạm vi (scope) trong Python là gì?

Mỗi đối tượng trong các hàm Python đều nằm trong một phạm vi (scope). Một phạm vi là một khối mã lệnh (block of code) liên quan đến một đối tượng. Một số phạm vi được tạo trong khi thực thi code trong Python: Phạm vi cục bộ (local scope), Phạm vi toàn cục (global scope), phạm vi ở mức module (module level scope), phạm vi ngoài cùng (outermost scope)

49/ Kiểm tra mức đơn vị (Unittest) là gì trong Python? 

  • Unit test – Kiểm thử mức đơn vị là một mức kiểm thử phần mềm với mục đích dùng để kiểm tra kiến trúc nội tại của chương trình. Đây là mức kiểm tra nhỏ nhất trong quy trình kiểm thử phần mềm.
  • Unit – Đơn vị phần mềm là một thành phần nhỏ nhất mà ta có thể kiểm tra được, các hàm (function), thủ tục (procedure), lớp (class), hoặc các phương thức (method) đều có thể được xem là Unit.
  • Unit test thường do lập trình viên thực hiện. Được chạy để kiểm tra mã nguồn của các chương trình, các chức năng riêng rẽ hoạt động đúng hay không. Unit test thường được chạy mỗi khi xây dựng và chạy thử nghiệm để đảm bảo các hàm đều chạy đúng sau khi ta sửa code.
  • Unit test đòi hỏi phải chuẩn bị trước các tình huống (test case) hoặc kịch bản (script), trong đó chỉ định rõ dữ liệu vào, các bước thực hiện và dữ liệu mong chờ sẽ xuất ra.
  • Việc viết unit test trong Python khá đơn giản, cách thông dụng nhất là sử dụng package unittest có sẵn trong standard library.
  • Module unittest cung cấp tập hợp các công cụ phong phú cho việc xây dựng và chạy thử nghiệm.

50/ Hàm help() và dir() được dùng làm gì trong Python?

Hàm Help() và dir() là hai hàm được truy xuất trong quá trình biên dịch (interpreter) chương trình Python và được dùng để xem thông tin, thuộc tính của các hàm xây dựng sẵn:

  • Hàm Help(): dùng để hiển thị các tài liệu và hệ thống trợ giúp của các module, hàm, lớp, từ khóa…
  • Hàm dir(): dùng để hiển thị các ký hiệu được định nghĩa trước (defined symbols)

Kết luận

Trên đây là 50 câu hỏi thông dụng thường gặp trong các cuộc phỏng vấn về Python. Dù bạn có là người có nhiều kinh nghiệm hay chỉ mới mới tập làm quen với Python, chuẩn bị kỹ cho một buổi phỏng vấn không bao giờ là thừa. 50 câu hỏi trên đây không phải là tất cả mọi kiến thức về Python bạn cần biết cho một buổi phỏng vấn mà chỉ là các câu hỏi thường gặp. Bạn cần có sự chuẩn bị thật chu đáo.

Bạn có biết?


tham gia cộng đồng ITguru trên Linkedin, Facebook và các kênh mạng xã hội khác có thể giúp bạn nhanh chóng tìm được những chủ đề phát triển nghề nghiệp và cập nhật thông tin về việc làm IT mới nhất

Linkedin Page: https://bit.ly/LinkedinITguru
Facebook Group: https://bit.ly/ITguruvn
cơ hội việc làm IT : ITguru.vn

100+ Python challenging programming exercises 1. Level description Level Description Level 1 Beginner means someone who has just gone through an introductory Python course. He can solve some problems with 1 or 2 Python classes or functions. Normally, the answers could directly be found in the textbooks. Level 2 Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He should be able to solve problems which may involve 3 or 3 Python classes or functions. The answers cannot be directly be found in the textbooks. Level 3 Advanced. He should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques. 2. Problem template #----------------------------------------# Question Hints Solution 3. Questions #----------------------------------------# Question 1 Level 1 Question: Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: Consider use range(#begin, #end) method Solution: l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) #----------------------------------------# #----------------------------------------# Question 2 Level 1 Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: def fact(x): if x == 0: return 1 return x * fact(x - 1) x=int(raw_input()) print fact(x) #----------------------------------------# #----------------------------------------# Question 3 Level 1 Question: With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. Suppose the following input is supplied to the program: 8 Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict() Solution: n=int(raw_input()) d=dict() for i in range(1,n+1): d[i]=i*i print d #----------------------------------------# #----------------------------------------# Question 4 Level 1 Question: Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12,98 Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98') Hints: In case of input data being supplied to the question, it should be assumed to be a console input. tuple() method can convert list to tuple Solution: values=raw_input() l=values.split(",") t=tuple(l) print l print t #----------------------------------------# #----------------------------------------# Question 5 Level 1 Question: Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods. Hints: Use __init__ method to construct some parameters Solution: class InputOutString(object): def __init__(self): self.s = "" def getString(self): self.s = raw_input() def printString(self): print self.s.upper() strObj = InputOutString() strObj.getString() strObj.printString() #----------------------------------------# #----------------------------------------# Question 6 Level 2 Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 Hints: If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26) In case of input data being supplied to the question, it should be assumed to be a console input. Solution: #!/usr/bin/env python import math c=50 h=30 value = [] items=[x for x in raw_input().split(',')] for d in items: value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print ','.join(value) #----------------------------------------# #----------------------------------------# Question 7 Level 2 Question: Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Note: i=0,1.., X-1; j=0,1,¡­Y-1. Example Suppose the following inputs are given to the program: 3,5 Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] Hints: Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. Solution: input_str = raw_input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] colNum=dimensions[1] multilist = [[0 for col in range(colNum)] for row in range(rowNum)] for row in range(rowNum): for col in range(colNum): multilist[row][col]= row*col print multilist #----------------------------------------# #----------------------------------------# Question 8 Level 2 Question: Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) #----------------------------------------# #----------------------------------------# Question 9 Level 2 Question£º Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: lines = [] while True: s = raw_input() if s: lines.append(s.upper()) else: break; for sentence in lines: print sentence #----------------------------------------# #----------------------------------------# Question 10 Level 2 Question: Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use set container to remove duplicated data automatically and then use sorted() to sort the data. Solution: s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) #----------------------------------------# #----------------------------------------# Question 11 Level 2 Question: Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. Example: 0100,0011,1010,1001 Then the output should be: 1010 Notes: Assume the data is input by console. Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: value = [] items=[x for x in raw_input().split(',')] for p in items: intp = int(p, 2) if not intp%5: value.append(p) print ','.join(value) #----------------------------------------# #----------------------------------------# Question 12 Level 2 Question: Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: values = [] for i in range(1000, 3001): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) print ",".join(values) #----------------------------------------# #----------------------------------------# Question 13 Level 2 Question: Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: if c.isdigit(): d["DIGITS"]+=1 elif c.isalpha(): d["LETTERS"]+=1 else: pass print "LETTERS", d["LETTERS"] print "DIGITS", d["DIGITS"] #----------------------------------------# #----------------------------------------# Question 14 Level 2 Question: Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. Suppose the following input is supplied to the program: Hello world! Then, the output should be: UPPER CASE 1 LOWER CASE 9 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: s = raw_input() d={"UPPER CASE":0, "LOWER CASE":0} for c in s: if c.isupper(): d["UPPER CASE"]+=1 elif c.islower(): d["LOWER CASE"]+=1 else: pass print "UPPER CASE", d["UPPER CASE"] print "LOWER CASE", d["LOWER CASE"] #----------------------------------------# #----------------------------------------# Question 15 Level 2 Question: Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. Suppose the following input is supplied to the program: 9 Then, the output should be: 11106 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: a = raw_input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) n3 = int( "%s%s%s" % (a,a,a) ) n4 = int( "%s%s%s%s" % (a,a,a,a) ) print n1+n2+n3+n4 #----------------------------------------# #----------------------------------------# Question 16 Level 2 Question: Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1,2,3,4,5,6,7,8,9 Then, the output should be: 1,3,5,7,9 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: values = raw_input() numbers = [x for x in values.split(",") if int(x)%2!=0] print ",".join(numbers) #----------------------------------------# Question 17 Level 2 Question: Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: D 100 W 200 D means deposit while W means withdrawal. Suppose the following input is supplied to the program: D 300 D 300 W 200 D 100 Then, the output should be: 500 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: netAmount = 0 while True: s = raw_input() if not s: break values = s.split(" ") operation = values[0] amount = int(values[1]) if operation=="D": netAmount+=amount elif operation=="W": netAmount-=amount else: pass print netAmount #----------------------------------------# #----------------------------------------# Question 18 Level 3 Question: A website requires the users to input username and password to register. Write a program to check the validity of password input by users. Following are the criteria for checking the password: 1. At least 1 letter between [a-z] 2. At least 1 number between [0-9] 1. At least 1 letter between [A-Z] 3. At least 1 character from [$#@] 4. Minimum length of transaction password: 6 5. Maximum length of transaction password: 12 Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. Example If the following passwords are given as input to the program: ABd1234@1,a F1#,2w3E*,2We3345 Then, the output of the program should be: ABd1234@1 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solutions: import re value = [] items=[x for x in raw_input().split(',')] for p in items: if len(p)<6 or len(p)>12: continue else: pass if not re.search("[a-z]",p): continue elif not re.search("[0-9]",p): continue elif not re.search("[A-Z]",p): continue elif not re.search("[$#@]",p): continue elif re.search("\s",p): continue else: pass value.append(p) print ",".join(value) #----------------------------------------# #----------------------------------------# Question 19 Level 3 Question: You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: 1: Sort based on name; 2: Then sort based on age; 3: Then sort by score. The priority is that name > age > score. If the following tuples are given as input to the program: Tom,19,80 John,20,90 Jony,17,91 Jony,17,93 Json,21,85 Then, the output of the program should be: [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use itemgetter to enable multiple sort keys. Solutions: from operator import itemgetter, attrgetter l = [] while True: s = raw_input() if not s: break l.append(tuple(s.split(","))) print sorted(l, key=itemgetter(0,1,2)) #----------------------------------------# #----------------------------------------# Question 20 Level 3 Question: Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. Hints: Consider use yield Solution: def putNumbers(n): i = 0 while ilen2: print s1 elif len2>len1: print s2 else: print s1 print s2 printValue("one","three") #----------------------------------------# 2.10 Question: Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number". Hints: Use % operator to check if a number is even or odd. Solution def checkValue(n): if n%2 == 0: print "It is an even number" else: print "It is an odd number" checkValue(7) #----------------------------------------# 2.10 Question: Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Solution def printDict(): d=dict() d[1]=1 d[2]=2**2 d[3]=3**2 print d printDict() #----------------------------------------# 2.10 Question: Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i**2 print d printDict() #----------------------------------------# 2.10 Question: Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i**2 for (k,v) in d.items(): print v printDict() #----------------------------------------# 2.10 Question: Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i**2 for k in d.keys(): print k printDict() #----------------------------------------# 2.10 Question: Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li printList() #----------------------------------------# 2.10 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[:5] printList() #----------------------------------------# 2.10 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[-5:] printList() #----------------------------------------# 2.10 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[5:] printList() #----------------------------------------# 2.10 Question: Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use tuple() to get a tuple from a list. Solution def printTuple(): li=list() for i in range(1,21): li.append(i**2) print tuple(li) printTuple() #----------------------------------------# 2.10 Question: With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. Hints: Use [n1:n2] notation to get a slice from a tuple. Solution tp=(1,2,3,4,5,6,7,8,9,10) tp1=tp[:5] tp2=tp[5:] print tp1 print tp2 #----------------------------------------# 2.10 Question: Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). Hints: Use "for" to iterate the tuple Use tuple() to generate a tuple from a list. Solution tp=(1,2,3,4,5,6,7,8,9,10) li=list() for i in tp: if tp[i]%2==0: li.append(tp[i]) tp2=tuple(li) print tp2 #----------------------------------------# 2.14 Question: Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". Hints: Use if statement to judge condition. Solution s= raw_input() if s=="yes" or s=="YES" or s=="Yes": print "Yes" else: print "No" #----------------------------------------# 3.4 Question: Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. Hints: Use filter() to filter some elements in a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = filter(lambda x: x%2==0, li) print evenNumbers #----------------------------------------# 3.4 Question: Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] squaredNumbers = map(lambda x: x**2, li) print squaredNumbers #----------------------------------------# 3.5 Question: Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use filter() to filter elements of a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) print evenNumbers #----------------------------------------# 3.5 Question: Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions. Solution evenNumbers = filter(lambda x: x%2==0, range(1,21)) print evenNumbers #----------------------------------------# 3.5 Question: Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). Hints: Use map() to generate a list. Use lambda to define anonymous functions. Solution squaredNumbers = map(lambda x: x**2, range(1,21)) print squaredNumbers #----------------------------------------# 7.2 Question: Define a class named American which has a static method called printNationality. Hints: Use @staticmethod decorator to define class static method. Solution class American(object): @staticmethod def printNationality(): print "America" anAmerican = American() anAmerican.printNationality() American.printNationality() #----------------------------------------# 7.2 Question: Define a class named American and its subclass NewYorker. Hints: Use class Subclass(ParentClass) to define a subclass. Solution: class American(object): pass class NewYorker(American): pass anAmerican = American() aNewYorker = NewYorker() print anAmerican print aNewYorker #----------------------------------------# 7.2 Question: Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. Hints: Use def methodName(self) to define a method. Solution: class Circle(object): def __init__(self, r): self.radius = r def area(self): return self.radius**2*3.14 aCircle = Circle(2) print aCircle.area() #----------------------------------------# 7.2 Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. Hints: Use def methodName(self) to define a method. Solution: class Rectangle(object): def __init__(self, l, w): self.length = l self.width = w def area(self): return self.length*self.width aRectangle = Rectangle(2,10) print aRectangle.area() #----------------------------------------# 7.2 Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. Hints: To override a method in super class, we can define a method with the same name in the super class. Solution: class Shape(object): def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self, l): Shape.__init__(self) self.length = l def area(self): return self.length*self.length aSquare= Square(3) print aSquare.area() #----------------------------------------# Please raise a RuntimeError exception. Hints: Use raise() to raise an exception. Solution: raise RuntimeError('something wrong') #----------------------------------------# Write a function to compute 5/0 and use try/except to catch the exceptions. Hints: Use try/except to catch exceptions. Solution: def throws(): return 5/0 try: throws() except ZeroDivisionError: print "division by zero!" except Exception, err: print 'Caught an exception' finally: print 'In finally block for cleanup' #----------------------------------------# Define a custom exception class which takes a string message as attribute. Hints: To define a custom exception, we need to define a class inherited from Exception. Solution: class MyError(Exception): """My own exception class Attributes: msg -- explanation of the error """ def __init__(self, msg): self.msg = msg error = MyError("something wrong") #----------------------------------------# Question: Assuming that we have some email addresses in the "" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: Then, the output of the program should be: john In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use \w to match letters. Solution: import re emailAddress = raw_input() pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print r2.group(1) #----------------------------------------# Question: Assuming that we have some email addresses in the "" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: Then, the output of the program should be: google In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use \w to match letters. Solution: import re emailAddress = raw_input() pat2 = "(\w+)@(\w+)\.(com)" r2 = re.match(pat2,emailAddress) print r2.group(2) #----------------------------------------# Question: Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. Example: If the following words is given as input to the program: 2 cats and 3 dogs. Then, the output of the program should be: ['2', '3'] In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use re.findall() to find all substring using regex. Solution: import re s = raw_input() print re.findall("\d+",s) #----------------------------------------# Question: Print a unicode string "hello world". Hints: Use u'strings' format to define unicode string. Solution: unicodeString = u"hello world!" print unicodeString #----------------------------------------# Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. Hints: Use unicode() function to convert. Solution: s = raw_input() u = unicode( s ,"utf-8") print u #----------------------------------------# Question: Write a special comment to indicate a Python source code file is in unicode. Hints: Solution: # -*- coding: utf-8 -*- #----------------------------------------# Question: Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). Example: If the following n is given as input to the program: 5 Then, the output of the program should be: 3.55 In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use float() to convert an integer to a float Solution: n=int(raw_input()) sum=0.0 for i in range(1,n+1): sum += float(float(i)/(i+1)) print sum #----------------------------------------# Question: Write a program to compute: f(n)=f(n-1)+100 when n>0 and f(0)=1 with a given n input by console (n>0). Example: If the following n is given as input to the program: 5 Then, the output of the program should be: 500 In case of input data being supplied to the question, it should be assumed to be a console input. Hints: We can define recursive function in Python. Solution: def f(n): if n==0: return 0 else: return f(n-1)+100 n=int(raw_input()) print f(n) #----------------------------------------# Question: The Fibonacci Sequence is computed based on the following formula: f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1 Please write a program to compute the value of f(n) with a given n input by console. Example: If the following n is given as input to the program: 7 Then, the output of the program should be: 13 In case of input data being supplied to the question, it should be assumed to be a console input. Hints: We can define recursive function in Python. Solution: def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(raw_input()) print f(n) #----------------------------------------# #----------------------------------------# Question: The Fibonacci Sequence is computed based on the following formula: f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1 Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. Example: If the following n is given as input to the program: 7 Then, the output of the program should be: 0,1,1,2,3,5,8,13 Hints: We can define recursive function in Python. Use list comprehension to generate a list from an existing list. Use string.join() to join a list of strings. In case of input data being supplied to the question, it should be assumed to be a console input. Solution: def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(raw_input()) values = [str(f(x)) for x in range(0, n+1)] print ",".join(values) #----------------------------------------# Question: Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. Example: If the following n is given as input to the program: 10 Then, the output of the program should be: 0,2,4,6,8,10 Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input. Solution: def EvenGenerator(n): i=0 while i<=n: if i%2==0: yield i i+=1 n=int(raw_input()) values = [] for i in EvenGenerator(n): values.append(str(i)) print ",".join(values) #----------------------------------------# Question: Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. Example: If the following n is given as input to the program: 100 Then, the output of the program should be: 0,35,70 Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input. Solution: def NumGenerator(n): for i in range(n+1): if i%5==0 and i%7==0: yield i n=int(raw_input()) values = [] for i in NumGenerator(n): values.append(str(i)) print ",".join(values) #----------------------------------------# Question: Please write assert statements to verify that every number in the list [2,4,6,8] is even. Hints: Use "assert expression" to make assertion. Solution: li = [2,4,6,8] for i in li: assert i%2==0 #----------------------------------------# Question: Please write a program which accepts basic mathematic expression from console and print the evaluation result. Example: If the following string is given as input to the program: 35+3 Then, the output of the program should be: 38 Hints: Use eval() to evaluate an expression. Solution: expression = raw_input() print eval(expression) #----------------------------------------# Question: Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. Hints: Use if/elif to deal with conditions. Solution: import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index li=[2,5,7,9,11,17,222] print bin_search(li,11) print bin_search(li,12) #----------------------------------------# Question: Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. Hints: Use if/elif to deal with conditions. Solution: import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index li=[2,5,7,9,11,17,222] print bin_search(li,11) print bin_search(li,12) #----------------------------------------# Question: Please generate a random float where the value is between 10 and 100 using Python math module. Hints: Use random.random() to generate a random float in [0,1]. Solution: import random print random.random()*100 #----------------------------------------# Question: Please generate a random float where the value is between 5 and 95 using Python math module. Hints: Use random.random() to generate a random float in [0,1]. Solution: import random print random.random()*100-5 #----------------------------------------# Question: Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. Hints: Use random.choice() to a random element from a list. Solution: import random print random.choice([i for i in range(11) if i%2==0]) #----------------------------------------# Question: Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. Hints: Use random.choice() to a random element from a list. Solution: import random print random.choice([i for i in range(201) if i%5==0 and i%7==0]) #----------------------------------------# Question: Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. Hints: Use random.sample() to generate a list of random values. Solution: import random print random.sample(range(100), 5) #----------------------------------------# Question: Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. Hints: Use random.sample() to generate a list of random values. Solution: import random print random.sample([i for i in range(100,201) if i%2==0], 5) #----------------------------------------# Question: Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. Hints: Use random.sample() to generate a list of random values. Solution: import random print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) #----------------------------------------# Question: Please write a program to randomly print a integer number between 7 and 15 inclusive. Hints: Use random.randrange() to a random integer in a given range. Solution: import random print random.randrange(7,16) #----------------------------------------# Question: Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". Hints: Use zlib.compress() and zlib.decompress() to compress and decompress a string. Solution: import zlib s = 'hello world!hello world!hello world!hello world!' t = zlib.compress(s) print t print zlib.decompress(t) #----------------------------------------# Question: Please write a program to print the running time of execution of "1+1" for 100 times. Hints: Use timeit() function to measure the running time. Solution: from timeit import Timer t = Timer("for i in range(100):1+1") print t.timeit() #----------------------------------------# Question: Please write a program to shuffle and print the list [3,6,7,8]. Hints: Use shuffle() function to shuffle a list. Solution: from random import shuffle li = [3,6,7,8] shuffle(li) print li #----------------------------------------# Question: Please write a program to shuffle and print the list [3,6,7,8]. Hints: Use shuffle() function to shuffle a list. Solution: from random import shuffle li = [3,6,7,8] shuffle(li) print li #----------------------------------------# Question: Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. Hints: Use list[index] notation to get a element from a list. Solution: subjects=["I", "You"] verbs=["Play", "Love"] objects=["Hockey","Football"] for i in range(len(subjects)): for j in range(len(verbs)): for k in range(len(objects)): sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) print sentence #----------------------------------------# Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. Hints: Use list comprehension to delete a bunch of element from a list. Solution: li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print li #----------------------------------------# Question: By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. Hints: Use list comprehension to delete a bunch of element from a list. Solution: li = [12,24,35,70,88,120,155] li = [x for x in li if x%5!=0 and x%7!=0] print li #----------------------------------------# Question: By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. Hints: Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. Solution: li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print li #----------------------------------------# Question: By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0. Hints: Use list comprehension to make an array. Solution: array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] print array #----------------------------------------# Question: By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. Hints: Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. Solution: li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] print li #----------------------------------------# Question: By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. Hints: Use list's remove method to delete a value. Solution: li = [12,24,35,24,88,120,155] li = [x for x in li if x!=24] print li #----------------------------------------# Question: With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. Hints: Use set() and "&=" to do set intersection operation. Solution: set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) set1 &= set2 li=list(set1) print li #----------------------------------------# With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. Hints: Use set() to store a number of values without duplicate. Solution: def removeDuplicate( li ): newli=[] seen = set() for item in li: if item not in seen: seen.add( item ) newli.append(item) return newli li=[12,24,35,24,88,120,155,88,120,155] print removeDuplicate(li) #----------------------------------------# Question: Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. Hints: Use Subclass(Parentclass) to define a child class. Solution: class Person(object): def getGender( self ): return "Unknown" class Male( Person ): def getGender( self ): return "Male" class Female( Person ): def getGender( self ): return "Female" aMale = Male() aFemale= Female() print aMale.getGender() print aFemale.getGender() #----------------------------------------# Question: Please write a program which count and print the numbers of each character in a string input by console. Example: If the following string is given as input to the program: abcdefgabc Then, the output of the program should be: a,2 c,2 b,2 e,1 d,1 g,1 f,1 Hints: Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value. Solution: dic = {} s=raw_input() for s in s: dic[s] = dic.get(s,0)+1 print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) #----------------------------------------# Question: Please write a program which accepts a string from console and print it in reverse order. Example: If the following string is given as input to the program: rise to vote sir Then, the output of the program should be: ris etov ot esir Hints: Use list[::-1] to iterate a list in a reverse order. Solution: s=raw_input() s = s[::-1] print s #----------------------------------------# Question: Please write a program which accepts a string from console and print the characters that have even indexes. Example: If the following string is given as input to the program: H1e2l3l4o5w6o7r8l9d Then, the output of the program should be: Helloworld Hints: Use list[::2] to iterate a list by step 2. Solution: s=raw_input() s = s[::2] print s #----------------------------------------# Question: Please write a program which prints all permutations of [1,2,3] Hints: Use itertools.permutations() to get permutations of list. Solution: import itertools print list(itertools.permutations([1,2,3])) #----------------------------------------# Question: Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? Hint: Use for loop to iterate all possible solutions. Solution: def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): j=numheads-i if 2*i+4*j==numlegs: return i,j return ns,ns numheads=35 numlegs=94 solutions=solve(numheads,numlegs) print solutions #----------------------------------------#

Những câu hỏi quan trọng trong lập trình Python là gì?

Câu hỏi phỏng vấn Python cơ bản cho Freshers..
Q1. Sự khác biệt giữa danh sách và bộ dữ liệu trong Python là gì ?.
Q2. Các tính năng chính của Python là gì ?.
Q3. Python là loại ngôn ngữ nào? ....
Q4.Python một ngôn ngữ được giải thích. Giải thích..
Q5. PEP 8 là gì ?.
Q17. Bộ nhớ được quản lý như thế nào trong Python ?.
Q18. ....

Có dễ dàng để bẻ khóa phỏng vấn Python không?

Mức độ khó của các câu hỏi phỏng vấn mã hóa Python khác nhau tùy thuộc vào vị trí bạn đang ứng tuyển, công ty và kỹ năng và kiến ​​thức hoặc kinh nghiệm làm việc của bạn. Nếu bạn là người mới bắt đầu có kiến ​​thức cơ bản, bạn có thể thấy các câu hỏi phỏng vấn mã hóa Python khó khăn.If you are a beginner with basic knowledge, you might find Python coding interview questions difficult.

Làm thế nào để bạn bẻ khóa người kiểm tra mã Python?

Làm và không phải là cuộc phỏng vấn việc làm của nhà phát triển Python..
Có kiến thức cơ bản về dòng điều khiển của Python ..
Sử dụng danh sách hiểu ..
Hiểu các khái niệm về lập trình hướng đối tượng ..
Biết việc sử dụng máy phát điện ..
Thực hành mã viết trên giấy hoặc bảng trắng ..

Những loại câu hỏi mã hóa python nào được hỏi trong các cuộc phỏng vấn?

Câu hỏi phỏng vấn mã hóa Python..
Làm thế nào để bạn gỡ lỗi một chương trình Python ?.
Từ khóa trong Python là gì ?.
Làm thế nào để chuyển đổi một danh sách thành một chuỗi ?.
Làm thế nào để chuyển đổi một danh sách thành một tuple ?.
Làm thế nào để chuyển đổi một danh sách thành một bộ ?.
Làm thế nào để đếm các sự xuất hiện của một yếu tố cụ thể trong danh sách ?.
Mảng Numpy là gì?.