帮我简化这段代码(Python)
我是 Python 初学者,在 Google Code University 自学。我将这个问题作为练习,并能够使用如下所示的解决方案来解决它:
# 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。有人吗?
I'm a beginner in Python, teaching myself off of Google Code University. I had this problem as an exercise, and was able to solve it using the solution shown below:
# 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:]
This produces the correct output and solves the problem. However, I am duplicating the logic of whether to split a string evenly or add the odd number to the first half, and this seems redundant. There has to be a more efficient way of doing this. The same exact check and logic is being applied to a and b. Anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用
//
进行除法使得此代码在 Python 2.x 和 3.x 中都可以工作。Using
//
for division makes this code work in both Python 2.x and 3.x.好吧,把它放在一个单独的函数中。
Well, put it in a separate function.
因为如果长度是奇数,则要在长度上加 1,而“奇数”意味着 len(a)%2 == 1...
当然,您甚至可以将其压缩为一行为了好玩(尽管它的可读性明显较差):
Since you're adding 1 to the length if it's odd, and 'odd' means that
len(a)%2 == 1
...Of course, you could even condense it to one line just for kicks (although, it's significantly less readable):
您可以使用
ceil
You can get the maximum index by using
ceil
Mhh试图理解@Sven答案我得到了这个:
威尔总是给你正确的索引。
因此,如果我们将其放入一个函数中:
我们可以在解决方案中使用它:
好的,我现在明白了。
我不太确定
/
和//
之间有什么区别Mhh trying to understand @Sven answer I got this:
Will always give you the correct index.
So if we put that in a function:
We can use it in the solution:
Ok, I got it now.
I'm not quite sure what's the difference between
/
and//
though这是我的:
打印:
Here's mine:
Prints: