Question

def slice_list(lst: List[Any], n: int) -> List[List[Any]]: """ Return a list containing slices of <lst> in...

def slice_list(lst: List[Any], n: int) -> List[List[Any]]:
"""
Return a list containing slices of <lst> in order. Each slice is a
list of size <n> containing the next <n> elements in <lst>.

The last slice may contain fewer than <n> elements in order to make sure
that the returned list contains all elements in <lst>.

=== Precondition ===
n <= len(lst)

>>> slice_list([3, 4, 6, 2, 3], 2) == [[3, 4], [6, 2], [3]]
True
>>> slice_list(['a', 1, 6.0, False], 3) == [['a', 1, 6.0], [False]]
True
"""
# TODO: complete the body of this function


def windows(lst: List[Any], n: int) -> List[List[Any]]:
"""
Return a list containing windows of <lst> in order. Each window is a list
of size <n> containing the elements with index i through index i+<n> in the
original list where i is the index of window in the returned list.

=== Precondition ===
n <= len(lst)

>>> windows([3, 4, 6, 2, 3], 2) == [[3, 4], [4, 6], [6, 2], [2, 3]]
True
>>> windows(['a', 1, 6.0, False], 3) == [['a', 1, 6.0], [1, 6.0, False]]
True
"""
# TODO: complete the body of this function

Can you please help me complete the #TODO in the above code using python 3.8? Thank you.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

Explanation:

The logic is that count variable notices every nth element and it gets incremented on every element and it resets to 0 on every nth element. n elements are appended to the tmp list at once and at every nth element, the tmp list is appended to final_list and tmp again becomes empty.

At last, if still there are some elements left in tmp, they are also appended.


def slice_list(l, n):
  
count = 0
final_list=[]
tmp=[]
for i in l:
tmp.append(i)
count= count+1
if(count%n==0):
final_list.append(tmp)
count=0
tmp=[]
  
if(count>0 and count<n):
final_list.append(tmp)
return final_list


print(slice_list([3, 4, 6, 2, 3], 2))

print(slice_list(['a', 1, 6.0, False], 3))

Output:

b)

Explanation:

Using a for loop, starting from every index one by one, if-condition checks that are there n elements available after that index using length of the slice. If yes, then only the slice is appended from i to i+n to the res list.

If we do not check, it will create IndexError.

def windows(l, n):
res = []
for i in range(len(l)):
if(len(l[i:])>=n):
res.append(l[i:i+n])
return res


print(windows([3, 4, 6, 2, 3], 2) == [[3, 4], [4, 6], [6, 2], [2, 3]])

print(windows(['a', 1, 6.0, False], 3) == [['a', 1, 6.0], [1, 6.0, False]])

PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!

Add a comment
Know the answer?
Add Answer to:
def slice_list(lst: List[Any], n: int) -> List[List[Any]]: """ Return a list containing slices of <lst> in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • this is the function and here's what I did for this function but there is an...

    this is the function and here's what I did for this function but there is an error showing saying nonetype does not have type len() because math.ceil function (we cannot import any math..) for this function in python, if you could help me with this code. thanks gerer grodpugu def slice_list(1st: List(Any) ni int) -> List[List[Any]]: Return a list containing slices of <st> in order. Each slice is a List of size <n> containing the next <n> elements in <tst>....

  • def _merge(lst: list, start: int, mid: int, end: int) -> None: """Sort the items in lst[start:end]...

    def _merge(lst: list, start: int, mid: int, end: int) -> None: """Sort the items in lst[start:end] in non-decreasing order. Precondition: lst[start:mid] and lst[mid:end] are sorted. """ result = [] left = start right = mid while left < mid and right < end: if lst[left] < lst[right]: result.append(lst[left]) left += 1 else: result.append(lst[right]) right += 1 # This replaces lst[start:end] with the correct sorted version. lst[start:end] = result + lst[left:mid] + lst[right:end] def find_runs(lst: list) -> List[Tuple[int, int]]: """Return a...

  • def calculate_total(price_list: List[list]) -> int: """Return the sum of all second elements in the sublists of...

    def calculate_total(price_list: List[list]) -> int: """Return the sum of all second elements in the sublists of price_list. Precondition: price_list is a list of lists of length 2, and the second element of it sublist is an int. >>> price_list = [["apple", 1], ["sugar", 5], ["mango", 3], ... ["coffee", 9], ["trail mix", 6]] >>> calculate_total(price_list)

  • def get_indices(lst, elm): ''' (list of lists, object) -> tuple of two ints Given a list...

    def get_indices(lst, elm): ''' (list of lists, object) -> tuple of two ints Given a list of lists and an element, find the first pair of indices at which that element is found and return this as a tuple of two ints. The first int would be the index of the sublist where the element occurs, and the second int would be the index within this sublist where it occurs. >>> get_indices([[1, 3, 4], [5, 6, 7]], 1) (0, 0)...

  • from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked...

    from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked list. Note that this is considered a "private class", one which is only meant to be used in this module by the LinkedList class, but not by client code. === Attributes === item: The data stored in this node. next: The next node in the list, or None if there are no more nodes. """ item: Any next: Optional[_Node] def __init__(self, item: Any) ->...

  • def most_expensive_item(price_list: List[list]) -> str: """Return the name of the most expensive item in price_list. Precondition:...

    def most_expensive_item(price_list: List[list]) -> str: """Return the name of the most expensive item in price_list. Precondition: price_list is a list of lists in the following format: [ [str, int], [str, int], ... ] where each 2-element list represents a name (str) and a price (int) of an item. price_list has at least one element. >>> price_list = [["apple", 1], ["sugar", 5], ["mango", 3], ... ["coffee", 9], ["trail mix", 6]] >>> most_expensive_item(price_list) """ please complete the function body in Python

  • 3 move_small_joker def move_small_joker(deck: List[int]) -> None: 'Swap the card with one follows it Precondition: card...

    3 move_small_joker def move_small_joker(deck: List[int]) -> None: 'Swap the card with one follows it Precondition: card is a non-negative integer I have a 3 here ! >>> deck = [1, 2, 4, 3] >>> move_small_joker(deck) >>> deck (3, 1, 2, 4 >>> deck = [1, 2, 3, 4] >>> move_small.joker(deck) >>> deck [1, 2, 4, 3] new = deck new.sort small_joker = new[-2] if deck.index(small_joker) == len(deck) -1: deck = [small_joker] + deck[O:-1] else: temp = deck[deck.index(small_joker)] deck[deck. index(small_joker)] =...

  • Python question class LinkNode: def __init__(self,value,nxt=None): assert isinstance(nxt, LinkNode) or nxt is None self.value = value...

    Python question class LinkNode: def __init__(self,value,nxt=None): assert isinstance(nxt, LinkNode) or nxt is None self.value = value self.next = nxt Question 2.1. Empty Node In some cases in it convenient to have a notion of an empty linked list. Usually it means that the linked list does not have any elements in it. In order to keep things simple (for now) we will assume that the list is empty, if it has a single node and its value is None. Add...

  • List of Indexes Complete the following function. Note that neither item List nor index list should...

    List of Indexes Complete the following function. Note that neither item List nor index list should be mutated 1 from typing import List 3 def find value indexes (iten list: list. index List: Listint). V: object) + List[int]: may appear multiple times in iton list. index list contains zero or more indexes. Return a list of the indexes from index list at which v appears in ite list. Precondition: the values in index_list are valid indexes in its list. >>>...

  • C ++Write a function, anyThree (int a[], int n), that returns true if the value 3...

    C ++Write a function, anyThree (int a[], int n), that returns true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other. The parameter n will be greater than or equal to 0. Write a function, anyThree (int all, int n), that returns true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other. The parameter n will be greater than or...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT