Hanwool Codes RSS Tag Admin Write Guestbook
Code Practice (3)
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))


Hanwool Codes. Designed by 코딩재개발.