text
stringlengths
37
1.41M
#Remember to use the random module #Hint: Remember to import the random module here at the top of the file. 🎲 #Write the rest of your code below this line 👇 import random; randomNumber = random.randint(0, 1) if(randomNumber == 1): print("Heads") else: print("Tails")
print("Hello"[0]) print("Hello"[3]) print(2311) #float print(3.14159) #only visual print(23_345_454) #boolena #type name = "Luis" type(name) # 🚨 Don't change the code below 👇 two_digit_number = input("Type a two digit number: ") # 🚨 Don't change the code above 👆 #################################### #Write your code below this line 👇 result = int(two_digit_number[0]) + int(two_digit_number[1]) print(result) # 🚨 Don't change the code below 👇 height = input("enter your height in m: ") weight = input("enter your weight in kg: ") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 #result = float(weight) / (float(height) * float(height)) result = float(weight) / (float(height) ** 2) print(int(result))
student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } # 🚨 Don't change the code above 👆 #TODO-1: Create an empty dictionary called student_grades. student_grades = {} #TODO-2: Write your code below to add the grades to student_grades.👇 #print(student_scores["Harry"]) #81 #print(student_scores.keys()) #Harry, Ron, etc #print(student_scores.values()) #81,78, etc #print(student_scores.items()) #('Harry', 81) etc for student in student_scores: grades = "" scores = student_scores[student] if scores >= 91 and scores <= 100: grades = "Outstanding" elif scores >= 81 and scores <= 90: grades = "Exceeds Expectations" elif scores >= 71 and scores <= 80: grades = "Acceptable" else: grades = "Fail" student_grades[student] = grades # 🚨 Don't change the code below 👇 print(student_grades)
import re hand = open('short.txt') for line in hand: line = line.rstrip() if re.search('From:', line): print(line) print('--------------') hand = open('short.txt') for line in hand: line = line.rstrip() if re.search('^From:', line): print(line)
country = 'Canada' exist = 'n' in country if(exist): print('Get it!') if 'd' in country: print('Found it!')
#Learn Python 3 The Hardway #Exercise 2 # A comment, this is so you can read your program laterself. # Anything after the # is ignored by Phyton. print ("I could hace code like this") # and the comment after is ignoredself. # You can also use a comment to "disable" or comment out code # print ("This won't run.") print("This will run.") print("Hi # there.")
""" 230-kth-smallest-element-in-a-bst leetcode/medium/230. Kth Smallest Element in a BST Difficulty: medium URL: https://leetcode.com/problems/kth-smallest-element-in-a-bst/ """ from typing import List # 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 pre_order_travelling(self, root, values): if root: values.append(root.val) self.pre_order_travelling(root.left, values) self.pre_order_travelling(root.right, values) def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: values = [] self.pre_order_travelling(root, values) return sorted(values)[k - 1] ############################################################################### # NOTE: Interest Solution # https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63703/Pythonic-approach-with-generator ############################################################################### class Solution: # @param {TreeNode} root # @param {integer} k # @return {integer} def kthSmallest(self, root, k): for val in self.inorder(root): if k == 1: return val else: k -= 1 def inorder(self, root): if root is not None: for val in self.inorder(root.left): yield val yield root.val for val in self.inorder(root.right): yield val
# human-readable-duration-format # https://www.codewars.com/kata/52742f58faf5485cae000b9a/ from unittest import TestCase from collections import OrderedDict def format_duration(seconds): if seconds == 0: return 'now' times = OrderedDict( second=(1, 60), minute=(60, 60), hour=(3600, 24), day=((3600 * 24), 365), year=(3600 * 24 * 365, 0) ) result = [] for key, v in times.items(): value = seconds // v[0] if v[1]: value %= v[1] if value > 1: result.append(f'{value} {key}s') elif value == 1: result.append(f'{value} {key}') result.reverse() if len(result) > 1: return ", ".join(result[0:len(result) - 1:]) + " and " + result[-1] return result[0] TestCase().assertEqual(format_duration(1), "1 second") TestCase().assertEqual(format_duration(62), "1 minute and 2 seconds") TestCase().assertEqual(format_duration(120), "2 minutes") TestCase().assertEqual(format_duration(3600), "1 hour") TestCase().assertEqual(format_duration(3662), "1 hour, 1 minute and 2 seconds") TestCase().assertEqual(format_duration(15731080), "182 days, 1 hour, 44 minutes and 40 seconds")
# 134-gas-station # leetcode/medium/134. Gas Station # URL: https://leetcode.com/problems/gas-station/description/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import List class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(gas) < sum(cost): return -1 index = 0 total = 0 for i in range(len(gas)): total += gas[i] - cost[i] if total < 0: index = i + 1 total = 0 return index gas = [1, 2, 3, 4, 5] cost = [3, 4, 5, 1, 2] print(Solution().canCompleteCircuit(gas, cost)) # Output: 3 gas = [2, 3, 4] cost = [3, 4, 3] print(Solution().canCompleteCircuit(gas, cost)) # Output: -1 gas = [2] cost = [2] print(Solution().canCompleteCircuit(gas, cost)) # 0
# leetcode/medium/80. Remove Duplicates from Sorted Array II # 80-remove-duplicates-from-sorted-array-ii # URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/?envType=study-plan-v2&id=top-interview-150 # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: index = 2 while index < len(nums): if nums[index] == nums[index - 2]: nums.remove(nums[index]) else: index += 1 return len(nums) nums = [1, 1, 1, 2, 2, 3] print(Solution().removeDuplicates(nums)) # Output: 5 nums = [1,1,2,2,3,_] nums = [0, 0, 1, 1, 1, 1, 2, 3, 3] print(Solution().removeDuplicates(nums)) # Output: 7, nums = [0,0,1,1,2,3,3,_,_]
""" leetcode/easy/160. Intersection of Two Linked Lists Difficulty: easy URL: https://leetcode.com/problems/intersection-of-two-linked-lists/ """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, head_a, head_b): list_a = [] list_b = [] while head_a: list_a.append(head_a) head_a = head_a.next while head_b: list_b.append(head_b) head_b = head_b.next list_a = list_a[::-1] list_b = list_b[::-1] list_a.append(None) list_b.append(None) last = None for a, b in zip(list_a, list_b): print(a,b) if a != b: return last last = a return "No intersection"
""" 832-flipping-an-image leetcode/easy/832. Flipping an Image URL: https://leetcode.com/problems/flipping-an-image/ """ from typing import List class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: return list(map( lambda _list: list( reversed( list( map( lambda x: 1 if x == 0 else 0, _list ) ) ) ), image )) def test(): image = [[1, 1, 0], [1, 0, 1], [0, 0, 0]] output = [[1, 0, 0], [0, 1, 0], [1, 1, 1]] assert Solution().flipAndInvertImage(image) == output image = [[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]] output = [[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]] assert Solution().flipAndInvertImage(image) == output
# even-numbers-in-an-array # Even numbers in an array # difficulty: 7kyu # https://www.codewars.com/kata/5a431c0de1ce0ec33a00000c from unittest import TestCase def even_numbers(arr, n): return list(filter(lambda e: e % 2 == 0, arr))[-n::] TestCase().assertEqual(even_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 3), [4, 6, 8]); TestCase().assertEqual(even_numbers([-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2), [-8, 26]); TestCase().assertEqual(even_numbers([6, -25, 3, 7, 5, 5, 7, -3, 23], 1), [6]);
""" 141-linked-list-cycle leetcode/easy Difficulty: easy URL: https://leetcode.com/problems/linked-list-cycle/ """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head) -> bool: visited_node = [] if head is None: return False while not head in visited_node and head.next: visited_node.append(head) head = head.next return head in visited_node
""" 1528-shuffle-string leetcode/easy/1528. Shuffle String Difficulty: easy URL: https://leetcode.com/problems/shuffle-string/ """ from typing import List class Solution: def restoreString(self, s: str, indices: List[int]) -> str: zipped_list = list(zip([*s], indices)) zipped_list.sort(key=lambda x: x[1]) return ''.join([x[0] for x in zipped_list]) def test(): solution = Solution() s = "codeleet" indices = [4, 5, 6, 7, 0, 2, 1, 3] output = "leetcode" assert solution.restoreString(s, indices) == output
""" 938-range-sum-of-bst leetcode/easy/938. Range Sum of BST Difficulty: easy URL: https://leetcode.com/problems/range-sum-of-bst/ """ # 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 depth_first_search(self, root): if root is None: return [] return [root.val, *self.depth_first_search(root.left), *self.depth_first_search(root.right)] def rangeSumBST(self, root, low: int, high: int) -> int: return sum( filter(lambda x: x if low <= x <= high else 0, sorted(self.depth_first_search(root))) ) # one of clever solution class Solution: def rangeSumBST(self, root, low, high): def dfs(node): if not node: return if low <= node.val <= high: self.out += node.val if node.val > low: dfs(node.left) if node.val < high: dfs(node.right) self.out = 0 dfs(root) return self.out
""" 1469-find-all-the-lonely-nodes leetcode/easy/1469. Find All The Lonely Nodes Difficulty: easy URL: https://leetcode.com/problems/find-all-the-lonely-nodes/ """ # 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 getLonelyNodes(self, root) -> List[int]: result = [] def pre_order_traversal(root): if not root.left or not root.right: if root.left: result.append(root.left.val) pre_order_traversal(root.left) if root.right: result.append(root.right.val) pre_order_traversal(root.right) else: pre_order_traversal(root.left) pre_order_traversal(root.right) pre_order_traversal(root) return result
# leetcode/medium/912. Sort an Array # 912-sort-an-array # URL: https://leetcode.com/problems/sort-an-array/description/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import List class Solution: def mergeSort(self, nums): if len(nums) == 1: return nums if len(nums) == 2: if nums[0] < nums[1]: return nums return [nums[1], nums[0]] mid = len(nums) // 2 left = self.mergeSort(nums[:mid]) right = self.mergeSort(nums[mid:]) result = [] while left and right: if left[0] < right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) if left: result += left if right: result += right return result def sortArray(self, nums: List[int]) -> List[int]: return self.mergeSort(nums) nums = [5, 2, 3, 1] print(Solution().sortArray(nums)) # Output: [1,2,3,5] nums = [5, 1, 1, 2, 0, 0] print(Solution().sortArray(nums)) # Output: [0,0,1,1,2,5]
# leetcode/medium/802. Find Eventual Safe States # 802-find-eventual-safe-states # URL: https://leetcode.com/problems/find-eventual-safe-states/description/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import List class Solution: def __init__(self): self.safe_nodes_set = set() def isSafeNode(self, index, node): if index in self.safe_nodes_set: return True for i in node: if i not in self.safe_nodes_set: return False return True def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: for i in range(len(graph)): if graph[i] == []: self.safe_nodes_set.add(i) has_safe_nodes = True while has_safe_nodes: has_safe_nodes = False for i in range(len(graph)): if i not in self.safe_nodes_set and self.isSafeNode(i, graph[i]): self.safe_nodes_set.add(i) has_safe_nodes = True return sorted(list(self.safe_nodes_set)) graph = [[1, 2], [2, 3], [5], [0], [5], [], []] assert Solution().eventualSafeNodes(graph) == [2, 4, 5, 6] Output: [2, 4, 5, 6] graph = [[1, 2, 3, 4], [1, 2], [3, 4], [0, 4], []] assert Solution().eventualSafeNodes(graph) == [4] # Output: [4] graph = [[], [0, 2, 3, 4], [3], [4], []] assert Solution().eventualSafeNodes(graph) == [0, 1, 2, 3, 4] # [0,1,2,3,4] graph = [[1, 3, 4, 5, 7, 9], [1, 3, 8, 9], [3, 4, 5, 8], [1, 8], [5, 7, 8], [8, 9], [7, 8, 9], [3], [], []] assert Solution().eventualSafeNodes(graph) == [5, 8, 9] # [5,8,9]
# https://leetcode.com/problems/excel-sheet-column-number from unittest import TestCase # Runtime: 32 ms, faster than 53.72% of Python3 online submissions for Excel Sheet Column Number. # Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Excel Sheet Column Number. # Runtime: 28 ms, faster than 81.16% of Python3 online submissions for Excel Sheet Column Number. # Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Excel Sheet Column Number. class Solution: def titleToNumber(self, s: str) -> int: sum = 0 for i, v in enumerate(s[::-1]): column_number = ord(v) % 65 + 1 exponent = (26 ** i) sum += exponent * column_number or column_number return sum TestCase().assertEqual(Solution().titleToNumber('A'), 1) # Input: "A" # Output: 1 TestCase().assertEqual(Solution().titleToNumber('AA'), 27) TestCase().assertEqual(Solution().titleToNumber('AAA'), 703) # TestCase().assertEqual(Solution().titleToNumber('AB'), 28) # # Input: "AB" # # Output: 28 # TestCase().assertEqual(Solution().titleToNumber('ZY'), 701) # Input: "ZY" # Output: 701
""" 1221-split-a-string-in-balanced-strings leetcode/easy/1221. Split a String in Balanced Strings Difficulty: easy URL: https://leetcode.com/problems/split-a-string-in-balanced-strings/ """ class Solution: def balancedStringSplit(self, s: str) -> int: balance = 0 count = 0 for i in range(len(s)): balance += 1 if s[i] == 'R' else -1 if balance == 0: count += 1 return count def test(): s = Solution() input = "RLRRLLRLRL" output = 4 assert s.balancedStringSplit(input) == output input = "RLLLLRRRLR" output = 3 assert s.balancedStringSplit(input) == output input = "LLLLRRRR" output = 1 assert s.balancedStringSplit(input) == output input = "RLRRRLLRLL" output = 2 assert s.balancedStringSplit(input) == output
# https://www.codewars.com/kata/5168bb5dfe9a00b126000018 def solution(string): return ''.join(str(x) for x in list(reversed(string))) print('123'.split()) print(solution('world')) print(solution('world') == 'dlrow')
""" 78-subsets leetcode/easy/78. Subsets Difficulty: medium URL: https://leetcode.com/problems/subsets/ """ from typing import List class Solution: def get_subsets(self, nums, result, prev=[]): if len(nums) == 0: return for index, value in enumerate(nums): print(index, value) result.append(prev + [value]) self.get_subsets(nums[index + 1:], result, prev + [value]) def subsets(self, nums: List[int]) -> List[List[int]]: result = [[]] self.get_subsets(nums, result) return result def test(): nums = [1, 2, 3] output = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] assert Solution().subsets(nums) == output nums = [0] output = [[], [0]] assert Solution().subsets(nums) == output
""" 728-self-dividing-numbers leetcode/easy/728. Self Dividing Numbers Difficulty: easy URL: https://leetcode.com/problems/self-dividing-numbers/ """ from typing import List class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: result = [] for i in range(left, right + 1): if all([(_i != 0 and i % _i == 0) for _i in map(int, str(i))]): result.append(i) return result def test(): left = 1 right = 22 output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] assert Solution().selfDividingNumbers(left, right) == output left = 47 right = 85 output = [48, 55, 66, 77] assert Solution().selfDividingNumbers(left, right) == output
""" 3sum leetcode/medium/3sum Difficulty: medium URL: https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/776/ """ from typing import List class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: result = [] nums = sorted(nums) last_index = len(nums) _set = set() for i in range(last_index - 2): left_index = i + 1 right_index = last_index - 1 while left_index < right_index: _total = nums[i] + nums[left_index] + nums[right_index] if _total == 0: _str = str([nums[i], nums[left_index], nums[right_index]]) if _str not in _set: _set.add(_str) result.append([nums[i], nums[left_index], nums[right_index]]) if _total < 0: left_index += 1 else: right_index -= 1 return result def test(): nums = [-1, 0, 1, 2, -1, -4] output = [[-1, -1, 2], [-1, 0, 1]] assert Solution().threeSum(nums) == output nums = [] output = [] assert Solution().threeSum(nums) == output nums = [0] output = [] assert Solution().threeSum(nums) == output
""" 1021-remove-outermost-parentheses leetcode/easy/1021. Remove Outermost Parentheses Difficulty: easy URL: https://leetcode.com/problems/remove-outermost-parentheses/ """ class Solution: def removeOuterParentheses(self, s: str) -> str: balance = 0 result = [] for i in range(len(s)): if s[i] == '(': if balance != 0: result.append(s[i]) balance -= 1 else: balance += 1 if balance != 0: result.append(s[i]) return ''.join(result) def test(): solution = Solution() s = "(()())(())" output = "()()()" assert solution.removeOuterParentheses(s) == output s = "(()())(())(()(()))" output = "()()()()(())" assert solution.removeOuterParentheses(s) == output s = "()()" output = "" assert solution.removeOuterParentheses(s) == output
# Reverse polish notation calculator # https://www.codewars.com/kata/52f78966747862fc9a0009ae/ from unittest import TestCase def is_number(string): try: float(string) return True except ValueError: return False def calc(expr): expressions = expr.split(" ") result = 0 if len(expressions) == 1 and is_number(expressions[0]): result = float(expressions[0]) while len(expressions) > 1: for i in range(len(expressions) - 2): if is_number(expressions[i]) \ and is_number(expressions[i + 1]) \ and not is_number(expressions[i + 2]): a = float(expressions[i]) b = float(expressions[i + 1]) operator = expressions[i + 2] if operator == '+': result = a + b elif operator == '-': result = a - b elif operator == '*': result = a * b elif operator == '/': result = a / b expressions[i] = result del expressions[i + 1] del expressions[i + 1] return result TestCase().assertEqual(calc(""), 0, "Should work with empty string") TestCase().assertEqual(calc("3"), 3, "Should parse numbers") TestCase().assertEqual(calc("3.5"), 3.5, "Should parse float numbers") TestCase().assertEqual(calc("1 3 +"), 4, "Should support addition") TestCase().assertEqual(calc("1 3 *"), 3, "Should support multiplication") TestCase().assertEqual(calc("1 3 -"), -2, "Should support subtraction") TestCase().assertEqual(calc("4 2 /"), 2, "Should support division") TestCase().assertEqual(calc("5 1 2 + 4 * + 3 -"), 14, "Should support division")
""" 1370-increasing-decreasing-string leetcode/easy/1370. Increasing Decreasing String Difficulty: easy URL: https://leetcode.com/problems/increasing-decreasing-string/ """ class Solution: def sortString(self, s: str) -> str: s = sorted(s) result = [] delete_list = [] while len(s): temp = [s.pop(0)] for item in s: print(item) if temp[-1] < item: temp.append(item) delete_list.append(item) result.extend(temp) for item in delete_list: s.remove(item) delete_list = [] if not len(s): continue temp = [s.pop(-1)] for item in s[::-1]: if temp[-1] > item: temp.append(item) delete_list.append(item) result.extend(temp) for item in delete_list: s.remove(item) delete_list = [] return ''.join(result) class Solution: def sortString(self, s: str) -> str: s = list(s) result = '' while s: for letter in sorted(set(s)): s.remove(letter) result += letter for letter in sorted(set(s), reverse=True): s.remove(letter) result += letter return result def test(): s = "aaaabbbbcccc" output = "abccbaabccba" assert Solution().sortString(s) == output s = "rat" output = "art" assert Solution().sortString(s) == output s = "leetcode" output = "cdelotee" assert Solution().sortString(s) == output s = "ggggggg" output = "ggggggg" assert Solution().sortString(s) == output s = "spo" output = "ops" assert Solution().sortString(s) == output
# WeIrD StRiNg CaSe # https://www.codewars.com/kata/52b757663a95b11b3d00062d/ from unittest import TestCase def to_weird_case(string): def to_weird_string_case(word): return "".join(list(map(lambda v: v[1].upper() if v[0] % 2 == 0 else v[1].lower(), enumerate(list(word))))) return " ".join([to_weird_string_case(word) for word in string.split(" ")]) TestCase().assertEqual(to_weird_case('This'), 'ThIs') TestCase().assertEqual(to_weird_case('is'), 'Is') TestCase().assertEqual(to_weird_case('This is a test'), 'ThIs Is A TeSt')
""" 1827-minimum-operations-to-make-the-array-increasing leetcode/easy/1827. Minimum Operations to Make the Array Increasing URL: https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/ """ from typing import List class Solution: def minOperations(self, nums: List[int]) -> int: maximum_num = nums[0] total = 0 for item in nums[1:]: diff = item - maximum_num if diff > 0: maximum_num = item else: total += abs(diff) + 1 maximum_num += 1 return total def test(): nums = [1, 1, 1] output = 3 assert Solution().minOperations(nums) == output nums = [1, 5, 2, 4, 1] output = 14 assert Solution().minOperations(nums) == output nums = [8] output = 0 assert Solution().minOperations(nums) == output
# leetcode/medium/2390. Removing Stars From a String # 2390-removing-stars-from-a-string # URL: https://leetcode.com/problems/removing-stars-from-a-string/description/?envType=study-plan-v2&id=leetcode-75 # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference class Solution: def removeStars(self, s: str) -> str: while s.find('*') != -1: index = s.index('*') s = s[:index - 1] + s[index + 1:] return s s = "leet**cod*e" print(Solution().removeStars(s)) # Output: "lecoe" s = "erase*****" print(Solution().removeStars(s)) # Output: ""
""" 704-binary-search leetcode/easy/704. Binary Search Difficulty: easy URL: https://leetcode.com/problems/binary-search/ """ from typing import List class Solution: def search(self, nums: List[int], target: int) -> int: if target not in nums: return -1 left = 0 right = len(nums) while True: middle = (left + right) // 2 if nums[middle] == target: return middle if nums[middle] < target: left = middle else: right = middle class Solution: def search(self, nums: List[int], target: int) -> int: return nums.index(target) if target in nums else -1 def test(): nums = [-1, 0, 3, 5, 9, 12] target = 9 output = 4 assert Solution().search(nums, target) == output nums = [-1, 0, 3, 5, 9, 12] target = 2 output = -1 assert Solution().search(nums, target) == output
""" 1720-decode-xored-array leetcode/easy/1720. Decode XORed Array Difficulty: easy URL: https://leetcode.com/problems/decode-xored-array/ """ from typing import List class Solution: def decode(self, encoded: List[int], first: int) -> List[int]: result = [first] for x in encoded: result.append(x ^ result[-1]) return result def test(): s = Solution() encoded = [1, 2, 3] first = 1 output = [1, 0, 2, 1] assert s.decode(encoded, first) == output encoded = [6, 2, 7, 3] first = 4 output = [4, 2, 0, 7, 4] assert s.decode(encoded, first) == output
# leetcode/medium/2113. Elements in Array After Removing and Replacing Elements # 2113-elements-in-array-after-removing-and-replacing-elements # URL: https://leetcode.com/problems/elements-in-array-after-removing-and-replacing-elements/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import List class Solution: def elementInNums(self, nums: List[int], queries: List[List[int]]) -> List[int]: result = [] for [time, index] in queries: targetTime = time % (len(nums) * 2) # print(time, index, targetTime) if targetTime < len(nums): if targetTime + index < len(nums): result.append(nums[targetTime + index]) else: result.append(-1) elif targetTime == len(nums): result.append(-1) else: maxIndex = targetTime - len(nums) if index < maxIndex: result.append(nums[index]) else: result.append(-1) return result nums = [0, 1, 2] queries = [[0, 2], [2, 0], [3, 2], [5, 0]] print(Solution().elementInNums(nums, queries)) # assert Solution().elementInNums(nums, queries) == [2, 2, -1, 0] # Output: [2,2,-1,0] nums = [2, 2, 1] queries = [[5, 1], [5, 2]] print(Solution().elementInNums(nums, queries)) # [2, -1] # 0 [2, 2, 1] # 1 [2, 1] # 2 [1] # 3 [] # 4 [2] # 5 [2, 2] # # 6 [2, 2, 1]
""" 1038-binary-search-tree-to-greater-sum-tree leetcode/medium/1038. Binary Search Tree to Greater Sum Tree Difficulty: medium URL: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ """ # 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 pre_order_traversal_for_collect_value(self, root, values): if root is None: return values.append(root.val) self.pre_order_traversal_for_collect_value(root.left, values) self.pre_order_traversal_for_collect_value(root.right, values) def pre_order_traversal_for_replace(self, root, values): if root is None: return root.val = sum(values[values.index(root.val):]) self.pre_order_traversal_for_replace(root.left, values) self.pre_order_traversal_for_replace(root.right, values) def bstToGst(self, root: TreeNode) -> TreeNode: values = [] self.pre_order_traversal_for_collect_value(root, values) values.sort() self.pre_order_traversal_for_replace(root, values) return root
""" find-the-position codewars/8kyu/Find the position! Difficulty: 8kyu URL: https://www.codewars.com/kata/5808e2006b65bff35500008f/ """ def position(alphabet): return f'Position of alphabet: {ord(alphabet) - 96}' def test_positio(): assert position('a') == 'Position of alphabet: 1' assert position('z') == 'Position of alphabet: 26' assert position('e') == 'Position of alphabet: 5'
#!/usr/bin/env python3 # -*- coding:utf-8 -*- def fibonacci1(n): assert(n>=0) a = 0 b = 1 print(a) if n > 0: print(b) i = 2 while i <= n: c = a + b print(c) a = b b = c i += 1 def fibonacci(n): memory = {0: 0, 1: 1} def loop(n): assert(n>=0) if n in memory: return memory[n] else: memory[n] = loop(n-1) + loop(n-2) return memory[n] return loop(n) print(fibonacci(0)) print('---') print(fibonacci(1)) print('---') print(fibonacci(10))
print("What is your first name?") initial = input() print("What is your surname?") surname = input() print("For how many months do you want your gym membership for?") months = int(input()) print("Hello,") print(f"{initial} {surname},") print("and welcome to your new gym membership with MathGyms Ltd!") print(f"You have chosen to stay with us for {months} months. Enjoy!")
def gcd(a, b): while b > 0: a, b = b, a % b return a def lcm(a, b): return int(a * b / gcd(a, b)) def solution(n, m): answer = [] if n < m: answer.append(gcd(n, m)) answer.append(lcm(n, m)) elif m < n: answer.append(gcd(m, n)) answer.append(lcm(m, n)) return answer print(solution(3, 12)) ''' 최소공배수 = a * b / 최대공약수 최대공약수는 유클리드 호제법으로 구한다. '''
# -*- coding: utf-8 -*- """ Created on Sun Aug 21 17:23:13 2016 @author: RITURAJ """ #observing the order class A(object): def m(self): print('m of B called') class B(A): pass class C(A): def m(self): print('m of C called') class D(C , B): pass x = D() print(x.m()) #observing method class A(): def m(self): print('m of A called') class B(): def m(self): print('m of B called') class C(): def m(self): print('m of C called') class D(C , B): def m(self): print('m of D called') x = D() print(B.m(x)) #one way to solve the diamond problem is to use super() method class A: def m(self): print("m of A called") class B(A): def m(self): print("m of B called") super().m() class C(A): def m(self): print("m of C called") super().m() class D(B,C): def m(self): print("m of D called") super().m() x = D() print(x.m()) #mro() method used to create linearization list print(D.mro())
# -*- coding: utf-8 -*- """ Created on Tue Aug 23 16:12:52 2016 @author: RITURAJ """ def the_answer(self , *args): return 42 class EssentialAnswers(type): def __init__(cls, clsname, superclasses, attributedict): cls.the_answer= the_answer class philosophi1(metaclass=EssentialAnswers): pass class philosophi2(metaclass= EssentialAnswers): pass class philosophi3(metaclass=EssentialAnswers): pass plato = philosophi1() print(plato.the_answer()) kant = philosophi2() print(kant.the_answer()) ramdev = philosophi3() print(ramdev.the_answer())
#Alunos: João Marcos Oliveira Melo, Ângelo Giordano Silveira, Leandro Moreira Souza "Faça um programa utilizando IF e que faça perguntas a cerca de uma cena de crime" "E que defina a posição do usuário diante do crime!!!" ct_crime = 0 print("\nPrazer meu nome é Jack, e eu sou o detetive dessa cidade!!!") print("Vamos dar uma olhada na sua situação") print("Você foi encontrado ao lado do corpo de Melanine Beatrice") print("Você diz que é inocente mas mesmo asssim preciso te fazer algumas perguntas!") print("Responda as perguntas com {sim} ou {não}") print("Ao final lhe direi sua situação!!!") while True: validar = str(input("\nVocê está pronto para começar? ")) if validar == "sim": print("Então vamos começar:") break else: validar2 = str(input("\nVocê quer revisar a história? ")) if validar2=="sim": print("\nPrazer meu nome é Jack, e eu sou o detetive dessa cidade!!!") print("Vamos dar uma olhada na sua situação") print("Você foi encontrado ao lado do corpo de Melanine Beatrice") print("Você diz que é inocente mas mesmo asssim preciso te fazer algumas perguntas!") print("Responda as perguntas com {sim} ou {não}") print("Ao final lhe direi sua situação!!!") else: print("\nTudo bem quando você estiver pronto nós começamos!!!") quest1=str(input("\nTelefonou para a vítima? ")) if quest1=="sim": ct_crime+=1 quest2=str(input("Esteve no local do crime? ")) if quest2=="sim": ct_crime+=1 quest3=str(input("Mora perto da vítima? ")) if quest3=="sim": ct_crime+=1 quest4=str(input("Devia para a vítima? ")) if quest4=="sim": ct_crime+=1 quest5=str(input("Já trabalhou com a vítima? ")) if quest5=="sim": ct_crime+=1 if ct_crime<2: print("\nVocê é considerado inocente!!!") elif ct_crime==2: print("\nVocê é considerado suspeito!!!") elif ct_crime>=3 and ct_crime<=4: print("\nVocê é considerado Cúmplice!!!") else: print("\nVocê é o Assassino!!!") print("\nFim do programa!!!")
String= input("enter string= ") print("Total length of string with spaces :",len(String)) striglength=len(String) if striglength < 5: print("String is short") elif striglength > 30: print("String is too long") else: print("String is optimum")
import os print(os.getcwd()) files=[] dirs=[] for file in os.listdir(): if os.path.isfile(file): files.append(file) if os.path.isdir(file): dirs.append(file) print("files") print("------") for file in files: print(file) print ("dirs") print("-----") for file in dirs: print(file)
Stringinput= input("Enter the string: ") value=list(Stringinput) print(Stringinput) print(value) digit=0 alpha=0 for i in value: if i.isdigit(): digit+=1 print("Stringinput is digit",i) if i.isalpha(): alpha+=1 print("String is alphabet",i) print (alpha, digit) ''' if Stringinput[i].isalpha(): print("is Alphabet", i) #i+=1'''
import sphere, cylinder, cone, cube, triangle, trapezoid, cuboid, equilateralTriangle #setting user selection in main program def userSelection(selection): return selection #main output loop def main(): while True: #Main menu output print("Welcome to the my Geometry Program") print("1. Sphere") print("2. Cylinder") print("3. Cone") print("4. Triangle") print("5. Cube") print("6. Trapezoid") print("7. Cuboid") print("8. Equilateral Triangle") print("0. Quit") #Get user selection from menu selection = int(input("Please enter your selection: ")) #call appropriate method if selection == 0: break if selection == 1: sphere.prompt() break if selection == 2: cylinder.prompt() break if selection == 3: cone.prompt() break if selection == 4: cube.prompt() break if selection == 5: triangle.prompt() break if selection == 6: trapezoid.prompt() break if selection == 7: cuboid.prompt() break if selection == 8: equilateralTriangle.prompt() break if __name__ == '__main__': main()
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right # solution def serialize(root): if root is None: return '' return root.val + '(' + serialize(root.left) + ')(' + serialize(root.right) + ')' def deserialize(s): if(s == ''): return None i = 0 while(s[i] != '('): i += 1 depth = 1 j = i+1 while(depth != 0): depth += (s[j] == '(') - (s[j] == ')') j += 1 # at this point s[i] = s[j] = '(' both selected at the least depth return Node(s[0:i], deserialize(s[i+1:j-1]), deserialize(s[j+1: -1])) # testing node = Node('root', Node('left', Node('left.left')), Node('right')) print(serialize(node)) print(serialize(deserialize(serialize(node)))) # outputs # root(left(left.left()())())(right()()) assert deserialize(serialize(node)).left.left.val == 'left.left'
"""Automates airconditioning control. Monitors climate inside and out, controlling airconditioning units in the house according to user defined temperature thresholds. The system can be disabled by its users, in which case suggestions are made (via notifications) instead based on the same thresholds using forecasted and current temperatures. User defined variables are configued in climate.yaml """ from __future__ import annotations from typing import Type from meteocalc import Temp, heat_index import app class Climate(app.App): """Control aircon based on user input and automated rules.""" def __init__(self, *args, **kwargs): """Extend with attribute definitions.""" super().__init__(*args, **kwargs) self.__suggested = False self.__temperature_monitor = None self.__aircons = None self.__door_open_listener = None self.__climate_control_history = {"overridden": False, "before_away": None} def initialize(self): """Initialise TemperatureMonitor, Aircon units, and event listening. Appdaemon defined init function called once ready after __init__. """ super().initialize() self.__climate_control = ( self.entities.input_boolean.climate_control.state == "on" ) self.__climate_control_history["before_away"] = self.climate_control self.__aircon = self.entities.input_boolean.aircon.state == "on" self.__aircons = { aircon: Aircon(f"climate.{aircon}", self) for aircon in ["bedroom", "living_room", "dining_room"] } self.__temperature_monitor = TemperatureMonitor(self) self.__temperature_monitor.configure_sensors() self.set_door_check_delay( float(self.entities.input_number.aircon_door_check_delay.state) ) self.listen_state( self.__handle_door_change, "binary_sensor.kitchen_door", new="off", immediate=True, ) @property def climate_control(self) -> bool: """Get climate control setting that has been synced to Home Assistant.""" return self.__climate_control @climate_control.setter def climate_control(self, state: bool): """Enable/disable climate control and reflect state in UI.""" self.log(f"{'En' if state else 'Dis'}abling climate control") self.__climate_control = state if state: self.handle_temperatures() else: self.__allow_suggestion() if ( self.__climate_control_history["overridden"] and ( ( self.datetime(True) - self.convert_utc( self.entities.input_boolean.climate_control.last_changed ) ).total_seconds() ) > 10 ): self.__climate_control_history["overridden"] = False self.call_service( f"input_boolean/turn_{'on' if state else 'off'}", entity_id="input_boolean.climate_control", ) @property def aircon(self) -> bool: """Get aircon setting that has been synced to Home Assistant.""" return self.__aircon @aircon.setter def aircon(self, state: bool): """Turn on/off aircon and sync state to Home Assistant UI.""" if self.aircon == state: self.log(f"Ensuring aircon is {'on' if state else 'off'}") else: self.log(f"Turning aircon {'on' if state else 'off'}") if state: self.__disable_climate_control_if_would_trigger_off() self.__turn_aircon_on() else: self.__disable_climate_control_if_would_trigger_on() self.__turn_aircon_off() self.__aircon = state self.call_service( f"input_boolean/turn_{'on' if state else 'off'}", entity_id="input_boolean.aircon", ) if self.__climate_control_history["overridden"]: self.log("Re-enabling climate control") self.climate_control = True def get_setting(self, setting_name: str) -> float: """Get temperature target and trigger settings, accounting for Sleep scene.""" if self.control.scene == "Sleep" or self.control.is_bed_time(): setting_name = f"sleep_{setting_name}" return float(self.get_state(f"input_number.{setting_name}")) def reset(self): """Reset climate control using latest settings.""" self.__temperature_monitor.configure_sensors() self.aircon = self.aircon self.handle_temperatures() def set_door_check_delay(self, minutes: float): """Configure listener for door opening, overwriting existing listener.""" if self.__door_open_listener is not None: self.cancel_listen_state(self.__door_open_listener) self.__door_open_listener = self.listen_state( self.__handle_door_change, "binary_sensor.kitchen_door", new="on", duration=minutes * 60, immediate=True, ) def transition_between_scenes(self, new_scene: str, old_scene: str): """Adjust aircon & temperature triggers, plus suggest climate control if appropriate.""" self.__temperature_monitor.configure_sensors() if "Away" in new_scene and "Away" not in old_scene: if not self.control.apps["presence"].pets_home_alone: self.__climate_control_history["before_away"] = self.climate_control self.climate_control = False self.aircon = False elif "Away" not in new_scene and "Away" in old_scene: self.climate_control = self.__climate_control_history["before_away"] if self.climate_control or not self.__suggested: self.handle_temperatures() if self.aircon: self.aircon = True elif self.climate_control is False and any( [ new_scene == "Day" and old_scene in ["Sleep", "Morning"], new_scene == "Night" and old_scene == "Day", "Away" not in new_scene and "Away" in old_scene, self.control.apps["presence"].pets_home_alone, ] ): self.__suggest_if_trigger_forecast() def handle_pets_home_alone(self): """Turn aircon on if temperatures require or enable climate control for the pets.""" if self.climate_control: if self.aircon is False and self.__temperature_monitor.is_too_hot_or_cold(): self.notify( f"It is {self.__temperature_monitor.inside_temperature}º inside at home, " "turning aircon on for the pets", title="Climate Control", ) self.aircon = True else: self.climate_control = True self.notify( "Pets alone at home, climate control is now enabled", title="Climate Control", ) def handle_temperatures(self, *args): """Control aircon or suggest based on changes in inside temperature.""" del args # args required for listen_state callback if self.aircon is False: if self.__temperature_monitor.is_too_hot_or_cold(): self.__handle_too_hot_or_cold() elif self.__temperature_monitor.is_within_target_temperatures(): message = ( f"A desirable inside temperature of " f"{self.__temperature_monitor.inside_temperature}º has been reached," ) if self.climate_control is True: self.aircon = False self.notify( f"{message} turning aircon off", title="Climate Control", targets="anyone_home" if self.control.apps["presence"].anyone_home() else "all", ) else: self.__suggest(f"{message} consider enabling climate control") def __handle_too_hot_or_cold(self): """Handle each case (house open, outside nicer, climate control status).""" if self.control.apps["presence"].pets_home_alone: self.handle_pets_home_alone() return if self.__temperature_monitor.is_outside_temperature_nicer(): message_beginning = ( f"Outside ({self.__temperature_monitor.outside_temperature}º) " "is a more pleasant temperature than inside " f"({self.__temperature_monitor.inside_temperature})º), consider" ) if self.climate_control: if self.get_state("binary_sensor.kitchen_door") == "off": self.aircon = True self.__suggest(f"{message_beginning} opening up the house") else: if self.get_state("binary_sensor.kitchen_door") == "off": message_beginning += " opening up the house and/or" self.__suggest(f"{message_beginning} enabling climate control") else: message_beginning = ( f"It's {self.__temperature_monitor.inside_temperature}º " "inside right now, consider" ) if self.climate_control: if self.get_state("binary_sensor.kitchen_door") == "off": self.aircon = True else: self.__suggest( f"{message_beginning}" " closing up the house so airconditioning can turn on" ) else: if self.get_state("binary_sensor.kitchen_door") == "on": message_beginning += " closing up the house and" self.__suggest(f"{message_beginning} enabling climate control") def __suggest_if_trigger_forecast(self): """Suggest user enables control if extreme's forecast.""" self.__allow_suggestion() forecast = self.__temperature_monitor.get_forecast_if_will_trigger() if forecast is not None: self.__suggest( f"It's forecast to reach {forecast}º, consider enabling climate control" ) def __turn_aircon_on(self): """Turn aircon on, calculating mode, handling Sleep/Morning scenes and bed time.""" if self.__temperature_monitor.is_below_target_temperature(): mode = "heat" elif self.__temperature_monitor.is_above_target_temperature(): mode = "cool" else: mode = self.__temperature_monitor.closer_to_heat_or_cool() self.log( f"The temperature inside ({self.__temperature_monitor.inside_temperature} " f"degrees) is {'above' if mode == 'cool' else 'below'} the target (" f"{self.get_state(f'input_number.{mode}ing_target_temperature')} degrees)" ) if ( self.control.scene == "Sleep" or self.control.is_bed_time() or ( self.control.apps["presence"].pets_home_alone and not self.control.apps["presence"].anyone_home() ) ): self.__aircons["bedroom"].turn_on( mode, "high" if self.control.pre_sleep_scene or self.control.scene != "Sleep" else "low", ) for room in ["living_room", "dining_room"]: self.__aircons[room].turn_off() elif self.control.scene == "Morning": for aircon in self.__aircons.keys(): self.__aircons[aircon].turn_on( mode, "low" if aircon == "bedroom" else "auto" ) else: for aircon in self.__aircons.values(): aircon.turn_on(mode, "auto") self.log(f"Aircon is set to '{mode}' mode") self.__allow_suggestion() def __turn_aircon_off(self): """Turn all aircon units off and allow suggestions again.""" for aircon in self.__aircons.values(): aircon.turn_off() self.log("Aircon is off") self.__allow_suggestion() def __disable_climate_control_if_would_trigger_on(self): """Disables climate control only if it would immediately trigger aircon on.""" if self.climate_control and self.__temperature_monitor.is_too_hot_or_cold(): self.climate_control = False self.__climate_control_history["overridden"] = True self.notify( "The current temperature (" f"{self.__temperature_monitor.inside_temperature}º) will immediately " "trigger aircon on again - climate control is now disabled to prevent this", title="Climate Control", targets="anyone_home" if self.control.apps["presence"].anyone_home() else "all", ) def __disable_climate_control_if_would_trigger_off(self): """Disables climate control only if it would immediately trigger aircon off.""" if ( self.climate_control and self.__temperature_monitor.is_within_target_temperatures() ): self.climate_control = False self.__climate_control_history["overridden"] = True self.notify( "Inside is already within the desired temperature range," " climate control is now disabled" " (you'll need to manually turn aircon off)", title="Climate Control", targets="anyone_home" if self.control.apps["presence"].anyone_home() else "all", ) def __suggest(self, message: str): """Make a suggestion to the users, but only if one has not already been sent.""" if not self.__suggested: self.__suggested = True self.notify( message, title="Climate Control", targets="anyone_home" if self.control.apps["presence"].anyone_home() else "all", ) def __allow_suggestion(self): """Allow suggestions to be made again. Use after user events & scene changes.""" if self.__suggested: self.__suggested = False def __handle_door_change( self, entity: str, attribute: str, old: str, new: str, kwargs: dict ): # pylint: disable=too-many-arguments """If the kitchen door status changes, check if aircon needs to change.""" del entity, attribute, old, kwargs self.log(f"Kitchen door is now {'open' if new == 'on' else 'closed'}") if new == "off": self.handle_temperatures() elif self.aircon and self.get_state("climate.living_room") != "off": self.aircon = False self.notify( "The kitchen door is open, turning aircon off", title="Climate Control", targets="anyone_home", ) class Sensor: """Capture temperature and humidity data from generic sensor entities.""" @staticmethod def detect_type_and_create(sensor_id: str, controller: Climate) -> Type["Sensor"]: """Detect the sensor type and create an object with the relevant subclass.""" if "climate" in sensor_id: sensor_type = ClimateSensor elif "multisensor" in sensor_id: sensor_type = MultiSensor elif "outside" in sensor_id: sensor_type = WeatherSensor else: sensor_type = Sensor return sensor_type(sensor_id, controller) def __init__(self, sensor_id: str, monitor: TemperatureMonitor): """Initialise sensor with appropriate variables and a monitor to callback to.""" self.sensor_id = sensor_id self.monitor = monitor if "bedroom" in self.sensor_id: self.location = "bedroom" elif "outside" in self.sensor_id: self.location = "outside" else: self.location = "inside" self.listeners = {"temperature": None, "humidity": None} def is_enabled(self) -> bool: """Check if the sensor is enabled - matches temperature_listener usage.""" return self.listeners["temperature"] is not None def disable(self): """Disable the sensor by cancelling its listeners.""" for name, listener in self.listeners.items(): if listener is not None: self.monitor.controller.cancel_listen_state(listener) self.listeners[name] = None def validate_measure(self, value: str) -> float: """Return numerical value of measure, warning if invalid.""" try: return float(value) except TypeError: self.monitor.controller.log( f"{self.sensor_id} could not get measure", level="WARNING" ) return None class ClimateSensor(Sensor): """Capture temperature and humidity data from climate.x entities.""" def get_measure(self, measure: str) -> float: """Get latest value from the sensor in Home Assistant.""" return self.validate_measure( self.monitor.controller.get_state( self.sensor_id, attribute=f"current_{measure}" ) ) def enable(self): """Initialise sensor values and listen for further updates.""" for name, listener in self.listeners.items(): if listener is None: self.listeners[name] = self.monitor.controller.listen_state( self.monitor.handle_sensor_change, self.sensor_id, attribute=f"current_{name}", measure=name, ) class MultiSensor(Sensor): """Capture temperature and humidity data from multisensor entities.""" def get_measure(self, measure: str) -> float: """Get latest value from the sensor in Home Assistant.""" return self.validate_measure( self.monitor.controller.get_state(f"{self.sensor_id}_{measure}") ) def enable(self): """Initialise sensor values and listen for further updates.""" for name, listener in self.listeners.items(): if listener is None: self.listeners[name] = self.monitor.controller.listen_state( self.monitor.handle_sensor_change, f"{self.sensor_id}_{name}", measure=name, ) class WeatherSensor(Sensor): """Capture temperature data from a WeatherFlow Tempest weather station.""" def __init__(self, sensor_id: str, monitor: TemperatureMonitor): """Keep only the temperature listener as methods change monitor's attribute.""" super().__init__(sensor_id, monitor) del self.listeners["humidity"] def enable(self): """Listen for changes in temperature.""" if self.listeners["temperature"] is None: self.listeners["temperature"] = self.monitor.controller.listen_state( self.monitor.controller.handle_temperatures, self.sensor_id ) class TemperatureMonitor: """Monitor various sensors to provide temperatures in & out, and check triggers.""" def __init__(self, controller: Climate): """Initialise with Climate controller and create sensor objects.""" self.controller = controller self.__inside_temperature = ( self.controller.entities.climate.bedroom.attributes.current_temperature ) self.__sensors = { sensor_id: Sensor.detect_type_and_create(sensor_id, self) for sensor_id in [ "climate.bedroom", "climate.living_room", "climate.dining_room", "sensor.kitchen_multisensor", "sensor.office_multisensor", "sensor.bedroom_multisensor", "sensor.outside_temperature_feels_like", ] } self.__last_inside_temperature = None @property def inside_temperature(self) -> float: """Get the calculated inside temperature that has been synced to Home Assistant.""" return self.__inside_temperature @inside_temperature.setter def inside_temperature(self, temperature: float): """Sync the calculated inside temperature to Home Assistant.""" self.__inside_temperature = temperature self.controller.set_state( "sensor.apparent_inside_temperature", state=temperature ) @property def outside_temperature(self) -> float: """Get the calculated outside temperature from Home Assistant.""" return float( self.controller.entities.sensor.outside_temperature_feels_like.state ) def configure_sensors(self): """Get values from appropriate sensors and calculate inside temperature.""" bed = ( self.controller.control.scene == "Sleep" or self.controller.control.is_bed_time() ) for sensor in self.__sensors.values(): if bed and sensor.location == "inside": sensor.disable() else: sensor.enable() self.calculate_inside_temperature() def handle_sensor_change( self, entity: str, attribute: str, old: float, new: float, kwargs: dict ): # pylint: disable=too-many-arguments """Calculate inside temperature then get controller to handle if changed.""" del entity, attribute, old, kwargs if new is not None: self.calculate_inside_temperature() def calculate_inside_temperature(self): """Use stored sensor values to calculate the 'feels like' temperature inside.""" self.__last_inside_temperature = self.inside_temperature temperatures = [] humidities = [] for sensor in self.__sensors.values(): if sensor.is_enabled() and sensor.location != "outside": temperature = sensor.get_measure("temperature") if temperature is not None: temperatures.append(temperature) humidity = sensor.get_measure("humidity") if humidity is not None: humidities.append(humidity) self.inside_temperature = round( heat_index( temperature=Temp( sum(temperatures) / len(temperatures), "c", ), humidity=sum(humidities) / len(humidities), ).c, 1, ) if self.__last_inside_temperature != self.inside_temperature: self.controller.log( f"Inside temperature calculated as {self.inside_temperature} degrees", level="DEBUG", ) self.controller.handle_temperatures() def is_within_target_temperatures(self) -> bool: """Check if temperature is not above or below target temperatures.""" return not ( self.is_above_target_temperature() or self.is_below_target_temperature() ) def is_above_target_temperature(self) -> bool: """Check if temperature is above the target temperature, with a buffer.""" return ( self.inside_temperature > float(self.controller.get_setting("cooling_target_temperature")) - self.controller.args["target_trigger_buffer"] ) def is_below_target_temperature(self) -> bool: """Check if temperature is below the target temperature, with a buffer.""" return ( self.inside_temperature < self.controller.get_setting("heating_target_temperature") + self.controller.args["target_trigger_buffer"] ) def is_outside_temperature_nicer(self) -> bool: """Check if outside is a nicer temperature than inside.""" mode = self.controller.entities.climate.bedroom.state hotter_outside = ( self.inside_temperature < self.outside_temperature - self.controller.args["inside_outside_trigger"] ) colder_outside = ( self.inside_temperature > self.outside_temperature + self.controller.args["inside_outside_trigger"] ) too_hot_or_cold_outside = ( not self.controller.get_setting("low_temperature_trigger") <= self.outside_temperature <= self.controller.get_setting("high_temperature_trigger") ) vs_str = f"({self.outside_temperature} vs {self.inside_temperature} degrees)" if any( [ mode == "heat" and hotter_outside, mode == "cool" and colder_outside, mode == "off" and (self.is_too_hot_or_cold() and not too_hot_or_cold_outside), ] ): self.controller.log( f"Outside temperature is nicer than inside {vs_str}", level="DEBUG" ) return True self.controller.log( f"Outside temperature is not better than inside {vs_str}", level="DEBUG" ) return False def is_too_hot_or_cold(self) -> bool: """Check if temperature inside is above or below the max/min triggers.""" if ( self.controller.get_setting("low_temperature_trigger") < self.inside_temperature < self.controller.get_setting("high_temperature_trigger") ): return False self.controller.log( f"It's too hot or cold inside ({self.inside_temperature} degrees)", level="DEBUG", ) return True def closer_to_heat_or_cool(self) -> str: """Return if temperature inside is closer to needing heating or cooling.""" if ( self.inside_temperature > ( self.controller.get_setting("cooling_target_temperature") + self.controller.get_setting("heating_target_temperature") ) / 2 ): return "cool" return "heat" def get_forecast_if_will_trigger(self) -> float: """Return the forecasted temperature if it exceeds thresholds.""" forecasts = [ float( self.controller.get_state( f"sensor.sensor.outside_apparent_temperature_{hour}h_forecast" ) ) for hour in ["2", "4", "6", "8"] ] max_forecast = max(forecasts) if max_forecast >= self.controller.get_setting("high_temperature_trigger"): return max_forecast min_forecast = min(forecasts) if min_forecast <= self.controller.get_setting("low_temperature_trigger"): return min_forecast return None class Aircon: """Control a specific aircon unit.""" def __init__(self, aircon_id: str, controller: Climate): """Initialise with an aircon's entity_id and the Climate controller.""" self.aircon_id = aircon_id self.controller = controller def turn_on(self, mode: str, fan: str = None): """Turn on the aircon unit with the specified mode and configured temperature.""" if mode == "cool": target_temperature = self.controller.get_setting( "cooling_target_temperature" ) elif mode == "heat": target_temperature = self.controller.get_setting( "heating_target_temperature" ) if self.controller.get_state(self.aircon_id) != mode: self.controller.call_service( "climate/set_hvac_mode", entity_id=self.aircon_id, hvac_mode=mode ) if ( self.controller.get_state(self.aircon_id, attribute="temperature") != target_temperature ): self.controller.call_service( "climate/set_temperature", entity_id=self.aircon_id, temperature=target_temperature, ) if fan: self.set_fan_mode(fan) def turn_off(self): """Turn off the aircon unit if it's on.""" if self.controller.get_state(self.aircon_id) != "off": self.controller.call_service("climate/turn_off", entity_id=self.aircon_id) def set_fan_mode(self, fan_mode: str): """Set the fan mode to the specified level (main options: 'low', 'auto').""" if self.controller.get_state(self.aircon_id, attribute="fan_mode") != fan_mode: self.controller.call_service( "climate/set_fan_mode", entity_id=self.aircon_id, fan_mode=fan_mode )
# PROG1700 - Jin """ Name : Myeongjin Kwon(Jin)\ ID...: W0417939 """ import math def main(): #input ask = input("Please enter your original bill amout: ") #process bill = int(85) tax = float(ask) * float(0.15) tip = float(ask) * float(0.20) total = float(ask) + float(tax) + float(tip) total1 = round(total, 2) #output print("Your original bill amount is: " + str(ask)) print("Your tip is: " + str(tip)) print("Your tax is: " + str(tax)) print("Your total is: " + str(total1)) if __name__ == "__main__": main()
import numpy from matplotlib import pyplot a=numpy.zeros([2,3]) print(a) b=a b[0,1]=1.5 b[1,0]=2 print(a) print(b) pyplot.imshow(a,interpolation="nearest")
from screen import Screen import curses from screens.create import CreateScreen class MenuScreen(Screen): """ Menu screen """ selection = 0 options = ["Create a new game", "Join an existing game"] def _draw_option(self, option_number, style): self.window.addstr( 5 + option_number, 4, "{:2} - {}".format(option_number + 1, self.options[option_number]), style, ) def on_enter(self): self.hilite_color = curses.color_pair(1) self.normal_color = curses.A_NORMAL self.window.keypad(1) def on_draw(self): self.window.addstr(1, 2, "Connected to 127.0.0.1!") option_count = len(self.options) self.window.border(0) for option in range(option_count): if self.selection == option: self._draw_option(option, self.hilite_color) else: self._draw_option(option, self.normal_color) def on_exit(self): pass def on_event(self, event): input_key = event down_keys = [curses.KEY_DOWN, ord("j")] up_keys = [curses.KEY_UP, ord("k")] option_count = len(self.options) - 1 ENTER_KEYS = [curses.KEY_ENTER, ord("\n"), 10, 13] if input_key in ENTER_KEYS: if self.selection == 0: self.manager.push(CreateScreen()) else: raise "Not yet implemented" if input_key in down_keys: if self.selection < option_count: self.selection += 1 else: self.selection = 0 if input_key in up_keys: if self.selection > 0: self.selection -= 1 else: self.selection = option_count self.on_draw() # print(f"event {event}")
import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename window = tk.Tk() window.title("AStext editor") window.iconphoto(False, tk.PhotoImage(file='media/icon.png')) window.geometry("1080x720") textbox = tk.Text(width = 100,height = 44.5,font = 30) def open_file(): """Open a file for editing.""" filepath = askopenfilename( filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")] ) if not filepath: return textbox.delete("1.0", tk.END) with open(filepath, "r") as input_file: text = input_file.read() textbox.insert(tk.END, text) window.title(f"AStext editor - {filepath}") def save_file(): """Save the current file as a new file.""" filepath = asksaveasfilename( defaultextension="txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")], ) if not filepath: return with open(filepath, "w") as output_file: text = textbox.get(1.0, tk.END) output_file.write(text) window.title(f"AStext editor - {filepath}") buttons = tk.Frame(window, relief=tk.RAISED, bd=2) btn_open = tk.Button(buttons, text="Open", command=open_file) btn_save = tk.Button(buttons, text="Save As...", command=save_file) btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5) btn_save.grid(row=1, column=0, sticky="ew", padx=5) buttons.grid(row=0, column=0, sticky="ns") textbox.grid(row=0, column=1, sticky="nsew") window.mainloop
import matplotlib.pyplot as plt class point: def __init__(self, x, y, label, weight): self.x = x self.y = y self.label = label self.weight = weight def plot(): x = [0, 1, -2, -1, 9, -7] y = [8, 4, 1, 13, 11, -1] x2 = [3, 12, -3, 5] y2 = [7, 7, 12, 9] plt.plot(x, y, 'o') plt.plot(x2, y2, 'x') plt.show() data = [] data.append(point(0, 8, False, 0.0625)) data.append(point(1, 4, False, 0.0625)) data.append(point(3, 7, True, 0.0625)) data.append(point(-2, 1, False, 0.0625)) data.append(point(-1, 13, False, 0.0625)) data.append(point(9, 11, False, 0.25)) data.append(point(12, 7, True, 0.0625)) data.append(point(-7, -1, False, 0.0625)) data.append(point(-3, 12, True, 0.25)) data.append(point(5, 9, True, 0.0625)) error = {} for i in range(-8, 14): e = 0 for j in range(10): if data[j].x > i and data[j].label is not True: e += data[j].weight elif data[j].x <= i and data[j].label is not False: e += data[j].weight error[i] = e print(error) plot()
# Take any class class Class(): def __init__(self, number): self.name = "Johnathan" self.number = str(number) def sayname(self): print("This is " + self.name + " #" + self.number) # i = 1 # # All that matters is that there are as many items in "numbers" as classes you want to make # numbers = [0, 1, 2, 3, 4] # classes = [] # # for number in numbers: # #reassigns items in list as classes # numbers[number] = Class(i) # classes.append(numbers[number]) # i += 1 # # # Lists all classes' names, to make sure it works # for thing in classes: # thing.sayname() # Scalable up to maybe 30 (you have to type the numbers in the list yourself, to save on calculations) # className = Class you want to make an instance of (e.g. Class()) # howMany = How many instances you want to make # Scalable pu to maybe 30 (you have to type in the numbers in listofClasses yourself, to save on calc) # className = name of class you want to make instance of, WIHTOUT parentheses # i = index, made specificaly for test function. You can remove it # # def createClasses(className, i): # global listofClasses # listofClasses = [0, 1, 2, 3, 4, 5, 6] # # for item in listofClasses: # #reassigns items in list as classes # listofClasses[item] = className(i) # i+=1 # # # # Calling function, Making every function say name # createClasses(Class, 0) # # for item in listofClasses: # item.sayname() # # # Function, infinitely scalable (until hardware breaks) # # howMany = how many instances you want to make # def createManyClasses(className, howMany, i): # global listOfManyClasses # listOfManyClasses = [] # index = 0 # while index < howMany: # listOfManyClasses.append(index) # index += 1 # for item in listOfManyClasses: # listOfManyClasses[item] = className(i) # i += 1 # # createManyClasses(Class, 5, 0) # for things in listOfManyClasses: # things.sayname() list = [] i = 0 for item in [0, 1, 2, 3, 4, 5]: item = Class(i) list.append(item) i+=1 for thing in list: thing.sayname()
#Rümeysa Coşkun #Python basit bir syntax örneği x=5 y=6 if x > y : print("X bigger than y") if y > x: print("Y bigger than X") if y==x: print ("X equal to Y")
rows=int(input('Enter the number of rows')) def show_stars(rows): for i in range(0,rows+1): for j in range(i): print('*',end='') print() show_stars(rows)
speed=int(input('Enter Speed')) def checker(speed): if(speed<70): print('OK') else: newspeed=int(speed-70) demerit=newspeed/5 return demerit demerit = checker(speed) print('Points:'+str(demerit)) if(demerit>=12): print('Licence Suspended')
num=list(map(int,input("enter an array ").split())) num.sort() for i in range(len(num)): if (num[i+1]-num[i]!=1): x=num[i+1]-num[i] z=num[i] for y in range(x-1): z+=1 print("missing number is " + str(z))
import random game = ['scissors','rock','paper'] win_cases = {'rock':'scissors','paper':'rock','scissors':'paper'} while True: user_input = input('enter your choice :') if user_input =="exit": print('Bye!') break elif user_input not in game: print("Invalid input") continue com_choice = random.choice(game) if win_cases[user_input] == com_choice: print('Well done. The computer chose {} and failed'.format(com_choice)) elif win_cases[com_choice] == user_input: print('Sorry, but the computer chose {}'.format(com_choice)) else: print('There is a draw ({})',format(user_input))
def getsum(limit): x=0 for i in range(limit+1): if i%3==0 or i%5==0: x=x+i return x sum=getsum(10) print(sum)
import pandas as pd import numpy as np """ 1. user defined function으로 구현 # pandas 내부에서는 Dtype이 object로 되어 있어서 record.str 같은 방식으로 string 형식으로 변환 # pandas split함수 -> :를 기준으로 2번째 :까지 나눔, expand가 true이면 별개의 column false이면 1개의 column # pandas astype -> dataframe을 특정한 data type으로 변경 def to_seconds(record): hms = record.str.split(':', n=2, expand =True) return hms[0].astype(int) * 3600 + hms[1].astype(int) * 60 + hms[2].astype(int) marathon_2017 = pd.read_csv("marathon_results_2017.csv") marathon_2017_clean = marathon_2017.drop(['Unnamed: 0','Bib','Unnamed: 9'], axis=1) marathon_2017_clean['Senior'] = marathon_2017_clean.Age > 60 marathon_2017_clean['Year'] = '2017' marathon_2017_clean['Official Time Sec'] = to_seconds(marathon_2017_clean['Official Time']) print(marathon_2017_clean.head()) """ marathon_2017 = pd.read_csv("../data/marathon_results_2017.csv") marathon_2017_clean = marathon_2017.drop(['Unnamed: 0','Bib','Unnamed: 9'], axis=1) marathon_2017_clean['Senior'] = marathon_2017_clean.Age > 60 marathon_2017_clean['Year'] = '2017' # timedelta 형으로 변환 marathon_2017_clean['Official Time Sec'] = pd.to_timedelta(marathon_2017_clean['Official Time']) # 초단위 형태로 변환, numpy를 이용해서 int64로 변환 marathon_2017_clean['Official Time New'] = marathon_2017_clean['Official Time Sec'].astype('m8[s]').astype(np.int64) print(marathon_2017_clean.info()) print(marathon_2017_clean.head())
players = [ { 'name': 'Derrick Henry', 'rushing_yds': 1540, 'rushing_att': 303 }, { 'name': 'Aaron Jones', 'rushing_yds': 1084, 'rushing_att': 236, }, { 'name': 'Christian McCaffrey', 'rushing_yds': 1387, 'rushing_att': 287 } ] max_rushing_yds = 0 max_rushing_yds_player = '' for player in players: if player['rushing_yds'] > max_rushing_yds: max_rushing_yds = player['rushing_yds'] max_rushing_yds_player = player['name'] print(max_rushing_yds_player, 'had the most rushing yds:', max_rushing_yds, 'yds') """ Alternate solution. Using the Python list method append """
#Aarian Dhanani print("1 2 3 4 5 6 7 8 9") print("1\n" + "2\n" + "3\n" + "4\n") print("1\n") print("2 2\n") print("3 3 3\n") for x in range(9): print(x * 2)
#Aarian Dhanani a = 7 b = 13 c = 14 d = 13 if a % 2 == 0: print(b+c) elif b % 2 == 0: print(c-d) else: print(d*c/a)
#Aarian Dhanani #Functions def testing_Functions(number): for x in range(number): for y in range(1,(number + 1) - x): print(((number + 1) - x) - y, end = " ") print() print() def running_Loops(): for x in range(1, 10): for z in range(9 - x): print(" ", end = "") for y in range(x): print(x, end = "") print(" ", end = "") for y in range(x): print(x, end = "") print("") def loops_rows_col(row, col): for rows in range(row): for cols in range(col): print("*", end = "") print() number = 10 for x in range(3): testing_Functions(number) running_Loops() loops_rows_col(5, 10)
# -*- coding: utf-8 -*- """ Display Yahoo! Weather forecast as icons. Based on Yahoo! Weather. forecast, thanks guys ! http://developer.yahoo.com/weather/ Find your city code using: http://answers.yahoo.com/question/index?qid=20091216132708AAf7o0g Configuration parameters: - cache_timeout : how often to check for new forecasts - city_code : city code to use - forecast_days : how many forecast days you want shown - request_timeout : check timeout The city_code in this example is for Paris, France => FRXX0076 """ from time import time import requests class Py3status: # available configuration parameters cache_timeout = 1800 city_code = 'FRXX0076' forecast_days = 1 request_timeout = 10 def _get_temp(self): """ Ask Yahoo! Weather. for a forecast """ q = requests.get( 'http://query.yahooapis.com/v1/public/yql?q=' + 'select item from weather.forecast ' + 'where location="%s"&format=json' % self.city_code, timeout=self.request_timeout ) r = q.json() status = q.status_code forecasts = [] if status == 200: tempature = r['query']['results']['channel']['item']['condition']['temp'] else: raise Exception('got status {}'.format(status)) # return current today + forecast_days days forecast return "it's "+tempature+"f out!" def outside_tempature(self, i3s_output_list, i3s_config): """ This method gets executed by py3status """ response = { 'cached_until': time() + self.cache_timeout, 'color':'#00ebff', 'full_text': '' } tempature = self._get_temp() response['full_text'] += '{} '.format(tempature) response['full_text'] = response['full_text'].strip() return response if __name__ == "__main__": """ Test this module by calling it directly. """ from time import sleep x = Py3status() config = { 'color_good': '#00FF00', 'color_bad': '#FF0000', } while True: print(x.outside_tempature([], config)) sleep(1)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Euler Project: Problem 1 Problem 1: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def main(): # initialize answer ans = 0 # loop over values for i in range(1, 1000): # if divisible by 3 or 5, add it to answer if i%3 == 0 or i%5 == 0: ans = ans + i # if not, continue to next number else: continue # print the result print(ans) # run the program if __name__ == '__main__': main()
#volume of a sphere is 4/3πr3. #In this section I define all variables #that I will use to apply to my function:" import math radius_r1 = 5 # first radius float_f1 = 4.0/3.0 radius_r2 = 7 # second radius float_f2 = 4.0/3.0 radius_r3 = 11 # third radius float_f3 = 4.0/3.0 #In this section I define 3 functions #using the variables that I assigned values to above # I also imported the math library and used it to define pi # Something I learned is that I can define one function, # only and just adjust my variables above # and receive the same results without defining two # additional functions. def sphere_vol(radius_r, float_f): volume = float_f * math.pi * radius_r **3 print("With 5 as the radius, the volume of the sphere is: ") print(volume) def sphere_vol2(radius_r1, float_f2): volume = float_f2 * math.pi * radius_r2 **3 print("With 7 as the radius, the volume of the sphere is: ") print(volume) def sphere_vol3(radius_r3, float_f3): volume = float_f3 * math.pi * radius_r3 **3 print("With 11 as the radius, the volume of the sphere is: ") print(volume) result = sphere_vol(radius_r1, float_f1) result = sphere_vol2(radius_r2, float_f2) result = sphere_vol3(radius_r3, float_f3) #used π as the value of "pi" given in Section 2.1 of the text #wrote a function called print_volume that takes an argument for r #the radius of the sphere, and prints the volume of the sphere #called print_volume function with three different values for radius. #by Keeno Simms - Thursday February 14th, 2019
print("Только не Ноль Плиз") while True: s = input("Знак (+,-,*,/): ") if s == '0': break if s in ('+', '-', '*', '/'): a = float(input("x=")) b = float(input("y=")) if s == '+': print(a+b) elif s == '-': print(a-b) elif s == '*': print(a*b) elif s == '/': if b != 0: print(a/b) else: print("Деление на ноль!" "\nНе надо так!") else: print("Прошу ввести еще раз!")
""" Angel David Cuellar 18382 Hoja de Trabajo 1 ejercicio 3 """ def amigos(n): divisores = [] for i in range(1,n+1): if(n%i==0): divisores.append(i) divisores.pop() suma=0 for m in divisores: suma=suma+m print "La suma de los divisores es: ", suma print "" return suma print("Bienvenido al programa amigos") print"" amigos(32)
import pyttsx3 import os import speech_recognition as sr name= input("Enter your name: ") pyttsx3.speak("hello {} how can I help you".format(name)) r=sr.Recognizer() while True: print("What would you like to do:" , end='') with sr.Microphone() as source: print('Start saying....') audio = r.listen(source) print('Done....') data=r.recognize_google(audio) choice=data print(choice) if ("run" in choice or "open" in choice) and ("Chrome" in choice): os.system("chrome") elif ("run" in choice or "open" in choice) and ("Notepad" in choice or "text editor" in choice): os.system("notepad") elif ("show" in choice or "tell" in choice) and ("date" in choice): os.system("date") elif ("exit" in choice) or ("terminate" in choice) or ("go back" in choice): print('exiting') break else: print("doesn't support") print("Thank youu", end='...') print('have a nice day!!')
#Agata Chmielowiec, Navan 2019 #This is a program that sum up positive interegs between 1 and i - the number that user selects. #Invention taken from 8th February lecture posted: Loops: while and for. i = int(input("Please enter a positive integer: ")) total = 0 while i>0: total = total + i i = i - 1 print(total)
import pandas as p # DataFrame Creation s1 = p.Series(['faiz', 'dravi', 'dishu', 'pari'], index=[0, 1, 2, 3]) s2 = p.Series(['ahmed', 'jain', 'jain', 'mamgain'], index=[0, 1, 2, 3]) s3 = p.Series([23, 23, 22.5, 23.5], index=[0, 1, 2, 3]) df = p.DataFrame({'FirstName': s1, 'LastName': s2, 'Age': s3}) print(df) # Applying loc knowledge print(df.get('Age')) # For Column dtype : float64 print(df.iloc[2]) # For rows dtype : object # Append a new row to existing df # one row at a time row = p.DataFrame([['priya', 'sharma', 35]], columns=['FirstName', 'LastName', 'Age']) df = df.append(row) print(df) print('---------------') # multiple row at a time row = p.DataFrame([['ragini', 'sharma', 24], ['mahi', 'bagi', 23.2]], columns=['FirstName', 'LastName', 'Age']) df = df.append(row) print(df) print('------_DELETE---------') # DELETE OR DROP ROWS df = df.drop(0) # all 0th index value would be dropped print(df)
# Print N lines M datas # Each datas on the line should have a blank between # datas on each line N = from (N-2)*M+1 to N*M # go to the next line by "\n" N = int(input("write the number of line (N) : ")) M = int(input("Write the number of int (M) : ")) for i in range(1, N+1): # line N result = [] result.clear() start_num = (i-1) * M + 1 last_num = i * M for j in range (start_num, last_num+1): result.append(j) print(result,"\n") # 출력하고 다음줄
###### this is the third .py file ########### #database state={"AP":'000',"DELHI":'001',"MAHARASTRA":'010'} city={"ROORKEE":'111',"KANPUR":'110',"NEWDELHI":'101'} district={"NIT":'000',"IIT ROORKEE":'001',"IIT DEHLI":'010'} print "1.add 2.modify 3.delete" choice=input("enter the operation you want to perform") #add block if choice==1: st=raw_input("enter the state ") cd=raw_input("enter the code ") state.update({st:cd}) st1=raw_input("enter the city ") cd1=raw_input("enter the code ") city.update({st1:cd1}) st2=raw_input("enter the district") cd2=raw_input("enter the code") district.update({st2:cd2}) #modify block if choice==2: st=raw_input("enter the state to modify\n") cd=raw_input("enter the new code\n") if st in state.keys(): state.update({st:cd}) else : print 'invalid state' st1=raw_input("enter the district to modify\n") cd1=raw_input("enter the new code\n") if st1 in district.keys(): district.update({st1:cd1}) else : print 'invalid district' st2=raw_input("enter the city to modify\n") cd2=raw_input("enter the new code\n") if st2 in city.keys(): city.update({st2:cd2}) else : print 'invalid city' #Delete block if choice==3: st=raw_input("enter state to delete\n") if st in state.keys(): del state[b] else : print "invalid key" ci=raw_input("enter the city delete\n") if ci in city.keys(): del city[b] else : print "invalid key" dt=raw_input("enter the district delete\n") if dt in district.keys(): del district[b] else : print "Invalid key" #query block else : l1=raw_input("customer name\n") l2=raw_input("customer district\n") l3=raw_input("customer city\n") l4=raw_input("customer state\n") if l4 in state.keys(): print "CC_NO = ",state.get(l4,"None") if l2 in district.keys(): print district.get(l2, "None") if l3 in city.keys(): print city.get(l3, "None") print state
seq="ATGCATGCA" # 0 1 2 3 4 5 6 7 8 left-right # | | | | | | | | | #['A','T','G','C','A','T','G',' C','A'] #-9 -8 -7 -6 -5 -4 -3 -2 -1 right-left #left to right indexing print(seq[0]) print(seq[2]) #right to left indexing print(seq[-1]) print(seq[-3]) #program to find the base present in the 3rd position print (seq[2]) #program to find out the base present at the third last position print([-3])
## aplicações from random import randint ### abertura do arquivo with open('data/sacramento.csv', 'rt') as arq: conteudo = arq.readlines() ## lista de strings que representam um registro # aplicar filtros em conteúdo de arquivos imoveis = [conteudo[randint(1,len(conteudo)-1)] for x in range(1,100) if float(conteudo[x].split(',')[9]) > 100000] exit() # exemplo gerar amostras aleatórias amostra = [conteudo[randint(1,len(conteudo)-1)] for x in range(50)] for indice in range(5): print(amostra[indice]) exit() def mostra_sequencia(num): lista = [] for numero in range(num): lista.append(numero) return lista lista = mostra_sequencia(10) nova_lista = [ numero for numero in range(10) ] quadrados = [numero * numero for numero in range(100)]
import csv with open("file.csv",newline="") as f: reader=csv.reader(f) data=list(reader) data.pop(0) newdata =[] for i in range (len(data)): num=data[i][2] newdata.append(float(num)) n =len(newdata) newdata.sort() if n % 2==0: m1=float(newdata[n//2]) m2=float(newdata[n//2-1]) median=(m1+m2)/2 else: median=newdata[n//2] print("median of height = "+ str(median))
# Exercise 20: Functions And Files from sys import argv script, input_file = argv # function which excepts a file and reads it def print_all(f): print f.read() # function which sets the file back to the begin of file def rewind(f): f.seek(0) # function which take in a line count and file name and prints out the line number and the line itself def print_a_line(line_count, f): print line_count, f.readline() # this opens the input file being used. current_file = open(input_file) print "First, let's print the whole file:\n" # ok, on this we are using current file which is open, then pass it into the funciton to read it print_all(current_file) print "Now le's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file)
# helltriangle.py import sys, ast class HellTriangle(): """ Returns the maximum total from top to bottom in a triangle. This method creates a copy of the triangle and traverses the new triangle from top to bottom, updating the value in each position, summing to it the maximum value of its two possible upper nearest elements, and returns the maximum value in the bottom level. """ @staticmethod def calculate_longest_path(triangle): # Corner/Exceptional cases if (triangle == None or len(triangle) == 0): raise ValueError("Invalid triangle passed as input! Empty triangle.") if (not isinstance(triangle[0], list)): # Input is a single-dimensional array. raise ValueError("Invalid triangle passed as input! Must be a multidimensional array.") if len(triangle) == 1: # Triangle only has one row. if (len(triangle[0]) != 1): # Triangle only has one row and more or less than one element. raise ValueError("Invalid triangle passed as input! Must be equilateral.") # Triangle only has one row and one element. Return it. return triangle[0][0] # Usual case prev_row = triangle[0][:] prev_row_length = 1 for i in range(1, len(triangle)): cur_row = triangle[i][:] cur_row_length = len(cur_row) if (cur_row_length - 1 != prev_row_length): raise ValueError("Invalid triangle passed as input! Must be equilateral.") for j in range(cur_row_length): if (j == 0): # Handling first element in a row. cur_row[j] += prev_row[j] elif (j == cur_row_length-1): # Handling last element in a row. cur_row[j] += prev_row[j-1] else: # Handling in-between elements in a row. cur_row[j] += max(prev_row[j-1], prev_row[j]) prev_row = cur_row prev_row_length += 1 return max(cur_row) """ Receives as input an equilateral triangle, in the format of a multidimensional array. For example: [[6],[3,5],[9,7,1],[4,6,8,4]] """ if __name__ == "__main__": inputList = ast.literal_eval(sys.argv[1]) print HellTriangle.calculate_longest_path(inputList)
import time def bubble_sort(data, drawrectangle, delay): for i in range(len(data)-1): for j in range(len(data)-1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] drawrectangle(data, ['blue' if x == j or x == j+1 else 'red' for x in range(len(data))] ) time.sleep(delay) drawrectangle(data, ['blue' for x in range(len(data))])
##################################### ## ## ## Best-First Search Algorithm ## ## ## ##################################### # This is an implementation of the SearchAlgorithm interface for the following # search algorithms: # - BestFirstGraphSearch import time from algorithm import SearchAlgorithm infinity = 1.0e400 class State: def __init__(self, state, score, orig_direction, chance): self.state = state self.score = score self.orig_direction = orig_direction self.chance = chance def search(self, heuristic): mutations = self.state.get_mutations() states = [] for mutation, chance in mutations: # print '*'*20 # print 'Mutation: ' # print mutation # print chance best = {'score': -1, 'successor': None, 'chance': 0} successors = mutation.get_successors() for successor in successors.itervalues(): score = heuristic.evaluate(successor) # print '*'*10 # print 'Successor: ' # print successor # print score if score > best['score']: best['score'] = score best['successor'] = successor best['chance'] = chance if best['successor']: states.append(State(best['successor'], best['score'], self.orig_direction, self.chance * best['chance'])) return states class BestFirstGraphSearch(SearchAlgorithm): """ Implementation of a best-first search algorithm for the Problem. This is inherently a greedy algorithm, as it takes the best possible action at each junction with no regard to the path so far. It may also take a maximum depth at which to stop, if needed. """ def __init__(self, time_limit=infinity, max_depth=infinity): """ Constructs the best-first graph search. Optionally, a maximum depth may be provided at which to stop looking for the goal state. """ self.time_limit = time_limit self.max_depth = max_depth def find(self, problem_state, heuristic): """ Search the nodes with the lowest heuristic evaluated scores first. You specify the heuristic that you want to minimize. For example, if the heuristic is an estimate to the goal, then we have greedy best first search. If the heuristic is the depth of the node, then we have DFS. Optionally a limit may be supplied to limit the depth of the seach. @param problem_state: The initial state to start the search from. @param heuristic: A heuristic function that scores the Problem states. """ start = time.time() scores = {} states = [] successors = problem_state.get_successors() for direction, new_state in successors.iteritems(): score = heuristic.evaluate(new_state) scores[direction] = score states.append(State(new_state, score, direction, 1.0)) # print scores # for s in states: # print s.state # print s.score # print s.orig_direction # print s.chance best_move = {'score': -1, 'direction': -1} moves = 0 while (time.time() - start) < self.time_limit and len(states): # Find the current best state best_index, best_state = max(enumerate(states), key=lambda state: state[1].score * state[1].chance) # Maybe multiply by the chance? # print '*'*40 # print 'Chose best state:' # print best_state.state # print best_state.score # print best_state.orig_direction # print best_state.chance # Replace the best state with all its children states.pop(best_index) children = best_state.search(heuristic) score = scores[best_state.orig_direction] score -= (best_state.score * best_state.chance) for child in children: score += (child.score * child.chance) states.append(child) # print '*'*10 # print 'New children:' # for s in children: # print s.state # print s.score # print s.orig_direction # print s.chance # print '*'*40 # print 'New state list:' # for s in states: # print s.state # print s.score # print s.orig_direction # print s.chance scores[best_state.orig_direction] = score if score > best_move['score']: best_move['score'] = score best_move['direction'] = best_state.orig_direction moves += 1 print moves return best_move['direction']
# Escribir un programa que pida al usuario su peso en kg y su estaruta en mts # Calcular el imc(indice de masa corporal) y almacenarlo en una variable # luego mostrar por pantalla el imc redondeado con dos decimales # Codigo: peso = float(input('Ingrese su peso en kilogramos:')) alt = float(input('Ingrese su estatura en metros:')) imc = round(peso/(alt**2), 2) print('Tu indice de masa corporal es ', imc)
#write a programm to find the fibinochii series of a agaiven set of numbers fib = [] def number(n): count = 0 c = 0 if count == 0: a = 1 b = 1 yield a yield b while c < n: temp = a a = b b += temp yield b c += 1 for i in number(int(input())): print(i)
class Graph(): def __init__(self): self.numberOfNodes = 0 self.adjacentList = {} def addVertex(self, node): self.adjacentList[node] = [] self.numberOfNodes+=1 def addEdge(self, node1, node2): self.adjacentList[node1].append(node2) self.adjacentList[node2].append(node1) def showConnections(self): for node,edges in self.adjacentList.items(): print("%s--->%s" % (node,",".join(edges))) a = Graph() a.addVertex("0") a.addVertex("1") a.addVertex("2") a.addVertex("3") a.addVertex("4") a.addVertex("5") a.addVertex("6") a.addVertex("7") a.addEdge("0","1") a.addEdge("0","2") a.addEdge("1","2") a.addEdge("1","3") a.addEdge("2","4") a.addEdge("3","4") a.addEdge("4","5") a.addEdge("5","6") a.showConnections()
nome = input('Olá, qual é o seu Nome?') print('Olá' , nome+ '! Seja Muito Bem-Vindo') dia = input('Qual é o dia do seu aníversário?') mês = input('De que mês?') ano = input('De que ano?') país = input('Onde você mora?') print('Você se chama' , nome+'?', 'nasceu em' , país, 'em', dia + '/' + mês + '/' + ano+'?') certo = input('Está Tudo Correto?') print('Personagem Criado com Sucesso') ajuda = input('Preciso calcular números pode me ajudar?') print('Primeiro vamos começar com soma') somanumero1 = int(input('Digite um número')) somanumero2 = int(input('Digite outro número')) resultadosoma = somanumero1+somanumero2 print('O resultado da soma é' , resultadosoma) print('Agora vamos para subtração') subnum1 = int(input('Digite um número')) subnum2 = int(input('DIgite Outro Número')) resultadosub = subnum1-subnum2 print('o resultado foi' , resultadosub) print('Agora multiplicação') mult1 = int(input('Digite um Número')) mult2 = int(input('Digite outro Número')) resultadomult = mult1*mult2 print('a multiplicação deu' , resultadomult) print('Acho que estou indo muito bem, o último teste é Divisão') div1 = int(input('Digite um Número')) div2 = int(input('Digite outro Número')) resultadodiv = div1/div2 print('o resultado é' , resultadodiv) tudobem = input('Está tudo correto?')
try: n=int(input()) if(n>=0): n=n%2 if(n==0): print('Even') else: print('Odd') else: print('invalid') except: print('invalid')
r = [] n = input() s = list(n) ns = list(set(s)) #removing duplicates using set and type-casting it to list. l = len(ns) for i in range(len(s)): if(l>0):# when distinct elements list length is not equal to zero it enters the loop. if n[i] in ns: r.append(s[i]) ns.remove(s[i]) #removing distinct in list whenever it encountered. l = l - 1 else: r.append(s[i]) else:# when distinct elements list length becomes zero it comes out of the loop. break print(len(r))
# -*- coding: utf-8 -*- # encoding=utf8 ''' This code does preprocessing on the input text to remove corner cases which cause trouble in the process of keyphrase extraction and then does the extraction process using RAKE extraction method. ''' import re import operator import nltk #File containing text #input_content = open('output_file_part2.txt','r').read() # for winnowing input_content = open('inputs/input.txt','r').read() #for nowinnowing contentforsplit = input_content[:] output_file = open('outputs/output_file.txt','w') stoplistlines = open("inputs/stopwords.txt",'r').readlines() stoplist = [] for i in stoplistlines: stoplist.append(i.strip().lower()) #refining data to appropriate form def preprocess(input_content): ''' Numbers like 1.34 are edge cases and the extractor will split the number into 1 and 34 if not handled properly. Hence it has been replaced by <dot> which is later replaced back to dot. Similarly for desginations like Mr., Mrs., Dr., are replaced to Mr, Mrs, Dr or initials like O. Schindler is replaced to O Schindler. ''' content = filter(None, re.sub('''Rs.''','''Rs''',input_content)) content = filter(None, re.sub('''Mr.''','''Mr''',content)) content = filter(None, re.sub('''Mrs.''','''Mrs''',content)) content = filter(None, re.sub('''Ms.''','''Ms''',content)) content = filter(None, re.sub('''Dr.''','''Dr''',content)) content = filter(None, re.sub('''([A-Z])\.''','''\\1''',content)) content = filter(None, re.sub('''([0-9])\.''','''\\1<dot>''',content)) content = filter(None, re.sub('''-and-''','''&''',content)) ''' Joining continuously occurring proper nouns into one proper noun separated by '-' to avoid unnecessary higher score to proper nouns. For example Oskar Schindler is replaced by Oskar-Schindler so the extractor considers it as one word and not as two separate words thus retaining the importance to both the proper nouns equally if they occur one after the other ''' token = nltk.word_tokenize(content.decode('utf-8')) pos = nltk.pos_tag(token) #pos tagger word_token = [] tag_token = [] for w,t in pos: word_token.append(w) tag_token.append(t) phraseList = [] p = 0 while p < len(tag_token): if tag_token[p] == 'NNP' or tag_token[p] == 'NNPS': #Proper noun tags ph = word_token[p] j = p + 1 if j >= len(tag_token): phraseList.append(ph) break flag = 0 while j < len(tag_token): if tag_token[j] == 'NNP' or tag_token[j] == 'NNPS': ph += '-' + word_token[j] j += 1 if j >= len(tag_token): flag = 1 else: p = j phraseList.append(ph) break if flag == 1: phraseList.append(ph) break else: phraseList.append(word_token[p]) p += 1 ''' phraseList contains merged proper nouns ''' phraseStr = ' '.join(phraseList) phraseStr = phraseStr.replace(' < dot > ', '<dot>') phraseStr = phraseStr.replace(' ,', ',') phraseStr1 = phraseStr.replace(' ,', ',') phraseStr1 = phraseStr1.replace('^',"'") #Made global since it is imported in proc_part2.py global content_no_dot content_no_dot = phraseStr1[:] content_no_dot = content_no_dot.encode('utf8').replace('-< dot >-','<dot>').replace('-< dot >','<dot>').replace('< dot >-','<dot>').replace(' <dot> ','<dot>') print content_no_dot phraseStr1 = phraseStr1.replace('<dot>', '.') #for Open IE sent = nltk.sent_tokenize(content.decode('utf-8')) input_content1 = phraseStr1[:] output_file.write(input_content1.encode('utf8')) content = phraseStr[:] #Removal of articles articles = [' the ',' a ', ' an '] for i in articles: content = content.replace(i,' ') #Removal of verbs which are not in stoplist ''' If the keyphrase consists of "Indian aeroplane is best of its kind ; thus gaining world ranking 3 in terms of safety" then it removes the verbs and replaces them with '|' Resultant statement will be "Indian aeroplane | best of its kind ; thus | world ranking 3 in terms of safety" ''' verb = ['VB','VBD','VBG','VBN','VBZ','VBP'] verbs = [] for t in sent: token = nltk.word_tokenize(t) pos = nltk.pos_tag(token) for i,v in pos: if v in verb: if i not in stoplist: verbs.append(i) for i in verbs: content = filter(None, re.sub(' ' +str(i.encode('utf8') + ' '),''' | ''',content)) return content #text split on the basis of following characters def contentSplit(content): ''' After the preprocessing step has been finished, the text is split on the basis of multiple symbols to get the shorter parts of sentences which can give us keyphrases Example: "Indian aeroplane | best of its kind ; thus | world ranking 3 in terms of safety" will be replaced to two sentences split on the ; and | Resultant will be "Indian aeroplane", "best of its kind", "thus", "world ranking 3 in terms of safety" ''' contentList = filter(None, re.split('''[`~!@#$%&*_?=+/,.\\\\;|{}\(\)]''',content)) return contentList #Finding candidate keywords def processPhrases(contentList): ''' stopwords like 'of' and 'its' won't be present now as we replace them by | "Indian aeroplane", "best of its kind", "thus", "world ranking 3 in terms of safety" will become "Indian aeroplane", "best", "kind", "thus", "world ranking 3", "terms", "safety" ''' candidateKeywords = [] for i in contentList: phraseStr = (i.replace('\t','').replace('\n','').strip()) phraseList = phraseStr.split() for k in phraseList: if k.lower() in stoplist: phraseList[phraseList.index(k)] = '|' phraseStr = ' '.join(phraseList) a = phraseStr.split('|') for o in a: candidateKeywords.append(o) candidateKeywords = [x.strip() for x in candidateKeywords if x] candidateKeywords = filter(None, candidateKeywords) return candidateKeywords #calculating word score def word_score(candidateKeywords): ''' Calculates the frequency of the words in the document. Frequency of the word is the number of times it appears in the document. Calculates the degree of the words. Degree of a word is the number of keyphrases present along with a specific keyphrase in a sentence. We add this for all the sentences to get the degree of the word. Thus degree is the total number of keyphrase related to a particular keyphrase. For -> "Indian aeroplane", "best", "kind", "world ranking 3", "terms", "safety" Frequency of each keyphrase is the total number of times they occur in the document Degree of each keyphrase in this sentence is 6 including themselves. We add individual degrees for each sentence to get the final degree. This final degree for each word is divided by the frequency of the world to find the score against a particular keyphrase. The more score, the higher will the keyphrase appear statistically in the list. ''' global word_frequency global word_degree word_frequency = {} word_degree = {} for i in candidateKeywords: for j in i.split(): if j.lower() in word_frequency: word_frequency[j.lower()] += 1 word_degree[j.lower()] += len(i.split()) else: word_frequency[j.lower()] = 1 word_degree[j.lower()] = len(i.split()) summed = {} for i in candidateKeywords: phrased = "" sumof = 0 for j in i.split(): phrased += " " phrased += j sumof += (word_degree[j.lower()])/(word_frequency[j.lower()] * 1.0) #phrase wise score summed[phrased.strip()] = sumof sort_list = sorted(summed.items(),key=operator.itemgetter(1),reverse=True) content = filter(None, re.sub('''Rs.''','''Rs''',input_content)) content = filter(None, re.sub('''Mr.''','''Mr''',content)) content = filter(None, re.sub('''Mrs.''','''Mrs''',content)) content = filter(None, re.sub('''Ms.''','''Ms''',content)) content = filter(None, re.sub('''Dr.''','''Dr''',content)) content = filter(None, re.sub('''([A-Z])\.''','''\\1''',content)) content = filter(None, re.sub('''([0-9])\.''','''\\1<dot>''',content)) content = filter(None, re.sub('''-and-''','''&''',content)) con = filter(None, re.split('''[.]''',content)) for i in range(len(con)): con[i] = con[i].replace('\t','').replace('\n','').strip() length = [0 for i in range(len(con))] dash = [] ##printing keyphrases in decreasing order of word scores print "NLTK POS TAGGER" new_sort_list = {} for i,v in sort_list: new_sort_list[i.replace('^',"'").replace('<dot>','.').strip()] = v new_sort_list = sorted(new_sort_list.items(),key=operator.itemgetter(1),reverse=True) new_sort_dict = {} for i,v in new_sort_list: new_sort_dict[i] = v #separating on the basis of paragraphs splitcontent = contentforsplit.split('\n') freq = [[] for i in range(len(splitcontent))] #contains keyphrases in one para for i,v in new_sort_list: for j in splitcontent: if i in j.decode('utf-8'): freq[splitcontent.index(j)].append(i) another_freq = [] another_score = [] for i in range(len(freq)): for j in range(50): #for 25 keyphrases in each paragraph if j < len(freq[i]): another_freq.append(freq[i][j]) another_score.append(new_sort_dict[freq[i][j]]) dictor = dict(zip(another_freq,another_score)) new_sort_dictor = sorted(dictor.items(),key=operator.itemgetter(1),reverse=True) return new_sort_dictor ''' return new_sort_list ''' #dealing with characters which cause in poor results articles0 = ['“','”','"'] for i in articles0: input_content = input_content.replace(i,'') input_content = input_content.replace("'",'^') input_content = input_content.replace("’",'^') articles = ['—','[',']'] for o in articles: input_content = input_content.replace(o,' ') articles1 = ['. The ', '. A ', '. An '] for o in articles1: input_content = input_content.replace(o,'. ') def main(): #Does preprocessing on the input text content = preprocess(input_content) #Splits processed input text on multiple symbols contentList = contentSplit(content) #Creates a list of keyphrases from the available text candidateKeywords = processPhrases(contentList) #calculates word scores of each keyphrase global new_sort_list new_sort_list = word_score(candidateKeywords) #Print keyphrases in descending order for i,v in new_sort_list: i = i.strip() print i, v print '\n\n\n' main()
# coding: utf-8 ''' 求解一元二次方程 ''' import math a = int(input('Enter a: ')) b = int(input('Enter b: ')) c = int(input('Enter c: ')) delta = b * b - 4 * a * c if delta > 0: sqrt_delta = math.sqrt(delta) root1 = (-b + sqrt_delta) / (2 * a) root2 = (-b - sqrt_delta) / (2 * a) print('The root is: {0} and {1}'.format(root1, root2)) elif delta == 0: root = -b / (2 * a) print('The root is: {0}'.format(root)) else: print('no root')
# coding:utf-8 ''' -计算圆的周长和面积 -提示用户输入半径(23) ''' import math radius = float(input("Enter the radius of circle: ")) # 参考老师的答案做了修改 circumference = math.pi * radius * 2 area = math.pi * radius * radius print('The circumference is :', round(circumference, 2)) print('The area is :', round(area, 2))
import collections def find_largest(arr): aux = collections.deque() def first_digit(num): digits = len(str(num)) first = num if digits > 1: first = num / (10**(digits - 1)) return first for x in arr: current = first_digit(x) if not aux: aux.append(x) else: aux_size = len(aux) for y in xrange(aux_size): aux_num = first_digit(aux[y]) if current < aux_num: if y == aux_size-1: aux.append(x) else: aux.appendleft(x) break return ''.join(str(x) for x in aux) print find_largest([52, 5, 3])
print("enter only integer numbers") print("First Rectangle") print("Enter x position:") ax1 = int(input()) print("Enter y position:") ay1 = int(input()) print("Enter width:") w1 = int(input()) print("Enter height:") h1 = int(input()) ax2 = ax1 + w1 ay2 = ay1 + h1 print("Second Rectangle") print("Enter x position:") bx1 = int(input()) print("Enter y position:") by1 = int(input()) print("Enter width:") w2 = int(input()) print("Enter height:") h2 = int(input()) bx2 = bx1 + w2 by2 = by1 + h2 print("First Rectangle") print("coordinate 1:", ax1, ay1) print("coordinate 2:", ax2, ay1) print("coordinate 3:", ax1, ay2) print("coordinate 2:", ax2, ay2) print("Second Rectangle") print("coordinate 1:", bx1, by1) print("coordinate 2:", bx2, by1) print("coordinate 3:", bx1, by2) print("coordinate 2:", bx2, by2) if (bx1 >= ax1 and bx1 <= ax2) and (by1 >= by1 and by1 <= by2): print("rectangles intersect") elif (bx2 >= ax1 and bx2 <= ax2) and (by1 >= by1 and by1 <= by2): print("rectangles intersect") elif (bx1 >= ax1 and bx1 <= ax2) and (by2 >= by1 and by2 <= by2): print("rectangles intersect") elif (bx2 >= ax1 and bx2 <= ax2) and (by2 >= by1 and by2 <= by2): print("rectangles intersect") else: print("rectangles dont intersect")
"""All the optimization methods go here. """ from __future__ import division, print_function, absolute_import import random import numpy as np class SGD(object): """Mini-batch stochastic gradient descent. Attributes: learning_rate(float): the learning rate to use. batch_size(int): the number of samples in a mini-batch. """ def __init__(self, learning_rate, batch_size): self.learning_rate = float(learning_rate) self.batch_size = batch_size def __has_parameters(self, layer): return hasattr(layer, "W") def compute_gradient(self, x, y, graph, loss): """ Compute the gradients of network parameters (weights and biases) using backpropagation. Args: x(np.array): the input to the network. y(np.array): the ground truth of the input. graph(obj): the network structure. loss(obj): the loss function for the network. Returns: dv_Ws(list): a list of gradients of the weights. dv_bs(list): a list of gradients of the biases. """ # TODO: Backpropagation code # print (x.shape) inputs=[x] for i in graph: # print (i.forward(inputs[-1]).shape) inputs.append(i.forward(inputs[-1])) dv_y=loss.backward(inputs[-1],y) dv_Ws = [] dv_bs = [] # Traverse List backward, do backpropogation for l, i in reversed(zip(graph, inputs[:-1])): if type(l).__name__=="FullyConnected": dv_y, w, b = l.backward(i, dv_y) dv_Ws=[w]+dv_Ws dv_bs=[b]+dv_bs else: dv_y=l.backward(i, dv_y) return dv_Ws,dv_bs def optimize(self, graph, loss, training_data): """ Perform SGD on the network defined by 'graph' using 'training_data'. Args: graph(obj): a 'Graph' object that defines the structure of a neural network. loss(obj): the loss function for the network. training_data(list): a list of tuples ``(x, y)`` representing the training inputs and the desired outputs. """ # Network parameters Ws = [layer.W for layer in graph if self.__has_parameters(layer)] bs = [layer.b for layer in graph if self.__has_parameters(layer)] # Shuffle the data to make sure samples in each batch are not # correlated random.shuffle(training_data) n = len(training_data) batches = [ training_data[k:k + self.batch_size] for k in xrange(0, n, self.batch_size) ] # TODO: SGD code for batch in batches: sum_ws=np.zeros(np.array(Ws).shape) sum_bs=np.zeros(np.array(bs).shape) for row in batch: ws, bs = self.compute_gradient(row[0], row[1], graph, loss) sum_ws= np.add(sum_ws, ws) sum_bs= np.add(sum_bs, bs) sum_ws= np.divide(sum_ws, len(batch)) sum_bs= np.divide(sum_bs, len(batch)) fullyC=[i for i in graph if type(i).__name__=="FullyConnected"] for i in range(len(fullyC)): fullyC[i].W = fullyC[i].W-(self.learning_rate*sum_ws[i]) fullyC[i].b = fullyC[i].b-(self.learning_rate*sum_bs[i])
''' Program 3: Below is the python program that verifies a positive integer from the user to be a prime, composite or neither prime or composite and prints the message accordingly. Logic: * Have written a function "primenum" which takes in one argument which is the number to be tested to be a prime or composite number. For loop is incorporated with numbers ranging from 2 to that number entered by user. * We assume from 2 as 0 and 1 are considered to be neither Prime nor Composite. * Later we check for the factors of the number by dividing and checking the remainder to be 0 for a composite number where the if loop returns False telling it to be a Composite number. In the else loop we return True meaning it is a Prime number without any factors other than 1 and itself. * The user is prompted for the number and is casted for int datatype. * If condition loop is written for the number to be greater than or equal to 0 with first if loop condition checking for 0 or 1 where it prints it to be "Neither prime nor composite" on entering the loop * In the elif loop the number is greater than 1 ,it enters the loop where it gives the control flow to the primenum function and expects the output to be True or False. * If false then it prints "It is composite" and true then it prints "It is Prime" * Else prints "Error: You did not enter a positive integer" ''' #function for prime number check with one argument as input def primenum(x): #checking for the factors of the number for n in range(2,x): #checking with if loop for remainder to be 0 on dividing the number with numbers starting from 2 till it. if (x % n) == 0: #if factors found return false claiming it to be composite number return False break else: #if not found return true claiming it to be a prime number return True #prompting the user for th input raw_inp = input('Enter positive integer:') try: #casting the numer to an int datatype pos_num = int(raw_inp) except: pos_num = -1 #if condition loop for checking the number to be greater than or equal to 0 if(pos_num >= 0): #if condition loop for checking the number to be equal to 0 or 1 if(pos_num == 0 or pos_num == 1): print('It is neither prime nor composite') #if condition loop for checking the number to be greater than 1 elif(pos_num > 1): #assigning the return value of function primenum by passing the input number as argument output = primenum(pos_num) #if condition loop for checking the output to be false if(output == False): #then the number is composite print('It is a composite') #if condition loop for checking the output to be true elif(output == True): #then the number is prime print('It is a prime') else: print('none of the above') else: print('Error: You did not enter a positive integer') else: #else condition loop for number other than integer datatype and lesser than 0 print('Error: You did not enter a positive integer')
#!/usr/bin/env python ''' --------------------------------------------------- PROBLEM STATEMENT: --------------------------------------------------- problem here --------------------------------------------------- INPUTS: x) binary tree representing lockable resources OUTPUTS: x) API with 3 functions: - isLock() - lock() - unLock() CONSTRAINTS: x) a node can not be locked if any of its children or ancestors are locked x) isLock() -> O(1) time complexity lock() -> O(h) time complexity, h is the height of a node unLock -> O(h) ime complexity, h is the height of a node OBJECTIVE: x) minimize space complexity while satisfying the constraints ASSUMPTIONS: x) TRADEOFFS: x) --------------------------------------------------- SOLUTIONS: --------------------------------------------------- BRUTE FORCE: x) ANY PATTERNS?: x) REFINED: x) EVEN BETTER: x) CASES: x) CAVEATS: x) --------------------------------------------------- ''' # import binary tree, add locking and counting logic class Node(object): def __init__(self): # relationships self.left = None self.right = None self.parent = None # lock tracking self.is_locked = False self.children_locked = 0 def isLock(self): return self.is_locked def lock(self): # check if already locked if self.is_locked: raise Exception('this node already locked!') # check if any children are locked if self.children_locked > 0: raise Exception('child nodes are locked, cannot lock this node') # check if ancestors are locked node = self while node.parent: node = node.parent if node.isLock(): raise Exception('an ancestors node is locked, cannot lock this node') # all conditions met, update the lock state self.is_locked = True # +1 to children_locked for all ancestors node = self while node.parent: node = node.parent node.children_locked += 1 def unlock(self): ''' undo everything done in lock() ''' # check if already unlocked if not self.is_locked: raise Exception('this node already unlocked!') self.is_locked = False # -1 to children_locked for all ancestors node = self while node.parent: node = node.parent node.children_locked -= 1 def __str__(self): return 'Node(locked:{0}, children_locked:{1})'.format(self.is_locked, self.children_locked) # *** TODO: needs real testing *** # build a test tree n0 = Node() print print n0 print n0.isLock() print n0.lock() print n0.unlock() print n0 print # IMPLEMENTATION # TEST DATA # TEST RUN # EYEBALL SOLUTION
#!/usr/bin/env python ''' INPUTS: x) an array 'A' with comparable elements x) an index 'i' into the array OUTPUTS: x) a partially sorted array OBJECTIVE: x) reorder 'A' into 3 groups - initial elements < A[i] - elements == A[i] - elements > A[i] SUBJECT TO: x) O(1) space complexity ''' # IMPLEMENTATION def partial_sort(A, i): ''' maintain 4 groups with 3 index pointers: pointers: smaller, equal, larger groups: bottom, middle, unknown, top ranges are index inclusive: bottom range: 0 to (smaller-1) middle range: smaller to (equal-1) unknown range: equal to (larger-1) top range: larger to len(A)-1 iterate over the each element in the array, swapping unknown elements into a known group, then updating pointers ''' # initalize pivot value and group pointers pivot = A[i] smaller, equal, larger = 0, 0, len(A) print 'pivot:', pivot, 'A:', A print print # while equal < larger: print smaller, equal, larger, A # A[equal] is the current unknown element if A[equal] < pivot: # swap with the first of the middle range temp = A[smaller] A[smaller] = A[equal] A[equal] = temp # +1 bottom and middle pointers smaller += 1 equal +=1 elif A[equal] == pivot: # do nothing, but advance the equal counter equal += 1 else: # swap with the last element of the unknown range temp = A[larger-1] A[larger-1] = A[equal] A[equal] = temp # -1 the larger pointer larger -= 1 print smaller, equal, larger, A print return A # TEST DATA A0, i0 = (4, 3, 7, 5, 9, 1, 0, 6), 2 # TEST EYEBALL print partial_sort(list(A0), i0) ''' # REAL TESTING def comparator(x, y): '' custom comparitor function for this special problem instance '' if x < y: return -1 if y < x: return 1 return 0 def test_partial_sort(A, i): '' compare A with A[i] then group the resulting comparisons. the ordered keys must match one of the asserted patters to be valid. '' compared = [comparator(x, A[i]) for x in A] import itertools unique_keys = tuple(k for k, grp in itertools.groupby(compared)) assert unique_keys == (-1, 0, 1) or unique_keys == (-1, 0) or unique_keys == (0, 1) or unique_keys == (0) test_partial_sort(partial_sort(list(A0), i0), i0) '''
#!/usr/bin/env python ''' http://stackoverflow.com/questions/13421424/how-to-evaluate-an-infix-expression-in-just-one-scan-using-stacks Dijkstra's two stack algorithm: 1) ignore left parenthesis 2) push values to value stack 3) push operand to operand stack 4) right parens, double pop values, pop operand, evaluate, push to value stack 5) at the end, should only be one value in the val stack. return it. ''' import operator def evaluate_infix_expression(expression): ''' assumes picky input format. doesn't handle negative values. ''' val_stack, op_stack = [], [] op_map = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv} for s in expression.split(): if s == '(': continue elif s.isdigit(): val_stack.append(int(s)) elif s in op_map: op_stack.append(op_map[s]) elif s == ')': y, x = val_stack.pop(), val_stack.pop() op = op_stack.pop() val_stack.append(op(x, y)) else: raise # assert len(op_stack) == 0 assert len(val_stack) == 1 return val_stack.pop() def test(): test_expression = '( 2 + ( 5 * 4 ) )' print test_expression print '\t=', evaluate_infix_expression(test_expression) pass if __name__ == '__main__': test()
#!/usr/bin/env python ''' http://interactivepython.org/runestone/static/pythonds/Trees/heap.html https://en.wikipedia.org/wiki/Binary_heap Binary Heaps have 2 neat properties/requirements: - shape property. the tree is a complete binary tree. - Heap property. all nodes are either greater than or equal to or less than or equal to each of its children, according to a comparison predicate defined for the heap. Can convert a list into a heap in linear time: - start at the middle element - call percolate_down() - decrement i - TODO: think about why this works. something to do with the binary tree structure and that percolation calls always pick the extremal child ''' class BinaryHeap: ''' binary min-heap implementation ''' def __init__(self): self.heapList = [0] self.currentSize = 0 def percUp(self,i): while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: tmp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = tmp i = i // 2 def insert(self,k): self.heapList.append(k) self.currentSize = self.currentSize + 1 self.percUp(self.currentSize) def percDown(self,i): while (i * 2) <= self.currentSize: mc = self.minChild(i) if self.heapList[i] > self.heapList[mc]: tmp = self.heapList[i] self.heapList[i] = self.heapList[mc] self.heapList[mc] = tmp i = mc def minChild(self,i): if i * 2 + 1 > self.currentSize: return i * 2 else: if self.heapList[i*2] < self.heapList[i*2+1]: return i * 2 else: return i * 2 + 1 def delMin(self): retval = self.heapList[1] self.heapList[1] = self.heapList[self.currentSize] self.currentSize = self.currentSize - 1 self.heapList.pop() self.percDown(1) return retval def buildHeap(self,alist): i = len(alist) // 2 self.currentSize = len(alist) self.heapList = [0] + alist[:] while (i > 0): self.percDown(i) i = i - 1 def test(): ''' ''' # test data a0 = (9,5,6,2,3) # heapify bh = BinaryHeap() bh.buildHeap(list(a0)) # test printing print print 'test data:', a0 print 'as a heap:', bh.heapList print print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) print if __name__ == '__main__': test()
''' Simple main routine for `awspricingfull` module. Call the class corresponding to your needs (EC2Prices(), RDSPrices(), etc.), and use any method with parameters needed. See the awspricingfull documentation for reference. In a nutshell: To save CSV use save_csv method for instance of any of the functional classes (EC2Prices() - EC2, RDSPrices() - RDS, ELCPrices() - ElastiCache, RSPrices() - Redshift, DDBPrices() - DynamoDB). With save_csv use "reserved" or "ondemand" as first parameter, your path as second (home dir by default) and file name as third (conventional default). Also, to save prices for all the products use AllAWSPrices() class and same save_csv method with small difference - you can set the first parameter to "all" which will return all the pricing (reserved and on-demand for all the services). Method print_table is available for EC2Prices(), RDSPrices(), ELCPrices(), RSPrices(), DDBPrices(). It outputs the pricing in a table format to console. Prettytable library is required. Method takes only one parameter: "reserved" or "ondemand". Not available for AllAWSPrices(). Method print_json is available for all classes. It returns the pricing in a JSON format and does not output it to console. Method takes only one parameter: "reserved" or "ondemand" and additional "all" for AllAWSPrices(). Created: Mar 26, 2015 Updated: Feb 14, 2017 @author: Ilia Semenov @version: 3.2 ''' import awspricingfull if __name__ == '__main__': ''' 1. Create 1nstance of the class needed: EC2Prices() - EC2, RDSPrices() - RDS, ELCPrices() - ElastiCache, RSPrices() - Redshift, DDBPrices - DynamoDB, AllAWSPrices() - full pricing. 2. Run the method needed: return_json, print_table, save_csv. ''' ''' FULL PRICING ''' allpricing=awspricingfull.AllAWSPrices2() #Full Pricing class instance #print (allpricing.return_json("ondemand")) #JSON - On-Demand Pricing: All Services #print (allpricing.return_json("reserved")) #JSON - Reserved Pricing: All Services #print (allpricing.return_json("all")) #JSON - Full Pricing: All Services #allpricing.save_csv("ondemand") #CSV - On-Demand Pricing: All Services #allpricing.save_csv("reserved") #CSV - Reserved Pricing: All Services allpricing.save_csv("all") #CSV - Full Pricing: All Services ''' EC2 ''' ec2pricing=awspricingfull.EC2Prices() #EC2 Pricing class instance #print (ec2pricing.return_json("ondemand")) #JSON - On-Demand Pricing: EC2 #print (ec2pricing.return_json("reserved")) #JSON - Reserved Pricing: EC2 #ec2pricing.print_table("ondemand") #PrettyTable - On-Demand Pricing: EC2 #ec2pricing.print_table("reserved") #PrettyTable - Reserved Pricing: EC2 #ec2pricing.save_csv("ondemand") #CSV - On-Demand Pricing: EC2 #ec2pricing.save_csv("reserved") #CSV - Reserved Pricing: EC2 ''' RDS ''' rdspricing=awspricingfull.RDSPrices() #RDS Pricing class instance #print (rdspricing.return_json("ondemand")) #JSON - On-Demand Pricing: RDS #print (rdspricing.return_json("reserved")) #JSON - Reserved Pricing: RDS #rdspricing.print_table("ondemand") #PrettyTable - On-Demand Pricing: RDS #rdspricing.print_table("reserved") #PrettyTable - Reserved Pricing: RDS #rdspricing.save_csv("ondemand") #CSV - On-Demand Pricing: RDS #rdspricing.save_csv("reserved") #CSV - Reserved Pricing: RDS ''' ELASTICACHE ''' elcpricing=awspricingfull.ELCPrices() #ElastiCache Pricing class instance #print (elcpricing.return_json("ondemand")) #JSON - On-Demand Pricing: ElastiCache #print (elcpricing.return_json("reserved")) #JSON - Reserved Pricing: ElastiCache #elcpricing.print_table("ondemand") #PrettyTable - On-Demand Pricing: ElastiCache #elcpricing.print_table("reserved") #PrettyTable - Reserved Pricing: ElastiCache #elcpricing.save_csv("ondemand") #CSV - On-Demand Pricing: ElastiCache #elcpricing.save_csv("reserved") #CSV - Reserved Pricing: ElastiCache ''' REDSHIFT ''' rspricing=awspricingfull.RSPrices() #Redshift Pricing class instance #print (rspricing.return_json("ondemand")) #JSON - On-Demand Pricing: Redshift #print (rspricing.return_json("reserved")) #JSON - Reserved Pricing: Redshift #rspricing.print_table("ondemand") #PrettyTable - On-Demand Pricing: Redshift #rspricing.print_table("reserved") #PrettyTable - Reserved Pricing: Redshift #rspricing.save_csv("ondemand") #CSV - On-Demand Pricing: Redshift #rspricing.save_csv("reserved") #CSV - Reserved Pricing: Redshift ''' DYNAMODB ''' ddbpricing=awspricingfull.DDBPrices() #DynamoDB Pricing class instance #print (ddbpricing.return_json("ondemand")) #JSON - On-Demand Pricing: DynamoDB #print (ddbpricing.return_json("reserved")) #JSON - Reserved Pricing: DynamoDB #ddbpricing.print_table("ondemand") #PrettyTable - On-Demand Pricing: DynamoDB #ddbpricing.print_table("reserved") #PrettyTable - Reserved Pricing: DynamoDB #ddbpricing.save_csv("ondemand") #CSV - On-Demand Pricing: DynamoDB #ddbpricing.save_csv("reserved") #CSV - Reserved Pricing: DynamoDB