# Python learning diary 05

Keywords: Python less Programming

# Day.05

2020.02.23
Today's main learning content is tuple and training seven exercises to consolidate the basis of the previous study.

## 1. tuple

Tuples are created in the same way as lists, except that lists are square brackets [] while tuples are round brackets (). The biggest difference is that elements in tuples cannot be changed, while lists can. There are two points to pay attention to: first, although the elements in the ancestor cannot be modified, the tuples can be connected and combined by the plus sign +, such as: tup3 = tup1 + tup2; second, although the elements in the tuple cannot be deleted individually, the entire tuple can be deleted through the del sentence. After deletion, if you want to use print() to access, an error will be reported.
In other aspects, tuples and lists are almost the same. They can also be indexed and intercepted, but there are many fewer built-in functions than lists

Function & method describe
len(tuple) Count the number of elements in a tuple
max(tuple) Returns the maximum value in a tuple element
min(tuple) Returns the minimum value in a tuple element
tuple(list) Convert list to tuple

## 2. Practice of constructing program logic

Because tuples are relatively simple, today we go directly to practice:

```#Exercise 1: find out the number of daffodils
#The number of Narcissus is also called super perfect number invariant, narcissistic number, self idempotent, Armstrong number,
#It's a three digit number, and the sum of the cubes in each digit is exactly equal to itself,
#For example: 1 ^ 3 + 5 ^ 3 + 3 ^ 3 = 153.
#Specific implementation method:
print('All daffodils are:')
for a in range(1, 10):
for b in range(10):
for c in range(10):
if (a**3 + b**3 + c**3) == (a*100 + b*10 + c):
print('%d' % (a*100+b*10+c), end=' ')  #end = 'is added to prevent line wrapping
#Test results:
#All daffodils are:
#153 370 371 407
```

Summary: This is a classic topic. I used Tan Haoqiang's book after class exercises to learn c + + to ask for daffodils. The idea is relatively simple, a is a hundred bit, b is a ten bit, c is a bit, and then use triple for loop to traverse one by one to find the number that meets the conditions. Note that a of the hundred bit starts from 1.

```#Exercise 2: inversion of positive integers
#Specific implementation method:
print('Positive integer inversion:')
while 1:
a = list(input('Please enter a positive integer:'))
a.reverse()
for x in range(len(a)):
print(a[x], end='')
print(end='\n')
#Test results:
#Positive integer inversion:
#Please enter a positive integer: 123456789
#987654321
#Please enter a positive integer: 147258369
#963852741
#Please enter a positive integer: 123
#321
#Please enter a positive integer: 1234
#4321
#Process finished with exit code -1
```

Summary: it's easy to use python to realize. It doesn't need to consider the number of bits on each bit as C + + does to be split and then stored in the array, then inverted and output one by one. At the same time, it doesn't need to consider the number of bits of positive integer. Here, I directly choose to save the number read by the keyboard into the list, and then reverse it through the reverse() function provided with the list, and then output each element of the list by the for loop.

```#Exercise 3: 100 yuan and 100 chickens
#Hundreds of money and hundreds of chickens are the mathematical problems put forward by Zhang Qiujian, an ancient Chinese mathematician, in the book "the book of calculation":
#One chicken is worth five, one hen is worth three, and three chickens are worth one. To buy a hundred chickens for a hundred bucks, ask the chicken Weng, the hen mother and the chicks how much are they?
#Translated into modern Chinese:
#Five yuan for a rooster, three yuan for a hen, three yuan for a chick, and 100 yuan for a hundred chickens. How many are there for each rooster, hen and chick?
#Specific implementation method:
for gongji in range(21):
for muji in range(34):
for xiaoji in range(301):
if (gongji*5 + muji*3 + xiaoji * (1/3) == 100) and (gongji + muji + xiaoji == 100):
print('100 Yuan can buy%d A cock,%d Hen,%d Chicken only' % (gongji, muji, xiaoji))
#Test results:
#100 yuan can buy 0 roosters, 25 hens and 75 chickens
#RMB 100 can buy 4 cocks, 18 hens and 78 chickens
#You can buy 8 cocks, 11 hens and 81 chickens for 100 yuan
#You can buy 12 cocks, 4 hens and 84 chickens for 100 yuan
```

Summary: it's better to frame the quantity range of each chicken by calculation, and then judge the output result by if condition. The only thing to note is that in the range(x) function mentioned many times before, if there is only one parameter x, it starts from 0 by default and ends at x (x cannot be retrieved).

```#Exercise 4: CRAPS gambling game
#CRAPS, also known as citidice, is a very popular table game in Las Vegas.
#The game uses two dice. Players can get points by rolling two dice.
#The simple rules are:
#If the player rolls the dice for the first time at 7 or 11, the player wins;
#If the player shakes out 2, 3 or 12 points for the first time, Chuang Jiasheng;
#Other points, the player continues to roll dice, if the player rolls out 7 points, Chuang Jiasheng;
#If the player shakes out the points of the first shake, the player wins;
#Other points, players continue to want dice, until the winner.
#Specific implementation method:
import random
print('CRAPS Gambling games:')
count = 0
while 1:
if count != 0:
print('A new round of games!!!')
start = int(input('Please press 0 to start rolling dice and other keys to end the game:'))
if start == 0:
a = random.randint(1, 6)  #Generate integer random numbers from 1 to 6
b = random.randint(1, 6)
num1 = a+b
print('Your dice are%d and%d，The number of points for the first shake is%d' % (a, b, num1))
if a+b == 7 or a+b == 11:
print('Congratulations! You win!')
count += 1
elif a+b == 2 or a+b == 3 or a+b == 12:
print('Pity! The dealer won!')
count += 1
else:
while 1:
c_ontinue = int(input('If you still don't know the winner, please continue to roll the dice by 0:'))
if c_ontinue == 0:
a = random.randint(1, 6)
b = random.randint(1, 6)
print('Your dice are%d and%d，Sum is%d，The number of points for the first shake is%d' % (a, b, a+b, num1))
if a+b == num1:
print('Congratulations! You win!')
count += 1
break
elif a+b == 7:
print('Pity! The dealer won!')
count += 1
break
else:
print('End the game')
break
#Test results:
#CRAPS gambling game:
#Please press 0 to start rolling dice and other keys to end the game: 0
#The dice you roll are 4 and 4, and the number of points you roll for the first time is 8
#You still have no winner. Please continue to roll the dice by 0: 0
#The dice you roll are 6 and 6. The sum is 12. The number of points you roll for the first time is 8
#You still have no winner. Please continue to roll the dice by 0: 0
#The dice you roll are 1 and 1. The sum is 2. The number of points you roll for the first time is 8
#You still have no winner. Please continue to roll the dice by 0: 0
#The dice you roll are 1 and 4, the sum is 5, and the number of points you roll for the first time is 8
#You still have no winner. Please continue to roll the dice by 0: 0
#The dice you roll out are 5 and 4. The sum is 9. The number of points you roll for the first time is 8
#You still have no winner. Please continue to roll the dice by 0: 0
#The dice you roll are 1 and 5. The sum is 6. The number of points you roll for the first time is 8
#You still have no winner. Please continue to roll the dice by 0: 0
#The dice you roll are 2 and 5. The sum is 7. The number of points you roll for the first time is 8
#Pity! The dealer won!
#A new round of games!!!
#Please press 0 to start rolling dice and other keys to end the game: 0
#The dice you roll are 1 and 1, and the number of points you roll for the first time is 2
#Pity! The dealer won!
#A new round of games!!!
#Please press 0 to start rolling dice and other keys to end the game: 1
#End the game
```

Summary: the general idea of this topic is relatively simple, mainly divided into the first round and the next several rounds, because the methods to determine the winner are different. The results of the first round use if condition to judge whether to enter the next few rounds, and the latter rounds use while loop. If the winner is selected, break will be enough. Here a new random module is used. Because it cannot be accessed directly, it needs to import. Its main function is to generate random numbers (simulation dice rolling).

Students who want to know more about random module can This web site Reading (notes in the bottom)

```#Exercise 5: generate the first 20 numbers of Fibonacci series
#Fibonacci series is characterized by the fact that the first two numbers of the series are 1,
#Starting from the third number, each number is the sum of the first two numbers.
#Specific implementation method:
fibonacci = [1, 1]
while 1:
fibonacci.append(fibonacci[len(fibonacci)-1]+fibonacci[len(fibonacci)-2])
if len(fibonacci) == 20:
break
for x in range(len(fibonacci)):
print('%d' % fibonacci[x], end=' ')
#Test results:
#1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
```

Summary: Fibonacci is also a frequent customer of program algorithm problems, and the ideas are relatively clear. As long as the last digit is equal to the sum of the first two digits, there is basically no big problem. Here, I choose to use list implementation, because it is very convenient to use append() to add elements behind the list.

```#Exercise 6: find the perfect number within 10000
#Perfect number is also called complete number or complete number. The sum of all its true factors (i.e. divisors other than itself) is exactly equal to itself.
#For example: 6 (6 = 1 + 2 + 3) and 28 (28 = 1 + 2 + 4 + 7 + 14) are perfect numbers.
#Specific implementation method:
print('10000 The perfect numbers within are:')
for x in range(1, 10000):
sum = 0
for y in range(1, x):
if x % y == 0:
sum += y
if sum == x:
print('%d' % x, end=' ')
#Test results:
#The perfect numbers within 10000 are:
#6 28 496 8128
```

Summary: it is also a relatively simple problem, which can be solved by two layers of for loop. The first layer for loop is used to traverse numbers from 1 to 10000. The second layer for loop is used to find the divisor corresponding to each number. Finally, it can determine whether the sum of the divisors is equal to itself.

```#Exercise 7: output all prime numbers within 100
#Specific implementation method:
print('100 Prime within:')
for x in range(2, 100):
count = 0
for y in range(1, x+1):
if x % y == 0:
count += 1
if count == 2:
print('%d' % x, end=' ')
#Test results:
#Prime numbers within 100:
#2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
```

Summary: I've done a topic to judge whether it's prime number or not before, so I'll just elaborate here. The idea is the same as that of the previous question. There are two layers of for loops. The second layer is used to find the number of divisors. According to the definition of prime numbers, if the number of divisors is equal to 2, then it is a prime number, so it is relatively simple.

## 3. Today's summary

Today, I practiced seven very classic questions. I think no matter what language I speak, I will encounter some of them more or less. These topics mainly cover the use of conditional structure and cyclic structure. When practicing, they will unconsciously use variable knowledge such as list, which undoubtedly exercises python's basic skills and enhances people's logical thinking ability.
Finally, I would like to share a sentence from Luo Hao:
For beginners of programming languages, after learning Python's core language elements (variables, types, operators, expressions, branch structures, loop structures, etc.), one of the things they must do is try to use the knowledge they have learned to solve problems in reality. In other words, exercise their own algorithms described in human natural languages (Methods and steps to solve problems )The ability to translate into Python code, which can only be achieved through a lot of practice.  Published 5 original articles, won praise 0, visited 29

Posted by azn_romeo_4u on Fri, 06 Mar 2020 23:32:34 -0800