《程序员的算法趣题》-(日)增井敏克 , 书中为69 道数学谜题编写了解题程序, 编程语言为:Ruby,JavaScript,C语言。有兴趣的同学,可以购书阅读~
在此更新个人编写的Python版,仅供学习使用。(运行环境:Python3.6)
Q14 世界杯参赛国的国名接龙
2014 年 FIFA 世界杯的 32 个参赛国
举个例子,如果像下面这样,那么连续 3 个国名之后接龙就结束了(因为没有英文名称以 D 开头的国家)。
“Japan” →“Netherlands” →“Switzerland”问题
假设每个国名只能使用一次,求能连得最长的顺序,以及相应的国名个数。
country_list = ["Brazil", "Croatia", "Mexico",
"Cameroon", "Spain", "Netherlands",
"Chile", "Australia", "Colombia",
"Greece", "Cote d'Ivoire", "Japan",
"Uruguay", "Costa Rica", "England",
"Italy", "Switzerland", "Ecuador",
"France", "Honduras", "Argentina",
"Bosnia and Herzegovina", "Iran", "Nigeria",
"Germany", "Portugal", "Ghana",
"USA", "Belgium", "Algeria",
"Russia", "Korea Republic", ]
max_country_list = []
def find_next_country(used_country_list, country_map):
bfind = False
if len(country_map) != 0:
for index, c in enumerate(country_map):
if c[0] == used_country_list[-1][-1].upper():
find_next_country(used_country_list + [c], country_map[:index] + country_map[index + 1:])
bfind = True
if not bfind or len(country_map) == 0:
global max_country_list
if len(max_country_list) < len(used_country_list):
max_country_list = used_country_list
for i, country in enumerate(country_list):
find_next_country([country], country_list[:i]+country_list[i+1:])
print("能连得最长的国名个数为:%s\n%s" % (len(max_country_list), max_country_list))
运行结果:
能连得最长的国名个数为:8
['Korea Republic', 'Cameroon', 'Netherlands', 'Spain', 'Nigeria', 'Australia', 'Argentina', 'Algeria']