联系方式

  • QQ:99515681
  • 邮箱:99515681@qq.com
  • 工作时间:8:00-23:00
  • 微信:codinghelp

您当前位置:首页 >> OS作业OS作业

日期:2018-08-01 04:11

import csv



def load_states():

   states_dict = dict()


   with open('us_states.csv', 'r') as f:

       for line in csv.reader(f):

           states_dict[line[1]] = int(line[3])


   return states_dict



def load_borders():

   borders_list = list()


   with open('border_data.csv', 'r') as f:

       for line in csv.reader(f, 1):

           states = line[1].split('-')

           if len(states) == 2:

               borders_list.append((states[0], states[1]))


   return borders_list



# This function returns the state and population of the "most populous

# neighbor" bordering the candidate nation.

def most_populous_neighbor(states, borders, nation):

   neighbor = ''

   pop = 0


   for s in nation:

       for border in borders:

           if border[0] == s and border[1] in states:

               candidate = border[1]

               candidate_pop = states[border[1]]


               if candidate not in nation and candidate_pop > pop:

                   neighbor = candidate

                   pop = candidate_pop


           if border[1] == s and border[0] in states:

               candidate = border[0]

               candidate_pop = states[border[0]]


               if candidate not in nation and candidate_pop > pop:

                   neighbor = candidate

                   pop = candidate_pop


   return neighbor, pop



def new_nation_n_states(n):

   new_nation = []

   max_pop = 0


   # The states of Alaska and Hawaii don't border any other state, so the

   # largest contiguous nation would consist of the "lower 48" states.

   if n > 0 and n <= 48:

       states = load_states()

       borders = load_borders()


       # Our naive implementation starts with MN. One easy improvement would

       # be to replace MN with CA (our most populous state), but you can do

       # far better than this!

       new_nation = ('MN',)

       max_pop = states['MN']


       # This is a "greedy" algorithm - we simply find the most populous

       # state bordering our candidate nation and append it to the list.

       while len(new_nation) < n:

           next_st, pop = most_populous_neighbor(states, borders, new_nation)

           new_nation += (next_st,)

           max_pop += pop


   return new_nation, max_pop


版权所有:留学生编程辅导网 2020 All Rights Reserved 联系方式:QQ:99515681 微信:codinghelp 电子信箱:99515681@qq.com
免责声明:本站部分内容从网络整理而来,只供参考!如有版权问题可联系本站删除。 站长地图

python代写
微信客服:codinghelp