How to use python
Published: 2024-06-24 11:49:41

```
def draw_shape(side_length, iterations):
    import turtle

    def rotate(length):
        turtle.speed(0)
        turtle.penup()
        turtle.setheading(90)
        turtle.forward(length / 2)
        turtle.setheading(180)
        turtle.forward(length / 2)
        turtle.setheading(0)
        turtle.pendown()

    def draw_square(length):
        turtle.color("red")
        for i in range(4):
            turtle.forward(length)
            turtle.right(90)

    def draw_triangle(length):
        turtle.color("blue")
        for i in range(3):
            turtle.forward(length)
            turtle.right(120)

    def draw_circle(radius):
        turtle.circle(radius)

    turtle.speed(0)
    rotate(side_length)
    for _ in range(iterations):
        draw_square(side_length)
        turtle.penup()
        turtle.forward(side_length / 2)
        turtle.right(60)
        turtle.pendown()
        draw_triangle(side_length)
        turtle.right(60)
        turtle.forward(side_length / 2)
        r = (side_length * (3 ** (0.5))) / 6
        turtle.color("green")
        turtle.circle(r, 705)
        turtle.setheading(0)

        side_length = (2 ** 0.5) * r

    turtle.done()


def main():
    side_length = int(input("Сторона квадрата: "))
    iterations = int(input("Сколько вложений: "))

    if iterations > 4:
        print("Превышено кол-во вложений")
        iterations = 4

    draw_shape(side_length, iterations)


if __name__ == '__main__':
    main()

```

```
import random
import nltk


def load_text(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        text = file.read()
    return text


def generate_ngrams(text):
    tokens = nltk.word_tokenize(text)
    bigrams = list(nltk.bigrams(tokens))
    trigrams = list(nltk.trigrams(tokens))
    return bigrams, trigrams


def generate_sentence_with_bigrams(bigrams):
    sentence = []
    if bigrams:
        start_words = [bigram[0] for bigram in bigrams]
        next_word = random.choice(start_words)
        sentence.append(next_word)

        while True:
            next_word_options = [bigram[1] for bigram in bigrams if bigram[0] == next_word]
            if not next_word_options:
                break
            next_word = random.choice(next_word_options)
            sentence.append(next_word)
            if len(sentence) > 20:
                break

    return ' '.join(sentence)


def generate_sentence_with_trigrams(trigrams):
    sentence = list(random.choice(trigrams))
    while True:
        next_word_options = [trigram[2] for trigram in trigrams if trigram[:2] == tuple(sentence[-2:])]
        if not next_word_options:
            break
        next_word = random.choice(next_word_options)
        sentence.append(next_word)
        if len(sentence) > 20:
            break
    return ' '.join(sentence)


filename = 'pismo_k_oneginu.txt'
text = load_text(filename)
bigrams, trigrams = generate_ngrams(text)

print("Предложения на основе биграммной модели:")
for _ in range(3):
    sentence = generate_sentence_with_bigrams(bigrams)
    print(sentence)

print("\n\nПредложения на основе триграммной модели:")
for _ in range(3):
    sentence = generate_sentence_with_trigrams(trigrams)
    print(sentence)

```

```
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans

nltk.download('punkt')
nltk.download('stopwords')

stop_words = set(stopwords.words('russian'))

with open('tihiy_don.txt', 'r', encoding='utf-8') as file:
    text = file.read()

words = word_tokenize(text.lower())

filtered_words = [word for word in words if word.isalnum() and word not in stop_words]

freq_dist = FreqDist(filtered_words)
most_common_words = freq_dist.most_common(int(input("Введите N:")))

print("Наиболее часто встречающиеся слова:")
for word, freq in most_common_words:
    print(f"{word}: {freq}")

common_word_set = set([word for word, _ in most_common_words])
sentences_with_common_words = []
for sentence in nltk.sent_tokenize(text):
    if len(set(word_tokenize(sentence.lower())) & common_word_set) > 1:
        sentences_with_common_words.append(sentence)

print("\nПредложения, содержащие более одного наиболее часто встречающегося слова:")
for sentence in sentences_with_common_words:
    print(sentence)

plt.figure(figsize=(10, 6))
words, freqs = zip(*most_common_words)
plt.bar(words, freqs)
plt.xlabel('Слово')
plt.ylabel('Частота')
plt.title('Распределение наиболее часто встречающихся слов')
plt.xticks(rotation=90)
plt.show()

mu, sigma = np.mean(freqs), np.std(freqs)
x = np.linspace(min(freqs), max(freqs), 100)
y = (1 / (sigma * np.sqrt(2 * np.pi))) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))
plt.plot(x, y, color='red', linestyle='--', label='Нормальное распределение')
plt.legend()
plt.show()

kmeans = KMeans(n_clusters=3)
X = np.array(freqs).reshape(-1, 1)
kmeans.fit(X)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_

print("\nКластеры ключевых слов:")
for i in range(len(centroids)):
    cluster_words = [word for j, (word, freq) in enumerate(most_common_words) if labels[j] == i]
    print(f"Кластер {i+1}: {cluster_words}")

```

```
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from sklearn.cluster import KMeans


def change_image_colors(image_path, num_colors):
    img = Image.open(image_path)
    img_array = np.array(img)

    h, w, _ = img_array.shape

    pixels = img_array.reshape((-1, 3))

    kmeans = KMeans(n_clusters=num_colors)
    kmeans.fit(pixels)

    colors = kmeans.cluster_centers_.astype(int)

    labels = kmeans.labels_
    new_pixels = colors[labels].reshape((h, w, 3))

    new_img = Image.fromarray(new_pixels.astype('uint8'))
    return new_img


def main():
    image_path = "priroda_kartinki_foto_03.jpg"
    num_colors = int(input("Количество цветов:"))

    new_image = change_image_colors(image_path, num_colors)

    plt.figure(figsize=(10, 5))
    plt.subplot(1, 2, 1)
    plt.title('До')
    plt.imshow(Image.open(image_path))
    plt.axis('off')

    plt.subplot(1, 2, 2)
    plt.title(f'После ({num_colors} цветов)')
    plt.imshow(new_image)
    plt.axis('off')

    plt.show()


if __name__ == '__main__':
    main()

```

```
from PIL import Image
import numpy as np
from sklearn.cluster import KMeans


def change_image_colors(image_path, num_colors):
    image = Image.open(image_path)

    image_np = np.array(image)
    pixels = image_np.reshape((-1, 3))

    kmeans = KMeans(n_clusters=num_colors)
    kmeans.fit(pixels)

    new_colors = kmeans.cluster_centers_.astype(int)

    labels = kmeans.predict(pixels)
    new_pixels = new_colors[labels]

    new_image_np = new_pixels.reshape(image_np.shape)
    new_image = Image.fromarray(new_image_np.astype('uint8'), 'RGB')

    return new_image


image_path = 'images.jpeg'
num_colors = int(input("Colors: "))

new_image = change_image_colors(image_path, num_colors)
new_image.show()

```

```
import random
from PIL import Image, ImageDraw

def get_color(char):
    vowels = "АУОИЭЕЁЮЯЫЬЪ"
    consonants = "БВГДЖЗЙКЛМНПРСТФХЦЧШЩ"
    punctuation = ".!?,;:()[]{}\"'"

    if char.isalpha():
        if char.upper() in vowels:
            vowel_colors = [
    # Оттенки желтого
    (255, 255, 0), (255, 255, 102), (255, 255, 51), (255, 215, 0),
    # Оттенки оранжевого
    (255, 165, 0), (255, 140, 0), (255, 127, 80), (255, 99, 71),
    # Оттенки красного
    (255, 0, 0), (220, 20, 60), (178, 34, 34), (255, 105, 180)
]

            vowel_index = vowels.index(char.upper())
            return vowel_colors[vowel_index % len(vowel_colors)]
        else:
            consonant_colors = [
                # Оттенки зеленого
                (144, 238, 144), (0, 255, 0), (50, 205, 50), (0, 201, 87), (189, 183, 107),
                # Оттенки голубого
                (135, 206, 250), (0, 191, 255), (127, 255, 212), (176, 224, 230), (64, 224, 208),
                # Оттенки синего
                (135, 206, 250), (100, 149, 237), (0, 0, 255), (0, 0, 205), (75, 0, 130),
                (230, 230, 250), (148, 0, 211), (138, 43, 226), (128, 0, 128), (147, 112, 219)
            ]

            consonant_index = consonants.index(char.upper())
            return consonant_colors[consonant_index % len(consonant_colors)]
    elif char in punctuation:
        punctuation_colors = [
            (128, 128, 128),  # Medium Gray
            (140, 140, 140),  # Slightly Lighter Gray
            (152, 152, 152),  # Light Gray
            (164, 164, 164),  # Lighter Gray
            (176, 176, 176),  # Even Lighter Gray
            (188, 188, 188),  # Very Light Gray
            (200, 200, 200),  # Pale Gray
            (212, 212, 212),  # Paler Gray
            (224, 224, 224),  # Very Pale Gray
            (236, 236, 236),  # Extremely Pale Gray
            (248, 248, 248),  # Near White Gray
            (220, 220, 220),  # Light Silver Gray
            (210, 210, 210),  # Silver Gray
            (190, 190, 190)   # Dark Silver Gray
        ]
        punctuation_index = punctuation.index(char)
        return punctuation_colors[punctuation_index % len(punctuation_colors)]
    else:
        return 255, 255, 255

with open("stih.txt", "r") as file:
    lines = file.readlines()

image_width = 3500
image_height = 3000
image = Image.new("RGBA", (image_width, image_height), color="white")
draw = ImageDraw.Draw(image)

square_size = 50

x = 0
y = 0

for text in lines:
    text = text.replace("\n", "")
    for char in text:
        if char.isalpha():
            char_type = "vowel" if char.lower() in "ауоиэеёюяыьъ" else "consonant"
            color = get_color(char.lower()) + (random.randint(0, 255),)
            draw.rectangle([x, y, x + square_size, y + square_size], fill=color)
            x += square_size
            if x + square_size > image_width:
                x = 0
                y += square_size
        elif char == " ":
            x += square_size
            if x + square_size > image_width:
                x = 0
                y += square_size
        else:
            color = get_color(char) + (random.randint(25, 255),)
            draw.rectangle([x, y, x + square_size, y + square_size], fill=color)
            x += square_size
            if x + square_size > image_width:
                x = 0
                y += square_size

    x = 0
    y += square_size

image_resolution = 300
image.save("text_image.png", dpi=(image_resolution, image_resolution))

```

```
import matplotlib.pyplot as plt
import numpy as np


def draw_spiral_grid_with_colors(n, m):
    x = np.linspace(0, 1, m + 1)
    y = np.linspace(0, 1, n + 1)

    colors = plt.cm.rainbow(np.linspace(0, 1, n * m))

    fig, ax = plt.subplots()
    hh = 0
    for layer in range(min(n, m) // 2 + min(n, m) % 2):
        for j in range(layer, m - layer):
            color = colors[hh]
            print((x[j], y[layer]))
            ax.add_patch(plt.Rectangle((x[j], y[layer]), x[j + 1] - x[j], y[layer + 1] - y[layer], color=color))
            hh += 1

        for i in range(layer + 1, n - layer):
            color = colors[hh]
            ax.add_patch(
                plt.Rectangle((x[m - layer - 1], y[i]), x[m - layer] - x[m - layer - 1], y[i + 1] - y[i], color=color))
            hh += 1

        for j in range(m - layer - 2, layer - 1, -1):
            color = colors[hh]
            ax.add_patch(
                plt.Rectangle((x[j], y[n - layer - 1]), x[j + 1] - x[j], y[n - layer] - y[n - layer - 1], color=color))
            hh += 1

        for i in range(n - layer - 2, layer, -1):
            color = colors[hh]
            ax.add_patch(plt.Rectangle((x[layer], y[i]), x[layer + 1] - x[layer], y[i + 1] - y[i], color=color))
            hh += 1

    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)

    plt.gca().set_aspect('equal', adjustable='box')
    plt.axis('off')
    plt.show()


draw_spiral_grid_with_colors(int(input("N:")), int(input("M:")))

```

```
import matplotlib.pyplot as plt
import numpy as np


def draw_square_grid_with_colors(n):
    x = np.linspace(0, 1, n + 1)
    y = np.linspace(0, 1, n + 1)
    xx, yy = np.meshgrid(x, y)
    grid = np.dstack((xx, yy))

    colors = plt.cm.rainbow(np.linspace(0, 1, n * n))

    hh = 0

    fig, ax = plt.subplots()
    for i in range(n):
        if i % 2 == 0:
            start = 0
            end = n
            step = 1
        else:
            start = n - 1
            end = -1
            step = -1

        for j in range(start, end, step):
            color = colors[hh]
            ax.add_patch(plt.Rectangle((x[j], y[i]), x[1] - x[0], y[1] - y[0], color=color))

            hh += 1

    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)

    plt.gca().set_aspect('equal', adjustable='box')
    plt.axis('off')
    plt.show()



n = int(input("N:"))
draw_square_grid_with_colors(n)
```