FIT1045 53 Workshop 11 Solutions FIT1045 53 Workshop 11 Solutions
FIT1045 53 Workshop 11 Solutions FIT1045 53 Workshop 11 Solutions
Objectives
After this workshop, you should be able to:
❼ Implement Greedy, Brute Force and Backtracking algorithms.
❼ Write a solution that can order bitlists and permutations in lexicographical order.
Warmup
def lex_less_eq (a , b ):
""" Determines whether sequence ( a ) is lexicographically less or equal to
sequence ( b ); equivalent to a <= b .
For example :
>>> lex_less_eq ( ✬ tactic ✬ , ✬ tree ✬ )
True
>>> lex_less_eq ( ✬ tactic ✬ , ✬ tactical display ✬ )
True
>>> lex_less_eq ([1 , 2 , 3] , [0 , 1 , 2 , 3])
False
"""
for i in range ( min ( len ( a ) , len ( b ))):
if a [ i ] != b [ i ]:
return a [ i ] < b [ i ]
return len ( a ) <= len ( b )
def rbitlists ( n ):
""" Generates list of all bitlists of length n in lexicographic order
using recursion .
For example .
>>> rbitlists (2)
[[0 , 0] , [0 , 1] , [1 , 0] , [1 , 1]]
>>> rbitlists (3)
[[0 , 0 , 0] , [0 , 0 , 1] , [0 , 1 , 0] , [0 , 1 , 1] , [1 , 0 , 0] , [1 , 0 , 1] , [1 , 1 , 0] , [1 ,
1
Downloaded by goodgamers99 gamers ([email protected])
lOMoARcPSD|9314401
For the base case of an empty input list the only permutation is the
empty list itself . For non - empty lst , assuming that we can enumerate all
permutations of the sublist lst [: -1] ( all except last element ) , we can
then recursively generate a list of all permutations by inserting
the last element in all possible positions for each permutation of the
smaller list .
"""
if len ( lst )==0:
return [[]]
2
Downloaded by goodgamers99 gamers ([email protected])
lOMoARcPSD|9314401
"""
res = []
s = 0
for i in range ( len ( denominations )):
c = ( amount - s ) // denominations [ i ]
s += c * denominations [ i ]
res += [ c ]
return res if s == amount else None
Part B1: Bounded Lists
def lex_suc ( bitlist , upper_bounds ):
"""
Input : bitlist a !=[1 ,... ,1]
Output : direct lex . successor of a
"""
res = bitlist [:]
i = len ( res ) - 1
while res [ i ] == upper_bounds [ i ]:
res [ i ] = 0
i -= 1
res [ i ] += 1
return res
upper_bounds = []
for denom in denominations :
3
Downloaded by goodgamers99 gamers ([email protected])
lOMoARcPSD|9314401
4
Downloaded by goodgamers99 gamers ([email protected])