# Python exercises (continuously updated)

Keywords: Python Pycharm IDE

## Example 001: digital combination

Title: there are four numbers: 1, 2, 3 and 4. How many three digits that are different from each other and have no duplicate numbers? How much is each?

The program analysis traverses all possibilities. Please shave off the duplicates.

```num = 0
for a in range(1, 5):
for b in range(1, 5):
for c in range(1, 5):
if ((a != b) and (a != c) and (b != c)):
print(a, b, c)
num += 1
print('Make up a non repeating three digit number{}individual'.format(num))```

## Example 002: complete square

Title: there is an integer from 1 to 100. After adding 100, it is a complete square, and 168 is a complete square. What is the number?

```Method 1
import math
for i in range(1, 100):
x = int(math.sqrt(i + 100))
y = int(math.sqrt(i + 100 + 168))
if x ** 2 == i + 100 and  y ** 2 == i + 100 + 168:
print(i)```
```Method 2
for i in range(1, 100):
x = int((i + 100) ** 0.5)
y = int((i + 100 + 168) ** 0.5)
if x ** 2 == i + 100 and y ** 2 == i + 100 + 168:
print(i)```

## Example 003: three number sorting

Title: enter three integers x, y and Z. please output these three numbers from small to large.

```Method 1
x = int(input("Please enter the first number, x:  "))
y = int(input("Please enter the first number, y:  "))
z = int(input("Please enter the first number, z:  "))
if x > y:
x, y = y, x
if x > z:
x, z = z, x
if y > z:
y, z = z, y
print(x, y, z)```
```Method 2
a = input("Please enter three numbers separated by English commas: ")
b = a.split(',')
for x in range(len(b)):
b[x] = int(b[x])
b.sort()
for y in b:
print(' '.join(str(y)), end=' ')```

## Example 004: Fibonacci I

Title: there is a group of numbers 1, 1, 2, 3, 5, 8... Please find out the law, implement it in code and print it out.

```a, b = 1, 0
for i in range(10):
a, b = b, b + a
print(b)```

## Example 005: Fibonacci II

There is a score sequence: 2 / 1, 3 / 2, 5 / 3, 8 / 5, 13 / 8, 21 / 13... Find the sum of the first 20 items of this sequence.

```a, b, c, d = 2, 1, 0, 0
for i in range(20):
c = a / b
d = round(d + c, 2)
a, b = a + b, a
print('The sum of the first 20 items is{}'.format(d))```

## Example 006: 99 multiplication

Title: output 9 * 9 multiplication formula table.

```Method 1
for x in range(1, 10):
for y in range(1, x + 1):
print('{} * {} = {}'.format(y, x, x * y), end='\t')
print()```
```Method 2
x = 0
while x < 9:
x += 1
y = 0
while y < x:
y += 1
print('{} * {} = {}'.format(y, x, x * y), end='\t')
print()```

## Example 007: raising rabbits

Title: a pair of rabbits give birth to a pair of rabbits every month from the third month after birth. After the third month, the little rabbit gives birth to another pair of rabbits every month. If the rabbits do not die, what is the total number of rabbits per month in a year?

```a, b = 1, 0
for i in range(1, 13):
a, b = b, b + a
print('The first{}The total number of rabbits per month is{}Only.'.format(i, b * 2))```

## Example 008: judging prime

Topic: judge how many primes there are between 100-200, and output all primes.

```num = 0
for x in range(100, 201):
for y in range(2, x):
if x % y == 0:
break
else:
print(x)
num +=1
print('100-200 Shared between{}Prime number'.format(num))```

## Example 009: number of daffodils

Title: print out all the "daffodils". The so-called "daffodils" refers to a three digit number, and the sum of each digit cube is equal to the number itself. For example, 153 is a "number of daffodils", because 153 = 1 * * 3 + 5 * * 3 + 3 * * 3.

```for i in range(100, 1000):
x = i // 100
y = i // 10 % 10
z = i % 10
if x ** 3 + y ** 3 + z ** 3 ==i:
print(i)```

## Example 010: repeat and add

Title: find the value of s=a+aa+aaa+aaaa+aa... A, where a is a number. For example, 2 + 22 + 222 + 2222 + 22222 (at this time, a total of 5 numbers are added), and the addition of several numbers is controlled by the keyboard.

```a = int(input('Please enter a positive integer:'))
c = 0
d = []
for i in range(b):
c += a * 10 ** i
d.append(c)
print(sum(d))```

## Example 011: monkeys steal peaches

Topic: monkeys eat peaches: on the first day, monkeys picked several peaches and ate half of them immediately. They were not addicted. They ate one more. The next morning, they ate half of the remaining peaches and one more. After that, I ate the remaining half and one every morning. When I wanted to eat again on the 10th morning, I saw that there was only one peach left. Ask how much you picked on the first day.

```s = 1
for i in range(9, 0, -1):
s = (s + 1) * 2
print('Monkey{}The number of peaches picked per day is{}'.format(i, s))```

## Example 012: competitors

Title: two table tennis teams compete with three players each. Team a consists of a, B and c, and team B consists of x, y and Z. Lots have been drawn to decide the list of matches. The players were asked about the list of matches. A says he doesn't compete with x, c says he doesn't compete with x and Z. please program to find out the list of players of the three teams.

```paly1 = ['a', 'b', 'c']
paly2 = ['x', 'y', 'z']
paly3 = []
for m in paly1:
for n in paly2:
if m + n != 'ax' and m + n != 'cx' and m + n != 'cz':
paly3.append(m + n)
for i in paly3:
print('The competition list is:Team a {} VS Team B {} '.format(i, i))```

## Example 013: reverse output I

Title: give a positive integer of no more than 5 bits.

Requirements: 1. Find out how many digits it is; 2. Print out the numbers in reverse order.

```num = input('Please enter a positive integer:')
num = num[::-1]
print('What you entered is{}Number of digits, its reverse number is{}'.format(len(num), num))```

## Example 014: reverse output II

Title: output the values of the list in reverse order.

```Method 1
list = [1,2,3,4,5]
list.reverse()
print(list)```
```Method 2
list = [1,2,3,4,5]
list = list[::-1]
print(list)```

## Example 015: palindrome number

Title: a 5-digit number to judge whether it is a palindrome number. That is, 12321 is the palindrome number, the number of bits is the same as 10000 bits, and the number of tens is the same as thousands.

```x = int(input('Please enter a five digit integer:'))
if x >= 0:
y = int(str(x)[::-1])
if x == y:
print(True)
else:
print(False)
else:
print(False)```

## Example 016: integer summation

Title: Statistics of the sum of 1 to 100.

```num = 0
for i in range(1, 101):
num += i
print(num)```

## Example 017: breaking the cycle

Title: find the square of the input number. If the square operation is greater than 100, exit. Otherwise, insert the square number into the list.

```ls = []
while True:
num = int(input('Please enter a positive integer:'))
if num **2 > 100:
break
else:
ls.append(num**2)
print(ls)```

## Example 018: exchange variables

Title: the values of two variables are exchanged by function.

```def num(x, y):
a, b = x, y
print('Before exchange a={},b={}'.format(a,b))
a, b = b, a
print('After exchange a={},b={}'.format(a, b))
num(10, 20)```

## Example 019: exchange location

Title: input array, exchange the largest with the first element, exchange the smallest with the last element, and output array.

```list = [3, 2, 5, 7, 8, 1, 6]
x = max(list)
y = min(list)
list[list.index(x)], list = list, x
list[list.index(y)], list[-1] = list[-1], y
print(list)```

## Example 020: making function

Title: write a function. When the input n is an even number, call the function to find 1 / 2 + 1 / 4 +... + 1/n. when the input n is an odd number, call the function 1 / 1 + 1 / 3 +... + 1/n

```n = int(input('Please enter a positive integer:'))
def num(x):
s = 0
if x % 2 == 0:
for i in range(2, x + 1, 2):
s = round(s + 1 / i, 2)
else:
for i in range(1, x + 1, 2):
s = round(s + 1 / i, 2)
return s
print(num(n))```

## Example 021: finding unknowns

Title: 809 *= 800*??+ 9*?? Where?? Represents two digits, 809 *?? Four digits, 8 *?? The result is double digits, 9 *?? The result is 3 digits. Please?? Represents two digits, and 809 *?? Results after.

```for i in range(10, 100):
if len(str(809 * i)) == 4 and len(str(8 * i)) == 2 and len(str(9 * i)) == 3:
print('The mysterious two digits are{}:'.format(i))
print('809*??The result is{}:'.format(809 * i))```

## Example 022: character summation

Title: input several integers separated by English commas from the keyboard, calculate the sum of all input integers and output.

For example, entering 1,2,3 returns 6

```n = input('Please enter several integers separated by English commas')
nums = n.split(',')
s = 0
for i in nums:
s += int(i)
print(s)```

## Example 023: initial letter capital

Title: convert the first letters of all words in list1 to uppercase and print.

```list1 = ['apple', 'banana']
for i in range(len(list1)):
list1[i] = list1[i].capitalize() #It is also possible to write as list1[i].title()
print(list1)```

## Example 024: integer squared

Title: write a program whose function is to obtain the positive integer input by the user from the keyboard and output the square of the inverse of the positive integer (the inverse of 123 is 321). If you enter a non positive integer, the output does not meet the requirements.

```num = input('Please enter a positive integer:')
if int(num) > 0:
num = num[::-1]
num = int(num) ** 2
print(num)
else:
print('Non conformance')```

## Example 025: judging integers

Title: write a function to judge whether the input string is an integer string. If yes, it will output True, and if not, it will output False. Enter 123 to return True, and - 123 and a123 to return False.

```Method 1
a = input('Please enter a string:')
print(True if a.isnumeric() == True else False)```
```Method 2
a = input('Please enter a string:')
try:
if int(a)>0:
print(True)
else:
print(False)
except:
print(False)```

## Example 026: letter de duplication

Title: the definition function accepts a string as a parameter and returns the de duplicated string; The function body must use a dictionary to handle strings; Call the function to de duplicate the string and print the result. For example, change 'AaaBbb' to 'AaBb'

```def str1(s):
dict1 = {}
for i in s:
dict1[i] = 0
str2 = "".join(dict1.keys())
return str2

print(str1('AaaBbb'))```

Example 036: who is the largest

Title: write a program to return to who is the oldest person in the dictionary

```dict = {'Wen Wen': 18, 'Orange orange': 23, 'Beibei': 20}
list = []
for x,y in dict.items():
list.append(y)
z = max(list)
for i in dict:
if dict[i]==z:
print('The oldest is:{}'.format(i))```

## Example 037: 100 yuan 100 chicken

Title: Wenwen wants 100 yuan to buy 100 chickens, 5 yuan for cocks, 4 yuan for hens and 1 yuan for chicks. Please write a program to find out how many cocks, hens and chicks you can buy for 100 yuan. The total number is just 100.

```for x in range(1,100):
for y in range(1,100):
z = 100 -x-y
if (5*x+4*y+z/3==100):
print(x,y,z)```

## Example 038: digital switching

Title: please exchange two adjacent numbers in the list. For example, ls = [2,1,4,3] returns the list ls = [1,2,3,4]

```a = [2,1,4,3,6,5,8,7,10,9,12,11]
b = a[1::2]
c = a[0::2]
d = []
for i in  list(zip(b,c)):
d.append(i)
d.append(i)
print(d)```

## Example 039: random number

Title: please write a random two-color ball number program.

```import random
while True:
a = random.sample(range(1,34),6)
a.sort()
b = str(random.randint(1,16))
for i in range(len(a)):
a[i]=str(a[i])
print('The random two-color ball number is:')
print('Red ball: {}'.format( ' '.join(a)))
c = input('Continue random number: 1.y or Y Continue 2.n or N sign out')
if c=='n' or c=='N':
break```

## Example 040: contact information

Title: there are two class information tables class1 and class2, including personnel mobile phone number, QQ number and personnel wechat information table WX.

1. Please combine the information of the two classes and add each wechat number in WX to the corresponding personnel information table,

For example, 'Xiaoxin': [13913000001, 1819122001,'xx9907'], if there is no micro signal in WX, the micro signal is the mobile phone number;

2. Modify Xiaoxin's mobile phone number to 13913000006;

3. Query service can be provided. Enter the person name and print the corresponding person information table. If the person does not exist, print "sorry! No contact information of xx classmate can be queried".

class1 = {
' Xiaoxin ': [13913000001, 1819122001],
' Xiaoliang ': [13913000002, 1819122002],
' Xiao Gang ': [13913000003, 1819122003]
}

class2 = {
' Liu ': [13914000001, 1819123001],
' King ': [13914000002, 1819123002],
' Big Zhang ': [13914000003, 1819123003]
}
WX = {
' Xiaoxin ':' xx9907 ',
' Xiaogang ':' gang1004 ',
' King ':'jack_w',
' Big Liu ':'liu666'

```class1 = {
'Xiaoxin': [13913000001, 1819122001],
'Xiao Liang': [13913000002, 1819122002],
'Xiao Gang': [13913000003, 1819122003]
}

class2 = {
'Da Liu': [13914000001, 1819123001],
'king': [13914000002, 1819123002],
'Da Zhang': [13914000003, 1819123003]
}
class1.update(class2)
WX = {
'Xiaoxin': 'xx9907',
'Xiao Gang': 'gang1004',
'king': 'jack_w',
'Da Liu': 'liu666'
}

for x in WX:
if x in class1:
class1[x].append(WX[x])

for y in class1:
if y not in WX:
class1[y].append(class1[y])

class1['Xiaoxin'] = 13913000006

name = input('Please enter the name of the person to be queried:')
if name in class1:
print('{}What is the student's personal information:phone number:{},QQ number:{},Wechat number:{}'.format(name, class1[name], class1[name], class1[name]))
else:
print('Sorry! No query found{}Contact information of students'.format(name))```

## Example 041: who is the best

Title: six students participate in the competition. Please find out the best sound, remove the highest and lowest scores, and print the player's name from high to low

good_voice = {
' Wen Wen ': [90,94,97,86,85,89,88,85],
' Wen Wen ': [91,91,92,98,90,96,90,95],
' Beibei ': [96,86,97,96,87,86,86,96],
' Orange ': [95,95,94,93,97,98,99,95],
' Zhuang Zhuang ': [95,87,94,94,93,99,96,97],
' Lin Lin ': [89,97,91,95,89,94,97,92]
}

```good_voice = {
'Wen Wen':[90,94,97,86,85,89,88,85],
'Smell':[91,91,92,98,90,96,90,95],
'Beibei':[96,86,97,96,87,86,86,96],
'Orange orange':[95,95,94,93,97,98,99,95],
'Strong':[95,87,94,94,93,99,96,97],
'Lin Lin':[89,97,91,95,89,94,97,92]
}

average = {}
for x in good_voice:
y = round((sum(good_voice[x])-max(good_voice[x])-min(good_voice[x]))/6,2)
average[x]=y
rank = dict(sorted(average.items(),key=lambda c:c,reverse=True))
print('The ranking of this competition is:')
for n in rank:
print('player{}-average:{}'.format(n,rank[n]))```

## Example 042: who did not participate

Title: there are 25 students in the class. The class plans to hold a thorough examination. Some students take one, some take two, some take three, and some don't take any. Please find out how many people didn't take the exam? Which students take one, two or three exams respectively?

test = {
' Chinese ': [' Li   Lei ',' Han Meimei ',' Wang Xiaogang ',' Chen   Static ',' Square   Xiang ',' Wen   Wen '],
' Mathematics': ['Li   Ran ',' Li Fangfang ',' Liu Xiaobei ',' Fang   Xiang ',' sun Yihang ',' Yu Xiaoman '],
' English ': [' Chen   Static ',' Square   Xiang ',' Liu Xiaobei ',' Han Meimei ',' Shi Xiaoran ',' Wen   Wen ']

}

```test = {
'language': ['Li Lei', 'Mei Mei Han', 'Xiao Gang Wang', 'Chen Jing', 'Direction', 'Wen Wen'],
'mathematics': ['Li Ran', 'Li Fangfang', 'Liu Xiaobei', 'Direction', 'Sun Yihang', 'Yu Xiaoman'],
'English': ['Chen Jing', 'Direction', 'Liu Xiaobei', 'Mei Mei Han', 'Shi Xiaoran', 'Wen Wen']
}
course = {}
for x in test:
for y in test[x]:
if y in course:
course[y] = course[y] + 1
else:
course[y] = 1
a = []
b = []
c = []
count = tuple(sorted(course.items(),key=lambda x:x))
print('All students have{}People take the exam, yes{}No one took the exam.'.format(len(course),25-len(course)))
for z in count:
if z==1:
a.append(z)
elif z==2:
b.append(z)
else:
c.append(z)
print('Who are the students taking an exam:{}'.format(','.join(a)))
print('Who are the students taking the second exam:{}'.format(','.join(b)))
print('Who are the students taking the three exams:{}'.format(','.join(c)))
```

## Example 043: finding the median

Title: please define a function to return the median of the combined two lists.

For example, ls = [1,2,3] returns 2, and ls = [1,2,3,4] Returns (2 + 3) / 2 = 2.5

```def median(nums1, nums2):
num = (nums1 + nums2)
num.sort()
if len(num) % 2 == 0:
x1 = num[int(len(num) / 2) - 1]
x2 = num[int(len(num) / 2)]
return (x1 + x2) / 2
else:
return num[int(len(num) / 2)]
```

## Example 044: sum of two numbers

Title: given an integer list nums and an integer target value target, please find the two integers with and as the target value target in the list and return their array subscripts.

For example, input: num = [2,7,8], target = 9, output: [0,1]   Num = [3,3,8], target = 6 output: [0,1]

```def twoSum(nums, target):
for x in range(len(nums)):
for y in range(x + 1, len(nums)):
if nums[x] + nums[y] == target:
print([x, y])

twoSum([2, 7, 8], 9)
twoSum([1, 4, 3, 3, 2, 5], 6)```

## Example 045: business card management

Title: please write a business card management system, which requires five functions: adding personnel, deleting personnel, modifying personnel and querying personnel.

```mpglq = {
'Smell': [18, 12300000001],
'Wen Wen': [21, 12300000002]
}
while True:
mp = input('Please select the operation content(1.Add business card 2.Delete business card 3.Modify business card 4.Query business card 5.Exit the system):')
if mp == '1':
tel = input('Please enter your phone number:')
mpglq[name] = [age, tel]
elif mp == '2':
name = input('Please select the name of the person you want to delete:')
mpglq.pop(name)
elif mp == '3':
xx = input('Please select the information to be modified(1.Name 2.Age 3.Telephone):')
if xx == '1':
name = input('Please enter the name of the person to be modified:')
new_name = input('Please enter the new name of the modifier:')
mpglq[new_name] = mpglq[name]
mpglq.pop(name)
elif xx == '2':
name = input('Please enter the name of the person to be modified:')
new_age = input('Please enter the new age of the modifier:')
mpglq[name] = new_age
elif xx == '3':
name = input('Please enter the name of the person to be modified:')
new_tel = input('Please enter the new telephone number of the modifier:')
mpglq[name] = new_tel
elif mp == '4':
name = input('Please enter the name of the person to be queried:')
nr = input('Please enter the content of the inquirer(1.Age 2.Phone 3.Age and telephone):')
if nr == '1':
print('{}What is your age{}'.format(name, mpglq[name]))
elif nr == '2':
print('{}Your phone number is{}'.format(name, mpglq[name]))
elif nr == '3':
print('{}What is your age{},The phone is{}'.format(name, mpglq[name], mpglq[name]))
elif mp == '5':
break
print(mpglq)```

A primary school student in the programming world, some exercises encountered in the learning process are for partners to exchange and learn,

Code optimization also asks the big guys to give more advice. The topics are constantly updated. Please also leave a message if you encounter interesting topics.

Posted by Infinitus 8 on Sun, 28 Nov 2021 17:21:22 -0800