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

https://pythonmana.com/2021/10/20211013015545897N.html