Hanwool Codes RSS Tag Admin Write Guestbook
Code Challenge (37)
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))
2023-01-26 06:11:27

Write a function | HackerRank

 

Write a function | HackerRank

Write a function to check if the given year is leap or not

www.hackerrank.com

 

Goal

 

This task is to return true if a give year is a leap year, otherwise return false

 

 

Solution

 

There are three main conditions to check leap year:

1. It can be evenly divided by 4 - leap year

2. It can be evenly divided by 100, it is NOT a leap year, unless it is evenly disivible by 400 - leap year

3. Otherwise it is not a leap year.

 

These conditions can be shown in this code.

# Write a function

def is_leap(year):
    leap = False
    
    # Write your logic here
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                leap = True
            else : 
                leap = False
        else:  
            leap = True
        
    else:
        leap = False
    
    return leap

year = int(input())
print(is_leap(year))
2023-01-24 06:01:01

For Loop | HackerRank

 

For Loop | HackerRank

Learn how to use for loop and print the output as per the given conditions

www.hackerrank.com

 

Goal

 

Print results according to two positive input values by using for loop statement.

 

 

Solution

 

To solve easily, I create vector string array included 1-9 numbers. If you use vector array, you can print numbers easily.

 

// For Loop
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
using namespace std;

int main() {
    // Complete the code.
    int a,b;
    cin >> a;
    cin >> b;
    
    vector<string> numbers {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    
    for(int i = a; i <= b; i++){
        
        if(i>9){
            if( i % 2 == 0){
                cout << "even" << endl;
            }
            else{
                cout << "odd" << endl;
            }
        }
        
        else{
            
            cout << numbers[i] << endl;
        }
    }
    
    return 0;
}
2023-01-24 05:55:31

https://www.hackerrank.com/challenges/c-tutorial-conditional-if-else/problem

 

Conditional Statements | HackerRank

Practice using chained conditional statements.

www.hackerrank.com

 

Goal

 

 

Solution

 

You just need to create condtion statements for each condition like below.

 

// Conditional Statements

#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);



int main()
{
    string n_temp;
    getline(cin, n_temp);

    int n = stoi(ltrim(rtrim(n_temp)));

    // Write your code here
    if(n > 9){
        printf("Greater than 9");
    }
    else if(n == 1){
        printf("one");
    }
    else if(n == 2){
        printf("two");
    }
    else if(n == 3){
        printf("three");
    }
    else if(n == 4){
        printf("four");
    }
    else if(n == 5){
        printf("five");
    }
    else if(n == 6){
        printf("six");
    }
    else if(n == 7){
        printf("seven");
    }
    else if(n == 8){
        printf("eight");
    }
    else { // n == 9
        printf("nine");
    }

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}
2023-01-22 18:00:34

Basic Data Types | HackerRank

 

Basic Data Types | HackerRank

Learn about the basic data types in C++. Take the given input and print them.

www.hackerrank.com

 

Goal

1. Read space-seprated values : int, long, char, float and double, respectively

2. Print each element on a new line in the same order it was received as input. + correct decimal points of floating and double points.

 

 

Solution

Follow HackerRank explanation of c++ data types and their format specifiers.

// Basic Data Types

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

int main() {
    // Complete the code.
    int a;
    long b;
    char c;
    float d;
    double e;

    scanf("%d %ld %c %f %lf", &a, &b, &c, &d, &e);
    printf("%d\n", a);
    printf("%ld\n", b);
    printf("%c\n", c);
    printf("%f\n", d);
    printf("%lf\n", e);
    return 0;
}


Hanwool Codes. Designed by 코딩재개발.