Mini Project Python FSP Sprint2 Python Programming Solution Fresco Play

Python Advance Hands-on, Learn: Exception Handling, Decorators, Generators, Advanced Modules. Advance list comprehension, Dictionary ChainMap function
Mini Project Python FSP Sprint2 Python Programming Solution Fresco Play - www.pdfcup.com

If you will find any issue; Comment below.

Mini-Project - Python FSP - Sprint2- Python Programming:-

Welcome to Python - Exception Handling, Decorators, Generators, Advanced Modules.

Question 1: Exception Handling.

Solution 1: Exception Handling.


# Enter your code here. Read input from STDIN. Print output to STDOUT

# Task 1: 
# Create a function which can accept a list of integer as input and store in variable 'A'.
# then, divide the first value by a second value of the list and calculate the sum of the list.


def handelExe():    
  while True:     
    # Check and handle the following exceptions:-
        
      try:
          error= False           
          A= input().strip().split()
          
          # Task 2. If the input values are not integer it will raise a 'ValueError'.
          # and print the message "Enter a valid numbers".
          
          if False in list(map(lambda x:  x.isdigit(), A) ):                
              raise ValueError
               
          A = list(map( lambda x : int(x), A))
          
          # Task 3. If zero division error occure raise 'ZeroDivisionError'.
          # and print the message "Second value should not be zero".
          
          if A[1]==0:                
              raise ZeroDivisionError
                 
              
          # Task 4. If an index error occure raise 'IndexError'.
          # and print the message "Number of Inputs should be more than one". 
             
          elif len(A)<2:                
              raise IndexError
          
          # Task 5. If sum of the list is greater than 100 raise 'Exception'.
          # and print the message "Sum of the list should be less than 100", and the sum of the list.  
            
          elif  sum(A)>100:                                            
              raise Exception
          
          # Task 6. If there is no exception occured print the division value.
          else:
              print(A[0]/A[1])                
              break            

      except ValueError:
          print("Enter a valid numbers")
              
      except ZeroDivisionError:
          print("Second value should not be zero") 
          
      except IndexError:
          print("Number of Inputs should be more than one") 
          
      except Exception:            
          print("Sum of the list should be less than 100")
          print(sum(A))
          
  # Task 7: After that, read the file "file.txt" if not able to read raise the OSError and 
  #         print the message "File not found".
  try:
      if not open('file.txt', 'r'):
          error= True
          raise OSError  
  
  except OSError:
      print("File not found")  
  
  # Task 8: At the end of the handling print the message "Code has been executed". 
  finally:
      print("Code has been executed")
      
      # Refer '__main__' method code which is given below if required.
  

if __name__ == '__main__':
# Starting from here:  
# Note: Do Not modify the below code
if __name__ == '__main__':
  handelExe()  
  

Question 2: Decorators.

Solution 2: Decorators.


# Enter your code here. Read input from STDIN. Print output to STDOUT

# Task 1:

# Create decorators to perform string join, find the aver age and find the total.
# The decorator should print the output in the following pattern:

# The decorator should print each function names as "function_name Decorator".

# Create Decorator here
def dic(func, *args):
    fn= func.__name__
    print( str(fn) + " Decorator" )
    
    def inn(self, *args):
      func(*args)
    return func  
    
# Print "Joining Strings..." and joined string output.  
@dic
def joinString(*args):
    strh =args
    print("Joining Strings...")
    return  "".join(strh)

# Print "Calculating Total..." and the calculated total.
@dic   
def findTotal(*args):
    A = args
    print("Calculating Total...")
    return sum(A)
    
# Print "Calculating Average..." and the calculated average.
@dic
def average(*args):
    A = args
    Len = len(A)  
    print("Calculating Average...")
    return sum(A)/Len
    
    # Refer '__main__' method code which is given below if required.


if __name__ == '__main__':
# Starting from here:  
# Note: Do Not modify the below code
if __name__ == '__main__':
    
    strInput=list(map(str,input().split()))
    numInput=list(map(int,input().split()))
    print(joinString(*strInput))
    print(average(*numInput))
    print(findTotal(*numInput))
  

Question 3: Generators.

Solution 3: Generators.


# Enter your code here. Read input from STDIN. Print output to STDOUT

# Task: 
# Create a function which can accept integer as an input.
def inpt():
  numb = int(input())
  return numb
  
# Then create generators to perform and print the sum of the square
#  of the Fibonacci Series for the given input.
def generator_sum():
  n = inpt()
  
  def generator_inner():    
    a, b = 0, 1
    for i in range(n+1):   
      yield a
      a, b = b, a + b
  fibonacci_list = list(generator_inner())[1:]
  # print(fibonacci_list)
  
  def fib_square(fib_lst):    
    generator_obj = ( i**2 for i in fib_lst) 
    return  generator_obj 
        
  fibonacci_square_list=  list(fib_square(fibonacci_list))
  # print(fibonacci_square_list)

  print( sum(fibonacci_square_list))
  
  # Refer '__main__' method code which is given below if required.

if __name__ == '__main__':
# Starting from here:
# Note: Do Not modify the below code
if __name__ == '__main__':
    generator_sum()  
  

Question 4: Advanced Modules.

Solution 4: Advanced Modules.


import collections

# Enter your code here. Read input from STDIN. Print output to STDOUT

# Task 1:
# Create a function 'actionDic' that should take n number of keys and values to create
# dictionary and merge it with the dictionary stored in the old_dic using 'ChainMap'.

def actionDic():
  key = input().rstrip().split()
  value = input().rstrip().split()
  n= int(input())
   
  new_dic = dict(zip(key, value))   
  merged = dict(collections.ChainMap(old_dic, new_dic) )
  
  # Then pass the dictionary as a arguments to the function 'printDic' to print the values of the dictionary.
  printDic(**merged)
    
  res = getEven(n)
  print(res)
    


def printDic(**args):
  for k, v in args.items():
    print(f'{v} is the value of the key {k}')
    
    
# Task 2: 
# Create a function 'getEven', which can take an integer as input and return the sum of the even numbers between 0 to integer value.
# Then print getEven function from 'actionDic'.    
def getEven(n):
  even_lst = []
  for i in range(1,n+1):
    if i%2==0:
      even_lst.append(i)
     
  return sum(even_lst)    
  
  # Refer '__main__' method code which is given below if required.
    
if __name__ == '__main__':
# Starting from here:  
# Note: Do Not modify the below code
if __name__ == '__main__':
    old_dic = {'ram':6,'mouse':4,'monitor':3}
    actionDic() 
  

Digital : Advance Python Programming Use Case_E2_FP

About the author

D Shwari
I'm a professor at National University's Department of Computer Science. My main streams are data science and data analysis. Project management for many computer science-related sectors. Next working project on Al with deep Learning.....

Post a Comment