Python Basic Certification

Python: Shopping Cart

The task is to implement two classes:
ShoppingCart and Item according to the following requirements:

Item

An item is instantiated using the constructor Item(name: str, price: int) where the name denotes the name of the item, and the price denotes the price of the item.
Its name can be retrieved as a normal attribute, that is, if item is an instance of Item, then item.name returns the name of the item.

ShoppingCart

A shopping cart is instantiated using a constructor without arguments, i.e. ShoppingCart()

It has a method add(item: Item) that adds the given item to the cart. An item may be added to the cart multiple times. An item will be added each time the add method is called.

-It has a method, tota/() -> int, that returns the sum of the prices of all items currently in the cart.

-Calling len(cart) where the cart is an instance of a ShoppingCart returns the number of items in the cart.

Implementations of the classes will be tested by a provided code stub and several input files that contain parameters. First, the stub initializes instances of Items an instance of the ShoppingCart. Next, it performs the given operations on the ShoppingCart instance. The result of their executions will be printed to the standard output by the provided code.

Constraints

. There will be at most 5 different items.
. There will be at most 500 operations to perform on the cart.

Solution Implementation

#!/bin/python3

import math
import os
import random
import re
import sys


class Item:
    name = ''
    price= 0
    
    def __init__(self,s,p):
        self.name = s
        self.price = p
    pass

class ShoppingCart:
    cart_names = []
    cart_prices= []
    tot = 0
    
    def __init__(self):
        super().__init__()
    
    def add(self, item):
        self.cart_names.append(item.name)
        self.cart_prices.append(item.price)
                
    def total(self):
        self.tot = sum(self.cart_prices)
        return self.tot     
    
    def __len__(self):
        return len(self.cart_names)
    pass
    
    

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())
    items = []
    for _ in range(n):
        name, price = input().split()
        item = Item(name, int(price))
        items.append(item)

    cart = ShoppingCart()

    q = int(input())
    for _ in range(q):
        line = input().split()
        command, params = line[0], line[1:]
        if command == "len":
            fptr.write(str(len(cart)) + "\n")
        elif command == "total":
            fptr.write(str(cart.total()) + "\n")
        elif command == "add":
            name = params[0]
            item = next(item for item in items if item.name == name)
            cart.add(item)
        else:
            raise ValueError("Unknown command %s" % command)
            
    fptr.close()

Python: Dominant Cells

There is a given list of lists of integers that represent a 2-dimensional grid with n rows and m columns. A cell is called a dominant cell if it has a strictly greater value than all of its neighbors. Two cells are neighbors when they share a common side or a common corner, so a cell can have up to 8 neighbors. Find the number of dominant cells in the grid.

Function Description
Complete the function numCells in the editor below.

numCells has the following parameter(s):
int grid[n][m]: a 2-dimensional array of
integers

Returns
int: the number of dominant cells in the grid

Constraints
· 1 ≤ n, m ≤ 500
. There are at least 2 cells in the grid.
. 1 ≤ grid[i][j] ≤ 100

import math
import os
import random
import re
import sys


def numCells(grid):
    n = len(grid)
    m = len(grid[0])

    count = 0

    for i in range(n):
        for j in range(m):
            cell_value = grid[i][j]
            is_dominant = True

            # Check all 8 neighbors of the cell
            for dx in [-1, 0, 1]:
                for dy in [-1, 0, 1]:
                    if dx == 0 and dy == 0:
                        continue

                    ni = i + dx
                    nj = j + dy

                    # Ignore cells outside the grid boundaries
                    if 0 <= ni < n and 0 <= nj < m and grid[ni][nj] >= cell_value:
                        is_dominant = False
                        break

                if not is_dominant:
                    break

            if is_dominant:
                count += 1

    return count


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    grid_rows = int(input().strip())
    grid_columns = int(input().strip())

    grid = []

    for _ in range(grid_rows):
        grid.append(list(map(int, input().rstrip().split())))

    result = numCells(grid)

    fptr.write(str(result) + '\n')

    fptr.close()

Balanced System File Partition

#!/bin/python3

import math
import os
import random
import re
import sys


#
# Complete the 'mostBalancedPartition' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER_ARRAY parent
#  2. INTEGER_ARRAY files_size
#

def mostBalancedPartition(parent, files_size):
    # Write your code here
    def helper(node, adj, files_size):
        queue = [node]
        weight = 0
        while queue:
            index = queue.pop()
            weight += files_size[index]
            if index in adj:
                queue.extend(adj[index])
        return weight

    adj = {}
    edges = []
    for index, p in enumerate(parent):
        edges.append((p, index))
        if p in adj:
            adj[p].append(index)
        else:
            adj[p] = [index]
    
    print(adj, edges)
    total_weight = sum(files_size)
    min_diff = sum(files_size)
    for e in edges:
        p,c = e
        adj[p].remove(c)
        w1 = helper(c, adj, files_size)
        min_diff = min(min_diff, abs(total_weight - 2*w1))
        adj[p].append(c)

    return min_diff
if __name__ == '__main__':

String Transformation

#!/bin/python3

import math
import os
import random
import re
import sys


#
# Complete the 'transformSentence' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING sentence as parameter.
#

def transformSentence(sentence):
    sentence.strip()
    res = ''
    ind = 0
    for x in sentence:
        if(ind==0):
            res+= x
            ind+=1
        elif(x == ' '):
            res += x
            ind+=1
        else:
            y = sentence[ind-1]
            if(y==' '):
                res+= x
                ind+=1
            elif(y.lower() < x.lower()):
                res += x.upper()
                ind+=1
            elif(y.lower()>x.lower()):
                res += x.lower()
                ind+=1
            else:
                res+= x
                ind+=1
    return res
if __name__ == '__main__':

Vowel Substring

#!/bin/python3

import math
import os
import random
import re
import sys


#
# Complete the 'findSubstring' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
#  1. STRING s
#  2. INTEGER k
#

def findSubstring(s, k):
    j = k
    mx = 0
    count= 0
    max_sub = ""
    ln = len(s)
    i = 0
    for i in s[0:j]:
        if i in 'aeiou':
            count+=1
    if count!=0:
        mx = count
        max_sub = s[0:j]
    i = 0
    while(j<ln-1):
        if(s[i] in 'aeiou'):
            if count!=0:
                count-=1
        i+=1        
        if(s[j] in 'aeiou'):
            count+=1

        j+=1
        if count>mx:
            mx = count
            max_sub = s[i:j]
             
        
        
    if max_sub == "":
        return "Not found!"
    else:
        return max_sub
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    k = int(input().strip())

    result = findSubstring(s, k)

    fptr.write(result + '\n')

    fptr.close()

Fizzbuzz

#!/bin/python3

import math
import os
import random
import re
import sys


#
# Complete the 'fizzBuzz' function below.
#
# The function accepts INTEGER n as parameter.
#

def fizzBuzz(n):
    for number in range(1, n + 1):
        if number % 3 == 0 and number % 5 == 0:
            print('FizzBuzz')
        elif number % 3 == 0:
            print('Fizz')
        elif number % 5 == 0:
            print('Buzz')
        else:
            print(number)


if __name__ == '__main__':
    n = int(input().strip())

    fizzBuzz(n)

The Above Solution Help you to get the Certificate in Python Basic

Start Test

Leave a Reply

Your email address will not be published. Required fields are marked *