×
Samples Blogs Make Payment About Us Reviews 4.9/5 Order Now

Create a Program to Choose Users Favourite Color in Python Assignment Solution

July 08, 2024
Dr. Muhammad Rahman
Dr. Muhammad
🇸🇬 Singapore
Python
Dr. Muhammad Rahman holds a Ph.D. in Computer Engineering and has successfully completed over 900 Python programming test assignments with ProgrammingHomeworkHelp.com. His expertise lies in Python for cybersecurity, network programming, data encryption, and software development.
Key Topics
  • Instructions
  • Requirements and Specifications
Tip of the day
Familiarize yourself with OCaml's pattern matching; it simplifies handling recursive data structures like lists and trees, making your code concise and easier to debug.
News
In 2024, Girls Who Code introduced a Data Science + AI track in their free summer programs for high school students, fostering skills in cybersecurity and creative coding​

Instructions

Objective

Write a python assignment program to choose users favourite color in python language.

Requirements and Specifications

program to choose users favourite color in python
program to choose users favourite color in python1

Source Code

# -*- coding: utf-8 -*- """Copy of Programming Assignment 2 Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1OKFQBtwHw5EEkjVuIsBFVtt_o-gmcn06 # Programming Assignment 2 (CSE1PE/PES 2021, Semester 2) """ STUDENT_NAME = 'Josh McCormick' STUDENT_ID = '21109698' """## Instructions This assignment is structured similarly to the labs, and as such the instructions are similar: - Read each question thoroughly multiple times to ensure that you understand the requirements. - Once you understand the question, code your solution in the associated code cell titled "Your Solution". - Test your solution multiple times, with a variety of inputs---not just those found in the example runs. - Unless explicitly asked in the question, you are _not_ required to validate user input, i.e. you can assume that the user will enter a valid input value. - Keep in mind that partial attempts at solutions will likely still be worth some marks, so be sure to have a go at writing code for every task. When you have satisfactorily attempted all problems, confirm that your solution works by resetting the notebook runtime and running your code again---instructions can be found at the bottom of this notebook. The submission for this assignment is the `.ipynb` notebook file. You should export this file and upload it via the link in the LMS---instructions can be found on the assignment submission page. Do not submit your solutions in any other format as they will not be graded. **This is an individual assignment, and the solutions that you submit for all of the tasks must be your own. Copying solutions from other students, relatives, friends, or strangers on the internet is plagiarism and treated as [academic misconduct](https://www.latrobe.edu.au/students/admin/academic-integrity) by La Trobe University. Plagiarism includes copying solutions and making superficial changes to the code (such as renaming variables or editing comments). The penalty for academic misconduct can be as serious as expulsion from the university.** ## Frequently Asked Questions _Q: I want to write the code in a text editor such as Visual Studio Code. Can I submit `.py` files instead of using this notebook?_ A: No, only `.ipynb` files will be graded. If you really want to write your code in a text editor, ensure that you copy your solutions into the appropriate notebook cells afterwards and run them to make sure that they work correctly. You can then follow the usual submission procedure. _Q: I'm getting ready for submission, but I can't open the downloaded `.ipynb` file on my computer. Is that a problem?_ A: That's not a problem, we know how to open it to mark your assignment. If you want to double-check the contents of the downloaded `.ipynb` file for your own peace of mind, you can upload it to [Google Colab](https://colab.research.google.com/) and open it there. _Q: There is a mismatch between the precision of values shown in the example runs and my solution's output (e.g. my code prints "\$23.33333334" but the question asks for 2 decimal places and the example run shows "\$23.34"). Is it still possible to achieve full marks with this kind of discrepancy?_ A: No, you would not receive full marks for such a solution. Unlike Programming Assignment 1, the **tasks in Programming Assignment 2 are designed to test your ability to format outputs as well as implement the program logic**. If you are having trouble with formatting your output, you may wish to revise f-strings (Topic 6). ## Programming Tasks This assignment consists of five programming tasks, with a total of 100 marks allocated between them according to their difficulty. Take your time to read and re-read the instructions before attempting to write your solution---you can save a lot of trouble by simply having a clear understanding of the problem before touching any code. ### Task 1 _(10 marks)_ For this task, you are to write code that checks whether the user's favourite colour is one of the seven colours of the rainbow. #### Instructions Your task is to write a program which asks the user what their favourite colour is. The program should then inform the user whether the colour that they entered is a traditional colour of the rainbow or not. The seven colours of the rainbow, according to Isaac Newton, are: * red * orange * yellow * green * blue * indigo * violet A set of strings describing the seven colours of the rainbow has already been defined for you as a constant and must be used in your solution. #### Requirements To achieve full marks for this task, you must follow the instructions above when writing your solution. Additionally, your solution must adhere to the following requirements: - You **must** ignore the case of the user input (i.e. "yellow" and "YELLOW" should both be considered colours of the rainbow). - You **must** use the `RAINBOW_COLOURS` constant appropriately in your code. - You **must not** compare the user input to different colours separately. #### Example Runs ##### Run 1 ``` Enter your favourite colour: red You chose a colour of the rainbow. ``` ##### Run 2 ``` Enter your favourite colour: YelloW You chose a colour of the rainbow. ``` ##### Run 3 ``` Enter your favourite colour: teal You did not choose a colour of the rainbow. ``` Your code should execute as closely as possible to the example runs above. To check for correctness, ensure that your program gives the same outputs as in the examples, as well as trying it with other inputs. #### Your Solution """ RAINBOW_COLOURS = { 'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet' } # Write your solution here colour = input("Enter your favourite colour: ") if colour.lower() in RAINBOW_COLOURS: print("You chose a colour of the rainbow.") else: print("You did not choose a colour of the rainbow.") """### Task 2 _(20 marks)_ For this task, you are to write code that tracks auction sale prices and prints the top most expensive sales. #### Instructions The auction history program found below is currently missing two important pieces of functionality---it doesn't record auction sales, nor is it able to print the top most expensive sales. Provided for you is the `AuctionSale` class which contains the item name and sale price for a particular auction, and the `AuctionHistory` class which is responsible for maintaining the list of past auction sales. Your task is to implement this missing functionality by adding two methods to the `AuctionHistory` class: `add_sale` and `print_top_sales`. ###### `add_sale` This method is to take an item name and its sale price as arguments, create a new `AuctionSale` object, and then append it to the appropriate list of sales. ###### `print_top_sales` This method is to take no arguments and print the item name and sale price of the top three most expensive auction sales in descending order of price (i.e. highest to lowest). In order to sort the auction sale items you should call the `sort` list method ([documented here](https://docs.python.org/3/library/stdtypes.html#list.sort)). You will need to make use of the `sort` method's two named arguments when calling it: `key` and `reverse`: * The `key` named argument can be provided with the _name_ of a function (no parentheses). That function will be called for each item, and sorting will be based on the values returned by the function. * The `reverse` named argument can be provided with a boolean which determines whether the sort order should be reversed or not. _Hint: A function which returns the price of an auction sale item has already been defined for you, and can be used as the `key` named argument for `sort`._ #### Requirements To achieve full marks for this task, you must follow the instructions above when writing your solution. Additionally, your solution must adhere to the following requirements: - You **must** use the `sort` list method with appropriate named arguments. - You **must** use list slicing and a loop to print the top sales. You **must not** use list indexing to retrieve individual list items. - You **must not** use `break`, `continue` or `return` statements in `print_top_sales`. #### Example Runs ##### Run 1 ``` McCartney III: $3047 Bathory: $3000 Reggatta De Blanc: $2945 ``` Your code should execute as closely as possible to the example runs above. To check for correctness, ensure that your program gives the same outputs as in the examples, as well as trying it with other inputs. #### Your Solution """ class AuctionSale: def __init__(self, item_name, price): self.item_name = item_name self.price = price def get_price(sale): return sale.price class AuctionHistory: def __init__(self): self.sales = [] # Write your methods here def add_sale (self, item_name, price): self.item_name = item_name self.price = price self.sales.append(item_name and price) def print_top_sales (the_list): temp_list = the_list.copy() temp_list.sort() print(temp_list[0:2]) history = AuctionHistory() history.add_sale('McCartney III', 3047) history.add_sale('Bleach', 1850) history.add_sale('Reggatta De Blanc', 2945) history.add_sale('Bathory', 3000) history.print_top_sales(AuctionHistory.sales) """### Task 3 _(20 marks)_ For this task, you are to write a simple program to track time spent studying. #### Instructions Your program should be capable of keeping a sum of the total hours spent studying each of any number of subjects. You are to add the missing methods to the `StudyTracker` class as described below. ###### `add_hours` This method takes a subject code and the number of hours spent studying this subject, and adds it to the total hours for that subject. You will need to consider two cases when this method is called: - No hours have been logged for the subject yet. - The subject already has some hours logged. ###### `print_summary` This method takes no arguments, and prints the name and total hours spent studying each subject (no sorting required). Additionally, you are to display the average number of hours spent studying a subject. Hours are to be displayed with two decimal places of precision. You can assume that `add_hours` has been called at least once before `print_summary` (that is, you don't need to worry about the study tracker not containing any subjects). _Hint: If you don't remember how to iterate over the items in a dictionary, you may wish to revise Topic 7._ #### Requirements To achieve full marks for this task, you must follow the instructions above when writing your solution. Additionally, your solution must adhere to the following requirements: - You **must** use f-strings to format the outputs (do not use string concatenation). - You **must** ensure that the hours are printed with two decimal places of precision. - The order in which the subjects are printed from `print_summary` is **not** important. - You **must** use a single loop to both print individual subject hours and aggregate the average hours. #### Example Runs ##### Run 1 ``` CSE1PE: 2.50 hours CSE1OOF: 0.50 hours CSE1IIT: 1.75 hours average: 1.58 hours ``` Your code should execute as closely as possible to the example runs above. To check for correctness, ensure that your program gives the same outputs as in the examples, as well as trying it with other inputs. #### Your Solution """ class StudyTracker: def __init__(self): self.subjects = {} # Write your methods here tracker = StudyTracker() tracker.add_hours('CSE1PE', 2.0) tracker.add_hours('CSE1OOF', 0.25) tracker.add_hours('CSE1IIT', 1.75) tracker.add_hours('CSE1PE', 0.5) tracker.add_hours('CSE1OOF', 0.25) tracker.print_summary() """### Task 4 _(25 marks)_ For this task, you are to write code that handles the transfer of funds between two bank accounts. #### Instructions As this task relates to tranferring funds between bank accounts, a `BankAccount` class has been provided, which supports depositing and withdrawing funds. A simple interactive loop has already been implemented, which allows the user to repeatedly transfer funds from one account to another. ##### Part A You are to write a function called `transfer_funds` with three parameters: the amount to transfer, the account the funds are coming from, and the account the funds are going to. It should use the appropriate instance methods on each of the accounts to update their balances as required. ##### Part B If you tested your solution thoroughly in the previous part, you probably came across a logic error in the program---there's nothing to stop us from transferring funds from an account, even if the account balance becomes negative! You are to fix this problem by raising an exception and preventing the account balance from becoming negative. You should do this by raising a `ValueError` in the appropriate place in the `BankAccount` class. _Hint: The order in which the withdrawal and deposit occur in `transfer_funds` matters---the wrong order will result in the creation of free money!_ ##### Part C At this point, the program prevents a transfer occurring if there aren't enough funds in the "from" account. However, simply crashing a program isn't a very nice user experience. You are to modify your program so that it handles the `ValueError` and displays `<>` to the user. The program should otherwise continue as normal, with the user being asked whether they would like to perform another transaction. A failed transaction should not result in either account balance changing. _Hint: A little rusty at exception handling? Take a look at the relevant lab for examples._ #### Requirements To achieve full marks for this task, you must follow the instructions above when writing your solution. Additionally, your solution must adhere to the following requirements: - The `transfer_funds` function **must not** directly access the `balance` instance variable of either bank account. - You **must** raise an exception from within the `BankAccount` class if a withdrawal would cause an account balance to become negative. - You **must** specify the appropriate exception type both when handling the exception. - The `transfer_funds` function call **must** be the only thing in your `try` block. - A failed transaction **must not** change either bank account balance (i.e. the total of the accounts should never change). #### Example Runs ##### Run 1 ``` == Account balances == Savings: $1000.00 Debit: $ 200.00 TOTAL: $1200.00 Enter transfer amount ($): 300.50 == Account balances == Savings: $ 699.50 Debit: $ 500.50 TOTAL: $1200.00 Perform another transfer? (y/n): n ``` ##### Run 2 ``` == Account balances == Savings: $1000.00 Debit: $ 200.00 TOTAL: $1200.00 Enter transfer amount ($): 95 == Account balances == Savings: $ 905.00 Debit: $ 295.00 TOTAL: $1200.00 Perform another transfer? (y/n): y Enter transfer amount ($): 1000 <> == Account balances == Savings: $ 905.00 Debit: $ 295.00 TOTAL: $1200.00 Perform another transfer? (y/n): y Enter transfer amount ($): 900 == Account balances == Savings: $ 5.00 Debit: $1195.00 TOTAL: $1200.00 Perform another transfer? (y/n): n ``` Your code should execute as closely as possible to the example runs above. To check for correctness, ensure that your program gives the same outputs as in the examples, as well as trying it with other inputs. #### Your Solution """ class BankAccount: def __init__(self, name, initial_balance): self.name = name self.balance = initial_balance def deposit(self, amount): self.balance = self.balance + amount def withdraw(self, amount): # Part B: Raise an exception as appropriate self.balance = self.balance - amount def print_balances(account_a, account_b): print('== Account balances ==') print(f'{account_a.name:>9s}: ${account_a.balance:7.2f}') print(f'{account_b.name:>9s}: ${account_b.balance:7.2f}') total_balance = account_a.balance + account_b.balance print(f' TOTAL: ${total_balance:7.2f}') # Part A. Write your transfer_funds function here account_a = BankAccount('Savings', 1000) account_b = BankAccount('Debit', 200) print_balances(account_a, account_b) another_transfer = 'y' while another_transfer == 'y': amount = float(input('Enter transfer amount ($): ')) # Part C. Print an appropriate message if an exception is encountered transfer_funds(amount, account_a, account_b) print_balances(account_a, account_b) another_transfer = input('Perform another transfer? (y/n): ') """### Task 5 _(25 marks)_ For this task, you are to graph the physical characteristics of gentoo penguins using Pandas and Matplotlib. #### Instructions This task uses a dataset containing some physical measurements of three penguin species: Adelie, Chinstrap and Gentoo. You can view the dataset online [by clicking here](https://gist.github.com/anibali/c2abc8cab4a2f7b0a6518d11a67c693c). Run the following code cell to load the dataset into a Pandas DataFrame and look at the first few rows. Read through the code before executing it. """ # Import the modules that we need for this task. import pandas as pd import matplotlib.pyplot as plt # This is the location of the penguin data file on the internet. URL = 'https://gist.githubusercontent.com/anibali/c2abc8cab4a2f7b0a6518d11a67c693c/raw/3b1bb5264736bb762584104c9e7a828bef0f6ec8/penguins.csv' # Download the penguin data and turn it into a Pandas DataFrame object. df = pd.read_csv(URL) # Display the first few rows of the DataFrame object. display(df.head()) """As you can see, the dataset consists of 7 columns. The species of penguin can be `Gentoo`, `Adelie`, or `Chinstrap`. The sex can be `MALE` or `FEMALE`. Your task is to produce a scatter plot which relates body mass and flipper length for **gentoo** penguins, with data points separated by sex. A successful solution should be identical to the example below, which clearly shows how these physical measurements are a good indicator of sex. #### Requirements To achieve full marks for this task, you must follow the instructions above when writing your solution. Additionally, your solution must adhere to the following requirements: - You **must** create a different DataFrame for male and female gentoo penguins by _filtering_ the data appropriately (hint: you can create an intermediate DataFrame containing all gentoo penguins first). - You **must not** plot data for Adélie or chinstrap penguins. - You **must** plot both sexes on the same graph, giving each data series an appropriate label. - You **must** give the plot a title, axis labels, and a legend. #### Your Solution """ # Write your solution here """--- ## Resetting the Notebook Runtime Due to the nature of notebooks, old variables, classes and functions may still be accessible even after they have been removed from the code. This may result in unexpected program behaviour. To ensure that this isn't the case, you can reset the runtime to reset the Python interpreter state. After doing so, you should run your solutions again to ensure they function correctly. To reset the runtime, click the "Runtime" button in the menu at the top, then click "Restart runtime". Then, click "yes" in the following warning. """ el('Weight') plt.show() From the results obtained in figure 2.b) we can see that the model is quite good since the trend is centered on the test and training data. If we observe each point of the obtained model, we can see that it is centered approximately on the mean of the dataset values. This means that the model is not overfitting and therefore does not try to recreate each oscillation of the data, because for each x value, there are several y values, but our model predicts a y value for each x. Also, we can see that the obtained RMSE in part 2.c) it is relatively low which indicates that the values are close to the median. # Solve question here. Add a Markdown cell after this cell if you want to add some comment on you solution. y_predict.shape x X_train

Related Samples

At ProgrammingHomeworkHelp.com, we offer comprehensive assignment support to students, featuring a dedicated section for related samples of Python assignments. Our expertly crafted Python samples cover a wide range of topics, from basic syntax and data types to advanced concepts like machine learning and data analysis. These samples are designed to help students understand complex topics and improve their coding skills. Explore our Python samples today and discover the quality and expertise that ProgrammingHomeworkHelp.com provides to help you succeed in your programming assignments.