My denomination "5" is not showing up and how do you reverse the dict easily. i dont want extra 5 line of code.lol
Can you guys help me out with it?
the code is working so far.
here is my code with a test case
def change(target, coins):
result = dict()
i= len(coins) -1
while i> 0:
coin = coins[i]
numOfThisCoin= target // coin
result[coin] = numOfThisCoin
target -= coin * numOfThisCoin
i-= 1
return result
print(change(185, (5, 10, 25, 100, 200)))
i am getting output
{200: 0, 100: 1, 25: 3, 10: 1}
but want it like
{5: 0, 10: 1, 25: 3, 100: 1, 200: 0}
Here is the corrected code for your problem:
from collections import OrderedDict
def change(target, coins):
result = dict()
i= len(coins) -1
while i>= 0:
coin = coins[i]
numOfThisCoin= target // coin
result[coin] = numOfThisCoin
target -= coin * numOfThisCoin
i-= 1
res = OrderedDict(sorted(result.items()))
return res
print(change(185, (5, 10, 25, 100, 200)))
If you (not only 25 you can access any coin denomination)
print(res[25])
Output will be
3
in this case.
dict- it does not keep the elements in order. You have to use OrderedDict for sorting the elements in the order you want. For more info follow the below link:
http://docs.python.org/library/collections.html#collections.OrderedDict
def change(target, coins):
result = dict()
i= len(coins) -1
while i>= 0:
coin = coins[i]
numOfThisCoin= target // coin
result[coin] = numOfThisCoin
target -= coin * numOfThisCoin
i-= 1
return dict(sorted(result.items()))
print(change(185, (5, 10, 25, 100, 200)))
Related
Que: https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap
What I tried & issue faced: I tried a recursive approach to solve this problem. Currently, unable to find the overlapping subproblems. Can anyone help me how can I optimize, memoize and modify/update my recursion approach?. (I am thinking my approach is Wrong)
approach: Either the word is in the current line(if and only if space is left) or will be in the new line.
Code Flow:
Input text = "Cat is on Floor" .
I stored len in an array = [3,2,2,5]
ans(a,b,c) : a: index, b: line (currently no use), c: current line sum
base condn if all elements are over a>=size: return pow(spaceleft,2)
will return min( subproblem(word in current line),subproblem(word in new line)+pow(spaceleft,2))
Initially : ans(1,1,3)
ans(2,1,6) ans(2,2,2)
ans(3,2,2) ans(3,2,5) ans(3,3,2)
ans(4,3,5) ans(4,3,5) ans(4,4,5)
The below code is in python3.x :
n=6
arr=[3,2,2,5]
size = 4
def ans(a,b,c):
if(a>=size):
return pow((n-c),2);
if(c+arr[a]+1 > n):
return (pow((n-c),2)+ans(a+1,b+1,arr[a]))
return (min(ans(a+1,b,c+arr[a]+1),pow((n-c),2)+ans(a+1,b+1,arr[a])))
print(ans(1,1,3))
Thanks in advance for giving your valuable time and helping me....
I think your formulation might be missing some cases. It surely is hard to understand. Here's one that seems to get the right answer.
class LineWrapper:
def __init__(self, lens, width):
self.lens = lens
self.width = width;
def cost(self, ptr=0, used=0):
remaining = self.width - used
# Case 1: No words: Cost is due to partially used line.
if ptr == len(self.lens):
return remaining ** 2 if used else 0
# Case 2: First word of line. Must skip.
if used == 0:
return self.cost(ptr + 1, self.lens[ptr])
# Case 3: Out of space. Must wrap.
needed = 1 + self.lens[ptr]
if remaining < needed:
return remaining ** 2 + self.cost(ptr)
# Case 4: Min cost of skip and wrap.
return min(self.cost(ptr + 1, used + needed), remaining ** 2 + self.cost(ptr))
There's lots of overlap among subproblems in this formulation, and yours, too. A simple example is [1, 1, 1, 1] with a width of 7. The solution will try putting this on all combinations of 1, 2, 3, and 4 lines. May sub-combinations will repeat.
To see this more obviously, we can memoize and check for hits:
def memo_cost(self, ptr=0, used=0):
args = (ptr, used)
print(args)
if args in self.memos:
print(f'Memo hit: {args}')
return self.memos[args]
remaining = self.width - used
# Case 1: No words has cost of partially used line
if ptr == len(self.lens):
r = remaining ** 2 if used else 0
self.memos[args] = r
print(f'Done: {r}')
return r
# Case 2: First word of line. Must skip.
if used == 0:
r = self.memo_cost(ptr + 1, self.lens[ptr])
self.memos[args] = r
print(f'Must skip: {r}')
return r
# Case 3: Out of space. Must wrap.
needed = 1 + self.lens[ptr]
if remaining < needed:
r = remaining ** 2 + self.memo_cost(ptr)
self.memos[args] = r
print(f'Must wrap: {r}')
return r
# Case 4: Min cost of skip wrap and wrap.
r = min(remaining ** 2 + self.memo_cost(ptr), self.memo_cost(ptr + 1, used + needed))
self.memos[args] = r
print(f'Min: {r}')
return r
print(LineWrapper([1, 1, 1, 1], 7).memo_cost())
When run, this produces:
$ python3 lb.py
(0, 0)
(1, 1)
(1, 0)
(2, 1)
(2, 0)
(3, 1)
(3, 0)
(4, 1)
Done: 36
Must skip: 36
(4, 3)
Done: 16
Min: 16
Must skip: 16
(3, 3)
(3, 0)
Memo hit: (3, 0)
(4, 5)
Done: 4
Min: 4
Min: 4
Must skip: 4
(2, 3)
(2, 0)
Memo hit: (2, 0)
(3, 5)
(3, 0)
Memo hit: (3, 0)
(4, 7)
Done: 0
Min: 0
Min: 0
Min: 0
Must skip: 0
0
My answer with memo thanks to #Gene
n=7
arr=[3,2,2,5]
INF = 9223372036854775807
size = 4
dp = [[INF for i in range(n+1)] for j in range(size+1)]
def ans(a,b,c):
if(dp[a][c]!=INF):
return dp[a][c]
if(a>=size):
dp[a][c] = pow((n-c),2)
return pow((n-c),2)
if(c+arr[a]+1 > n):
dp[a][c] = (pow((n-c),2)+ans(a+1,b+1,arr[a]))
return dp[a][c]
dp[a][c] = (min(ans(a+1,b,c+arr[a]+1),pow((n-c),2)+ans(a+1,b+1,arr[a])))
return dp[a][c]
print(ans(1,1,3))
The conditional statements below have a pattern, n is multiples of 127 and P2OUT[i] is P2OUT[i-1]*2 + 1.
if n >= 127:
P2OUT = 0x01;
if n >= 254:
P2OUT = 0x03;
if n >= 381:
P2OUT = 0x07;
if n >= 508:
P2OUT = 0x0F;
if n >= 635:
P2OUT = 0x1F;
if n >= 762:
P2OUT = 0x3F;
if n >= 889:
P2OUT = 0x7F;
if n >= 1016:
P2OUT = 0xFF;
Is there any way I can put all those conditionals inside of a python function so I put in n and get P2OUT, without explicitly writing all of them out given there is an obvious pattern.
I am aware that writing the program in general form might as well be longer than just writing out the following conditionals but I am doing is an an exercise as if there were 1000 conditionals but the pattern remains the same.
You can do something like this
def calculate_P2OUT(n):
steps=int(n//127)
P2OUT=0
while steps > 0:
P2OUT= P2OUT*2+1
steps -= 1
return hex(P2OUT)
print(calculate_P2OUT(889))
OUT: 0x7f
A loop isn't required for the calculation.
In [45]: def p2out(n):
...: return 2**(n // 127) - 1
In [46]: [p2out(i*127) for i in range(1, 9)]
Out[46]: [1, 3, 7, 15, 31, 63, 127, 255]
In [47]: # or in hex:
In [48]: [hex(p2out(i*127)) for i in range(1, 9)]
Out[48]: ['0x1', '0x3', '0x7', '0xf', '0x1f', '0x3f', '0x7f', '0xff']
In [49]: # check range:
In [50]: [hex(p2out(i*127 + 126)) for i in range(1, 9)]
Out[50]: ['0x1', '0x3', '0x7', '0xf', '0x1f', '0x3f', '0x7f', '0xff']
In [51]:
I am trying to define a function, median, that consumes a list of numbers and returns the median number from the list. If the list is empty, then I want to return None. To calculate the median, I need to find the middle index of the list after it has been sorted. Do not use a built-in function.
SURVEY_RESULTS = [1.5, 1, 2, 1.5, 2, 3, 1, 1, 1, 2]
def median(SURVEY_RESULTS):
length = 0
order = sorted(SURVEY_RESULTS)
I'm not sure how to use indexing to now determine the median.
Here is my implementation:
def QuickSort(myList,start,end):
if start < end:
i,j = start,end
base = myList[i]
while i < j:
while (i < j) and (myList[j] >= base):
j = j - 1
myList[i] = myList[j]
while (i < j) and (myList[i] <= base):
i = i + 1
myList[j] = myList[i]
myList[i] = base
QuickSort(myList, start, i - 1)
QuickSort(myList, j + 1, end)
return myList
def median(l):
half = len(l) // 2
return (l[half] + l[~half])/2 # Use reverse index
SURVEY_RESULTS = [1.5, 1, 2, 1.5, 2, 3, 1, 1, 1, 2]
# Sort first
QuickSort(SURVEY_RESULTS, 0, len(SURVEY_RESULTS)-1)
result = median(SURVEY_RESULTS)
print (result)
I am using the following program to find the maximum sum and indices of the sum.I am able to get the right index but having trouble finding the right index.
def max_sum_new(a):
max_current = max_global = a[0]
r_index = 0
for i in range(1, len(a)):
max_current = max(a[i], max_current+a[i])
if max_current > max_global:
max_global = max_current
r_index = i
return (max_global, r_index)
#Driver Code:
my_arr = [-2, 3, 2, -1]
print(max_sum_new(my_arr))
I am getting
(5, 2)
which is expected but i also want to get the starting index which in this case should be 1
so i expect
(5, 1, 2)
is there any way to get a start index here? How should i put the variable to record start index?
You just need to apply the same logic as you did with r_index. Whenever you change the max_current, that's when the start of the maximum sub-array changes. In the end it looks like this
max_current = max_global = a[0]
r_index = 0
left_index = 0
for i in range(1, len(a)):
if a[i] > max_current + a[i]:
# Here is where your start index changes
left_index = i
max_current = a[i]
else:
max_current = a[i] + max_current
if max_current > max_global:
max_global = max_current
r_index = i
print(max_global, left_index, r_index)
I am having problems with my quicksort function constantly re cursing the best of three function. I dont know why it is doing that and i need help. I am trying to practice this for my coding class next semester and this is one of the assignments from last year that my friend had and im lost when it comes to this error
This is my quicksort function:
def quick_sort ( alist, function ):
if len(alist) <= 1:
return alist + []
pivot, index = function(alist)
#print("Pivot:",pivot)
left = []
right = []
for value in range(len(alist)):
if value == index:
continue
if alist[value] <= pivot:
left.append(alist[value])
else:
right.append(alist[value])
print("left:", left)
print("right:", right)
sortedleft = quick_sort( left, function )
print("sortedleft", sortedleft)
sortedright = quick_sort( right, function )
print("sortedright", sortedright)
completeList = sortedleft + [pivot] + sortedright
return completeList
#main
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
x = quick_sort(alist, best_of_three)
print(x)
this is my best of three function:
def best_of_three( bNlist, nine = False ):
rightindex = 2
middleindex = 1
if nine == False:
left = blist[0]
rightindex = int(len(blist) - 1)
rightvalue = int(blist[rightindex])
middleindex = int((len(blist) - 1)/2)
middlevalue = int(blist[middleindex])
bNlist.append(left)
bNlist.append(middlevalue)
bNlist.append(rightvalue)
BN = bNlist
print("Values:",BN)
left = bNlist[0]
middle = bNlist[1]
right = bNlist[2]
if left <= middle <= right:
return middle , middleindex
elif left >= middle >= right:
return middle, middleindex
elif middle <= right <= left:
return right, rightindex
elif middle >= right >= left:
return right, rightindex
else:
return left, 0
#main
bNlist = []
print('Best of Three')
blist = [54,26,93,17,77,31,44,55]
print("")
print( "List: [54,26,93,17,77,31,44,55]" )
x, index = best_of_three(bNlist)
print("Pivot: ",x)
print("----------------------------")
i really dont know why it keeps infinitely re cursing,
There is also a third function called ninther
def ninther( bNlist ):
stepsize = int(len(blist) / 9)
left = 0
middle = left + 2
right = left + 2 * stepsize
blist[left]
blist[middle]
blist[right]
leftvalue = blist[left]
rightvalue = blist[right]
middlevalue = blist[middle]
left2 = right + stepsize
middle2 = left2 + 2
right2 = left2 + 2 * stepsize
blist[left2]
blist[middle2]
blist[right2]
left2value = blist[left2]
middle2value = blist[middle2]
right2value = blist[right2]
left3 = right2 + stepsize
middle3 = left3 + 2
right3 = left3 + 2 * stepsize
blist[left3]
blist[middle3]
blist[right3]
left3value = blist[left3]
middle3value = blist[middle3]
right3value = blist[right3]
bN3list = []
bN2list = []
bNlist = []
bNlist.append(leftvalue)
bNlist.append(middlevalue)
bNlist.append(rightvalue)
bN2list.append(left2value)
bN2list.append(middle2value)
bN2list.append(right2value)
bN3list.append(left3value)
bN3list.append(middle3value)
bN3list.append(right3value)
BN3 = bN3list
BN2 = bN2list
BN = bNlist
print("Ninter ")
print("Group 1:", BN)
print("Group 2:", BN2)
print("Group 3:", BN3)
x = best_of_three(bNlist, True)[0]
c = best_of_three(bN2list, True)[0]
d = best_of_three(bN3list, True)[0]
print("Median 1:", x)
print("Median 2:", c)
print("Median 3:", d)
bN4list = [x,c,d]
print("All Medians:", bN4list)
z = best_of_three(bN4list, True)
return z[0], z[1]
#main
blist = [2, 6, 9, 7, 13, 4, 3, 5, 11, 1, 20, 12, 8, 10, 32, 16, 14, 17, 21, 46]
Y = ninther(blist)
print("Pivot", Y)
print("----------------------------")
i have looked everywhere in it and i cant figure out where the problem is when calling best of three
Summary: The main error causing infinite recursion is that you don't deal with the case where best_of_three receives a length 2 list. A secondary error is that best_of_three modifies the list you send to it. If I correct these two errors, as below, your code works.
The details: best_of_three([1, 2]) returns (2, 3), implying a pivot value of 2 at the third index, which is wrong. This would give a left list of [1, 2], which then causes exactly the same behavior at the next recursive quick_sort(left, function) call.
More generally, the problem is that the very idea of choosing the best index out of three possible values is impossible for a length 2 list, and you haven't chosen how to deal with that special case.
If I add this special case code to best_of_three, it deals with the length 2 case:
if len(bNlist) == 2:
return bNlist[1], 1
The function best_of_three also modifies bNlist. I have no idea why you have the lines of the form bNlist.append(left) in that function.
L = [15, 17, 17, 17, 17, 17, 17]
best_of_three(L)
print(L) # prints [15, 17, 17, 17, 17, 17, 17, 54, 17, 55]
I removed the append lines, since having best_of_three modify bNlist is unlikely to be what you want, and I have no idea why those lines are there. However, you should ask yourself why they are there to begin with. There might be some reason I don't know about. When I do that, there are a couple of quantities you compute that are never used, so I remove the lines that compute those also.
Then I notice you have the code
rightindex = 2
middleindex = 1
if nine == False:
rightindex = int(len(blist) - 1)
middleindex = int((len(blist) - 1)/2)
left = bNlist[0]
middle = bNlist[1]
right = bNlist[2]
This doesn't seem to make any sense, since you set rightindex and middleindex to other values, but then you still access values using the old indices (2 and 1 respectively). So I removed the if nine == False block. Again, ask yourself why you had this code to begin with, maybe there's some other way you should modify this to account for something I don't know about.
The result is the following for best_of_three:
def best_of_three(bNlist):
print(bNlist)
if len(bNlist) == 2:
return bNlist[1], 1
rightindex = 2
middleindex = 1
left = bNlist[0]
middle = bNlist[1]
right = bNlist[2]
if left <= middle <= right:
return middle , middleindex
elif left >= middle >= right:
return middle, middleindex
elif middle <= right <= left:
return right, rightindex
elif middle >= right >= left:
return right, rightindex
else:
return left, 0
If I use this, your code does not recurse infinitely, and it sorts.
I don't know why you mentioned ninther at all, since it seems to have nothing to do with your question. You should probably edit it to remove that code.