Created
February 11, 2016 22:54
-
-
Save laurencestokes/1207ec8d6ae6c6ff9577 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
def replace(l, x, y): | |
s = l.split(",") | |
print s | |
keys = x # Strings to be replaced | |
values = y # Strings to replace with | |
isComplete = False # Boolean | |
# Check if lengths of x and y arguments are equal before proceeding | |
if(len(x) is not len(y)): | |
print isComplete | |
print 'Lengths do not match' | |
return | |
# Map a dictionary of x and y | |
dict = getDictionary(x,y) | |
# List of the final string to return | |
finalString = list() | |
# Get the count of the replacements | |
counterList = list() | |
# Iterate over the initial list | |
for count,string in enumerate(s): | |
# Build our new list - which at first is a copy of the original | |
finalString.insert(count, s[count]) | |
# If the string in the new list we're building is equal to the current string in the list of strings to be replaced | |
# then replace its associated value from the dictionary | |
# Also add this string to the counter so we know it was removed (we can count occurences of that string later to get total count) | |
if string in dict.keys(): | |
counterList.insert(count, string) | |
finalString.remove(string) | |
finalString.insert(count, str(dict.get(string))) | |
isComplete = True | |
print isComplete | |
getNumberOfTimes(counterList, keys) | |
return finalString | |
# Returns a dictionary from 2 lists | |
def getDictionary(x,y): | |
if (len(x) is len(y)): | |
dictionary = dict(zip(x, y)) | |
return dictionary | |
# Gets the number of times items were replaced | |
def getNumberOfTimes(removedList, originalList): | |
itemList = [item for item in collections.Counter(removedList).items()] | |
temp3 = [x for x in originalList if x not in removedList] | |
for y in itemList: | |
if y[1] is 1: | |
print y[0] + " removed " + str(y[1]) + " time" | |
else: | |
print y[0] + " removed " + str(y[1]) + " times" | |
for z in temp3: | |
print z + " removed " + str(0) + " times" | |
# Main Method | |
def main(): | |
txt = "yes,the,answer,is,yes" | |
newString = replace(txt,["yes","the","twelve"],["no","a", "thirteen"]) | |
if(newString): | |
print newString | |
# Program Entry point | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment