HackerRank-Python-Basic Flashcards

Revise Code

1
Q

Take Multiple Inputs in Single Line

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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

A

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])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

2D list like [[‘Harry’, 37.21], [‘Berry’, 37.21]….], Find names of second lowest scores.

A

sec = sorted(list(set([marks for name, marks in x])))[1]

y = sorted([name for name,marks in x if marks==sec])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Execute input strings as commands on a list li. Eg :insert 0 5, insert 1 10, insert 0 6, print

A

cmd = x[0]
args = x[1:]
cmd+=”(“+”,”.join(args)+”)”
eval(‘li.’+cmd)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Find the Number of times a sub string is repeated in string.

A

c = sum([1 for i in range(len(string)-len(sub_string)+1)

if string[i:i+len(sub_string)] == sub_string])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

how to add an element to a list and a set?

Other funcs of set?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to return the number of ints repeating for each int in a number. Eg- 11223333

A

Groupby(), returns (2,1) (2,2)(4,3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How lambda works?

A

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’)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Zip func, reduce func, filter func

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Sort a string as per demand, lowercase, then uppercase, then odd digits, then even.

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you solve the mountain pile up problem of 4 3 2 1 2 3 4

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to make a combination of a dict and a counter?

A
from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
    pass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a decorator?

A
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!")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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

A
n = int(input().strip())
check = {True: "Not Weird", False: "Weird"}
print(check[
        n%2==0 and (
            n in range(2,6) or 
            n > 20)
    ])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Print multiple results using a single print statement (format function)

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

print(‘{0} \n{1} \n{2}’.format((a + b), (a - b), (a * b)))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Without using any string methods, try to print the following 123….N in a single line code

A

print(*range(1, int(input())+1), sep=’’)

Range can also be printed, no need for comprehension

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Given a 2D list: [[Name,Score],[Name,Score]], print the name of a score x using * JOIN, * GENERATOR, *LIST

A

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

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.

A

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))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

what does itertool.product() does, where can you use it

A

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)

20
Q

Use of any, all and global keyword and getattr()

A

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!

21
Q
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

A
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]
22
Q

What is the diff between tuple and named tuple? Why use named tuple? Why is it better than dict?

A
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.

23
Q

What do rpartition() do on a string? In our case string is the input : BANANA FRIES 12

A

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).

24
Q

How iter() works? Describe its function when combined with zip!

A

> > > 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
25
Q

Write GENERATOR function and print first 5 even numbers.

A
def all_even():
    n = 0
    while True:  // required for generators
        yield n
        n += 2

my_gen = all_even() // create an object by calling func

# Generate the first 5 even numbers.
for i in range(5):
    print(next(my_gen))  // next is called on object and not func itself
26
Q

A single line code to convert a number n to a list of integers(its digits).

A

A = list(map(int, str(n)))

Map requires the second argument to be an iterable. A string is iterable but an int is not.

27
Q

How do you convert 0 to 1 and 1 to 0 without using conditionals like if else.

A

val = 1 - val

28
Q

what is map(f,list) equivalent to?

A

[f(x) for x in list]

29
Q

Find the sum of max of each row and max of each column.

A

x = sum[max(row) for row in matrix]
is equivalent to x = sum(map(max, matrix))
To find the max of each column, we use zip which is literally the transpose of the matrix i.e. the columns become rows. Once the columns become rows, we apply the same concept as above on those rows.
z = zip(*matrix)
x = sum(map(max,matrix))

so simply put:
sum(map(max,matrix)) + sum(map(max,zip(*matrix)))

30
Q

What is the difference between print(max(grid))
and print(*map(max, grid))
Your input
[[3,2,1],[4,6,5],[7,8,9]]

A

The simple max function returns the row which is max i.e. whose sum is max.
But the map function iterates over each row in the grid and then returns the max from that row.
Output
[7, 8, 9]
3 6 9

31
Q

Create a loop to find an index from a given start point. You can only go forward, if you reach the end of the array, start again from 0 index.

A

while i!=index
i = (i+1)%n
instead of using if-else and stuff, we divide i+1 by n and take the remainder. So if array length is 10, when i becomes 10, array[10] won’t exist, hence we take the remainder which is 0 and i becomes 0 and hence it rotates over the array!

32
Q

Find the first occurrence index of all numbers in a list.

A

for i,num in enumerate(nums):
first.setdefault(num,i)
if the key in dict first exists, it won’t be replaced and setdefault will simply return that value. But if the key doesn’t exist, it adds the num as key and i as value into the dict.

33
Q

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

A
tmp = bin(x ^ y)[2:]
        dist = 0
        for char in tmp:
            dist += int(char)
        return dist
34
Q

Will split return an error if the given char in split is not in string?

A

No it won’t return an error. You just need to make sure you are using the right number of variables to get the result. Eg- test.emailalex@leetcode.com
local_name =”“.join(local_name.split(‘+’)[0].split(‘.’))

35
Q

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

A
100110, its complement is 011001, the sum is 111111. So we only need get the min number large or equal to num, then do subtraction.        
        n = 0
        while (n < num) :
            n = (n << 1) | 1
        return n - num

find another number that is one bit left than num and do minus 1. e.g. 1000 (8) - 1 = 111 (7)
which will be the largest one in that bit-length, only having ‘1’s
i = 1
while i <= num:
i = i &laquo_space;1
return (i - 1) ^ num

36
Q

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Input:
s = “abcd”
t = “abcde”
Do it using bit manipulation!

A

code = 0
for ch in s + t:
code ^= ord(ch)
return chr(code)

37
Q

times = int(math.ceil(float(len(B)) / len(A)))

easy replacement for this?

A

times = -(-len(B) // len(A))

38
Q

When to use subset?
Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard.

Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]

A

line1, line2, line3 = set(‘qwertyuiop’), set(‘asdfghjkl’), set(‘zxcvbnm’)
ret = []
for word in words:
w = set(word.lower())
if w.issubset(line1) or w <= line2 or w <= line3:
ret.append(word)
return ret
We use subset here to avoid looping through one set. It would be like for every letter in w, is it in line1 or line2 or line3. Instead we use w.issubset(of whatever) to avoid looping through the elements of a set.

39
Q

Whats the trick to avoid too many if else condition checks? As happens in linked list cycle check:
https://leetcode.com/problems/linked-list-cycle/discuss/44494/Except-ionally-fast-Python

A
The "trick" is to not check all the time whether we have reached the end but to handle it via an exception. "Easier to ask for forgiveness than permission."
The algorithm is of course Tortoise and hare.
def hasCycle(self, head):
    try:
        slow = head
        fast = head.next
        while slow is not fast:
            slow = slow.next
            fast = fast.next.next
        return True
    except:
        return False
40
Q
def mergeTrees(self, t1, t2):
    if not t1 and not t2: return None
    ans = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))
    ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)
    ans.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)
    return ans

what do t1 and t1.left mean here?

A

I am using t1 and t1.left as a shortcut for t1.left if t1 is not None else None.

Here, “x and y” evaluates as follows: If x is truthy, then the expression evaluates as y. Otherwise, it evaluates as x.

When t1 is None, then None is falsy, and t1 and t1.left evaluates as t1 which is None.

When t1 is not None, then t1 is truthy, and t1 and t1.left evaluates as t1.left as desired.

This is a standard type of idiom similar to the “?” operator in other languages. I want t1.left if t1 exists, otherwise nothing.

Alternatively, I could use a more formal getattr operator: getattr(t1, ‘left’, None)

41
Q

How to combine two for loops into one? One for loop is direct and the other is reverse of the the same!

A

for i in list(range(n)) + list(range(n)[::-1]):

42
Q
Convert this code to one liner!
out = []
        for i in range(1,n+1):
            if i%3==0 and i%5==0:
                out.append('FizzBuzz')
            elif i%3==0:
                out.append('Fizz')
            elif i%5==0:
                out.append('Buzz')
            else:
                out.append(str(i))
        return out
A

return [‘Fizz’ * (not i % 3) + ‘Buzz’ * (not i % 5) or str(i) for i in range(1, n+1)]

43
Q

Can a function be used as the key in sorted func? Give example?

A
def key(c, phase={}):
            p = phase[c] = phase.get(c, 1) + 1
            return p, ord(c) * (-1)**p
        return ''.join(sorted(s, key=key))
44
Q

Get sign of a number x without using if else i.e. using algebra only.

A

s = (x > 0) - (x < 0)

45
Q

Convert if not nodea and not nodeb:
elif not node and nodeb:
elif not nodeb and nodea:
to a single line!

A
if not(x and y):
                return x is y