Программа на Python для отображения степени двойки: анонимная функция и альтернативные методы

Вот программа на Python, которая отображает степени 2 с помощью анонимной функции:

# Program to display powers of 2 using anonymous function
# Define the number of terms
terms = 10
# Use an anonymous function to calculate the power of 2
result = list(map(lambda x: 2  x, range(terms)))
# Display the result
print("Powers of 2 using anonymous function:")
for i in range(terms):
    print("2 raised to the power", i, "is", result[i])

Эта программа использует функцию map()вместе с анонимной лямбда-функцией для вычисления степеней 2. Она генерирует список степеней 2 от 2^0 до 2^(terms- 1), а затем печатает каждую степень вместе с соответствующим показателем.

Вот несколько альтернативных методов отображения степеней двойки:

Метод 1: использование цикла for

# Program to display powers of 2 using a for loop
# Define the number of terms
terms = 10
# Display the result
print("Powers of 2 using a for loop:")
for i in range(terms):
    print("2 raised to the power", i, "is", pow(2, i))

Метод 2: использование понимания списка

# Program to display powers of 2 using list comprehension
# Define the number of terms
terms = 10
# Use list comprehension to calculate the powers of 2
result = [2  i for i in range(terms)]
# Display the result
print("Powers of 2 using list comprehension:")
for i in range(terms):
    print("2 raised to the power", i, "is", result[i])

Метод 3. Использование цикла while

# Program to display powers of 2 using a while loop
# Define the number of terms
terms = 10
# Initialize variables
i = 0
result = []
# Calculate the powers of 2 using a while loop
while i < terms:
    result.append(2  i)
    i += 1
# Display the result
print("Powers of 2 using a while loop:")
for i in range(terms):
    print("2 raised to the power", i, "is", result[i])