I am working on the file "Python/Plotting/Plot_from_CSV_data.ipynb".
The first task is:
Depending on the oscilloscope settings, you can get the occasional artifact in the graph. Note that the wavegenerator swept back and forth between -5V and 5V, and where it started and stopped depended on details like the time scale and the trigger settings. If your curve does not look like this, you may need to limit the data set to a range where voltage sweep was from a negative to a positive value, and nothing else.
To get multiple curves, we repeat some of the statements, we read a different file, but plot the results at the same time.
Can you write Python code for it?

data_green = pandas.read_csv("IV_Curve_Green_LED.csv")
data_red = pandas.read_csv("IV_Curve_Red_LED.csv")
data_orange = pandas.read_csv("IV_Curve_Orange_LED.csv")
data_aqua= pandas.read_csv("IV_Curve_Aqua_LED.csv")
data_violet= pandas.read_csv("IV_Curve_Violet_LED.csv")
data_yellow= pandas.read_csv("IV_Curve_Yellow_LED.csv")

data_green.head()

plt.figure(figsize=(10,7))   # Set the size of your plot. It will determine the relative size of all the labels.
plt.plot(data_violet['Channel 1 (V)'],data_violet['Math 1 (mA)'],color="violet",label="Violet Led")
plt.plot(data_blue['Channel 1 (V)'],data_blue['Math 1 (mA)'],color="blue",label="Blue Led") # Plot a curve.
plt.plot(data_aqua['Channel 1 (V)'],data_aqua['Math 1 (mA)'],color="aqua",label="Aqua Led")
plt.plot(data_green['Channel 1 (V)'],data_green['Math 1 (mA)'],color="green",label="Green Led") # Plot a curve.
plt.plot(data_yellow['Channel 1 (V)'],data_red['Math 1 (mA)'],color="yellow",label="Yellow Led")
plt.plot(data_orange['Channel 1 (V)'],data_orange['Math 1 (mA)'],color="orange",label="Orange Led")
plt.plot(data_red['Channel 1 (V)'],data_red['Math 1 (mA)'],color="red",label="Red Led")
plt.xlabel("V [V]")
plt.xlim((-0.5,3.5))
plt.ylabel("I [mA]")
plt.legend(loc="upper left")
plt.title("I-V curves for LEDs")
plt.savefig("LED_curves.pdf")
plt.show()


I am working on the file "Python/Plotting/Plot_from_CSV_data.ipynb".
The first task is:
Once Pandas is enabled, we can use it to rear the csv file that the AD produced. To read an Excel xlmx file you can use "pandas.read_excel" instead.
Can you write Python code for it?

import os
os.listdir()   # Show me what is in the directory

data_blue = pandas.read_excel("IV_Curve_Blue_LED.xlsx")


I am working on the file "Python/Plotting/Plot_from_CSV_data.ipynb".
The first task is:
To access individual values, we would specify which column, e.g. "Channel 1(V)", and which row. We see that the actual data was more accurate than the head() function printed.
Can you write Python code for it?


I am working on the file "Python/Plotting/Plot_from_CSV_data.ipynb".
The first task is:
We now want to plot two of the columns against each other. We want "Math 1(mA)" on the y axis and "Channel 1(V)" on the x-axis. We tell plt (Matplotlib.pyplot) that we was a figure, we plot the data, we label the axis and give the plot a title, then show the results.
Can you write Python code for it?

plt.figure(figsize=(10,7))   # Set the size of your plot. It will determine the relative size of all the labels.
plt.plot(data_blue['Channel 1 (V)'],data_blue['Math 1 (mA)'],label="Blue Led") # Plot a curve.
plt.xlabel("V [V]")
plt.ylabel("I [mA]")
plt.title("I-V curves for LEDs")
plt.show()


I am working on the file "Python/Python Language Basics.ipynb".
The first task is:
Everything is represented by objects in python or relation among objects. Every object has a value, type, identity. Identity can be thought of as address of object in memory which never changes. The 'is' operator compares the identity of the objects. Type of an object is also unchangable.

List of types available in python

None -> Objects of type None have value None

NotImplemented -> Same as None but it is returned when methods do not implement the operations on the operand

Elipses -> Singled value accessed using ... or Ellipses. It contains int, bool, float(Real), complex

Sequences -> We can use len() to find number of itemsin the sequencem, also support slicing. These are strings. Tuples, Bytes. ord() converts string to int, chr() converts char to int, str.encode() to convert str to bytes and bytes.decode() to convert bytes to str. Mutable sequences are Lists, Byte Arrays

Set types -> They cannot be indexed by subscripts only iterated, unique with no repetitions. These are sets and frozen sets

Mapping -> Dictionaries

User definded functions

\__doc\__ -> The description of the object

\__name\__ -> It tells the function's name

\__qualname\__ -> It shows the path from a module's global scope to a class.

\__module\__ -> name of module function was defined in

\__code\__

\__globals\__ -> reference to the global variables of a function

\__dict\__ -> Namespace supporting arbitrary functions attributes

\__closure\__ -> None or tuple of cells containing binding of function's free variables

Instance methods

\__self\__ -> It is the class instance object

\__doc\__

\__name\__

\__module\__

\__bases\__ -> Tuples containing the base classes

Generator functions -> which uses yield. It return an iterator object which can be used to execute the body of the function.

async def is called a coroutine...
Can you write Python code for it?

class Meta(type):
    pass
class MyClass(metaclass = Meta):
    pass
class MySubclass(MyClass):
    pass


I am working on the file "Python/Python Library.ipynb".
The first task is:
Lists
Can you write Python code for it?

a = list(('a','b','c','d'))
print(a)

a = ['a','b','c','d']
print(a)

myList = [4,5,8,1,23,4,6,8]
myList.sort(reverse = False)
print(myList)

myList.append('a')
print(myList)

myList.remove(1)
print(myList)

a = myList.pop()
print(a)

myList.insert(3, 'b')
print(myList)


I am working on the file "Python/Python Library.ipynb".
The first task is:
Tuples
Immutable sequences to store hetrogenous data
Can you write Python code for it?

myTuple = tuple((1,2,3,'a'))
print(myTuple)

myTuple = (1,2,3,'a', 1+2j)
print(myTuple[3])
# you cannot now add or remove elements from a tuple after its creation


I am working on the file "Python/Python Library.ipynb".
The first task is:
Various exception that youmay face

__AssertionError__ -> When an assert statement fails

__AttributeError__ -> When an assignment or attribute reference fails

__EOFError__ -> Most proabl;y when you miss a bracket.

__FloatingPointError__ -> When a flaoting point operation fails

__ImportError__

__ModuleNotFoundError__

__IndexError__ -> During incorrect indexing of a sequence

__KeyError__ -> When a mapping dictionary key is not found in set of existing keys

__KeyboardInterrupt__

__MemoryError__ -> When an operation runs out of memory but it can be overcome by deleting some objects

__NameError__ -> When a local or global name is not found

__OSError__ -> When a system related error occurs like failed file I/O operation or disk full.

__OverflowError__ -> When result of arithematic operation is too large to be represented.

__RecursionError__ -> When maximum recursion depth is exceeded.

__ReferenceError__ -> When we try to access an attribute of the referent after it has been garbage collected.

Can you write Python code for it?

import sys
sys.getrecursionlimit()
# Always remember that tail recursion is not efficient inpython so
# always try to solve the problem iteratively that recursively in pyton.


I am working on the file "Python/Python Morsels/3.compact/better_solution/.ipynb_checkpoints/compact-checkpoint.ipynb".
The first task is:
Key Takeaways

object() - This will give an unique object, which can used instead of None

Another solution: Will not work for iterator objects passed as parameters
Reason: the *items will consume the iterator
Can you write Python code for it?

def compact(items):
    """Return new iterable with adjacent duplicate values removed."""
    for item, prev in zip(items, [object(), *items]):
        if item != prev:
            yield item


I am working on the file "Python/Python Morsels/multimax/Trey's Solutions/multimax.ipynb".
The first task is:
Bonus3: multimax function accept a keyword argument called "key" that is a function which will be used to determine the key by which to compare values as maximums
Can you write Python code for it?

def multimax(iterable, key=None):
    """ Return a list of all maximum values """
    if key is None:
        def key(item): return item

    maximums = []
    key_max = None

    for item in iterable:
        k = key(item)

        if k == key_max:
            maximums.append(item)
        elif not maximums or k > key_max:
            key_max = k
            maximums = [item]

    return maximums

multimax([1, 2, 4, 3])

multimax([1, 4, 2, 4, 3])

numbers = [1, 3, 8, 5, 4, 10, 6]
odds = (n for n in numbers if n % 2 == 1)

multimax(odds)

multimax([])

words = ["cheese", "shop", "ministry", "of", "silly", "walks", "argument", "clinic"]

multimax(words, key=len)


I am working on the file "Python/Python Morsels/multimax/Trey's Solutions/multimax.ipynb".
The first task is:
Unit Tests
Can you write Python code for it?

import unittest

class MultiMaxTests(unittest.TestCase):

    """Tests for multimax."""

    def test_single_max(self):
        self.assertEqual(multimax([1, 2, 4, 3]), [4])

    def test_two_max(self):
        self.assertEqual(multimax([1, 4, 2, 4, 3]), [4, 4])

    def test_all_max(self):
        self.assertEqual(multimax([1, 1, 1, 1, 1]), [1, 1, 1, 1, 1])

    def test_lists(self):
        inputs = [[0], [1], [], [0, 1], [1]]
        expected = [[1], [1]]
        self.assertEqual(multimax(inputs), expected)

    def test_order_maintained(self):
        inputs = [
            (3, 2),
            (2, 1),
            (3, 2),
            (2, 0),
            (3, 2),
        ]
        expected = [
            inputs[0],
            inputs[2],
            inputs[4],
        ]
        outputs = multimax(inputs)
        self.assertEqual(outputs, expected)
        self.assertIs(outputs[0], expected[0])
        self.assertIs(outputs[1], expected[1])
        self.assertIs(outputs[2], expected[2])

    # To test the Bonus part of this exercise, comment out the following line
    # @unittest.expectedFailure
    def test_empty(self):
        self.assertEqual(multimax([]), [])

    # To test the Bonus part of this exercise, comment out the following line
    # @unittest.expectedFailure
    def test_iterator(self):
        numbers = [1, 4, 2, 4, 3]
        squares = (n**2 for n in numbers)
        self.assertEqual(multimax(squares), [16, 16])

    # To test the Bonus part of this exercise, comment out the following line
    # @unittest.expectedFailure
    def test_key_function(self):
        words = ["alligator", "animal", "apple", "artichoke", "avalanche"]
        outputs = ["alligator", "artichoke", "avalanche"]
        self.assertEqual(multimax(words, key=len), outputs)

if __name__ == "__main__":
    unittest.main(argv=['first-arg-is-ignored'], exit=False)


I am working on the file "Python/Python Morsels/multimax/Trey's Solutions/multimax.ipynb".
The first task is:
We may use lambda when no key is provided like so:
Can you write Python code for it?

def multimax(iterable, key=lambda x: x):
    """ Return a list of all maximum values """
    maximums = []
    key_max = None

    for item in iterable:
        k = key(item)

        if k == key_max:
            maximums.append(item)
        elif not maximums or k > key_max:
            key_max = k
            maximums = [item]

    return maximums


I am working on the file "Python/Python Morsels/multimax/my_try/multimax.ipynb".
The first task is:
Bonus1: Make sure the function returns an empty list if the iterable is empty
Can you write Python code for it?


I am working on the file "Python/Python Morsels/multimax/my_try/multimax.ipynb".
The first task is:
Bonus2: Make sure the function works well with iterator such as files, generators etc
Can you write Python code for it?

numbers = [1, 3, 8, 5, 4, 10, 6]
odds = (n for n in numbers if n % 2 == 1)
multimax(odds)


I am working on the file "Python/Python Morsels/multimax/my_try/multimax.ipynb".
The first task is:
Bonus3: The multimax function accept a keyword argument called "key" that is a function which will be used to determine the key by which to compare values as maximums. For example the key function could be used to find the longest words in a list of words
Can you write Python code for it?

words = ["cheese", "shop", "ministry", "of", "silly", "walks", "argument", "clinic"]

multimax(words, key=len)

words = ["cheese", "shop", "ministry", "of", "silly", "walks", "argument", "clinic"]
max(words, key=len)

words = ["cheese", "shop", "argument", "of", "silly", "walks", "ministry", "clinic"]
max(words, key=len)


I am working on the file "Python/Python Morsels/uniques_only/my_try/uniques_only.ipynb".
The first task is:
Bonus2: allow your uniques_only function to work with unhashable objects
Can you write Python code for it?

list(uniques_only([['a', 'b'], ['a', 'c'], ['a', 'b']]))

def uniques_only(iterable):
    """
    Function that accepts an iterable and returns a new iterable
    with all items from the original iterable except for duplicates.
    """
    uniques_dict = {}

    for item in iterable:
        item = tuple(item)
        if item not in uniques_dict:
            uniques_dict[item] = 1
            yield item

list(uniques_only([['a', 'b'], ['a', 'c'], ['a', 'b']]))

list(uniques_only([1, 2, 2, 1, 1, 3, 2, 1]))

def uniques_only(iterable):
    """
    Function that accepts an iterable and returns a new iterable
    with all items from the original iterable except for duplicates.
    """
    uniques_dict = {}

    for item in iterable:
        try:
            hashed = tuple(item)
        except TypeError:
            hashed = item

        if hashed not in uniques_dict:
            uniques_dict[hashed] = 1
            yield item

list(uniques_only([1, 2, 2, 1, 1, 3, 2, 1]))

nums = [1, -3, 2, 3, -1]
squares = (n**2 for n in nums)

list(uniques_only(squares))

list(uniques_only([['a', 'b'], ['a', 'c'], ['a', 'b']]))

from timeit import default_timer
import unittest

class UniquesOnlyTests(unittest.TestCase):

    """Tests for uniques_only."""

    def assertIterableEqual(self, iterable1, iterable2):
        self.assertEqual(list(iterable1), list(iterable2))

    def test_no_duplicates(self):
        self.assertIterableEqual(uniques_only([1, 2, 3]), [1, 2, 3])

    def test_adjacent_duplicates(self):
        self.assertIterableEqual(uniques_only([1, 1, 2, 2, 3]), [1, 2, 3])

    def test_non_adjacent_duplicates(self):
        self.assertIterableEqual(uniques_only([1, 2, 3, 1, 2]), [1, 2, 3])

    def test_lots_of_duplicates(self):
        self.assertIterableEqual(uniques_only([1, 2, 2, 1, 1, 2, 1]), [1, 2])

    def test_accepts_iterator(self):
        nums = (n**2 for n in [1, 2, 3])
        self.assertIterableEqual(uniques_only(nums), [1, 4, 9])

    # To test the Bonus part of this...


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Add a vector to each column of a matrix
x has shape (2, 3) and w has shape (2,).
If we transpose x then it has shape (3, 2) and can be broadcast
against w to yield a result of shape (3, 2); transposing this result
yields the final result of shape (2, 3) which is the matrix x with
the vector w added to each column. Gives the following matrix:
Can you write Python code for it?


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Another solution is to reshape w to be a row vector of shape (2, 1);
we can then broadcast it directly against x to produce the same
output.
Can you write Python code for it?


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
As usual, you can find all the gory details about lists in the documentation.
Slicing
In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:
Can you write Python code for it?

nums = list(range(5))
print(nums)
print(nums[2:4])        # Get a slice from index 2 to 4 (exclusive)
print(nums[2:])         # Get a slice from index 2 to the end
print(nums[:2])         # Get a slice from the start to index 2 (exclusive)
print(nums[:])          # Get a slice of the whole list, creates a shallow copy
print(nums[:-1])        # Slice indices can be negative
nums[2:4] = [8, 9, 10]  # Assign a new sublist to a slice
nums


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Basic data types
Numbers
Integers and floats work as you would expect from other languages:
Can you write Python code for it?

x = 3
x, type(x)

print(x + 1)   # Addition;
print(x - 1)   # Subtraction;
print(x * 2)   # Multiplication;
print(x ** 2)  # Exponentiation;

x += 1
print(x)  # Prints "4"
x *= 2
print(x)  # Prints "8"

y = 2.5
print(type(y))
print(y, y + 1, y * 2, y ** 2)


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:
Can you write Python code for it?

import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])
print('a = \n', a, sep='')
bool_idx = (a > 2)  # Find the elements of a that are bigger than 2;
                    # this returns a numpy array of Booleans of the same
                    # shape as a, where each slot of bool_idx tells
                    # whether that element of a is > 2.
bool_idx

# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
a[bool_idx]

# We can do all of the above in a single concise statement:
a[a > 2]


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
CS228 Python Tutorial
Adapted by Volodymyr Kuleshov and Isaac Caswell from the CS231n Python tutorial by Justin Johnson
Python Numpy Tutorial.
Introduction
Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific computing.
We expect that many of you will have some experience with Python and numpy; for the rest of you, this section will serve as a quick crash course both on the Python programming language and on the use of Python for scientific computing.
Some of you may have previous knowledge in Matlab, in which case we also recommend the numpy for Matlab users page (https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html).
In this tutorial, we will cover:

Basic Python: Basic data types (Containers, Lists, Dictionaries, Sets, Tuples), Functions, Classes
Numpy: Arrays, Array indexing, Datatypes, Array math, Broadcasting
Matplotlib: Plotting, Subplots, Images
IPython: Creating notebooks, Typical workflows

Basics of Python
Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable. As an example, here is an implementation of the classic quicksort algorithm in Python:
Can you write Python code for it?

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot  = arr[len(arr) // 2]
    left   = [x for x in arr if x <  pivot]
    middle = [x for x in arr if x == pivot]
    right  = [x for x in arr if x >  pivot]
    return quicksort(left) + middle + quicksort(right)

quicksort([3,6,8,10,1,2,1])


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Classes
The syntax for defining classes in Python is straightforward:
Can you write Python code for it?

class Greeter:

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # Instance method
    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello, %s' % self.name)

g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method
g.greet(loud=True)


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Dictionaries
A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript. You can use it like this:
Can you write Python code for it?

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print(d['cat'])       # Get an entry from a dictionary
print('cat' in d)     # Check if a dictionary has a given key

d['fish'] = 'wet'    # Set an entry in a dictionary
d['fish']

d['monkey']  # KeyError: 'monkey' not a key of d

print(d.get('monkey', 'N/A'))  # Get an element with a default
print(d.get('fish', 'N/A'))    # Get an element with a default

del d['fish']         # Remove an element from a dictionary
d.get('fish', 'N/A')  # "fish" is no longer a key


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:
Can you write Python code for it?

nums = [0, 1, 2, 3, 4, 5, 6]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
even_num_to_square


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
For brevity we have left out a lot of details about numpy array indexing; if you want to know more you should read the documentation.
Datatypes
Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:
Can you write Python code for it?

x = np.array([1, 2])                  # Let numpy choose the datatype
y = np.array([1.0, 2.0])              # Let numpy choose the datatype
z = np.array([1, 2], dtype=np.int64)  # Force a particular datatype

x.dtype, y.dtype, z.dtype


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
If you want access to keys and their corresponding values, use the <tt>items</tt> method:
Can you write Python code for it?

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
    print('A %s has %d legs.' % (animal.ljust(6), legs))


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
If you want access to the index of each element within the body of a loop, use the built-in enumerate function:
Can you write Python code for it?

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:
Can you write Python code for it?


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
List comprehensions:
When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:
Can you write Python code for it?

nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
squares


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:
Can you write Python code for it?

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Note that unlike certain other languages like <tt>C</tt>, <tt>C++</tt>, Java, or <tt>C#</tt>, Python does not have unary increment (x++) or decrement (x--) operators.
Python also has built-in types for long integers and complex numbers; you can find all of the details in the documentation.
Booleans
Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&, ||, etc.):
Can you write Python code for it?

t, f = True, False
type(t)

print(type(t))


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Now we let's look at the operations:
Can you write Python code for it?

print(t and f) # Logical AND
print(t or  f) # Logical OR
print(  not t) # Logical NOT
print(t !=  f) # Logical XOR


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Numpy
Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays.
To use Numpy, we first need to import the numpy package:
Can you write Python code for it?


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Numpy also provides many functions to create arrays:
Can you write Python code for it?

np.zeros((2,2))  # Create an array of all zeros

np.ones((1,2))   # Create an array of all ones

np.full((2,2), 7) # Create a constant array

np.eye(2)        # Create a 2x2 identity matrix

np.random.random((2,2)) # Create an array filled with random values


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Plotting
The most important function in matplotlib is plot, which allows you to plot 2D data. Here is a simple example:
Can you write Python code for it?

# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

# Plot the points using matplotlib
plt.plot(x, y)


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Python versions
This version of the notebook has been adapted to work with Python 3.6.
You can check your Python version at the command line by running python --version.
Can you write Python code for it?


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:
Can you write Python code for it?

from math import sqrt
{ int(sqrt(x)) for x in range(30) }


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
String objects have a bunch of useful methods; for example:
Can you write Python code for it?

s = "hello"
print(s.capitalize())  # Capitalize a string
print(s.upper())       # Convert a string to uppercase
print(s.rjust(7))      # Right-justify a string, padding with spaces
print(s.center(7))     # Center a string, padding with spaces
print(s.replace('l', '\N{greek small letter lamda}'))  # Replace all instances of one substring with another
print('  world '.strip())  # Strip leading and trailing whitespace


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Subplots
You can plot different things in the same figure using the subplot function. Here is an example:
Can you write Python code for it?

# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)

# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')

# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
This works; however when the matrix x is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix x is equivalent to forming a matrix vv by stacking multiple copies of v vertically, then performing elementwise summation of x and vv. We could implement this approach like this:
Can you write Python code for it?

vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other
vv

y = x + vv  # Add x and vv elementwise
y


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
Two ways of accessing the data in the middle row of the array.
Mixing integer indexing with slices yields an array of lower rank,
while using only slices yields an array of the same rank as the
original array:
Can you write Python code for it?

row_r1 = a[1, :]    # Rank 1 view of the second row of a
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
row_r3 = a[[1], :]  # Rank 2 view of the second row of a
print(row_r1, row_r1.shape)
print(row_r2, row_r2.shape)
print(row_r3, row_r3.shape)

# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape)
print()
print(col_r2, col_r2.shape)


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
We will often define functions to take optional keyword arguments, like this:
Can you write Python code for it?

def hello(name, loud=False):
    if loud:
        print('HELLO, %s' % name.upper())
    else:
        print('Hello, %s!' % name)

hello('Bob')
hello('Fred', loud=True)


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array.
Can you write Python code for it?

# Create the following rank 2 array with shape (3, 4)
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
a


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
You can find a list of all string methods in the documentation.
Containers
Python includes several built-in container types: lists, dictionaries, sets, and tuples.
Lists
A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
Can you write Python code for it?

xs = [3, 1, 2]    # Create a list
print(xs, xs[2])  # Indexing starts at 0
print(xs[-1])     # Negative indices count from the end of the list; prints "2"

xs[2] = 'foo'    # Lists can contain elements of different types
xs

xs.append('bar') # Add a new element to the end of the list
xs

x = xs.pop()     # Remove and return the last element of the list
x, xs


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
You can find all you need to know about dictionaries in the documentation.
It is easy to iterate over the keys in a dictionary:
Can you write Python code for it?

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
    legs = d[animal]
    print('A %s has %d legs.' % (animal.ljust(6), legs))


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
You can find the full list of mathematical functions provided by numpy in the documentation.
Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T attribute of an array object:
Can you write Python code for it?

x

x.T

v = np.array([[1,2,3]])
print(v)
print(v.T)


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
You can read all about numpy datatypes in the documentation.
Array math
Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:
Can you write Python code for it?

x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

# Elementwise sum
x + y

np.add(x, y)

# Elementwise difference
x - y

np.subtract(x, y)

# Elementwise product
x * y

np.multiply(x, y)

# Elementwise division
x / y

np.divide(x, y)

# Elementwise square root
np.sqrt(x)


I am working on the file "Python/Python-Tutorial.ipynb".
The first task is:
same as a[0,0], a[1,2], a[2,0], a[3,1],
Can you write Python code for it?

a[0,0], a[1,2], a[2,0], a[3,1]

# Mutate one element from each row of a using the indices in b
a[[0, 1, 2, 3], b] += 100
a


I am working on the file "Python/Python_Morsels_Revised/11.lstrip/let_me_try/lstrip.ipynb".
The first task is:
Bonus2: allow your lstrip function to accept a function as its second argument which will determine whether the item should be stripped
Can you write Python code for it?

def lstrip(iterable, obj):
    lstrip_stop = False
    for item in iterable:
        if lstrip_stop:
            yield item
        else:
            if not callable(obj):
                if item != obj:
                    yield item
                    lstrip_stop = True
            else:
                if not obj(item):
                    yield item
                    lstrip_stop = True

def is_falsey(value): return not bool(value)

list(lstrip(['', 0, 1, 0, 2, 'h', ''], is_falsey))

list(lstrip([-4, -2, 2, 4, -6], lambda n: n < 0))

numbers = [0, 2, 4, 1, 3, 5, 6]

def is_even(n): return n % 2 == 0

list(lstrip(numbers, is_even))

list(lstrip([0, 0, 1, 0, 2, 3], 0))

list(lstrip('  hello ', ' '))


I am working on the file "Python/Python_Morsels_Revised/11.lstrip/redo_with_Trey/lstrip.ipynb".
The first task is:
Bonus1: The lstrip function should return an iterator
Can you write Python code for it?

def lstrip(iterable, strip_value):
    """ Return iterable with strip_value removed from the beginnning"""
    iterator = iter(iterable)
    for item in iterator:
        if not item == strip_value:
            yield item
            break

    for item in iterator:
        yield item

import unittest

class LStripTests(unittest.TestCase):

    """Tests for lstrip."""

    def assertIterableEqual(self, iterable1, iterable2):
        self.assertEqual(list(iterable1), list(iterable2))

    def test_list(self):
        self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])

    def test_nothing_to_strip(self):
        self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])

    def test_string(self):
        self.assertIterableEqual(lstrip('  hello', ' '), 'hello')

    def test_empty_iterable(self):
        self.assertIterableEqual(lstrip([], 1), [])

    def test_strip_all(self):
        self.assertIterableEqual(lstrip([1, 1, 1], 1), [])

    def test_none_values(self):
        self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])

    def test_iterator(self):
        squares = (n**2 for n in [0, 0, 1, 2, 3])
        self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])

    # To test the Bonus part of this exercise, comment out the following line
    # @unittest.expectedFailure
    def test_returns_iterator(self):
        stripped = lstrip((1, 2, 3), 1)
        self.assertEqual(iter(stripped), iter(stripped))

    # To test the Bonus part of this exercise, comment out the following line
    @unittest.expectedFailure
    def test_function_given(self):
        numbers = [0, 2, 4, 1, 3, 5, 6]
        def is_even(n): return n % 2 == 0
        self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])

if __name__ == "__main__":
    unittest.main(argv=['ignore-first-arg'], exit=False)


I am working on the file "Python/Python_Morsels_Revised/11.lstrip/redo_with_Trey/lstrip.ipynb".
The first task is:
Bonus2: We're supposed to optionally accept a function as our strip value and call that function to determine whether values should be removed
Can you write Python code for it?

def lstrip(iterable, strip_value):
    """Return iterable with strip_value items removed from beginning."""
    iterator = iter(iterable)
    for item in iterator:
        if (callable(strip_value) and not strip_value(item)
                or item != strip_value):
            yield item
            break
    for item in iterator:
        yield item

import unittest

class LStripTests(unittest.TestCase):

    """Tests for lstrip."""

    def assertIterableEqual(self, iterable1, iterable2):
        self.assertEqual(list(iterable1), list(iterable2))

    def test_list(self):
        self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])

    def test_nothing_to_strip(self):
        self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])

    def test_string(self):
        self.assertIterableEqual(lstrip('  hello', ' '), 'hello')

    def test_empty_iterable(self):
        self.assertIterableEqual(lstrip([], 1), [])

    def test_strip_all(self):
        self.assertIterableEqual(lstrip([1, 1, 1], 1), [])

    def test_none_values(self):
        self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])

    def test_iterator(self):
        squares = (n**2 for n in [0, 0, 1, 2, 3])
        self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])

    # To test the Bonus part of this exercise, comment out the following line
    # @unittest.expectedFailure
    def test_returns_iterator(self):
        stripped = lstrip((1, 2, 3), 1)
        self.assertEqual(iter(stripped), iter(stripped))

    # To test the Bonus part of this exercise, comment out the following line
    # @unittest.expectedFailure
    def test_function_given(self):
        numbers = [0, 2, 4, 1, 3, 5, 6]
        def is_even(n): return n % 2 == 0
        self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])

if __name__ == "__main__":
    unittest.main(argv=['ignore-first-arg'], exit=False)

def lstrip(iterable, strip_value):
    """Return iterable with strip_value items removed from beginning."""
    iterator =...


I am working on the file "Python/Python_Morsels_Revised/11.lstrip/redo_with_Trey/lstrip.ipynb".
The first task is:
Experiments : Testing iterator
Can you write Python code for it?

my_list = [1, 2, 3, 4]
iterator1 = iter(my_list)
iterator2 = iter(my_list)
iterator1 == iterator2

my_list = [1, 2, 3, 4]
iterator = iter(my_list)
iterator1 = iter(iterator)
iterator2 = iter(iterator)
iterator1 == iterator2


I am working on the file "Python/Python_Morsels_Revised/11.lstrip/redo_with_Trey/lstrip.ipynb".
The first task is:
Using dropwhile helper function in itertools module
========================================
The dropwhile function in the itertools module will give us an iterable that has our original iterable's values except it drops any at the beginning that pass a certain test.
Bonus1: The lstrip function should return an iterator
Can you write Python code for it?

from itertools import dropwhile
def lstrip(iterable, strip_value):
    """Return iterable with strip_value items removed from beginning."""
    def is_strip_value(item): return item == strip_value

    return dropwhile(is_strip_value, iterable)

import unittest

class LStripTests(unittest.TestCase):

    """Tests for lstrip."""

    def assertIterableEqual(self, iterable1, iterable2):
        self.assertEqual(list(iterable1), list(iterable2))

    def test_list(self):
        self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])

    def test_nothing_to_strip(self):
        self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])

    def test_string(self):
        self.assertIterableEqual(lstrip('  hello', ' '), 'hello')

    def test_empty_iterable(self):
        self.assertIterableEqual(lstrip([], 1), [])

    def test_strip_all(self):
        self.assertIterableEqual(lstrip([1, 1, 1], 1), [])

    def test_none_values(self):
        self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])

    def test_iterator(self):
        squares = (n**2 for n in [0, 0, 1, 2, 3])
        self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])

    # To test the Bonus part of this exercise, comment out the following line
    # @unittest.expectedFailure
    def test_returns_iterator(self):
        stripped = lstrip((1, 2, 3), 1)
        self.assertEqual(iter(stripped), iter(stripped))

    # To test the Bonus part of this exercise, comment out the following line
    @unittest.expectedFailure
    def test_function_given(self):
        numbers = [0, 2, 4, 1, 3, 5, 6]
        def is_even(n): return n % 2 == 0
        self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])

if __name__ == "__main__":
    unittest.main(argv=['ignore-first-arg'], exit=False)


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
A Parser for Regular Expression
This notebook implements a parser for regular expressions. The parser that is implemented in the function parseExpr parses a regular expression
according to the following EBNF grammar.
regExp  -> product ('+' product)*
   product -> factor factor*
   factor  -> atom '*'?
   atom    -> '(' expr ')' | CHAR | '""' | '0'
The parse tree is represented as a nested tuple.
- characters are represented by themselves,
- '0' is interpreted as $\emptyset$ and is represented as 0,
- "" is interpreted as the regular expression $\varepsilon$ and represented as '',
- $r_1 \cdot r_2$ is represented as ('cat', 'a', 'b'),
- $r_1 + r_2$ is represented as ('or',$r_1, r_2$ ),
- $r^*$ is represented as (star, r) .
The parser is implemented as a recursive top-down parser.
In order to tokenize strings, we need regular expressions from the module re.
Can you write Python code for it?


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
A Parser for Regular Expression
This notebook implements a parser for regular expressions. The parser that is implemented in the function parseExpr parses a regular expression
according to the following EBNF grammar.
regExp  -> product ('+' product)*
   product -> factor factor*
   factor  -> atom '*'?
   atom    -> '(' expr ')' | CHAR | '""' | '0'
The parse tree is represented as a nested tuple.
- characters are represented by themselves,
- '0' is interpreted as $\emptyset$ and is represented as 0,
- "" is interpreted as the regular expression $\varepsilon$ and represented as '',
- ab is interpreted as $\texttt{a} \cdot \texttt{b}$ and is represented as ('cat', 'a', 'b'),
- $r_1 + r_2$ is represented as ('or',$r_1, r_2$ ),
- $r^*$ is represented as (star, r) .
In order to tokenize strings, we need regular expressions from the module re.
Can you write Python code for it?


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
The function $\texttt{isWhiteSpace}(s)$ checks whether the string $s$ contains only blanks and tabulators.
Can you write Python code for it?

def isWhiteSpace(s):
    whitespace = re.compile(r'[ \t]+')
    return whitespace.fullmatch(s)


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
The function parse takes a string s and tries to parse it as a regular expression.  The parse tree is returned as a nested tuple.
Can you write Python code for it?

def parse(s):
     TokenList = tokenize(s)
     regExp, Rest = parseRegExp(TokenList)
     assert Rest == [], f'Parse Error: could not parse {TokenList}'
     return regExp


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
The function parseAtom implements the following grammar rule:
atom    -> '0'
         | '(' expr ')'
         | '""'
         | CHAR
Can you write Python code for it?

def parseAtom(TokenList):
    if TokenList[0] == '0':
        return 0, TokenList[1:]
    if TokenList[0] == '(':
        regExp, Rest = parseRegExp(TokenList[1:])
        assert Rest[0] == ")", "Parse Error"
        return regExp, Rest[1:]
    if TokenList[0] == '""':
        return '', TokenList[1:]
    s = TokenList[0]
    assert len(s) <= 1, f'parse error: {TokenList}'
    return s, TokenList[1:]

parse('a*b + b*a')


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
The function parseFactor implements the following grammar rule:
factor  -> atom '*'?
Can you write Python code for it?

def parseFactor(TokenList):
    atom, Rest = parseAtom(TokenList)
    if len(Rest) > 0 and Rest[0] == "*":
        return ('star', atom), Rest[1:]
    return atom, Rest


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
The function parseProduct implements the following grammar rule:
product -> factor factor*
Can you write Python code for it?

def parseProduct(TokenList):
    result, Rest = parseFactor(TokenList)
    while len(Rest) > 0 and not (Rest[0] in ["+", "*", ")"]):
        arg, Rest = parseFactor(Rest)
        result = ('cat', result, arg)
    return result, Rest


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
The function parseRegExp takes a token list TokenList and tries to interpret this list
as a regular expression.  It returns the regular expression in the form of a nested tuple and
a list of those tokens that could not be parsed.  It is implemented as a top-down-parser.
The function parseRegExp implements the following grammar rule:
regExp  -> product ('+' product)*
Can you write Python code for it?

def parseRegExp(TokenList):
    result, Rest = parseProduct(TokenList)
    while len(Rest) > 1 and Rest[0] == '+':
        arg, Rest = parseProduct(Rest[1:])
        result = ('or', result, arg)
    return result, Rest


I am working on the file "Python/RegExp-Parser.ipynb".
The first task is:
The function tokenize(s) partitions the string s into a list of tokens.
It recognizes
- the operator symbols + and *,
- the parentheses (, ),
- single upper or lower case letters,
- 0,
- the empty string "".
All whitespace characters are discarded.
Can you write Python code for it?

def tokenize(s):
    regExp = r'''
              [+*()]   |  # operators and parentheses
              [ \t\n]  |  # white space
              [a-zA-Z] |  # single characters from the alphabet
              0        |  # empty regular expression
              ""          # epsilon
              '''
    return [t for t in re.findall(regExp, s, flags=re.VERBOSE) if not isWhiteSpace(t)]


I am working on the file "Python/Regexp-2-NFA.ipynb".
The first task is:
For a letter $c \in \Sigma$ the Fsm genCharNFA$(c)$ is defined as
$$ A(c) =
   \bigl\langle { q_0, q_1 }, \Sigma,
   \bigl{ \langle q_0, c \rangle \mapsto {q_1}\bigr}, q_0, { q_1 } \bigr\rangle.
$$
Graphically, this Fsm looks as follows:
Can you write Python code for it?

def genCharNFA(self, c):
    q0 = self.getNewState()
    q1 = self.getNewState()
    delta = { (q0, c): {q1} }
    return {q0, q1}, self.Sigma, delta, q0, { q1 }

RegExp2NFA.genCharNFA = genCharNFA
del genCharNFA


I am working on the file "Python/Regexp-2-NFA.ipynb".
The first task is:
From Regular Expressions to Fsms
This notebook shows how a given regular expression $r$ can be transformed into an equivalent finite state machine.
It implements the theory that is outlined in section 4.4. of the
lecture notes.
The class RegExp2NFA administers two member variables:
- Sigma is the alphabet, i.e. the set of characters used.
- StateCount is a counter that is needed to create unique state names.
Can you write Python code for it?

class RegExp2NFA:
    def __init__(self, Sigma):
        self.Sigma      = Sigma
        self.StateCount = 0


I am working on the file "Python/Regexp-2-NFA.ipynb".
The first task is:
Given an Fsm f, the function kleene(f)
creates an Fsm that recognizes a string $s$ if it can be written as
$$ s = s_1 s_2 \cdots s_n $$
and all $s_i$ are recognized by f.  Note that $n$ might be $0$.
If f is defined as
$$ f = \langle Q, \Sigma, \delta, q_1, { q_2 } \rangle,
$$
then  kleene(f) is defined as follows:
$$ \bigl\langle { q_0, q_3 } \cup Q, \Sigma,
                \bigl{ \langle q_0,\varepsilon\rangle \mapsto {q_1, q_3},
                        \langle q_2,\varepsilon\rangle \mapsto {q_1, q_3} \bigr}
                \cup \delta, q_0, { q_3 } \bigr\rangle.
$$
Graphically, this Fsm looks as follows:
Can you write Python code for it?

def kleene(self, f):
    M, Sigma, delta0, q1, A = f
    q2, = A
    q0 = self.getNewState()
    q3 = self.getNewState()
    delta = delta0
    delta[q0, ''] = { q1, q3 }
    delta[q2, ''] = { q1, q3 }
    return { q0, q3 } | M, Sigma, delta, q0, { q3 }

RegExp2NFA.kleene = kleene
del kleene


I am working on the file "Python/Regexp-2-NFA.ipynb".
The first task is:
Given two Fsms f1 and f2, the function disjunction(f1, f2)
creates an Fsm that recognizes a string $s$ if it is either
is recognized by f1 or by f2.
Assume again that the states of
$f_1$ and $f_2$ are different and that $f_1$ and $f_2$ have the following form:
- $f_1 = \langle Q_1, \Sigma, \delta_1, q_1, { q_3 }\rangle$,
- $f_2 = \langle Q_2, \Sigma, \delta_2, q_2, { q_4 }\rangle$,
- $Q_1 \cap Q_2 = {}$.
Then $\texttt{disjunction}(f_1, f_2)$ is defined as follows:
$$ \bigl\langle { q_0, q_5 } \cup Q_1 \cup Q_2, \Sigma,
                \bigl{ \langle q_0,\varepsilon\rangle \mapsto {q_1, q_2},
                   \langle q_3,\varepsilon\rangle \mapsto {q_5},
                   \langle q_4,\varepsilon\rangle \mapsto {q_5} \bigr}
                   \cup \delta_1 \cup \delta_2, q_0, { q_5 } \bigr\rangle
$$
Can you write Python code for it?

def disjunction(self, f1, f2):
        M1, Sigma, delta1, q1, A1 = f1
        M2, Sigma, delta2, q2, A2 = f2
        q3, = A1
        q4, = A2
        q0 = self.getNewState()
        q5 = self.getNewState()
        delta = delta1 | delta2
        delta[q0, ''] = { q1, q2 }
        delta[q3, ''] = { q5 }
        delta[q4, ''] = { q5 }
        return { q0, q5 } | M1 | M2, Sigma, delta, q0, { q5 }

RegExp2NFA.disjunction = disjunction
del disjunction


I am working on the file "Python/Regexp-2-NFA.ipynb".
The first task is:
Given two Fsms f1 and f2, the function disjunction(f1, f2)
creates an Fsm that recognizes a string $s$ if it is either
is recognized by f1 or by f2.
Assume again that the states of
$f_1$ and $f_2$ are different and that $f_1$ and $f_2$ have the following form:
- $f_1 = \langle Q_1, \Sigma, \delta_1, q_1, { q_3 }\rangle$,
- $f_2 = \langle Q_2, \Sigma, \delta_2, q_2, { q_4 }\rangle$,
- $Q_1 \cap Q_2 = {}$.
Then $\texttt{disjunction}(f_1, f_2)$ is defined as follows:
$$ \bigl\langle { q_0, q_5 } \cup Q_1 \cup Q_2, \Sigma,
                \bigl{ \langle q_0,\varepsilon\rangle \mapsto {q_1, q_2},
                   \langle q_3,\varepsilon\rangle \mapsto {q_5},
                   \langle q_4,\varepsilon\rangle \mapsto {q_5} \bigr}
                   \cup \delta_1 \cup \delta_2, q_0, { q_5 } \bigr\rangle
$$
Graphically, this Fsm looks as follows:
Can you write Python code for it?


I am working on the file "Python/Regexp-2-NFA.ipynb".
The first task is:
The Fsm genEpsilonNFA is defined as
$$  \bigl\langle { q_0, q_1 }, \Sigma,
                          \bigl{ \langle q_0, \varepsilon\rangle \mapsto {q_1} \bigr}, q_0, { q_1 } \bigr\rangle.
$$
Can you write Python code for it?

def genEpsilonNFA(self):
    q0 = self.getNewState()
    q1 = self.getNewState()
    delta = { (q0, ''): {q1} }
    return {q0, q1}, self.Sigma, delta, q0, { q1 }

RegExp2NFA.genEpsilonNFA = genEpsilonNFA
del genEpsilonNFA


I am working on the file "Python/Regexp-2-NFA.ipynb".
The first task is:
The function getNewState returns a new number that has not yet been used as a state.
Can you write Python code for it?

def getNewState(self):
    self.StateCount += 1
    return self.StateCount

RegExp2NFA.getNewState = getNewState
del getNewState


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Above, the regular expression r'a{2,3}' matches the string 'aaaa' only once since the first match consumes three occurrences of a and then there is only a single a left.
If $r$ is a regular expressions and $n\in\mathbb{N}$, then $r{n}$ is a regular expression.  This regular expression matches exactly $n$ repetitions of $r$.  Formally, we have
  $$\mathcal{L}(r{n}) = \mathcal{L}(r{n,n}).$$
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Character Classes
In order to match a set of characters we can use a character class.
If $c_1$, $\cdots$, $c_n$ are Unicode characters, then $[c_1\cdots c_n]$ is a regular expression that
matches any of the characters from the set ${c_1,\cdots,c_n}$:
$$ \mathcal{L}\bigl([c_1\cdots c_n]\bigr) := { c_1, \cdots, c_n } $$
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Character classes can be negated if the first character after the opening [ is the character ^.
For example, [^abc] matches any character that is different from a, b, or c.
Can you write Python code for it?

re.findall(r'[^abc]+', 'axyzbuvwchij')

re.findall(r'\b\w+\b', 'This is some text where we want to count the words.')


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Choice
Regular expressions provide the operator | that can be used to choose between
alternatives:
- If $r_1$ and $r_2$ are regular expressions, then $r_1|r_2$ is a regular expression.  This
  regular expression matches any string $s$ that can is matched by either $r_1$ or $r_2$.
  Formally, we have
  $$\mathcal{L}(r_1|r_2) := \mathcal{L}(r_1) \cup \mathcal{L}(r_2).  $$
In the lecture notes we have used the notation $r_1 + r_2$ instead of the Python notation $r_1|r_2$.
Can you write Python code for it?

re.findall(r'The|a', 'The horse, the dog, and a cat.', flags=re.IGNORECASE)


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Grouping
If $r$ is a regular expression, then $(r)$ is a regular expression describing the same language as
$r$.  There are two reasons for using parentheses:
- Parentheses can be used to override the precedence of an operator.
  This concept is the same as in programming languages.  For example, the regular expression ab+
  matches the character a followed by any positive number of occurrences of the character b because
  the precedence of a quantifiers is higher than the precedence of concatenation of regular expressions.
  However, (ab)+ matches the strings ab, abab, ababab, and so on.
- Parentheses can be used for back-references because inside
  a regular expression we can refer to the substring matched by a regular expression enclosed in a pair of
  parentheses using the syntax $\backslash n$ where $n \in {1,\cdots,9}$.
  Here, $\backslash n$ refers to the $n$th parenthesized group in the regular
  expression, where a group is defined as any part of the regular expression enclosed in parentheses.
  Counting starts with the left parentheses,  For example, the regular expression
  (a(b|c)*d)?ef(gh)+
  has three groups:
  1. (a(b|c)*d) is the first group,
  2. (b|c) is the second group, and
  3. (gh) is the third group.
For example, if we want to recognize a string that starts with a number followed by some white space and then
  followed by the same number we can use the regular expression (\d+)\w+\1.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Here, the regular expression starts with the alternative [0-9], which matches any single digit.
So once a digit is found, the resulting substring is returned and the search starts again.  Therefore, if this regular expression is used in findall, it will only return a list of single digits.
There are some predefined character classes:
- \d matches any digit.
- \D matches any non-digit character.
- \s matches any whitespace character.
- \S matches any non-whitespace character.
- \w matches any alphanumeric character.
  If we would use only Ascii characters this would
  be equivalent to the character class [0-9a-zA-Z_].
- \W matches any non-alphanumeric character.
- \b matches at a word boundary.  The string that is matched is the empty string.
- \B matches at any place that is not a word boundary.
  Again, the string that is matched is the empty string.
These escape sequences can also be used inside of square brackets.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
How many non-empty lines does this story have?
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
If $r$ is a regular expressions and $m,n\in\mathbb{N}$ such that $m \leq n$, then $r{m,n}$ is a
  regular expression.  This regular expression matches any number $k$ of repetitions of $r$ such that   $m \leq k \leq n$.
  Formally, we have
  $$\mathcal{L}(r{m,n}) =
    \Bigl{ s \mid \exists k \in \mathbb{N}: \bigl(m \leq k \leq n \wedge
            \exists s_1,\cdots,s_k : (s_1 \cdots s_k = s \wedge
             \forall i \in {1,\cdots, k}:  s_i \in \mathcal{L}(r)\bigr)
    \Bigr}.
  $$
  Informally, $r{m,n}$ matches $r$ at least $m$ times and at most $n$ times.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
If $r$ is a regular expressions and $n\in\mathbb{N}$, then $r{,n}$ is a regular expression.  This regular expression matches up to $n$ repetitions of $r$.  Formally, we have
  $$\mathcal{L}(r{,n}) = \mathcal{L}(r{0,n}).$$
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
If $r$ is a regular expressions and $n\in\mathbb{N}$, then $r{n,}$ is a regular expression.  This regular expression matches $n$ or more repetitions of $r$.  Formally, we have
  $$\mathcal{L}(r{n,}) = \mathcal{L}(r{n}r*).$$
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
If $r$ is a regular expressions, then $r$ is a regular expression.  This
  regular expression matches either the empty string or any string $s$ that can be split into a list on $n$ substrings $s_1$,
  $s_2$, $\cdots$, $s_n$ such that $r$ matches $s_i$ for all $i \in {1,\cdots,n}$.
  Formally, we have
  $$\mathcal{L}(r) := \bigl{ \texttt{''} \bigr} \cup
    \Bigl{ s \Bigm| \exists n \in \mathbb{N}: \bigl(n \geq 1 \wedge
            \exists s_1,\cdots,s_n : (s_1 \cdots s_n = s \wedge
             \forall i \in {1,\cdots, n}:  s_i \in \mathcal{L}(r)\bigr)
    \Bigr}.
  $$

Informally, $r*$ matches $r$ any number of times, including zero times.  Therefore, in the following example the result also contains various empty strings.  For example, in the string 'abaabaaaba' the regular expression a* will find an empty string at the beginning of each occurrence of the character 'b'.  The final occurrence of the empty string is found at the end of the string:
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
If $r$ is a regular expressions, then $r?$ is a regular expression.  This
  regular expression matches either the empty string or any string $s$ that is matched by $r$.  Formally we have
  $$\mathcal{L}(r?) := \bigl{ \texttt{''} \bigr} \cup \mathcal{L}(r). $$
  Informally, $r?$ matches $r$ at most one times but also zero times.  Therefore, in the following example the result also contains two empty strings.  One of these is found at the beginning of the character 'b', the second is found at the end of the string.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
In general, given a digit $n$, the expression $\backslash n$ refers to the string matched in the $n$-th group of the regular expression.
The Dot
The regular expression . matches any character except the newline.  For example, c.*?t matches any string that starts with the character c and ends with the character t and does not contain any newline.  If we are using the non-greedy version of the quantifier *, we can find all such words in the string below.
Can you write Python code for it?

re.findall(r'c.*?t', 'ct cat caat could we look at that!')


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
In the following example we have to use raw strings in order to prevent
the backlash character to be mistaken as an escape sequence.  A string is a
raw string if the opening quote character is preceded with the character
r.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
In the next example, the flag re.IGNORECASE is set and hence the function call returns a list of length 3.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Lookahead Assertions
Sometimes we need to look ahead in order to know whether we have found what we are looking for.  Consider the case that you want to add up all numbers followed by a dollar symbol but you are not interested in any other numbers.  In this case a
lookahead assertion comes in handy.  The syntax of a lookahead assertion is:
$$ r_1 (\texttt{?=}r_2) $$
Here $r_1$ and $r_2$ are regular expressions and ?= is the lookahead operator.  $r_1$ is the regular expression you are searching for while $r_2$ is the regular expression describing the lookahead.  Note that this lookahead is not matched.  It is only checked whether $r_1$ is followed by $r_2$ but only the text matching $r_1$ is matched.   Syntactically, the
lookahead $r_2$ has to be preceded by the lookahead operator and both have to be surrounded by parentheses.
In the following example we are looking for all numbers that are followed by dollar symbols and we sum these numbers up.
Can you write Python code for it?

text = 'Here is 1$, here are 21€, and there are 42 $.'
L = re.findall(r'([0-9]+)(?=\s*\$)', text)
print(f'L = {L}')
sum(int(x) for x in L)


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Next, let us check, whether this text is suitable for minors.  In order to do so we search for all four
letter words that start with either d, f or s and end with k or t.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Non-Greedy Quantifiers
The quantifiers ?, +, *, {m,n}, {n}, {,n}, and {n,} are greedy, i.e. they
match the longest possible substrings.  Suffixing these operators with the character ? makes them
non-greedy.  For example, the regular expression a{2,3}? matches either
two occurrences or three occurrences of the character a but will prefer to match only two characters.  Hence, the regular expression a{2,3}? will find two matches in the string 'aaaa', while the regular expression a{2,3} only finds a single match.
Can you write Python code for it?

re.findall(r'a{2,3}?', 'aaaa'), re.findall(r'a{2,3}', 'aaaa')


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Note that the next example looks quite similar but gives a different result:
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Quantifiers
The most interesting regular expression operators are the quantifiers.
The official documentation calls them repetition qualifiers but in this notebook
they are called quantifiers, since this is shorter.  Syntactically, quantifiers are
postfix operators.
- If $r$ is a regular expressions, then $r+$ is a regular expression.  This
  regular expression matches any string $s$ that can be split into a list on $n$ substrings $s_1$,
  $s_2$, $\cdots$, $s_n$ such that $r$ matches $s_i$ for all $i \in {1,\cdots,n}$.
  Formally, we have
  $$\mathcal{L}(r+) :=
    \Bigl{ s \Bigm| \exists n \in \mathbb{N}: \bigl(n \geq 1 \wedge
            \exists s_1,\cdots,s_n : (s_1 \cdots s_n = s \wedge
             \forall i \in {1,\cdots, n}:  s_i \in \mathcal{L}(r)\bigr)
    \Bigr}.
  $$
  Informally, $r+$ matches $r$ any positive number of times.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Regular Expressions in Python (A Short Tutorial)
This is a tutorial showing how regular expressions are supported in Python.
The assumption is that the reader already has a grasp of the concept of
regular expressions as it is taught in lectures
on formal languages, for example in
Formal Languages and Their Application, but does not know how regular expressions are supported in Python.
In Python, regular expressions are not part of the core language but are rather implemented in the module re.  This module is part of the Python standard library and therefore there is no need
to install this module.  The full documentation of this module can be found at
https://docs.python.org/3/library/re.html.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Regular expressions are strings that describe languages, where a
language is defined as a set of strings.
In the following, let us assume that $\Sigma$ is the set of all Unicode characters and $\Sigma^$ is the set
of strings consisting of Unicode characters.  We will define the set $\textrm{RegExp}$ of regular expressions inductively.
In order to define the meaning of a regular expression $r$ we define a function
$$\mathcal{L}:\textrm{RegExp} \rightarrow 2^{\Sigma^} $$
such that $\mathcal{L}(r)$ is the language specified by the regular expression $r$.
In order to demonstrate how regular expressions work we will use the function findall from the module
re.  This function is called in the following way:
$$ \texttt{re.findall}(r, s, \textrm{flags}=0) $$
Here, the arguments are interpreted as follows:
- $r$ is a string that is interpreted as a regular expression,
- $s$ is a string that is to be searched by $r$, and
- $\textrm{flags}$ is an optional argument of type int which is set to $0$ by default.
  This argument is useful to set flags that might be used to alter the interpretation of the regular
  expression $r$.
  For example, if the flag re.IGNORECASE is set, then the search performed by findall is not
  case sensitive.
The function findall returns a list of those non-overlapping substrings of the string $s$ that
match the regular expression $r$.  In the following example, the regular expression $r$ searches
for the letter a and since the string $s$ contains the character a two times, findall returns a
list with two occurrences of a:
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
Start and End of a Line
The regular expression ^ matches at the start of a string.  If we set the flag re.MULTILINE, which we
will usually do when working with this regular expression containing the expression ^,
then ^ also matches at the beginning of each line,
i.e. it matches after every newline character.
Similarly, the regular expression $ matches at the end of a string.  If we set the flag re.MULTILINE, then $ also matches at the end of each line,
i.e. it matches before every newline character.
Can you write Python code for it?

data = \
'''
This is a text containing five lines, two of which are empty.
This is the second non-empty line,
and this is the third non-empty line.
'''
re.findall(r'^.*$', data, flags=re.MULTILINE)


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
The dot . does not have any special meaning when used inside a character range.  Hence, the regular expression
[.] matches only the character ..
Named Groups
Referencing a group via the syntax \n where n is a natural number is both cumbersome and error-prone.  Instead, we can use named groups.
The syntax to define a named group is
(?P<name>r)
where name is the name of the group and r is the regular expression.  To refer to the string matched by this group we use the following syntax:
(?P=name)
For example, below we try to find a string of alphanumeric characters that is either contained in single quotes or in double quotes.  The regular
expression [\'"] matches either a single or a double quote.  By referring to the regular expression that has been named
quote we ensure that an opening single quote is matched by a closing single quote and an opening double quote is matched by a
closing double quote.
Can you write Python code for it?

re.findall(r'((?P<quote>[\'"])\w*(?P=quote))', 'abc "uvw" and \'xyz\'')


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
The dot . does not have any special meaning when used inside a character range.  Hence, the regular expression
[.] matches only the character ..
Start and End of a Line
The regular expression ^ matches at the start of a string.  If we set the flag re.MULTILINE, which we
will usually do when working with this regular expression containing the expression ^,
then ^ also matches at the beginning of each line,
i.e. it matches after every newline character.
Similarly, the regular expression $ matches at the end of a string.  If we set the flag re.MULTILINE, then $ also matches at the end of each line,
i.e. it matches before every newline character.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
The following regular expression uses the character class \b to isolate numbers.  Note that we had to use parentheses since concatenation of regular expressions binds stronger than the choice operator |.
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
There are also negative lookahead assertion.  The syntax is:
$$ r_1 (\texttt{?!}r_2)  $$
Here $r_1$ and $r_2$ are regular expressions and ?! is the negative lookahead operator.
The expression above checks for all occurrences of $r_1$ that are not followed by $r_2$.
In the following examples we sum up all numbers that are not followed by a dollar symbol.
Note that the lookahead expression has to ensure that there are no additional digits.  In general, negative lookahead is very tricky and I recommend against using it.
Can you write Python code for it?

text = 'Here is 1$, here are 21 €, and there are 42 $.'
L = re.findall(r'[0-9]+(?![0-9]*\s*\$)', text)
print(f'L = {L}')
sum(int(x) for x in L)


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
To begin our definition of the set $\textrm{RegExp}$ of Python regular expressions, we first have to define
the set $\textrm{MetaChars}$ of all meta-characters:
MetaChars := { '.', '^', '$', '*', '+', '?', '{', '}', '[', ']', '\', '|', '(', ')' }
These characters are used as operator symbols or as
part of operator symbols inside of regular expressions.
Now we can start our inductive definition of regular expressions:
- Any Unicode character $c$ such that $c \not\in \textrm{MetaChars}$ is a regular expression.
  The regular expressions $c$ matches the character $c$, i.e. we have
  $$ \mathcal{L}(c) = { c }. $$
- If $c$ is a meta character, i.e. we have $c \in \textrm{MetaChars}$, then the string $\backslash c$
  is a regular expression matching the meta-character $c$, i.e. we have
  $$ \mathcal{L}(\backslash c) = { c }. $$
Can you write Python code for it?


I am working on the file "Python/Regexp-Tutorial.ipynb".
The first task is:
To begin our definition of the set $\textrm{RegExp}$ of Python regular expressions, we first have to define
the set $\texttt{MetaChars}$ of all meta-characters:
MetaChars := { '.', '^', '$', '*', '+', '?', '{', '}', '[', ']', '\', '|', '(', ')' }
These characters are used as operator symbols or as
part of operator symbols inside of regular expressions.
Now we can start our inductive definition of regular expressions:
- Any Unicode character $c$ such that $c \not\in \textrm{MetaChars}$ is a regular expression.
  The regular expressions $c$ matches the character $c$, i.e. we have
  $$ \mathcal{L}(c) = { c }. $$
- If $c$ is a meta character, i.e. we have $c \in \textrm{MetaChars}$, then the string $\backslash c$
  is a regular expression matching the meta-character $c$, i.e. we have
  $$ \mathcal{L}(\backslash c) = { c }. $$
Can you write Python code for it?


I am working on the file "Python/SOTD-Design.ipynb".
The first task is:
Deriving the maximal coupling
In the paper a maximal permissible interaction is derived by the magnitude of the minor diagonal transfer functions:
$|h_{12}| \leq \kappa_1$ and $|h_{21}| \leq \kappa_2$.
In the following, we will just focus on the first equation.
Substituing the closed loop transfer functions the equation becomes:
$\mid \frac{q_{12} c_2}{(1+q_{11}c_1)(1+q_{22}c_2)} \mid \leq \kappa_1$
We can now use the approximation for small frequencies $q_{12} \approx k_{12}s$, $c_2 = \frac{k_{I2}}{s} + k_{p2}~b$ and using the definition of the sensitivity $S = \frac{1}{1+G~C}$ we get:
$\mid k_{12}~(k_{I2}+b~k_{P2}) ~S_1 ~S_2 \mid \leq \kappa_1$
To get the worst case, substitute the maximum over all possible frequencies for the Sensitivity, the maximum Sensititvity $M_{Si} = \max_\limits{\omega} \mid S_i \mid$:
$\mid k_{12}~(k_{I2}+b~k_{P2}) \mid ~M_{S1} ~M_{S2}  \leq \kappa_1$
So we can derive the upper interaction due to the small frequency approximation and the robustness constrains given to be:
$\mid k_{12}~(k_{I2}+b~k_{P2}) \mid \leq \frac{\kappa_1}{ ~M_{S1} ~M_{S2}} = \gamma_1$
Using the knowledge from above we get:
Can you write Python code for it?

# Get the upper limit of the interaction in terms of the original coeffients
gamma1 = sp.Abs(k12*s*sp.simplify(sub2.coeff('1/s')/s)+k12*s*b*(sp.simplify(sub2-sub2.coeff('1/s')/s)))
gamma1 = sp.simplify(gamma1)
gamma2 = sp.Abs(k21*s*sp.simplify(sub1.coeff('1/s')/s)+k21*s*b*sp.simplify(sub1-sub1.coeff('1/s')/s))
gamma2 = sp.simplify(sp.simplify(gamma2))

gamma1

gamma2


I am working on the file "Python/SOTD-Design.ipynb".
The first task is:
Interpretation
We can see that the inverse of the determinant of the DCGain is a scaling factor describing the influence of the main diagonal elements in relation to the off diagonal elements. Hence, if the matrix is nearly equal in its gains the interaction is large.
The scaling is completed with the influence of the gains of the row affecting the output.
The results of the calculation give a direct interpretation:
Consider a TITO system described by FOTD functions. The Influence of the static decoupled system Q from an input i on an output j is neglectable iff:

$T_i = T_j$ and $L_i = L_j$
$T_i = L_j$ and $T_j = L_i$
$K_i K_j \leq 1$ and $det(G_0) \geq 1$

Decomposition of the Interaction
Since we want to directly apply the AMIGO procedure, we can state that:
$Q C^* = G D C = G C'$
Where $C'$ is the controller we would design from the regular system. Hence, we force the regular controller to behave like the ideal, decoupling controller.
$ D C = C'$
Or to get the decoupling controller as a function of the regular controller:
$C = D^{-1} C'$
Can you write Python code for it?

# Define the symbols for interaction
k1,k2 = sp.symbols('k_1 k_2', real = True)
c1,c2 = sp.symbols('c_1 c_2',real = True)
# Define symbols for the decoupling controller --> SMALL LETTER
ki1,ki2 = sp.symbols('k_{i1} k_{i2}',real = True)
kp1,kp2 = sp.symbols('k_{p1} k_{p2}',real = True)
b = sp.symbols('b',real = True)
# Define the symbols for the regular controller
KI1,KI2,KI3,KI4 = sp.symbols('K_{I1} K_{I2} K_{I3} K_{I4}',real = True)
KP1,KP2,KP3,KP4 = sp.symbols('K_{P1} K_{P2} K_{P3} K_{P4}',real = True)
B = sp.symbols('B',real = True)
# Vectorize
kV = [k1,k2]
cV = [c1,c2]
kiV = [ki1,ki2]
kpV = [kp1,kp2]
solvar =[ki1,ki2,kp1,kp2]
KIV = [KI1,KI2,KI3,KI4]
KPV = [KP1,KP2,KP3,KP4]

# Create a symbolic Controller
def PI(I,P,S):
    # Here S is setpointweight
    return P*S+I/s

# Create an decoupling controller -> Design Space Q
C_D = sp.diag(PI(ki1,kp1,1),PI(ki2,kp2,1))
# Create the regular controller -> Design Space G
C_R = sp.zeros(2)
for i in range(0,4):
    C_R[i]= PI(KIV[i],KPV[i],1)

C_RD = G.subs(s,0) * C_R

# Get substituion Rules -> make a list of equations
EQ = []
for i in range(0,4):
    EQ.append(C_D[i]- C_RD[i])


I am working on the file "Python/SOTD-Design.ipynb".
The first task is:
We get the decoupled controller - original designed by using Q - as a function of the choosen (main loop) controller
Can you write Python code for it?

# First Controller
sub1

# Second Controller
sub2


I am working on the file "Python/SOTD-Design.ipynb".
The first task is:
We now have a relation between the choosen (main loop) controller and the other (coupling loop) controller, given by the following relationships:
Can you write Python code for it?


I am working on the file "Python/SOTD-Design.ipynb".
The first task is:
We use this relationship to substitute the controller in the relationship for the decoupling controller.
Can you write Python code for it?

# Decoupling Controller 1
# Set the key of the dictionary of solutions
a = C_D[0]
# Substitute the regular controllers in the current solutions
sub1 = kisol[0][a].subs(KPV[1],P12).subs(KPV[2],P21).subs(KIV[1],I12).subs(KIV[2],I21)
# Simplify the equation
sub1 = sp.simplify(sub1)

# Decoupling Controller 2
# Set the key of the dictionary of solutions
a = C_D[3]
# Substitute the regular controllers in the current solutions
sub2 = kisol[0][a].subs(KPV[1],P12).subs(KPV[2],P21).subs(KIV[1],I12).subs(KIV[2],I21)
# Simplify the equation
sub2 = sp.simplify(sub2)


I am working on the file "Python/Scope.ipynb".
The first task is:
可以发现nonlocal只会让解释器在最近的外层函数作用域中去查找相关的变量名，并不会影响到更外层的作用域。
那nonlocal可不可以影响到全局作用域呢？
Can you write Python code for it?

abc = 123
def modify_nonlocal():
    nonlocal abc
    abc = 456

modify_nonlocal()
print(abc)


I am working on the file "Python/Scope.ipynb".
The first task is:
在使用了global关键字之后，解释器默认的从全局作用域中去查找变量var，如果没有找到，解释器会为var变量分配一段内存，并在全局作用域中给这段内存添加一个名字var。
闭包作用域和局部作用域
前面说了，在局部作用域嵌套了一个局部作用域的时候，外面那层局部作用域的名字被叫做闭包作用域。
Can you write Python code for it?

def outer():
    x, y = 1, 2
    def inner():
        x, y = 3, 4
        print(x, y)
    inner()
    print(x, y)
outer()


I am working on the file "Python/Scope.ipynb".
The first task is:
在函数的局部作用域中可以访问到全局作用域中的变量x，但是需要注意的是这里的访问是读去x的值，下面我们试一试，如果在函数中写全局变量会怎么样
Can you write Python code for it?

y = 15

def modify():
    y = 20
    print(y)
modify()
print(y)


I am working on the file "Python/Scope.ipynb".
The first task is:
如果是多层嵌套怎么办？
Can you write Python code for it?

def out4():
    i, j = 1, 2
    def middle():
        i, j = 3, 4
        def inner():
            nonlocal i, j
            i, j = 5, 6
        inner()
        print(i, j)
    middle()
    print(i, j)

out4()


I am working on the file "Python/Scope.ipynb".
The first task is:
既然函数是对象，那么不同函数就应该占有不同的内存空间，在这里第二次执行了out_1函数，这个函数又定义了一个新的函数对象，并将其返回给全局作用域。
这个时候f函数和f2函数复制的out_1的作用域就变成了完全不同的两套作用域。所以打印出来的东西并不相同
这种函数嵌套的方式就叫做闭包，用法很灵活，可以举个很简单的例子：
Can you write Python code for it?

def pow_n(n):
    def power(num):
        return num ** n
    return power

square = pow_n(2)
cube = pow_n(3)
print(square(5))
print(cube(5))


I am working on the file "Python/Scope.ipynb".
The first task is:
让外层函数把内层函数当作一个对象返回，在全局作用域中，用一个引用指向这个对象，那么这个对象在全局作用域也就有了自己的名字，用这个新名字就可以调用这个内层函数了。
这里还有一个非常厉害的特性，注意到上面这段代码中，在out_1函数调用完成之后，out_1的局部变量按理说就应该死掉了，但是由于inner_1函数中引用到了两个变量，而inner_1又被全局变量引用了，所以out_1函数中的局部变量的生命周期就变的和inner_1的局部变量一样长了，相当于是inner_1复制了一份out_1的作用域。
Can you write Python code for it?


I am working on the file "Python/Scope.ipynb".
The first task is:
这里举了一个函数嵌套的例子，
首先有一个问题，函数在python中是一等对象，也就是说函数和普通对象的作用域是一样的，inner是定义在outer的局部作用域中的。
所以无论如何，在全局作用域中都不可以通过inner这个名字来访问到这个函数的。但是既然是一等对象，就可以用引用来访问到它，下面是绕过inner函数无法被全局作用域访问到的一种方法：
Can you write Python code for it?

def out_1(x, y):
    def inner_1():
        print(x, y)
        print('hello world')
    return inner_1

f = out_1(1, 2)
f()


I am working on the file "Python/Scope.ipynb".
The first task is:
闭包作用域和赋值语句的冲突并没有被解决。
所以，在python3中引进了一个新的关键字nonlocal，这个关键字告诉解释器，不要在这一层函数的局部作用域中去找这个名字，我要在外面一层函数的作用域中去找这个名字。
Can you write Python code for it?

def out3():
    i, j = 1, 2
    def inner():
        nonlocal i, j
        i, j = 3, 4
    inner()
    print(i, j)
out3()


I am working on the file "Python/Set.ipynb".
The first task is:
Display Code
Can you write Python code for it?


I am working on the file "Python/Set.ipynb".
The first task is:
Given an ordered binary tree $t$, the expression $t.\texttt{isEmpty}()$ checks whether $t$ is the empty tree.
Can you write Python code for it?

def isEmpty(self):
    return self.mKey is None

Set.isEmpty = isEmpty
Set.__bool__ = isEmpty

def __bool__(self):
    return self.mKey is not None

Set.__bool__ = __bool__


I am working on the file "Python/Set.ipynb".
The first task is:
Given an ordered binary tree, this function renders the tree graphically using graphviz.
Can you write Python code for it?

def toDot(self):
    Set.sNodeCount = 0 # this is a static variable of the class Set
    dot = gv.Digraph(node_attr={'shape': 'record', 'style': 'rounded'})
    NodeDict = {}
    self._assignIDs(NodeDict)
    for n, t in NodeDict.items():
        if t.mKey != None:
            dot.node(str(n), label=str(t.mKey))
        else:
            dot.node(str(n), label='', shape='point')
    for n, t in NodeDict.items():
        if not t.mLeft == None:
            dot.edge(str(n), str(t.mLeft.mID))
        if not t.mRight == None:
            dot.edge(str(n), str(t.mRight.mID))
    return dot

Set.toDot = toDot


I am working on the file "Python/Set.ipynb".
The first task is:
Given two ordered binary trees $s$ and $t$, the expression $s.\texttt{update}(t)$ overwrites the attributes of $s$ with the corresponding attributes of $t$.
Can you write Python code for it?

def _update(self, t):
    self.mKey    = t.mKey
    self.mLeft   = t.mLeft
    self.mRight  = t.mRight
    self.mHeight = t.mHeight

Set._update = _update


I am working on the file "Python/Set.ipynb".
The first task is:
Let's generate an ordered binary tree with random keys.
Can you write Python code for it?

import random as rnd

t = Set()
for k in range(30):
    k = rnd.randrange(100)
    t.insert(k)
display(t.toDot())
while not t.isEmpty():
    print(t.pop(), end=' ')
display(t.toDot())


I am working on the file "Python/Set.ipynb".
The first task is:
Next, we compute the set of prime numbers $\leq 100$.  Mathematically, this set is given as follows:
$$ \bigl{2, \cdots, 100 \bigr} - \bigl{ i \cdot j \bigm| i, j \in {2, \cdots, 100 }\bigr}$$
Can you write Python code for it?

S = Set()
for k in range(2, 101):
    S.insert(k)
display(S.toDot())
for i in range(2, 101):
    for j in range(2, 101):
        S.delete(i * j)
display(S.toDot())
while not S.isEmpty():
    print(S.pop(), end=' ')
display(S.toDot())


I am working on the file "Python/Set.ipynb".
The first task is:
Sets implemented as AVL Trees
This notebook implements sets as AVL trees.  The set $\mathcal{A}$ of AVL trees is defined inductively:

$\texttt{Nil} \in \mathcal{A}$.
$\texttt{Node}(k,l,r) \in \mathcal{A}\quad$  iff
$\texttt{Node}(k,l,r) \in \mathcal{B}_<$,
$l, r \in \mathcal{A}$, and
$|l.\texttt{height}() - r.\texttt{height}()| \leq 1$.

According to this definition, an AVL tree is an ordered binary tree
such that for every node $\texttt{Node}(k,l,r)$ in this tree the height of the left subtree $l$ and the right
subtree  $r$ differ at most by one.
The class Set represents the nodes of an AVL tree.  This class has the following member variables:

mKey is the key stored at the root of the tree,
mLeft is the left subtree,
mRight is the right subtree, and
mHeight is the height.

The constructor __init__ creates the empty tree.
Can you write Python code for it?

class Set:
    def __init__(self):
        self.mKey    = None
        self.mLeft   = None
        self.mRight  = None
        self.mHeight = 0


I am working on the file "Python/Set.ipynb".
The first task is:
Testing
The function $\texttt{demo}()$ creates a small ordered binary tree.
Can you write Python code for it?

def demo():
    m = Set()
    m.insert("anton")
    m.insert("hugo")
    m.insert("gustav")
    m.insert("jens")
    m.insert("hubert")
    m.insert("andre")
    m.insert("philipp")
    m.insert("rene")
    return m

t = demo()
t.toDot()

while not t.isEmpty():
    print(t.pop())
    display(t.toDot())


I am working on the file "Python/Set.ipynb".
The first task is:
The function $\texttt{createNode}(k, l, r)$ creates an AVL-tree of that has the key $k$ stored at its root,
left subtree $l$ and right subtree $r$.
Can you write Python code for it?

def createNode(key, left, right):
    node         = Set()
    node.mKey    = key
    node.mLeft   = left
    node.mRight  = right
    node.mHeight = max(left.mHeight, right.mHeight) + 1
    return node


I am working on the file "Python/Set.ipynb".
The first task is:
The function $\texttt{restore}(\texttt{self})$ restores the balancing condition of the given binary tree
at the root node and recompute the variable $\texttt{mHeight}$.
The method $\texttt{restore}$ is specified via conditional equations.

$\texttt{Nil}.\texttt{restore}() = \texttt{Nil}$,
because the empty tree already is an  AVL tree.
  - $|l.\texttt{height}() - r.\texttt{height}()| \leq 1 \rightarrow
   \texttt{Node}(k,l,r).\texttt{restore}() = \texttt{Node}(k,l,r)$.
If the balancing condition is satisfied, then nothing needs to be done.
  - $\begin{array}[t]{cl}
          & l_1.\texttt{height}() = r_1.\texttt{height}() + 2    \
   \wedge & l_1 = \texttt{Node}(k_2,l_2,r_2)                 \
   \wedge & l_2.\texttt{height}() \geq r_2.\texttt{height}()     \[0.2cm]
   \rightarrow & \texttt{Node}(k_1,l_1,r_1).\texttt{restore}() =
                 \texttt{Node}\bigl(k_2,l_2,\texttt{Node}(k_1,r_2,r_1)\bigr)
   \end{array}
$
  - $\begin{array}[t]{cl}
           & l_1.\texttt{height}() = r_1.\texttt{height}() + 2    \
    \wedge & l_1 = \texttt{Node}(k_2,l_2,r_2)               \
    \wedge & l_2.\texttt{height}() < r_2.\texttt{height}()     \
    \wedge & r_2 = \texttt{Node}(k_3,l_3,r_3)               \
    \rightarrow & \texttt{Node}(k_1,l_1,r_1).\texttt{restore}() =
                  \texttt{Node}\bigl(k_3,\texttt{Node}(k_2,l_2,l_3),\texttt{Node}(k_1,r_3,r_1) \bigr)
    \end{array}
$
  - $\begin{array}[t]{cl}
          & r_1.\texttt{height}() = l_1.\texttt{height}() + 2    \
   \wedge & r_1 = \texttt{Node}(k_2,l_2,r_2)               \
   \wedge & r_2.\texttt{height}() \geq l_2.\texttt{height}()     \[0.2cm]
   \rightarrow & \texttt{Node}(k_1,l_1,r_1).\texttt{restore}() =
                 \texttt{Node}\bigl(k_2,\texttt{Node}(k_1,l_1,l_2),r_2\bigr)
   \end{array}
$
  - $\begin{array}[t]{cl}
           & r_1.\texttt{height}() = l_1.\texttt{height}() + 2    \
    \wedge & r_1 = \texttt{Node}(k_2,l_2,r_2)               \
    \wedge & r_2.\texttt{height}() < l_2.\texttt{height}()     \
    \wedge & l_2 =...
Can you write Python code for it?

def _restore(self):
    if abs(self.mLeft.mHeight - self.mRight.mHeight) <= 1:
        self._restoreHeight()
        return
    if self.mLeft.mHeight > self.mRight.mHeight:
        k1, l1, r1 = self.mKey, self.mLeft, self.mRight
        k2, l2, r2 = l1.mKey, l1.mLeft, l1.mRight
        if l2.mHeight >= r2.mHeight:
            self._setValues(k2, l2, createNode(k1, r2, r1))
        else:
            k3, l3, r3 = r2.mKey, r2.mLeft, r2.mRight
            self._setValues(k3, createNode(k2, l2, l3),
                                createNode(k1, r3, r1))
    elif self.mRight.mHeight > self.mLeft.mHeight:
        k1, l1, r1 = self.mKey, self.mLeft, self.mRight
        k2, l2, r2 = r1.mKey, r1.mLeft, r1.mRight
        if r2.mHeight >= l2.mHeight:
            self._setValues(k2, createNode(k1, l1, l2), r2)
        else:
            k3, l3, r3 = l2.mKey, l2.mLeft, l2.mRight
            self._setValues(k3, createNode(k1, l1, l3),
                                createNode(k2, r3, r2))
    self._restoreHeight()

Set._restore = _restore


I am working on the file "Python/Set.ipynb".
The first task is:
This method assigns a unique identifier with each node.  The dictionary NodeDict maps these identifiers to the nodes where they occur.
Can you write Python code for it?

def _assignIDs(self, NodeDict):
    Set.sNodeCount += 1
    self.mID = Set.sNodeCount
    NodeDict[self.mID] = self
    if self.isEmpty():
        return
    self.mLeft ._assignIDs(NodeDict)
    self.mRight._assignIDs(NodeDict)

Set._assignIDs = _assignIDs


I am working on the file "Python/Set.ipynb".
The first task is:
This method counts all nodes in the tree.
Can you write Python code for it?

def __len__(self):
    if self.isEmpty():
        return 0
    return 1 + len(self.mLeft) + len(self.mRight)

Set.__len__ = __len__


I am working on the file "Python/Set.ipynb".
The first task is:
This tree looks more or less balanced.  Lets us try to create a tree by inserting sorted numbers because that resulted in linear complexity for ordered binary trees.
Can you write Python code for it?

t = Set()
for k in range(30):
    t.insert(k)
display(t.toDot())
while not t.isEmpty():
    print(t.pop(), end=' ')
display(t.toDot())


I am working on the file "Python/Shift-Reduce-Parser-Pure.ipynb".
The first task is:
Testing
Can you write Python code for it?

def test(s):
    parser = ShiftReduceParser(actionTable, gotoTable)
    TL     = tokenize(s)
    print(f'tokenlist: {TL}\n')
    if parser.parse(TL):
        print('Parse successful!')
    else:
        print('Parse failed!')

test('(1 + 2) * 3')

test('1 * 2 + 3 * (4 - 5) / 2')

test('11+22*(33-44)/(5-10*5/(4-3))')

test('1+2*3-')


I am working on the file "Python/Shift-Reduce-Parser-Pure.ipynb".
The first task is:
The function tokenize scans the string s into a list of tokens using Python's regular expressions.  The scanner distinguishes between
* whitespace, which is discarded,
* numbers,
* arithmetical operators and parenthesis,
* all remaining characters, which are treated as lexical errors.
See below for an example.
Can you write Python code for it?

def tokenize(s):
    '''Transform the string s into a list of tokens.  The string s
       is supposed to represent an arithmetic expression.
    '''
    lexSpec = r'''([ \t\n]+)      |  # blanks and tabs
                  ([1-9][0-9]*|0) |  # number
                  ([-+*/()])      |  # arithmetical operators and parentheses
                  (.)                # unrecognized character
               '''
    tokenList = re.findall(lexSpec, s, re.VERBOSE)
    result    = []
    for ws, number, operator, error in tokenList:
        if ws:        # skip blanks and tabs
            continue
        elif number:
            result += [ 'NUMBER' ]
        elif operator:
            result += [ operator ]
        else:
            result += [ f'ERROR({error})']
    return result

tokenize('1 + 2 * (3 - 4)')


I am working on the file "Python/Shift-Reduce-Parser-Pure.ipynb".
The first task is:
The function tokenize transforms the string s into a list of tokens. See below for an example.
Can you write Python code for it?

def tokenize(s):
    '''Transform the string s into a list of tokens.  The string s
       is supposed to represent an arithmetic expression.
    '''
    lexSpec = r'''([ \t\n]+)      |  # blanks and tabs
                  ([1-9][0-9]*|0) |  # number
                  ([()])          |  # parentheses
                  ([-+*/])        |  # arithmetical operators
                  (.)                # unrecognized character
               '''
    tokenList = re.findall(lexSpec, s, re.VERBOSE)
    result    = []
    for ws, number, parenthesis, operator, error in tokenList:
        if ws:        # skip blanks and tabs
            continue
        elif number:
            result += [ 'NUMBER' ]
        elif parenthesis:
            result += [ parenthesis ]
        elif operator:
            result += [ operator ]
        else:
            result += [ f'ERROR({error})']
    return result

tokenize('1 + 2 * (3 - 4)')


I am working on the file "Python/Shift-Reduce-Parser-Pure.ipynb".
The first task is:
The method parse takes a list of tokens TL as its argument.  It returns True if the token list can be parsed successfully or False otherwise.
It algorithm that is applied is known as shift/reduce parsing.
Can you write Python code for it?

def parse(self, TL):
    index   = 0      # points to next token
    Symbols = []     # stack of symbols
    States  = ['s0'] # stack of states, s0 is start state
    TL     += ['EOF']
    while True:
        q = States[-1]
        t = TL[index]
        # Below, an undefined table entry is interpreted as an error entry.
        match self.mActionTable.get((q, t), 'error'):
            case 'error':
                return False
            case 'accept':
                return True
            case 'shift', s:
                Symbols += [t]
                States  += [s]
                index   += 1
            case 'reduce', rule:
                head, body = rule
                n       = len(body)
                Symbols = Symbols[:-n]
                States  = States [:-n]
                Symbols = Symbols + [head]
                state   = States[-1]
                States += [ self.mGotoTable[state, head] ]

ShiftReduceParser.parse = parse
del parse

%run Parse-Table.ipynb


I am working on the file "Python/Shift-Reduce-Parser.ipynb".
The first task is:
A Shift-Reduce Parser for Arithmetic Expressions
In this notebook we implement a simple recursive descend parser for arithmetic expressions.
This parser will implement the following grammar:
$$
  \begin{eqnarray}
  \mathrm{expr}        & \rightarrow & \mathrm{expr}\;\;\texttt{'+'}\;\;\mathrm{product}   \
                       & \mid        & \mathrm{expr}\;\;\texttt{'-'}\;\;\mathrm{product}   \
                       & \mid        & \mathrm{product}                                    \[0.2cm]
  \mathrm{product}     & \rightarrow & \mathrm{product}\;\;\texttt{''}\;\;\mathrm{factor} \
                       & \mid        & \mathrm{product}\;\;\texttt{'/'}\;\;\mathrm{factor} \
                       & \mid        & \mathrm{factor}                                     \[0.2cm]
  \mathrm{factor}      & \rightarrow & \texttt{'('} \;\;\mathrm{expr} \;\;\texttt{')'}     \
                       & \mid        & \texttt{NUMBER}
  \end{eqnarray*}
$$
Can you write Python code for it?


I am working on the file "Python/Shift-Reduce-Parser.ipynb".
The first task is:
Testing
Can you write Python code for it?

def test(s):
    parser = ShiftReduceParser(actionTable, gotoTable, stateTable)
    TL     = tokenize(s)
    print(f'tokenlist: {TL}\n')
    if parser.parse(TL):
        print('Parse successful!')
    else:
        print('Parse failed!')

test('1 + 2 * 3')

test('1 + 2 * (3 - 4)')


I am working on the file "Python/Shift-Reduce-Parser.ipynb".
The first task is:
The function tokenize transforms the string s into a list of tokens. See below for an example.
Can you write Python code for it?

def tokenize(s):
    '''Transform the string s into a list of tokens.  The string s
       is supposed to represent an arithmetic expression.
    '''
    lexSpec = r'''([ \t\n]+)      |  # blanks and tabs
                  ([1-9][0-9]*|0) |  # number
                  ([()])          |  # parentheses
                  ([-+*/])        |  # arithmetical operators
                  (.)                # unrecognized character
               '''
    tokenList = re.findall(lexSpec, s, re.VERBOSE)
    result    = []
    for ws, number, parenthesis, operator, error in tokenList:
        if ws:        # skip blanks and tabs
            continue
        elif number:
            result += [ 'NUMBER' ]
        elif parenthesis:
            result += [ parenthesis ]
        elif operator:
            result += [ operator ]
        else:
            result += [ f'ERROR({error})']
    return result

tokenize('1 + 2 * (3 - 4)')

class ShiftReduceParser():
    def __init__(self, actionTable, gotoTable, stateTable):
        self.mActionTable = actionTable
        self.mGotoTable   = gotoTable
        self.mStateTable  = stateTable

def parse(self, TL):
    index   = 0      # points to next token
    Symbols = []     # stack of symbols
    States  = ['s0'] # stack of states, s0 is start state
    TL     += ['EOF']
    while True:
        q = States[-1]
        t = TL[index]
        print(f'States:  [ {", ".join(States)} ]')
        print('Symbols:', ' '.join(Symbols + ['|'] + TL[index:]).strip())
        print('State:   {', ", ".join(self.mStateTable[q]), '}')
        p = self.mActionTable.get((q, t), 'error')
        if p == 'error':
            print(f'Action({q}, {t}) undefined.')
            print('Syntax error!\n')
            return False
        elif p == 'accept':
            print('Accepting!\n')
            return True
        elif p[0] == 'shift':
            s = p[1]
            print(f'Shifting state {s}')
            print('State:   {', ', '.join(self.mStateTable[s]), '}\n')
            Symbols += [t]
          ...


I am working on the file "Python/Signal/Solving_RC_low_pass_with_ODE.ipynb".
The first task is:
Setting up the ODE
We now step through the problem in a simple loop. Each next step is computed from the
previous one, as we have shown above.
$$
\begin{eqnarray}
V_{i+1}^c &=& \frac{1}{RC}(V_{i}^{in} - V_{i}^c)\Delta t + V_{i}^c
\end{eqnarray}
$$
Since the i+1 depends on the i, we cannot use a simple Numpy call. Instead we just compute this as a loop over i. Note that because of the i+1, we need to make Vc one step larger. When plotting we need to remember that.
Can you write Python code for it?

# Some reasonable values for R=2kΩ and C= 1µF
R = 1.e+3
C = 1.e-6
Vc = np.zeros(len(Vin)+1)  # A zero array of the needed length.
Vc[0] = Vin[0]           # Initialize the first step.
for i in indexes:  # Careful, we cannot do the last step because of the i+1 !!!
    Vc[i+1] = (Vin[i]-Vc[i])*DT/(R*C) + Vc[i]

plt.figure(figsize=(10,5))
plt.plot(1000*t,Vin,label="Vin" )             # Change the x-axis scale to ms by multiplying by 10^3
plt.plot(1000*t,Vc[:-1],label="Vout")
ax = plt.gca()
ax.set_xlim(0.,50.)               # Show only the first 50 ms of the signal
plt.grid(True)
plt.title("Square Wave")
plt.xlabel("time(ms)",position=(0.95,1))
plt.ylabel("signal(V)",position=(1,0.9))
plt.show()