Saturday, March 17, 2012

Python programming Day 02

#Compute median number among the three numbers
def bigger(a,b):
    if a > b:
        return a
    else:
        return b
     
def biggest(a,b,c):
    return bigger(a,bigger(b,c))

def median(a,b,c):
    biggest_number=biggest(a,b,c)
    if a==biggest_number:
        median_number=bigger(b,c)
    else:
        if b==biggest_number:
            median_number=bigger(a,c)
        else:
            median_number=bigger(a,b)
    return median_number
 
print median(4,5,6)

#Print numbers n,n-1,n-2,...,1, Blastoff
def countdown(n):
    while n >= 1:
        print n
        n=n-1
    print 'Blastoff'
 
countdown(9)

#Find the last position of a target string in the search string. If there are no occurrences output is -1.

def find_last(s,t):
    post=0
    result=s.find(t,post)
    if result == -1:
        return -1
    else:
        while result != -1:
            post=result+1
            result=s.find(t,post)
        return post-1

find_last('abc','a') # Output will be 0.

#Print the multiplication table
def print_multiplication_table(n):
    p=1
    while p<=n:
m=1
        while m <=n:
            result=m*p
            print str(p) + '*' + str(m) + '=' + str(result)
            m=m+1
        p=p+1

print_multiplication_table(10)

#To create a list, use
my_list=['a','b','d']
print my_list[0] #This will print a

#To create a tuple, use
my_tuple=('x','y')

#An example of accessing a nested list

countries = [['China','Beijing',1350],
             ['India','Delhi',1210],
             ['Romania','Bucharest',21],
             ['United States','Washington',307]]

#Write code to print out the capital of India by accessing the array.
print countries[1][1]

# List operations
my_list=[1,2]
my_list.append(3)
my_list=my_list + [4,5]
len(my_list) # This results 5

#List operations using append method
p=[1,2]

q=[3,4]
p.append(q)
print p
[1, 2, [3, 4]]

#Using a FOR loop to print out number of days in each month
days_in_month=[31,28,31,30,31,30,31,31,30,31,30,31]
months=[1,2,3,4,5,6,7,8,9,10,11,12]
for i in months:
     print days_in_month[i-1]

#Using a FOR loop to print the sum of the list

def sum_list(my_list):
    sum=0
    for e in my_list:
        sum=sum+e
    return sum
 
print sum_list([1,7,4,8,9])

#The following function takes a list of strings and returns a new list that contains capitalized strings.
def capitalize_all(t):
    result = []
    for s in t:
        result.append(s.capitalize())
    return result

#Several ways to delete elements in the list


#Define a procedure, measure_udacity, that takes its input a list of Strings,
#and outputs a number that is a count of the number of elements in the input
#list that start with the letter 'U' (uppercase).

#measure_udacity(['Dave','Sebastian','Katy']) => 0

#measure_udacity(['Umika','Umberto']) => 2
def measure_udacity(my_list):
    count=0
    for i in range(len(my_list)):
        if my_list[i][0]=='U':
            count=count+1
    return count

print measure_udacity(['Dave','Sebastian','Katy'])

#Another way to do it

def measure_udacity(my_list):
    count=0
    for e in my_list:
        if e[0]=='U':
            count=count+1
    return count

print measure_udacity(['Dave','Sebastian','Katy'])

#Define a procedure, find_element, that takes as its inputs a List and a value of any type, and
#outputs the index of the first element in the input list that matches the value.

#If there is no matching element, output -1.
#find_element([1,2,3],3) => 2
#find_element(['alpha','beta'],'gamma') => -1

def find_element(my_list, t):
    index=0
    for e in my_list:
        if e == t:
            return index
        index=index + 1
    return -1
 
print find_element([1,2,5,3,6,3],3)
print find_element(['alpha','beta'],'gamma')    

#Another way to do it using the 'index' method and 'in' operator
def find_element(my_list,t):
    if t not in my_list:
        return -1
    else:
        return my_list.index(t)

print find_element([1,2,3],3)
print find_element(['alpha','beta'],'gamma')

If we need to return the index for the output, a WHILE loop is a good choice.

>>> p=(0,1,2) #p is a tuple
>>> print p
(0, 1, 2)
>>> q=[0,1,2] #q is a list
>>> print q
[0, 1, 2]

<List>.pop()
Mutates <List> by removing its last element. Outputs the value of that element. If there are no elements in <List>, [].pop() produces an error.

# After running the procedure proc1(p) the value of p is unchanged.
def proc1(p):
      p=p+[1]

#Define a procedure, greatest, that takes as input a list of positive numbers, and
#returns the greatest number in that list. If the input list is empty, the output should be 0.

#greatest([4,23,1]) => 23
#greatest([]) => 0

def greatest(my_list):
    max=0
    if len(my_list)==0:
        return 0
    else:
        for e in my_list:
            if e >= max:
                max=e
        return max

References
Allen B. Downey, Think Python: How to Think Like a Computer Scientist, http://www.greenteapress.com/thinkpython/html/index.html
Udacity, CS101 Lecture Notes, February-April 2012

No comments:

Post a Comment

Mounting USB drives in Windows Subsystem for Linux

Windows Subsystem for Linux can use (mount): SD card USB drives CD drives (CDFS) Network drives UNC paths Local storage / drives Drives form...