Advertisement
coachdarek

Untitled

May 7th, 2022
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. class Node:
  2.     def __init__(self,value=None,next=None):
  3.         self.value=value
  4.         self.next=next
  5.    
  6.     def print_list(self):
  7.         node=self
  8.         while node:
  9.             print(node.value)
  10.             node=node.next
  11.  
  12. class LinkedList:
  13.     def __init__(self, head):
  14.         self.head = head
  15.  
  16.     def print_list(self):
  17.        
  18.  
  19. # Write a function that returns a LinkedList given a Python list as input.
  20. # [4,1,5] -> (4) -> (1) -> (5) return the head of that list.
  21. # i,j,k are reserved for idices. E.g. for i in range(), for j in range()
  22. def linkedlist(lis):
  23.     head=Node(0,None)
  24.     temp=head
  25.     for num in lis:
  26.         temp.next=Node(num,None)
  27.         temp=temp.next
  28.     return  head.next
  29.  
  30. lis=[1,2,3]
  31. myList = linkedlist(lis)
  32. myList.print_list()
  33.  
  34. # Homework.
  35. # Write your own stack/queue using LinkedList nodes.
  36. # Deque (doubly ended queue).
  37.  
  38. # Given a list of N (x,y) coordiantes, return the k farthest from the origin.
  39. #heap_>until k elem_>just post smallest one
  40. import heapq
  41. def get_k_farthest(coordindates, k):
  42.     heap=[]
  43.     for x,y in coordindates:
  44.         heapq.heappush(heap,((x**2+y**2),(x,y)))#N log k N-> num of elem, k ->height
  45.         if len(heap)>k:
  46.             heapq.heappop(heap)
  47.     top_k=[]
  48.     for i in range(len(heap)):
  49.         top_k.append(heap[i][1])
  50.     return top_k
  51.  
  52. # O ( N  log N)
  53. def dareks_k_farthest(coordinates,k):
  54.     heap = []
  55.     # O(n log n)
  56.     for x,y in coordinates: # O(n)
  57.         heapq.heappush(heap, (-(x**2+y**2),(x,y))) # O(log n)
  58.  
  59.     top_k = []
  60.     # k log (n)
  61.     for i in range(k): # O(k)
  62.         dist, coord = heapq.heappop(heap) # O(log N)
  63.         top_k.append(coord)
  64.     return top_k
  65.  
  66.  
  67. # Given a list of numbers sort it.
  68. # If a number is divisible by 10, it should have highest prioriy.
  69. # To break ties, then you should take the larger number.
  70. # [900, 20, 1, 990,70,400,5,44] - input
  71. # [1, 5, 44, 20,,70, 400,900,990] - output
  72. # [20,900,
  73. #   i
  74.  
  75. def sortNumsLambda(nums):
  76.     nums.sort(key = lambda num: (num % 10 == 0, num))
  77.  
  78. def numKey(num):
  79.     return (num % 10 == 0, num)
  80.  
  81. def sortNums(nums):
  82.     nums.sort(key = numKey)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement