In [1]:
%pylab inline
In [2]:
plot([1,4,3,2,7,3,5])
Out[2]:
In [3]:
plot(rand(100))
Out[3]:
In [4]:
x = linspace(-10,10,300)
In [14]:
x
Out[14]:
In [5]:
l=range(1,10)
In [20]:
l
Out[20]:
In [21]:
l[2]
Out[21]:
In [17]:
l2=range(1,10,2)
In [8]:
l2[2]
Out[8]:
In [18]:
for i in l2:
print(i)
In [10]:
for i in range(4):
print(i)
In [19]:
s = 'Hello, world.'
In [20]:
str(s)
Out[20]:
In [21]:
repr(s)
Out[21]:
In [22]:
str(1/7)
Out[22]:
In [23]:
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print(s)
In [26]:
for i in range(4):
print('The value of i is '+repr(i))
In [27]:
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
# Note use of 'end' on previous line
print(repr(x*x*x).rjust(4))
In [40]:
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
In [45]:
def foo(love):
print(love*5)
foo("s=4")
In [47]:
def formula(conversion,input):
if conversion == "inches_to_centimeters":
input=float(input)
input = input*2.54
elif conversion =="centimeters_to_inches":
input=float(input)
input = input/2.54
elif conversion =="Fahrenheit_to_Celsius":
input=float(input)
input = (input-32)/1.8
elif conversion =="Celsius_to_Fahrenheit":
input=float(input)
input = 32 + (input*1.8)
elif conversion =="bytes_to_kilobytes":
input=float(input)
input=input/1000
elif conversion =="kilobytes_to_bytes":
input=float(input)
input=input/1000
elif conversion =="bytes_to_megabytes":
input=float(input)
input=input/1000000
elif conversion =="megabytes_to_bytes":
input=float(input)
input=input*1000000
return input
formula("Celsius_to_Fahrenheit",30)
Out[47]:
In [49]:
__author__ = 'williamchuang'
import turtle
import re
def setup(col, x, y, w, s, shape):
record.write("DOWN\n")
turtle.up()
turtle.goto(x,y)
turtle.width(w)
turtle.turtlesize(s)
turtle.color(col)
turtle.shape(shape)
turtle.down()
wn.onkey(up, "Up")
wn.onkey(left, "Left")
wn.onkey(right, "Right")
wn.onkey(back, "Down")
wn.onkey(quitTurtles, "Q")
wn.onkey(quitTurtles, "q")
wn.onkey(quitTurtles, "Escape")
wn.listen()
wn.mainloop()
#Event handlers
def up():
x=turtle.xcor()
y=turtle.ycor()
turtle.fd(5)
record.write(str(x)+" "+str(y)+"\n")
def left():
turtle.lt(5)
x=turtle.xcor()
y=turtle.ycor()
record.write(str(x)+" "+str(y)+"\n")
def right():
turtle.rt(5)
x=turtle.xcor()
y=turtle.ycor()
record.write(str(x)+" "+str(y)+"\n")
def back():
turtle.bk(5)
x=turtle.xcor()
y=turtle.ycor()
record.write(str(x)+" "+str(y)+"\n")
def quitTurtles():
wn.bye()
record=open("record.txt","a")
record.close()
wn = turtle.Screen()
wn.setworldcoordinates(-300, -300, 300, 300)
record=open("record.txt","a")
setup("blue",0,0,2,2,"turtle")
In [1]:
def plotRegression(data):
import turtle
wn = turtle.Screen()
t = turtle.Turtle()
t.speed(1)
lit=[]
x_lst=[]
y_lst=[]
# Set up our variables for the formula.
for i in data:
lit+=i.split()
x_lst.append(float(lit[0].strip()))
y_lst.append(float(lit[1].strip()))
lit=[]
print(x_lst)
print(y_lst)
x_sum=0
for j in x_lst:
x_sum+=float(j)
x_mean=(x_sum/len(x_lst))
y_sum=0
for j in y_lst:
y_sum+=float(j)
y_mean=(y_sum/len(y_lst))
xysum=0
for k in range(len(x_lst)):
xysum+=(float(x_lst[k])*float(y_lst[k]))
xsquaresum=0
for l in range(len(x_lst)):
xsquaresum+=(float(x_lst[l])*float(x_lst[l]))
m=(xysum-len(x_lst)*x_mean*y_mean)/(xsquaresum-len(x_lst)*x_mean*x_mean)
ymin=y_mean+m*(float(min(x_lst))-x_mean)
ymax=y_mean+m*(float(max(x_lst))-x_mean)
# Get min and max values for coordinate system.
x_min, x_max, y_min, y_max = float(min(x_lst)), float(max(x_lst)), float(min(y_lst)), float(max(y_lst))
#print(x_min, x_max, y_min, y_max)
# Add 10 points on each line to be safe.
wn.setworldcoordinates(x_min-10,y_min-10,x_max+10,y_max+10)
#t.pensize(5)
t.up()
for i in range(len(x_lst)):
#t.down()
t.setpos(float(x_lst[i]), float(y_lst[i]))
t.dot()
t.up()
t.goto(float(min(x_lst)),ymin)
t.down()
t.goto(float(max(x_lst)),ymax)
wn.exitonclick()
data=open("labdata.txt","r")
plotRegression(data)
data.close()
In [7]:
fo = open("labdata.txt", "r")
print("Name of the file: ", fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print("Read Line: %s" % (line))
line = fo.readline()
print("Read Line: %s" % (line))
line = fo.readline()
print("Read Line: %s" % (line))
# Close opend file
fo.close()
In [11]:
class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
return str(self.cargo)
In [12]:
left = Tree(2)
right = Tree(3)
In [13]:
tree = Tree(1, left, right)
In [11]:
tree = Tree(1, Tree(2), Tree(3))
In [12]:
def total(tree):
if tree == None: return 0
return total(tree.left) + total(tree.right) + tree.cargo
In [14]:
tree = Tree("+", Tree(1), Tree("*", Tree(2), Tree(3)))
In [15]:
def printTree(tree):
if tree == None: return
print(tree.cargo)
printTree(tree.left)
printTree(tree.right)
In [16]:
printTree(tree)
In [21]:
def multadd (x, y, z):
return x * y + z
In [22]:
multadd (3, 2, 1)
Out[22]:
In [42]:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return '(' + str(self.x) + ',' + str(self.y) + ')'
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __mul__(self, other):
return self.x * other.x + self.y * other.y
def __rmul__(self, other):
return Point(other * self.x, other * self.y)
def reverse(self):
self.x , self.y = self.y, self.x
p1 = Point(3, 4)
p2 = Point(5, 7)
p3 = p1 + p2
p = Point(3, 4)
print(p3)
print(p1 * p2)
print(2 * p2)
str(p)
print(multadd (2, p1, p2))
print(multadd (p1, p2, 1))
In [40]:
def frontAndBack(front):
import copy
back = copy.copy(front)
back.reverse()
print(str(front) + str(back))
myList = [1, 2, 3, 4]
frontAndBack(myList)
In [43]:
p = Point(3, 4)
frontAndBack(p)
In [44]:
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
In [45]:
tel
Out[45]:
In [16]:
del tel['sape']
tel['irv'] = 4127
tel
In [47]:
list(tel.keys())
Out[47]:
In [48]:
sorted(tel.keys())
Out[48]:
In [49]:
'guido' in tel
Out[49]:
In [50]:
'jack' not in tel
Out[50]:
In [51]:
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
In [53]:
for k, v in knights.items():
print(k, v)
In [55]:
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
In [97]:
class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
def print_backward(self):
if self.next != None:
tail = self.next
tail.print_backward()
print(self.cargo, end=' ')
In [66]:
node = Node("test")
print(node)
In [90]:
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node2.next = node3
In [88]:
def print_list(node):
while node != None:
print(node, end=' ')
node = node.next
print()
In [91]:
print_list(node1)
In [92]:
def print_backward(list):
if list == None: return
head = list
tail = list.next
print_backward(tail)
print(head,end=' ')
In [93]:
print_backward(node1)
In [94]:
def removeSecond(list):
if list == None: return
first = list
second = list.next
# make the first node refer to the third
first.next = second.next
# separate the second node from the rest of the list second.next = None
return second
In [95]:
removed = removeSecond(node1)
print_list(removed)
In [96]:
print_list(node1)
In [98]:
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
def print_backward(self):
print("[", end=' ')
if self.head != None:
self.head.print_backward()
print("]", end=' ')
def addFirst(self, cargo):
node = Node(cargo)
node.next = self.head
self.head = node
self.length = self.length + 1
In [99]:
class Stack :
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return (self.items == [])
s = Stack()
s.push(54)
s.push(45)
s.push("+")
In [100]:
while not s.is_empty():
print(s.pop(), end=' ')
In [101]:
import string
"Now is the time".split(" ")
Out[101]:
In [15]:
import re
re.split("([^0-9])", "123+456*/")
Out[15]:
In [108]:
#In this code:
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print(self.x + ' ' + foo)
#... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically, as in ...
a = A() # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument
#The __init__ method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters (e.g., A(24, 'Hello')) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.
In [14]:
import numpy
import gzip
import six.moves.cPickle
# Load the dataset
f = gzip.open('mnist.pkl', 'rb')
train_set, valid_set, test_set = cPickle.load(f)
f.close()
In [ ]: