I am working on the file "Section 1 - Core Python/Chapter 11 - Exceptions/Chapter13_Exceptions.ipynb".
The first task is:
Exception hierarchy
The class hierarchy for built-in exceptions is:
```
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning
```
Can you write Python code for it?

import inspect
inspect.getclasstree(inspect.getmro(Exception))

# https://stackoverflow.com/questions/18296653/print-the-python-exception-error-hierarchy
def classtree(cls, indent=0):
    print ('.' * indent, cls.__name__)
    for subcls in cls.__subclasses__():
        classtree(subcls, indent + 3)

classtree(BaseException)


I am working on the file "Section 1 - Core Python/Chapter 11 - Exceptions/Chapter13_Exceptions.ipynb".
The first task is:
If except receives the name of an exception, only that exception will be handled. If no exception name is passed as a parameter, all exceptions will be handled.
Example:
Can you write Python code for it?

import sys

try:
    print("... TESTing.. ")
    with open('myfile.txt', "w") as myFile:
        for a in ["a", "b", "c"]:
            myFile.write(str(a))
        for a in [1, 2, 3, 4, 5, "6"]:
            myFile.write(str(a))

#     f = open('myfile.txt')
#     s = f.readline()
#     i = int(s.strip())
    raise Exception("Test Exception")
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
    raise
except:
    print("Unexpected error:", sys.exc_info())
    try:
        print(1/0)
    except:
        print("Hallo, Ja")
    raise

import sys

try:
#     print(1 > z)
    print(1 / a)
except (OSError, NameError,  ValueError, ZeroDivisionError) as err:
    print("Some common error: {0}".format(err))
except:
    print("Unexpected error:", sys.exc_info())

# -*- coding: utf-8 -*-
"""
Created on Fri Aug  5 08:50:42 2016

@author: mayankjohri@gmail.com
"""
import traceback

# Try to get a file name
try:
#     fn = input('File Name (temp.txt): ').strip()
    fn = "temp.txt"
    # Numbering lines
    for i, s in enumerate(open(fn)):
        print( i + 1,"> ", s,)
        if i == 2:
            raise ValueError

# If an error happens
except:
    # Show it on the screen
    trace = traceback.format_exc()

    # And save it on a file
    print ('An error happened:\n', trace)

    with open("trace_asd.log", "a+") as file:
        file.write(trace)

#    file('trace_asd.log', 'a').write(trace)

    # end the program
#     raise SystemExit


I am working on the file "Section 1 - Core Python/Chapter 11 - Exceptions/Chapter13_Exceptions.ipynb".
The first task is:
The module traceback offers functions for dealing with error messages. The function format_exc() returns the output of the last exception formatted in a string.
The handling of exceptions may have an else block, which will be executed when no exception occurs and a finally block, which will be executed anyway, whether an exception occurred or not. New types of exceptions may be defined through inheritance of the class Exception.
Since version 2.6, the instruction with is available, that may replace the combination of try / finally in many situations. It is possible to define an object that will be used during the with block execution. The object will support the context management protocol, which means that it will need to have an __enter__() method, which will be executed at the beginning of the block, and another called __exit__(), which will be called at the end of the block.
Example:
Can you write Python code for it?

def do_some_stuff():
    print("Doing some stuff")

def do_some_stuff_e():
    print("Doing some stuff and will now raise error")
    raise ValueError('A very specific bad thing happened')

def rollback():
    print("reverting the changes")

def commit():
    print("commiting the changes")

print("Testing")

try:
#   do_some_stuff()
  do_some_stuff_e()
except:
  rollback()
#   raise
else:
  commit()
finally:
    print("Exiting out")

# #### ERROR Condtion
# Testing
#     try block
# Doing some stuff and will now raise error
#     except block
# reverting the changes
#     Finally block
# Exiting out

# NO ERROR
# Testing
#     Try block
# Doing some stuff
#     else block
# commiting the changes
#     finally block
# Exiting out


def do_some_stuff():
    print("Doing some stuff")

def do_some_stuff_e():
    print("Doing some stuff and will now raise error")
    raise ValueError('A very specific bad thing happened')

def rollback():
    print("reverting the changes")

def commit():
    print("commiting the changes")

print("Testing")

try:
#   do_some_stuff()
    do_some_stuff_e()
except:
        rollback()
#   raise
else:
    commit()
finally:
    print("Exiting out")

# #### ERROR Condtion
# Testing
#     try block
# Doing some stuff and will now raise error
#     except block
# reverting the changes
#     Finally block
# Exiting out

# NO ERROR
# Testing
#     Try block
# Doing some stuff
#     else block
# commiting the changes
#     finally block
# Exiting out


I am working on the file "Section 1 - Core Python/Chapter 11 - Exceptions/Chapter13_Exceptions.ipynb".
The first task is:
The try instruction allows exception handling in Python. If an exception occurs in a block marked by try, it is possible to handle the exception through the instruction except. It is possible to have many except blocks for the same try block.
Can you write Python code for it?

try:
    print (1/0)
except ZeroDivisionError:
    print ('Error trying to divide by zero.')

try:
    print (1/0)
except:
    print ('Error trying to divide by zero.')

try:
    print (1/0)
except Exception:
    # Please put the ex.message in some logfile instead of on the console
    print ('Error trying to divide by zero.', Exception)

try:
    print (1/0)
except Exception as e:
    # Please put the ex.message in some logfile instead of on the console
    print ('Error trying to divide by zero.', e)
    print(dir(e))


I am working on the file "Section 1 - Core Python/Chapter 12 - Introspection/Chapter14_Introspection.ipynb".
The first task is:
Python also has a module called types, which has the definitions of the basic types of the interpreter.
Example:
Can you write Python code for it?

import types

s = ''
if isinstance(s, types.StringType):
    print 's is a string.'


I am working on the file "Section 1 - Core Python/Chapter 12 - Introspection/Chapter14_Introspection.ipynb".
The first task is:
Through introspection, it is possible to determine the fields of a database table, for example.
Inspect
The module inspect provides a set of high-level functions that allow for introspection to investigate types, collection items, classes, functions, source code and the runtime stack of the interpreter.
Example:
Can you write Python code for it?

import os.path
# inspect: "friendly" introspection module
import inspect

print 'Object:', inspect.getmodule(os.path)

print 'Class?', inspect.isclass(str)

# Lists all functions that exist in "os.path"

print 'Member:',

for name, struct in inspect.getmembers(os.path):

    if inspect.isfunction(struct):
        print name,


I am working on the file "Section 1 - Core Python/Chapter 13 - Decorators/Decorators.ipynb".
The first task is:
!!! Order Matters !!!
Can you write Python code for it?

@ingredients
@bread
def sandwich(food="--Say Cheese--"):
    print(food)

sandwich()

@bread
@ingredients
def hotdog(food="Jam"):
    print(food)

hotdog()

def Names(test_funct):
    def inner():
        print("{Hello}")
        print("\tA-Priya")
        print("\tManish Gupta")
        print("\tNeha", end="\n\t")
        test_funct()
        print("(/Hello}")
    return inner

@Names
def print_AShanti():
    print("A-Shanti")

print_AShanti()

def names(test_funct):
    def inner():
        print("\t", name)
        test_funct()
    return inner()

def Hello(test_funct):
    def inner():
        print("{Hello}")
        print("\tA-Priya")
        print("\tManish Gupta")
        print("\tNeha", end="\n\t")
        test_funct()
        print("(/Hello}")
    return inner

@Hello
@names(name="Mayank")
def print_AShanti():
    print("A-Shanti")

print_AShanti()


I am working on the file "Section 1 - Core Python/Chapter 13 - Decorators/Decorators.ipynb".
The first task is:
Class Decorators
Bound methods

Unless you tell it not to, Python will create what is called a bound method when a function is an attribute of a class and you access it via an instance of a class. This may sound complicated but it does exactly what you want.
Can you write Python code for it?

class A(object):
    def method(*argv):
        return argv
a = A()
a.method

a.method('an arg')


I am working on the file "Section 1 - Core Python/Chapter 13 - Decorators/Decorators.ipynb".
The first task is:
Function Decorators
A function decorator is applied to a function definition by placing it on the line before that function definition begins
Can you write Python code for it?

@bread
@ingredients
def sandwich(food="--Say Cheese--"):
    print(food)

sandwich()


I am working on the file "Section 1 - Core Python/Chapter 13 - Decorators/Decorators.ipynb".
The first task is:
When we call a static method we don’t get any additional arguments.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 13 - Decorators/Decorators.ipynb".
The first task is:
classmethod
A class method is like a bound method except that the class of the instance is passed as an argument rather than the instance itself.
Can you write Python code for it?

class A(object):
    @classmethod
    def method(*argv):
        return argv
a = A()
a.method

a.method('an arg')

def test(strg):
    print("Name: ", strg)

def hello(func, name):
    print("Ja")
    func(name)

hello(test, "Mayank")

class B(object):
    @classmethod
    def method(*argv):
        return argv

a = B()
a.method()


I am working on the file "Section 1 - Core Python/Chapter 13 - Decorators/Decorators.ipynb".
The first task is:
staticmethod()
A static method is a way of suppressing the creation of a bound method when accessing a function.
Can you write Python code for it?

class A(object):
    @staticmethod
    def method(*argv):
        return argv
a = A()
a.method


I am working on the file "Section 1 - Core Python/Chapter 14 - Properties/property.ipynb".
The first task is:
Another example to
Can you write Python code for it?

### Method 3
class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature

    def to_fahrenheit(self):
        return (self._temperature * 1.8) + 32

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

    @temperature.deleter
    def temperature(self):
        print("deleting the property")
        del(self._temperature)

celc = Celsius()
celc.temperature = 100
print(celc.temperature)
del(celc.temperature)
print(celc.temperature) # This property is no longer valid thus will error out


I am working on the file "Section 1 - Core Python/Chapter 14 - Properties/property.ipynb".
The first task is:
Deep in Property
Can you write Python code for it?

### Method 1
temperature = property(get_temperature, set_temperature)

### Method 2
# make empty property
temperature = property()
# assign getter
temperature = temperature.getter(get_temperature)
# assign setter
temperature = temperature.setter(set_temperature)

### Method 3
class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature

    def to_fahrenheit(self):
        return (self._temperature * 1.8) + 32

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

celc = Celsius()
celc.temperature = 100
print(celc.temperature)
# del(celc.temperature) # Need to explicitly define a deleter
# print(celc.temperature)


I am working on the file "Section 1 - Core Python/Chapter 14 - Properties/property.ipynb".
The first task is:
We can see above that new methods get_temperature() and set_temperature() were defined and furthermore, temperature was replaced with _temperature. An underscore (_) at the beginning is used to denote private variables in Python.
Python Way - Property

The pythonic way to deal with the above problem is to use property. Here is how we could have achieved it.
Can you write Python code for it?

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    def get_temperature(self):
        print("Getting value")
        return self._temperature

    def set_temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

    temperature = property(get_temperature, set_temperature)

man = Celsius()
# set temperature
man.temperature = 137

# get temperature
print(man.temperature)

# get degrees Fahrenheit
print(man.to_fahrenheit())
##### print(Celsius.temperature)


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
Fractions can be initialized in several ways: as a string, as a pair of integers, or as a real number. The module also has a function called gcd() which calculates the greatest common divisor (gcd) of two integers.
Files and I/O
Files in Python are represented by objects of type file, which offer various methods for file operations. Files can be opened for reading ('r', which is the default), writing ('w'), or appending ('a'), in text or binary ('b') mode.
In Python:

sys.stdin is the standard input.
sys.stdout is the standard output.
sys.stderr is the standard error output.

The standard input, output and error are handled by Python as open files. The input in read mode and the other in the recording mode.
Sample of writing:
Can you write Python code for it?

# The old way .... the C,C++ etc way
import sys

# Create an object of type file
temp = open('temp.txt', 'w')

# Write output
for i in range(20):
    temp.write('%03d\n' % i)

temp.close()

temp = open('temp.txt')
temp1 = open('temp1.txt', "w")

# Write in terminal
for x in temp:
    # writing in sys.stdout sends
    # text to standard output
    print("x")
    sys.stdout.write(x)
    temp1.write(x)

temp.close()
temp1.close()

#  Python way
import sys

# Create an object of type file
with open('temp.txt', 'w') as temp:
    # Write output
    for i in range(20):
        temp.write('%03d\n' % i)

with open('temp.txt') as temp:
    # Write in terminal
    for x in temp:
        # writing in sys.stdout sends
        # text to standard output
        sys.stdout.write(x)

### TODO
# replace content of the file without temp file.
# on the fly content changes
txt = []
temp = open('temp.txt', 'r')
for t in temp.readlines():
#     print("d")
    txt.append(t.replace('0','11'))

with open('temp.txt', 'w') as tfile:
    tfile.writelines(txt)

# print(help(open))


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
In the standard library there is the decimal module that defines operations with real numbers with fixed precision.
Example:
Can you write Python code for it?

from decimal import Decimal

t = 5.
for i in range(50):
    t = t - 0.1

print ('Float:', t)

t = Decimal('5.')
for i in range(50):
    t = t - Decimal('0.1')

print ('Decimal:', t)


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
It is possible to read all the lines with the method readlines():
Can you write Python code for it?

# Prints a list with all the lines from a file
print (open('temp.txt').readlines())

print(len(open('temp.txt').readlines())) # 20
print(len(open('temp.txt').read())) # 4x20


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
Python also provides modules for gzip, bzip2 and tar formats that are widely used in UNIX environments.
Data file
In the standard library, Python also provides a module to simplify the processing of files in CSV (Comma Separated Values) format.
In CSV format, the data is stored in text form, separated by commas, one record per line.
Writing example:
Can you write Python code for it?

import csv

with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

lst = [["a", "a1"], ["b", "b1"], ["d", "d1 ,one"], "c", "f" ]
with open('list.csv', 'w', newline='') as csvfile:
    listWriter = csv.writer(csvfile)
    for l in lst:
        listWriter.writerow(l)


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
The glob.glob() function returns a list of filenames that meet the criteria passed as a parameter in a similar way to the ls command available on UNIX systems.
Temporary files
The module os implements some functions to facilitate the creation of temporary files, freeing the developer from some concerns, such as:

Avoiding collisions with names of files that are in use.
Identifying the appropriate area of the file system for temporary files (which varies by operating system).
Not exposing the implementation risks (temporary area is used by other processes).

Example:
Can you write Python code for it?

import tempfile

# create a temporary file and write some data to it
fp = tempfile.TemporaryFile()
fp.write(b'Hello world!')
# read data from file
fp.seek(0)
fp.read()

# close the file, it will be removed
fp.close()

# create a temporary file using a context manager
with tempfile.TemporaryFile() as fp:
    fp.write(b'Hello world!')
    fp.seek(0)
    fp.read()

# file is now closed and removed

# create a temporary directory using the context manager
with tempfile.TemporaryDirectory() as tmpdirname:
    print('created temporary directory', tmpdirname)

# directory and contents have been removed


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
The random module brings functions for random number generation.
Examples:
Can you write Python code for it?

import random
import string

# Choose a letter
# print(string.printable)
# print(string.lowercase)

# print(help(random))
print (random.choice(string.ascii_uppercase))
print (random.choice([10, 200, 399, "Hello", "God", "Python", [222]]))
# Choose a number from 1 to 10
x = random.randrange(1, 100)
print (x)

# Choose a float from 0 to 1
print (random.random()*100)

lst = ["a", "b", "c", "e"]
dirs ={}

for  l in lst:
    dirs[l] = random.randrange(1, 100)

print(dirs)


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
textwrap — Text wrapping and filling
The textwrap module provides some convenience functions, as well as TextWrapper, the class that does all the work. If you’re just wrapping or filling one or two text strings, the convenience functions should be good enough; otherwise, you should use an instance of TextWrapper for efficiency

textwrap.wrap - Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines. Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 70.
Can you write Python code for it?

import textwrap
txt = "    The   `textwrap` module provides some convenience functions, as well as `TextWrapper`, the class that does all the work. If you’re just wrapping or filling one or two text strings, the convenience functions should be good enough; otherwise, you should use an instance of `TextWrapper` for efficiency"
print(txt)

for t in textwrap.wrap(txt):
    print(t)

for t in textwrap.wrap(txt, width=100):
    print(t)

for t in textwrap.wrap(txt, width=60, initial_indent="* "):
    print(t)


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
textwrap.dedent - Remove any common leading whitespace from every line in text.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Chapter 10_Standard_library.ipynb".
The first task is:
textwrap.shorten - Collapse and truncate the given text to fit in the given width. First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width
Can you write Python code for it?

print(textwrap.shorten(txt, width=60))
print(textwrap.shorten(txt, width=50))
s = textwrap.shorten(txt, width=25, placeholder="...")
print(s)
print(len(s))
s = textwrap.shorten(txt, width=20, placeholder="...")
print(s)
print(len(s))


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb".
The first task is:
Copy with the Slice Operator
Copying using slice can help us upto a certain level as shown in the below example
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb".
The first task is:
Difference between shallow and deep copying
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Two problems often exist with deep copy operations that don't exist with shallow copy operations:
Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.

The deepcopy() function avoids these problems by:
keeping a 'memo' dictionary of objects already copied during the current copying pass; and
letting user-defined classes override the copying operation or the set of components copied.

Controlling Copy Behavior
It is possible to control how copies are made using the copy and deepcopy hooks.
__copy__() is called without any arguments and should return a shallow copy of the object.
__deepcopy__() is called with a memo dictionary, and should return a deep copy of the object. Any member attributes that need to be deep-copied should be passed to copy.deepcopy(), along with the memo dictionary, to control for recursion (see below).

This example illustrates how the methods are called:
Can you write Python code for it?

import copy

class MyClass:
    def __init__(self, name):
        self.name = name
    def __cmp__(self, other):
        return cmp(self.name, other.name)
    def __copy__(self):
        print ('__copy__()')
        return MyClass(self.name)
    def __deepcopy__(self, memo):
        print ('__deepcopy__(%s)' % str(memo))
        return MyClass(copy.deepcopy(self.name, memo))

a = MyClass('a')

sc = copy.copy(a)
dc = copy.deepcopy(a)


I am working on the file "Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb".
The first task is:
but may will fail, if we have heterogeneous data-types in the list as shown in below examples
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter S1.A - Review & Class work/Interview Questions - Core Python.ipynb".
The first task is:
Find the number of times a value is present in a list
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter S1.A - Review & Class work/Interview Questions - Core Python.ipynb".
The first task is:
What is the output of the followings

```python
def listing(num, lst=[]):
    lst.append(num)
    return True

l = [1, 2, 3]
b = listing(10, l)
print(b, l)
-python
def listing(num, lst):
    lst.append(num)
    return True
l = [1, 2, 3]
b = listing(10, l)
print(b, l)
-python
def listing(num, lst=[]):
    lst.append(num)
    return True
l = [1, 2, 3]
b = listing([10], l)
print(b, l)
-python
def listing(num, lst=[]):
    lst.append(num)
    return True
l = [1, 2, 3]
b = listing([10], l)
print(b, l)
-python
101 in [101, 102, 103]
-python
104 in [101, 102, 103]
-python
l = ["Mango", 'is', 'a', 'fruit']
" ".join(l)
```

Dictionary

What is dictionary
How to get all the keys from the dictionary
How to get all the values from the dictionary

How to get both key & value from the dictionary as tuple of list

List all methods to dictionary be initialized using lists

Create a dictionary using two list

Create a dictionary from a list with key as position in list

Create a dictionary from a text file which contains unique words as keys and its occurrence as value
Can you write Python code for it?

# using open command to read the text file and store the value in `v_txt` variable
v_txt = """O nourisher, and enlightened person the policy which urges upon others the attainment of knowledge and
wealth is like a saw, that uphold the heart of people like you and spread good virtues far and near.

O teachers and preachers! you uphold kingdom or wealth every day (by your noble teachings), by the simile of illustration of the sun, you make firm the summit or the
advancement of the State, by whose association a man who is illuminator or instructor of all objects becomes firm and not decayinghaving
reached the earth and desirable knowledge, is increaser of the life, those who approach such a man and those (teachers and
preachers) ever enjoy happiness.

O men ! always have association with those teachers and preachers, who illuminate the dealirg of knowledge like the sun and increase kingdom, wealth and span of life and uphold
(establish) all in happiness. It is they by whose association, men become endowed with knowledge.
"""

words = v_txt.split()

# Lets create the dictionary with words, all the values has been defaulted to 0
v_dict = {}.fromkeys(words,0)

print(v_dict)
print("*"*20)
for w in words:
    v_dict[w] += 1
print(v_dict)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/0 - Introduction to Programming Paradigm.ipynb".
The first task is:
Functional
Can you write Python code for it?

from functools import reduce

def add(x, y):
    return x + y

sum = reduce(add, L)
print(sum)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/0 - Introduction to Programming Paradigm.ipynb".
The first task is:
Imperative
Can you write Python code for it?

sum = 0

for x in L:
    sum += x

print(sum)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/0 - Introduction to Programming Paradigm.ipynb".
The first task is:
the above example is below implemented using lambda
Can you write Python code for it?

import functools

Sum = functools.reduce(lambda x, y: x + y, L)
print(Sum)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/00_01_Introduction_to_Programming_Paradigm.ipynb".
The first task is:
Design Patterns
Flyweight pattern
In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the objects temporarily when they are used.
A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally.
REFERENCE: https://en.wikipedia.org/wiki/Flyweight_pattern
Can you write Python code for it?

# Instances of CheeseBrand will be the Flyweights
class CheeseBrand(object):
    def __init__(self, brand, cost):
        self.brand = brand
        self.cost = cost
        self._immutable = True   # Disables future attributions

    def __setattr__(self, name, value):
        if getattr(self, '_immutable', False):  # Allow initial attribution
            raise RuntimeError('This object is immutable')
        else:
            super(CheeseBrand, self).__setattr__(name, value)

class CheeseShop(object):
    menu = {}  # Shared container to access the Flyweights

    def __init__(self):
        self.orders = {}  # per-instance container with private attributes

    def stock_cheese(self, brand, cost):
        cheese = CheeseBrand(brand, cost)
        self.menu[brand] = cheese   # Shared Flyweight

    def sell_cheese(self, brand, units):
        self.orders.setdefault(brand, 0)
        self.orders[brand] += units   # Instance attribute

    def total_units_sold(self):
        return sum(self.orders.values())

    def total_income(self):
        income = 0
        for brand, units in self.orders.items():
            income += self.menu[brand].cost * units
        return income

shop1 = CheeseShop()
shop2 = CheeseShop()

shop1.stock_cheese('white', 1.25)
shop1.stock_cheese('blue', 3.75)
# Now every CheeseShop have 'white' and 'blue' on the inventory
# The SAME 'white' and 'blue' CheeseBrand

shop1.sell_cheese('blue', 3)    # Both can sell
shop2.sell_cheese('blue', 8)    # But the units sold are stored per-instance

assert shop1.total_units_sold() == 3
assert shop1.total_income() == 3.75 * 3

assert shop2.total_units_sold() == 8
assert shop2.total_income() == 3.75 * 8


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/00_01_Introduction_to_Programming_Paradigm.ipynb".
The first task is:
Functional
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/00_01_Introduction_to_Programming_Paradigm.ipynb".
The first task is:
Functional: Every statement in functional programming is treated as mathematical equation. Also state or mutable data are avoided. Its main advantage are

that any side effects due to data are avoided,
good at parallel processing because there is no state, recursion and lambda calculus.

Object-oriented: Relies on data fields that are treated as objects and manipulated only through prescribed methods. Python doesn’t fully support this coding form because it can’t implement features such as data hiding. However, this remains a useful coding style for complex applications because it supports encapsulation and polymorphism. This coding style also favors code reuse.

Procedural: Tasks are treated as step-by-step iterations where common tasks are placed in functions that are called as needed. This coding style favors iteration, sequencing, selection, and modularization. It is a type of imperative programming in which, programs are created using one or more procedures (also known as subroutines or functions).

Examples
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/00_01_Introduction_to_Programming_Paradigm.ipynb".
The first task is:
Imperative
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/00_01_Introduction_to_Programming_Paradigm.ipynb".
The first task is:
Object-oriented
Can you write Python code for it?

class Saving(object):
    def __init__(self, list_data):
        self.total_savings = list_data

    def add(self):
        sum = 0
        for a in self.total_savings:
            sum += a
        return sum

s = Saving(L)
print(s.add())


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/00_01_Introduction_to_Programming_Paradigm.ipynb".
The first task is:
Procedural
Can you write Python code for it?

def add(a, b):
    return a + b

sum = 0
for a in L:
    sum = add(sum, a)

print(sum)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/00_01_Introduction_to_Programming_Paradigm.ipynb".
The first task is:
the above example is below implemented using lambda
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
13=2*4+5
F -> product_func
m => 5
x -> 2
y -> 4
2*4+5 = 8+5 = 13
In the above example higher-order function that takes two inputs- A function F(x) and a multiplier m.
Nested Functions
In Python, Function(s) can also be defined within the scope of another function. If this type of function definition is used the inner function is only in scope inside the outer function, so it is most often useful when the inner function is being returned (moving it to the outer scope) or when it is being passed into another function.
Notice that in the below example, a new instance of the function inner() is created on each call to outer(). That is because it is defined during the execution of outer(). The creation of the second instance has no impact on the first.
Can you write Python code for it?

def outer(a):
    """
    Outer function
    """
    y = 0

    def inner(x):
        """
        inner function
        """
        y = x*x*a
        return(y)
    print(a)

    return inner

my_out = outer

my_out(102)

o = outer(10)
b = outer(20)
print("*"*20)
print(b)
print(o)
print("*"*20)
print(o(10))
print(b(10))

def outer():
    """
    Outer function
    """
    if 'a' in locals():
        a +=10
    else:
        print("~"),
        a = 20
    def inner(x):
        """
        inner function
        """
        return(x*x*a)
    print(a)
    return inner

# oo = outer
# print(oo.__doc__)
o = outer()
print("*"*20)
print(o)
print(o(10))
print(o.__doc__)

b = outer()
print(b)
print(b(30))
print(b.__doc__)

x = 0

def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
??? why code
Can you write Python code for it?

def test():
    print("TESTTESTTEST")
    def yes(name):
        print("Ja, ", name)
        return True
    return yes

d = test()
print("XSSSS")
print(d("Venky"))

def power(exp):
    def subfunc(a):
        return a**exp
    return subfunc

square = power(2)
hexa = power(6)

print(square)
print(hexa)

print(square(5)) # 5**2
print()
print(hexa(3)) # 3**6
print(power(6)(3))
# subfunc(3) where exp = 6
# SQuare

# exp -> 2
# Square(5)
# a -> 5
# 5**2
# 25

 Power(6)(3, x)

def a1(m):
    x = m * 2
    def b(v, t=None):
        if t:
            print(x, m, t)
            return v + t
        else:
            print(x, m, v)
            return v + x
    return b
n = a1(2)
print(n(3))
print(n(3, 10))

def f1(a):
    def f2(b):
        return f2
        def f3(c):
            return f3
            def f4(d):
                return f4
                def f5(e):
                    return f5
print (f1(1)(2)(3)(4)(5))

def f1(a):
    def f2(b):
        def f3(c):
            def f4(d):
                def f5(e):
                    print(e)
                return f5
            return f4
        return f3
    return f2

f1(1)(2)(3)(4)(5)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Adding attributes to a function
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Closures & Factory Functions 1
They are techniques for implementing lexically scoped name binding with first-class functions. It is a record, storing a function together with an environment. a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.
A closure—unlike a plain function—allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.
Can you write Python code for it?

def f(x):
    def g(y):
        return x + y
    return g

def h(x):
    return lambda y: x + y

a = f(1)
b = h(1)
print(a, b)
print(a(5), b(5))
print(f(1)(5), h(1)(5))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Following DRY (Don't Repeat Yourself)
This type can be used if you have a section of code base in function is repeated in numerous places. For example, you might write a function which processes a file, and you want to accept either an open file object or a file name:
Can you write Python code for it?

# Keepin’ it DRY

def process(file_name):
    def do_stuff(file_process):
        for line in file_process:
            print(line)

    if isinstance(file_name, str):
        with open(file_name, 'r') as f:
            do_stuff(f)
    else:
        do_stuff(file_name)

process(["test", "test3", "t33"])
# process("test.txt")


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Functions as Objects
Functions are first-class objects in Python, meaning they have attributes and can be referenced and assigned to variables.
Can you write Python code for it?

def square(x):
    """
    This returns the square of the requested number `x`
    """
    return x**2

print(square(10))

print(square(100))

# Assignation to another variable
mySquare = square
print(mySquare(100))
print(square)
print(mySquare)
print(id(square))
print(id(mySquare))

# attributes present
print("*"*30)
print(dir(square))
print("*"*30)
print(mySquare.__name__)
print("*"*30)
print(square.__code__)
print("*"*30)
print(square.__doc__)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Inner / Nested Functions - When to use
Encapsulation
You use inner functions to protect them from anything happening outside of the function, meaning that they are hidden from the global scope.
Can you write Python code for it?

# Encapsulation

def increment(current):
    def inner_increment(x):  # hidden from outer code
        return x + 1
    next_number = inner_increment(current)
    return [current, next_number]

print(increment(10))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
NOTE: We can not access directly the inner function as shown below
Can you write Python code for it?

try:
    increment.inner_increment(109)
except Exception  as e:
    print(e)


try:
    increment.inner_increment(109)
except Exception  as e:
    print(e)

### NOT WORKING

def update(str_val):
    def updating(ori_str, key, value):
        token = "$"
        if key in ori_str:
            ori_str = ori_str.replace(token+key, value)
        return ori_str

    keyval = [{"test1": "val_test", "t1" : "val_1"}, {"test2": "val_test2", "t2" : "val_2"}]

    keyval1 = [{"test1": "val_test", "t1" : "val_1"}, {"test2": "val_test2", "t2" : "val_2"}]
    ori_str = "This is a $test1 and $test2, $t1 and $t2"

#     for k in keyval:
#         for key, value in k.items():
#             ori_str = updateing(ori_str, key, value)

    sdd = [ key, value [for key, value in k] for(k in keyval) ]

    print(ori_str)

update("D")

ld = [{'a': 10, 'b': 20}, {'p': 10, 'u': 100}]
[kv for d in ld for kv in d.items()]

ori_str = "This is a $test;1 and $test2, $t1 and $t2"
print(ori_str.replace("test1", "TEST1"))
print(ori_str)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Problem with local and global
lets take the above example, we have two functions, outer & inner. We also have x variable which is present as global and also present in both the functions.
If we want to access x of outer function from inner function than global keyword not help. Fortunately, Python provides a keyword nonlocal which allows inner functions to access variables to outer functions as shown in below example.
Can you write Python code for it?

x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:",x, "id:", id(x))

    inner()
    print("outer:",x, "id:", id(x))

outer()
print("global:",x, "id:", id(x))

def outer(a):
    """
    Outer function
    """
    y = 1
    def inner(x):
        """
        inner function
        """
        nonlocal y
        print(y)
        y = x*x*a
        return("y =" + str(y))
    print(a)
    return inner

o = outer(10)
b = outer(20)
print("*"*20)
print(o)
print(o(10))
print("*"*20)
print(b)
print(b(10))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
The lambda
The simplest way to initialize a pure function in python is by using lambda keyword, which helps in defining the one-line function. Functions initialized with lambda can often called anonymous functions
Can you write Python code for it?

# Example lambda keyword

product_func = lambda x, y: x*y

print(product_func(10, 20))
print(product_func(10, 2))

concat = lambda x, y: [x, y]

print(concat([1,2,3], 4))


# Example lambda keyword
product_func = lambda x, y: x*y

print(product_func(10, 20))
print(product_func(10, 2))

concat = lambda x, y: [x, y]

print(concat([1,2,3], 4))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
both a and b are closures—or rather, variables with a closure as value—in both cases produced by returning a nested function with a free variable from an enclosing function, so that the free variable binds to the parameter x of the enclosing function. However, in the first case the nested function has a name, g, while in the second case the nested function is anonymous. The closures need not be assigned to a variable, and can be used directly, as in the last lines—the original name (if any) used in defining them is irrelevant. This usage may be deemed an "anonymous closure".
1: Copied from : "https://en.wikipedia.org/wiki/Closure_(computer_programming)"
Can you write Python code for it?

def make_adder(x):
    def add(y):
        return x + y
    return add

plus10 = make_adder(10)
print(plus10(12))  # make_adder(10).add(12)
print(make_adder(10)(12))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
higher-order function
Python also supports higher-order functions, meaning that functions can accept other functions as arguments and return functions to the caller.
Can you write Python code for it?

print(square(square(square(2))))

product_func = lambda x, y: x*y

sum_func = lambda F, m: lambda x, y: F(x, y)+m

print(sum_func(product_func, 5)(2, 4))

print(sum_func)

print(sum_func(product_func, 5))

print(sum_func(product_func, 5)(3, 5))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.01_Functions_as_First_Class_citizens.ipynb".
The first task is:
or have similar logic which can be replaced by a function, such as mathematical functions, or code base which can be clubed by using some parameters.
Can you write Python code for it?

def square(n):
    return n**2

def cube(n):
    return n**3

print(square(2))

def sqr(a, b):
    return a**b


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.02_Comprehensions.ipynb".
The first task is:
!!!! Tip !!!!

Copy the variable assignment for our new empty list (line 3)
Copy the expression that we’ve been append-ing into this new list (line 6)
Copy the for loop line, excluding the final : (line 4)
Copy the if statement line, also without the : (line 5)
Can you write Python code for it?

# FROM
numbers = range(2,10)

doubled_odds = []
for n in numbers:
    if n % 2 == 1:
        doubled_odds.append(n * 2)
print(doubled_odds)

# TO
numbers = range(2,10)

doubled_odds = [n * 2 for n in numbers if n % 2 == 1]


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.02_Comprehensions.ipynb".
The first task is:
Can be rewritten into a list comprehension like this:
Can you write Python code for it?

new_things = [ITEM for ITEM in old_things if condition_based_on(ITEM)]
print(new_things)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.02_Comprehensions.ipynb".
The first task is:
Conditional Compreshensions
Can you write Python code for it?

doubled_odds = []

for n in range(1,12):
    if n % 2 == 1:
        doubled_odds.append(n * 2)
print(doubled_odds)

doubled_odds = [n * 2 for n in range(1,12) if n% 2 == 1]

print(doubled_odds)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.02_Comprehensions.ipynb".
The first task is:
Dictionary Comprehensions
Can you write Python code for it?

original = {'a':10, 'b': 34, 'A': 7, 'Z':3, "z": 199}

mcase_frequency = { k.lower() : original.get(k.lower(), 0) + original.get(k.upper(), 0) for k in original.keys() }
print(mcase_frequency)

original = {'a':10, 'b': 34, 'A': 7, 'Z':3, "z": 199, 'c': 10}
flipped = {value: key for key, value in original.items()}
print(flipped)

original = {'a':10, 'b': 34, 'A': 7, 'Z':3, "z": 199, 'c': 10}
newdict = {}
for key, value in original.items():
#     print(ori)
    if (value not in newdict):
        newdict[value] = key
print(newdict)

newdict = {value: key for key, value in original.items() if (value not in newdict)}
print(newdict)

x = {"a": 10, "b": 20, "c": 20}

print(x)
x["a"] = 100

print(x)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.02_Comprehensions.ipynb".
The first task is:
Generator Comprehension
They are simply a generator expression with a parenthesis "()" around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a generator instead of a list.
Can you write Python code for it?

x = (x**2 for x in range(20))
print(x)
print(list(x))

itm = 10
print(itm / 2)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/01.02_Comprehensions.ipynb".
The first task is:
Summary
When struggling to write a comprehension, don’t panic. Start with a for loop first and copy-paste your way into a comprehension.
Any for loop that looks like this:
Can you write Python code for it?

def condition_based_on(itm):
    return itm % 2 == 0

old_things = range(2,20, 3)
new_things = []
for ITEM in old_things:
    if condition_based_on(ITEM):
        new_things.append(ITEM)
print(new_things)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
As we have passed operator.itemgetter function as key, we can pass some custom function as well.
Now lets assume a situation, were we have to calculate total marks, which are calculated as sum of 10% of first 6 semesters and 100% of 7th & 8th semester and we wants to find the highest mark obtained for the year 1994 batch.
Can you write Python code for it?

# %%timeit
def marks_sum_v1(marks_list):
    total = 0
    for a in range(5):
        total += marks_list[a]
    total *= 0.1
    for a in range(6, 8):
        total += marks_list[a]
    return total

marks_sum_v1(max(marks, key = marks_sum_v1))

print('Maximum marks:\t', marks_sum_v1(max(marks, key = marks_sum_v1)))

# %%timeit

def marks_sum_v2(marks_list):
    total = 0

    total = sum(marks_list[a] * 0.1 for a in range(5))
    total += sum([marks_list[a] for a in range(6, 8)])
    return total

marks_sum_v2(max(marks, key=marks_sum_v2))

# %%timeit

def marks_sum_v2(marks_list):
    total = sum((sum(marks_list[a] for a in range(6, 8)),
                 sum(marks_list[a] * 0.1 for a in range(5))))
    return total

marks_sum_v2(max(marks, key=marks_sum_v2))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Closures & Factory Functions 1
They are techniques for implementing lexically scoped name binding with first-class functions. It is a record, storing a function together with an environment. a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.
A closure—unlike a plain function—allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.
Can you write Python code for it?

def f(x):
    def g(y):
        return x + y
    return g

def h(x):
    return lambda y: x + y

a = f(1)
b = h(1)
print(a, b)
print(a(5), b(5))
print(f(1)(5), h(1)(5))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Closures can avoid the use of global values and provides some form of data hiding. It can also provide an object oriented solution to the problem.
When there are few methods (one method in most cases) to be implemented in a class, closures can provide an alternate and more elegant solutions. But when the number of attributes and methods get larger, better implement a class.
In functional programming, functions can be treated as objects. That is, they can assigned to a variable, can be passed as arguments or even returned from other functions.
Can you write Python code for it?

a = 10
def test_function():
    pass
print(id(a), dir(a))
print(id(test_function), dir(test_function))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Following DRY (Don't Repeat Yourself)
This type can be used if you have a section of code base in function is repeated in numerous places. For example, you might write a function which processes a file, and you want to accept either an open file object or a file name:
Can you write Python code for it?

# Keepin’ it DRY
import os

def process(file_name):

    if isinstance(file_name, str):
        with open(file_name, 'r') as f:
            for line in f.readlines():
                print(line)
    else:
        for line in file_name:
            print(line)

process(["test", "test3", "t33"])
process(os.path.join("files", "process_me.txt"))

# Keepin’ it DRY
import os

def process(data):
    def do_stuff(file_process):
        for line in file_process:
            print(line)

    if isinstance(data, str):
        with open(data, 'r') as f:
            do_stuff(f)
    else:
        do_stuff(data)

process(["test", "test3", "t33"])
process(os.path.join("files", "process_me.txt"))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
In the above example higher-order function that takes two inputs- A function F(x) and a multiplier m.
Can you write Python code for it?

concat = lambda x, y: [x, y]

print(concat([1, 2, 3], 4))

print(concat({}, (2, 4)))

product_func = lambda x, y: x * y

sum_func = lambda F, m: lambda x, y: F(x, y) + m

### TODO: some expl.

print(sum_func(product_func, 6)(2, 4))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
In the above example higher-order function that takes two inputs- A function F(x) and a multiplier m.
In-built Higher Order Functions
Python provides many functions which can also act as higher order functions. We are going to cover few of them in this section.
max()
Max returns the largest item in an iterable or the largest of two or more arguments.
If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)).
Example: Basic Example
Can you write Python code for it?

marks = [[1, 2], [2, 1], [2, 4], [3, 0], [3, 4], [3, 2]]
max(marks)

marks = [1, 2, 4, 2, (5)]
max(marks)

try:
    marks = [1, 2, 4, 2, (5, 1)]
    max(marks)
except Exception as e:
    print(e)

try:
    marks = [1, 2, 4, 2, [5]]
    max(marks)
except Exception as e:
    print(e)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
In the above example, my_out contains the address of the instance of inner function when value of a is 102. Lets check that out by just printing my_out
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
In the above example, value 10 is behaving like an object, with multiple attributes exposed to the world.
Now lets do the same to a function and validate if that also behaves the same.
In the below example, we are creating a function test_function and then passed it to functions id and dir similar to what we did with the variable a.
Can you write Python code for it?

def test_function():
    """Test Function.

    This is just a test function.
    """
    pass

print(id(test_function))
print(dir(test_function))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
In the above example, we have three functions, done, square and increment.
- done takes two argument, val and func
- square & increment takes one val argument each
Since, both square & increment take one argument, they both can be passed to done and in both the cases the behaviour of done will change depending upon the behaviour of passed function.
Lets try it out.
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
In the above execution, we can see that both power and square are pointing to same function square.
Can you write Python code for it?

# attributes present
print("*"*30)
print(power.__name__)
print("*"*30)
print(square.__code__)
print("*"*30)
print(square.__doc__)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Now lets take an excercise, below are the marks for students for 8 semesters, and we need to find what is the highest marks in 3rd semester.
Can you write Python code for it?

import random
student_count = 10000
max_marks = 100
min_marks = 0
semester = 8
marks = [[random.randint(min_marks, max_marks) for _ in range(semester)] for _ in range(student_count)]

print(marks[:3])


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Now, lets check what happens if we pass it to functions id and dir in order to know more about them
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Now, lets perform some operations on it by passing values to my_out.
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Now, we have two instances of outer with different values of a thus returns they both return different values for same set of code (except where we updated the value of a).
Lets take another example, and see what happens when we have identifiers with same name in differnet scopes
Can you write Python code for it?

x = 0

def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
Problem with local and global
Lets take the above example, we have two functions, outer & inner. We also have x variable which is present as global and also present in both the functions.
If we want to access x of outer function from inner function than global keyword not help. Fortunately, Python provides a keyword nonlocal which allows inner functions to access variables to outer functions as shown in below example.
The details of nonlocal are details in https://www.python.org/dev/peps/pep-3104/
Can you write Python code for it?

x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:",x, "id:", id(x))

    inner()
    print("outer:",x, "id:", id(x))

outer()
print("global:",x, "id:", id(x))

def outer(a):
    """
    Outer function
    """
    PI = 3.1415

    def inner(x):
        """
        inner function
        """
        nonlocal PI
        print(PI)
        y = x*PI*a
        return("y =" + str(y))

    print(a)
    return inner

ten = outer(10)
second = outer(20)
print("*"*20)
print(ten)
print(ten(10))
print("*"*20)
print(second)
print(second(10))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
The lambda
The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce(). The lambda feature was added to Python due to the demand from Lisp programmers.
The general syntax of a lambda function is quite simple:
lambda argument_list: expression
The argument list consists of a comma separated list of arguments and the expression is an arithmetic expression using these arguments. You can assign the function to a variable to give it a name.
The following example of a lambda function returns the sum of its two arguments:
The simplest way to initialize a pure function in python is by using lambda keyword. It helps in defining an one-line function.
Functions initialized with lambda are also called anonymous functions.
Can you write Python code for it?

# Example lambda keyword
product_func = lambda x, y: x * y

print(product_func(10, 20))
print(product_func(120, 2))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
min()
Similer to max, min also provide the same functionality. thus is not covering in it in details except one example
Can you write Python code for it?

import random
student_count = 10000
max_marks = 100
min_marks = 0
semester = 8
marks = [[random.randint(min_marks, max_marks) for _ in range(semester)] for _ in range(student_count)]

def marks_sum_v1(marks_list):
    total = 0
    for a in range(5):
        total += marks_list[a]
    total *= 0.1
    for a in range(6, 8):
        total += marks_list[a] * 1
    return total

d = round(marks_sum_v1(min(marks, key = marks_sum_v1)),2)
print(d)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
or have similar logic which can be replaced by a function, such as mathematical functions, or code base which can be clubed by using some parameters.
Can you write Python code for it?

def square(n):
    return n**2

def cube(n):
    return n**3

print(square(2))

def sqr(a, b):
    return a**b


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
python
14 = 2 * 4 + 6
F -> product_func
m => 6
x -> 2
y -> 4
2 * 4 + 6 = 8 + 6 = 14
Can you write Python code for it?

print(sum_func)

print(sum_func(product_func, 5))

print(sum_func(product_func, 5)(3, 5))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_01_Functions_as_First_Class_citizens.ipynb".
The first task is:
the reason we got 21 is due to the fact that increment returns one move value than the number passed to it. In our case we passed 10 to done, which increased it to 20 before passing it to increment function and inturn received 21 from increment.
Nested Functions
Python allows function(s) to be defined within the scope of another function. In this type of setting the inner function is only in scope inside the outer function, thus inner functions are returned (without executing) or passed into another function for more processing.
In the below example, a new instance of the function inner() is created on each call to outer(). That is because it is defined during the execution of outer(). The creation of the second instance has no impact on the first.
So, we have two functions, outer and inner. outer function returns the instance of inner function and inner function performs some operations on the values provided and returns them.
Can you write Python code for it?

def outer(a):
    """
    Outer function
    """
    y = 0

    def inner(x):
        """
        inner function
        """
        y = x*x*a
        return(y)
    print(a)

    return inner

my_out = outer(10)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_02_map_reduce_and_filter.ipynb".
The first task is:
Reduce
Reduce takes a function and a collection of items. It returns a value that is created by combining the items. This is a simple reduce. It returns the sum of all the items in the collection.
Can you write Python code for it?

from functools import reduce

product = reduce(lambda a, x: a * x, range(1, 6))

print(product) # (((1 * 2 )* 3 )* 4) * 5
print(reduce(lambda a, x: a + x, range(1, 6), 10)) #-> 10 + 1 + 2+

help(reduce)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_02_map_reduce_and_filter.ipynb".
The first task is:
This can be rewritten as a lamba:
Can you write Python code for it?

import random

names = ["Mayank", "Manish", "Aalok", "Roshan Musheer"]
code_names = ['Mr. Normal', 'Mr. God', 'Mr. Cool', 'The Big Boss']
random.shuffle(code_names)

a_dict = lambda: {k: v for k, v in zip(names, code_names)}
print(a_dict())

# Excercise -> Try the above one using map, if possible

def dictMap(f, xs) :
    return dict((f(i), i) for i in xs)
lst = [1,2,4,6]
lst2 = [3,5, 7,9]
print(list(map(pow, lst, lst2)))

def fahrenheit(T):
    return ((float(9)/5)*T + 32)

temp = (36.5, 37, 37.5, 39)

F = map(fahrenheit, temp)
print(list(F))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_03_iter.ipynb".
The first task is:
iter()
The iter() method returns an iterator for the given object.
Syntax:
python
iter(object[, sentinel])
Where object is an object based on which the iterator needs to be constructed. The behavior of iterator is dependent on the value of sentinel, if sentinel is not provided then object should be an interator and the construct will behave as such, where as if sentinel is provided then object should be callable, and value returned will be treated as next call. Iteration ends when the value retuned equals to value in sentinel
Can you write Python code for it?

class MyDummy(object):
    def __init__(self):
        self.lst = [1, 2, 3, 4, 5, 6]
        self.i = 0

    def __call__(self):
        ret = self.lst[self.i]
        self.i += 1
        return ret

d = MyDummy()

for a in iter(d, 3):
    print(a, end=" ")

m = MyIter([1, 2, 3, 4, 5, 6])
for a in iter(m):
    print(a, end=" ")


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_03_iter.ipynb".
The first task is:
lets try another example, this time lets take a string
Can you write Python code for it?

st = "Welcome to the city of lakes"

for a in iter(st):
    print(a, end=" ")


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_04_Comprehensions.ipynb".
The first task is:
Conditional Compreshensions
Can you write Python code for it?

doubled_odds = []

for n in range(1,12):
    if n % 2 == 1:
        doubled_odds.append(n * 2)
print(doubled_odds)

doubled_odds = [n * 2 for n in range(1,12) if n% 2 == 1]

print(doubled_odds)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_04_Comprehensions.ipynb".
The first task is:
Dictionary Comprehensions
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_04_Comprehensions.ipynb".
The first task is:
Now, lets consolidate the above dictionary in such a way that resultant dictionary will have only lower case keys and if both lower and upper case keys are found in the original dictionary than values of both the keys should be added.
Can you write Python code for it?

mcase_freq = {}
for k in original.keys():
    mcase_freq[k.lower()] = original.get(k.lower(),0) + original.get(k.upper, 0)
print(mcase_freq)

mcase_frequency = { k.lower() : original.get(k.lower(), 0) + original.get(k.upper(), 0) for k in original.keys() }
print(mcase_frequency)

original = {'a':10, 'b': 34, 'A': 7, 'Z':3, "z": 199, 'c': 10}
flipped = {value: key for key, value in original.items()}
print(flipped)

original = {'a':10, 'b': 34, 'A': 7, 'Z':3, "z": 199, 'c': 10}
newdict = {}
for key, value in original.items():
#     print(ori)
    if (value not in newdict):
        newdict[value] = key
print(newdict)

newdict = {value: key for key, value in original.items() if (value not in newdict)}
print(newdict)

x = {"a": 10, "b": 20, "c": 20}

print(x)
x["a"] = 100

print(x)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_04_Comprehensions.ipynb".
The first task is:
Set Comprehensions
Set comprehensions allow sets to be constructed using the same principles as list comprehensions, the only difference is that resulting sequence is a set and "{}" are used instead of "[]".
Can you write Python code for it?

names = [ 'aaLok', 'Manish', 'AalOK', 'Manish', 'Gupta', 'Johri', 'Mayank' ]

new_names1 = [name[0].upper() + name[1:].lower() for name in names if len(name) > 1 ]
new_names = sorted({name[0].upper() + name[1:].lower() for name in names if len(name) > 1 })
print(new_names1)
print(new_names)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_04_Comprehensions.ipynb".
The first task is:
This map doesn’t take a named function. It takes an anonymous, inlined function defined with lambda. The parameters of the lambda are defined to the left of the colon. The function body is defined to the right of the colon. The result of running the function body is (implicitly) returned.
The unfunctional code below takes a list of real names and appends them with randomly assigned code names.
Can you write Python code for it?

import random

names_dict = {}
names = ["Mayank", "Manish", "Aalok", "Roshan Musheer"]
code_names = ['Mr. Normal', 'Mr. God', 'Mr. Cool', 'The Big Boss']

random.shuffle(code_names)

for i in range(len(names)):
    names_dict[names[i]] = code_names[i]

print(names_dict)

# Better implementation
import random

names_dict = {}
names = ["Mayank", "Manish", "Aalok", "Roshan Musheer"]
code_names = ['Mr. Normal', 'Mr. God', 'Mr. Cool', 'The Big Boss']

random.shuffle(code_names)

for i, _ in enumerate(names):
    names_dict[names[i]] = code_names[i]

print(names_dict)

# best implementation
import random

names_dict = {}
names = ["Mayank", "Manish", "Aalok", "Roshan Musheer"]
code_names = ['Mr. Normal', 'Mr. God', 'Mr. Cool', 'The Big Boss']

random.shuffle(code_names)

names_dict = dict(zip(names, code_names))

print(names_dict)

ld = [{'a': 10, 'b': 20}, {'p': 10, 'u': 100}]
dict([kv for d in ld for kv in d.items()])


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/03_map_reduce_and_filter.ipynb".
The first task is:
In the above example, x is the current iterated item and a is the accumulator.
It is the value returned by the execution of the lambda on the previous item. reduce() walks through the items. For each one, it runs the lambda on the current a and x and returns the result as the a of the next iteration.
What is a in the first iteration? There is no previous iteration result for it to pass along. reduce() uses the first item in the collection for a in the first iteration and starts iterating at the second item. That is, the first x is the second item.
This code counts how often the word 'the' appears in a list of strings:
Can you write Python code for it?

sentences = ['Copy the variable assignment for our new empty list'
             'Copy the expression that we’ve been append-ing into this new list'
             'Copy the for loop line, excluding the final'
             'Copy the if statement line, also without the']

count = 0
for sentence in sentences:
    count += sentence.count('the')

print(count)

help(reduce)

# # This is the same code written as a reduce:

# ### NOT WORKING
# from functools import reduce

# def countme(x):
#     print(x)
#     print("*" * 20)
#     return x.count('the')

# sentences = ['Copy the variable assignment for our new empty list'
#              'Copy the expression that we’ve been append-ing into this new list'
#              'Copy the for loop line, excluding the final'
#              'Copy the if statement line, also without the']

# sam_count = reduce(countme,
#                    sentences)
# print(sam_count)

import random

colours = ["pink", "purple", "black", "yellow", "purple", "indego", "white", "peach"]

def foo(counter, i):
  colour = random.choice(colours)
  try:
    counter[colour] += 1
  except KeyError:
    counter[colour] = 1
  return counter

counts = reduce(foo, range(1, 50), {})
print(counts)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/03_map_reduce_and_filter.ipynb".
The first task is:
NOTE:
How does this code come up with its initial a? The starting point for the number of incidences of 'Sam' cannot be 'Mary read a story to Sam and Isla.' The initial accumulator is specified with the third argument to reduce(). This allows the use of a value of a different type from the items in the collection.
Benefits map and reduce

they are often one-liners.
the important parts of the iteration - the collection, the operation and the return value - are always in the same places in every map and reduce.
the code in a loop may affect variables defined before it or code that runs after it. By convention, maps and reduces are functional.
map and reduce are elemental operations. Every time a person reads a for loop, they have to work through the logic line by line. There are few structural regularities they can use to create a scaffolding on which to hang their understanding of the code. In contrast, map and reduce are at once building blocks that can be combined into complex algorithms, and elements that the code reader can instantly understand and abstract in their mind. “Ah, this code is transforming each item in this collection. It’s throwing some of the transformations away. It’s combining the remainder into a single output.”
map and reduce have many friends that provide useful, tweaked versions of their basic behaviour. For example: filter, all, any and find.

Filtering
The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function function returns True.
The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True will the element of the list be included in the result list.
Can you write Python code for it?

fib = [0,1,1,2,3,5,8,13,21,34,55]

result = filter(lambda x: x % 2 != 0, fib)
print(result)

result = filter(lambda x: x % 2 == 0, fib)
print(list(result))

apis = [{'name': 'UpdateUser', 'type': 'POST', "body": "{'name': '$name'}"},
    {'name': 'addUser', 'type': 'POST', "body": "{name : '$name'}"},
    {'name': 'listUsers', 'type': 'GET'}]

posts = 0
for api in apis:
    if 'type' in api and api['type'] == 'POST':
        posts += 1

print(posts)

posts = 0
c = []

c = filter(lambda x:'type' in x and x['type'] == 'POST', apis)
print(c)
print(len(list(c)))

people = [{'name': 'Mary', 'height': 160},
          {'name': 'Isla', 'height': 80},
          {'name': 'Sam'}]

heights = map(lambda x: x['height'],
              filter(lambda x: 'height' in x, people))
print(heights)

if len(heights) > 0:
    from operator import add
    average_height = reduce(add, heights) / len(heights)
    print(average_height)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/03_map_reduce_and_filter.ipynb".
The first task is:
Reduce
Reduce takes a function and a collection of items. It returns a value that is created by combining the items. This is a simple reduce. It returns the sum of all the items in the collection.
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/03_map_reduce_and_filter.ipynb".
The first task is:
This can be rewritten as a lamba:
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/04_functools.ipynb".
The first task is:
Here we import wraps from the functools module and use it as a decorator for the nested wrapper function inside of another_function to map the name and doc to the wrapper function
update_wrapper
The partial object does not have name or doc attributes by default, and without those attributes decorated functions are more difficult to debug. Using update_wrapper(), copies or adds attributes from the original function to the partial object.
Can you write Python code for it?

import functools

def myfunc1(a, b=2):
    print ('\tcalled myfunc1 with:', (a, b))
    return

def myfunc(a, b=2):
    """Docstring for myfunc()."""
    print ('\tcalled myfunc with:', (a, b))
    return

def show_details(name, f):
    """Show details of a callable object."""
    print ('%s:' % name)
    print ('\tobject:', f)
    print ('\t__name__:',)
    try:
        print (f.__name__)
    except AttributeError:
        print ('(no __name__)')
    print ('\t__doc__', repr(f.__doc__))
    print
    return

show_details('myfunc1', myfunc1)
print("~"*20)
show_details('myfunc', myfunc)

p1 = functools.partial(myfunc, b=4)
print("+"*20)
show_details('raw wrapper', p1)
print("^"*20)
print ('Updating wrapper:')
print ('\tassign:', functools.WRAPPER_ASSIGNMENTS)
print ('\tupdate:', functools.WRAPPER_UPDATES)
print("*"*20)

functools.update_wrapper(p1, myfunc)
show_details('updated wrapper', p1)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/04_functools.ipynb".
The first task is:
Now lets see the magic of partial
Can you write Python code for it?

from functools import partial

square = partial(power, exponent=2)
cube = partial(power, exponent=3)

print(square(2))
print(cube(2))

print(square(2, exponent=4))
print(cube(2, exponent=9))

from functools import partial

def multiply(x,y):
        return x * y

# create a new function that multiplies by 2
db2 = partial(multiply,2)
print(db2(4))
db4 = partial(multiply, 4)
print(db4(3))

from functools import partial

#----------------------------------------------------------------------
def add(x, y):
    """"""
    return x + y

#----------------------------------------------------------------------
def multiply(x, y):
    """"""
    return x * y

#----------------------------------------------------------------------
def run(func):
    """"""
    print (func())

#----------------------------------------------------------------------
def main():
    """"""
    a1 = partial(add, 1, 2)
    m1 = partial(multiply, 5, 8)
    run(a1)
    run(m1)

if __name__ == "__main__":
    main()

def another_function(func):
    """
    A function that accepts another function
    """

    def wrapper():
        """
        A wrapping function
        """
        val = "The result of %s is %s" % (func(),
                                          eval(func())
                                          )
        return val
    return wrapper

#----------------------------------------------------------------------
@another_function
def a_function():
    """A pretty useless function"""
    return "1+1"

#----------------------------------------------------------------------
if __name__ == "__main__":
    print (a_function.__name__)
    print (a_function.__doc__)
    print(a_function())

from functools import wraps

#----------------------------------------------------------------------
def another_function(func):
    """
    A function that accepts another function
    """

    @wraps(func)
    def wrapper():
        """
        A wrapping function
        """
        val = "The result of %s is %s" % (func(),
          ...


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/Excersise - Functional Programming.ipynb".
The first task is:
Ans:
Can you write Python code for it?

secret_names = map(hash, names)
print(secret_names)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/0 - Introduction to Programming Paradigm.ipynb".
The first task is:
Imperative
Can you write Python code for it?

sum = 0

for x in L:
    sum += x

print(sum)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/0 - Introduction to Programming Paradigm.ipynb".
The first task is:
Procedural
Object-oriented
Design Patterns
Flyweight pattern
In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the objects temporarily when they are used.
A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally.
REFERENCE: https://en.wikipedia.org/wiki/Flyweight_pattern
Can you write Python code for it?

# Instances of CheeseBrand will be the Flyweights
class CheeseBrand(object):
    def __init__(self, brand, cost):
        self.brand = brand
        self.cost = cost
        self._immutable = True   # Disables future attributions

    def __setattr__(self, name, value):
        if getattr(self, '_immutable', False):  # Allow initial attribution
            raise RuntimeError('This object is immutable')
        else:
            super(CheeseBrand, self).__setattr__(name, value)

class CheeseShop(object):
    menu = {}  # Shared container to access the Flyweights

    def __init__(self):
        self.orders = {}  # per-instance container with private attributes

    def stock_cheese(self, brand, cost):
        cheese = CheeseBrand(brand, cost)
        self.menu[brand] = cheese   # Shared Flyweight

    def sell_cheese(self, brand, units):
        self.orders.setdefault(brand, 0)
        self.orders[brand] += units   # Instance attribute

    def total_units_sold(self):
        return sum(self.orders.values())

    def total_income(self):
        income = 0
        for brand, units in self.orders.items():
            income += self.menu[brand].cost * units
        return income

shop1 = CheeseShop()
shop2 = CheeseShop()

shop1.stock_cheese('white', 1.25)
shop1.stock_cheese('blue', 3.75)
# Now every CheeseShop have 'white' and 'blue' on the inventory
# The SAME 'white' and 'blue' CheeseBrand

shop1.sell_cheese('blue', 3)    # Both can sell
shop2.sell_cheese('blue', 8)    # But the units sold are stored per-instance

assert shop1.total_units_sold() == 3
assert shop1.total_income() == 3.75 * 3

assert shop2.total_units_sold() == 8
assert shop2.total_income() == 3.75 * 8


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/0 - Introduction to Programming Paradigm.ipynb".
The first task is:
the above example is below implemented using lambda
Can you write Python code for it?

import functools

Sum = functools.reduce(lambda x, y: x + y, L)
print(Sum)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
!!!! Tip !!!!

Copy the variable assignment for our new empty list (line 3)
Copy the expression that we’ve been append-ing into this new list (line 6)
Copy the for loop line, excluding the final : (line 4)
Copy the if statement line, also without the : (line 5)
Can you write Python code for it?

# FROM
numbers = range(2,10)

doubled_odds = []
for n in numbers:
    if n % 2 == 1:
        doubled_odds.append(n * 2)
print(doubled_odds)

# TO
numbers = range(2,10)

doubled_odds = [n * 2 for n in numbers if n % 2 == 1]


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
??? why code
Can you write Python code for it?

def test():
    print("TESTTESTTEST")
    def yes(name):
        print("Ja, ", name)
        return True
    return yes

d = test()
print("XSSSS")
print(d("Venky"))

def power(exp):
    def subfunc(a):
        return a**exp
    return subfunc

square = power(2)
hexa = power(6)

print(square)
print(hexa)

print(square(5)) # 5**2
print()
print(hexa(3)) # 3**6
print(power(6)(3))
# subfunc(3) where exp = 6
# SQuare

# exp -> 2
# Square(5)
# a -> 5
# 5**2
# 25

 Power(6)(3, x)

def a1(m):
    x = m * 2
    def b(v, t=None):
        if t:
            print(x, m, t)
            return v + t
        else:
            print(x, m, v)
            return v + x
    return b
n = a1(2)
print(n(3))
print(n(3, 10))

def f1(a):
    def f2(b):
        return f2
        def f3(c):
            return f3
            def f4(d):
                return f4
                def f5(e):
                    return f5
print (f1(1)(2)(3)(4)(5))

def f1(a):
    def f2(b):
        def f3(c):
            def f4(d):
                def f5(e):
                    print(e)
                return f5
            return f4
        return f3
    return f2

f1(1)(2)(3)(4)(5)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
Adding attributes to a function
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
Can be rewritten into a list comprehension like this:
Can you write Python code for it?

new_things = [ITEM for ITEM in old_things if condition_based_on(ITEM)]
print(new_things)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
Conditional Compreshensions
Can you write Python code for it?


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
Dictionary Comprehensions
Can you write Python code for it?

original = {'a':10, 'b': 34, 'A': 7, 'Z':3, "z": 199}

mcase_frequency = { k.lower() : original.get(k.lower(), 0) + original.get(k.upper(), 0) for k in original.keys() }
print(mcase_frequency)

original = {'a':10, 'b': 34, 'A': 7, 'Z':3, "z": 199, 'c': 10}
flipped = {value: key for key, value in original.items()}
print(flipped)

original = {'a': 10, 'b': 34, 'A': 7, 'Z':3, "z": 199, 'c': 10}
newdict = {}
for key, value in original.items():
    if (value not in newdict):
        newdict[value] = key
print(newdict)

newdict = {value: key for key, value in original.items() if (value not in newdict)}
print(newdict)

x = {"a": 10, "b": 20, "c": 20}

print(x)
x["a"] = 100

print(x)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
Following DRY (Don't Repeat Yourself)
This type can be used if you have a section of code base in function is repeated in numerous places. For example, you might write a function which processes a file, and you want to accept either an open file object or a file name:
Can you write Python code for it?

# Keepin’ it DRY

def process(file_name):
    def do_stuff(file_process):
        for line in file_process:
            print(line)

    if isinstance(file_name, str):
        with open(file_name, 'r') as f:
            do_stuff(f)
    else:
        do_stuff(file_name)

process(["test", "test3", "t33"])do_stuff(file_name)

process("test.txt")


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
Generator Comprehension
They are simply a generator expression with a parenthesis "()" around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a generator instead of a list.
Can you write Python code for it?

x = (x**2 for x in range(20))
print(x)
print(list(x))

itm = 10
print(itm / 2)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
Here we import wraps from the functools module and use it as a decorator for the nested wrapper function inside of another_function to map the name and doc to the wrapper function
update_wrapper
The partial object does not have name or doc attributes by default, and without those attributes decorated functions are more difficult to debug. Using update_wrapper(), copies or adds attributes from the original function to the partial object.
Can you write Python code for it?

import functools

def myfunc1(a, b=2):
    print ('\tcalled myfunc1 with:', (a, b))
    return

def myfunc(a, b=2):
    """Docstring for myfunc()."""
    print ('\tcalled myfunc with:', (a, b))
    return

def show_details(name, f):
    """Show details of a callable object."""
    print ('%s:' % name)
    print ('\tobject:', f)
    print ('\t__name__:',)
    try:
        print (f.__name__)
    except AttributeError:
        print ('(no __name__)')
    print ('\t__doc__', repr(f.__doc__))
    print
    return
show_details('myfunc1', myfunc1)
print("~"*20)
show_details('myfunc', myfunc)

p1 = functools.partial(myfunc, b=4)
print("+"*20)
show_details('raw wrapper', p1)
print("^"*20)
print ('Updating wrapper:')
print ('\tassign:', functools.WRAPPER_ASSIGNMENTS)
print ('\tupdate:', functools.WRAPPER_UPDATES)
print("*"*20)

functools.update_wrapper(p1, myfunc)
show_details('updated wrapper', p1)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
In the above example, the output of the function global_sum changed due to the value of a, thus it is unfunctional function.
Can you write Python code for it?

# a better functional function
def better_sum(a, x):
    return a+x

num = better_sum(1, 1)
print(num)
num = better_sum(1, 3)
print(num)
num = better_sum(1, 1)
print(num)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
Inner / Nested Functions - When to use
Encapsulation
You use inner functions to protect them from anything happening outside of the function, meaning that they are hidden from the global scope.
Can you write Python code for it?

# Encapsulation

def increment(current):
    def inner_increment(x):  # hidden from outer code
        return x + 1
    next_number = inner_increment(current)
    return [current, next_number]

print(increment(10))


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
NOTE:
How does this code come up with its initial a? The starting point for the number of incidences of 'Sam' cannot be 'Mary read a story to Sam and Isla.' The initial accumulator is specified with the third argument to reduce(). This allows the use of a value of a different type from the items in the collection.
Benefits map and reduce

they are often one-liners.
the important parts of the iteration - the collection, the operation and the return value - are always in the same places in every map and reduce.
the code in a loop may affect variables defined before it or code that runs after it. By convention, maps and reduces are functional.
map and reduce are elemental operations. Every time a person reads a for loop, they have to work through the logic line by line. There are few structural regularities they can use to create a scaffolding on which to hang their understanding of the code. In contrast, map and reduce are at once building blocks that can be combined into complex algorithms, and elements that the code reader can instantly understand and abstract in their mind. “Ah, this code is transforming each item in this collection. It’s throwing some of the transformations away. It’s combining the remainder into a single output.”
map and reduce have many friends that provide useful, tweaked versions of their basic behaviour. For example: filter, all, any and find.

Filtering
The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function function returns True.
The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True will the element of the list be included in the result list.
Can you write Python code for it?

fib = [0,1,1,2,3,5,8,13,21,34,55]

result = filter(lambda x: x % 2 != 0, fib)
print(list(result))

def get_odd(val):
    return val % 2 != 0

result = list(filter(get_odd, fib))
print(result)

result = filter(lambda x: x % 2 == 0, fib)
print(list(result))

def get_even(val):
    return val % 2 == 0

result = list(filter(get_even, fib))
print(result)

apis = [{'name': 'UpdateUser', 'type': 'POST', "body": "{'name': '$name'}"},
        {'name': 'addUser', 'type': 'POST', "body": "{name : '$name'}"},
        {'name': 'listUsers', 'type': 'GET'},
        {'name': 'listUsers', 'type': ''},
        {'name': 'listUsers_withNone', 'type': None},
        {'name': 'testWithoutType'}]

posts = 0
for api in apis:
    if 'type' in api and api['type'] == 'POST':
        posts += 1

print(posts)

posts = 0
c = []

c = list(filter(lambda x:'type' in x and x['type'] is not 'POST', apis))
print(c)
print(len(list(c)))

posts = 0
c = []

c = list(filter(lambda x:'type' in x and x['type'] is 'POST', apis))
print(c)
print(len(list(c)))

people = [{'name': 'Mary', 'height': 160},
          {'name': 'Isla', 'height': 80},
          {'name': 'Sam'}]

heights = map(lambda x: x['height'],
              filter(lambda x: 'height' in x, people))
print(heights)

if len(heights) > 0:
    from operator import add
    average_height = reduce(add, heights) / len(heights)
    print(average_height)


I am working on the file "Section 2 - Advance Python/Chapter S2.01 - Functional Programming/n/1 - About Functional Programming .ipynb".
The first task is:
NOTE: We can not access directly the inner function
Can you write Python code for it?

increment.inner_increment(109)

### NOT WORKING

def update(str_val):
    def updating(ori_str, key, value):
        token = "$"
        if key in ori_str:
            ori_str = ori_str.replace(token+key, value)
        return ori_str

    keyval = [{"test1": "val_test", "t1" : "val_1"}, {"test2": "val_test2", "t2" : "val_2"}]

    keyval1 = [{"test1": "val_test", "t1" : "val_1"}, {"test2": "val_test2", "t2" : "val_2"}]
    ori_str = "This is a $test1 and $test2, $t1 and $t2"

#     for k in keyval:
#         for key, value in k.items():
#             ori_str = updateing(ori_str, key, value)

    sdd = [ key, value [for key, value in k] for(k in keyval) ]

    print(ori_str)

update("D")

ld = [{'a': 10, 'b': 20}, {'p': 10, 'u': 100}]
[kv for d in ld for kv in d.items()]

ori_str = "This is a $test;1 and $test2, $t1 and $t2"
print(ori_str.replace("test1", "TEST1"))
print(ori_str)