-
Notifications
You must be signed in to change notification settings - Fork 0
/
一行Python代码——电话簿上的字符.html
265 lines (254 loc) · 14.3 KB
/
一行Python代码——电话簿上的字符.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="littlewhite" />
<meta name="copyright" content="littlewhite" />
<meta property="og:type" content="article" />
<meta name="twitter:card" content="summary">
<meta name="keywords" content="python, Language, " />
<meta property="og:title" content="一行Python代码——电话簿上的字符 "/>
<meta property="og:url" content="https://chukeer.github.io/一行Python代码——电话簿上的字符.html" />
<meta property="og:description" content="Question¶ Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Answer¶ num2letter = { '1':'', '2':'abc', '3 ..." />
<meta property="og:site_name" content="楚客" />
<meta property="og:article:author" content="littlewhite" />
<meta property="og:article:published_time" content="2015-05-12T00:00:00+08:00" />
<meta property="" content="2015-05-12T00:00:00+08:00" />
<meta name="twitter:title" content="一行Python代码——电话簿上的字符 ">
<meta name="twitter:description" content="Question¶ Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Answer¶ num2letter = { '1':'', '2':'abc', '3 ...">
<title>一行Python代码——电话簿上的字符 · 楚客
</title>
<!--
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.1/css/font-awesome.css" rel="stylesheet">
--!>
<link href="https://chukeer.github.io/theme/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="https://chukeer.github.io/theme/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://chukeer.github.io/theme/css/pygments.css" media="screen">
<link rel="stylesheet" type="text/css" href="https://chukeer.github.io/theme/tipuesearch/tipuesearch.css" media="screen">
<link rel="stylesheet" type="text/css" href="https://chukeer.github.io/theme/css/elegant.css" media="screen">
<link rel="stylesheet" type="text/css" href="https://chukeer.github.io/theme/css/custom.css" media="screen">
</head>
<body>
<div id="content-sans-footer">
<div class="navbar navbar-static-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="https://chukeer.github.io/"><span class=site-name>楚客</span></a>
<div class="nav-collapse collapse">
<ul class="nav pull-right top-menu">
<li ><a href="https://chukeer.github.io">Home</a></li>
<li ><a href="https://chukeer.github.io/categories.html">Categories</a></li>
<li ><a href="https://chukeer.github.io/tags.html">Tags</a></li>
<li ><a href="https://chukeer.github.io/archives.html">Archives</a></li>
<li><form class="navbar-search" action="https://chukeer.github.io/search.html" onsubmit="return validateForm(this.elements['q'].value);"> <input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input"></form></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
<div class="span1"></div>
<div class="span10">
<article>
<div class="row-fluid">
<header class="page-header span10 offset2">
<h1><a href="https://chukeer.github.io/一行Python代码——电话簿上的字符.html"> 一行Python代码——电话簿上的字符 </a></h1>
</header>
</div>
<div class="row-fluid">
<div class="span2 table-of-content">
<nav>
<h4>Contents</h4>
<div class="toc">
<ul>
<li><a href="#question">Question</a></li>
<li><a href="#answer">Answer</a></li>
<li><a href="#_1">答案分析</a></li>
</ul>
</div>
</nav>
</div>
<div class="span8 article-content">
<h3 id="question">Question<a class="headerlink" href="#question" title="Permanent link">¶</a></h3>
<p>Given a digit string, return all possible letter combinations that the number could represent.</p>
<p>A mapping of digit to letters (just like on the telephone buttons) is given below.</p>
<p><img alt="" src="http://littlewhite.us/pic/20150512/1.png"/></p>
<div class="highlight"><pre><span></span><span class="n">Input</span><span class="o">:</span><span class="n">Digit</span> <span class="n">string</span> <span class="s2">"23"</span>
<span class="n">Output</span><span class="o">:</span> <span class="o">[</span><span class="s2">"ad"</span><span class="o">,</span> <span class="s2">"ae"</span><span class="o">,</span> <span class="s2">"af"</span><span class="o">,</span> <span class="s2">"bd"</span><span class="o">,</span> <span class="s2">"be"</span><span class="o">,</span> <span class="s2">"bf"</span><span class="o">,</span> <span class="s2">"cd"</span><span class="o">,</span> <span class="s2">"ce"</span><span class="o">,</span> <span class="s2">"cf"</span><span class="o">].</span>
</pre></div>
<h3 id="answer">Answer<a class="headerlink" href="#answer" title="Permanent link">¶</a></h3>
<div class="highlight"><pre><span></span>num2letter = {
'1':'',
'2':'abc',
'3':'def',
'4':'ghi',
'5':'jkl',
'6':'mno',
'7':'pqrs',
'8':'tuv',
'9':'wxyz'}
def letterCombinations(digits):
return [] if digits == "" else reduce(lambda x, y:reduce(lambda a,b:a+b, [[i+j for i in x] for j in y], []), filter(lambda x:x!='', [num2letter[digit] for digit in digits]), [''])
</pre></div>
<h3 id="_1">答案分析<a class="headerlink" href="#_1" title="Permanent link">¶</a></h3>
<p>我们先求得每个数字对应的字符串,然后求这些字符串能组合的所有情况,比如根据数字得到的字符为'abc', 'def','ghi',那么组合数是3<em>3</em>3=27种,具体思路就是先求'abc'和'def'的组合['ab','ae','af','bd','be','bf','cd','ce','cf'],再算和'ghi'的组合,以此类推,这本身是每什么难度的,在Python里正好有个内建函数是干这个事的,那就是reduce</p>
<p>reduce的函数原型如下</p>
<div class="highlight"><pre><span></span>def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
initializer = next(it)
except StopIteration:
raise TypeError('reduce() of empty sequence with no initial value')
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value
</pre></div>
<p>我们举个例子来说明</p>
<div class="highlight"><pre><span></span>reduce(lambda a,b:a+b, [1,2,3], 100)
</pre></div>
<p>这里返回的是100+1+2+3,lambda a,b:a+b定义了一个匿名函数,等价于</p>
<div class="highlight"><pre><span></span>def add(a, b):
return a + b
</pre></div>
<p>这个reduce函数的具体计算步骤如下</p>
<div class="highlight"><pre><span></span>1. redult = 100
2. result = add(result, 1) # 101
3. result = add(result, 2) # 103
4. result = add(result, 3) # 106*
5. return result
</pre></div>
<p>现在再来分析答案中的letterCombinations函数</p>
<p>为了看得清晰,我们先使用一些中间变量,改写函数如下</p>
<div class="highlight"><pre><span></span>def letterCombinations(digits):
data = filter(lambda x:x!='', [num2letter[digit] for digit in digits])
return [] if digits == "" else reduce(lambda x, y:reduce(lambda a,b:a+b, [[i+j for i in x] for j in y], []), data, [''])
</pre></div>
<ul>
<li>
<p>[num2letter[digit] for digit in digits]</p>
<p>根据digits获取对应字符串</p>
</li>
<li>
<p>filter(lambda x:x!='', [num2letter[digit] for digit in digits])</p>
<p>过滤掉空字符串</p>
</li>
<li>
<p>return [] if digits == "" else something</p>
<p>python的三元组表达式,类似C的<code>condition ? value1 : value2</code>,Python的形式为<code>value1 if condition else value2</code>,这里意思是如果digits为空则返回[],否则返回后面的something,这里的something就是我们要重点分析的如下表达式</p>
<div class="highlight"><pre><span></span> reduce(lambda x, y:reduce(lambda a,b:a+b, [[i+j for i in x] for j in y], []), data, [''])
</pre></div>
</li>
</ul>
<p>下面我们来一层层抽丝剥茧。先看外层的reduce,我们将其表示成如下</p>
<div class="highlight"><pre><span></span>reduce(func(x,y), data, [''])
</pre></div>
<p>这是这道题的核心解题思路,我们还是以例子来说明,假设data=['abc','def','ghi'],那么计算步骤应该是</p>
<div class="highlight"><pre><span></span>1. result = ['']
2. result = func(result, 'abc')
3. result = func(result, 'def')
4. result = func(result, 'ghi')
5. return result
</pre></div>
<p>我们只需要实现func函数,问题就迎刃而解</p>
<p>其实func函数要做的就是将y里的每个字符添加到x里的每个字符串的末尾,比如</p>
<div class="highlight"><pre><span></span>x=['ab', 'cd']
y='ef'
</pre></div>
<p>那么func(x,y)应该返回<code>['abe','cde', 'abf', 'cdf']</code>,然后就是求func函数的实现</p>
<p>很容易我们想到列表解析,这里需要两层嵌套如下</p>
<div class="highlight"><pre><span></span>def func(x,y):
return [[i + j for i in x] for j in y]
</pre></div>
<p>但是这样的结果是[['abe', 'cde'], ['abf', 'cdf']],此时我们还需要将列表的每个元素(注意,元素类型也为列表)连接起来,这不就是元素求和吗,只是这里的元素是列表而已,我们以文章开头reduce为参考</p>
<div class="highlight"><pre><span></span>reduce(lambda a,b:a+b, [1,2,3], 100)
</pre></div>
<p>只需稍作替换即可</p>
<div class="highlight"><pre><span></span>reduce(lambda a,b:a+b, [[i + j for i in x] for j in y], [])
</pre></div>
<p>这样func(x,y)函数的实现就成了下面这样</p>
<div class="highlight"><pre><span></span>def func(x,y):
return reduce(lambda a,b:a+b, [[i + j for i in x] for j in y, [])
</pre></div>
<p>我们再将最外层reduce中的func函数改写成lambda表达式</p>
<div class="highlight"><pre><span></span>reduce(lambda x,y:reduce(lambda a,b:a+b, [[i + j for i in x] for j in y], []), data, [''])
</pre></div>
<p>大功告成!</p>
<hr/>
<aside>
<nav>
<ul class="articles-timeline">
<li class="previous-article">« <a href="https://chukeer.github.io/一行Python代码——单词逆转.html" title="Previous: 一行Python代码——单词逆转">一行Python代码——单词逆转</a></li>
<li class="next-article"><a href="https://chukeer.github.io/Linux程序编译链接动态库版本的问题.html" title="Next: Linux程序编译链接动态库版本的问题">Linux程序编译链接动态库版本的问题</a> »</li>
</ul>
</nav>
</aside>
</div>
<section>
<div class="span2" style="float:right;font-size:0.9em;">
<table class="table">
<!-- <time pubdate="pubdate" datetime="2015-05-12T00:00:00+08:00"> 5 12, 2015</time> -->
<tr>
<td>Published</td>
<td><time pubdate="pubdate" datetime="2015-05-12T00:00:00+08:00">2015- 5-12</time></td>
</tr>
<tr>
<td>Category</td>
<td><a class="category-link" href="https://chukeer.github.io/categories.html#language-ref">Language</a></td>
</tr>
<tr>
<td>Tags</td>
<td>
<ul class="list-of-tags tags-in-article">
<li><a href="https://chukeer.github.io/tags.html#python-ref">python
<span>6</span>
</a></li>
</ul>
</td>
</tr>
</table>
</div>
</section>
</div>
</article>
</div>
<div class="span1"></div>
</div>
</div>
<div id="push"></div>
</div>
<footer>
<div id="footer">
<ul class="footer-content">
<li class="elegant-power">Powered by <a href="http://getpelican.com/" title="Pelican Home Page">Pelican</a>. Theme: <a href="http://oncrashreboot.com/pelican-elegant" title="Theme Elegant Home Page">Elegant</a> by <a href="http://oncrashreboot.com" title="Talha Mansoor Home Page">Talha Mansoor</a></li>
</ul>
</div>
</footer> <!--
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
-->
<script src="https://chukeer.github.io/theme/js/jquery.min.js"></script>
<script src="https://chukeer.github.io/theme/js/bootstrap.min.js"></script>
<script>
function validateForm(query)
{
return (query.length > 0);
}
</script>
<script>
$("div.article-content table").addClass("table table-hover");
</script>
</body>
<!-- Theme: Elegant built for Pelican
License : http://oncrashreboot.com/pelican-elegant -->
</html>