Zhejiang University Python Programming (MOOC) Exercises Answers

chapter

Chapter One

7-1 Input two numbers from the keyboard, calculate their sum and output

a=int(input())
b=int(input())
print(a+b)

7-2 Input three numbers from the keyboard into a, b, c, and output according to the formula value

Enter three values ​​a, b, c in sequence on the same line, separated by spaces, and output the value b*b-4*a*cof

a,b,c=input().split()
a,b,c=int(a),int(b),int(c)
print(b*b-4*a*c)

7-3 Output "Life is short, I learn Python"

print("人生苦短,我学Python")

7-4 Write the letter H

Write a program with * and output H

for i in range(1,6):
    if i==3:
        print("*****")
    else:
        print("*   *")

Chapter two

7-1 Calculate 11 + 12 + 13 + ⋯ + m 11+12+13+\dots+m11+12+13++m

Enter a positive integer m ( 20 ≤ m ≤ 100 ) m(20\le m\le100)m(20m1 0 0 ) , calculate11 + 12 + 13 + ⋯ + m 11+12+13+\dots+m11+12+13++the value of m .
Output format:
in one line according to the format"sum = S" "sum = S"sum=S output corresponding to andSSS

m=int(input())
S=0
for i in range(11,m+1):
    S=S+i
print("sum = {}".format(S))

7-2 Computing piecewise functions

Evaluates the following piecewise function:
g ( x ) = { 0 x = 0 1 2 xx ! = 0 g(x)=\begin{cases}0\quad x=0\\\frac{1}{2x} \quad x!=0\end{cases}g(x)={ 0x=02x _1x!=0
Output format: "g(x) = result" "g(x) = result"
in one lineg(x)=r e s u l t " format output, wherexxx r e s u l t result r e s u l t all reserved3 33 decimal places.

x=float(input())
if x!=0:
    result=1/(2*x)
else:
    result=0
print("g({0:.3f}) = {1:.3f}".format(x,result))

7-3 Tiered electricity price

The electricity price of residential users is divided into two "ladders": monthly electricity consumption 50 505 0 kwh (including50 5050 kwh ), the electricity price is0.53 0.530.5 3 yuan/kwh; more than 50 5050kwh , the excess electricity consumption, the electricity price will increase by XXX yuan/kWh.
Input format:
Enter a user's monthly electricity consumption (unit: kWh) andXXX value (unit: yuan), separated by spaces.
Output format:
Output the electricity fee (yuan) that the user should pay in one line, and the result has two decimal places. The format is: "cost = value of electricity fee payable".

power,x=input().split()
power=int(power)
x=float(x)
if power<=50:
    cost=0.53*power
else:
    cost=0.53*50+(power-50)*(x+0.53)
print("cost = {:.2f}".format(cost))

7-4 Find the approximate sum of the first N items of the sequence of odd numbers

Calculate the first NN of the sequenceN- term approximation sum 1 + 1 / 3 + 1 / 5 + ⋯ 1+1/3 + 1/5 + \cdots1+1/3+1/5+ Output format:
in one line according to" sum ≈ S " " sum ≈ S "sumS format outputs approximate andSSS S S S is the smallest integer greater than the sum of the sequences

import math
N=int(input())
s=0
for i in range(1,N+1,2):
    a=float(1/i)
    s=s+a
S=math.ceil(s)
print("sum ≈ {}".format(S))

7-5 Find the sum of the first N terms of the interleaved sequence

Calculate the front NN of an interleaved sequenceThe sum of N terms 1 − 2 / 3 + 3 / 5 − 4 / 7 + 5 / 9 − 6 / 11 + ⋯ 1-2/3+3/5-4/7+5/9-6/11+\ cdots12/3+3/54/7+5/96/11+

N=int(input())
s=0
for i in range(1,N+1):
    if i%2==1:
        s=s+i/(2*i-1)
    else:
        s=s-i/(2*i-1)
print("{:.3f}".format(s))

7-6 Generate n digits with the same digit

read in 2 22 positive integersAAA andBBB1 ≤ A ≤ 9 , 1 ≤ B ≤ 10 1\le A\le9, 1\le B\le101A9,1B1 0 , generate numbers AA...A, a total of B A

a,b=input().split(",")
a,b=int(a),int(b)
for i in range(1,b+1):
    print(a,end='')

7-7 Conversion function usage

Input an integer and base, convert to decimal output

a,b=input().split(",")
a,b=int(a),int(b)
c=(a//10)*b+(a%10)
print(c)

7-8 Compare size

input 3 33 different integers, these3 33 integers correspond to3 3The ASCII code value of 3 letters, put this3 33 letters are output in ascending order of their ASCII code values.

a,b,c=input().split()
a,b,c=int(a),int(b),int(c)
i,j,k=chr(a),chr(b),chr(c)
if a>b:
    i,j=j,i
if a>c:
    i,k=k,i
if b>c:
    j,k=k,j
print("{0:}<{1:}<{2:}".format(i,j,k))

7-9 Output Celsius-Fahrenheit temperature conversion table

Enter 2 positive integers lower and upper (-20<=lower<=upper<=50), indicating the Celsius range. Please output a Celsius-Fahrenheit temperature conversion table with a value range of [lower, upper] and increments of 2 degrees Celsius each time. Calculation formula for temperature conversion: $ F=C×1.8+32
Input format:
Enter 2 integers in one line, representing the values ​​of lower and upper respectively, separated by spaces.
Output format:
The first line outputs: "celsius□□□□fahr"
and then each line outputs a Celsius temperature celsius (integer) and a Fahrenheit temperature fahr (occupies 14 character widths, aligns to the right, and retains 1 decimal place).
If the input range is invalid, "Invalid." will be output.

lower,upper=map(int,input().split())
if -20<=lower<=upper<=50:
    print("celsius    fahr")
    while lower<=upper:
        f=float(lower*1.8+32)
        print("{0:d}{1:>14.1f}".format(lower,f))
        lower=lower+2
else:
    print("Invalid.")

7-10 even-numbered special sequences and

Given a positive integer a not exceeding 9, given a positive integer n, n is an even number, 4<=n<=18, write a program to find the sum of aa+aaaa+aaaaaa+⋯+aa⋯a (n a)

a,n=map(int,input().split())
s=0
b=a
for i in range(1,n+1):
    b=10*b+a
    if i%2==1:
        s=s+b
print(s)

7-11 Approximate sums of squares and reciprocal sequences

Calculate the sequence approximate sum for m and n (m≤n): m 2 +1/m+(m+1) 2 +1/(m+1)+⋯+n 2 +1/n

import math
a,b=map(int,input().split())
c=0
for i in range(a,b+1):
    s=i**2+float(1/i)
    c=s+c
S=math.floor(c)
print("sum ≈ {}".format(S))

7-12 Calculation function f(x)

f ( x ) = s i n ( 35 ° ) + e x − 15 x x 4 + 1 − l n ( 7 x ) f(x)=sin(35°)+\frac{e^x-15x}{\sqrt{x^4+1}}-ln(7x) f(x)=sin(35°)+x4+1 ex15xl n ( 7 x )

import math
x=float(input())
y=math.sin(35*math.pi/180)+(math.e**x-15*x)/math.sqrt(x**4+1)-math.log(7*x)
print("f({0:})={1:.3f}".format(x,y))

7-13 Calculation of residents' water charges by section

According to the step-by-step pricing of water consumption, the water fee y (yuan) that residents should pay is related to the monthly water consumption x (tons): when x does not exceed 15 tons, y=4x/3; after exceeding, y=2.5x−17.5.

x=float(input())
if x<=15:
    y=4*x/3
else:
    y=2.5*x-17.5
print("{:.2f}".format(y))

7-14 Output Specified Graphics

Input a positive integer (1<=n<=7), and output the specified graphics. (hint: use *operators)

n=int(input())
for i in range(1,n+1):
    print('* '* i)

third chapter

7-1 above average for height

The height of a class has been measured, please output those heights that exceed the average height. The input of the program is a line of data, which is separated by spaces, and each data is a positive integer. The program is to output those input values ​​that exceed the average of the input positive integers, each number is followed by a space, and the output order is the same as the input.

sheight = map(int,input().split())
theight = list(sheight)
average = sum([i for i in theight])/len(theight)
over = [n for n in theight if n > average]
for j in over:
    print(j,end=' ')

7-2 The position index of the output letter in the string

lst=(input())
a,b=input().split()
lst1=[]
for i in range(len(lst)):
    if lst[i]==a or lst[i]==b:
        lst1.extend([(i,lst[i])])
res=lst1[::-1]
for i in range(len(res)):
    print(res[i][0],res[i][1])

7-3 Find the number of digits in an integer and the sum of the digits

n=int(input())
t=[i for i in str(n)]
l=len(t)
s=sum([int(i) for i in t])
print(l,s)

7-4 Character Substitution

str = input()
lst = list(str)
for i in lst:
    n = ord(i)
    if n >= ord('A') and n <= ord('Z'):
        n = ord('A')+ord('Z')-n
    print(chr(n),end='')

7-5 Delete characters

Input a string str, and then enter the character c to be deleted, case-insensitive, delete all the characters c that appear in the string str.

str = input().strip()
c = input().strip()
str = str.replace(c.upper(),'')
str = str.replace(c.lower(),'')
print("result: {}".format(str))

7-6 Output 10 non-repeated English letters

Randomly enter a character string, and pick out the 10 non-repeated English letters (case-insensitive) on the far left. If there are no 10 English letters, the message "not found" will be displayed

letter='abcdefghijklmnopgrstuvwxyz'
s=input().strip()
s1=s.lower()
t=list(s1)
t1=[k for k in range(len(t)) if t[k] in letter and t.index(t[k])==k]
s2=''.join([s[k] for k in t1])
if len(s2)>=10:
    print(s2[:10])
else:
    print("not found")

7-7 Three-digit numbers in reverse order

The program reads in a positive 3-digit number each time, and then outputs the digits in reverse order. Note: When the input number contains a trailing 0, the output should not have a leading 0. For example, if you input 700, the output should be 7.

n=int(input())
s=str(n)
res=s[::-1]
print(int(res))

7-8 Determine whether two strings are anagrams

If one string is a rearranged combination of the other, then the two strings are anagrams of each other. For example, "heart" and "earth" are anagrams for each other, and "Mary" and "arMy" are also anagrams for each other.

lst1 = list(input())
lst2 = list(input())
lst1.sort()
lst2.sort()
if lst1 == lst2:
    print("yes")
else:
    print("no")

7-9 Input a string, output the largest character and the index of the character in the original string after sorting

tup = tuple(input())
for i in tup:
    if i == max(tup):
        result = i
ind = len(tup)-1-tup[::-1].index(result)
print("{}   {}".format(max(tup),ind))

7-10 Calculate the length of the longest string among n strings

n = int(input())
lst = []
lst1 = []
for i in range(1,n+1):
    lst.append(input().strip())
for l in lst:
    lst1.append(len(l))
length = max(lst1)
print("length={}".format(length))

7-11 Number of 1's

Enter a non-negative integer, find the number of 1 after it becomes binary

n = int(input())
count = 0
for i in bin(n):
    if i == '1':
        count += 1
print(count)

7-12 Binary addition of integers

Enter two integers with a size [0,63]between . Find their binary sum, which is represented by 8 bits.

m = int(input())
n = int(input())
a = m + n
m1 = int(format(m, "b"))
n1 = int(format(n, "b"))
a1 = int(format(a, "b"))
print("%08d" % m1)
print("%08d" % n1)
print("-" * 8)
print("%08d" % a1)

7-13 Hamming distance

The Hamming distance between two integers refers to the number of positions in which the corresponding binary bits of the two numbers differ. Input two integers x , y , 0 ≤ x , y ≤ 2 31 x,y, \quad0\le x,\quad y\le2^{31}x,y,0x,y23 1 outputx , yx,yx,The Hamming distance of y .

x,y = input().split()
x = int(x)
y = int(y)
count = 0
temp = bin(x^y)
for i in temp:
    if i == '1':
        count += 1
print(count)

7-14 Determine the palindrome string

A palindrome is a central symmetry of a string, and the content read from left to right is the same as read from right to left. Enter a string and determine whether the string is a palindrome. Only numbers and letters are considered, and there is no difference in the case of letters.

s = input().lower()
str = ''.join([i for i in s if i.isalnum()])
str1 = str[::-1]
if str == str1:
    print("yes")
else:
    print("no")

7-15 Input a line of string and convert it to decimal output

Input a line of string, remove non-hexadecimal characters, and convert it to decimal number output.

s = input().strip()
cha = '0123456789abcdeABCDE'
str = ''.join([i for i in s if i in cha])
print("{}\n{}".format(str,int(str,16)))

7-16 Count the number of characters that meet certain conditions

Enter string A (no repeating characters), enter string B, find the number of characters in string A, and these characters must be in string B at the same time.

A = input().strip()
B = input().strip()
count = 0
for i in A:
    if i in B:
        count += 1
print(count)

7-17 ID verification

A legal ID card number consists of 17 digits of region, date number and sequence number plus 1 check code. The calculation rules of the check code are as follows:
First, the first 17 digits are weighted and summed, and the weight distribution is: {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5 , 8, 4, 2}; then take the calculated sum modulo 11 to obtain the value Z; finally, correspond to the Z value and the value of the check code M according to the following relationship:

Z:0 1 2 3 4 5 6 7 8 9 10
M:1 0 X 9 8 7 6 5 4 3 2

Now given some ID numbers, please verify the validity of the check code and output the number in question.

n=int(input())
wrong=0
w=(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2)
m=('1','0','X','9','8','7','6','5','4','3','2')
for i in range(n):
    s=input()
    t=list(s)
    c=[t[i] for i in range(0,17) if ord(t[i]) in range(ord('0'),ord('9')+1)]
    if len(c)<17:
        print(s)
        wrong+=1
    else:
        a=sum([int(t[i])*w[i] for i in range(17)])
        z=a%11
        if m[z]!=t[17]:
            print(s)
            wrong+=1
if wrong==0:
    print("All passed")

Chapter Four

7-1 Generate the power table of the input number

Enter a non-negative and positive integer nnn3 ≤ n ≤ 9 3\le n\le93n9 , generate a power table of the input number. Output n + 1 n+1in increasing order of powern+1 line, the calculation result is kept2 2Two decimal places.

a,n = input().split()
a,n = float(a),int(n)
for i in range(n+1):
    print("{0:.1f}**{1:d}={2:.2f}".format(a,i,a**i))

7-2 Determine the prime number

import math
N = int(input())
count = 0
for i in range(1,N+1):
    num = int(input())
    for j in range(2,int(math.sqrt(num))):
        if num%j == 0:
            count += 1
    if count == 0:
        print("Yes")
    else:
        print("No")

7-3 Display and sum the prime numbers in the specified range

Display the prime numbers in the specified range, with one space between the prime numbers and a new line every five. Output the number of prime numbers and the sum of prime numbers on a single line.

M,N = map(int,input().split())
amount = 0
sum = 0
for i in range(M,N+1):
    count = 0
    if i>1:
        for j in range(2,i):
            if i%j == 0:
                count += 1
        if count == 0:
            amount += 1
            sum += i
            print(i,end=' ')
            if amount%5 == 0:
                print()
print("\namount={} sum={}".format(amount,sum))

7-4 Monkey eating peach problem

A monkey picked several peaches on the first day, ate half of them immediately, and was not satisfied, so he ate one more; the next morning he ate half of the remaining peaches, and ate another one. After that, I ate the remaining half of the previous day plus one every morning. When I wanted to eat again in the morning of the Nth day, I saw that there was only one peach left. Question: How many peaches were picked on the first day?

N = int(input())
n = 1
for i in range(1,N):
    n = (n+1)*2
print(n)

7-5 Find the sum of the first N terms of the score sequence

Calculates the sequence 2 / 1 + 3 / 2 + 5 / 3 + 8 / 5 + . . . 2/1+3/2+5/3+8/5+...2/1+3/2+5/3+8/5+. . . the sum of the first N items. Note that the sequence starts from item 2, and the numerator of each item is the sum of the numerator and denominator of the previous item, and the denominator is the numerator of the previous item.

N = int(input())
a,b,c,sum = 1,2,0,0
for i in range(1,N+1):
    sum += b/a
    c = b
    b = a+b
    a = c
print("{:.2f}".format(sum))

7-6 Shipping discounts

A transportation company calculates the freight for the user. The farther the distance (S) is, the lower the shipping fee per kilometer. The basic transportation fee is 1 yuan per ton per kilometer, and the standard is as follows:
insert image description here

W,S = map(eval,input().split())
if S<250:
    cost = W*S
if S>=250 and S<500:
    cost = 0.98*W*S
if S>=500 and S<1000:
    cost = 0.95*W*S
if S>=1000 and S<2000:
    cost = 0.92*W*S
if S>=2000 and S<3000:
    cost = 0.9*W*S
if S>=3000:
    cost = 0.85*W*S
print(int(cost))

7-7 Greatest common divisor and least common multiple

M,N = map(int,input().split())
a = 1
for i in range(2,min(M,N)):
    while(M%i == 0 and N%i == 0):
        M,N = M/i,N/i
        a = a*i
print("{} {}".format(a,int(a*M*N)))

7-8 Find the Fibonacci numbers that meet the conditions

Fibonacci numbers, also known as the Fibonacci sequence, refer to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, ... , 1, 1, 2, 3, 5, 8, 13, 21, ...,1123581321, this sequence starts from the third item, and each item is equal to the sum of the previous two items. Find the smallest Fibonacci number greater than the input number.

n = int(input())
lst = [1,1]
while(lst[-1]<=n):
    lst.append(lst[len(lst)-2]+lst[len(lst)-1])
print(lst[-1])

7-9 Find the approximate value of e whose error is less than the input value

natural constant eee can use the series1 + 1 / 1 ! + 1 / 2 ! + ⋯ + 1 / n ! 1+1/1!+1/2!+⋯+1/n!1+1/1!+1/2!++1 / n ! to approximate the calculation. ei e_ieiRepresents the sum of the previous i items. Input error range error errorerror,当 e i + 1 − e i < e r r o r e_{i+1}-e_i<error ei+1ei<e r r o r meanseeThe approximation of e satisfies the margin of error.

error = float(input())
a,b = 1,1
s1 = 1+1/1
s2 = 1+1/1+1/2
while((s2-s1) > error):
    b = b+1
    a = a*b
    s1 += 1/a
    s2 += 1/(a*(b+1))
print("{:.6f}".format(s2))

7-10 p.mApproximate value of π

Use the formula to find π πApproximate value of π : π 2 / 6 = 1 + 1 / 2 2 + 1 / 3 2 + 1 / 4 2 + … π^2/6=1+1/2^2+1/3^2+1/4 ^2+\dotsPi2/6=1+1/22+1/32+1/42+... when the summed term is less than the error, end the summation.

import math
error = float(input())
s = 1
i = 1
while(1/(i**2) > error):
    i += 1
    s += 1/(i**2)
pi = math.sqrt(s*6)
print("{:.6f}".format(pi))

7-11 daffodil number

The daffodil number refers to a NNN- digit positive integer( N ​​≥ 3 ) (N≥3)(N3 ) , the sum of the Nth powers of the numbers on each of its bits is equal to itself. For example:153 = 1 × 1 × 1 + 5 × 5 × 5 + 3 × 3 × 3 153=1×1×1+5×5×5+3×3×3153=1×1×1+5×5×5+3×3×3

N = int(input())
i = 0
for n in range(10**(N-1),10**N):
    sum = 0
    for j in range(0,N):
        i = n//(10**j)%10
        sum += i**N
    if sum == n:
        print(n)

7-12 Find elements that are not public

lst1 = input().split()
lst2 = input().split()
for i in lst1:
    count = 0
    for j in lst2:
        if i == j:
            count +=1
    if count == 0:
        print(i,end=' ')
for i in lst2:
    count = 0
    for j in lst1:
        if i == j:
            count +=1
    if count == 0 and i!=lst2[-1]:
        print(i,end=' ')
    if count == 0 and i == lst2[-1]:
        print(i,end='')

7-13 find the number

A perfect number is a number that is exactly equal to the sum of its factors except itself. For example: 6 = 1 + 2 + 3 6=1+2+36=1+2+3 , of which1, 2, 3 1, 2, 31 , 2 , 3 are6 6Factor of 6 .

import math
m,n= map(int,input().split())
count = 0
for i in range(m,n+1):
    lst = [1]
    for j in range(2,int(math.sqrt(i))+1):
        if i%j == 0:
            lst.append(j)
            if j*j != i:
                lst.append(i//j)
    if i == sum([a for a in lst]):
        count += 1
        print('{} = '.format(i), end="")
        lst.sort()
        print(" + ".join("%s" %a for a in lst))
if count == 0:
    print("None")

7-14 The monkey chooses the king

A group of monkeys want to choose a new monkey king. The selection method of the new monkey king is: let NNN candidate monkeys form a circle, numbered1 11~ N N N number. from 1st1Counting begins on the 1st, and each round starts from 1 11 check in3 33 , where the registration is3 3The monkey at 3 exits the circle, and then starts the same counting from the next monkey next to it. This cycle continues, and the last remaining monkey is selected as the monkey king. Excuse me, which monkey was elected the monkey king?

N = int(input())
lst = []
for i in range(1,N+1):
    lst.append(i)
length = 0
index = 1
while True:
    if len(lst) == 1:
        print(lst[0])
        break
    if length == len(lst):
        length = 0
    if index == 3:
        del lst[length]
        index = 1
    else:
        index += 1
        length += 1

7-15 Specific matrix elements and

Given an n × nn×nn×For a square matrix of n , calculate the sum of all elements on the main and subdiagonals of the matrix. The main diagonal is the line from the upper left corner to the lower right corner of the matrix, and the subdiagonal is the line from the upper right corner to the lower left corner of the matrix

n = int(input())
lst = []
sum = 0
for i in range(n):
    lst.append(input().split())
for j in range(n):
    for k in range(n):
        if j == k or j+k == n-1:
           sum += float(lst[j][k])
print("{:.2f}".format(sum))

7-16 Maximum value of matrix row, column, diagonal sum

Find the maximum value of each row, column and diagonal of a 3*3 matrix

num = input().split()
lst = [num[:3],num[3:6],num[6:]]
lst1 = []
sum3,sum4 = 0,0
for i in range(3):
    sum1,sum2 = 0,0
    for j in range(3):
        sum1 += int(lst[i][j])
        sum2 += int(lst[j][i])
        if i == j:
            sum3 += int(lst[i][j])
        if i+j == 2:
            sum4 += int(lst[i][j])
    lst1.append(sum1)
    lst1.append(sum2)
lst1.append(sum3)
lst1.append(sum4)
print(max(lst1))

7-17 Judging triangular matrix

Triangular matrices include upper triangular matrices and lower triangular matrices. The upper triangular matrix refers to the matrix whose elements below the main diagonal are all 0; the lower triangular matrix refers to the matrix whose elements above the main diagonal are all 0; the main diagonal is the connection from the upper left corner to the lower right corner of the matrix .

T = int(input())
for i in range(1,T+1):
    n = int(input())
    lst = []
    for j in range(n):
        lst.append(input().split())
    index,index1 = 0,0
    for h in range(n):
        for l in range(n):
            if l<h:
                index += int(lst[h][l])
            if l>h:
                index1 += int(lst[h][l])
    if index == 0 and index1 != 0:
        print("upper triangular matrix")
    elif index1 == 0 and index != 0:
        print("lower triangular matrix")
    else:
        print("no")

7-18 Print Jiujiu formula table

N = int(input())
for i in range(1,N+1):
    for j in range(1,i+1):
        print("%d*%d=%-4d"%(j,i,j*i),end='')
        if j == i:
            print()

7-19 Finding the local maximum of a matrix

Given MMM rowNNInteger matrixAA with N columnsA,You FruitAANon-boundary elements of A A [ i ] [ j ] A[i][j]A [ i ] [ j ] is greater than the 4 adjacent elements, up, down, left, and right, then the element is calledA [ i ] [ j ] A[i][j]A [ i ] [ j ] is the local maximum of the matrix.

M,N = map(int,input().split())
A = []
for n in range(M):
    A.append(list(map(int,input().split())))
count = 0
for i in range(1,M-1):
    for j in range(1,N-1):
        if A[i][j]>A[i-1][j] and A[i][j]>A[i][j-1] and A[i][j]>A[i+1][j] and A[i][j]>A[i][j+1]:
            print(A[i][j],i+1,j+1)
            count += 1
if count == 0:
    print("None {} {}".format(M,N))

7-20 Matrix Transpose

m,n = map(int,input().split())
A = []
for i in range(m):
    A.append(list(map(int,input().split())))
A1 = []
for i in range(n):
    j = 0
    while(j<m):
        A1.append(str(A[j][i]))
        j += 1
for i in range(n):
    print(' '.join(A1[i*m:(i+1)*m]))

7-21 Display right-angle digital graphics

n = int(input())
for i in range(1,n+1):
    for j in range(1,i+1):
        print(chr(j+64),end='')
    print()

7-22 Display diamond shape

n = int(input())
for i in range(1,n+1,2):
    print('{:^11s}'.format('*'*i))
for i in range(n-2,0,-2):
    print('{:^11s}'.format('*'*i))

7-23 Display Pascal triangle

n = int(input())
print('1 ')
if n>1:
    print("1 1 ")
    add = 0
    i = 3
    lst = [1, 1]
    while(i<n+1):
        lst1 = lst[:]
        lst = [1, 1]
        for j in range(1,i-1):
            add = lst1[j-1]+lst1[j]
            lst.insert(-1,add)
        i += 1
        for k in lst:
            print(k,end=' ')
        print()

Guess you like

Origin blog.csdn.net/Lillian_f/article/details/123724640