HackerRank-Python-Basic Flashcards
Revise Code (45 cards)
Take Multiple Inputs in Single Line
x,y,z,n = (int(input()) for _ in range(4) ) // remember its a generator which returns one thing at a time, a list comprehension cant be used here.
List comprehension: You are given three integers x,y,z and representing the dimensions of a cuboid along with an integer N . You have to print a list of all possible coordinates where the sum of x+y+z is not equal to .N
print([[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])
2D list like [[‘Harry’, 37.21], [‘Berry’, 37.21]….], Find names of second lowest scores.
sec = sorted(list(set([marks for name, marks in x])))[1]
y = sorted([name for name,marks in x if marks==sec])
Execute input strings as commands on a list li. Eg :insert 0 5, insert 1 10, insert 0 6, print
cmd = x[0]
args = x[1:]
cmd+=”(“+”,”.join(args)+”)”
eval(‘li.’+cmd)
Find the Number of times a sub string is repeated in string.
c = sum([1 for i in range(len(string)-len(sub_string)+1)
if string[i:i+len(sub_string)] == sub_string])
how to add an element to a list and a set?
Other funcs of set?
append and add. Remove - returns none + key error, discard - none +no error raised, pop - returns the value popped and raises key error, issubset
set.update() only works for iterable objects. Eg -myset.update([1, 2, 3, 4])
Also, remember that sets are unordered
How to return the number of ints repeating for each int in a number. Eg- 11223333
Groupby(), returns (2,1) (2,2)(4,3)
How lambda works?
lambda argument : expression
C = [(‘a’, ‘a’), (‘a’, ‘c’), (‘a’, ‘d’), (‘a’, ‘c’), (‘a’, ‘d’), (‘c’, ‘d’)]
F = filter(lambda c: ‘a’ in c, C)
returns [(‘a’, ‘a’), (‘a’, ‘c’), (‘a’, ‘d’), (‘a’, ‘c’), (‘a’, ‘d’)]
Zip func, reduce func, filter func
Zip eg - [[1,2],[7,0]] returns [1,7] and [2,0]
filter(func, iterable) , reduce(func, iterable)
Eg - sum a list using reduce.. Whole list is reduced to a single summed number. Func here = a+b
Sort a string as per demand, lowercase, then uppercase, then odd digits, then even.
order = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468’
print(*sorted(input(), key=order.index), sep=’’)
order.index is a function just like lambda and in sorted, keys dont have () after function, for example, myfunc() is a function,then sorted(iterable,key = func) i.e without the (),remember it!
Sort using boolean properties:
print(*sorted(input(), key=lambda c: (c.isdigit() - c.islower(), c in ‘02468’, c)), sep=’’)
Here tuples are returned by lambda like: (1,false). Note that false and true are treated as 0 and 1 in sort. And a tuple is sorted by comparison of elements like (1,0) >(0,1)
How do you solve the mountain pile up problem of 4 3 2 1 2 3 4
while i < l - 1 and lst[i] >= lst[i+1]: i += 1
while i < l - 1 and lst[i] <= lst[i+1]: i += 1
OR min_list = lst.index(min(lst))
left = lst[:min_list]
# right = lst[min_list+1:]
# if left == sorted(left,reverse=True) and right == sorted(right): print(“Yes”)
How to make a combination of a dict and a counter?
from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): pass
What is a decorator?
A decorator is just a callable that takes a function as an argument and RETURNS(NOTE IT) a replacement function. We’ll start simply and work our way up to useful decorators. In Python, functions are first-class objects. This means that functions can be passed around and used as arguments, just like any other object (string, int, float, list, and so on). def my_decorator(func): def wrapper(): //this is made as a dec always returns print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper
def say_whee(): print("Whee!")
say_whee = my_decorator(say_whee) Syntactic Sugar : @my_decorator def say_whee(): print("Whee!")
If else using dictionary:
If is odd, print Weird
If is even and in the inclusive range of 2 to 5 , print Not Weird
If is even and in the inclusive range of 6 to 20 , print Weird
If is even and greater than 20 , print Not Weird
n = int(input().strip()) check = {True: "Not Weird", False: "Weird"}
print(check[ n%2==0 and ( n in range(2,6) or n > 20) ])
Print multiple results using a single print statement (format function)
a = int(input()) b = int(input())
print(‘{0} \n{1} \n{2}’.format((a + b), (a - b), (a * b)))
Without using any string methods, try to print the following 123….N in a single line code
print(*range(1, int(input())+1), sep=’’)
Range can also be printed, no need for comprehension
Given a 2D list: [[Name,Score],[Name,Score]], print the name of a score x using * JOIN, * GENERATOR, *LIST
print(‘\n’.join([a for a,b in sorted(li) if b==second_highest]))
print((a for a,b in sorted(li) if b==second_highest),sep=’\n’)
print([a for a,b in sorted(li) if b==second_highest],sep=’\n’)
print octal, binary, hex and decimal of a numbers upto a given number n, all should be FORMATTED to the width of the binary number of the number.
width = len(“{0:b}”.format(n))
for i in range(1,n+1):
print (“{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}”.format(i,width=width))
what does itertool.product() does, where can you use it
This tool computes the cartesian product of input iterables.
It is equivalent to nested for-loops.
For example, product(A, B) returns the same as ((x,y) for x in A for y in B)
Use of any, all and global keyword and getattr()
any()
This expression returns True if any element of the iterable is true
all()
This expression returns True if all of the elements of the iterable are true. If the iterable is empty, it will return True.
getattr(obj, key, def):
Calling getattr(x, “foo”) is just another way to write x.foo
getattr(setA, command)(setB)
which means setA.command(SetB)
IMP: you cant simply use setA.command(SetB) as command is a variable that contains the actual command but compiler wont run it directly, using getattr is like using eval and it will take the value of the variable and not the variable name itself. So it will make it like:
setA.update(setB)
Also,getattr is a faster replacement for eval!
Input: 3 Mike Thomson 20 M Robert Bustle 32 M Andria Bustle 30 F Output: Mr. Mike Thomson Ms. Andria Bustle Mr. Robert Bustle This question is important from the perspective of decorators, sorted function and also the map function.
https://www.hackerrank.com/challenges/decorators-2-name-directory/problem
def person_lister(f): def inner(people): return map(f, sorted(people, key=lambda x: int(x[2]))) return inner
@person_lister def name_format(person): return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1]
if __name__ == ‘__main__’:
people = [input().split() for i in range(int(input()))]
print(*name_format(people), sep=’\n’)
Here decorator has been used to sort. The key points to note here are that sorted takes a key = a function, function can be a lambda or some other.
Another thing to note is that map also takes a function as an argument, the function here is our own defined function name_format which we passed as f. The map here will return the sorted values in a form of the f function(By passing the values through it).If we use int func in map, the values are passed through int().
Using - return sorted(people, key=lambda x: int(x[2])) returns:
[‘Mike’, ‘Thomson’, ‘20’, ‘M’]
[‘Andria’, ‘Bustle’, ‘30’, ‘F’]
[‘Robert’, ‘Bustle’, ‘32’, ‘M’]
But - return map(f, sorted(people, key=lambda x: int(x[2]))) returns: Mr. Mike Thomson Ms. Andria Bustle Mr. Robert Bustle
Because the first sorted returns lists, which are given to function f by map(): def name_format(list): return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1]
What is the diff between tuple and named tuple? Why use named tuple? Why is it better than dict?
It supports both access from key value and iteration. Use of named tuple to avoid class usage: class Container: def \_\_init\_\_(self, name, date, foo, bar): self.name = name self.date = date self.foo = foo self.bar = bar
mycontainer = Container(name, date, foo, bar)
and not change the attributes after you set them in __init__, you could instead use
Container = namedtuple(‘Container’, [‘name’, ‘date’, ‘foo’, ‘bar’])
mycontainer = Container(name, date, foo, bar)
mynamedtuple = MyNamedTuple(firstvalue, secondvalue)
is prettier than
mydict = {‘fieldname’: firstvalue, ‘secondfield’: secondvalue}
Finally, namedtuples are ordered, unlike regular dicts, so you get the items in the order you defined the fields in.
What do rpartition() do on a string? In our case string is the input : BANANA FRIES 12
item, space, quantity = input().rpartition(‘ ‘)
rpartition() function in Python split the given string into three parts. rpartition() start looking for separator from right side, till the separator is found and return a tuple which contains part of the string before separator(here item i.e BANANA FRIES), argument of the string(here space i.e ‘ ‘) and the part after the separator(here quantity i.e 12).
How iter() works? Describe its function when combined with zip!
> > > s=’abdefghi’
i=iter(s)
zip(i, i, i)
[(‘a’, ‘b’, ‘c’), (‘d’, ‘e’, ‘f’), (‘g’, ‘h’, ‘i’)]
When passing iterators, zip internally invokes the next on the subsequent passed iterators before combining them. Since here, the iterator is to the same list. Hence you get such an output. For example,
Output of (a, b, c) comes out like this:
>>next(i) # first iterator passed a >>next(i) # second iterator passed b >>next(i) # third iterator passed c