当需要使用递归检查给定数字是奇数还是偶数时,可以使用递归。递归计算较大问题的小片段的输出,并将这些片段组合起来以给出较大问题的解决方案。示例以下是相同的演示 -实时演示def check_odd_even(my_num): if (my_num < 2): return (my_num % 2 == 0) return (check_odd_even(my_num - 2)) my_number = int(input("Enter the number that needs to be checked:")) if(check_odd_even(my_number)==True): print("The number is even") else: print("The number is odd!")输出输入需要检查的数字 ... 阅读更多
当需要显示存在于第一个字符串中但不存在于第二个字符串中的字母时,会从用户那里获取两个字符串输入。“set”用于查找两个字符串之间的差异。Python 带有一个称为“set”的数据类型。此“set”仅包含唯一的元素。set 可用于执行诸如交集、差集、并集和对称差集等操作。示例以下是相同的演示 -实时演示my_str_1 = input("Enter the first string...") my_str_2 = input("Enter the second string...") my_result = list(set(my_str_1)-set(my_str_2)) print("The letters in first string but not in second ... 阅读更多
当需要创建一个字典,其键为第一个字符,关联值为以该字符开头的单词时,将使用“split”方法、字典和简单的“if”条件。示例以下是相同的演示 -实时演示my_string=input("Enter the string :") split_string = my_string.split() my_dict={} for elem in split_string: if(elem[0] not in my_dict.keys()): my_dict[elem[0]]=[] my_dict[elem[0]].append(elem) else: if(elem not in my_dict[elem[0]]): my_dict[elem[0]].append(elem) print("The dictionary created is") for k, v in my_dict.items(): print(k, ":", v)输出输入 ... 阅读更多
当需要在字典的帮助下统计字符串中出现的单词频率时,将使用“split”方法分割值,并使用列表推导式。“list comprehension”是迭代列表并在其上执行操作的简写。列表可以用来存储异构值(即任何数据类型的数据,如整数、浮点数、字符串等)。示例以下是相同的演示 -实时演示my_string = input("Enter the string :") my_list=[] my_list=my_string.split() word_freq=[my_list.count(p) for p in my_list] print("The frequency of words is ...") print(dict(zip(my_list, word_freq)))输出输入 ... 阅读更多