Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การยกกำลัง Tuple ด้วย Tuple อีกตัวใน Python

Raise Tuple Elements to Power of Another Tuple

เมื่อต้องการยกกำลัง Element ของ Tuple ตัวหนึ่ง ด้วย Element ของ Tuple อีกตัว (Index ตรงกัน) ใช้ zip() และ Generator Expression พร้อม Operator **

ตัวอย่างโค้ด

my_tuple_1 = (7, 8, 3, 4, 3, 2)
my_tuple_2 = (9, 6, 8, 2, 1, 0)

print("The first tuple is : ")
print(my_tuple_1)
print("The second tuple is : ")
print(my_tuple_2)

# zip จับคู่ แล้วยกกำลัง (base ** exponent)
my_result = tuple(elem_1 ** elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))

print("The tuple raised to power of another tuple is : ")
print(my_result)

ผลลัพธ์

The first tuple is : (7, 8, 3, 4, 3, 2)
The second tuple is : (9, 6, 8, 2, 1, 0)
The tuple raised to power of another tuple is : (40353607, 262144, 6561, 16, 3, 1)

คำอธิบาย

  • กำหนด Tuple 2 ตัว (Base และ Exponent) และแสดงผล
  • ใช้ zip() จับคู่ Element ที่ Index ตรงกัน
  • Generator Expression ยกกำลัง elem_1 ** elem_2
  • แปลงเป็น Tuple ด้วย tuple()
  • เก็บผลลัพธ์และแสดง

การคำนวณแบบละเอียด

IndexBaseExponentCalculationResult
0797⁹40,353,607
1868⁶262,144
2383⁸6,561
3424²16
4313¹3
5202⁰1

กรณี Exponent เป็นลบ

t1 = (2, 4, 8)
t2 = (-1, -2, 0)
result = tuple(a ** b for a, b in zip(t1, t2))
print(result)  # (0.5, 0.0625, 1.0) - ผลลัพธ์เป็น Float

ใช้ NumPy (รองรับ Broadcasting)

import numpy as np
t1 = (7, 8, 3, 4, 3, 2)
t2 = (9, 6, 8, 2, 1, 0)
result = tuple(np.power(t1, t2))
print(result)  # (40353607, 262144, 6561, 16, 3, 1)

ข้อควรระวัง: Overflow

# Python จัดการ Big Integer อัตโนมัติ ไม่ Overflow
print(10 ** 1000)  # ทำงานได้ปกติ

# แต่ NumPy อาจ Overflow (Fixed Width)
import numpy as np
print(np.power(10, 1000))  # ผลลัพธ์ผิดหรือ Warning