
#lec11.py

2+4

6

(2+5) * (3-5)

-14

#Float Expressions:

2.7 + 4.5

(2 + 3.5) * (2.7 -4)

(2 + 3.5) * (2.7 - 4)

#Complex Expressions: (!)

2 + 3j

-5.2 + 6j

(2 + 3j) * (-5.2 + 6j)

#String Expressions:

"this "
"this is " + "cool"





str(50)

str(92.7)

int("22")

int("abc")

int(3.9)

float(22)

float("3.14")

# assignment statements

x = 2

y = x + 4

s = "abc"

t = "this" + s * y



# sequence types
s

len(s)

t

len(t)

#we can do access the i'th element of a sequence...

s[0]

s[1]

(s[0],s[1],s[2])

t[6]

#slicing:  s[i:j] is the (sub)sequence of characters from position i through j-1.



t

t[0:4]

t[5:7]

t[3:] 

t[:4] 


#forall t. t[:i] + t[i:] is always equal to t

t[:2] + t[2:]

t[:6] + t[6:]


#Tuples:

t1 = (3,5)

t2 = ("abc",2.9,99)

t3 = (t1,t2)


(1,2) + (3.6, "a")

t4 = ("abc",10) * 4

# tuples are also sequences

t1

len(t1)

t3

len(t3)

t4

len(t4)


#Can select:

t1[0]

t2[2]

t2[1:2]

t2[1:]


#Another sequence Lists:


l1 = [9,1,1]

l2 = [1,"a",3.0,["moo","koo"]]


len(l1)

len(l2)


l1[0]

l2[1]

l2[3]

l2[3][0]


l2[1:3]


l1 + l2

l1 * 3

2 * l2

# mutation

l2

l2[0] = "zzz"

l2


x = [1,2,3,4,5]

y = x

y[0] = "a"

y

x






# slice assignment

l2[0:3] = l1 * 7



# negative wraparound

l2[-1]



#Statements:

#if

x = 10
if x < 0:
   x = abs(x)
   print "Negative, flipped", x
elif x == 0:
   print "Zero!"
else:
   print "Positive", x


#indentation matters
if x==15:
	pass
	print "is 15"

if x==15:
	pass
print "is 15"


if 1: print "true"

if 0: print "true"

if []: print "true"

if ["a"]: print "true"

#while - statement
a,b = 0,1
while b < 20:
  print b
  a,b = b,a+b

print b






#functions
def fib(n):
  a,b = 0,1
  while (b < n):
    print b
    a,b = b,a+b
  return b




fib(20)


print fib(20)


def fac(n):
  if n == 0: 
    return 1
  else:
    return n * fac(n-1)


fac(10)


def fac(n):
	if n < 0: 
		return "Rubbish negative arg"
	elif n == 0: 
		return 1
	else:
		return n * fac(n-1)


fac(-10)

fac(10)

#"default" parameters.

def greet(i,name="Bob"):
	print "Hi "*i, name



greet(3, "Sally")


greet(3)


fac

def incr(x): return x + 1

def app(f, x): return f(x)


let compose f g = 
  fun x -> f (g x) in

def compose(f,g):
  def foo(x):
    return f(g(x))
  return foo


def f1(x): return 3*x
def f2(x): return x[0:2]

baz = compose(f1,f2)

baz([1,2.2,"three",4,"five"]) #works for sequences

baz("thank god its friday") #works for sequences



