Python代写:COMP20003 Python Libraries

完成使用Python库函数的五个基础练习题。

Python

Using Python libraries: Math & Random

Write a program that uses different Python libraries in different subroutines:

  1. Calculate the area of a circle with the math library. The program asks the user for the radius of the circle and then calculates the surface area of the circle. Use the pi value (pi) found in the math library and the power calculation function pow. Finally, print the area rounded to 2 decimals.
  2. Guessing a random number with the random library. The program selects a random number between 0-1000 with the randint function of the random library. After that, the program asks the user for a guess and tells whether the searched number is larger or smaller until the user guesses the number correctly. When the user guesses the number, the program also informs how many tries the user needed to find the correct number
    You should use pseudo-random numbers. To make testing the program possible, set the seed number before the number is drawn with the random.seed(1) command.

See the example run below for more detailed operation of the program.

Example run:

This program uses libraries to solve tasks.
What do you want to do:
1) Calculate the area of the circle
2) Guess the number
0) Stop
Your choice:
1
Enter the radius of the circle as an integer:
7
With a radius of 7, the area of the circle is 153.94.
What do you want to do:
1) Calculate the area of the circle
2) Guess the number
0) Stop
Your choice:
2
Guess the integer drawn by the program.
Enter an integer between 0 and 1000:
500
The requested number is lower.
Enter an integer between 0 and 1000:
250
The requested number is lower.
Enter an integer between 0 and 1000:
125
The requested number is higher.
Enter an integer between 0 and 1000:
187
The requested number is lower.
Enter an integer between 0 and 1000:
140
The requested number is lower.
Enter an integer between 0 and 1000:
132
The requested number is higher.
Enter an integer between 0 and 1000:
137
Correct! You used 7 tries to guess the correct integer..
What do you want to do:
1) Calculate the area of the circle
2) Guess the number
0) Stop
Your choice:
0

Creating & Using your own library

Write a Python program that converts temperatures between Fahrenheit, Kelvin and Celsius temperature scales. For example, 0 degrees Celcius is 273.15 degrees in Kelvin. There are simple formulas for all these conversions (see e.g., Wikipedia).

Program each temperature conversion into its own subroutine, which receives the temperature to be converted as a parameter and returns a floating-point result as a return value. Put these conversion functions in your own file as a subprogram library and add the library’s version number as a fixed value, now 1.0.

Make another file that contains the main program. In this task, it is the menu and the associated selection structure, as shown in the example run below. The user starts by selecting the desired conversion and gives the temperature to be converted as an integer. After this, the main program calls a library function to perform this conversion and prints the result on the screen rounded to two decimals.

With libraries, it is essential that the interface and functionality are understood correctly. In this program each function receives an integer as a parameter and returns a floating-point number after conversion without rounding it. Since it is a temperature conversion library, the library only contains conversion functions and a number telling the version of the library (fixed value). In this task, the main program and the menu form the user interface of the program and are therefore in another file.

In this task, the name of the file containing the library needs to be L08T2Library.py and the file containing the main program is main.py. Submit them both to CodeGrade submission box and only after you have uploaded them both, click “Submit”.

Example run:

Using version 1.0 of the temperature conversion library.
What temperature conversion do you want to do?
1) Celsius->Fahrenheit
2) Celsius->Kelvin
3) Fahrenheit->Kelvin
4) Fahrenheit->Celsius
5) Kelvin->Celsius
6) Kelvin->Fahrenheit
0) Stop
Your choice:
1
Enter the starting temperature:
-20
Temperature in degrees Fahrenheit: -4.0
What temperature conversion do you want to do?
1) Celsius->Fahrenheit
2) Celsius->Kelvin
3) Fahrenheit->Kelvin
4) Fahrenheit->Celsius
5) Kelvin->Celsius
6) Kelvin->Fahrenheit
0) Stop
Your choice:
5
Enter the starting temperature:
100
Temperature in degrees Celsius: -173.15
What temperature conversion do you want to do?
1) Celsius->Fahrenheit
2) Celsius->Kelvin
3) Fahrenheit->Kelvin
4) Fahrenheit->Celsius
5) Kelvin->Celsius
6) Kelvin->Fahrenheit
0) Stop
Your choice:
0

Using Python libraries, datetime

We will continue practicing the use of datetime library. The program is menu-based, see the example runs below. The selected operation should call a function doing the required task.

The tasks are the following:

Instance variables of the datetime object. The program asks the user for the date and time as a string in the format dd.mm.yyyy hh:mm and converts the string into a datetime object. From this object, it is easy to use instance variables: date, month, year, hour, minute to print them to the screen according to the example run.

Calculation of the length of the period. The program asks the user for date of birth in the format dd.mm.yyyy and calculates how old he/she was on the beginning of this year, that is, on January 1, 2022, and prints the answer in days. By using timedelta objects you can deal with periods of time.

Printing the names of the days of the week. With the strftime function, you can print the information contained in the datetime object in a versatile way. Use this function to print the names of the days of the week on the screen.

  1. Start by creating a datetime object using Monday’s date (any Monday’s date will do).
  2. After that, go through all the days of one week with the repeat structure and move to the next day by using timedelta. Please note that the language settings in the computer settings may affect the language of the printout, but in CodeGrade the days of the week are printed in English with the strftime function.

Printing the names of the months of one year as abbreviations. The task is to print the names of the 12 months correctly. Note that the transition must always fall on the next month, but not necessarily on the same day. The names of the months should be printed as abbreviations.

See the example run below for more detailed operation of the program and the programming manual describes the most important functions of the datetime module. Implement each of the above functions as its own subroutine, typically less than 10 lines per subroutine.

Example run:

This program uses the datetime library to deal with time.
What do you want to do:
1) Identify the components of a time object
2) Calculate age in days
3) Print the days of the week
4) Print the months
0) Stop
Your choice:
1
Enter the date and time in the format 'dd.mm.yyyy hh:mm':
24.12.2021 18:45
You gave year 2021
You gave month 12
You gave day 24
You gave hour 18
You gave minute 45
What do you want to do:
1) Identify the components of a time object
2) Calculate age in days
3) Print the days of the week
4) Print the months
0) Stop
Your choice:
2
Enter your birthday as dd.mm.yyyy:
07.07.1977
On January 1, 2022, you were 16249 days old.
What do you want to do:
1) Identify the components of a time object
2) Calculate age in days
3) Print the days of the week
4) Print the months
0) Stop
Your choice:
3
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
What do you want to do:
1) Identify the components of a time object
2) Calculate age in days
3) Print the days of the week
4) Print the months
0) Stop
Your choice:
4
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
What do you want to do:
1) Identify the components of a time object
2) Calculate age in days
3) Print the days of the week
4) Print the months
0) Stop
Your choice:
0

Python module fraction

This exercise deals with fraction package. The task is to demonstrate how mathematical operations work on fractions. Write a program that ask the numerator and the denominator of two fractions. The program also asks an integer as an exponent. The program forms fractions from the given numerators and denominators and performs the usual mathematical operations according to the example below:

Example run:

Give the first fraction.
Give numerator (top):
26
Give denominator (bottom):
37
Give the second fraction.
Give numerator (top):
17
Give denominator (bottom):
41
Give an exponent:
3
Sum: 26/37 + 17/41 = 1695/1517
Subtract: 26/37 - 17/41 = 437/1517
Multiply: (26/37) * (17/41) = 442/1517
Divide: (26/37) / (17/41) = 1066/629
Power: (26/37)**3 = 17576/50653

Python module JSON and lists

In this exercise we have a file containing statistics of inhabitants of Helsinki between the years 1900-1961. The data has been fetched from public Finnish open data set, available at: https://www.avoindata.fi/data/en_GB/dataset/helsingin-historialliset-tilastot
The name of the file is helsinki_stats.json and it is available in Moodle.

The file content displays the inhabitants by year, age-group and gender. The age groups in use are 20-24, 25-29, 30-34 and 35-39 years. The JSON-format is widely used data format and it is a common way to transfer data between web-programs. You will see this format in many places across the internet.

Your goal is to:

  1. read the .json file (you can use the familiar open() -function) and convert the text into a json format. Use the json-library of Python to do this (read more from https://docs.python.org/3/library/json.html)
  2. Allow the user to calculate the total number of inhabitants by gender for the whole period 1900-1961.
  3. Allow the user to search for the number of inhabitants by a given year. Helsinki hosted the world Olympics in 1952, how many people lived in the city back then?
  4. Allow the user to search for inhabitants by age cohorts and starting year. For example, calculate the total number of inhabitants of ages 30-34 from year 1950 until the year 1961

Some helpers for the task:

  • Please, open the file and check its contents to get a good understanding of the contents
  • Once you read the data into a json-format, you can access the data in a similar way as using list of words.
  • You can access the actual data with json_stats[“data”]. You need to use a loop to go through the entries and process them json_stats[“data”][0]points to the first row in the data, which is
    • {“key”: [“1900”, “0”, “4”], “values”: [“7501”]}
    • To compare the year, you could compare the value json_stats[“data”][0][“key”][0], if it matches with the year 1900 (yes it does)
    • To read the value of this data row, use json_stats[“data”][0][ “values”][0]

This may look confusing, but you have all the skills to master this task! Remember, this is what real-life data may look like.

Clarifications for the file:
data[“key”]is a list that contains 3 values. [0]= year, [1]= gender, [2]= age group

Year options are: 1900-1961 [Notice that there are some years missing]
Gender options are: 0 = male, 1 = female
Age group options are: 4 = 20-24, 5 = 25-29, 6 = 30-34, 7 = 35-39
Note: All numbers in the text file are actual strings. Remember int-string conversions!

Example runs:

Welcome to history data analyzer.
Enter the file to open: helsinki_stats.json
File read successfully, ready for analysis.
What would you like to do?
1) Calculate total amount of inhabitants by gender
2) Calculate inhabitants on a given year
3) Calculate inhabitants after given year by age cohort
0) Stop
Make your choice:
1
Select your gender (0=male, 1=female):
0
There were a total of 1086873 males in Helsinki between years 1900-1961
What would you like to do?
1) Calculate total amount of inhabitants by gender
2) Calculate inhabitants on a given year
3) Calculate inhabitants after given year by age cohort
0) Stop
Make your choice:
1
Select your gender (0=male, 1=female):
1
There were a total of 1410942 females in Helsinki between years 1900-1961
What would you like to do?
1) Calculate total amount of inhabitants by gender
2) Calculate inhabitants on a given year
3) Calculate inhabitants after given year by age cohort
0) Stop
Make your choice:
0
Bye!
###
Welcome to history data analyzer.
Enter the file to open: helsinki_stats.json
File read successfully, ready for analysis.
What would you like to do?
1) Calculate total amount of inhabitants by gender
2) Calculate inhabitants on a given year
3) Calculate inhabitants after given year by age cohort
0) Stop
Make your choice:
2
Please enter year for search (1900-1961):
1952
There were a total of 124263 inhabitants in Helsinki on year 1952
What would you like to do?
1) Calculate total amount of inhabitants by gender
2) Calculate inhabitants on a given year
3) Calculate inhabitants after given year by age cohort
0) Stop
Make your choice:
0
Bye!
###
Welcome to history data analyzer.
Enter the file to open: helsinki_stats.json
File read successfully, ready for analysis.
What would you like to do?
1) Calculate total amount of inhabitants by gender
2) Calculate inhabitants on a given year
3) Calculate inhabitants after given year by age cohort
0) Stop
Make your choice:
3
Please enter year for search (1900-1961):
1950
Select age cohort (4=20-24, 5=25-29, 6=30-34, 7=35-39):
6
There were a total of 410839 inhabitants of ages 30-34 between the years 1950 and
1961
What would you like to do?
1) Calculate total amount of inhabitants by gender
2) Calculate inhabitants on a given year
3) Calculate inhabitants after given year by age cohort
0) Stop
Make your choice:
0
Bye!