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

Занятие 2. Conditions

Difficulty level:

Task«Super secret message»

& nbsp; you & mdash; An elite spy working for the Alpha secret organization. You intercepted the enemy’s message, but it is encrypted. Your liaison handed you the rules by which the keys for decryption are created. In order for the key to be accepted by the system, it must correspond to three strict criteria at the same time:

rn
    rn
  1. uniqueness: & nbsp; all symbols are all symbols The key should be unique. For example, & nbsp; key123 & nbsp; suitable, a & nbsp; Hellow1 & nbsp; & mdash; No, since the symbol & nbsp; l & nbsp; repeats.
  2. rn
  3. & nbsp; there should be at least one letter of any register in the key (from & nbsp; a & nbsp; to & nbsp; z , from & nbsp; a & nbsp; to & nbsp; z ).
  4. rn
  5. the presence of numbers: & nbsp; there should be at least one digit in the key (from & nbsp; 0 & nbsp; before & nbsp; 9 ).
  6. rn rn

    & mdash; Write a program that will check the proposed lines and determine whether they are valid keys. If the line meets all three rules, the system must issue the message "Access perception". Otherwise & mdash; "Access is prohibited".

    Input format

    A potential key for checking (line, StR).

    Output format

    The result of checking the key (line, str): "access is permitted" or "access is prohibited".

    Example

    Input

    agentcode9

    Output

    Access is allowed

    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
# Получаем строку от пользователя, которая является потенциальным ключом.
secret_key = input()

# Создаем флаги (логические переменные), чтобы отслеживать наличие букв и цифр.
# Изначально мы предполагаем, что их нет.
has_letter = False  # Флаг, который покажет, есть ли в строке буква.
has_digit = False   # Флаг, который покажет, есть ли в строке цифра.
has_rep = True # Флаг, который покажет был ли повтор символа
# Проверяем уникальность символов.
# Самый простой способ - сравнить длину исходной строки с длиной множества (set) из её символов.
# Множество автоматически удаляет все дубликаты.
# Если длины равны, значит, все символы были уникальны.
is_unique = len(secret_key) == len(set(secret_key))

# Запускаем цикл, который перебирает каждый символ в полученной строке.
for char in secret_key:
    # Проверяем, является ли текущий символ буквой.
    if char.isalpha():
        has_letter = True  # Если да, поднимаем флаг "есть буква".
    # Проверяем, является ли текущий символ цифрой.
    if char.isdigit():
        has_digit = True   # Если да, поднимаем флаг "есть цифра".
    if secret_key.count(char) > 1:
        has_rep = False
# После проверки всей строки, выносим окончательное решение.
# Условие сработает, только если все три переменных (is_unique, has_letter, has_digit) истинны (True).
if is_unique and has_letter and has_digit and has_rep:
    # Если все условия выполнены, выводим сообщение об успехе.
    print("Доступ разрешен")
else:
    # Если хотя бы одно условие не выполнено, выводим сообщение об отказе.
    print("Доступ запрещен")

🎉 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, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!