Oct 25-31, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/arcesium-basic-oct/day4.html © Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
names = ["Elsa", "Elisa", "Alex", "Oz"]
surnames = ["Frozen", "Hacker", "Lion", "Wizard"]
for name in names:
print(name)
for name in reversed(names):
print(name)
reversednames = reversed(names) # do not use it like this, use it inside for loops only!
print(reversednames)
for name in reversednames:
print(name)
for name in reversednames:
print(name)
for i, name in enumerate(names):
print(i , name)
with open("numbers.txt") as f:
for i, line in enumerate(f):
print(i+1, line, end="")
nums = [i for i in range(10000)]
len(nums)
nums_ = (i for i in range(10000))
nums_
len(nums)
len(nums_)
sum(nums)
sum(nums_)
sum(nums_)
nums_1 = (i for i in range(10000))
a = 10
b = a
a = 20
print(a)
print(b)
la = [1,2,3,4]
lb = la
la.append(5)
lb
for name, surname in zip(names, surnames):
print(name, surname)
for a, name in zip([1,2,3,4,5,6,7], names):
print(a, name)
cart = {"Pencil":10, "Pen":15, "Eraser":5, "Box":30}
def add(*args):
print(args)
return sum(args)
add(1,2)
add(1,2,3,4,5)
def cylinder_volume(radius, height):
return 3.14*radius**2*height
cylinder_volume(1, 1.5)
cylinder_volume(1, height=2.0)
cylinder_volume(radius=1, height=2.1)
cylinder_volume(height=2.1, radius=1)
cart = {"Pencil":10, "Pen":15, "Eraser":5, "Box":30}
for item in cart:
print(item)
for item in cart:
print(cart[item])
for item, cost in cart.items():
print(item, cost)
for cost in cart.values():
print(cost)
sum([cost for cost in cart.values()])
import numpy as np
help(np.average)
np.average(list(cart.values()), weights=[0.1, 0.3, 0.4, 0.2])
cart.values()
for key, value in cart.items():
print(value, key)
for key in cart.keys():
print(key)
for key in cart:
print(key)
import random
def get_data(url, s):
return [random.random()*100 for i in range(3)]
def get_stock_data(url):
stocks = ["Tata", "Reliance", "Infosys"]
data = {}
for s in stocks:
d = get_data(url, s) # [current_price, day_change, average_of_month]
data[s] = d
return data
get_stock_data("skjadkjsahdjh")
problem
%%file words.txt
one
one two
one two three
one two three four
one two three four five
one two three four six
one two three seven
one two eight
one nine
one
l = [1,1,1,1,2,2,2,3,4]
l.count(1)
def get_words(filename):
with open(filename) as f:
return f.read().split()
get_words("words.txt")
def get_freq(words):
freq = {}
uniq = set(words)
for word in uniq:
freq[word] = words.count(word)
return freq
words = get_words("words.txt")
get_freq(words)
def get_words(filename):
with open(filename) as f:
words = []
for line in f:
words = words + line.split()
#words.extend(line.split())
return words
def get_words(filename):
with open(filename) as f:
return f.read().split()
get_words("words.txt")
def get_freq(words):
freq = {}
uniq = set(words)
for word in uniq:
freq[word] = words.count(word)
return freq
def get_freq(words):
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
return freq
cart
cart['ruler']
person = {"name":"alice", "email":"alice@wonder.land"}
person["country"]
person.get("country", "India")
def get_freq(words):
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
fr = get_freq(words)
for word, freq in fr.items():
print(word, freq)
for word, freq in fr.items():
print(word.rjust(5), freq)
for word, freq in fr.items():
print(word.rjust(5), freq*"*")
import requests
ticker = requests.get("https://koinex.in/api/ticker").json()
type(ticker)
len(ticker)
ticker.keys()
type(ticker['prices'])
len(ticker['prices'])
ticker['prices'].keys()
ticker['prices']['bitcoin']
ticker['prices']['ether']
pip install requests
answer = 42
"Answer to every question in life is {}".format(answer)
"{} of oz is {}".format("wizard", "python")
"{desg} of oz is {who}".format(desg="Wizard", who="python")
for i in range(1,11):
print(i, i*i, i*i*i)
for i in range(1,11):
print("{} {} {}".format(i, i*i, i*i*i))
for i in range(1,11):
print("{:2d} {:3d} {:4d}".format(i, i*i, i*i*i))
%%file bank0.py
balance = 0
def get_balance():
return balance
def withdraw(amount):
global balance
balance -= amount
def deposit(amount):
global balance
balance += amount
import bank0
bank0.get_balance()
bank0.deposit(100)
bank0.get_balance()
bank0.withdraw(20)
bank0.get_balance()
%%file bank1.py
def make_account():
return {"balance":0}
def get_balance(account):
return account['balance']
def withdraw(account, amount):
account['balance'] -= amount
def deposit(account, amount):
account['balance'] += amount
import bank1
a1 = bank1.make_account()
bank1.get_balance(a1)
a2 = bank1.make_account()
bank1.deposit(a1, 1000)
print("a1", bank1.get_balance(a1))
print("a2", bank1.get_balance(a2))
class BankAccount:
def __init__(account):
account.balance = 0
def get_balance(account):
return account.balance
def withdraw(account, amount):
account.balance -= amount
def deposit(account, amount):
account.balance += amount
acc1 = BankAccount() #a1 = bank1.make_account()
acc1.get_balance()
acc1.deposit(1000)
acc1.get_balance()
acc1.withdraw(20)
acc1.get_balance()
a1
class BankAccount:
def __init__(account):
account._balance = 0
def get_balance(account):
return account._balance
def withdraw(account, amount):
account._balance -= amount
def deposit(account, amount):
account._balance += amount
class BankAccount1:
"""
A class which models bank account
"""
def __init__(self, balance=0):
"""
Help for constructor of BankAccount1
"""
self._balance = balance
def get_balance(self):
return self._balance
def withdraw(self, amount):
self._balance -= amount
def deposit(self, amount):
self._balance += amount
acccount1 = BankAccount1(3000)
acccount1._balance
acccount1.get_balance()
help(BankAccount1)
problem
Write a class for working with stock data
Stock -
data:
symbol, _current
methods:
add_value
get_std
get_max
get_return
import numpy as np
class StockData:
def __init__(self, symbol, current):
self.symbol = symbol
self._current = current
self.history = [current]
self.returns = []
def add_value(self, value):
self._current = value
self.returns.append(value - self.history[-1])
self.history.append(value)
def get_max(self):
return max(self.history)
def get_std(self):
return np.std(self.history)
def get_returns(self):
return np.average(self.returns)
r = StockData("Reliance", 50)
import random
for i in range(10):
r.add_value(random.random()*5 + 50)
r.get_max()
r.get_std()
r.get_returns()
r.history
import xlsxwriter
from xlsxwriter import Workbook
workbook = Workbook(filename="sample.xlsx")
sheet = workbook.add_worksheet("sample1")
sheet.write("A1", "Some data in A1")
for i in range(1, 10):
for j in range(1, 5):
sheet.write(i, j, i*j)
workbook.close()
with Workbook(filename="sample1.xlsx") as w:
s = w.add_worksheet("s")
s.write("A1","A")
!pip install XlsxWriter
data = [["Pencil", "Pen", "Earaser", "Notebook"], [10,25,5,25]]
with Workbook(filename="format.xlsx") as w:
s = w.add_worksheet("sheet1")
bold = w.add_format({"bold":True})
number_format = w.add_format({"num_format": "$#,##0"})
s.write("A1","Products", bold)
s.write("B1", "Prices", bold)
for i,product in enumerate(data[0]):
s.write(i+1, 0, product)
for i, cost in enumerate(data[1]):
s.write(i+1, 1, cost, number_format)
data = [["Pencil",10],["Pen", 25], ["Earaser",5], ["Notebook",25]]
with Workbook(filename="tables.xlsx") as w:
s = w.add_worksheet("sheet1")
s.add_table("B2:C6",
{"data":data})
data = [["Pencil",10],["Pen", 25], ["Earaser",5], ["Notebook",25]]
with Workbook(filename="tables1.xlsx") as w:
s = w.add_worksheet("sheet1")
s.add_table("B2:C7",
{"data":data,
"columns":[{'header':"Products",'total_string':"Total"},
{'header':"Cost", "total_function":"sum"}]})