Five exercises for lambda expressions
Grammar:
The lambda function, which is an anonymous function , creates the syntax:
Lambda parameters:express
Parameters: Optional, if provided, is usually a comma-delimited form of variable expressions, that is, positional parameters.
Expression: You cannot include a branch or loop (but allow a conditional expression ), and you cannot include a return (or yield) function. If it is a tuple , the parentheses are applied to enclose it.
Call the lambda function, and the result returned is the result of the evaluation of the expression .
Print (str (score) + ' belongs to ' +
(Lambda x: (x>=90 and ' A ' or x>=60 and ' B ' or ' C ')) (score))
2. Title: Recursive invocation of Lambda. Prints an integer n, split. such as 234, should be 2,3,4 minute three lines print out.
n = Int (input ()) F=m,f: ( (M/10)!=0 f (int (M/10), f) (m!=0 print (% (m%10)))) F (n,f)
3. Title: Decompose a positive integer into factorization. For example: Enter 90 and print out 90=2*3*3*5.
Program Analysis: The decomposition of n factorization, should first find a minimum prime number k, and then the following steps to complete:
(1) If the prime number is exactly equal to N, then the process of decomposing the factorization is finished and printed out.
(2) if n<>k, but n can be divisible by K, the value of k should be printed, and n divided by the quotient of K, as a new positive integer you n,
Repeat the first step.
(3) If n cannot be divisible by K, the first step is repeated with k+1 as the value of K.
Import OS
Import Sys
From Functools Importreduce
From math import sqrt
n = Int (input ("Pleaseinput a int:\n"))
Ans =[]
Nn=n
F=lambda m,i,c,f: (m%i ==0and F (m//i,i,c+1,f) or (m,c))
def func (x, y):
Ret,count=f (X,Y,0,F)
If count>0:
Ans.append (count * [y])
return ret
Reduce (func,[nn]+list (range (2,NN)))
Print (ANS)
4. Title: Find the value of S=A+AA+AAA+AAAA+AA...A, where a is a number. For example 2+22+222+2222+22222 (a total of 5 numbers are added at this time), several numbers are added to be controlled by the input.
n= int (Input ("n=:\n"))
AA =a= Int (input (' a=:\n '))
F=lambda n,a,ans,la,f:n==0 and Ans or f (n-1,a,ans+[la*10+a],la*10+a,f)
Print (Reduce (lambda x,y:x+y,f (n,aa,[],0,f)))
Programming: Find out all the numbers within 1000.
factors = Lambda X:filter (lambda i:x%i==0 and I,range (1,x))
f = Lambda x:sum (factors (x)) = = X
Print ([(I,list (Factors (i))) for I in List (filter (F, Range (2,1001))))