Students Learn About
Students Learn To: • document the logic required to solve problems, including:
• develop a suitable set of test data • desk check algorithms and source code that include complex logic • select an appropriate data structure to solve a given problem Student Activity Review each Standard Algorithm and create code to implement them Sample code: #------------------------------------------------------------------------------- # Name: Writing Dictionaries to File # Purpose: # # Author: jlai # # Created: 26/02/2018 # Copyright: (c) jlai 2018 # Licence: <your licence> #------------------------------------------------------------------------------- import json from collections import OrderedDict # Use OrderedDict to maintain the order of the elements personArray = OrderedDict() def uploadFile(): ##Keep loading into Dictionary until no Person ID entered ##Note: the use of nested WHILE loops - look at use of BREAK to terminate loops while True: finish = False ## Request entry of a Person ID - must not already exist - or blank to finish ## Note: use of WHILE TRUE (infinite loop) and BREAK (to finish loop) allows ## the use of WHILE as a "Pretest" or "Post-Test" Loop while True: personId = input("Person Id") if personId == "": finish = True break else: if personId in personArray: print("Try again - person id already exists") else: person = OrderedDict() break if finish: break ## input the corresponding Person Information for the nominated Person ID personName = input("Person Name").lower().strip() personDOB = input("DOB") ## put the details into a "RECORD" - using a Python Dictionary to do this person = { 'name' : personName, 'DOB': personDOB } personArray[personId] = person ## Using JSON to save the OBJECT to FILE print(f'Create {personArray}') with open('data.json','w') as f: json.dump(personArray, f) def unloadFile(): ## Retrieve the OBJECTS from File using JSON ## - in this case I specify the OrderedDict Collection object ## This then returns the items in the correct order with open('data.json','r') as f: personArray = json.load(f, object_pairs_hook=OrderedDict) #print(personArray) ##print out elements of OrderedDict #for person in personArray: # print(person,personArray[person]) searchName = input("What name/part of name to search for?").lower().strip() for personId, person in personArray.items(): personName = person['name'] if searchName in personName: print(f"found '{searchName}' in '{personName}'") personDOB = person['DOB'] print(f'{personId} - {personName} - {personDOB}') def main(): ## ask upload a new file? if input("Upload New File? (Y/N)").upper() =="Y": uploadFile() ## process contents of file unloadFile() if __name__ == '__main__': main() |
12 SDD > Stem 3.0 Software Development Cycle > 3.2 Planning and designing software solutions (9.2.2) >

