Skip to content

Instantly share code, notes, and snippets.

View C6UJ-0.py
def SortByExampleArray(exampleArr,testArr):
CountDict=dict((el,0) for el in testArr) #initialize dictionary
Result=[] #initialize empty Result array
for x in testArr:
CountDict[x]+=1 #Store count of each number with it's key
for x in exampleArr:
if x in testArr:
for i in range(CountDict[x]):
Result.append(x)
return Result
View PrintSpirals.py
def printsprial(m,n):
arr=[]
count=0
for i in range(m):
arr.append([])
for j in range(n):
count+=1
arr[i].append(count)
print(arr)
View BinarySearch.py
def binarySearch(arr,searchterm):
pivotpos=int((len(arr)-1)/2)
if pivotpos==0:
return False
if arr[pivotpos]==searchterm:
return arr[pivotpos]
elif arr[pivotpos]>searchterm:
return binarySearch(arr[:pivotpos],searchterm) #search left when searchterm is less than pivot
else:
return binarySearch(arr[pivotpos:],searchterm)#search right when searchterm is greater than pivot
View PythonGenerator.py
#Generator function yields iterator rather than returning value, no function calls or calls on stack thus saving memory
def f(n):
for x in range(n):
yield x**3
for i in f(5):
print(i)
View LongestSubString.py
def goo_longestsubstring(str,dictionary):
longest=0
longeststr=""
for k,v in dictionary.items():
if v in str:
if longest<len(v):
longest=len(v)
longeststr=v
return longeststr
dictionary={0:"i",1:"charles",2:"am",3:"gomes",4:"substitute",5:"subcharlessubstitute"}
View FileOperations.py
def write2file(filename,content,mode):
try:
with open(filename,mode) as f:
f.write(content)
return("Write Successful")
except IOError:
return("IOError-- "+IOError)
def readfromfile(filename):
View AnagramTester.py
#Test if strings are anagram provided their length is same.
def anagramtester(str1,str2):
#dictionary=dict(range(0,26))
#CountDict=dict((el,0) for el in str1)
CountDictStr1=dict()
# i need dictionary to keep count
for i in range(len(str1)):
if str1[i] in CountDictStr1.keys():
CountDictStr1[str1[i]]+=1
else:
View Recursive_SumofList.py
#Calculate the sum of list of numbers
def sumoflist(list,count):
if len(list)==1:#Escape Clause
print(count+list[0])
return count+list[0]
else:
count+=list[0]
sumoflist(list[1:],count)
print(sumoflist([1,2,3,4,5],0))
#Wrong way of using recursion above
View recursiveint2stringconvert.py
#Recursive way to convert integer to string
def int2string(num):
#Base case:
if num<10:##check if it is single digit number
return stringlookup(num)
else:
return int2string(int(num/(10**1)))+stringlookup(int(num%(10**1)))
def stringlookup(n):
d = {1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",0:"0"}
return d[n]
View RecursiveStringReverse.py
#Recursive way of string reverse
def reversestring(str):
return str[len(str)-1::-1]
def recursivereversestr(str):
if len(str)<1:
return str
else:
return recursivereversestr(str[1:])+str[0]
print(reversestring("ADCA"))
print(recursivereversestr("charles"))
You can’t perform that action at this time.