冒泡排序(从小到大升序)
冒泡分析:
冒泡代码:
lists = [11,77,34,6,28]
for i in range(len(lists) - 1): #轮数
for j in range(i + 1,len(lists)): #次数
if lists[i] > lists[j]:
lists[i],lists[j] = lists[j],lists[i]
print(lists)
练习题:(最后一小问属于冒泡)
# 商品字典
dict_commodity_infos = {
1001: {"name": "屠龙刀", "price": 10000},
1002: {"name": "倚天剑", "price": 10000},
1003: {"name": "金箍棒", "price": 52100},
1004: {"name": "口罩", "price": 20},
1005: {"name": "酒精", "price": 30},
}
#订单列表
list_orders = [
{"cid": 1001, "count": 1},
{"cid": 1002, "count": 3},
{"cid": 1005, "count": 2},
]
# 打印所有商品信息,
# 格式:商品编号xx,商品名称xx,商品单价xx.
for cid,commodity in dict_commodity_infos.items():
print("商品编号:{},商品名称:{},商品单价:{}".format(cid,commodity['name'],commodity['price']))
# 打印所有订单中的信息,
# 格式:商品编号xx,购买数量xx.
for order in list_orders:
print("商品编号:%d,购买数量:%d" % (order['cid'],order['count']))
# 打印所有订单中的商品信息,
# 格式:商品名称xx,商品单价:xx,数量xx.
for order in list_orders:
cid = order['cid']
commodity = dict_commodity_infos[cid]
print(cid,commodity)
print(f"商品名称:{commodity['name']},商品单价:{commodity['price']},数量:{order['count']}")
# 查找数量最多的订单(使用自定义算法,不使用内置函数)
max_oder_count = list_orders[0]
for j in range(1,len(list_orders)):
if max_oder_count['count'] < list_orders[j]['count']:
max_oder_count = list_orders[j]
print(max_oder_count)
# 根据购买数量对订单列表降序(大 --> 小)排列
for j in range(len(list_orders)-1):
for i in range(j+1, len(list_orders)):
if list_orders[j]['count'] < list_orders[i]['count']:
list_orders[j], list_orders[i] = list_orders[i], list_orders[j]
print(list_orders)
函数练习题
# 练习1: 定义函数, 在终端中打印一维列表.
# list01 = [5, 546, 6, 56, 76]
# for item in list01:
# print(item)
# list02 = [7, 6, 879, 9, 909]
# for item in list02:
# print(item)
def print_list(list_data):
for i in list_data:
print(i)
list01 = [5,546,6,56,76]
list02 = [7,6,879,9,909]
print_list(list01)
print_list(list02)
# 练习2:创建函数,在终端中打印矩形.
def print_rect(number):
for row in range(number):
if row == 0 or row == number - 1:
print("*" * number)
else:
print("*%s*" % (" " * (number - 2)))
number = int(input("请输入整数:"))
print_rect(number)
函数有点难昂,哭辽,今天就先到这里吧