├── .gitignore
├── Playwright.txt
├── __pycache__
└── array.cpython-37.pyc
├── array.py
├── assert.py
├── baseball-game.py
├── block.txt
├── break.py
├── bst.py
├── built-in-packages.py
├── continue.py
├── currencies.txt
├── data.pickle
├── dictionary-comprehension.py
├── dictionay.py
├── duplicateRecord.py
├── duplicateRecordCsv.py
├── duplicates.csv
├── exercise-1-10.py
├── fizzbuzz.py
├── for.py
├── functions.py
├── gaming.txt
├── generators.py
├── hackerrank.py
├── hash-tables.py
├── lamda-function.py
├── linked-list.py
├── list-comprehension.py
├── list.py
├── log.txt
├── no_duplicates.py
├── not_sent.py
├── num.txt
├── playway.csv
├── plw.txt
├── print.py
├── queue.py
├── read.py
├── recurrsion.py
├── replace_phone_num.py
├── sandbox.py
├── save.py
├── search.py
├── set-comprehension.py
├── sets.py
├── slicing.py
├── sort.py
├── stack.py
├── stocks.json
├── string.py
├── strings.py
├── summary.py
├── temp.py
├── test.py
├── test2.py
├── test3.py
├── trees.py
├── tuples.py
├── tx.py
├── users.csv
├── while.py
└── zip.py
/.gitignore:
--------------------------------------------------------------------------------
1 | nitda-total.csv
2 | nitda.csv
3 | test.py
4 | testing.csv
5 |
--------------------------------------------------------------------------------
/Playwright.txt:
--------------------------------------------------------------------------------
1 | Date,Open,High,Low,Close,Volume
2 | 2020-04-01,302,314,300,310,12940
3 | 2020-04-02,310,315,305,313,10311
4 | 2020-04-03,313,318.5,312,318,12372
--------------------------------------------------------------------------------
/__pycache__/array.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/calistus-igwilo/python/796f65dd6ebf29434481f7ddfce793910c42d8ca/__pycache__/array.cpython-37.pyc
--------------------------------------------------------------------------------
/array.py:
--------------------------------------------------------------------------------
1 | """
2 | You are given an array of integers in which each subsequent
3 | value is not less than previous value. Write a function that
4 | takes this array as an input and returns a new array with the
5 | squares of each number sorted in ascending order
6 | """
7 | from operator import truediv
8 |
9 |
10 | def square_num(arr):
11 | result = [num**2 for num in arr]
12 | result.sort()
13 | return result
14 |
15 | print(square_num([-4, -2, 1, 3, 4]))
16 |
17 | """
18 | An array is monotonic if it is either monotone increasing or monotone
19 | decreasing. An array is monotone increasing if all its elements from left
20 | to right are non-decreasing. An array is monotone decreasing if all its
21 | elements from left to right are non-increasing. Given an integer array
22 | return true if the given array is monotonic, or false otherwise.
23 | """
24 | def monotonic(arr):
25 | end = len(arr) - 1
26 | if len(arr) == 0 or len(arr) == 1:
27 | return True
28 | elif arr[0] > arr[end]:
29 | for i in range(end - 1):
30 | if arr[i] < arr[i+1]:
31 | return False
32 | elif arr[0] < arr[end]:
33 | for i in range(end-1):
34 | if arr[i] > arr[i+1]:
35 | return False
36 | elif arr[0] == arr[end]:
37 | for i in range(end-1):
38 | if i != i+1:
39 | return False
40 |
41 | return True
42 |
43 | print(monotonic([-2, 3, 6, 8]))
44 |
45 |
46 | """
47 | Rotate an array to the right by k elements
48 | """
49 | def rotate_array(arr, k):
50 | end = len(arr)-1
51 | if k <= 0:
52 | return arr
53 | for i in range(0, k, 1):
54 | #a, b = arr[0], arr[end]
55 | arr = [arr[end]] + [arr[0]] + arr[1:end]
56 | return arr
57 | print(rotate_array([1, 2, 3, 4], 4))
58 |
59 |
60 | """
61 | You are given an integer array height of length n. There are n vertical
62 | lines drawn such that the two endpoints of the nth line are (i,0) and
63 | (i, height[i]).
64 | Find two lines that together with the x-axis form a container, such that
65 | the container contains the most water (depth is constant across containers)
66 | Return the area (that the 2lines and the x axis make) of container which
67 | can store the max amount of water.
68 | Notice that you may not slant the container.
69 | """
70 | def max_area_brute(arr):
71 | end = len(arr)-2
72 | max_ = 0
73 | for i in range(end):
74 | for j in range(i+1, end+2):
75 | area = min(arr[i], arr[j]) * (j-i)
76 | if area > max_:
77 | max_ = area
78 | return max_
79 | # Note; the time complexity is O(n**2) since the array was traversed
80 | # twice. The space complexity is O(1) since no extra space was created
81 | print(max_area_brute([9,1,2,3,10]))
82 |
83 | def max_area_optimum(arr):
84 | end = len(arr)-1
85 | pointerLeft = 0
86 | pointerRight = end
87 | area = 0
88 | while pointerLeft < pointerRight:
89 | width = pointerRight - pointerLeft
90 | height = min(arr[pointerLeft], arr[pointerRight])
91 | newArea = width * height
92 | area = max(area, newArea)
93 | if arr[pointerLeft] < arr[pointerRight]:
94 | pointerLeft += 1
95 | else:
96 | pointerRight -= 1
97 | return area
98 | # Note: Time complexity for this is O(n) since the array was traversed
99 | # only once. Space complexity is O(1) since no extra space was created
100 | print(max_area_optimum([9,1,2,3,10]))
101 |
102 |
103 |
--------------------------------------------------------------------------------
/assert.py:
--------------------------------------------------------------------------------
1 | #######################
2 | # Asert
3 | #######################
4 | """
5 | Assert the is_italy variable using the assert statement
6 | """
7 | countries = ['POL', 'ENG', 'GER', 'USA', 'ITA']
8 | is_italy = 'ITA' in countries
9 |
10 | assert is_italy, f'ITA expected to be in the list of countries'
11 |
12 |
13 | """
14 | The implementation of the max_min_diff() function is given:
15 |
16 | def max_min_diff(numbers):
17 | # enter your solution here
18 | return max(numbers) - min(numbers)
19 |
20 | Modify the implementation of the max_min_diff() function. By using the
21 | assert statement inside this function, add the ability to check the
22 | length of the numbers arguement before retruning the result. If the
23 | length of the numbers object is 0 raise the AssertionErrorw without
24 | any message. Otherwise return the correct result.
25 |
26 | In response, call max_min_diff() function passin an empty list
27 | """
28 | def max_min_diff(numbers):
29 | assert len(numbers) != 0
30 | return max(numbers) - min(numbers)
31 | max_min_diff([])
32 |
33 |
34 | """
35 | The following area() function is given, which returns the area of a
36 | rectangle (no argument validation).
37 |
38 | def area(width, height):
39 | return width * height
40 | Assert the following funtion calls:
41 | area(4, 10)
42 | area(5, 6)
43 | with the appropriate values:
44 | 40
45 | 30
46 | """
47 | def area(width, height):
48 | return width * height
49 |
50 | assert area(4, 10) == 40
51 | assert area(5, 6) == 30
52 |
53 |
54 | """
55 | The following area function is given which returns the area of a
56 | rectangle with additional argument validation:
57 |
58 | def area(width, height):
59 | '''The function returns the area of the rectangle.'''
60 |
61 | if not (isinstance(width, int) and isinstance(height, int)):
62 | raise TypeError('The width and height must be of type int.')
63 |
64 | if not (width > 0 and height > 0):
65 | raise ValueError('The width and height must be positive.')
66 |
67 | return width * height
68 |
69 | Assert the following function call:
70 | area('5', '4')
71 | with value of 20
72 | """
73 | def area(width, height):
74 | """The function returns the area of the rectangle."""
75 |
76 | if not (isinstance(width, int) and isinstance(height, int)):
77 | raise TypeError('The width and height must be of type int.')
78 |
79 | if not (width > 0 and height > 0):
80 | raise ValueError('The width and height must be positive.')
81 |
82 | return width * height
83 |
84 | assert area('5', '4') == 20
85 |
86 | area('5', '4')
87 |
--------------------------------------------------------------------------------
/baseball-game.py:
--------------------------------------------------------------------------------
1 | # Baseball Game
2 |
3 |
4 | def baseball_game(ops):
5 | '''
6 | You are keeping score for a baseball game with strange rules.
7 | The game consists of several rounds, where the scores of past rounds
8 | may affect future rounds' scores.
9 |
10 | At the beginning of the game, you start with an empty record.
11 | You are given a list of strings ops, where ops[i] is the ith operation
12 | you must apply to the record and is one of the following:
13 |
14 | An integer x - Record a new score of x.
15 |
16 | "+" - Record a new score that is the sum of the previous two scores.
17 | It is guaranteed there will always be two previous scores.
18 |
19 | "D" - Record a new score that is double the previous score.
20 | It is guaranteed there will always be a previous score.
21 |
22 | "C" - Invalidate the previous score, removing it from the record.
23 | It is guaranteed there will always be a previous score.
24 |
25 | '''
26 | #ops = ["5", "2", "C", "D", "+"]
27 | result = []
28 | for n in ops:
29 | if n == "+":
30 | result.append(result[-1] + result[-2])
31 | elif n == "D":
32 | result.append(2 * result[-1])
33 | elif n == "C":
34 | result.pop()
35 | else:
36 | result.append(int(n))
37 | return sum(result)
38 |
39 | print(baseball_game(["5", "2", "C", "D", "+"]))
40 |
41 |
42 |
--------------------------------------------------------------------------------
/block.txt:
--------------------------------------------------------------------------------
1 | {
2 | "hash" : "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
3 | "confirmations" : 308321,
4 | "size" : 285,
5 | "height" : 0,
6 | "version" : 1,
7 | "merkleroot" : "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
8 | "tx" : [
9 | "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
10 | ],
11 | "time" : 1231006505,
12 | "nonce" : 2083236893,
13 | "bits" : "1d00ffff",
14 | "difficulty" : 1.00000000,
15 | "nextblockhash" : "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
16 | }
--------------------------------------------------------------------------------
/break.py:
--------------------------------------------------------------------------------
1 | """
2 | Write a program that compares two lists and returns True if the list
3 | contains at least one of the same element. Otherwise, it will return
4 | False.
5 | Use break statement in the solution and print result to the console
6 | List:
7 | list1 = [1, 2, 0]
8 | list2 = [4, 5, 6, 1]
9 | """
10 | list1 = [1, 2, 0]
11 | list2 = [4, 5, 6, 1]
12 |
13 | result = False
14 | for item1 in list1:
15 | if item1 in list2:
16 | result = True
17 | break
18 | print(result)
19 |
20 |
21 | """
22 | The following list of hashtags is given:
23 |
24 | hashtags = ['holiday', 'sport', 'fit', None, 'fashion']
25 | Check if all object in the list are of str type. If so, print True,
26 | otherwise print False. Use the break statement in the solution
27 | """
28 | hashtags = ['holiday', 'sport', 'fit', None, 'fashion']
29 | result = True
30 | for item in hashtags:
31 | if not type(item) == str: # if not isinstance(item, str):
32 | result = False
33 | break
34 | print(result)
35 |
36 |
37 | """
38 | Write a program that checks if the given number is a prime number
39 | (use the break statement)
40 | number = 13
41 | Print one of the following to the console depending on the result
42 | 13 - prime number
43 | 13 - not a prime number
44 |
45 | Expected result
46 | 13 - prime number
47 | """
48 | number = 13
49 | if number > 1:
50 | for i in range(2, number):
51 | if number% i == 0:
52 | print(f'{number} - not a prime number')
53 | break
54 | else:
55 | print(f'{number} - prime number')
--------------------------------------------------------------------------------
/bst.py:
--------------------------------------------------------------------------------
1 | # # # Binary search tree
2 | class binarySearchTree:
3 | def __init__(self,val=None):
4 | self.val = val
5 | self.left = None
6 | self.right = None
7 |
8 | def insert(self,val):
9 | # check if there is no root
10 | if (self.val == None):
11 | self.val = val
12 | # check where to insert
13 | else:
14 | # check for duplicate then stop and return
15 | if val == self.val: return 'no duplicates aloowed in binary search tree'
16 | # check if value to be inserted < currentNode's value
17 | if (val < self.val):
18 | # check if there is a left node to currentNode if true then recurse
19 | if(self.left):
20 | self.left.insert(val)
21 | # insert where left of currentNode when currentNode.left=None
22 | else: self.left = binarySearchTree(val)
23 |
24 | # same steps as above here the condition we check is value to be inserted > currentNode's value
25 | else:
26 | if(self.right):
27 | self.right.insert(val)
28 | else: self.right = binarySearchTree(val)
29 |
30 |
31 |
32 |
33 | def breadthFirstSearch(self):
34 | currentNode = self
35 | bfs_list = []
36 | queue = []
37 | queue.insert(0,currentNode)
38 | while(len(queue) > 0):
39 | currentNode = queue.pop()
40 | bfs_list.append(currentNode.val)
41 | if(currentNode.left):
42 | queue.insert(0,currentNode.left)
43 | if(currentNode.right):
44 | queue.insert(0,currentNode.right)
45 |
46 | return bfs_list
47 |
48 | # In order means first left child, then parent, at last right child
49 | def depthFirstSearch_INorder(self):
50 | return self.traverseInOrder([])
51 |
52 | # Pre order means first parent, then left child, at last right child
53 | def depthFirstSearch_PREorder(self):
54 | return self.traversePreOrder([])
55 |
56 | # Post order means first left child, then right child , at last parent
57 | def depthFirstSearch_POSTorder(self):
58 | return self.traversePostOrder([])
59 |
60 | def traverseInOrder(self, lst):
61 | if (self.left):
62 | self.left.traverseInOrder(lst)
63 | lst.append(self.val)
64 | if (self.right):
65 | self.right.traverseInOrder(lst)
66 | return lst
67 |
68 | def traversePreOrder(self, lst):
69 | lst.append(self.val)
70 | if (self.left):
71 | self.left.traversePreOrder(lst)
72 | if (self.right):
73 | self.right.traversePreOrder(lst)
74 | return lst
75 |
76 | def traversePostOrder(self, lst):
77 | if (self.left):
78 | self.left.traversePostOrder(lst)
79 | if (self.right):
80 | self.right.traversePostOrder(lst)
81 | lst.append(self.val)
82 | return lst
83 |
84 | def findNodeAndItsParent(self,val, parent = None):
85 | # returning the node and its parent so we can delete the node and reconstruct the tree from its parent
86 | if val == self.val: return self, parent
87 | if (val < self.val):
88 | if (self.left):
89 | return self.left.findNodeAndItsParent(val, self)
90 | else: return 'Not found'
91 | else:
92 | if (self.right):
93 | return self.right.findNodeAndItsParent(val, self)
94 | else: return 'Not found'
95 |
96 | # deleteing a node means we have to rearrange some part of the tree
97 | def delete(self,val):
98 | # check if the value we want to delete is in the tree
99 | if(self.findNodeAndItsParent(val)=='Not found'): return 'Node is not in tree'
100 | # we get the node we want to delete and its parent-node from findNodeAndItsParent method
101 | deleteing_node, parent_node = self.findNodeAndItsParent(val)
102 | # check how many children nodes does the node we are going to delete have by traversePreOrder from the deleteing_node
103 | nodes_effected = deleteing_node.traversePreOrder([])
104 | # if len(nodes_effected)==1 means, the node to be deleted doesn't have any children
105 | # so we can just check from its parent node the position(left or right) of node we want to delete
106 | # and point the position to 'None' i.e node is deleted
107 | if (len(nodes_effected)==1):
108 | if (parent_node.left.val == deleteing_node.val) : parent_node.left = None
109 | else: parent_node.right = None
110 | return 'Succesfully deleted'
111 | # if len(nodes_effected) > 1 which means the node we are going to delete has 'children',
112 | # so the tree must be rearranged from the deleteing_node
113 | else:
114 | # if the node we want to delete doesn't have any parent means the node to be deleted is 'root' node
115 | if (parent_node == None):
116 | nodes_effected.remove(deleteing_node.val)
117 | # make the 'root' nodee i.e self value,left,right to None,
118 | # this means we need to implement a new tree again without the delted node
119 | self.left = None
120 | self.right = None
121 | self.val = None
122 | # construction of new tree
123 | for node in nodes_effected:
124 | self.insert(node)
125 | return 'Succesfully deleted'
126 |
127 | # if the node we want to delete has a parent
128 | # traverse from parent_node
129 | nodes_effected = parent_node.traversePreOrder([])
130 | # deleting the node
131 | if (parent_node.left == deleteing_node) : parent_node.left = None
132 | else: parent_node.right = None
133 | # removeing the parent_node, deleteing_node and inserting the nodes_effected in the tree
134 | nodes_effected.remove(deleteing_node.val)
135 | nodes_effected.remove(parent_node.val)
136 | for node in nodes_effected:
137 | self.insert(node)
138 |
139 | return 'Successfully deleted'
140 |
141 |
142 | bst = binarySearchTree()
143 | bst.insert(7)
144 | bst.insert(4)
145 | bst.insert(9)
146 | bst.insert(0)
147 | bst.insert(5)
148 | bst.insert(8)
149 | bst.insert(13)
150 |
151 | # 7
152 | # / \
153 | # / \
154 | # 4 9
155 | # / \ / \
156 | # 0 5 8 13
157 |
158 |
159 | print('IN order: ',bst.depthFirstSearch_INorder()) # useful in sorting the tree in ascending order
160 | print('PRE order:' ,bst.depthFirstSearch_PREorder()) # pre order is useful in reconstructing a tree
161 | print('POST order:', bst.depthFirstSearch_POSTorder()) # useful in finding the leaf nodes
162 |
163 | print(bst.delete(5))
164 | print(bst.delete(9))
165 | print(bst.delete(7))
166 |
167 | # after deleting
168 | print('IN order: ',bst.depthFirstSearch_INorder())
169 |
170 |
171 |
172 |
173 | """
174 | Another Implementation
175 | """
176 | class GFG :
177 | @staticmethod
178 | def main( args) :
179 | tree = BST()
180 | tree.insert(30)
181 | tree.insert(50)
182 | tree.insert(15)
183 | tree.insert(20)
184 | tree.insert(10)
185 | tree.insert(40)
186 | tree.insert(60)
187 | tree.inorder()
188 | class Node :
189 | left = None
190 | val = 0
191 | right = None
192 | def __init__(self, val) :
193 | self.val = val
194 | class BST :
195 | root = None
196 | def insert(self, key) :
197 | node = Node(key)
198 | if (self.root == None) :
199 | self.root = node
200 | return
201 | prev = None
202 | temp = self.root
203 | while (temp != None) :
204 | if (temp.val > key) :
205 | prev = temp
206 | temp = temp.left
207 | elif(temp.val < key) :
208 | prev = temp
209 | temp = temp.right
210 | if (prev.val > key) :
211 | prev.left = node
212 | else :
213 | prev.right = node
214 | def inorder(self) :
215 | temp = self.root
216 | stack = []
217 | while (temp != None or not (len(stack) == 0)) :
218 | if (temp != None) :
219 | stack.append(temp)
220 | temp = temp.left
221 | else :
222 | temp = stack.pop()
223 | print(str(temp.val) + " ", end ="")
224 | temp = temp.right
225 |
226 | if __name__=="__main__":
227 | GFG.main([])
228 |
229 | # This code is contributed by rastogik346.
230 |
--------------------------------------------------------------------------------
/built-in-packages.py:
--------------------------------------------------------------------------------
1 | """
2 | Print the calendar for 2020 to the console using the calendar built-in module
3 |
4 | Expected result:
5 |
6 | 2020
7 |
8 | January February March
9 | Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
10 | 1 2 3 4 5 1 2 1
11 | 6 7 8 9 10 11 12 3 4 5 6 7 8 9 2 3 4 5 6 7 8
12 | 13 14 15 16 17 18 19 10 11 12 13 14 15 16 9 10 11 12 13 14 15
13 | 20 21 22 23 24 25 26 17 18 19 20 21 22 23 16 17 18 19 20 21 22
14 | 27 28 29 30 31 24 25 26 27 28 29 23 24 25 26 27 28 29
15 | 30 31
16 |
17 | April May June
18 | Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
19 | 1 2 3 4 5 1 2 3 1 2 3 4 5 6 7
20 | 6 7 8 9 10 11 12 4 5 6 7 8 9 10 8 9 10 11 12 13 14
21 | 13 14 15 16 17 18 19 11 12 13 14 15 16 17 15 16 17 18 19 20 21
22 | 20 21 22 23 24 25 26 18 19 20 21 22 23 24 22 23 24 25 26 27 28
23 | 27 28 29 30 25 26 27 28 29 30 31 29 30
24 |
25 | July August September
26 | Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
27 | 1 2 3 4 5 1 2 1 2 3 4 5 6
28 | 6 7 8 9 10 11 12 3 4 5 6 7 8 9 7 8 9 10 11 12 13
29 | 13 14 15 16 17 18 19 10 11 12 13 14 15 16 14 15 16 17 18 19 20
30 | 20 21 22 23 24 25 26 17 18 19 20 21 22 23 21 22 23 24 25 26 27
31 | 27 28 29 30 31 24 25 26 27 28 29 30 28 29 30
32 | 31
33 |
34 | October November December
35 | Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
36 | 1 2 3 4 1 1 2 3 4 5 6
37 | 5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13
38 | 12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20
39 | 19 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 27
40 | 26 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31
41 | """
42 | import calendar
43 | from datetime import datetime
44 | print(calendar.calendar(2020))
45 |
46 |
47 | """
48 | Using the datetime built-in module, calculate the difference for dates (date 2 - date 1)
49 |
50 | date 1: 2020-06-01
51 | date 2: 2020-07-18
52 | """
53 | from datetime import date
54 | date1 = date(2020,6,1)
55 | date2 = date(2020,7,18)
56 | diff = date2 - date1
57 | print(diff)
58 |
59 |
60 | """
61 | Using the built-module for regular expressions, find all digits in the following list:
62 | string = 'Python 3.8'
63 | Print result to the console
64 | Tip: Use the findall() function and the regular expression '\d'
65 |
66 | Expected reault:
67 | ['3', '8']
68 | """
69 | import re
70 |
71 | string = 'Python 3.8'
72 | #result = re.findall(r"/d", string)
73 | result = re.findall(pattern=r"\d", string=string)
74 | print(result)
75 |
76 |
77 | """
78 | Using the built=in module for regular expressions, find all alphanumeric characters
79 | in the following text
80 | string = '!@#$%^&45wc'
81 | Print the result to the console.
82 |
83 | Tip: Use the findall() function and the regular expression '\w'
84 |
85 | Expected result:
86 | ['4', '5', 'w', 'c']
87 | """
88 | string = '!@#$%^&45wc'
89 | result = re.findall(pattern=r"\w", string=string)
90 | print(result)
91 |
92 |
93 | """
94 | Use the built-in module for the regular expressions, find all email addresses in
95 | the following text:
96 | raw_text = "Send an email to info@template.com or sales-info@template.it"
97 | Print the result to the console
98 |
99 | Tip: Use the findall() function and the regular expression '[\w\.-]+@[\w\.-]+'
100 |
101 | Expected result:
102 |
103 | """
104 | raw_text = "Send an email to info@template.com or sales-info@template.it"
105 | result = re.findall(pattern=r'[\w\.-]+@[\w\.-]+', string=raw_text)
106 | print(result)
107 |
108 |
109 | """
110 | Using the built-in module for regular expressions, split the following text by
111 | whitespace (spaces):
112 | text = 'Programming in Python - from A to Z'
113 | Print the result to the console
114 |
115 | Tip: Use the re.split() function and the regular expression '\s+'
116 | """
117 | text = 'Programming in Python - from A to Z'
118 | result = re.split(pattern=r'\s+', string=text)
119 | print(result)
120 |
121 |
122 | """
123 | Using the string built-in module, print a string of lowercase and uppercase letters
124 | to the console
125 | """
126 | import string
127 |
128 | print(string.ascii_letters)
129 |
130 |
131 | """
132 | Using the collections built-in package, create a Counter class object that counts the
133 | frequency of items in the following list:
134 | items = ['YES', 'NO', 'NO', 'YES', 'EMPTY', 'YES', 'NO']
135 | """
136 | from collections import Counter
137 | counter = Counter()
138 | items = ['YES', 'NO', 'NO', 'YES', 'EMPTY', 'YES', 'NO']
139 | for item in items:
140 | counter[item] += 1
141 | print(counter)
142 |
143 |
144 | """
145 | Using the random built-in module set the random seed as follows:
146 | random.seed(12)
147 | And select randomly [pseudo-random] an item from the list below
148 | items = ['python', 'java', 'sql', 'c++', 'c']
149 | """
150 | import random
151 |
152 | random.seed(12)
153 |
154 | items = ['python', 'java', 'sql', 'c++', 'c']
155 | choice = random.choice(items)
156 | print(choice)
157 |
158 |
159 | """
160 | Using the random built-in module set the random seed as follows:
161 | random.seed(15)
162 | And shuffle (pseudo-randomly) items in the follwing list;
163 | items = ['python', 'java', 'sql', 'c++', 'c']
164 | In response, print the list to the console
165 | """
166 | random.seed(15)
167 |
168 | items = ['python', 'java', 'sql', 'c++', 'c']
169 | random.shuffle(items)
170 | print(items)
171 |
172 |
173 | """
174 | Using the pickle built-in module, save the follwoing list tothe data.pickle file.
175 | ids = ['001', '003', '011']
176 | """
177 | import pickle
178 |
179 | ids = ['001', '003', '011']
180 | with open('data.pickle', 'wb') as file:
181 | pickle.dump(ids, file)
182 |
183 |
184 | """
185 | Using the json package, dump the follwoing dictionary:
186 | stocks = {'PLW': 360.0, 'TEN': 320.0, 'CDR': 329.0}
187 | to the string, sorted by keys with indent 4. Print the result to the console
188 | """
189 | import json
190 |
191 | stocks = {'PLW': 360.0, 'TEN': 320.0, 'CDR': 329.0}
192 | result = json.dumps(stocks, sort_keys=True, indent=4)
193 | print(result)
194 |
--------------------------------------------------------------------------------
/continue.py:
--------------------------------------------------------------------------------
1 | """
2 | The list of companies from the WIG.GAMES index is given with the closing
3 | price and currency:
4 |
5 | gaming = {
6 | '11B': [362.5, 'PLN'],
7 | 'CDR': [74.25, 'USD'],
8 | 'CIG': [0.85, 'PLN'],
9 | 'PLW': [79.5, 'USD'],
10 | 'TEN': [300.0, 'PLN']
11 | Using the continue statement, create a for loop that will change the
12 | closing price from USD to PLN in the dictionary. Take USDPLN = 4.0
13 |
14 | Expected result
15 | {'11B': [362.5, 'PLN'], 'CDR': [297.0, 'PLN'], 'CIG': [0.85, 'PLN'], 'PLW': [318.0, 'PLN'], 'TEN': [300.0, 'PLN']}
16 | """
17 | gaming = {
18 | '11B': [362.5, 'PLN'],
19 | 'CDR': [74.25, 'USD'],
20 | 'CIG': [0.85, 'PLN'],
21 | 'PLW': [79.5, 'USD'],
22 | 'TEN': [300.0, 'PLN']
23 | }
24 | for ticker, info in gaming.items():
25 | if info[1] == 'PLN':
26 | continue
27 | info[0] *= 4.0
28 | info[1] = 'PLN'
29 | print(gaming)
30 |
31 |
32 | """
33 | The list of names is given (one missing):
34 | names = ['Jack', 'Leon', 'Alice', None, 'Bob']
35 | Using the continue statement, print only the correct names to the
36 | console as shown below
37 |
38 | Expected result:
39 | Jack
40 | Leon
41 | Alice
42 | Bob
43 | """
44 | names = ['Jack', 'Leon', 'Alice', None, 'Bob']
45 | for name in names:
46 | if name is None:
47 | continue
48 | print(name)
--------------------------------------------------------------------------------
/currencies.txt:
--------------------------------------------------------------------------------
1 | ARSAUD
2 | ARSBGN
3 | ARSBRL
4 | ARSBTC
5 | ARSCAD
6 | ARSCHF
7 | ARSCLP
8 | ARSCNY
9 | ARSCZK
10 | ARSDKK
11 | ARSEGP
12 | ARSEUR
13 | ARSGBP
14 | ARSHKD
15 | ARSHRK
16 | ARSHUF
17 | ARSIDR
18 | ARSILS
19 | ARSINR
20 | ARSISK
21 | ARSJPY
22 | ARSKRW
23 | ARSMXN
24 | ARSMYR
25 | ARSNAD
26 | ARSNOK
27 | ARSNZD
28 | ARSPHP
29 | ARSPLN
30 | ARSRON
31 | ARSRUB
32 | ARSSEK
33 | ARSSGD
34 | ARSTHB
35 | ARSTRY
36 | ARSTWD
37 | ARSUAH
38 | ARSUSD
39 | ARSXAG
40 | ARSXAU
41 | ARSXDR
42 | ARSXPD
43 | ARSXPT
44 | ARSZAR
45 | AUDARS
46 | AUDBGN
47 | AUDBRL
48 | AUDBTC
49 | AUDCAD
50 | AUDCHF
51 | AUDCLP
52 | AUDCNY
53 | AUDCZK
54 | AUDDKK
55 | AUDEGP
56 | AUDEUR
57 | AUDGBP
58 | AUDHKD
59 | AUDHRK
60 | AUDHUF
61 | AUDIDR
62 | AUDILS
63 | AUDINR
64 | AUDISK
65 | AUDJPY
66 | AUDKRW
67 | AUDMXN
68 | AUDMYR
69 | AUDNAD
70 | AUDNOK
71 | AUDNZD
72 | AUDPHP
73 | AUDPLN
74 | AUDRON
75 | AUDRUB
76 | AUDSEK
77 | AUDSGD
78 | AUDTHB
79 | AUDTRY
80 | AUDTWD
81 | AUDUAH
82 | AUDUSD
83 | AUDXAG
84 | AUDXAU
85 | AUDXDR
86 | AUDXPD
87 | AUDXPT
88 | AUDZAR
89 | BGNARS
90 | BGNAUD
91 | BGNBRL
92 | BGNBTC
93 | BGNCAD
94 | BGNCHF
95 | BGNCLP
96 | BGNCNY
97 | BGNCZK
98 | BGNDKK
99 | BGNEGP
100 | BGNEUR
101 |
--------------------------------------------------------------------------------
/data.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/calistus-igwilo/python/796f65dd6ebf29434481f7ddfce793910c42d8ca/data.pickle
--------------------------------------------------------------------------------
/dictionary-comprehension.py:
--------------------------------------------------------------------------------
1 | """
2 | Using dict comprehension, create a dictionary that maps the numbers 1 to 7 into squares
3 | and print the result to the console
4 |
5 | Expeted result:
6 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
7 | """
8 | from pickle import NONE
9 |
10 |
11 | result = {num:num**2 for num in range(1, 8)}
12 | print(result)
13 |
14 |
15 | """
16 | The following list is given:
17 | stocks = ['Playway', 'CD Projekt', 'Boombit']
18 | Use dict comprehension to build a dictionary that maps company names to the number of
19 | characters of its name and print the result to the console.
20 | stocks = ['Playway', 'CD Projekt', 'Boombit']
21 |
22 | Expected result:
23 | 'Playway': 7, 'CD Projekt': 10, 'Boombit': 7}
24 | """
25 | stocks = ['Playway', 'CD Projekt', 'Boombit']
26 | result = {name:len(name) for name in stocks}
27 | print(result)
28 |
29 |
30 | """
31 | The following dictionary is given:
32 | stocks = {'Boombit': '001', 'CD Projekt': '002', 'Playway': '003'}
33 | Use dict comprehension to replace values with keys and print the result to console
34 |
35 | Expected result:
36 | {'001': 'Boombit', '002': 'CD Projekt', '003': 'Playway'}
37 | """
38 | stocks = {'Boombit': '001', 'CD Projekt': '002', 'Playway': '003'}
39 | result = {value:key for key, value in stocks.items()}
40 | print(result)
41 |
42 |
43 | """
44 | The following dictionary is given:
45 | stocks = {'Boombit': 22, 'CD Projekt': 295, 'Playway': 350}
46 | using dict comprehension extract a key:value pair from the dictionary with a value
47 | greater than 100 and print the result to the console
48 |
49 | Expected result:
50 | {'CD Projekt': 295, 'Playway': 350}
51 | """
52 | stocks = {'Boombit': 22, 'CD Projekt': 295, 'Playway': 350}
53 | result = {key:value for key, value in stocks.items() if value > 100}
54 | print(result)
55 |
56 |
57 | """
58 | Create a list consisting of dictionaries mapping consecutive digits from 1 to 9
59 | inclusive to their respective k-th powers, for k = 1,2,3
60 |
61 | Print result to the console as shown below
62 |
63 | Formated output:
64 | [{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9},
65 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81},
66 | {1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}]
67 | """
68 | result = [{i:i**j for i in range(1,10)} for j in range(1, 4)]
69 | print(result)
70 |
71 |
72 | """
73 | The following list of indexes is given:
74 | indeks = ['WIG20', 'mWIG40', 'sWIG80']
75 | and a list of properties for each index:
76 | properties = ['number of companies', 'companies', 'cap']
77 | Use dict comprehension to create the follwoing dictionary:
78 |
79 | {'WIG20': {'number of companies': None, 'companies': None, 'cap': None},
80 | 'mWIG40': {'number of companies': None, 'companies': None, 'cap': None},
81 | 'sWIG80': {'number of companies': None, 'companies': None, 'cap': None}}
82 |
83 | Set the default value in each property to None and print the result to console.
84 | """
85 | properties = ['number of companies', 'companies', 'cap']
86 | indeks = ['WIG20', 'mWIG40', 'sWIG80']
87 |
88 | result = {ind: {prop: None for prop in properties} for ind in indeks}
89 | print(result)
90 |
91 |
92 | """
93 | The following is given:
94 | indexes = ['WIG20', 'mWIG40', 'sWIG80']
95 | Using dict comprehension, convert the above list into the following dictionary:
96 | {0: 'WIG20', 1: 'mWIG40', 2: 'sWIG80'}
97 | Print resutl to console
98 | """
99 | indexes = ['WIG20', 'mWIG40', 'sWIG80']
100 | result = {key: val for key, val in enumerate(indexes) }
101 | print(result)
102 |
--------------------------------------------------------------------------------
/dictionay.py:
--------------------------------------------------------------------------------
1 | """
2 | Create a dictionary from the following pairs (key, value):
3 | 'USA': 'Washington'
4 | 'Germany': 'Berlin'
5 | 'Austria': 'Vienna'
6 | and print to the console
7 | """
8 |
9 | from ast import Delete
10 |
11 |
12 | dict = {'USA': 'Washington', 'Germany': 'Berlin', 'Austria': 'Vienna'}
13 | print(dict)
14 |
15 |
16 | """
17 | The following dictionary is given:
18 |
19 | capitals = {
20 | 'USA': 'Washington',
21 | 'Germany': 'Berlin',
22 | 'Austria': 'Vienna'
23 | }
24 |
25 | Use the appropriate method to extract all keys from the capitals
26 |
27 | Expected result:
28 | dict_keys(['USA', 'Germany', 'Austria'])
29 | """
30 |
31 | capitals = {
32 | 'USA': 'Washington',
33 | 'Germany': 'Berlin',
34 | 'Austria': 'Vienna'
35 | }
36 | dict_keys = capitals.keys()
37 | print(dict_keys)
38 |
39 |
40 | """
41 | The following dictonary is given:
42 |
43 | capitals = {
44 | 'USA': 'Washington',
45 | 'Germany': 'Berlin',
46 | 'Austria': 'Vienna'
47 | }
48 | Using appropriate method, extract the list containing tuple
49 | objects(key,value) from the capitoals dictionary and print to console
50 |
51 | Expected result:
52 | dict_items([('USA', 'Washington'), ('Germany', 'Berlin'), ('Austria', 'Vienna')])
53 | """
54 |
55 | capitals = {
56 | 'USA': 'Washington',
57 | 'Germany': 'Berlin',
58 | 'Austria': 'Vienna'
59 | }
60 | print(capitals.items())
61 |
62 | """
63 | Using the dict.get() method, extract the value for the key 'Austria'
64 | and print it to the console
65 | """
66 | print(capitals.get('Austria'))
67 |
68 |
69 | """
70 | The following dictionary is given:
71 |
72 | stocks = {
73 | 'MSFT.US': {'Microsoft Corp': 184},
74 | 'AAPL.US': {'Apple Inc': 310},
75 | 'MMM.US': {'3M Co': 148}
76 | }
77 | Extract the value for the key 'APPL.US' and print to the console
78 |
79 | Expected result:
80 | {'Apple Inc': 310}
81 | """
82 | stocks = {
83 | 'MSFT.US': {'Microsoft Corp': 184},
84 | 'AAPL.US': {'Apple Inc': 310},
85 | 'MMM.US': {'3M Co': 148}
86 | }
87 | print(stocks['AAPL.US'])
88 |
89 |
90 | """
91 | Get the price for Microsoft (value for the 'Microsoft Corp' key) and
92 | print to the console
93 |
94 | Expected result:
95 | 184
96 | """
97 |
98 | print(stocks['MSFT.US']['Microsoft Corp'])
99 |
100 | """
101 | Update the price for Microsoft to 190 and print the value for the 'MSFT.US'
102 | key to the console
103 |
104 | Expected result:
105 | {'Microsoft Corp': 190}
106 | """
107 | stocks['MSFT.US']['Microsoft Corp'] = 190
108 | print(stocks['MSFT.US'])
109 |
110 |
111 | """
112 | The following dictionary is given:
113 |
114 | stocks = {
115 | 'MSFT.US': {'Microsoft Corp': 184},
116 | 'AAPL.US': {'Apple Inc': 310},
117 | 'MMM.US': {'3M Co': 148}
118 | }
119 | Add a fourth pair to the dictionary with the key 'V.US' and the value
120 | {'Visa Inc': 185} Print the value to console
121 |
122 | Expected result:
123 | dict_values([{'Microsoft Corp': 184}, {'Apple Inc': 310}, {'3M Co': 148}, {'Visa Inc': 185}])
124 | """
125 | stocks = {
126 | 'MSFT.US': {'Microsoft Corp': 184},
127 | 'AAPL.US': {'Apple Inc': 310},
128 | 'MMM.US': {'3M Co': 148}
129 | }
130 | stocks['V.US'] = {'Visa Inc': 185}
131 | print(stocks.values())
132 |
133 |
134 | """
135 | A list of tickers from the Dow Jones index is given:
136 |
137 | tickers = [
138 | 'AAPL.US', 'AXP.US', 'BA.US', 'CAT.US',
139 | 'CSCO.US', 'CVX.US', 'DIS.US', 'DOW.US',
140 | 'GS.US', 'HD.US', 'IBM.US', 'INTC.US'
141 | ]
142 | Transform the list into a list of a two-element tuple objects (index, ticker)
143 | and print to the console.
144 |
145 | Expected result:
146 | (0, 'AAPL.US'), (1, 'AXP.US'), (2, 'BA.US'), (3, 'CAT.US'), (4, 'CSCO.US'), (5, 'CVX.US'), (6, 'DIS.US'), (7, 'DOW.US'), (8, 'GS.US'), (9, 'HD.US'), (10, 'IBM.US'), (11, 'INTC.US')]
147 | """
148 |
149 | tickers = [
150 | 'AAPL.US', 'AXP.US', 'BA.US', 'CAT.US',
151 | 'CSCO.US', 'CVX.US', 'DIS.US', 'DOW.US',
152 | 'GS.US', 'HD.US', 'IBM.US', 'INTC.US'
153 | ]
154 |
155 | print(list(enumerate(tickers)))
156 |
157 |
158 | """
159 | Transform the tickers into a dictionary and print to the console
160 | """
161 | # list_tuple = list(enumerate(tickers))
162 | # print(f' To tuple {list_tuple}')
163 | # print(dict(enumerate(tickers)))
164 | # dct = dict((y, x) for x, y in list_tuple)
165 |
166 |
167 | """
168 | The following dictionary is given:
169 |
170 | project_ids = {
171 | '01': 'open',
172 | '03': 'in progress',
173 | '05': 'in progress',
174 | '04': 'completed'
175 | }
176 | Extract a list of unique values (sorted alphabetically) from the
177 | project_ids dictionary and print to the console
178 |
179 | Expected result:
180 | ['completed', 'in progress', 'open']
181 | """
182 |
183 | project_ids = {
184 | '01': 'open',
185 | '03': 'in progress',
186 | '05': 'in progress',
187 | '04': 'completed'
188 | }
189 | result = list(set(project_ids.values()))
190 | result.sort()
191 | print(result)
192 |
193 |
194 | # Delete (del)
195 | """
196 | The following dictionary is given:
197 | stats = {'site': 'e-smartdata.org', 'traffic': 100, 'type': 'organic'}
198 | Delete the 'traffic' key pair from the dictionary and print to the console
199 |
200 | """
201 |
202 | stats = {'site': 'e-smartdata.org', 'traffic': 100, 'type': 'organic'}
203 | del stats['traffic']
204 | print(stats)
205 |
206 |
207 |
--------------------------------------------------------------------------------
/duplicateRecord.py:
--------------------------------------------------------------------------------
1 |
2 | # Read a CSV file and write duplicate records to a file
3 |
4 | hash = {}
5 | with open('nitda-total.csv', 'r') as file:
6 | content = file.read().splitlines()
7 |
8 |
9 | for line in content:
10 | values = line.split(',')
11 | print(values[1], values[2]) # get the email address and firstname
12 |
13 | if values[1] in hash:
14 | with open('duplicates.csv', 'a') as duplicate:
15 | duplicate.write(line)
16 | duplicate.write('\n') # add a new line
17 | hash[values[1]] = "" # set the duplicate value to empty string
18 | hash[values[1]] = values[1] # if not a duplicate, store value in hash table
19 |
20 |
21 |
--------------------------------------------------------------------------------
/duplicateRecordCsv.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 | # Read a CSV file and write duplicate records to a file
4 |
5 | hash = {}
6 | with open('nitda-total.csv', 'r') as file:
7 | content = csv.reader(file)
8 |
9 |
10 | for line in content:
11 | if line[1] in hash:
12 | with open('duplicates.csv', 'a') as duplicate:
13 | duplicate.write(line)
14 | duplicate.write('\n') # add a new line
15 | hash[line[1]] = "" # set the duplicate value to empty string
16 | hash[line[1]] = line[1] # if not a duplicate, store value in hash table
17 |
18 |
19 |
--------------------------------------------------------------------------------
/duplicates.csv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/calistus-igwilo/python/796f65dd6ebf29434481f7ddfce793910c42d8ca/duplicates.csv
--------------------------------------------------------------------------------
/exercise-1-10.py:
--------------------------------------------------------------------------------
1 | """
2 | Find the sum of all numbers that are divisible by 5 or 7 less than 100.
3 | Present the solution in the form of calculate(). In response, call
4 | calculate() function and print the result to the console.
5 |
6 | Expected result:
7 | 1580
8 | """
9 | from pickle import FALSE
10 |
11 |
12 | def calculate():
13 | sum_ = 0
14 | for n in range(100):
15 | if n%5 == 0 or n%7 == 0:
16 | sum_ += n
17 | return(sum_)
18 | print(calculate())
19 |
20 |
21 | # Fibonaci
22 | """
23 | Consider the Fibonaci sequence. It is a sequence of natuarl numbers
24 | defined recursively as follows:
25 | - the first element of the sequence is 0
26 | - the second element of the sequence is 1
27 | - each next element of the sequence is the sum of the previous two elements.
28 | The begining of the Fibonaci sequence:
29 | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
30 | Find the sum of all the even elements of the Fibonaci sequence with vlaues
31 | less than 1,000,000(1million)
32 |
33 | Expected result:
34 | 1089154
35 | """
36 |
37 | def fibonaci_even():
38 | a = 0
39 | b = 1
40 | total = 0
41 | while a < 1000000:
42 | if a%2 == 0:
43 | total += a
44 | a, b = b, a + b
45 | return total
46 | print(fibonaci_even())
47 |
48 | """
49 | Check if a number is a prime number
50 | """
51 | def isprime(num):
52 | isprime = True
53 | if num > 1:
54 | for i in range(2, num):
55 | if num % i == 0:
56 | isprime = False
57 | break
58 | return isprime
59 | print(f'isprime {isprime(2)}')
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/fizzbuzz.py:
--------------------------------------------------------------------------------
1 | def fizzBuzz(n):
2 | '''
3 | Given a number n, for each integer i in the range from
4 | 1 to n inclusive, print one value per line as follows:
5 |
6 | - if i is a multile of both 3 and 5 print FizzBuzz.
7 | - if i is a multiple of 3 (but not 5), print Fizz
8 | - if i is a multip of 5 (but not 3), print Buzz
9 | - if i is not a multiple of 3 or 5, print the value of i
10 | '''
11 | for i in range(1, n+1):
12 | if i%3 == 0 and n%5 == 0:
13 | print("FizzBuZZ")
14 | elif i%3 == 0 and i%5 != 0:
15 | print("Fizz")
16 | elif i%3 != 0 and i%5 == 0:
17 | print("Buzz")
18 | else:
19 | print(i)
20 |
21 | fizzBuzz(15)
22 |
--------------------------------------------------------------------------------
/for.py:
--------------------------------------------------------------------------------
1 | """
2 | Write a program that finds all two-digit numbers divisible by 11
3 | (use a for loop). Print the result to the console as comma-separated
4 | values as shown
5 |
6 | 11,22,33,44,55,66,77,88,99
7 | """
8 | numbers = []
9 | for num in range(1, 100):
10 | if num % 11 == 0:
11 | numbers.append(str(num))
12 | result = ','.join(numbers)
13 | print(result)
14 |
15 |
16 | """
17 | The following list of numbers is given:
18 | items = [1, 3, 4, 5, 6, 9, 10, 17, 23, 24]
19 | Write a program that removes odd numbers and returns the remaining ones.
20 | Print the result to the console
21 |
22 | Expected result:
23 | [4, 6, 10, 24]
24 | """
25 | items = [1, 3, 4, 5, 6, 9, 10, 17, 23, 24]
26 | result = []
27 | for item in items:
28 | if item % 2 == 0:
29 | result.append(item)
30 | print(result)
31 |
32 |
33 | """
34 | The following is given:
35 | items = [1, 5, 3, 2, 2, 4, 2, 4]
36 | Write a program that removes duplicates from the list (the order must
37 | be kept) and print the list to the console
38 |
39 | Expected result
40 | [1, 5, 3, 2, 4]
41 | """
42 | items = [1, 5, 3, 2, 2, 4, 2, 4]
43 | result = []
44 | for item in items:
45 | if not item in result:
46 | result.append(item)
47 | print(result)
48 |
49 |
50 | """
51 | The following list is given:
52 |
53 | text = 'Python is a very popular programming language'
54 | Write a program which extracts exactly the first four words as a list.
55 | Standardize each work, i.e replace uppercase leters with lowercase.
56 | Present the result in a list and print to the console as shwon below
57 | """
58 | text = 'Python is a very popular programming language'
59 | counter = 0
60 | result = []
61 | for char in text:
62 | if char == ' ':
63 | counter += 1
64 | if counter == 4:
65 | break
66 | result.append(char.lower())
67 | words = ''.join(result).split()
68 | print(words)
69 |
70 | # Another solution using enumarate
71 | words = text.split(' ')
72 | result = []
73 | for idx, word in enumerate(words):
74 | if idx < 4:
75 | result.append(word.lower())
76 | print(result)
77 |
78 |
79 | """
80 | Consider the problem of binary classification in machine learning.
81 | The machine learning model returns the probability of belonging to
82 | the class. If it's less than 0.5, the sample is assigned to class 0,
83 | otherwise to class 1.
84 |
85 | A list of probabilities from the machine learning model is given:
86 |
87 | probabilities = [0.21, 0.91, 0.34, 0.55, 0.76, 0.02]
88 | Write a program that assigns class 0 for values less than 0.5 and 1 for
89 | valuies greater than or equal to 0.5. Print the result to the console
90 |
91 | Expected result:
92 | [0, 1, 0, 1, 1, 0]
93 | """
94 | probabilities = [0.21, 0.91, 0.34, 0.55, 0.76, 0.02]
95 | result = []
96 | for num in probabilities:
97 | if num < 0.5:
98 | result.append(0)
99 | else:
100 | result.append(1)
101 | print(result)
102 |
103 |
104 | """
105 | Write a program that creates a histogram as a dictionary of the
106 | following values:
107 | items = ['x', 'y', 'z', 'y', 'x', 'y', 'y', 'z', 'x']
108 | In response, print the histogram to the console
109 | """
110 | items = ['x', 'y', 'z', 'y', 'x', 'y', 'y', 'z', 'x']
111 | dic = {}
112 | for char in items:
113 | if not char in dic:
114 | cnt = items.count(char)
115 | dic[char] = cnt
116 | print(dic)
117 |
118 |
119 | """
120 | The following text is given:
121 |
122 | text = '''Python is powerful... and fast
123 | plays well with others
124 | runs everywhere
125 | is friendly & easy to learn
126 | is Open
127 | These are some of the reasons people who use Python would
128 | rather not use anything else'''
129 |
130 | Create a list of words from the given text. Then standardize this text
131 | (change uppercase letters to lowercase, remove punctuation marks).
132 | Extract words longer than six characters and print the result to console
133 |
134 | Expected result
135 | ['powerful', 'everywhere', 'friendly', 'reasons', 'anything']
136 | """
137 | text = """Python is powerful... and fast
138 | plays well with others
139 | runs everywhere
140 | is friendly & easy to learn
141 | is Open
142 | These are some of the reasons people who use Python would rather not use anything else"""
143 |
144 | words = text.lower().strip().replace('.', '').split()
145 | result = []
146 | for word in words:
147 | if len(word) > 6:
148 | result.append(word)
149 | print(result)
150 |
151 | # Another solution using list comprehension
152 | words = text.lower().strip().replace('.', '').split()
153 | words = [word for word in words if len(word) > 6]
154 | print(words)
155 |
156 |
157 | """
158 | A dictionary of companies from the WIG.GAMES index is given. The key is
159 | the 3-ltter company ticker and value - close price.
160 |
161 | gaming = {
162 | '11B': 362.5,
163 | 'CDR': 297.0,
164 | 'CIG': 0.85,
165 | 'PLW': 318.0,
166 | 'TEN': 300.0
167 | }
168 | Iterate through this dictionary and print the tickers of those companies
169 | where closing price is greater than 100.00 PLN.
170 |
171 | Expected result:
172 |
173 | """
174 | gaming = {
175 | '11B': 362.5,
176 | 'CDR': 297.0,
177 | 'CIG': 0.85,
178 | 'PLW': 318.0,
179 | 'TEN': 300.0
180 | }
181 | for ticker, close in gaming.items():
182 | if close > 100.00:
183 | print(ticker)
184 |
185 |
186 |
187 |
188 |
--------------------------------------------------------------------------------
/functions.py:
--------------------------------------------------------------------------------
1 | ##############################
2 | # INBUILT FUNCTIONS
3 | ##############################
4 | """
5 | The variable x
6 | x = -1.5
7 | and the follwing expreasion are given:
8 | expression = 'x**2 + x'
9 | Using the appropriate function, calculate thevalue of this expression
10 | and print the result to the console
11 |
12 | Tip: Use the eval() funtion.
13 | """
14 | x = -1.5
15 | expression = 'x**2 + x'
16 | print(eval(expression))
17 |
18 |
19 | """
20 | The following variables are given:
21 |
22 | var1 = 'Python'
23 | var2 = ('Python')
24 | var3 = ('Python',)
25 | var4 = ['Python']
26 | var5 = {'Python'}
27 |
28 | Using the appropriate function, chek if the variables are instances
29 | of tuple class. Print the result to the console
30 |
31 | Tip: Use the isinstance() built-in function.
32 | """
33 | var1 = 'Python'
34 | var2 = ('Python')
35 | var3 = ('Python',)
36 | var4 = ['Python']
37 | var5 = {'Python'}
38 |
39 | print(isinstance(var1, tuple))
40 | print(isinstance(var2, tuple))
41 | print(isinstance(var3, tuple))
42 | print(isinstance(var4, tuple))
43 | print(isinstance(var5, tuple))
44 |
45 |
46 | """
47 | The following list is given:
48 | characters = ['k', 'b', 'c', 'j', 'z', 'w']
49 | Using the built-in functions, return the first and the last letter in
50 | alphabetical order from the list and print the result to the console
51 |
52 | Tip: use the min() and max() functions.
53 |
54 | Expected result
55 | First: b
56 | Last: z
57 | """
58 | characters = ['k', 'b', 'c', 'j', 'z', 'w']
59 | print((f'First: {min(characters)}'))
60 | print((f'Last: {max(characters)}'))
61 |
62 |
63 | """
64 | Two tuples are given:
65 |
66 | ticker = ('TEN', 'PLW', 'CDR')
67 | full_name = ('Ten Square Games', 'Playway', 'CD Projekt')
68 | Using appropriate built-in function, create a list consisting of
69 | tuples (ticker, full_name) and print the result to the console
70 |
71 | Tip: use the zip() function.
72 |
73 | Expected result:
74 | [('TEN', 'Ten Square Games'), ('PLW', 'Playway'), ('CDR', 'CD Projekt')]
75 | """
76 | ticker = ('TEN', 'PLW', 'CDR')
77 | full_name = ('Ten Square Games', 'Playway', 'CD Projekt')
78 | result = list(zip(ticker, full_name))
79 | print(result)
80 |
81 |
82 | """
83 | Using the appropriate built-in function, verify if all elements of the
84 | following tuple return a logical value True
85 | items = (' ', '0', 0.1, True)
86 | Print the result to the console
87 |
88 | Exptected result:
89 | True
90 | """
91 | items = (' ', '0', 0.1, True)
92 | print(all(items))
93 |
94 |
95 | """
96 | Using the appropriate built-in function, verify if any element of the
97 | following tuple returns the boolean value True
98 | items = ('', 0.0, 0, False)
99 | Print the result to the console
100 | """
101 | items = ('', 0.0, 0, False)
102 | print(all(items))
103 |
104 |
105 | """
106 | Count the number of ones in the binary representaion of the number;
107 | number = 234
108 | print the resutl to the console
109 | """
110 | number = 234
111 | binary = bin(number)
112 | binary = binary[2:] # as the first two digits are representations
113 | print(binary.count('1'))
114 |
115 | #################################
116 | # DEFINING YOUR OWN FUNCTIONS
117 | #################################
118 |
119 | """
120 | Implement a function called maximum() that returns the maximum of two
121 | numbers. Use conditional statement
122 | """
123 | def maximum(x, y):
124 | if x > y:
125 | return x
126 | else:
127 | return y
128 | print(maximum(2,6))
129 |
130 |
131 | """
132 | Implement a function called maximum() that returns the maximum of three
133 | numbers. Use conditional statement
134 | """
135 | def maximum(x, y, z):
136 | if x >= y and x >= z:
137 | return x
138 | elif y >= z:
139 | return y
140 | else:
141 | return z
142 | print(maximum(3,2,5))
143 |
144 |
145 | """
146 | Implement a function called multi(), which accepts an iterable
147 | object (list, tuple) as an argument and returns the product of all
148 | elements of this iterable object.
149 | """
150 | def multi(numbers):
151 | product = 1
152 | for number in numbers:
153 | product *= number
154 | return product
155 | print(multi([3, 2, 4]))
156 |
157 |
158 | """
159 | Implement a function map_longest() that accepts the list of words and
160 | reutn the word with the longest length in the list.
161 | """
162 | def map_longest(words):
163 | dic = {word: len(word) for word in words}
164 | longest = max(dic, key= lambda x: dic[x])
165 | return longest
166 |
167 | print(map_longest(['python', 'sql', 'javascript']))
168 |
169 |
170 | """
171 | Implement a function called filter_ge_6() that takes a list of word
172 | and returns list of words with the length greater than or equal to
173 | 6 characters
174 |
175 | """
176 | def filter_ge_6(words):
177 | fil = [word for word in words if len(word)>=6]
178 | return fil
179 |
180 | print(filter_ge_6(['python', 'sql', 'javascript']))
181 |
182 |
183 | """
184 | Implement a function factorial() that calculates the factorial for a
185 | given number.
186 | """
187 | def factorial(num):
188 | #numbers = [n for n in range(1, num+1)]
189 | result = 1
190 | for n in range(1, num+1):
191 | result *=n
192 | return result
193 |
194 | print(factorial(10))
195 |
196 |
197 | """
198 | Implement a function count_str(), which returns the number of str objects
199 | in an iterable object (list tuple, set).
200 | """
201 | def count_str(obj):
202 | total = 0
203 | for item in items:
204 | if isinstance(item, str):
205 | total += 1
206 | return total
207 |
208 |
209 | """
210 | Implement a function count_str(), which returns the number of str objects
211 | with a lenght more than 2 characters from an iterable object (list tuple, set).
212 | """
213 | def count_str(obj):
214 | total = 0
215 | for item in items:
216 | if isinstance(item, str):
217 | if len(item) > 2:
218 | total += 1
219 | return total
220 |
221 |
222 | """
223 | Implement a function remove_duplicates() that removes duplicates from
224 | the list (the order of the items in the list does not have to be kept)
225 | """
226 | def remove_duplicates(string):
227 | result = []
228 | for item in string:
229 | if item not in result:
230 | result.append(item)
231 | return result
232 | print(remove_duplicates([1, 1, 1, 1, 1]))
233 |
234 | # Solution using set
235 | def remove_duplicates(items):
236 | return list(set(items))
237 |
238 |
239 | """
240 | Implement a function is_distinct() to check if the list contains unique
241 | """
242 | def is_distinct(items):
243 | return len(items) == len(set(items))
244 |
245 | """
246 | Analyse the results of the functions below
247 | """
248 | def function(idx, l=[]):
249 | for i in range(idx):
250 | l.append(i ** 3)
251 | print(l)
252 | function(3)
253 | function(5, ['a', 'b', 'c'])
254 | function(6)
255 |
256 | def function(*args, **kwargs):
257 | print(args, kwargs)
258 | function(3,4)
259 | function(x=3, y=4)
260 | function(1, 2, x=3, y=4)
261 |
262 |
263 | """
264 | Implement a function is_palindrome(), which takes as an argument
265 | str object and checks if the object is a palindrome
266 |
267 | If so, the function should return True, on the contrary False
268 | """
269 | def is_palindrome(string):
270 | reverse = string[::-1]
271 | if string == reverse:
272 | return True
273 | else:
274 | return False
275 | print(is_palindrome('level'))
276 |
277 |
--------------------------------------------------------------------------------
/gaming.txt:
--------------------------------------------------------------------------------
1 | Activision Blizzard
2 |
3 | Activision Blizzard, Inc. is a developer and publisher of interactive entertainment content and services. The Company develops and distributes content and services across various gaming platforms,
4 | including video game consoles, personal computers (PC) and mobile devices. Its segments include Activision Publishing, Inc. (Activision), Blizzard Entertainment, Inc. (Blizzard),
5 | King Digital Entertainment (King) and Other. Activision is a developer and publisher of interactive software products and content. Blizzard is engaged in developing and publishing of interactive
6 | software products and entertainment content, particularly in PC gaming. King is a mobile entertainment company. It is engaged in other businesses, including The Major League Gaming (MLG) business;
7 | The Activision Blizzard Studios (Studios) business, and The Activision Blizzard Distribution (Distribution) business. It also develops products spanning other genres, including action/adventure,
8 | role-playing and simulation.
--------------------------------------------------------------------------------
/generators.py:
--------------------------------------------------------------------------------
1 | ##########################
2 | # GENERATORS
3 | ##########################
4 | """
5 | Implement a generator named file_gen(), which selects only those names
6 | of files with the '.txt' extension from the list
7 | """
8 | def file_gen(names):
9 | for name in names:
10 | if name.endswith('.txt'):
11 | yield name
12 |
13 | names = ['data1.txt', 'data2.txt', 'data3.txt', 'view.jpg']
14 | print(list(file_gen(names)))
15 |
16 |
17 | """
18 | Implement a generator called enum() that works just like the enumerate()
19 | built-in function. For simplicity, the function gets an iterable object
20 | and returns a tuple(index, element)
21 |
22 | Example:
23 | Given: ['TEN', 'CDR', 'BBT']
24 | Result: [(0, 'TEN'), (1, 'CDR'), (2, 'BBT')]
25 | """
26 | def enum(objects):
27 | idx = 0
28 | for object in objects:
29 | yield (idx, object)
30 | idx += 1
31 | print(list(enum(['TEN', 'CDR', 'BBT'])))
32 |
33 |
34 | """
35 | Implement a generator named dayname() that accepts the index of the
36 | element from the following list:
37 | days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
38 | and allows us to iterate over 3 days (previous day, present day, next day)
39 | """
40 | def dayname(index):
41 | days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
42 | yield days[index - 1]
43 | yield days[index]
44 | yield days[(index + 1) % 7]
45 | print(list(dayname(6)))
46 |
47 |
48 |
--------------------------------------------------------------------------------
/hackerrank.py:
--------------------------------------------------------------------------------
1 | """
2 | Leap Year: A year is a leap year if:
3 | 1. The year is a multiple of 400
4 | 2. The year is a multiple of 4 but not a multiple of 100
5 | """
6 | import numbers
7 | from turtle import position
8 | from typing import Counter, Dict
9 |
10 |
11 | def is_leap(year):
12 | leap = False
13 |
14 | # Write your logic here
15 | if year % 4 == 0 and year % 100 != 0:
16 | leap = True
17 | elif year % 400 == 0:
18 | leap = True
19 | return leap
20 |
21 | """
22 | Given the participants' score sheet for your University Sports Day, you are required
23 | to find the runner-up score. You are given scores. Store them in a list and find the
24 | score of the runner-up.
25 | """
26 | numbers = [2, 3, 6, 6, 5]
27 | numbers = Counter(numbers)
28 | numbers = sorted(numbers.keys())
29 | print(numbers[-2])
30 |
31 | # Or
32 | scores = [2, 3, 6, 6, 5]
33 | result = list(set(scores))
34 | result = sorted(result)
35 | print(f' Second runner up {result[-2]}')
36 |
37 |
38 | """
39 | Given the names and grades for each student in a class of students, store them in a
40 | nested list and print the name(s) of any student(s) having the second lowest grade.
41 | Note: If there are multiple students with the second lowest grade, order their names
42 | alphabetically and print each name on a new line
43 | """
44 | record =[["chi", 20.0], ["beta", 50.0], ["alpha", 50.0], ["ojiugo", 30], ["madala", 30]]
45 |
46 | # find the second position
47 | scores = sorted(list(set([score[1] for score in record])))
48 | position = scores[1]
49 |
50 | # sort the list of second positions
51 | sec_pos = sorted([item for item in record if item[1] == position])
52 | for item in sec_pos:
53 | print(item[0])
54 |
55 |
56 | """
57 | The provided code stub will read in a dictionary containing key/value pairs of
58 | name:[marks] for a list of students. Print the average of the marks array for the
59 | student name provided, showing 2 places after the decimal.
60 | """
61 |
62 | student_marks = {'ojiugo': [20,30,40], 'uliaku': [30,50,70]}
63 | query_name = 'uliaku'
64 |
65 | data = [score[1] for score in student_marks.items() if query_name == score[0]]
66 | result = float(sum(data[0])/len(data[0]))
67 | print(f'{result} :2f')
68 |
69 | """
70 | You are given a positive integer N. Print a numerical triangle of height N-1 like the one below:
71 |
72 | 1
73 | 22
74 | 333
75 | 4444
76 | 55555
77 |
78 | Can you do it using only arithmetic operations, a single for loop and print statement?
79 | Use no more than two lines. The first line (the for statement) is already written for you. You have to complete the print statement.
80 | Note: Don't use anything related to strings
81 | """
82 | for i in range(1, 5):
83 | print(i * 10**i // 9) # use math operation to get all 1s and multiply by index
84 |
85 |
86 | """
87 | You are given a string S
88 | Your task is to print all possible permutations of size of the string
89 | in lexicographic sorted order.
90 | """
91 | from itertools import permutations
92 | s, num = input().split()
93 | result = sorted(list(permutations(s, int(num))))
94 | for i in result:
95 | print("".join(i))
96 |
97 |
98 | # """
99 | # Read input from STDIN and display the cartesan space.
100 |
101 | # Example
102 | # input 1: 1 2
103 | # input 2: 3 4
104 | # Output:
105 | # (1, 3) (1, 4) (2, 3) (2, 4)
106 | # """
107 | # a = list(map(int, input().split()))
108 | # b = list(map(int, input().split()))
109 | # result = [(i, j) for i in a for j in b]
110 | # for i in result:
111 | # print(i, end=" ")
112 |
113 | """
114 | Valid Parenthesis:
115 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
116 | determine if the input string is valid.
117 |
118 | An input string is valid if:
119 | Open brackets must be closed by the same type of brackets.
120 | Open brackets must be closed in the correct order.
121 | """
122 | def brackets(s):
123 | stack = []
124 | if len(s) % 2 != 0:
125 | return 'invalid'
126 | dic = {'(': ')', '{': '}', '[': ']' }
127 | for i in s:
128 | if i in dic.keys():
129 | stack.append(i)
130 | print(stack)
131 | else:
132 | if stack == []:
133 | return 'invalid'
134 | a = stack.pop()
135 | if i != dic[a]:
136 | return 'invalid'
137 | return 'valid'
138 |
139 | s = "({[]})"
140 | print(brackets(s))
141 |
--------------------------------------------------------------------------------
/hash-tables.py:
--------------------------------------------------------------------------------
1 | """
2 | You are given an array of integers and another integer targetvalue. Write a function
3 | that will take these inputs and return the indices of the 2 integers in the array
4 | that add up targetvalue
5 | """
6 | # Method 1: Brute force
7 | def target_value(arr, target):
8 | if arr == [] or len(arr) == 1:
9 | return []
10 | for i in range(len(arr)-1):
11 | for j in range(i+1, len(arr)):
12 | if arr[i] + arr[j] == target:
13 | return i, j
14 | return []
15 | # Time complexity = O(n**2). Space complexity = O(1)
16 |
17 | arr = [2, 7, 3, -2, 4]
18 | target = 2
19 | print(f'Brute force solution: {target_value(arr, target)}')
20 |
21 | # Method 2: Hash Table
22 | def target_value_hash(arr, target):
23 | hashTable = {}
24 | for i in range(len(arr)):
25 | needed_value = target - arr[i]
26 | if needed_value in hashTable:
27 | return [i, hashTable[needed_value]]
28 | else:
29 | hashTable[arr[i]] = i
30 | return []
31 | # Time complexity = O(n). Space complexity = O(n)
32 | print(f'hash table soluition: {target_value_hash(arr, target)}')
33 |
34 |
35 | """
36 | Given two strings s and t, determine if they are isomorphic. Two strings s and t
37 | are isomorphic if the characters in s can be replaced to get t. All occurrences of
38 | hcaracter must be replaced with another character while preserving the order of
39 | characters. No two characters may map to the same character, but a character may
40 | map to itself. s and t consist of any valid ascii character
41 | """
42 | def check_isomorphic(s, t):
43 | if len(s) != len(t):
44 | return False
45 | sHash = {}
46 | tHash = {}
47 |
48 | for i in range(len(s)-1):
49 | charS = s[i]
50 | charT = t[i]
51 | if charS not in sHash:
52 | sHash[charS] = charT
53 | if charT not in tHash:
54 | tHash[charT] = charS
55 | if sHash[charS] != charT or tHash[charT] != charS:
56 | return False
57 | return True
58 | # Time complexity = O(n). space complexity = O(1) since it uses ascii characters
59 | # which has a fixed size (max of 256)
60 |
61 | s = "green"
62 | t = "abccd"
63 | print(check_isomorphic(t, s))
--------------------------------------------------------------------------------
/lamda-function.py:
--------------------------------------------------------------------------------
1 | ################################
2 | # LAMBDA EXPRESSIONS
3 | ###############################
4 | """
5 | The following list of words is given:
6 | stocks = ['playway', 'boombit', 'cd projekt']
7 | Using the map() function and the lambda expression, transform the given
8 | list into a list containing the lenghs of each word and print to console
9 | """
10 | stocks = ['playway', 'boombit', 'cd projekt']
11 | length = list(map(lambda item: len(item), stocks))
12 | print(length)
13 |
14 |
15 | """
16 | Implement the sort_list() function that suorts a list of two-element
17 | tupple objects according to the second element of the tuple
18 |
19 | Tip: use sorted function
20 |
21 | Example:
22 | Given: [(1, 3), (4, 1), (4, 2), (0, 7)]
23 | Result: [(4, 1), (4, 2), (1, 3), (0, 7)]
24 | """
25 | def sort_list(items):
26 | return sorted(items, key=lambda x: x[1])
27 | print(sort_list([(1, 3), (4, 1), (4, 2), (0, 7)]))
28 |
29 |
30 | """
31 | The func_1() function is defined below:
32 | def func_1(x, y):
33 | return x + y + 2
34 | Using the lambda expression, define an analogous function and assign
35 | it to the variable func_2
36 | """
37 | func_2 = lambda x,y: x+y+2
38 |
39 |
40 | """
41 | The following list is given
42 | items = [(3, 4), (2, 5), (1, 4), (6, 1)]
43 | Sort the list by growing sum of squares of numbers in each tuple.
44 | Use the sort() method and the lambda expression and print sorted
45 | list to the console
46 |
47 | Expected result
48 | [(1, 4), (3, 4), (2, 5), (6, 1)]
49 | """
50 | items = [(3, 4), (2, 5), (1, 4), (6, 1)]
51 | items.sort(key=lambda x: x[0]**2 + x[1]**2)
52 | print(items)
53 |
54 |
55 | """
56 | Sort the given list of dictionaries by price key
57 |
58 | stocks = [
59 | {'index': 'mWIG40', 'name': 'TEN', 'price': 304},
60 | {'index': 'mWIG40', 'name': 'PLW', 'price': 309},
61 | {'index': 'sWIG80', 'name': 'BBT', 'price': 22}
62 | ]
63 | Print sorted list to the console
64 |
65 | Formated result:
66 | [{'index': 'sWIG80', 'name': 'BBT', 'price': 22},
67 | {'index': 'mWIG40', 'name': 'TEN', 'price': 304},
68 | {'index': 'mWIG40', 'name': 'PLW', 'price': 309}]
69 | """
70 | stocks = [
71 | {'index': 'mWIG40', 'name': 'TEN', 'price': 304},
72 | {'index': 'mWIG40', 'name': 'PLW', 'price': 309},
73 | {'index': 'sWIG80', 'name': 'BBT', 'price': 22}
74 | ]
75 | result = sorted(stocks, key=lambda item: item['price'])
76 | print(result)
77 |
78 | """
79 | Extract companies from the 'mWIG40' index and print the result to
80 | the console
81 |
82 | Formated result:
83 |
84 | [{'index': 'mWIG40', 'name': 'TEN', 'price': 304},
85 | {'index': 'mWIG40', 'name': 'PLW', 'price': 309}]
86 | """
87 | result = list(filter(lambda item: item['index'] == 'mWIG40', stocks))
88 | print(result)
89 |
90 |
91 | """
92 | Convert the stocks list to a list of boolean values (True, False). True
93 | if the company belongs to the 'mWIG40' index, False on the contrary and
94 | print the result to the console
95 |
96 | Tip: Use the map() function.
97 |
98 | Expected result
99 | [True, True, False]
100 | """
101 | result = list(map(lambda item: item['index'] == 'mWIG40', stocks))
102 | print(result)
103 |
104 |
105 | """
106 | The following list is given:
107 | items = ['P-1', 'R-2', 'D-4', 'F-6']
108 | Using the map() function and the lambda expression, get rid of the '-'
109 | (dash) from each element and print items list to the console.
110 |
111 | Expected result:
112 | ['P1', 'R2', 'D4', 'F6']
113 | """
114 | items = ['P-1', 'R-2', 'D-4', 'F-6']
115 | result = list(map(lambda x: x.replace('-', ''), items))
116 | print(result)
117 |
118 |
119 | """
120 | Two lists are given:
121 | num1 = [4, 2, 6, 2, 11]
122 | num2 = [5, 2, 3, 3, 9]
123 | Using the map() function and lambda expression, create a list containing
124 | the remainders of dividing the first list by the second
125 |
126 | Expected result:
127 | [4, 0, 0, 2, 2]
128 | """
129 | num1 = [4, 2, 6, 2, 11]
130 | num2 = [5, 2, 3, 3, 9]
131 |
132 | result = list(map(lambda x, y: x % y, num1, num2 ))
133 | print(result)
134 |
135 |
--------------------------------------------------------------------------------
/linked-list.py:
--------------------------------------------------------------------------------
1 | """
2 | Design a singly linked list class that has a head and tail. Every node is to have
3 | two attributes: value: the value of the current node, and next: a pointer to the next
4 | node. The linke list is to be 0-indexed. The class should support the following:
5 | - SinglyLinkeList() Initializes the SinglyLinkeList object
6 | - get(indx) Get the value of the index(th) node. If the index is invalid, return -1
7 | - addAtHead(vlaue) - Add a node of give value before the first element of the linked list
8 | - addAtTail(value) - Add a node of given value before the index(th) node in the linked
9 | list. if index equals the length of the linked list, the node will be appended to
10 | the end of the linked list. If index is greater than the lenght, don't insert the node
11 | - deleteAtIndex(index) - Delete the index(th) node in the linked list. If the index is
12 | valid, else nothing happens
13 | """
14 |
15 |
16 | class Node:
17 | def __init__(self, value):
18 | self.value = value
19 | self.next = None
20 |
21 | class Singly_Linked_List:
22 | def __init__(self):
23 | self.head = None
24 | self.tail = None
25 | self.size = 0 # use to track the size of the linked list
26 |
27 | def get(self, index):
28 | if index < 0 or index >= self.size:
29 | return -1
30 | counter = 0
31 | current = self.head
32 | while counter != index:
33 | current = current.next
34 | counter += 1
35 | return current
36 |
37 |
38 | def add_at_head(self, value):
39 | node = Node(value)
40 | if not self.head:
41 | self.head = node
42 | self.tail = node
43 | else:
44 | node.next = self.head
45 | self.head = node
46 | self.size += 1
47 | return self
48 |
49 | def add_at_tail(self, value):
50 | node = Node(value)
51 | if not self.head:
52 | self.head = node
53 | self.tail = node
54 | else:
55 | self.tail.next = node
56 | self.tail = node
57 | self.size += 1
58 | return self
59 |
60 |
61 | def add_at_index(self, value, index):
62 | if index < 0 or index > self.size:
63 | return 'Invalid index'
64 | if index == self.size:
65 | return self.add_at_tail(value)
66 | if index == 0:
67 | return self.add_at_head(value)
68 | node = Node(value)
69 | prev = self.get(index-1)
70 | temp = prev.next
71 | prev.next = node
72 | node.next = temp
73 | self.size += 1
74 | return self
75 |
76 | def delete_at_index(self, index):
77 | if index < 0 or index > self.size:
78 | return 'invalid index'
79 | # return the node that we are deleting
80 | if index == 0:
81 | # delete head
82 | temp = self.head
83 | self.head = temp.next
84 | self.size -= 1
85 | if self.size == 0:
86 | self.tail = None
87 | return temp
88 | if index == self.size-1:
89 | # delete tail
90 | old_tail = self.tail
91 | new_tail = self.get(index-1)
92 | self.tail = new_tail
93 | new_tail.next = None
94 | self.size -= 1
95 | # no need to check if size = 0 as it has been taken careof earlier
96 | return old_tail
97 | else:
98 | # delete another node
99 | prev = self.get(index-1)
100 | deleted_node = prev.next
101 | prev.next = deleted_node.next
102 | self.size -= 1
103 | return deleted_node
104 |
105 | def print_list(self):
106 | current = self.head
107 | while current is not None:
108 | print(current.value, end=" ")
109 | current = current.next
110 |
111 | sl = Singly_Linked_List()
112 | sl.add_at_head(1)
113 | sl.add_at_head(2)
114 | sl.add_at_tail(3)
115 | sl.add_at_index(2, 3)
116 | print(sl.print_list())
117 |
118 |
119 | """
120 | You are given the head of a Sorted Singly Linked list. Write a function that will
121 | take the given head as input, delete all nodes that have a value that is already
122 | the value of another node so that each value appears 1 time only and return the
123 | linked list, which is still to be a sorted linked list
124 | """
125 | # create some entries into a linked list called head
126 | head = Node(1)
127 | head.next = Node(2)
128 | head.next.next = Node(2)
129 | head.next.next.next = Node(3)
130 | head.next.next.next.next = Node('a')
131 | head.next.next.next.next.next = Node('a')
132 |
133 |
134 | def delete_duplicates(head):
135 | current = head
136 | while current:
137 | next_distinct_value = current.next
138 | while next_distinct_value != None and current.value == next_distinct_value.value:
139 | next_distinct_value = next_distinct_value.next
140 | current.next = next_distinct_value
141 | current = next_distinct_value
142 | return head
143 |
144 | def print_list(node):
145 | current = head
146 | while current is not None:
147 | print(current.value, end=" ")
148 | current = current.next
149 |
150 | print_list(delete_duplicates(head))
151 |
152 |
153 | """
154 | Reverse SLL: You are given a head of a Singly Linked List. Write a function that will
155 | take the given head as input, reverse the Linked List and return the new head of the
156 | reversed Linked List.
157 | """
158 | # store some values in the singly linked list
159 | head = Node(1)
160 | head.next = Node(2)
161 | head.next.next = Node(3)
162 | head.next.next.next = Node(4)
163 |
164 | def reverse_linked_list(head):
165 | prev = None
166 | current = head
167 | while current:
168 | next = current.next
169 | current.next = prev
170 | prev = current
171 | current = next
172 | return prev
173 |
174 | print_list(reverse_linked_list(head))
175 |
176 |
177 | """
178 | Tortise and Hare: You are given the head of alinked list. Check if there is a cycle
179 | and if yes, return the node where the cycle begins. If there is no cycle, return null
180 | There is a cycle in a linked list if there is some node inthe list that can be reached
181 | again by continuously following the next pointer. Do not modify the linked list
182 | """
183 | def checkloop(head):
184 | if not head:
185 | return None
186 | if not head.next:
187 | return None
188 |
189 | hare = head
190 | tortoise = head
191 | while hare and hare.next: # while there is a node and no null
192 | hare = hare.next.next
193 | tortoise = tortoise.next
194 | if hare == tortoise: # when they meet, it means that there is a loop
195 | break
196 | if hare != tortoise: # if the reason for breakout is not hare = tortoise
197 | return None
198 | # find where the cycle begins
199 | pointer = head
200 | while pointer != tortoise:
201 | pointer = pointer.next
202 | tortoise = tortoise.next
203 | return tortoise
204 |
205 |
206 | # input values to the linked list
207 | one = Node(1)
208 | two = Node(2)
209 | three = Node(3)
210 | four = Node(4)
211 | five = Node(5)
212 | six = Node(6)
213 |
214 | one.next = two
215 | two.next = three
216 | three.next = four
217 | four.next = five
218 | five.next = six
219 | # make a loop
220 | six.next = two
221 |
222 | head = one
223 |
224 | print(checkloop(head))
225 |
226 |
227 | """
228 | Given an array of integers nums containing n+1 integers where each integer is in the
229 | range [1, n] inclusive. There is only one repeated number in nums, return this repeated
230 | number. You must solve the problem without modifying the array nums and use only constant
231 | extra space
232 | """
233 | def get_duplicate(nums):
234 | tortoise = 0
235 | hare = 0
236 |
237 | while True:
238 | hare = nums[nums[hare]] # moves 2 spaces at a time
239 | tortoise = nums[tortoise] # moves a single space
240 |
241 | if hare == tortoise:
242 | pointer = 0
243 | while pointer != tortoise:
244 | pointer = nums[pointer]
245 | tortoise = nums[tortoise]
246 | return pointer
247 |
248 |
249 | """
250 | You are give two non-empty linked lists representing two non-negative integers. The
251 | digits are stored in reverse order, and each of their nodes contains a single digit.
252 | Add the two numbers and return the sum as a linked list. You may assume the two numbers
253 | do not contain anyleading zero, except the number 0 itself. 0<=Node value<=9
254 | """
255 | def add_2_numbers(l1, l2):
256 | carry_forward = 0
257 | results = Singly_Linked_List()
258 | while l1 or l2 or carry_forward:
259 | l1_value = l1.value if l1 else 0 #conditional operator
260 | l2_value = l2.value if l2 else 0
261 | sum_ = l1_value + l2_value + carry_forward
262 | node_value_in_result = sum_ % 10
263 | #print(f'node value: {node_value_in_result}')
264 | results.add_at_tail(node_value_in_result)
265 | carry_forward = sum_ // 10
266 | #print(f'carry forward: {carry_forward}')
267 | l1 = l1.next if l1 else None
268 | l2 = l2.next if l2 else None
269 | return results
270 |
271 | l1 = Singly_Linked_List()
272 | l2 = Singly_Linked_List()
273 | # 540 + 723 = 1263
274 | l1.add_at_tail(0)
275 | l1.add_at_tail(4)
276 | l1.add_at_tail(5)
277 |
278 | l2.add_at_tail(3)
279 | l2.add_at_tail(2)
280 | l2.add_at_tail(7)
281 |
282 | print(add_2_numbers(l1.head, l2.head))
283 |
284 |
285 | """
286 | Create a Doubly Linked List class. Write Instance Methods for this class to be able to
287 | 1. Remove a node when the node to be removed is given as input
288 | 2. Insert a node before a particluar node (both the node to be inserted and the node
289 | before which the insertion is to happen will be given as input). If the node to be
290 | inserted is
291 | - part of the linked list then shift its place to the dsired location
292 | - a new node, then insert the new node at the place desired.
293 | """
294 | class Node:
295 | def __init__(self, value):
296 | self.value = value
297 | self.next = None
298 | self.prev = None
299 |
300 | def link_nodes(node1, node2):
301 | node1.next = node2
302 | node2.prev = node1
303 |
304 | class DoublyLinkedList:
305 | def __init__(self):
306 | self.head = None
307 | self.tail = None
308 |
309 | def remove(self, node):
310 | # remove from head or tail
311 | if self.head == node:
312 | self.head = node.next
313 | if self.tail == node:
314 | self.tail = node.prev
315 |
316 | # remove from inside the list
317 | if node.prev:
318 | node.prev.next = node.next
319 | if node.next:
320 | node.next.prev = node.prev
321 | # remove the existing pointers on the node
322 | node.next = None
323 | node.prev = None
324 |
325 | def insert_before(self, node_position, node_insert):
326 | # check if the DLL has only one node
327 | if self.head == node_insert and self.tail == node_insert:
328 | return
329 | self.remove(node_insert) #if node to insert is part of the DLL
330 | node_insert.prev = node_position.prev
331 | node_insert.next = node_position
332 |
333 | #check if nodeposition is the head, point the head to node_to_insert
334 | if node_position == self.head:
335 | self.head = node_insert
336 | else:
337 | node_position.prev.next = node_insert
338 | node_position.prev = node_insert
339 |
340 | def remove_all_nodes_value(self, value):
341 | current = self.head # pass the head into the function
342 | while current: #if not None
343 | temp = current #to keep track and not loose the node pointers
344 | current = current.next
345 | if temp.value == value:
346 | self.remove(temp)
347 |
348 | def insert_position(self, position, node):
349 | current = self.head
350 | counter = 0
351 | # traverse the nodes until insert position is found
352 | while current != None and counter != position:
353 | current = current.next
354 | counter += 1
355 | #Either
356 | if current != None:
357 | self.insert_before(current, node)
358 | else:
359 | # if the DLL is empty or does not have any node
360 | if self.head == None:
361 | self.head = node
362 | self.tail = node
363 | else:
364 | # if head is not equal to None and current is None, it means
365 | # that current is at the tail
366 | self.remove(node) #in case the node to insert is in the DLL
367 | node.next = None
368 | node.prev = self.tail
369 | self.tail.next = node
370 | self.tail = node
371 |
372 |
373 | def display(self):
374 | #Node current will point to head
375 | current = self.head;
376 | if(self.head == None):
377 | print("List is empty");
378 | return;
379 | print("Nodes of doubly linked list: ");
380 | while(current != None):
381 | #Prints each node by incrementing pointer.
382 | print(current.value, end=" "),;
383 | current = current.next;
384 |
385 | one = Node(1)
386 | two = Node(2)
387 | three = Node(3)
388 | four = Node(4)
389 | five = Node(5)
390 | six = Node(2)
391 | seven = Node(7)
392 |
393 | linked_list_doubly = DoublyLinkedList()
394 |
395 | link_nodes(one,two)
396 | link_nodes(two,three)
397 | link_nodes(three,four)
398 | link_nodes(four,five)
399 | link_nodes(five,six)
400 | link_nodes(six,seven)
401 |
402 | linked_list_doubly.head = one
403 | linked_list_doubly.tail = five
404 |
405 | linked_list_doubly.display()
406 | #linked_list_doubly.insert_before(three, Node(6))
407 | #linked_list_doubly.display()
408 | #linked_list_doubly.remove_all_nodes_value(2)
409 | linked_list_doubly.insert_position(2, Node(6))
410 | linked_list_doubly.display()
411 |
412 |
413 | """
414 | Create a Doubly Linked List class. Write instance methods for this class to be able to
415 | 1. remove all the nodes in the doubly linked list which have their value equal to a
416 | given value
417 | 2. Insert a node at a desired position (node and position are given). The linked list
418 | is 0 indexed. If given node is a node existing in the linked list, shift it to
419 | the desired position
420 | """
421 | # Solutions given inside the DoublyLinkedList class as:
422 | # 1. remove_all_node_values()
423 | # 2. insert_position
--------------------------------------------------------------------------------
/list-comprehension.py:
--------------------------------------------------------------------------------
1 | """
2 | The gaming.txt file is attached to this excercise. This file has been loaded into
3 | the text variable. From the text list, delete all newline characters. Then delete
4 | emply lines and print the text to the console.
5 |
6 | text before:
7 |
8 | ['Activision Blizzard\n',
9 | '\n',
10 | 'Activision Blizzard, Inc. is a developer and publisher of interactive entertainment content and services. The Company develops and distributes content and services across various gaming platforms,\n',
11 | 'including video game consoles, personal computers (PC) and mobile devices. Its segments include Activision Publishing, Inc. (Activision), Blizzard Entertainment, Inc. (Blizzard),\n',
12 | 'King Digital Entertainment (King) and Other. Activision is a developer and publisher of interactive software products and content. Blizzard is engaged in developing and publishing of interactive\n',
13 | 'software products and entertainment content, particularly in PC gaming. King is a mobile entertainment company. It is engaged in other businesses, including The Major League Gaming (MLG) business;\n',
14 | 'The Activision Blizzard Studios (Studios) business, and The Activision Blizzard Distribution (Distribution) business. It also develops products spanning other genres, including action/adventure,\n',
15 | 'role-playing and simulation.']
16 |
17 | """
18 | from lib2to3.pgen2 import token
19 |
20 |
21 | with open('gaming.txt', 'r') as file:
22 | text = file.readlines()
23 | text = [line.replace('\n', '') for line in text]
24 | text = [line for line in text if len(line)>0]
25 | print(text)
26 |
27 |
28 | """
29 | The list of product prices is given:
30 | net_price = [5.5, 4.0, 9.0, 10.0]
31 | The VAT for these products is equal to 23%
32 | tax = 0.23
33 | Using the list comprehension, calculate the gross price for each product. Round the
34 | price to two decimal places and print result to console.
35 | """
36 | tax = 0.23
37 | net_price = [5.5, 4.0, 9.0, 10.0]
38 | gross_price = [round(num*(1+0.23),2) for num in net_price]
39 | print(gross_price)
40 |
41 |
42 | """
43 | The present value - pv and the investment value - n are given below:
44 | pv = 1000
45 | n = 10
46 | Depending on the interest rates given below, calculate the future value fv of your
47 | investment
48 | rate = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07]
49 | round the result to full cent and print the result to the console
50 |
51 | Expected result:
52 | [1104.62, 1218.99, 1343.92, 1480.24, 1628.89, 1790.85, 1967.15]
53 | """
54 | pv = 1000
55 | n = 10
56 | rate = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07]
57 |
58 | fv = [round(pv*(1 + r)**n, 2) for r in rate]
59 | print(fv)
60 |
61 |
62 | """
63 | The present value - pv and the investment period - n are given below:
64 | pv = 1000
65 | n = 10
66 | Depending on the interest rates given below, calculate the value of interest on
67 | investments:
68 | rate = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07]
69 | Round the result to the full cent and print the result to the console.
70 |
71 | Expected result:
72 | [104.62, 218.99, 343.92, 480.24, 628.89, 790.85, 967.15]
73 | """
74 | pv = 1000
75 | n = 10
76 | rate = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07]
77 | fvs = [round(pv*(1 + r)**n, 2) for r in rate]
78 | interest = [round(fv - pv, 2) for fv in fvs]
79 | print(interest)
80 |
81 |
82 | """
83 | The contents of the file plw.txt were loaded as follows:
84 | with open('plw.txt', 'r') as file:
85 | lines = file.read().splitlines()
86 |
87 | lines variable:
88 |
89 | ['PLAYWAY',
90 | '',
91 | 'PlayWay is a producer and publisher of computer and mobile games. The company is characterized by a very large number of development teams and a large number of games produced simultaneously.',
92 | "PlayWay sells, among others via the STEAM portal, AppStore and GooglePlay. The US and German markets are the two largest markets for the Group's sales.",
93 | 'In addition, the company has PlayWay Campus - a campus for cooperating development teams.']
94 |
95 | Task to perform:
96 | 1. Get rid of blank lines
97 | 2. Split each line into tokens/words as hsown below
98 |
99 | Formatted result:
100 |
101 | """
102 | with open('plw.txt', 'r') as file:
103 | lines = file.read().splitlines()
104 |
105 | lines = [line for line in lines if len(line) > 0]
106 | lines = [line.split() for line in lines]
107 | print(lines)
108 |
109 |
110 | """
111 | The contents of the file plw.txt were loaded as follows:
112 | with open('plw.txt', 'r') as file:
113 | lines = file.read()
114 |
115 | lines variable:
116 |
117 | Tasks to perform:
118 | 1. Change uppercase letters to lowercase
119 | 2. Remove commas and periods
120 | 3. Split the text into tokens
121 | 4. Extract words with minimum of 8 characters length
122 | 5. Sort the words alphabetically
123 | """
124 |
125 | with open('plw.txt', 'r') as file:
126 | lines = file.read()
127 | lines = lines.lower()
128 | lines = lines.replace(',','').replace('.','')
129 | tokens = lines.split()
130 | tokens = [token for token in tokens if len(token) >= 8]
131 | tokens = sorted(tokens)
132 | print(tokens)
133 |
134 |
135 | """
136 | The following dictionary is given:
137 | data = dict(zip(('a', 'b', 'c', 'd', 'e', 'f'),(1, 2, 3, 4, 5, 6)))
138 | Convert the dictionary into the following list and print the result to console
139 |
140 | Expected result:
141 | [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5], ['f', 6]]
142 | """
143 | data = dict(zip(('a', 'b', 'c', 'd', 'e', 'f'),(1, 2, 3, 4, 5, 6)))
144 | data = [[key, val] for key, val in data.items()]
145 | print(data)
146 |
147 |
148 | """
149 | You are given three integers x, y and z representing the dimensions of a cuboid along with an
150 | integer n. Print a list of all possible coordinates given by (i,j,k) on a 3D grid where
151 | the sum of i+j+k is not equal to n. Here, 0<=i<=x; 0<=j<=y<=k<=z. Use list comprehensions
152 | """
153 | x=1; y=1; z=2; n=3
154 | result = [[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]
155 | print(result)
--------------------------------------------------------------------------------
/list.py:
--------------------------------------------------------------------------------
1 | """
2 | The following text is given:
3 |
4 | text = 'Python programming'
5 | Standadize the text(replace uppercase letters with lowercase). Then create
6 | a list of uniqe characters in the text. Remove the space from this list and
7 | sort from a to z. Print the list to the console.
8 |
9 | Tip: You can use set to generate unique characters
10 | """
11 |
12 | text = 'Python programming'
13 | text = text.lower().replace(' ', '')
14 | text = list(set(text))
15 | text.sort()
16 | print(text)
17 |
18 |
19 | """
20 | The following list is given:
21 |
22 | filenames = ['view.jpg', 'bear.jpg', 'ball.png']
23 | Add the file 'phone.jpg' to the list at the beginning. Then delete the
24 | file 'ball.png'. In response, print the filenames list to console
25 |
26 | Expected result:
27 |
28 | ['phone.jpg', 'view.jpg', 'bear.jpg']
29 | """
30 |
31 | filenames = ['view.jpg', 'bear.jpg', 'ball.png']
32 | filenames.insert(0, 'phone.jpg')
33 | filenames.remove('ball.png')
34 | print(filenames)
35 |
36 |
37 | """
38 | The following list represents order ids for a given day:
39 |
40 | day1 = ['3984', '9042', '4829', '2380']
41 | Using the appropriate method, extend the list to the next day
42 | day2 = ['4231', '5234', '1345', '2455']
43 |
44 | Expected result:
45 | ['3984', '9042', '4829', '2380', '4231', '5234', '1345', '2455']
46 | """
47 | day1 = ['3984', '9042', '4829', '2380']
48 | day2 = ['4231', '5234', '1345', '2455']
49 | next_day = day1+day2
50 | print(next_day)
51 |
52 |
53 | """
54 | The following tuple is given:
55 | techs = ('python', 'java', 'sql', 'aws')
56 | Sort the tuple from a to z and print it to the console
57 |
58 | Tip: Tuples are immutable. You have to create a new one
59 |
60 | Expected result:
61 | ('aws', 'java', 'python', 'sql')
62 | """
63 | techs = ('python', 'java', 'sql', 'aws')
64 | sort = tuple(sorted(techs))
65 | print(sort)
66 |
67 |
68 | """
69 | The following list is given:
70 |
71 | hashtags = ['summer', 'time', 'vibes']
72 | Using the appropriate method, combine the elements of the list with
73 | the '#' character. Also add this sign to the beginning of the text
74 | and print the result to the console as shown below:
75 |
76 | Expected result
77 |
78 | """
79 |
80 | hashtags = ['summer', 'time', 'vibes']
81 | print('#' + '#'.join(hashtags))
--------------------------------------------------------------------------------
/log.txt:
--------------------------------------------------------------------------------
1 | 10.1.2.1 - car [01/Mar/2022:13:05:05 +0900] "GET /python HTTP/1.0" 200 2222
2 | 10.1.1.9 - bike [01/Mar/2022:13:05:10 +0900] "GET /python HTTP/1.0" 200 2222
--------------------------------------------------------------------------------
/no_duplicates.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 | # Read a CSV file and write duplicate records to a file
4 |
5 | hash = {}
6 |
7 | with open('duplicates.csv', 'r') as main:
8 | duplicate = csv.reader(main)
9 | for line in duplicate:
10 | hash[line[0]] = line[0]
11 |
12 | with open('nitda-total.csv', 'r') as file:
13 | content = csv.reader(file)
14 |
15 | for line in content:
16 | #print(f"{line[1]}\n")
17 | if line[1] not in hash:
18 | with open('no-duplicates.csv', 'a') as items:
19 | items.write(f"{line[1]}, {line[2]}\n")
20 | #hash[line[1]] = "" # set the duplicate value to empty string
21 | #hash[line[1]] = line[1] # if not a duplicate, store value in hash table
22 |
23 |
24 |
--------------------------------------------------------------------------------
/not_sent.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 | # Read a CSV file and write duplicate records to a file
4 |
5 | hash = {}
6 |
7 | with open('sent-total-40-50-hours.csv', 'r') as main:
8 | sent = csv.reader(main)
9 | for line in sent:
10 | hash[line[2]] = line[2]
11 |
12 | with open('not-sent-3.csv', 'r') as file:
13 | content = csv.reader(file)
14 |
15 | for line in content:
16 | #print(f"{line[1]}\n")
17 | if line[0] not in hash:
18 | with open('not-sent-4.csv', 'a') as items:
19 | items.write(f"{line[0]}, {line[1]}\n")
20 | #hash[line[1]] = "" # set the duplicate value to empty string
21 | #hash[line[1]] = line[1] # if not a duplicate, store value in hash table
22 |
23 |
24 |
--------------------------------------------------------------------------------
/num.txt:
--------------------------------------------------------------------------------
1 | 2
2 | 4
3 | 6
4 | 8
5 | 10
6 | 12
7 | 14
8 | 16
9 | 18
10 |
--------------------------------------------------------------------------------
/playway.csv:
--------------------------------------------------------------------------------
1 | Date,Open,High,Low,Close,Volume
2 | 2020-03-02,305,324.5,283.5,310,64081
3 | 2020-03-03,325.5,340.5,320,340.5,55496
4 | 2020-03-04,324,340.5,315,330,36152
5 | 2020-03-05,344,344,310,315,35992
6 | 2020-03-06,306.5,307,291,305,32539
7 | 2020-03-09,274,291,250,258,79402
8 | 2020-03-10,278,284.5,256,264,35700
9 | 2020-03-11,270,270,238.5,245,60445
10 | 2020-03-12,218,228,196,197,94031
11 | 2020-03-13,210,229,198.8,211,100412
12 | 2020-03-16,205,248,197.8,240.5,50659
13 | 2020-03-17,245,269,232.5,264,99480
14 | 2020-03-18,264,280,251,270,70136
15 | 2020-03-19,267,280,267,279.5,30732
16 | 2020-03-20,297.5,307,280,280.5,43426
17 | 2020-03-23,274,289,258,285,37098
18 | 2020-03-24,305,309,296.5,309,31939
19 | 2020-03-25,313,330,295,304,46724
20 | 2020-03-26,300,309,295.5,300,27213
21 | 2020-03-27,302,306.5,290,296,13466
22 | 2020-03-30,299,300,287,300,10316
23 | 2020-03-31,302.5,309,302,306.5,15698
--------------------------------------------------------------------------------
/plw.txt:
--------------------------------------------------------------------------------
1 | PLAYWAY
2 |
3 | PlayWay is a producer and publisher of computer and mobile games. The company is characterized by a very large number of development teams and a large number of games produced simultaneously.
4 | PlayWay sells, among others via the STEAM portal, AppStore and GooglePlay. The US and German markets are the two largest markets for the Group's sales.
5 | In addition, the company has PlayWay Campus - a campus for cooperating development teams.
--------------------------------------------------------------------------------
/print.py:
--------------------------------------------------------------------------------
1 | # """
2 | # Assing twor variables that store the follwing values:
3 | # - $34.99 - product price (float)
4 | # - 20 lbs - product weight (int)
5 |
6 | # Using the f-string formatting style print to the console with
7 | # the following message:
8 |
9 | # Price: $34.99. Weight: 20 lbs.
10 | # """
11 |
12 | # price = 34.99
13 | # weight = 20
14 |
15 | # print(f'Price: ${price}. Weight: {weight} lbs.')
16 |
17 | """
18 | Below is an approximation of pi:
19 | pi = 3.1415926535
20 | using f-string formatting, print the approximation of pi to two
21 | decimal places as shown below:
22 | Pi: 3.14
23 | """
24 | pi = 3.1415926535
25 | print(f'Pi: {pi :.2f}')
26 |
27 | # New code
28 | """
29 | Using three pirnt() functions (one line - one function)
30 | print the following text:
31 |
32 | -----------------------------------------
33 | VERSION: 1.0.1
34 | -----------------------------------------
35 |
36 | Tip: The lines consist of 40 dash characters '-'
37 | """
38 |
39 | print('-'*40)
40 | print('VERSION: 1.0.1')
41 | print('-'*40)
42 |
43 | # New code: sep argument
44 | print('summer', 'time', 'holiday', sep='#')
45 |
46 |
47 |
--------------------------------------------------------------------------------
/queue.py:
--------------------------------------------------------------------------------
1 | """
2 | Implement a queue:
3 | 1. Using an Array
4 | 2. with a Queue class using a Linked list
5 | One should be able to add to the queue and remove from the queue following
6 | the FIFO property
7 | """
8 | class QueueArray:
9 | """FIFO queue implementation using a Python list as underlying storage"""
10 | DEFAULT_CAPACITY = 10 # moderate capacity for all new queues
11 |
12 | def __init__(self):
13 | """Create an empty queue"""
14 | self._data = [None] * QueueArray.DEFAULT_CAPACITY
15 | self._size = 0
16 | self._front = 0
17 |
18 | def __len__(self):
19 | """Return the number of elements in the queue"""
20 | return self._size
21 |
22 | def is_empty(self):
23 | """Return True if the queue is empty"""
24 | return self._size == 0
25 |
26 | def first(self):
27 | """Return (but do not remove) the element at the front of the queue
28 | Raise Empty exception if the queue is empty
29 | """
30 | if self.is_empty():
31 | raise IndexError("Queue is empty")
32 | return self._data[self._front]
33 |
34 | def dequeue(self):
35 | """Remove and return the first element of the queue i.e FIFO
36 | Raise Empty exception if the queue is empty
37 | """
38 | if self.is_empty():
39 | raise IndexError("Queue is empty")
40 | answer = self._data[self._front]
41 | self._data[self._front] = None # help garbage collection
42 | self._front = (self._front + 1) % len(self._data)
43 | self._size -= 1
44 | # shrink the list when elements stored falls below 1/4 of its capacity
45 | if 0 < self._size < len(self._data) // 4:
46 | self._resize(len(self._data) // 2)
47 | return answer
48 |
49 | def enqueue(self, value):
50 | """Add a value/element to the back of the queue"""
51 | if self._size == len(self._data):
52 | self._resize(2 * len(self._data)) # double the array size
53 | avail = (self._front + self._size) % len(self._data) #compute location of next opening
54 | self._data[avail] = value
55 |
56 | def _resize(self, cap): # we assume cap >= len(self)
57 | """Resize to a new list of capacity >= len(self)"""
58 | old = self._data # keep track of exisiting list
59 | self._data = [None] * cap # allocate list with new capacity
60 | walk = self._front
61 | for k in range(self._size): # only consider existing elements
62 | self._data[k] = old[walk] # intentionally shift indices
63 | walk = (1 + walk) % len(old) # use old size as modulus
64 | self._front = 0 # front realigned
65 |
66 |
67 | class Node:
68 | def __init__(self, value):
69 | """Create a node"""
70 | self.value = value
71 | self.next = None
72 |
73 |
74 | class QueueLinkedList:
75 | """Implement Queue data structure using Singly Linked List"""
76 | def __init__(self):
77 | """Create an empty queue"""
78 | self.first = None
79 | self.last = None
80 | self.size = 0
81 |
82 | def enqueue(self, value):
83 | """Add a value at the end of the queue"""
84 | node = Node(value) # create a node
85 | #if queue is empty, make the new node the head and tails
86 | if not self.first:
87 | self.first = node
88 | self.last = node
89 | else:
90 | # add the new node at the tail
91 | self.last.next = node
92 | self.last = node
93 | self.size += 1
94 | return self
95 |
96 | def dequeue(self):
97 | """Remove the first element in a queue"""
98 | if not self.first: #if queue is empty return None
99 | return None
100 | # remove the first element
101 | temp = self.first
102 | self.first = self.first.next #make the next element the first
103 | self.size -= 1
104 | #if the removed node is the only node, then the queue is empty
105 | if self.size == 0:
106 | self.last = None
107 | return temp # return the removed node
108 |
109 | def display(self):
110 | #Node current will point to head
111 | current = self.first
112 | if(self.first == None):
113 | print("Queue is empty")
114 | return;
115 | print("Elements of Queue: ")
116 | while(current != None):
117 | #Prints each node by incrementing pointer.
118 | print(current.value, end=" ")
119 | current = current.next
120 |
121 | queue = QueueLinkedList()
122 | queue.enqueue(1)
123 | queue.enqueue(2)
124 | queue.enqueue(3)
125 |
126 | queue.display()
127 | queue.dequeue()
128 | queue.display()
129 |
130 |
131 | """
132 | Queue with Stack:
133 | Implement a first in first out (FIFO) queue using only two stacks. The implemented
134 | queue should support all the functions of a normal queue (push, peek, pop, and empty)
135 | Implement the MyQueue class:
136 | - push(val): Pushes element val tothe back of the queue
137 | - pop(): Removes the element from the front of the queue and returns it
138 | - peek(): Returns the element at the front of the queue
139 | - empty(): Returns true if the queue is empty, false otherwise.
140 | """
141 | class MyQueue:
142 | def __init__(self):
143 | """Create an empty Queue object"""
144 | self.in_stack = []
145 | self.out_stack = []
146 |
147 | def push(self, value):
148 | """Add element at the end of the queue"""
149 | self.in_stack.append(value)
150 |
151 | def pop(self):
152 | """Remove and return the last element of the queue"""
153 | # if out_stack is empty, then pop from the in_stack
154 | if not len(self.out_stack): # check if the out_stack is empty
155 | while len(self.in_stack): # while data exists in the in_stack
156 | self.out_stack.append(self.in_stack.pop()) #pop from in_stack and push to out_stack
157 | # remove and return the last item in out_stack which was first item in in_stack (FIFO)
158 | return self.out_stack.pop()
159 |
160 | def peek(self):
161 | """Return the element at the begining of the queue"""
162 | # if out_stack is empty, then pop from the in_stack
163 | if not len(self.out_stack): # check if the out_stack is empty
164 | while len(self.in_stack): # while data exists in the in_stack
165 | self.out_stack.append(self.in_stack.pop()) #pop from in_stack and push to out_stack
166 | # return the last item in out_stack which was first item in in_stack (FIFO)
167 | return self.out_stack[len(self.out_stack)-1]
168 |
169 | def empty(self):
170 | """
171 | Return True if the queue is empty
172 |
173 | :rtype: bool
174 | """
175 | in_stack_length = len(self.in_stack)
176 | out_stack_length = len(self.out_stack)
177 | # if both are 0, then return true
178 | return not in_stack_length and not out_stack_length
179 |
180 | q = MyQueue()
181 | q.push(1)
182 | q.push(2)
183 | q.push(3)
184 | #print(q.pop())
185 | print(q.empty())
186 | print(q.peek())
187 |
188 |
--------------------------------------------------------------------------------
/read.py:
--------------------------------------------------------------------------------
1 | # with open('fizzbuzz.py') as f:
2 | # read_data = f.read()
3 |
4 | # print(read_data)
5 |
6 |
7 | with open('fizzbuzz.py') as f:
8 | print(f.readline())
9 |
10 | """
11 | Write a program that reads playway.txt file containing Playway stock data,
12 | and then calculates the average closing price (3-day average).
13 | Playwright.txt contents:
14 | Date,Open,High,Low,Close,Volume
15 | 2020-04-01,302,314,300,310,12940
16 | 2020-04-02,310,315,305,313,10311
17 | 2020-04-03,313,318.5,312,318,12372
18 |
19 |
20 | Print result to the console as show below
21 |
22 | Expected result
23 |
24 | """
25 | with open('Playwright.txt', 'r') as file:
26 | lines = file.read().splitlines()
27 |
28 | close = []
29 | for idx, line in enumerate(lines):
30 | if idx > 0:
31 | close.append(int(line.split(',')[-2]))
32 | result = sum(close)/len(close)
33 | print(f'{result :.2f}')
34 |
35 |
36 | """
37 | Read the currencies.txt file. Each line has different currency pair.
38 | Create a list with the names of currency pairs containing the 'USD'
39 | symbol.
40 | """
41 | pairs = []
42 | with open('currencies.txt', 'r') as file:
43 | lines = file.read().splitlines()
44 |
45 | symbols = [symbol for symbol in lines if 'USD' in symbol]
46 | print(symbols)
47 |
48 |
49 | """
50 | The playway.csv file contains Playway's listing for March 2020. This file
51 | was loaded as follows to the content variable:
52 | with open('playway.csv', 'r') as file:
53 | content = file.read().splitlines()
54 |
55 | Transform the contents of the file to get a dictionary containing two
56 | keys 'Date' and 'Close'. The values for these keys will be respectively,
57 | lists consisting of all dates and closing prices. Convert closing prices
58 | to float type and print this dictionary to the console as shown belos
59 |
60 | Formatted result:
61 |
62 | """
63 | with open('playway.csv', 'r') as file:
64 | content = file.read().splitlines()
65 | date = []
66 | close = []
67 | for idx, line in enumerate(content):
68 | if idx > 0:
69 | date.append(line.split(',')[0])
70 | close.append(float(line.split(',')[-2]))
71 | print(date)
72 | print(close)
73 |
74 | with open('playway.csv', 'r') as file:
75 | content = file.read().splitlines()
76 | data = [(line.split(',')[0], line.split(',')[4]) for line in content ]
77 | result = {
78 | data[0][0]: [data[1:][i][0] for i in range(len(data) - 1)],
79 | data[0][1]: [float(data[1:][i][1]) for i in range(len(data) - 1)]
80 | }
81 | print(result)
82 |
83 |
84 | """
85 | The playway.csv file contains Playway's listing for March 2020. This
86 | file was loaded as follows to the content variable
87 | with open('playway.csv', 'r') as file:
88 | content = file.read().splitlines()
89 | Find the highest volume for a given month and print the result tothe console
90 |
91 | Expected result
92 | Max Vol: 100412
93 | """
94 | with open('playway.csv', 'r') as file:
95 | content = file.read().splitlines()
96 | volumes = [(line.split(',')[-1]) for line in content[1:]]
97 | volumes = [int(vol) for vol in volumes]
98 | max_vol = max(volumes)
99 | print(f'Max Vol: {max_vol}')
100 |
101 | """
102 | Find the date with the highest volume
103 |
104 | Expected result
105 | Date: 2020-03-13
106 | """
107 | with open('playway.csv', 'r') as file:
108 | content = file.read().splitlines()
109 | data = [(line.split(',')[0], line.split(',')[-1]) for line in content[1:] ]
110 | dic = {item[0]: int(item[1]) for item in data}
111 | max_vol = max(dic, key = lambda x: dic[x])
112 | print(dic)
113 | print(max_vol)
--------------------------------------------------------------------------------
/recurrsion.py:
--------------------------------------------------------------------------------
1 | """
2 | In the Fibonacci sequence, each subsequent term is obtained by adding the preceeding
3 | 2 terms. This is true for all the numbers except the first 2 numbers of Fibonacci series
4 | as they do not have 2 preceeding numbers. The first 2 terms in the Fibonacci series is
5 | 0 and 1. F(n) = F(n-1) + F(n-2) for n>1. Write a funtion that finds F(n) given n
6 | where n is an integer greater than equal to0. For the first term n = 0.
7 | """
8 | def fibonacci(n):
9 | if n <= 1:
10 | return n
11 | else:
12 | return fibonacci(n-1) + fibonacci(n-2)
13 | # Time complexity = O(2**n). Space complexity O(n)
14 |
15 | print(f'fibonnaci: {fibonacci(6)}')
16 |
17 | # Using memoization where values are stored in a hash table and referenced
18 | def fibonacci(n):
19 | ht = {0:0, 1:1}
20 | if n in ht:
21 | return ht[n]
22 | else:
23 | ht[n] = fibonacci(n-1) + fibonacci(n-2)
24 | return ht[n]
25 | # Time complexity = O(n). Space complexity O(n)
26 | print(f'fibonnaci optimized: {fibonacci(6)}')
27 |
28 |
29 | # Method 3: Using a while loop
30 | def fibonacci(n):
31 | if n <= 1:
32 | return n
33 | cnt = 1
34 | prev = 0
35 | current = 1
36 | while cnt < n:
37 | next = prev + cnt
38 | prev = current
39 | current = next
40 | cnt += 1
41 | return current
42 | # Time complexity = O(n). Space complexity = O(1)
43 | print(f'fibonacci loop: {fibonacci(8)}')
44 |
45 |
46 | """
47 | Let's define a peculiar type of array in which each element is either an integer or
48 | another peculiar array. Assume that a peculiar array is never empty. Write a function
49 | that will take a peculiar array as its input and find the sum of its elements. If an
50 | array is an element in the peculiar array, you have to convert it to its equivalent
51 | value so that you can sum it with the other elements. Equivalent value of an array
52 | is the sum of its elements raised to the number which represents how far nested it is.
53 | For e.g [2,3[4,1,2]] = 2+3+(4+1+2^2)
54 | [1,2,[7,[3,4],2]] = 1+2+(7+(3+4)^3+2)^2
55 | """
56 | def power_sum(arr, power=1):
57 | sum_ = 0
58 | for element in arr:
59 | if type(element) == list:
60 | sum_ += power_sum(element, power+1)
61 | else:
62 | sum_ += element
63 | return sum_ ** power
64 |
65 | arr = [1,2,[4,1]]
66 | print(power_sum(arr))
--------------------------------------------------------------------------------
/replace_phone_num.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 | # Read a CSV file and replace empty cells in a named column with a default number
4 |
5 | hash = {}
6 | default_phone_num = "1234567890"
7 |
8 | with open('testing2.csv', 'r') as file:
9 | content = csv.reader(file)
10 |
11 | for line in content:
12 | if line[6] == " " or line[6] == '':
13 | line[6] = default_phone_num
14 | with open('phone_update.csv', 'a') as items:
15 | items.write(f"{line[0]},{line[1]},{line[2]},{line[3]},{line[4]},{line[5]},{line[6]}\n")
16 | with open('phone_update.csv', 'a') as items:
17 | items.write(f"{line[0]},{line[1]},{line[2]},{line[3]},{line[4]},{line[5]},{line[6]}\n")
18 |
19 |
20 |
--------------------------------------------------------------------------------
/sandbox.py:
--------------------------------------------------------------------------------
1 | from itertools import count
2 |
3 |
4 | first, *last = [1, 2, 3, 4, 5, 6, 7]
5 | print("first: ", first)
6 | #print("second: ", second)
7 | print("last: ", last)
8 |
9 | word = 'letters in deo'
10 | print(word.count('t'))
11 |
12 | # from collections import Counter
13 | # def solution(cards):
14 | # highest =[]
15 | # count = []
16 | # for item in cards:
17 | # highest.append(max(item))
18 | # for item in highest:
19 | # for i in cards:
20 | # if highest[item] in cards[i]:
21 | # count.append(item)
22 | # max_list = Counter(count)
23 | # return max_list
24 |
25 | input_cards = [[5,7,3,9,4,9,8,3,1], [1,2,2,4,4,1], [1,2,3]]
26 | #print(solution(input_cards))
27 | def solution(cards):
28 | max_nums = [max(num) for num in input_cards]
29 | print(max_nums)
30 | cnt = []
31 | for num in max_nums:
32 | for i in range(len(input_cards)):
33 | if num in input_cards[i]:
34 | cnt.append(num)
35 | res = [num for num in cnt if cnt.count(num)==1]
36 | if len(res) == 1:
37 | return res
38 | else:
39 | return -1
40 |
41 |
42 | def draw_rating(vote):
43 | # Write your code here...
44 | if vote >= 0 and vote <= 20:
45 | df.assign(Rating=df['Rating'].apply(lambda x: x * '*') )
46 | elif vote > 20 and vote <= 40:
47 | df.assign(Rating=df['Rating'].apply(lambda x: x * '**') )
--------------------------------------------------------------------------------
/save.py:
--------------------------------------------------------------------------------
1 | """
2 | Generate all even numbers from 2 to 18 inclusive. Then write each number
3 | on a separate line fo the file called num.txt
4 | """
5 | numbers = []
6 | for i in range(2, 20, 2):
7 | numbers.append(i)
8 | print(numbers)
9 |
10 | with open('num.txt', 'w') as file:
11 | for num in numbers:
12 | file.write(str(num) + '\n')
13 |
14 |
15 | """
16 | The follwoing dictionary is given:
17 | stocks = {'PLW': ['Playway', 350], 'BBT': ['Boombit', 22]}
18 | save to stocks.json using the json package. Set the indent to 4
19 | """
20 | import json
21 |
22 | stocks = {'PLW': ['Playway', 350], 'BBT': ['Boombit', 22]}
23 |
24 | with open('stocks.json', 'w') as file:
25 | json.dump(stocks, file, indent=4)
26 |
27 |
28 | """
29 | The following list are given:
30 |
31 | headers = ['user_id', 'amount']
32 | users = [['001', '1400'], ['004', '1300'], ['007', '900']]
33 |
34 | Save the above data to the users.csv file (file in csv format - comma-separated
35 | values)as shown below
36 |
37 | """
38 | headers = ['user_id', 'amount']
39 | users = [['001', '1400'], ['004', '1300'], ['007', '900']]
40 |
41 | with open('users.csv', 'w') as file:
42 | file.write(','.join(headers) + '\n')
43 | for user in users:
44 | file.write(','.join(user) + '\n')
--------------------------------------------------------------------------------
/search.py:
--------------------------------------------------------------------------------
1 | """
2 | You are given an array of integers sorted in non-decreasing order, find the starting
3 | and ending position of a given target value. If target is not found in the array,
4 | return [-1, -1]. You must write an algorithm with O(logn) runtime complexity
5 | """
6 | def start_end_sorted_array(nums, target):
7 | left_extreme = left_index(nums, target)
8 | right_extreme = right_index(nums, target)
9 |
10 | return [left_extreme, right_extreme]
11 |
12 | def left_index(nums,target):
13 | left = 0
14 | right = len(nums)-1
15 | while left <= right:
16 | middle = (left + right) // 2
17 | if target == nums[middle]:
18 | if middle == 0:
19 | return middle
20 | if nums[middle -1] == target:
21 | right = middle-1
22 | else:
23 | return middle
24 | else:
25 | if target < nums[middle]:
26 | right = middle -1
27 | else:
28 | left = middle + 1
29 | return -1
30 |
31 | def right_index(nums,targe):
32 | left = 0
33 | right = len(nums)-1
34 | while left <= right:
35 | middle = (left + right) // 2
36 | if nums[middle] == target:
37 | if middle == len(nums)-1:
38 | return middle
39 | if nums[middle + 1] == target:
40 | left = middle+1
41 | else:
42 | return middle
43 | else:
44 | if target > nums[middle]:
45 | left = middle + 1
46 | else:
47 | right = middle - 1
48 | return -1
49 |
50 | nums = [1,2,3,3,3,3,4,5]
51 | target = 3
52 | print(start_end_sorted_array(nums, target))
53 |
54 |
55 | """
56 | Search in Matrix: Write an efficient algorithm that searches for a value target in
57 | an m x n integer matrix. This matrix has the following properties:
58 | - Integers in each row are sorted from left to right
59 | - The first integer of each row is greater than the last integer of the previous row
60 | If the value is there in the matrix, retrun true, else false.
61 | """
62 | def search_matrix(matrix, target):
63 | top = 0
64 | bottom = len(matrix)-1
65 | # Find the array that contains the target and store it in nums
66 | while top <= bottom:
67 | middle = (top + bottom) // 2
68 | if matrix[middle][0] <= target and matrix[middle][-1] >= target:
69 | nums = matrix[middle]
70 | if matrix[middle][0] > target:
71 | bottom = middle - 1
72 | else:
73 | top = middle + 1
74 |
75 | # Use binary search to find the target in the array above
76 | left = 0
77 | right = len(nums)-1
78 | while left <= right:
79 | midpoint = (left + right) // 2
80 | if nums[midpoint] == target:
81 | return True
82 | if nums[midpoint] > target:
83 | right = midpoint - 1
84 | else:
85 | left = midpoint + 1
86 | return False
87 |
88 |
89 |
90 | matrix = [[1,5,7,11], [12,13,17,20], [25,26,30,31], [32,35,39,43], [45,60,62,65]]
91 | target = 62
92 | print(search_matrix(matrix, target))
93 |
--------------------------------------------------------------------------------
/set-comprehension.py:
--------------------------------------------------------------------------------
1 | """
2 | Consider the two-roll of the dice. Create the probability space (omega) and count the
3 | probabioity of getting a sum of points higher than 10. Use set comprehension
4 | """
5 | omega = {(i, j) for i in range(1, 7) for j in range(1, 7)}
6 | sum_gt_10 = {pair for pair in omega if pair[0] + pair[1] > 10}
7 | #filter_pair = {pair for pair in omega if pair[0]==1 and pair[1]==2}
8 | #print(f'filter {filter_pair}')
9 | #print(f'Omega: {omega}')
10 | #print(f'Pair: {sum_gt_10}')
11 | #print(f'lenth of Omega: {len(omega)}')
12 | print(f'Probability: {len(sum_gt_10) / len(omega):.2f}')
13 |
14 |
15 | """
16 | The following text is given:
17 | desc = "Playway: Playway is a producer of computer games."
18 | Change all characters to lowercase, remove colon, period and then split the text into
19 | words. Create a set of unique words and print the lenght of this set to the console
20 | """
21 | desc = "Playway: Playway is a producer of computer games."
22 | transform = desc.lower().replace(':', '').replace('.', '').split()
23 | result = len(list(set(transform)))
24 | print(result)
25 |
26 |
27 | """
28 | Consider the two-roll of the dice. Create the probability space(omega) and calculate
29 | the probability of getting a sum of squares higher or equal to 45. Use set comprehension
30 | Round the reuslt to two decimal places and print the result to the console.
31 | """
32 | omega = {(i, j) for i in range(1, 7) for j in range(1, 7)}
33 | sum_sq = {sum for sum in omega if sum[0]**2 + sum[1]**2 >= 45}
34 | probility = len(sum_sq)/len(omega)
35 | print(f'Probability: {probility :.2}')
36 |
37 |
38 | """
39 | Consider a three-roll of the dice. Create the probability space (omega) and calculate
40 | the probability of obtaining three values which the sum is divisible by 7. Use set
41 | comprehension. Round result to two decimal places and print the result to the console
42 | """
43 | omega = {(i, j, k) for i in range(1, 7) for j in range(1, 7) for k in range(1, 7)}
44 | sum_ = {(i, j, k) for i, j, k in omega if (i+j+k)%7 == 0 }
45 | print(f'Probability: {round(len(sum_) / len(omega), 2)}')
46 |
47 |
48 | """
49 | Calculate the probability that in three throws of symmetrical cubic dice, the sum of
50 | the squares of points will be divisible by 3. Use set comprehension. Round the result
51 | to the fourth decimal place and print the result to the console.
52 | """
53 | sum_sq = {(i, j, k) for i, j, k in omega if (i**2 + j**2 + k**2)%3 == 0}
54 | prob = round(len(omega) / len(sum_sq), 4)
55 | print(f'Probability of squares: {prob}')
56 |
57 |
58 | """
59 | We roll the symmetrical dice three times. Calculate the probabioity of the follwing:
60 | odd number of points in each roll
61 | Use set comprehension. Round the result to three decimal places and print to console
62 | """
63 | omega = {(i, j, k) for i in range(1, 7) for j in range(1, 7) for k in range(1, 7)}
64 | odd = {(i, j, k) for i, j, k in omega if i%2 ==1 and j%2 ==1 and k%2 ==1}
65 | print(f'Odd numbers: {odd}')
66 | prob = round(len(odd)/len(omega), 3)
67 | print(prob)
68 |
69 |
--------------------------------------------------------------------------------
/sets.py:
--------------------------------------------------------------------------------
1 | """
2 | The following set is given:
3 |
4 | subjects = {'mathematics', 'biology'}
5 | Using the appropriate method add 'english' to the set.
6 | in response print subjets to the console as shown below
7 |
8 | {'biology', 'mathematics', 'english'}
9 | Note: Remember that set is an unordered data structure. You may
10 | get different order of the items
11 | """
12 |
13 | subjects = {'mathematics', 'biology'}
14 | subjects.add('english')
15 | print(subjects)
16 |
17 | """
18 | The following text is given:
19 |
20 | text = 'Programming in python.'
21 | follow the next steps:
22 | 1. Change all letters to lowercase
23 | 2. Delete spaces and period
24 | 3. Create a set consisiting of all letters in the text and
25 | assign to letters variable
26 | 4. Using the appropriate method for sets, remove all vowels from
27 | the letters set.
28 |
29 | vowels = {'a', 'e', 'i', 'o', 'u'}
30 | 5. Print the number of items in the letters set as shown below:
31 | """
32 |
33 | text = 'Programming in python.'
34 | vowels = {'a', 'e', 'i', 'o', 'u'}
35 |
36 | text = text.lower().strip('.').replace(' ', '')
37 | letters = set(text)
38 | consonats = letters.difference(vowels)
39 | print(consonats)
40 | print(f'Number of items: {len(consonats)}')
41 |
42 |
43 | """
44 | In mathematics, the symmetric difference of two sets is the set of elements
45 | which are in either of the sets, but not in their intersection
46 | The following sets are given:
47 |
48 | A = {2, 4, 6, 8}
49 | B = {4, 10}
50 | Using the appropriate method, extract the symmetrical difference of
51 | sets A and B and print result to the console as shown below:
52 |
53 | Symetric difference: {2, 6, 8, 10}
54 | """
55 |
56 | A = {2, 4, 6, 8}
57 | B = {4, 10}
58 |
59 | intersect = A.intersection(B)
60 | a_diff = A.difference(intersect)
61 | b_diff = B.difference(intersect)
62 | sym_diff1 = a_diff.union(b_diff)
63 | print(f'Symetric difference 1: {sym_diff1}')
64 | # OR
65 | sym_diff = A.symmetric_difference(B)
66 | print(f'Symetric difference: {sym_diff}')
67 |
68 | print(set(sym_diff) == set(sym_diff1))
69 |
70 |
71 | """
72 | We have two sets of customer IDs
73 | ad1_id = {'001', '002', '003'}
74 | ad2_id = {'002', '003', '007'}
75 | Each set stores the id of the customers who made the purchase based on
76 | the specific ad. We have two ads. Each customer can use the offer only
77 | twice in campaign. Choose the ID of the customers to whom you can send
78 | another ad (or ids that only appeared once in both sets)
79 |
80 | Expected result:
81 | Selected ID: { '007', '001'}
82 | Note: Remember that the set is an unordered data structure. You may get
83 | a different order of items than expected result.
84 | """
85 |
86 | ad1_id = {'001', '002', '003'}
87 | ad2_id = {'002', '003', '007'}
88 |
89 | sym_diff3 = ad1_id.symmetric_difference(ad2_id)
90 | print(f'Selected ID: {sym_diff3}')
--------------------------------------------------------------------------------
/slicing.py:
--------------------------------------------------------------------------------
1 | """
2 | From the given file name:
3 | filename = 'view.jpg'
4 | extract extension and print it to the console
5 | """
6 |
7 | filename = 'veiw.jpg'
8 | print(filename[-3:])
9 | # or
10 | print(filename[5:])
11 |
12 | # remove spaces
13 | """
14 | From the following text
15 | string = '1 0 0 1 0 1'
16 | remove spaces using slicing. Then convert the result to
17 | decimal notation and print to the console as shown below:
18 |
19 | Number found: 37
20 | """
21 |
22 | string = '1 0 0 1 0 1'
23 | binary = string[::2]
24 | number = int(binary, 2)
25 | print(f'Number found: {number}')
--------------------------------------------------------------------------------
/sort.py:
--------------------------------------------------------------------------------
1 | """
2 | Bubble Sort: You are given an array of integers. Write a function that will take
3 | this array as input and return the sorted array using Bubble sort.
4 | """
5 | def bubble_sort(nums):
6 | sorted_ = False # use this to know when there is no more swaps
7 | cnt = 0
8 | while sorted_ == False:
9 | sorted_ = True
10 | for i in range(len(nums)-1-cnt): # cnt help to skip biggest nums that have been pushed to the end
11 | j = i+1
12 | if len(nums) == 0 or len(nums) == 1:
13 | return nums
14 | if nums[i] > nums[j]:
15 | a, b = nums[i], nums[j]
16 | nums[i], nums[j] = b, a
17 | sorted_ = False # only false when items are swapped
18 | cnt += 1
19 | return nums
20 | # Time complexity = O(n**2). Space complexity = O(1)
21 |
22 | nums = [2,3,7,1,8]
23 | print(bubble_sort(nums))
24 |
25 |
26 | """
27 | Given an array of integers. Write a function that will take this array as input
28 | and return sorted array using insertion sort
29 | """
30 | def insertion_sort(nums):
31 | for i in range(len(nums)):
32 | j = i-1
33 | temp = nums[i]
34 | while j >= 0 and nums[j] > temp:
35 | nums[j+1] = nums[j]
36 | j -= 1
37 | nums[j+1] = temp
38 | return nums
39 |
40 | nums = [4,3,2,1]
41 | print(insertion_sort(nums))
42 |
43 |
44 | """
45 | You are given an array of integers. Write a function that will take this array as
46 | input and return the sorted array using Selection sort.
47 | """
48 | def selection_sort(nums):
49 | for i in range(len(nums)):
50 | smallest = i
51 | for j in range(i+1, len(nums)):
52 | if nums[smallest] > nums[j]:
53 | smallest = j
54 | if i != smallest:
55 | nums[i], nums[smallest] = nums[smallest], nums[i]
56 | return nums
57 | nums = [4,3,2,1,2]
58 | print(selection_sort(nums))
59 |
60 |
61 | """
62 | Merge sort
63 | """
64 | def merge_sorted_array(arr1, arr2):
65 | merged_array = []
66 | i = 0
67 | j = 0
68 | while i < len(arr1) and j < len(arr2):
69 | if arr1[i] <= arr2[j]:
70 | merged_array.append(arr1[i])
71 | i += 1
72 | else:
73 | merged_array.append(arr2[j])
74 | j += 1
75 | while i < len(arr1):
76 | merged_array.append(arr1[i]) #push the remaining arr1 elements into merged array
77 | i += 1
78 | while j < len(arr2):
79 | merged_array.append(arr2[j]) # push the remaining arr2 elements into merged array
80 | j += 1
81 | return merged_array
82 |
83 | def merge_sort(arr):
84 | if len(arr) <= 1:
85 | return arr
86 | middle = len(arr) // 2
87 | leftside = merge_sort(arr[:middle])
88 | rightside = merge_sort(arr[middle:])
89 | return merge_sorted_array(leftside, rightside)
90 |
91 | arr = [5,3,7,8,1,9,12]
92 | print(merge_sort(arr))
93 |
94 |
95 | """
96 | Quick Sort: You are given an array of integers. Write a function that will take this
97 | array as input and return the sorted array using Quick sort
98 | """
99 |
--------------------------------------------------------------------------------
/stack.py:
--------------------------------------------------------------------------------
1 | """
2 | Design a Stack:
3 | Implement a Stack:
4 | 1. using an Array
5 | 2. with a Stack class using a Linked list
6 | One should be able to add to the stack and remove from the stack following the LIFO
7 | property.
8 | """
9 |
10 | class Node:
11 | def __init__(self, value):
12 | self.value = value
13 | self.next = None
14 |
15 |
16 | class Stack:
17 | """
18 | Use a singly linked list to implement stack.
19 | Add and remove nodes at the beginning to achieve O(1) time complexity
20 | """
21 | def __init__(self):
22 | self.first = None
23 | self.last = None
24 | self.size = 0
25 |
26 | def add_at_beginning(self, value):
27 | node = Node(value)
28 | #check if SLL is empty, and make the node the head and tail
29 | if not self.first:
30 | self.first = node
31 | self.last = node
32 | else:
33 | # add node at the begining
34 | temp = self.first
35 | self.first = node
36 | self.first.next = temp
37 | self.size += 1
38 | return self
39 |
40 | def remove_from_begining(self):
41 | #check if stack is empty and return None
42 | if not self.first:
43 | return None
44 | temp = self.first #to be able to return the removed node
45 | self.first = self.first.next
46 | self.size -= 1
47 | if self.size == 0: #if the last node was removed
48 | self.last = None
49 | return temp
50 |
51 | def display(self):
52 | #Node current will point to head
53 | current = self.first
54 | if(self.first == None):
55 | print("List is empty")
56 | return;
57 | print("Nodes of singly linked list: ")
58 | while(current != None):
59 | #Prints each node by incrementing pointer.
60 | print(current.value, end=" ")
61 | current = current.next
62 |
63 | stack = Stack()
64 | stack.add_at_beginning(1)
65 | stack.add_at_beginning(2)
66 | stack.display()
67 | stack.remove_from_begining()
68 | stack.display()
69 |
70 |
71 | """
72 | Implement a Stack class using List Array
73 | """
74 | class StackArray:
75 | """ LIFO Stack implementation using Python list/array as underlying storage"""
76 | def __init__(self):
77 | """ Create an empty stack """
78 | self._data = [] #non-public list instance
79 |
80 | def __len__(self):
81 | """ Return the number of elements in the stack """
82 | return len(self._data)
83 |
84 | def is_empty(self):
85 | """Return True if stack is empty"""
86 | return len(self._data) == 0
87 |
88 | def push(self, value):
89 | """Add value/element to the top of the stack"""
90 | self._data.append(value)
91 |
92 | def top(self):
93 | """Return (but do not remove) the element at the top of the stack
94 | Raise Empty exception if the stack is empty
95 | """
96 | if self.is_empty():
97 | raise IndexError("Stack is empty")
98 | return self._data[-1] # last item in the list
99 |
100 | def pop(self):
101 | """Remove and return the element from the top of the stack (LIFO)
102 | Raise Empty exception if the stack is empty
103 | """
104 | if self.is_empty():
105 | raise IndexError("Stack is empty")
106 | return self._data.pop() # remove last item from the list
107 |
108 | """
109 | Reverse polish notation:
110 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid
111 | operators are +, -, *, and / Note that division between two integers should truncate
112 | toward zero. It is guaranteed that the given RPN expression is always valid. That
113 | means the expression would always evaluate to a result, and there will not be any
114 | division by zero operation. The input is an array of strings where each element is
115 | either a valid operator or an integer. E.g ["1", "2", "+"]
116 | """
117 | def postfix(tokens):
118 | """Implement the Reverse Polish Notation a.k.a postfix"""
119 | stack = StackArray() #StackArray has the push method
120 | # define key-value pairs for the operators
121 | valid_operator = {
122 | '+': lambda n1, n2: n1 + n2,
123 | '-': lambda n1, n2: n1 - n2,
124 | '*': lambda n1, n2: n1 * n2,
125 | '/': lambda n1, n2: n1 // n2
126 | }
127 | for token in tokens:
128 | # if token is an operator, execute the operation and push value to stack
129 | if token in valid_operator:
130 | n2 = stack.pop()
131 | n1 = stack.pop()
132 | result = valid_operator[token](n1, n2)
133 | stack.push(result)
134 | else:
135 | # token is a number, push it to the stack
136 | stack.push(int(token))
137 | return stack.pop() #return the final result
138 |
139 | print(postfix(['4','13','5','/','+']))
140 |
141 |
142 |
143 |
144 |
145 |
146 |
--------------------------------------------------------------------------------
/stocks.json:
--------------------------------------------------------------------------------
1 | {
2 | "PLW": [
3 | "Playway",
4 | 350
5 | ],
6 | "BBT": [
7 | "Boombit",
8 | 22
9 | ]
10 | }
--------------------------------------------------------------------------------
/string.py:
--------------------------------------------------------------------------------
1 | """
2 | You are given a string consisting of only lowercase and uppercase English Alphabets
3 | and integers 0 to 9. Write a function that will take this string as input and return
4 | the index of the first character that is repeating.
5 | """
6 |
7 | from posixpath import split
8 | from turtle import clear
9 |
10 |
11 | def repeat(s):
12 | hashTable = {}
13 | for i in range(len(s)-1):
14 | if s[i] in hashTable:
15 | return i
16 | else:
17 | hashTable[s[i]] = i
18 | return []
19 |
20 | s = "abcdeefgghhij"
21 | print(repeat(s))
22 |
23 | """
24 | You are given a string consisting of only lowercase and uppercase English Alphabets
25 | and integers 0 to 9. Write a function that will take this string as input and return
26 | the index of the first character that is non-repeating.
27 | """
28 | # Method 1:
29 | def non_repeat(s):
30 | repeats = []
31 | for i in range(len(s)-1):
32 | if s[i] in s[i+1:]:
33 | repeats.append(s[i])
34 | for i in range(len(s)):
35 | if s[i] not in repeats:
36 | return i
37 | return None
38 | # Time complexity = O(n). Space complexity = O(n)
39 | s = "abaccbd"
40 | print(non_repeat(s))
41 |
42 | # Method 2: Improved brute force
43 | def non_repeat(s):
44 | for i in range(len(s)):
45 | repeat = False
46 | for j in range(len(s)):
47 | if s[i] == s[j] and i != j:
48 | repeat = True
49 | if repeat == False:
50 | return i
51 | return None
52 | # Time complexity = O(n**2). Space complexity = O(1)
53 | print(non_repeat(s))
54 |
55 | # Method 3 Use of Hash Table
56 | def non_repeat(s):
57 | hashTable = {}
58 | for i in s:
59 | if i in hashTable:
60 | hashTable[i] += 1
61 | else:
62 | hashTable[i] = 1
63 | for i in range(len(s)):
64 | if hashTable[s[i]] == 1:
65 | return i
66 | return None
67 | # Time complexity = O(n).
68 | # Space complexity = O(1) because s has a fixed value (26 upper + 26 lower + 10 digits)
69 | print(non_repeat(s))
70 |
71 |
72 | """
73 | You are given a string. Write a function to check whether the string is a
74 | palindrome or not.
75 | """
76 | def palindrome(s):
77 | str_ = ""
78 | for i in range(len(s)-1, -1, -1):
79 | str_ += s[i]
80 | print(str_)
81 | if str_ == s:
82 | return True
83 | return False
84 | # Time complexity = O(n**2) because strings are immutable, so append creates a
85 | # new string for each call.
86 | # Space complexity = O(n)
87 | s = "abba"
88 | print(palindrome(s))
89 |
90 | # Method 2: Appending to an array
91 | def palindrome(s):
92 | arr = []
93 | for i in range(len(s)-1, -1, -1):
94 | arr.append(s[i])
95 | result = ''.join(arr)
96 | if s == result:
97 | return True
98 | return False
99 | # Time complexity = O(n) because append to array is a constant time operation
100 | # and the array was traversed once.
101 | # Space complexity = O(n) as extra sapce was created to store the new array
102 | print(palindrome(s))
103 |
104 | # Method 3
105 | def palindrome(s):
106 | i = 0
107 | j = len(s)-1
108 | while i <= j:
109 | if s[i] != s[j]:
110 | return False
111 | i += 1
112 | j -= 1
113 | return True
114 | # Time complexity = O(n)
115 | # Space complexity = O(1) since no extra space was created
116 | print(palindrome(s))
117 |
118 |
119 | """
120 | Given a string s, find the length of the longest substring without repeating characters
121 | """
122 | def max_substr(s):
123 | strList = []
124 | hashTable = {}
125 | max_ = 0
126 | start = 0
127 | for i in range(len(s)-1):
128 | if s[i] not in hashTable:
129 | hashTable[s[i]] = i
130 | max_ = max(start, i - start+1)
131 | else:
132 | strList.append(s[start:i])
133 | start = max(start, hashTable[s[i]]+1)
134 | hashTable[s[i]] = i
135 | print(f'Substrings: {strList}')
136 | return max_
137 | # Time complexity = O(n). Space complexity = O(n)
138 | s = 'abcdbefghijklmef'
139 | print(max_substr(s))
140 |
141 |
142 | """
143 | Given an array of strings consisting of lower case English letters, group the
144 | anagrams together. You can return the answer in any order. An Anagram is a
145 | word or phrase formed by rearranging the letters of a different word or phrase,
146 | using all the original letters exactly once.
147 | """
148 | def anagrams(arr):
149 | list_ = []
150 | hashTable = {}
151 | if len(arr) == 1 or len(arr) == 0:
152 | return arr
153 | print(arr)
154 | sortList = [''.join(sorted(item)) for item in arr]
155 | for i in range(len(arr)):
156 | if sortList[i] in hashTable:
157 | hashTable[sortList[i]] += [arr[i]]
158 | else:
159 | hashTable[sortList[i]] = [arr[i]]
160 | return hashTable.values()
161 | # Time complexity = O(S x nlogn) where S = number of strings and n = max number of
162 | # strings in the character.
163 | # Space complexity = O(S x n)
164 |
165 | arr = ['arc', 'abc', 'car', 'cat', 'act', 'acb', 'atc']
166 | print(anagrams(arr))
167 |
168 |
169 | """
170 | Given an array of integers which is sorted in ascending order, and a target integer,
171 | write a function to search for whether the target integer is there in the given array.
172 | If it is there, then return its index. Otherwise, return -1. You must write an
173 | algorithm with O(logn) runtime complexity.
174 | """
175 | def binary_search(nums, target):
176 | pointerLeft = 0
177 | pointerRight = len(nums)-1
178 | while pointerLeft <= pointerRight:
179 | middle = (pointerRight + pointerLeft) // 2
180 | print(f'pointerLeft: {pointerLeft}, pointerRight: {pointerRight}')
181 | if target == nums[middle]:
182 | return middle
183 | elif target < nums[middle]:
184 | pointerRight = middle - 1
185 | elif target > nums[middle]:
186 | pointerLeft = middle + 1
187 | return -1
188 | nums = [2, 3, 7, 9, 11, 23, 37, 81, 87, 89]
189 | print(binary_search(nums, 9))
190 |
191 |
192 | """
193 | You are given an integer array nums sorted in ascending order (with disctinct values).
194 | Prior to being passed to your function, nums is possibly rotated at an unkown pivot
195 | index k (1 <= k < nums.lenght) such that the resulting array is
196 | [nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed).
197 | For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
198 | Given an integer target, return the index of target if it is in the array, else return
199 | -1. You must write an alogrithm with O(logn) runtime complexity.
200 | """
201 | def search_rotation(nums, target):
202 | left = 0
203 | right = len(nums)-1
204 | while left <= right:
205 | middle = (left + right) // 2
206 | if nums[middle] == target:
207 | return middle
208 | if nums[left] < nums[middle]:
209 | if nums[left] <= target and target < nums[middle]:
210 | right = middle-1
211 | else:
212 | left = middle+1
213 | else:
214 | if nums[middle] < target and target <= nums[right]:
215 | left = middle+1
216 | else:
217 | right = middle-1
218 | return -1
219 | nums = [5,6,7,8,9,1,2,3,4]
220 | target = 3
221 | print(search_rotation(nums, target))
222 |
223 |
224 | # Compress the string
225 | """
226 | You are given a string S Suppose a character 'c' occurs consecutively X
227 | times in the string. Replace these consecutive occurrences of the
228 | character 'c' with (X, c) in the string.
229 | """
230 | S = 1222311
231 | def compress_string(S):
232 | result = []
233 | temp = []
234 | pointer = 1
235 | i = 0
236 | j = i+1
237 | cnt = 1
238 |
239 |
240 | if len(S) == 0:
241 | return "string must contain at least 1 element"
242 | while S(j):
243 | temp.append(S[i])
244 | while S[i] == S[j]:
245 | cnt += 1
246 | i += 1
247 | result.append((cnt, temp[-1]))
248 | temp = []
249 | print(result)
250 |
251 |
252 | """
253 | Kevin and Stuart want to play the 'The Minion Game'.
254 |
255 | Game Rules
256 |
257 | Both players are given the same string, .
258 | Both players have to make substrings using the letters of the string .
259 | Stuart has to make words starting with consonants.
260 | Kevin has to make words starting with vowels.
261 | The game ends when both players have made all possible substrings.
262 |
263 | Scoring
264 | A player gets +1 point for each occurrence of the substring in the string .
265 | """
266 | def minion_game(string_):
267 | vowel_strings = 0
268 | consonant_strings = 0
269 | string_length = len(string_) # length of string
270 |
271 | for i in range(string_length):
272 | if string_[i] in "AEIOU":
273 | vowel_strings += string_length - i # the number of substrings that can be formed from the length
274 | else:
275 | consonant_strings += string_length -i # the number of substrings that can be formed
276 |
277 | # Determine the winner
278 | if consonant_strings > vowel_strings:
279 | print("Stuart", consonant_strings )
280 | elif consonant_strings < vowel_strings:
281 | print("Kevin", vowel_strings)
282 | else:
283 | print("Draw")
284 |
285 | minion_game("BANANA")
286 |
287 |
288 | def merge_the_tools(string, k):
289 | sub_sequences = []
290 | temp = ""
291 | for i in range(0, len(string), k):
292 | sub_sequences.append((string[i:i+k]))
293 | print(sub_sequences)
294 | print("lenght of subsequence: ",len(sub_sequences))
295 |
296 | # check for duplicate alphabets
297 | for string in sub_sequences:
298 | for i in range(k):
299 | if string[i] not in temp:
300 | temp += string[i]
301 | print(temp)
302 | temp = ""
303 |
304 | s = 'AAABCADDE'
305 | merge_the_tools(s)
306 |
307 |
308 | """
309 | You are given a string and your task is to swap cases. In other words, convert all
310 | lowercase letters to uppercase letters and vice versa.
311 | """
312 | def swap_case(s):
313 | result = ""
314 | for i in range(len(s)):
315 | if s[i].isupper():
316 | result += s[i].lower()
317 | else:
318 | result += s[i].upper()
319 | return result
320 |
321 | t = "Www.HackerRank.com"
322 | swap_case(t)
323 |
324 |
325 | """
326 | A user enters a string and a substring. You have to print the number of times that the
327 | substring occurs in the given string. String traversal will take place from left to right,
328 | not from right to left.
329 | String letters are case-sensitive.
330 | """
331 | def count_substring(string, sub_string):
332 | substring_length = len(sub_string)
333 | string_length = len(string)
334 | end = string_length - 2
335 | cnt = 0
336 |
337 | for i in range(0, end):
338 | if string[i:i+substring_length] == sub_string:
339 | cnt += 1
340 | return cnt
341 |
342 | s = "ABCDCDC"
343 | sub = "CDC"
344 | count_substring(s, sub) # 2
345 |
346 |
347 | """
348 | You are given a string S.
349 | Your task is to find out if the string contains: alphanumeric characters,
350 | alphabetical characters, digits, lowercase and uppercase characters.
351 |
352 | Output Format:
353 | In the first line, print True if has any alphanumeric characters. Otherwise, print False.
354 | In the second line, print True if has any alphabetical characters. Otherwise, print False.
355 | In the third line, print True if has any digits. Otherwise, print False.
356 | In the fourth line, print True if has any lowercase characters. Otherwise, print False.
357 | In the fifth line, print True if has any uppercase characters. Otherwise, print False.
358 | """
359 | s = "qA2"
360 | print(s.isalnum())
361 | def string_type(s):
362 | temp = []
363 |
364 | for char in s:
365 | temp.append(char.isalnum())
366 | if True in temp:
367 | print(True)
368 | else:
369 | print(False)
370 | temp =[]
371 |
372 | for char in s:
373 | temp.append(char.isalpha())
374 | if True in temp:
375 | print(True)
376 | else:
377 | print(False)
378 | temp =[]
379 |
380 | for char in s:
381 | temp.append(char.isdigit())
382 | if True in temp:
383 | print(True)
384 | else:
385 | print(False)
386 | temp =[]
387 |
388 | for char in s:
389 | temp.append(char.islower())
390 | if True in temp:
391 | print(True)
392 | else:
393 | print(False)
394 | temp =[]
395 |
396 | for char in s:
397 | temp.append(char.isupper())
398 | if True in temp:
399 | print(True)
400 | else:
401 | print(False)
402 | temp =[]
403 |
404 | z = "qA2"
405 | string_type(z)
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
--------------------------------------------------------------------------------
/strings.py:
--------------------------------------------------------------------------------
1 | """
2 | The folowing text is given:
3 | text = 'python is a popular programming language.'
4 | Use the appropriate method to replace the first letter
5 | of the text with uppercase. Print the result to console
6 | """
7 |
8 | from typing import Counter
9 |
10 |
11 | text = 'python is a popular programming language.'
12 | print(text.capitalize())
13 |
14 | # Count the number of occurrences of the letter 'p' and
15 | # print the result to the consle as shown
16 | # Number of occurrencies: 4
17 |
18 | #cnt = Counter(text)
19 | print(f"Number of occurences: {text.count('p')}")
20 |
21 | # Check if string ends with a substring
22 | """
23 | The following codes are given:
24 | code1 = 'FVNISJND-XX-2020'
25 | code2 = 'FVNISJND-XY-2019'
26 |
27 | Using the appropriate method check if the codes end in '2020'.
28 | Print the results to the console as shown below:
29 | code1: True
30 | code2: False
31 |
32 | """
33 | code1 = 'FVNISJND-XX-2020'
34 | code2 = 'FVNISJND-XY-2019'
35 | print(f"code1: {code1.endswith('2020')}")
36 | print(f"code2: {code2.endswith('2020')}")
37 |
38 | """
39 | The following paths are given:
40 |
41 | path1 = 'https://e-smartdata.teachable.com/p/sciezka-data-scientist-machine-learning-engineer'
42 | path2 = 'https://e-smartdata.teachable.com/p/sciezka-data-scientist-deep-learning-engineer'
43 | path3 = 'https://e-smartdata.teachable.com/p/sciezka-bi-analyst-data-analyst'
44 | Using the appropriate method, find the word 'scientist' in the given paths,
45 | returning the index for the first letter of the found word. If the word is
46 | not in the path, the method should return -1. Print the result to the console
47 | as shown below:
48 |
49 | path1: 49
50 | path2: 49
51 | path3: -1
52 | """
53 |
54 | path1 = 'https://e-smartdata.teachable.com/p/sciezka-data-scientist-machine-learning-engineer'
55 | path2 = 'https://e-smartdata.teachable.com/p/sciezka-data-scientist-deep-learning-engineer'
56 | path3 = 'https://e-smartdata.teachable.com/p/sciezka-bi-analyst-data-analyst'
57 |
58 | print(f"path1: {path1.find('scientist')}")
59 | print(f"path2: {path2.find('scientist')}")
60 | print(f"path3: {path3.find('scientist')}")
61 |
62 | # isalnum
63 | """
64 | The following codes are given:
65 |
66 | code1 = 'FVNISJND-20'
67 | code2 = 'FVNISJND20'
68 | Using the appropriate method, check whether the codes consist only of
69 | alphanumeric characters (numbers + letters). Print the result to
70 | the console as shown below:
71 |
72 | code1: False
73 | code2: True
74 | """
75 | code1 = 'FVNISJND-20'
76 | code2 = 'FVNISJND20'
77 | print(f'code1: {code1.isalnum()}')
78 | print(f"code2: {code2.isalnum()}")
79 |
80 | # strip()
81 | """
82 | The following text is given:
83 |
84 | text = ' Google Colab '
85 | Using appropriate method, remove whitespace characters around the text.
86 | Print the result to the console
87 | """
88 | text = ' Google Colab '
89 | print(text.strip())
90 |
91 | """
92 | The following text is given:
93 |
94 | txt = ",,,,,rrttgg.....banana....rrr"
95 | Using appropriat method, remove the characters: ,.grt
96 | Print the output to the console as shown below:
97 |
98 | banana
99 | """
100 | txt = ",,,,,rrttgg.....banana....rrr"
101 | x = txt.strip(",.grt")
102 | print(x)
103 |
104 | # replace()
105 | """
106 | The following code is given:
107 |
108 | code = 'FVNISJND-XX'
109 | Using the appropriate method, replace the dash with a space.
110 | Print the output to the console as shown below:
111 |
112 | FVNISJND XX
113 | """
114 | code = 'FVNISJND-XX'
115 | print(code.replace('-', ' '))
116 |
117 | # remove all dashes from the text below
118 | text = '340-23-245-235'
119 | print(text.replace("-", ''))
120 |
121 | # split()
122 | """
123 | The folowing text is given:
124 |
125 | text = 'Open,High,Low,Close'
126 | Using the appropriate method split the text by comma.
127 | Print the result to the console as shown below:
128 |
129 | ['Open', 'High', 'Low', 'Close']
130 | """
131 | text = 'Open,High,Low,Close'
132 | print(text.split(','))
133 |
134 |
135 | # The following text is given
136 | #
137 | # text = """Python is a general-purpose language.
138 | # Python is popular."""
139 | # Using appropriate method, split the text into sentences.
140 | # print the result to the console as shown belos
141 | #
142 | # ['Python is a general-purpose language.', 'Python is popular']
143 | #
144 |
145 | text = """Python is a general-purpose language.
146 | Python is popular."""
147 |
148 | print(text.strip('"').split('\n'))
149 |
150 | """
151 | The following variable is given:
152 |
153 | num = 34
154 | Using the appropriate method for an object of type str, print
155 | the variable num preceded by four zeros to console as shown:
156 |
157 | 000034
158 | """
159 | num = 34
160 | print(str(num).zfill(6))
161 |
162 |
163 | """
164 | From the given url:
165 | url = 'https://e-smartdata.teachable.com/p/sciezka-data-scientist-machine-learning-engineer'
166 | extract the slug after the last character '/'. Then replace all dashes
167 | with spaces and print the result to console as shown below:
168 | """
169 |
170 | url = 'https://e-smartdata.teachable.com/p/sciezka-data-scientist-machine-learning-engineer'
171 | slug = url.split('/')[4] # or url.split('/)[-1]
172 | print(slug.replace('-', ' '))
173 |
174 |
175 | """
176 | Write 3 Python functions that parse and output only the date and time part of each log
177 | in log.txt as follows.
178 |
179 | Content of "log.txt":
180 | 10.1.2.1 - car [01/Mar/2022:13:05:05 +0900] "GET /python HTTP/1.0" 200 2222
181 | 10.1.1.9 - bike [01/Mar/2022:13:05:10 +0900] "GET /python HTTP/1.0" 200 2222
182 |
183 | Expected output:
184 | 01/Mar/2022:13:05:05 +0900
185 | 01/Mar/2022:13:05:10 +0900
186 | """
187 | def parse1():
188 | for line in open("log.txt"):
189 | print(line.split("[")[1].split("]")[0])
190 |
191 | def parse2():
192 | for line in open("log.txt", "rw"):
193 | print(" ".join(line.split()[3:5]).strip("[]"))
194 |
195 | def parse3():
196 | for line in open("log.txt"):
197 | print(re.split("\[|\]", line)[1])
198 |
199 |
200 | class FunEvent:
201 | def __init__(self, tags, year):
202 | self.tags = tags
203 | self.year = year
204 |
205 | def __str__(self):
206 | return f"FunEvent(tags={self.tags}, year={self.year})"
207 |
208 | tags = ["google", "ml"]
209 | year = 2022
210 | bootcamp = FunEvent(tags, year)
211 | print(f'First bootcamp: {bootcamp}')
212 | tags.append("bootcamp")
213 | year = 2023
214 | print(bootcamp)
215 |
216 |
217 | class BaseLayer:
218 | def __init__(self, name=""):
219 | self.name = name
220 |
221 | def __repr__(self):
222 | return f"{self.name}Layer"
223 |
224 | class ActivationLayer(BaseLayer):
225 | def __init__(self, size):
226 | super().__init__("Activation")
227 | self.size = size
228 |
229 | class FCLayer(BaseLayer):
230 | def __init__(self, size):
231 | super().__init__("FullyConnected")
232 | self.size = size
233 |
234 | print(FCLayer(42))
235 |
236 |
--------------------------------------------------------------------------------
/summary.py:
--------------------------------------------------------------------------------
1 | """
2 | Consider the problem of binary classification in machine learning. We have the
3 | following y_true list with classes from the test set and the follwoing y_prod list
4 | with classes provided by the model:
5 | y_true = [0, 0, 1, 1, 0, 1, 0]
6 | y_pred = [0, 0, 1, 0, 0, 1, 0]
7 | Our task is to implement a function called accuracy(), which takes two arguments
8 | y_true and y_pred and calculates the accuracy of our model. The result is rounded to
9 | four decimal places
10 | """
11 | from dataclasses import fields
12 | from itertools import count
13 | from optparse import Values
14 |
15 |
16 | y_true = [0, 0, 1, 1, 0, 1, 0]
17 | y_pred = [0, 0, 1, 0, 0, 1, 0]
18 |
19 | def accuracy(y_true, y_pred):
20 | cnt = 0
21 | for i, j in zip(y_true, y_pred):
22 | if i == j:
23 | cnt +=1
24 | return round(cnt/len(y_true), 4)
25 | print(accuracy(y_true, y_pred))
26 | print(zip(y_true, y_pred))
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/temp.py:
--------------------------------------------------------------------------------
1 | S = [1, 1, 1, 2, 2, 2, 3, 1, 1]
2 | def compress_string(S):
3 | result = []
4 | temp = []
5 | repeat = []
6 |
7 |
8 |
9 | if len(S) == 0:
10 | return "string must contain at least 1 element"
11 | S = S[::-1]
12 | print("reverse", S)
13 |
14 | while len(S):
15 | temp.append(S.pop())
16 | while S[-1] == temp[-1]:
17 | temp.append(S.pop())
18 | result.append(temp[-1])
19 | repeat.append(len(temp))
20 | print(result)
21 | print(repeat)
22 | temp = []
23 | answer = dict(zip(result, repeat))
24 | print("numbe, repeat", answer)
25 |
26 |
27 |
28 | compress_string(S)
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import array
2 | from curses.ascii import isdigit
3 |
4 |
5 | nums = [2,1,2,3,5]
6 | missing = [num for num in range(1, len(nums)+1) if num not in nums]
7 | duplicate = [num for num in nums if nums.count(num)>1]
8 | result = (duplicate[1], missing[0])
9 | print(result)
10 |
11 | # a = list(map(int, input().split()))
12 | # b = list(map(int, input().split()))
13 | # result = [(i, j) for i in a for j in b]
14 | # for i in result:
15 | # print(i, end=" ")
16 |
17 | # s, num = input().split()
18 | # print(f's: {s}, num: {num}')
19 |
20 | """
21 | Valid Parenthesis:
22 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
23 | determine if the input string is valid.
24 |
25 | An input string is valid if:
26 | Open brackets must be closed by the same type of brackets.
27 | Open brackets must be closed in the correct order.
28 | """
29 | def brackets(s):
30 | stack = []
31 | if len(s) % 2 != 0:
32 | return 'invalid'
33 | dic = {'(': ')', '{': '}', '[': ']' }
34 | for i in s:
35 | if i in dic.keys():
36 | stack.append(i)
37 | print(stack)
38 | else:
39 | if stack == []:
40 | return 'invalid'
41 | a = stack.pop()
42 | if i != dic[a]:
43 | return 'invalid'
44 | return 'valid'
45 |
46 | s = "({[]})"
47 | print(brackets(s))
48 |
49 | # print(f's: {s}')
50 |
51 | # stack2 = []
52 | # if stack2:
53 | # print('Yes')
54 | # else:
55 | # print("No")
56 |
57 | arr = [2, 3]
58 | print(f' Type arr: {type(arr)}')
59 | if type(arr) == list:
60 | print(f'{arr} is a list array')
61 | else:
62 | print("Not a list array")
63 |
64 | # l = [1, 2, 3]
65 | # permutation = [[i, j, k] for i, j, k in l]
66 | # print(f'Permutation of {l}: {permutation}')
67 |
68 | lines = [1,2,3,4,5,6,7,8,9]
69 | print(lines[-4:])
70 |
71 | # import re
72 | # with open('log.txt', 'r') as lines:
73 | # for line in lines:
74 | # #print(line[3])
75 | # print(line.split("[")[1].split("]")[0])
76 | # #print(line.split()[3].strip("[]"))
77 | # #print(line.split("[" or "]"[3:5]))
78 | # #print(" ".join(line.split()[3:5]).strip("[]"))
79 | # #print(re.split("\[|\]", line)[1])
80 |
81 |
82 | class Node:
83 | def __init__(self, value):
84 | self.value = value
85 | self.next = None
86 | self.prev = None
87 |
88 | def link_nodes(node1, node2):
89 | node1.next = node2
90 | node2.prev = node1
91 |
92 | class DoublyLinkedList:
93 | def __init__(self):
94 | self.head = None
95 | self.tail = None
96 |
97 | def remove(self, node):
98 | # remove from head or tail
99 | if self.head == node:
100 | self.head = node.next
101 | if self.tail == node:
102 | self.tail = node.prev
103 |
104 | # remove from inside the list
105 | if node.prev:
106 | node.prev.next = node.next
107 | if node.next:
108 | node.next.prev = node.prev
109 | # remove the existing pointers on the node
110 | node.next = None
111 | node.prev = None
112 |
113 | def display(self):
114 | #Node current will point to head
115 | current = self.head;
116 | if(self.head == None):
117 | print("List is empty");
118 | return;
119 | print("Nodes of doubly linked list: ");
120 | while(current != None):
121 | #Prints each node by incrementing pointer.
122 | print(current.value, end=" "),;
123 | current = current.next;
124 |
125 | one = Node(1)
126 | two = Node(2)
127 | three = Node(3)
128 | four = Node(4)
129 | five = Node(5)
130 |
131 | linked_list_doubly = DoublyLinkedList()
132 |
133 | link_nodes(one,two)
134 | link_nodes(two,three)
135 | link_nodes(three,four)
136 | link_nodes(four,five)
137 | linked_list_doubly.head = one
138 | linked_list_doubly.tail = five
139 |
140 | linked_list_doubly.display()
141 | linked_list_doubly.remove(two)
142 | linked_list_doubly.display()
143 |
144 |
145 | height = 100
146 | bounce = 1
147 | while bounce <= 3:
148 | height = height * (3/5)
149 | bounce += 1
150 | new = height
151 | print(new)
152 |
153 |
154 | S = "111222311"
155 | def compress_string(S):
156 | result = []
157 | temp = []
158 | i = 0
159 | j = i+1
160 | cnt = 1
161 |
162 | if len(S) == 0:
163 | return "string must contain at least 1 element"
164 | while S[j]:
165 | temp.append(S[i])
166 | while S[i] == S[j]:
167 | cnt += 1
168 | i += 1
169 | result.append((cnt, temp[-1]))
170 | temp = []
171 | print(f'Groups: {result}')
172 |
173 | compress_string(S)
174 |
175 | arr = [1, 2, 3, 4]
176 | print(f'Arr.pop {arr.pop([0])}')
--------------------------------------------------------------------------------
/test2.py:
--------------------------------------------------------------------------------
1 | from curses.ascii import islower
2 | from itertools import combinations, permutations
3 |
4 |
5 |
6 | x = [1, 2, 3, 4]
7 | y = [5, 6]
8 | x.append(y)
9 | print(x)
10 |
11 |
12 | """
13 | Rotate an array to the right by k elements
14 | """
15 | def rotate_array(arr, k):
16 | end = len(arr)-1
17 | if k <= 0:
18 | return arr
19 | for i in range(0, k, 1):
20 | #a, b = arr[0], arr[end]
21 | # arr = [arr[end]] + [arr[0]] + arr[1:end]
22 | arr = [arr[end]] + arr[0:end]
23 | return arr
24 | print(rotate_array([1, 2, 3, 4, 5], 4))
25 |
26 |
27 | text = """Python is powerful... and fast
28 | plays well with others
29 | runs everywhere
30 | is friendly & easy to learn
31 | is Open
32 | These are some of the reasons people who use Python would rather not use anything else"""
33 |
34 | # words = text.lower().strip().replace('.', '').split()
35 | # result = []
36 | # for word in words:
37 | # if len(word) > 6:
38 | # result.append(word)
39 | # print(result)
40 |
41 | # Another solution using list comprehension
42 | words = text.lower().strip().replace('.', '').replace(',', '').split()
43 | words = [word for word in words if len(word) > 6]
44 | print(words)
45 |
46 |
47 | ###############################
48 | x=1; y=1; z=2; n=3
49 | result = [[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if (a+b+c) != n]
50 | print(result)
51 |
52 | ################################
53 |
54 | def score_words(words):
55 | str = words.split()
56 | score = 0
57 |
58 | for word in str:
59 | if len(word)%2 == 0:
60 | score+=2
61 | print(score)
62 |
63 | score_words("programming is awesome")
64 | #################################
65 |
66 | # All substrings of a string and calculate how many that starts with vowels and consonants
67 | def minion_game(string_):
68 | vowel_strings = 0
69 | consonant_strings = 0
70 | string_length = len(string_) # length of string
71 |
72 | for i in range(string_length):
73 | if string_[i] in "AEIOU":
74 | vowel_strings += string_length - i
75 | else:
76 | consonant_strings += string_length -i
77 |
78 | # Determine the winner
79 | if consonant_strings > vowel_strings:
80 | print("Stuart", consonant_strings )
81 | elif consonant_strings < vowel_strings:
82 | print("Kevin", vowel_strings)
83 | else:
84 | print("Draw")
85 |
86 | minion_game("BANANA")
87 |
88 | def merge_the_tools(string, k):
89 | sub_sequences = []
90 | temp = ""
91 | for i in range(0, len(string), k):
92 | sub_sequences.append((string[i:i+k]))
93 | print(sub_sequences)
94 | print("lenght of subsequence: ",len(sub_sequences))
95 |
96 | # check for duplicate alphabets
97 | for string in sub_sequences:
98 | for i in range(k):
99 | if string[i] not in temp:
100 | temp += string[i]
101 | print(temp)
102 | temp = ""
103 |
104 | s = 'AAABCADDE'
105 | merge_the_tools(s, 3)
106 |
107 |
108 | def swap_case(s):
109 | result = ""
110 | for i in range(len(s)):
111 | if s[i].isupper():
112 | s = s.replace(s[i], s[i].upper())
113 | else:
114 | s = s.replace(s[i], s[i].lower())
115 |
116 |
117 | print(s)
118 | return s
119 |
120 | t = "Www.HackerRank.com"
121 | swap_case(t)
122 |
123 | B = "baNM.y"
124 | C = "caLY"
125 | d = ""
126 | if B[1].islower():
127 | d += B[1].upper()
128 | print(d)
129 | print(B[4].isupper())
130 | print(B[1].upper())
131 | print(C[2].isupper())
132 |
--------------------------------------------------------------------------------
/test3.py:
--------------------------------------------------------------------------------
1 | def swap_case(s):
2 | result = ""
3 | for i in range(len(s)):
4 | if s[i].isupper():
5 | result += s[i].lower()
6 | else:
7 | result += s[i].upper()
8 | return result
9 |
10 | t = "Www.HackerRank.com"
11 | swap_case(t)
12 |
13 | def count_substring(string, sub_string):
14 | substring_length = len(sub_string)
15 | string_length = len(string)
16 | end = string_length - 2
17 | cnt = 0
18 |
19 | for i in range(0, end):
20 | if string[i:i+substring_length] == sub_string:
21 | cnt += 1
22 | return cnt
23 |
24 | s = "ABCDCDC"
25 | sub = "CDC"
26 | count_substring(s, sub)
27 |
28 |
29 | def string_type(s):
30 | temp = []
31 |
32 | for char in s:
33 | temp.append(char.isalpha())
34 | if True in temp:
35 | print(True)
36 | else:
37 | print(False)
38 | temp =[]
39 |
40 | for char in s:
41 | temp.append(char.isalpha())
42 | if True in temp:
43 | print(True)
44 | else:
45 | print(False)
46 | temp =[]
47 |
48 | for char in s:
49 | temp.append(char.isdigit())
50 | if True in temp:
51 | print(True)
52 | else:
53 | print(False)
54 | temp =[]
55 |
56 | for char in s:
57 | temp.append(char.islower())
58 | if True in temp:
59 | print(True)
60 | else:
61 | print(False)
62 | temp =[]
63 |
64 | for char in s:
65 | temp.append(char.isupper())
66 | if True in temp:
67 | print(True)
68 | else:
69 | print(False)
70 | temp =[]
71 |
72 | z = "qA2"
73 | string_type(z)
74 |
--------------------------------------------------------------------------------
/trees.py:
--------------------------------------------------------------------------------
1 | """
2 | Design a Binary Search Tree class that supports the following:
3 | 1. Insert a value
4 | 2. Remove a value. This method shold remove the first occurence of a value
5 | 3. Find a value. If the value is found it should return the node with the value
6 | else return false.
7 | """
8 |
9 | class Node:
10 | def __init__(self, value):
11 | self.value = value
12 | self.left = None
13 | self.right = None
14 |
15 |
16 | class BinarySearchTree:
17 | def __init__(self):
18 | self.root = None
19 |
20 | def insert(self, value):
21 | node = Node(value)
22 | if not self.root: #if there is no root, make the node the root
23 | self.root = node
24 | return self
25 | tree = self.root # else, store the root in tree variable
26 | while True:
27 | if value < tree.value:
28 | # move left
29 | if not tree.left: # if the node is a leaf
30 | tree.left = node
31 | return self
32 | tree = tree.left
33 | else:
34 | # move right
35 | # value > = tree.value
36 | if not tree.right:
37 | tree.right = node
38 | return self
39 | tree = tree.right
40 |
41 |
42 | def find(self, value):
43 | if not self.root:
44 | return False
45 | tree = self.root
46 | while tree:
47 | if value < tree.value:
48 | # move left
49 | tree = tree.left
50 | elif value > tree.value:
51 | # move right
52 | tree = tree.right
53 | elif value == tree.value:
54 | return tree
55 | return False
56 |
57 |
58 | def remove(self, value, current, parent=None):
59 | current = self.root
60 | if not self.root:
61 | return False
62 | while current:
63 | if value < current.value:
64 | parent = current
65 | current = current.left
66 | elif value > current.value:
67 | parent = current
68 | current = current.right
69 | else:
70 | # found the node to be deleted
71 | # if node to be deleted has 2 children
72 | if current.left != None and current.right != None:
73 | current.value = self.getMin(current.right)
74 | self.remove(current.value, current.right, current) #remove the min value
75 | elif parent != None: # if deleting the root node
76 | if current.left != None: #if it has a lefft child only.
77 | current.value = current.left.value
78 | current.left = current.left.left
79 | current.right = current.left.right
80 | elif current.right != None: # if it has a right child only
81 | current.value = current.right.value
82 | current.left = current.right.left
83 | current.right = current.right.right
84 | else:
85 | # this is a single node bst
86 | self.root = None
87 | elif current == parent.left:
88 | parent.left = current.left if current.left != None else current.right
89 | elif current == parent.right:
90 | parent.right = current.left if current.left != None else current.right
91 | # break out of the while loop
92 | break
93 | return self
94 |
95 | def getMin(self, value):
96 | node = Node(value)
97 | while node.left != None:
98 | node = node.left
99 | return node.value
100 |
101 | def breadth_first(self):
102 | if self.root == None:
103 | return []
104 | arr = []
105 | # queue as array to save time (queue as linked list is better)
106 | queue = []
107 | node = self.root
108 | while len(queue):
109 | node = queue.pop(0)
110 | arr.append(node)
111 | if node.left:
112 | queue.append(node.left)
113 | if node.right:
114 | queue.append(node.right)
115 | return arr
116 |
117 | def dfs_in_order(self):
118 | if self.root == None:
119 | return []
120 | arr = []
121 | current = self.root
122 | def trav(self, node):
123 | if node.left:
124 | trav(node.left)
125 | arr.append(node)
126 | if node.right:
127 | trav(node.right)
128 | trav(current)
129 | return arr
130 |
131 | # current, left, right
132 | def dfs_pre_order(self):
133 | if self.root == None:
134 | return []
135 | arr = []
136 | current = self.root
137 | def trav(self, node):
138 | node = Node(self, node)
139 | arr.append(node)
140 | if node.left:
141 | trav(node.left)
142 | if node.right:
143 | trav(node.right)
144 | trav(current)
145 | return arr
146 |
147 | # left, right, current
148 | def dfs_post_order(self):
149 | if self.root == None:
150 | return []
151 | arr = []
152 | current = self.root
153 | def trav(node):
154 | if node.left:
155 | trav(node.left)
156 | if node.right:
157 | trav(node.right)
158 | arr.append(node)
159 | trav(current)
160 | return arr
161 |
162 |
163 | """
164 | Write a 4 instance methods for a Binary Search Tree class to traverse the BST
165 | 1. Method 1: traverse the tree breadth first and return an array that contains
166 | all values of the BST
167 | 2. Method 2: traverse the tree depth first - in-order and return an array that
168 | contains all the values of the BST
169 | 3. Method 3: traverse the tree depth first - Pre-order and return an array that
170 | contains all the values fo the BST
171 | 4. Method 4: traverse the tree depth first - Post-order and return an array that
172 | contains all the values of the BST
173 | """
174 | # implemented in the BinarySearchTree class
175 | # 1. breadth_first()
176 | # 2. dfs_in_order()
177 | # 3. dfs_pre_order()
178 | # 4. dfs_post_order()
179 |
180 |
181 |
182 | bst = BinarySearchTree()
183 |
184 | bst.insert(20)
185 | bst.insert(6)
186 | bst.insert(35)
187 | bst.insert(3)
188 | bst.insert(8)
189 | bst.insert(27)
190 | bst.insert(55)
191 | bst.insert(1)
192 | bst.insert(3)
193 | bst.insert(25)
194 | bst.insert(29)
195 | bst.insert(60)
196 |
197 | print(f'breadth first: {bst.breadth_first()}')
198 |
199 |
200 | """
201 | Write a function that takes the root of a binary tree, and returns the level order
202 | traversal of its nodes' values. (i.e., from left to right, level by level). Initially
203 | write an instance method for the Binary Search tree class to insert the values given
204 | as an array into the Binary tree (from left to right, level by level). Each value in
205 | the array which is not null is to be made a node and added to the tree
206 | """
207 | class BinaryTree:
208 | def __init__(self):
209 | self.root = None
210 |
211 | def insert(self, arr):
212 | if len(arr) == 0:
213 | return
214 | i = 0
215 | # if root is null
216 | if not self.root:
217 | if arr[0] == None:
218 | return
219 | else:
220 | node = Node(arr[0])
221 | self.root = node
222 | i += 1
223 | if i == len(arr):
224 | return self
225 | # insert elements
226 | queue = [self.root]
227 | while queue:
228 | current = queue.pop(0)
229 | # left
230 | if not current.left:
231 | if arr[i] is not None:
232 | node = Node(arr[i])
233 | current.left = node
234 | i += 1
235 | if i == len(arr):
236 | return self
237 | if current.left:
238 | queue.append(current.left)
239 | # right
240 | if not current.right:
241 | if arr[i] is not None:
242 | node = Node(arr[i])
243 | current.right = node
244 | i += 1
245 | if i == len(arr):
246 | return self
247 | if current.right:
248 | queue.append(current.right)
249 |
250 |
251 | def level_order_traversal(root):
252 | if not root:
253 | return []
254 | output = []
255 | queue = [root]
256 | while len(queue):
257 | length = len(queue)
258 | count = 0
259 | curr_level_values = []
260 | while count < length:
261 | curr = queue.pop(0)
262 | curr_level_values.append(curr)
263 | if curr.left:
264 | queue.append(curr.left)
265 | if curr.right:
266 | queue.append(curr.right)
267 | count += 1
268 | output.append(curr_level_values)
269 |
270 |
271 |
272 | tree = BinaryTree()
273 | tree.insert([7,11,1,None,7,2,8,None,None,None,3,None,None,5,None])
274 |
275 | print(level_order_traversal(tree.root))
276 |
277 |
278 | """
279 | 1. Given the root of a binary tree, imagine yourself standing on the right side of it
280 | return the values of the nodes you can see ordered from top to bottom.
281 | 2. Given the root of the binary tree, imagine yourself standing on the left side of it
282 | return the values of the nodes you can see ordered from top to bottom
283 | """
284 | def right_view(root):
285 | if not root:
286 | return []
287 | right = []
288 | queue = [root]
289 | while len(queue):
290 | length = len(queue)
291 | count = 0
292 | while count < length:
293 | count += 1
294 | current = queue.pop(0)
295 | if count == length:
296 | right.append(current)
297 | if current.left:
298 | queue.append(current.ledft)
299 | if current.right:
300 | queue.append(current.right)
301 | return right
302 |
303 |
304 | def left_view(value):
305 | root = Node(value)
306 | if not root:
307 | return []
308 | left = []
309 | queue = [root]
310 | while len(queue):
311 | length = len(queue)
312 | count = 0
313 | while count < length:
314 | count += 1
315 | current = queue.pop(0)
316 | if count == 1:
317 | left.append(current.value)
318 | if current.left:
319 | queue.append(current.left)
320 | if current.right:
321 | queue.append(current.right)
322 | return left
323 |
324 |
325 | """
326 | Given the root of a binary tree, invert the tree, and return its root.
327 | (Invert means to swap every left node for its corresponding right node/get mirror image)
328 | """
329 | def invert_iterative(value):
330 | root = Node(value)
331 | if not root:
332 | return []
333 | queue = [root]
334 | while len(queue):
335 | current = queue.pop(0)
336 | # swap left and right
337 | temp = current.right
338 | current.right = current.left
339 | current.left = temp
340 | if current.left:
341 | queue.append(current.left)
342 | if current.right:
343 | queue.append(current.right)
344 | return root
345 |
346 |
347 | def invert_recursive(value):
348 | node = Node(value)
349 | if not node:
350 | return []
351 | # swap
352 | temp = node.left
353 | node.left = node.right
354 | node.right = temp
355 | # recursive call
356 | invert_recursive(node.left)
357 | invert_recursive(node.right)
358 | return node
359 |
--------------------------------------------------------------------------------
/tuples.py:
--------------------------------------------------------------------------------
1 | """
2 | Two following tuples are given:
3 |
4 | dji1 = ('AAPL.US', 'IBM.US', 'MSFT.US')
5 | dji2 = ('HD.US', 'GS.US', 'NKE.US')
6 | Combine these tuples into one as shown below and print result to console
7 |
8 | ('AAPL.US', 'IBM.US', 'MSFT.US', 'HD.US', 'GS.US', 'NKE.US')
9 | """
10 | from itertools import count
11 |
12 |
13 | dji1 = ('AAPL.US', 'IBM.US', 'MSFT.US')
14 | dji2 = ('HD.US', 'GS.US', 'NKE.US')
15 | result = dji1 + dji2
16 | print(result)
17 |
18 |
19 | """
20 | The following tuples are given:
21 |
22 | dji1 = ('AAPL.US', 'IBM.US', 'MSFT.US')
23 | dji2 = ('HD.US', 'GS.US', 'NKE.US')
24 | Nest these tuples into one tuple as shown below and print the result
25 | to console
26 |
27 | Expected result:
28 | (('AAPL.US', 'IBM.US', 'MSFT.US'), ('HD.US', 'GS.US', 'NKE.US'))
29 | """
30 | dji1 = ('AAPL.US', 'IBM.US', 'MSFT.US')
31 | dji2 = ('HD.US', 'GS.US', 'NKE.US')
32 | result = (dji1, dji2)
33 | print(result)
34 |
35 |
36 | """
37 | Tuples are immutable. The following tuple is given:
38 |
39 | members = (('Kate', 23), ('Tom', 19))
40 | insert a tuple ('John', 26) between Kate and Tom as shown belo.
41 | Print the result to the console
42 |
43 | Tip: You have to create a new tuple
44 |
45 | Expected result:
46 | (('Kate', 23), ('John', 26), ('Tom', 19))
47 | """
48 |
49 | members = (('Kate', 23), ('Tom', 19))
50 | members = (members[0], ('John', 26), members[1])
51 | print(members)
52 |
53 |
54 | """
55 | The following is given:
56 | default = ('YES', 'NO', 'NO', 'YES', 'NO')
57 | Using the appropriate method return the number of occurrences of the
58 | string 'YES' and print the result to the console as shown below
59 |
60 | Number of occurences: 2
61 | """
62 |
63 | default = ('YES', 'NO', 'NO', 'YES', 'NO')
64 | cnt = default.count('YES')
65 | print(f'Number of occurences: {cnt}')
66 |
67 |
68 | """
69 | Sort the given tuple (from A to Z)
70 |
71 | names = ('Monica', 'Tom', 'John', 'Michael')
72 | Print the sorted tuple to the console as shown below
73 |
74 |
75 | """
76 | names = ('Monica', 'Tom', 'John', 'Michael')
77 |
78 | result = tuple(sorted(names))
79 | print(result)
80 |
81 |
82 | """
83 | The following tuple is given (name,age):
84 |
85 | info = (('Monica', 19), ('Tom', 21), ('John', 18))
86 | Sort the tuple:
87 | - ascending by age
88 | - descending by age
89 | And print the result to the console as shown below
90 |
91 |
92 | """
93 |
94 | info = (('Monica', 19), ('Tom', 21), ('John', 18))
95 | asc = tuple(sorted(info, key=lambda item: item[1]))
96 | desc = tuple(sorted(info, key=lambda item: item[1], reverse=True))
97 | print(f'Ascending: {asc}')
98 | print((f'descending: {desc}'))
99 |
100 |
101 | """
102 | The following tuple is given:
103 | stocks = (('Apple Inc', ('AAPL.US', 310)), ('Microsoft Corp', ('MSFT.US', 184)))
104 | Extract a ticker for Apple and print the result to the comsole.
105 |
106 | Expected result:
107 | APPL.US
108 | """
109 |
110 | stocks = (('Apple Inc', ('AAPL.US', 310)), ('Microsoft Corp', ('MSFT.US', 184)))
111 | print(stocks[0][1][0])
112 |
--------------------------------------------------------------------------------
/tx.py:
--------------------------------------------------------------------------------
1 | with open("block.txt", "r") as txs:
2 | lines = txs.readlines()
3 | print(lines)
--------------------------------------------------------------------------------
/users.csv:
--------------------------------------------------------------------------------
1 | user_id,amount
2 | 001,1400
3 | 004,1300
4 | 007,900
5 |
--------------------------------------------------------------------------------
/while.py:
--------------------------------------------------------------------------------
1 | """
2 | Write a program that prints to the console the first ten prim numbers
3 | separated by comma
4 |
5 | Tip: use the while loop with break statement
6 | Expected result
7 | 2,3,5,7,11,13,17,19,23,29
8 | """
9 | counter = 0
10 | number = 2
11 | prime = []
12 | while counter < 10:
13 | for i in range(2, number):
14 | if number%i == 0:
15 | break
16 | else:
17 | prime.append(str(number))
18 | counter +=1
19 | number +=1
20 | print(','.join(prime))
21 |
22 |
23 | """
24 | Using the while loop, calculate how many years you have to wait for the
25 | return on the investment described below to at least double your
26 | money (we only take into account full periods).
27 |
28 | Description
29 | n - number of periods (in years)
30 | pv - present value
31 | r - interest rate (annual)
32 | fv - future value
33 |
34 | Invstment paramenters
35 | pv = 1000
36 | r = 0.04
37 | Print result tothe console as shown below:
38 | Future value: 2025.82 USD. Number of period: 18 years
39 | """
40 | pv = 1000
41 | r = 0.04
42 | fv = pv * (1 + r)
43 | n = 1
44 | while fv <= 2000:
45 | fv = fv * (1+r)
46 | n += 1
47 | print(f'Future value: {fv :.2f} USD. Number of period: {n} years')
48 |
49 |
50 | """
51 | Write a program that checks if the given element (target) is in the
52 | sorted list (numbers). Given:
53 |
54 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
55 | target = 7
56 |
57 | Algorithim:
58 |
59 | 1. We set the start and end index as well as the flag = None
60 |
61 | 2. As long as the start index is not greater than the end index, select the
62 | middle index mid of the list (arithmetic average of the start and end index =>
63 | remember to convert the result with the int() function). If the start index
64 | is greater than the end index, we end the algorithm.
65 |
66 | 3. Check if the element for the index calculated in this way is our target.
67 | If so, we set the flag to True and terminate the algorithm. If not => step 4.
68 |
69 | 4. We check if the element of the list for the index mid is less than the target. If so, we increase the start index by 1. If not, we reduce the end index by 1 and go to step 2.After while loop, depending on the value of the flag, print to the console:'Found' or 'Not found'
70 | """
71 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
72 | target = 7
73 | start = 0
74 | end = len(numbers) - 1
75 | flag = None
76 |
77 | while start <= end:
78 | mid = int((start + end) / 2)
79 | if numbers[mid] == target:
80 | flag = True
81 | break
82 | else:
83 | if numbers[mid] < target:
84 | start = mid + 1
85 | else:
86 | end = mid - 1
87 |
88 | if flag:
89 | print('Found')
90 | else:
91 | print('Not found')
92 |
--------------------------------------------------------------------------------
/zip.py:
--------------------------------------------------------------------------------
1 | """
2 | Traverse list in parralel using the zip() function. Given:
3 | letters = ['a', 'b', 'c']
4 | numbers = [0, 1, 2]
5 | Expected result:
6 | Letter: a
7 | Number: 0
8 | Letter: b
9 | Number: 1
10 | Letter: c
11 | Number: 2
12 | """
13 | letters = ['a', 'b', 'c']
14 | numbers = [0, 1, 2]
15 | for l, n in zip(letters, numbers):
16 | print(f'Letter: {l}')
17 | print(f'Number: {n}')
18 |
19 |
20 | """
21 | Use zip() to iterate through two dictionaries in parralel
22 |
23 | Expected result:
24 | name -> John
25 | name -> Jane
26 | last_name -> Doe
27 | last_name -> Doe
28 | job -> Python Consultant
29 | job -> Community Manager
30 | """
31 | dict_one = {'name': 'John', 'last_name': 'Doe', 'job': 'Python Consultant'}
32 | dict_two = {'name': 'Jane', 'last_name': 'Doe', 'job': 'Community Manager'}
33 | for (k1, v1), (k2, v2) in zip(dict_one.items(), dict_two.items()):
34 | print(k1, '->', v1)
35 | print(k2, '->', v2)
36 |
37 |
38 | """
39 | Separate a list tuples elements into independent sequences
40 | pairs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
41 |
42 | Expected result:
43 | numbers: (1, 2, 3, 4)
44 | letters: ('a', 'b', 'c', 'd')
45 | """
46 | pairs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
47 | numbers, letters = zip(*pairs)
48 | print(f'numbers: {numbers}')
49 | print(f'letters: {letters}')
50 |
51 |
52 | """
53 | Calculating in pairs using zip() function. Given the following monthly sales data:
54 | total_sales = [52000.00, 51000.00, 48000.00]
55 | prod_cost = [46800.00, 45900.00, 43200.00]
56 | calculate the monthly profit
57 |
58 | Expected result:
59 | Total profit: 5200.0
60 | Total profit: 5100.0
61 | Total profit: 4800.0
62 | """
63 | total_sales = [52000.00, 51000.00, 48000.00]
64 | prod_cost = [46800.00, 45900.00, 43200.00]
65 |
66 | for sales, cost in zip(total_sales, prod_cost):
67 | profit = sales - cost
68 | print(f'Total profit: {profit}')
69 |
70 |
71 | """
72 | Build dictionary from two lists using the zip() function. Given the following:
73 | fields = ['name', 'last_name', 'age', 'job']
74 | values = ['John', 'Doe', '45', 'Python Developer']
75 | Expected result:
76 | {'name': 'John', 'last_name': 'Doe', 'age': '45', 'job': 'Python Developer'}
77 | """
78 | fields = ['name', 'last_name', 'age', 'job']
79 | values = ['John', 'Doe', '45', 'Python Developer']
80 | a_dict = dict(zip(fields, values))
81 | print(a_dict)
--------------------------------------------------------------------------------