text
stringlengths
37
1.41M
def stringRotate(temp_str, rotate_str): if len(temp_str) == len(rotate_str): return rotate_str in (temp_str + temp_str) return False str1 = "race" str2 = "cere" print(stringRotate(str1, str2))
def findMin(nums): left,right=0,len(nums)-1 if nums[left]<nums[right]: return nums[0] while left<right: mid = left+(right-left)//2 if nums[mid]>nums[mid+1]: return nums[mid+1] elif nums[mid]>nums[right]: left=mid+1 else: right=right-1 return nums[left] nums = [4,5,6,7,0,1] print(findMin(nums))
def count(s): w_count, l_count, d_count = 0, 0, 0 for c in s: if c == "W": w_count += 1 elif c == "D": d_count += 1 elif c == "L": l_count += 1 res = "" while l_count or d_count or w_count: if w_count > 0: res += "W" w_count -= 1 if d_count > 0: res += "D" d_count -= 1 if l_count > 0: res += "L" l_count -= 1 return res s = "DLWDL" print(count(s))
class Node(object): def __init__(self, value): self.value = value self.next = None def insert_Node_toEnd(self, head, val_to_insert): currentNode = head while currentNode is not None: if currentNode.next is None: currentNode.next = Node(val_to_insert) return head currentNode = currentNode.next def delete_Node(self, head, val_to_delete): currentNode = head prevNode = None while currentNode is not None: if currentNode.value == val_to_delete: # if value to be deleted is first node if prevNode is None: newhead = currentNode.next currentNode.next = None return newhead prevNode.next = currentNode.next return head prevNode = currentNode currentNode = currentNode.next def insert_Node(self, head, val_to_Insert, position): currentNode = head prevNode = None currentpos = 0 new_node = Node(val_to_Insert) if not head: head = new_node if position == 0: currentNode.next = head head = new_node return head while currentNode is not None: if currentpos == position and currentNode.next: prevNode.next = new_node new_node.next = currentNode elif currentNode.next == None: currentNode.next = new_node break prevNode = currentNode currentNode = currentNode.next currentpos += 1 a = Node(1) b = Node(2) c = Node(3) a.next = b b.next = c # traverse and print linked list def print_LinkedList(head): currentNode = head while currentNode is not None: print(currentNode.value) currentNode = currentNode.next head = a print(head) # a.insert_Node_toEnd(a,5) # print_LinkedList(a) # a.delete_Node(a,2) # print("after") # print_LinkedList(a) a.insert_Node(a, 5, 3) print_LinkedList(a)
"""Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ class Solution: def singleNumber(self, nums: List[int]) -> int: dict1 = {} for num in nums: if num not in dict1: dict1[num] = 1 else: dict1[num] += 1 for k, v in dict1.items(): if v == 1: return k
def threeSumClosest(nums, target): minRes = float("inf") if not nums or len(nums) < 3: return 0 nums.sort() for i in range(len(nums)): low, high = i + 1, len(nums) - 1 while low < high: sumVal = nums[i] + nums[low] + nums[high] if sumVal == target: minRes = 0 break elif abs(target - sumVal) < abs(minRes): minRes = target - sumVal if sumVal < target: low += 1 else: high -= 1 if minRes == 0: break return target - minRes
""" Given an integer array, find three numbers whose product is maximum and output the maximum product. Input: [1,2,3,4] Output: 24 """ def maxProduct(nums): nums.sort() return max((nums[-3] * nums[-2] * nums[-1]), (nums[0] * nums[1] * nums[-1])) nums = [-4, -3, -2, -1, 60] print(maxProduct(nums))
def findMin(nums): left, right = 0, len(nums) - 1 # edge cases if nums[left] < nums[right]: return nums[left] if len(nums) == 1: return nums[0] while left <= right: mid = left + (right - left) // 2 if nums[mid] > nums[mid + 1]: return nums[mid + 1] elif nums[mid - 1] > nums[mid]: return nums[mid] elif nums[mid] > nums[left]: left = mid + 1 else: right = mid - 1 nums = [4, 5, 6, 7, 0, 1, 2] print(findMin(nums))
def dfs(board, i, j, word): if not word: return True if ( i < 0 or i > len(board) - 1 or j < 0 or j > len(board[0]) - 1 or board[i][j] != word[0] ): return False temp = board[i][j] board[i][j] = " " found = ( dfs(board, i + 1, j, word[1:]) or dfs(board, i - 1, j, word[1:]) or dfs(board, i, j - 1, word[1:]) or dfs(board, i, j + 1, word[1:]) ) board[i][j] = temp return found def exist(board, word): A = len(board) B = len(board[0]) for i in range(0, A): for j in range(0, B): if dfs(board, i, j, word): return True return False board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]] word = "ABCCED" print(exist(board, word))
def reverseWords(s): """ easy method that can be used in first round - please try using data structures """ # s = s.strip() # s2 = "" # lst = s.split() # return ' '.join(iter(lst[::-1])) i = 0 N = len(s) s2 = "" while i < N: while i < N and s[i] == " ": i += 1 j = i + 1 while j < N and s[j] != " ": j += 1 if s2 != "": s2 = s[i:j] + " " + s2 else: s2 += s[i:j] i = j + 1 return s2 s = "the sky is blue" s2 = " hello world! " s3 = "a good example" print(reverseWords(s2))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isMirror(self, node1, node2): if node1 is None and node2 is None: return True if node1 is not None and node2 is not None and node1.val == node2.val: return self.isMirror(node1.left, node2.right) and self.isMirror( node1.right, node2.left ) return False def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True return self.isMirror(root, root)
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def bfsHelper(node, level, levels): if node is None: return if len(levels) == level: levels.append([]) levels[level].append(node.val) if node.left: bfsHelper(node.left, level + 1, levels) if node.right: bfsHelper(node.right, level + 1, levels) def levelOrderTraversalRec(root): if root is None: return levels = [] bfsHelper(root, 0, levels) return levels from collections import deque def levelOrderTraversalIter(root): levels = [] if root is None: return levels queue = deque( [ root, ] ) level = 0 while queue: if len(levels) == level: levels.append([]) level_length = len(queue) for _ in range(level_length): node = queue.popleft() levels[level].append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) level += 1 return levels # Driver program to test above function root = Node(3) root.left = Node(9) root.right = Node(20) root.right.left = Node(15) root.right.right = Node(7) print(levelOrderTraversalIter(root))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right def buildTreeRec(inOrder, postOrder, i1, i2, p2, p2): if i1 >= i2 or p1 >= p2: return node = TreeNode(postOrder[p2 - 1]) idx = inOrder.index(postOrder[p2 - 1]) diff = idx - i1 node.left = buildTreeRec(inOrder, postOrder, i1, i1 + diff, p1, p1 + diff) node.right = buildTreeRec(inOrder, postOrder, i1 + diff + 1, i2, p1 + diff, p2 - 1) return node def buildTree(inOrder, postOrder): n = len(inorder) if not n: return None return buildTreeRec(inOrder, postOrder, 0, n, 0, n)
def finder(a1, a2): a1.sort() a2.sort() for i in range(0, len(a1)): if a1[i] != a2[i]: return a1[i] # x = finder([1,2,3,4,5,6,7],[3,7,2,1,4,6]) # print(x) # #Other solution # def finder2(a1,a2): # a1.sort() # k = int(len(a1)/2) + 1 # for i in range(0,len(a2)): # if a2[i] < a1[k]: # for j in range(0,k): # if a1[j] != a2[i]: # else: # for j in # x = finder2([1,2,3,4,5,6,7],[3,7,2,1,4,6]) import collections def finder3(arr1, arr2): d = collections.defaultdict(int) for num in arr2: d[num] += 1 print(d) for num in arr1: if d[num] == 0: return num else: d[num] = -1 y = finder3([1, 2, 3, 4, 5, 6, 7], [3, 7, 2, 1, 4, 6]) print(y)
def minCostClimbingStairs(cost): # bottom up dynamic approach/Recurrence relation n = len(cost) + 1 cost_list = [0] * (n) for i in range(2, n): cost_list[i] = min( cost_list[i - 1] + cost[i - 1], cost_list[i - 2] + cost[i - 2] ) return cost_list[n - 1] cost = [10, 15, 20] assert 15 == minCostClimbingStairs(cost)
""" LeetCode: 106 Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. inorder = [9,3,15,20,7] postorder = [9,15,7,20,3] 3 / \ 9 20 / \ 15 7 """ class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def binaryTreeRecursive(inorder, postorder, i1, i2, p1, p2): if i1 >= i2 or p1 >= p2: return root = TreeNode(postorder[p2 - 1]) it = inorder.index(postorder[p2 - 1]) diff = it - i1 root.left = binaryTreeRecursive(inorder, postorder, i1, i1 + diff, p1, p1 + diff) root.right = binaryTreeRecursive( inorder, postorder, i1 + diff + 1, i2, p1 + diff, p2 - 1 ) return root def binaryTree(inorder, postorder): n = len(inorder) if not n: return None return binaryTreeRecursive(inorder, postorder, 0, n, 0, n) inorder = [9, 3, 15, 20, 7] postorder = [9, 15, 7, 20, 3] print(binaryTree(inorder, postorder))
def run_spiral(lst, m, n, final_lst): top = 0 bottom = m - 1 left = 0 right = n - 1 direction = 0 while (top <= bottom) and (left <= right): if direction == 0: for i in range(left, right + 1): final_lst.append(lst[top][i]) top += 1 direction += 1 elif direction == 1: for i in range(top, bottom + 1): final_lst.append(lst[i][right]) right -= 1 direction += 1 elif direction == 2: for i in range(right, left - 1, -1): final_lst.append(lst[bottom][i]) bottom -= 1 direction += 1 elif direction == 3: for i in range(bottom, top - 1, -1): final_lst.append(lst[i][left]) left += 1 direction = 0 return final_lst final_lst = [] # matrix = [[1,2,3],[4,5,6],[7,8,9]] matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] m = len(matrix) n = len(matrix[0]) print(run_spiral(matrix, m, n, final_lst))
def rotate_image(matrix): n = len(matrix) for i in range(0, n): for j in range(1, n): temp = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = temp for i in range(0, n): for j in range(0, n // 2): temp = matrix[i][j] matrix[i][j] = matrix[i][n - j - 1] matrix[i][n - j - 1] = temp return matrix lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] lst1 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]] # step1 : # [ # [1, 4, 7], # [2, 5, 8], # [3, 6, 9] # ] # step2: # [ # [7,4,1], # [8,5,2], # [9,6,3] # ] print(rotate_image(lst1))
def strStr(haystack, needle): if len(haystack)<len(needle): return -1 if haystack == needle: return 0 n=len(needle) for i in range(len(haystack)-n): if haystack[i:i+n]==needle: return i return -1 haystack = "hello" needle = "ll" print(strStr(haystack,needle))
def defangIPaddr(address): str2 = "" for i in range(0, len(address)): if address[i] == ".": str2 += "[.]" else: str2 += address[i] return str2
def findMin(nums): def find_rotation_idx(nums): left,right = 0, len(nums)-1 if nums[left]<nums[right]: return 0 while left<right: mid = (left+right)//2 if nums[mid]>nums[mid+1]: return mid+1 else: if nums[mid]>=nums[left]: left = mid+1 else: right=mid idx = find_rotation_idx(nums) return nums[idx] if idx else nums[0] nums=[3,1,2] print(findMin(nums))
class Node: def __init__(self, val): self.left = None self.right = None self.val = val from collections import deque def printLevelOrder(root): if root is None: return queue = [] queue.append(root) while len(queue) > 0: print(queue[0].val) node = queue.pop(0) if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) def bstToGstUtils(root, total): if root == None: return # recursive call for Right side sub tree bstToGstUtils(root.right, total) total += root.val root.val = total - root.val # recurring call for left side sub tree bstToGstUtils(root.left, total) return root def bstToGst(root): total = 0 bstToGstUtils(root, total) if __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.right = Node(5) root.left.left = Node(4) printLevelOrder(root)
def thirdMax(nums): # easy pythonic way new_set = set(nums) if len(new_set) < 3: return max(nums) return sorted(new_set)[-3] def thirdMax2(nums): # more space optimized pythonic way using set new_set = set() for num in nums: new_set.add(num) if len(new_set) > 3: new_set.remove(min(new_set)) return max(nums) if len(new_set) < 3 else min(new_set) nums = [2, 2, 3, 1] print(thirdMax(nums)) print(thirdMax2(nums))
def fancyRide(l, fares): max_val = 0 lst = ["UberX", "UberXL", "UberPlus", "UberBlack", "UberSUV"] for i, fare in enumerate(fares): if l * fare <= 20: max_val = i return lst[max_val] l = 30 fares = [0.3, 0.5, 0.7, 1, 1.3] print(fancyRide(l, fares))
from collections import Counter def longestPalindrome(s): if len(s) == 0: return 0 d = Counter(s) odd_count = 0 even_count = 0 odd_present = False for v in d.values(): if v % 2 == 0: even_count += int(v) else: odd_present = True odd_count += int(v) - 1 if odd_present: return even_count + odd_count + 1 return even_count + odd_count s = "abccccdd" print(longestPalindrome(s))
def missingNumber(nums): nums.sort() if nums[0] != 0: return 0 if nums[-1] != len(nums): return len(nums) slow, fast = 0, 1 while fast != len(nums): if nums[slow] + 1 != nums[fast]: return nums[slow] + 1 slow += 1 fast += 1 return nums[-1] + 1 nums = [9, 6, 4, 2, 3, 5, 7, 0, 1] print(missingNumber(nums))
def permutation(nums): nums = sorted(nums) res = [] path = [] status = [False] * len(nums) dfs(nums, res, path, status) return res def dfs(nums, res, path, status): if len(nums) == len(path): res.append(path[:]) return for i in range(len(nums)): if not status[i]: if i > 0 and nums[i] == nums[i - 1] and status[i - 1] != True: continue status[i] = True path.append(nums[i]) dfs(nums, res, path, status) path.pop() status[i] = False lst = [3, 3, 0, 3] print(permutation(lst))
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(headA, headB): if headA is None and headB is None: return None ptr1 = headA ptr2 = headB while ptr1 != ptr2: # if ptr2 is None: # ptr2 = headA # else: # ptr2=ptr2.next # if ptr1 is None: # ptr1 = headB # else: # ptr1=ptr1.next ptr2 = headA if ptr2 is None else ptr2.next ptr1 = headB if ptr1 is None else ptr1.next return ptr1
""" Question: Based on the above employee table structure, explain how you would write a python function to read data from the above employee data and output it into a dictionary ---------------------------------------------------------------------------------------------------------------- Sample Output(Assumed): Based on the assumption from the question there are two methods done and attempted a. function - func_generate_employee_list_of_dict() Returns a List of dictionaries - [ {'EMPLOYEE_ID': 'ByoreQAB', 'TITLE':'VP', 'DEPARTMENT':'AD','ACTIVE':TRUE}, {'EMPLOYEE_ID': 'ByoreQAB', 'TITLE':'RSD','DEPARTMENT':'AD','ACTIVE':TRUE}, {'EMPLOYEE_ID': 'CSDymQAH', 'TITLE':'VP', 'DEPARTMENT':'Services','ACTIVE':TRUE} ] b. Returns a dictionary of the form - { EMPLOYEE_ID:['ByoreQAB','ByoreQAB','CSDymQAH'], TITLE:['VP','RSD','AD'] } ---------------------------------------------------------------------------------------------------------------- # Assumptions,steps and decisions taken regarding the below code for function 1. The source of data is from a database table that supports the odbc connector functionality (using pyodbc) 2. We don't have the connection details so we are assuming that "CONNECTION_STRING" below just includes the information for connection 3. Assuming the database is up and create a connection works without a failure - we then move to run the actual query required to extract the data (this is read from a config to support any runtime variables). Using separate function for the connection 4. Records are retrieved through the cursor and then the header is retrieved using the cursor description as a list 5. Due to the columns and their names being obtained at runtime from the above step it will remove any issues seen due to change in schema later 6. func_generate_employee_list_of_dict - in this function we use zip function to help us create the dictionaries by simeltaneously traversing through column list array and the tuple 7. func_generate_employee_dict - in this function we first obtain the tuple and unpack it using the column_name through the zip function to traverse through the column list and row (tuple) from the query output """ import pyodbc from collections import defaultdict def connect_to_db(connection_string): """returns the necessary cursor and connector from DB after connection Args: connection_string ([type]): connection string params Raises: Exception: if connection fails raise an exception Returns: cursor: DB cursor conn: DB connection """ try: conn=pyodbc.connect(connection_string) except Exception as e: raise Exception('Connection Failed') cursor = conn.cursor() return cursor,conn def func_generate_employee_list_of_dict(connection_string,sql_query): """[summary] Args: connection_string ([type]): connection string object sql_query ([type]): [description] Returns: [type]: [description] """ # connection to DB cursor,conn = connect_to_db(connection_string) # execute the query that is passed to the function cursor.execute(sql_query) # results list will contain the list of dictionaries obtained from output # and columns list will contain the headers results,columns_list= [], [] for column in cursor.description: columns_list.append(column[0]) # retrieve all records from cursor and start adding as separate dictionary items records = cursor.fetchall() # iterate and create individual dictionaries based on the number of items returned from the query on DB for row in records: results.append(dict(zip(columns_list,row))) # close any DB connections which are open at the end of the method conn.close() return results def func_generate_employee_dict(connection_string,sql_query): """ Args: connection_string ([type]): connection string object sql_query ([type]): [description] Returns: dict: dictionary with results of key as the column names and values as the corresponding column values in separate rows """ res = defaultdict(list) # connection to DB cursor,conn = connect_to_db(connection_string) # execute the query that is passed to the function cursor.execute(sql_query) columns_list = [column[0] for column in cursor.description] records = cursor.fetchall() for row in records: for key,value in zip(columns_list,row): res[key].append(value) conn.close() return res def main(): sql_query = "select * from employee" connection_string = "CONNECTION_STRING_PARAMS" res_list_of_dict = func_generate_employee_list_of_dict(connection_string,sql_query) res_dict = func_generate_employee_dict(connection_string,sql_query) if __name__ == "__main__": main() """ Solution to the programs from DB # solution 2 # SELECT e1.* # from employee e1 # left join employee e2 # on e1.employee_id = e2.employee_id # and e1.effective_date<e2.effective_date # where e2.effective_date is null # solution 1 # -- as per the details provided in question 1 employee profile change = 1 entry in the effective date column under the same employee group # select e.employee_id, count(effective_date) as cnt_profile_change # from employee e # GROUP by e.employee_id # having count(effective_date)>=2 """
from collections import defaultdict def highFive(items): dict1 = defaultdict(list) lst3 = [] for lst in items: dict1[lst[0]].append(lst[1]) print(dict1) for key in dict1.keys(): id = key val = int(sum(sorted(dict1[id], reverse=True)[:5]) / 5) lst3.append([id, val]) return lst3 items = [ [1, 91], [1, 92], [2, 93], [2, 97], [1, 60], [2, 77], [1, 65], [1, 87], [1, 100], [2, 100], [2, 76], ] x = highFive(items) print(x)
""" 26. Remove Duplicates from Sorted Array Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length. """ def removeDuplicates(nums): writePointer = 1 for readPointer in range(1, len(nums)): if nums[readPointer] != nums[readPointer - 1]: nums[writePointer] = nums[readPointer] writePointer += 1 return writePointer nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] print(removeDuplicates(nums))
def removeDuplicates(nums): for i, c in enumerate(nums): temp = nums[i] for i in nums[i + 1 :]: if i > temp: break if temp == i: nums.remove(i) return nums nums = [1, 1, 2] print(removeDuplicates(nums))
""" In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. Input: [1,2,3,3] Output: 3 Input: [5,1,5,2,5,3,5,4] Output: 5 """ def repeatedNTimes(A): dict1 = {} for ele in A: if ele not in dict1.keys(): dict1[ele] = 1 else: dict1[ele] += 1 for k, v in dict1.items(): if v == (len(A) / 2): return k return None lst = [5, 1, 5, 2, 5, 3, 5, 4] print(repeatedNTimes(lst))
def max_sub_array_of_size_k(k, arr): # TODO: Write your code here sum_val,max_sum,start=0,0,0 cnt = 0 for end in range(len(arr)): sum_val+=arr[end] cnt+=1 if cnt>=k: cnt-=1 max_sum=max(max_sum,sum_val) sum_val-=arr[start] start+=1 return max_sum arr = [2, 1, 5, 1, 3, 2] k=3 print(max_sub_array_of_size_k(k,arr))
def multiply(num1, num2): if len(num1) == 0 or len(num2) == 0: return "0" n1 = len(num1) n2 = len(num2) num1 = num1[::-1] num2 = num2[::-1] res = [0] * (n1 + n2) for j in range(n2): for i in range(n1): res[i + j] = res[i + j] + (int(num1[i]) * int(num2[j])) res[i + j + 1] = res[i + j + 1] + res[i + j] // 10 res[i + j] = res[i + j] % 10 i = len(res) - 1 while i > 0 and res[i] == 0: i -= 1 res = res[: i + 1] return "".join(map(str, res[::-1])) num1 = "123" num2 = "456" print(multiply(num1, num2))
""" Binary Tree Level order traversal practice Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 / \ 9 20 / \ 15 7 [ [3], [9,20], [15,7] ] """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque def levelOrderTraversal(root): if root is None: return None queue = deque([root]) res = [] level = 0 while queue: if len(levels) == level: res.append([]) level_length = len(queue) for _ in range(level_length): node = queue.popleft() res[level].append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) level += 1 return res
class Solution: def isMirror(self, root1, root2): if root1 is None and root2 is None: return True if root1 is not None and root2 is not None and root1.val == root2.val: return self.isMirror(root1.left, root2.right) and self.isMirror( root1.right, root2.left ) def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True return self.isMirror(root, root)
def min_heapify(array, i): left = 2 * i + 1 right = 2 * i + 2 length = len(array) - 1 smallest = i if left <= length and array[i] > array[left]: smallest = left if right <= length and array[smallest] > array[right]: smallest = right if smallest != i: array[i], array[smallest] = array[smallest], array[i] min_heapify(array, smallest) # def () def build_min_heap(array): for i in reversed(range(len(array) // 2)): min_heapify(array, i) return array array = [5, 4, 3, 2, 1] print(build_min_heap(array)) import heapq as hq def minMeetingRooms(intervals): intervals.sort(key=lambda x: x[0]) # sorting listoflists using the first val mhp = [] # heap initialized hq.heappush(mhp, intervals[0][1]) for i in intervals[1:]: if mhp[0] <= i[0]: hq.heappop(mhp) hq.heappush(mhp, i[1]) return len(mhp) lst = [[0, 30], [5, 10], [15, 20]] print(minMeetingRooms(lst))
def combinationSum2(nums, target): res = [] lst = [] nums.sort() dfs(nums, res, lst, 0, target) return res def dfs(nums, res, lst, start, target): if target == 0 and lst not in res: res.append(lst[:]) return for i in range(start, len(nums)): if nums[i] > target: return lst.append(nums[i]) dfs(nums, res, lst, i + 1, target - nums[i]) lst.pop() candidates = [10, 1, 2, 7, 6, 1, 5] target = 8 print(combinationSum2(candidates, target))
def climbStairs(n): if n < 1: return 0 lst = [1] * (n + 1) for i in range(2, n + 1): lst[i] = lst[i - 2] + lst[i - 1] return lst[n] print(climbStairs(10))
""" Using the Greedy algorithm - piece by piece addition """ def partitionLabels(S): dict_label = {c: i for i, c in enumerate(S)} res = [] j, anchor = 0, 0 for i, c in enumerate(S): j = max(j, dict_label[c]) if i == j: res.append(i - anchor + 1) anchor = i + 1 return res S = "ababcbacadefegdehijhklij" print(partitionLabels(S))
print('Contador de Una semana en dias horas y minutos') contador_dias = 1 contador_horas = 00 contador_minutos = 00 while contador_dias < 8: while contador_horas < 24: while contador_minutos <= 59: print(contador_dias, contador_horas, contador_minutos) contador_minutos += 1 contador_horas +=1 contador_minutos =0 contador_dias += 1 contador_horas = 0
""" After Class Notes """ # 9/19 # skipped expressions & statements # ended with variables (msg.py) # Might be best to stay in terminal together for longer (Quicker responses) # Move from terminal when functions/oop start # 9/26 # Took way to long to configure GitHub accts # Next time, send instructions to do at home # went over expressions, statements, variable and string concatenation # one successful git push! # start on user input next week # create student github with EZ credentials for the few who are having trouble with configuring GitHub accts. # Have those clone/push to this repo. # 10/3 # New student # Review what we learned so far via the interpreter # handling input from the user intro # store input # challenge: output something "sensible" with the input from user # Still, slow progress. Likely need to break up into groups. # 10/10 # Ada Lovelace day: review, who was she. What is today about? # Introduce Computational Thinking -clean whole house problem # Abstraction: Look at layers of a computer system # Functions: built-in functions we've used: print(), input()/raw_input() # Code block # passing arguments to a function, arguments # Encapsulation: another example of Abstraction # test it out by creating a function with a variable inside, then try to call the variable when outside def hello(): name = raw_input("tell me your name: ") print name # Case Study: Interface Design with turtle # draw a write angle using turtle 'methods'; # challenge: add instructions to make a complete square # introduce for loop # stopped before while loop and creating a square function # majority of class is having trouble knowing exactly what to type # though, the content is on the slides. May be best to display Python GUI # on tv screen to walk through the programs, rather than slides. # 10/17 # Turtle Graphics (Case Study-style) # driving home the idea of giving instructions to computer to do something # right angle # full square # for loop intro to complete square # create your own function --> "encapsulation" # generalize the function to highlight code reusability "generalization" # 10/24 # brainteaser (Day 6) # testing competence in basics: # fire up a python program # kick off complete thoughts # general cs # challenge to create a simple calculator program using turtle graphics to draw answer # quick slackbot intro --> to dive in fully next week # 10/31 # Halloween (no class) # 11/07 # # 11/14 # temp humidity program # challenge: make your own temp warnings # slackbot code_em: push first changes to repo, then test sirexa # only four weeks left... likely jump to OOD # break up class into groups based on skill level to get more done # 11/21 # Object-oriented: Turkey class creation! # Quick exercise in using matplotlib to visualize fake temperature data # 11/28 # graphics.py # used graphics.py to draw shapes to screen # 12/4 # getting mouse clicks with graphics.py # three clicks make a triangle # 12/12 # more faces of computer science: Turing and Hopper # find your birthday in the first million digits of pi.py
""" Problem 1 You have two strings. Put one in the middle of the other one. Example: s1 = "Environment", s2 = "Earth", result should be "EnviroEarthnment" """ s1 = "University" s2 = "Earth" new_txt = s1[:6] + s2 + s1[6:] print(new_txt) """ Problem 2 You have five strings. Create two strings, 1 containing all the beginning letters of the five strings, and 1 containing all the ending letter of the 5 strings. """ t1 = "qwerty" t2 = "asdfg" t3 = "tyu" t4 = "1234" t5 = "p" beginning = t1[:1] + t2[:1] + t3[:1] + t4[:1] + t5[:1] print(beginning) ending = t1[-1:] + t2[-1:] + t3[-1:] + t4[-1:] + t5[-1:] print(ending) """ Problem 3 Create a function that gets a name. If the length of the name is odd (կենտ) it returns the name all in upper case. If the length of the name is even (զույգ) just return it. """ def problem3(name): if (len(name)) % 2 == 0: return name else: print(name.upper()) problem3("David") """ Problem 4 You have a CNN article. You want to find out how many time the words 'university', 'vaccine', 'student' (but not 'students') appear in the text. You also want to find out how many numbers from 1 to 5 can be found in the text. """ article = """ (CNN)The University of Virginia has disenrolled 238 students for its fall semester on Friday for not complying with the university's Covid-19 vaccine mandate, according to a university spokesperson. UVA requires "all students who live, learn, or work in person at the university" to be fully vaccinated for the upcoming 2021-2022 academic year, according to current university Covid-19 policies. Out of the 238 incoming Fall semester students, only 49 of them were actually enrolled in classes, and the remaining 189 "may not have been planning to return to the university this fall at all," UVA spokesperson Brian Coy told CNN. "Disenrolled means you're not eligible to take courses," Coy said. He added that students who were enrolled at the university on Wednesday still have a week to update their status at which point they can re-enroll. """ x = str(article.count('university')) z = str(article.count('vaccine')) y = (article.count('student')) - (article.count('students')) print("Word university - " + x) print("Word vaccine - " + z) print("Word student - " + str(y)) print("Numbers from 1 to 5 founded in the text" , article.count("1") + article.count("2") + article.count("3") + article.count("4") + article.count("5") , "times") """ Problem 5 Find out if there is '2021-2022' string in the article and slice it. """ a = article.find("2021-2022") b = len("2021-2022") print(article[a:a + b]) """ Problem 6 Create a function that gets a string and returns the same string but the half of it UPPERCASE. (It's okay if the string has odd number of characters and half is not the exact half) """ def problem6(text): str_len = len(text) poqr = text.lower() mec = text.upper() half = str_len - int(str_len / 2) printstr = poqr[:half] + mec[half:] return(printstr) print(problem6("muradyan")) """ Problem 7 Write a function that takes a name and a (future) profession and returns the sentence "I am Ani Amirjanyan and I am a backend developer.". Use .format or f" " """ def problem7 (): name = "David Muradian" profession = "backend developer" txt = "I am {0} and I am a {1}".format(name, profession) txt1 = f"I am {name} and I am a {profession}" print(txt) print(txt1) problem7() """ Problem 8 Create a function that takes a 3 digit number (can't take more or less digits) and returns the reverse number. Example: take "987" return 789. (It is okay if the result starts with 0) """ def reverse(): l = list(input("please enter a 3 digit numbers = ")) print(l[2], l[1], l[0]) reverse()
""" Problem 3. Calculate your age using the value of the year you were born and the value of current year. """ current_year = 2021 year_i_was_born = 1999 my_age = 22 print("I am " + str(my_age) + " years old.")
import sys friend = sys.stdin.readline() friend = friend[ :-1] greeting = "Hello dogfriend" if friend == "Pants" or friend == "Joel" or friend == "Sarah": greeting = "It's the homegirl Pants! Where's the ball?" elif friend == "Lola" or friend == "Frances": greeting = "Hello Lola, sorry I can't feed you, please don't bark." print greeting
from random import randint print("Welcome to game") user = input("Hey what's your name: ") user.capitalize() #Game Rules print("Game Rules:") print("There will be 5 rounds") print("Paper beats Rock") print("Rock beats scissor") print("Scissor beats paper") print("Winner will get 10 points for each round") #Game Design sample = ["rock","paper","scissor"] user_score = 0 comp_score = 0 i = 1; while i<=5: choice = randint(0,2) print("Round : ",i) comp = sample[choice] user_entry = input(f"Hey {user}, enter one of rock,paper,scissor : ") user_entry.lower() print(f"computer chois is {comp}") if (user_entry=="rock" and comp=="scissor") or (user_entry=="paper" and comp=="rock") or (user_entry=="scissor" and comp=="paper"): print(f"congrats {user}, you get 10 points.") user_score+=10 elif (comp=="rock" and user_entry=="scissor") or (comp=="paper" and user_entry=="rock") or (comp == "scissor" and user_entry=="paper"): print("OOPS! computer gets 10 points.") comp_score+=10 elif user_entry==comp: print("No one get points.") i+=1 # winner print(f"{user} : {user_score}") print(f"Computer : {comp_score}") if user_score>comp_score: print(f"Congrats {user}, You won.") elif user_score<comp_score: print('OOps computer won, try AGAIN!!') else: print('GAME TIED, NICE TRY.')
def xor(plaintext, n): #plaintext = input('Input Text: ') asciiText = [] if len(plaintext) % 2 != 0: plaintext+='.' for char in plaintext: letBin = bin(ord(char))[2:] while(len(letBin) < 7): letBin = '0' + letBin asciiText.append(letBin) binText = ''.join(asciiText) encryptedText = '' for i in range(n): for char in range(len(binText)): if char == 0: encryptedText += binText[1] elif char == len(binText) - 1: encryptedText += binText[-2] else: encryptedText += str(int(binText[char - 1]) ^ int(binText[char + 1])) binText = encryptedText encryptedText = '' encryptedAscii='' for i in range(int(len(binText)/7)): sevenbits=binText[7*i:7*(i+1)] encryptedAscii+=chr(int(sevenbits,2)) return encryptedAscii def rxor(ciphertext, n): binary = '' rxored = [] for char in ciphertext: binno = bin(ord(char))[2:] while len(binno) < 7: binno = '0'+binno binary += binno for i in range(len(binary)): rxored.append('') for i in range(n): rxored[1] = boolToNum(int(binary[0])) rxored[-2] = boolToNum(int(binary[-1])) for i in range(int((len(binary) - 2) / 2)): pos = 2 * i + 3 if int(binary[pos - 1]): rxored[pos] = boolToNum(not int(rxored[pos - 2])) else: rxored[pos] = rxored[pos - 2] for i in range(int((len(binary) - 2) / 2)): pos = (len(binary) - 4) - 2 * i if int(binary[pos + 1]): rxored[pos] = boolToNum(not int(rxored[pos + 2])) else: rxored[pos] = rxored[pos + 2] binary = ''.join(rxored) encryptedAscii='' for i in range(int(len(binary)/7)): sevenbits=binary[7*i:7*(i+1)] encryptedAscii+=chr(int(sevenbits,2)) return encryptedAscii def boolToNum(booleanBoio): if isinstance(booleanBoio, str): return str(booleanBoio) else: if booleanBoio: return '1' else: return '0' plain = input("Text is yay: ") print(xor(plain,1)) xored = input("It is xored: ") print(rxor(xored,1))
import unittest from ArrangeBoardAndBoats import ArrangeBoardAndBoats from Board import Board from Boat import Boat class BattleShipTests(unittest.TestCase): """ Test class for the battleship game. This class will contain unittests for different functions implemented in the battleship code. """ emptymatrix = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ]] def test_board_creation(self): """" Function to test if a blank board can be created. """ board = Board() boardmatrix = board.create_board() self.assertListEqual(self.emptymatrix, boardmatrix, msg="Test to determine if the generated board contains only empty double spaces") def test_board_length(self): """ :return: Test to validate that the generated board is 10X10. """ board = Board() boardmatrix = board.create_board() self.assertEqual(len(self.emptymatrix), len(boardmatrix), msg="Test to check length of the genereated board matrix and make sure it is 10X10") def test_len_boats(self): """ :return: Test to see if the length of the generated boats is correct. """ expected_numbers = {1: 6, 2: 4, 3: 3, 3: 2} boatdict = {} boat = Boat() boatlists = boat.create_boats() for boatlist in boatlists: for boat in boatlist: boatdict[len(boatlist)] = len(boat) self.assertDictEqual(expected_numbers, boatdict, msg="Test to se that the correct number of boats are generated") def test_validation_fails_for_to_long_column(self): """ Test to see that validation fails for a boat that intends to be placed with to high column numbers. """ arrangements = ArrangeBoardAndBoats() boat = Boat() boatlist = boat.create_boat(1, 6, "A") self.assertFalse(arrangements.validate_placement_coordinates(self.emptymatrix, boatlist[0], 1, 2, 9)) def test_validation_fails_for_to_long_row(self): """ Test to see that validation fails for a boat that intends to be placed with to high row numbers. """ arrangements = ArrangeBoardAndBoats() boat = Boat() boatlist = boat.create_boat(1, 6, "A") self.assertFalse(arrangements.validate_placement_coordinates(self.emptymatrix, boatlist[0], 0, 9, 5)) def test_validation_is_ok(self): """ Test to see that a boat can be placed with valid rows and column coordinates. :return: """ arrangements = ArrangeBoardAndBoats() boat = Boat() boatlist = boat.create_boat(1, 6, "A") self.assertTrue(arrangements.validate_placement_coordinates(self.emptymatrix, boatlist[0], 0, 2, 3)) def test_boards_creation(self): """ Test to see that boards where boats are placed out are not empty """ arrangements = ArrangeBoardAndBoats() boards = arrangements.place_boats() self.assertIsNotNone(boards) if __name__ == "__main__": unittest.main()
import argparse import re from math import ceil, sqrrt def arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('grid_fname') parser.add_argument('dict_fname') return parser.parse_args() def make_board(fname): with open(fname, 'r') as f: data = f.read() data = data.split('\n') n = int(data[0]) layers = [layer.split() for layer in data[1:]] board = Board() board.insert(layers) return board def make_trie(dict_file, grid_file): # cheap way to prune search tree with open(grid_file) as g: alphabet = g.read() alphabet = ''.join(set(filter(str.isalpha, alphabet))) with open(dict_file) as f: data = f.read() words = data.split('\n') # skip word if first 3 letters aren't in the grid # to prune search tree early prune_regex = re.compile('[' + alphabet + ']{3,}$', re.I).match words = filter(prune_regex, words) root = TrieNode(None, '') for word in words: current_node = root for letter in word: # between 'A', ... 'Z', '[' # should always be, but just to be safe... if 65 <= ord(letter) < 91: next_node = current_node.children[ord(letter) - 65] # node wasn't in trie, so put it in if next_node is None: next_node = TrieNode(current_node, letter) current_node = next_node current_node.isWord = True return root def search(grid, dictionary): size = grid.size queue = [] valid_words = [] for x in range(-size + 1, size): for y in range(-size + 1, size): # outside of grid if abs(x) + abs(y) >= size: break c = grid.hexagons[(x, y)].value node = dictionary.children[ord(c) - 65] if node is not None: queue.append((x, y, c, node)) while queue: x, y, s, node = queue[0] queue.pop(0) for dx, dy in ((1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)): x_2, y_2 = x + dx, y + dy if abs(x) < size and abs(y) < size and abs(x) + abs(y) < size: s_temp = grid.hexagons[(x2, y2)] s_2 = s + s_temp node_2 = node.children[ord(s_temp) - 65] if node_2 is not None: if node_2.isWord: valid_words.append(s_2) queue.append((x_2, y_2, s_2, node_2)) return valid_words class Hex: def __init(self, value, x, y): self.value = None self.x = 0 self.y = 0 self.neighbors = {(0, 1): None, (1, 0): None, (1, -1): None, (0, -1): None, (-1, 0): None, (-1, 1): None} def __repr(self): return '({0}, {1}, {2})'.format(self.value, self.x, self.y) class Board: def __init__(self): self.size = 0 # hexagons get hashed by (x,y) tuple, and store hexagon as value self.hexagons = {} # isn't same size as grid, but doesn't matter if we only look in grid. self.visited = {(i, j): False for i in range(self.size) for j in range(self.size)} # neighboring directions self.dx = [0, 1, 1, 0, -1, -1] self.dy = [1, 0, -1, -1, 0, 1] def insert(self, layers): # feels slightly less sloppy doing this than making calls to methods # in the constructor # TODO should probably rename this something else to be more clear # TODO should implement testing and error handling self.size = len(layers) index = 0 for layer in layers: for value in layer: x, y = self.number_to_grid_coord(index) temp_hex = Hex(value, x, y) self.hexagons[(x, y)] = temp_hex self.update_neighbors(temp_hex) index += 1 return self.hexagons[(0, 0)] def number_to_grid_coord(self, n): # TODO CLEAN THIS UP """Convert a number to its coordinates in the hexagonal coordinate system Args: number: A number assigned to a hexagon Returns: Coordinates of the number in the hexagonal coordinate system as a tuple. """ # dx = [0, -1, -1, 0, 1, 1, 0] # dy = [1, 0, -1, -1, 0, 1, 1] # NUMBER OF HEXAGONS IN A HONEYCOMB LATTICE OF RADIUS N+1 IS GIVEN BY # THE SEQUENCE OEIS003215 => 3n^2 + 3n + 1 if n == 0: return (0, 0) else: dist = int(ceil((-3 + sqrt(-3 + 12 * n)) / 6)) # highest index in previous level given by OEIS003215 max_in_prev_layer = 3 * (dist - 1) * (dist - 1) + 3 * (dist - 1) + 1 # number of nodes between previous level and current node level_shift = number - max_number_prev_level diagonal = int(ceil(level_shift / float(distance))) diagonal_shift = diagonal * distance - level_shift start = diagonal % 6 end = diagonal % 6 + 2 # diagonal_coordinates = tuple(self.dx[start:end]) diagonal_coordinates = tuple( [coord * distance for coord in self.dx[start:end]]) start = diagonal - 1 end = diagonal + 1 # diagonal_shift_coordinates = tuple(self.dy[start:end]) diagonal_shift_coordinates = tuple( [coord * diagonal_shift for coord in self.dy[start:end]]) res = tuple(map(operator.add, diagonal_coordinates, diagonal_shift_coordinates)) res = tuple([ int(diagonal_coordinates[i] + diagonal_shift_coordinates[i]) for i in range(len(diagonal_coordinates))]) # res = tuple([int(coord) for coord in res]) return res def get_neighbors(self, hex): return [x[1] for x in hex.neighbors.items() if x.value is not None] def update_neighbors(self, h): if h is None: print "Invalid hexagon, h=None" return x, y = h.x, h.y # updates current hexagon's neighbors for i in range(6): # need to check to avoid KeyError if (x + self.dx[i], y + self.dy[i]) in self.hexagons: neighbors[(self.dx[i], self.dy[i])] = self.hexagons[ (x + self.dx[i], y + self.dy[i])] surrounding_neighbors = self.get_neighbors(h) # going in the reverse direction just negates self.dx[i], self.dy[i] for neighbor in surrounding_neighbors: neighbor.neighbors[(-self.dx[i], -self.dy[i])] = h return h def check_board(word, current_ind, r, c, word_len): if current_ind == word_len - 1: return True ret = False for i in range(6): new_col = c + self.dx[i] new_row = r + self.dy[i] if abs(new_col) >= self.size - 1 or abs(new_row) >= self.size or new_col + new_row >= self.size and not visited[(new_row, new_col)] and word[current_ind + 1] == board[new_row][new_col]: current_ind += 1 visited[(new_row, new_col)] = True ret = check_board(word, current_ind, new_row, new_col, word_len) if ret: break visited[(new_row, new_col)] = False return ret # class Node: # # Trie node implementation borrowed from pythonfiddle # # http://pythonfiddle.com/python-trie-implementation/ # # def __init__(self): # self.word = None # self.nodes = {} # # def __repr__(self): # return self.word # # def get_all_words(self): # all_words = [] # # get words from children nodes # for key, node in self.nodes.iteritems(): # if node.word is not None: # all_words.append(node.word) # # append list of child words # all_words += node.get_all_words() # return all_words # # def insert(self, word, string_pos=0): # current_letter = word[string_pos] # if current_letter not in self.nodes: # self.nodes[current_letter] = Node() # if string_pos + 1 == len(word): # self.nodes[current_letter].word = word # else: # self.nodes[current_letter].insert(word, string_pos + 1) # # return True # # def get_all_with_prefix(self, prefix, string_pos): # x = [] # for key, node in self.nodes.iteritems(): # if string_pos >= len(prefix) or key == prefix[string_pos]: # if node.word is not None: # x.append(node.word) # if node.nodes != {}: # if string_pos + 1 <= len(prefix): # x += node.get_all_with_prefix(prefix, string_pos + 1) # else: # x += node.get_all_with_prefix(prefix, string_pos) # return x # # # class Trie: # # Trie implementation borrowed from pythonfiddle # # http://pythonfiddle.com/python-trie-implementation/ # # def __init__(self): # self.root = None # # def insert(self, word): # self.root.insert(word) # # def get_all_words(self): # return self.root.get_all_words() # # def get_all_with_prefix(self, prefix, string_pos=0): # return self.root.get_all_with_prefix(prefix, string_pos) # class TrieNode: def __init__(self, parent, value): self.parent = parent self.children = [None] * 26 self.isWord = False if parent is not None: # use ascii codes to get correct node parent.children[ord(value) - 97] = self if __name__ == "__main__": # parses command line arguments # takes the filepath to the grid/board and the filepath to the dictionary args = arg_parser() # get list of characters that are in the grid # builds the board/grid grid = parse_board(args.grid_fname) # use trie since you don't have to restart search every time word_trie = parse_dictionary(args.dict_fname, args.grid_fname)
# -*- coding: utf8 -*- class Square(object): """Quadrados do tabuleiro""" def __init__(self,atribute=None): self.__atribute = atribute; self.__letter = None; @property def atribute(self): return self.__atribute; @atribute.setter def atribute(self,value): self.__atribute = value; @property def letter(self): return self.__letter; @letter.setter def letter(self,value): self.__letter = value;
from heapq import * def find_k_largest_numbers(nums, k): min_heap = [] # if heap size is smaller than k, insert first k elements for i in range(k): heappush(min_heap, nums[i]) for j in range(k, len(nums)): if nums[j] > min_heap[0]: heappop(min_heap) heappush(min_heap, nums[j]) return min_heap def main(): print("Here are the top K numbers: " + str(find_k_largest_numbers([3, 1, 5, 12, 2, 11], 3))) print("Here are the top K numbers: " + str(find_k_largest_numbers([5, 12, 11, -1, 12], 3))) main()
def search_next_letter(letters, key): # Assume array is circular start, end = 0, len(letters) - 1 if ord(letters[start]) > ord(key) or ord(key) > ord(letters[end]): return letters[start] while start <= end: mid = start + ((end - start) // 2) # since we want a higher order than the order of the key # move up if key == mid letter if ord(key) >= ord(letters[mid]): start = mid + 1 # if key < mid letter else: end = mid - 1 return letters[start % len(letters)] def main(): print(search_next_letter(['a', 'c', 'f', 'h'], 'f')) print(search_next_letter(['a', 'c', 'f', 'h'], 'b')) print(search_next_letter(['a', 'c', 'f', 'h'], 'm')) main()
from heapq import * def secretString(triplets): ''' Returns the secret string synthesized through working with triplets list ''' max_heap, freq_map = [], dict() # build map, key = char, value = set of all chars that come after it for triplet in triplets: char1, char2, char3 = triplet[0], triplet[1], triplet[2] freq_map[char1] = freq_map.get(char1, set()) freq_map[char1].add(char2) freq_map[char1].add(char3) freq_map[char2] = freq_map.get(char2, set()) freq_map[char2].add(char3) # recursively calculate the weight of each character # the character with the lowest weight will be last # the character with the greatest weight will be first # and all chars in between will be sorted as such visited = dict() for key, value in freq_map.items(): traverseGraph(freq_map, key, visited) result = list(visited.keys()) result.reverse() return ''.join(result) def traverseGraph(freq_map, current_char, visited): ''' Helper function to recursively figure out weight of given char ''' chars = freq_map.get(current_char, None) # if there are no children, return 0, mark as visited if not chars: visited[current_char] = 0 return 0 # if current char's weight has been calculated, return it if visited.get(current_char, None) is not None: return visited[current_char] # calculate weights for all chars that come after current "char" weight = 0 for c in chars: weight += traverseGraph(freq_map, c, visited) weight += len(chars) visited[current_char] = weight return weight def main(): secret_1 = "whatisup" triplets_1 = [ ['t','u','p'], ['w','h','i'], ['t','s','u'], ['a','t','s'], ['h','a','p'], ['t','i','s'], ['w','h','s'] ] s = secretString(triplets_1) print('Triplet found:', s) print('-> Which is %s' % 'Correct' if secret_1 == s else 'Incorrect') main()
# ========================= # Square Sorted Array Items # ========================= # PROBLEM STATEMENT # Given a sorted array, create a new array containing squares of # all the number of the input array in the sorted order. # EXAMPLE # Input: [-2, -1, 0, 2, 3] # Output: [0, 1, 4, 4, 9] # Input: [-3, -1, 0, 1, 2] # Output: [0 1 1 4 9] def make_squares(arr): squares = [] left, right = 0, len(arr) - 1 while left <= right: left_square = arr[left] * arr[left] right_square = arr[right] *arr[right] if left_square >= right_square: squares.insert(0, left_square) left += 1 else: squares.insert(0, right_square) right -= 1 return squares def main(): print("Squares: " + str(make_squares([-2, -1, 0, 2, 3]))) print("Squares: " + str(make_squares([-3, -1, 0, 1, 2]))) main()
from os import close def generate_valid_parentheses(num): result = [] default_string = [0 for x in range(2*num)] # 1 open and 1 close bracket for each num generate_valid_parentheses_recursive(num, 0, 0, default_string, 0, result) return result def generate_valid_parentheses_recursive(num, openCount, closeCount, current_str, index, result): if openCount == num and closeCount == num: result.append(''.join(current_str)) else: # one option is to add open bracket, as long openCount < num if openCount < num: current_str[index] = '(' generate_valid_parentheses_recursive(num, openCount + 1, closeCount, current_str, index + 1, result) # if not empty string and closeCount < if openCount > closeCount: current_str[index] = ')' generate_valid_parentheses_recursive(num, openCount, closeCount + 1, current_str, index + 1, result) def main(): print("All combinations of balanced parentheses are: " + str(generate_valid_parentheses(2))) print("All combinations of balanced parentheses are: " + str(generate_valid_parentheses(3))) main()
from heapq import * class job: def __init__(self, start, end, cpu_load): self.start = start self.end = end self.cpu_load = cpu_load def __lt__(self, other): return self.end < other.end def find_max_cpu_load(jobs): jobs.sort(key=lambda x: x.start) maxLoad = 0 currentLoad = 0 minHeap = [] for job in jobs: # NOTE: the head of the min heap is the meeting with the earliest end time # remove all mettings in the heap which have ended while len(minHeap) > 0 and job.start >= minHeap[0].end: currentLoad -= minHeap[0].cpu_load heappop(minHeap) # add the current job heappush(minHeap, job) currentLoad += job.cpu_load # take a snapshot of current load against maxLoad seen so far maxLoad = max(maxLoad, currentLoad) return maxLoad def main(): print("Maximum CPU load at any time: " + str(find_max_cpu_load([job(1, 4, 3), job(2, 5, 4), job(7, 9, 6)]))) print("Maximum CPU load at any time: " + str(find_max_cpu_load([job(6, 7, 10), job(2, 4, 11), job(8, 12, 15)]))) print("Maximum CPU load at any time: " + str(find_max_cpu_load([job(1, 4, 2), job(2, 4, 1), job(3, 6, 5)]))) main()
# ======================== # Find All Missing Numbers # ======================== # We are given an unsorted array containing numbers taken from # the range 1 to ‘n’. The array can have duplicates, which means # some numbers will be missing. Find all those missing numbers. def find_missing_numbers(nums): missingNumbers = [] i = 0 while i < len(nums): correctIndex = nums[i] - 1 # if the element at i doesn't belong there and the element # at its correct index isn't a duplicate if nums[i] != nums[correctIndex]: nums[i], nums[correctIndex] = nums[correctIndex], nums[i] else: i += 1 for i in range(len(nums)): if nums[i] != i + 1: missingNumbers.append(i+1) return missingNumbers def main(): print(find_missing_numbers([2, 3, 1, 8, 2, 3, 5, 1])) print(find_missing_numbers([2, 4, 1, 2])) print(find_missing_numbers([2, 3, 2, 1])) main()
# ===================================== # Longest Substring W/ Distinct K Chars # ===================================== import string # Problem Statement # ^^^^^^^^^^^^^^^^^ # Given a string, find the length of the longest substring # in it with no more than K distinct characters. # Ex: string = "araaci", for K = 2 output = "araa" => ('r' & 'a') # Ex: string = "araaci", for K = 1 output = "aa" => ('a') def longest_substring_with_k_distinct(str, k): windowStart, windowEnd = 0, 0 # initialize window maxLength = 0; charMap = {} # HashMap to be used for tracking character frequency # iterator over each character in str # windowEnd automatically shifts right each iteration for windowEnd in range(len(str)): # ASCII value of current str window end rightChar = str[windowEnd] # update rightChar frequency in HashMap if rightChar not in charMap: charMap[rightChar] = 0 charMap[rightChar] +=1 # as we shift to the right, there can be a state in the logic # when there are more than K distinct chars in the window, so: # while no. of distinct characters in current substring # are more than k, shift leftChar to the right until they are == K # ex: if the 3 leftmost chars are all 'a', this loop runs thrice while len(charMap) > k: leftChar = str[windowStart] charMap[leftChar] -= 1 # update leftChar in hashmap if charMap[leftChar] == 0: del charMap[leftChar] # shift start of window left by 1 windowStart += 1 # update largest substring size maxLength = max(maxLength, windowEnd - windowStart + 1) return maxLength def main(): print("Length of the longest substring: " + str(longest_substring_with_k_distinct("araaci", 2))) print("Length of the longest substring: " + str(longest_substring_with_k_distinct("araaci", 1))) print("Length of the longest substring: " + str(longest_substring_with_k_distinct("cbbebi", 3))) print("Length of the longest substring: " + str(longest_substring_with_k_distinct("llllllll", 3))) # if run directly if __name__ == '__main__': main()
# =========================== # Unique Triplets Sum To Zero # =========================== # PROBLEM STATEMENT # Given an array of unsorted numbers, # find all unique triplets in it that add up to zero. # Input: [-3, 0, 1, 2, -1, 1, -2] # Output: [-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1] # Explanation: There are four unique triplets whose sum is equal to zero. def search_duplet(arr, target_sum, left, triplets): right = len(arr) - 1 while left < right: current_sum = arr[left] + arr[right] # if we've found left and right that add to target_sum # append a combination to triplets # then shift left and right appropriately # subsequently handle duplicates if current_sum == target_sum: triplets.append([-target_sum, arr[left], arr[right]]) # both right and left elements have been used in this triplet # so either one can't be used again with the current target sum # since if left is used with target sum the only answer is right # and same with right being used with target sum, the only value # that makes a triplet with those two is left. Hence we shift # left index to the right and right index to the left left += 1 right -= 1 # handle duplicates on either side while left < right and arr[left] == arr[left - 1]: left += 1 # skip duplicate element while left < right and arr[right] == arr[right + 1]: right -= 1 # skip duplicate element # target sum is still greater than current sum elif target_sum > current_sum: left += 1 # target sum is less than current sum else: right -= 1 def search_triplets(arr): triplets = [] arr.sort() # iterate through all elements in arr # use that as a potential target sum # and search for a pair that sums with # current element - to zero (found triplet) for index in range(len(arr)): if index > 0 and arr[index] == arr[index - 1]: continue # this is a duplicate, skip # find a pair that completes a triplet # use search_duplet(arr, -arr[index], index + 1, triplets) return triplets def main(): print(search_triplets([-3, 0, 1, 2, -1, 1, -2])) print(search_triplets([-5, 2, -1, -2, 3])) main()
# ----------------------------------------------------------------- # CALCULATOR # ----------------------------------------------------------------- class Calculator(): # NOTE: This class does allow for .plus().one().one(), which would evaluate to be 2 def __init__(self): ''' Calculate an operation between two Integers ''' self.first, self.second, self.operation, self.result = None, None, None, None def new(self): ''' Reset all variables. Called before any method. ''' self.first, self.second, self.operation, self.result = None, None, None, None return self def plus(self, *args): ''' Bind to add ''' self.operation = self.add return self def minus(self, *args): ''' Bind to subtract ''' self.operation = self.subtract return self def divided_by(self, *args): ''' Bind to divide ''' self.operation = self.divide return self def times(self, *args): ''' Bind to multiply ''' self.operation = self.multiply return self def add(self): return (self.first + self.second) def subtract(self): return (self.first - self.second) def multiply(self): return (self.first * self.second) def divide(self): # if denominator is 0, just return 0 (assumption) if self.second == 0: return 0 return (self.first / self.second) # ----------------------------------------------------------------- # HELPER LIBRARY # ----------------------------------------------------------------- digits = { 'zero' : 0, 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5, 'six' : 6, 'seven' : 7, 'eight' : 8, 'nine' : 9 } # helper function to bind given string to a class method def make_digit_callable(name): # closure def _method(self): # method called on first digit if self.first is None: self.first = digits[name] # method called on second digit else: if self.operation is None: print('Incorrect Syntax (operator missing).') return None self.second = digits[name] return self.operation() return self return _method # Create methods associated with each digit (0-9) for name in digits: _method = make_digit_callable(name) setattr(Calculator, name, _method) # bind 'name' to _method # ===============================================================
from heapq import * from collections import deque def reorganize_string(str, k): reorganized_string = '' max_heap = [] char_frequency = dict() # build a hash map of char frequencies in str for char in str: char_frequency[char] = char_frequency.get(char, 0) + 1 # build a max heap with format tuple(frequency, char) for key in char_frequency: heappush(max_heap, (-char_frequency[key], key)) current_char_list = deque() while max_heap: # pop top k elements from the heap, push them to a list freq, char = heappop(max_heap) reorganized_string += char # add the current char to list of chars added in this round of "k" distinct adds current_char_list.append((freq + 1, char)) if len(current_char_list) == k: freq, char = current_char_list.popleft() if freq < 0: heappush(max_heap,(freq, char)) return reorganized_string if len(reorganized_string) == len(str) else '' def main(): print("Reorganized string: " + reorganize_string("mmpp", 2)) print("Reorganized string: " + reorganize_string("Programming", 3)) print("Reorganized string: " + reorganize_string("aab", 2)) print("Reorganized string: " + reorganize_string("aapa", 3)) main()
import random as dados preço = 5000 empuxo = 0 empuxo2 = empuxo chance_de_erro = 0 chance_de_erro1 = 0 chance_de_erro2 = 0 chance_de_erro3 = 0 chance_de_erro4 = 0 chance_de_erro5 = 0 contador = 1 parte = "" while (parte != "sair"): parte = input("parte do foquete: ") if parte == "motor": mortor = int(input("motor: ")) if mortor == 1: preço -= 10 empuxo += 8 chance_de_erro1 += 17 elif mortor == 2: preço -= 100 empuxo += 12.7 chance_de_erro1 += 14 elif mortor == 3: preço -= 500 empuxo += 18.4 chance_de_erro1 += 8 elif mortor == 4: preço -= 750 empuxo += 19.6 chance_de_erro1 += 4 elif mortor == 5: preço -= 1000 empuxo += 31 chance_de_erro1 += 1 else: print("erro") elif parte == "estagio": estagio = int(input("estagio: ")) if estagio == 1: preço -= 50 empuxo -= 8.5 chance_de_erro2 += 18 elif estagio == 2: preço -= 500 empuxo -= 8.3 chance_de_erro2 += 16 elif estagio == 3: preço -= 2500 empuxo -= 8 chance_de_erro2 += 10 elif estagio == 4: preço -= 3750 empuxo -= 7.5 chance_de_erro2 += 8 elif estagio == 5: preço -= 5000 empuxo -= 7 chance_de_erro2 += 5 elif parte == "combustivel": combustivel = int(input("combustivel: ")) if combustivel == 1: preço -= 5 empuxo += 0.5 chance_de_erro3 += 19 elif combustivel == 2: preço -= 50 empuxo += 1 chance_de_erro3 += 18 elif combustivel == 3: preço -= 250 empuxo += 1.2 chance_de_erro3 += 12 elif combustivel == 4: preço -= 330 empuxo += 1.5 chance_de_erro3 += 10 elif combustivel == 5: preço -= 500 empuxo += 2 chance_de_erro3 += 8 else: print("todo escolido") chance_de_erro = chance_de_erro1+chance_de_erro2+chance_de_erro3/3 if (preço < 0 or empuxo < 0): if preço < 0: print("muito caro") else: print("muito pesado ou pouca força") else: print(preço, " ", empuxo, " ", chance_de_erro) while (empuxo2 > 0): if empuxo2 >= 10: chance_de_erro4 += 1 empuxo2 -= 10 contador += 1 elif empuxo == 5: chance_de_erro4 += 5 empuxo2 -= 5 contador += 1 elif empuxo2 >= 1: chance_de_erro4 += 10 empuxo2 -= 1 contador += 1 elif empuxo == 0.5: chance_de_erro4 += 14 empuxo2 -= 0.5 contador += 1 else: chance_de_erro4 += 18 empuxo2 -= 0.1 contador += 1 chance_de_erro5 += ((chance_de_erro4/contador)+chance_de_erro)/2 dado = dados.random(1, 20) if dado > chance_de_erro5: dados2 = dados.random(1, 4) if dados2 <= 3: print("deu certo") else: print("explodio") else: dados3 = dados.random(1, 4) if dados3 <= 2: print("não decolou") else: print("explodio")
# Uses python3 def calc_fib_slow(n): if (n <= 1): return n return calc_fib(n - 1) + calc_fib(n - 2) def calc_fib(n): a = 0 b = 1 if (n <= 1): return n for i in range(2,n+1): a, b = b, a+b return b n = int(input()) print(calc_fib(n))
# Uses python3 def evalt(a, b, op): if op == '+': return a + b elif op == '-': return a - b elif op == '*': return a * b else: assert False def MinAndMax(i,j,m,M,operators,digits): #write your code here min_val = float('inf') max_val = float('-inf') for k in range(i, j): #print('kanna', i, j, k) a = evalt(M[(i,k)], M[(k+1,j)], operators[k-1]) b = evalt(M[(i,k)], m[(k+1,j)], operators[k-1]) c = evalt(m[(i,k)], M[(k+1,j)], operators[k-1]) d = evalt(m[(i,k)], m[(k+1,j)], operators[k-1]) #print('haha', a, b, c, d) min_val = min(min_val, a, b, c, d) max_val = max(max_val, a, b, c, d) return (min_val, max_val) def get_maximum_value(dataset): operators = dataset[1::2] digits = list(map(int, dataset[::2])) n = len(digits) m = {} M = {} for i in range(1,n+1): m[(i,i)] = digits[i-1] M[(i,i)] = digits[i-1] #print(m, M) for s in range(1,n): for i in range(1,n-s+1): j = i + s #print(i,j) m[(i,j)], M[(i,j)] = MinAndMax(i,j,m,M,operators,digits) #print(m, M) return M[(1,n)] if __name__ == "__main__": print(get_maximum_value(input()))
#automate the for loop to ensure it uses a for loop # Python code for the Grade students = {"John":70, "Mike":90, "Sandra":60, "Jennifer":10} for name,score in students.items(): print("Student Name: " + name + ", Score: " + str(score))
income_input = {"Alex": 500, "James": 20500, "Kinuthia": 70000} def calculate_tax(income_input): for item in income_input: income = income_input[item] # print(income) if (income >= 0) and (income <= 1000): tax = (0*income) elif (income > 1000) and (income <= 10000): tax = (0.1 * (income-1000)) elif (income > 10000) and (income <= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income > 20200) and (income <= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income > 30750) and (income <= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income > 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass income_input[item] = int(tax) return (calculate_tax(income_input)) {'Kinuthia': 15352, 'James': 2490, 'Alex': 0} print(calculate_tax(income_input))
"""This file contains representation of different graphs as well as all the elements necessary for those graph. This file is created by Nessreddine LOUDIY.""" class Vertex: """A class to represent a Vertex.""" """Vertex initialization.""" def __init__(self, key, value=None): self.key = key self.value = value """Implement == operation.""" def __eq__(self, other): return self.key == other.key \ and self.value == other.value \ and self.__class__ == other.__class__ """Implement the hash function of the Vertex. Otherwise the Vertex object can't be added to any dictionary/set! In fact, python3 makes an object unhashable when implementing __eq__ without __hash__. The following link explains the reason behind implementing this method: https://docs.python.org/3/glossary.html#term-hashable Some other good resources that explain why you should implement a __hash__ method when you implement __eq__ if you would like to use those objects in sets and dictionaries: https://hynek.me/articles/hashes-and-equality/ http://zetcode.com/python/hashing/""" def __hash__(self): return hash((self.__class__, self.key, self.value)) class Edge: """A class to represent an Edge.""" """Edge initialization.""" def __init__(self, u: Vertex, v: Vertex, w=None): self.u = u self.v = v self.weight = w class GraphAdjList: """Class to represents a Directed Graph using Adjacency Lists.""" """GraphAdjList initialization.""" def __init__(self): self.adj = dict() self.vertices = set() """Function to add a vertex to the graph.""" def add_vertex(self, vertex): self.vertices.add(vertex) self.adj[vertex] = dict() """Function to add an edge to the graph.""" def add_edge(self, edge): if edge.u not in self.vertices: self.add_vertex(edge.u) if edge.v not in self.vertices: self.add_vertex(edge.v) for vertex in self.vertices: if vertex == edge.u: u = vertex if vertex == edge.v: v = vertex self.adj[u][v] = edge.weight """Function to perform a Breath-First Search.""" def bfs(self, s): for vertex in self.vertices: if vertex == s: source = vertex vertex.d = float('Inf') if vertex != s else 0 queue = [source] while queue: u = queue.pop() for vertex in self.adj[u]: if vertex.d == float('Inf'): vertex.d = u.d + 1 queue.append(vertex) """Function to perform a Depth-First Search.""" def dfs(self): for vertex in self.vertices: vertex.color = "White" time = 0 for vertex in self.vertices: if vertex.color == "White": time = self.dfs_visit(vertex, time) """Auxiliary function for DFS""" def dfs_visit(self, vertex, time): time = time + 1 vertex.d = time vertex.color = "Gray" for v in self.adj[vertex]: if v.color == "White": time = self.dfs_visit(v, time) vertex.color = "Black" time = time + 1 vertex.f = time return time
# Calculating conditional entropy of a text # Program expects first argument to be filename of the text file to be examined. # The script iterates over the text file and messes up the words or characters. # The script then calculates counts c(i,j), which is a number of bigrams ij. # And stores this in biGram dictionary. # Finally it iterates over the biGram dicrionary and calculates conditional entropy. # @AUTHOR: Ondřej Švec import sys import random import operator import functools from math import log EXPERIMENT_COUNT = 10 # number of repetitions for one messup probability FIRST_WORD_PADDING = "<s>" # word used as a beginning of a text # P(word | h1): calculates conditional bigram probability def biGramProbConditional(word, h1): if (h1 not in biGram) or (word not in biGram[h1]): return 0 if h1 not in uniGram: return 0 return biGram[h1][word] / uniGram[h1] # P(h1, word): calculates joint bigram probability def biGramProb(word, h1): if (h1 not in biGram) or (word not in biGram[h1]): return 0 return biGram[h1][word] / len(data) # calculates conditional entropy of dataSet using biGram dictionary def calculateEntropy(dataSet): entropy = 0 for h1 in biGram.keys(): for w in biGram[h1].keys(): if biGramProbConditional(w, h1) == 0: continue entropy -= biGramProb(w, h1) * log(biGramProbConditional(w, h1), 2) return entropy # read text file and save lines as array to data data = [line.strip() for line in open(sys.argv[1], 'r', encoding="iso-8859-2")] characters = {} # dictionary of characters that appear in the text file words = {} # dictionary of words that appear in the text file # array of messup probabilities (probability with which the word or character is messed up) messUpLikelihoods = [0, .00001, .0001, .001, .01, .05, .1, .2, .3 , .4, .5, .6, .7, .8, .9, 1] # get all unique words and characters from the input text file for w in data: words[w] = 1 if w not in words else words[w] + 1 for c in w: characters[c] = 1 if c not in characters else characters[c] + 1 # converting dictionaries to lists wordsList = list(words.keys()) charList = list(characters.keys()) # mess up characters (messUpWords==0) and words (messUpWords==1) for messUpWords in [0,1]: print("=== Messing up characters ===" if messUpWords == 0 else "=== Messing up words ===") # iterate over all messup probabilities for messUpProb in messUpLikelihoods: # lists in which we store calculated information from individual experiments (each messup probability is run 10 times) entropies = [] wordCounts = [] characterCounts = [] biggestFrequencies = [] noOfFreqOne = [] # mess the words/characters up 10 times for i in range(EXPERIMENT_COUNT): if (messUpProb == 0) and i > 0: break # no need to repeat when probability is 0 uniGram = {} # dictionary for unigram counts biGram = {} # dictionary for bigram counts newDataSet = [] wh1 = FIRST_WORD_PADDING # word history for w in data: # iterate over data (text file) newWord = w # get a random word from available words when the messup prob is higher than random if messUpWords: if random.random() <= messUpProb: newWord = random.choice(wordsList) # iterate over a word and get a random character from all available characters if the messup prob is higher then random else: newWord = list(newWord) for il in range(len(newWord)): if random.random() <= messUpProb: newWord[il] = random.choice(charList) newWord = ''.join(newWord) # +1 for the word in unigram dictionary uniGram[newWord] = 1 if newWord not in uniGram else uniGram[newWord] + 1 if wh1 not in biGram: biGram[wh1] = {} # add history to biGram if not there yet # +1 for the word in bigram dictionary biGram[wh1][newWord] = 1 if newWord not in biGram[wh1] else biGram[wh1][newWord] + 1 # add the messed up word in list to save for later (calculating entropy) newDataSet.append(newWord) wh1 = newWord # move history # calculate conditional entropy and add it into list entropies.append(calculateEntropy(newDataSet)) # number of unique words wordCounts.append(len(uniGram)) # number of characters in the new (messed up) text characterCounts.append(sum([ len(x) for x in newDataSet ])) # what is a frequency of a word that is most common? biggestFrequencies.append(max(uniGram.items(), key=operator.itemgetter(1))[1]) # number of words that only appear once in the text noOfFreqOne.append(functools.reduce(lambda count, x: count + (x == 1), uniGram.values(), 0)) # print results of all experiments for one messup probability print("Messup: ", messUpProb) print("Entropies: ", entropies) print("Word count: ", wordCounts) print("Number of characters: ", characterCounts) print("Number of characters per word: ", [ x / len(newDataSet) for x in characterCounts]) print("Biggest frequency: ", biggestFrequencies) print("Words with frequency 1: ", noOfFreqOne) print()
import os #get file names from a folder #os.getcwd() gets current working dir #loop through each files but first change dir def rename_file(): file_list = os.listdir(r"/Users/khushali/Coding/Udacity_Programming_Foundation_with_Python/prank") saved_path = os.getcwd() os.chdir(r"/Users/khushali/Coding/Udacity_Programming_Foundation_with_Python/prank") for file_name in file_list: os.rename(file_name,file_name.translate(None,"0123456789"))#old,new #file_name.translate(None,"012334")(table which translates one char to another set of char,list of char to remove) os.chdir(saved_path) rename_file() #python -m tabnanny secretMessage.py #for indentation error
import pandas as pd from numpy import nan from random import randint from random import choice #### A toy dataframe with some random data d2 = {'D':list(range(10)),'E':[randint(1,10) for i in range(10)], 'F':[choice(['x','y','z']) for i in range(10)]} df2 = pd.DataFrame(d2) df2 #### And one more exciting toy dataframe with null values (gasp!) dnone = {'D':list(range(10)),'E':[randint(1,10) for i in range(10)], 'F':[choice(['x','y','z',nan]) for i in range(10)]} dfnone = pd.DataFrame(dnone) dfnone #### SELECT * FROM df2: df2 #### SELECT E from df2: df2['E'] df2.E #### SELECT E, F FROM df: df[['A','B']] #### SELECT TOP 2 * FROM df2: df2.head(2) #### SELECT DISTINCT * FROM df2: df2.drop_duplicates() #### SELECT DISTINCT E FROM df2: df2['E'].drop_duplicates() #### SELECT DISTINCT * FROM dfnone - in SQL NULL counts as a distinct value in this context dfnone['F'].drop_duplicates() #### And NaN shows up here as well, so the behavior w/ DISTINCT is similar to SQL #### SELECT DISTINCT E,F FROM df2: df2[['E','F']].drop_duplicates() #### SELECT * FROM df2 WHERE F='x': df2[df2['F']=='x'] df2.loc[df2['F']=='x'] #### equivalently (When is .loc necessary?) #### Breaking this down a bit: df2['F']=='x' #### returns a pd series of booleans type(df2['F']=='x') df2[[True]*5+[False]*5] #### Selecting the first 10 rows by booleans #### SELECT * FROM dfnone WHERE F='x' - in SQL NULL is left out dfnone.loc[dfnone['F']=='x'] #### SELECT * FROM dfnone WHERE F != 'x' - in SQL NULL is left out here as well, because NULL yields an Unknown truth value when compared dfnone.loc[dfnone['F'] != 'x'] #### notice the NaN is *not* left out here; one way Pandas != SQL #### SELECT * FROM df2 WHERE F='x' AND E > 5 df2[(df2['F']=='x') & (df2['E']>5)] df2.loc[(df2['F']=='x') & (df2['E']>5)] #### equivalently (again, when is .loc necessary?) #### Break this down: selection using series of booleans (df2['F']=='x') (df2['E']>5) #### both series of booleans (df2['F']=='x') & (df2['E']>5) #### A series of booleans, True where both arguments are true and false otherwise #### SELECT * FROM df2 WHERE F IN ('x','y') df2 df2[df2['F'].isin(['x','y'])] #### Breaking this down somewhat df2['F'].isin(['x','y']) #### series of booleans #### SELECT * FROM df2 ORDER BY E DESC df2.sort_values(by='E',axis=0,ascending=False) #### 'axis' determines whether we sort rows or columns. Here's sorting by rows according to column E df2[['D','E']].sort_values(by=3,axis=1,ascending=False) #### sorted by columns according to the value in row 3. (not very useful) df2.sort_values(by='E',axis=0,ascending=False) #### Notice that there's now no neatly ordered index - the existing index is out of order df2.sort_values(by='E',axis=0,ascending=False).reset_index() #### Now there's a new ordered index, as well as a new 'index' column preserving the old index #### SELECT SUM(D) FROM df2 GROUP BY F df2.groupby('F').sum() df2 #### Notice that F has been turned from a column to an index, and the df2.groupby('F').sum().reset_index() #### Now there's a new index so F can be a column again #### SELECT SUM(D) FROM df2 WHERE F IN ('x','y') GROUP BY F df2[df2['F'].isin(['x','y'])].groupby('F').sum() #### SELECT SUM(D) FROM df2 GROUP BY F,E df2 df2.groupby(['F','E']).sum() df2.groupby(['F','E']).sum().reset_index() #### Dealing with null values: note that there are two to watch out for, None and np.nan ('NaN') #### A simple dataframe from a dictionary with a None value d = {'A':[1,2,3],'B':[20,nan,60],'c':['x','y',None]} d df = pd.DataFrame(d) df #### One thing to note: in SQL NULL = NULL has Unknown truth value. Python behaves differently: None == None #### True nan==nan #### False df.isna() df.isnull() #### This seem equivalent, but there may be a difference between isna and isnull #### SELECT ISNULL(B,0) FROM df
import math def reverse(x: int) -> int: rem = abs(x) % 10 temp = int(abs(x) / 10) result = 0 while temp > 0: result = result * 10 + rem rem = temp % 10 temp = int(temp / 10) result = result * 10 + rem if x < 0: result = result * -1 if -1 * (math.pow(2, 31)) <= result <= (math.pow(2, 31)) - 1: return result return 0
"""Perform flood algorithms on numpy arrays.""" import numpy def flood_fill(array, start_pos, fill_value): """Fill contiguous region of an array with a new value""" for row, col in flood_select(array, start_pos): array[row][col] = fill_value def _valid_neighbors(array, position): """Return neighbors of a position that are inside the array.""" row, col = position num_rows, num_cols = array.shape[:2] neighbors = [] for row_delta, col_delta in [(0, -1), (1, 0), (0, 1), (-1, 0)]: new_row, new_col = row + row_delta, col + col_delta if new_row >= 0 and new_row < num_rows: if new_col >= 0 and new_col < num_cols: neighbors.append((new_row, new_col)) return neighbors def recursive_flood_select(array, start_pos, selected=None): """Return list of positions in order that they will be flood-filled This implementation is recursive so it will be extremely limited! """ if selected is None: selected = [[False for _ in array[0]] for _ in array] num_rows = len(array) num_cols = len(array[0]) row, col = start_pos selected[row][col] = True rest = [] for delta_row, delta_col in [(-1, 0), (0, 1), (1, 0), (0, -1)]: new_row = row + delta_row new_col = col + delta_col in_array = (new_row >= 0 and new_row < num_rows and new_col >= 0 and new_col < num_cols) # Is this a valid, unvisited neighbor? if in_array and not(selected[new_row][new_col]): # Does the neighbor have the same value? if array[row][col].all() == array[new_row][new_col].all(): new_pos = (new_row, new_col) rest.extend(recursive_flood_select(array, new_pos, selected)) return [start_pos] + rest def flood_select(array, start_pos): """Return list of positions in order that they will be flood-filled Stack-based implementation- keep track of which locations still need to be processed on a stack. """ stack = [start_pos] target_color = array[start_pos] selection = [] visited = numpy.zeros(array.shape[:2], dtype=numpy.bool8) # Pop from stack and push neighbors on until it's empty while stack: #print "stack: {}".format(stack) current_pos = stack.pop() color_matches = (array[current_pos] == target_color).all() if color_matches and not(visited[current_pos]): selection.append(current_pos) stack.extend(_valid_neighbors(array, current_pos)) visited[current_pos] = True return selection def test_recursive_iterative_flood_select(): """Make sure recursive and iterative flood select have the same results""" pass
def ADD(v1, v2): n = v1 + v2 return n def SUBT(v1, v2): n = v1 - v2 return n def DIVI(v1, v2): n = v1 / v2 return n def MUL(v1, v2): n = v1 * v2 return n X = int(input("Enter first value: ")) Y = int(input("Enter second value: ")) print("Press 1 to ADD.") print("Press 2 to SUB.") print("Press 3 to MUL.") print("Press 4 to DIV.") print("Press 5 to Exit.") op = int(input()) if op == 1: myAns = ADD(X, Y) if op == 2: myAns = SUBT(X, Y) if op == 4: myAns = DIVI(X, Y) if op == 3: myAns = MUL(X, Y) print("Answer is =", myAns)
def displayOptions(): print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Exit") return def addData(x, y): z = x + y return z def subData(x, y): z = x - y return z def mulData(x, y): z = x * y return z def divData(x, y): z = x / y return z choice = 0 while not choice == 5: displayOptions() choice = 0 while not 1 <= choice <= 5: choice = int(input("Enter choice (1..5) ")) if choice != 5: first = int(input("Enter first value: ")) second = int(input("Enter second value: ")) if choice == 1: result = addData(first, second) if choice == 2: result = subData(first, second) if choice == 3: result = mulData(first, second) if choice == 4: result = divData(first, second) print("Your result is =", result)
import random def gameWin(comp,you): if comp==you: return None elif comp== 's': if you=='w': return False elif you=='g': return True elif comp=='w': if you=='g': return False elif you=='s': return True elif comp=='g': if you=='s': return False elif you=='w': return True print("Comp Turn: Snake(s) Water(w) or Gun(g)") randNo= random.randint(1,3) if randNo==1: comp='s' elif randNo==2: comp='s' elif randNo==3: comp='s' you = input("Your Turn: Snake(s) Water(w) or Gun(g) ") a= gameWin(comp,you) print(f"Computer chose {comp}") print(f"You chose {you}") if a == None: print("Tie!") elif a: print("You Win!") else: print("You Lose!")
import sqlite3 conn = sqlite3.connect('dealership.sqlite') cur = conn.cursor() f = open('dealership_db.sql','r') sql = f.read() cur.executescript(sql) dealer = input("Enter dealer id") cur.execute("SELECT * FROM Dealership WHERE dealer_id = ?", (dealer)) dealership = cur.fetchone() if dealership is None: dealer_id = input("Enter new dealer id") address = input("Enter address of dealership") telno = input("Enter Telephone of dealership") cur.execute('''INSERT INTO Dealership(dealer_id, address, tel_no) VALUES(?,?,?)''', (dealer_id, address, telno)) print("Added") conn.commit() else: print("Dealership already exists")
from tkinter import ttk import os class StdoutRedirect: ''' Class used to redirect stdout to widget. Used with widgets that accept text Usage: import sys sys.stdout=TextRedirect(widget) Parameters ----------------------- widget : tk.widget object ''' def __init__(self,widget): self.widget = widget def write(self, str): self.widget.configure(state="normal") self.widget.insert("end", str) self.widget.configure(state="disabled") def window_size(root,size='Full_screen'): ''' Function to resize window. Default is full screen. Takes a turple that divides width and height by to produce new window dimentions Parameters ----------- root : tk object, window size : turple of two int , optional First element is int to divde width by second elment is int to divide height by Returns ---------- Dictionary of width and value dimensions ''' if size =='Full_screen': width = root.winfo_screenwidth() height = root.winfo_screenheight() else: width = root.winfo_screenwidth() /size[0] height = root.winfo_screenheight()/size[1] spec={'width':int(width) ,'height':int(height)} return spec def current_size(root): ''' Function to get window size. Parameters ----------- root : tk object, window Returns ---------- Dictionary of width and value dimensions ''' width = root.winfo_screenwidth() height = root.winfo_screenheight() size={'width':width ,'height':height} return size def set_style(root,style='awdark'): ''' Function to set style. Default is awdark. Parameters ----------- root : Tk() object style: str optional. Default is awdark Returns ---------- style ''' ttk_style=style location=os.getcwd() if '/bean_gui/' in location: os.chdir('..') styles_path = os.path.abspath('styles') #todo find a more robust way to find the 'styles' folder. currently only works if in bean_gui directory style = ttk.Style(root) root.tk.eval(f"""set base_theme_dir {styles_path}/awthemes-10.4.0 package ifneeded awthemes 10.4.0 \ [list source [file join $base_theme_dir awthemes.tcl]] package ifneeded colorutils 4.8 \ [list source [file join $base_theme_dir colorutils.tcl]] package ifneeded {ttk_style} 7.12 \ [list source [file join $base_theme_dir {ttk_style}.tcl]] """) root.tk.call("package", "require", ttk_style) return style.theme_use(ttk_style)
number = int(input()) for i in range(number): print(" "*(number-i),"*"*(((i+1)*2)-1))
a = 0 if a <= 10: print('menor') else: print('maior') if a == 1: print('é um') elif a > 1 and a <= 10: print('esta entre 1 e 10') elif a == 0: print('é zero') elif a < 1: print('é um numero negativo') else: print('maior q 10') teste = 'Teste 123 teste' if 'Teste' in teste: print('Achei') if '123' in teste: print('tem numero') else: print('nao tem numero')
for i in range(6): print(i) for i in range(10, 20): print(i) else: print("Acabooooooo!") x = 0 while True: print('Loop') x += 1 if x >= 10: break x = 0 y = 0 while x <= 10: print(x) y += 1 if y == 10: break
from math import * def isprime(n): if n == 1: return False for i in range(2, int(sqrt(n)+1)): if n % i == 0: return False return True def t(n): L = [] while isprime(n) == False: for i in range(2, n): if isprime(i): if n % i == 0: L.append(i) n = n // i break L.append(n) return L def h(n): L = [i for i in range(2, n+1)] L1 = [] for i in L: if isprime(i): continue else: L1.append(i) for i in L1: L.remove(i) L2 = [t(i) for i in L1] L1 = [] for i in L2: for j in i: L1.append(j) L1 += L L2 = [] for i in L: x = L1.count(i) if x != 1: s = str(i) + '^' + str(x) else: s = str(i) L2.append(s) return str(n) + '=' + '*'.join(L2) print(h(6))
#-- coding: utf-8 -- L = 'caayyhheehhbzbhhjhhyyaac' size = len(L) length = -1 maxup = -1 maxdown = -1 for i in range(size-1): if L[i] == L[i+1]:#中心字母有两个 down = i up = i + 1 if (L[i] != L[i+1] or (i - 1 >= 0 and L[i] == L[i-1] and L[i] == L[i+1])):#中心字母为一个 down = i up = i while True: if (down - 1 >= 0 and up + 1 < size and L[down-1] == L[up+1]): down -= 1 up += 1 else: if length < up - down + 1: length = up - down + 1 maxdown = down maxup = up break print(L[maxdown : maxup+1])
C = int(input()) for i in range(C): cont = 0 N = int(input()) for i in range(N): if i % 2 == 0 or i == 0: cont += 1 else: cont -= 1 print(cont)
aux1 = 0 for i in range(5): x = int(input()) if x % 2 == 0: aux1 += 1 print("%d valores pares" %aux1)
aux1 = aux2 = aux3 = 0 for i in range(6): x = float(input()) if x > 0: aux1 += 1 aux2 = aux2 + x aux3 = "%.1f" % (aux2 / aux1) print("%d valores positivos" %aux1) print(aux3)
contg = inter = gremio = emp = quem = 0 cond = 1 while cond == 1: gr1, gr2 = map(int, input().split()) contg += 1 if gr1 > gr2: inter += 1 elif gr2 > gr1: gremio += 1 else: emp += 1 cond = int(input("Novo grenal (1-sim 2-nao)\n")) if inter > gremio: quem = "Inter venceu mais" elif gremio > inter: quem = "Gremio venceu mais" else: quem = "Nao houve vencedor" print("%s grenais\n" "Inter:%s\n" "Gremio:%s\n" "Empates:%s\n" "%s" %(contg, inter, gremio, emp, quem))
aux = cont = 0 X = int(input()) Z = int(input()) while Z <= X: Z = int(input()) while aux < Z: if cont == 0: aux = X else: X += 1 aux = X + aux cont += 1 print(cont)
x = float(input()) aux = i = 0 print("NOTAS:") for i in [100, 50, 20, 10, 5, 2]: while x >= i: x -= i aux += 1 print("%d nota(s) de R$ %d.00" %(aux, i)) aux = 0 x2 = int(x * 100) print("MOEDAS:") for i in [100, 50, 25, 10, 5, 1]: while x2 >= i: x2 -= i aux += 1 x3 = "%.2f" % (i / 100) print("%d moeda(s) de R$ %s" %(aux, x3)) aux = 0
def tip_calculator(): print("Total Price with tip: " + str(pirce * .15 + pirce)) def calculator_for_tip(): print("Tip Calculator") print("_" * 40) pirce = float(input("Please enter cost: ")) tip_calculator()
import csv import error import listGenrator def au(): print(listGenrator.addUserList()) order = str(input(" Your username:")) words = order.split() if words[0] == 'B' or words[0] == 'b': return if words[1] == 'A' or words[1] == 'a': with open('addUser.csv') as myFile: reader = csv.DictReader(myFile) data = [r for r in reader] myFile.close() x = 0 while data: if data[x]['user'] == words[0]: row = [data[x]['user'], data[x]['pass'], '1397/1/1', 'N/A'] if data[x]['type'] == 's': with open('students.csv', 'a') as csvFile: writer = csv.writer(csvFile) writer.writerow(row) csvFile.close() elif data[x]['type'] == 't': with open('teachers.csv', 'a') as csvFile: writer = csv.writer(csvFile) writer.writerow(row) csvFile.close() elif data[x]['type'] == 'a': with open('admin.csv', 'a') as csvFile: writer = csv.writer(csvFile) writer.writerow(row) csvFile.close() else: print(error.errorsList("003")) odd = [] with open("addUser.csv", 'r') as csvFile: reader = csv.DictReader(csvFile) for row in reader: data = dict(row) if data['user'] != words[0]: odd.append(data) with open('addUser.csv', 'w') as csvFile: fields = ['type', 'user', 'pass', 'condition'] writer = csv.DictWriter(csvFile, fieldnames=fields) writer.writeheader() writer.writerows(odd) break x += 1 # odd = [] # newCon = {'condition': 'A'} # with open("addUser.csv", 'r') as csvFile: # reader = csv.DictReader(csvFile) # for row in reader: # data = dict(row) # # if data['user'] == words[0]: # data.update(newCon) # odd.append(data) # # with open('addUser.csv', 'w') as csvFile: # fields = ['type', 'user', 'pass', 'condition'] # writer = csv.DictWriter(csvFile, fieldnames=fields) # writer.writeheader() # writer.writerows(odd) elif words[1] == 'd' or words[1] == 'D': odd = [] newCon = {'condition': 'D'} with open("addUser.csv", 'r') as csvFile: reader = csv.DictReader(csvFile) for row in reader: data = dict(row) if data['user'] == words[0]: data.update(newCon) odd.append(data) with open('addUser.csv', 'w') as csvFile: fields = ['type', 'user', 'pass', 'condition'] writer = csv.DictWriter(csvFile, fieldnames=fields) writer.writeheader() writer.writerows(odd) else: print(error.errorsList("003")) return '' def al(): print(listGenrator.addLesList()) order = str(input(" Your username:")) words = order.split() if words[0] == 'B' or words[0] == 'b': return if words[1] == 'A' or words[1] == 'a': with open('addLesson.csv') as myFile: reader = csv.DictReader(myFile) data = [r for r in reader] myFile.close() x = 0 while data: if data[x]['lesson'] == words[0]: row = [data[x]['lesson'], data[x]['tea']] with open('lessons.csv', 'a') as csvFile: writer = csv.writer(csvFile) writer.writerow(row) csvFile.close() odd = [] with open("addLesson.csv", 'r') as csvFile: reader = csv.DictReader(csvFile) for row in reader: data = dict(row) if data['lesson'] != words[0]: odd.append(data) with open('addLesson.csv', 'w') as csvFile: fields = ['lesson', 'tea', 'condition'] writer = csv.DictWriter(csvFile, fieldnames=fields) writer.writeheader() writer.writerows(odd) break x += 1 elif words[1] == 'd' or words[1] == 'D': odd = [] newCon = {'condition': 'D'} with open("addLesson.csv", 'r') as csvFile: reader = csv.DictReader(csvFile) for row in reader: data = dict(row) if data['lesson'] == words[0]: data.update(newCon) odd.append(data) with open('addLesson.csv', 'w') as csvFile: fields = ['lesson', 'tea', 'condition'] writer = csv.DictWriter(csvFile, fieldnames=fields) writer.writeheader() writer.writerows(odd) else: print(error.errorsList("003")) return '' def ep(user): newPasscode = str(input(" please enter new pas:")) odd = [] newPass = {'pass': newPasscode} with open("admins.csv", 'r') as csvFile: reader = csv.DictReader(csvFile) for row in reader: data = dict(row) if data['username'] == user: data.update(newPass) odd.append(data) with open('admins.csv', 'w') as csvFile: fields = ['username', 'pass', 'lastLogin', 'name'] writer = csv.DictWriter(csvFile, fieldnames=fields) writer.writeheader() writer.writerows(odd) print("writing completed") csvFile.close() def e(user): newUsername = str(input(" please enter new Username:")) newNames = str(input(" please enter new Name:")) odd = [] newUser = {'username': newUsername} newName = {'name': newNames} with open("admins.csv", 'r') as csvFile: reader = csv.DictReader(csvFile) for row in reader: data = dict(row) if data['username'] == user: data.update(newUser) data.update(newName) odd.append(data) # del data[2] with open('admins.csv', 'w') as csvFile: fields = ['username', 'pass', 'lastLogin', 'name'] writer = csv.DictWriter(csvFile, fieldnames=fields) writer.writeheader() writer.writerows(odd) print("writing completed") csvFile.close()
def main(): # Main function from os import system, name # Imports OS to allow us to clear the console to print the ASCII text. from random import choice # Import the choice function from the random library to choose a random word from our words list. system("cls" if name == "nt" else "clear") # Clears the terminal, should work across all operating systems. # List of words the program will choose from. words = ["apple", "banana", "mango", "strawberry", "orange", "grape", "pineapple", "apricot", "lemon", "coconut", "watermelon", "cherry", "papaya", "berry", "peach", "lychee", "muskmelon"] hangman = ["""\n +---+\n | |\n |\n |\n |\n |\n=========""", """\n +---+\n | |\n O |\n |\n |\n |\n=========""", """\n +---+\n | |\n O |\n | |\n |\n |\n=========""", """\n +---+\n | |\n O |\n /| |\n |\n |\n=========""", """\n +---+\n | |\n O |\n /|\ |\n |\n |\n=========""", """\n +---+\n | |\n O |\n /|\ |\n / |\n |\n=========""", """\n +---+\n | |\n O |\n /|\ |\n / \ |\n |\n========="""] # List of ASCII hangman images if len(words) > 0: # Checks to see if the list of words is empty, check end of if so it will print an error, otherwise it will continue. word = choice(words) # Chooses a random word from our list of words. guesses = "" # Initiates a blank string for our list of guesses which will be used within the code and also allow the user to know what they have already guessed. replaced = "" # Initiates a blank string to print our already found characters and the underlines. for char in word: # For loop to properly create the replaced string. if char == " ": # Checks to see if the character is a space, if so adds a space to the replaced string. replaced += " " else: # Checks to see if the character is not a space, if so it adds an underline to the string. replaced += "_" turns = 6 # Amount of turns a user is allowed. Default amount of turns is six as that"s how many limbs will be printed, if changed limbs will not be printed. failed = 0 # How many times the user has failed. while failed != turns: # Create a while loop to keep going until the user runs out of turns. system("cls" if name == "nt" else "clear") # Clears the terminal. if turns == 6: # Checks to see if the turns is the default amount, if so it'll print out ASCII hangman image. print(hangman[failed]) print(f"Word: {replaced.upper()}") # Prints our replaced string so the user knows what characters they got successfully and what else they need to get. right = 0 # Initiates a variable called right which will be used in the for loop below. for char in word: # For loop, will go through each character in the word. if char in guesses: # Checks to see if the character is in the guesses list and if so it'll add one to the right count. right += 1 if right >= len(word): # If the length of the word is less then or equal to the right variable the program will end and alert the user they finished successfully. print("Nice job! You guessed the word correctly!") return print(f"Guesses: {guesses.upper()}") # Prints what the user has already guessed. guess = input("Please provide a guess!: ") # Asks the user for a guess. if guess not in guesses: # If the guess they provided is not in the guesses string it will go through a for loop for each character in the guess, if the character is not in guesses it will add it. f = 0 # Initiates an f variable for failed. for char in guess: if char not in guesses: guesses += char if char not in word: f = 1 # If it does fail it won't count per character but per guess so it will set f to 1 failed += f # Add f to failed, if they already guessed their guess it won't add anything but if they guess something that they haven't guessed before it'll add one to the failed count. if guess in word: # Checks to see if their guess is in the word. replaced = "" # Initiates the replaced string again. for char in word: # Looks through each character in the word. if char in guesses: # If the character is in guesses it will add the character to the string. replaced += char elif char == " ": # If the character is a space it will add a space. replaced += " " else: # If the character is not in the guesses list and not a space it will add an underline. replaced += "_" system("cls" if name == "nt" else "clear") # Clears the console. if turns == 6: # If the turns amount is default it will print the final ASCII hangman image. print(hangman[6]) print("You had to many failed attempts, feel free to run this file again to play again!") # Alerts the user that they used up all of their attempts. else: print('Empty list of words provided, please edit the file and add at least one word to the list named "words".') # Alerts the user that the words list is empty. main() # Calls the main function.
student_name = input("enter the student name: ") print("Hi " + student_name) city_name = input("enter the name of city: ") print("The city name is ",city_name,":-)") age = int(input("enter the age: ")) #every input is str but here we convert it into int print(type(age)) age2= int(age) print(int(age2)) print(type(age2)) print ("age = ",age) get_email = input (" want to get email, y/n? : ") print ("get email = " + get_email) print("it's a quote") print('I said, "we can use/print doube quote now it string like this"') # Boolean string Test print("Python".isalpha()) "3rd".isalnum() "A Cold Stormy Night".istitle() "1003".isdigit() cm_height = "176" print("cm height:",cm_height, "is all digits =",cm_height.isdigit()) print("SAVE".islower()) print("SAVE".isupper()) "Boolean".startswith("B") print("alphabetical".isalpha()) print("Are spaces and punctuation Alphabetical?".isalpha()) menu = "salad, pasta, sandwich, pizza, drinks, dessert" print('pizza' in menu)
''' cow will give born to a litter cow each year, and litter cow will do the same after four years, so when the nth year, how many cows in total? ''' def cow_story(n): if n<3: return 1 else: return cow_story(n-1)+cow_story(n-3) if __name__=="__main__": for n in range(6): print("year{}".format(n+1)) print(cow_story(n))
import better_exceptions def binary_search(l,low,high,v): mid = int((low+high)/2) if v==l[mid]: return mid elif v>l[mid]: return binary_search(l,mid+1,high,v) else: return binary_search(l,low,mid,v) def binary_search2(l,v): low = 0 high = len(l)-1 while low<high: mid = int((low+high)/2) if l[mid] == v: return mid elif v>l[mid]: low = mid+1 else: high = mid if __name__=="__main__": a=[1,2,2,3,5,7,10] print(binary_search(a,0,len(a)-1,2)) print(binary_search2(a,2))
''' find max path value for tree 1 1 10 30 1 2 the max valu path is 1-->1-->30 = 32 ''' class Node(): def __init__(self, value, row, col): self.value = value self.row = row self.col = col self.__left_child = None self.__right_child = None @property def left_child(self): return self.__left_child @left_child.setter def left_child(self, value): self.__left_child = value @property def right_child(self): return self.__right_child @right_child.setter def right_child(self, value): self.__right_child = value def max_value(self, tree): if self.left_child == None: return self.value else: return self.value + max(tree.node(self.left_child).max_value(tree), tree.node(self.right_child).max_value(tree)) class Tree(): def __init__(self, l): self.tree = [] for row_index in range(len(l)): self.tree.append([]) for col_index in range(len(l[row_index])): self.tree[row_index].append(None) def __str__(self): result = [] for row in self.tree: tmp = [] for col in row: tmp.append(col.value) result.append(tmp) return str(result) def node(self, location): return self.tree[location[0]][location[1]] def set_node(self, location, value): self.tree[location[0]][location[1]] = value def build_tree(l): ''' l = [[1],[2,3],[4,5,6], [7,8,9,10]] 1 2 3 4 5 6 7 8 9 10 ''' tree = Tree(l) for row_index in range(len(l)): for col_index in range(len(l[row_index])): node = Node(l[row_index][col_index], row_index, col_index) if row_index+1<len(l): node.left_child = [row_index+1, col_index] node.right_child = [row_index+1, col_index+1] tree.set_node([row_index, col_index], node) return tree if __name__=="__main__": l = [[1],[1,10],[30,5,6]] tree = build_tree(l) print(tree) print(tree.node([0,0]).max_value(tree))
class Edge(): def __init__(self, l_node, r_node, weight = 0): self.l_node = l_node self.r_node = r_node self.weight = weight class Graph(): def __init__(self, vertices=[], edges=[]): self.vertices = vertices self.edges = [] for i in edges: print(i) self.edges.append(Edge(edges[0], edges[1])) if __name__ == '__main__': v = [1, 2, 3] e = [[1, 2], [1, 3], [2, 3]] g = Graph (v, e) # See PyCharm help at https://www.jetbrains.com/help/pycharm/
def diagonal(n): y=len(n0 if n==1: return n; if n>1: for i in range(0,n): x=[0,0] x[0]=x[0]+(n[i][i]) x[1]=x[1]+(n[y-i-1][y-i-1]) return(x[0]*x[1]) return 0 try: with open('Diagonal.txt') as f: data = f.read().split() num_of_tests = data[0] data = data[1:] for i in range(0, int(num_of_tests)): matrix = [] dimen = int(data[0]) data = data[1:] for j in range(0, dimen): row = data[:dimen] matrix.append(row) data = data[dimen:] print diagonal(matrix) except IOError, e: print e
def digit_sum(n): x=[] y=str(n) for char in y: z=int(char) x.append(z) return sum(x) def is_int(x): y=int(x) if (x-y)==0: return True else: return False def is_even(x): if x%2==0: return True else: return False def factorial(x): if x==0 or x==1: return 1 else: return x*factorial(x-1) def is_prime(x): if x<2: return False for i in range(2,x+1): if (x/i)==1: return True elif x%i==0: return False def reverse(text): x = [] y = "" i = len(text)-1 while i >= 0: x.append(text[i]) i-=1 for char in x: y=y+char return yr def anti_vowel(text): vowels=['a','e','i','o','u','A','E','I','O','U'] x=[] t=list(text) for char in text: if char not in vowels: x.append(char) return ''.join(x) score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} def scrabble_score(word): result=0 word=word.lower() for char in word: result+=score[char] return result
# Match score is X:Y, user prediction is A:B. # If user predicts the result of the match - user gets 10 point # If user predicts the win or lose or draw - user gets 5 point # If user make a mistake - user gets nothing def f(x, y, a, b): score = 0 if x == a and b == y: score = 10 elif x > y and a > b or y > x and b > a or a == b and x == y: score = 5 return score