• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Lesson 6. Lists

Difficulty level:

Task«Create a phone number»

💻 Python
You are developing an application for travelers, which allows you to automatically formate the phone numbers of different countries. Your task is to write a function that correctly formates the number depending on its length so that the user can easily call abroad.

Input format

list of integers representing the numbers of the phone number (from 10 to 14 digits)

Output format

a line representing an international phone number in accordance with the length of the number:
rn
10 digits & rarr; Format: (XXX) YYY-ZZZZ RN
11 digits & rarr; Format: +x (xxx) yyy-zzzz
rn
12 digits & rarr; Format: +XX (XXX) YYY-ZZZZ RN
13 digits & rarr; Format: +XXX (XXX) Yyy-ZZZZ RN
14 digits & rarr; Format: +xxxx (xxx) yyy-ZZZZ

Example

Input

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Output

(123) 456-7890

Hint

There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
def format_phone_number(digits):
    # Преобразуем список цифр в строку
    phone_str = ''.join(map(str, digits))
    length = len(phone_str)
    
    if length == 10:
        # Формат: (XXX) YYY-ZZZZ
        return f"({phone_str[:3]}) {phone_str[3:6]}-{phone_str[6:]}"
    elif length == 11:
        # Формат: +X (XXX) YYY-ZZZZ
        return f"+{phone_str[0]} ({phone_str[1:4]}) {phone_str[4:7]}-{phone_str[7:]}"
    elif length == 12:
        # Формат: +XX (XXX) YYY-ZZZZ
        return f"+{phone_str[:2]} ({phone_str[2:5]}) {phone_str[5:8]}-{phone_str[8:]}"
    elif length == 13:
        # Формат: +XXX (XXX) YYY-ZZZZ
        return f"+{phone_str[:3]} ({phone_str[3:6]}) {phone_str[6:9]}-{phone_str[9:]}"
    elif length == 14:
        # Формат: +XXXX (XXX) YYY-ZZZZ
        return f"+{phone_str[:4]} ({phone_str[4:7]}) {phone_str[7:10]}-{phone_str[10:]}"

# Пример использования
digits = [int(i) for i in input().replace('[', '').replace(']', '').split(',')]
result = format_phone_number(digits)
print(result)  # Выведет: (123) 456-7890

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

AI Helper

Hi! I am your programming assistant. Ask me anything about Python — I can explain functions, methods, and help you understand the current task!