Hanwool Codes RSS Tag Admin Write Guestbook
Categories (45)
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)
2023-02-17 04:32:12

Text Wrap | HackerRank

 

Text Wrap | HackerRank

Wrap the given text in a fixed width.

www.hackerrank.com

 

Goal

 

You are given a string S and width W.

Your task is to wrap the string S into a paragraph of width W.

 

Solution

 

You need to use textwrap module in python.

In textwrap, the function "wrap" is to wrap the string to the specified maximum width by breaking it into multiple lines.

The resulting lines are stored as a list in s_wrap_list. 

'\n'.join() function to return a string by joining the elements of the list with a newline character.

 

import textwrap

def wrap(string, max_width):
    
    s_wrap_list = textwrap.wrap(string, max_width)
    
    return '\n'.join(s_wrap_list)

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)
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;
}

 

 



Hanwool Codes. Designed by 코딩재개발.