Example-Read a file and count words
file ex1.txt The THE ranking of world universities of each specialized subject is expanded this year to include the top 500 ones. AU is ranked to be in the top 401-500 list of the subject of “life sciences,” and is the No.3 private university in Taiwan in this specialized area. In addition, AU is ranked similarly in the subject of “clinical, pre-clinical & health,” and is the No.4 private university in Taiwan in this area.
Count the words in the file
Version-1
count = 0
with open('ex1.txt','r') as f:
for line in f:
for word in line.split():
print(word)
count += 1
print('The number of words is ', count)
Version-2
import re
count = 0
with open("ex1.txt") as f:
for line in f:
for word in re.findall('\w+[-\w+]*', line):
print(word)
count += 1
print('The number of words is ', count)
Example-99 Multiplication Table
D:\python>python mul99.py
1*1= 1 2*1= 2 3*1= 3 1*2= 2 2*2= 4 3*2= 6 1*3= 3 2*3= 6 3*3= 9 1*4= 4 2*4= 8 3*4=12 1*5= 5 2*5=10 3*5=15 1*6= 6 2*6=12 3*6=18 1*7= 7 2*7=14 3*7=21 1*8= 8 2*8=16 3*8=24 1*9= 9 2*9=18 3*9=27
Version-1
for x in range(0,3):
for y in range(1,10):
for z in range(1,4):
m = x*3+z
print ('%s*%s=%2s' % (m,y,m*y), end='\t')
print ()
print ()
Version-2
print ('\n'.join([' '.join(['%s*%s=%-2s' % (j,i,i*j) for j in range(1,10)]) for i in range(1,10)]))
Compute the greatest common divisor (GCD) of two positive integers
Version-1
def gcd(x, y):
gcd = 1
if x % y == 0:
return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
print(gcd(700,630))
Version-2
def gcd(a,b):
t = b
b = a % b
if b == 0:
return t
else:
return gcd(t,b)
print(gcd(700,630))