Python FSP - Mini-Project - Sprint3 - Python Testing Frameworks || Fresco Play || 72109

Pytest - Testing Framework

In this challenge you are supposed to write test cases based on given scenario

Instructions

  • Read the instructions and code for the questions given
  • file.pickle contains a list of words.
  • Use assert function to check or assert
  • Write the fixture function unpick which reads the pickle file "file.pickle" and return the list of words
  • Mark the function as fixture
  • Open the file "file.pickle" with "rb" and load the data using pickle.load function
  • Write the test method test1 to check whether the count of words is equal to 6720
  • Write the pytest test method test_len_endswith to check whether the count of words ending with 'ing' is greater than 350
  • Write the pytest test method test_len_lessthan to check whether the count of words having characters less than 3 is equalto 80
  • Write the test method test_keyword to check whether the count of keywords present in the list are not equal to zero
  • Write the test method test_word to check whether the word "jupyter" is present in the list
  • Write the test method test_len_startswith to check whether the count of words that starts with character 'c' is equal to 700
  • Write the test method test_words_ag to check the count of words that starts with 'a' and endwith 'g' is a two digit number and the second digit is zero
  • Write the test method char_words to check the whether count of words having alphabets only is greater than 6400
  • Write the parameterized test method test_words_starts_with to run against a set of multiple inputs
  • Mark the function as parameterize
  • Write the function to check the count of words starting with the input character is equal to the output
  • [('a',570),('e',327),('h',1296),('t',321)] is the set of inputs and outputs

IDE Instructions

Step 1:Coding

  • Once the IDE is opened, Click File->New->Terminal and run the below command
    pip3 install -r requirements.txt
    
  • Open test.py file and code for the questions given.

Step 2: Testing

  • After Completing the solution, Save the test.py file .
  • After saving the test.py file , Click File->New->Terminal and run the below command to generate test1.xml file
    pytest test.py --junitxml=test1.xml
    
  • Now Click File->New->Terminal and run the below command to run test cases with keyword "len" and generate the test2.xml file
    pytest test.py -k len --junitxml=test2.xml
    
  • Now test your solution by Click File->New->Terminal and run the below command to run sample test cases
    pytest sample_test.py
    

Step 3 : Submit the Solution

  • Once all the sample test cases are passed, click 'Submit' to submit your solution to HackerRank.

Solution

import pytest
import pickle
import keyword

'''
Write the fixture function unpick which reads the pickle file "file.pickle" and return the list of words
Mark the function as fixture
Open the file "file.pickle" with "rb" and load the data using pickle.load function
'''
@pytest.fixture
def unpick():
    with open("file.pickle", "rb") as f:
        data = pickle.load(f)
    return data

'''
Write the test method test1 to check whether the count of words is equal to 6720
'''
def test1(unpick):
    words = unpick  # This will call the fixture and get the list of words
    assert len(words) == 6720, f"Expected 6720 words, but got {len(words)}"

'''
Write the test method test_len_endswith to check whether the count of words ending with 'ing' is greater than 350
'''
def test_len_endswith(unpick):
    words = unpick  # This will call the fixture and get the list of words
    count_ending_with_ing = sum(1 for word in words if word.endswith('ing'))
    assert count_ending_with_ing > 350, f"Expected more than 350 words ending with 'ing', but got {count_ending_with_ing}"

'''
Write the test method test_len_lessthan to check whether the count of words having characters less than 3 is equalto 80
'''
def test_len_lessthan(unpick):
    words = unpick  # This will call the fixture and get the list of words
    count_less_than_3 = sum(1 for word in words if len(word) < 3)
    assert count_less_than_3 == 80, f"Expected 80 words with less than 3 characters, but got {count_less_than_3}"

'''
Write the test method test_keyword to check whether the count of keywords present in the list are not equal to zero 
Hint Use iskeyword function of library keyword.
'''
def test_keyword(unpick):
    words = unpick  # This will call the fixture and get the list of words
    keywords_in_list = [word for word in words if keyword.iskeyword(word)]
    assert len(keywords_in_list) > 0, "Expected at least one keyword in the list, but found none."

'''
Write the test method test_word to check whether the word "jupyter" is present in the list
'''
def test_word(unpick):
    words = unpick  # This will call the fixture and get the list of words
    assert "jupyter" in words, "Expected the word 'jupyter' to be present in the list, but it was not found."

'''
Write the test method test_len_startswith to check whether the count of words that starts with character 'c' is equal to 700
'''
def test_len_startswith(unpick):
    words = unpick  # This will call the fixture and get the list of words
    count_starts_with_c = sum(1 for word in words if word.startswith('c'))
    assert count_starts_with_c == 700, f"Expected 700 words starting with 'c', but got {count_starts_with_c}"

'''
Write the test method test_words_ag to check the count of words that starts with 'a' and endwith 'g' is a two digit number and the second digit is zero
'''
def test_words_ag(unpick):
    words = unpick  # This will call the fixture and get the list of words
    count_starts_with_a_ends_with_g = sum(1 for word in words if word.startswith('a') and word.endswith('g'))

    # Check if the count is a two-digit number and the second digit is zero
    assert 10 <= count_starts_with_a_ends_with_g < 100 and count_starts_with_a_ends_with_g % 10 == 0, \
        f"Expected a two-digit number ending with zero, but got {count_starts_with_a_ends_with_g}"

'''
Write the test method char_words to check the whether count of words having alphabets only is greater than 6400
'''  
def test_char_words(unpick):
    words = unpick  # This will call the fixture and get the list of words
    count_alpha_only = sum(1 for word in words if word.isalpha())

    assert count_alpha_only > 6400, f"Expected more than 6400 words with alphabets only, but got {count_alpha_only}"

'''
Write the parameterized test method test_words_starts_with to run against a set of multiple inputs
Mark the function as parameterize
Write the function to check the count of words starting with the input character is equal to the output
[('a',570),('e',327),('h',1296),('t',321)] is the set of inputs and outputs
'''
@pytest.mark.parametrize("char, expected_count", [
    ('a', 570),
    ('e', 327),
    ('h', 1296),
    ('t', 321)
])
def test_words_starts_with(unpick, char, expected_count):
    words = unpick  # This will call the fixture and get the list of words
    count_starts_with_char = sum(1 for word in words if word.startswith(char))

    assert count_starts_with_char == expected_count, f"Expected {expected_count} words starting with '{char}', but got {count_starts_with_char}"
Share:

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:

Python FSP - Mini-Project - Sprint1 - Data Structures || Fresco Play || 72107

1. Basics of Python

Function Numbers

Write the function numbers that accepts four numbers as parameters and performs operation specified below

  1. Find the sum of all the numbers and store it in variable sum_of_numbers
  2. Find the sum of float numbers among the numbers and store it in variable sum_of_float_numbers
  3. Find the smallest integer number among the numbers and store it in variable min_number
  4. Find the count of prime numbers among the numbers and store it in variable prime_count
  5. Check for zeros. If there are zeros present among the numbers, store True else store False in the variable zero_check

Sample Case 0

Sample Input

2
3.5
0
1

Sample Output

6.5
3.5
0
1
True

Explanation

Sum of all the numbers are 6.5

Sum of float numbers are 3.5

Smallest integer number is 0

Count of prime numbers are 1. 2 is the only prime number among them.

Zero is present among the numbers. So the output is True.

Solution

import ast

# Enter your code here. Read input from STDIN. Print output to STDOUT
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

def numbers(*args):
    '''
    Find the sum of all the numbers and store it in variable sum_of_numbers
    '''
    sum_of_numbers = sum(args)

    '''
    Find the sum of float numbers among the numbers and store it in variable sum_of_float_numbers
    '''
    sum_of_float_numbers = sum(i for i in args if isinstance(i, float))

    '''
    Find the smallest integer number among the numbers and store it in variable min_number
    '''
    min_number = min(i for i in args if isinstance(i, int))

    '''
    Find the count of prime numbers among the numbers and store it in variable prime_count
    '''
    prime_count = sum(1 for i in args if not isinstance(i, float) and is_prime(i))

    '''
    Check for zeros. If there are zeros present among the numbers, store True else store False in the variable zero_check
    '''
    zero_check = bool(sum(1 for i in args if i == 0 ))

    print(sum_of_numbers)
    print(sum_of_float_numbers)
    print(min_number)
    print(prime_count)
    print(zero_check)


if __name__=='__main__':
    num1 = ast.literal_eval(input())
    num2 = ast.literal_eval(input())
    num3 = ast.literal_eval(input())
    num4 = ast.literal_eval(input())
    numbers(num1,num2,num3,num4)

2. Objects and Data Structures

Function Data_oper

Write the function data_oper which accepts two strings as inputs and performs operations that are specified below

  1. Split the string string1 with whitespace as delimiter Remove the words that contain characters that are not alphabets Remove the words whose length is less than 3 Convert first letter of each word in to Upper case Store it in variable list1
  2. Split the string string2 with whitespace as delimiter Remove the words that contain characters that are not alphabets Remove the words whose length is less than 3 Convert first letter of each word in to Upper case Store it in variable list2
  3. Concatenate the lists list1,list2 and store it in variable list3
  4. Find the count of each word in the list list3 and store it in variable count_dictionary Type of count_dictionary - Dictionary Keys have to be words Dictionary must be ordered in ascending order based on Keys
  5. Find the unique words from words of list3 and store it in variable list3_uni Type of list3_uni - list list3_uni must be sorted in ascending order
  6. Find the common words in list1,list2 and store it in variable common_tuple Type of common_tuple - tuple Words have to unique and sorted in ascending order If there are no common words in list1,list2 store an empty tuple
  7. Find the words of list3 that ends with 's' and store it in variable ends_with Type of ends_with - tuple Words have to be unique and sorted in ascending order If there are no words in list3 that ends with 's', store an empty tuple

Sample Input

String1 : A glance at the outline map on page 4 may shows the location of theseancient works.
String2 : To begin with the Mounds and Earthworks themselves, it may be said that there are many thousands of them.

Sample Output

['Glance', 'The', 'Outline', 'Map', 'Page', 'May', 'Shows', 'The', 'Location', 'Theseancient', 'Begin', 'With', 'The', 'Mounds', 'And', 'Earthworks', 'May', 'Said', 'That', 'There', 'Are', 'Many', 'Thousands']
{'And': 1, 'Are': 1, 'Begin': 1, 'Earthworks': 1, 'Glance': 1, 'Location': 1, 'Many': 1, 'Map': 1, 'May': 2, 'Mounds': 1, 'Outline': 1, 'Page': 1, 'Said': 1, 'Shows': 1, 'That': 1, 'The': 3, 'There': 1, 'Theseancient': 1, 'Thousands': 1, 'With': 1}
['And', 'Are', 'Begin', 'Earthworks', 'Glance', 'Location', 'Many', 'Map', 'May', 'Mounds', 'Outline', 'Page', 'Said', 'Shows', 'That', 'The', 'There', 'Theseancient', 'Thousands', 'With']
('May', 'The')
('Earthworks', 'Mounds', 'Shows', 'Thousands')

Solution

# Enter your code here. Read input from STDIN. Print output to STDOUT
def data_oper(string1,string2):
    '''
    Split the string string1 with whitespace as delimiter
    Remove the words that contain characters that are not alphabets
    Remove the words whose length is less than 3
    Convert first letter of each word in to Upper case
    Store it in variable list1
    Type of list1 - List
    '''
    list1 = string1.split()
    list1 = list(filter(lambda x: x.isalpha() and len(x) >= 3, list1))
    list1 = list(map(lambda x: x.title(), list1))

    '''
    Split the string string2 with whitespace as delimiter
    Remove the words that contain characters that are not alphabets
    Remove the words whose length is less than 3
    Convert first letter of each word in to Upper case
    Store it in variable list2
    Type of list2 - List
    '''
    list2 = string2.split()
    list2 = list(filter(lambda x: x.isalpha() and len(x) >= 3, list2))
    list2 = list(map(lambda x: x.title(), list2))

    '''
    Concatinate the lists list1,list2 and store it in variable list3
    Type of list3 - List
    '''
    list3 = list(list1 + list2)

    '''
    Find the count of each word in the list list3 and store it in variable count_dictionary
    Type of count_dictionary - Dictionary
    Keys have to be words
    Dictionary must be ordered based on Keys
    '''
    count_dictionary = {}
    for word in set(list3):
        count_dictionary[word] = list3.count(word)
    count_dictionary = dict(sorted(count_dictionary.items()))

    '''
    Find the unique words from words of list3 and store it in variable list3_uni
    Type of list3_uni - list
    list3_uni must be sorted in ascending order
    '''
    list3_uni = list(sorted(count_dictionary.keys()))

    '''
    Find the common words in list1,list2 and store it in variable common_tuple
    Type of common_tuple - tuple
    Words have to unique and sorted in ascending order
    If there are no common words in list1,list2 store an empty tuple
    '''
    common_tuple = tuple(sorted(set(list1).intersection(set(list2))))

    '''
    Find the words of list3 that ends with 's' and store it in variable ends_with
    Type of ends_with - tuple
    Words have to be unique and sorted in ascending order
    If there are no words in list3 that ends with 's', store an empty tuple
    '''
    ends_with = tuple(sorted(set(filter(lambda x: x.endswith('s'), list3))))

    print(list3)
    print(count_dictionary)
    print(list3_uni)
    print(common_tuple)
    print(ends_with)

if __name__=='__main__':
    string1 = input()
    string2 = input()
    data_oper(string1,string2)

3. Functions and Methods

Functions and Methods

Read the Instructions and code for the questions given.

  1. Write the function list_oper that takes two list as input. Function should return a string after performing the operations specified below:
    • Check for the squares and cubes of elements in list1 are present in list2
    • Return "Squares and Cubes are present" if squares and cubes of all elements in list1 are present in list2.
    • Return "Squares are only present" if squares of all elements in list1 are only present in list2.
    • Return "Cubes are only present" if cubes of all the elements in list1 are only present in list2.
    • Return "No such pattern is present" if there are squares and cubes of any element in list1 is not present in list2
  2. Write the function armstrong which takes two numbers (num1,num2) as input. Function should return the list of armstrong numbers between num1 and num2.
  3. Write the function string_oper which takes a string as input and return another string after removing words that have characters repeated.
  4. Write a function string_reverse which takes a string as input and return another string with each word in reversed order.

Sample Case 0

Sample Input

[1,2,3,4]
[12,13,20,1,8,16,9,2,4,27,10,64]
10
200
HAMMER AND TONGS
Here is a characteristic letter

Sample Output

Squares and Cubes are present
[153]
AND TONGS
ereH si a citsiretcarahc rettel

Explanation

Squares and cubes of numbers 1,2,3,4 are present in list2. So the function list_oper should return "Squares and Cubes are present"

153 is the armstrong number present between the numbers 10 and 200. So the function armstrong should return [153]

'M' is repeated twice in the word "HAMMER" . So the function string_oper should return "AND TONGS" after removing the word "HAMMER" from the string.

Function string_reverse should return "ereH si a citsiretcarahc rettel" with each word in the string "Here is a characteristic letter" in reversed order

Solution

import ast
import sys

# Enter your code here. Read input from STDIN. Print output to STDOUT
'''
Write the function list_oper that takes two list as input.

Function should return a string after performing the operations specified below
 - Check for the squares and cubes of elements in list1 is present in list2
 - Return "Squares and Cubes are present" if squares and cubes of all elements in list1 are present in list2.
 - Return "Squares are only present" if squares of all elements in list1 are only present in list2.
 - Return "Cubes are only present" if cubes of all the elements in list1 are only present in list2.
 - Return "No such pattern is present" if there are squares and cubes of any element in list1 is not present in list2
'''
def list_oper(list1,list2):
    if all(i**2 in list2 and i**3 in list2 for i in list1):
        return "Squares and Cubes are present"
    elif all(i**2 in list2 for i in list1):
        return "Squares are only present"
    elif all(i**3 in list2 for i in list1):
        return "Cubes are only present"
    else:
        return "No such pattern is present"

'''
Write the function amstrong which takes two numbers(num1,num2) as input. Function should return the list of amstrong numbers between num1 and num2

Example : [0,1,..]
'''
def amstrong(num1,num2):
    amstrong_list = []
    for i in range(num1,num2+1):
        temp = i
        sum = 0
        length = len(str(i))
        while temp != 0:
            last_digit = temp % 10
            sum += last_digit**length
            temp //= 10
        if sum == i:
            amstrong_list.append(i)
    return amstrong_list

'''
Write the function string_oper which takes a string as input and return another string after removing words that have characters repeated

Input : "This is an example"
Output : "This is an"
'''
def string_oper(string):
    string = string.split()
    string = [i for i in string if len(set(i)) == len(i)]
    return ' '.join(string)

'''
Write a function string_reverse which takes a string as input and return another string with each word in reversed order.

Example : "START OF THE PROJECT"
Output :  "TRATS FO EHT TCEJORP"
'''
def string_reverse(string):
    string = string.split()
    string = [i[::-1] for i in string]
    return ' '.join(string)

if __name__=='__main__':
    list1 = ast.literal_eval(input())
    list2 = ast.literal_eval(input())
    num1 = ast.literal_eval(input())
    num2 = ast.literal_eval(input())
    string1 = input()
    string2 = input()
    print(list_oper(list1,list2))
    print(amstrong(num1,num2))
    print(string_oper(string1))
    print(string_reverse(string2))

4. Hierarchical Inheritance

Read the Instructions and code for the questions specified below

  1. Create a class Person
    Initialize the class with first_name,last_name
    Create a member function "Name" that returns the Full name of the person
    Type of first_name - str
    Type of last_name - str
  2. Create another class Student that inherits the proporties of class Person
    Initialize the class variable "count" with value 0
    Initialize the class with fist_name,last_name,rollno,mark1,mark2
    class variable count should have the number of students
    Create a member function "GetStudent" that returns the fullname,rollno,total marks seperated by commas
    Type of first_name - str
    Type of last_name -str
    Type of rollno - int
    Type of mark1 - int
    Type of mark2 - int
  3. Create another class Staff that inherits the proporties of class Person
    Initialize the class variable "count" with value 0
    Initialize the class with fist_name,last_name,staffnum
    class variable count should have the number of staffs
    Create a member function "GetStaff" that returns the fullname and staffnumber seperated by comma
    Type of first_name - str
    Type of last_name -str
    Type of staffnum - int

Sample Case 0

Sample Input

[["Joseph", "Paul",1, 100,30],["Mathew","John",2,100,0]]
[["Abin", "Joy", 1832],["Liza","Clare",1003]]

Sample Output

Abin Joy,1832
Liza Clare,1003
2
Joseph Paul,1,130
Mathew John,2,100
2

Solution

import ast

# Enter your code here. Read input from STDIN. Print output to STDOUT
'''
Create class Person
Initialize the class with first_name,last_name
Create a member function "Name" that returns the Full name of the person
Type of first_name - str
Type of last_name - str
'''
class Person:
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
    def Name(self):
        return self.first_name + " " + self.last_name

'''
Create another class Student that inherits the proporties of class Person
Initialize the class variable "count" with value 0
Initialize the class with fist_name,last_name,rollno,mark1,mark2
class variable count should have the number of students
Create a member function "GetStudent" that returns the fullname,rollno,total marks seperated by commas
Type of first_name - str
Type of last_name -str
Type of rollno - int
Type of mark1 - int
Type of mark2 - int
'''    
class Student(Person):
    count = 0
    def __init__(self,first_name,last_name,rollno,mark1,mark2):
        super().__init__(first_name,last_name)
        self.rollno = rollno
        self.mark1 = mark1
        self.mark2 = mark2
        Student.count += 1
    def GetStudent(self):
        return self.Name() + "," + str(self.rollno) + "," + str(self.mark1 + self.mark2)

'''
Create another class Staff that inherits the proporties of class Person
Initialize the class variable "count" with value 0
Initialize the class with fist_name,last_name,staffnum
class variable count should have the number of staffs
Create a member function "GetStaff" that returns the fullname and staffnumber seperated by comma
Type of first_name - str
Type of last_name -str
Type of staffnum - int
'''      
class Staff(Person):  
    count = 0 
    def __init__(self,first_name,last_name,staffnum):
        super().__init__(first_name,last_name)
        self.staffnum = staffnum
        Staff.count += 1
    def GetStaff(self):
        return self.Name() + "," + str(self.staffnum)

if __name__=='__main__':
    students = ast.literal_eval(input())
    staff = ast.literal_eval(input())
    t = []
    s = []
    for i in staff:
        t.append(Staff(i[0],i[1],i[2]))
    for i in students:
        s.append(Student(i[0],i[1],i[2],i[3],i[4]))

    for i in t:
        print(i.GetStaff())
    print(Staff.count)

    for i in s:
        print(i.GetStudent())
    print(Student.count)
Share:

HTML CSS - Mini Project || Fresco Play || 63003

Problem:

Expense Tracker is a simple HTML and CSS application where user's can enter details of their expenses.

  • Create an Expense Tracker app in which users can track expenses incurred by them.
  • Develop front-end content using HTML and CSS.
  • Create 4 HTML pages and 1 CSS page. Creating HTML Pages
  • Every HTML page must have the main content inside a div tag class named main-content.
  • Every HTML page must have a header and a footer tag.
  • To mark the current page in the navbar use the class name current in the anchor tag to indicate that the current page is being accessed.

index.html

  • For the home page, create a simple web page containing a header, footer, and a div class named main-content.
  • Use the current class to mark the link to the home page. Refer to the following screenshot:

login.html

In main-content, use the form tag to create a form containing 2 input fields, 1 button, and a link to redirect to the registration page for users who are not registered (no login credentials). Refer to the following screenshot:

register.html

In main-content, use the form tag to create a form containing 3 input fields, 1 button, and a link to redirect to the login page for users who are already registered. Refer to the following screenshot:

expense.html

In main-content, use the form tag to create a form containing a drop-down menu (Card, Cash, Cryptocoin, and Other), 3 input fields, and 1 button. Refer to the following screenshot:

Creating CSS Page

  • Refer to the screenshots for details about the styling of the page
  • Use a relative position and place the content of the div tag class main-content in the center of the page.
  • Use proper color specifications for all the text and backgrounds on the page. Note: There is a linear-gradient type of styling on the background of each page.

Notes:

  • Use appropriate headings and font size.
  • Use appropriate placeholders for form elements.
  • Link the style page with all the static HTML pages.

Solution:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="style.css">
  <title>Expense Tracker</title>
</head>
<body>
  <header>
    <nav>
      <a href="index.html" class="current">Home</a>
      <a href="login.html">Login</a>
      <a href="register.html">Register</a>
      <a href="expense.html">Note Expense</a>
    </nav>
  </header>
  <div class="main-content">
      <h1>Welcome to the expense tracker system!!!!!</h1>
      <h3>Quote of the day:</h3>
      <p>Being in control of your finances is a great stress reliever!!!!!</p>
  </div>
  <footer>Copyright © 2020 All Rights Reserved</footer>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="style.css">
  <title>Login</title>
</head>

<body>
  <header>
    <nav>
      <a href="index.html">Home</a>
      <a href="login.html" class="current">Login</a>
      <a href="register.html">Register</a>
      <a href="expense.html">Note Expense</a>
    </nav>
  </header>
  <div class="main-content">
    <form action="">
      <input type="text" placeholder="username" name="username">
      <input type="password" placeholder="password" name="password">
      <button>Login</button>
      <p>Not registered? <a href="register.html">Create an account</a></p>
    </form>
  </div>
  <footer>Copyright © 2020 All Rights Reserved</footer>
</body>

</html>

register.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="style.css">
  <title>Register</title>
</head>

<body>
  <header>
    <nav>
      <a href="index.html">Home</a>
      <a href="login.html">Login</a>
      <a href="register.html" class="current">Register</a>
      <a href="expense.html">Note Expense</a>
    </nav>
  </header>
  <div class="main-content">
    <form action="">
      <input type="text" name="name" placeholder="name">
      <input type="password" name="password" placeholder="password">
      <input type="text" name="email address" placeholder="email address">
      <button>Create</button>
      <p>Already registered? <a href="login.html">Sign In</a></p>
    </form>
  </div>
  <footer>Copyright © 2020 All Rights Reserved</footer>
</body>

</html>

expense.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="style.css">
  <title>Note Expense</title>
</head>

<body>
  <header>
    <nav>
      <a href="index.html">Home</a>
      <a href="login.html">Login</a>
      <a href="register.html">Register</a>
      <a href="expense.html" class="current">Note Expense</a>
    </nav>
  </header>
  <div class="main-content">
    <form action="">
      <h1>Add a new item:</h1>
      <label for="type">Type:</label>
      <select name="type" id="type">
        <option value="card">Card</option>
        <option value="cash">Cash</option>
        <option value="cryptocoin">Cryptocoin</option>
        <option value="other">Other</option>
      </select>
      <label for="name">Name:</label>
      <input type="text" placeholder="What did you spend on?" name="name">
      <label for="date">Date:</label>
      <input type="date" name="date">
      <label for="amount">Amount:</label>
      <input type="number" placeholder="How much?" name="amount">
      <button>Add a new expense</button>
    </form>
  </div>
  <footer>Copyright © 2020 All Rights Reserved</footer>
</body>

</html>

style.css

*{
  box-sizing: border-box;
}
body {
  background: linear-gradient(to left, rgb(0, 0, 0), rgb(128, 128, 128));
  position: relative;
  padding: 0;
  margin: 0;
}
header{
  background: rgb(51, 51, 51) none repeat scroll 0% 0% / auto padding-box border-box;
  position: fixed;
  top: 0;
  width: 100%;
  padding: 0.5rem;
}
nav a, nav a:visited, nav a:link{
  color: white;
  padding: 0.5rem;
  text-decoration: none;
}
nav a:hover{
  background-color: white;
  color: black;
}

nav a.current{
  background-color: rgba(211, 211, 211, 1);
}

footer{
  background: rgb(51, 51, 51) none repeat scroll 0% 0% / auto padding-box border-box;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  padding: 0.5rem;
  color: white;
}
.main-content{
  background-color:rgba(255, 255, 255, 1);
  position: relative;
  text-align:center;
  max-width: 500px;
  padding: 2rem 1.5rem;
  margin: 5rem auto 1rem;
}

form p {
  color: #999;
}

form a{
  color: black;
  text-decoration: none;
}

input, button, select{
  display: block;
  width: 100%;
  padding: 0.75rem;
  margin: 0.5rem;
}

input, select{
  background-color: #ddd;
  border: 1px solid #ddd;
}

button{
  background-color: black;
  color: white;
  border-radius: 0;
  border: 1px solid black;
  text-transform: uppercase;
}
button:hover{
  color: black;
  background-color: white;
}

Output:

Index Page

Login Page

Register Page

Note Expense Page

Share: