Hanwool Codes RSS Tag Admin Write Guestbook
전체 글 (45)
2023-03-10 05:50:32

Collections.OrderedDict() | HackerRank

 

Collections.OrderedDict() | HackerRank

Print a dictionary of items that retains its order.

www.hackerrank.com

Goal

 

You are the manager of a supermarket.
You have a list of N items together with their prices that consumers bought on a particular day.
Your task is to print each item_name and net_price in order of its first occurrence.

 

Solution

 

You use collections.OrderedDict() function to solve this task.

Thid script reads an integer value n from standard input, which represents the number of items in the dictionary.

A loop then runs n times to read item names and their corresponding net prices from standard input. 

The input is split into words, and the script checks if each word is numeric or not.

If the word is numeric, the script assigns it to the net_price variable,

otherwise, it appends it to a list called item_name.

After iterating over the words, the item_name list is joined to create a string representation of the item name. 

Then, the script checks if the item name already exists in the ordered_dictionary

If it does, the script adds the new net price to the existing net price of the item. 

Otherwise, the script creates a new key-value pair in the ordered_dictionary.


Finally, the script iterates over the ordered_dictionary and prints each item name and its net price

Since OrderedDict() maintains the order of the keys, the items are printed in the same order 

in which they were inserted into the dictionary.

# Collections.OrderedDict()

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

ordered_dictionary = OrderedDict()

n = int(input())

for i in range(n):
    
    item_name = []
    net_price = 0
    
    for x in input().split():
        if x.isnumeric():
            net_price = int(x)
        else:
            item_name.append(x)
            
    item_name = " ".join(item_name)
            
    if item_name in ordered_dictionary:
        ordered_dictionary[item_name] += net_price
        
    else:
        ordered_dictionary[item_name] = net_price


for k, v in ordered_dictionary.items():
    print(k, v)
2023-03-08 03:14:27

Collections.namedtuple() | HackerRank

 

Collections.namedtuple() | HackerRank

You need to turn tuples into convenient containers using collections.namedtuple().

www.hackerrank.com

 

Goal

 

Dr. John Wesley has a spreadsheet containing a list of student's IDs, marks, class and name.
Your task is to help Dr. Wesley calculate the average marks of the students.

Print the average marks of the list corrected to 2 decimal places.

 

Solution

 

You use collections.namedtuple()  to solve this task.

 

This code takes input from the standard input (STDIN) in the following format:

  • The first line contains an integer n, which represents the number of students.
  • The second line contains space-separated strings representing the columns of the table.
  • The following n lines contain space-separated values representing the data for each student.

The first line of code reads the integer value n from the standard input and stores it in the variable n.

The second line reads the column names from the standard input 

and converts them into a list of strings using the split() method. 

The index() method is then used to find the index of the 'MARKS' column, which is stored in the variable colum.

The for loop iterates n times, and for each iteration, 

it reads the input data for a student, splits the input string into a list of values using the split() method, 

and adds the value in the 'MARKS' column to the variable average.

Finally, the average of the 'MARKS' column is calculated 

by dividing the sum of all the values in the 'MARKS' column by n.

The result is then printed to the standard output (STDOUT) using the format() method

with a precision of two decimal places.

 

# Collections.namedtuple()

# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
colum = input().split().index('MARKS')
average = 0.0

for i in range(n):
    data = input().split()
    average += float(data[colum])


print('{:.2f}'.format(average / n))
2023-03-01 03:30:00

Exceptions | HackerRank

 

Exceptions | HackerRank

Handle errors detected during execution.

www.hackerrank.com

 

Goal

 

You are given two values  a and b.
Perform integer division and print a / b .

 

Solution

 

We use Exceptions to handle errors for this task. 

Here is code explanation.

It reads the input from standard input and then loops for n times, 

where n is the number entered as the first input.

Inside the loop, it reads two integers from the input, performs integer division, and prints the result. 

 

However, if there is a ZeroDivisionError, 

it prints a custom error message saying "Error Code: integer division or modulo by zero"

If there is a ValueError, it prints "Error Code:" followed by the error message.

 

The try block contains the code that might raise an exception

and the except block is where the exception is handled. 

In this code, there are two except blocks, one for ZeroDivisionError and another for ValueError.

 

The ZeroDivisionError occurs when dividing by zero, which is not possible in arithmetic. 

The ValueError occurs when the input cannot be converted to an integer

such as when the input is a string or a floating-point number.

 

By handling these exceptions, the code prevents the program from crashing 

and provides a useful error message to the user.

# Exceptions

# Enter your code here. Read input from STDIN. Print output to STDOUT
for i in range(int(input())):
    
    try:
        values = input().split()
        print(int(int(values[0]) / int(values[1])))
        
    except ZeroDivisionError as ze:
        print("Error Code: integer division or modulo by zero")
        #print("Error Code:",ze) if you use this one, Error Code: division by zero. it is not correct answer for them.
    
    except ValueError as ve:
        print("Error Code:",ve)


Hanwool Codes. Designed by 코딩재개발.