def euclidean_distance(x1: float, y1: float, x2: float, y2: float) -> float:
return ((x2 - x1)**2 + (y2 - y1)**2) ** 0.5
print(euclidean_distance(x1=0, y1=0, x2=3, y2=4))
5.0
تعريف الإجراء فعل مساعد للبرمجة وليس هو تنفيذيًّا بذاته. لذا ستكون تطبيقات هذا الجزء عبارة عن قولَبة التطبيقات السابقة بتعريفها في إجراءات:
في هذا المثال نعرف نقطتين ثم نحسب المسافة بينهما. والمسافة الإقليدية بين نقطتين \((x_1, y_1)\) و \((x_2, y_2)\) تتبع معادلة فيثاغورس:
\[ \text{distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} \]
وتذكر أن:
\[ \sqrt{x} = x^{1/2} \]
def withdraw_cash(balance, amount, atm_cash):
if balance >= amount:
if atm_cash >= amount:
balance -= amount
atm_cash -= amount
print("Withdrawal successful!")
else:
print("ATM does not have enough cash.")
else:
print("Insufficient balance.")
withdraw_cash(balance=500, amount=200, atm_cash=1000)
withdraw_cash(balance=500, amount=200, atm_cash=100)
withdraw_cash(balance=500, amount=600, atm_cash=1000)
Withdrawal successful!
ATM does not have enough cash.
Insufficient balance.
ما نريد صياغته هو مجموع الأرقام من 1 إلى n
:
وحلها بالإجراء المتسلسل:
def sum_of_numbers(n: int) -> int:
# Terminal case (نهاية)
if n == 1:
return 1
# Recursive case (تسلسل)
return n + sum_of_numbers(n - 1)
print(sum_of_numbers(n=5))
print(sum_of_numbers(n=10))
15
55
وإذا صغناها رياضيًّا وعلمنا المعادلة الرياضية، فلا حاجة للتكرار أصلاً:
\[ \sum_{i=1}^{n} i = \frac{n(n + 1)}{2} \]