Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

In lũy thừa dùng Anonymous Function (Lambda) trong Python


Ở đây dùng anonymous (lambda) function bên trong map() built-in. Trong Python, anonymous function định nghĩa không tên, dùng từ khóa lambda.

Thuật toán

Bước 1: Nhập n.
Bước 2: Nhập p.
Bước 3: Dùng anonymous function.
Bước 4: Hiển thị kết quả.

Ví dụ mã

# Hiển thị lũy thừa của số dùng anonymous function
n = int(input("Enter how many terms want to display??"))
p = int(input("Enter the number want to calculate power ::"))
# anonymous function
cal = list(map(lambda i: p ** i, range(n)))
# hiển thị kết quả
print("The total terms is ::>", n)
for j in range(n):
    print(p, "raised to power", j, "is", cal[j])

Kết quả

Enter how many terms want to display??10
Enter the number want to calculate power ::3
The total terms is ::> 10
3 raised to power 0 is 1
3 raised to power 1 is 3
3 raised to power 2 is 9
3 raised to power 3 is 27
3 raised to power 4 is 81
3 raised to power 5 is 243
3 raised to power 6 is 729
3 raised to power 7 is 2187
3 raised to power 8 is 6561
3 raised to power 9 is 19683