Showing posts with label 72108. Show all posts
Showing posts with label 72108. Show all posts

Python FSP - Mini-Project - Sprint2 - Python Programming || Fresco Play || 72108

Mini-Project - Python FSP - Sprint2 - Python Programming

1. Exception Handling

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.

Check and handle the following exceptions:

  1. If the input values are not integer it will raise a ValueError print the message "Enter a valid numbers"

  2. If zero division error occurs raise ZeroDivisionError and print the message "Second value should not be zero"

  3. If an index error occurs raise IndexError and print the message "Number of Inputs should be more than one"

  4. If the 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

  5. If there is no exceptions occurred print the division value

Note: The program should run until it gets the division value without any exceptions

After that read the file "file.txt" if not able to read raise the OSError and print the message "File not found"

At the end of the handling print the message "Code has been executed"

Sample Case 0

Sample Input

2 g 7 8
2 0 5 3
5
5 3 2 7 34

Sample Output

Enter a valid numbers
Second value should not be zero
Number of Inputs should be more than one
1.6666666666666667
File not found
Code has been executed

Explanation

Input 1: Here due to "g", it will occur ValueError, so print the message "Enter a valid numbers" and get the input again

Input 2: Here due to second value "0", it will occur ZeroDeivisionError, so print the message "Second value should not be zero" and get the input again

Input 3: Here due to a single input, it will occur IndexError, so print the message "Number of Inputs should be more than one" and get the input again

Input 4: Here no exception is occurred, so its prints the division value then check for the file.txt file not found so its prints "File not found" and at the end it prints "Code has been executed"

Solution

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

def handelExe():
    #Write your code here
    while True:
        try:
            A = list(map(int, input().split()))
            if len(A) < 2:
                raise IndexError
            if sum(A) > 100:
                raise Exception(f"Sum of the list should be less than 100\n{sum(A)}")
            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 as e:
            print(e)

    try:
        with open("file.txt", "r") as f:
            print(f.read())
    except OSError:
        print("File not found")
    print("Code has been executed")

if __name__ == '__main__':
    handelExe()

2. Decorators

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

  1. The decorator should print each function name as "function_name Decorator"
  2. Print "Joining Strings..." and joined string output
  3. Print "Calculating Total..." and the calculated total
  4. Print "Calculating Average..." and the Calculated average

The function should take two inputs

  1. Input one should be a list of string values
  2. Input two should be a list of integer values

Sample Case 1

Sample Input

Decorators are a useful tool in python
12 7 5 45 28

Sample Output

joinString Decorator
findTotal Decorator
average Decorator
Joining Strings...
Decoratorsareausefultoolinpython
Calculating Average...
19.4
Calculating Total...
97

Solution

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

# Create Decorator here
def function_name(func):
    print(f"{func.__name__} Decorator")
    def wrapper(*args):
        return func(*args)
    return wrapper

@function_name
def joinString(*args):
    print("Joining Strings...")
    return "".join(args)

@function_name
def findTotal(*args):
    print("Calculating Total...")
    return sum(args)


@function_name
def average(*args):
    print("Calculating Average...")
    return sum(args)/len(args)

if __name__ == '__main__':
    strInput=list(map(str,input().split()))
    numInput=list(map(int,input().split()))

    print(joinString(*strInput))
    print(average(*numInput))
    print(findTotal(*numInput))

3. Generators

Create a function which can accept integer as an input, then create generators to perform and print the sum of the square of the Fibonacci series for the given input.

Sample Case 1

Sample Input

8

Sample Output

714

Explanation

Fibonacci series : 1 1 2 3 5 8 13 21

Square of the series : 1 1 4 9 25 64 169 441

Sum of the series : 714

Solution

# Enter your code here. Read input from STDIN. Print output to STDOUT
def square_fibonacci(n):
    a = 0
    b = 1
    c = 0
    t = 0
    while t < n:
        c = a + b
        a = b
        b = c
        yield a*a
        t += 1

def generator_sum():
    #Write your code here
    n = int(input())
    print(sum(square_fibonacci(n)))

if __name__ == '__main__':
    generator_sum()

4. Python advanced modules

Code for the following :

  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, then pass the dictionary as a arguments to the function printDic to print the values of the dictionary.

  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.

Note:

  1. Dictionary old_dic is given in the environment
  2. Print the output in the format X is the value of the key Y

Sample Case 1

Sample Input

keyboard mic speaker
3 6 8
10

Sample Output

3 is the value of the key keyboard
6 is the value of the key mic
8 is the value of the key speaker
6 is the value of the key ram
4 is the value of the key mouse
3 is the value of the key monitor
30

Explanation

Here the output keys and values of the dictionary as mentioned in the problem statement

10 is the sum of the even numbers between 0 to 62988032 (2 + 4 + 6+ 8 + 10)

Solution

import collections

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

def actionDic():
    keys = input().split()
    values = list(map(int, input().split()))
    n = int(input())
    d = dict(zip(keys,values))
    printDic(**collections.ChainMap(old_dic,d))
    print(getEven(n))

def printDic(**args):
    for key,value in args.items():
        print(f"{value} is the value of the key {key}")

def getEven(n):
    sum = 0
    for i in range(n+1):
        if i%2 == 0:
            sum += i
    return sum


if __name__ == '__main__':
    old_dic = {'ram':6,'mouse':4,'monitor':3}
    actionDic()
Share: