items = [1, 2, 3, 5, 6, 8]
for i in items:
print(i)
1 2 3 5 6 8
l = len(items)
for i in range(len(items)): # not recommanded way in python
print(items[l-i])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-10-6e5de25a24b1> in <module> 1 l = len(items) 2 for i in range(len(items)): # not recommanded way in python ----> 3 print(items[l-i]) IndexError: list index out of range
l = len(items)
for i in range(len(items)):
print(items[l-i-1])
8 6 5 3 2 1
for item in reversed(items):
print(item, end=",")
8,6,5,3,2,1,
first = ["Alice", "Elsa", "Alex", "Elisa"]
lastnames = ["Wondergirl", "Frozen", "Lion", "Hacker"]
for i in range(len(first)): # this is not recommanded way in python
print(first[i], lastnames[i]) # avoid puting indices, instead make use of for loop
Alice Wondergirl Elsa Frozen Alex Lion Elisa Hacker
for f,l in zip(first, lastnames):
print(f, l)
Alice Wondergirl Elsa Frozen Alex Lion Elisa Hacker
x, y = 1, 2 # python supports multiple assignments on same line
x
1
y
2
import this
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
poem = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
poem
"The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n\n"
for i, line in enumerate(poem.split("\n")):
print(i+1, line)
1 The Zen of Python, by Tim Peters 2 3 Beautiful is better than ugly. 4 Explicit is better than implicit. 5 Simple is better than complex. 6 Complex is better than complicated. 7 Flat is better than nested. 8 Sparse is better than dense. 9 Readability counts. 10 Special cases aren't special enough to break the rules. 11 Although practicality beats purity. 12 Errors should never pass silently. 13 Unless explicitly silenced. 14 In the face of ambiguity, refuse the temptation to guess. 15 There should be one-- and preferably only one --obvious way to do it. 16 Although that way may not be obvious at first unless you're Dutch. 17 Now is better than never. 18 Although never is often better than *right* now. 19 If the implementation is hard to explain, it's a bad idea. 20 If the implementation is easy to explain, it may be a good idea. 21 Namespaces are one honking great idea -- let's do more of those! 22 23
lines = poem.split("\n")
for i, line in enumerate(lines, start=1):
print(i, line)
1 The Zen of Python, by Tim Peters 2 3 Beautiful is better than ugly. 4 Explicit is better than implicit. 5 Simple is better than complex. 6 Complex is better than complicated. 7 Flat is better than nested. 8 Sparse is better than dense. 9 Readability counts. 10 Special cases aren't special enough to break the rules. 11 Although practicality beats purity. 12 Errors should never pass silently. 13 Unless explicitly silenced. 14 In the face of ambiguity, refuse the temptation to guess. 15 There should be one-- and preferably only one --obvious way to do it. 16 Although that way may not be obvious at first unless you're Dutch. 17 Now is better than never. 18 Although never is often better than *right* now. 19 If the implementation is hard to explain, it's a bad idea. 20 If the implementation is easy to explain, it may be a good idea. 21 Namespaces are one honking great idea -- let's do more of those! 22 23
ritems = reversed(items)
zipped = zip(first, lastnames)
elines = enumerate(lines)
print(ritems)
<list_reverseiterator object at 0x7fbf599640a0>
for item in ritems:
print(item)
8 6 5 3 2 1
for item in ritems:# it won't work
print(item)
for item in reversed(items):
print(item)
8 6 5 3 2 1
list(reversed(items))
[8, 6, 5, 3, 2, 1]
list(zip(first, lastnames))
[('Alice', 'Wondergirl'),
('Elsa', 'Frozen'),
('Alex', 'Lion'),
('Elisa', 'Hacker')]
for f,l in zip(first, lastnames):
print(f, l)
Alice Wondergirl Elsa Frozen Alex Lion Elisa Hacker
list(enumerate(items))
[(0, 1), (1, 2), (2, 3), (3, 5), (4, 6), (5, 8)]
list(enumerate(lines))
[(0, 'The Zen of Python, by Tim Peters'), (1, ''), (2, 'Beautiful is better than ugly.'), (3, 'Explicit is better than implicit.'), (4, 'Simple is better than complex.'), (5, 'Complex is better than complicated.'), (6, 'Flat is better than nested.'), (7, 'Sparse is better than dense.'), (8, 'Readability counts.'), (9, "Special cases aren't special enough to break the rules."), (10, 'Although practicality beats purity.'), (11, 'Errors should never pass silently.'), (12, 'Unless explicitly silenced.'), (13, 'In the face of ambiguity, refuse the temptation to guess.'), (14, 'There should be one-- and preferably only one --obvious way to do it.'), (15, "Although that way may not be obvious at first unless you're Dutch."), (16, 'Now is better than never.'), (17, 'Although never is often better than *right* now.'), (18, "If the implementation is hard to explain, it's a bad idea."), (19, 'If the implementation is easy to explain, it may be a good idea.'), (20, "Namespaces are one honking great idea -- let's do more of those!"), (21, ''), (22, '')]
Question
vector_add which adds two vectors>>> m = [[1,0,0],
[0,1,0],
[0,0,1]]
>>> is_unit_matrix(m)
True
v1 = [1, 2, 3]
v2 = [4, 5, 6]
def vector_add(vector1, vector2):
result = []
for x,y in zip(vector1, vector2):
result.append(x+y)
return result
vector_add(v1, v2)
[5, 7, 9]
def is_unit_matrix(matrix):
for i, row in enumerate(matrix):
#row[i] == 1 # checks if diagonal is one!
#sum(row) == 1 # if remaining itesms are zero
if row[i] != 1 or sum(row) != 1:
return False
return True
m = [[1,0,0],
[0,1,0],
[0,0,1]]
is_unit_matrix(m)
True
m = [[0,1,0],
[0,1,0],
[0,0,1]]
is_unit_matrix(m)
False
seq = ["one", "two", "three", "four"]
upper = []
for word in seq:
upper.append(word.upper())
upper
['ONE', 'TWO', 'THREE', 'FOUR']
upper_three = []
for item in seq:
if len(item)==3:
upper_three.append(item.upper())
upper_three
['ONE', 'TWO']
nums = [2, 3, 5, 7, 11, 13]
squares = []
for n in nums:
squares.append(n*n)
squares
[4, 9, 25, 49, 121, 169]
p = []
for item in seq:
new = do_processing(item)
p.append(new)
[do_processing(item) for item in seq] # mapping
[item for item in seq if condition(item)] # filtering
[do_proceeing(item) for item in seq if cond(item)] # conditional mapping
[x*x for x in nums]
[4, 9, 25, 49, 121, 169]
[w.upper() for w in seq]
['ONE', 'TWO', 'THREE', 'FOUR']
[w.upper() for w in seq if len(w)==3]
['ONE', 'TWO']
[w for w in seq if len(w)==4]
['four']
def cube(x):
return x*x*x
[cube(i) for i in range(5)]
[0, 1, 8, 27, 64]
Quetions
factors which finds all factors of given number (include 1 and that number itself)is_prime which will tell us if given number is prime or notprimes which has a list comprehension which genarates prime numbers less than n8%2==0
True
def factors(n):
f = []
for i in range(1, n+1):
if n%i==0:
f.append(i)
return f
factors(10)
[1, 2, 5, 10]
def factors(n):
return [i for i in range(1,n+1) if n%i==0]
factors(5)
[1, 5]
factors(6)
[1, 2, 3, 6]
def is_prime(n):
return factors(n) == [1, n]
is_prime(5)
True
is_prime(13)
True
is_prime(10)
False
def even(x):
return x%2==0
[i for i in range(10) if even(i)]
[0, 2, 4, 6, 8]
[p for p in range(10) if is_prime(p)]
[2, 3, 5, 7]
def primes(n):
return [p for p in range(1, n) if is_prime(p)]
primes(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
## can you generate all numbers less than 1000
[i for i in range(1000)]
# can you add condition to this and get only number those are multiple of 7
[i for i in range(1000) if i%7==0]
# can you add condition to this and get only number those are multiple of 7 or multiple of 11
[i for i in range(1000) if i%7==0 or i%11==0]
# I am interested in sum!
sum([i for i in range(1000) if i%7==0 or i%11==0])
110110
import os # import module os
os.getcwd() # a function from os module which will return current working directory
'/home/vikrant/trainings/2021/pccoe-python-ml'
from os import getcwd
getcwd()
'/home/vikrant/trainings/2021/pccoe-python-ml'
import os as myname
myname.getcwd()
'/home/vikrant/trainings/2021/pccoe-python-ml'
os.listdir() # contects of current working directory
['index.html', 'Lecture6-Comprehensions-1.ipynb', 'presenty5.txt', 'sample.html', 'presenty3.txt', 'Welcome.html', 'push', 'Lecture4-Working_With_Data.html', 'joy.py', 'Lecture2-Quick_Tour.ipynb', 'sample.ipynb', '#presenty4.txt#', '__pycache__', 'Untitled.html', 'Lecture4-Working_With_Data.ipynb', 'Lecture5-Comprehensions.html', 'Lecture1-Fundamental_ideas_of_programming.ipynb.ipynb', 'index.ipynb', 'presenty5.txt~', 'Lecture6-Comprehensions-1.html', 'test.html', 'Lecture5-Comprehensions.ipynb', 'Lecture3-Quick_Tour.ipynb', 'Lecture1-Fundamental_ideas_of_programming.ipynb.html', 'Makefile', 'Lecture2-Quick_Tour.html', '.ipynb_checkpoints', 'Lecture3-Quick_Tour.html']
os.listdir("/home/vikrant/trainings")
['2018', 'nakul', 'day5.org', 'hello.py', 'day5.org~', '__pycache__', '2020', 'trainingvenv', '2021', '2019', '2017', 'indexdata.xlsx']
os.path.isdir("/home/vikrant/trainings/2018/")
True
os.path.isdir("/home/vikrant/trainings/hello.py")
False
os.path.isfile("/home/vikrant/trainings/hello.py")
True
os.path.getsize("/home/vikrant/trainings/hello.py")
0
Question : Find all py files from given directory
def listpy(dirpath):
return [file for file in os.listdir(dirpath) if file.endswith(".py")]
listpy("/home/vikrant/programming/explorations/python/")
['imageplot.py', 'example.py', 'classes.py', 'crontest.py', 'process.py', 'calc.py', 'advancedlogg.py', 'commands.py', 'main_kivy.py', 'example2.py', 'pytest_raises.py', 'bulksms.py', 'excelparser.py', 'hello.py', 'grep.py', 'quicksort.py', 'para.py', 'simple_plot.py', 'bokeh_plot.py', 'simplelogging.py', 'cmdline.py', 'hugedata.py', 'watertank.py', 'primes.py', 'clickhello.py', 'feedbackemail.py', 'test_weekday.py', 'argv.py', 'coroutines.py', 'web.py', 'mobilebill.py', 'functions.py', 'weekday.py', 'sockets.py', 'generators.py', 'fibgen.py', 'fixture.py', 'webserver.py', 'fib1.py', 'pipe.py', 'pytest_mark.py', 'ammusements.py', 'multiply.py', 'x.py', 'pascal.py', 'wc.py', 'imageslice.py', 'calender.py', 'decor.py', 'setup.py']
Qustion
[2,4,6,8,10,,12,14,18,20]
[2*i for i in range(1, 11)]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[[n*i for i in range(1, 11)] for n in range(1, 6)]
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], [3, 6, 9, 12, 15, 18, 21, 24, 27, 30], [4, 8, 12, 16, 20, 24, 28, 32, 36, 40], [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
Question
tables = [[n*i for i in range(1, 11)] for n in range(1, 6)]
[row for row in tables]
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], [3, 6, 9, 12, 15, 18, 21, 24, 27, 30], [4, 8, 12, 16, 20, 24, 28, 32, 36, 40], [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
tables[0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
tables[0][3]
4
tables[1][3]
8
tables[2][3]
12
rows = len(tables)
[tables[i][3] for i in range(rows)]
[4, 8, 12, 16, 20]
def column(data, n):
rows = len(data)
return [data[i][n] for i in range(rows)]
column(tables, 0)
[1, 2, 3, 4, 5]
column(tables, 3)
[4, 8, 12, 16, 20]
def transpose(data):
numcols = len(data[0])
return [column(data, i) for i in range(numcols)]
tables
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], [3, 6, 9, 12, 15, 18, 21, 24, 27, 30], [4, 8, 12, 16, 20, 24, 28, 32, 36, 40], [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
transpose(tables)
[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25], [6, 12, 18, 24, 30], [7, 14, 21, 28, 35], [8, 16, 24, 32, 40], [9, 18, 27, 36, 45], [10, 20, 30, 40, 50]]