Python after class exercises (junior / October 11, 2021)

Code Taoist 2021-10-28 18:32:43
python class exercises junior october

Topic 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? 

analysis : The title is typical ” Chicken and rabbit in the same cage “ problem , Solving the problem depends on the algorithm :

1. As the tip says , use for Circular violence ( Brute force yyds

def tonglong(heads,legs):
for i in range(heads): # Don't forget to range()
if i*4+(35-i)*2==legs:
return i
return None # Wrong judgment
def num(heads=35,legs=94):
tu=tonglong(heads,legs)
if(tu!=None):
print(" Number of Rabbits :"+str(tu))
print(" Number of chickens :"+str(heads-tu))
else:
print(" Data error !")
num()

2. According to the ingenious function solution : Number of Rabbits =( Number of legs - Number of heads *2), Number of chickens = Number of heads - Number of Rabbits

# Only core algorithms
def tonglong(heads,legs):
tu=int((legs-heads*2)/2)
if tu>=0 and (tu*4+(heads-tu)*2)==legs:
return tu
else:
return None

Running results :

​​​​​​​​​​​​​​​

Topic two

Please write a program which prints all permutations of [1,2,3].

Simple method , Use the... In the prompt itertools modular Medium permutation function . The functionality : Arrange and combine the elements in a given list , Returns the list of each permutation .

from itertools import permutations # Import itertools In bag permutation
for i in permutations([1,2,3]):
print(i)

Running results :

Two layers of for The circular brute force cracking method is not repeated here .

Topic three

Please write a program which accepts a string from console and print the characters that have even indexes.

This question tests our familiarity with lists , Anything can be listed , The problem can be solved by skillfully using the step size :

txt=list(input())
print("".join(txt[::2]))

Running results :

Use for Loops can also be solved , This question shows Python The simplicity and simplicity of the code

Topic four

Please write a program which accepts a string from console and print it in reverse order.

Same as question 3 , Use step size [::-1]:

txt=list(input())
print("".join(txt[::-1]))

Running results :

Topic 5

Please write a program which count and print the numbers of each character in a string input by console.

The key to this problem is to connect the letters with the number of occurrences , So a dictionary is a good choice :

dict={}
c=list(input())
for i in c:
dict[i]=dict.get(i,0)+1 #dict.get(i,0) If key i non-existent , Then return to 0, It means that 0 Time
for i,j in dict.items(): # Output specifications
print('%s,%s'%(i,j))

Running results :

This question can also be found one by one , namely a How many , After counting, output , Then look for the next letter , But the time complexity is O(n^2), Obviously not as good as using a dictionary .

Topic 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.

This problem requires the use of parent-child knowledge , In limine Forget the Do not understand the mechanism of parent-child classes , After reading the title, I have no clue , After that, check the reference book 、 Ask your classmates , Know how the subclass should inherit the parent class 、 The connection between them . The code is as follows :

class Person(object):
def __init__(self,gender):
self.gender=gender
def getGender(self):
print(self.gender)
class Male(Person):
def __init__(self):
super(Person,self).__init__()# Use the initialization method of the parent class to initialize the inherited properties
self.gender="Male"
class Female(Person):
def __init__(self):
super(Person,self).__init__()
self.gender="Female"
male=Male()
female=Female()
male.getGender()
female.getGender()

Running results :

About Python The knowledge points of the middle class still need to be strengthened and consolidated !!!

Topic 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.

Remove duplicate numbers from the list , You can use data types set Characteristics of :set It's a Unordered non repeating element set

#l=list(input().split(',')) # This comment allows the program to be extended to be inputable
l=[12,24,35,24,88,120,155,88,120,155]
s=list(set(l))
s.sort()
print(s)

Running results :

If not used set(), It can be used for Loop to achieve de duplication .

Topic 8

With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists.

Sure enough , This question can also witness Python The simplicity of , Use it directly set The intersection operation of :

l1 = set([1,3,6,78,35,55])
l2 = set([12,24,35,24,88,120,155])
l1 &= l2
print(list(l1))

Running results :

set It can realize the of data hand over (&)、 and (|)、 Bad (-)、 repair (^

reflection :set Have non repeatability , If there is a pair in each of the two lists 24, After the intersection, only one is left , Is it still in line with the meaning of the title ?

Stupid method : Use for A nested loop .

Topic nine

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].

This problem can be used list Of remove() function :

l1 = [12,24,35,24,88,120,155]
l1.remove(24)
print(l1)

Running results :

We found that , Only one... Is deleted from the list 24, We can optimize the code :

l1 = [12,24,35,24,88,120,155]
while 24 in l1: # Join in while loop , Determine whether there are still... In the list 24
l1.remove(24)
print(l1)

Running results :

There are no more left in the list 24 了 .

This question uses for Loops can also solve .( All things can be for Circulation ...)

Topic ten

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].

This question needs to pay attention to the deletion order , Direct sequential deletion will change the subscript of the elements to be deleted later , This results in the deletion of the wrong element , You can delete... In reverse order .

l1 = [12,24,35,70,88,120,155]
for i,item in enumerate(l1):# Use enumerate() Each local function lists the data and the corresponding subscript
print(i,item)
print('***********')# Separate before and after deletion
del l1[5]# Delete in reverse order , Will not destroy the entire set of data structures , It will not cause the deleted data to be disordered
del l1[4]# If necessary, it can be changed to for Loop delete
del l1[0]
for i,item in enumerate(l1):
print(i,item)

Running results :

Use... In questions enumerate() Function to enumerate each element and its subscript , Make the element change more obvious .

版权声明
本文为[Code Taoist]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/10/20211013015545897N.html

  1. matlab改为python,偏最小二乘回归分析的一个程序
  2. 应该是python基础题希望能用基础方法解决
  3. 想找个会Python的做场外援助,上课没听明白
  4. Python程序,插入不了MySQL的date格式
  5. (初学者)关于Python操作Excel问题
  6. 求人来解答这两道Python题
  7. python中用三引号换行,举例说明
  8. python数码管该怎么用,十四段
  9. python进行中文文本聚类(切词以及Kmeans聚类)
  10. Python - 字符串作为文件
  11. Python - 转换二进制为ASCII码
  12. Python - 在段落中计算令牌
  13. Python - 重新格式化段落
  14. Python - 排序线
  15. Python - 字符串不变性
  16. Python - 文本摘要
  17. Python+微信小程序开发(六)双向绑定和前后端通信
  18. 基于Anaconda搭建Django环境
  19. Django基础篇(2)--视图
  20. 288页的python编程文档,从入门到实践,入门看这一篇就够了
  21. Python Web实战:Flask + Vue 开发一个漂亮的词云网站
  22. 让我深夜十二点催她睡觉,我用 Python 轻松搞定!
  23. 4.Python-常用语句
  24. 【Python】基于FastAPI的Restful规范实践
  25. 【Python】FastAPI脚手架:规范FastAPI后端接口项目开发
  26. 【Python】单元测试实践内部指南
  27. Django开发中使用Cache缓存提升10倍效率
  28. python如何重复执行程序命令而不是一次退出
  29. python 编写程序题使用for循环
  30. 一道简单的python作业题,就是不能运行
  31. 使用python回答,望有人来帮
  32. 用python插入日期格式到mysql数据库中,一直运行不了。
  33. 关于以下Python问题如何解决
  34. Use Python to help the financial sister solve the PDF splitting. The sister said it was great...
  35. Comment résoudre les problèmes Python suivants
  36. 如何使用python建立列表?新手入门
  37. python 3d画图库matplotlib,第一次用
  38. python 3d畫圖庫matplotlib,第一次用
  39. Python 3D painting Library matplotlib, utilisé pour la première fois
  40. Comment créer une liste en utilisant python? Débutant
  41. python定义列表 新手入门级别
  42. Liste de définition Python débutant
  43. 如何用Python实现,急!!xdm
  44. 如何用Python實現,急!!xdm
  45. Comment implémenter en python, urgent!! Xdm
  46. 新猿木子李:0基础学python培训教程 Python操作Redis之hash类型
  47. python导入模块变量后,打印的值固定不变了,大老们怎么破。
  48. Why is my rust slower than Python!
  49. 用Python给喜欢的女孩写一个办公小工具,她说棒极了!
  50. python中\t是空一个tab,那这个1.2后面怎么没空格?
  51. Il y a un onglet vide en python, alors pourquoi n'y a - t - il pas d'espace après ce 1.2?
  52. 关于python中pygame.display.set_mode()的一点小问题
  53. 猜我能否用Python编程抢到茅台?已经全部开源到GitHub了
  54. python数据分析numpy 补充短试题
  55. 2W + word long article, an article on literacy python, numpy and pandas, recommended collection!
  56. Python培训-自动化运维常用库
  57. On the magical usage and principle of weak reference in Python
  58. Formation python - bibliothèques d'exploitation et de maintenance automatisées
  59. Python培训-HTTP与HTTPS之间的区别
  60. Python有哪些高级特性?