andraskiss.hu

Home / Development / Software Development / Python / HackerRank Challenges

HackerRank Python Challenges

In this article I show how I solved HackerRank Python challenges. The main purpose of the content is to present my acquired experiences primarily for learning purposes.

Other categories:

Introduction
Basic Data Types
Strings
Sets
Itertools
Collections
Built-Ins
Numpy
Others

Introduction

Say "Hello, World!" With Python

Task:

Print "Hello, World!".

Solution:

print("Hello, World!")

Arithmetic Operators

Task:

The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:

  1. The first line contains the sum of the two numbers.
  2. The second line contains the difference of the two numbers (first - second).
  3. The third line contains the product of the two numbers.


Solution:
a = int(input())
b = int(input())

print(a + b)
print(a - b)
print(a * b)

Python: Division

Task:

The provided code stub reads two integers, a and b, from STDIN.
Add logic to print two lines. The first line should contain the result of integer division, a // b.
The second line should contain the result of float division, a / b.
No rounding or formatting is necessary.

Solution:

a = int(input())
b = int(input())

print(a // b)
print(a / b)

Loops

Task:

The provided code stub reads and integer, n, from STDIN. For all non-negative integers i < n, print i2.

Solution:

n = int(input())

i = 0
while i < n:
    print(i ** 2)
    i += 1

Write a function

Task:

Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False.
Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function.

Solution:

def is_leap(year):
    leap = False
    
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                leap = True
        else:
            leap = True
            
    return leap

year = int(input())
print(is_leap(year))

Print Function

Task:

The included code stub will read an integer, n, from STDIN.
Without using any string methods, try to print the following:
123...n
Note that "..." represents the consecutive values in between.

Solution:

n = int(input())

i = 1
result = ''
while i <= n:
    result = result + str(i)
    i += 1

print(result)