Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
1. The use of the slicing operation, to achieve a trim () function, end to end string of blanks is removed. Be careful not to call the str strip () method.
def trim(s):
while len(s)>0 and s[:1]==' ':
s=s[1:]
while len(s)>0 and s[-1:]==' ':
s=s[:-1]
return s
def test_trim():
assert trim('hello ') == 'hello'
assert trim(' hello') == 'hello'
assert trim('hello ') == 'hello'
assert trim(' hello') == 'hello'
test_trim()
2. Use an iterative find a list of the minimum and maximum values, and returns a tuple. Iteration is actually for traversal.
def findMinAndMax(L):
if L==[]:
return (None,None)
else:
min=max=L[0]
for x in L:
if x>max:
max=x
for y in L:
if y<min:
min=y
return (min,max)
Do not use an iterative method to achieve
def findMinAndMax(L):
n = len(L)
L.sort()
if n == 0:
return(None,None)
else:
return (L[0],L[n-1])
3. Use formula list, the list of elements of type String Africa was filtered off, and the lower case string.
L1 = ['Hello', 'World', 18, 'Apple', None]
Results: [ 'hello', 'world', 'apple']
L2 = [i.lower() for i in L1 if isinstance(i, str)]