Hanwool Codes RSS Tag Admin Write Guestbook
Code Challenge (37)
2023-02-16 05:42:04

String Validators | HackerRank

 

String Validators | HackerRank

Identify the presence of alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters in a string.

www.hackerrank.com

 

Goal

 

Find out if the give string S contains : alphanumeric characters, alphabetical characters, digits, lowercase and uppercaser characters.

 

Solution

 

You can use built-in string validation methods to solve this solution.

The script initializes a boolean variable is_pass to False, which will be used to determine whether or not a given test has passed.

The first loop in the script iterates over each character in the input string s.

For each character, it checks whether or not it is alphanumeric using the isalnum() method.

If it is, the script prints "True", sets is_pass to True, and breaks out of the loop.

If the loop completes without finding an alphanumeric character, the script prints "False".

The next four loops work similarly, but check for alphabetical characters(isalpha()), digits(isdigit()), lowercase characters(islower()), and uppercase characters(isuppper()), respectively.

After each loop, the script checks whether or not is_pass is still False.

If it is, this means that the test has not been passed, so the script prints "False".

 

# String Validators

if __name__ == '__main__':
    s = input()
    
    is_pass = False
    
    for c in s:
        if c.isalnum():
            print("True")
            is_pass = True
            break
            
    if(is_pass == False):
        print("False")
        
    is_pass = False
    
    for c in s:
        if c.isalpha():
            print("True")
            is_pass = True
            break
            
    if(is_pass == False):
        print("False")
        
    is_pass = False
        
    for c in s:
        if c.isdigit():
            print("True")
            is_pass = True
            break
            
    if(is_pass == False):
        print("False")
        
    is_pass = False
        
    for c in s:
        if c.islower():
            print("True")
            is_pass = True
            break
            
    if(is_pass == False):
        print("False")
        
    is_pass = False
        
    for c in s:
        if c.isupper():
            print("True")
            is_pass = True
            break
        
    if(is_pass == False):
        print("False")
2023-02-15 04:58:23

Find a string | HackerRank

 

Find a string | HackerRank

Find the number of occurrences of a substring in a string.

www.hackerrank.com

 

Goal

 

You have to print the number of times that the substring occurs in the given string. 

String traversal will take place from left to right, not from right to left.

 

 

Solution

 

The function starts by initializing the number variable to zero, which will be used to keep track of the count of the number of times sub_string occurs in string.

Then, it calculates the length of string and stores it in the n variable.

The function then enters a loop that will iterate n times.

In each iteration, the function uses the find method to search for the first occurrence of sub_string in the new_string variable.

If the find method returns -1, it means that sub_string is not found in new_string and the loop increments the index i by 1.

If find returns a value other than -1, it means that sub_string has been found, and the function increments the number count by 1.

The new_string is then updated to start from the position just after the found sub_string.

Finally, the function returns the number count, which is the number of times sub_string occurs in string.

 

# Find a string

def count_substring(string, sub_string):
    
    number = 0
    n = len(string)
    new_string = string
    
    for i in range(0, n):
        
        result = new_string.find(sub_string)
        
        if(result == -1):
            new_string = new_string[i:]
            i += 1
            
        else:
            new_string = new_string[result + 1:]
            i = result + 1
            number += 1
    
        
    
    
    return number

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)
2023-02-14 06:03:58

Mutations | HackerRank

 

Mutations | HackerRank

Understand immutable vs mutable by making changes to a given string.

www.hackerrank.com

 

Goal

 

Read a given string, change the character at a given index and then print the modified string.

 

Solution

 

We need to understand slicing and indexing Strings in Python. You can check this link

 

 

#Mutations

def mutate_string(string, position, character):
    
    new_string = string[:position] + character + string[position+1:]
    
    return new_string

if __name__ == '__main__':
    s = input()
    i, c = input().split()
    s_new = mutate_string(s, int(i), c)
    print(s_new)

 

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-10 02:45:54

Variable Sized Arrays | HackerRank

 

Variable Sized Arrays | HackerRank

Find the element described in the query for integer sequences.

www.hackerrank.com

 

Goal

 

Create N number of variable-length arrays and find a element from quaries

 

Solution

 

If you know vector in C++, it would be easy problem.

you initialize vector of vector a and insert variable sized vector into a.

 

# Variable Sized Arrays

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n = 0;
    int q = 0;
    
    cin >> n >> q;
    
     vector<vector<int>> a;
    
    for(int i = 0 ; i < n ; i++){
        int k = 0;
        
        cin >> k;
        
        vector<int> v;
        
        int value = 0;
        int index = 1;
        while(cin >> value){
            
            v.push_back(value);
            index++;
            
            if (index > k){
                break;
            }
            
        }
        
        a.push_back(v);
        
    }
    
    for(int i = 0; i < q ; i++){
        int index, j ;
        cin >> index >> j;
        cout << a[index][j] << endl;
    }
    
    
    return 0;
}
2023-02-09 05:43:55

Arrays Introduction | HackerRank

 

Arrays Introduction | HackerRank

How to access and use arrays. Print the array in the reverse order.

www.hackerrank.com

 

Goal

 

Print the N integers of the array in the reverse order, space-separated on a single line.

 

Solution

 

1. Create array with N size.

2. Save N integers into array.

3. Print reverse array with space

 

// Arrays Introduction

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n;
    
    cin >> n;
    
    int a[n];
    int tmp;
    int i = 0;
    
    while (cin >> tmp)
    {
        a[i] = tmp;
        i++;
    }
    
    for(int index = n - 1; index >=0 ; index--){
        if(index !=0){
            cout << a[index] << " ";
        }
        else{
            cout << a[index] << endl;
        }
    }
    
    
    return 0;
}

 

 

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)


Hanwool Codes. Designed by 코딩재개발.