示例:
输入
hello world
输出
5
考察split()函数和取列表最后一个值
s = input()
lst = s.split(' ')
print(len(lst[-1]))
示例:
输入
ABCDEF
A
输出
1
考察大小写转换upper(), lower()函数和count()函数
s = input()
c = input()
lower = s.count(c.lower())
upper = s.count(c.upper())
print(lower + upper)
示例:
输入:
3
2
2
1
输出:
1
2
考察sorted()函数与集合
import sys
while True:
try:
lst = []
n = int(sys.stdin.readline())
for i in range(n):
lst.append(int(sys.stdin.readline()))
sort = sorted((set(lst)))
for i in sort:
print(i)
except:
break
示例:
输入
abc
123456789
输出
abc00000
12345678
90000000
考察字符串切片
字符串切片,可以越界:如s=‘abc’ s[:5]–>‘abc’
import sys
s1 = sys.stdin.readline().strip()
s2 = sys.stdin.readline().strip()
a = [s1[i:i + 8] for i in range(0, len(s1), 8)]
b = [s2[i:i + 8] for i in range(0, len(s2), 8)]
c = a + b
for i in c:
if len(i) < 8:
i += '0' * (8 - len(i))
print(i)
示例:
输入
0xA
输出
10
while True:
try:
s = input()
s = s[2:]
hash_map = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
ans = 0
for i, c in enumerate(s[::-1]):
ans += hash_map.get(c) * 16 ** i
print(ans)
except:
break
示例:
输入
180
输出
2 2 3 3 5
一个整数的质因子,一定都小于其开平方的数,如340
2 ∗ 170 2*170 2∗170
4 ∗ 85 = 2 ∗ 2 ∗ 85 4*85=2*2*85 4∗85=2∗2∗85
5 ∗ 68 5*68 5∗68
10 ∗ 34 = 2 ∗ 5 ∗ 34 10*34=2*5*34 10∗34=2∗5∗34
17 ∗ 20 = 17 ∗ 2 ∗ 2 ∗ 5 17*20=17*2*2*5 17∗20=17∗2∗2∗5
即去重质因子为2,5,17
所有质因子为2, 2, 5, 17
import sys
while True:
try:
num = int(sys.stdin.readline().strip())
# 0和1都不是质数,从2开始
i = 2
# 结果字符串
res = ''
# 一个整数的质因子
while i * i < num:
if num % i == 0:
res += str(i) + ' '
num = num // i
else:
i += 1
res += str(num) + ' '
print(res)
except:
break
示例:
输入
5.5
输出
6
考察int()取整为向下取整
import sys
while True:
try:
float_num = float(sys.stdin.readline().strip())
if float_num % 1 >= 0.5:
print(int(float_num) + 1)
else:
print(int(float_num))
except:
break
示例:
输入
4
0 1
0 2
1 2
3 4
输出
0 3
1 2
3 4
考察字典的使用
import sys
while True:
try:
n = int(sys.stdin.readline().strip())
hash_map = {}
for i in range(n):
de = sys.stdin.readline().split(' ')
key = int(de[0])
value = int(de[1])
if key in hash_map:
hash_map[key] += value
else:
hash_map[key] = value
lst = sorted(hash_map.keys())
for i in lst:
print(str(i)+' '+str(hash_map.get(i)))
except:
break
示例:
输入
9876673
输出
37689
考察字典的使用
import sys
while True:
try:
num_str_reverse = sys.stdin.readline().strip()[::-1]
hash_map = {}
no_repeat = ''
for i in num_str_reverse:
if i not in hash_map:
no_repeat += i
hash_map[i] = 1
else:
continue
print(int(no_repeat))
except:
break
示例:
输入
abc
输出
3
ord()函数可以返回字符的ASCII码
while True:
try:
s = input()
ret = set()
for i in s:
if 0 <= ord(i) <= 127 and (i not in ret):
ret.add(i)
print(len(ret))
except:
break