Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#383 Python all() & any() & string.count() & string.ascii_lowercase #3

Open
LiuL0703 opened this issue Apr 16, 2017 · 3 comments
Open

Comments

@LiuL0703
Copy link
Owner

all()
Return True if all elements of the iterable are true (or if the iterable is empty).
如果iterable的所有元素为真 , 则all(iterable)返回True,否则返回False;函数等价于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

例如:

all(['a', 'b', 'c', 'd'])  # True
all([‘a’,'b','','d'])      #False

any() 则与all()相对
Return True if any element of the iterable is true. If the iterable is empty, return False.
如果iterable的任一元素为true 则返回true

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
any(['a', 'b', 'c', 'd'])  # True
any(['a','',''])      #True
@LiuL0703
Copy link
Owner Author

LiuL0703 commented Apr 16, 2017

string.count()
语法:

str.count(sub, start= 0,end=len(string))
  • sub -- 搜索的子字符串
  • start 搜索起始位置默认为第一个字符串 即索引为0
  • end 搜索结束位置 默认为最后一个字符串位置
    例子:
#!/usr/bin/python

str = "this is string example....wow!!!";

sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)  
sub = "wow";
print "str.count(sub) : ", str.count(sub)    
str.count(sub, 4, 40) :  1
str.count(sub, 4, 40) :  2

array.count(x)
返回数组中x 出现的次数

@LiuL0703
Copy link
Owner Author

LiuL0703 commented Apr 16, 2017

string.ascii_lowercase 'abcdefjhijklmmnopqrstuvwxyz'

@LiuL0703
Copy link
Owner Author

#383 的 一种解法

class Solution(object):
 def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        return all(ransomNote.count(i)<=magazine.count(i) for i in string.ascii_lowercase)

@LiuL0703 LiuL0703 changed the title #383 all() & any() & string.count() & string.ascii_lowercase #383 Python all() & any() & string.count() & string.ascii_lowercase Apr 26, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant