본문 바로가기
Software Engineering

코딩테스트에 유용한 Python 코드조각들

by 엔지니어의 노트 2023. 1. 2.

 

List

  • flatten a nested list

https://stackoverflow.com/a/952952/7883783

# to flat the nested list 
flat_list = [item for sublist in l for item in sublist]
# shorter, but not efficient, not readable
flat = sum(nums, [])

 

  • creating a dictionary of Lists
from collections import defaultdict
 
lst = [('Geeks', 1), ('For', 2), ('Geeks', 3)]
orDict = defaultdict(list)
 
# iterating over list of tuples
for key, val in lst:
    orDict[key].append(val)

 

 

STRING

  • build hash map : character and how often it appears - collections.Counter(s)
from collections import Counter
s = 'abcccc'

count = collections.Counter(s)
print(count)
Counter({'c': 4, 'a': 1, 'b': 1})

 

 

#### DICT ####

# delete a key

del a['alice']

# loop key/val

for key, val in a.items():

# loop with val

for val in a.values():

# loop with key (order is random)

for key in a:

 

# adding dict with checking if the value is in there or not

if count_dic.get(i) is None:

       count_dic[i] = 1

   else:

       count_dic[i] += 1

# or

try:

       count_dic[i] += 1

   except KeyError:

       count_dic[i] = 1

 

 

 

####################

### Linked list ####

####################

# 1. reverse list - iteration

   prev = None   

   while head is not None:

       curr_head = head

       head = head.next # curr_head refers to the head. the same linked list classes.

       curr_head.next = prev

       prev = curr_head

   return prev

 

# 2. reverse list - recursive

# https://youtu.be/S92RuTtt9EE

   def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:

       if (not head) or (not head.next): # base condition - first thing in recursive

           return head

       p = self.reverseList(head.next)

       head.next.next = head

       head.next = None

       return p

반응형