check the python code below that doesn’t work properly, adjust it and explain?
Question:
Please check the python code as below, but the code doesn’t work properly. Please adjust it and explain.
How to use the condition “lst[i] <= upper bound[i].” ?
def bounded_upper_lists(upper_bounds): n=len(upper_bounds) first=n*[0] last=upper_bounds res=[first] while res[-1]!=last: res+=[lex_suc(res[-1])] return res def lex_suc(bitlst): res=bitlst[:] i=len(res)-1 while res[i]==1: res[i]=0 i-=1 res[i]=1 return res upper_bounds=[1,1,2] print(bounded_upper_lists(upper_bounds))
Task:
Write a function bounded upper lists(upper bounds) that accept as an argument a list of positive integers of
length n and returns a list of all lists of length n consisting of non-negative integers with the following
property:
for list lst, holds for all indices i, lst[i] <= upper bound[i].
Hint: adapt the enumeration algorithm from the lecture that enumerates bitlists in lexicographic order.
For example,
>>> bounded_lists([1, 1, 2])
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2],
[1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2]].
Summary:
In this program, we have to check the python code adjust it, and explain. They have given the logic of finding the lexical successor of the sequence of numbers. We have to change the logic as the given logic produces an infinite loop and runtime error.
Explanation:
The program is to seek out lexically increasing order of a sequence of numbers of which the last element is passed as an argument to a function named bounded_upper_lists.
In this function, the lower element may be a list containing a sequence of 0 numbered elements.
And the last element is passed to the function.
Another function named lex_suc is defined to seek out the lexical successor of the present element passed thereto.
After finding each lexical successor to the present element, it’s appended to the result list, and eventually, it’s printed as output to the console.
In the given question, the logic for locating the lexical successor of the present element is wrong. It’s corrected to urge the right output. Here, the logic is wrong, in order that the last element isn’t within the least reached. And therefore the loop in the function bounded_upper_lists runs infinitely and occurs runtime error. So we have to check the python code adjust it and explain the code.
Source code:
def bounded_upper_lists(upper_bounds): n=len(upper_bounds) fst=n*[0] lst=upper_bounds res=[] res.append(fst) while res[-1]!=lst: res.append(lex_suc(res[-1])) return res def lex_suc(bitlst): res=bitlst[:] i=len(res)-1 if res[i]==0: res[i]=1 return res elif res[i]==1: res[i]=2 return res elif res[i]==2: if res[i-1]==0: res[i-1]=1 res[i]=0; return res elif res[i-1]==1: if res[i-2]==0: res[i-2]=1 res[i-1]=0 res[i]=0 return res upper_bounds=[1,1,2] print(bounded_upper_lists(upper_bounds))
Output: