type : function
describe
Write a function isPrime(n) Used to judge a number n Is it a prime number , The user enters a positive integer , Output all prime numbers not greater than this number in one line , Separate with a space after .
Input format
Enter a positive integer
Output format
All prime numbers not greater than this number , Separate with a space after .
Example
Input :100
Output :2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
The standard answer
def isPrime(n): # A function of judging prime numbers
if n < 2:
return False #0 and 1 Not primes
for i in range(2, n):
if n % i == 0:
return False
break
else:
return True
num = int(input()) # Receive user input and convert to an integer
for i in range(num):
if isPrime(i):
print(i,end=' ') # Output results on the same line , Don't wrap , Space between
type : function
describe
Design a dichotomy to calculate a greater than or equal to 1 The real number n A function of the square root of sqrt_binary(n), The calculation accuracy shall be controlled so that the error between the square of the calculation result and the input is not greater than 1e-6.
notes : The initial interval is [0,n]
Input format
Enter a real number n( Greater than or equal to 1)
Output format
The first line outputs the square root calculated by the function designed by yourself
For output of the second line math The square root calculated by the Kukai square function
Example
Input :5.0
Output :
2.2360679507255554
2.23606797749979
The standard answer
import math
def sqrt_binary(num):
low, high= 0,num
while True:
x = (high + low)/2
if abs(x**2 - num)<=1e-6:
return x
elif x**2 - num<0:
low = x
else:
high = x
num = float(input())
if num >=0:
print(sqrt_binary(num))
print(math.sqrt(num))
else:
print(' Please enter a non negative number !')
type : function
describe
Design a dichotomy to calculate a greater than or equal to 0 The real number n A function of the square root of sqrt_binary(n), The set of real Numbers n And calculation accuracy control are entered by the user in the same line , Separate with commas , The output results are retained 8 Decimal place . When (abs(x * x - n) ) Less than or equal to the set accuracy , It is approximated that x * x == n.
notes : The initial interval is [0,n+0.25]
Input format
At the same time Enter a real number in the line n( Greater than or equal to 0) And a number representing precision ( You can use 1e-m Format input ), Comma interval
Output format
The first line outputs the square root calculated by the function designed by yourself
For output of the second line math The square root calculated by the Kukai square function
Example
Input :5.0,1e-7
Output :
2.23606796
2.23606798
The standard answer
import math
def sqrt_binary(num, accuracy):
""" Receive a floating point number num And a floating-point number that represents the precision of the calculation accuracy Is the parameter , Calculate the square root of floating point number by dichotomy x,
When abs(x * x - num) <= accuracy It is considered that the calculation accuracy is reached , Returns the calculated square root as a floating-point number ."""
low, high = 0, num + 0.25 # Set the initial interval
while True: # Build an infinite loop
x = (high + low) / 2 # Suppose that the square root falls in half of the interval , The midpoint
if abs(x * x - num) <= accuracy: # When the error is less than the calculation accuracy , End cycle
return x # Returns the current x The value is the square root
elif x * x - num < 0: # At present x The square of is less than num when , The square root should be in the right section
low = x # Take the current value as the lower limit of the interval , Reduce the range by half
else: # At present x The square of is greater than num when , The square root should be in the left section
high = x # Take the current value as the upper limit of the range , Reduce the range by half
n, error = map(float, input().split(',')) # Enter floating point number n And calculation accuracy
print('{:.8f}'.format(sqrt_binary(n, error))) # Call the dichotomy function to calculate the square root
print('{:.8f}'.format(math.sqrt(n))) # use math In the library sqrt() Calculate the square root
type : function
describe
My WeChat ID It's capital letters WHUT The following numbers are two prime numbers connected together , The big one is ahead , The small one is behind , If I tell you what the product of two numbers is , You can calculate my ID No.? ?
If you enter a [0-9] Number between , Can you count from 1 Start to me ID In the sequence of numbers in , How many times does this number appear ?
Input format
First line input ID The product of two prime numbers in
On the second line, enter a [0-9] Number between
Output format
The first line outputs ID Number
The number of times the second line outputs numbers
I / O example
Example
Input :
196409
3
Output :
WHUT997197
599140
The standard answer
def isPrime(n): # Judgment parameters n Whether it is a function of prime
if n < 2: # Less than 2 The numbers of are not prime numbers
return False
for i in range(2, int(n ** 0.5) + 1): # Determine whether it is a prime number according to the definition of prime number , It's a prime number that returns 1
if n % i == 0: # from 2 To n-1 If there is a number in is i, send n Divisibility i, be n Not primes
return False
else: # if for Loop did not encounter return Normal end , be n Prime number
return True
def checkId(n):
if n % 2 == 0 and isPrime(n // 2): # If n Can be 2 to be divisible by , individualization , Increase of efficiency
return int(str(n // 2) + str(2))
else:
for num in range(3,n//2+1,2): # If n Can not be 2 to be divisible by , Then the two prime numbers do not include 2, It's all odd
if isPrime(num) and n % num == 0 and isPrime(n // num): # isPrime(n // num) In the last , Use the short circuit effect , It can minimize the number of primes of large numbers
return int(str(n // num) + str(num)) # The return value is converted to string concatenation and then to integer
def countnumber(n,num):
m, countnum = 1, 0
while n//m > 0:
high, mod = divmod(n, m*10)
curNum, low = divmod(mod, m)
if curNum > num:
countnum += high*m + m
elif curNum == num:
countnum += high*m + low + 1
else:
countnum+= high*m
m = m*10
return countnum
if __name__ == '__main__':
n = int(input()) # Input ID, Integers , The guarantee is the product of two primes
number = int(input()) # Input 0-9 A number between
ID = checkId(n)
countNumber = countnumber(ID,number) # Statistics number The number of
print('WHUT' + str(ID))
print(countNumber)
# def occ3(n,num):
# s = 0
# for i in range(len(str(n))):
# x = int(str(n)[-i-1])
# s += n//10**(i+1)*10**i
# if x == num:
# s += n%10**i+1
# if x > num:
# s += 10**i
# return s
# def isPrime(n): # A function of judging prime numbers
# if n < 2 or n % 2==0:
# return False #0、1、 Negative numbers and even numbers are not prime numbers
# for i in range(3, int(n**0.5)+1,2):
# if n % i == 0: # Can be 2 To itself minus 1 The number divided by the number of is not a prime number
# return False
# else:
# return True #for End of cycle , Not encountered return The number of is prime
# n = int(input()) # Receive user input and convert to an integer 707829217
# number = int(input())
# for i in range(n):
# if isPrime(i) and n%i==0 and isPrime(n//i): # Judge i and N-i Whether it is also a prime number , At the same time, ensure that the sum of two numbers is N
# print("WHUT{}{}".format(n//i,i))
# break # Find a qualified number and end the loop
# m = int(str(n//i)+str(i))
# print(occ3(m,number))
# print(three(m,number))
# m = int(str(n//i)+str(i))
# num=0
# for j in range(1,m+1):
# if number in str(j):
# num=num+str(j).count(number)
# print(num)
type : function
describe
Palindrome prime refers to a number that is both prime and palindrome . for example ,131, It's both prime and palindrome . The user enters a positive integer n , Please output the first... From small to large in one line n Palindrome prime , Numbers are separated by a space after them .
Input format
Enter a positive integer
Output format
The prime number of palindromes that meet the requirements
Example
Input :10
Output :2 3 5 7 11 101 131 151 181 191
The standard answer
def is_prime(n):
""" A function of judging prime numbers , Receive a positive integer as a parameter , When the parameter is a prime number, it returns True, Otherwise return to False
Reduce the decision interval , Reduce the number of cycles , Improve efficiency .
"""
if n < 2:
return False # 0、1、 Negative numbers and even numbers are not prime numbers
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0: # Can be 2 To its root n The number divided by an integer between is not a prime number
return False
else:
return True # for End of cycle , Not encountered return The number of is prime
def palindromic(num):
""" Receive a number as a parameter , Determine whether it is palindrome number , Returns a Boolean value ."""
if str(num) == str(num)[::-1]:
return True
else:
return False
def output_prime(num):
""" Receive a positive integer num Is the parameter , Before outputting from small to large in a line num Palindrome prime .
Function has no return value
"""
i = 2 # From the smallest prime 2 Start testing
count = 0 # Counter set 0
while True: # Infinite loop
if palindromic(i) and is_prime(i): # Judge palindromes first, then prime numbers , Efficient
print(i, end=' ') # i Output when it is palindrome prime i, Output does not wrap
count = count + 1 # The prime count increases for each palindrome found 1
if count == num: # If the number of palindromes found is the same as the required number
break # End of cycle
i = i + 1 # Test the next number
if __name__ == "__main__":
n = int(input())
output_prime(n)
type : function
describe
Anti prime number ( Reverse spelled prime numbers ) It refers to a non palindrome number that is also a prime number after reverse spelling .
for example :
13 and 31 All prime numbers , And 13 and 31 Not even palindromes , therefore ,13 and 31 It's an inverse prime .
Enter a positive integer n , Please output the first... In the same line from small to large n Inverse prime number , Add a space after each number .
Input format
Enter a positive integer
Output format
A qualified inverse prime number
Example
Input :
10
Output :
13 17 31 37 71 73 79 97 107 113
The standard answer
def is_prime(n):
if n <= 1: # Less than 2 The numbers of are processed separately
return True
for i in range(2, int(n ** (1 / 2) + 1)): # Determine whether it is a prime number according to the definition of prime number , It's a prime number that returns 1
if n % i == 0:
return False
return True
def palindromic(num):
""" Receive a number as a parameter , Determine whether it is palindrome number , Returns a Boolean value ."""
return str(num) == str(num)[::-1]
def reverse_num(num):
""" Receive an integer , Returns the integer corresponding to the string in reverse order """
return int(str(num)[::-1])
def reverse_prime(number):
i = 2
count = 0
while True:
if not palindromic(i) and is_prime(i) and is_prime(reverse_num(i)):
print(i, end=' ') # i Output when it is palindrome prime i, Output does not wrap
count = count + 1
if count == number:
break
i = i + 1
if __name__ == "__main__":
n = int(input())
reverse_prime(n)
type : function
describe
Famous in the field of mathematics “ Goldbach conjectures ” The general meaning of : Any one is greater than 2 The even number of can always be expressed as the sum of two prime numbers . for example :24=5+19, among 5 and 19 All prime numbers . The task of this experiment is to design a program , verification 20 Even numbers within 100 million can be decomposed into the sum of two prime numbers . Enter a value greater than 2 The positive integer , When the input is even , Format in one line “N = p + q” Output N The prime decomposition of , among p 、 q Are prime and p ≤ q. Because such decomposition may not be unique ( for example 24 It can also be broken down into 7+17), It is required that all solutions must be output p The smallest solution . When the input is odd , Output 'Data error!' .
Input format
Enter a value greater than 2 The positive integer
Output format
When the input is even , By format “N = p + q” Output N The prime decomposition of ; When the input is odd , Output 'Data error!' .
Example
Input :36
Output :36 = 5 + 31
The standard answer
def isPrime(n): # A function of judging prime numbers
if n < 2:
return False #0 and 1 Not primes
for i in range(2, n):
if n % i == 0:
return False
else:
return True
N = int(input()) # Receive user input and convert to an integer
flag = False
if N % 2 == 0:
for i in range(N):
for j in range(N):
if isPrime(i) and isPrime(j) and i+j==N:
print("{} = {} + {}".format(N, i,N-i))
flag = True
break
if flag:
break
else:
print('Data error!')
'''
def isPrime(n): # A function of judging prime numbers
if n < 2:
return False #0 and 1 Not primes
for i in range(2, n):
if n % i == 0:
return False
else:
return True
N = int(input()) # Receive user input and convert to an integer
if N % 2 == 0:
for i in range(N):
if isPrime(i) and isPrime(N - i) :
print("{} = {} + {}".format(N, i,N-i))
break
else:
print('Data error!')
'''
type : function
describe
Mr. hou would climb stairs to exercise every day , There are only two steps for him to climb stairs , Or step up one level at a time , Or two levels at a time .
One day Mr. Hou wanted to figure out a difficult problem : From the bottom platform to the top platform n How many kinds of walking methods are there in level ?
for example n yes 2 when , There are two ways : Step directly from the platform to step 2 level , Or step from the platform to 1 Take another step to the 2 level .
Please help Mr. hou , Here you are. n(1<=n<40) Value , You help calculate and output how many ways to climb to the top .
Input format
Input n Value ,n yes 1 To 40 Integer between .
Output format
How many types of output are there, from the platform to the n How to walk the steps .
I / O example :
Example 1
Input :3
Output :3
Example 2
Input :5
Output :8
The standard answer
def upstrs(n):
if n==1:
return 1
elif n==2:
return 2
else:
return upstrs(n-1)+upstrs(n-2)
n=int(input())
print(upstrs(n))
type : function
describe
Define a function to realize the power operation of an integer , To calculate x Of n Power .
Input format
Enter two nonnegative integers on one line x and n, The numbers are separated by spaces .
Output format
x Of n Operation result of power
Example
Input :2 3
Output :8
The standard answer
def power(x,n):
po=1
for i in range(n):
po=po*x
return po
x,n = map(int,input().split())
print(power(x,n))
type : function
describe
Write a function to implement from 1 To N common N The accumulation of numbers
Input format
A positive integer N
Output format
The result of the calculation is
Example
Input :100
Output :5050
The standard answer
def summ(n):
sum = 0
for i in range(1,n+1):
sum = sum + i
return sum
print(summ(int(input())))
type : function
describe
Hanoi : Hanoi ( Also known as the river tower ) The problem is a puzzle toy from an ancient Indian legend . Vatican made three diamond pillars when he created the world , Stack on a column from bottom to top in order of size 64 A golden disk . Brahman ordered Brahman to rearrange the disc from below on another pillar in order of size . And stipulate , You can't enlarge a disc on a small disc , Only one disc can be moved between the three pillars at a time .
The column number is a, b, c, Take all the discs from a Move to c Can be described as : If a There's only one disc , It can be moved directly to c; If a Yes N Disc , Can be seen as a Yes 1 Disc ( chassis ) + (N-1) Disc , First of all, we need to put (N-1) A disk moves to b, then , take a The last disc of moves to c, then b Of (N-1) A disk moves to c. Please write a function move(n, a, b, c) , A given input n, a, b, c, Print out the moving steps : for example , Input move(2, ‘A’, ‘B’, ‘C’), Print out : A –> B A –> C B –> C
Input format
There are two lines :
First line a positive integer
The second line has three symbols , Such as A、B、C or a,b,c etc. , Input is separated by spaces .
Output format
Records of the movement process
Example
Input :
2
A B C
Output :
A --> B
A --> C
B --> C
The standard answer
def hanoi_move(n, a, b, c):
""" Receive an integer representing the number of discs n And three characters for columns , Printout handle n The process of moving a disk from the first column to the third column ."""
if n == 1: # Termination conditions , When there is only one disk , from A Move to C End the program after
print(a, '-->', c)
return None
else: # Recursively call , Each time the disc is called, it is reduced by one
hanoi_move(n - 1, a, c, b) # First of all, we need to put (N-1) A disk moves to b
hanoi_move(1, a, b, c) # take a The last disc of moves to c
hanoi_move(n - 1, b, a, c) # then b Of (N-1) A disk moves to c
if __name__ == '__main__': # Make the previously defined function can be called by other modules
num = int(input()) # Enter the initial number of discs
s1, s2, s3 = input().split() # Enter the character representing the column , For example, the input A B C
hanoi_move(num, s1, s2, s3) # Call the recursive function to move the disc
type : function
describe
1179 It works 3 The two methods are expressed as 3 An integer that is the sum of the squares of different primes .
Such as :
1179 = 1717 + 1919 + 23*23
1179 = 77 + 1313 + 31*31
1179 = 77 + 1717 + 29*29
Please output usable 6 The two ways are expressed as 3 The smallest integer of the sum of squares of different primes .
( The maximum prime number involved in this question does not exceed 100)
Input format
There is no input for this topic
Output format
Output available 6 The two ways are expressed as 3 The smallest integer of the sum of squares of different primes
I / O example
It works 3 The two methods are expressed as 3 The output form of the smallest integer of the sum of squares of different primes is as follows , Output the result of this question according to the same rule :
Example
Output :1179
The standard answer
# Get all first 100 List of primes within
# recycling itertools Medium combinations You can quickly get all the non repeating 3 A combination of primes
# Then get a list of the sum of squares of each group of primes , Count the number of occurrences of each number in this list , If appear 6 Time , Is the answer to the question
from itertools import combinations
def is_prime(n):
""" A function of judging prime numbers , Receive a positive integer as a parameter , When the parameter is a prime number, it returns True, Otherwise return to False
Reduce the decision interval , Reduce the number of cycles , Improve efficiency """
if n < 2:
return False # 0、1、 Negative numbers and even numbers are not prime numbers
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0: # Can be 2 To its n-1 The number divided by the number between is not a prime number
return False
else:
return True # for End of cycle , Not encountered return The number of is prime
def combine(ls_of_prime, n):
""" according to n Get all possible combinations in the list (3 Elements in a group )"""
comb_of_prime = []
for c in combinations(ls_of_prime, n):
comb_of_prime.append(c)
return comb_of_prime
def six_ways(comb_of_prime):
""" Pass in a combined list of all three primes , Calculate the sum of the squares of the elements in each combination , Create a new list ,
Traverse 10000 The following integers , If the number of times this integer appears in the list is 6 Time , Then it is the smallest 、
There can be 6 The two representations are expressed as 3 The sum of the squares of prime numbers """
result = [sum((c[0] ** 2, c[1] ** 2, c[2] ** 2)) for c in comb_of_prime]
for i in range(10000):
if result.count(i) == 6: # Count the number of times the current number appears in the list
return i
if __name__ == '__main__':
lsOfPrime = [i for i in range(100) if is_prime(i)]
combOfPrime = combine(lsOfPrime, 3)
print(six_ways(combOfPrime))
# It can also be solved directly , But less efficient
def is_prime(n):
# """ A function of judging prime numbers , Receive a positive integer as a parameter , When the parameter is a prime number, it returns True, Otherwise return to False
# Reduce the decision interval , Reduce the number of cycles , Improve efficiency """
# if n < 2:
# return False # 0、1、 Negative numbers and even numbers are not prime numbers
# for i in range(2, int(n ** 0.5) + 1):
# if n % i == 0: # Can be 2 To its n-1 The number divided by the number between is not a prime number
# return False
# else:
# return True # for End of cycle , Not encountered return The number of is prime
#
# def six_ways():
# i = 2
# while True:
# lsnew = [tuple(sorted(list((i, j, k, l)))) for j in ls for k in ls for l in ls if
# i == j * j + k * k + l * l and j != k and k != l and j != l]
# if len(set(lsnew)) == 6: # If the non repeating elements in the list have 6 individual , Then find the answer
# return i
# else:
# i = i + 1
#
#
# ls = [i for i in range(100) if is_prime(i)] # To improve efficiency , Mr Into 100 List of prime numbers within
# print(six_ways())
type : function
describe
Call the function in the attachment to perform four operations
Input format
Two integers
Output format
and
Example
Input :3 4
Output :7
The standard answer
import cal
a,b = map(int,input().split())
print(cal.add(a,b))
type : function
describe
Monkey number 1 One day I picked a pile of peaches and ate half and one more , The first 2 One day, I ate the remaining half and one more ,..., The first 10 One morning, I found only 1 A peach . Ask No 1 How much did the sky pick ?
Example
Output :xxxx
The standard answer
num = 1
for i in range(9):
num = (num + 1) * 2
print(num)
# def g(n):
# if n==10:
# return 1
# else:
# return 2*(g(n+1)+1)
# print(g(1))
type : function
describe
Enter a positive integer n, Put the numbers n Factorization into multiplications that can no longer be factorized , such as :8=222, 10 = 2*5, instead of 8 = 2 * 4 This kind of decomposable .
Input format
Enter a positive integer n
Output format
Output a list of all factors
Example
Input :12
Output :[2, 2, 3]
The standard answer
def defactor(N): # Define a function named defactor, The meaning is to return to N All the factors of
for i in range(2,N): # from 2 Start to try
if N % i ==0: # If you try i yes N If the factor of , Just go back to i All the factors and N/i All the factors of A list of
return defactor(i)+defactor(int(N/i)) # Splicing list + list
else: # If you don't try, it means that N It's a prime number , It's directly involved in list
return [N] # Returns a list of
if __name__ == '__main__':
n = int(input())
print(defactor(n))
type : function
describe
Enter a positive integer n, Statistics from [0,n] The biggest between 10 Sum of prime numbers . This question ensures that the test case has at least 10 A prime number that satisfies the condition .
for example : Input 31 , Should be obtained 3,5,7,11,13,17,19,23,29,31 The sum of the .
This question requires the use of custom functions to complete , The code framework reference is as follows :
def isprime(n): # Judge prime function
......
def f(n): # Find less than n And sum the prime numbers of
......
......
p=int(input())
print(f(p))
Example
Input :31
Output :158
The standard answer
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
else:
return True
def f(n):
sumPrime,count=0,0
for i in range(n,1,-1):
if isprime(i):
sumPrime = sumPrime + i
count = count + 1
if count == 10:
return sumPrime
num = int(input())
print(f(num))
type : function
describe
Enter a string consisting entirely of numeric characters s, Count the sum of odd and even character values respectively
Such as the input ‘123456789’
Output oddsum=25,evensum=20
This problem needs to be completed with a user-defined function , The suggested code framework is as follows :
def f(n):
......
def p(t):
......
def .......
s=input()
print('oddsum={},evensum={}'.format(......))
Example
Input :123456789
Output :oddsum=25,evensum=20
The standard answer
def f(n): # Parity function
if n%2==0:
return 0
return 1
def p(t): # Odd sum
j=0
for i in t:
if f(int(i))==1:
j+=int(i)
return j
def q(t): # Even sum
j=0
for i in t:
if f(int(i))==0:
j+=int(i)
return j
s=input()
print('oddsum={},evensum={}'.format(p(s),q(s)))
type : function
describe
Enter a string in each of the two lines s And integer n, Define a function that will string s Cycle to the right n position ,n Shift left when negative .
if s Is an empty string '', No matter n How much? , Both output empty strings ''.
Such as s='123456' n=3
Output results :456123
The code framework is as follows :
def f(s,n):
......
s=input()
n=int(input())
print(f(s,n))
Example
Input :
123456
2
Output :
561234
The standard answer
def f(s,n):
p=''
if s=='':
return p
t=(len(s)-n)%len(s)
p=s[t:]
p+=s[:t]
return p
s=input()
n=int(input())
print(f(s,n))
'''def f(s,n):
p=''
if s=='':
return p
if n>=0:
t=len(s)-n%len(s)
else:
t=abs(n)%len(s)
p=s[t:]
p+=s[:t]
return p
s=input()
n=int(input())
print(f(s,n))
'''
type : function
describe
Xiao Ming is a car fan , When you see a car, you can immediately tell the production year of the car 、 Model and brand . Define a function , Can output the introduction of the car .
For example, the input :
2020 AMG_S65 Mercedes
Can output :
This is a car 2020 Annual production , Model is AMG_S65 Mercedes Benz
The function is required to have the following functions : When the user only enters the production year 、 Model time , Brand press “ BMW ” Output .
Input format
Enter the years separated by spaces 、 Model and brand ( The brand may not )
Output format
This is a car Annual production , Model is Of Brand car ( Replace according to user input )
Example
Input :2020 AMG_S65 Mercedes
Output : This is a car 2020 Annual production , Model is AMG_S65 Mercedes Benz .
The standard answer
# 2020 AMG_S65 Mercedes
# 2019 745li
# 2018 760 BMW
def car(year,model,brand = ' BMW '):
return f' This is a car {year} Annual production , Model is {model} Of {brand} Brand car .'
ls = input().split()
print(car(*ls))
type : function
describe
One does not contain 0 Number of numbers , If it can be divided by every bit of it , Then it is a self divisor . for example 128 It's a self divisor , because 128 Can be 1、2、8 to be divisible by . Write function selfDivisor(num) Judge num Whether it is a self divisor , Use this function to output no more than N All the self divisors of .
( Be careful , With numbers 0 The number of is not a self divisor )
Input format
Enter as one line , A positive integer N(N>=1).
Output format
Output as a line , No more than N All the self divisors of , There is a space after each number .
Example 1
Input :1
Output :1
Example 2
Input :22
Output :1 2 3 4 5 6 7 8 9 11 12 15 22
The standard answer
def selfDivisor(num):
if '0' in str(num):
return False # Contains figures 0 Is not a self divisor
for c in str(num): # Pairs of numbers num Each number in the
if num % int(c) != 0: # test num Whether each of us is num Factor of
return False # If there is a number that cannot be divided , Is not a self divisor
else: # If for Traversal finished successfully , Not encountered return, execute else Clause , return True
return True
n=int(input())
for num in range(1,n+1): # Note that not greater than or equal to n
if selfDivisor(num): # Call function , When the return value is True when , This number is a self divisor , Output this number
print(num,end=' ') # The output ends with a space
type : function
describe
The formula for converting Fahrenheit temperature to Celsius temperature is known :C=5×(F−32)/9, among :C It means the temperature in centigrade ,F Fahrenheit temperature .
Write function F2C(f) Convert Fahrenheit to Celsius , Read in two Fahrenheit values f1 and f2, The printing range is f1~f2 Inside , A quick look-up table with two Fahrenheit scales added at a time .
Be careful : If f1>f2, Print directly error.
Input format
Enter as one line , For two not less than 32 The positive integer f1 and f2, Indicates two Fahrenheit temperatures . Two numbers are separated by commas , Form like f1,f2.
Output format
If f1>f2, Output error.
If f1<=f2, Then output the temperature conversion quick look-up table from Fahrenheit to Celsius , The quick look-up table may have multiple lines , One temperature conversion pair per line , Form like f1 : c1, among c1 Keep two decimal places . Look up the table to 2 Fahrenheit is a scale .
Example 1
Input :86,44
Output :error
Example 2
Input :32,32
Output :32 : 0.00
Example 3
Input :44,45
Output :44 : 6.67
Example 4
Input :44,46
Output :
44 : 6.67
46 : 7.78
Example 5
Input :60,73
Output :
60 : 15.56
62 : 16.67
64 : 17.78
66 : 18.89
68 : 20.00
70 : 21.11
72 : 22.22
The standard answer
def F2C(f):
c=5*(f-32)/9
return c
left,right=map(int,input().split(','))
if left>right:
print('error')
else:
for f in range(left,right+1,2):
print("{} : {:.2f}".format(f,F2C(f)))
type : function
describe
Enter an English sentence with multiple words , Words are separated by spaces , Punctuation followed by a space . Define a function , The function is to connect words with specified symbols .
Input format
Enter an English sentence in the first line
On the second line, enter a symbol
Output format
Words connected by symbols
Example
Input :
a string can be split on a delimiter.
-
Output :
a-string-can-be-split-on-a-delimiter.
The standard answer
def split_and_join(line,sign):
return sign.join(line.split())
# Do not change the following code
if __name__ == '__main__':
line = input()
sign = input()
result = split_and_join(line,sign)
print(result)
type : function
describe
Define a function to judge words m Whether it can be determined by the string n The letters that appear in .
This question guarantees that the letters appearing in the string are all lowercase letters , Regardless of n The number of times the letters in
Enter two strings in each of the two lines m,n
If m,n Meet the conditions , The output ’FOUND‘ , Otherwise output 'NOT FOUND'
If you enter m Contains characters other than letters , Output ’ERROR‘ end
Example 1
Input :
word
world
Output :
FOUND
Example 2
Input :
1a3e
Output :
ERROR
Example 3
Input :
at
bcda
Output :
NOT FOUND
The standard answer
def f(m,n):
for i in m:
if i not in n:
return 'NOT FOUND'
return 'FOUND'
m=input()
if m.isalpha():
n=input()
print(f(m,n))
else:
print('ERROR')
type : function
describe
Commodity prices change every day , As a businessman , Need to buy low and sell high to make a profit , Usually based on historical data , Test the benefits of the strategy .
It is known that there is a list of historical price changes of commodities . Among them the first i An element is the i The price of this commodity .
The greedy strategy used now is to require as many profitable transactions as possible in the process , And every time you buy, you have to clear your position first ( Sell all the goods you bought last time ), Multiple transactions cannot be conducted at the same time .
Define a function , Calculate the maximum profit you can make under this strategy .
For example, the price list is [1,3,5,1,8], The maximum profit is 11 element ,
The first 1 Sky buying , The first 2 Day sell Reap profit 3-1=2 element
The first 2 Sky buying , The first 3 Day sell Reap profit 5-3=2 element
The first 4 The price fell for days , So there was no deal on the third day
The first 4 Sky buying , The first 5 Day sell Reap profit 8-1=7 element
The total profit is 2+2+7=11 element
The programming template for this topic will help you create a random price list ( The price in 1-100 In the closed interval of element ), You need to enter an integer in each of the two lines , On the first line, enter a total number of days that can be traded ( That is, the number of prices in the list ), In the second line, enter an integer as the random seed .
During output, the template will output the generated price list and the maximum profit that can be obtained in two lines respectively .
Tips : The index of the list is used in the same way as the string .
Input format
Enter an integer in each of the two lines
Output format
Generated price list
The biggest profit you get
Example
Input :
10
6
Output :
[74, 11, 63, 98, 34, 5, 1, 19, 85, 76]
171
The standard answer
import random
def f(prices):
s=0
for i in range(len(prices)-1): # Be careful not to cross the line here
if prices[i]<prices[i+1]:
s+=prices[i+1]-prices[i]
return s
n=int(input())
random.seed(int(input()))
ls=[]
for i in range(0,n):
ls.append(random.randint(1,100))
print(ls)
print(f(ls))
type : function
describe
Define a function to judge words m Whether it can be determined by the string n The letters that appear in .
This question guarantees that the letters appearing in the string are all lowercase letters ,n The letters in can only be used once .
Enter two strings in each of the two lines m,n
If m,n Meet the conditions , The output ’FOUND‘ , Otherwise output 'NOT FOUND'
If you enter m Contains characters other than letters , Output ’ERROR‘ end
Example 1
Input :
word
world
Output :
FOUND
Example 2
Input :
1a3e
Output :
ERROR
Example 3
Input :
at
bcda
Output :
NOT FOUND
Example 4
Input :
hello
heol
Output :
NOT FOUND
The standard answer
def f(m,n):
for i in m:
if n.count(i)>0:
n=n.replace(i,'',1)
else:
return 'NOT FOUND'
return 'FOUND'
m=input()
if m.isalpha():
n=input()
print(f(m,n))
else:
print('ERROR')
type : function
describe
Prime or prime , It refers to a greater than 1 The integer of , except 1 And it itself , Cannot be divided by other positive integers . The prime number determination method is : First use a certain method to enumerate positive integers n All possible true factors , And verify whether the number of each enumeration is a true factor . if , Then stop enumerating , determine n As composite ; If you do not find the true factor after enumeration , Determinable n As a prime number . Define and complete the following functions :
Input and output
problem 1 If input ' prime number ', Enter a positive integer n, Output in order from small to large, no more than n All prime numbers of .
problem 2 If input ' Palindrome prime number ', Enter a positive integer n, Output less than... In descending order n All palindrome primes of .
problem 3 If input ' Anti prime number ', Enter a positive integer n, Enter a positive integer n, Output less than... In descending order n All the antiprime numbers of .
problem 4 If input ' Goldbach conjectures ', Receive a message greater than 2 An even number of , Output two prime numbers , And the sum of the two prime numbers is equal to the original even number , If there are multiple different combinations , All output , Refer to the following example for the format . If the number entered is not greater than 2 An even number of , Output 'Data error!'
If the input is not the above string , Output ' Input error '.
Example 1
Input :
prime number
100
Output :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Example 2
Input :
Palindrome prime number
200
Output :
2 3 5 7 11 101 131 151 181 191
Example 3
Input :
Anti prime number
200
Output :
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199
Example 4
Input :
Goldbach conjectures
30
Output :
30=7+23
30=11+19
30=13+17
The standard answer
def question_judge(question):
""" Receive a string as a parameter , Judge the problem type according to the parameters """
if question == ' prime number ': # If input ” prime number “, Enter a positive integer n, Output not greater than n All prime numbers of
n = int(input())
output_prime(n) # Output prime number
elif question == ' Palindrome prime number ':
n = int(input())
palindromic_prime(n) # Output palindrome prime
elif question == ' Anti prime number ':
n = int(input())
reverse_prime(n) # Output inverse prime
elif question == ' Goldbach conjectures ':
n = int(input())
goldbach_conjecture(n)
else:
print(' Input error ')
def is_prime(n):
""" A function of judging prime numbers , Receive a positive integer as a parameter , When the parameter is a prime number, it returns True, Otherwise return to False
Reduce the decision interval , Reduce the number of cycles , Improve efficiency """
if n < 2:
return False # 0、1、 Negative numbers and even numbers are not prime numbers
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0: # Can be 2 To its root n The number divided by an integer between is not a prime number
return False
else:
return True # for End of cycle , Not encountered return The number of is prime
def output_prime(number):
""" Receive a positive integer as a parameter , Ergodic 0 To number Between all the integers
Output no more than... In one line number All prime numbers of , Function has no return value """
for i in range(number + 1): # Ergodic less than n The integer of
if is_prime(i): # i Output when it is a prime number i
print(i, end=' ') # Output does not wrap , Space delimited output
def palindromic(num):
""" Receive a number as a parameter , Determine whether it is palindrome number , Returns a Boolean value ."""
if str(num) == str(num)[::-1]:
return True
else:
return False
def palindromic_prime(number):
""" Receive a positive integer parameter number, Ergodic 0 To number Between all the integers ,
If a number is prime , And after being converted to a string, it is a palindrome string , Is called palindrome prime number
Find and output less than... In the same line from small to large number All palindrome primes of , The numbers are separated by a space ,
Function has no return value """
for i in range(number): # Ergodic less than n The integer of
if palindromic(i) and is_prime(i):
print(i, end=' ') # i Output when it is palindrome prime i, Output does not wrap
def reverse_num(num):
""" Receive an integer , Returns the integer corresponding to the string in reverse order """
return int(str(num)[::-1])
def reverse_prime(number):
""" Receive a positive integer parameter , Find and output all less than... In the same line number The inverse prime of , Numbers are separated by a space .
An antiprime number is a number i And its inverse numbers are prime numbers , But the number i The corresponding string is not a palindrome string
Function has no return value """
for i in range(number): # Ergodic less than n The integer of
if not palindromic(i) and is_prime(i) and is_prime(reverse_num(i)):
print(i, end=' ') # i Output when it is palindrome prime i, Output does not wrap
def goldbach_conjecture(num):
""" Goldbach conjectures , Receive one not less than 4 The positive integer of is a parameter .
When the parameter is not less than 4 Even numbers , Decompose it into the sum of two prime numbers , By decimal + Number format output .
When there are multiple combinations, all outputs , But do not output duplicate combinations , For example, output 8=3+5, No output 8=5+3.
The parameter is odd or less than 4 when , Output 'Data error!'
"""
if num % 2 == 0 and num >= 4: # Only even numbers are judged
for i in range(num // 2+1): # exceed num // 2 The combination of is a repeated combination
if is_prime(i) and is_prime(num - i):
print(f"{num}={i}+{num-i}")
else:
print('Data error!')
if __name__ == '__main__':
problems = input()
question_judge(problems)
type : function
describe
Enter a 8 The month, year and day represented by digits , Read the month number and output the number of days in the month .
Input format
Enter a 8 Bit string representing month, year and day
Output format
Days of the month
Example
Input :20000219
Output :29
The standard answer
# Output ** How many days are there in a month
def is_leap(year):
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
return True
else:
return False
def days_of_month(date_str):
year = int(date_str[:4])
month = int(date_str[4:6])
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
elif month == 2 and is_leap(year):
return 29
else:
return 28
if __name__ == '__main__':
date_in = input() # Enter a month, year and day
print(days_of_month(date_in))