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

## Others

### Words Score

**Task:**

In this challenge, the task is to debug the existing code to successfully execute all provided test files.
Consider that vowels in the alphabet are a, e, i, o, u and y.
Function score_words takes a list of lowercase words as an argument and returns a score as follows:
The score of a single word is 2 if the word contains an even number of vowels.
Otherwise, the score of this word is 1.
The score for the whole list of words is the sum of scores of all words in the list.
Debug the given function score_words such that it returns a correct score.
Your function will be tested on several cases by the locked template code.

**Solution:**

def score_words(words): score = 0 for word in words: num_vowels = 0 #print(word) for letter in word: #print(letter) if letter in ['a', 'e', 'i', 'o', 'u', 'y']: num_vowels += 1 #print('num_vowels: ' + str(num_vowels)) if num_vowels % 2 == 0: score += 2 else: score += 1 #print(score) return score n = int(input()) words = input().split() print(score_words(words))

### Default Arguments

**Task:**

Debug the given function print_from_stream using the default value of one of its arguments.
This function should print the first *n* values returned by get_next() method of stream object provided as an argument. Each of these values should be printed in a separate line.
Whenever the function is called without the stream argument, it should use an instance of EvenStream class defined in the code stubs below as the value of stream.
Your function will be tested on several cases by the locked template code.

**Solution:**

class EvenStream(object): def __init__(self): self.current = 0 def get_next(self): to_return = self.current self.current += 2 return to_return class OddStream(object): def __init__(self): self.current = 1 def get_next(self): to_return = self.current self.current += 2 return to_return def print_from_stream(n, stream=EvenStream()): if type(stream) == EvenStream: stream = EvenStream() else: stream = OddStream() for i in range(n): print(stream.get_next()) queries = int(input()) for _ in range(queries): stream_name, n = input().split() n = int(n) if stream_name == "even": print_from_stream(n) else: print_from_stream(n, OddStream())

### Polar Coordinates

**Task:**

You are given a complex *z*. Your task is to convert it to polar coordinates.

**Solution:**

import math import cmath z = complex(input()) print(math.sqrt(pow(z.real, 2) + pow(z.imag, 2))) print(cmath.phase(z))

### Find Angle MBC

**Task:**

*ABC* is a right triangle, 90° at *B*.
Therefore, angle *ABC* = 90°.
Point *M* is the midpoint of hypotenuse *AC*.
You are given the lengths *AB* and *BC*.
Your task is to find angle *MBC* in degrees.

**Solution:**

import math ab = input() ab = float(ab) bc = input() bc = float(bc) ac = math.sqrt(pow(ab, 2) + pow(bc, 2)) cm = ac / 2 acb = math.acos((pow(ac, 2) + pow(bc, 2) - pow(ab , 2)) / (2 * ac * bc)) mb = math.sqrt(pow(bc, 2) + pow(cm, 2) - 2 * bc * cm * math.cos(acb)) mbc = math.acos((pow(mb, 2) + pow(bc, 2) - pow(cm, 2)) / (2 * mb * bc)) print(str(int(round(math.degrees(mbc)))) + u'\N{DEGREE SIGN}')

### Mod Divmod

**Task:**

Read in two integers, *a* and *b*, and print three lines.
The first line is the integer division *a//b* (While using Python2 remember to import division from __future__).
The second line is the result of the modulo operator: *a%b*.
The third line prints the divmod of *a* and *b*.

**Solution:**

a = int(input()) b = int(input()) print(a//b) print(a%b) print(divmod(a, b))

### Power - Mod Power

**Task:**

You are given three integers: *a*, *b*, and *m*.
Print two lines.
On the first line, print the result of pow(a,b). On the second line, print the result of pow(a,b,m).

**Solution:**

a = int(input()) b = int(input()) m = int(input()) print(pow(a, b)) print(pow(a, b, m))

### Integers Come In All Sizes

**Task:**

Read four numbers, *a*, *b*, *c*, and *d*, and print the result of *a*^b + *c*^d.

**Solution:**

a = int(input()) b = int(input()) c = int(input()) d = int(input()) print(a**b + c**d)

### Calendar Module

**Task:**

You are given a date. Your task is to find what the day is on that date.

**Solution:**

import datetime import calendar d = input() d_list = d.split() date = datetime.datetime(int(d_list[2]), int(d_list[0]), int(d_list[1])) print(calendar.day_name[date.weekday()].upper())

### Time Delta

**Task:**

When users post an update on social media,such as a URL, image, status update etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published, i.e, how many hours, minutes or seconds ago.

Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format:

Day dd Mon yyyy hh:mm:ss +xxxx

Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them.

**Solution:**

import math import os import random import re import sys from datetime import datetime import time def time_delta(t1, t2): t1_datetime = datetime.strptime(t1, '%a %d %b %Y %H:%M:%S %z') t2_datetime = datetime.strptime(t2, '%a %d %b %Y %H:%M:%S %z') return str(abs(int((t1_datetime - t2_datetime).total_seconds()))) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): t1 = input() t2 = input() delta = time_delta(t1, t2) fptr.write(delta + '\n') fptr.close()

### Exceptions

**Task:**

You are given two values *a* and *b*.
Perform integer division and print *a/b*.

**Solution:**

amount = input() l = [] for i in range(int(amount)): inp = input() l = inp.split() try: print(int(int(l[0]) / int(l[1]))) except ZeroDivisionError as e: print("Error Code:", "integer division or modulo by zero") except ValueError as e: print("Error Code:", e)

### Map and Lambda Function

**Solution:**

cube = lambda x: x ** 3 def fibonacci(n): lst = [] if n < 1: return lst lst.append(0) if n < 2: return lst lst.append(1) if n < 3: return lst for i in range(2, n): lst.append(lst[i - 1] + lst[i - 2]) return lst if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))

### Detect Floating Point Number

**Solution:**

t = int(input()) for i in range(t): try: s = input() if '.' not in s: raise Exception('') n = float(s) print(True) except: print(False)

### Group(), Groups() & Groupdict()

**Task:**

You are given a string *S*.
Your task is to find the first occurrence of an alphanumeric character in *S* (read from left to right) that has consecutive repetitions.

**Solution:**

s = input() def func(): for i in range(1, len(s)): if s[i].isalnum() and s[i] == s[i - 1]: return s[i] f = func() if f is not None: print(f) else: print(-1)