您的位置:首页 > 编程语言 > Python开发

python实现 leetcode 771 jewels and stones

2018-03-04 17:39 651 查看
说来惭愧,别人几年前干的事情,拖到今天自己才开始自己的leetcode之路。但是开始就好吧!
题目描述不再摘抄。
AC率最高的一题,一个寒假都没编程的我开始竟然有些懵,参考了discuss里大神lee215的方法得到结果:class solution:
def numofJewels(self,J,S):
setJ=set(J)
return sum(s in setJ for s in S)又参考Stefanpochmann的方法,进一步得到:class solution:
def numofJewels(self,J,S):
return sum(s in J for s in S)此外还有:
def numJewelsInStones(self, J, S):
return sum(map(J.count, S))
def numJewelsInStones(self, J, S):
return sum(map(S.count, J))
ps:win+R可打开cmd。cmd中ls为dir
然后我们来解决一下我在做题过程中遇到的问题。
问题一,python成员运算符in的用法:
a in b
如果在指定序列b中找到元素a,则返回True,否则返回False。not in相反。



通过上图可知,序列b应为iterable。



由此可得,list,tuple和dict的key都可用。string也可。
一句话总结提炼,iterable可迭代对象都可使用运算符in。
拓展一下,python的比较操作符==和同一性运算符is的联系和区别是什么呢?
python对象包含的三个基本元素:id,type,value。
==对比的是type和value,而is对比的是id。例如:



更多的见https://www.cnblogs.com/CheeseZH/p/5260560.html,这篇博客。
问题二,生成器的用法:
形如(x for x in range(5))的语句即为生成器。注意生成器外围的一对圆括号。如果换成[]就变成了列表生成器。
具体的见廖雪峰老师的python教程。另外和生成器稍微形似的还有lambda函数(匿名函数)。
问题三,Iterable和Iterator:
具体的仍见廖雪峰老师的python教程中的迭代器部分以及python官方文档。这里摘选部分重点。
先来简单的吧。



可作用于for循环,也就是可以和成员运算符in搭配使用。
再来看看官方文档更为全面的解释:
iterable
An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return succes
e2d9
sive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.

iterator
An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.
可以看到每个iterator都是iterable的。而list,dict,string等类型的数据都只是iterable,所以只能和in/for搭配使用,不能使用next()方法。
更详细的可见python官方文档  https://docs.python.org/3/library/stdtypes.html#iterator-types
(官方文档中4.6的 SequenceType也很有用哦)
问题四,built-in type set:
详见 https://docs.python.org/3/library/stdtypes.html?highlight=set#set-types-set-frozenset
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in 
dict
list
, and 
tuple
classes, and the 
collections
 module.)Like other collections, sets support 
x in set
len(set)
, and 
for x in set
. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.There are currently two built-in set types, 
set
 and 
frozenset
. The 
set
 type is mutable — the contents can be changed using methods like 
add()
 and 
remove()
. Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The 
frozenset
 type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.
add
(elem)Add element elem to the set.
remove
(elem)Remove element elem from the set. Raises 
KeyError
 if elem is not contained in the set.
discard
(elem)Remove element elem from the set if it is present.
pop
()Remove and return an arbitrary element from the set. Raises 
KeyError
 if the set is empty.
clear
()Remove all elements from the set.hashableAn object is hashable if it has a hash value which never changes during its lifetime (it needs a 
__hash__()
 method), and can be compared to other objects (it needs an 
__eq__()
 method). Hashable objects which compare equal must have the same hash value.Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.All of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their 
id()
.提炼一下,set类可变,frozenset类不可变,构造方法中参数应为iterable,同时将要成为set里的object的元素应为hashable,如:



a中,[1,2,3]为iterable(但是list不hashable),而1,2,3这三个要成为set元素的int是hashable的。
问题五,built-in functions sum方法:

sum
(iterable[, start])Sums start and the items of an iterable from left to right and returns the total. start defaults to 
0
. The iterable’s items are normally numbers, and the start value is not allowed to be a string.For some use cases, there are good alternatives to 
sum()
. The preferred, fast way to concatenate a sequence of strings is by calling 
''.join(sequence)
. To add floating point values with extended precision, see 
math.fsum()
. To concatenate a series of iterables, consider using 
itertools.chain()
.


sum方法还可以这么用。本题中就用到了。问题六,python类:
详见https://docs.python.org/3/tutorial/classes.html 
主要讲了9.2 python的作用域(Scopes)和命名空间(Namespaces),9.3 python类的定义,__doc__属性,类变量(class variable),mutable class variable可变类变量可以用来在不同实例间传递信息。9.5讲了继承和多重继承。9.6私有变量还没有看。
问题七,回到问题本身:
首先,想到将String J中的字母都存到set中去,然后利用python的生成器语法,对S中的字母是否在J中进行判断。
然而中间忘了,J本来就是Iterable的,所以可以不用set,直接利用生成器,就又减少了一行代码。
而利用map方法是怎么做的呢?
首先看map方法的用法:



跑个示例代码:



结果:



可以看出,map中可以接收多个iterable参数,但是这些参数不是随意的,应该是function方法有几个参数,这里就有几个对应的iterable。然后会在较短的iterable结束结束算法。对dict类型计算的是key。
另外,string.count()方法:
python的string.count(str, begin=0, end=len(string)函数用于返回str在string中出现的次数

所以结合string.count()和map()方法,就得到了第三种和第四种解法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: