ankitpatel2100
BAN USERdef printPattern(n):
i = 1
while(True):
print (n-i)/2 * " " + i * "*"
if i >= n:
break
i += 2
i=n-2
while(True):
print (n-i)/2 * " " + i * "*"
if i <= 1:
break
i -= 2
def distictPatterns(mylist):
mydict = dict()
for item in mylist:
unique_set_of_chars = "".join(set(item))
if mydict.has_key(unique_set_of_chars):
mydict[unique_set_of_chars] += 1
else:
mydict[unique_set_of_chars] = 1
for key,val in mydict.items():
print key + ":"+ str(val)
import random
def getNumber():
mynum = ""
while True:
if len(mynum) == 4:
return int(mynum)
rnum = random.randint(0,9)
if (len(mynum)!=0 and mynum[-1] == str(rnum)) or (len(mynum) == 0 and rnum == 0):
#if prev digit is not equal to current digit or first digit is 0,skip
continue
if len(mynum) ==3 and rnum % 2 != 0 :
#odd num out
continue
mynum += str(rnum)
def ReturnNonZero(mylist):
i = 0
while (mylist[i] != '?'):
if mylist[i] == 0:
mylist.append("?")
del mylist[i]
i -= 1
else:
i += 1
return mylist,i
print ReturnNonZero([1,0,2,0,0,3,4]) #returns ([1, 2, 3, 4, '?', '?', '?'], 4)
def Combinations(num,deduct=0,combs=[]):
num = num - deduct
if num == 0:
combs.append(deduct)
return True
elif num < deduct:
return False
else:
if deduct != 0:
combs.append(deduct)
if Combinations(num,20,combs) or Combinations(num,9,combs) or Combinations(num,6,combs):
return True,combs
else:
if len(combs)> 0 :
combs.pop()
return False
print Combinations(24,0,[]) #returns (True, [9, 6, 9])
print Combinations(13,0,[]) #returns False
print Combinations(47,0,[]) #returns (True, [20, 9, 9, 9])
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = Node(None)
def InsertNode(self,data):
newnode = Node(data)
if self.head.next == None:
self.head.next = newnode
else:
currnode = self.head.next
while currnode.next:
currnode = currnode.next
currnode.next = newnode
def Print(self):
if self.head.next == None:
print "No Data available"
return
currnode = self.head.next
while (currnode):
print currnode.data
currnode = currnode.next
def RotateonKthElement(self,k):
if k ==1 :
print "First element can not be rotated"
return
if self.head.next == None:
print "No Data available"
return
currnode = self.head.next
i=1
while currnode.next:
if i+1 == k:
nextnode = currnode.next
currnode.next = None
currnode = nextnode
rotatenode = currnode
if currnode.next:
currnode =currnode.next
i += 1
lastnode = currnode
nexttoheadnode = self.head.next
self.head.next = rotatenode
lastnode.next = nexttoheadnode
ll = LinkedList()
ll.InsertNode(1)
ll.InsertNode(2)
ll.InsertNode(3)
ll.InsertNode(4)
ll.InsertNode(5)
ll.RotateonKthElement(4)
ll.Print() #prints 4 5 1 2 3
def RemoveConsecutiveChars(mystring):
for i in range(len(mystring)-2):
if mystring[i] == mystring[i+1] == mystring[i+2]:
mystring= mystring.replace(mystring[i:i+3],"")
return RemoveConsecutiveChars(mystring)
return mystring
print RemoveConsecutiveChars("aabbbaccddddc") #Returns ccdc
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class Linkedlist:
def __init__(self):
self.head = Node(None)
def AddNode(self,data):
newnode = Node(data)
currnode = self.head.next
if currnode == None:
currnode = self.head
while currnode.next is not None:
currnode = currnode.next
currnode.next = newnode
newnode.prev = currnode
def IsPalindrome(self):
tempstring_frwd= ""
tempstring_rev = ""
if self.head.next == None :
print "LinkedList doesn't have any nodes"
return
currnode = self.head.next
while currnode.next :
tempstring_frwd += str(currnode.data)
currnode = currnode.next
tempstring_frwd += str(currnode.data)
while currnode.prev:
tempstring_rev += str(currnode.data)
currnode = currnode.prev
if tempstring_rev == tempstring_frwd :
return "Palindrome"
else:
return "Not Palindrome"
dl = Linkedlist()
dl.AddNode(1)
dl.AddNode(2)
dl.AddNode(3)
dl.AddNode(2)
dl.AddNode(1)
print dl.IsPalindrome()
def CheckIfBalance(mystring):
stack = list()
for eachchar in mystring:
if eachchar == '(' or eachchar == '{' or eachchar == '[' or eachchar == '<':
stack.append(eachchar)
elif eachchar == ')' and len(stack) > 0 and stack.pop() == '(':
continue
elif eachchar == '}' and len(stack) > 0 and stack.pop() == '{':
continue
elif eachchar == ']' and len(stack) > 0 and stack.pop() == '[':
continue
elif eachchar == '>' and len(stack) > 0 and stack.pop() == '<':
continue
else:
return "Not Balanced"
if len(stack) == 0:
return "Balanced"
else:
return "Not Balanced"
print CheckIfBalance("<({()})[]>") #Returns Balanced
print CheckIfBalance("<({([)})[]>") #Returns Not Balanced
print CheckIfBalance("))((") #Returns Not Balanced
print CheckIfBalance("((()") #Returns Not Balanced
def Find(mylist):
multiplication=1
Zerocount=0
for i in mylist:
if i!=0:
multiplication*=i
else:
Zerocount +=1
if Zerocount ==1 :
return [multiplication if i==0 else 0 for i in mylist]
elif Zerocount > 1:
return [0 for i in mylist]
return [multiplication/i for i in mylist]
print Find([1,2,3,4,5,0]) #returns [0, 0, 0, 0, 0, 120]
class FindSortedArray():
array1=list()
array2=list()
sortedarray=list()
def __init__(self,array1,array2):
self.array1 = array1
self.array2 = array2
def AddElemIntoSortedArray(self,elem):
for i in range(len(self.sortedarray)):
if self.sortedarray[i] > elem:
self.sortedarray.insert(i,elem)
return
self.sortedarray.append(elem)
def SortArrays(self):
for i in range(max(len(self.array1),len(self.array2))):
if i <= len(self.array1)-1 :
arry1_element=self.array1[i]
else:
arry2_element=self.array2[i]
self.AddElemIntoSortedArray(arry2_element)
continue
if i <= len(self.array2)-1 :
arry2_element=self.array2[i]
else:
arry1_element=self.array1[i]
self.AddElemIntoSortedArray(arry1_element)
continue
if arry1_element < arry2_element :
self.AddElemIntoSortedArray(arry1_element)
self.AddElemIntoSortedArray(arry2_element)
elif arry1_element >= arry2_element:
self.AddElemIntoSortedArray(arry2_element)
self.AddElemIntoSortedArray(arry1_element)
return self.sortedarray
if __name__ == "__main__":
s=FindSortedArray([5,10,3,9],[1,40,4,30,9,9,9])
print s.SortArrays()
class Equation:
visited= list()
series1=['A = B', 'B = D', 'C = D', 'F = G', 'E = H', 'H = C']
series2=['A != C', 'D != H', 'F != A']
def GetEquivalentValue(self,mychar):
resultlist=list()
for equ in self.series1:
if equ[0] not in self.visited and equ[-1] not in self.visited:
if mychar.strip() in equ[0]:
resultlist.append(equ[-1].strip())
elif mychar.strip() in equ[-1]:
resultlist.append(equ[0].strip())
self.visited.append(mychar)
if len(resultlist) == 0:
return False,""
return resultlist
def EvaluateEquations(self,val1,val2):
resultlist = self.GetEquivalentValue(val1)
if not resultlist[0]:
return
if val2 in resultlist:
return True
for result in resultlist:
flag=self.EvaluateEquations(result,val2)
if flag == True:
return True
return False
if __name__ == "__main__":
eq= Equation()
for subseries in eq.series2:
flag=eq.EvaluateEquations(subseries[0].strip(),subseries[-1].strip())
if flag:
print "Invalid"
elif not flag:
print "Valid"
eq.visited=[]
#Solution in Python
def longestsubstring(mystring,k):
allsubstrings=list()
currentsubstring=""
distictchars=list()
for i in range(len(mystring)):
if len(distictchars) == k and mystring[i] not in distictchars:
allsubstrings.append(currentsubstring)
currentsubstring=""
distictchars=[]
if mystring[i] not in distictchars:
distictchars.append(mystring[i])
currentsubstring+=mystring[i]
if len(distictchars) == k:
allsubstrings.append(currentsubstring)
print allsubstrings
return
longestsubstring("asdfrttt",3)
def CountOccurences(mystring):
mynewstring=""
prev=mystring[0]
count=0
for char in mystring:
if char != prev :
mynewstring += str(count)+prev
count=0
count+=1
prev=char
mynewstring += str(count)+prev
return mynewstring
if __name__ == "__main__":
print CountOccurences("aaaggbbbbcaaaa") #Outputs 3a2g4b1c4a
from itertools import groupby
#Solution in Python
def CountOccurences(mystring):
for val,occur in groupby(mystring):
char,num=val,len(list(occur))
mystring=mystring.replace(char*(num),str((num))+char,1)
return mystring
if __name__ == "__main__":
print CountOccurences("aaaggbbbbcaaaa") #Outputs 3a2g4b1c4a
- ankitpatel2100 May 21, 2017