def crossprod (list1, list2): output = 0 for i in range(0,len(list1)): output += list1[i]*list2[i] return output def breakit(target, coins): coinslimit = [(target / coins[i]) for i in range(0,len(coins))] count = 0 temp = [] for i in range(0,len(coins)): temp.append([j for j in range(0,coinslimit[i]+1)]) r=[[]] for x in temp: t = [] for y in x: for i in r: t.append(i+[y]) r = t targArr = [] for targets in r: if crossprod(targets, coins) == target: targArr.append(targets) count +=1 return targArr def printSentence(lowest, coins, names): sentence = "" print lowest for g in range(0, len(lowest)) : if lowest[g] != 0: sentence += names[g] if lowest[g] > 1: sentence += "times " + str(inNames(lowest[g], coins, names)) + " " sentence += "plus " sentence = sentence[:len(sentence)-5] print sentence def inNames(num, coins, names): for x in range(0,len(names)): if num == coins[x]: return names[x] return num if __name__ == "__main__": names = ["Garrett ", "Hannah ", "Kevin ", "Jack ", "Daniel "] coins = [17, 15, 11, 7, 3] target = 21 answer = breakit(target, coins) lowest = answer[0] lowestNum = 0 for b in range(0, len(answer)) : numCount = answer[b][0] if numCount > lowestNum: lowestNum = numCount lowest = answer[b] printSentence(lowest, coins, names) for b in range(0, len(answer)) : numCount = 0 for i in range(0, len(answer[b])): if answer[b][i] == 0: numCount += 1 if numCount > lowestNum: lowest = answer[b] lowestNum = numCount printSentence(lowest, coins, names)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question