Hanwool Codes RSS Tag Admin Write Guestbook
Categories (45)
2023-02-08 05:29:54

Pointer | HackerRank

 

Pointer | HackerRank

Learn how to declare pointers and use them.

www.hackerrank.com

 

Goal

 

By using pointer in C++, save a + b value into a and | a - b | into b.

 

 

Solution

 

This problem makes us to pratice pointer. 

You can save sum and abs_min of a and b with * sign in a and b, respectively. 

 

// Pointer

#include <stdio.h>
#include <cstdlib>


void update(int *a,int *b) {
    // Complete this function

    int sum = *a + * b;
    
    int abs_min = (*a) - (*b);
    *a = sum;
    *b = abs(abs_min);
        
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;
    
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}
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-02-04 04:29:14

Functions | HackerRank

 

Functions | HackerRank

Learn how to write functions in C++. Create a function to find the maximum of the four numbers.

www.hackerrank.com

 

 

Goal

 

Get four arguments and return the greatest of the four integers

 

 

Solution

 

Because you just need to return the greatest integer.

You can compare a and b first, then c and d.

If you find already greateest integer, you can simply return the value.

 

// Functions

#include <iostream>
#include <cstdio>
using namespace std;

/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/

int max_of_four(int a, int b, int c, int d){
    
    
    if(a >= b){
        if (a >= c){
            if (a >= d){
                return a;
            }
            else{
                return d;
            }
        }
            
        else{
            
            if( c>=d){
                return c;
            }
            
            else{
                return d;
            }
        }
    }
    
    else{
        
        if (b >= c){
            if (b >= d){
                return b;
            }
            else {
                return d;
            }
        }
        
        else{
            
            if (c >= d){
                return c;
            }
            
            else {
                return d;
            }
            
        }
        
    }
    
    return 0;
}



int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);
    
    return 0;
}
2023-02-03 03:44:47

sWAP cASE | HackerRank

 

sWAP cASE | HackerRank

Swap the letter cases of a given string.

www.hackerrank.com

 

Goal

 

You are given a string and your task is to swap cases. 

In other words, convert all lowercase letters to uppercase letters and vice versa.

 

Solution

 

You can read one character in string and swap cases and return new string.

 

# sWAP cASE

def swap_case(s):
    
    new_s = ""
    
    for c in s:
        if c.isupper():
            new_s += c.lower()
            
        else:
            new_s += c.upper()
            
    return new_s


if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)
2023-02-02 05:26:03

Lists | HackerRank

 

Lists | HackerRank

Perform different list operations.

www.hackerrank.com

 

Goal

 

read different commands, operate commands and print the results.

 

 

Solution

 

you can create if statement to operate each command.

But important is to read the values after commands.

I use *line to read values.

 

# Lists

if __name__ == '__main__':
    N = int(input())
    
    results = []
    
    for _ in range(N):
        name, *line = input().split()
        
        if name == "insert":
            results.insert(int(line[0]), int(line[1]))
        
        elif name == "append":
            results.append(int(line[0]))
            
        elif name == "sort":
            results.sort()
            
        elif name == "print":
            print(results)
        
        elif name == "pop":
            results.pop()
            
        elif name == "remove" :
            results.remove(int(line[0]))
            
        else: #name == reverse
            results.reverse()
2023-02-01 04:46:40

Finding the percentage | HackerRank

 

Finding the percentage | HackerRank

Store a list of students and marks in a dictionary, and find the average marks obtained by a student.

www.hackerrank.com

 

Goal

 

Print the average of the marks array for the given student name and showing 2 places after the decimal.

 

 

Solution

 

First, we need to get average score from the give student marks.

Secondly, we need to print out only 2 places after the decimal.

I use {:.2f} format to show 2 places after the decimal. But there are other ways too.

 

# Finding the percentage

if __name__ == '__main__':
    n = int(input())
    student_marks = {}
    for _ in range(n):
        name, *line = input().split()
        scores = list(map(float, line))
        student_marks[name] = scores
    query_name = input()
    
    query_scores = [x for x in student_marks[query_name]]
    
    print("{:.2f}".format(float(sum(query_scores)) / len(query_scores)))

 

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])
2023-01-29 22:03:44

Find the Runner-Up Score! | HackerRank

 

Find the Runner-Up Score! | HackerRank

For a given list of numbers, find the second largest number.

www.hackerrank.com

 

Goal

 

1. Give n scores

2. Store them in a list

3. find the score of the runner-up

 

so, you should print the runner-up score.

 

Solution

 

You can convert map into list

After then sort asending order and then convert list to set because you need to escape duplicate scores

You can print runner-up score with index -2 because negative indexing is used in Python to begins slicing from the end of list. So in our case, you need to read index -2.

# Find the Runner-Up Score!

if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())
    
    list_arr = list(arr)
    list_arr.sort()
    
    convert_arr = list(set(list_arr))
    
    print(convert_arr[-2])
2023-01-28 05:21:45

List Comprehensions | HackerRank

 

List Comprehensions | HackerRank

You will learn about list comprehensions.

www.hackerrank.com

 

Goal

 

Print a list of all possible coordinates given by (i, j, k) on a 3D grid where the sum of i + j + k is not equal to n.

 

 

Solution

You can simply make a condition statement {(i + j + k) != n} to append all (i,j,k) combinations into list and print the list. 

 

There are two simple ways to solve this problem. You can use simply multiple loops, but you can use easily loop comprehensions. 

 

1) The for statement

 

# List Comprehensions

if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())

    results = []

    for i in range( x + 1):
        for j in range( y + 1):
            for k in range(z + 1):
                if (i + j + k) != n:
                    results.append([i, j, k])


    print(results)

 

2) List Comprehension

# List Comprehensions

if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())

    results = [[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k != n]

    print(results)
2023-01-27 04:59:45

Print Function | HackerRank

 

Print Function | HackerRank

Learn to use print as a function

www.hackerrank.com

 

Goal

 

Print the list of integers from 1 through give n as a string, without spaces

 

 

Solution

 

To solve this problem, you can use for statement and str class to convert integer value to string object. 

 

# Print Function

if __name__ == '__main__':
    n = int(input())
    
    number = ""
    for i in range(1, n+1, 1):
        number += str(i)
        
    print(int(number))


Hanwool Codes. Designed by 코딩재개발.