一些Python代码
Posted candyyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一些Python代码相关的知识,希望对你有一定的参考价值。
统计字符串中的字符个数。未通过
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])
以上是关于一些Python代码的主要内容,如果未能解决你的问题,请参考以下文章