Hanwool Codes RSS Tag Admin Write Guestbook
Python Challenge (7)
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-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-11 04:20:10

What's Your Name? | HackerRank

 

What's Your Name? | HackerRank

Python string practice: Print your name in the console.

www.hackerrank.com

 

Goal

 

You are given the firstname and lastname of a person on two different lines. 

Your task is to read them and print the following:

Hello firstname lastname! You just delved into python.

 

Solution

 

This problem is to check you can read parameters from function and print with parameter values. 

There are several ways to output formatting

 

# What's Your Name?

#
# Complete the 'print_full_name' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
#  1. STRING first
#  2. STRING last
#

def print_full_name(first, last):
    # Write your code here
    
    answer = "Hello {} {}! You just delved into python.".format(first, last)
    
    print(answer)

if __name__ == '__main__':
    first_name = input()
    last_name = input()
    print_full_name(first_name, last_name)

 

2023-02-07 05:45:56

String Split and Join | HackerRank

 

String Split and Join | HackerRank

Use Python's split and join methods on the input string.

www.hackerrank.com

 

Goal

Replace " "(space) into - (hyphen) in string.

 

 

Solution

You can use replace function in string to replace space into hyphen. 

It is very useful function. So, please remember this function!

 

# String Split and Join

def split_and_join(line):
    # write your code here
    split_line = line.replace(' ', '-')
    
    return split_line

if __name__ == '__main__':
    line = input()
    result = split_and_join(line)
    print(result)
2023-01-31 05:30:54

Nested Lists | HackerRank

 

Nested Lists | HackerRank

In a classroom of N students, find the student with the second lowest grade.

www.hackerrank.com

Goal

 

Given the names and grades for each student in a class of  N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.

 

Solution

 

I use two lists to solve this problem. One list is for student name and score. The other list is only for score.

So, we need to sort score list and then find second lowest score.

After then, we sort student by name and find students which have second lowest score and print them alphabetically

 

# Nested Lists

if __name__ == '__main__':
    
    students = []
    scores = []
    
    for _ in range(int(input())):
        name = input()
        score = float(input())
        
        students.append([name, score])
        scores.append(score)
        
    scores.sort()
    mini = scores[0]
    second_min = 0
    students.sort()
    
    for score in scores:
        if score != mini:
            second_min = score
            break
        
    
    for student in students:
        if student[1] == second_min:
            print(student[0])


Hanwool Codes. Designed by 코딩재개발.