基础第一练
第一题
#encoding=utf-8
def first(num):
ls = [
'Twinkle,twinkle,little star,',
' How I wonder what you are!',
' Up above thr world so high,',
' Like a diamond in the sky.'
]
for i in range(num):
print(ls[i%4])
if __name__ == '__main__':
print(first(6))
第二题
#encoding=utf-8
import sys
def check():
return sys.version_info.major, sys.version_info.minor
a,b = check()
print('python版本为{0}.{1}'.format(a,b))
第三题
#encoding=utf-8
import time
def get_now_time():
return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
print(get_now_time())
第四题
#encoding-utf-8
from math import pi
def circle_area(r):
return pow(r,2) * pi
print(circle_area(1.1))
第五题
#encoding=utf-8
def name(last_name,first_name):
return first_name+' '+last_name
a = str(input('输入名:'))
b = str(input('输入姓:'))
if __name__ == '__main__':
print(name(a,b))
排序算法
插入排序:
#encoding=utf-8
def insert_sort(nums):
for i in range(1,len(nums)): #遍历未排序元素
for j in range(i): #遍历已排序元素
if nums[j] > nums[i]:
num = nums.pop(i)
nums.insert(j,num)
break #插入完成结束循环
return nums
if __name__ == '__main__':
nums = [10, -5, 7, 9, 2, 3, 8, -2, 0, -6]
print(insert_sort(nums))
选择排序
#encoding=utf-8
def select_sort(nums):
for i in range(len(nums)-1): #更新末尾位置
minInd = i
for j in range(i,len(nums)): #找出最小值索引
if nums[j] < nums[minInd]:
minInd = j
nums[i],nums[minInd] = nums[minInd],nums[i] #最小值与第一位交换
return nums
if __name__ == '__main__':
nums = [10,-5,7,9,2,3,8,-2,0,-6]
print(select_sort(nums))
冒泡排序
#encoding=utf-8
def bubble_sort(list):
length = len(list)
index1 = 0
while index1 < length:
index2 = 0
# print('第{}次排序'.format(index1))
while index2 < length-index1-1:
if list[index2] > list[index2+1]:
list[index2], list[index2+1] = list[index2+1],list[index2]
index2 += 1
# print(list)
index1 +=1
return list
if __name__ == '__main__':
data = [10,-5,7,9,2,3,8,-2,0,-6]
print('排序后的数据:',bubble_sort(data))
归并排序
#encoding=utf-8
def MergeSort(nums): #分冶思想
if len(nums) <= 1:
return nums
mid = int(len(nums)/2)
left_list,right_list = MergeSort(nums[:mid]),MergeSort(nums[mid:])
l,r = 0,0
ls = []
while l < len(left_list) and r < len(right_list):
if right_list[r] < left_list[l]:
ls.append(right_list[r])
r += 1
else :
ls.append(left_list[l])
l += 1
ls += left_list[l:] + right_list[r:]
return ls
if __name__ == '__main__':
nums = [10, -5, 7, 9, 2, 3, 8, -2, 0, -6]
print(MergeSort(nums))