Monday, November 23, 2015

Python (1): Array, list, tuple, dictionaries, loops, modules, functions, methods,variables, file handling............

Python is interpreted, interactive, object-oriented
Its strength is its ease, in-built functions, rich library, database compatibility, scalability
PATH="$PATH:/usr/local/bin/python"
Applications----------->Accessories----------->Terminal
IDEs: Eclipse with PyDev plugin, PyCharm, Spyder, Komodo
ipynb: IPython Notebook 
While running from IDE
I use PyCharm (its cross-platform). It is a good IDE for python programming.
#To install package locally, go to wrench symbol (settings)
Go to  project interpreter------
2.7.5 (C:\Python27\python.exe)
Python27\Lib\site-packages\
Installed python packaging tools
Biopython, mysql-connector tools, pip, setuptools are automatically installed
NumPy: Array processing for numbers, strings, records, and objects
pip install --user numpy
python setup.py install
Microsoft Visual C++ Compiler needed for Python 2.7 (so that python can read C++) in Windows
#I could install swampy, panda, pip....but not numpy, its complicated
-----------------------------------------
#ipython
IPython 4.0.0 -- An enhanced Interactive Python.
ipython
5+2*6**2
5/2
7/2.0
13 % 4

import math
math.pi
math.e
math.pi/4
math.sin(math.pi/4)
math.asin(math.sin(math.pi/4))
math.sqrt(16)


s = "My first string"
s[0]
s[1]
s[-1]
#’g’
s[0:2]
#’My’
s[3:8]
#’first’
s[3:8:2]
#’frt’
s[::-1]
#’gnirts tsrif yM’


alist = [1,2,3.14,’foo’,’bar’,[’a’,’b’,True]]
alist[5]
#[’a’, ’b’, True]
alist[5][2]
#True
alist[1] = 99
alist
#[1, 99, 3.14, ’foo’, ’bar’, [’a’, ’b’, True]]


atuple = (1,2,3.14,’foo’,’bar’,[’a’,’b’,True])
atuple[5]
#[’a’, ’b’, True]
atuple[5][2]
#True
atuple[1] = 99
# A list can be grown by insert, append, concatenation
# A list can be reduced by pop, del, assigning

blist = []
blist.append(1)
blist.append(99)
blist = blist + [3,4,5]
blist
blist[2:2] = [’a’,’b’,’c’]
blist
#[1, 99, ’a’, ’b’, ’c’, 3, 4, 5]
blist[2:4] = []
blist
#[1, 99, ’c’, 3, 4, 5]
blist.pop()
#5
blist
#[1, 99, ’c’, 3, 4]
del blist[3]
blist
#[1, 99, ’c’, 4]

emails = {}
emails[’smith’] = ’smith@gmail.com’
emails[’jones’] = ’jones@gmail.com’
emails[’smith’]
emails.keys()
emails.values()
emails



zip([’a’,’b’,’c’,’d’], [1,2,3,4])
adict = dict(zip([’a’,’b’,’c’,’d’], [1,2,3,4]))
adict
adict[’b’]
adict.get(’e’, 0)
adict
adict.setdefault(’e’, 0)
adict


adict
for ch in "ajfljldjajfeljad":
try:
print adict[ch]
except KeyError:
pass

numlist = [3,1,4,1,5,1,6,9]
numlist.sort()
numlist
numlist.reverse()
numlist


blist
#methods of the list class
[b for b in dir(blist) if not b.startswith(’_’)]
#[’append’, ’count’, ’extend’, ’index’, ’insert’, ’pop’, ’remove’, ’reverse’, ’sort’]

quote = "My philosophy, like color television, is all there in black and white"
#methods of the string class
[m for m in dir(quote) if not m.startswith(’_’)]
#[’capitalize’, ’center’, ’count’, ’decode’, ’encode’, ’endswith’, ’expandtabs’, ’find’, ’format’,

’index’, ’isalnum’, ’isalpha’,’isdigit’, ’islower’, ’isspace’, ’istitle’, ’isupper’, ’join’, ’ljust’, ’lower’, ’lstrip’, ’partition’, ’replace’, ’rfind’, ’rindex’, ’rjust’, ’rpartition’, ’rsplit’, ’rstrip’, ’split’, ’splitlines’, ’startswith’, ’strip’, ’swapcase’, ’title’, ’translate’, ’upper’, ’zfill’]

quote.lower()
quote.upper()
quote.split()
quote = ’’.join(quote)
quote.split(’,’)

grade = None
score = 86
if (score > 93):
grade = ’A’
elif (score > 85):
grade = ’B’
elif (score > 70):
grade = ’C’
else:
grade = ’D’
grade


range(10, 15)
for number in range(10, 15):
print number
for char in ’abcde’:
print char
for name in [’Jon’, ’Roy’]:
print name


for i, name in enumerate([’Jon’, ’Roy’, ’Amy’]):
print i, name

squares = []
for i in range(10, 16):
squares.append(i**2)
squares

oddsquares = []
for i in range(10, 16):
if i%2==1:
oddsquares.append(i**2)
oddsquares



squares = [i**2 for i in range(10, 16)]
squares
oddsquares = [i**2 for i in range(10, 16) if i%2==1]
oddsquares


wells = [’%s%02d’ % (r, c) for r in ’ABCDEF’ for c in range(1, 13)]
wells[:15]


wells = []
for r in ’ABCDEF’:
for c in range(1,13):
wells.append(’%s%02d’ % (r, c))
wells[:15]


i = 0
while (i < 5):
i = i+1
print i


’%4d’ % 123
#’ 123’
’%5f’ % 3.14
# ’3.140000’
’%5.2f’ % 3.14
#’ 3.14’
’%05d’ % 23
#’00023’
’%-5d’ % 23
#’23 ’
’%+5d’ % 23
#’ +23’

#to print out the layout of a 96 well plate
for r in ’ABCDEF’: print ’ ’.join([’%s%02d’ % (r, c) for c in range(1, 13)])



fin = open(’file’)
fin = open(’file’, ’r’)
fin = open(’file’, ’rU’)

noted = ’\n’.join([’Autumn is crisp’, ’Rose is fragrant’])
fo = open(’noted.txt’, ’w’)
fo.write(noted)
fo.close()

with open(’noted.txt’, ’w’) as fo:
fo.write(noted)
fo = open(’noted.txt’, ’a’)
fo.write(’\n’ + ’I like hiking’)
fo.close()

poem = open(’noted.txt’, ’rU’).read()
poem
poem = open(’noted.txt’, ’rU’).readlines()
poem

numbers = [1,6,23,8,1,2,90]
sum(numbers)

#list comprehension, string interpolation  (%s for strings
, %d for integers, %f for floats), string padding
 #Variables to be inserted into the string are given as a tuple following the % separator. However, the default
#ipython is great for learning because of the instant feedback, but scripts are reusable
While running from Linux command-line
Common commands
help
pydoc modules   #To know python modules from command-line
help ('modules')  #To know python modules from python interpreter
Python  #In Linux terminal
import swampy

easy_install pandas
easy_install NumPy
#gcc is needed to compile
sudo apt_get install gcc

sudo pip install swampy
python script.py
http://www.tutorialspoint.com/execute_python_online.php
---------------------------------------------
Books and links :
'Python for Data Analysis' by Wes McKinney
'Bioinformatics Programming using Python' by Mitchell L Model
'Think Python' by Allen B. Downey
https://github.com/pydata/pydata-book
http://pythoncentral.io/
http://openwetware.org/wiki/Open_writing_projects/Beginning_Python_for_Bioinformatics
-------------------------------------------------------------------------------
python
print "Hello, Python!"
------------------------------------------------------
copy : for shallow and deep copy operations
glob : finds all pathnames matching a pattern
itertools: creates iterators for easy looping
numpy :for scientific computing
panda: A Python implementation of the Panda REST interface
platform : derives architecture information
swampy: A suite of programs
-------------------------------------------------
STEP 1: import modules
STEP 2: function defining
STEP 3: variables assignment
STEP 4: loop, if...else
STEP 5: print
-------------------------------------------------------------------------------
Keywords (about 31)
e.g. The reserved words include and, del, from, while, or, global
-------------------------------------------------------------------------------
Modules
e.g. random, sys, os, re, time, calendar, pip, commands, io, itertools, keyword, json, sqlite3, math, csv, string, stat, pdb, pipes, parser, token, pydoc, gzip, array, imp, swampy
Modules are imported . These are writen codes, which cab be reused.
import module
import os
import itertools
import time;
import calendar;
----------------------------
os: finds directory structure
os.getcwd()
os.listdir ('.')
os.chdir ('./dir_sub')
#
import itertools
a = (1,2)
b =(a, b)
c = itertools.product (a,b)

for i in c:
   print i

for seq in seq_list
   print seq
#
import time;  
time_elapsed = time.time()
print "Ticks since January 6, 2015:", time_elapsed

localtime = time.localtime(time.time())
print "Local current time :", localtime


Ticks since January 6, 2015: 1449090154.73                                                                               
Local current time : time.struct_time(tm_year=2015, tm_mon=12, tm_mday=2, tm_hour=21,
tm_min=2, tm_sec=34, tm_wday=2     
, tm_yday=336, tm_isdst=0)       
#
import calendar;
cal = calendar.month(2014, 6)
print "Calendar for the asked month and year:"
print cal
Calendar for the asked month and year:                                                                                   
     June 2014                                                                                                           
Mo Tu We Th Fr Sa Su                                                                                                     
                   1                                                                                                     
 2  3  4  5  6  7  8                                                                                                     
 9 10 11 12 13 14 15                                                                                                     
16 17 18 19 20 21 22                                                                                                     
#w is width, l is length and c is columns
#It prints the calendar, no need o print statements as prcal is the method.
import calendar
cal = calendar.prcal(2015,w=0.2,l=0.2,c=4)
pprint: It “pretty-prints” Python data structuresSome of the Built-in Python methods
time:
thread:
-----------------------------------------------------------------------
Functions
Modules have functions. The code blocks will tell the functions present in those modules.
Some important functions e.g. len, range
import time
content1 = dir(time)
print content1

import calendar
content2 = dir(calendar)
print content2

#.pow, .sqrt, .sin are functions of math module
import math
content3 = dir(math)
print content3

import math
x = math.sin (0.5)

s = 'afgtfstyjh'
len(s)

for i in range (0, list1):
     print (list1[i])
-----------------------------------------------------------------------
Methods
capitalize() : Capitalizes first letter of string
center(width, fillchar): Add characters to original string 
count(str, beg= 0,end=len(string)): Counts occurrence frequency of the string
endswith(suffix, beg=0, end=len(string)): Determines if string ends with a particular suffix
find(str, beg=0 end=len(string)):Finds if str occurs in string
index(str, beg=0, end=len(string)): Raises an exception if str not found.
isdigit(): Returns true if string contains only digits a
islower(): Returns true if string has only lowercase alphabets.
isupper(): Returns true if string has only uppercase alphabets.
join(seq): Concatenates  strings
len(string): Returns the length of the string
lower(): Converts all uppercase letters  to lowercase.
lstrip(): Removes all leading white space in string.
max(str): Returns the max alphabetical character
split (str="", num=string.count(str)): Splits string according to delimiter str
strip([chars]): Does both lstrip() and rstrip() on string
-----------------------------------------------------------------------------------------------------------------------
Usage
print str.capitalize()
print str.find(str)
print str.lower()
----------------------------------------------------------------------------------------------------------------------
[] is mutable as a default argument
Parameters (abstract) hold arguments (value)
'Return' gives the result and exits the function
----------------------------------------------------
#Local variable are part of functions. There scoping is local only
Variables (Local and global)
global_total = 0;

def sum( arg1, arg2 ):
   local_total = arg1 + arg2;
   print "Local_total is: ", local_total
   return local_total;

sum( 10, 20 );
print "Global_total is: ", global_total
Local_total is:  30                                                                                     
Global_total is:  0 
-------------------------------------------------------------------------------
#Opening, reading, writing and closing a file
#Reading a file (the file should be supplied, if you did not write is before this command)
fo = open("test.txt", "r+")
str = fo.read(10);
print "The sub-string is:", str
fo.close()

#Write in the file
#example 1
fo = open("test.txt", "wb")
print "Name of the file: ", fo.name
fo.write( "Autumn is my favorite season.\nSierra road trip is \
fabulous during this time\n");
fo.close()
#example 2
my_file = open(r"c:\Users\Seema\Desktop\file.txt", "w")
my_file.write("Hello world\n")
my_file.write("Hi there\n")
my_file.close()

#Opening, reading and performing calculation  on the file (file has 1 DNA seq)
my_file = open("data")
my_dna = my_file.read()
dna_length = len(my_dna)
print("The sequence is: " + my_dna + "and length is " + str(dna_length))

##########################
#Finding characters of the substrings
# Open a file
fo = open("test.txt", "r+")
str = fo.read(21);
print "Read String is: ", str
# Check current position
position = fo.tell();
print "Sliced part is: ", position, "characters of the paragraph"
# Resetting pointer again
position = fo.seek(0,0);
str = fo.read(21);
# Close opend file
fo.close()

#####################################################
Arithmetic
print ("5+2 =", 5+2)
print ("5-2 =", 5-2)
print ("5*2 =", 5*2)
print ("5/2 =", 5/2)
print ("5%2 =", 552)
print ("5**2 =", 5**2)
print ("5//2 =", 5//2)
print ("1+2-3*2 =", 1+2-3*2)
print ("(1+2-3)*2 =", (1+2-3)*2)


def calcExample():
    x = 6
    y = 2
z = 99/4
    print ("x + y = ", x + y)
    print ("{} + {} = ".format(x, y), x + y)
    print ("{} - {} = ".format(x, y), x - y)
    print ("{} * {} = ".format(x, y), x * y)
    print ("{} / {} = ".format(x, y), x / y)
    print ("{} % {} = ".format(x, y), x % y)
    print ("{} ** {} = ".format(x, y), x ** y)
print ("Binary format for 5", bin(5))
    print (type (z))
print(math.floor(z))
    w = decimal.Decimal (5.7)
    print(w)

calcExample()
#####################################################
Slicing examples
x = [1,2,3,3,4,5,6]
print len (x)
print x[0] #first element
print x[-1] #last element
print x[0:1] #The element between index 0 and index 1
print x[0:2] #First two element
print x[1] #second element
print x[5] #Sixth element
print x[-1] #element first from last
print x[-2] #element second from last
print x[1:] #All element except the first one
print x[:1] #Only the first element
print x[:2] #Keep first two element
print x[2:] #All but first two element
print x[:6] #All element except the last one (as item number is 7 here)
print x[:-2] #Delete 2 element from end of the list; everthing except the last 2 items
print x[1:2] #(from index 1 to index 2)-1
print x[1:4] #(from index 1 to index 4)-1
print x[4:6] #Last 2 of 6 element
print x[1:-1] #All elements except the last one
print x[2:4:2] #find elements from index 2 to 4 and print 2nd element
print x[3:5] #print element from index 3 to 5 (-1)
print x[2:-3:-1]
print x[: :-1]#reversed the list
print x[-2: ]#keep last 2 element
print x[-5: ]#remove the first 2 element i.e keep last 5 element
print x[-10: ]#keep last 10 element
print x[::-1]  #To reverse a sequence
print x[::-2] #reverses list and prints skipping 1 item each time
print x[::-3] #reverses list and prints skipping 2 item each time
#####################################################
Prototype of function defining and subsequent calling
#Function defining
def printme( str ):
   print str
   return;

#Function calling
printme("abcdefg")
printme("wxyz")
**********************
#Function defining
def Multiply( fx ):
  newValue = fx *10
  return newValue

#Function calling
testData = Multiply(23)
print testData
**********************
#Function defining
def Adding ( fx, fy ):
  newValue = fx +fy
  return newValue

#Function calling
testData = Adding(12,35)
print testData
#####################################################
To test multiple variables against multiple values
x = 0
y = 1
z = 3
v = {0: 'a', 1:'b', 2:'c', 3:'d', 4:'e', 5: 'f'}
v = "abcd"
my_List = ["abcd"[k] for k in [x, y, z]]

print my_List
#####################################################
Making one big list by combining many small lists 
import itertools
list_list = [[1,2,3],[4,5,6], [7], [8,9]]
merged = list(itertools.chain(*list_list))

print  merged
#####################################################
User input-based program
Asking user to enter age
age = int(input("Please type your age: "))
if age >= 18:
    print("You have to pay full price!")
else:
    print("You can pay half price.")
Please type your age: 22                                                              
You have to pay full price!                                                         
#####################################################
Catching an error with while loop;  try....except; continue...break
while True:
    try:
        age = int(raw_input("Please mention your age: "))
    except ValueError:
        print("Please type again")
        continue
    else:
        break
if age >= 12:
    print("You have to pay full price.")
else:
    print("You can pay half price.")


while True:
    data = raw_input("Enter your full name (in capital case): ")
    if not data.isupper():
        print("Enter it again")
        continue
    else:
        break

while True:
    data = raw_input("Pick an answer from A to D:")
    if data.lower() not in ('a', 'b', 'c', 'd'):
        print("Not an appropriate choice.")
    else:
        break
Please mention your age: 32                                                           
You have to pay full price.                                                           
Enter your full name (in capital case): RON SMITH                                     
Pick an answer from A to D:A                                                          
#####################################################
Reference being overwritten by a new value

def changeValue( mylist ):
   my_list.append([1,2,3]);
   return;

my_list = [10,20,30];
changeValue( my_list );
print "Changed value: ", my_list
Changed value:  [10, 20, 30, [1, 2, 3]] 
#####################################################

Iterable example
my_list = [1, 2, 3]
for i in my_list:
      print(i)
1                                                                                               
2                                                                                               
--------------
mylist = [x**x for x in range(4)]
for i in mylist:
    print(i)
1                                                                                               
1                                                                                               
4                                                                                               
27                                                                                              
------------------------------------------
Iterator example
my_generator = (x*x for x in range(4))
for i in my_generator:
   print(i)
0                                                                                               
1                                                                                               
4                                                                                               
9                                                                                              
#####################################################
A generator to make even-sized fragments of  a list
def chunks(l, n):
      for i in xrange(0, len(l), n):
        yield l[i:i+n]

import pprint
pprint.pprint(list(chunks(range(4, 30), 5)))
[[4, 5, 6, 7, 8],                                                                                          
 [9, 10, 11, 12, 13],                                                                                      
 [14, 15, 16, 17, 18],                                                                                     
 [19, 20, 21, 22, 23],                                                                                     
 [24, 25, 26, 27, 28],                                                                                     
 [29]]
#####################################################
Concatenation of sequences
myDNA1 = "ACGTACGTACGTACGTACGTACGT"
myDNA2 = "ACGTACGTACGTACGTACGTACGTAAA"
myDNA3 = "CGTACGT"
joinedSeq = (myDNA1+myDNA2+myDNA3)


print joinedSeq
ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTAAACGTACGT
#####################################################
Two ways of string conversion (modular way and string way)
Use of regular expression /to convert all'T' to 'U'
import re
myDNA = 'ACGTTGCAACGTTGCAACGTTGCA'
regexp = re.compile('T')
myRNA = regexp.sub('U', myDNA)

print myRNA
ACGUUGCAACGUUGCAACGUUGCA 
----------------------------------------
Transcribing by string manipulation
myDNA = 'ACGTTGCAACGTTGCAACGTTGCA'
myRNA = myDNA.replace('T', 'U')

print myRNA 
ACGUUGCAACGUUGCAACGUUGCA 
#####################################################
Reading files in python using list (tab of print command must be correct; input file is xyz.seq)
dnafile = "xyz.seq"
file = open(dnafile, 'r').readlines()
for line in file:


     print line
TCGGCCG                                                                                                    
                                                                                                           
AGGCTCCG                                                                                                   
                                                                                                           
GGTCGATT                                                                                                   
                                                                                                           


TTGCACTG                                                                                                   
#####################################################
To find parameter type
import random
import sys
import os
#Variables, Expressions, and Statements
print type('Hello, World!')
print type(19)
print type(4.2)
print type('19')
print type('4.2')
print 1,000

message = 'Autumn colors'
print type(message)

n = 16
print type (n)

pi = 3.1415926535897932
print type(pi) 
<type 'str'>                                                                               
<type 'int'>                                                                               
<type 'float'>                                                                             
<type 'str'>                                                                               
<type 'str'>                                                                               
1 0                                                                                        
<type 'str'>                                                                               
<type 'int'>                                                                               


<type 'float'>                                                                         
#####################################################
#To create an object diagram (IDE-dependent result seen; may not be imported in some IDE)
from swampy.Lumpy import Lumpy
#from Lumpy import Lumpy
lumpy = Lumpy()
lumpy.make_reference()

mesage = 'Hi'
n = 34
m = 51
z = 43
pi = 3.25
lumpy.object_diagram()
#####################################################
List: []
Tuple: ()
Dictionary: {'a' : 'b', 'c' : 'd'}

*List can be nested (list within list), so list can 1D , 2D.
*Strings are immutable, tuples are immutable
*List is mutable
###########################
List (Square brackets)
#Create a list
list1 = [ 'summer', 20, 'ocean', 3.5 ]
list1
list1[0]
list1[3]
list2 = ['soup', 25]

#Printing, slicing, calculating list
print list1      
print list1[3]  
print list1[1:2]
print list1[2:]  
print list2 * 3
print list1 + list2
['summer', 20, 'ocean', 3.5]                                                                            
3.5                                                                                                     
[20]                                                                                                    
['ocean', 3.5]                                                                                          
['soup', 25, 'soup', 25, 'soup', 25]                                                                    
['summer', 20, 'ocean', 3.5, 'soup', 25] 

#Add elements to list
list1.insert (0, "moon")
list1

#Append elements to list
list1.append (["summer", "woods"])
list1

#Extend  list
list1.extend (["summer", "woods"])
list1

#Check length of list
len(list1)

#Search the list (also sublist can be searched)

list.index ("soup")

#Search presence of the element in the list 

"soup" in list1

#Remove element from list
list1.remove ("soup")

###########################
Tuple (parentheses)
tuple1 = ( 'apple', 'flower', 12 , 3.41 )
tuple2 = ('milk', 2015)
tuple3 = ('garden', 7)

print tuple1      
print tuple1[3]
print tuple1[1:3]  
print tuple1[2:] #everything starting index 2
print tuple1[:2] # everthing before index 2
print tuple2 * 5
print tuple1 + tuple2 + tuple3
('apple', 'flower', 12, 3.41)                                                                           
3.41                                                                                                    
('flower', 12)                                                                                          
(12, 3.41)                                                                                              
('apple', 'flower')                                                                                     
('milk', 2015, 'milk', 2015, 'milk', 2015, 'milk', 2015, 'milk', 2015)                                  
('apple', 'flower', 12, 3.41, 'milk', 2015, 'garden', 7)      
###########################
Dictionaries (curly bracket/braces)
dict = {}
dict['name'] = "Its a string"
dict[5]     = "Its a number"
example_dict = {'season': 'autumn','age':30, 'fruit':'grapes', 'salary':200}

print dict['name']  
print dict[5]      
print example_dict    
print example_dict.keys()
print example_dict.values()
Its a string                                                                                            
Its a number                                                                                            
{'salary': 200, 'season': 'autumn', 'age': 30, 'fruit': 'grapes'}                                       
['salary', 'season', 'age', 'fruit']                                                                    
[200, 'autumn', 30, 'grapes'] 
###########################
If............(comparator)
a = 20
if ( a  == 20 ) : print "It matched"
print "Got the match."

var = 18
if ( var  <= 20 ) : print "Its less"
print "Did not match."

var = 25
if ( var  >= 20 ) : print "Its more"
print "Did not match."
It matched                                                                                              
Got the match.                                                                                          
Its less                                                                                                
Did not match.                                                                                          
Its more                                                                                                
Did not match. 

###########################
List: Nested loop, iteration over a list, list_to_dict conversion
Array: Array shuffling
------------------------------------------------
#Key value manipulation
def number_to_string(argument):
    options = {
        0: "zero",
        1: "one",
        2: "two",
        3: "three",
        4: "four",
    }
    return options.get(argument, "Does not exist")
print number_to_string(3)
three
------------------------------------------------
#Nested loop for list comprehension
for x in range(1, 5):
   for y in range(1, x):
         print x, y
2 1
3 1
3 2
4 1
4 2
4 3
for x in range(1, 5):
    for y in range(1, x):
         print x * y
2
3
6
4
8
12
------------------------------------------------
#Iteration over a list
def get_next_element(my_itr):    
     try:            
         return my_itr.next()    
     except StopIteration:    
         return None    
my_list = [1, 2, 3]
my_itr = iter(my_list)
for i in range(0, 4):
     value = get_next_element(my_itr)    
     if value is None:    
         my_itr = iter(my_list)
         value = get_next_element(my_itr)    
     print value
1
2
3
1
------------------------------------------------
#Converting a list to dictionary
def list_to_dict(my_list):
     my_dictionary = {}
     for item in my_list:
         if my_dictionary.has_key(item):
             my_dictionary[item] = my_dictionary[item] + 1 else:  
             my_dictionary[item] = 1 return my_dictionary
my_list = [1, 1, 4, 5, 6, 7]
print list_to_dict(my_list)
{1: 2, 4: 1, 5: 1, 6: 1, 7: 1}
------------------------------------------------
#Random shuffling of an array
import random
def shuffle(ary):
    a=len(ary)
    b=a-1 for d in range(b,0,-1):
      e=random.randint(0,d)
      if e == d:
            continue ary[d],ary[e]=ary[e],ary[d]
    return ary
ary = [4,7,9,3,6,1]
print shuffle(ary)
[6, 1, 7, 3, 9, 4]
[9, 1, 4, 3, 7, 6]
------------------------------------------------
#A diagram creation using math and swampy
import math
try:
    from swampy.TurtleWorld import *
except ImportError:
    from TurtleWorld import *
def square(t, length):
    for i in range(6):
        fd(t, length)
        lt(t)
def polyline(t, n, length, angle):
    for i in range(n):
        fd(t, length)
        lt(t, angle)
def polygon(t, n, length):
     angle = 270.0/n
     polyline(t, n, length, angle)
def arc(t, r, angle):
    arc_length = 2 * math.pi * r * abs(angle) / 270 n = int(arc_length / 6) + 1 step_length = arc_length / n
    step_angle = float(angle) / n
    lt(t, step_angle/2)
    polyline(t, n, step_length, step_angle)
    rt(t, step_angle/2)
def circle(t, r):
    arc(t, r, 270)
if __name__ == '__main__':
    world = TurtleWorld()
    bob = Turtle()
    bob.delay = 0.001
    radius = 50 pu(bob)
    fd(bob, radius)
    lt(bob)
    pd(bob)
    circle(bob, radius)
    wait_for_user()
------------------------------------------------
#Manhattan tourist problem solving by Dynamic programming
# A 3x3 grid is used, with vertical and horizontal matrix given below
vWeight = [[5,3,0], [3,5,0], [10,3,5], [5,1,2]]
hWeight = [[1,2,5], [2,1,5], [2,3,4],  [0,0,0]]
# Empty matrix to hold the path
Manhattan = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
Manhattan[
0][0] = 0
# Compute the first row and column
for row in range(1, 4):
    Manhattan[row][
0] = Manhattan[row-1][0] + vWeight[0][row-1]
for col in range(1, 4):
    Manhattan[
0][col] = Manhattan[0][col-1] + hWeight[0][col-1]
for row in range(1, 4):
   
for col in range(1, 4):        
       
Manhattan[row][col] = max(Manhattan[row-1][col] + vWeight[col][row-1], Manhattan[row][col-1] + hWeight[row][col-1
])
print  "The Maximum possible path :", Manhattan[3][3]

The Maximum possible path : 22  
#####################################################
Once code block is written, right syntax for print block is important. 
my_data = [1,4,6]
print shuffle(my_data)
###########################
Errors.......
IndexError: list index out of range i.e You are trying to access an element of the list that does not exist.

No comments:

Post a Comment