見出し画像

pythonアルゴリズム勉強

今日は、動画を見て学んだことを共有したいと思います。
勉強の記録として残します。

✅実行結果①

画像1

実行コード

from typing import List
def sample1(chars: str) -> List[List[str]]:
    result = [[],[],[]]
    result_1 = {012} 
    insert_index = 1
    for i, s in enumerate(chars):
        if i % 4 == 1:
            insert_index = 0 # 1段目
        elif i % 2 == 0:
            insert_index = 1 # 2段目
        elif i % 4 == 3:
            insert_index = 2 # 3段目
        result[insert_index].append(s) # 0が1番上, 1が真ん中, 2が1番下にデータを追加
        for j in result_1 - {insert_index}: # 数字が入っていない場所は半角スペースにする。
            result[j].append(" ")
    return result

for line in sample1(input('文字入力...')):
    print(''.join(line))

✅実行結果②

画像2

実装コード

def sample2(chars: str, depth: int) -> List[List[str]]:
    result = [[] for _ in range(depth)] # 深さを受け取る(何行か?)配列の個数をセット
    result_indexes = {i for i in range(depth)} # 何行かを決める
    insert_index = int(depth / 2# 深さを2で割る
    def pos(i):
        return i + 1
    def neg(i):
        return i - 1
    op = neg
    for s in chars:
        result[insert_index].append(s)
        for rest_index in result_indexes - {insert_index}:
            result[rest_index].append(' ')
        if insert_index <= 0# 0以下になったら足し算
            op = pos
        if insert_index >= depth -1# 深さが最大になったら引き算
            op = neg
        insert_index = op(insert_index)
    return result
import string
alphabet = [s for _ in range(2)for s in string.ascii_uppercase] # 大文字のアルファベットを2回ループする
strings = ''.join(alphabet)
for line in sample2(strings, 5): # 深さは5にする。最大5行まで出力
    print(''.join(line))

以上になります。

この記事が参加している募集

この記事が気に入ったらサポートをしてみませんか?