Esempio n. 1
0
def main():
    # Task 1: Ask questions here

    for destination in Destinations().get_all():
        # Task 2+: Add comparison logic here

        # Task 1: The following code is example code, and
        #         should be deleted once you implement task 2.
        print("Name:", destination.get_name())
        print("Continent:", destination.get_continent())
        print("Kid Friendly:", destination.is_kid_friendly())
        print("Cost:", destination.get_cost())
        print("Crime:", destination.get_crime())

        print("Climate:", destination.get_climate())

        print("Season Factors:",
              destination.get_season_factor("spring"),
              destination.get_season_factor("summer"),
              destination.get_season_factor("autumn"),
              destination.get_season_factor("winter"))

        print("Scores:",
              destination.get_interest_score("sports"),
              destination.get_interest_score("wildlife"),
              destination.get_interest_score("nature"),
              destination.get_interest_score("historical"),
              destination.get_interest_score("cuisine"),
              destination.get_interest_score("adventure"),
              destination.get_interest_score("beach"))
        print("-" * 40)
        print(type(destination))
Esempio n. 2
0
    def __init__(self,
                 config=None,
                 force_net_build=False,
                 verbose=False,
                 debug=False,
                 host=None,
                 db_name=None,
                 user=None,
                 password=None):
        """Connects to the BNA database

        kwargs:
        config -- path to the config file, if not given use the default config.yaml
        force_net_build -- force a rebuild of the network even if an existing one is found
        verbose -- output useful messages
        debug -- set to debug mode
        host -- hostname or address (overrides the config file if given)
        db -- name of database on server (overrides the config file if given)
        user -- username to connect to database (overrides the config file if given)
        password -- password to connect to database (overrides the config file if given)

        return: pyBNA object
        """
        Destinations.__init__(self)
        Connectivity.__init__(self)
        Core.__init__(self)
        Conf.__init__(self)
        self.verbose = verbose
        self.debug = debug
        self.module_dir = os.path.dirname(os.path.abspath(__file__))
        if config is None:
            config = os.path.join(self.module_dir, "config.yaml")
        self.config = self.parse_config(yaml.safe_load(open(config)))
        self.config["bna"]["connectivity"]["max_detour"] = float(
            100 + self.config["bna"]["connectivity"]["max_detour"]) / 100
        self.db_connectivity_table = self.config["bna"]["connectivity"][
            "table"]
        self.net_config = self.config["bna"]["network"]

        # km/mi
        if "units" in self.config:
            if self.config.units == "mi":
                self.km = False
            elif self.config.units == "km":
                self.km = True
            else:
                raise ValueError("Invalid units \"{}\" in config".format(
                    self.config.units))
        else:
            self.km = False

        if self.verbose:
            print("")
            print("---------------pyBNA---------------")
            print("   Create and test BNA scenarios")
            print("-----------------------------------")
            print("")

        # set up db connection
        print("Connecting to database")
        if host is None:
            host = self.config["db"]["host"]
        if db_name is None:
            db_name = self.config["db"]["dbname"]
        if user is None:
            user = self.config["db"]["user"]
        if password is None:
            password = self.config["db"]["password"]
        db_connection_string = " ".join([
            "dbname=" + db_name, "user="******"host=" + host,
            "password="******"DB connection: %s" % db_connection_string)
        DBUtils.__init__(self, db_connection_string, self.verbose, self.debug)

        # srid
        if "srid" in self.config:
            self.srid = self.config["srid"]
        elif not self.debug:
            self.srid = self.get_srid(self.config.bna.blocks.table)

        # destinations
        self.destinations = dict()
        self.destination_blocks = set()
        if not self.debug:
            pass
            # self.set_destinations()

        self.sql_subs = self.make_bna_substitutions(self.config)

        if force_net_build:
            print("Building network tables in database")
            self.build_network()
        elif self.debug:
            pass
        elif not self.check_network():
            print("Network tables not found in database...building")
            self.build_network()
        elif self.verbose:
            print("Network tables found in database")
Esempio n. 3
0
def main():

    # Task 1: Ask questions here
    print("Welcome to Travel Inspiration!")
    name = input("What is your name?")
    print("Hi, ", name)

    # paste from here
    invalid = True
    continent = ""
    money = ""
    crime = ""
    chidren = ""
    season = ""
    climate = ""
    #Likes
    sports = nature = dining = historical = adventure = beach = wildlife = -6

    while continent == "":
        travel_to = input("Which continent would you like to travel to?"
                          "\n1)  Asia"
                          "\n2)  Africa"
                          "\n3)  North America"
                          "\n4)  South America"
                          "\n5)  Europe"
                          "\n6)  Oceania"
                          "\n7)  Antarctica\n")
        travel_to = int(travel_to)

        if travel_to == 1:
            continent = "asia"
        elif travel_to == 2:
            continent == "africa"
        elif travel_to == 3:
            continent == "north america"
        elif travel_to == 4:
            continent = "south america"
        elif travel_to == 5:
            continent = "europe"
        elif travel_to == 6:
            continent = "oceania"
        elif travel_to == 7:
            continent = "antarctica"
        else:
            print("Please reply with a valid option")
            continent = ""

    while money == "":
        money_to_you = input(
            "What is money to you?"
            "\n$$$)  No object"
            "\n$$)  Spendable, so long as I get value from doing so"
            "\n$)  Extremely important; I want to spend as little as possible\n"
        )

        if money_to_you == "$$$":
            money = "$$$"
        elif money_to_you == "$$":
            money = "$$"
        elif money_to_you == "$":
            money = "$"
        else:
            print("Please reply with a valid option")
            money = ""

    while crime == "":
        crime_acceptable = input(
            "How much crime is acceptable when you travel?"
            "\n1)  Low"
            "\n2)  Avarage"
            "\n3)  High\n")
        crime_acceptable = int(crime_acceptable)
        if crime_acceptable == 1:
            crime = "low"
        elif crime_acceptable == 2:
            crime == "avarage"
        elif crime_acceptable == 3:
            crime = "high"
        else:
            print("Please reply with a valid option")
            crime = ""

    while chidren == "":
        traveling_with_children = input("Will you be travelling with children?"
                                        "\n1)  Yes"
                                        "\n2)  No\n")
        traveling_with_children = int(traveling_with_children)
        if traveling_with_children == 1:
            chidren = "yes"
        elif traveling_with_children == 2:
            chidren = "no"
        else:
            print("Please reply with a valid option")
            chidren = ""

    while season == "":
        season_of_travel = input("Which season do you plan to travel in?"
                                 "\n1) Spring"
                                 "\n2) Summer"
                                 "\n3) Autumn"
                                 "\n4) Winter\n")
        season_of_travel = int(season_of_travel)

        if season_of_travel == 1:
            season = "spring"
        elif season_of_travel == 2:
            season = "summer"
        elif season_of_travel == 3:
            season = "autumn"
        elif season_of_travel == 4:
            season = "winter"
        else:
            print("Please reply with a valid option")
            season = ""
    while climate == "":
        prefered_climate = input("What climate do you prefer?"
                                 "\n1) Cold"
                                 "\n2) Cool"
                                 "\n3) Moderate"
                                 "\n4) Warm"
                                 "\n5) Hot\n")
        prefered_climate = int(prefered_climate)
        if prefered_climate == 1:
            climate = "cold"
        elif prefered_climate == 2:
            climate = "cool"
        elif prefered_climate == 3:
            climate = "moderate"
        elif prefered_climate == 4:
            climate = "warm"
        elif prefered_climate == 5:
            climate = "hot"
        else:
            print("Please reply with a valid option")
            climate = ""

    print(
        "Now we would like to ask you some questions about your interests, on a scale of -5 to 5. -5 indicates strong dislike, whereas 5 indicates strong interest, and 0 indicates indifference."
    )

    while sports == -6:
        like_sports = input("How much do you like wildlife? (-5 to 5)\n")
        like_sports = int(like_sports)
        if like_sports > -6 and like_sports < 6:
            sports = like_sports
        else:
            print("Please reply with a valid response(-5 to 5)")
            sports = -6

    while wildlife == -6:
        like_wild_life = input("How much do you like nature? (-5 to 5)\n")
        like_wild_life = int(like_wild_life)
        if like_wild_life > -6 and like_wild_life < 6:
            wildlife = like_wild_life
        else:
            print("Please reply with a valid response(-5 to 5)")
            wildlife = -6

    while nature == -6:
        like_nature = input("How much do you like nature? (-5 to 5)\n")
        like_nature = int(like_nature)
        if like_nature > -6 and like_nature < 6:
            nature = like_nature
        else:
            print("Please reply with a valid response(-5 to 5)")
            nature = -6

    while historical == -6:
        like_historical_sites = input(
            "How much do you like historical sites? (-5 to 5)\n")
        like_historical_sites = int(like_historical_sites)
        if like_historical_sites > -6 and like_historical_sites < 6:
            historical = like_historical_sites
        else:
            print("Please reply with a valid response(-5 to 5)")
            historical = -6

    while dining == -6:
        like_fine_dining = input(
            "How much do you like fine dining? (-5 to 5)\n")
        like_fine_dining = int(like_fine_dining)
        if like_fine_dining > -6 and like_fine_dining < 6:
            dining = like_fine_dining
        else:
            print("Please reply with a valid response(-5 to 5)")
            dining = -6

    while adventure == -6:
        like_adventure = input(
            "How much do you like adventure activities? (-5 to 5)\n")
        like_adventure = int(like_adventure)
        if like_adventure > -6 and like_adventure < 6:
            adventure = like_adventure
        else:
            print("Please reply with a valid response(-5 to 5)")
            adventure = -6

    while beach == -6:
        like_beach = input("How much do you like the beach? (-5 to 5)\n")
        like_beach = int(like_beach)
        if like_beach > -6 and like_beach < 6:
            beach = like_beach
        else:
            print("Please reply with a valid response(-5 to 5)")
            beach = -6

    print(
        "Thank you for answering all our questions. Your next travel destination is:"
    )

    found = False
    season_score = 0.0
    dest_name = ""
    score = ""

    print("Continent", continent)
    print("Money", money)
    print("Crime", crime)
    print("Continent", continent)
    print("Children", chidren)
    print("Season", season)
    print("Climate", climate)
    print("Wildlife", wildlife)
    print("Nature", nature)
    print("Hisorical", historical)
    print("Dining", dining)
    print("Adventure", adventure)
    print("Beach", beach)
    for destination in Destinations().get_all():
        # Task 2+: Add comparison logic here

        if destination.get_continent(
        ) == continent:  #and match_children(destination.is_kid_friendly(),"no" and cost_int(destination.get_cost())<= cost_int("$$$") and  crimeRate(destination.get_crime())<= crimeRate("high")):

            if match_children(destination.is_kid_friendly(), chidren):
                if cost_int(destination.get_cost()) <= cost_int(money):
                    if crimeRate(destination.get_crime) <= crimeRate(crime):
                        if destination.get_climate() == climate:

                            if destination.get_season_factor(
                                    season) >= season_score:
                                season_score = destination.get_season_factor(
                                    season)

                                interest_score = sports * destination.get_interest_score(
                                    "sports"
                                ) + wildlife * destination.get_interest_score(
                                    "wildlife"
                                ) + nature * destination.get_interest_score(
                                    "nature"
                                ) + historical * destination.get_interest_score(
                                    "historical"
                                ) + dining * destination.get_interest_score(
                                    "cuisine"
                                ) + adventure * destination.get_interest_score(
                                    "adventure"
                                ) + beach * destination.get_interest_score(
                                    "beach")
                                temp_score = season_score * interest_score
                                if score == "":
                                    score = int(temp_score)
                                if temp_score >= score:
                                    found = True
                                    dest_name = destination.get_name()

    if found == False:
        print("None")
    else:
        print(dest_name)
Esempio n. 4
0
def main():

    name()

    continent = continent_input()
    while continent is False:
        continent = continent_input()

    cost = cost_input()
    while cost is False:
        cost = cost_input()

    crime = crime_input()
    while crime is False:
        crime = crime_input()

    kids = kids_input()
    while kids is False:
        kids = kids_input()

    season = season_input()
    while season is False:
        season = season_input()

    climate = climate_input()
    while climate is False:
        climate = climate_input()

    print(
        "\nNow we would like to ask you some questions about your interests, on a scale "
        "of -5 to 5. -5 indicates strong dislike, whereas 5 indicates strong interest, "
        "and 0 indicates indifference.")

    while True:
        print("\nHow much do you like sports? (-5 to 5)")
        sports = input("> ")
        if sports in [
                "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"
        ]:
            sports = int(sports)
            break
        else:
            print("\nI'm sorry, but", sports,
                  "is not a valid choice. Please try again.")

    while True:
        print("\nHow much do you like wildlife? (-5 to 5)")
        wildlife = input("> ")
        if wildlife in [
                "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"
        ]:
            wildlife = int(wildlife)
            break
        else:
            print("\nI'm sorry, but", wildlife,
                  "is not a valid choice. Please try again.")

    while True:
        print("\nHow much do you like nature? (-5 to 5)")
        nature = input("> ")
        if nature in [
                "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"
        ]:
            nature = int(nature)
            break
        else:
            print("\nI'm sorry, but", nature,
                  "is not a valid choice. Please try again.")

    while True:
        print("\nHow much do you like historical sites? (-5 to 5)")
        historical = input("> ")
        if historical in [
                "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"
        ]:
            historical = int(historical)
            break
        else:
            print("\nI'm sorry, but", historical,
                  "is not a valid choice. Please try again.")

    while True:
        print("\nHow much do you like fine dining? (-5 to 5)")
        cuisine = input("> ")
        if cuisine in [
                "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"
        ]:
            cuisine = int(cuisine)
            break
        else:
            print("\nI'm sorry, but", cuisine,
                  "is not a valid choice. Please try again.")

    while True:
        print("\nHow much do you like adventure activities? (-5 to 5)")
        adventure = input("> ")
        if adventure in [
                "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"
        ]:
            adventure = int(adventure)
            break
        else:
            print("\nI'm sorry, but", adventure,
                  "is not a valid choice. Please try again.")

    while True:
        print("\nHow much do you like the beach? (-5 to 5)")
        beach = input("> ")
        if beach in [
                "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"
        ]:
            beach = int(beach)
            break
        else:
            print("\nI'm sorry, but", beach,
                  "is not a valid choice. Please try again.")

    destination_set = Destinations().get_all()

    first_exact_match_result = first_exact_match(destination_set, continent,
                                                 cost, crime, climate, kids)

    final_result = season_interest_match(first_exact_match_result, season,
                                         sports, wildlife, nature, historical,
                                         cuisine, adventure, beach)

    print(
        "\nThank you for answering all our questions. Your next travel destination is:"
    )
    if final_result is None:
        print(None)
    else:
        print(final_result.get_name())
Esempio n. 5
0
def main():
    # Task 1: Ask questions here
    
    
    print("\nWelcome to Travel Inspiration!")
    name = str(input("\nWhat is your name? ", ))
    print("\nHi,",name+"!")
    
    print("\nWhich continent would you like to travel to?")
    print("  1) Asia\n  2) Africa\n  3) North America\n  4) South America\n  5) Europe\n  6) Oceania\n  7) Antarctica")
    choice1 =  input("> ")
    if choice1 == "1" :
        continent = "asia"
    elif choice1 == "2" :
        continent = "africa"
    elif choice1 == "3" :
        continent = "north america"
    elif choice1 == "4" :
        continent = "south america"
    elif choice1 == "5" :
        continent = "europe"
    elif choice1 == "6" :
        continent = "oceania"
    elif choice1 == "7" :
        continent = "antarctica"

    print("\nWhat is money to you?")
    print("  $$$) No object\n  $$) Spendable, so long as I get value from doing so\n  $) Extremely important; "
          "I want to spend as little as possible")
    choice2 = input("> ")
    if choice2 == "$$$" :
        cost = "$$$"
    elif choice2 == "$$" :
        cost = "$$"    
    elif choice2 == "$" :
        cost = "$"
    
    print("\nHow much crime is acceptable when you travel?")
    print("  1) Low\n  2) Average\n  3) High")
    choice3 = input("> ")
    if choice3 == "1" :
        crime = "low"
    elif choice3 == "2" :
        crime = "average"
    elif choice3 == "3" :
        crime = "high"    

    
    print("\nWill you be travelling with children?")
    print("  1) Yes\n  2) No")
    choice4 = input("> ")
    if choice4 == "1" :
        kids = True
    else:
        kids = False

    
    print("\nWhich season do you plan to travel in?")
    print("  1) Spring\n  2) Summer\n  3) Autumn\n  4) Winter")
    choice5 = input("> ")
    if choice5 == "1" :
         season_fator = "spring"
    elif choice5 == "2" :
         season_fator = "summer"
    elif choice5 == "3" :
         season_fator = "autumn"
    elif choice5 == "4" :
         season_fator = "winter"   
        

    print("\nWhat climate do you prefer?")
    print("  1) Cold\n  2) Cool\n  3) Moderate\n  4) Warm\n  5) Hot")
    choice6 = input("> ")
    if choice6 == "1" :
         climate = "cold"
    elif choice6 == "2" :
         climate = "cool"
    elif choice6 == "3" :
         climate = "moderate"
    elif choice6 == "4" :
         climate = "warm"   
    elif choice6 == "5" :
         climate = "hot"


    print("\nNow we would like to ask you some questions about your interests, on a scale " \
          "of -5 to 5. -5 indicates strong dislike, whereas 5 indicates strong interest, " \
          "and 0 indicates indifference.")
    print("\nHow much do you like sports? (-5 to 5)")
    interests1 = input("> ")
    
    
    print("\nHow much do you like wildlife? (-5 to 5)")
    interests2 = input("> ")

    
    print("\nHow much do you like nature? (-5 to 5)")
    interests3 = input("> ")

    
    print("\nHow much do you like historical sites? (-5 to 5)")
    interests4 = input("> ")

    
    print("\nHow much do you like fine dining? (-5 to 5)")
    interests5 = input("> ")

    
    print("\nHow much do you like adventure activities? (-5 to 5)")
    interests6 = input("> ")

    
    print("\nHow much do you like beach? (-5 to 5)")
    interests7 = input("> ")

    
    print("\nThank you for answering all our questions. Your next travel destination is:\n")
    

    for destination in Destinations().get_all():
        # Task 2+: Add comparison logic here
       if continent == destination.get_continent() :
           if len(cost) >= len(destination.get_cost()) :
               if crime >= destination.get_crime() :
                   if kids == destination.is_kid_friendly() :
                       if season_fator == destination.get_season_factor() :
                           if climate == destination.get_climate():
                               print(destination.get_name(),sep="")          


        season_fator == destination.get_season_factor(season_fator)

        score = season_factor * interest_score
        interest_score = response_sports * score_sports
                         + response_wildlife * score_wildlife
                         + response_nature * score_nature
                         + response_historical * score_historical
                         + response_cuisine * score_cuisine
                         + response_adventure * score_adventure
                         + response_beach * score_beach
Esempio n. 6
0
def main():
    # Task 1: Ask questions here
    hasDestination = False
    print("Welcome to Travel Inspiration!\n")

    getName = input("What is your name? ")
    print("\nHi,", getName + "!\n")

    ################## The first part questions(begin) ############################

    def theFirstQuestion():
        """
        1,Return the choice from traveler
        2,obtain multiple input from traveler
        3,Judge whether the traveler input the invalid choice
        
        """

        print("Which continents would you like to travel to?")
        print(
            "  1) Asia\n  2) Africa\n  3) North America\n  4) South America\n",
            " 5) Europe\n  6) Oceania\n  7) Antarctica")

        sortMutipleInput = []
        obtainChoice = input("> ")  # obtain multiple input
        obtainChoiceAsList = []  # use for storing all inputs into the list.

        for i in obtainChoice:
            if i not in ["1", "2", "3", "4", "5", "6", "7", ",", " "]:
                return obtainChoice
                break
            else:
                obtainChoiceAsList.append(i)

        for i in obtainChoiceAsList:
            if i.isdigit():
                sortMutipleInput.append(i)

        finalMultipleChoice = list(
            set(sortMutipleInput)
        )  # eliminate repeat values and get the final multiple choices

        collections = []  # use for collecting the choice number : 1),2) ... 7)
        getChoice = []
        result = [
            "asia", "africa", "north america", "south america", "europe",
            "oceania", "antarctica"
        ]
        for i in finalMultipleChoice:
            collections.append(int(i))

        for i in collections:
            getChoice.append(result[i - 1])

        return getChoice

    def theSecondQuestion():
        """
        1,Return the choice from traveler
        2,Judge whether the traveler input the invalid choice
        
        """

        print("\nWhat is money to you?")
        print(
            "  $$$) No object\n",
            " $$) Spendable, so long as I get value from doing so\n",
            " $) Extremely important; I want to spend as little as possible")
        getChoice = input("> ")
        if getChoice == "$$$" and getChoice == "$$" and getChoice == "$":
            result = getChoice
            return result
        else:
            return getChoice

    def theThirdQuestion():
        """
        1,Return the choice from traveler
        2,Judge whether the traveler input the invalid choice
        
        """

        print("\nHow much crime is acceptable when you travel?")
        print("  1) Low\n  2) Average\n  3) High")
        getChoice = int(input("> "))
        result = ["low", "average", "high"]
        if getChoice == 1 or getChoice == 2 or getChoice == 3:
            return result[getChoice - 1]
        else:
            return getChoice

    def theForthQuestion():
        """
        1,Return the choice from traveler
        2,Judge whether the traveler input the invalid choice
        
        """

        print("\nWill you be travelling with children?")
        print("  1) Yes\n  2) No")
        getChoice = input("> ")
        if getChoice == "1":
            return True
        elif getChoice == "2":
            return False
        else:
            return getChoice

    def theFifthQuestion():
        """
        1,Return the choice from traveler
        2,obtain multiple input from traveler
        3,Judge whether the traveler input the invalid choice
        
        """

        print("\nWhich seasons do you plan to travel in?")
        print("  1) Spring\n  2) Summer\n  3) Autumn\n  4) Winter")

        sortMutipleInput = []
        obtainChoice = input("> ")  # obtain multiple input
        obtainChoiceAsList = []  # use for storing all inputs into the list.
        for i in obtainChoice:
            if i not in ["1", "2", "3", "4", ",", " "]:
                return obtainChoice
                break
            else:
                obtainChoiceAsList.append(i)

        for i in obtainChoiceAsList:
            if i.isdigit():
                sortMutipleInput.append(i)

        finalMultipleChoice = list(
            set(sortMutipleInput)
        )  # eliminate repeat values and get the final multiple choices

        collections = []  # use for collecting the choice number : 1),2)...7)
        getChoice = []
        result = ["spring", "summer", "autumn", "winter"]
        for i in finalMultipleChoice:
            collections.append(int(i))

        for i in collections:
            getChoice.append(result[i - 1])

        return getChoice

    def theSixthQuestion():
        """
        1,Return the choice from traveler
        2,Judge whether the traveler input the invalid choice
        
        """

        print("\nWhat climate do you prefer?")
        print("  1) Cold\n  2) Cool\n  3) Moderate\n  4) Warm\n  5) Hot")
        getChoice = int(input("> "))
        result = ["cold", "cool", "moderate", "warm", "hot"]
        if getChoice == 1 or getChoice == 2 or getChoice == 3 or getChoice == 4 or getChoice == 5:
            return result[getChoice - 1]
        else:
            return getChoice

################## The first part questions(end) ############################

    """
    
    1,Collect the answer from the first part questions by defining value1, value2, ... value6
    2,tell the travelers when they enter the wrong value
    
    """

    isWrongInput = True
    while isWrongInput:  #assume the input is wrong and get in the while loop
        value1 = theFirstQuestion()
        for i in value1:
            if i not in [
                    "asia", "africa", "north america", "south america",
                    "europe", "oceania", "antarctica"
            ]:
                print("\nI'm sorry, but", value1,
                      "is not a valid choice. Please try again.")
                break
            else:
                isWrongInput = False

    value3 = theSecondQuestion()
    while value3 != "$$$" and value3 != "$$" and value3 != "$":
        print("\nI'm sorry, but", value3,
              "is not a valid choice. Please try again.")
        value3 = theSecondQuestion()

    value4 = theThirdQuestion()
    while value4 != "low" and value4 != "average" and value4 != "high":
        print("\nI'm sorry, but", value4,
              "is not a valid choice. Please try again.")
        value4 = theThirdQuestion()

    value2 = theForthQuestion()
    while value2 != False and value2 != True:
        print("\nI'm sorry, but", value2,
              "is not a valid choice. Please try again.")
        value2 = theForthQuestion()

    isWrongEnter = True
    while isWrongEnter:  # assume the enter is wrong and get in the while loop
        value6 = theFifthQuestion()
        for i in value6:
            if i not in ["spring", "summer", "autumn", "winter"]:
                print("\nI'm sorry, but", value6,
                      "is not a valid choice. Please try again.")
                break
            else:
                isWrongEnter = False

    value5 = theSixthQuestion()
    while value5 != "cold" and value5 != "cool" and value5 != "moderate" and value5 != "warm" and value5 != "hot":
        print("\nI'm sorry, but", value5,
              "is not a valid choice. Please try again.")
        value5 = theSixthQuestion()

    print(
        "\nNow we would like to ask you some questions about your interests," +
        " on a scale of -5 to 5. -5 indicates strong dislike," +
        " whereas 5 indicates strong interest, and 0 indicates indifference.\n"
    )

    ################## The Second part questions(begin) ############################

    def levelOfPerference():
        """

        1, return the degree from different perference
        2, use list as the value of return
        
        """

        LevelOfPerference = []

        print("How much do you like sports? (-5 to 5)")
        getLevel1 = int(input("> "))
        LevelOfPerference.append(getLevel1)

        print("\nHow much do you like wildlife? (-5 to 5)")
        getLevel2 = int(input("> "))
        LevelOfPerference.append(getLevel2)

        print("\nHow much do you like nature? (-5 to 5)")
        getLevel3 = int(input("> "))
        LevelOfPerference.append(getLevel3)

        print("\nHow much do you like historical sites? (-5 to 5)")
        getLevel4 = int(input("> "))
        LevelOfPerference.append(getLevel4)

        print("\nHow much do you like fine dining? (-5 to 5)")
        getLevel5 = int(input("> "))
        LevelOfPerference.append(getLevel5)

        print("\nHow much do you like adventure activities? (-5 to 5)")
        getLevel6 = int(input("> "))
        LevelOfPerference.append(getLevel6)

        print("\nHow much do you like the beach? (-5 to 5)")
        getLevel7 = int(input("> "))
        LevelOfPerference.append(getLevel7)

        return LevelOfPerference


################## The Second part questions(end) ############################

    nameStore = []  # record the city name later
    scoreStore = []  # record the total score later
    """ collect the answer from the second part questions by defining answer1, answer2, ... answer7 """
    answer = levelOfPerference()
    answer1 = answer[0]
    answer2 = answer[1]
    answer3 = answer[2]
    answer4 = answer[3]
    answer5 = answer[4]
    answer6 = answer[5]
    answer7 = answer[6]

    for destination in Destinations().get_all():

        # Task 2+: Add comparison logic here
        def filter1():
            judge = False
            """

            1,judge that whether the choice is equal to the "contients" from datebase
            2,return a list of boolean value when the contients are equal or unequal to the traveler choice

            """
            for i in value1:
                judgeSingleChoice = i == destination.get_continent(
                )  # filter the boolean value when the single choice is equal to continent.
                judge = judge or judgeSingleChoice
            return judge  # return the boolean value

        def filter2():
            """

            1,judge that whether the choice is equal to the "kids" from datebase
            2,return a list of boolean value when the kid friendly is equal or unequal to the traveler choice
            3,satisfy the criteria that If the user will be travelling with children, it must be kid friend

            """

            if value2 == False:
                judge = False == destination.is_kid_friendly(
                ) or True == destination.is_kid_friendly()
            else:
                judge = False == destination.is_kid_friendly()
            return judge  # return the boolean value

        def filter3():
            """

            1,judge that whether the choice is equal to the "cost" from datebase
            2,return a list of boolean value when the anticipant cost is equal or unequal to the traveler choice
            3,satisfy the criteria that cost must be less than or equal to the user's response to the money question

            """

            if value3 == "$$$":
                judge = destination.get_cost(
                ) == "$$$" or destination.get_cost(
                ) == "$$" or destination.get_cost() == "$"
                return judge
            elif value3 == "$$":
                judge = destination.get_cost() == "$$" or destination.get_cost(
                ) == "$"
                return judge
            elif value3 == "$":
                judge = destination.get_cost() == "$"
                return judge

        def filter4():
            """

            1,judge that whether the choice is equal to the "crime" from datebase
            2,return a list of boolean value when the anticipant safety is equal or unequal to the traveler choice
            3,satisfy the criteria that crime cannot be greater than is acceptable to the user

            """

            if value4 == "high":
                judge = destination.get_crime(
                ) == "high" or destination.get_crime(
                ) == "average" or destination.get_crime() == "low"
                return judge
            elif value4 == "average":
                judge = destination.get_crime(
                ) == "average" or destination.get_crime() == "low"
                return judge
            elif value4 == "low":
                judge = destination.get_crime() == "low"
                return judge

        def filter5():
            """

            1,judge that whether the choice is equal to the "climate" from datebase
            2,return a list of boolean value when the climate perference is equal or unequal to the traveler choice

            """

            judge = value5 == destination.get_climate()
            return judge

        def calculate_sum_score():
            """

            1,use the list[] to store the sum of score
            2,return the max score

            """

            score1 = answer1 * destination.get_interest_score('sports')
            score2 = answer2 * destination.get_interest_score('wildlife')
            score3 = answer3 * destination.get_interest_score('nature')
            score4 = answer4 * destination.get_interest_score('historical')
            score5 = answer5 * destination.get_interest_score('cuisine')
            score6 = answer6 * destination.get_interest_score('adventure')
            score7 = answer7 * destination.get_interest_score('beach')
            interest_score = score1 + score2 + score3 + score4 + score5 + score6 + score7
            season_factor_score = []
            for i in value6:
                season_factor_score.append(destination.get_season_factor(
                    i))  # store the season factor in the list

            total_score = []
            for i in season_factor_score:
                total_score.append(
                    i * interest_score)  # store the total score in the list

            return max(total_score)  # return the max score in the list

        if filter1() and filter2() and filter3() and filter4() and filter5():
            hasDestination = True
            nameStore.append(destination.get_name())

            scoreStore.append(calculate_sum_score())
    """ obtain the max score and city name in the scoreStore and nameStore """
    if hasDestination == True:
        the_max_score = scoreStore[0]
        the_max_score_name = nameStore[0]
        counter = 1
        while counter < len(nameStore):
            if the_max_score < scoreStore[counter]:
                the_max_score = scoreStore[counter]
                the_max_score_name = nameStore[counter]

            counter += 1

    # Task 2+: Output final answer here
    if hasDestination == True:
        print(
            "\nThank you for answering all our questions. Your next travel destination is:\n"
            + the_max_score_name)
    else:
        print(
            "\nThank you for answering all our questions. Your next travel destination is:",
            "None")
Esempio n. 7
0
def main():
    # Task 1: Ask questions here

    continent = ""
    cost = ""
    crime = ""
    is_kid_friendly = True

    climate = ""

    season_selected = ""

    arrayM = []
    array_cost = []
    array_crime = []
    array_kids = []
    array_climate = []
    array_season_score = []

    name = input("What is your name? ")
    print("Hello", name + "! ")
    # print("Which continent would you like to travel to?")
    print("  1) Asia")
    print("  2) Africa")
    print("  3) North America")
    print("  4) South America")
    print("  5) Europe")
    print("  6) Oceania")
    print("  7) Antarctica")

    print("> ")



    #-----------------------------------------------------------------


    print('Which continent would you like to travel to?:')

    choice = str(input())

    print(choice)

    if choice == '1':
        continent = "asia"
        print('choice1:' + choice)
        print('continent====:' + continent)
    elif choice == "2":
        continent = "africa"
    elif choice == "3":
        continent = "north america"
    elif choice == "4":
        continent = "south america"
    elif choice == "5":
        continent = "europe"
    elif choice == "6":
        continent = "oceania"
    elif choice == "7":
        continent = "antarctica"
    else:
        print('invailid')

    for destination in Destinations().get_all():
        if continent == destination.get_continent():
            arrayM.append(destination)

    # -----------------------------------------------------------------



    print("What is money to you?")
    print("  1) No object")
    print("  2) Spendable, so long as I get value from doing so")
    print("  3) Extremely important; I want to spend as little as possible")


    choice = str(input(""))

    if choice == '1':
        cost = "$"
    elif choice == "2":
        cost = "$$"
        print('cost2-2-2-2-2====:' + cost)
    elif choice == "3":
        cost = "$$$"
    else:
        print('invailid')

    for destination in arrayM:
        # print("destination=========:" + destination.get_name())
        if cost == "$":
            if destination.get_cost() == "$":
                array_cost.append(destination)
                print('cost$:-=-=-=-===---==--== ' + str(destination.get_name()))
        elif cost == "$$":
            print('cost2$$:-=-=-=-===---==--== ' + str(destination.get_cost()))
            if (destination.get_cost() == "$") or (destination.get_cost() == "$$"):
                array_cost.append(destination)
                print('cost$$:-=-=-=-===---==--== ' + str(destination.get_name()))
        elif cost == "$$$":
            if (destination.get_cost() == "$") or (destination.get_cost() == "$$") or (destination.get_cost() == "$$$"):
                array_cost.append(destination)
                print('cost$$$:-=-=-=-===---==--== ' + str(destination.get_name()))
        else:
            print('invailid')


#----------------------------------------------------------------------

    print("How much crime is acceptable when you travel?")
    print("1) low")
    print("2) average")
    print("3) high")

    choice = str(input(""))

    if choice == '1':
        crime = "low"
    elif choice == "2":
        crime = "average"
        print('cost2-2-2-2-2====:' + cost)
    elif choice == "3":
        crime = "high"
    else:
        print('invailid')


    for destination in array_cost:
        # print("destination=========:" + destination.get_name())
        if cost == "$":
            if destination.get_crime() == "low":
                array_crime.append(destination)
                print('crime$:-=-=-=-===---==--== ' + str(destination.get_name()))
        elif cost == "$$":
            print('cost2$$:-=-=-=-===---==--== ' + str(destination.get_cost()))
            if (destination.get_crime() == "low") or (destination.get_crime() == "average"):
                array_crime.append(destination)
                print('crime$$:-=-=-=-===---==--== ' + str(destination.get_name()))
        elif cost == "$$$":
            if (destination.get_crime() == "low") or (destination.get_crime() == "average") or (destination.get_crime() == "high"):
                array_crime.append(destination)
                print('crime$$$:-=-=-=-===---==--== ' + str(destination.get_name()))
        else:
            print('invailid')


#-----------------------------------------------------------------

    print("Will you be travelling with children?")
    print("  1) Yes")
    print("  2) No")
    choice = str(input(""))


    if choice == '1':
        is_kid_friendly = True
        print('is_kid_friendly--==-=-=-=:-=-=-=-===---==--== ' + str(is_kid_friendly))
    elif choice == "2":
        is_kid_friendly = False
    else:
        print('invailid')


    for destination in array_crime:
        if destination.is_kid_friendly() == is_kid_friendly:
            array_kids.append(destination)
            print('Result ======== :-=-=-=-===---==--== ' + str(destination.get_name()))



#----------------------------------------------------------------

    print("What climate do you prefer?")
    print(" 1) cold")
    print(" 2) cool")
    print(" 3) moderate")
    print(" 4) warm")
    print(" 5) hot")
    choice = str(input(""))

    if choice == '1':
        climate = "cold"
    elif choice == "2":
        climate = "cool"
    elif choice == "3":
        climate = "moderate"
    elif choice == "4":
        climate = "warm"
    elif choice == "5":
        climate = "hot"
    else:
        print('invailid climate')


    for destination in array_kids:

        # print('climate====9999999:' + destination.get_climate())

        # print('array_climate.count====99999991111:' + array_climate.count())

        if destination.get_climate() == climate:

            array_climate.append(destination)
            print('Result66666666 ======== :-=-=-=-===---==--== ' + str(destination.get_name()))

    if len(array_climate) == 0:
        print('None Climate')
        return;










    #------------------------------------------------

    print("Which season do you plan to travel in?")
    print(" 1) spring")
    print(" 2) summer")
    print(" 3) autumn")
    print(" 4) winter")
    choice = str(input(""))

    if choice == '1':
        season_selected = "spring"
    elif choice == "2":
        season_selected = "summer"
    elif choice == "3":
        season_selected = "autumn"
    elif choice == "4":
        season_selected = "winter"
    else:
        print('invailid season')


    for destination in array_climate:
        print('season_selected9999====:' + season_selected)
        array_season_score.append((float(destination.get_season_factor(season_selected))))


    if len(array_season_score) == 0:
        print('None season')
        return;
    else:
        print('season')
def main():
    """Determine a possible destination for a user based on their interests."""
    print("Welcome to Travel Inspiration!\n")
    name = input("What is your name? ")
    print(f"\nHi, {name}!\n")

    # Task 1: Questions & Inputs
    # Prompts the user for their travel preferences and interests.
    responses = {}
    interests = {}

    # Decides how to get the input from the user
    for key, (question, options), type_ in QUESTIONS:
        if type_ == "numeric":
            responses[key] = input_numeric_options(question, options)
        elif type_ == "multiple_numeric":
            responses[key] = input_multiple_numeric_options(question, options)
        elif type_ == "string":
            responses[key] = input_str_options(question, options)
        else:
            raise ValueError(f"Unknown question type: {type_}")
        print()

    print(
        "Now we would like to ask you some questions about your interests, on "
        "a scale of -5 to 5. -5 indicates strong dislike, whereas 5 indicates "
        "strong interest, and 0 indicates indifference.\n")

    for key, label in INTEREST_INPUT:
        interests[key] = input_interest_question(label)
        print()

    # Selects the best matching destination based on the user's preferences.
    match = None  # Signal that no match has been found yet.

    # Tasks 2-6:
    for destination in Destinations().get_all():
        # If destination's continent, crime level, cost, kid friendliness, climate
        # does not match the user's preferences, will skip to the next destination.
        if destination.get_continent().title() not in responses['continent']:
            continue

        if (CRIME_INPUT[1].index(destination.get_crime().title()) >
                CRIME_INPUT[1].index(responses['crime'])):
            continue

        if len(destination.get_cost()) > len(responses['cost']):
            continue

        if responses['kids'] == "Yes" and not destination.is_kid_friendly():
            continue

        # Task 3: Climate & Season Factor
        if responses['climate'].lower() != destination.get_climate():
            continue

        if match is None:
            match = destination
        else:
            # Task 6:
            # Based on the season factor, which season has the highest score.
            prev_score = max(
                match.get_season_factor(season.lower())
                for season in responses['season'])
            score = max(
                destination.get_season_factor(season.lower())
                for season in responses['season'])

            # Task 4: Interests
            prev_interest_score = sum(response * match.get_interest_score(key)
                                      for key, response in interests.items())
            interest_score = sum(response * destination.get_interest_score(key)
                                 for key, response in interests.items())

            prev_score *= prev_interest_score
            score *= interest_score

            if score > prev_score:
                match = destination

    print("Thank you for answering all our questions.",
          "Your next travel destination is:")
    if match is None:
        print(match)
    else:
        print(match.get_name())
Esempio n. 9
0
def main():
    """ Logic for Travel program. The user will be asked a number of questions
    and an exact match (or None) will be returned based on parameters.

    Variables:
        final_match (bool): Exact match based on parameters. Start as FALSE.
        greatest_score (int): Value start at -200 (min score for any destination)
        user_xxx (misc): User input for each question. 
        interest_score (int): Sum of all interest scores for destination.
        season_factor (float): Season factor of destination based on user input.
        destination_score (float): Total score is interest score * season factor.

    Return:
        Destination name:  if match for continent, kid friendly, cost, crime and
        climate. The destination will have the greatest destination score.
        OR "None" if no match.
    """

    #INTRODUCTION - Welcome and name
    print("Welcome to Travel Inspiration!\n")
    user_name = input("What is your name? ")
    print("\nHi, ", user_name, "!\n", sep="")

    #TRAVEL PREFERENCE INPUTS - Continent, Money, Children, Season, Climate
    user_continent = int(
        get_user_preference(
            "Which continent would you like to travel to?\n"
            "  1) Asia\n  2) Africa\n  3) North America\n  4) South America\n  5) Europe\n"
            "  6) Oceania\n  7) Antarctica",
            ["1", "2", "3", "4", "5", "6", "7"]))
    user_cost = get_user_preference(
        "What is money to you?\n"
        "  $$$) No object\n  $$) Spendable, so long as I get value from doing so\n"
        "  $) Extremely important; I want to spend as little as possible",
        ["$$$", "$$", "$"])
    user_crime = int(
        get_user_preference(
            "How much crime is acceptable when you travel?\n"
            "  1) Low\n  2) Average\n  3) High", ["1", "2", "3"]))
    user_children = int(
        get_user_preference(
            "Will you be travelling with children?\n"
            "  1) Yes\n  2) No", ["1", "2"]))
    user_season = float(
        get_user_preference(
            "Which season do you plan to travel in?\n"
            "  1) Spring\n  2) Summer\n  3) Autumn\n  4) Winter",
            ["1", "2", "3", "4"]))
    user_climate = int(
        get_user_preference(
            "What climate do you prefer?\n"
            "  1) Cold\n  2) Cool\n  3) Moderate\n  4) Warm\n  5) Hot",
            ["1", "2", "3", "4", "5"]))

    # INTEREST INPUTS - Sports, wildlife, nature, historical, cuisine, adventure, beach
    print(
        "Now we would like to ask you some questions about your interests,"
        " on a scale of -5 to 5. -5 indicates strong dislike, whereas 5 indicates"
        " strong interest, and 0 indicates indifference.\n")
    destination_interests = [
        "sports", "wildlife", "nature", "historical sites", "fine dining",
        "adventure activities", "the beach"
    ]
    user_interests = []
    get_user_interest(destination_interests, user_interests)

    # CHECK PARAMETERS
    greatest_score = -200  # Any matching destination will have a higher score.
    final_match = False  # Set default to false

    for destination in Destinations().get_all():
        # For each destination run through parameters based on user inputs.
        if match_continent(user_continent, destination.get_continent()):
            if match_children(user_children, destination.is_kid_friendly()):
                if match_cost(user_cost, destination.get_cost()):
                    if match_crime(user_crime, destination.get_crime()):
                        if match_climate(user_climate,
                                         destination.get_climate()):
                            # All the user inputs match the current destination.
                            # At least one final match will be returned.
                            # Now calculate destination score.
                            # Determine season factor and interest score.
                            season_factor = destination.get_season_factor(
                                match_season(user_season))
                            interest_score = match_interest(
                                user_interests, destination)
                            destination_score = interest_score * season_factor

                            # Name and greatest destination score will be stored.
                            if destination_score > greatest_score:
                                greatest_score = destination_score
                                final_match_name = destination.get_name()
                                final_match = True

    #FINAL OUTPUT:
    print(
        "Thank you for answering all our questions."
        " Your next travel destination is:",
        sep="\n")
    if final_match == True:
        print(final_match_name)
    else:
        print("None")
Esempio n. 10
0
def main():
    user_reqs = {}
    user_interests = {}
    current_match = None

    # Task 1: Ask questions here

    # Start the User Requirements Questionnaire
    print('Welcome to Travel Inspiration!\n')
    username = input('What is your name? ')
    print('\nHi, ', username, '!', sep='')

    # User Requirements Questionnaire categories, questions and answer options
    reqs = {
        'continents': [
            'Which continents would you like to travel to?',
            [
                '  1) Asia', '  2) Africa', '  3) North America',
                '  4) South America', '  5) Europe', '  6) Oceania',
                '  7) Antarctica'
            ]
        ],
        'money': [
            'What is money to you?',
            [
                '  $$$) No object',
                '  $$) Spendable, so long as I get value from doing so',
                '  $) Extremely important; I want to spend as little as'
                ' possible'
            ]
        ],
        'crime': [
            'How much crime is acceptable when you travel?',
            ['  1) Low', '  2) Average', '  3) High']
        ],
        'kids':
        ['Will you be travelling with children?', ['  1) Yes', '  2) No']],
        'seasons': [
            'Which seasons do you plan to travel in?',
            ['  1) Spring', '  2) Summer', '  3) Autumn', '  4) Winter']
        ],
        'climate': [
            'What climate do you prefer?',
            [
                '  1) Cold', '  2) Cool', '  3) Moderate', '  4) Warm',
                '  5) Hot'
            ]
        ]
    }

    # Ask requirements questions and add answers to the user_reqs dictionary
    for category in reqs:
        is_money = category == 'money'
        is_multi = category in ['continents', 'seasons']
        user_reqs[category] = reqs_q(reqs[category][0], reqs[category][1],
                                     is_money, is_multi)

    # Start the User Interests Questionnaire
    print('\nNow we would like to ask you some questions about your interests,'
          ' on a scale of -5 to 5. -5 indicates strong dislike, whereas 5'
          ' indicates strong interest, and 0 indicates indifference.')

    # User Interests Questionnaire, categories and question wording
    interests = {
        'sports': 'sports',
        'wildlife': 'wildlife',
        'nature': 'nature',
        'historical': 'historical sites',
        'cuisine': 'fine dining',
        'adventure': 'adventure activities',
        'beach': 'the beach'
    }

    # Ask interest questions and add answers to the user_interests dictionary
    for interest in interests:
        user_interests[interest] = interest_q(interests[interest])

    for destination in Destinations().get_all():

        # Task 2+: Add comparison logic here
        if not find_match(user_reqs, destination):  # There is no match
            continue

        else:
            potential_match = destination  # Store the new match to compare

        if current_match is None:  # Nothing to compare yet so save as current
            current_match = destination

        else:
            # check score of potential against current match, keep best
            current_season_factors = []
            potential_season_factors = []
            for user_season in user_reqs['seasons']:
                current_season_factors.append\
                    (current_match.get_season_factor(SEASONS[user_season]))
                potential_season_factors.append\
                    (potential_match.get_season_factor(SEASONS[user_season]))
            # Max gets highest season score and multiplies with interest score
            if max(current_season_factors) * \
                    interest_score(user_interests, current_match) < \
                    max(potential_season_factors) * \
                    interest_score(user_interests, potential_match):
                current_match = potential_match

    # Task 2+: Output final answer here

    print('\nThank you for answering all our questions. Your next travel'
          ' destination is:')

    if current_match is None:
        print(current_match)
    else:
        print(current_match.get_name())
Esempio n. 11
0
def main():
    """

    :return:
    """
    ask_username()

    continent = ask_continent()
    cost = ask_money()
    crime = ask_crime()
    kidfriendly = ask_kidfriendly()
    season = ask_season()
    climate = ask_climate()

    interests()

    sports = float(ask_interests_sports())
    wildlife = float(ask_interests_wildlife())
    nature = float(ask_interests_nature())
    historical = float(ask_interests_historical())
    cuisine = float(ask_interests_cuisine())
    adventure = float(ask_interests_adventure())
    beach = float(ask_interests_beach())

    # Get original data from .csv file

    new_destination = []

    final_destination = {}

    # select destinations in the selected continent

    for select_continent in Destinations().get_all():
        if select_continent.get_continent() == continent:
            new_destination.append(select_continent)

    # select destinations match the user cost

    for money_select in new_destination:

        if len(money_select.get_cost()) <= len(cost):
            continue
        else:
            new_destination.remove(money_select)
    # select destinations with selected crime rate

    for crime_select in new_destination:
        if crime == "high":
            continue
        elif crime == "low" and crime_select.get_crime() != "low":
            new_destination.remove(crime_select)
        elif crime == "average" and crime_select.get_crime() == "high":
            new_destination.remove(crime_select)

    for kid_select in new_destination:
        if kidfriendly == "TRUE" and kid_select.is_kid_friendly() == "FALSE":
            new_destination.remove(kid_select)

    # select destinations with certain climate

    for climate_select in new_destination:
        if climate_select.get_climate() != climate:
            new_destination.remove(climate_select)

    highest_score = -9999
    highest_score_destination = None

    for destination in new_destination:

        _sports = sports * float(destination.get_interest_score('sports'))
        _wildlife = wildlife * float(
            destination.get_interest_score('wildlife'))
        _nature = nature * float(destination.get_interest_score('nature'))
        _historical = historical * float(
            destination.get_interest_score('historical'))
        _cuisine = cuisine * float(destination.get_interest_score('cuisine'))
        _adventure = adventure * float(
            destination.get_interest_score('adventure'))
        _beach = beach * float(destination.get_interest_score('beach'))

        interest_score = _sports + _wildlife + _nature + _historical + _cuisine + _adventure + _beach

        score = destination.get_season_factor(season) * interest_score

        if score > highest_score:
            highest_score = score
            highest_score_destination = destination.get_name()

    print(
        "Thank you for answering all our questions. Your next travel destination is:"
    )
    print(highest_score_destination)
Esempio n. 12
0
def main():
    # Task 1: Ask questions here

    # Welcome Information
    print("Welcome to Travel Inspiration!\n")

    # Prompt the user to input the name
    user_name = input("What is your name? ")
    print("\nHi,", user_name + "!\n")

    # Get the user's preferred continents
    continent = input("Which continents would you like to travel to?" +
                      "\n  1) Asia" + "\n  2) Africa" +
                      "\n  3) North America" + "\n  4) South America" +
                      "\n  5) Europe" + "\n  6) Oceania" +
                      "\n  7) Antarctica" + "\n> ")
    continent_list = [
        "", "asia", "africa", "north america", "south america", "europe",
        "oceania", "antarctica"
    ]
    valid_continent_input = continent_validation(continent)
    continent_input_list = valid_continent_input.split(",")

    # Get the user's response to travel cost
    money = input(
        "\nWhat is money to you?" + "\n  $$$) No object" +
        "\n  $$) Spendable, so long as I get value from doing so" +
        "\n  $) Extremely important; I want to spend as little as possible" +
        "\n> ")
    valid_cost_input = cost_validation(money)

    # Get the user's attitude towards crime issues
    crime = input("\nHow much crime is acceptable when you travel?" +
                  "\n  1) Low" + "\n  2) Average" + "\n  3) High" + "\n> ")
    crime_list = ["", "low", "average", "high"]
    valid_crime_input = crime_validation(crime)

    # Determine if the user will go travelling with children
    children = input("\nWill you be travelling with children?" + "\n  1) Yes" +
                     "\n  2) No" + "\n> ")
    valid_kid_friendly_input = kid_friendly_validation(children)
    if valid_kid_friendly_input == "1":
        chi = True
    elif valid_kid_friendly_input == "2":
        chi = False

    # Get the user's attitude towards different seasons
    season = input("\nWhich seasons do you plan to travel in?" +
                   "\n  1) Spring" + "\n  2) Summer" + "\n  3) Autumn" +
                   "\n  4) Winter" + "\n> ")

    valid_season_input = season_validation(season)
    season_input_list = valid_season_input.split(",")
    season_list = ["", "spring", "summer", "autumn", "winter"]

    # Get the user's attitude towards different climates
    climate = input("\nWhat climate do you prefer?" + "\n  1) Cold" +
                    "\n  2) Cool" + "\n  3) Moderate" + "\n  4) Warm" +
                    "\n  5) Hot" + "\n> ")
    valid_climate_input = climate_validation(climate)
    if valid_climate_input == "1":
        cli = "cold"
    elif valid_climate_input == "2":
        cli = "cool"
    elif valid_climate_input == "3":
        cli = "moderate"
    elif valid_climate_input == "4":
        cli = "warm"
    elif valid_climate_input == "5":
        cli = "hot"

    # Introduction of the interst questionnair
    print(
        "\nNow we would like to ask you some questions about your interests, on a scale of -5 to 5. -5 indicates strong dislike, whereas 5 indicates strong interest, and 0 indicates indifference."
    )

    # Get user's interest score
    sports = input("\nHow much do you like sports? (-5 to 5)" + "\n> ")
    valid_sports_input = sports_validation(sports)
    wildlife = input("\nHow much do you like wildlife? (-5 to 5)" + "\n> ")
    valid_wildlife_input = wildlife_validation(wildlife)
    nature = input("\nHow much do you like nature? (-5 to 5)" + "\n> ")
    valid_nature_input = nature_validation(nature)
    historical_sites = input(
        "\nHow much do you like historical sites? (-5 to 5)" + "\n> ")
    valid_historical_site_input = historical_site_validation(historical_sites)
    fine_dining = input("\nHow much do you like fine dining? (-5 to 5)" +
                        "\n> ")
    valid_fine_dining_input = fine_dining_validation(fine_dining)
    adventure_activities = input(
        "\nHow much do you like adventure activities? (-5 to 5)" + "\n> ")
    valid_adventure_activity_input = adventure_activity_validation(
        adventure_activities)
    beach = input("\nHow much do you like the beach? (-5 to 5)" + "\n> ")
    valid_beach_input = beach_validation(beach)

    # Ending statement
    print(
        "\nThank you for answering all our questions. Your next travel destination is:"
    )

    # Some variables which are going to be used in the comparison later
    largest = -999999
    destination_name = ""
    destination_list = []

    for destination in Destinations().get_all():
        # Task 2+: Add comparison logic here
        for continents in continent_input_list:
            int_continents = int(continents)
            temp_continents = continent_list[int_continents]
            for seasons in season_input_list:
                int_seasons = int(seasons)
                temp_seasons = season_list[int_seasons]
                # Decide the continent, cost, crime, kid-friendly and climate factor
                if temp_continents == destination.get_continent() and\
                    valid_cost_input >= destination.get_cost() and\
                    int(valid_crime_input) >= crime_list.index(destination.get_crime()) and\
                    chi <= bool(destination.is_kid_friendly()) and \
                    cli == destination.get_climate() :
                    # Calculate the total score
                    interest_score = int(valid_sports_input) * destination.get_interest_score("sports") \
                        + int(valid_wildlife_input) * destination.get_interest_score("wildlife") \
                        + int(valid_nature_input) * destination.get_interest_score("nature") \
                        + int(valid_historical_site_input) * destination.get_interest_score("historical") \
                        + int(valid_fine_dining_input) * destination.get_interest_score("cuisine") \
                        + int(valid_adventure_activity_input) * destination.get_interest_score("adventure") \
                        + int(valid_beach_input) * destination.get_interest_score("beach")
                    score = destination.get_season_factor(
                        temp_seasons) * interest_score
                    # compare the score and decide the final destination
                    if score > largest:
                        largest = score
                        destination_name = destination.get_name()
                        destination_list.append(destination_name)

    # Task 2+: Output final answer here
    if destination_list != []:
        print(destination_name)
    else:
        print("None")
from string import punctuation

from destinations import Destinations
from testrunner import OrderedTestCase, TestMaster, RedirectStdIO, skipIfFailed

# So we don't remove $ from output
punctuation = punctuation.replace('$', '')

TEST_DATA = Path('test_data') / 'marking'

# Compile regex expression "dest_1|dest_2|dest_3|dest_n"
# Reverse order because some destinations have names that are part other other
# destinations. Search in reverse to match the longer destination name first.
DESTINATIONS_PATTERN = re.compile('|'.join(
    sorted((fr'{re.escape(d.get_name())}'
            for d in Destinations('destinations_long.csv').get_all()),
           reverse=True) + ['None']),
                                  flags=re.MULTILINE | re.IGNORECASE)
NEWLINES_PATTERN = re.compile(r'\n+')
SPACES_PATTERN = re.compile(r'[^\S\n]{2,}')


class TestDesign(OrderedTestCase):
    def setUp(self):
        if self.a1 is None:
            raise RuntimeError('Failed to import travel.py')

    def test_main_defined(self):
        """ test a main function has been defined """
        self.assertFunctionDefined(self.a1, 'main', 0)