LoginSignup
1
2

More than 3 years have passed since last update.

「世界で闘うプログラミング力を鍛える本」Pythonコード解答例 - 1.5 一発変換

Last updated at Posted at 2020-02-01

「世界で闘うプログラミング力を鍛える本」Pythonコード解答例 - 1.5 一発変換

目次

CHAP1. 配列と文字列

  1. 重複のない文字列
  2. 同じ文字の数を数える
  3. URLify
  4. 回文の順列
  5. 一発変換
  6. 文字列圧縮
  7. 行列の回転
  8. "0"の行列
  9. 文字列の回転

Pythonコード解答例

def oneEditAway(first,second):

    if len(first) == len(second):
        return oneEditReplace(first,second)

    elif len(first)+1 == len(second):
        return oneEditInsert(first,second)

    elif len(first)-1 == len(second):
        return oneEditInsert(second,first)

    return False

def oneEditReplace(s1,s2):

    foundDifference = False

    for i in range(len(s1)):

        if s1[i] != s2[i]:

            if foundDifference:
                return False

            foundDifference = True

    return True

def oneEditInsert(s1,s2):

    index1 = 0
    index2 = 0

    while index2 < len(s2) and index1 < len(s1):

        if s1[index1] != s2[index2]:
            if index1 != index2:
                return False
            index2 = index2 + 1
        else:
            index1 = index1 + 1
            index2 = index2 + 1

    return True

input_str_1 = "pale"
input_str_2 = "ple"

print(oneEditAway(input_str_1,input_str_2))

input_str_3 = "pales"
input_str_4 = "pale"

print(oneEditAway(input_str_3,input_str_4))

input_str_5 = "pale"
input_str_6 = "bale"

print(oneEditAway(input_str_5,input_str_6))

input_str_7 = "pale"
input_str_8 = "bake"

print(oneEditAway(input_str_7,input_str_8))
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2