Refatorar código Python

Refatorar o código Python para melhorar a modularidade e adicionar funcionalidades.

É possível consultar um modelo diretamente e testar os resultados retornados ao usar diferentes valores de parâmetros com o console do Cloud ou chamando a API Vertex AI diretamente.

Comando Freeform

Tenho um programa Python que gera nomes aleatórios e realiza diferentes tipos de processamento de dados com base nas seleções do usuário em um menu no console. Você pode me ajudar a refatorar o código dividindo a função data_processor e removendo-a completamente? Além disso, adicione funcionalidade para nomes de siglas invertidas e mova a recuperação de entrada do usuário para uma função separada. O guard principal precisa conter apenas uma chamada de função.

import random
from faker import Faker

def transform_data(data):
    upper_names = [name.upper() for name in data]
    lower_names = [name.lower() for name in data]
    reversed_names = [name[::-1] for name in data]
    acronym_names = ["".join([word[0] for word in name.split()]) for name in data]
    return upper_names, lower_names, reversed_names, acronym_names

def calculate_statistics(data):
    name_lengths = [len(name) for name in data]
    average_length = sum(name_lengths) / len(name_lengths)
    max_length = max(name_lengths)
    min_length = min(name_lengths)
    return average_length, max_length, min_length

def group_by_first_letter(data):
    grouped_data = {}
    for name in data:
        grouped_data.setdefault(name[0], []).append(name)
    return grouped_data

def analyze_name_frequencies(data):
    name_counts = {}
    for name in data:
        name_counts[name] = name_counts.get(name, 0) + 1
    return name_counts

def display_menu():
    print("Menu:")
    print("1. Display original names")
    print("2. Display uppercased names")
    print("3. Display lowercased names")
    print("4. Display reversed names")
    print("5. Display acronym names")
    print("6. Display name statistics")
    print("7. Display names grouped by first letter")
    print("8. Display name frequencies")
    print("9. Exit")
    choice = input("Enter your choice: ")
    return choice

if __name__ == "__main__":
    # Generate random names
    fake = Faker()
    names = [fake.name() for _ in range(10)]

    upper_names, lower_names, reversed_names, acronym_names = transform_data(names)
    avg_length, max_length, min_length = calculate_statistics(names)
    grouped_names = group_by_first_letter(names)
    name_frequencies = analyze_name_frequencies(names)

    processed_data = {
        "original_names": names,
        "upper_names": upper_names,
        "lower_names": lower_names,
        "reversed_names": reversed_names,
        "acronym_names": acronym_names,
        "average_length": avg_length,
        "max_length": max_length,
        "min_length": min_length,
        "grouped_names": grouped_names,
        "name_frequencies": name_frequencies
    }

    while True:
        choice = display_menu()
        if choice == "1":
            print(processed_data["original_names"])
        elif choice == "2":
            print(processed_data["upper_names"])
        elif choice == "3":
            print(processed_data["lower_names"])
        elif choice == "4":
            print(processed_data["reversed_names"])
        elif choice == "5":
            print(processed_data["acronym_names"])
        elif choice == "6":
            print(f"Average name length: {processed_data['average_length']}")
            print(f"Maximum name length: {processed_data['max_length']}")
            print(f"Minimum name length: {processed_data['min_length']}")
        elif choice == "7":
            for letter, names in processed_data["grouped_names"].items():
                print(f"Names starting with {letter}: {names}")
        elif choice == "8":
            for name, count in processed_data["name_frequencies"].items():
                print(f"{name}: {count}")
        elif choice == "9":
            break
        else:
            print("Invalid choice")

Resposta

import random
from faker import Faker

def generate_names(num_names=10):
    fake = Faker()
    return [fake.name() for _ in range(num_names)]

def transform_names(names):
    upper_names = [name.upper() for name in names]
    lower_names = [name.lower() for name in names]
    reversed_names = [name[::-1] for name in names]
    acronym_names = ["".join(word[0] for word in name.split()) for name in names]
    reversed_acronym_names = ["".join(word[0] for word in name.split())[::-1] for name in names] #Added reversed acronym
    return upper_names, lower_names, reversed_names, acronym_names, reversed_acronym_names

def calculate_statistics(names):
    name_lengths = [len(name) for name in names]
    average_length = sum(name_lengths) / len(name_lengths) if name_lengths else 0
    max_length = max(name_lengths) if name_lengths else 0
    min_length = min(name_lengths) if name_lengths else 0
    return average_length, max_length, min_length

def group_by_first_letter(names):
    grouped_data = {}
    for name in names:
        grouped_data.setdefault(name[0], []).append(name)
    return grouped_data

def analyze_name_frequencies(names):
    name_counts = {}
    for name in names:
        name_counts[name] = name_counts.get(name, 0) + 1
    return name_counts

def get_user_input():
    choice = input("Enter your choice: ")
    return choice

def display_menu():
    print("Menu:")
    print("1. Display original names")
    print("2. Display uppercased names")
    print("3. Display lowercased names")
    print("4. Display reversed names")
    print("5. Display acronym names")
    print("6. Display reversed acronym names") #Added menu option
    print("7. Display name statistics")
    print("8. Display names grouped by first letter")
    print("9. Display name frequencies")
    print("10. Exit")
    return get_user_input()

def main():
    names = generate_names()
    upper_names, lower_names, reversed_names, acronym_names, reversed_acronym_names = transform_names(names)
    avg_length, max_length, min_length = calculate_statistics(names)
    grouped_names = group_by_first_letter(names)
    name_frequencies = analyze_name_frequencies(names)

    processed_data = {
        "original_names": names,
        "upper_names": upper_names,
        "lower_names": lower_names,
        "reversed_names": reversed_names,
        "acronym_names": acronym_names,
        "reversed_acronym_names": reversed_acronym_names,
        "average_length": avg_length,
        "max_length": max_length,
        "min_length": min_length,
        "grouped_names": grouped_names,
        "name_frequencies": name_frequencies
    }

    while True:
        choice = display_menu()
        try:
            choice = int(choice)
            if choice == 1:
                print(processed_data["original_names"])
            elif choice == 2:
                print(processed_data["upper_names"])
            elif choice == 3:
                print(processed_data["lower_names"])
            elif choice == 4:
                print(processed_data["reversed_names"])
            elif choice == 5:
                print(processed_data["acronym_names"])
            elif choice == 6:
                print(processed_data["reversed_acronym_names"])
            elif choice == 7:
                print(f"Average name length: {processed_data['average_length']}")
                print(f"Maximum name length: {processed_data['max_length']}")
                print(f"Minimum name length: {processed_data['min_length']}")
            elif choice == 8:
                for letter, names in processed_data["grouped_names"].items():
                    print(f"Names starting with {letter}: {names}")
            elif choice == 9:
                for name, count in processed_data["name_frequencies"].items():
                    print(f"{name}: {count}")
            elif choice == 10:
                break
            else:
                print("Invalid choice")
        except ValueError:
            print("Invalid input. Please enter a number.")


if __name__ == "__main__":
    main()
Modelo: gemini-1.5-flash-002
Temperatura: 0,2
Máximo de tokens de saída: 8192
TopK: 40.0
TopP: 0,95