+ -

Pages

Sunday, March 25, 2012

Code I Rode with Notes


There is a difference between functions and method. For example:
l=list(“khalid”)
sorted(l)
This will produce a sorted list of l. l itself will not be affected. But If I were to:

l.sort()

l will be modified into a sorted list.

So, a function just takes arguments and return a value based on those arguments, where a method can actually change and object (in this cas the l).
f»»» l=list("khalid")
»»» l
['k', 'h', 'a', 'l', 'i', 'd']
»»» for i in range(len(l)):
             print (i,l[i])

             
0 k
1 h
2 a
3 l
4 i
5 d

this is the same as:

»»» for i in range (6):
             print (i,l[i])

==
the difference between the break and continue is :
break: breaks out of the entire if block including the final (else) and jumps to the next block of code

continue: restarts the block and skips any code INSIDE the block if the condition is met. if it is not block continues normally.

else: else has to always be executed if it is present (?)

==
»»» x=dict([(n,n*2)for n in (1,2,3,4)])
»»» x
{1: 2, 2: 4, 3: 6, 4: 8}
»»»l=['khalid','majid','raid']
»»» def x(x):
     'print hello, variables!'   #this is just a docstring
             if len(x)!=0:
                           for i in x:
                                         print ("hello {0} !".format(i))
»»» x(l)
hello khalid !
hello majdi !
hello raid !


==
lists can be nested inside lists. and this is hwo to access items inside a nested list!!!
»»» q=list("lakdfj")
»»» a=["d",q,"m"]
»»» a
['d', ['l', 'a', 'k', 'd', 'f', 'j'], 'm']
»»» a[0]
'd'
»»» a[1]
['l', 'a', 'k', 'd', 'f', 'j']
»»» a[1][0]
'l'
»»» a[1][1]
'a'
»»» a[1][2]
'k'
you can also append to a nested list!!
a=list("lskdjf")
»»» b=[a,'b','s']
»»»
»»» b
[['l', 's', 'k', 'd', 'j', 'f'], 'b', 's']
»»» b[0].append("khalid")
»»»
»»» b
[['l', 's', 'k', 'd', 'j', 'f', 'khalid'], 'b', 's']

==
the following function takes any number of arguments and returns their average:
def average(*num):
             print (sum(num)/len(num))

note that the *num argument means that you can enter any number of arguments and they will be treated as a tuple.
The sum function works on iteratable  data types and returns their sum.

==
When iterating over a dictionary the return value is always the key:

d={“khalid”:23, “majid”:32}
for I in d:
print (I)

==
the range() funciton takes can take 3 args. It can take only one, but it has to be an integer. If you use a reference to a list, it won't work, unless you use the * before it's name!
arg=[3,100]
»»» list(range(*arg))
this will produce a list from 3 to 99

==
You can use set() to create a set, list() for a list, and dict () for a dictionary , tuple() for a tuple!

==
you can use list comprehensions to create lists quickly out of existing lists or other iterators
x=list(range(10))
x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
here I'm using a LC to create the y list our of the x list (note that you have to use for)
y=[a*2 for a in x]
»»» y
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

above can be duplicated without using an existing list:
»»» lc=[x*2 for x in range(10)]
»»» lc
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
»»»
you can use if optionally to filter your new list
z=[a+1 for a in x if a«5]
z
[1, 2, 3, 4, 5]

==
you can also create dictionary comprehensions like the above:

»»» dc={x:x*100 for x in range(5)}
»»» dc
{0: 0, 1: 100, 2: 200, 3: 300, 4: 400}

==


in lists, you can access its items via index:
list[0]
or
list[1:3]

but in dictionaries, you have to use the keys:
d={1:"khalid",2:"elham",3:"dra"}
»»» d[1]
'khalid'

to get all the keys in a list
»»» d
{'dra': 4.5, 'elham': 32, 'khalid': 37}
»»» list(d.keys())
['dra', 'elham', 'khalid']

to get a sorted list:

»»» sorted(d.keys())
['dra', 'elham', 'khalid']

note that sorted and list works also for d.values():
»»» sorted(d.values())
[4.5, 23, 34]
»»» sorted(d.keys())
['dra', 'elham', 'khalid']
»»»
“items” can be used to iterate over both values and keys; it's combination of both:
d
[('dra', 4.5), ('elham', 32), ('khalid', 37)]

for x,y in d.items():
print (x,y)
dra 4.5
elham 32
khalid 37
»»» d={"khalid":37,"elham":32,"dra":4.5}
»»» for i in d.keys():
             print ("your name is {0}, and your age is                                           {1}".format(i,d[i]))

your name is dra, and your age is 4.5
your name is elham, and your age is 32
your name is khalid, and your age is 37

==
to combine 2 or more lists (or other iterators) you can use the zip() function which returns tuples of both iterateors:

»»» names=["khalid","ahmed","rayan"]
»»» ages=[12,45,23]
»»» x=zip(names,ages)
»»» x
«zip object at 0x02C18DC8»
»»» for i in x:
             print (I)
('khalid', 12)
('ahmed', 45)
('rayan', 23)
you can also use zip () to produce the following:
»»» question=['name','age','sex']
»»» answer=['khalid','45','male']
»»» for q,a in zip(question,answer):
             print ('what is your {0}? I am {1}'.format(q,a))

what is your name? I am khalid
what is your age? I am 45
what is your sex? I am male

here it is working with the range funciotn :
»»» n1=range(10)
»»» n2=range(10,21)
»»» n3=zip(n1,n2)
»»» list(n1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
»»» list(n2)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
»»» list(n3)
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]

==
you can use sorted(set(Mylist)) to get a compact list that is sorted and only contains unique items:

['k', 'h', 'a', 'l', 'i', 'd', 'm', 'a', 'j', 'i', 'd']
»»» set(k)
{'a', 'd', 'i', 'h', 'k', 'j', 'm', 'l'}
»»» sorted(k)
['a', 'a', 'd', 'd', 'h', 'i', 'i', 'j', 'k', 'l', 'm']
»»» z=sorted(set(k))
»»» z
['a', 'd', 'h', 'i', 'j', 'k', 'l', 'm']

==
modules can be loaded once during any given session, if changes are done to a module and you want to see
If you import a module you can't reimport it if you made chages to it unles you do the following:

»»» import average
»»» average.aver(1,2)
1.5
»»» import imp
»»» imp.reload(average)
«module 'average' from 'C:\Python31\average.py'»
»»» average.aver(1,2)
150.0

==
if you want to iterate over two values use a nested loops such as (where x is a list):

>>> for i in x:
for f in range(20):
print(i.rjust(f))

==


def number_table(x):
"prints a table of mulitplied numbers"
for i in range (x):
print ('{0:2d} {1:4d} {2:6d}'.format(i,i*i,i*i*i))

==



you can use rjust(),ljust(),center() to pad any string with spaces (note the space on the lest)

"khalid".rjust(34)
'                            khalid'

==

to truncate a long string (maybe str(long number), or just a string, you can always use slicing. (strings are objects!)


==


you can use other operations to format numbers in strings such as (note the “.” before the “2f”:

import math
print ('the value of pi is {0:.2f}'.format(math.pi))
the value of pi is 3.14

==

to read or write from a file you have to create a an object (note the double backslash. This is to “escape the escape”:

>>> f=open("c:\\testing\\testdoc.txt",”r”)

if you don't add anything, read is assumed. “w” is for writing and “r+” is for reading and writing. “b” is for binary data.

==

this will erase the contents and write anew:
f=open("c:\\testing\\testdoc.txt",”w”)

this will not erase but “write over” the content; erasing only as it goes along (of course while also reading):
f=open("c:\\testing\\testdoc.txt",”r+”)

this just add the to the end of the content without erasing anything:
f=open("c:\\testing\\testdoc.txt",”a”)

appending “b” to any of the above, such as “rb+”, “wb”, will write in binary mode.

==

the following code handles and exception in an add function of my creation!.. actually it's my first full functioning (kind of!) program!

def add():
while True:
try:
x=int(input("enter no.1: "))
y=int(input("enter no.2: "))
print(x+y)
break
except:
print("start over")

note that in:
x=int(input(“enter no.1: ')) converts the input value into an integer. Therefore, entering an letter or anything else will raise the exception, which has been “proudly” handled!

==

A stupid mistake that I took me some time to realize why:

>>> class add: #here I’m creating the class
def add(self,x,y):
print (x+y)

#here I’m creating a sub/child class “Myadd” from the super/parent class (unwittingly, I might add, assuming that I can use it, or the parent class, for that matter, without creating an object (instance) first... poor fool)

>>> class Myadd(add):
pass #I passed here because I don’t want to alter any functions

>>> Myadd.add(4,5)
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
Myadd.add(4,5)
TypeError: add() takes exactly 3 positional arguments (2 given)

OF COURSE THIS IS WRONG BECAUSE I'M TRYING TO APPLY THE METHOD TO THE CLASS. I SHOULD CREATE A AN OBJECT FIRST! IT IS TELLING ME THAT THE CLASS TAKE 3 ARGUMENTS, WHICH IS TRUE, AND THEY ARE (SELF,X,Y). THE MYSTERY CAN BE SOLVED THUS:
 
>>> ObjectMyadd=Myadd()
>>> ObjectMyadd.add(3,3)
6

note to my poor ass: you don’t need to make a sub class to create a method. just create an object from the first class. so the concept of super/sub class doesn’t really “enter into it”>>python slang
==

Reading a Poem from a file:

def ReadPoem(x):
import time
try:
 f=open(x)
 while True:
line=f.readline()#note that readline() not lines
if len(line)==0:
break
print (line, end="")
time.sleep(2)

except:
#control+c to invoke this exception
print("did you stop my poem!!!")
finally:
 f.close()
 print (" ")
 print ('file has been closed')

>>> ReadPoem("c:\\testing\\testdoc.txt")
from a friend a read a poem
a lonely bird away from home
tidely rest for days shall come
when a lady's breath and a child's hum
shall fill you heart with dispair
and fill your head with heaps of air
file has been closed


an interesting aside is that if you change the scope of the file object to inside the while loop, the function will continue to read the first line only. Why? Because every time it runs the while loop, reopens the file object anew therefore starting again at the first line. If placed at the higher scope, it retains the last line read and starts reading from the next line.
==

an interesting way to print an serialized list of a file's contents is to use to iterate using the glob module:

>>> import glob
>>> x=glob.glob("c:\\Windows\\*.*")
>>> for i in range(len(x)):
print (i, x[i])


0 c:\Windows\bfsvc.exe
1 c:\Windows\bootstat.dat
2 c:\Windows\bthservsdp.dat
3 c:\Windows\cdplayer.ini
4 c:\Windows\csup.txt
5 c:\Windows\DLA.EXE
6 c:\Windows\explorer.exe
7 c:\Windows\fveupdate.exe
8 c:\Windows\HelpPane.exe
9 c:\Windows\hh.exe
10 c:\Windows\HomePremium.xml
11 c:\Windows\IsUninst.exe
12 c:\Windows\mib.bin
13 c:\Windows\Microsoft.NET
14 c:\Windows\msdfmap.ini
15 c:\Windows\msdownld.tmp
16 c:\Windows\notepad.exe
17 c:\Windows\nsreg.dat
18 c:\Windows\ntbtlog.txt
19 c:\Windows\ocsetup_cbs_install_OEMHelpCustomization.dpx
20 c:\Windows\ocsetup_cbs_install_OEMHelpCustomization.perf
21 c:\Windows\ocsetup_install_OEMHelpCustomization.etl
22 c:\Windows\ODBC.INI
23 c:\Windows\ODBCINST.INI
24 c:\Windows\PFRO.log
25 c:\Windows\regedit.exe
26 c:\Windows\setup.iss
27 c:\Windows\SPInstall.etl
28 c:\Windows\sql.MIF
29 c:\Windows\ST5UNST.EXE
30 c:\Windows\ST6UNST.EXE
31 c:\Windows\sttray.exe
32 c:\Windows\system.ini
33 c:\Windows\twain.dll
34 c:\Windows\twain_32.dll
35 c:\Windows\twunk_16.exe
36 c:\Windows\twunk_32.exe
37 c:\Windows\unvise32.exe
38 c:\Windows\win.ini
39 c:\Windows\WindowsShell.Manifest
40 c:\Windows\WindowsUpdate.log
41 c:\Windows\winhelp.exe
42 c:\Windows\winhlp32.exe
43 c:\Windows\wininit.ini
44 c:\Windows\WLXPGSS.SCR
45 c:\Windows\WMSysPr9.prx
46 c:\Windows\_default.pif
>>>


==

to generate random numbers:
>>> import random
>>> random.sample(range(10000),100)
[8824, 1120, 4573, 6372, 4196, 5122, 5407, 467, 138, 5180, 3438, 2579, 2392, 3956, 4542, 3791, 4814, 8923, 1185, 2221, 8799, 2569, 7605, 1011, 4737, 7228, 3733, 7595, 199, 2499, 2816, 9227, 4984, 1251, 5042, 9609, 6146, 4152, 149, 4184, 4245, 3188, 2503, 8716, 3581, 6250, 2445, 4554, 2066, 8136, 3903, 167, 7739, 3014, 7692, 4058, 1999, 4508, 1630, 3243, 2565, 6124, 8212, 3605, 2995, 5668, 9910, 4926, 1433, 8906, 3969, 242, 2342, 103, 7874, 808, 9124, 315, 2584, 2246, 92, 5797, 7024, 5237, 6703, 716, 2931, 7603, 7087, 8237, 2552, 2955, 8133, 8234, 6574, 9753, 4910, 5393, 2778, 146]
>>>

==
THIS IS A FUNCTION THAT TAKES WORD YOU WRITE AND THEN QUIZZES YOU ON IT AND STORES YOU INPUT AND RETURNS IN THE END. IF YOU WANT TO USE NUMBERS, MAKE SURE TO INT WITH INPUT AS IT TAKES ONLY STRINGS.

def wa():
x=input('enter a word.')
word=list(x)
print ('now enter the letters of the word you entered one by one')
z=[]
for i in range(len(word)):
y=input('enter letter?')
z.append(y)
if y==word[i]:
print ('good')
else:
print ('wrong')
print('the letters you entered were {0}'.format(z))
==========================
THIS IS A FUNCTION THAT PRODUCES A RANDOM SAMPLE BASED ON YOUR INPUT, THEN PRINTS LISTS OF RANDOM NUMBERS UNITL IT FINDS YOUR REQUIRED QUIRY IN WHICH TIME IT STOPS.


>>> def chk_random(population,sample,query):
import random
x=random.sample(range(population),sample)
while query not in x:
x=random.sample(range(population),sample) #new list
print(x)
else:
print('we have found {0}'.format(query))

===================================================
USING REGULAR EXPERSSIONS THIS CODE PARSES A SIMEPLE PHONE NUMBER AND RETURNS ITS THREE PARTS. FIRST I USE THE COMILE METHOD TO GET A PATTERN OBJECT WHICH I USE IN TURN WITH THE SEARCH().GROUPS() METHOD TO GET A TUPLE OF THE THREE PARTS


def phone(phnum):
pattern=re.compile(r'(\d{0,5})\D*(\d{3})\D*(\d{6})')
x=pattern.search(phnum).groups()
print('INTRNL CODE IS ',x[0])
print('TRUNK IS ', x[1])
print('PHONE NO IS ',x[2])

==============================
THIS IS A FUNCTION THAT IS AN EXERCISE THAT TRIES TO USE FUNCTIONS WITHIN A LIST(!) NOTE THE WAY THE ARGS WERE PASSED

def fun():
x=random.sample(range(100),5)
y=random.sample(range(100),5)
for i,v in zip(x,y):
print('i = ',i)
print('v = ',v)
ld[0](i,v)
ld[1](i,v)
x
y
====

IF YOU WANT TO CREAT A DICTIONARY FROM TWO LISTS YOU HAVE TO USE DICT()+ZIP(). THE FIRST IS A FUNCTION TO CREATE DICTIONARIES THE SECOND COMBINES SEQUENSES SO THEY CAN BE USED AS KEYS AND VALUES. THUS:

>>> l=list('khalid')
>>> n=range(6)
>>> d=dict(zip(n,l))
>>> d
{0: 'k', 1: 'h', 2: 'a', 3: 'l', 4: 'i', 5: 'd'}


====

THE ENUMERATE FUNCTION ADDS A SERIALIZED NUMBER AFTER A SEQUENCE, BUT KEEP IN MIND YOU HAVE TO CALL THE SERIAL + THE ITEMS THUS:

>>> l
['k', 'h', 'a', 'l', 'i', 'd']
>>> for i,k in enumerate(l):
print(i,k)


0 k
1 h
2 a
3 l
4 i
5 d
=====

WHEN USING MULTIPLE ARGS IN A FUNCTION, REMEMBER THAY ARE STORED AS TUPLES AND CAN BE ACCESS ACCORDINGLY THUS:


>>> def math(*nums):
for i in range(len(nums)):
print(nums[i])
return sum(nums)

>>> math(3,45,3,2,2)
3
45
3
2
2
55

====

REMEMBER YOU CAN ITERATE AND MANIPULATE ITEMS IN A DICTIONARY THUS:

>>> d
{0: 'k', 1: 'h', 2: 'a', 3: 'i', 4: 'd'}

>>> for x,y in d.items():
print(x,y)


0 k
1 h
2 a
3 i
4 d

========

THIS IS A FIRST FOR ME... AN EXCEL SHEET (IN CSV FORMAT) ADDED TO A DICTIONARY WITH A SERIAL AS THE KEY:

>>> with open('results.csv') as f:
reader=csv.reader(f)
rng=range(100)
d=dict(zip(rng,reader))
5 Khalid's Python Journal: Code I Rode with Notes There is a difference between functions and method. For example: l=list(“khalid”) sorted(l) This will produce a sorted list of l. l itself...

No comments:

Post a Comment

<