Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

IPython notebook Utah_Workshop/Utah_Notebooks/01-Intro-to-Python/Lesson_02_MorePython-student.ipynb

12 views
Kernel: Unknown Kernel

Looping through your list

make a new list of stuff

  • your name

  • favorite fruit

  • favorite number

  • favorite animal

  • number of siblings

  • favorite musician

eg. mybag = ['cindee', 'blueberry', 13, 'cat', 1, 'Lorde']

mybag = ["black apple", "Danny", "Pops","Smurfette", 2134567890876543213456789] print mybag
['black apple', 'Danny', 'Pops', 'Smurfette', 2134567890876543213456789L]

I want to refer to each item in my bag and tell you what it is

to do this I use a for loop

There are two important parts:

  • : colon at the end of the line

  • indent so python knows this is the activity at each pass

for thing in mybag: print thing
# thing is just a temporary variable , holding one of the items for a short time

#Asking questions about things in our bag ##Sometimes we want to check the things in our bag

  • is my name in the bag? (what about misspelling?)

  • is there a cat in mybag?

for i, thing in enumerate(mybag): print i,thing
0 black apple 1 Danny 2 Pops 3 Smurfette 4 2134567890876543213456789
# I can check if something specific is in my bag

Booleans?

True and False are a special type of object called Booleans

True and False are used in comparisons.

isinstance

We can use a special function called isinstance, to check if something is a string or a number

  • for strings use: str (short for string)

  • for numbers use: int (short for integer)

type("wendy")
# finding a type type(3)

Exercise

See if the third thing in your bag is a number

isinstance(3, int)
True
a = 1 b = a b==a
True

Lets combine looping, and questions

  • We can loop through the things in our bag

  • Check if the thing is a string (use isinstance and str to make this comparison)

  • print the thing if it is a string

for thing in mybag: print thing, 'is an int?',isinstance (thing, int)
black apple is an int? False Danny is an int? False Pops is an int? False Smurfette is an int? False 2134567890876543213456789 is an int? False

Multiple Dimensions

##What if we combined everyones bag into one bigbag?

So

##How do I access all the favorite animals?

mean = 2 mean=[]
# I wished that worked, now what do I do?

#import and arrays

import

Python comes with a bunch of cool tools, but sometimes I need other tools (like above)

To get access to these tools I need to import them into my Python workspace

##arrays

  • One set of tools comes in a package called numpy

  • Numpy is used in data science all the time, because it allows us to easily work with lists of lists efficiently.

  • These objects are called arrays

Import numpy to use arrays

  • lets import numpy

  • we can even give it an alias or nickname

import numpy import numpy as np
# np.asarray arr = np. asarray(mybag)
#print bigbag arr.dtype
dtype('S25')
ones = np.arange(25) ones.shape = (5,5)
ones
ones [1:,3]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-2-792c3430596c> in <module>() ----> 1 ones [1:,3] TypeError: 'function' object has no attribute '__getitem__'

Images as Arrays

Now that you have exposure to arrays, lets think about how a two-dimensional array can introduce us to image processing.

Many images you see on the web are just arrays of color values, but at such a low resolution, it blends together into a smoth image.

Mona Lisa

Consider the images below.

  • One looks like the painting

  • The other looks like an array of colors

  • Squint your eyes, how does this impact the image on the right?

ones
array([[ 1., 1., 1.], [ 1., 1., 1.]])

When we look into face detection, I want you to think of all the images as arrays of colors.

#Visualizing multiple dimensions using ipythonblocks

Our next session will help us get better acquianted with thinking about indexing into arrays and images as arrays. ##ipythonblocks ipython blocks allow us to understand this complex structure of multidimensional objects a little more easily

Lets create a simple set of blocks that has 4 rows and 4 columns

Colors

Colors are represented as RGB triplets

  • each value can range from 0 -> 255

  • 0 is black

  • 255 is a fully saturated color

from ipythonblocks import BlockGrid # define some colors (R, G, B) or (red, green, blue) black = (0, 0, 0) violet = (132, 23 , 54) orange = (255, 123, 34) red = (255, 51, 51) yellow = (255, 255 , 0) blue = (51, 51, 255) green = (51, 255, 51) indigo =(102, 0, 204) # make a black grid blocks = BlockGrid(10,10, fill=black) blocks[0,1:9] = red blocks[1:,0] = red blocks[1:,9] = red blocks[1,1:9] = orange blocks[2,1:9] = yellow blocks[3,1:9]= green blocks [4,1:9] = blue blocks [5,1:9] = indigo blocks [6,1:9] = violet blocks [7,1] = red blocks [7,2] = orange blocks [7,3] = yellow blocks [7,4] = green blocks [7,5] = blue blocks [7,6] = indigo blocks [7,7] = violet blocks [7,8] = red blocks [8,1] =red blocks [8,2] = orange blocks [8,3] = yellow blocks [8,4] = green blocks [8,5] = blue blocks [8,6] = indigo blocks [8,7] = violet blocks [8,8] = red blocks [9,1] = red blocks [9,2] = violet blocks [9,3] =indigo blocks [9,4] = blue blocks [9,5] = green blocks [9,6] = yellow blocks [9,7] = orange blocks [9,8] = red # show the grid blocks
# Once you have created the block # use your mouse to hover over each block, what does it tell you?
blocks = BlockGrid(4,4) previous_block = None for block in blocks.animate(0.8): block.rgb=red if previous_block: previous_block.rgb = black previous_block = block
# we can make a whole column red blocks = BlockGrid(4,4, fill=black) blocks[:,2] = red blocks

###Exercise:

  • Can you make the blocks and make the whole 2nd row red and everything else black?

  • what other shapes can you come up with?

Advanced

Using math to generate images.

from ipythonblocks import BlockGrid import math math.fabs?
w = 20 # width of grid h = 20 # height of grid r = 3 # minor radius (size of inner ring) grid = BlockGrid(w, h, block_size=8)

Equation for Torus

  • c = radius form center of hole to center of torus tube

  • a = radius of the tube

  • x = x coordinate

  • y = y coordinate

ParseError: KaTeX parse error: {align} can be used only in display mode.

## Lets Draw the Torus for block in grid: # Color value is set by location on the torus val = math.fabs(math.sqrt((w / 2. - block.col) ** 2 + (h / 2. - block.row) ** 2) - r) ** 2 / r * 255 #print block.row, block.col, val block.red = val block.green = val block.blue = val print grid
BlockGrid Shape: (20, 20)
grid

Can you manipulate the parameters to change the torus?