求助各位大神, 如何将(a,(b,(c,(d,(e,(f))))))转换为(f,(e,(d,(c,(b,(a))))))

2018-03-17 16:21:41 +08:00
 koplyp
7960 次点击
所在节点    Python
68 条回复
gowl
2018-03-17 22:52:39 +08:00
谁教教我插图片啊 ><
gowl
2018-03-17 22:56:44 +08:00
gowl
2018-03-17 22:59:20 +08:00
<img src="https://i.loli.net/2018/03/17/5aad2b85743e9.png" class="embedded_image">
gowl
2018-03-17 23:09:04 +08:00
然后再用 Python 写一个 lisp 解释器就可以了;)
vegito2002
2018-03-17 23:13:23 +08:00
这个就是一个单链表反转, 不用栈操作, 直接把字母全都提取出来, 倒序, 然后加括号就行了, 你看你的输出, 除了最后的右括号, 左边的实际上就是一个简单的循环结构, 一个 for loop 完成
(f,(e,(d,(c,(b,(a,
去掉最后一个逗号, 然后加上对应数量的右括号就行了;
gbin
2018-03-17 23:39:57 +08:00
gbin
2018-03-18 00:05:44 +08:00
@whileFalse 求详解,get 不到重点。
contmonad
2018-03-18 00:07:18 +08:00
为什么你们都把输入当做字符串,不是 tuple 吗?如果允许稍微改一下题目,在最后加一个 nil 就很简单了:

l = ('a', ('b', ('c', ('d', ('e', ('f', ()))))))
acc = ()
while l:
   acc, l = (l[0], acc), l[1]
linuap
2018-03-18 00:30:14 +08:00
@contmonad
不用改题目
看 3l 回答,是一样的方法
ballshapesdsd
2018-03-18 00:34:59 +08:00
@contmonad 完美
imn1
2018-03-18 00:54:20 +08:00
1.正则提取->列表 A
2.A 倒序->B
3.AB zip ->二维列表 C
4.替换 C (有需要的话用正则)
有需要的 escape 一下

数据源非字符串的话,可以借用 json 过渡
coffeSlider
2018-03-18 01:15:04 +08:00
import re
def wtf(s):
return re.sub('\w', '{}', s).format(*[i for i in s[::-1] if i.isalpha()])

"Life is short"
aokihu
2018-03-18 01:36:36 +08:00
这个不是二叉树么!
animal
2018-03-18 01:39:42 +08:00
我怎么觉得应该把这串字符转换成树形结构,用中序或者后序遍历
aminic
2018-03-18 03:01:17 +08:00
递归就可以吧
nicktogo
2018-03-18 05:17:19 +08:00
two pointer ?
qq529633582
2018-03-18 05:48:20 +08:00
>>> def reverse(a):
... f = (lambda x, y : (x[0],y) if len(x)==1 else f(x[1], (x[0],y)))
... return f(a[1], (a[0],))
...
>>> reverse(('a',('b',('c',('d',('e',('f',)))))))
('f', ('e', ('d', ('c', ('b', ('a',))))))
lemontv
2018-03-18 06:08:30 +08:00
woodo
2018-03-18 08:56:03 +08:00
>>> n=ord('f')-ord('a')
>>> for x in s:
... if x in string.ascii_letters:
... print(chr(ord(x)+n), end=''); n-=2
... else: print(x,end='')
... print()
realpg
2018-03-18 09:37:35 +08:00
@contmonad #28
@qq529633582 #37

老师,这题太难了,我自己换了个题啊

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/438930

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX