تطبيقات

الكلمة المتناظرة

في هذا المثال نوضح استعمال مؤشرين على نفس النص لمعرفة ما إذا كانت الكلمة متناظرة:

  • المؤئر الأول بإصبعك الأيمن: i يبدأ من أول حرف وينتهي عند المنتصف
  • المؤئر الثاني بإصبعك الأيسر: j يبدأ من آخر حرف وينتهي عند المنتصف
def is_palindrome(word):
    """
    A palindrome word is one that can be read the same way from both ends.
    """

    # Remove the difference of capitalization
    word = word.lower()
    
    # Remove the spaces (to match things like: "Race car")
    word = word.replace(" ", "")

    # Check if the word is a palindrome
    for i in range(len(word) // 2):
        j = len(word) - i - 1
        if word[i] != word[j]:
            return False
    return True

# Test examples
assert is_palindrome("radar")
assert is_palindrome("level") 
assert is_palindrome("madam")
assert is_palindrome("توت")
assert is_palindrome("خوخ")
assert is_palindrome("Race car")
assert is_palindrome("حصان ناصح")
assert not is_palindrome("python")

بدل الحلقة، وكان لنا أن نكتب باختصار: word == word[::-1] وهي تعني أن النص متناظر إذا كان مساوياً لنفسه بالمقلوب.

def is_palindrome(word):
    word = word.lower()
    word = word.replace(" ", "")
    return word == word[::-1]

عد الكلمات

هذا مثال لاستخراج الكلمات (من غير تكرار) من قاموس من العبارات (ثلاثة عبارات). هذه العملية تستعمل كثيرًا في تحليل النصوص إذ نريد أن نعرف جميع الكلمات الواردة في مجموعة من النصوص، ولا نريد الكلمات المعهودة جدًّا (هنا نسميها stop_words)، كما أننا نستعمل .lower() في التعبير الناتج حتى لا يفرق بين الحروف في حالتيها الإنجليزية:

stop_words = {'is', 'and', 'the', 'be', 'not'}

documents = {
    'Python':     "python is great and Python is easy",
    'Java':       "Java is verbose and java is popular",
    'JavaScript': "JavaScript is for the web and javascript is everywhere"
}

word_counts = dict()

for doc in documents.values():
    doc = doc.lower()
    words = doc.split()
    for w in words:
        if w not in stop_words:
            word_counts[w] = word_counts.get(w, 0) + 1

for w, count in word_counts.items():
    print(f"{w}: {count}")
python: 2
great: 1
easy: 1
java: 2
verbose: 1
popular: 1
javascript: 2
for: 1
web: 1
everywhere: 1

ترجمة إجراءات

نكتب برنامج يقرأ سطرًا يفعله بعملية حسابية على عوامل محددة. فهو كلغة برمجة بسيطة.

def parse_command(cmd):
    """
    Parse a command and return the result of the operation.

    Example:
    >>> parse_command("+ 5 10 2")
    17
    >>> parse_command("* 5 10 2")
    100
    >>> parse_command("max 5 10 2")
    10
    """

    operator, *operands = cmd.split(" ")

    match operator:
        case "+":
            total = 0
            for item in operands:
                total += float(item)
            return total

        case "*":
            total = 1
            for item in operands:
                total *= float(item)
            return total

        case "max":
            max_value = float(operands[0])
            for item in operands[1:]:
                f = float(item)
                if f > max_value:
                    max_value = f
            return max_value

        case _:
            raise ValueError(f"Unknown operator: {operator}")

assert parse_command("+ 5 10 2") == 17
assert parse_command("* 5 10 2") == 100
assert parse_command("max 5 10 2") == 10

تطبيقات النصوص كثيرة جدًّا في الواقع، لكن نكتفي بهذا هنا، ولعلك تراجع مصادر مختصة بالتحليل النصي لتعلم المزيد.

تلوين الخارج

تقبل نافذة الأوامر تغيير لون الطباعة بأحرف تحكُّم معيَّنة تبدأ بالحرف \033 وتنتهي بالحرف m على التحو التالي، يمكن استعمالها في ثنايا النص لتغيير لون الحبر، ثم يجب استعمال الحرف الذي يرمز إلى RESET لإعادة اللون إلى الأصل.

GREEN = '\033[92m'  # ANSI escape code for green text
RED = '\033[91m'    # ANSI escape code for red text
BLUE = '\033[94m'   # ANSI escape code for blue text
YELLOW = '\033[93m' # ANSI escape code for yellow text

BRIGHT = '\033[1m'  # ANSI escape code for bright text
DIM = '\033[2m'    # ANSI escape code for dimmed text

BG_GREEN = '\033[42m'  # ANSI escape code for green background
BG_RED = '\033[41m'    # ANSI escape code for red background
BG_BLUE = '\033[44m'   # ANSI escape code for blue background
BG_YELLOW = '\033[43m' # ANSI escape code for yellow background

RESET = '\033[0m'   # Reset text color


# Print different color text with different background
print(f"{YELLOW}This text is yellow!")
print(f"{BG_GREEN}This has a green background (and still yellow because we did not reset)")
print(f'{RESET}', end='')
print(f"{RED}{BG_BLUE}This is red text on a blue background{RESET}")
This text is yellow!
This has a green background (and still yellow because we did not reset)
This is red text on a blue background

تنبيه: لن ترى الألوان هنا على الكتاب، لكن انسخ القطعة وشغله وستراها.

راجع ANSI escape code لمزيد من التفاصيل عن الألوان في نافذة الأوامر.