<jupyter_start><jupyter_text>Week 1 Discussion - EC 414 - Python ReviewOfficial Python 3.6 documentation: https://docs.python.org/3.6/Official Python tutorial: https://docs.python.org/3/tutorial/Unofficial Python tutorial (slightly easier to navigate than the official one): https://www.w3schools.com/python/Helpful cheat sheets: https://ehmatthes.github.io/pcc/cheatsheets/README.htmlTopics:  Basics (Importance of indentation [tabs/spaces], Loops, Functions, Lists, Tuples, Dictionaries, indexing, slicing), Numpy, Matplotlib  Basics<jupyter_code># Loops:
# for, while,...

# for: - display all odd numbers in the range [1,1000] that are divisible both by 7 and 9
print('For: ')
low = 1
high = 1000
for i in range(low,high):
    if (i % 2 == 1) and (i % 7 == 0) and (i % 9 == 0):
        print(i)
        
# while: - display all odd numbers in the range [1,1000] that are divisible both by 7 and 9
print('\nWhile: ')
val = low
while (val <= high):
    if (val % 2 == 1) and (val % 7 == 0) and (val % 9 == 0):
        print(val)
    val += 1
# Functions

def circleData(radius):
    c = 2*3.14159*radius
    a = 3.14159*radius*radius
    d = 2*radius
    return c,a,d

rad = 3
[c,a,d] = circleData(rad)
# c, a, d = circleData(rad)    # alternate option to unpack into variables and not create a list
print('Circumfrence:',c)
print('Area:',a)
print('Diameter',d)
# Lists + Indexing/Slicing
# Lists are ordered (have indices) and changeable (can alter content in it)

a = [3, 4, 5]
b = [3, 'hello', [4, 5], '3', 55]

print(a[0])
print(b[2])
print(b[2][1])
print(b[1:3])

# List methods ->
c = [12, 24, 'no']

c.append(222)
print(c)

c.insert(2, 'yes')
print(c)

c.pop(2)
print(c)

c.reverse()
print(c)

length = len(c)
print(length)
# Tuples:
# Tuples are ordered (have indices) and unchangeable (cannot alter content in it)

d = ('red', 'green', 12)
print(d)
print(d[1])
print(len(d))
# Dictionaries
# Dictionaries are unordered and changeable.

# keys and values
demo_dict = {'Name': 'Susan', 'Age': 22, 'Graduation Year': 2020}
print(demo_dict)
print(demo_dict['Name'])
print(len(demo_dict))

# changing content
demo_dict['Name'] = 'Daniel'
print('\n', demo_dict, '\n')

# displaying content
for x, y in demo_dict.items():
  print(x,':', y)

# adding/removing content
demo_dict['hair'] = 'bald'
print('\n',demo_dict,'\n')

demo_dict.pop('hair')
print(demo_dict)<jupyter_output>{'Name': 'Susan', 'Age': 22, 'Graduation Year': 2020}
Susan
3

 {'Name': 'Daniel', 'Age': 22, 'Graduation Year': 2020} 

Name : Daniel
Age : 22
Graduation Year : 2020

 {'Name': 'Daniel', 'Age': 22, 'Graduation Year': 2020, 'hair': 'bald'} 

{'Name': 'Daniel', 'Age': 22, 'Graduation Year': 2020}<jupyter_text>NumPyOfficial documentation: https://docs.scipy.org/doc/numpy-1.15.0/reference/index.htmlHelpful cheat sheet: https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Numpy_Python_Cheat_Sheet.pdfThe basic object in which arrays and matrices are represented is called an n-dimensional array or _ndarray_. ndarray's can hold data of several data types, the most common ones being float64, float32, float16, int64, int32, int16, uint64, uint32, uint16, bool_, etc. For an exhaustive list of basic data types and information on structured data types, please refer the docs (or talk to a TA!).<jupyter_code># MUST. IMPORT. FIRST.
import numpy as np
# Initialization

# create an ndarray of shape (4, 2) and fill it with 0's
foo = np.zeros((4, 2))
fee = np.zeros((4, 2), dtype=np.uint8)    # can also specify the data type of items in ndarray
faa = np.zeros_like(fee)                  # create an ndarray of 0's with shape and dtype same as fee
bar = np.ones((4, 2))                     # init ndarray of 1's

# create an ndarray of shape (4, 2) and fill it with random values 
randfoo = np.random.rand(4, 2)                               # floats selected uniformly from [0, 1)
randfee = np.random.randint(low=-5, high=10, size=(4, 2))    # integers selected uniformly from [-5, 10)

# create an empty ndarray of shape (4, 2) - CAUTION this is unintialized, you will have to initialize it manually some time before use
emparr = np.empty((4, 2))
# Operations

# operands for demo
operand1 = np.random.rand(2, 3)
operand2 = np.random.rand(2, 3)
operand3 = np.random.rand(2, 1)
operand4 = np.random.rand(3, 3)
operand5 = 7

# addition, subtraction - just like scalar variables
res = operand1 + operand2    # both operands should be of same shape
res = operand1 - operand3    # or shape of one should have a "1" where it does not match the shape of other 
res = operand2 + operand5    # or one of them should be a scalar

# elementwise multiplication
res = operand3 * operand5    # multiply each value by the scalar operand5
res = operand1 * operand2
res = np.multiply(operand1, operand2)

# matrix multiplication
res = operand1 @ operand4
res = np.matmul(operand1, operand4)

# transpose (i.e., "flipping dimensions")
resT = res.T
resT = res.transpose()
resT = np.transpose(res)
# reshaping - the product of the dimensions before and after must be the same. in this case, 3 * 2 = 6 * 1

print("shape of res is", res.shape)
res_reshaped = res.reshape(6)
print("shape of res_reshaped is", res_reshaped.shape)
res_reshaped = res.flatten()           # flatten the array (collapse all dimension into 1)
print("shape of res_reshaped is", res_reshaped.shape)
res_reshaped = res.reshape(6, 1)
print("shape of res_reshaped is", res_reshaped.shape)
res_reshaped = res.reshape(3, -1)    # -1 means infer the dimension along that axis
print("shape of res_reshaped is", res_reshaped.shape)
res_reshaped = res.reshape(-1, 2)    # -1 means infer the dimension along that axis
print("shape of res_reshaped is", res_reshaped.shape)
# Commonly used stats - min, max, mean, std

print("min of all elements is", res.min())
print("max values of elements along axis 1 is", res.max(axis=1))
print("mean of all elements is", res.mean())
print("std of elements along axis 0 is", res.std(axis=0))<jupyter_output>min of all elements is 0.46146728761112144
max values of elements along axis 1 is [1.24845258 1.53976143]
mean of all elements is 0.969669283177634
std of elements along axis 0 is [0.09147607 0.14565443 0.12226059]<jupyter_text>MatplotlibOfficial matplotlib.pyplot documentation: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.htmlmodule-matplotlib.pyplotOfficial tutorial: https://matplotlib.org/tutorials/index.htmlHelpful cheat sheet: https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Python_Matplotlib_Cheat_Sheet.pdfThis is the most commonly used library for making graphs/plots. You will mostly be using the pyploy module of this library. The basic object here is called _figure_. Each figure is divided into one or more _subplots_. Graphs are plotte on _axes_.<jupyter_code># MUST. IMPORT. FIRST.
from matplotlib import pyplot as plt
# dummy data to plot
x = [i for i in range(10)]
y = [i**2 for i in x]
# print(x)
# print(y)

# initalize figure
fig = plt.figure()

# add 4 subplots. the argument of add_subplot is row-col-index. i.e. 223 means 2nd row 2nd column figure number 3
fig.add_axes()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)

# draw various plots on the axes
ax1.scatter(x, y)    # scatter plot
ax2.plot(x, y)       # line plot
ax3.bar(x, y)        # bar plot
ax4.hist(y, bins=20) # histogram

# add metadata like title, labels, legends, etc
ax1.set(title='Fig 1', yticks=[0, 20, 40, 60, 80, 100])                   # manually set y ticks
ax2.set(title='Fig 2', xlabel='Days Into Semester', ylabel='Motivation')  # add labels on x and y axes
ax3.set(title='Fig 3')
ax4.set(title='Fig 4')

# display figure
plt.tight_layout()    # to prevent overlapping of subplot titles with axis ticks 
plt.show()            # display figure<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1255593913821762, 'fraction_numerical': 0.04577419767293185, 'mean_word_length': 4.13254593175853, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 9, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '85088', 'license': 'MIT', 'n_tokens_mistral': 2960, 'n_tokens_neox': 2673, 'n_words': 925, 'path': 'discussions/Week1/Week 1 - Python Review.ipynb', 'repo_name': 'AtlasUnion/EC414', 'size': '7821'}