تطبيقات

تعريف الإجراء فعل مساعد للبرمجة وليس هو تنفيذيًّا بذاته. لذا ستكون تطبيقات هذا الجزء عبارة عن قولَبة التطبيقات السابقة بتعريفها في إجراءات:

طول الخط المستقيم بين نقطتين

في هذا المثال نعرف نقطتين ثم نحسب المسافة بينهما. والمسافة الإقليدية بين نقطتين \((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 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

كم عمرك يومئذ؟

def age_at(age_now: int, current_year: int, at_year: int) -> int:
    return age_now + (at_year - current_year)

print(age_at(0, 2000, 2010)) # بعد الولادة
print(age_at(20, 2000, 2010)) # في المستقبل
print(age_at(20, 2000, 1995)) # في الماضي
10
30
15

حساب الأجر

def gross_pay(hours: float, per_hour_rate: float) -> float:
    return hours * per_hour_rate

print(gross_pay(10, 10))
print(gross_pay(40, 10))
100
400

سحب الرصيد

  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:
    pass

وحلها بالإجراء المتسلسل:

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} \]

def sum_of_numbers(n: int) -> int:
    return n * (n + 1) // 2

assert sum_of_numbers(n=5) == 1+2+3+4+5
assert sum_of_numbers(n=10) == 1+2+3+4+5+6+7+8+9+10