Hanwool Codes RSS Tag Admin Write Guestbook
Python Learning (28)
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-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-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])


Hanwool Codes. Designed by 코딩재개발.