0

英単語を複数形にするプログラムです

インプットは

7
box
photo
axis
dish
church
leaf
knife

です。

input_line = int(input())
words_spell=[list(input()) for i in range(input_line)]



for i in range(input_line):
    #s, sh, ch, o, x は末尾にes
    if words_spell[i][-1]=="s" or words_spell[i][-1]=="o" or words_spell[i][-1]=="x" or words_spell[i][-2]+words_spell[i][-1]=="sh" or words_spell[i][-2]+words_spell[i][-1]=="ch":
        words_spell[i].append("es")
    #末尾が f, fe のいずれかである英単語の末尾の f, fe を除き、末尾に ves を付ける
    elif words_spell[i][-1]=="f" :
        del words_spell[-1]
        words_spell[i].append("ves")
    elif words_spell[i][-1]+words_spell[i][-2]=="fe":
        del words_spell[-2:-1]
        words_spell[i].append("ves")

    #末尾の1文字が y で、末尾から2文字目が a, i, u, e, o のいずれでもない英単語の末尾の y を除き、末尾に ies を付ける
    elif words_spell[i][-1]=="y" and words_spell[i][-2]!="a" and words_spell[i][-2]!= "i" and words_spell[i][-2]!="u" and words_spell[i][-2]!="e" and words_spell[i][-2]!="o":
        del words_spell[i][-1]
        words_spell[i].append("ies")

    #上のいずれの条件にも当てはまらない英単語の末尾には s を付ける
    else:
        words_spell[i].append("s")

エラーメッセージ

Traceback (most recent call last):
  File "Main.py", line 12, in <module>
    if words_spell[i][-1]=="s" or words_spell[i][-1]=="o" or words_spell[i][-1]=="x" or words_spell[i][-2]+words_spell[i][-1]=="sh" or words_spell[i][-2]+words_spell[i][-1]=="ch":
IndexError: list index out of range

エラーの理由がわかりません。
ちなみにもう提出済みなのでカンニングではありません

5
  • del words_spell[-1] とかしてますけど、これって del words_spell[i][-1] ではないですかね。
    – user39889
    2019年12月19日 14:13
  • そうですね!ただ、それとはちがうところでエラーになっていると思います。
    – Tap
    2019年12月19日 14:26
  • あと、del words_spell[-2:-1]del words_spell[i][-2:-1] なのではないでしょうか。
    – user39889
    2019年12月19日 14:29
  • なるほど!いま修正して動かしたらいい感じになりました!
    – Tap
    2019年12月19日 14:32
  • ありがとうございます!
    – Tap
    2019年12月19日 14:36

1 件の回答 1

1

エラーの原因についての質問なので回答にはなっていないのですが、Python では文字列型のオブジェクトにもスライス記法を使うことが可能です。また、

words_spell[i][-1]=="s" or words_spell[i][-1]=="o" or ...

などとしていますが、endswith() メソッドや in, not in 演算子を使うと読みやすく書くことができます。

# First line represents number of words
num_words = int(input())
# Take words
words = [input() for _ in range(num_words)]

# Pluralize
plurals = []
for w in words:
  # s, sh, ch, o, x は末尾にes
  if w.endswith(('s', 'sh', 'ch', 'o', 'x')):
    w += 'es'
  # 末尾が f, fe のいずれかである英単語の末尾の f, fe を除き、末尾に
  # ves を付ける
  elif w.endswith('f'):
    w = w[:-1] + 'ves'
  elif w.endswith('fe'):
    w = w[:-2] + 'ves'
  # 末尾の1文字が y で、末尾から2文字目が a, i, u, e, o のいずれでもない
  # 英単語の末尾の y を除き、末尾に ies を付ける
  elif w.endswith('y') and w[-2] not in ('a', 'i', 'u', 'e', 'o'):
    w = w[:-1] + 'ies'
  # 上のいずれの条件にも当てはまらない英単語の末尾には s を付ける
  else:
    w += 's'

  plurals.append(w)

print(plurals)
1
  • 勉強になりました!ありがとうございます!
    – Tap
    2019年12月19日 16:15

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。