20讲课后编程题有bug
假如我们的字符串是 'ABCaABCbABCcABCd' 的时候,按照答案的代码,不会打印 'b',代码如下:str1 = '''ABCaABCbABCcABCd'''
c1 = 0
c2 = 0
c3 = 0
lenth = len(str1)
for i in range(lenth):
if str1 == '\n':
continue
if str1.isupper():
if c2 == 1:
c3 += 1
c1 = 0
else:
c1 += 1
continue
if str1.islower() and c1 == 3:
c2 = 1
c1 = 0
t = i
continue
if str1.islower() and c3 == 3:
print(str1,end='')
c1 = 0
c2 = 0
c3 = 0
i=0时,大写,此时c1=1,c2=0,c3=0
i=1时,大写,此时c1=2,c2=0,c3=0
i=2时,大写,此时c1=3,c2=0,c3=0
i=3时,小写,此时c1=0,c2=1,c3=0,t=3
i=4时,大写,此时c1=0,c2=1,c3=1
i=5时,大写,此时c1=0,c2=1,c3=2
i=6时,大写,此时c1=0,c2=1,c3=3
i=7时,小写,此时c1=0,c2=1,c3=3,所以打印a,然后重置c1=0,c2=0,c3=0
以此重复,当i=11时和i=7时的情况一样,理所当然会打印t=11时的字符,也就是'c',这样就跳过了t=7时的字符也就是'b'
有没有什么解决的办法,我想了好久没想明白怎么改代码 补充一下,题目的要求是
a) 每位密码为单个小写字母
b) 每位密码的左右两边均有且只有三个大写字母 小白的转行之路 发表于 2020-11-1 21:25
补充一下,题目的要求是
a) 每位密码为单个小写字母
b) 每位密码的左右两边均有且只有三个大写字母
这题目的两个要求 明显有冲突呀 str1 = '''ABCaABCbABCcABCd'''
c1 = 0
c2 = 0
c3 = 0
lenth = len(str1)
for i in range(lenth):
if str1 == '\n':
continue
if str1.isupper():
if c2 == 1:
c3 += 1
c1 = 0
else:
c1 += 1
continue
if str1.islower() and (c1 == 3):
c2 = 1
c1 = 0
t = i
continue
ifstr1.islower() and (c3 == 3):
print(str1,end='')
t = i #如果发现前一个字母符合条件,而当前字母是小写,则符合前3大写+小写规则
c1 = 3 #
c2 = 1 #
c3 = 0 #
else: #
c1 = 0
c2 = 0
c3 = 0 txxcat 发表于 2020-11-2 04:52
如果把字符串改为 'ABCaABCbbABCcABCd' 的话,这个代码还是不对...... txxcat 发表于 2020-11-2 04:52
我这个是旧代码,更新后的代码思路很清晰
https://fishc.com.cn/thread-42685-1-1.html 小白的转行之路 发表于 2020-11-2 20:44
如果把字符串改为 'ABCaABCbbABCcABCd' 的话,这个代码还是不对......
str1 = '''ABCaABCbABCcABCd'''
c1 = 0
c2 = 0
c3 = 0
lenth = len(str1)
for i in range(lenth):
if str1 == '\n':
continue
if str1.isupper():
if c2 == 1:
c3 += 1
c1 = 0
else:
c1 += 1
continue
if str1.islower() and (c1 == 3):
c2 = 1
c1 = 0
t = i
continue
ifstr1.islower() and (c3 == 3):
print(str1,end='')
t = i #
c1 = 0 #<---改这里
c2 = 1 #
c3 = 0 #
else: #
c1 = 0
c2 = 0
c3 = 0 txxcat 发表于 2020-11-2 22:10
古德古德
页:
[1]