开始学习python 的第4天,看完了基础语法,打算写一些简单的题目来巩固一下语法
本人看的教程是“廖雪峰老师”的python教程,非常实用,非常适合入门
链接在此:廖雪峰python教程
# -*- coding:utf-8 -*-
## 输入年月日,判断是一年的多少天
def getN(year,month,day):
sum = 0 ## 到最后在判断是闰年还是平年
for i in range(0,month):
sum += m[i]
sum += day
if (year%400==0) or (year%4==0 and year%10!=0 ): ## 表示是闰年
sum += 1
return sum
year = input("year : ") ## 输出数据
month = input("month : ")
day = input("day : ")
m = [0,31,28,31,30,31,30,31,31,30,31,30] ## 只包括前 11 个月
year = int(year)
month = int(month)
day = int(day)
print( getN(year,month,day))
def trianges(n): ## 表示有 n 行数据
L1 = [1]
L2 = [1,1] ## 第n 行有n 个数据,首尾是1
print(L1)
print(L2)
i = 3 ## 表示开始从第 3 行开始循环
while i## i = 3
L = list(range(0,i)) ## 0 1 2
L[0],L[i-1] = 1,1
for j in range(1,i-1):
L[j] = L2[j] + L2[j-1] ## 上下两行的关系
i = i+1 ## 下一行
L2 = L
print(L)
trianges(10) ## 测试数据
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
将字符串的“23.45”转换成浮点型的23.45
DIGITS = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '0': 0}
def char2num(s):
return DIGITS[s] ## 返回数字
def fn1(x,y):
return x*10+y
def fn2(x,y):
return x/10+y
def str2folat(s):
L = s.split('.') ## 划分成两个
n1 = reduce(fn1,map(char2num,L[0])) ## 前半部分的数字
L[1] = '0'+L[1] ## 人为加个 0
n2 = reduce(fn2,map(char2num,L[1][::-1]))
n = n1+n2
return n
print(str2folat("23.45"))
import random
def get_random_list(n):
l = []
for i in range(0,n):
l.append( random.randint(1,11))
return l
def select_sort(arr):
length = len(arr) # 拿到数组的长度
for i in range(0, length - 1):
k=i
for j in range(i + 1, length):
if arr[k] > arr[j]: # 从小到大排序
k = j
# swap(arr[k],arr[i]) # 在函数中实现参数的交换不行,说明python的函数传递是“值传递”
t = arr[k]
arr[k] = arr[i]
arr[i] = t
list = get_random_list(10) # 自动生成 list
print(list)
select_sort(list)
print(list)
# 冒泡排序
def bubble_sort(arr):
length = len(arr)
for i in range(0,length-1):
for j in range(0,length-i-1):
if arr[j]>arr[j+1]:
t = arr[j]
arr[j] = arr[j+1]
arr[j+1] = t
def get_random_list(n):
l = []
for i in range(0,n):
l.append(random.randint(1,10))
return l
l = get_random_list(10)
print(l)
bubble_sort(l)
print(l)