Как преобразовать ввод пользователя в «инопланетный язык»?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Как преобразовать ввод пользователя в «инопланетный язык»?

Сообщение Anonymous »

Секретное сообщение инопланетян - моя собственная идея кодирования. Я пытаюсь преобразовать ввод пользователя в «инопланетный язык».
«Чужой язык» имеет 26 букв (только буквы заглавных , представлено "+" и конец, представлен "x". Все символы повторяются 4 раза, кроме специальных символов, которые повторяются только один раз. < /P>
Вот код до сих пор. < /P>

Код: Выделить всё

from itertools import permutations
import numpy as np
import matplotlib.pyplot as plt

def generate_permutations():
# Create the base pattern for the 3x3 grid with 5 ones and 4 zeros
base_pattern = [1] * 5 + [0] * 4
# Generate all unique permutations of the base pattern
all_permutations = set(permutations(base_pattern))
return list(all_permutations)

def format_grid(grid):
# Convert a tuple of binary digits into a formatted string
return ''.join(map(str, grid))

def assign_grids_to_characters(permutations):
characters = (
list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") +
[f"{i}" for i in range(4)] * 4 +  # Base 4 numbers repeated 4 times
[' ', ',', '.', "'"]
)
special_symbols = ['+', 'x']

# Ensure the total number of symbols is 126
total_symbols = len(characters) + len(special_symbols)
print(f"Total symbols: {total_symbols}")  # Debug statement
assert total_symbols == 126, "Total symbols must be 126"

mappings = {}
mappings[special_symbols[0]] = (0, 1, 0, 1, 1, 1, 0, 1, 0)  # Start character '+'
mappings[special_symbols[1]] = (1, 0, 1, 0, 1, 0, 1, 0, 1)  # End character 'x'

permutations.remove(mappings[special_symbols[0]])
permutations.remove(mappings[special_symbols[1]])

index = 0
for char in characters:
mappings[char] = permutations[index]
index += 1

return mappings

def encode_message(message, mappings):
encoded_message = [mappings['+']]  # Start with the Start Character
for char in message:
if char in mappings:
encoded_message.append(mappings[char])
else:
print(f"Character {char} not in Alien Dictionary!")  # Debug statement
encoded_message.append(mappings['x'])  # End with the End Character
return encoded_message

def print_encoded_message(encoded_message):
# Convert the encoded message to a complete grid
num_grids = len(encoded_message)
grid_size = 3
grid_height = grid_size
grid_width = grid_size * num_grids
result_grid = np.zeros((grid_height, grid_width), dtype=int)

for i, grid in enumerate(encoded_message):
for j in range(grid_size):
result_grid[j, i*grid_size:(i+1)*grid_size] = grid[j*grid_size:(j+1)*grid_size]

# Plot the grid
plt.imshow(result_grid, cmap='gray', interpolation='nearest')
plt.axis('off')
plt.show()

def main():
# Generate all valid permutations
permutations = generate_permutations()
print(f"Number of permutations: {len(permutations)}")  # Debug statement

# Assign grids to characters
mappings = assign_grids_to_characters(permutations)

# Get user input
user_input = input("Enter your message: ").upper()  # Convert to uppercase

# Encode the message
encoded_message = encode_message(user_input, mappings)

# Print the encoded message
print("Encoded Alien Message:")
print_encoded_message(encoded_message)

if __name__ == "__main__":
main()

Код выдает три ошибки.
  • assert total_symbols == 126, «Всего символов должно быть 126"
    ^^^^^^^^^^^^^^^^^^^
    AssertionError: общее количество символов должно быть 126
  • сопоставления = Assign_grids_to_characters(перестановки)
  • main()


Подробнее здесь: https://stackoverflow.com/questions/793 ... n-language
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»