小白的转行之路 发表于 2020-11-1 21:23:36

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'
有没有什么解决的办法,我想了好久没想明白怎么改代码

小白的转行之路 发表于 2020-11-1 21:25:10

补充一下,题目的要求是
a) 每位密码为单个小写字母
b) 每位密码的左右两边均有且只有三个大写字母

阿奇_o 发表于 2020-11-1 22:10:30

小白的转行之路 发表于 2020-11-1 21:25
补充一下,题目的要求是
a) 每位密码为单个小写字母
b) 每位密码的左右两边均有且只有三个大写字母

这题目的两个要求 明显有冲突呀

txxcat 发表于 2020-11-2 04:52:09

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

小白的转行之路 发表于 2020-11-2 20:44:28

txxcat 发表于 2020-11-2 04:52


如果把字符串改为 'ABCaABCbbABCcABCd' 的话,这个代码还是不对......

小白的转行之路 发表于 2020-11-2 21:42:09

txxcat 发表于 2020-11-2 04:52


我这个是旧代码,更新后的代码思路很清晰
https://fishc.com.cn/thread-42685-1-1.html

txxcat 发表于 2020-11-2 22:10:05

小白的转行之路 发表于 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

小白的转行之路 发表于 2020-11-3 22:41:41

txxcat 发表于 2020-11-2 22:10


古德古德
页: [1]
查看完整版本: 20讲课后编程题有bug