def factors(n):
return [i for i in range(1, n+1) if n%i==0]
Module 2 - Day 2
problems
- Write a function
factorswhich finds all factors of given number (include 1 and self) - write a function
is_primewhich tells if given number is prime or not - Write a list comprehension to generate prime numbers less than 100
factors(5)[1, 5]
factors(10)[1, 2, 5, 10]
factors(16)[1, 2, 4, 8, 16]
factors(7)[1, 7]
def is_prime(n):
return len(factors(n)) == 2 is_prime(5)True
is_prime(13)True
is_prime(12)False
[p for p in range(1, 100) if is_prime(p)][2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97]
def is_prime1(n):
if len(factors(n)) == 2:
print("True")
else:
print("False")[p for p in range(10) if is_prime1(p)]False
False
True
True
False
True
False
True
False
False
[]
l = [1, 2, 3]
el = [] # result into False in if statement
text = "sdsdasd"
etext = "" # result into False in if statement
x = None # result into False in if statement
if x:
print("X is True")
else:
print("X is False")X is False
text = "sdsdasd"
if text:
print("This text is not empty")
else:
print("The text is empty")This text is not empty
Reading files
%%file zen.txt
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!Overwriting zen.txt
%%file sample.txt
ksjdkjs
kjdshfkjds
some data has to be given
here is next lineWriting sample.txt
with open("zen.txt") as filehandle:
contents = filehandle.read() # read complete file as single string
# here the file is closed
print(contents)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!
with open("zen.txt") as f: # this variable f, which corresponds to file handle object is valid only in in with block
for i in range(4):
print(f.readline()) # this will read only one line at a time.The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
with open("zen.txt") as f: # this variable f, which corresponds to file handle object is valid only in in with block
lines = [f.readline() for i in range(4)]
lines['The Zen of Python, by Tim Peters\n',
'\n',
'Beautiful is better than ugly.\n',
'Explicit is better than implicit.\n']
print("hello") # it prints hello and a new line
print("World")hello
World
with open("zen.txt") as f: # this variable f, which corresponds to file handle object is valid only in in with block
for i in range(4):
print(f.readline(), end="") # this will ensure that print will add its own new line character at endThe Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
with open("zen.txt") as f: # this variable f, which corresponds to file handle object is valid only in in with block
for i in range(4):
print(f.readline().strip()) # this will ensure that print will add its own new line character at endThe Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
" hello ".strip()'hello'
"hello \n".strip()'hello'
with open("zen.txt") as f:
for line in f: # f also works as iterator, you can put for loop on it to read line by line
print(line, end="")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!
with open("zen1.txt") as f:
print(f.read())FileNotFoundError: [Errno 2] No such file or directory: 'zen1.txt'
%%file zen1.txt
write some data
some text
to play with
then try to read it using
python!Writing zen1.txt
with open("zen1.txt") as f:
print(f.read())write some data
some text
to play with
then try to read it using
python!
problem
Write a python script cat.py which takes filename as argument and prints contents of file on screen
python cat.py zen1.txt
write some data
some text
to play with
then try to read it using
python!
%%file cat.py
import sys
def cat(filename):
with open(filename) as f:
print(f.read())
file = sys.argv[1] # take first argument. zeroth one is always script name
cat(file)Writing cat.py
!python cat.py zen.txtThe 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!
problem
Write a python script wc.py which mimics unix command wc. It should show line count , word count and character count of a file.
!python wc.py zen.txt
21 144 857 zen.txt
filehandle = open("sample.txt")filehandle.readline()'ksjdkjs\n'
filehandle.readline()'kjdshfkjds\n'
filehandle.close()with open("sample.txt") as filehandle:
print(filehandle.readline())ksjdkjs
with open("sample.txt") as samplefile:
print(samplefile.readline())ksjdkjs
for c in "texakjsdhakj kjdsah":
print(c, end=",")t,e,x,a,k,j,s,d,h,a,k,j, ,k,j,d,s,a,h,
for char_ in "texakjsdhakj kjdsah":
print(char_, end=",")t,e,x,a,k,j,s,d,h,a,k,j, ,k,j,d,s,a,h,
len("sdfsdfds\n jkhdsf ksjhdkjshfa \n kjhsakjdhsaf")44
Q: Do we need to convert the data read from file into str?
No
file.read() # this already a string
file.readline() # is also a string
with open("sample.txt") as w:
print(xyz.read())NameError: name 'xyz' is not defined
with open("sample.txt") as w:
print(w.read())ksjdkjs
kjdshfkjds
some data has to be given
here is next line
with open("sample.txt") as f:
print(f.read()) # this will complete file! that means after this the iterator is consumed!
print("End of f.read()")
print(f.readline()) # this will be empty string here
print("End of f.readline()")ksjdkjs
kjdshfkjds
some data has to be given
here is next line
End of f.read()
End of f.readline()
%%file short.txt
one
twoWriting short.txt
S = open("short.txt")S.readline()'one\n'
S.readline()'two\n'
S.readline()''
S.read()''
S.close()contents = """ljsadlj skjasd
kjsahdkjhsa
hdsfkjhds
dsflkd;flk lkdsjfdsjf
kjdshfkjdhsjf
kjhdfkjhds kjshdfkjdsh sdfahdkjfh"""contents'ljsadlj skjasd\nkjsahdkjhsa\nhdsfkjhds\ndsflkd;flk lkdsjfdsjf\nkjdshfkjdhsjf \nkjhdfkjhds kjshdfkjdsh sdfahdkjfh'
def countchars(contents):
return len(contents)
def countlines(contents):
lines = contents.split("\n")
return len(lines)
def countwords(contents):
words = contents.split()
return len(words)countchars(contents)107
countlines(contents)6
countwords(contents)10
%%file add.py
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
a + b # this will not print the expected result Overwriting add.py
a, b = 3, 5
a+b8
!python add.py 3 5%%file add1.py
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
print(a + b) # this will print the expected result Overwriting add1.py
!python add1.py 3 58
%%file add2.py
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
def add(x, y):
return x+y
add(a,b) # this will not print the expected result Overwriting add2.py
!python add2.py 3 5%%file add3.py
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
def add(x, y):
return x+y
print(add(a,b)) # this will print the expected result Writing add3.py
!python add3.py 3 58
def add(x, y):
return x + yadd(4, 5) # this is not same as print9
%%file wc.py
import sys
def readfile(filename):
with open(filename) as f:
return f.read()
def countchars(contents):
return len(contents)
def countlines(contents):
lines = contents.split("\n")
return len(lines)
def countwords(contents):
words = contents.split()
return len(words)
def wc(filename):
contents = readfile(filename)
l = countlines(contents)
w = countwords(contents)
c = countchars(contents)
print(l, w, c, filename)
filename = sys.argv[1]
wc(filename)Writing wc.py
!python wc.py zen.txt22 144 857 zen.txt
%%file wc1.py
import sys
def wc(filename):
lines = 0
words = 0
chars = 0
with open(filename) as f:
for line in f:
lines += 1
words += len(line.split())
chars += len(line)
print (lines, words, chars)
file= sys.argv[1]
wc(file)Writing wc1.py
problem
Write a function read_price_column to read price column from csv file which has indexdata written in it that we used yesterday.
>>> read_price_column("data.csv")
[111.71436961893693,
141.21220022208635,
112.40571010053796,
137.54133351926248,
140.25154281801224,
235.0403622499107,
225.0206535036475,
216.10342426936444,
200.38038844494193,
235.80850482793264,
321.49182055844256,
340.63612771662815,
303.9065277507285,
338.1350605764038,
318.3912296144338]
%%file data.csv
symbol,day,price
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 Overwriting data.csv
def read_price_column(filename):
prices = []
with open(filename) as f:
headers = f.readline().strip().split(",") # firstline
price_index = headers.index("price")
for line in f:
fields = line.strip().split(",")
p = fields[price_index]
prices.append(p)
return pricesread_price_column("data.csv")['111.71436961893693',
'141.21220022208635',
'112.40571010053796',
'137.54133351926248',
'140.25154281801224',
'235.0403622499107',
'225.0206535036475',
'216.10342426936444',
'200.38038844494193',
'235.80850482793264',
'321.49182055844256',
'340.63612771662815',
'303.9065277507285',
'338.1350605764038',
'318.3912296144338']
def read_price_column(filename):
prices = []
with open(filename) as f:
headers = f.readline().strip().split(",") # firstline
price_index = headers.index("price")
for line in f:
fields = line.strip().split(",")
p = float(fields[price_index])
prices.append(p)
return pricesread_price_column("data.csv")[111.71436961893693,
141.21220022208635,
112.40571010053796,
137.54133351926248,
140.25154281801224,
235.0403622499107,
225.0206535036475,
216.10342426936444,
200.38038844494193,
235.80850482793264,
321.49182055844256,
340.63612771662815,
303.9065277507285,
338.1350605764038,
318.3912296144338]
"this is some text data".split(" ")['this', 'is', 'some', 'text', 'data']
"this is some text data".split()['this', 'is', 'some', 'text', 'data']
"this-is-text-data".split("-")['this', 'is', 'text', 'data']
"x,y,z".split(",")['x', 'y', 'z']
"x,y,z\n".split(",")['x', 'y', 'z\n']
"x,y,z\n".strip().split(",")['x', 'y', 'z']
Writing files
To write file we use similar approach to open file, but we open in write mode
Writing file using write and text mode
passing “w” as second argument to open function will open the file in write-text mode. This mode will overwrite the file if it already exists
with open("one.txt", "w") as f:
f.write("one")!python cat.py one.txtone
words = "one two three four five six".split()
with open("nums.txt", "w") as f:
for w in words:
f.write(w)
f.write("\n")!python cat.py nums.txtone
two
three
four
five
six
Write file in append mode
with open("nums.txt", "a") as f:
f.write("seven\n")!python cat.py nums.txtone
two
three
four
five
six
seven
path of file
with open("sample.txt") as f: # this will work only if sample.txt is in current working directory
f.read()import osos.getcwd()'/home/jupyter-vikrant/arcesium-python-2024'
with open("b.txt") as f:
f.read()FileNotFoundError: [Errno 2] No such file or directory: 'b.txt'
with open("b.txt") as f:
f.read()FileNotFoundError: [Errno 2] No such file or directory: 'b.txt'
with open("/home/jupyter-vikrant/b.txt") as f: # absolute path
print(f.read())hello this
is some text
with open("../b.txt") as f: # absolute path
print(f.read())hello this
is some text