HackerRank-Python-Basic Flashcards
Revise Code
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))