by Vikrant Patil
at MIT Pune, IT Dept. Mar 12-16, 2018
Notes are available online at
print("Hello World!")
name = input()
print(name)
There are integers
1 + 2
2 -3
2 *3
4/2
5//2
2 ** 3
2 ** 100
2 ** 1000
5 % 2
There are floats
2.3 + 3.4
There are strings
name = "Rupali"
print(name)
single = 'a string " quote inside it'
print(single)
doublequotes = "a string with ' inside it"
print(doublequotes)
name
surname = "Rupak"
name + surname
x = "Rupali" "Rupak"
x
star = "*"
star*5
"="*20
multiline = """
this is
multi line string
with few
lines in
it
"""
print(multiline)
s = "sdkjfhsdkjfhdskhjgf sdjgsad dkjhfds gkjhdsfgkjhadfg ksdjhgfkjdshg kjdfhg dfkjghdfgkjdsfh g dfkghdfkjgh dsfkhkgjdsfh "
s
print(multiline)
multiline
twolines = "one\ntwo\t2"
print(twolines)
name1 = "Rupali Rupak"
name1
"""one
two
three"""
unicode = "\u0c85"
print(unicode)
regional = "आ ड ब"
regional
empty = ""
print(empty)
empty
There are binary arrays
binary = b"This is binary string"
binary
binary1 = "\x056"
binary1
There are higher level data types.. Lists
digits = [0,1,2,3,4,5,6,7,8,9]
print(digits)
digits[0]
digits[-1]
digits[1:] # drop first
digits[3:] #drop first 3
digits[:3] # take first three
ones = [1,1,1,1]
ones + ones
firstthree = digits[:3]
firstthree
digits
ones
ones + ones
ones * 5
ones - ones
ones * 1.2
ones - 1
mixed = ["ones", "two", 1, 2, 3]
mixed
m = [[1,2,3],[4,5,6],[7,8,9]]
m[0] # 0th row
m[-1] # last row
m[0][2] #2nd element from 0th row
ones
ones[0]
ones[0] = 0
ones
ones[0] = 1
tuples .. sibling of lists
t = (0,1,2,3,4)
t + t
t * 4
t[0]
t[-1]
t[2:]
t[0] = 1
origin = (0,0)
origin[0] = 2
person = {"name":"alice", "email":"alice@wonder.land",
"place":"wonmderland", "PIN":42}
person
person["name"]
person["place"]
person['email']
person
person["PIN"]
d = {"integer":2,
"list":[1,2,3,4],
"tuple":(1,2,3),
2:"two"}
d
person['PIN'],person['email']
x,y = 2,3
There are sets
s = {1,2,3}
sentence = """This is a randome statement from which we
will find out which english alphabets are used in this!"""
alphabets = set(sentence)
alphabets
s = "first second \nthird"
print(s)
s
pre = "Isac"
post = "Asimove"
pre post
"Isac" "Asimove"
{"key":{"one":1}}
len("what is length of this string")
len([1,2,3,4,5])
len((0,1,2,3,4))
len(person)
len(alphabets)
int("43")
int("A")
str(43)
list((1,2,3,4))
t = (1,2,3,4)
l = list(t)
l
t
range(10)
list(range(10))
#list(range(100))
sum([1,2,3])
sum(["one", "two", "three"])
help(sum)
sum(["one", "two", "three"])
sum((1,2,3,4,5))
problems
find number of digits in 2^1000
2**1000
n = 2**1000
n
digits = str(n)
digits
len(digits)
2 ** 100
x = 2**100
def add(x, y):
s = x + y
return s
def dummy():
pass
def do_nothing():
print("Print nothing")
s = 2 +3
def twice(x):
return 2*x
add(2,3)
dummy()
twice(3)
do_nothing()
problem
count_digits which counts number of digits from given numbersum_natural to find sum of first n natural numbersdef twice(x):
return 2*x
def twice1(x):
print(2*x)
What will be output of
print(twice(twice(3)))
What will be output of
print(twice1(twice1(4)))
a = add(2,3)
print(a)
def dummy():
pass
r = dummy()
print(r)
r
def twice(x):
return 2*x
def twice1(x):
print(2*x)
twice(3)
twice1(4)
t = twice(3)
print(t)
t1 = twice1(4)
t1
print(t1)
x = 2
x
def fun(x):
return 3*x
fun
print(x)
print(fun)
y = x
print(y)
aliasfun = fun
print(aliasfun)
print(fun)
fun(3)
aliasfun(4)
def sqaure(x):
return x*x
def sumofsquares(x,y):
return sqaure(x) + sqaure(y)
def cube(x):
return x*x*x
def sumofcubes(x,y):
return cube(x) + cube(y)
def sumof(f, x , y):
return f(x) + f(y)
sumofsquares(2,3)
sumof(sqaure, 2, 3)
sumofcubes(2,3)
sumof(cube, 2, 3)
def make_adder(x):
def adder(y):
return x+y
return adder
adder5 = make_adder(5)
adder5
type(adder5)
adder5(6)
adder5(7)
adder4 = make_adder(4)
adder4(5)
sum3 = lambda x,y,z : x+y+z
sum3(2,3,4)
problem
def make_adder(x):
return lambda y: x+y
max([3,4,51,2,3,4])
max(["one","two","three","four","five"])
words = ["one","two","three","four","five"]
max(words)
max(words, key=len)
records = [
("A", 7.8),
("B", 8.7),
("C", 7.0),
("D", 5.5),
("E", 7.7)
]
records
max(records)
def get_score(t):
return t[1]
max(records, key=get_score)
min(records)
min(records, key=get_score)
sorted(records, key=get_score)
sorted(words, key=len)
sorted(words)
sorted(records, key=lambda r:r[1])
Strings
s = "Some random statement"
s.lower()
s.upper()
s.count("e")
s.split(" ")
s.split()
words
"_".join(words)
"/".join(["","home","vikrant", "trainings","2018"])
" ".join(words)
trailingspces = " jdkslfd kjdhsfkjhsd kjhfsdkfh "
trailingspces.strip()
"Wizard of oz was lisp".replace("lisp", "python")
filename = "hello.py"
filename.startswith("hello")
filename.endswith(".py")
s.center(50)
s.rjust(50)
s.ljust(50)
Lists
numbers = list(range(10))
numbers
numbers.count(0)
ones.count(1)
ones
numbers.append(10)
numbers
numbers.pop()
numbers
numbers.pop(0)
numbers
numbers.insert(0, -1)
numbers
numbers.pop()
numbers.pop(0)
numbers
numbers.sort()
numbers
numbers.sort(reverse=True)
numbers
numbers.reverse()
numbers
words
words.sort(key=len)
words
sorted(words, key=len, reverse=True)
words.extend(["six", "seven"])
words
problem
count_zeros which counts number of zeros in given number
>>> count_zeros(1000)
3
head which returns first n elements from a list
>>> head([1,2,3,4,5,6,7,8,9], 4)
[1,2,3,4]
rearrangemax which rearranges digits of given number to form a max number out of it.
>>> rearrangemax(5498)
9854
sum = 6
sum([1,2,3])
del sum
sorted("hello world")
def count_zeros(n):
return str(n).count("0")
def head(items, n):
return items[:n]
def rearrangemax(n):
strn = str(n)
orderd = sorted(strn, reverse=True)
return int("".join(orderd))
count_zeros(10002)
head([1,2,3,4,5,6,7], 3)
rearrangemax(5678)
filename
i = filename.index(".")
filename[i+1:]
filename.split(".")
filename.split(".")[-1]
tuples
t = (1,1,1,1,0,0,0)
t.count(1)
t.index(0)
t.append(0)
t.sort()
import os
os
type(os)
os.getcwd()
os.listdir(os.getcwd())
os.listdir("/home/")
import math
math.pi
math.sin(math.pi)
from math import cos
cos(3.14)
import math as m
m.pi
m.sin(m.pi)
del math
math
m
m.pi
cos
from math import sin
sin(3.14)
math
os.path.exists("/home")
os.path.getsize("day1.ipynb")
os.listdir(os.getcwd())
def count_files(path):
return len(os.listdir(path))
count_files("/home/vikrant")
count_files(".")
os.mkdir("/tmp/xyz")
os.path.exists("/tmp/xyz")
os.path.exists("/tmp/xyz1")
True
False
problem
biggestfile to find file with largest size from given directoryimport os
def biggestfile(path):
files = os.listdir(path)
return max(files, key=os.path.getsize)
biggestfile(".")
%%file module.py
x = 42
def square(x):
return x*x
def mean(x,y):
return (x+y)/2
def add(x,y):
return x+y
def say_hello(name):
print("Hello ", name)
import module
module.x
module.square(43)
module.say_hello("python!")
%%file module1.py
import sys
def say_hello(name):
print("Hello ", name)
print(sys.argv)
!python module1.py MIT
!python module1.py MIT ITDEPT PUNE
%%file hello.py
import sys
def say_hello(name):
print("Hello ", name)
say_hello(sys.argv[1])
!python hello.py MIT