统计字符串中的字符个数。未通过
def countchar(string): c_dict = {} for i in range(26): c_dict[chr(ord('a')+i)] = 0 for c in string: if c in c_dict: c_dict[c] += 1 return list(c_dict.values()) if __name__ == "__main__": string = input() string = string.lower() print(countchar(string))
以下为通过代码,注意字典是无序的
def countchar(string): c_dict = {} c_list = [] for i in range(26): c_dict[chr(ord('a')+i)] = 0 for c in string: if c in c_dict: c_dict[c] += 1 c_list = c_dict.items() c_list= sorted(c_list, key = lambda x:x[0]) c_list = [x[1] for x in c_list] return c_list if __name__ == "__main__": string = input() string = string.lower() print(countchar(string))
判断完全数
#判断一个数字是否是全数字 def is_pan(x): x = str(x) n = len(x) flag = True for i in range(1,n+1): if str(i) not in x: flag = False break return flag def pandigital(nums): lst = [] for x in nums: if is_pan(x): lst.append(x) return lst if __name__ == "__main__": lst = pandigital(eval(input())) #调用函数根据结果输出 for x in lst: print(x) if lst == []: print('not found')
统计词频
def countfeq(s): lst = s.split() w_dict = {} for w in lst: if w not in w_dict: w_dict[w] = 1 else: w_dict[w] += 1 return w_dict if __name__ == "__main__": s = "Not clumsy person in this world, only lazy people, only people can not hold out until the last." s = s.replace(',','') s = s.replace('.','') s = s.replace(':','') s = s.replace(')','') s_dict = countfeq(s.lower()) word = input() #基于s_dict判断word的词频并输出(可能是0次) if word not in s_dict: print(0) else: print(s_dict[word])
基数排序(未通过)
def func(mylist): # your code here base_lists = [] for i in range(10): base_lists.append([]) re_list = mylist[:] base = 1 while base <= 10000: for x in re_list: base_lists[x//base%10].append(x) re_list.clear() for ls in base_lists: re_list.extend(ls) ls.clear() base *= 10 return re_list mylist = eval(input()) print(func(mylist))
猜数字,你在一定范围内想一个是,程序来猜,每次猜你要回答,高了,低了,对了,最后还要对可能不存在的情况做判断
#!/usr/bin/env python3 # # Number Guessing Game! def prompt(num): # Use this function to ask the user about a guess. # This function returns 'H', 'L', or 'C'. print(f"My guess: {num}") inp = "" while inp.upper() not in ['H', 'L', 'C']: inp = input(f"Is {num} too (H)igh, too (L)ow, or (C)orrect? ") return inp.upper() def play(max): print(f"Think of a number from 1 to {max}.") input("When you're ready, press Enter.") # # Write your code here! # if __name__ == '__main__': play(1000)
子字符串
>>> is_substring('bad', 'abracadabra')
False
>>> is_substring('dab', 'abracadabra')
True
>>> is_substring('pony', 'pony')
True
>>> is_substring('', 'balloon')
True
>>> is_substring('balloon', '')
False
查找子字符串第一次出现的位置
def locate_first(string, sub): index = 0 while index < (len(string) - len(sub) + 1): if string[index : index + len(sub)] == sub: return index index += 1 return -1
查找子字符串出现的所有位置
def locate_all(string, sub): matches = [] index = 0 while index < len(string) - len(sub) + 1: if string[index : index + len(sub)] == sub: matches.append(index) index += len(sub) else: index += 1 return matches