我正在学习Python并试图解决不同的问题,我遇到了这个程序,它是Get编程中的名称mashup :学习用python编写代码。
问题陈述:编写一个程序,自动组合由用户指定的两个名称。这是一个开放的问题陈述,所以让我们添加一些更多的细节和限制:
我想知道是否有任何方法来改进这个程序,比如使用函数使这个程序更好。
print('Welcome to the Name Mashup Game')
name1 = input('Enter one full name(FIRST LAST): ')
name2 = input('Enter second full name(FIRST LAST): ')
space = name1.find(" ")
name1_first = name1[0:space]
name1_last = name1[space+1:len(name1)]
space = name2.find(" ")
name2_first = name2[0:space]
name2_last = name2[space+1:len(name2)]
# find combinations
name1_first_1sthalf = name1_first[0:int(len(name1_first)/2)]
name1_first_2ndhalf = name1_first[int(len(name1_first)/2):len(name1_first)]
name1_last_1sthalf = name1_last[0:int(len(name1_last)/2)]
name1_last_2ndhalf = name1_last[int(len(name1_last)/2):len(name1_last)]
name2_first_1sthalf = name2_first[0:int(len(name2_first)/2)]
name2_first_2ndhalf = name2_first[int(len(name2_first)/2):len(name2_first)]
name2_last_1sthalf = name2_last[0:int(len(name2_last)/2)]
name2_last_2ndhalf = name2_last[int(len(name2_last)/2):len(name2_last)]
new_name1_first = name1_first_1sthalf + name2_first_2ndhalf
new_name1_last = name1_last_1sthalf + name2_last_2ndhalf
new_name2_first = name2_first_1sthalf + name1_first_2ndhalf
new_name2_last = name2_last_1sthalf + name1_last_2ndhalf
# print results
print(new_name1_first, new_name1_last)
print(new_name2_first, new_name2_last)发布于 2020-04-05 05:49:09
当您对不同的值做本质上相同的事情(即使是不同的顺序)时,强烈的提示是,这些值应该是集合(如列表或元组),而不是独立命名的变量。它通常会使您的代码更短,并且使扩展变得容易得多--如果您想要使用更多名称的mashup游戏怎么办?
from itertools import permutations
from typing import List
print('Welcome to the Name Mashup Game')
names = [
input('Enter one full name(FIRST LAST): ').split(),
input('Enter second full name(FIRST LAST): ').split(),
# input('Enter third full name(FIRST LAST):' ).split(), <- try me!
]
def mash(first: List[str], second: List[str]) -> List[str]:
"""
Produce a list where each element has the first half of the corresponding
element from the first list and the second half of the corresponding
element from the second list.
For example:
mash(['AA', 'BB'], ['XX', 'YY']) -> ['AX', 'BY']
"""
return [
a[:len(a)//2] + b[len(b)//2:]
for a, b in zip(first, second)
]
for first, second in permutations(names, 2):
print(' '.join(mash(first, second)))https://codereview.stackexchange.com/questions/239956
复制相似问题