20讲中动动手第1题
以下是我的代码:h = '''需要筛选的字符串'''
a = 0
b = []
if h.isupper() and h.islower() and h.isupper() and not(h.isupper):
b.append(h)
while a+8 < len(h):
if not(h.isupper()):
if h.isupper():
if h.isupper():
if h.isupper():
if h.islower():
if h.isupper():
if h.isupper():
if h.isupper():
if not(h.isupper()):
b.append(h)
a += 1
print(b)
我自己分析了一下和小甲鱼答案的思路,发现:
优点是在 for i in range(length)中每个字符仅参与寻找一遍,我的答案相当于除了前后几个字符,大部分字符都需要参与8遍运算,比较耗费资源。另外我的遇到\n时会判断为非大写字母,如果字符串为:
'''UTGgUY\nY'''
那g是不会被找出的,但是答案里的g就会,因为答案里认为\n两边的字符算连着的。
请大神帮忙分析一下我的答案与小甲鱼答案的其它利弊,多谢。 本帖最后由 jackz007 于 2020-11-19 17:16 编辑
h = '''需要筛选的字符串'''
s = 'a' + '' . join(h . split('\n')) + 'a' # 消灭 h 中的换行符 '\n',并在字符串首尾添加字符 'a' 以便判断规则同时适用于字符串内部和首尾
p = ''
for k in range(4 , len(s) - 4):
if s . islower() and s . isupper() and s . islower() and s . isupper() and s . islower():
p += s
print(p)
单纯冲代码上来说,你的代码太多 if 了,而程序员其实蛮忌讳的就是一堆 if 语句嵌套
这种代码就是很‘丑’的代码,甲鱼哥的更为整洁些
如果想排除 \n 换行符的影响,你只需要将字符串使用 replace() 将 '\n' 替换为 '' 空字符串即可
页:
[1]