Q1: Program Design, Function, and Purpose
- The purpose of this function is to store and provide information about famous landscapes worldwide, allowing travelers to explore and discover destinations of interest. By offering detailed descriptions, images, and travel recommendations, the function helps users gain insights into various landscapes and inspires their travel plans.
Q2
a) Algorithm Development
for field in required_fields:
if field not in data or not data[field].strip():
return jsonify({"error": f"Missing or empty field: {field}"}), 400
- This loop iterates exactly four times, corresponding to the number of required fields:
name,country,city, anddescription. - If all fields are present, the loop runs four times without returning an error.
- If a missing or empty field is found, the loop exits early with an error response.
b) Errors and Testing
-
Error Identification: If the data is empty or missing necessary fields, the code returns an error message. If the data is not in JSON format,
request.get_json()will returnNone, which will lead to a runtime error when attempting to call thestrip()method onNoneType. -
Correction: After
request.get_json(), addif not isinstance(data, dict): return jsonify({"error": "Invalid JSON format"}), 400to avoid theNoneTypeerror.
c) Data and Procedural Abstraction
def isEqual(a, b):
return a == b
def count_landscapes_by_country(country):
landscapes = Landscape.query.all() # Get all landscapes from the database
count = 0
for landscape in landscapes:
if isEqual(landscape.country, country):
count += 1
return count
# Example usage
country_name = "USA"
result = count_landscapes_by_country(country_name)
print(f"Number of landscapes in {country_name}: {result}")
- The algorithm iterates through all landscapes in the database and uses
isEqual(a, b)to check if each landscape’s country matches the given one. If a match is found, a counter is incremented. Finally, the function returns the total count. This effectively determines the number of landscapes in a specified country using list traversal and comparison.