CS作业代写 OPIM 5641: Business Decision Modeling – University of Connecticut

Homework 2 – Solution

Homework 2¶
OPIM 5641: Business Decision Modeling – University of Connecticut

Copyright By PowCoder代写 加微信 powcoder

Due Monday, February 14, 11:59pm

Please add detailed comments to all code so that I can follow your solution. If I cannot understand your code then you will not receive full credit.

Your Name Here
Your NetID Here

Problem 1¶
Problem 1a¶
We will be using the table titled ‘List of municipalities in Connecticut’ from this website. Use pandas to read the table as a variable called df and show the first 30 rows.

https://en.wikipedia.org/wiki/List_of_municipalities_in_Connecticut

Problem 1b¶
i) How many unique values are in the ‘Designation’ column? Use .nunique()

ii) What are the unique values in the ‘Designation’ column? Use .unique()

ii) Use .value_counts() to show the number of values per unique entry. What trends do you see?

Problem 1c¶
Make a histogram of the Land area (square miles) column. Add a nice main title, and sensible $x$ and $y$ axis titles. Choose a fun color of your choice to fill in the histogram.

Problem 1d – Extra credit¶
Same as 1c, but use a kernel density plot. Add the mean of the column as a dashed red line on the plot.

Problem 1e¶
i) Calculate the difference between the 2010 and 2020 populations (a positive number should mean there was population growth in that town). Note that you may have to transform the columns to remove the commas in the numbers since they aren’t read as numerical columns.

Read this website.

https://stackoverflow.com/questions/28986489/how-to-replace-text-in-a-string-column-of-a-pandas-dataframe

Now that you know what to do, replace the comma (“,”) with NOTHING (“”).

Store this value as a new column in the dataframe called PopChangeRaw.

ii) Calculate the mean, median, std, min, max, 10th percentile and 90th percentile of the column.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from math import *
import seaborn as sb

from google.colab import drive
drive.mount(‘/content/drive’)

Mounted at /content/drive
time: 19.2 s (started: 2022-03-01 17:36:32 +00:00)

Problem 1a¶

df = pd.read_csv(“/content/drive/MyDrive/OPIM 5641/2022_Spring/Module2/Homework 2/list_of_municipalities_in_ct.csv”)
print(df.head(10))

Name Designation … Council of Governments Native American name
0 Andover Town … Capitol Region NaN
1 Ansonia City … Naugatuck Valley NaN
2 … Northeast CT NaN
3 Avon Town … Capitol Region NaN
4 Barkhamsted Town … Northwest Hills NaN
5 Beacon Falls Town … Naugatuck Valley NaN
6 Berlin Town … Capitol Region NaN
7 … South Central NaN
8 … Western CT NaN
9 Bethlehem Town … Naugatuck Valley NaN

[10 rows x 11 columns]
time: 60.3 ms (started: 2022-03-01 17:53:13 +00:00)

Problem 1b¶

df[‘Designation’].nunique(dropna=True)
print(“There total number of unique values in destination is”, df[‘Designation’].nunique(dropna=True))

df[‘Designation’].unique()
print(“The unique values in ‘destination’ are”,df[‘Designation’].unique())

df[‘Designation’].value_counts()
print(df[‘Designation’].value_counts())
print(“The vast majorty is Towns in CT. “)

There total number of unique values in destination is 3
The unique values in ‘destination’ are [‘Town’ ‘City’ ‘Borough’]
Town 149
City 19
Borough 1
Name: Designation, dtype: int64
The vast majorty is Towns in CT.
time: 31.2 ms (started: 2022-03-01 17:53:52 +00:00)

Problem 1c¶

df[‘Land area (square miles)’].hist(color=”blue”)
plt.tight_layout()
plt.ylabel(‘Land Area in Square Miles ‘)
plt.xlabel(‘Municipalities’)
plt.title(‘Histogram of Land Area of Municipalities’)
plt.show()

time: 629 ms (started: 2022-03-01 17:54:12 +00:00)

Problem 1d¶

sb.kdeplot(data=df, x=df[‘Land area (square miles)’])
plt.plot([df[‘Land area (square miles)’].mean(), df[‘Land area (square miles)’].mean()], [0, 0.03])
plt.show()

time: 237 ms (started: 2022-03-01 17:54:35 +00:00)

Problem 1e¶

df[‘Population (in 2010)’] = df[‘Population (in 2010)’].str.replace(“,”,””)
df[‘Population (in 2010)’] = df[‘Population (in 2010)’].astype(float)

df[‘Population (in 2020)’] = df[‘Population (in 2020)’].str.replace(“,”,””)
df[‘Population (in 2020)’] = df[‘Population (in 2020)’].astype(float)

df[‘PopChangeRaw’] = df[‘Population (in 2020)’] – df[‘Population (in 2010)’]

print(“Mean of PopChangeRaw = “, df[‘PopChangeRaw’].mean())
print(“Median of PopChangeRaw = “,df[‘PopChangeRaw’].median())
print(“Standard Deviation of PopChangeRaw = “,df[‘PopChangeRaw’].std())
print(“Minimum of PopChangeRaw = “,df[‘PopChangeRaw’].min())
print(“Maximum of PopChangeRaw = “,df[‘PopChangeRaw’].max())
print(“10th Percentile of PopChangeRaw = “,df[‘PopChangeRaw’].quantile(0.1))
print(“90th Percentile of PopChangeRaw = “,df[‘PopChangeRaw’].quantile(0.9))

Mean of PopChangeRaw = 188.44378698224853
Median of PopChangeRaw = -75.0
Standard Deviation of PopChangeRaw = 1444.498610731288
Min of PopChangeRaw = -3721.0
Max of PopChangeRaw = 12827.0
10th Percentile of PopChangeRaw = -577.2
90th Percentile of PopChangeRaw = 1012.0000000000005
time: 25.4 ms (started: 2022-03-01 17:52:32 +00:00)

df[‘Population (in 2010)’] = df[‘Population (in 2010)’].str.replace(“,”,””)
df[‘Population (in 2010)’].astype(float)

0 3303.0
1 19249.0
2 4317.0
3 18098.0
4 3799.0
164 12498.0
165 16680.0
166 8990.0
167 9975.0
168 7964.0
Name: Population (in 2010), Length: 169, dtype: float64

time: 30.7 ms (started: 2022-03-01 17:51:43 +00:00)

Problem 2¶
The p-harmonic series is the infinite sum of the reciprical of the natural numbers raised to the $p$ power:

$\sum\limits_{i=1}^∞ \frac{1}{i^p}$.

Problem 2a¶
If $p=1$, you get the harmonic series:

$\sum\limits_{i=1}^∞ \frac{1}{i}$.

(i) Instead of counting this all the way to infinity, calculate the sum of the first 10 terms:

$\sum\limits_{i=1}^{10} \frac{1}{i} = \frac{1}{1} + \frac{1}{2} + \cdots + \frac{1}{10}$.

(ii) Again for $p=1$, calulate the sum of the first 100 terms.

(ii) Again for $p=1$, calulate the sum of the first 10,000 terms.

Problem 2b¶
Now, for $p=2$, do the same exercise, i.e., calculate the sum of the first $n$ terms in the sum

$\sum\limits_{i=1}^{n} \frac{1}{i^2} = \frac{1}{1^2} + \frac{1}{2^2} + \cdots + \frac{1}{n^2}$.

Do this for:

(i) $n=10$.

(ii) $n=100$.

(ii) $n=10,000$.

Problem 2c¶
Compare the answers from 2a and 2b. Which one grows faster? Any observations?

# For problem 2a, we can write the code like this:

for i in range(1,n+1):
total += 1/i
print(total)

for i in range(1,n+1):
total += 1/i
print(total)

for i in range(1,n+1):
total += 1/i
print(total)

# For problem 2b, we can write the code like this:

for i in range(1,n+1):
total += 1/i**2
print(total)

for i in range(1,n+1):
total += 1/i**2
print(total)

for i in range(1,n+1):
total += 1/i**2
print(total)

2.9289682539682538
5.187377517639621
9.787606036044348
1.5497677311665408
1.6349839001848923
1.6448340718480652
time: 29.7 ms (started: 2022-03-01 16:59:31 +00:00)

It appears as if for $p=1$ the summation is divergent, i.e., it will grow forever. For $p=2$, the summation actually converges. Even if we go to millions of terms it barely grows:

n = 1000000
for i in range(1,n+1):
total += 1/i**2
print(total)
n = 10000000
for i in range(1,n+1):
total += 1/i**2
print(total)

1.64493306684877
1.6449339668472596
time: 4.47 s (started: 2022-03-01 17:01:14 +00:00)

Problem 3¶
Directions:
Adopted from Chapter 9, Problem 5 from Powell using the brute force method.

Planning Automobile Production. The Auto Company
of America (ACA) produces four types of cars: subcompact,
compact, intermediate, and luxury. ACA also produces trucks
and vans. Vendor capacities limit total production capacity to
at most 1.2 million vehicles per year. Subcompacts and com-
pacts are built together in a facility with a total annual capacity
of 620,000 cars. Intermediate and luxury cars are produced in
another facility with capacity of 400,000; and the truck/van
facility has a capacity of 275,000. ACA’s marketing strategy
requires that subcompacts and compacts must constitute at
least half of the product mix for the four car types. The
Corporate Average Fuel Economy (CAFE) standards in the
Energy Policy and Conservation Act require an average fleet
fuel economy of at least 27 mpg.

Profit margins, market potential, and fuel efficiencies are
summarized as follows:

Type Profit Margin (USD/vehicle) Market Potential (sales in ‘000) Fuel Economy (mpg)
Subcompact 50 600 40
Compact 225 400 34
Intermediate 250 300 15
Luxury 500 225 12
Truck 400 325 20
Van 200 100 25

To simplify the problem, use a step size of 25 in your range() functions!

What is the optimal profit for ACA?
How long did it take to run your script in total? Mine took X minutes to run.

# run this so that we can time our code
!pip install ipython-autotime
%load_ext autotime

Collecting ipython-autotime
Downloading ipython_autotime-0.3.1-py2.py3-none-any.whl (6.8 kB)
Requirement already satisfied: ipython in /usr/local/lib/python3.7/dist-packages (from ipython-autotime) (5.5.0)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython->ipython-autotime) (0.7.5)
Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython->ipython-autotime) (1.0.18)
Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/dist-packages (from ipython->ipython-autotime) (57.4.0)
Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython->ipython-autotime) (4.4.2)
Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython->ipython-autotime) (4.8.0)
Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython->ipython-autotime) (0.8.1)
Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython->ipython-autotime) (2.6.1)
Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython->ipython-autotime) (5.1.1)
Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->ipython-autotime) (1.15.0)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->ipython-autotime) (0.2.5)
Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect->ipython->ipython-autotime) (0.7.0)
Installing collected packages: ipython-autotime
Successfully installed ipython-autotime-0.3.1
time: 2.35 ms (started: 2022-03-01 15:56:43 +00:00)

# your code here – DOWNLOAD YOUR OWN COPY then complete the assignment

# https://en.wikipedia.org/wiki/Array_data_structure
products = [“subcompact”,”compact”,”intermediate”,”luxury”,”truck”,”van”]

# dictionary
profit = {
“subcompact” : 50,
“compact” : 225,
“intermediate” : 250,
“luxury” : 500,
“truck” : 400,
“van” : 200
demand = {
“subcompact” : 600,
“compact” : 400,
“intermediate” : 300,
“luxury” : 225,
“truck” : 325,
“van” : 100
“subcompact” : 40,
“compact” : 34,
“intermediate” : 15,
“luxury” : 12,
“truck” : 20,
“van” : 25
# you can express this in 000’s
fabrication = {
“total” : 1200,
“subcompacts_and_compacts” : 620,
“intermediates_and_luxurys” : 400,
“trucks_and_vans” : 275

# CAFE means that your fuel economy has got to be greater than 27 MPG across EVERYTHING you are manufacturing
CAFE = 27 #mpg

# Variables containing current best value and current best solution
# you need to add all of your decision variables here
best_profit = 0
best_n_subcompact = 0
best_n_compact = 0
best_n_intermediate = 0
best_n_luxury = 0
best_n_truck = 0
best_n_van = 0

# now you will make the GREATEST nested for loop… SIX LOOPS FOR SIX VARIABLES!
# make sure you tabbed everything over
for subcompacts in range(0,demand[“subcompact”]+1,25):
for compacts in range(0,demand[“compact”]+1,25):
for intermediates in range(0,demand[“intermediate”]+1,25):
for luxurys in range(0,demand[“luxury”]+1,25):
for trucks in range(0,demand[“truck”]+1,25):
for vans in range(0,demand[“van”]+1,25):

# Check subcompact and compact manufacturing totals
if subcompacts + compacts > fabrication[“subcompacts_and_compacts”]:
# Check intermediate and luxury manufacturing totals
if intermediates + luxurys > fabrication[“intermediates_and_luxurys”]:
# Check the product capacity
if subcompacts + compacts + intermediates + luxurys + trucks + vans > fabrication[‘total’]:
# Check the market_strategy sub + com >= ((inter + lux + sub + com)/2)
if subcompacts + compacts < intermediates + luxurys: # Check subcompact and compact manufacturing totals if trucks + vans > fabrication[“trucks_and_vans”]:
# Check the CAFE mpg standard
totalcars = subcompacts + compacts + intermediates + luxurys + trucks + vans
if totalcars == 0:
if (mpg[“subcompact”]*subcompacts + mpg[“compact”]*compacts + mpg[“intermediate”]*intermediates + mpg[“luxury”]*luxurys + mpg[“truck”]*trucks + mpg[“van”]*vans)/totalcars < CAFE: # store the profit if profit["subcompact"]*subcompacts + profit["compact"]*compacts + profit["intermediate"]*intermediates + profit["luxury"]*luxurys + profit["truck"]*trucks + profit["van"]*vans > best_profit:
# if ALL OF THAT IS VALID… then store the results
best_profit = profit[“subcompact”]*subcompacts + profit[“compact”]*compacts + profit[“intermediate”]*intermediates + profit[“luxury”]*luxurys + profit[“truck”]*trucks + profit[“van”]*vans
best_n_subcompact = subcompacts
best_n_compact = compacts
best_n_intermediate = intermediates
best_n_luxury = luxurys
best_n_truck = trucks
best_n_van = vans
# track your progress
# print(“Maximum profit:”,best_profit)
# print(“Subcompacts”,best_n_subcompact)
# print(“Compacts”,best_n_compact)
# print(“Intermediates”,best_n_intermediate)
# print(“Luxurys”,best_n_luxury)
# print(“Trucks”,best_n_truck)
# print(“Vans”,best_n_van)

# remember, print statements will slow this down ENORMOUSLY – don’t do it!

print(“Maximum profit:”,best_profit)
print(“Subcompacts”,best_n_subcompact)
print(“Compacts”,best_n_compact)
print(“Intermediates”,best_n_intermediate)
print(“Luxurys”,best_n_luxury)
print(“Trucks”,best_n_truck)
print(“Vans”,best_n_van)

Maximum profit: 322500
Subcompacts 200
Compacts 400
Intermediates 0
Luxurys 225
Trucks 275

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com