In [2]:
#1.1
In [29]:
def isUnique(s):
count=0
for i in s:
if s.count(i)>1:
count+=1
return (count==0)
In [35]:
isUnique('hello')
Out[35]:
In [33]:
def isUnique(s):
seen=set()
for i in s:
if i in seen:
return False
else:
seen.add(i)
return True
In [36]:
#1.2
In [41]:
def reverse(s):
#base
if len(s)==1:
return s
return s[-1]+reverse(s[:-1])
In [42]:
reverse('hello')
Out[42]:
In [ ]:
#1.3
In [45]:
def rmDublicate(s):
return "".join(set(s))
In [46]:
rmDublicate('hello')
Out[46]:
In [74]:
#1.4
In [75]:
def isAnagram(s1,s2):
s1=sorted(s1.lower())
s2=sorted(s2.lower())
if s1==s2:
return True
else:
return False
In [76]:
isAnagram('bob','obb')
Out[76]:
In [77]:
#1.5
In [78]:
def replace(s):
return s.replace(' ','%20')
In [79]:
replace('hello world')
Out[79]:
In [84]:
def rotate_matrix(matrix):
'''rotates a matrix 90 degrees clockwise'''
n = len(matrix)
for layer in range(n // 2):
first, last = layer, n - layer - 1
for i in range(first, last):
# save top
top = matrix[layer][i]
# left -> top
matrix[layer][i] = matrix[-i - 1][layer]
# bottom -> left
matrix[-i - 1][layer] = matrix[-layer - 1][-i - 1]
# right -> bottom
matrix[-layer - 1][-i - 1] = matrix[i][- layer - 1]
# top -> right
matrix[i][- layer - 1] = top
return matrix
In [85]:
a=[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]
In [86]:
rotate_matrix(a)
Out[86]:
In [133]:
def zero_matrix(mat):
m=len(mat)
n=len(mat[0])
rows=[]
cols=[]
for i in range(n):
for j in range(m):
if mat[i][j]==0:
rows.append(i)
cols.append(j)
for row in rows:
nullify_row(mat,row)
for col in cols:
nullify_col(mat,col)
return mat
def nullify_row(mat,row):
for i in range(len(mat[0])):
mat[row][i]=0
def nullify_col(mat,col):
for i in range(len(mat)):
mat[i][col]=0
In [134]:
a=[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 0, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]
In [135]:
zero_matrix(a)
Out[135]:
In [129]:
nullify([1, 2, 0, 4, 5])
Out[129]:
In [155]:
#1.8
In [156]:
def is_sub(string,sub):
return string.find(sub)!=-1
def isSubstring(s1,s2):
if len(s1)!=len(s2):
return False
return is_sub(s1+s1,s2)
In [157]:
isSubstring('waterbottle','erbottlewat')
Out[157]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: