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.
Basic Data Types
You are given a two lists A and B. Your task is to compute their cartesian product AXB.
a = input().split() b = input().split() a1 =  b1 =  for i in a: a1.append(int(i)) for i in b: b1.append(int(i)) prod =  prod = [(x, y) for x in a1 for y in b1] str_prod = '' for i in prod: str_prod += str(i) + ' ' print(str_prod)
You are given a string S. Your task is to print all possible permutations of size k of the string in lexicographic sorted order.
from itertools import permutations s = input().split() text = s length = s #print(permutations(text, int(length))) l = [''.join(p) for p in permutations(text, int(length))] l.sort() for i in l: print(i)
You are given a string S. Your task is to print all possible combinations, up to size k, of the string in lexicographic sorted order.
from itertools import combinations s = input() arr = s.split() sList =  sList[:0] = arr sList.sort() for i in range(1, int(arr) + 1): for j in list(combinations(sList, i)): line = '' for k in j: line += k print(line)
You are given a string S. Your task is to print all possible size k replacement combinations of the string in lexicographic sorted order.
from itertools import combinations_with_replacement s = input() s_split = s.split() letter_list =  letter_list[:0] = s_split letter_list.sort() for i in [''.join(x) for x in list(combinations_with_replacement(letter_list, int(s_split)))]: print(i)
Compress the String!
In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this function, Check this out . You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences of the character 'c' with (X, c) in the string.
from itertools import groupby s = input() s_list =  s_list[:0] = s result_list = '' for k, g in groupby(s_list): result_list += '(' + str(len(list(g))) + ', ' result_list += str(k) + ') ' print(result_list)
Iterables and Iterators
You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list. Find the probability that at least one of the K indices selected will contain the letter: 'a'.
import itertools n = input() letters = input() k = int(input()) combinations = 0 contains = 0 for i in itertools.combinations(letters.split(), k): combinations += 1 for j in i: if j == 'a': contains += 1 break print(contains / combinations)