#! /usr/bin/env python3 # def json_test ( ): #*****************************************************************************80 # ## json_test() makes some simple tests involving JSON files. # print ( '' ) print ( 'json_test():' ) print ( ' Some simple tests involving JSON files.' ) collatz_json_test ( ) image_json_test ( ) print ( '' ) print ( 'json_test():' ) print ( ' Normal end of execution.' ) return def collatz_json_test ( ): #*****************************************************************************80 # ## collatz_json_test() reads a collatz dict from a JSON file and updates it. # import json print ( '' ) print ( 'collatz_json_test ( ):' ) print ( ' Read the collatz dict from a JSON file.' ) print ( ' Verify that it has information in it already.' ) print ( ' Add some more.' ) # # Read the json file. # filename = 'collatz_dict.json' input = open ( filename, 'r' ) collatz_dict = json.load ( input ) input.close ( ) print ( '' ) print ( ' After retrieval from json file "' + filename + '", collatz_dict' ) print ( ' has "length" (number of entries) = ', len ( collatz_dict ) ) # # Now add data for n = 100 # n = 100 collatz_add_to_dict ( collatz_dict, n ) print ( '' ) print ( ' After adding data for n = ', n, 'the Collatz dict' ) print ( ' has "length" (number of entries) = ', len ( collatz_dict ) ) return def image_json_test ( ): #*****************************************************************************80 # ## image_json_test() reads a little information from a JSON file. # import json print ( '' ) print ( 'image_json_test ( ):' ) print ( ' Read some information from a JSON file.' ) filename = 'cake.json' input = open ( filename, 'r' ) my_image = json.load ( input ) id = my_image["id"] print ( ' Cake image id = ', id ) image = my_image["image"] url = image["url"] print ( ' Cake image url = "' + url + '"' ) input.close ( ) return def collatz_add_to_dict ( collatz_dict, n ): #*****************************************************************************80 # ## collatz_add_to_dict() adds information to a Collatz dict. # while ( not ( n in collatz_dict ) ): n2 = collatz ( n ) collatz_dict[n] = n2 n = n2 return def collatz ( n ): #*****************************************************************************80 # ## collatz() applies one step of the Collatz iteration to an integer. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 11 June 2022 # # Author: # # John Burkardt # # Input: # # integer n: the starting value. # # Output: # # integer n2: the transformed value. # if ( not isinstance ( n, int ) ): raise Exception ( 'collatz: type(n) = ', type ( n ), \ ', but n must be an integer.' ) elif ( n < 1 ): raise Exception ( 'collatz: n =', n, ', but 1 <= n required.' ) elif ( n == 1 ): n2 = 1 elif ( ( n % 2 ) == 0 ): n2 = n // 2 else: n2 = 3 * n + 1 return n2 if ( __name__ == '__main__' ): json_test ( )