当需要使用递归检查给定数字是奇数还是偶数时,可以使用递归。递归计算较大问题的小部分输出,并将这些部分组合起来以给出较大问题的解决方案。示例下面是一个演示——在线演示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!")输出Enter the number that needs ... 阅读更多
当需要显示存在于第一个字符串中但不位于第二个字符串中的字母时,将从用户处获取两个字符串输入。“集合”用于查找两个字符串之间的差异。Python 带有一个称为“集合”的数据类型。“集合”包含唯一的元素。集合可用于执行诸如交集、差集、并集和对称差集之类的操作。示例下面是一个演示——在线演示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 ... 阅读更多
当需要创建一个字典,其键是第一个字符,关联值是以该字符开头的单词时,将使用“分割”方法、字典和简单的“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)输出Enter the ... 阅读更多