# 实践案例：Python22个构造函数法-助力数据挖掘与分析

“写函数”也就是自己写一个算法，用来实现一些功能。比如最简单的给电脑两个参数，让他计算这两个参数的关系。

a = 5                               b = 10                                                     a, b = b, a    print(a) # 10    print(b) # 5# 这个看起来不是函数，但是这种用法在函数中常用

def is_even(num):return num % 2 == 0is_even(10)  # True

def split_lines(s):return s.split('\n')split_lines('50\n python\n snippets') # ['50', ' python', ' snippets']

import sysprint(sys.getsizeof(5)) # 28print(sys.getsizeof("Python")) # 55

language = "sumer-minus"   # SUMER是我公众号，minus是我一个网名reversed_language = language[::-1]print(reversed_language)  # sunim-remus

def repeat(string, n):return (string * n)a=repeat('oop!',10) print(a)>>>oop!oop!oop!oop!oop!oop!oop!oop!oop!oop!

def palindrome(string):return string == string[::-1]print(palindrome('python')) # False

strings = ['老虎', '老鼠', '蟑螂']print('kill'.join(strings))# 老虎kill老鼠kill蟑螂

def union(a,b):return list(set(a + b))union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4]) # 答案：[1,2,3,4,5,6,8]

def unique_elements(numbers):return list(set(numbers))unique_elements([1, 2, 3, 2, 4]) # 答案：[1, 2, 3, 4]

def average(*args):return sum(args, 0.0) / len(args)average(5, 8, 2) # 5.0

def unique(list):if len(list)==len(set(list)):        print("所有数据都是唯一的")else:        print("并不唯一")unique([1,2,3,4,5]) # 所有数据都是唯一的

def most_frequent(list):return max(set(list), key = list.count)numbers = [1, 2, 3, 2, 4, 3, 1, 3]most_frequent(numbers) # 3

π在math 库中是有定义的,就叫做math.pi

import mathdef degrees_to_radians(deg):return (deg * math.pi) / 180.0degrees_to_radians(90) # 1.5707963267948966

import timestart_time = time.time()a,b = 5,10  #随便一个过程c = a+b     #随便一个过程end_time = time.time()time_taken = (end_time- start_time)*(10**6)print("运行这个耗费微秒数为:", time_taken)# 运行这个耗费微秒数为: 2.1457672119140625

from functools import reduceimport mathdef gcd(numbers):return reduce(math.gcd, numbers)gcd([24,108,90]) # 6

x = lambda a, b, c : a + b + cprint(x(5, 10, 20)) # 35# 或者也可以这样def x(a, b, c): return a + b + cprint(x(5, 10, 30))  # 35

def multiply(n):return n*nlist1 =[1, 2, 3]result = list(map(multiply, list1))print(result)# [1, 4, 9]

arr = [1, 2, 3, 4, 5]def Even(x):return list(filter(lambda x: x % 2 == 0, arr))Even(arr)  # [2, 4]

numbers = [1, 2, 3]def squares(nums):return [number**2 for number in nums] squares(numbers)# [1, 4, 9]

def rotate(arr, d):return arr[d:] + arr[:d]if __name__ == '__main__':    arr = [1, 2, 3, 4, 5]    arr = rotate(arr, 2)print (arr) # 结果：[3, 4, 5, 1, 2]

def add(a, b):return a + bdef subtract(a, b):   return a - ba, b = 5, 10print((subtract if a > b else add)(a, b))  # 15print((subtract if a < b else add)(a, b))  # -5