数字格式化
三位一节的逗号
print("{:0,d}".format(a))
# >>> "{:0,d}".format(-9999)
# '-9,999'
字符串replace
str.replace(old, new[, max])
# max是最大替换次数
空间换时间:快速寻找小于N的所有素数
传统方法判断太慢了,这里有个用空间换取时间的解法:如果一个数p是素数,那么2p,3p到N*p(N * p < n+1)都是合数。对于合数,应该跳过。
def find_prime(n, result):
flag = [1]*(n+2)
p = 2
while p <= n:
result.append(p)
for i in range(2*p, n+1, p):
flag[i] = 0
while True:
p += 1
if flag[p] == 1: break
1067试密码
我跪在倒数第二个测试点了。
注意这个“再”字。如果是第N次错误,除了输出密码错误外还要输出一行账户锁定。
此外,注意不要写成 while p = input() and p != ‘#’
info = input().split()
n = int(info[1])
count = 0
p = input()
while p != '#':
if p == info[0]:
print("Welcome in")
exit(0)
else:
print("Wrong password: " + p)
if count == n-1:
print("Account locked")
exit(0)
count += 1
p = input()
构建矩阵问题
不要写list * num这样啊!!!这是复制引用!!!!
>>> matrix = [['-1']*5] * 5
>>> matrix
[['-1', '-1', '-1', '-1', '-1'], ['-1', '-1', '-1', '-1', '-1'], ['-1', '-1', '-1', '-1', '-1'], ['-1', '-1', '-1', '-1', '-1'], ['-1', '-1', '-1', '-1', '-1']]
>>> matrix[0][1] = 'c'
>>> matrix
[['-1', 'c', '-1', '-1', '-1'], ['-1', 'c', '-1', '-1', '-1'], ['-1', 'c', '-1', '-1', '-1'], ['-1', 'c', '-1', '-1', '-1'], ['-1', 'c', '-1', '-1', '-1']]
>>> width=3
>>> matrix = [['-1' for i in range(width)] for j in range(width)]
>>> matrix
[['-1', '-1', '-1'], ['-1', '-1', '-1'], ['-1', '-1', '-1']]
>>> matrix[0][1] = 'c'
>>> matrix
[['-1', 'c', '-1'], ['-1', '-1', '-1'], ['-1', '-1', '-1']]
1080 MOOC期终成绩
“输出顺序为按照总评分数(四舍五入精确到整数)递减。若有并列,则按学号递增”
这里涉及到字典排序问题,要求是按value降序,如果值相同,按key升序排列。
ans = sorted(total.items(),key=lambda i:(-i[1], i[0]))
本题要求计算 A/B,其中 A 是不超过 1000 位的正整数,B 是 1 位正整数。你需要输出商数 Q 和余数 R,使得 A=B×Q+R 成立。
直接用 // 和 % 就可以了。python3可以处理这么大的数字。
1081检查密码
该网站要求用户设置的密码必须由不少于6个字符组成,并且只能有英文字母、数字和小数点 .,还必须既有字母也有数字。
对每个用户的密码,在一行中输出系统反馈信息,分以下5种:
- 如果密码合法,输出Your password is wan mei.;
- 如果密码太短,不论合法与否,都输出Your password is tai duan le.;
- 如果密码长度合法,但存在不合法字符,则输出Your password is tai luan le.;
- 如果密码长度合法,但只有字母没有数字,则输出Your password needs shu zi.;
- 如果密码长度合法,但只有数字没有字母,则输出Your password needs zi mu.。
要点:先将 . 替换掉,然后用isXXX判断。
n = int(input())
for i in range(n):
info = input()
len_ = len(info)
if len_ < 6:
print("Your password is tai duan le.")
continue
a = info.replace(".", '')
if a.isdigit():
print("Your password needs zi mu.")
continue
if a.isalpha():
print("Your password needs shu zi.")
continue
if a.isalnum():
print("Your password is wan mei.")
continue
else:
print("Your password is tai luan le.")
continue