Skip to content

Instantly share code, notes, and snippets.

@totechite
Last active July 5, 2018 05:35
Show Gist options
  • Save totechite/e841108ecc108caf746bc2009093741d to your computer and use it in GitHub Desktop.
Save totechite/e841108ecc108caf746bc2009093741d to your computer and use it in GitHub Desktop.

bubbleS.py補足

def bubbleSort(files):
    frag = False  
    for idx in range(0, len(files) - 1):
        fst = int(re.search('\d+', files[idx]).group())  # 比較する左の数
        scd = int(re.search('\d+', files[idx + 1]).group())  # 比較する右の数
        if fst > scd:  # これは昇順の場合
            frag = True  # フラグを立たせる
            tmp = files[idx + 1]  # 次でfiles[idx + 1]は上書きされるので変数に値を保存する
            files[idx + 1] = files[idx]
            files[idx] = tmp
    if frag:  # フラグが立ってる場合、再帰的にbubbleSortを呼び出す。
        bubbleSort(files)
    return files

文字列リストを引数に取って、文字列に含まれる数字をソートして返す関数

def bubbleSort(files):
    frag = False  

再帰呼び出しの判定のフラグ。後述

    for idx in range(0, len(files) - 1):

0から、配列filesの要素数を-1した数までイテレーションする。     ‐1引いてるのは、最後にscdを初期化する際に配列filesの長さ+1を参照しちゃうので そんなところに要素ねーよとエラーになるから。
ちなみにidxはindexの略。

        fst = int(re.search('\d+', files[idx]).group())  # 比較する左の数
        scd = int(re.search('\d+', files[idx + 1]).group())  # 比較する右の数
  • re.search(条件, 文字列)
    手軽に好きな文字列取り出せるイカした奴。2つの引数を取りmatchクラスのオブジェクトを返す。
  • .group()
    Stringを返すmatchクラスの関数。
        if fst > scd:  # これは昇順の場合
            frag = True  # フラグを立たせる
            tmp = files[idx + 1]  
            files[idx + 1] = files[idx]
            files[idx] = tmp

ソートの処理
変数tmpにfiles[idx + 1]の値を保存するのがミソ。
ソートが行われたことが分かるようにフラグを立たせる。

    if frag:  # フラグが立ってる場合、再帰的にbubbleSortを呼び出す。
        bubbleSort(files)
    return files

ようやくfragの解説
リストが完全にソートされるようにする為、再帰的にbubbleSort関数を呼び出している。
完全にソートされたか否かは、ソートが行われたか否かが分かればよいので、このプログラムでは変数fragの真偽値をその目印とする。
fragがFalseの場合、すなわち一度もソートされなかった場合に、リストは完全にソートされたとみなすことができる。
このとき初めてif文を抜け、ソートされたリストを返して関数の処理が終わる。   

import sys
import re
def main():
sample = "ファイル10.pdf, ファイル11.pdf, ファイル.pdf, ファイル1.pdf, ファイル100.pdf, ファイル33.pdf, ファイル4.pdf"
files = sample.split(",") # テスト用の配列
for file in bubbleSort(files):
print(file)
# 結果
# ファイル1.pdf
# ファイル3.pdf
# ファイル4.pdf
# ファイル10.pdf
# ファイル11.pdf
# ファイル33.pdf
# ファイル100.pdf
def bubbleSort(files):
frag = False
for idx in range(0, len(files) - 1):
fst = int(re.search('\d+', files[idx]).group()) # 比較する左の数
scd = int(re.search('\d+', files[idx + 1]).group()) # 比較する右の数
if fst > scd: # これは昇順の場合
frag = True
tmp = files[idx + 1]
files[idx + 1] = files[idx]
files[idx] = tmp
if frag:
bubbleSort(files)
return files
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment