Question

please do a and b

Lab Exercise 9 Assignment Overview This lab exercise provides practice with dictionaries of lists and sets in Python. A. Writand cities.txt contains city Country Bulgaria China Japan Tunisia Poland Germany Poland Bulgaria Nigeria China Tunisia France

0 0
Add a comment Improve this question Transcribed image text
Answer #1

a)

Code Screenshots:

def build_map in_file1, in_file2 ) in file1.readline ) in_file2.readline ) data_map {} #READ EACH LINE FROM FILE 1 for line iif country in data_map[continent] # YOUR CODE if City not in data_map[continent] [country]: data_map[continent] [country].appreturn in_file ain(): YOUR CODE in_file1 open file( #Continents with countries file: continents.txt in_file2 open_file) #Coun

Sample Input File(continents.txt):

Continent    Country

Africa      Tunisia

Europe      Bulgaria

Asia        China

Asia        Japan

Europe     Poland

Europe      Germany

Africa      Nigeria

Africa      Tunisia

Sample Input File(cities.txt):

Country        City

Bulgaria    Sofia

China       Beijing

Japan       Tokyo

Tunisia     Sousse

Poland      Warsaw

Poland      Ponzan

Germany     Berlin

Bulgaria    Plovdiv

Nigeria     Abuja

China       Shanghai

Tunisia     Tunis

France      Paris

Japan       Tokyo

Sample Output:

Enter file name: continents.txt Enter file name: cities.txt Africa: Nigeria Tunisia --> Sousse, Tunis Asia: -- Abuia China >

Code To Copy:

def build_map( in_file1, in_file2 ):

   

    in_file1.readline()

    in_file2.readline()

    data_map = {}

    #READ EACH LINE FROM FILE 1

    for line in in_file1:

        # Split the line into two words

        countries_list = line.strip().split()

       

        # Convert to Title case, discard whitespace

        continent = countries_list[0].strip().title()

        country = countries_list[1].strip().title()

        # Ignore empty strings

        if continent != "":

            # If current continent not in map, insert it

            # YOUR CODE

            if continent not in data_map:

               

            # insert country (continent is guaranteed to be in map)

                data_map[continent] = {country: []}

            else:

            #YOUR CODE

            # If current country not in map, insert it

                if country not in data_map[continent]:

                        data_map[continent][country] = []

     #READ EACH LINE FROM FILE 2       

    for line in in_file2:

        # Split the line into two words (based on :)

        cities_list = line.strip().split()

       

        # Convert to Title case, discard whitespace

        country = cities_list[0].strip().title()

        City = cities_list[1].strip().title()

       

        # Ignore empty strings

        if country != "":

           

            # insert city (country is guaranteed to be in map)

            for continent in data_map:

                if country in data_map[continent]:

                    # YOUR CODE

                    if City not in data_map[continent][country]:

                        data_map[continent][country].append(City)

       

   

    return data_map

def display_map( data_map ):

    #Modify this code to display a sorted nested dictionary

    continents_list = sorted(data_map.keys()) #sorted list of the continent keys

    for continents in continents_list:

        print("{}:".format(continents)) #continents in continents_list

        countries_list = sorted(data_map[continents].keys()) #sorted list of the countries keys in the continents

        for countries in countries_list:

            print("{:>10s} --> ".format(countries),end = '') #countries in countries_list

            cities = sorted(data_map[continents][countries]) #sorted list of the cities

            #when printing add a comma and a space after the cities names

            # if it is the last, don't add a comma and a space.

            for i in range (len(cities)):

                city = cities[i]

                if i != len(cities) - 1:

                    print('{}, '.format(city),end = '') # city in cities

                else:

                    print('{}'.format(city)) # city in cities

def open_file():

    try:

        filename = input("Enter file name: ")

        in_file = open( filename, "r" )

       

    except IOError:

        print( "\n*** unable to open file ***\n" )

        in_file = None

    return in_file

def main():

    # YOUR CODE

    in_file1 = open_file() #Continents with countries file: continents.txt

    in_file2 = open_file() #Countries with cities file: cities.txt

    if in_file1 != None and in_file2 != None:

        data_map = build_map( in_file1, in_file2 ) # data_map is a dictionary

        display_map( data_map )

        in_file1.close()

        in_file2.close()

if __name__ == "__main__":

    main()

b)

Code Screenshots:

def build_map in_file1, in_file2 ) in file1.readline ) in_file2.readline ) data_map {} #READ EACH LINE FROM FILE 1 for line iif country in data_map[continent] # YOUR CODE data_map[continent] [country].add (City) return data_map def display map data mreturn in_file def main(): # YOUR CODE open file #Continents with countries file: continents.txt in filel in_file2 open_file)

Sample Input File(continents.txt):

Continent    Country

Africa      Tunisia

Europe      Bulgaria

Asia        China

Asia        Japan

Europe     Poland

Europe      Germany

Africa      Nigeria

Africa      Tunisia

Sample Input File(cities.txt):

Country        City

Bulgaria    Sofia

China       Beijing

Japan       Tokyo

Tunisia     Sousse

Poland      Warsaw

Poland      Ponzan

Germany     Berlin

Bulgaria    Plovdiv

Nigeria     Abuja

China       Shanghai

Tunisia     Tunis

France      Paris

Japan       Tokyo

Sample Output:

Enter file name: continents.txt Enter file name: cities.txt Africa: Nigeria Tunisia --> Sousse, Tunis Asia: -- Abuia China >

Code To Copy:

def build_map( in_file1, in_file2 ):

   

    in_file1.readline()

    in_file2.readline()

    data_map = {}

    #READ EACH LINE FROM FILE 1

    for line in in_file1:

        # Split the line into two words

        countries_list = line.strip().split()

       

        # Convert to Title case, discard whitespace

        continent = countries_list[0].strip().title()

        country = countries_list[1].strip().title()

        # Ignore empty strings

        if continent != "":

            # If current continent not in map, insert it

            # YOUR CODE

            if continent not in data_map:

               

            # insert country (continent is guaranteed to be in map)

                data_map[continent] = {country: set()}

            else:

            #YOUR CODE

            # If current country not in map, insert it

                if country not in data_map[continent]:

                        data_map[continent][country] = set()

     #READ EACH LINE FROM FILE 2       

    for line in in_file2:

        # Split the line into two words (based on :)

        cities_list = line.strip().split()

       

        # Convert to Title case, discard whitespace

        country = cities_list[0].strip().title()

        City = cities_list[1].strip().title()

       

        # Ignore empty strings

        if country != "":

           

            # insert city (country is guaranteed to be in map)

            for continent in data_map:

                if country in data_map[continent]:

                    # YOUR CODE

                    data_map[continent][country].add(City)

       

   

    return data_map

def display_map( data_map ):

    #Modify this code to display a sorted nested dictionary

    continents_list = sorted(data_map.keys()) #sorted list of the continent keys

    for continents in continents_list:

        print("{}:".format(continents)) #continents in continents_list

       countries_list = sorted(data_map[continents].keys()) #sorted list of the countries keys in the continents

        for countries in countries_list:

            print("{:>10s} --> ".format(countries),end = '') #countries in countries_list

            cities = sorted(data_map[continents][countries]) #sorted list of the cities

            #when printing add a comma and a spce after the cities names

            # if it is the last, don't add a comma and a space.

            for i in range (len(cities)):

                city = cities[i]

                if i != len(cities) - 1:

                    print('{}, '.format(city),end = '') # city in cities

                else:

                    print('{}'.format(city)) # city in cities

def open_file():

    try:

        filename = input("Enter file name: ")

        in_file = open( filename, "r" )

       

    except IOError:

        print( "\n*** unable to open file ***\n" )

        in_file = None

    return in_file

def main():

    # YOUR CODE

    in_file1 = open_file() #Continents with countries file: continents.txt

    in_file2 = open_file() #Countries with cities file: cities.txt

    if in_file1 != None and in_file2 != None:

        data_map = build_map( in_file1, in_file2 ) # data_map is a dictionary

        display_map( data_map )

        in_file1.close()

        in_file2.close()

if __name__ == "__main__":

    main()

Add a comment
Know the answer?
Add Answer to:
please do a and b Lab Exercise 9 Assignment Overview This lab exercise provides practice with...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • HI, I need help with this question. Please answer in details. The data set is found below for eac...

    HI, I need help with this question. Please answer in details. The data set is found below for each countries sugar consumption. Thanks! Country,Sugar, GDP, Continent Albania,15.3,4556.144342, Europe Argentina, 38.1,13693.70379, South America Armenia, 33.2,3421.704509, Europe Australia, 34.1, 62080.98242, Europe Austria, 37.9,49485.48219, Europe Azerbaijan,13.9,7189.691229, Europe Belarus,31.8,6305.773662, Europe Belgium, 41.4,46463.60378, Europe Bosnia and Herzegovina,13.4,4754.197861, Europe Brazil, 36.5,12576.19559, South America Canada, 31.3,51790.56695, North America Chile, 41.7,14510.9661, South America China, 6.2,5447.309378,Asia Colombia,23.2, 7124.54892, South America Czech Republic, 30.6,20584.92655, Europe Denmark, 38,59911.90466,Europe Egypt, 26.4,2972.583516,Africa Estonia,31.4,16982.30031,...

  • Will reward thumbs up 100% if works. thank you Pickling with Python code and Pandas code Do both ...

    Will reward thumbs up 100% if works. thank you Pickling with Python code and Pandas code Do both pickling assignment in one Jupyter Notebook file. Python Pickle steps: Download the CSV file. Load into a Pandas DataFrame. Make the column ‘country’ the index. Print the header. Using Python code, pickle the DataFrame and name the file: PythonPickle. Load back the PythonPickle data into the DataFrame. Print the header. (Note both printed headers should match.) Pandas Pickle steps: Download the CSV...

  • HI, I need help with answering these questions. Please explain and answer all parts. Data for all...

    HI, I need help with answering these questions. Please explain and answer all parts. Data for all the countries and then the question at the bottom. Sugar Consumption Per Capita.csv Country Albania Argentina Armenia Australia Austria Azerbaijan Belarus Belgium Bosnia and Herzegovina 13.4 4754.197861 Europe Brazil Canada Chile China Colombia Czech Republic Denmark Egypt Estonia Finland France Georgia Germany Ghana Greece Hungary Iceland India Indonesia Iran Sugar GDP Continent 15.3 4556.144342 Europe 38.1 13693.70379 South America 33.2 3421.704509 Europe 34.1...

  • QUESTION 3)What is the critical value of the test statistic to test the mean child mortality...

    QUESTION 3)What is the critical value of the test statistic to test the mean child mortality rate for countries in Africa is more than the mean child mortality rate for countries in South Asia? 0.59 0.299 0.126 2.015 2.35 Case Description Corporations with international operations need to assess the risks associated with setting up and maintaining operations in different regions of the world. Consideration of the risks include considering such issues as political and economic stability. One indicator of the...

  • Lab Exercise #15 Assignment Overview This lab exercise provides practice with Pandas data analysis library. Data...

    Lab Exercise #15 Assignment Overview This lab exercise provides practice with Pandas data analysis library. Data Files We provide three comma-separated-value file, scores.csv , college_scorecard.csv, and mpg.csv. The first file is list of a few students and their exam grades. The second file includes data from 1996 through 2016 for all undergraduate degree-granting institutions of higher education. The data about the institution will help the students to make decision about the institution for their higher education such as student completion,...

  • QUESTION 2) What is the conclusion for t-test concerning if the mean child mortality rate for...

    QUESTION 2) What is the conclusion for t-test concerning if the mean child mortality rate for countries in Eastern Europe is more than the mean child mortality rate for countries in the Middle East? There is insufficient evidence that the mean child mortality rate for countries in Eastern Europe is more than the mean Child mortality rate for countries in the Middle East.   The means are exactly the same.   There is insufficient evidence that the mean child mortality rate for...

  • Case Description Corporations with international operations need to assess the risks associated with setting up and...

    Case Description Corporations with international operations need to assess the risks associated with setting up and maintaining operations in different regions of the world. Consideration of the risks include considering such issues as political and economic stability. One indicator of the healthcare and quality of life in a country or region that is considered correlated with the risk and stability in the region is the child mortality rate. As a result, the healthcare and quality of care as measured by...

  • 12 Use data_2002. Use ggplot. Plot gdpPercap vs lifeExp. 13 Use data_2002. Use ggplot. Plot gdpPercap...

    12 Use data_2002. Use ggplot. Plot gdpPercap vs lifeExp. 13 Use data_2002. Use ggplot. Plot gdpPercap vs lifeExp by continent (color) 14 Use data_2002. Use ggplot. Plot gdpPercap vs lifeExp by continent and pop (color and size) 15 Get data for Europe in 2002. Call it data_Europe Looking for these problems in R command code answers. 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 2002 2007 142 142 142 142 142 142 142 142 142 142 142 142...

  • DATA: # happy2.py import csv def main(): happy_dict = make_happy_dict() print_sorted_dictionary(happy_dict) def make_happy_dict(): filename = "happiness.csv"...

    DATA: # happy2.py import csv def main(): happy_dict = make_happy_dict() print_sorted_dictionary(happy_dict) def make_happy_dict(): filename = "happiness.csv" happy_dict={} with open(filename, 'r') as infile: csv_happy = csv.reader(infile) infile.readline() for line in csv_happy: happy_dict[line[0]] = line[2]       return happy_dict def lookup_happiness_by_country(happy_dict): return def print_sorted_dictionary(D): if type(D) != type({}): print("Dictionary not found") return print("Contents of dictionary sorted by key.") print("Key","Value") for key in sorted(D.keys()): print(key, D[key]) main() "happines.csv" Country,Year of Estimate,Happiness Index Afghanistan,2018,2.694303274 Albania,2018,5.004402637 Algeria,2018,5.043086052 Angola,2014,3.794837952 Argentina,2018,5.792796612 Armenia,2018,5.062448502 Australia,2018,7.17699337 Austria,2018,7.396001816 Azerbaijan,2018,5.167995453 Bahrain,2017,6.227320671 Bangladesh,2018,4.499217033...

  • Please help me answer theses practice questions QUESTION 2 Which of the following can a country...

    Please help me answer theses practice questions QUESTION 2 Which of the following can a country implement to protect local industries (e.g. bicycles) according to the video on the deceptive promise of free trade? Border walls local training programs to strengthen local industries protectionist policies such as tarrifs creating a high minimum wage locally governments can't do anything QUESTION 3 Which of the following European countries has a trade surpluse with the US as well as most other European countries...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT