Sunday, February 11, 2018

PY EX from ZS 26-39, map, reduce, datastructures, numpy

26-39 of ZS, DataStructures, Sequences & MapReduce, NumPy
In [7]:
#EX from 25 ZS#

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
     """Sorts the words."""
     return sorted(words)

def print_first_word(words):
     """Prints the first word after popping it off."""
     word = words.pop(0)
     print word

def print_last_word(words):
     """Prints the last word after popping it off."""
     word = words.pop(-1)
     print word

def sort_sentence(sentence):
     """Takes in a full sentence and returns the sorted words."""
     words = break_words(sentence)
     return sort_words(words)

def print_first_and_last(sentence):
     """Prints the first and last words of the sentence."""
     words = break_words(sentence)
     print_first_word(words)
     print_last_word(words)

def print_first_and_last_sorted(sentence):
     """Sorts the words then prints the first and last one."""
     words = sort_sentence(sentence)
     print_first_word(words)
     print_last_word(words)
In [8]:
#EX from 25 ZS#

print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print "--------------"
print poem
print "--------------"

five = 10 - 2 + 3 - 6
print "This should be five: %s" % five

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
beans, jars, crates = secret_formula(start_point)

print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)

start_point = start_point / 10

print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates."
Let's practice everything.
You'd need to know 'bout escapes with \ that do 
 newlines and   tabs.
--------------

 The lovely world
with logic so firmly planted
cannot discern 
 the needs of love
nor comprehend passion from intuition
and requires an explanation

  where there is none.

--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have %d beans, %d jars, and %d crates.
In [9]:
#EX from 25 ZS#

def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78,4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)


 # A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"
Let's do some math with just functions!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That becomes:  -4391 Can you do it by hand?
In [11]:
#EX from 20 ZS#

from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tape."

rewind(current_file)

print "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-ba335d262e77> in <module>()
     14     print line_count, f.readline()
     15 
---> 16 current_file = open(input_file)
     17 
     18 print "First let's print the whole file:\n"

NameError: name 'input_file' is not defined
In [12]:
#EX from 19 ZS#

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print "You have %d cheeses!" % cheese_count
    print "You have %d boxes of crackers!" % boxes_of_crackers
    print "Man that's enough for a party!"
    print "Get a blanket.\n"


print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)


print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese, amount_of_crackers)


print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)


print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.

OR, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.

We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.

And we can combine the two, variables and math:
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.

In [13]:
#EX from 18 ZS#

# this one is like your scripts with argv
def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
    print "arg1: %r, arg2: %r" % (arg1, arg2)

 # this just takes one argument
def print_one(arg1):
    print "arg1: %r" % arg1

# this one takes no arguments
def print_none():
    print "I got nothin'."


print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg1: 'First!'
I got nothin'.
In [5]:
#EX 28#
print True and True
print False and True
print 1 == 1 and 2 == 1
print "test" == "test"
print 1 == 1 or 2 != 1
print True and 1 == 1
print False and 0 != 0
print True or 1 == 1
print "test" == "testing"
print 1 != 0 and 2 == 1
print "test" != "testing"
print "test" == 1
print not (True and False)
print not (1 == 1 and 0 != 1)
print not (10 == 1 or 1000 == 1000)
print not (1 != 10 or 3 == 4)
print not ("testing" == "testing" and "Zed" == "Cool Guy")
print 1 == 1 and not ("testing" == 1 or 1 == 0)
print "chunky" == "bacon" and not (3 == 4 or 3 == 3)
print 3 == 3 and not ("testing" == "testing" or "Python" == "Fun")
True
False
False
True
True
True
False
True
False
False
True
False
True
False
False
False
True
True
False
False
In [6]:
#EX 29#

people = 20
cats = 30
dogs = 15


if people < cats:
    print "Too many cats! The world is doomed!"

if people > cats:
    print "Not many cats! The world is saved!"

if people < dogs:
    print "The world is drooled on!"

if people > dogs:
    print "The world is dry!"


dogs += 5

if people >= dogs:
    print "People are greater than equal to dogs."

if people <= dogs:
    print "People are less than equal to dogs."

if people == dogs:
    print "People are dogs."
Too many cats! The world is doomed!
The world is dry!
People are greater than equal to dogs.
People are less than equal to dogs.
People are dogs.
In [7]:
#EX 30#

people = 30
cars = 40
buses = 15

if cars > people:
    print "We should take the cars."
elif cars < people:
    print "We should not take the cars."
else:
    print "We can't decide."

if buses > cars:
    print "That's too many buses."
elif buses < cars:
    print "Maybe we could take the buses."
else:
    print "We still can't decide."

if people > buses:
    print "Alright, let's just take the buses."
else:
    print "Fine, let's stay home then."
We should take the cars.
Maybe we could take the buses.
Alright, let's just take the buses.
In [9]:
#EX 31#

print "You enter a dark room with two doors. Do you go through door #1 or door #2?"

door = raw_input("> ")

if door == "1":
    print "There's a giant bear here eating a cheese cake. What do you do?"
    print "1. Take the cake."
    print "2. Scream at the bear."

    bear = raw_input("> ")

    if bear == "1":
        print "The bear eats your face off. Good job!"
    elif bear == "2":
        print "The bear eats your legs off. Good job!"
    else:
        print "Well, doing %s is probably better. Bear runs away." % bear

elif door == "2":
    print "You stare into the endless abyss at Cthuhlu's retina."
    print "1. Blueberries."
    print "2. Yellow jacket clothespins."
    print "3. Understanding revolvers yelling melodies."

    insanity = raw_input("> ")

    if insanity == "1" or insanity == "2":
        print "Your body survives powered by a mind of jello. Good job!"
    else:
        print "The insanity rots your eyes into a pool of muck. Good job!"

else:
    print "You stumble around and fall on a knife and die. Good job!"
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake. What do you do?
1. Take the cake.
2. Scream at the bear.
> 1
The bear eats your face off. Good job!
In [11]:
#EX 32#

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list
for number in the_count:
    print "This is count %d" % number

# same as above
for fruit in fruits:
    print "A fruit of type: %s" % fruit

# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
    print "I got %r" % i
    
# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 20 counts
for i in range(0, 6):
    print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)

# now we can print them out too
for i in elements:
    print "Element was: %d" % i
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got 'pennies'
I got 2
I got 'dimes'
I got 3
I got 'quarters'
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Element was: 5
In [13]:
#EX 33#
i = 0
numbers = []

while i < 6:
    print "At the top i is %d" % i
    numbers.append(i)

    i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i


print "The numbers: "

for num in numbers:
    print num
 At the top i is 0
Numbers now:  [0]
At the bottom i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers: 
0
1
2
3
4
5
In [ ]:
#EX 35#

from sys import exit

def gold_room():
    print "This room is full of gold. How much do you take?"

    next = raw_input("> ")
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("You greedy bastard!")


def bear_room():
    print "There is a bear here."
    print "The bear has a bunch of honey."
    print "The fat bear is in front of another door."
    print "How are you going to move the bear?"
    bear_moved = False

while True:
    next = raw_input("> ")

    if next == "take honey":
        dead("The bear looks at you then pimp slaps your face off.")
    elif next == "taunt bear" and not bear_moved:
        print "The bear has moved from the door. You can go through it now."
        bear_moved = True
    elif next == "taunt bear" and bear_moved:
        dead("The bear gets pissed off and chews your crotch off.")
    elif next == "open door" and bear_moved:
        gold_room()
    else:
        print "I got no idea what that means."


def cthulu_room():
    print "Here you see the great evil Cthulu."

    print "He, it, whatever stares at you and you go insane."
    print "Do you flee for your life or eat your head?"

    next = raw_input("> ")

    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!")
    else:
        cthulu_room()

def dead(why):
    print why, "Good job!"
    exit(0)

def start():
    print "You are in a dark room."
    print "There is a door to your right and left."
    print "Which one do you take?"

    next = raw_input("> ")

    if next == "left":
        bear_room()
    elif next == "right":
        cthulu_room()
    else:
        dead("You stumble around the room until you starve.")


start()
In [17]:
#EX 39#

ten_things = "Apples Oranges Crows Telephone Light Sugar"

print "Wait there's not 10 things in that list, let's fix that."

stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]

while len(stuff) != 10:
    next_one = more_stuff.pop()
    print "Adding: ", next_one
    stuff.append(next_one)
    print "There's %d items now." % len(stuff)

print "There we go: ", stuff

print "Let's do some things with stuff."

print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar!
Wait there's not 10 things in that list, let's fix that.
Adding:  Boy
There's 7 items now.
Adding:  Girl
There's 8 items now.
Adding:  Banana
There's 9 items now.
Adding:  Corn
There's 10 items now.
There we go:  ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephone Light Sugar Boy Girl Banana
Telephone#Light
In [18]:
#Filter function#

print("Filter Functions ................................")

pList1 = list(range(1,10))
print(pList1)

def pEven(x) : return x%2 == 0
pList2 = list(filter(pEven,pList1))
print(pList2)

pList3 = ["Ram", "RamPM", "Shyam", "PMShyam", "Sita", "SiPMMta"]
print(pList3)

def hasPM(x) : return "PM" in x
pList4 = list(filter(hasPM, pList3))
print(pList4)
Filter Functions ................................
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8]
['Ram', 'RamPM', 'Shyam', 'PMShyam', 'Sita', 'SiPMMta']
['RamPM', 'PMShyam', 'SiPMMta']
In [19]:
# Lambda functions#
print("Lambda Functions ................................")

pList2a = list(filter (lambda x : x%2 == 0, pList1))
print(pList2a)

pList4a = list(filter(lambda x: "PM" in x, pList3))
print(pList4a)
Lambda Functions ................................
[2, 4, 6, 8]
['RamPM', 'PMShyam', 'SiPMMta']
In [20]:
# Map
print("Map Functions ................................")

pList5 = list(map(lambda x : x*x, pList1))            # square each number in the list
print(pList5)

pList6 = list(map(lambda x : "Y"+x, pList3))          # appends the char Y to each string in the list
print(pList6)

pList7 = map(lambda x : len(x), pList3)         # returns the number of characters in each string of the list
print(pList7)

pList8 = map(lambda x : (x, len(x)),pList3)     # returns a list of tuples
print(pList8)
Map Functions ................................
[1, 4, 9, 16, 25, 36, 49, 64, 81]
['YRam', 'YRamPM', 'YShyam', 'YPMShyam', 'YSita', 'YSiPMMta']
[3, 5, 5, 7, 4, 7]
[('Ram', 3), ('RamPM', 5), ('Shyam', 5), ('PMShyam', 7), ('Sita', 4), ('SiPMMta', 7)]
In [21]:
# Reduce
print("Reduce Functions ................................")

import functools
pVal1 = functools.reduce(lambda x,y: x+y, pList1)         #   adding the numbers in a list
print(pVal1)

pVal2 = functools.reduce(lambda x,y: x+y, pList3)         # concatenating string in a list
print(pVal2)

pVal3 = functools.reduce(lambda x,y: (x[0]+y[0], x[1]+y[1]), pList8)  #   adding and concatenating elements in a list
print(pVal3)
Reduce Functions ................................
45
RamRamPMShyamPMShyamSitaSiPMMta
('RamRamPMShyamPMShyamSitaSiPMMta', 31)
In [22]:
#DS 1

pInt = 2
pReal = 2.318281828
pString = "some Test String"
pList2 = [ pInt, pReal, pString, pList1]
print(pList2)
[2, 2.318281828, 'some Test String', [1, 2, 3, 4, 5, 6, 7, 8, 9]]
In [23]:
#DS 2

print("Members ---------------------")

print(pList2[0])
print(pList2[1])
print(pList2[2])
print(pList2[3])

print(pList2[3][0])
print(pList2[3][1])
Members ---------------------
2
2.318281828
some Test String
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1
2
In [24]:
#DS 3

print("Methods ---------------------")

pList1.append(pInt)
print(pList1)
pList1.insert(1,pReal)
print(pList1)
pList1.remove(pReal)
print(pList1)
pList1.extend(pList2)
print(pList1)
Methods ---------------------
[1, 2, 3, 4, 5, 6, 7, 8, 9, 2]
[1, 2.318281828, 2, 3, 4, 5, 6, 7, 8, 9, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 2, 2.318281828, 'some Test String', [...]]
In [25]:
#DS 4

print("More Methods ---------------------")

print(pList1.count("some Test String"), pList1.count(pInt))
print(pList1.index(pInt), pList1.index("some Test String"))
pList1.reverse()
print(pList1)
pList1.sort()
print(pList1)
More Methods ---------------------
(1, 3)
(1, 12)
[[...], 'some Test String', 2.318281828, 2, 2, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 2, 2, 2.318281828, 3, 4, 5, 6, 7, 8, 9, [...], 'some Test String']
In [26]:
#DS 5

# List as Stack

print("Stack ---------------------")

pStack1 = [12, 20, 7]
pStack1.append(45)
print(pStack1)
pPopped = pStack1.pop()
print(pPopped, pStack1)
Stack ---------------------
[12, 20, 7, 45]
(45, [12, 20, 7])
In [27]:
#DS 6

# List as Q

print("Q ---------------------")

from collections import deque 
pList3 = ["Ram", "Shyam", "Jadu"]
pQ = deque(["Ram", "Shyam", "Jadu"])
a = pQ.popleft()
print(a)
print(pQ)
pQ.append("Sita")
print(pQ)
Q ---------------------
Ram
deque(['Shyam', 'Jadu'])
deque(['Shyam', 'Jadu', 'Sita'])
In [28]:
#DS 7

# Sets

print("Sets ---------------------")

pList10 = ["Apple", "Orange", "Pear", "Mango", "Apple", "Orange", "Pineapple"]
print(pList10)

pSet = set(pList10)
print(pSet)
Sets ---------------------
['Apple', 'Orange', 'Pear', 'Mango', 'Apple', 'Orange', 'Pineapple']
set(['Orange', 'Mango', 'Pear', 'Apple', 'Pineapple'])
In [29]:
#DS 8

# Tuples

print("Tuples ---------------------")

pTuple1 = 1, 34, "king", "queen"
print(pTuple1)
print(pTuple1[0], pTuple1[3])
pTuple2 = 23, "new fellow", pTuple1
print(pTuple2)
Tuples ---------------------
(1, 34, 'king', 'queen')
(1, 'queen')
(23, 'new fellow', (1, 34, 'king', 'queen'))
In [30]:
#DS 9

# Dictionaries

print("Dictionaries ---------------------")

dTel = { "prithwis": 2066, "charan" : 8077, "govind" : 9234, "jaydeep" : 9324}
print(dTel)
print(dTel.keys())
print(dTel.values())
dTel['SDG'] = 9056
print(dTel)
dTel['prithwis'] = 6602
print(dTel)
print("prithwis" in dTel)
print("Prithwis" in dTel)
Dictionaries ---------------------
{'jaydeep': 9324, 'prithwis': 2066, 'govind': 9234, 'charan': 8077}
['jaydeep', 'prithwis', 'govind', 'charan']
[9324, 2066, 9234, 8077]
{'jaydeep': 9324, 'prithwis': 2066, 'SDG': 9056, 'govind': 9234, 'charan': 8077}
{'jaydeep': 9324, 'prithwis': 6602, 'SDG': 9056, 'govind': 9234, 'charan': 8077}
True
False
In [31]:
#DS 10

# Looping

print("Looping ..........................")

for key, val in dTel.items():
    print (key, val)
Looping ..........................
('jaydeep', 9324)
('prithwis', 6602)
('SDG', 9056)
('govind', 9234)
('charan', 8077)
In [32]:
#DS 11

print("Enumerate ..........................")

for ix, val in enumerate(pList1):
    print (ix,val)
    
for ix, val in enumerate(pTuple1):
    print (ix,val)
    
for ix, val in enumerate(dTel):
    print (ix,val)
Enumerate ..........................
(0, 1)
(1, 2)
(2, 2)
(3, 2)
(4, 2.318281828)
(5, 3)
(6, 4)
(7, 5)
(8, 6)
(9, 7)
(10, 8)
(11, 9)
(12, [1, 2, 2, 2, 2.318281828, 3, 4, 5, 6, 7, 8, 9, [...], 'some Test String'])
(13, 'some Test String')
(0, 1)
(1, 34)
(2, 'king')
(3, 'queen')
(0, 'jaydeep')
(1, 'prithwis')
(2, 'SDG')
(3, 'govind')
(4, 'charan')
In [33]:
#DS 12
print("Zip ..........................")

teachers = ["prithwis","charan","jaydeep","subhasis"]
subjects = ["bigdata", "communications", "stats", "datamining"]

for t,s in zip(teachers,subjects):
    print(t," teaches ",s)
Zip ..........................
('prithwis', ' teaches ', 'bigdata')
('charan', ' teaches ', 'communications')
('jaydeep', ' teaches ', 'stats')
('subhasis', ' teaches ', 'datamining')
In [34]:
#DS 13

# Membership

print(pInt in pList2)
print(2 in pList2)
print(33  not in pList2)

fruit1 = ["apple", "pear", "orange", "mango"]
fruit2 = ["apple", "grape", "banana","mango"]

print("pear" in fruit1)
print("pear" in fruit2)
print (set(fruit1).intersection(fruit2))
print (set(fruit1).union(fruit2))
True
True
True
True
False
set(['mango', 'apple'])
set(['grape', 'apple', 'pear', 'mango', 'orange', 'banana'])
In [39]:
#numpy

import numpy as np

a = np.arange(15).reshape(3, 5)
print a
print a.shape
print a.ndim
print a.dtype.name
print a.size
print a.itemsize
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
(3, 5)
2
int64
15
8
In [40]:
b = np.array([1.2, 3.4, 5.1])

print b.dtype
float64
In [42]:
b = np.array([(1,2), (8,9)], dtype = complex)
b
Out[42]:
array([[ 1.+0.j,  2.+0.j],
       [ 8.+0.j,  9.+0.j]])
In [43]:
a = np.zeros((3,4))
b = np.ones((5,6))
c = np.empty((2,2))

print a
print b
print c
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]
[[ 1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.]]
[[ 0.  0.]
 [ 0.  0.]]
In [44]:
a = np.arange(10,20,2)
print a
[10 12 14 16 18]
In [49]:
from numpy import pi
import matplotlib.pyplot as plt
%matplotlib inline

a = np.linspace(0,2*pi,100)
b = np.sin(a)

plt.plot(a, b)
Out[49]:
[<matplotlib.lines.Line2D at 0x7fd2609bbd90>]
In [54]:
a = np.arange(20).reshape(4,5)
b = np.arange(20).reshape(5,4)

a<15
Out[54]:
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [False, False, False, False, False]], dtype=bool)
In [58]:
A = np.array( [[1,1],[0,1]] )
B = np.array( [[2,0],[3,4]] )

print A*B
print np.cross(A, B)
print np.dot(A, B)
[[2 0]
 [0 4]]
[-2 -3]
[[5 4]
 [3 4]]
In [60]:
a = np.ones((2,3), dtype=int)
b = np.random.random((2,3))
a *= 3
print a
[[3 3 3]
 [3 3 3]]
In [65]:
a = np.random.random((2, 3))
print a
print a.min()
print a.max()
print a.mean()
[[ 0.31454163  0.39223899  0.862532  ]
 [ 0.90714677  0.04767701  0.83792565]]
0.0476770086603
0.907146772735
0.560343674073
In [67]:
b = np.arange(12).reshape(3,4)
print b
print b.sum(axis=0)                            # sum of each column
print b.min(axis=1)                            # min of each row
print b.cumsum(axis=1)                         # cumulative sum along each row
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[12 15 18 21]
[0 4 8]
[[ 0  1  3  6]
 [ 4  9 15 22]
 [ 8 17 27 38]]
In [69]:
B = np.arange(3)
C = np.array([2., -1., 4.])

print np.exp(B)
print np.sqrt(B)
print np.add(B, C)
[ 1.          2.71828183  7.3890561 ]
[ 0.          1.          1.41421356]
[ 2.  0.  6.]
In [78]:
a = np.arange(10)**3

print a
print a[2:5]
print a[1:7:2]
print a[::-1]

for i in a:
    print (i**(1/3))
[  0   1   8  27  64 125 216 343 512 729]
[ 8 27 64]
[  1  27 125]
[729 512 343 216 125  64  27   8   1   0]
1
1
1
1
1
1
1
1
1
1
In [87]:
def f(x,y):
        return 10*x+y

b = np.fromfunction(f,(5,4),dtype=int)
print b

print b[:, 2]
print b[:3, :]

for row in b:
    print row
    
for element in b.flat:
    print element
[[ 0  1  2  3]
 [10 11 12 13]
 [20 21 22 23]
 [30 31 32 33]
 [40 41 42 43]]
[ 2 12 22 32 42]
[[ 0  1  2  3]
 [10 11 12 13]
 [20 21 22 23]]
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43
In [99]:
a = np.floor(10*np.random.random((3,4)))
print a
print a.shape
print a.ravel()
print a.reshape(6,2)
print a.T
print a.T.shape
[[ 9.  1.  0.  1.]
 [ 1.  6.  6.  6.]
 [ 0.  8.  6.  5.]]
(3, 4)
[ 9.  1.  0.  1.  1.  6.  6.  6.  0.  8.  6.  5.]
[[ 9.  1.]
 [ 0.  1.]
 [ 1.  6.]
 [ 6.  6.]
 [ 0.  8.]
 [ 6.  5.]]
[[ 9.  1.  0.]
 [ 1.  6.  8.]
 [ 0.  6.  6.]
 [ 1.  6.  5.]]
(4, 3)
In [100]:
a = np.floor(10*np.random.random((2,2)))
print a
b = np.floor(10*np.random.random((2,2)))
print b
print np.vstack((a,b))
print np.hstack((a,b))
[[ 7.  3.]
 [ 3.  1.]]
[[ 9.  7.]
 [ 0.  1.]]
[[ 7.  3.]
 [ 3.  1.]
 [ 9.  7.]
 [ 0.  1.]]
[[ 7.  3.  9.  7.]
 [ 3.  1.  0.  1.]]
In [103]:
from numpy import newaxis
print np.column_stack((a,b))   # With 2D arrays


a = np.array([4.,2.])
b = np.array([2.,8.])

print a[:,newaxis]  # This allows to have a 2D columns vector
print np.column_stack((a[:,newaxis],b[:,newaxis]))
print np.vstack((a[:,newaxis],b[:,newaxis]))
[[ 4.  2.]
 [ 2.  8.]]
[[ 4.]
 [ 2.]]
[[ 4.  2.]
 [ 2.  8.]]
[[ 4.]
 [ 2.]
 [ 2.]
 [ 8.]]
In [104]:
a = np.floor(10*np.random.random((2,12)))
print a
print np.hsplit(a,3)   
print np.hsplit(a,(3,4))
[[ 4.  7.  0.  8.  6.  6.  5.  9.  4.  3.  0.  5.]
 [ 2.  3.  6.  0.  1.  6.  4.  6.  7.  5.  7.  4.]]
[array([[ 4.,  7.,  0.,  8.],
       [ 2.,  3.,  6.,  0.]]), array([[ 6.,  6.,  5.,  9.],
       [ 1.,  6.,  4.,  6.]]), array([[ 4.,  3.,  0.,  5.],
       [ 7.,  5.,  7.,  4.]])]
[array([[ 4.,  7.,  0.],
       [ 2.,  3.,  6.]]), array([[ 8.],
       [ 0.]]), array([[ 6.,  6.,  5.,  9.,  4.,  3.,  0.,  5.],
       [ 1.,  6.,  4.,  6.,  7.,  5.,  7.,  4.]])]
In [105]:
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot( h,w, maxit=20 ):
    """Returns an image of the Mandelbrot fractal of size (h,w)."""
    y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
    c = x+y*1j
    z = c
    divtime = maxit + np.zeros(z.shape, dtype=int)

    for i in range(maxit):
        z = z**2 + c
        diverge = z*np.conj(z) > 2**2            # who is diverging
        div_now = diverge & (divtime==maxit)  # who is diverging now
        divtime[div_now] = i                  # note when
        z[diverge] = 2                        # avoid diverging too much

    return divtime
plt.imshow(mandelbrot(400,400))
plt.show()
In [106]:
import numpy as np
a = np.array([[1.0, 2.0], [3.0, 4.0]])
print(a)



a.transpose()



np.linalg.inv(a)



u = np.eye(2) # unit 2x2 matrix; "eye" represents "I"
u


j = np.array([[0.0, -1.0], [1.0, 0.0]])

np.dot (j, j) # matrix product



np.trace(u)  # trace


y = np.array([[5.], [7.]])
np.linalg.solve(a, y)



np.linalg.eig(j)
[[ 1.  2.]
 [ 3.  4.]]
Out[106]:
(array([ 0.+1.j,  0.-1.j]),
 array([[ 0.70710678+0.j        ,  0.70710678-0.j        ],
        [ 0.00000000-0.70710678j,  0.00000000+0.70710678j]]))
In [107]:
import numpy as np
import matplotlib.pyplot as plt
# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2
mu, sigma = 2, 0.5
v = np.random.normal(mu,sigma,10000)
# Plot a normalized histogram with 50 bins
plt.hist(v, bins=50, normed=1)       # matplotlib version (plot)
plt.show()
In [ ]: