|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 观测者 于 2017-4-7 16:28 编辑
以下为代码:
- file = open('string2.txt','r',encoding='utf8')
- str1 = file.read()
- countA = 0 # 统计前边的大写字母
- countB = 0 # 统计小写字母
- countC = 0 # 统计后边的大写字母
- length = len(str1)
- for i in range(length):
- #①=======================================================================
- if str1[i] == '\n': #如果字符是转行符
- continue
- #②=======================================================================
- if str1[i].isupper(): #如果字符是大写字母,进行下列判断
- if countB: #countB如果出现即小写字母数量不等于0,运行下列代码:
- countC += 1 #开始统计后边的大写字母
- else: #若没有出现小写字母,则清空后面大写字母的统计,开始统计前面的大写字母
- countC = 0
- countA += 1
- #③=======================================================================
- if str1[i].islower(): #如果字符是小写字母,进行下列判断
- if countA != 3: #如果字符前面三个字符部不是大写字母,即该字符不符合条件,不是其中一位密码
- countA = 0 #重置,重新统计
- countB = 0
- countC = 0
- else: #如果字符前面三个字符部是大写字母,即该字符符合其中一个条件(左边三位为大写字母)
- if countB: #如果已经存在小写字母,即出现了两个小写字母,则清空记录,重新统计
- countA = 0
- countB = 0
- countC = 0
- else: #如果该字符前后是唯一的小写字母
- countB += 1 #则countB记录出现小写字母,准备开始统计countC,即后面是否为三个大写
- countC = 0
- target = i #记录这个字符位置
- #[color=Red]④[/color]===============================================================
- if countA == 3 and countC == 3: #如果前后都为三个大写字母,则符合其中一个条件
- if [color=Red]i+1 != length [/color]and str1[i+1].isupper(): #如果后面第四个字符也是大写,则不符合其中一个条件
- countB = 0 #清空B和C的记录,重新统计
- countC = 0
- else: #如果后面第四个字符不是大写字母,即后面仅有三个大写字母,则符合其中一个条件,至此该字符完全符合密码条件
- print(str1[target], end=' ') #打印结果,并清空记录,进入下一轮统计
- countA = 3
- countB = 0
- countC = 0
-
- file.close()
复制代码
以下为问题:
在程序的第④部分中 i+1 != length 的作用是什么?
=============================================================================
以下为实现程序的第二种方法:利用切片
- with open('string2.txt','r',encoding='utf8') as file:
- str1 = file.read()
- for i in range(3,len(str1)-4):
- if str1[i].islower() and str1[i-3:i].isupper() and str1[i+1:i+4].isupper() and[color=Red] str1[i-4].islower() and str1[i+4].islower() [/color]and "\n" not in str1[i-3:i+4]:
- print(str1[i],end="")
复制代码
以下为问题:
str1[i].islower() and str1[i-3:i].isupper() and str1[i+1:i+4].isupper() 我知道这行是检测小写字母左右是否为三个大写字母
and str1[i-4].islower() and str1[i+4].islower() 而这行代码我没看懂,是检测小写字母是否相邻的吗?希望能得到解释。
以下为附件:
|
|