Problem Solving with Algorithms

반응형

갑자기 코딩인터뷰를 꼭 파이썬으로 봐야한다고 해서.. 파이썬을 리마인드 할수 있는 몇개의 사이트를 둘러봤다.

가장 먼저 생각나기도 했던, 이 사이트가 좋은것 같다.

www.interviewbit.com/invite/hail-29ad

 

사이트에서 제공하는 여러가지 무료 코스
프로그래밍 언어를 배울 수 있는 패스트 트랙


Level 1 : Basics of Python

Input and Output Easy 6 minutes
Variables and Types Easy 6 minutes
Arithmetic operators on Numbers Easy 6 minutes
Arithmetic operators on Strings Easy 3 minutes

 

Level 2 : Flow Control & Functions

Conditions and If-Else Easy 5 minutes
Loops and Jump statements Easy 8 minutes
Functions Easy 9 minutes

0!이 1이라는걸 잊고있었다.

#Return the factorial of the number N
def factorial(N):
    # Your code goes here
    if N<=1:
        return 1
    else:
        return N*factorial(N-1)

Level 3 : Strings

String Formatting Easy 14 minutes
String Operations Easy 6 minutes
String Validators Easy 20 minutes

 

def main():
    S = input()
    #Your code goes here
    ans  = [False, False, False, False, False]
    for c in S:
        ans[0] |= c.isalnum()
        ans[1] |= c.isalpha()
        ans[2] |= c.isdigit()
        ans[3] |= c.islower()
        ans[4] |= c.isupper()
    
    for answer in ans:
        print(answer)
        
    return 0

if __name__ == '__main__':
    main()

Level 4 : Containers & Classes

Lists Easy 5 minutes
Tuples Easy 7 minutes
Dictionary Easy 25 minutes
Sets Easy 7 minutes
Set operations Easy 17 minutes
Nested List Easy 8 minutes
List Comprehensions Easy 4 minutes
Classes and Objects Easy 6 minutes
Numpy Arrays Easy 5 minutes
  • List is a collection which is ordered and changeable. Allows duplicate members.

  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

  • Set is a collection which is unordered and unindexed. No duplicate members.

  • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

my_dict = {1 : 'Robin', 2 : 'Rahul', 3 : 'Aman'}
for x in my_dict:
    print(x)    # print 1 2 3

# values() method to return values of a dictionary
for x in my_dict.values():
    print(x)    # print 'Robin' 'Rahul' 'Aman'

# Loop through both keys and values, by using the items() method
for key, val in my_dict.items():
    print(key, val)
my_dict = {1 : 'Robin', 2 : 'Rahul', 3 : 'Aman'}
my_dict.pop(2) # Removes item with key 2 and value 'Rahul'
print(my_dict)

my_dict = {1 : 'Robin', 2 : 'Rahul', 3 : 'Aman'}
del my_dict[2] # Removes item with key 2 and value 'Rahul'
print(my_dict)

 

numpy 얼마나 쓰려나?

import numpy as np
def main():
    arr = [1, 3, 2, 2, 5, 3, 8, 2]
    
    # Convert the above array into ndarray
    arr = np.array(arr)
    
    print(type(arr))
    
    # Use where to find all the indexes of 2
    x = np.where(arr==2)
    
    print(x)
    return 0

if __name__ == '__main__':
    main()

Level 5 : Itertools & Collections

Itertools: Infinite Iterators Easy 38 minutes
Itertools: Combinatoric Iterators Easy 26 minutes
Itertools: Terminating Iterators Easy 12 minutes
Collections Module Tutorial Easy 47 minutes
Collections Module I Easy 23 minutes
Collections Module II Easy 56 minutes

 

Itertools: Infinite Iterators

BookmarkSuggest Edit

Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

Different types of iterators provided by this module are Infinite Iterators, Combinatoric iterators and Terminating iterators.

Infinite Iterators

Iterator in Python is any Python type that can be used with a ‘for in loop’. Python lists, tuples, dictionaries, and sets are all examples of inbuilt iterators. But it is not necessary that an iterator object has to exhaust, sometimes it can be infinite. Such type of iterators are known as Infinite iterators.

Python provides three types of infinite itertors:

count(start, step): This iterator starts printing from the “start” number and prints infinitely. If steps are mentioned, the numbers are skipped else step is 1 by default.
See the below example for its use with for in loop.

import itertools # for in loop for i in itertools.count(5, 5): if i == 35: break else: print(i, end =" ") # prints 5 10 15 20 25 30

cycle(iterable): This iterator prints all values in order from the passed container. It restarts printing from the beginning again when all elements are printed in a cyclic manner.

import itertools count = 0 # for in loop for i in itertools.cycle('AB'): if count > 7: break else: print(i, end = " ") count += 1 # prints A B A B A B A B

repeat(val, num): This iterator repeatedly prints the passed value infinite number of times. If the optional keyword num is mentioned, then it repeatedly prints num number of times.

import itertools # using repeat() to repeatedly print number print ("Printing the numbers repeatedly : ") print (list(itertools.repeat(25, 4))) # prints Printing the numbers repeatedly : [25, 25, 25, 25]

 

Try the following excercise in the editor below.

Perform the operations as described in the comments in the order given.

 

import itertools
def main():
    # print 1000 space separated integers starting from 1000 with common difference 500
    # 1000 1500 2000 2500 3000........
    count = 0
    for i in itertools.count(1000, 500):
        if count == 1000:
            break
        else:
            print(i, end = " ")
            count += 1
    print()
    
    # print all uppercase alphabets 15 times, printing from A-Z then repeating again
    # A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D........
    # There should be exactly one space after every character
    count = 0
    for i in itertools.cycle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):  
        if count == 15*26:  
            break
        else:  
            print(i, end = " ")  
            count += 1
    print()
    
    # print list of integers containing 1000 4's
    print (list(itertools.repeat(4, 1000)))

    return 0

if __name__ == '__main__':
    main()

중간에 프린트문 적어야 되는거랑 마지막에 1000, 4 아니고 4, 1000인거에서 삽질을..

Itertools: Combinatoric Iterators

BookmarkSuggest Edit

We had learnt about the Infinite Iterators. Now, we will look at the type of Combinatoric Iterators

Combinatoric Iterators

The recursive generators that are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products are called combinatoric iterators.

In Python there are 4 combinatoric iterators:

Product(): This tool computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions.
The output of this function are tuples in sorted order.

from itertools import product print(list(product([1, 2], repeat = 2))) # prints [(1, 1), (1, 2), (2, 1), (2, 2)] print(list(product([1, 2], '2'))) # prints [(1, '2'), (2, '2')] print(list(product('AB', [3, 4]))) # prints [('A', 3), ('A', 4), ('B', 3), ('B', 4)]

Permutations(): Permutations() as the name speaks for itself is used to generate all possible permutations of an iterable. All elements are treated as unique based on their position and not their values. This function takes an iterable and group_size, if the value of group_size is not specified or is equal to None then the value of group_size becomes length of the iterable.

from itertools import permutations print (list(permutations([1, 'InterviewBit'], 2))) # prints [(1, 'InterviewBit'), ('InterviewBit', 1)] print (list(permutations('AB'))) # prints [('A', 'B'), ('B', 'A')] print(list(permutations(range(3), 2))) # prints [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]

Combinations(): This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order.

from itertools import combinations print(list(combinations(['A', 2], 2))) # prints [('A', 2)] print(list(combinations('AB', 2))) # prints [('A', 'B')] print(list(combinations(range(2), 1))) # prints [(0,), (1,)]

Combinations_with_replacement(): This function returns a subsequence of length n from the elements of the iterable where n is the argument that the function takes determining the length of the subsequences generated by the function. Individual elements may repeat itself in combinations_with_replacement function.

from itertools import combinations_with_replacement print(list(combinations_with_replacement("AB", 2))) # prints [('A', 'A'), ('A', 'B'), ('B', 'B')] print(list(combinations_with_replacement([1, 2], 2))) # prints [(1, 1), (1, 2), (2, 2)] print(list(combinations_with_replacement(range(2), 1))) # prints [(0,), (1,)]

 

Try the following excercise in the editor below.

You are given a string S.
Your task is to print all possible permutations of size K of the string in lexicographic sorted order.

Constraints

1 <= K <= len(S) String S consist of lowercase letters.

Input Format

First line contains space separated input S and K.

Output Format

Print the permutations of the string S of size K on separate lines.

Example Input

one 2

Example Output

eo en ne no oe on

 

 

Collections Module Tutorial

BookmarkSuggest Edit

The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them.

Some of the built-in containers are Tuple, List, Dictionary, etc.
Some of the different containers provided by collections module are discussed below.

Counters

A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.

from collections import Counter

my_list = [1, 1, 2, 3, 4, 5, 3, 2, 3, 4, 2, 1, 2, 3] print Counter(my_list) # prints Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1}) print Counter(my_list).items() # prints [(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)] print Counter(my_list).keys() # prints [1, 2, 3, 4, 5] print Counter(myList).values() # prints [3, 4, 4, 2, 1]

DefaultDict

It’s similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn’t use a defaultdict you’d have to check to see if that key exists, and if it doesn’t, set it to what you want.

from collections import defaultdict

# Defining the dict

# When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.

d = defaultdict(int)

my_list = [1, 2, 3, 2, 4, 2, 4, 1, 2]

# Iterate through the list for keeping the count for i in my_list:

# The default value is 0 so there is no need to enter the key first d[i] += 1 print(d) # prints defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

OrderedDict

An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.

from collections import OrderedDict
# Dictionary 
d = {} 
d['b'] = 1 d['a'] = 2 d['c'] = 3 d['d'] = 4 
for key, value in d.items(): 
  print(key, value) 
# This can be printed in any order 
# OrderDictionary 
od = OrderedDict() 
od['b'] = 1 od['a'] = 2 od['c'] = 3 od['d'] = 4 
for key, value in od.items(): 
	print(key, value) 
# The order remains same as the key are inserted

ChainMap

A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries.

from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) print(c) # prints ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}) # Accessing Values using key name print(c['a']) # prints 1 # Accesing values using values() method print(c.values()) # prints ValuesView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})) # Accessing keys using keys() method print(c.keys()) # prints KeysView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}))

NamedTuple

Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of a tuple.

from collections import namedtuple Point = namedtuple('Point','x,y') pt1 = Point(1,2) pt2 = Point(3,4) dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y ) print(dot_product) # prints 11

 

Deque

Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to list with O(n) time complexity.

from collections import deque d = deque() d.append(1) print(d) # prints deque([1]) d.appendleft(2) print(d) # prints deque([2, 1]) d.clear() # empty the deque d.extend('1') print(d) # prints deque(['1']) d.extendleft('234') print(d) # prints deque(['4', '3', '2', '1']) print(d.count('1')) # prints 1 print(d.pop()) # prints '1' print(d) # prints deque(['4', '3', '2']) print(d.popleft()) # prints '4' print(d) # prints deque(['3', '2']) d.extend('7896') print(d) # prints deque(['3', '2', '7', '8', '9', '6']) d.remove('2') print(d) # prints deque(['3', '7', '8', '9', '6']) d.reverse() print(d) # prints deque(['6', '9', '8', '7', '3']) d.rotate(3) print(d) # prints deque(['8', '7', '3', '6', '9'])

Try the following example in the editor below.

You are given two list of lowercase characters A of length N and B of length M. For each ith character in B print space separated indices of all the occurence of B[i] in A in a new line.

If the character is not present in A, then print -1.
Considered index to be 0-based.

Example Input

A = ['a', 'a', 'b', 'a', 'b', 'c', 'x'] B = ['a', 'x', 'z']

Example Output

0 1 3 6 -1

 

 

출력부분에서 시간 엄청 뺐김 ㅠㅠ 밑에 answer과 mine 비교..

from collections import defaultdict  

def main():
    A = input().split()
    N = len(A)
    B = input().split()
    M = len(B)
    
    d = defaultdict(int)
    for i in A:
        d[i] += 1
    
    for b in B:
        if d[b] != 0:
            c = []
            # answer
            for i, a in enumerate(A):
                if a is b:
                    print(i, end=" ")
            print()
            # mine
            # for i, a in enumerate(A):
            #     if a is b:
            #         c.append(i)
            # print(*c)
        else:
            print(-1)
    
    return 0

if __name__ == '__main__':
    main()

 


Level 6 : Functionals & Regex

Python Functionals I Easy 16 minutes
Validating Email Address using Filter Easy 22 minutes
RegEx Easy 12 minutes
Validating Roman Numerals Easy 18 minutes
Validating Phone Numbers Medium 11 minutes
Exceptions Handling Easy 15 minutes

 

Let’s learn some new Python concepts!. Map, Filter, lambda and Reduce are paradigms of functional programming. They allow the programmer (you) to write simpler, shorter code, without neccessarily needing to bother about intricacies like loops and branching.

lambda

Lambda is a single expression anonymous function often used as an inline function. In simple words, it is a function that has only one line in its body. It proves very handy in functional and GUI programming.

sum = lambda a, b, c: a + b + c print(sum(1, 2, 3)) # prints 6

Map

The map() function executes a specified function for each item in iterables(as many as they are). The item is sent to the function as a parameter.

map(function, iterables)

Let’s say you are given a list of names, and you have to print a list that contains the length of each name.

print (list(map(len, ['Tina', 'Raj', 'Tom']))) # prints [4, 3, 3]

Filter

While map() passes each element in the iterable through a function and returns the result of all elements having passed through the function, filter(), first of all, requires the function to return boolean values (true or false) and then passes each element in the iterable through the function, “filtering” away those that are false.

filter(func, iterable)

Let’s see an example.

The following is a list (iterable) of the scores of 10 students in an exam. Let’s filter out those who passed with scores more than 75…using filter.

# Python 3 scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65] def is_A_student(score): return score > 75 over_75 = list(filter(is_A_student, scores)) print(over_75)

Reduce

reduce applies a function of two arguments cumulatively to the elements of an iterable, optionally starting with an initial argument.

Reduce is not in the __builtins__ module, so it needs to be imported as it resides in the functools module.

reduce(func, iterable[, initial])

Say you have a list, say [1,2,3] and you have to find its sum.

from functools import reduce print(reduce(lambda x, y : x + y,[1,2,3])) # prints 6

You can also define an initial value. If it is specified, the function will assume initial value as the value given, and then reduce. It is equivalent to adding the initial value at the beginning of the list.
For example:

from functools import reduce print(reduce(lambda x, y : x + y, [1,2,3], -3)) # prints 3 from fractions import gcd print(reduce(gcd, [2,4,8], 3)) # prints 1

Try the following excerise in the editor below.

In this exercise, you’ll use each of map, filter, and reduce to fix broken code.

 

from functools import reduce 
def main():
    
    # Use map to print the square of each numbers 
    my_ints = [4, 6, 3, 9, 2, 8, 12]
    
    # Use filter to print only the names that are less than or equal to seven letters
    my_names = ["scaler", "interviewbit", "rishabh", "student", "course"]
    
    # Use reduce to print the product of these numbers
    my_numbers = [4, 6, 9, 23, 5]
    
    # Fix all three respectively. 
    map_result = list(map(lambda x: x*x, my_ints))
    filter_result = list(filter(lambda name: len(name) <= 7, my_names))
    reduce_result = reduce(lambda num1, num2: num1 * num2, my_numbers, 1)
    
    print(map_result)
    print(filter_result)
    print(reduce_result)
    return 0

if __name__ == '__main__':
    main()

 

 

 

Validating Email Address using Filter

코인주고삼 ㅠㅠ(12/17) 내일 다시 풀어보기

def fun(s):
    try:
        user, www = s.split("@")
        web, ext = www.split(".")
        if not user or not web or not ext:
            return False
        return not any([user != "".join(filter(lambda x: x.isalnum() or x in ["_", "-"], user)),
            web != "".join(filter(lambda x: x.isalnum(), web)) , len(ext)>3])
    except:
        return False

def filter_mail(emails):
    return list(filter(fun, emails))

if __name__ == '__main__':
    n = int(input())
    emails = []
    for _ in range(n):
        emails.append(input())

filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)

 

레직스도 코인주고 사서 대충함..

위에 필요는 좀 알아야 될 필요가 있지 않나 싶다(12/18)

 

a/b 의 에러메시지 -> Error Code: division by zero

a//b의 에러메시지 -> Error Code: integer division or modulo by zero

def main():
    for i in range(int(input())):
        try:
            a,b = map(int, input().split())
            print (a//b)
        except ZeroDivisionError as e:
            print ('Error Code:',e)
        except ValueError as e:
            print ('Error Code:',e)
    return 0

if __name__ == '__main__':
    main()
반응형
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band