lichanglin1987 发表于 2020-4-2 11:35:49

python 20讲课后作业

lenth = len(str1)
counta = 0
countb = 0
for i in range(lenth-4):
    if str1 == '\n':
      continue
    if str1.islower():
      for each in str1:
            if each.isupper():
                counta += 1
      for some in str1:
            if some.isupper():
                countb += 1   
      if counta == 3 and countb == 3:
            if (str1.islower()) and (str1.islower()):
                print(str1,end="")

这个代码问题出在哪里?为什么运行之后没有东西出来?

永恒的蓝色梦想 发表于 2020-4-2 11:38:27

str1是啥?

lichanglin1987 发表于 2020-4-2 11:44:41

就是这个文档

lichanglin1987 发表于 2020-4-2 11:49:03

永恒的蓝色梦想 发表于 2020-4-2 11:38
str1是啥?

在楼上

永恒的蓝色梦想 发表于 2020-4-2 11:52:11

lichanglin1987 发表于 2020-4-2 11:49
在楼上

你这个代码要干嘛啊?

lichanglin1987 发表于 2020-4-2 12:05:35

永恒的蓝色梦想 发表于 2020-4-2 11:52
你这个代码要干嘛啊?

    a) 每位密码为单个小写字母Powered by bbs.fishc.com
    b) 每位密码的左右两边均有且只有三个大写字母j~

raimond 发表于 2020-4-2 12:58:15

str1 = 'AAAaBBBddfasSSS3GGGok'
lenth = len(str1)
counta = 0
countb = 0
for i in range(lenth-4):
    if str1 == '\n':
      continue
    if str1.islower():
      for each in str1:
            if each.isupper():
                counta += 1
      for some in str1:
            if some.isupper():
                countb += 1
      if counta == 3 and countb == 3:
            if (str1.islower()) and (str1.islower()):
                print(str1,end="")

你这个代码只能检测开始第一部分里面是否有符合要的, 你替换字符测试几次看下

txxcat 发表于 2020-4-2 13:31:08

判断思路对了, counta、countb初始化位置错了,现在的位置,只有第一次循环有正确值,后面会一直累加,当然就不会有正确答案了,换到循环里就OK了。
lenth = len(str1)
for i in range(lenth-4):
    counta = 0      #放这里才能每次循环有正确的值
    countb = 0
    if str1 == '\n':
      continue
    if str1.islower():
      for each in str1:
            if each.isupper():
                counta += 1
      for some in str1:
            if some.isupper():
                countb += 1   
      if counta == 3 and countb == 3:
            if (str1.islower()) and (str1.islower()):
                print(str1,end="")

txxcat 发表于 2020-4-2 13:48:59

虽然以上的代码可以运行,但是效率不高,一个是没必要判断'\n',因为str(1).islower()就会排除掉'\n',所以删除这个判断程序正常运行,二是累加计算大写的方法,你的代码无论如何,都会把前后6个字符检测一遍,没有必要,只要一个不符,就可以判断不符了,修改代码如下:
lenth = len(str1)
for i in range(lenth-4):
    allupper=True
    if str1.islower():
      for each in str1+str1:
            if not each.isupper():
                allupper=False
                break
      if allupper:
            if (str1.islower()) and (str1.islower()):
                print(str1,end="")
页: [1]
查看完整版本: python 20讲课后作业