I couldn’t upload the file of the code so here is is👇:
################################################################################
# This function does the optimization for the resistor #
# Inputs: #
# r_value – value of the resistor #
# ide_value – value of the ideality #
# phi_value – value of phi #
# area – area of the diode #
# temp – temperature #
# src_v – source voltage #
# meas_i – measured current #
# Outputs: #
# err_array – array of error measurements #
################################################################################
def opt_r(r_value,ide_value,phi_value,area,temp,src_v,meas_i):
est_v = np.zeros_like(src_v) # an array to hold the diode voltages
diode_i = np.zeros_like(src_v) # an array to hold the diode currents
prev_v = P1_VDD_STEP # an initial guess for the voltage
# need to compute the reverse bias saturation current for this phi!
is_value = area * temp * temp * np.exp(-phi_value * Q / ( KB * temp ) )
for index in range(len(src_v)):
prev_v = optimize.fsolve(solve_diode_v,prev_v,
(src_v[index],r_value,ide_value,temp,is_value),
xtol=1e-12)[0]
est_v[index] = prev_v # store for error analysis
# compute the diode current
diode_i = compute_diode_current(est_v,ide_value,temp,is_value)
return meas_i – diode_i
################################################################################
# This is how leastsq calls opt_r #
################################################################################
r_val_opt = optimize.leastsq(opt_r,r_val,
args=(ide_val,phi_val,P2_AREA,P2_T,
source_v,meas_diode_i))
r_val = r_val_opt[0][0]
Category: Python
The initial project consisted of developing a machine learning model in Python f
The initial project consisted of developing a machine learning model in Python for a specific application or problem domain. The project requires to demonstrate the understanding of data preprocessing, model selection, evaluation metrics, and effective communication of results. This step of creating the machine learning model in Python is already finished and I will provide it to you below. For my part, the help I need is to complete a presentation where I give my feedback about how this project is progressing. Below I will leave you some of the most important requirements that this presentation needs:
Submit a progress demo recording that includes:
Data preprocessing steps and any challenges encountered.
Details of the machine learning models implemented and the rationale behind their selection.
Evaluation metrics used to assess the models’ performance.
Preliminary results and any insights gained from the analysis.
Plan for finalizing the project, including potential refinements and improvements.
First q : Write an algorithm to determine if a given string contains a balanced
First q :
Write an algorithm to determine if a given string contains a balanced sequence of parentheses.
Input
The input consists of a string containing “(” or “)” only.
Output
Print an Integer representing the count of balanced pairs if the string is balanced. Else print -1 Second q2:
Write an algorithm to find the number of occurrences of needle in a given positive number haystack.
Input
The first line of the input consists of an integer needle, representing a digit.
The second line consists of an integer haystack, representing the positive number.
Output
Print an integer representing the number of occurrences of needle in haystack,
Constraints
0 ≤ needle ≤ 9
0 ≤ haystack ≤ 99999999
Example
Input:
2
123228
Output:
3
Dont use chatgpt at all I can use it!!!
Instructions: In one file, write programs for the tasks below and upload the fi
Instructions: In one file, write programs for the tasks below and upload the file (.py) to Blackboard. In the top comments section of the file, please include your name, the date, and the assignment number. While you do not have to add comments for every line of code, please include comments to tell a reader what you are doing. Commenting your code also suggests to me that you know what you are doing.
While there is no one way to do things, your code should only use commands and methods from class. I do not want you using other commands that you got from the internet.
Please save your file with the following name: “Last name_First name_
Also use the #%% command to divide each answer into its own cell. Note also include #%% after the last line of code in the program, The assignment in word paper ” Assignment 5″ , the attached as well Power points for the lecture.
###Python basic operations ##Check Python version import sys print(‘Python: {}’.
###Python basic operations
##Check Python version
import sys
print(‘Python: {}’.format(sys.version))
###############################################################################
##1 Arithmetic
# Python as a calculator
# Addition and subtraction
4+4
print(4+4 +5)
# Space does not matter
print(5 – 5)
# Multiplication and division
print(3 * 5)
print(10 / 2)
# Exponentiation
print(4 ** 2)
# Modulo
print(18 % 7)
#More complicated math functions do not exist in Python base package
sin(30) #NameError: name ‘sin’ is not defined
import math
math.sin(30)
dir(math) # all available functions in “math”
###############################################################################
##2 Python variables, types and operators
#Python has five standard data types:
#-Numbers
#-String
#-List
#-Tuple
#-Dictionary
#In Python, a variable allows you to refer to a value with a name.
#Python is case sensitive
#To create a variable use “=”, like this example:
print (“John is 20 years old” )
print (“He doesn’t like being 20 years old” )
age = ’20’
print (“John is “+ age +” years old,” )
print (“He doesn’t like being ” + age+ ” years old” )
weight = 60
height = 1.7
bmi = weight/height**2
bmi
#You can now use the name of this variable, weight, instead of the actual value,
60.
#Remember, = in Python means assignment, it doesn’t test equality!
#To check the type of a variable:
type(bmi) # bmi is a float
x=3 # x is an integer
y=’I love Python’ # y is a string
z=True # z is a boolean
type(x)
type(y)
type(z)
#Different types have different operation rules, for example,
2+3
True + False
True – False
False-True
#and, or, not operators
True and False
True or False
not (True and False)
3>4
3==4
3==3.0
3!=3
‘ab’+’cd’
‘ab ‘+’cd’
a+a #name ‘a’ is not defined
#local and global variable
x=10
def myfun(x):
y=x**2
x=4
return y
myfun(x)
myfun(5)
myfun(2)
x
###############################################################################
##3. Data structures: list, array, dictionary and dataframe
##3.1. Lists are a simple container of items, much like arrays in many languages.
#They can change size at any time, can contain items of different types.
list_family_member = [‘Mom’, ‘Dad’, ‘Son’, ‘Daughter’]; list_family_member
list_family_height1 = [‘Mom’, 1.65, ‘Dad’, 1.85, ‘Son’, 1.79, ‘Daughter’, 1.52]
print(list_family_height1)
#Check the type of a list
type(list_family_height1)
##index pointer: zero based indexing and backward indexing
list_family_height1[0]
list_family_height1[7]
list_family_height1[-1]
list_family_height1[-8]
#list slicing
list_family_height1[2:4] #the ending index “4” is not included
list_family_height1[:4]
list_family_height1[4:]
##You saw that a Python list can contain practically anything; it can even contain
other lists!
x = [[“a”, “b”, “c”],
[“d”, “e”, “f”],
[“g”, “h”, “i”]]
x
#To subset a list of lists, you can use the same technique as before: square
brackets.
x[2]
x[2][0]
#x[2] results in a list, that you can subset again by adding additional square
brackets.
x[2][:2]
#Replace/delete/extend list elements
x = [“a”, “b”, “c”, “d”]
x[1] = “r”; x
x[2:] = [“s”, “t”]
x
del(x[1]);x #del() is associated with an index
x.remove(‘s’); x #remove() is associated with an element
y = x + [“e”, “f”]; y
y.append(“z”);y
y.clear();y #clear() to empty a list
#Exercise #1
#The areas of the different parts of your house are stored in separate variables,
#as shown below:
# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
#a. Create a list of lists “areas” such that each sub-list contains the name of
each room as a string
#More specifically, use the strings “hallway”, “kitchen”, “livingroom”, “bedroom”
and “bathroom” for
#the appropriate locations and then its corresponding area.
#b. Sum of the areas of kitchen and bedroom and name it “eat_sleep_area”
#c. Use two different ways of slicing to create a new list, “downstairs”, that
contains the first 3 sub-lists of areas.
#d. Do a similar thing to create a new variable, upstairs, that contains the last 2
sub-lists of areas.
#e. You did a miscalculation when determining the area of the bathroom;
#it’s 10.50 square meters instead of 9.50. Can you make the changes?
#Make the areas list more trendy! Change “livingroom” to “chillzone”.
#f. Use the + operator to paste the list [“poolhouse”, 24.5] to the end
#of the areas list. Store the resulting list as areas_1.
#g. Further extend areas_1 by adding data on your garage. Add the string
#”garage” and float 15.45. Name the resulting list areas_2
#h. remove the “poolhouse” and its corresponding float from the areas list.
#List summary
#Powerful
#Collection of values
#Hold different types
#Change, add, remove
#Question: Can we perform mathematical operations over lists?
height = [1.73, 1.68, 1.71, 1.89, 1.79]
height
#Out: [1.73, 1.68, 1.71, 1.89, 1.79]
weight = [65.4, 59.2, 63.6, 88.4, 68.7]
weight
#Out: [65.4, 59.2, 63.6, 88.4, 68.7]
weight / height ** 2
#TypeError: unsupported operand type(s) for **: ‘list’ and ‘float’
###############################################################################
##3.2 We’ll need other data structures such as array (can be created using array()
#from “numpy” module)
#if we want to perform mathematical operation over the data,
#array operation offers element-wise calculations
###############################################################################
###Pyhton package installation
#list all the modules installed in your system
help(“modules”)
#check if a module ‘numpy’ is installed
help(‘numpy’) # documentation will be found if previously installed
help(‘pulp’) #no documentation can be found if not installed
import sys
‘numpy’ in sys.modules
#To install a package, use “!pip install” or “!conda install”
pip install pulp
help(‘pulp’) #shows the documentation for the module
#If the installation doesn’t work for you, try the following excerpts
#import pip
#pip.main([“install”, “pulp”])
#If not try
#sudo pip install pulp
? numpy # object is not found if not imported even it is installed
import numpy
array([1, 2, 3])
# NameError: name ‘array’ is not defined
numpy.array([1, 2, 3])
#Alternatively,
import numpy as np
np.array([1, 2, 3])
#We can also import a function from a module
from numpy import array
array([1, 2, 3])
#or
from numpy import * #very inadvisable practice-function member may be mixed up
array([1, 2, 3])
#output: array([1, 2, 3])
##Exercise #2
#Import the ‘math’ package so you can access the constant pi with math.pi.
#Calculate the circumference of the circle and store it in C, C=2pir
#Calculate the area of the circle and store it in A,A=pir^2
#Print out the results as
#Circumference: C
#Area: A
# Selectively only import pi from the math package
#you can always make your import more selective.
###############################################################################
np_height = np.array(height)
np_height
#Out: array([ 1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = np.array(weight)
np_weight
type(np_weight)
#Out: array([ 65.4, 59.2, 63.6, 88.4, 68.7])
bmi = np_weight / np_height ** 2
bmi
#array([ 21.852, 20.975, 21.75 , 24.747, 21.441])
65.4/1.73**2
#NumPy remarks: it contains only one type!
np.array([1.0, “is”, True])
#array([‘1.0’, ‘is’, ‘True’],
# dtype=’
#Out: array([False, False, False, True, False], dtype=bool)
bmi[bmi > 23]
#Out: array([ 24.747])
##Exercise #3
# a. Create list baseball_height that contains data of the baseball players’ height
in inches
baseball_height = [74, 69, 71, 73, 76, 79, 75, 81]
#Use np.array() to create a numpy array from baseball_height. Name this array
np_baseball_height.
#Print out the type of np_baseball_height to check that you got it right.
#convert the units to meters by Multiplying np_baseball_height with 0.0254.
#Store the new values in a new array, np_baseball_height_m.
#Print out np_baseball_height_m and check if the output makes sense.
# b. Create list baseball_weight that contains data of the baseball players’ weight
in pounds
baseball_weight = [174, 210, 181, 193, 230, 200, 185, 190]
#Create a numpy array from the baseball_weight list. Name this array
np_baseball_weight.
#Multiply by 0.453592 to go from pounds to kilograms. Store the resulting numpy
array as np_baseball_weight_kg.
#Use np_baseball_height_m and np_baseball_weight_kg to calculate the BMI of each
player.
#Print out bmi
#c. Create a boolean numpy array: the element of the array should be True if the
corresponding
#baseball player’s BMI is below 21. You can use the < operator for this. Name the
array light.
#Print the array light.
# Print out a numpy array with the BMIs of all baseball players whose BMI is below`
21.
#Use light inside square brackets to do a selection on the bmi array.
##2D NumPy Arrays
#Type of NumPy Arrays
type(np_height)
#Out: numpy.ndarray
type(np_weight)
#Out: numpy.ndarray
#ndarray = N-dimensional array
np_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.79],
[65.4, 59.2, 63.6, 88.4, 68.7]])
np_2d
#Out:array([[ 1.73, 1.68, 1.71, 1.89, 1.79],
# [ 65.4 , 59.2 , 63.6 , 88.4 , 68.7 ]])
np_2d.shape
#(2, 5); 2 rows, 5 columns
np.array([[1.73, 1.68, 1.71, 1.89, 1.79],
[65.4, 59.2, 63.6, 88.4, "68.7"]])
#array([['1.73', '1.68', '1.71', '1.89', '1.79'],
# ['65.4', '59.2', '63.6', '88.4', '68.7']],
# dtype='
dict_doubleCond
# Dictionary has other Replace/delete/extend operations that are similar to list
Dict_family_height1[‘Mom’] = 1.60;Dict_family_height1
# Delete a single element
del Dict_family_height1[‘Mom’];Dict_family_height1
# Delete all elements in the dictionary
Dict_family_height1.clear();Dict_family_height1
#Exercise #5
#In a supply chain system, there were 7 customers, namely “customer1”,
“customer2″…”customer7″
#and their corresponding demands are 20,35,60,70,42,80,15
StrDemand =”customer”
DemandKeys=[]
for i in range(1,8):
DemandKeys.append(StrDemand+str(i))
DemandKeys
DemandValues=[20,35,60,70,42,80,15]
#a. Creates a dictionary “demand” to store the demand information and use the name
of the customers
#as the keys. First create two lists for keys and values respectively and then make
dictionary from them.
#b. What is the demand of customer7?
#c. The demand of each customer is increased by 20% in the next season. Create the
new dictionary “newdemand”.
#d. Find out the customers who have demand between 21 and 50.
###############################################################################
#3.4 Data frame is a 2-D labeled data structure with columns of potentially
different type (like an excel sheet).
#DataFrame makes data manipulation easy, from selecting or replacing columns and
indices to reshaping data
## Create a dataframe – a function from Pandas module
#Create a dataFrame with 3 months of sales information for 3 companies
account Jan Feb Mar
0 Jones LLC 150 200 140
1 Alpha Co 200 210 215
2 Blue Inc 50 90 95
#3.4.1 The “default” manner to create a DataFrame from python is to use a list of
dictionaries.
#In this case each dictionary key is used for the column headings. A default index
will be
#created automatically:
help(“pandas”)
? pandas
import pandas
import pandas as pd
sales = [{‘account’: ‘Jones LLC’, ‘Jan’: 150, ‘Feb’: 200, ‘Mar’: 140},
{‘account’: ‘Alpha Co’, ‘Jan’: 200, ‘Feb’: 210, ‘Mar’: 215},
{‘account’: ‘Blue Inc’, ‘Jan’: 50, ‘Feb’: 90, ‘Mar’: 95 }]
sales
type(sales)
df = pd.DataFrame(sales)
df
type()
#3.4.2 Alternatively, use from_dict()
sales = {‘account’: [‘Jones LLC’, ‘Alpha Co’, ‘Blue Inc’],
‘Jan’: [150, 200, 50],
‘Feb’: [200, 210, 90],
‘Mar’: [140, 215, 95]}
df = pd.DataFrame.from_dict(sales)
df
sales
#3.4.3 Use lists to create dataframe
#This is a row oriented approach using pandas from_records().
#This approach is similar to the dictionary approach but you need to explicitly
#call out the column labels.
sales = [(‘Jones LLC’, 150, 200, 50),
(‘Alpha Co’, 200, 210, 90),
(‘Blue Inc’, 140, 215, 95)]
labels = [‘account’, ‘Jan’, ‘Feb’, ‘Mar’]
df = pd.DataFrame.from_records(sales, columns=labels)
df
### Exercise 6
#Create the following datafame in two ways (using dictionary and list)
one two three four
a 1.0 1 10.0 11.0
b 2.0 2 20.0 22.0
c 3.0 3 30.0 33.0
#a. From dictionary
#b. From list
##############################################################################
##4. Functions
#Next we learn how to define (create) functions and how to use them.
# In order to define a function, we need to use a reserved word “def”
#A function also has a body, which is indented
#In order for a function to run, it must be called into action.
#Otherwise, a function will not run by itself
#Function hello1 below requires no argument.
#To run it, you need just to call it by typing its name in the program body
#This function returns nothing back
def hello1():
print (“hello world inside the function”)
return
hello1() ##To run it, you need just to call it
#Function hello2 requires one argument.
#Upon calling this function, you have to pass it an argument
def hello2(x):
print (x)
return
hello2()#TypeError: hello2() missing 1 required positional argument: ‘x’
hello2(‘I love Python’)
x=56
hello2(x)
#Function hello3 below requires no argument.
#To run it, you need just to call it by typing its name in the program body
#This function returns content of x
def hello3():
x = “hello world passed to script”
return(x)
hello3()
#Function hello4 below requires no argument.
#To run it, you need just to call it by typing its name in the program body
#This function returns nothing
#Notice that there is no call of this function in the program body
def hello4():
x= “hello world will not be printed as I am not called in the program body”
#this is just an assignment and will not return anything if x is not called
return
hello4()
#Define funtions to do calculation
def sumProblem(x, y):
sum = x + y
print(sum)
sumProblem(2, 3)
def main():
a = int(input(“Enter an integer: “))
b = int(input(“Enter another integer: “))
print( sumProblem(a, b))
main()
#Excercises 7
#Create the following 2 functions.
#a. Write a function “function1”:It takes three argument, all strings. The function
returns the concatenated three arguments.
#test the function with the three strings: I, love, Python. The expected results is
“l love Python”
#b. Write a function “function2”: It takes 3 arguments, three numbers. The function
returns the Max of three arguments.
#test the function with numnbers 2, 3 and 4. Hint: you can first define a funtion
that returns the max of two arguments
#and then define the funtion that returns the max of the three aguments. Use “if”
syntax for condtion
###############################################################################
##5. Loop
#The excerpts bellow helps you to master loop functions
#We create two sets of numbers, and symbols (which is also strings)
list_num = [1, 2, 3, 4, 5]
list_str = [“@”, “#”, “$”, “%”, “&”]
for number in list_num:
print (‘Number_FOR: ‘, number)
#newlist=[]
#for i in list_num:
# i=1+i
# newlist.append(i)
#newlist
#Use for loop to extract data from dictionary
Dict_family_height1= {‘Mom’: 1.65, ‘Dad’: 1.85, ‘Son’: 1.79, ‘Daughter’: 1.52}
Dict_family_height1[‘Mom’]
for i in Dict_family_height1: #i refers to the keys
print(i)
for i in Dict_family_height1: #i refers to the keys
print(Dict_family_height1[i])
num=0
while (num < 5):
print ('Number_while: ', list_num[num])
num = num +1
# we get the length of the list_str from the set itself
#range(a, b): a, a+1, a+2, ..., b-1
range(len(list_str))
for index in range(len(list_str)):
print ('Current String_FOR: ', list_str[index])
#or
for data in list_str:
print ('Current String_FOR: ', data)
#Since we know the number of elements in the set, the above loop could be also
written like this:
SP=0
while (SP < 5):
print ('Current String_while: ', list_str[SP])
SP = SP +1
# we can also build lists using loop, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print ("Adding %d to the list." % i) #%d is a space holder for numbers
# append is a function that lists understand
elements.append(i)
elements
#Now, we create one nested loop, i.e., a loop inside another loop
for vertical in range(1, 6):
print (vertical)
for horizontal in ['a','b','c']:
print (horizontal)
# Exercise 8
#a. Write a function "function3": use loop function to sum all the numbers in a
list.
#The contents of the list should be user specified
#Hint: use "+=" operator
#Sample List : [4, 2, 7, 1, 3]
#Expected Output : 17
#b. Write a function "function4": use loop function to print the even numbers from
a given list.
#Hint: even number means n % 2 == 0
#Sample List : [4, 10, 13, 14, 50, 61, 70, 87, 90]
#Expected Result : [4, 10, 14, 50, 70, 90]
# The "+=" and *=" operators
bmi
bmi+=bmi #"+=" if number, add the right hand side to the left hand side
bmi*=2 #"*=" if number, multiply the right hand side to the left hand side
#"+=" and *=" are useful in looping
Fish hatcheries grow baby fish and release them into streams. The fish then swim
Fish hatcheries grow baby fish and release them into streams. The fish then swim down the streams, sometimes as far as the oceans. The State of Oregon has historically spent tens of millions of dollars operating fish hatcheries, especially to support salmon spawning. These funds not only pay for raising and releasing baby fish; they also pay for monitoring of fish populations as the fish eventually return to spawn their own natural babies in dozens of streams, rivers and other waterways throughout the state.
All those monitoring stations produce data that scientists then need to analyze. That’s where you come in. In this assignment, you will use the third-party OpenPyXL library to calculate some statistics based on Excel spreadsheets. You will read from file (CLO2), use lists (CLO4), do computations (CLO1) and, of course, use a 3rd-party library (CLO6).
To illustrate, a typical spreadsheet might look a bit like the following:
Monitoring point:WILLAMETTE FALLS (downstream)Notes
WillametteTeam5/135/145/155/165/175/18
CHINOOK ADULTA37240023216218192Fish were sampled and sent to OSU on 5/14 and 5/17
CHINOOK JACKA572928(data missing)226
TOTAL STEELHEADB544752484158
Monitoring point:WILLAMETTE FALLS (upstream)data was not gathered on all dates
WillametteTeam5/135/145/155/165/18
CHINOOK ADULTA36538121915581
CHINOOK JACKA471227130
TOTAL STEELHEADB3944514038
You will need to grab data out of the spreadsheet and compute some statistics.s
What you must do
Use your text editor to create a .py file containing a Python program with a function called analyze(filename, query) that accepts two parameters. The first parameter, filename, will indicate the name of an XLSX file. The second parameter, query, will give the name of a fish type (such as ‘CHINOOK ADULT’). Your function should do the following:
Open the file
Iterate the rows and find those whose first column matches the query
Having found the rows that match, retrieve all numbers from all columns within those rows
Return a tuple containing the (minimum, average, maximum) of these values.
For example, calling analyze(filename, ‘CHINOOK JACK’) on the sample spreadsheet shown above would identify the following values: [57, 29, 28, 22, 6, 47, 12, 27, 13, 0]. The minimum of these is 0, the maximum is 57, and the average is 24.1. Thus, the function would return (0, 24.1, 57).
Please note that the sample spreadsheet above is just an example. The real spreadsheet passed in might have more columns, fewer columns, more rows, fewer rows, more fish names, or fewer fish names. There might be missing values as illustrated above. There might be unusual columns inserted into unpredictable places (such as the “Team” column above). Just find the rows based on the leftmost column, then scan horizontally to retrieve all of the cells in those rows that look like floating-point numbers. Finally, compute and return the requested statistics.
Required 1. In this assignment, you are to write codes that generate a unique pa
Required
1. In this assignment, you are to write codes that generate a unique password for different websites.
2. The rules are as follows:
Assume the website url address is “http://www.google.com”,
Rule 1: Write codes to remove “http://www.” as this part is same across any websites.
Rule 2: For the same reason, write codes to remove “.com”. At this point, what you are left with is the unique website name (usually the name of a company, “google”, in our example)
Rule 3: Create a variable and write codes to extract the first three characters of the website name. In our example, the first three characters are “goo.”
Rule 4: Create a variable and write codes to count the number of characters of the website name. In our example, the number of characters is 6 (g, o, o, g, l, e).
Rule 5. Create a variable and write codes to count the number of letter “e” in the unique website name. In our example, we only have one instance of “e” in “google”.
Rule 6. Create a variable and write codes to concatenate the outputs of Rule 3, Rule 4, Rule 5, and also add “!” at the end.
Rule 7. After creating the variable containing the unique password, print the following statement: “The unique password for website url address is: unique password!”In case of “http://www.google.com,” the output statement would look like as the follows: “The unique password for http://www.google.com is: goo61!”
If the url address is “http://www.youtube.com,” the output statement would look like as the follows: “The unique password for http://www.youtube.com is: you71!”
3. Once you write codes, copy and paste them onto MS word doc. Do NOT screenshot the codes.
Suggestions
1. Begin by creating a variable (url)
url = “http://www.google.com”
2. Then, write codes to satisfy the rules. For example, you are to write codes to remove “http://www” to satisfy Rule 1.
3. Make sure that you write codes in detail so that anyone without Python background can run your codes by copying and pasting onto Visual Studio Codes. For example, if a package is required to run your code, you are to include the codes that import necessary packages. If directions/instructions are required when running your codes, include the directions/instructions hashed out.
Required 1. In this assignment, you are to write codes that generate a unique pa
Required
1. In this assignment, you are to write codes that generate a unique password for different websites.
2. The rules are as follows:
Assume the website url address is “http://www.google.com”,
Rule 1: Write codes to remove “http://www.” as this part is same across any websites.
Rule 2: For the same reason, write codes to remove “.com”. At this point, what you are left with is the unique website name (usually the name of a company, “google”, in our example)
Rule 3: Create a variable and write codes to extract the first three characters of the website name. In our example, the first three characters are “goo.”
Rule 4: Create a variable and write codes to count the number of characters of the website name. In our example, the number of characters is 6 (g, o, o, g, l, e).
Rule 5. Create a variable and write codes to count the number of letter “e” in the unique website name. In our example, we only have one instance of “e” in “google”.
Rule 6. Create a variable and write codes to concatenate the outputs of Rule 3, Rule 4, Rule 5, and also add “!” at the end. Rule 7. After creating the variable containing the unique password, print the following statement: “The unique password for website url address is: unique password!”In case of “http://www.google.com,” the output statement would look like as the follows: “The unique password for http://www.google.com is: goo61!”
If the url address is “http://www.youtube.com,” the output statement would look like as the follows: “The unique password for http://www.youtube.com is: you71!”
3. Once you write codes, copy and paste them onto MS word doc. Do NOT screenshot the codes. Suggestions
1. Begin by creating a variable (url)
url = “http://www.google.com”
2. Then, write codes to satisfy the rules. For example, you are to write codes to remove “http://www” to satisfy Rule 1.
3. Make sure that you write codes in detail so that anyone without Python background can run your codes by copying and pasting onto Visual Studio Codes. For example, if a package is required to run your code, you are to include the codes that import necessary packages. If directions/instructions are required when running your codes, include the directions/instructions hashed out.
This assignment assesses your skills and knowledge on constructing code to manip
This assignment assesses your skills and knowledge on constructing code to manipulate the content of a dictionary.
In this unit, we have explored the fundamental concepts of Iterations and Strings in Python. Before you proceed with this assignment, please review the reading material listed below: Think Python: How to think like a computer scientist : Chapter 11 – Dictionaries Python Beginner Tutorial 8 – For loop, Lists, and Dictionaries Please ensure that you review all examples presented in the Chapter before you work on this assignment. In a program, a dictionary contains lists of students and their courses. The teacher is interested to have a dictionary that has the courses as key and the students enrolled in each course as values. Each key has three different values. To address this requirement, write a function to invert the dictionary and implement a solution that satisfies the teacher’s need. In particular, the function will need to turn each of the list items into separate keys in the inverted dictionary. Also provide a technical explanation for the code and its output in minimum 200 words. Sample input: { ‘Stud1: [‘CS1101’, ‘CS2402’, ‘CS2001’], ‘Stud2: [‘CS2402’,’CS2001’,’CS1102’] } Inverted Output: { ‘CS1101’: [‘Stud1’], ‘CS2402’:[‘Stud1’,’Stud2’], ‘CS2001’: [‘Stud1’,’Stud2’] ‘CS 1102’[‘Stud2’] } Programming Instructions: Print the original dictionary as well as the inverted dictionary. Include your the Python program and the output in your submission. The code and its output must be explained technically. The explanation can be provided before or after the code, or in the form of comments within the code. Submission Instructions:Submit the solution in a word document. Make sure your submission is double-spaced, using Times New Roman, 12-point font, with 1” margins. Use sources to support your arguments. Add a reference list at the end of the submission. For assistance with APA formatting, view the Learning Resource Center: Academic Writing. Your submission should be clearly written, concise, and well organized, and free of spelling and grammar errors. Read the grading rubric to understand on how your work will be evaluated. References: Downey, A. (2015). Think Python: How to think like a computer scientist (2nd ed.). Green Tea Press. kjdElectronics. (2017, August 5). Python beginner tutorial 8 – For loop, lists, and dictionaries [Video]. YouTube. https://youtu.be/bE6mSBNp4YU Raj, A. (2022, March 3). Reverse a dictionary in Python. PythonForBeginners. Python Dictionaries. (n.d.). W3schools.
Here’s a hint to figure out how to interpret the confusion matrix. After splitti
Here’s a hint to figure out how to interpret the confusion matrix. After splitting the data into train and test, execute this code. (Be sure to comment this out before turning in your project!) If the number of mines and rocks in the test data differ, you can look at your confusion matrix and easily determine which row is for rocks and which is for mines.
rocks = 0 # initialize counters
mines = 0
for obj in y_test: # for all of the objects in the test set
if obj == 2: # mines are class 2, rocks are class 1
mines += 1 # increment the appropriate counter
else:
rocks += 1
print(“rocks”,rocks,” mines”,mines) # print the results
..
i shared a link for the the data to use as I’m unable to upload it.?
https://drive.google.com/file/d/1YrWWoSpUZruCL02LmVVB6HDYP56SsUiq