• 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
  • к

Занятие 1. Entering and output of data

Difficulty level:

Task«Parser Log Failov»

Write a program that accepts the server log-file, finds all the unique IP addresses and displays their number. & nbsp;

rn

a few lines of text, a few lines of text, a few lines. Each of which is a record in the log. The IP address is always the first element in the line and is separated from the rest of the gap. The input ends when it is transmitted "0".

Input format

several lines. IP is always written at the very beginning.

Output format

One number & mdash; The number of unique IP addresses found in the input data.

Example

Input

192.168.0.1 - [10/Jan/2024: 13: 55: 36 +0000] "Get /index.html http/1.1" 200 2326
192.168.0.2 - [10/Jan/2024: 12: 11: 06 +0000] "Get /index.html http/1.1" 200 1234
192.168.0.1 - [11/Jan/2024: 16: 45: 21 +0000] "Get /index.html http/1.1" 200 2326
0

Output

2

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
# Множество для хранения уникальных IP-адресов
unique_ips = set()

while True:
    line = input().strip()
    
    # Проверка на завершение ввода
    if line == "0":
        break
    
    # Пропускаем пустые строки
    if not line:
        continue
    
    # Извлекаем первый элемент строки (предполагаемый IP)
    parts = line.split()
    if not parts:
        continue
        
    potential_ip = parts[0]
    
    # Проверяем, является ли строка валидным IPv4 адресом
    # Разделяем строку по точкам
    ip_parts = potential_ip.split('.')
    
    # Должно быть ровно 4 части
    if len(ip_parts) != 4:
        continue
    
    valid_ip = True
    # Проверяем каждую часть IP
    for part in ip_parts:
        # Каждая часть должна состоять только из цифр
        if not part.isdigit():
            valid_ip = False
            break
        
        # Преобразуем в число и проверяем диапазон (0-255)
        num = int(part)
        if num < 0 or num > 255:
            valid_ip = False
            break
        
        # Проверяем, нет ли ведущих нулей (кроме случая, когда число равно 0)
        if len(part) > 1 and part[0] == '0':
            valid_ip = False
            break
    
    # Если IP валиден - добавляем в множество
    if valid_ip:
        unique_ips.add(potential_ip)

# Выводим количество уникальных IP-адресов
print(len(unique_ips))

🎉 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...

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!