python - 如何获得一个对称的子列表,然后得到该子列表的总和?
问题描述
代码的作用:将整数的 Python 列表作为输入并搜索列表的“对称”内部部分,然后获取该内部部分并获取其总和。
如果列表开头的第 i 个元素的值等于列表末尾的第 i 个元素的值,则对称发生。
我想要的例子:
symmetrical_sum([10,11,12,11,12]) == ([11, 12, 11], 34)
symmetrical_sum([9,99,88,8,77,7,77,8,88,10,100]) == ([88, 8, 77, 7, 77, 8, 88], 353)
symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37)
是否有任何短编码解决方案来获得上面给出的示例中的输出?我有一个正确的编码版本,但它有 30 多行代码,想知道是否有更短的方法。
解决方案
def symmetrical_sum(a):
dup=[x for n, x in enumerate(a) if x in a[:n]] #to get the duplicate
to_int = int(''.join(map(str,dup))) #change duplicate into int
dup1_index=a.index(to_int) #index the first duplicate
dup2_index=a.index(to_int,dup1_index+1) #index the second duplicate
portion=a[dup1_index:dup2_index+1] #get the symetric portion
total = sum(portion) #sum the elements in portion
tuple1 = (portion,total) #create tuple
return tuple1
推荐阅读
- python-3.x - 带有 Gstreamer 的 cv2。错误:GST_PIPELINE 语法。y:716:priv_gst_parse_yyparse:没有元素 xxx
- python - 使用 Airflow 的 Impala 查询
- android - 如何为 UI 和 Android 服务使用两个 android 应用程序类?
- git - 我可以从 git-lfs 中排除一些文件吗?
- gulp - gulp-clean 和 del 无法清理我想要的文件夹
- python - 使用 ExternalCredentials 对 rabbitmq 进行身份验证
- apache-kafka - 处于状态时等待连接超时:CONNECTING
- python - 使用 Counter().most_common 找到所有具有相同计数的元素
- python - 最后一个子进程启动后,主进程什么也没有执行,为什么?
- c# - 如何在后台工作线程中调用要在主 UI 线程上完成的函数?