[python Programming] introduction series 1.0

Keywords: Python

Question 1:

Write a program that will find all these numbers, which can be divided by 7, but not a multiple of 5, 2000 to 3200. The resulting numbers should be printed on one line in comma separated order.

Solution: use range (begin, end).

Knowledge points:

(1) Use the. Join function to interval comma output. Note that the join function parameter is a string and cannot be a number;

(2) The normal output method is: for i in list: print (i, end = ')

code:

list1=[]
for i in range(2000,3201):
    if i%7==0 and i%5>0:
        list1.append(i)
print(",".join(str(i) for i in list1))
# print(",".join('%s' % i for i in list1))
    #   list1.append(str(i))
# print(','.join(list1))

Question 2:

Write a program that can calculate the factorial of a given number. The results should be printed on one line in comma separated order. Assuming the following input is provided to the program: 8, the output is: 40320.

Knowledge points: note that the input accepted by input is a string, which should be converted into an integer first;

code:

num=input()
num=int(num)
res=1
for i in range(1,num+1):
    res*=i
print(res)

Here, supplement solution 2 and write a function to realize:

def Factorial(n):
    if n==0:
        return 1
    else:
        return n*Factorial(n-1)

num=int(input())
print(Factorial(num))

Question 3:

Using the given integer n, write a program to generate a dictionary containing (i, i*i), which contains integers between 1 and n (both). Then the program should print the dictionary.
Suppose the following inputs are provided to the program: 8
Then the output is: {1:1, 2:4, 3:9, 4:16, 5:25, 6:36,, 7:49, 8:64}

Knowledge points: master the usage of functions.

code:

def Generator(n):
    dic={}
    for i in range(n+1):
        dic[i]=i*i
    return dic

num=int(input())
print(Generator(num))

Question 4:

Write a program that accepts the comma separated sequence of numbers in the console and generates a list and tuple containing each number. Suppose the following inputs are provided to the program:

34, 67, 55, 33, 12, 98

Then the output is: [34 ',' 67 ',' 55 ',' 33 ',' 12 ',' 98 ']
               ('34', '67', '55', '33', '12', '98')

Knowledge points: use split function and findall function.

(1) Str.split (STR = '', num) [n], the first parameter represents the separator (space or comma), the second parameter represents the number of slices, and the parameter n represents the number of slices after segmentation, which can be used directly; Returns a list of intercepted strings.

(2) re.findall ( pattern,   string,   flags=0): returns all strings matching pattern in string in the form of array.

code:

import re
str1=input()
# l=str1.split(',')
# print(l)
list=re.findall(r'[0-9]+',str1)
print(list)
print(tuple(list))

Question 5:

Define a class with at least two methods: (1) getString: get string from console input; (2) printString: print the string of uppercase parent.

Also include simple test functions to test class methods.

Knowledge point: constructor__ init__ () method. It is usually used to define initialization with parameters in a class. You can declare attributes (i.e. variables) in the class. The first parameter must be self, and subsequent parameters are passed in and defined by yourself. The parameter passed in must be assigned to the parameter in the class, that is, the self parameter, before it can be used in the class.

code:

class MyString():
    def __init__(self):
        self.s=''

    def getString(self):
        print('Please enter a string:')
        self.s = input()

    def printString(self):
        print(self.s.upper())

str1=MyString()
str1.getString()
str1.printString()

Supplement: note the class definition specification, class + class name, which is generally used first__ init__ () method defines the parameters in the class, and then defines the method with def. The object defined in the following text can use the method directly.

Question 6:

Write a program to calculate and print the value according to the given formula:. The following are fixed values for C and H: C is 50. H is 30. D is a variable whose value should be entered into the program in a comma separated sequence.

The example assumes that the input sequence of the program is comma separated: 100150180,
Program output: 18, 22, 24

Tip: if the received output is decimal, it should be rounded to its nearest value (for example, if the received output is 26.0, it should be printed as 26).

Knowledge points: rounding function and square root function

code:

import math
def Calculate(n):
    res=math.sqrt((2*50*n)/30)
    res=round(res)
    return res

str1=input()
num_list=str1.split(',')
print_list=[]
for i in num_list:
    res=Calculate(int(i))
    print_list.append(str(res))
print(','.join(print_list))

Question 7:

Write a program to generate a two-dimensional array with 2-digit numbers, X and y as input. The element value in row i and column j of the array should be i*j.
Note: I = 0,1., X - 1;     j = 0, 1, ­ Y-1.
The example assumes that the program has the following inputs: 3 and 5
Then the program output is: [0,0,0,0,0], [0,1,2,3,4], [0,2,4,6,8]]

Knowledge points: pay attention to the method of generating two-dimensional array. There is a point. If a list is multiplied three times to generate a binary list, the three arrays will be updated synchronously when updating the array, so it cannot be generated by multiplication. Here is a method to generate a two-dimensional list using two methods, both of which can be used.

code:

def Generate_Array(row,col):
    # arr=[[] for i in range(row)]
    # for i in range(row):
    #     for j in range(col):
    #         arr[i].append(i*j)
    arr=[[0 for i in range(col)] for j in range(row)]
    for i in range(row):
        for j in range(col):
            arr[i][j]=i*j
    return arr

print('Please enter two numbers:')
str1=input()
dimentions=[int(x) for x in str1.split(',')]
arr=Generate_Array(row=dimentions[0],col=dimentions[1])
print(arr)

Question 8:

Problem: write a program to accept the comma separated word sequence as input, sort alphabetically, and print the words according to the comma separated sequence. Suppose the following inputs are provided to the program:
without,hello,bag,world
The output is:
bag,hello,without,world

Knowledge points: pay attention to the difference between the list.sort function and the sorted function. The former can sort the sequence of the same elements in the list, whether numbers or strings, as long as the element types are the same, and the latter can only sort the number list and strings.

code:

print('Please enter word sequence:')
str1=input()
words=[x for x in str1.split(',')]
words.sort()
print(','.join(words))

Question 9:

Write a program that accepts a line sequence as input and prints a line after capitalization of all characters in the sentence.
Suppose the following inputs are provided to the program:
Hello world
Practice makes perfect
The output is:
HELLO WORLD
PRACTICE MAKES PERFECT

Knowledge point: it is mainly to continuously accept input, so just input while True all the time.

code:

lines=[]
while True:
    str1=input()
    if str1:
        lines.append(str1.upper())
    else:
        break
for i in lines:
    print(i)

Question 10:

Write a program that accepts a series of space separated words as input, and print these words after deleting all duplicate words and sorting them alphabetically.
Suppose the following inputs are provided to the program:
hello world and practice makes perfect and hello world again
The output is:
again and hello makes perfect practice world

Knowledge points: use the set container to automatically delete duplicate data, remove duplicate elements in the list, and return a set; Sort string function list.sort().

code:

lines=input()
str1=lines.split(' ')
list1=list(set(str1))
list1.sort()
print(' '.join(list1))

Question 11:

Write a program that accepts a series of comma separated 4-bit binary numbers as input, and then check whether they can be divided by 5. Numbers divisible by 5 will be printed in comma separated order.
Example:
0100,0011,1010,1001
Then the output should be:
1010

Knowledge points: convert binary into decimal numbers. int (x, base=10) is used here. The first X can be a numeric string or number, and the following base indicates the base of the previous X.

code:

print('Please enter the number sequence:')
str1=input()
list1=[]
nums=[x for x in str1.split(',')]
for i in nums:
    int_num=int(i,2)
    if int_num%5==0:
        list1.append(i)
print(','.join(list1))

Question 12:

The website requires users to enter a user name and password to register. Write a program to check the validity of the password entered by the user.
The following are the criteria for checking passwords:
1. There is at least one letter between [A-Z]
2. There is at least one number between [0-9]
1. There is at least one letter between [A-Z]
3. At least 1 character in [$@]
4. Minimum transaction password length: 6
5. Maximum length of transaction password: 12
Your program should accept a series of comma separated passwords and will be checked against the above criteria. Qualified passwords will be printed, each separated by a comma.
Example: if the following password is used as the input of the program:

ABd1234@1,a F1#,2w3E*,2We3345
Then, the output of the program should be:

ABd1234 @ 1

Knowledge points: use of re.search function and string matching.

code:

import re
print('Please input a password:')
password=input().split(',')
value=[]
for p in password:
    if len(p)<6 or len(p)>12:
        continue
    if not re.search('[a-z]',p):
        continue
    elif not re.search('[0-9]',p):
        continue
    elif not re.search('[A-Z]',p):
        continue
    elif not re.search('[@#$]',p):
        continue
    else:
        pass
    value.append(p)
print(','.join(value))

Question 13:

You need to write a program to sort tuples (name, age, height) in ascending order, where name is a string and age and height are numbers. Tuples are entered by the console. The sorting criteria are:
1: Sort by name;
2: Then sort according to age;
3: Then sort by score.
Priority is name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John','20','90'),('Jony','17','91'),('Jony','17','93'),('Json','21 ','85'),('Tom','19','80')]

Knowledge points: when multiple sorting keys are involved in sorted sorting, the operator.itemsetter method in the operator library is used to select multiple fields for multi-level sorting. The format is as follows:

sorted(lists,key=lambda list:list[2])
sorted(lists,key=operator.itemgetter(1),reverse=False) # The default flash is in ascending order
sorted(lists,key=operator.itemgetter(1,2))

However, the list sorting list.sort() function can automatically implement this sorting function.

code:

import operator
list1=[]
while True:
    tup=input()
    if not tup:
        break
    list1.append(tuple(tup.split(',')))
l=sorted(list1,key=operator.itemgetter(0,1,2))
# list1.sort()
print(l)

Question 14:

Use a generator to define a class that iterates over numbers divisible by 7 between a given range of 0 and n.

Knowledge points: knowledge about generator yield. Yield can be understood as a return. A function with a generator is called a generator function. When the generator function is called and meets yield, the generated value is returned from this step, and the original function is returned to continue execution. The next time the generator function is called, it will be executed from the last returned place without starting from the beginning.

code:

def Generator_Num(n):
    i=0
    while i<n:
        i=i+1
        if i%7==0:
            yield i
    return

for i in Generator_Num(100):
    print(i)

Question 15:

Write a program to calculate the frequency of words in the input. Output after sorting the keys alphabetically.
It is assumed that the following inputs are provided to the program:

New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.

Then, the output should be:

2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1

Knowledge points: the dictionary and the get method in the dictionary are used. dic.get (key, default=None), where key is the key to find in the dictionary. Default if the specified key does not exist, the default value will be returned.

code:

l=input()
dic1={}
for i in l.split(' '):
    dic1[i]=dic1.get(i,0)+1
words=sorted(dic1.keys())
for i in words:
    print('%s:%d'%(i,dic1[i]))

Question 16:

Python has many built-in functions. Please write a program to print some Python built-in function documents, such as abs(), int(), and add documents for your own functions

Knowledge points: the method to view documents is__ doc__, Take abs as an example__ doc__.

code:

print(abs.__doc__)
print(int.__doc__)
print(input.__doc__)

def square(num):
    '''Return the square value of the input number.
    The input number must be integer.
    '''
    return num ** 2

print(square(2))
print(square.__doc__)

Summary:

(1) print method: two methods ending with comma and space, including the usage of join function;

(2) Usage of function;

(3) The input function input accepts a string;

(4) String segmentation functions: re.findall and split;

(5) Constructor in class:__ init__ () method;

(6) Note the class definition specification, class + class name, which is generally used first__ init__ () the method defines the parameters in the class, and then defines the method with def. The object defined later can use the method directly;

For the rest, see another blog: summary of knowledge points in the introductory series.

Posted by belaraka on Sat, 18 Sep 2021 19:16:47 -0700