Q1:Return the number (count) of vowels in the given string.We will consider a, e, i, o, and u as vowels for this Kata.The input string will only consist of lower case letters and/or spaces.也就是返回给定字符串中的元音字母(a, e, i, o, u)个数。
分析:这是一道非常基础的编程题,不加思索就想到用循环遍历字符串每个字母,然后一个if加或逻辑判断是否是元音,一个变量记录元音个数。
num = 0 for i in range(len(inputStr)): if inputStr[i] == ‘a‘ or inputStr[i] == ‘e‘ or inputStr[i] == ‘i‘ or inputStr[i] == ‘o‘ or inputStr[i] == ‘u‘: num = num +1
然鹅真正让我觉得有必要写在这里的是看了一条高赞答案,先贴代码:
def getCount(inputStr): return sum(1 for let in inputStr if let in "aeiou")
上述涉及到sum(iterable, [, start])函数
参数说明:iterable:可迭代对象,列表、元组、集合等。
start:指定相加的参数,缺省为0
上述代码在满足if条件的时候会生成一个1加入序列,最终包含多个1的序列作为sum的函数,对每个1求和,得到的是1的个数。
Q2:Remove First and Last Character
It‘s pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You‘re given one parameter, the original string. You don‘t have to worry with strings with less than two characters.去掉给定字符串的收尾字母。
很容易想到切片,即下面的写法:
def remove_char(s): return s[1 : len(s)]
然鹅python的脚码还有个隐藏彩蛋是,负数代表倒序。这个语法都学过,写的时候就不容易想起来了。所以最简洁的写法甚至不需要调用len函数。
def remove_char(s): return s[1 : -1]
原文:https://www.cnblogs.com/poi-kexin/p/11761897.html