Getting Started with Python - write a simple little program with 3 pycharm

Environment: Win10 operating system; Python3.7; Pycharm 

Topic Source: PTA

Programming Example 1: Date Format

Different countries have different habits of writing the date in the world. Such as the Americans used to write "Month - Day - Year", and the Chinese people are used to write "year - month - day." Below you please write a program that automatically read the format of the date the United States rewrite the date of Chinese habits.

Input formats:

Enter the given month in accordance with the "mm-dd-yyyy" format in a row, day, and year. Topic guarantee date given is 1900 New Year's Day has a legitimate date.

Output formats:

In a row given year, month, day in accordance with the "yyyy-mm-dd" format.

Sample input:

03-15-2017

Sample output:

2017-03-15

str = input()
mm = str.split("-",2)[0]
dd = str.split("-",2)[1]
yy = str.split("-",2)[2]
date = yy+"-"+mm+"-"+dd
print(date)

split () method:

str.split(str="", num=string.count(str)).

  • str - separator, default for all null characters, including spaces, linefeed (\ n-), tab (\ t) and the like.
  • num - the number of divisions. Defaults to -1, i.e., all separated.

Programming Example 2: Integer Arithmetic

This problem requires programming, calculates two positive integers, difference, product, quotient and outputs. Title ensure that all inputs and outputs in the range of integers.

Input formats:

Input given two positive integers A and B. in a row

Output formats:

4 in the format line "A operator B = Result" and sequentially output, the difference, product, quotient.

Sample input:

3 2

Sample output:

3 + 2 = 5

3 - 2 = 1

3 * 2 = 6

3 / 2 = 1

method 1:

a,b = map(int,input().split())
print("{} + {} = {}".format(a,b,a+b))
print("{} + {} = {}".format(a,b,a-b))
print("{} * {} = {}".format(a,b,a*b))
print("{} / {} = {}".format(a,b,a//b))

Method 2:

A,B = map(int, input().split())
c = str(A)
d = str(B)
print(c+" + "+d+" =",A+B);
print(c+" - "+d+" =",A-B);
print(c+" * "+d+" =",A*B);
print(c+" / "+d+" =",A//B);

map () method:

We will do the mapping function in accordance with the specified sequence provided.

The first parameter argument function to call the function function of each element in the sequence, each time the function returns a new list of function return values.

map(function, iterable, ...)

  • function - Function
  • iterable - one or more sequences

 format method:

Python2.6 started, a new function of formatting strings  str.format (), which enhances the string formatting functions.

By basic syntax  {} and  : instead of the previous  %.

Any format function can take arguments, the position may not be in sequence.

For chestnut:

print("{}{}".format(" hello ", " world "))  #一一对应,输出 hello  world 
print("{0}{1}".format(" hello ", " world ")) #输出 hello  world
print("{1}{0}".format(" hello ", " world ""(PrintSet specified position, the output Hello World #))
} {0} 0 {{}. 1 " .format ( " Hello " , " World " )) # set specified position , the output hello hello world

 Another common use is divided format string

Print ( ' {:} .2f ' .format (11.25555)) # represents two decimals, the output 11.26 
Print ( ' {:} .2% ' .format (.1125555)) # represented converted to two decimal places hundred quantile, the output of 11.26%

Programming Example 3: Calculate the sum of the product of each corresponding bit

Reads two integers a and b, the output of the absolute value of the absolute values ​​of a and b, and the sum of products for each corresponding bit, such as a = 1234, b = 608, the output value of: "1 × 0 + 2 × 6 + 3 × 0 + 4 × 8 "value, i.e., 44.

Input formats:

Enter the number of two in a row

Output formats:

Corresponding to the output bit in a row and the sum of products

Sample input:

Here we are given a set of inputs. E.g:

1234 608

Sample output:

Given here corresponding output. E.g:

44

a,b = map(int,input().split())
a = abs(a)
b = abs(b)
a = str(a)
b = str(b)
sum = 0
if len(a)>len(b):
    for i in range(0,len(b)):
        sum = sum + int(a[i+len(a)-len(b)])*int(b[i])
if len(a)<len(b):
    for i in range(0,len(a)):
        sum = sum + int(b[i+len(b)-len(a)])*int(a[i])
if len(a)==len(b):
    for i in range(0,len(a)):
        sum = sum + int(a[i])*int(b[i])
print(sum)

Programming Example 4: find the singer's score

Enter a positive integer n (n> 4), and then enter the real numbers n, determining the score singer (2 decimal places). There are n (n> 4) judges a singer singing a score is provided on the awards party scoring rules: Each in turn judges score, then remove the two highest and two lowest points, calculating the average scores for the remaining scores singer .

Input formats:

Input n-input n-th fraction in the second line in the first row

Output formats:

The average score in the output line

Sample input:

Here we are given a set of inputs. E.g:

10

10 10 9 9 9 8 8 8 7 7

Sample output:

Given here corresponding output. E.g:

aver=8.50

n = input()
num = [int(n) for n in input().split()]
num.sort()
for i in range(0,4):
    num.pop()
    num.reverse()
sum = 0
for j in range(len(num)):
    sum += num[j]
aver = sum/len(num)
print("{:.2f}".format(aver))
Import numpy AS NP 
n- = INPUT () 
NUM = [int (n-) for n- in INPUT () Split ().] 
num.sort () 
for I in Range (0,4 ):
     num.pop () 
    num.reverse () 
SUM = 0
 for J in Range (len (NUM)): 
    SUM + = NUM [J]
 # can mean function comes numpy 
AVG = np.mean (NUM)
 Print ( " {:} .2f " . format (avg))

reverse () method:

The elements in the table stored in the reverse

pop () method:

Python dictionary pop () method removes a given dictionary keys and key values ​​corresponding to the return value is deleted. key value must be given. Otherwise, return default values.

pop(key[,default])

  • key: the key to be deleted

  • default: If there is no key, return default values

Note 1: After calling pop function, the original list will have an impact, that is to say, pop delete function is the value of the original list

For chestnut:

= NUM [1,2,3,4,5 ] 
num.pop () 
Print (NUM)
 # output [1, 2, 3, 4]

Note 2: pop function in a different value results are different, the first elements in the default list 0 reference numeral, the last element is -1, and so on

For chestnut:

= NUM [1,2,3,4,5 ] 
num.pop ( -1 )
 Print (NUM) # Output [. 1, 2,. 3,. 4] 
num.pop (0)
 Print (NUM) # output [2, 3, 4]

Programming Example 5: Delete character

Enter a string str, and then enter the character you want to delete c, case-insensitive, will delete all characters appear in the string str c.

Input formats:

Type in one line in the first row to be deleted in the second line of input characters

Output formats:

Delete string output in a row

Sample input:

Here we are given a set of inputs. E.g:

        Bee
   E

Sample output:

Given here corresponding output. E.g:

result: B

str = list(input().strip())
x = input().strip()
s = [i for i in str if not(i.lower() == x or i.upper() == x)]
print(s)
print('result: %s' %''.join(s).strip())

strip () Method:

Python strip () method for removing head and tail of the specified character string (line feed spaces or default) or character sequence.

Note: This method can only delete the beginning or end of the character, the character can not be deleted middle part.

str.strip([chars]);

  •  chars - remove the head and tail string specified sequence of characters.

 For chestnut:

= STR " 123abcrunoob321 " 
Print (str.strip ( ' 12 ' ))   # sequence of characters is 12, the output 3abcrunoob3 
str1 = "     123456      " 
Print (str1.strip ())   # outputs 123,456, the first free space

lower () method with the upper () Method:

Python lower () method converts the string in all uppercase characters to lowercase. python upper () method converts all lowercase characters in a string to upper case

For chestnut:

str = "hello!"
print (str.upper())  # 输出HELLO!
str1 = "HELLO!"
print(str1.lower())  #输出hello!

Programming Example 6: jmu-python- statistical results

Enter the number of student achievement, grade point average is calculated, and the statistical number of students failing.

Input formats:

Each line of input data, the input data is the 负数end of the input

Output formats:

平均分=XX,不及格人数=XXWhich XXindicates that the corresponding data. If there is no student data, output没有学生

Sample input:

30

50

70

80

90

20

-1

Sample output:

平均分=56.67,不及格人数=3

a = float(input())
list = []
sum = a
list.append(a)
count = 1
if a >= 0:
    while 1:
        a = float(input())
        if a < 0:
            break
        list.append(a)
        sum = a + sum
        count = count + 1
    print("平均分={:.2f},不及格人数=".format(sum / count), end="")
    n = 0
    for i in list:
        if i < (sum / count):
            n = n + 1
    print("%d" % n)
else :
    print("没有学生")

Programming Example 7: jmu-python- repeat element determines

Each element of a list as long as there appears twice, i.e. it is determined that the list contains duplicate elements.
Write function determining whether the list contains duplicate elements, if you include the return Trueotherwise False.
This function is then used to process n lines of character strings. The last statistics the number of rows contain duplicate elements and the number of rows that do not contain duplicate elements.

Input formats:

Input n, representative of n lines to be input next string.
Then n input lines of character strings, the space between the elements of the phase-separated string.

Output formats:

True = number of rows contain duplicate elements, False = number of rows does not contain duplicate elements
,followed by a space.

Sample input:

5

1 2 3 4 5

1 3 2 5 4

1 2 3 6 1

1 2 3 2 1

1 1 1 1 1

Sample output:

True=3, False=2

n = int(input())
f = 0
t = 0
for i in range(n):
    a = input()
    a = list(a.split())
    if len(list(a)) == len(set(a)):
        f += 1
    else:
        t += 1
print('True=%d, False=%d' %(t,f))

set () method:

set ()  function creates an unordered set of elements is not repeated, the relationship can be tested, deduplication may also be calculated intersection, difference, and sets the like.

For chestnut:

X = SET ( ' aaabbc ' )
 Print (X)   # output { 'A', 'C', 'B'} 
Y = SET ( ' abcddee ' ) 
 Print (Y)    # output { 'd', 'c' , 'B', 'A', 'E'} 
Print (SET (X & Y))   # output { 'A', 'B', 'C'} 
Print (SET (X | Y)) # output { 'd', 'A', 'C', 'B', 'E'} 
Print (SET (YX)) # output { 'd', 'e' }

 

 

 

 

Guess you like

Origin www.cnblogs.com/CoffeeSoul/p/12084135.html