1
Write a program to solve a classic ancient Chinese puzzle:
We count 35 heads and 94 legs among the chickens and rabbits in a
farm. How many rabbits and how many chickens do we have?
Use for loop to iterate all possible solutions.
分析:鸡的数量从0开始数,使用for循环,直到鸡兔腿数和等于94,输出并跳出循环
1 | heads = 35 |
运行截图
2
Please write a program which prints all permutations of [1,2,3]
Use itertools.permutations() to get permutations of list.
分析: itertools.permutations()函数返回的是可迭代元素的全排列
如果直接输出则返回它所在的地址,需要使用for循环遍历所有排列
1 | import itertools |
运行截图:
3
Please write a program which accepts a string from console and print
the characters that have even indexes.
Use list[::2] to iterate a list by step 2.
分析:输入字符串并以步长为2输出字符,可以使用input()读入,并使用list[::2]进行输出
1 | list = input("请输入:") |
运行截图:
4
Please write a program which accepts a string from console and print
it in reverse order.
Use list[::-1] to iterate a list in a reverse order.
分析:list[::-1]中的-1表示逆向以步长为1输出字符
1 | list = input("请输入:") |
运行截图:
5
Please write a program which count and print the numbers of each
character in a string input by console.
Use dict to store key/value pairs.
Use dict.get() method to lookup a key with default value.
分析:使用字典dict进行统计,
dict.get(key, default=None)
返回指定键的值,如果键不在字典中返回 default 设置的默认值
1 | st = input("请输入:") |
运行截图:
6
Define a class Person and its two child classes: Male and Female. All
classes have a method “getGender” which can print “Male” for Male
class and “Female” for Female class.
Use Subclass(Parentclass) to define a child class.
分析:主要考察了类的继承,以及父类方法的覆写
1 | class Person: |
运行截图:
7
With a given list [12,24,35,24,88,120,155,88,120,155], write a program
to print this list after removing all duplicate values with original order
reserved.
Use set() to store a number of values without duplicate.
分析:主要考察集合set
set() 创建空集合
set.add() 添加新元素
1 | list = [12,24,35,24,88,120,155,88,120,155] |
运行截图:
8
By using list comprehension, please write a program to print the list
after removing the value 24 in [12,24,35,24,88,120,155].
Use list’s remove method to delete a value
分析:
s1 &=s2 相当于 s1= s1&s2 即取s1和s2的交集并赋给s1
1 | s1 = {1,3,6,78,35,55} |
运行截图:
9
By using list comprehension, please write a program to print the list
after removing the value 24 in [12,24,35,24,88,120,155].
Use list’s remove method to delete a value.
分析:使用del删除第二个元素即24
1 | li = [12,24,35,24,88,120,155] |
运行截图:
10
By using list comprehension, please write a program to print the list
after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155].
Use list comprehension to delete a bunch of element from a
list.
Use enumerate() to get (index, value) tuple.
分析:主要考察推导式和enumerate() 函数
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
1 | li = [12,24,35,70,88,120,155] |
运行截图:
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论