私はPythonの初心者で、GoogleCodeUniversityで学んでいます。私は演習としてこの問題を抱えていましたが、以下に示す解決策を使用して解決することができました。
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
def front_back(a, b):
if len(a) % 2 == 0:
ad = len(a) / 2
if len(b) % 2 == 0:
bd = len(b) / 2
else:
bd = (len(b) / 2) + 1
else:
ad = (len(a) / 2) + 1
if len(b) % 2 == 0:
bd = len(b) / 2
else:
bd = (len(b) / 2) + 1
return a[:ad] + b[:bd] + a[ad:] + b[bd:]
これにより、正しい出力が生成され、問題が解決されます。ただし、文字列を均等に分割するか、前半に奇数を追加するかというロジックを複製しているため、これは冗長に思えます。これを行うには、より効率的な方法が必要です。同じ正確なチェックとロジックがaとbに適用されています。誰?