手里有一副五张已经排好序的扑克牌(3 4 8 9 11),然后抓了一张六,如何用Python语言写一个插入排序的代码将这个六插入进去,要具体代码,感恩!
大概就是把图片这样的VB写法改成Python😭
cards = [3, 4, 8, 9, 11] # 已排序的牌
new_card = 6 # 新牌
# 插入排序
for i in range(1, len(cards)):
key = cards[i]
j = i - 1
while j >= 0 and key < cards[j]:
cards[j+1] = cards[j]
j -= 1
cards[j+1] = key
# 将新牌插入已排序的牌中
cards.append(new_card)
for i in range(len(cards)-1, 0, -1):
if cards[i] < cards[i-1]:
cards[i], cards[i-1] = cards[i-1], cards[i]
print(cards) # 输出结果:[3, 4, 6, 8, 9, 11]
代码解释:
可以使用Python的插入排序算法来将新的牌插入到已排序的牌中。具体步骤如下:
定义一个已排序的列表,将五张已排好序的牌放入其中。
定义一个新的变量来存储需要插入的牌,即六。
遍历已排序的列表,比较每张牌和需要插入的牌的大小。
如果已排序的牌比需要插入的牌小,将其添加到新的列表中。
插入需要插入的牌。
将剩余的已排序的牌添加到新的列表中。
输出新的列表,即为插入后的牌序列。
下面是Python实现的代码:
cards = [3, 4, 8, 9, 11] # 已排序的牌
new_card = 6 # 需要插入的牌
# 插入排序算法
def insert_card(sorted_cards, new_card):
new_cards = [] # 新的列表
inserted = False # 记录是否已经插入过新牌
for card in sorted_cards:
if card < new_card:
new_cards.append(card)
elif not inserted:
new_cards.append(new_card)
new_cards.append(card)
inserted = True
else:
new_cards.append(card)
if not inserted:
new_cards.append(new_card)
return new_cards
# 输出插入后的牌序列
print(insert_card(cards, new_card))
输出结果为:[3, 4, 6, 8, 9, 11]
题目都打在注释里了。
#ex6-1 friend
#使用一个字典存储一个朋友的信息,包括:名、姓、年龄和居住的城市
#该字典应包含键first_name、last_name、age和city
friend={'first_name':'Jenne','last_name':'Liu','age':22,'city':"Xi'an"}
#将存储在字典中的每项信息全部打印出来
print("She is my friend,and her name is "+
friend['first_name']+
" "+
friend['last_name']+
","+
"She "+
str(friend['age'])+
" years old"+
","
"and live in "+
friend['city']+
" now."+
"\n")
#ex6-2 favorite_number
#使用一个字典来存储一些人喜欢的数字,想出5个人的名字,将这些名字用作字典中的键
#想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中
favorite_number={
'Ann':5,
'Anne':26,
'Ben':1,
'Benny':21,
'Coco':6,
}
#打印每个人的名字和喜欢的数字
print("Ann:"+
str(favorite_number['Ann'])+
"\n"+
"Anne:"+
str(favorite_number['Anne'])+
"\n"+
"Ben:"+
str(favorite_number['Ben'])+
"\n"+
"Benny:"+
str(favorite_number['Benny'])+
"\n"+
"Coco:"+
str(favorite_number['Coco'])+
"\n")
#ex6-3 vocabulary
#创建一个字典,存储5个学过的词汇,将其用作词汇表中的键,并将它们的含义作为值存储在词汇表中
vocabulary={
'a':'one single;any',
'abandon':'give up completely',
'anne':'Queen of England',
'anyone':'any person or people',
'rice':'the grains of this cereal used as food'}
#以整洁的方式打印每个词汇及其含义,先打印词汇,后面加上一个冒号,再打印词汇含义
#在一行打印词汇,再使用换行符(\n),插入一个空行
#在下一行以缩进的方式打印词汇含义
print("a:\n\t"+
vocabulary['a']+
"\n"+
"abandon:\n\t"+
vocabulary['abandon']+
"\n"+
"anne:\n\t"+
vocabulary['anne']+
"\n"+
"anyone:\n\t"+
vocabulary['anyone']+
"\n"+
"rice:\n\t"+
vocabulary['rice']+
"\n")
#ex6-4 vocabulary_2
#将ex6-3中的一系列print语句替换为一个遍历字典中的键和值的循环
for word,paraphrase in vocabulary.items():
print("Word:"+word)
print("Paraphrase:"+paraphrase)
print("\n")
print("________________________________________________________________")
#向列表中添加5个词语,再次运行时将这5个新术语及其含义自动包含在输出中
vocabulary['balance']='remain in a steady position without falling'
vocabulary['cat']='a wild animal of the cat family'
vocabulary['dog']='a wild animal of the dog family'
vocabulary['deal']='take part in commercial trading of a particular commodity'
vocabulary['dawn']='the first appearance of light in the sky before sunrise'
#将新术语包含在输出中
for word,paraphrase in vocabulary.items():
print("Word:"+word)
print("Paraphrase:"+paraphrase)
print("\n")
#ex6-5 river
#创建一个字典,存储三条大河流及其流经的国家
river={
'nile':'egypt',
'yellow river':'china',
'ganges':'india',
}
#使用循环为每条河流打印一条消息
for river_name,country in river.items():
print("The "+river_name.title()+
" runs through "+country.title()+
".")
print("\n")
#使用循环将该字典中每条河流的名字都打印出来
for river_name in river.keys():
print(river_name.title())
print("\n")
#使用循环将该字典包含的每个国家的名字都打印出来
for country in river.values():
print(country.title())
print("\n")
#ex6-6 investigate
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,其他人未包含在字典中
users=['jen','sarah','dannel','edward','phil','coco']
#遍历人员名单
for user_name in users:
#对于已参与调查的人,打印一条消息表示感谢
if user_name in favorite_languages.keys():
print(user_name.title()+",thank you for taking the poll.")
#对于未参与调查的人,打印一条消息邀请他参与调查
if user_name not in favorite_languages.keys():
print(user_name.title()+",please take our poll as soon as possible.")
print("\n")
#ex6-7 friend_2
#基于ex6-1,再创建两个表示人的字典
friend_0={'first_name':'Jenne','last_name':'Liu','age':22,'city':"Xi'an"}
friend_1={'first_name':'Jerry','last_name':'Zhang','age':21,'city':"Xi'an"}
friend_2={'first_name':'Casey','last_name':'Deng','age':21,'city':'Manchester'}
#将这三个字典都存储在一个名为people的列表中
people=[friend_0,friend_1,friend_2]
#遍历这个列表,将其中每个人的信息都打印出来
for friend in people:
print(friend)
print("\n")
#ex6-8 pets
#创建多个字典,对于每个字典都使用一个宠物的名称来命名
Ding={'variety':'British short','host':'Sylvia'}
Ro={'variety':'Muppet','host':'Rodaddy'}
Nine={'variety':'Chinese pastoral cat','host':'Ninemommy'}
#将这些字典存储在一个名为pets的列表中
pets=[Ding,Ro,Nine]
#遍历这个列表,将宠物所有信息都打印出来
for pet in pets:
print(pet)
print("\n")
#ex6-9 favorite_places
#创建名为favorite_places的字典
#将三个人名用作键,对于每个人存储1~3个喜欢的地方
favorite_places={
"Sylvia":['Beijing','Guangzhou'],
"Nana":['Hangzhou'],
"Jenny":['Shanghai','Dalian'],
}
for friend_name,favorite_place in favorite_places.items():
if len(favorite_place)==1:
print("\n"+friend_name.title()+"'s favorite place is:")
for favorite_city in favorite_place:
print("\t"+favorite_city.title())
else:
print("\n"+friend_name.title()+"'s favorite places are:")
for favorite_city in favorite_place:
print("\t"+favorite_city.title())
#ex6-10 favorite_number_2
#基于ex6-2,让每个人可以有更多个喜欢的数字
favorite_numbers={
'Ann':[5,26],
'Anne':[50],
'Ben':[1,21],
'Benny':[5,20],
'Coco':[6],
}
#将每个人的名字和喜欢的数字打印出来
for friend_name,favorite_number in favorite_numbers.items():
if len(favorite_number)==1:
print("\n"+friend_name.title()+"'s favorite number is:")
for favorite_number_2 in favorite_number:
print("\t"+str(favorite_number_2))
else:
print("\n"+friend_name.title()+"'s favorite numbers are:")
for favorite_number_2 in favorite_number:
print("\t"+str(favorite_number_2))
#ex6-11 cities
#创建一个名为cities的字典,其中三个城市名称用作键
#对于每座城市都创建一个字典,并包含该城市所属国家,人口
cities={
'Xian':{
'Country':'China',
'Population':13163000,
},
'New York':{
'Country':'America',
'Population':8510000,
},
'Manchester':{
'Country':'England',
'Population':514400,
},
}
#将每座城市的名字以及有关他们的信息都打印出来
for city_name,city_information in cities.items():
print("\nCityname:"+city_name+
"\n\tCountry:"+city_information['Country']+
"\n\tPopulation:"+str(city_information['Population']))