Module II - Day 4

Python Made Easy: Science and Math Edition

Sep-Dec 2025 batch, Vikrant Patil

Date: 07 Dec 2025

Click here for All Notes

Live note are here https://vikrant.dev/python-made-easy-science-math/students-module2-day4.html

Please login to https://traininghub.vikrant.dev and create a notebook with name module2-day4.ipynb

© Vikrant Patil

List Comprehensions

names = ["pallavi", "samiha", "poorva", "vikrant"]
for name in names:
    print(name)
pallavi
samiha
poorva
vikrant
upper_words = []
for w in names:
    upper_words.append(w.upper())
upper_words
['PALLAVI', 'SAMIHA', 'POORVA', 'VIKRANT']
nums = [1, 3, 5, 6,2, 43, 6]
sqr = []
for n in nums:
    sqr.append(n*n)
sqr
[1, 9, 25, 36, 4, 1849, 36]
for i in nums:
    print(i)
1
3
5
6
2
43
6
for num in nums:
    print(num)
1
3
5
6
2
43
6
[ n*n for n in nums]
[1, 9, 25, 36, 4, 1849, 36]
[n**3 for n in nums]
[1, 27, 125, 216, 8, 79507, 216]
def poly(x):
    return x**2 + 2*x + 1
[poly(n) for n in nums]
[4, 16, 36, 49, 9, 1936, 49]
[w.upper() for w in names]
['PALLAVI', 'SAMIHA', 'POORVA', 'VIKRANT']
ticker = ["INFY", "M&M", "AT&T", "APPLE"]
values = [1000.0, 800.5, 700.0, 6832.5]
stocks = {"INFY": 1000.0,
           "M&M": 800.5}
stocks['INFY']
1000.0
for t, v in zip(ticker, values):
    print(t, v)
INFY 1000.0
M&M 800.5
AT&T 700.0
APPLE 6832.5
stocks = {}
for t, v in zip(ticker, values):
    stocks[t] = v
stocks
{'INFY': 1000.0, 'M&M': 800.5, 'AT&T': 700.0, 'APPLE': 6832.5}
{t:v for t, v in zip(ticker, values)}
{'INFY': 1000.0, 'M&M': 800.5, 'AT&T': 700.0, 'APPLE': 6832.5}
{t.lower(): int(v) for t, v in zip(ticker, values)}
{'infy': 1000, 'm&m': 800, 'at&t': 700, 'apple': 6832}
x, y = 10, 20
a, b, c, = 1, 2, 3
zip(ticker, values)
<zip at 0x7f5ba04aef80>
list(zip(ticker, values))
[('INFY', 1000.0), ('M&M', 800.5), ('AT&T', 700.0), ('APPLE', 6832.5)]
x = ["x1", "x2", "x3", "x4", "x5"]
y = ["y1", "y2", "y3", "y4", "y5"]
z = ["z1", "z2", "z3", "z4", "z5"]
for i, j, k in zip(x, y, z):
    print(i, j, k)
x1 y1 z1
x2 y2 z2
x3 y3 z3
x4 y4 z4
x5 y5 z5
list(zip(x, y, z))
[('x1', 'y1', 'z1'),
 ('x2', 'y2', 'z2'),
 ('x3', 'y3', 'z3'),
 ('x4', 'y4', 'z4'),
 ('x5', 'y5', 'z5')]
 indexdata = [('IBM', 'Monday', 111.71436961893693),
            ('IBM', 'Tuesday', 141.21220022208635),
            ('IBM', 'Wednesday', 112.40571010053796),
            ('IBM', 'Thursday', 137.54133351926248),
            ('IBM', 'Friday', 140.25154281801224),
            ('MICROSOFT', 'Monday', 235.0403622499107),
            ('MICROSOFT', 'Tuesday', 225.0206535036475),
            ('MICROSOFT', 'Wednesday', 216.10342426936444),
            ('MICROSOFT', 'Thursday', 200.38038844494193),
            ('MICROSOFT', 'Friday', 235.80850482793264),
            ('APPLE', 'Monday', 321.49182055844256),
            ('APPLE', 'Tuesday', 340.63612771662815),
            ('APPLE', 'Wednesday', 303.9065277507285),
            ('APPLE', 'Thursday', 338.1350605764038),
            ('APPLE', 'Friday', 318.3912296144338)]
[ name  for name, day, value in indexdata]
['IBM',
 'IBM',
 'IBM',
 'IBM',
 'IBM',
 'MICROSOFT',
 'MICROSOFT',
 'MICROSOFT',
 'MICROSOFT',
 'MICROSOFT',
 'APPLE',
 'APPLE',
 'APPLE',
 'APPLE',
 'APPLE']
[ (name, value)  for name, day, value in indexdata]
[('IBM', 111.71436961893693),
 ('IBM', 141.21220022208635),
 ('IBM', 112.40571010053796),
 ('IBM', 137.54133351926248),
 ('IBM', 140.25154281801224),
 ('MICROSOFT', 235.0403622499107),
 ('MICROSOFT', 225.0206535036475),
 ('MICROSOFT', 216.10342426936444),
 ('MICROSOFT', 200.38038844494193),
 ('MICROSOFT', 235.80850482793264),
 ('APPLE', 321.49182055844256),
 ('APPLE', 340.63612771662815),
 ('APPLE', 303.9065277507285),
 ('APPLE', 338.1350605764038),
 ('APPLE', 318.3912296144338)]
nums = [1, 3, 5, 6,2, 43, 6]
sqr = []
for n in nums:
    if n%2==0:
        sqr.append(n*n)
sqr
[36, 4, 36]
[n*n for n in nums if n%2==0 ]
[36, 4, 36]
[(day, value)  for name, day, value in indexdata if name=="APPLE"]
[('Monday', 321.49182055844256),
 ('Tuesday', 340.63612771662815),
 ('Wednesday', 303.9065277507285),
 ('Thursday', 338.1350605764038),
 ('Friday', 318.3912296144338)]
def extract_for_day(indexdata, day_):
    {name:value for name, day, value in indexdata if day==day_}
extract_for_day(indexdata, "Monday")
def extract_for_day(indexdata, day_):
    return {name:value for name, day, value in indexdata if day==day_}
extract_for_day(indexdata, "Monday")
{'IBM': 111.71436961893693,
 'MICROSOFT': 235.0403622499107,
 'APPLE': 321.49182055844256}
for item in indexdata:
    print(item)
('IBM', 'Monday', 111.71436961893693)
('IBM', 'Tuesday', 141.21220022208635)
('IBM', 'Wednesday', 112.40571010053796)
('IBM', 'Thursday', 137.54133351926248)
('IBM', 'Friday', 140.25154281801224)
('MICROSOFT', 'Monday', 235.0403622499107)
('MICROSOFT', 'Tuesday', 225.0206535036475)
('MICROSOFT', 'Wednesday', 216.10342426936444)
('MICROSOFT', 'Thursday', 200.38038844494193)
('MICROSOFT', 'Friday', 235.80850482793264)
('APPLE', 'Monday', 321.49182055844256)
('APPLE', 'Tuesday', 340.63612771662815)
('APPLE', 'Wednesday', 303.9065277507285)
('APPLE', 'Thursday', 338.1350605764038)
('APPLE', 'Friday', 318.3912296144338)
indexdata[0]
('IBM', 'Monday', 111.71436961893693)
for name, day, value in indexdata:
    print(name, day, value)
IBM Monday 111.71436961893693
IBM Tuesday 141.21220022208635
IBM Wednesday 112.40571010053796
IBM Thursday 137.54133351926248
IBM Friday 140.25154281801224
MICROSOFT Monday 235.0403622499107
MICROSOFT Tuesday 225.0206535036475
MICROSOFT Wednesday 216.10342426936444
MICROSOFT Thursday 200.38038844494193
MICROSOFT Friday 235.80850482793264
APPLE Monday 321.49182055844256
APPLE Tuesday 340.63612771662815
APPLE Wednesday 303.9065277507285
APPLE Thursday 338.1350605764038
APPLE Friday 318.3912296144338

problems

problems

  • write function listpy (just like os.listdir!) which uses list comprehension to identify py files in given directory.::
    >>> listpy(os.getcwd())
    add.py
    add1.py
    add2.py
    hello.py
  • find sum of all multiples of 7 or 11 below 1000.
  • There is a string “abrakadabra”, we want to capitalize alternate character from it. how can we do it? can a list comprehension be used to do this?

solve these in this sequence

  • Write a function factors which finds all factors of given number (include 1 and self)

  • Write a function is_prime which checks if given number is prime based on fact that prime number has only two factors 1 and self.

  • Write a list comprehension to generate prime numbers less than 100.

import os
os.listdir()
['revision.ipynb',
 'notes.qmd~',
 'say_hello.py',
 'students-module2-day4.ipynb',
 'hello.txt',
 'args1.py',
 'wallet.csv',
 'module1-day5.ipynb',
 '.quarto',
 'notes_test.qmd',
 'mymodule.py',
 'poem.txt',
 'students-practice2.ipynb',
 '_quarto.yml',
 'zen.txt',
 'hello_person.py',
 '<function invoice_number at 0x7fac68410b80>.xlsx',
 'stocks.csv',
 'styles.css',
 'index.qmd~',
 'students-module2-day4.html',
 'topics.qmd',
 'x.txt',
 'y.txt',
 'maths_test_new.py',
 'hypotheticals.csv',
 'cat.py',
 'Makefile',
 'test_args.py',
 'module2-day1.ipynb',
 'a.pdf',
 'today.org',
 'helloworld.py',
 'trainer.qmd~',
 'notes.qmd',
 'module1-day1.ipynb',
 'notes_test.html',
 'wallet.xlsx',
 'students-module2-day3.ipynb',
 'students-module2-day3_files',
 'module1-day2.ipynb',
 'c.pdf',
 'push',
 'invoice-automation.org',
 'Makefile~',
 'module2-day4.ipynb',
 'image.xlsx',
 'b.pdf',
 'notes.html',
 'module2-day1.html',
 'students-practice2.html',
 'module2-day5.ipynb',
 'module3-day3.ipynb',
 'tail.py',
 'power.py',
 'revision.html',
 '_site',
 'module2-day3.ipynb',
 'module3-day1.ipynb',
 'records.csv',
 'problems.ipynb',
 'module1-day4.ipynb',
 'test_prog.py',
 'head.py',
 'module3-day2.ipynb',
 'topics.html',
 'mymodule1.py',
 'students-module1-day2.ipynb',
 'students-module1-day3.ipynb',
 'students-practice3.ipynb',
 'l.html',
 'site_libs',
 'n.html',
 'Untitled.ipynb',
 'trainer.qmd',
 'welcome_multi_lingual.py',
 'module2-practice.ipynb',
 'z.txt',
 'students-module2-day2.ipynb',
 'test_exception.py',
 'bosch.csv',
 'chaos1.py',
 'square.py',
 'po1.csv',
 '__pycache__',
 'invoice-generator.py',
 '.ipynb_checkpoints',
 'm.html',
 'testargs.py',
 '.gitignore',
 'about.qmd~',
 'Untitled1.ipynb',
 'hello.py',
 'module1-day5.html',
 'maths_test.py',
 'wallet-category.csv',
 'copyzen.txt',
 '_quarto.yml~',
 'topics.qmd~',
 'promotions',
 'index.qmd',
 'invoice-automation.org~',
 'module1-day3.ipynb',
 'chaos.py',
 'module1-day1.html',
 'students-module1-day4.ipynb',
 'students-practice.ipynb']
files = os.listdir()
[i for i in nums if i%2==1]
[1, 3, 5, 43]
"vikrant".endswith("t")
True
files
['revision.ipynb',
 'notes.qmd~',
 'say_hello.py',
 'students-module2-day4.ipynb',
 'hello.txt',
 'args1.py',
 'wallet.csv',
 'module1-day5.ipynb',
 '.quarto',
 'notes_test.qmd',
 'mymodule.py',
 'poem.txt',
 'students-practice2.ipynb',
 '_quarto.yml',
 'zen.txt',
 'hello_person.py',
 '<function invoice_number at 0x7fac68410b80>.xlsx',
 'stocks.csv',
 'styles.css',
 'index.qmd~',
 'topics.qmd',
 'x.txt',
 'y.txt',
 'maths_test_new.py',
 'hypotheticals.csv',
 'cat.py',
 'Makefile',
 'test_args.py',
 'module2-day1.ipynb',
 'a.pdf',
 'today.org',
 'helloworld.py',
 'trainer.qmd~',
 'notes.qmd',
 'module1-day1.ipynb',
 'wallet.xlsx',
 'students-module2-day3.ipynb',
 'module1-day2.ipynb',
 'c.pdf',
 'push',
 'invoice-automation.org',
 'Makefile~',
 'module2-day4.ipynb',
 'image.xlsx',
 'b.pdf',
 'module2-day5.ipynb',
 'module3-day3.ipynb',
 'tail.py',
 'power.py',
 '_site',
 'module2-day3.ipynb',
 'module3-day1.ipynb',
 'records.csv',
 'problems.ipynb',
 'module1-day4.ipynb',
 'test_prog.py',
 'head.py',
 'module3-day2.ipynb',
 'mymodule1.py',
 'students-module1-day2.ipynb',
 'revision_files',
 'students-module1-day3.ipynb',
 'students-practice3.ipynb',
 'l.html',
 'n.html',
 'Untitled.ipynb',
 'trainer.qmd',
 'welcome_multi_lingual.py',
 'module2-practice.ipynb',
 'z.txt',
 'students-module2-day2.ipynb',
 'test_exception.py',
 'bosch.csv',
 'chaos1.py',
 'square.py',
 'po1.csv',
 '__pycache__',
 'invoice-generator.py',
 '.ipynb_checkpoints',
 'm.html',
 'testargs.py',
 '.gitignore',
 'about.qmd~',
 'Untitled1.ipynb',
 'hello.py',
 'maths_test.py',
 'wallet-category.csv',
 'copyzen.txt',
 '_quarto.yml~',
 'topics.qmd~',
 'promotions',
 'index.qmd',
 'invoice-automation.org~',
 'module1-day3.ipynb',
 'chaos.py',
 'students-module1-day4.ipynb',
 'students-practice.ipynb']
files[0].endswith(".py")
False
import os

def listpy(folder):
    files = os.listdir(folder)
    return [f for f in files if f.endswith(".py")]
listpy(os.getcwd())
['say_hello.py',
 'args1.py',
 'mymodule.py',
 'hello_person.py',
 'maths_test_new.py',
 'cat.py',
 'test_args.py',
 'helloworld.py',
 'tail.py',
 'power.py',
 'test_prog.py',
 'head.py',
 'mymodule1.py',
 'welcome_multi_lingual.py',
 'test_exception.py',
 'chaos1.py',
 'square.py',
 'invoice-generator.py',
 'testargs.py',
 'hello.py',
 'maths_test.py',
 'chaos.py']
import os

def filter_ext(folder, ext):
    files = os.listdir(folder)
    return [f for f in files if f.endswith(ext)]
filter_ext(os.getcwd(), ".py")
['say_hello.py',
 'args1.py',
 'mymodule.py',
 'hello_person.py',
 'maths_test_new.py',
 'cat.py',
 'test_args.py',
 'helloworld.py',
 'tail.py',
 'power.py',
 'test_prog.py',
 'head.py',
 'mymodule1.py',
 'welcome_multi_lingual.py',
 'test_exception.py',
 'chaos1.py',
 'square.py',
 'invoice-generator.py',
 'testargs.py',
 'hello.py',
 'maths_test.py',
 'chaos.py']
filter_ext(os.getcwd(), ".txt")
['hello.txt', 'poem.txt', 'zen.txt', 'x.txt', 'y.txt', 'z.txt', 'copyzen.txt']
filter_ext(os.getcwd(), ".xlsx")
['<function invoice_number at 0x7fac68410b80>.xlsx',
 'wallet.xlsx',
 'image.xlsx']
filter_ext(os.getcwd(), ".ipynb")
['revision.ipynb',
 'students-module2-day4.ipynb',
 'module1-day5.ipynb',
 'students-practice2.ipynb',
 'module2-day1.ipynb',
 'module1-day1.ipynb',
 'students-module2-day3.ipynb',
 'module1-day2.ipynb',
 'module2-day4.ipynb',
 'module2-day5.ipynb',
 'module3-day3.ipynb',
 'module2-day3.ipynb',
 'module3-day1.ipynb',
 'problems.ipynb',
 'module1-day4.ipynb',
 'module3-day2.ipynb',
 'students-module1-day2.ipynb',
 'students-module1-day3.ipynb',
 'students-practice3.ipynb',
 'Untitled.ipynb',
 'module2-practice.ipynb',
 'students-module2-day2.ipynb',
 'Untitled1.ipynb',
 'module1-day3.ipynb',
 'students-module1-day4.ipynb',
 'students-practice.ipynb']
os.getcwd()
'/home/vikrant/programming/work/github/vikrant.dev/python-made-easy-science-math'
listpy("test")
['untitled1.py', 'untitled.py', 'a1.py']
import random

def generate_random_points(n):
    return [(random.choice(range(0, 50)),
             random.choice(range(0, 50)),
            random.choice(range(0, 50))) for i in range(n)]
generate_random_points(10)
[(49, 32, 18),
 (23, 23, 20),
 (24, 31, 33),
 (26, 30, 36),
 (21, 24, 39),
 (40, 42, 5),
 (14, 5, 12),
 (29, 22, 23),
 (10, 39, 1),
 (30, 37, 24)]
with open("points.csv", "w") as f:
    for x, y, z in generate_random_points(10):
        f.write(str(x))
        f.write(",")
        f.write(str(y))
        f.write(",")
        f.write(str(z))
        f.write("\n")

        
points = generate_random_points(10)
points
[(1, 39, 46),
 (20, 0, 25),
 (32, 39, 9),
 (35, 6, 34),
 (5, 20, 19),
 (22, 27, 44),
 (0, 27, 42),
 (14, 38, 21),
 (36, 2, 20),
 (16, 38, 37)]
[(x+10, y, z) for x, y, z in points]
[(11, 39, 46),
 (30, 0, 25),
 (42, 39, 9),
 (45, 6, 34),
 (15, 20, 19),
 (32, 27, 44),
 (10, 27, 42),
 (24, 38, 21),
 (46, 2, 20),
 (26, 38, 37)]
def read_points(filename):
    with open(filename) as f:
        return [line.strip().split(",") for line in f]
            
!cat points.csv
19,24,30
34,47,28
27,16,33
11,37,44
18,31,29
23,22,2
47,31,26
2,1,20
45,5,1
40,0,27
read_points("points.csv")
[['19', '24', '30'],
 ['34', '47', '28'],
 ['27', '16', '33'],
 ['11', '37', '44'],
 ['18', '31', '29'],
 ['23', '22', '2'],
 ['47', '31', '26'],
 ['2', '1', '20'],
 ['45', '5', '1'],
 ['40', '0', '27']]
def convert_int(textints):
    return [int(x) for x in textints]

def read_points(filename):
    with open(filename) as f:
        return [convert_int(line.strip().split(",")) for line in f]
            
points = read_points("points.csv")
def shift_x(points, shiftby):
    return [(x+shiftby, y, z) for x, y, z in points]
primeshift_x(points, 20)
[(39, 24, 30),
 (54, 47, 28),
 (47, 16, 33),
 (31, 37, 44),
 (38, 31, 29),
 (43, 22, 2),
 (67, 31, 26),
 (22, 1, 20),
 (65, 5, 1),
 (60, 0, 27)]
points
[[19, 24, 30],
 [34, 47, 28],
 [27, 16, 33],
 [11, 37, 44],
 [18, 31, 29],
 [23, 22, 2],
 [47, 31, 26],
 [2, 1, 20],
 [45, 5, 1],
 [40, 0, 27]]
sum([m for m in range(1000) if m%7==0 or m%11==0])
110110
def foo():
    return sum([i for i in range(100) if i%3==0])
foo()
1683
foo()
1683
def sum_():
    return [n for n in range(1000) if n%7==0 or n%11==0]
sum(sum_())
110110
text = "abrakadabra"
text[2:5:1]
'rak'
text[::2]
'arkdba'
text[1::2]
'baaar'
word1 = text[::2]
word2 = text[1::2]
word2 = word2.upper()
word1
'arkdba'
word2
'BAAAR'
len(word1)
6
len(word2)
5
[c1+c2 for c1,c2 in zip(word1, word2)]
['aB', 'rA', 'kA', 'dA', 'bR']
["one", "two", "three"]
['one', 'two', 'three']
"one-two-three".split("-")
['one', 'two', 'three']
"".join([c1+c2 for c1,c2 in zip(text[::2], text[1::2].upper())]) + text[-1]
'aBrAkAdAbRa'