编程题
1.乱序匹配
https://ceshiren.com/t/topic/13957
# set(iterable) 集合 不重复
# str1.count(str2) str2在str1出现的次数
def scramble(s1: str, s2: str):
for s in s2:
if (s not in s1) or s1.count(s) < s2.count(s):
return False
return True
2.完美列表
https://ceshiren.com/t/topic/14568
# all(iterable) 对可迭代对象所有的都为true才返回true
def is_nice(nums: list) -> bool:
return all([ i-1 in nums or i+1 in nums for i in nums])
3.回文
https://ceshiren.com/t/topic/19787/13
def palindrome(num):
pal_list = []
str_num = str(num)
for l in range(2,len(str_num)+1):
for start in range(len(str_num)-l+1):
temp_num = str_num[start:start+l]
if temp_num == temp_num[::-1] and (int(temp_num) not in pal_list) and (temp_num[0] != '0'):
pal_list.append(int(temp_num))
pal_list.sort()
return pal_list
assert palindrome(1221) == [22, 1221]
assert palindrome(34322122) == [22, 212, 343, 22122]
assert palindrome(1001331) == [33, 1001, 1331]
assert palindrome(13598) == []
4.列表中移动0到列表末尾
https://ceshiren.com/t/topic/12939
def move_zeros(num_list):
# 方式1
# reverse 降序
# return sorted(num_list,reverse=True,key=bool)
# 方式2
# num_list.sort(reverse=True, key=bool) # 不能直接返回这个调用,直接打印这个返回None,得打印num_list
# return num_list
# 方式3
for i in range(len(num_list)):
if num_list[i] == 0:
num_list.pop(i)
num_list.append(0)
return num_list
5.交替位二进制
https://ceshiren.com/t/topic/21775
bin()是将数字转为二进制
# 方式1:因为是交替的,所有肯定不存在 11或者00在里面
def binary_num(num):
bin_num = bin(num)[2:]
if '00' not in bin_num and '11' not in bin_num:
return True
return False
#方式2:逐个比较,前一位和后一位相同,那就返回False
def binary_num(num):
bin_num = bin(num)[2:]
for i in range(len(bin_num)-1):
if bin_num[i] == bin_num[i+1]:
return False
return True
6.单词前缀
https://ceshiren.com/t/topic/16552
sentence.split(‘xx’) 使用xx分隔句子sentence
word.startswith(‘xx’) xx是word的前缀么
def word_prefix(sentence:str, word:str)-> int:
word_list = sentence.split()
for i in range(len(word_list)):
if word_list[i].startswith(word):
return i+1
return 0