Сортировка текста

Сортируйте строки текста по алфавиту, длине или случайным образом.

Часто задаваемые вопросы

Реализация кода

import locale
from functools import cmp_to_key

def sort_lines(text: str,
               reverse: bool = False,
               case_sensitive: bool = False,
               numeric: bool = False,
               by_length: bool = False,
               remove_duplicates: bool = False) -> str:
    """Sort lines of text with multiple options."""
    lines = text.splitlines()

    if remove_duplicates:
        seen = set()
        unique = []
        for line in lines:
            key = line if case_sensitive else line.lower()
            if key not in seen:
                seen.add(key)
                unique.append(line)
        lines = unique

    def sort_key(line: str):
        if by_length:
            return len(line)
        if numeric:
            try:
                return float(line.strip())
            except ValueError:
                return float("inf")
        return line if case_sensitive else line.lower()

    lines.sort(key=sort_key, reverse=reverse)
    return "\n".join(lines)

# Examples
text = """banana
apple
Cherry
date
10
2
1"""

print("Alphabetical (case-insensitive):")
print(sort_lines(text))

print("\nNumerical (last 3 lines):")
numbers = "10\n2\n1\n20"
print(sort_lines(numbers, numeric=True))

print("\nBy length:")
print(sort_lines(text, by_length=True))

print("\nWith duplicate removal:")
dup_text = "apple\nbanana\napple\ncherry\nbanana"
print(sort_lines(dup_text, remove_duplicates=True))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.