Performing a task with each item in a list is something a loop can make trivial! However, sometimes it is more complex. What happens when the task we perform depends on what has already been encountered in the list? In this exercise you’ll create a function to square the first instance (and ONLY the first instance) of a number in a list.
comp110/exercises
directory, create a directory named review
and create a file called square_first_instance
.square_first_instance
List
of int
valuesList
of int
values__name__
is "__main__"
idiom to test the implementation of your function with some sample calls to it whose return values are printed (documentation: https://docs.python.org/3/library/__main__.html
).Everything that can be done with a loop, can also be done with recursion. Let’s try translating the following into a recursive function.
comp110/exercises/review
directory, create a file named simple_recur.py
simple_recur
int
sint
__name__
is "__main__"
idiom to test the implementation of your function with some sample calls to it whose return values are printed (documentation: https://docs.python.org/3/library/__main__.html
).This function should be equivalent to the one written above. In this context, equivalent means that when functions are called with the same arguments, both functions will return the same value.
review
directory create a new file named fac_rec
int
and return another int.
In this exercise, you will use recursion to process a linked list of ints
to return a new linked list of only even numbers.
comp110/exercises/review
directory, create a file called only_evens.py
.only_evens
Optional Node
of ints
Optional Node
of ints
__name__
is "__main__"
idiom to test the implementation of your function with some sample calls to it whose return values are printed (documentation: https://docs.python.org/3/library/__main__.html
).When a number is odd, add 1 to it in the result list. Example usage:
test: Optional[Node[int]] = Node(1, Node(2, Node(3, Node(4, None))))
only_evens(test)
This should return 2 -> 2 -> 4 -> 4 -> None
def square_first_instance(input: List[int]) -> List[int]:
"""Squares the first instance of every number in a list."""
output: List[int] = []
numbersSeen: Set[int] = set()
for i in input:
if i not in numbersSeen:
numbersSeen.add(i)
i = i * i
output.append(i)
else:
output.append(i)
return output
ef simple_recur(m: int, n: int) -> int:
"""Calls itself recursively 10 times."""
if m > 10:
return n
return simple_recur(m + 1, m * n)
def fac_rec(input: int) -> int:
"""Compute factorial recursively."""
if input == 0:
return 1
if input == 1:
return input
return input * fac_rec(input - 1)
from __future__ import annotations
from typing import TypeVar, Generic, Optional
T = TypeVar("T")
class Node(Generic[T]):
"""A generic linked list Node for any data type T."""
data: T
next: Optional[Node[T]]
def __init__(self, data: T, next: Optional[Node[T]]):
"""Construct a Node in a Linked list that forms head of a new list."""
self.data = data
self.next = next
def __repr__(self) -> str:
"""Produce a string representation of a linked list."""
if self.next is None:
return f"{self.data} -> None"
else:
return f"{self.data} -> {self.next}"
def only_evens(input: Optional[Node[int]]) -> Optional[Node[int]]:
"""Only keep the even elements of a linked list."""
if input is None:
return None
first = input.data
rest = input.next
if first % 2 == 0:
return Node(first, only_evens(rest))
else:
first += 1
return Node(first, only_evens(rest))