python exercise set 11-30

'''
Example 11: Title: classical question: there is a pair of rabbits. They give birth to a pair of rabbits every month from the third month after birth,
The little rabbit grows to the third month and gives birth to a pair of rabbits every month. If the rabbits don't die, what is the total number of rabbits every month?
Program analysis: the law of rabbits is sequence 1,1,2,3,5,8,13,21
'''

f1=1
f2=1
for i in range(1,21):
    print('%12ld %12ld' %(f1,f2),end="")
    if(i%3)==0:
        print('')
    f1=f1+f2
    f2=f1+f2

'''
Example 12: judge the number of primes between 101-200 and output all primes
Methods of judging prime numbers
'''

h=0
leap=1
from math import sqrt
from sys import stdout

for m in range(101,201):
    k=int(sqrt(m+1))
    for i in range(2,k+1):
        if (m%i==0):
            leap=0
            break
    if leap==1:
        print('%-4d'%m)
        h+=1
        if h%10==0:
            print('')
    leap=1
print('The total is %d' % h)

'''
Example 13: print out all the "number of daffodils". The so-called "number of daffodils" refers to a three digit number,
The sum of each digit cube is equal to the number itself. For example, 153 is a "daffodil number", because 153 = the third power of 1 + the third power of 5 + the third power of 3.
Program analysis: use the for loop to control 100-999 numbers, and each number is decomposed into bits, tens and hundreds.
'''

for n in range(100,1000):
    i=n//100
    j=n//10%10
    k=n%10
    if n==i*i*i+j*j*j+k*k*k:
        print(n)

'''
Example 14: Title: decompose a positive integer into prime factors. For example, enter 90 and print out 90 = 233 * 5.
Program analysis:
To decompose the prime factor of n, first find a minimum prime number k, and then complete the following steps:
(1) If the prime number is exactly equal to n, it means that the process of decomposing the prime factor has ended, and you can print it out.
(2) If n < > k, but n can be divided by K, print out the value of K, divide n by the quotient of K as a new positive integer, and repeat the first step.
(3) If n cannot be divided by k, repeat the first step with k+1 as the value of k.
'''

def reduceNum(n):
    print('{}='.format(n),end=" ")
    if not isinstance(n,int) or n<=0:
        print('Please enter a correct number!')
        exit(0)
    elif n in [1]:
        print('{}'.format(n))
    while n not in [1]:
        for index in range(2,n+1):
            if n%index==0:
                n//=index
                if n==1:
                    print(index)
                else:
                    print('{}*'.format(index),end=" ")
                break
reduceNum(90)
reduceNum(100)

'''
Example 15: Title: use the nesting of conditional operators to complete this title:
Students with academic achievement > = 90 points are represented by A, those with 60-89 points are represented by B, and those with less than 60 points are represented by C.
Program analysis: program analysis: (a > b)? a: B this is a basic example of a conditional operator
'''

score=int(input('Enter score:\n'))
if score>90:
    grade='A'
elif score>=60:
    grade='B'
else:
    grade='C'

print('%d belong to %s '%(score,grade))

'''
Example 16:
Title: output the date in the specified format.
Program analysis: use the datetime module.
'''

import datetime

if __name__=='__main__':
    #Output today's date in the format dd/mm/yyyy
    print(datetime.date.today().strftime('%d/%m/%Y'))

    #Create date object
    miyazakiBirthDate=datetime.date(1941,1,5)

    print(miyazakiBirthDate.strftime('%d/%m/%Y'))

    #Date arithmetic operation
    miyazakiBirthNextDay=miyazakiBirthDate+datetime.timedelta(days=1)

    print(miyazakiBirthNextDay.strftime('%d/%m/%Y'))

    #Date replacement
    miyazakiFirstBirthday=miyazakiBirthDate.replace(year=miyazakiBirthDate.year+1)

    print(miyazakiFirstBirthday.strftime('%d/%m/%Y'))

'''
Example 17: input a line of characters and count the number of English letters, spaces, numbers and other characters respectively
Program analysis: using the while or for statement, the condition is that the input character is not '\ n'
'''

import string
s=input('Please enter a string:\n')
letters=0
space=0
digit=0
others=0
for c in s:
    if c.isalpha():
        letters+=1
    elif c.isspace():
        space+=1
    elif c.isdigit():
        digit+=1
    else:
        others+=1
print('char=%d,space=%d,dight=%d,others=%d' %(letters,space,digit,others))

'''
Example 18: 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.
Program analysis: the key is to calculate the value of each item.
'''

from functools import reduce

Tn=0
Sn=[]
n=int(input('n= '))
a=int(input('a= '))
for count in range(n):
    Tn=Tn+a
    a=a*5
    Sn.append(Tn)
    print(Tn)

Sn=reduce(lambda x,y:x+y,Sn)
print("The calculated sum is:",Sn)

'''
Example 19: if a number is exactly equal to the sum of its factors, the number is called "perfect". For example, 6 = 1 + 2 + 3
Program to find all completions within 100
'''

from sys import stdout
for j in range(2,1001):
    k=[]
    n=-1
    s=j
    for i in range(1,j):
        if  j%i==0:
            n+=1
            s-=i
            k.append(i)

    if s==0:
        print(j)
        for i in range(n):
            stdout.write(str(k[i]))
            stdout.write(' ')
        print(k[n])

'''
Example 20: a ball falls freely from a height of 100m and jumps back to half of the original height after each landing; Fall again and ask it to fall on the 10th landing
How many meters has it passed? How high is the tenth rebound?
'''

tour=[]
height=[]

hei=100.0 #Starting height
tim=10 #frequency

for i in range(1,tim+1):
    # From the second time, the distance when landing should be the rebound height multiplied by 2 (bounce to the highest point and then fall)
    if i==1:
        tour.append(hei)
    else:
        tour.append(2*hei)
    hei/=2
    height.append(hei)

print('Total height: tour={0}'.format(sum(tour)))
print('10th rebound height: height={0}'.format(height[-1]))

'''
Example 21: the monkey ate peaches: the monkey picked some peaches on the first day and ate half of them immediately. It was not fun, so he ate another one
The next morning, he ate half of the remaining peaches and another one. 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.
Program analysis: adopt the method of reverse thinking and infer from back to front
'''

x2=1
for day in range(9,0,-1):
    x1=(x2+1)*2
    x2=x1
print(x1)

'''
Example 22: 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.
'''

for i in range(ord('x'),ord('z')+1):
    for j in range(ord('x'),ord('z')+1):
        if i != j:
            for k in range(ord('x'),ord('z')+1):
                if (i!=k)and (j!=k):
                    if (i!=ord('x'))and(k!=ord('x'))and(k!=ord('z')):
                        print('order is a -- %s\t b -- %s\tc--%s' % (chr(i),chr(j),chr(k)))

'''
Example 23: printing diamond pattern
*

Program analysis: first divide the graph into two parts, one rule for the first four lines and one rule for the last three lines,
Using a double for loop, the first layer controls rows and the second layer controls columns
'''

from sys import stdout
for i in range(4):
    for j in range(2-i+1):
        stdout.write(' ')
    for k in range(2*i-1):
        stdout.write('*')
    print('')

for i in range(3):
    for j in range(i+1):
        stdout.write(' ')
    for k in range(4-2*i+1):
        stdout.write('*')
    print('')

'''
Example 24: 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.
'''

#Method 1
a=2.0
b=1.0
s=0
for n in range(1,21):
    s+=a/b
    t=a
    a=a+b
    b=t
print(s)
#Method 2
from functools import reduce
#functools module is mainly designed for functional programming to enhance the function
#The reduce function is used to summarize a sequence into an output
a=2.0
b=1.0
l=[]
l.append(a/b)
for n in range(1,20):
    b,a=a,a+b
    l.append(a/b)
print(reduce(lambda x,y:x+y,l))
#lambda arguments:expression
#lambda functions can accept any number of arguments, but only one expression

'''
Example 25: find 1 + 2+ 3!+…+ 20! And. – > Turn accumulation into Multiplication
'''

#Method 1
n=0
s=0
t=1
for n in range(1,21):
    t*=n
    s+=t
print('1!+2!+3!+,,,+20!=%d'%s)
#Method 2
s=0
l=range(1,21)
def op(x):
    r=1
    for i in range(1,x+1):
        r*=i
    return r
s=sum(map(op,l))
print('1!+2!+3!+,,,+20!=%d'%s)

'''
Example 26: use the recursive method to find 5!
Recursive formula: fn=fn_1*4!
'''

def fact(j):
    sum=0
    if j==0:
        sum=1
    else:
        sum=j*fact(j-1)
    return sum
print(fact(5))

'''
Example 27: use the recursive function call method to print the input 5 characters in reverse order
'''

def output(s,l):
    if l==0:
        return
    print(s[l-1])
    output(s,l-1)

s=input('input a string:')
l=len(s)
output(s,l)

'''
Example 28: five people sat together and asked how old the fifth person was? He said he was two years older than the fourth man.
Asked the age of the fourth person, he said that he was 2 years older than the third person.
Ask the third person and say that he is two years older than the second. Ask the second person and say that he is two years older than the first.
Finally, the first person was asked. He said he was 10 years old. How old is the fifth person?
'''

def age(n):
    if n==1:
        c=10
    else:
        c=age(n-1)+2
    return c
print(age(5))

'''
Example 29: give a positive integer with no more than 5 digits. Requirements: 1. Find out how many digits it is, and 2. Print out each digit in reverse order.
Learn to break down each digit
'''

#/ in python indicates floating-point division, returns floating-point result, and / / indicates integer division
x=int(input("Please enter a number:\n"))
a=x//10000
b=x%10000//1000
c=x%1000//100
d=x%100//10
e=x%10

if a!=0:
    print("5 Digits:",e,d,c,b,a)
elif b!=0:
    print("4 Digits:",e,d,c,b)
elif c!=0:
    print("3 Digits:",e,d,c)
elif d!=0:
    print("2 Digits:",e,d)
else:
    print("1 Digits:",e)

'''
Example 30: 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.
'''

a=int(input("Please enter a number:\n"))
x=str(a)
flag=True

for i in range(len(x)//2):
    if x[i]!=x[-i-1]:
        flag=False
        break
if flag:
    print("%d Is a palindrome number!"%a)
else:
    print("%d Not a palindrome number!"%a)

Keywords: Python

Added by hob_goblin on Tue, 04 Jan 2022 07:37:58 +0200