python - Python。我很好奇我解决这个编程问题的解决方案是否奇怪?另外,有更多经验的人可能会提供什么合适的解决方案
问题描述
我正在做一个 google python 练习,我想出了一个可行的解决方案。我觉得这个练习很有趣。我只是想知道我的解决方案是否奇怪,有经验的人是否可以通过更正常的方式解决同样的问题?我只是想改进我的编码。我都是自学的,所以只是在寻找反馈。谢谢!
# 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):
# +++your code here+++
lengthABack = len(a)/2
lengthAFront = len(a)/2 + len(a)%2
lengthBBack = len(b)/2
lengthBFront = len(b)/2 + len(b)%2
return a[:lengthAFront]+b[:lengthBFront]+a[-lengthABack:]+b[-lengthBBack:]
解决方案
一个稍微短一些,也许更 Pythonic 的解决方案:
def front_back(a, b):
a_split = (len(a) + 1) // 2
b_split = (len(b) + 1) // 2
return a[:a_split] + b[:b_split] + a[a_split:] + b[b_split:]
我们(len(a) + 1) // 2
在这里使用是因为它在数学上给出了与 相同的结果,len(a)/2 + len(a)%2
但只涉及对 的一次评估len(a)
。
推荐阅读
- r - 饼图中的可变字体颜色
- javascript - 如何获取折线图的日期标签?
- javascript - 如何在数据库中正确保存 div 的 HTML
- javascript - Ajax 调用在我的脚本中不起作用。但是在邮递员工作
- xml - Microsoft Flow - 迭代和解析 XML 文件
- javascript - Highchart,“系列”部分是否可以有一个“for循环”?
- powershell - 从 Tee-Object Powershell 中删除颜色
- jenkins - Jenkins如何通过电子邮件发送包含多个作业的视图的状态
- slider - 从另一个屏幕更改 Kivy 滑块值
- java - Java 2D 数组长度