Hanwool Codes RSS Tag Admin Write Guestbook
software Engineering/(Python)HackerRank (29)
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)
2023-02-25 04:51:49

DefaultDict Tutorial | HackerRank

 

DefaultDict Tutorial | HackerRank

Create dictionary value fields with predefined data types.

www.hackerrank.com

 

Goal

 

The first line contains integers, n and m separated by a space.
The next  lines contains the words belonging to group A.
The next  lines contains the words belonging to group B.

Output m lines.
The i-th line should contain the 1-indexed positions of the occurrences of the i-th word separated by spaces.

 

 

Solution

 

We can practice with defaultdict to solve this task. 

Importing the defaultdict class from the collections module 

and creating a defaultdict object d that will hold the input values.

 

Taking two inputs separated by a space and storing them in x and y.

 

Then using a for loop to iterate int(x) times, taking input values

and appending them to the 'A' key of the defaultdict object d.

 

Similarly, for int(y) times, taking input values

and appending them to the 'B' key of the defaultdict object d.

 

Taking two inputs separated by a space and storing them in x and y

 

Then using a for loop to iterate int(x) times, taking input values 

and appending them to the 'A' key of the defaultdict object d

 

Similarly, for int(y) times, taking input values and appending them to the 'B' key of the defaultdict object d.

 

# DefaultDict Tutorial

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

d = defaultdict(list)

x, y = input().split()

for i in range(int(x)):
    d['A'].append(input())


for j in range(int(y)):
    d['B'].append(input())

for i in range(len(d['B'])):
    
    value = d['B'][i]
    
    matches = [k+1 for k in range(0,len(d['A'])) if value == d['A'][k]]
    
    if len(matches) == 0:
        print("{}".format(-1))
    else:
        print(*matches,sep=' ')
2023-02-24 04:02:50

Introduction to Sets | HackerRank

 

Introduction to Sets | HackerRank

Use the set tool to compute the average.

www.hackerrank.com

 

Goal

 

Ms. Gabriel Williams is a botany professor at District College.

One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.

 

Task : You are given array of all the plants of height. You need to compute the average.

 

Solution

 

You need to use set data structure to solve this task.

 

Here is a step-by-step explanation of how this function works:


First, the input list is converted to a set using the set() function.

This removes any duplicate values from the input list, as sets only store unique values.

The length of the resulting set is computed using the len() function and stored in the total_length variable.
The sum of the values in the set is computed using the sum() function and stored in the total_values variable.
The average is computed by dividing the total_values by the total_length, and the result is returned.

 

# Introduction to Sets

def average(array):
    # your code goes here
    set_array = set(array)
    total_length = len(set_array)
    total_values = sum(set_array)
    
    return total_values / total_length
        


if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    result = average(arr)
    print(result)
2023-02-23 04:14:37

itertools.permutations() | HackerRank

 

itertools.permutations() | HackerRank

Find all permutations of a given size in a given string.

www.hackerrank.com

 

Goal

 

You are given a string S.

Your task is to print all poissible permutations of size K of the string in lexicographic sorted order.

 

Solution

 

You need to use itertools.permutations(iterable[, r]) method to solve this task. 

 

The itertools module in Python provides a number of powerful functions for working with iterable objects.

One of these functions is permutations(), which generates all possible permutations of an iterable object. 

The input() function is used to read a line of input from standard input, 

and the split() method is used to split the input line into a list of strings. 

The first element in the list is the string that we want to generate permutations for, 

and the second element is the length of the permutations that we want to generate.

The permutations() function is called with two arguments: 

the first is the string that we want to generate permutations for, and the second is the length of the permutations. 

The list() function is called to convert the result to a list. The list of permutations is stored in the perm variable.

The perm list is iterated over using a for loop, and a new string is created for each permutation.

The join() method is used to concatenate the elements of the permutation into a string,

and the resulting string is appended to the results list.
Once all the permutations have been generated, 

the sorted() function is called to sort the results list in lexicographic order. 

The join() method is used to concatenate the sorted strings together with a newline character, 

and the resulting string is printed to standard output.

# itertools.permutations()
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import permutations

com = input().split()

perm = list(permutations(com[0], int(com[1])))

results = []

for element_set in perm:
    
    tmp = ""
    
    for element in element_set:
        tmp += element
        
    results.append(tmp)
    
print('\n'.join(sorted(results)))
2023-02-22 05:00:19

https://www.hackerrank.com/challenges/collections-counter/problem

 

collections.Counter() | HackerRank

Use a counter to sum the amount of money earned by the shoe shop owner.

www.hackerrank.com

 

Goal

 

You are given X number of shoes and a list containing the size of each shoe.

Additoinally, you are give N number of customers who are willing to pay X(i) amount of money only if they get the shoe their desired size.

 

So, you need to compute how much money you can earn.

 

You need to use collection.Counter() function to solve this task.

 

Solution

 

The script you provided uses the collections library in Python to solve a problem related to sales of shoes.

The problem involves keeping track of the available shoe sizes and the prices of shoes, and then calculating the total amount of money earned by selling shoes to a group of customers.

The script starts by importing the Counter function from the collections library.

The Counter function is used to count the frequency of elements in a list.

Next, the script prompts the user to input the number of shoes in stock and their sizes. The input() function is used to take user input, and the int() and map() functions are used to convert the resulting string of shoe sizes into a list of integers.

The number of shoes in stock is assigned to the variable n_shoes, and the list of shoe sizes is assigned to the variable shoe_sizes.

The script then prompts the user to input the number of customers and the size and price of the shoes they wish to purchase.

The input() function is used to take user input, and the int() and map() functions are used to convert the resulting string of size and price into two separate integers.

The number of customers is assigned to the variable n_customers, and the total price of all shoes sold is assigned to the variable total_price.

A for loop is then used to iterate over each customer.

For each customer, a Counter object is created using the shoe_sizes list. The Counter object counts the frequency of each shoe size in the shoe_sizes list.

The customer's desired shoe size and its price are then read from standard input and assigned to the variables size and price, respectively.

If the desired shoe size is in the shoe_sizes list, the price of the shoe is added to the total_price variable, and the desired shoe size is removed from the shoe_sizes list using the remove() method.

Finally, the total price of all shoes sold is printed to standard output using the print() function.

 

In summary, the script uses the Counter function from the collections library to count the frequency of shoe sizes in a list of shoes, and uses a for loop to sell shoes to customers and calculate the total price of all shoes sold. This script can be useful in scenarios where it is necessary to keep track of inventory and sales in a retail environment.

 

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

n_shoes = int(input())

shoe_sizes = list(map(int, input().split()))

n_customers = int(input())
total_price = 0

for i in range(n_customers):
    shoes_collection = Counter(shoe_sizes)
    
    size, price = list(map(int, input().split()))
    
    if size in shoes_collection.keys():
        total_price += price
        shoe_sizes.remove(size)
    

print(total_price)
2023-02-21 06:13:03

itertools.product() | HackerRank

 

itertools.product() | HackerRank

Find the cartesian product of 2 sets.

www.hackerrank.com

 

Goal

You are given a two lists  A and B. Your task is to compute their cartesian product A x B by using itertools.product()

 

Solution

 

The script you provided utilizes the Python itertools library to generate the Cartesian product of two lists A and B, where each element in A is paired with each element in B.

The resulting pairs are printed to standard output.

The script begins by importing the product function from the itertools library.

The product function generates the Cartesian product of multiple iterables, which in this case are the lists A and B.

Next, the script prompts the user to input the elements of list A and list B.

The input() function takes user input as a string, and the map() function applies the int() function to each element of the resulting string to convert them into integers.

The resulting lists of integers are assigned to the variables A and B, respectively.

The product function is then called with A and B as arguments.

The resulting pairs are stored in the result variable as a list of tuples.

The script then iterates over the result list using a for loop.

The range() function is used to iterate from 0 to the length of result minus 1.

For each iteration, the current tuple in result is printed to standard output with a space separator between its elements. The end parameter of the print() function is set to a single space, so that each printed tuple is followed by a space instead of a newline character.

When the loop reaches the last tuple in result, the end parameter is not set, so the final tuple is printed on its own line.

 

In summary, the script generates the Cartesian product of two lists using the product function from the itertools library and prints the resulting pairs to standard output. This script can be useful in scenarios where it is necessary to combine every element in one list with every element in another list, such as when generating all possible combinations of variables in a simulation.

 

# itertools.product()
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import product

A = list(map(int, input().split()))
B = list(map(int, input().split()))

result = list(product(A,B))

for i in range(len(result)):
    
    if i < len(result) - 1 :
        print(result[i], end=' ')
    else:
        print(result[i])
2023-02-19 16:11:52

https://www.hackerrank.com/challenges/capitalize/problem

 

Capitalize! | HackerRank

Capitalize Each Word.

www.hackerrank.com

 

Goal

 

You are asked to ensure that the first and last names of people begin with a capital letter in their passports.

For example, alison heck should be capitalised correctly as Alison Heck.


Given a full name, your task is to capitalize the name appropriately.

 

 

Solution

 

The solve function takes a string s as an input and returns a new string where the first letter of each word in the original string is capitalized.

The function first initializes an empty list called new_string.

Then, it uses the split method to split the input string s into a list of individual words. The split method separates the string at each occurrence of a space character, creating a list of strings.

Next, the function iterates through each word in the list, capitalizes the first letter of the word using the capitalize() method, and adds the modified word to the new_string list.

Finally, the function joins the list of capitalized words into a single string using the join method, with a space character as the separator, and returns the resulting string.

 

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the solve function below.
def solve(s):
    
    new_string = []
    
    for name in s.split(' '):
        new_string.append(name.capitalize())
    
    
    return ' '.join(new_string)
    
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()
2023-02-18 21:28:11

String Formatting | HackerRank

 

String Formatting | HackerRank

Print the formatted decimal, octal, hexadecimal, and binary values for $n$ integers.

www.hackerrank.com

 

Goal

 

given an integer, n, print the following values for each integer i from 1 to n:

1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary

 

Each value should be space-padded to match the width of the binary value of number and the values should be separated by a single space.

 

 

Solution

 

In this script, we have a function called print_formatted which takes an integer number as input.

The function then sets the maximum width of the binary representation of number and initializes an empty string called text.

The function then uses a for loop to iterate through the range from 1 to number.

Inside the loop, it adds the right-justified string of the current number in decimal, octal, hexadecimal, and binary format to the text string.

The right-justified strings are created using the rjust method which takes an integer argument indicating the minimum width of the resulting string.

By adding 1 to the max_width variable, we create a space between the formatted strings.

After constructing the text string for each value of i, the function prints it to the console and then resets the text string to an empty string.

 

# String Formatting

def print_formatted(number):
    # your code goes here
    binary_max = str(bin(number))
    max_width = len(binary_max[2:])
    text = ""
    
    for i in range(1, number + 1):
    
        text += str(i).rjust(max_width)
        text += str(oct(i))[2:].rjust(max_width + 1)
        text += str(hex(i))[2:].upper().rjust(max_width + 1)
        text += str(bin(i))[2:].rjust(max_width + 1)
        
        print(text)
        text = ""
        

if __name__ == '__main__':

    n = int(input())
    print_formatted(n)


Hanwool Codes. Designed by 코딩재개발.