text
stringlengths
37
1.41M
""" Solution for Algorithms #412: Fizz Buzz - Time Complexity: O(N) - Space Complexity: O(N) Runtime: 52 ms, faster than 90.93% of Python3 online submissions for Fizz Buzz. Memory Usage: 14.1 MB, less than 78.99% of Python3 online submissions for Fizz Buzz. """ class Solution: def fizzBuzz(self, n: int) -> List[str]: output = [0] * n for i in range(1, n+1): if i % 15 == 0: output[i-1] = 'FizzBuzz' elif i % 3 == 0: output[i-1] = 'Fizz' elif i % 5 == 0: output[i-1] = 'Buzz' else: output[i-1] = str(i) return output
""" Set + Filter solution for Algorithms #301: Remove Invalid Parentheses - Space Complexity: O(N) - Time Complexity: O(2^N) Runtime: 284 ms, faster than 26.67% of Python3 online submissions for Remove Invalid Parentheses. Memory Usage: 14 MB, less than 13.95% of Python3 online submissions for Remove Invalid Parentheses. """ class Solution: def _is_valid(self, candidate): if not candidate: return False # We will add it manually if needed count = 0 for c in candidate: if c == '(': count += 1 if c == ')': count -= 1 if count < 0: return False return count == 0 def removeInvalidParentheses(self, s: str) -> List[str]: # It's a Set (Unique elements) + Queue (FIFO) candidate_set = {s} output = [] while candidate_set: # Check if the candidate_set has any valid candidates valid_candidates = list(filter(self._is_valid, candidate_set)) if valid_candidates: return valid_candidates else: candidate_set = {candidate[:i] + candidate[i+1:] for candidate in candidate_set for i in range(len(candidate))} # If nothing is found, removing all parentheses is always a valid solution # ex) ')(a' -> 'a' return output if output else [''.join([c for c in s if c not in '()'])]
""" Solution for Algorithms #20: Valid Parentheses Runtime: 36 ms, faster than 87.97% of Python3 online submissions for Valid Parentheses. Memory Usage: 13.2 MB, less than 5.22% of Python3 online submissions for Valid Parentheses. """ class Solution: def isValid(self, s: str) -> bool: paren_stack = [] for c in s: if c in ['(', '{', '[']: paren_stack.append(c) elif c == ')': if not paren_stack or paren_stack[-1] != '(': return False else: del paren_stack[-1] elif c == '}': if not paren_stack or paren_stack[-1] != '{': return False else: del paren_stack[-1] elif c == ']': if not paren_stack or paren_stack[-1] != '[': return False else: del paren_stack[-1] return (not paren_stack)
class Solution: def reverse(self, x: int) -> int: x_str = str(x) reversed_x_str = x_str[::-1] if reversed_x_str[-1] == '-': reversed_x = -1 * int(reversed_x_str[:-1]) else: reversed_x = int(reversed_x_str) if reversed_x < - (2 ** 31) or reversed_x > 2 ** 31 - 1: return 0 else: return reversed_x
""" Solution for July LeetCoding Challenges Week 4 Day 5: Add Digits """ class Solution: """ Repeat until the number is less than 10. Space : O(1) ------------ Nothing taking up space other than a few variables. Time : ? ----------- Difficult to determine. Runtime: 24 ms / 97.30% Memory Usage: 13.5 MB / 99.60% """ def step(self, num: int) -> int: new_num = sum(int(c) for c in str(num)) return new_num def addDigits(self, num: int) -> int: while num >= 10: num = self.step(num) return num
""" Solution for August LeetCoding Challenges Week 3 Day 5: Numbers With Same Consecutive Differences """ from collections import deque class Solution: """ Use BFS to append digits one by one. Space : O(2^N) ------------ At any time, the BFS queue only holds sequences that are either length L or L+1 for some L. Therefore, it is biggest when L+1 = N, so it holds at most 2^{N-1} + 2^N elements. Time : O(N 2^N) ----------- There are 2^N potential sequences of length N, and it takes N time to build each sequence. Runtime: 48 ms / 56.74% Memory Usage: 14 MB / 60.00% """ def _is_valid(self, num: int) -> bool: return 0 <= num and num <= 9 def numsSameConsecDiff(self, N: int, K: int) -> List[int]: if N == 1: return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] if K == 0: return [ "1" * N, "2" * N, "3" * N, "4" * N, "5" * N, "6" * N, "7" * N, "8" * N, "9" * N, ] output = set() d = deque([[1], [2], [3], [4], [5], [6], [7], [8], [9]]) while d: if len(d[0]) == N: break seq = d.popleft() if self._is_valid(seq[-1] + K): new_seq = seq.copy() new_seq.append(seq[-1] + K) d.append(new_seq) if self._is_valid(seq[-1] - K): new_seq = seq.copy() new_seq.append(seq[-1] - K) d.append(new_seq) return ["".join(str(digit) for digit in seq) for seq in d]
""" Solution for Algorithms #238: Product of Array Except Self. - N: Length of `nums` - Space Complexity: O(1) - Excluding the output array - Time Complexity: O(N) Runtime: 92 ms, faster than 98.49% of Python3 online submissions for Product of Array Except Self. Memory Usage: 20.8 MB, less than 11.10% of Python3 online submissions for Product of Array Except Self. """ class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: products = [] last_left_product = 1 for i in range(0, len(nums)): products.append(last_left_product) last_left_product *= nums[i] last_right_product = 1 for i in range(len(nums)-1, -1, -1): products[i] *= last_right_product last_right_product *= nums[i] return products
""" Dynamic programming solution for Algorithms #139 (Word Break). - N: len(s) - Space Complexity: O(N) - Time Complexity: O(N^3) - Substring operation: O(N) Runtime: 32 ms, faster than 99.04% of Python3 online submissions for Word Break. Memory Usage: 12.9 MB, less than 99.29% of Python3 online submissions for Word Break. """ class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: # Edge cases if not s: return True if not wordDict: return False # For faster search, use Dict instead of List wordDict = {word: None for word in wordDict} # If dp[i] == True, s[:dp[i]] can be word-broken # NOTE: We want to find dp[len(s)], so the size is len(s) + 1 dp = [False] * (len(s) + 1) dp[0] = True for i in range(1, len(s)+1): for j in range(i): if dp[j] and s[j:i] in wordDict: dp[i] = True break # NOTE: dp[i] defaults to False return dp[len(s)]
""" DoubleLinkedList + Dict Solution for Algorithms #146: LRU Cache - GET Time Complexity: O(1) - PUT Time Complexity: O(1) Runtime: 148 ms, faster than 36.82% of Python3 online submissions for LRU Cache. Memory Usage: 22 MB, less than 33.26% of Python3 online submissions for LRU Cache. """ class DoubleLinkedListNode: def __init__(self, key, val): self.key = key self.val = val self.prev_node = None self.next_node = None class DoubleLinkedList: def __init__(self): self.head = DoubleLinkedListNode(None, None) self.tail = DoubleLinkedListNode(None, None) self.head.next_node = self.tail self.tail.prev_node = self.head self.size = 0 def add(self, node: DoubleLinkedListNode): """ Add node on the left. """ node_after = self.head.next_node self.head.next_node = node node_after.prev_node = node node.prev_node = self.head node.next_node = node_after self.size += 1 def remove(self, node: DoubleLinkedListNode): """ Remove given node. """ node_before = node.prev_node node_after = node.next_node node_before.next_node = node_after node_after.prev_node = node_before self.size -= 1 def move_to_front(self, node: DoubleLinkedListNode): self.remove(node) self.add(node) def __str__(self): nodes = [] current = self.head while current is not None: nodes.append('({}, {})'.format(current.key, current.val)) current = current.next_node return 'Size: {} | '.format(self.size) + ' '.join(nodes) class LRUCache: def __init__(self, capacity: int): self.key_to_node_dict = {} self.key_list = DoubleLinkedList() self.capacity = capacity def get(self, key: int) -> int: # Edge case if not self.capacity: return -1 # print('GET {}: '.format(key)) # print('List: ', self.key_list) # print('Dict: ', list(self.key_to_node_dict.keys())) if key in self.key_to_node_dict: self.key_list.move_to_front(self.key_to_node_dict[key]) # print('List: ', self.key_list) # print('Dict: ', list(self.key_to_node_dict.keys())) return self.key_to_node_dict[key].val return -1 def put(self, key: int, value: int) -> None: # Edge case if not self.capacity: return # print('PUT {}->{}: '.format(key, value)) # print('List: ', self.key_list) # print('Dict: ', list(self.key_to_node_dict.keys())) if key in self.key_to_node_dict: self.key_list.move_to_front(self.key_to_node_dict[key]) self.key_to_node_dict[key].val = value else: if self.key_list.size == self.capacity: del self.key_to_node_dict[self.key_list.tail.prev_node.key] if self.key_list.size: self.key_list.remove(self.key_list.tail.prev_node) self.key_to_node_dict[key] = DoubleLinkedListNode(key, value) self.key_list.add(self.key_to_node_dict[key]) # print('List: ', self.key_list) # print('Dict: ', list(self.key_to_node_dict.keys())) # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
""" Solution for Algorithms #19: Remove Nth Node From End of List Double-pass. Runtime: 40 ms, faster than 92.06% of Python3 online submissions for Remove Nth Node From End of List. Memory Usage: 13.2 MB, less than 5.60% of Python3 online submissions for Remove Nth Node From End of List. """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: # Method 1: 1st pass to find length, 2nd pass to remove node current = head length = 1 while current.next is not None: current = current.next length += 1 print(length) # Edge case: Remove first element (length == n) if length == n: return head.next before_nth = head # The node before the node to remove for _ in range(length - n - 1): before_nth = before_nth.next before_nth.next = before_nth.next.next return head
""" Non-string-sorting solution for Algorithms #49: Group Anagrams. - N: Number of strings - K: Maximum length of strings - Space Complexity: O(NK) - Time Complexity: O(NK) - Generate key: O(K) Runtime: 128 ms, faster than 41.78% of Python3 online submissions for Group Anagrams. Memory Usage: 17.7 MB, less than 17.10% of Python3 online submissions for Group Anagrams. """ class Solution: def _get_key_from_str(self, s): # NOTE Probably could use Python Counter letter_counts = [0] * 26 for c in s: letter_counts[ord(c) - ord('a')] += 1 # return '.'.join([str(n) for n in letter_counts]) return tuple(letter_counts) def groupAnagrams(self, strs: List[str]) -> List[List[str]]: # Edge cases (len == 0 or 1) if not strs: return [] if len(strs) == 1: return [[strs[0]]] anagram_groups = {} for s in strs: key = self._get_key_from_str(s) if key in anagram_groups: anagram_groups[key].append(s) else: anagram_groups[key] = [s] return [v for _, v in anagram_groups.items()]
def turn(direction): """turns to the next wall""" if direction == "left": wall += 1 elif direction == "right": wall -= 1 else: invalid() if wall == 1: front() elif wall == 2: left() elif wall == 3: back() elif wall == 4: right() elif wall == 5: wall= 1 front() else: wall = 4 right() wall = 1 def change(direction): """turns to the next wall""" if direction == "left": return 1 elif direction == "right": return -1 elif direction == "none" return 0 else: invalid() wall += change(direction) def wall(): """prints wall description""" if wall == 1: front() elif wall == 2: left() elif wall == 3: back() elif wall == 4: right() elif wall == 5: wall= 1 front() else: wall = 4 right() def turn(direction): """turns to the next wall"""
#!/usr/bin/env python3 number=23 guess=int(input('Enter number:')) if guess==number: print('You WIN') print('Not priz') elif guess<number: print('Number>guess') else: print('number<guess') print('End GAME')
#!/usr/bin/env python3 def printMax(x, y): '''Print max from two number. Each may be INT.''' x=int(x) y=int(y) if x>y: print(x, 'max') else: print(y, 'max') printMax (3, 5) print (printMax.__doc__) help(printMax)
#!/usr/bin/env python3 age=26 name='Serhii' print('Age {0} -- {1} year.'.format(name, age)) print('Why {0} play this Python?'.format(name))
'''Python Programe to print fibonacci numbers from 1 to n "Buzz" when F(n) is divisible by 3. "Fizz" when F(n) is divisible by 5. "FizzBuzz" when F(n) is divisible by 15. "BuzzFizz" when F(n) is prime. the value F(n) otherwise. Author: Nisarg Pandya ([email protected]) ''' #Get two numbers from the user for the range. Two numbers are used for custom range example: 20 - 20000000 def fibo(): print "Program to print fibonacci numbers" print '"Buzz" when F(n) is divisible by 3' print '"Fizz" when F(n) is divisible by 5' print '"FizzBuzz" when F(n) is divisible by 15' print '"BuzzFizz" when F(n) is prime' print 'The value F(n) otherwise' #Get input from user, if input is not a positive integer, ask again for input from the user. while True: endNumber = raw_input("Enter the end number here: ") if endNumber >= 0 and endNumber.isdigit() == True: break else: print "Please provide positive integers only!!" endNumber = raw_input("Enter the end number here: ") #Function to check if the number is prime def isPrime(n): if n is 0: return False if n < 2: return False for i in range(2,int(n**0.5)+1): if n%i==0: return False return True #Local variables for generating the fibonacci sequence operation a,b=0,1 #Loop to generate fibonacci sequence along with requested prints while(a <= int(endNumber)): if a > 0 and a%15 is 0: print "FizzBuzz", elif a > 0 and a%3 is 0: print "Buzz", elif a > 0 and a%5 is 0: print "Fizz", elif a > 0 and isPrime(a): print "BuzzFizz", else: print a, a,b=b,a+b if __name__ == '__main__': fibo()
#!/usr/bin/python import math r1 = {'milk': 100, 'flour': 4, 'sugar': 10, 'butter': 5} r2 = {'milk': 100, 'butter': 50, 'cheese': 10} r3 = {'milk': 2, 'sugar': 40, 'butter': 20} l1 = {'milk': 1288, 'flour': 9, 'sugar': 95} l2 = dict([('milk', 198), ('butter', 50), ('cheese', 10), ]) l3 = {'milk': 5, 'sugar': 120, 'butter': 500} def recipe_batches(recipe, ingredients): # print recipe and larder print(f"recipe : {recipe}\n larder : {ingredients}\n") # establsh base case batches = 0 recipe_keys = [] larder_keys = [] recipe_items = [] larder_items = [] checker = [] # compare keys in recipe to keys in larder # if ingredient for recipe is missing, kill process # create new list from each of just keys for k, v in recipe.items(): recipe_keys.append(k) for k, v in ingredients.items(): larder_keys.append(k) for i in recipe_keys: if i not in larder_keys: print( f"we do not have {i} in the larder and cannot make this recipe") return batches # create new list of values in recipe # create new list of values in larder # compare values in recipe to values in larder # divide value in larder using integer division # and store it in a new list # once thats done, select minimum val # from list to get potential whole batches for k, v in recipe.items(): recipe_items.append(v) for k, v in ingredients.items(): larder_items.append(v) for i in range(len(larder_items)): checker.append(larder_items[i]//recipe_items[i]) print( f"larder_items[i] : {larder_items[i]}\nrecipe_items[i] : {recipe_items[i]}") batches = min(checker) print(f"recipe_items : {recipe_items}") print(f"larder_items : {larder_items}") print(f"checker : {checker}") # return batches return f"you have made {batches} whole batches!" # if __name__ == '__main__': # # Change the entries of these dictionaries to test # # your implementation with different inputs # recipe = {'milk': 100, 'butter': 50, 'flour': 5} # ingredients = {'milk': 132, 'butter': 48, 'flour': 51} # print("{batches} batches can be made from the available ingredients: {ingredients}.".format( # batches=recipe_batches(recipe, ingredients), ingredients=ingredients)) # test1 = recipe_batches(r1, l1) # print(test1) # test3 = recipe_batches(r3, l3) print(test3) # test2 = recipe_batches(r2, l2)
# Written: 01/31/2015 from fractions import Fraction from numbers import Number class Matrix(): """ Defines a Matrix Ryan Forsyth 2015 """ # Redefining Built-in Functions def __init__(self, values): """ Constructor for a matrix object. Pass in arguments as a 2D list. """ self.values = values self.m = len(self.values) # num_rows self.n = len(self.values[0]) # num_cols def __repr__(self): return str(self) def __str__(self): """ String representation of the matrix. """ string = "" for row in range(self.m): for col in range(self.n): value = self.values[row][col] valueString = str(value) string += takeNspaces(valueString, 5) + " " string += "\n" return string def __eq__(self, other): """ Equals Method """ for row in range(self.m): for col in range(self.n): if self.values[row][col] != other.values[row][col]: return False return True def __getitem__(self, num): """ Indexes the matrix. """ return self.values[num] # Copying a Matrix def copy(self): """ A deep copy of the matrix. """ newValues = [] for row in range(self.m): newEntries = [] for col in range(self.n): newEntries.append(self.values[row][col]) newValues.append(newEntries) return Matrix(newValues) # Operator overloading def __add__(self, other): """ Add two matrices """ return self.add(other) def __mul__(self, other): """ Multiply two matrices or multiply a matrix by a scalar. """ if isinstance(other, self.__class__): return self.matrixMultiply(other) elif isinstance(other, Number): return self.scalarMultiply(other) def __rmul__(self, other): """ Multiply a matrix by a scalar. """ if isinstance(other, Number): return self.scalarMultiply(other) # Identity def identity(n): """ The n x n identity matrix. """ values = [] for row in range(n): entries = [] for col in range(n): if row == col: entries.append(1) else: entries.append(0) values.append(entries) return Matrix(values) # Elementary Matrices def rowSwitchE(row1, row2, m): """ Elementary matrix for switching rows. """ I = Matrix.identity(m) return I.rowSwitch(row1, row2) def rowMultiplyE(row, weight, m): """ Elementary matrix for multiplying a row by a scalar. """ I = Matrix.identity(m) return I.rowMultiply(row, weight) def rowAddE(row1, row2, weight, m): """ Elementary matrix for adding a multiple of another row to a row. """ I = Matrix.identity(m) return I.rowAdd(row1, row2, weight) # Elementary Row Operations def rowSwitch(self, row1, row2): """ Elementary Row Operation Permute the matrix by switching row1 with row2 """ A = self.copy() row1 = row1 - 1 # zero-indexed row2 = row2 - 1 # zero-indexed for col in range(A.n): temp = A.values[row1][col] A.values[row1][col] = A.values[row2][col] A.values[row2][col] = temp return A def rowMultiply(self, row , weight): """ Elementary Row Operation Multiply row by weight """ A = self.copy() row = row - 1 # zero-indexed for col in range(A.n): A.values[row][col] = weight * A.values[row][col] return A def rowAdd(self, row1, row2, weight): """ Elementary Row Operation Add weight * row2 to row1 """ A = self.copy() row1 = row1 - 1 # zero-indexed row2 = row2 - 1 # zero-indexed for col in range(A.n): A.values[row1][col] = (A.values[row1][col] + weight * A.values[row2][col]) return A # Gaussian Elimination def ref(self, logger=False): """ Put the matrix into row echelon form """ A = self.copy() pivotRow = 0 for col in range(A.n): # For every column if pivotRow < A.m and A.values[pivotRow][col] == 0: # Short-circuit the operator switchTo = A.m while A.values[switchTo - 1][col] != 0 and pivotRow + 1 != switchTo: A = A.rowSwitch(pivotRow + 1, switchTo) switchTo -= 1 if logger: print(A) if pivotRow < A.m and A.values[pivotRow][col] != 0: for lowerRow in range(pivotRow + 1, A.m): weight = -1 * A.values[lowerRow][col] * Fraction(1, A.values[pivotRow][col]) A = A.rowAdd(lowerRow + 1, pivotRow + 1, weight) if logger: print(A) pivotRow += 1 return A def rref(self, logger=False): """ Put the matrix into reduced row echelon form """ A = self.ref(logger) pivotRow = A.m - 1 pivotCols = A.pivotCols() # Start from the right hand side pivotCols.reverse() for col in pivotCols: # For every pivot column col = col - 1 # Go back to zero indexing while pivotRow >= 0 and A.values[pivotRow][col] == 0: # Short-circuit the operator pivotRow -= 1 # Go up to the next row for upperRow in range(pivotRow - 1, -1, -1): weight = -1 * A.values[upperRow][col] * Fraction(1, A.values[pivotRow][col]) A = A.rowAdd(upperRow + 1, pivotRow + 1, weight) if logger: print(A) pivotRow -= 1 return A def specialrref(self, logger=False): """ Put the matrix into reduced row echelon form with 1s along the diagonal """ A = self.rref(logger) pivotCols = A.pivotCols() col = 0 for row in range(A.rank()): weight = Fraction(1, A.values[row][pivotCols[col] - 1]) # Go back to zero-indexing A = A.rowMultiply(row + 1, weight) if logger: print(A) col += 1 return A def pivotCols(self): """ Determine where the pivot columns are. """ pivotCols = [] A = self.ref() # Pivots will be first non-zero entry in each row col = 0 for row in range(A.m): while col < A.n and A.values[row][col] == 0: # short-circuit the operator col += 1 if col < A.n: pivotCols.append(col + 1) # zero-indexed return pivotCols def rank(self): """ The rank of the matrix. """ return len(self.pivotCols()) # The inverse def inverse(self): """ The inverse of the current matrix. """ A = self.copy() if A.m != A.n: raise MatrixException("Non-Square Matrix!") I = Matrix.identity(A.n) AI = A.augment(I) AI = AI.specialrref() split = AI.split(A.n) if (split[0] == I): return split[1] else: raise MatrixException("Not invertible!") # The transpose def transpose(self): """ The transpose of the current matrix. A m x n => A* n x m """ A = self.copy() rows = [] for col in range(A.n): entries = [] for row in range(A.m): entries.append(A.values[row][col]) rows.append(entries) return Matrix(rows) # The determinant def determinant(self): """ See Lay's textbook p. 165 The determinant of the current matrix. """ A = self.copy() if A.m != A.n: raise MatrixException("Non-Square Matrix!") elif A.n == 1: return A.values[0][0] else: det = 0 for j in range(1, A.n + 1): w1 = (-1) ** (1 + j) w2 = A.values[0][j - 1] # account for zero-indexing w3 = A.subMatrix(1, j).determinant() det += w1 * w2 * w3 return det def subMatrix(self, rowRemoved, colRemoved): """ Remove the row and column from this matrix """ # Get back to zero-indexing rowRemoved -= 1 colRemoved -= 1 A = self.copy() rows = [] for row in range(A.m): if row != rowRemoved: entries = [] for col in range(A.n): if col != colRemoved: entries.append(A.values[row][col]) rows.append(entries) return Matrix(rows) # Matrix Operations def add(self, B): """ Adds two matrices """ A = self.copy() if A.m != B.m or A.n != B.n: raise MatrixException("These matrices cannot be added!") for row in range(A.m): for col in range(A.n): A.values[row][col] += B.values[row][col] return A def scalarMultiply(self, c): """ Multiplies a matrix by a scalar """ A = self.copy() for row in range(A.m): for col in range(A.n): A.values[row][col] *= c return A def matrixMultiply(self, B): """ Multiplies two matrices A m x n B n x r => C m x r """ A = self.copy() if A.n != B.m: raise MatrixException("These matrices cannot be multiplied!") values = [] for row in range(A.m): entries = [] for col in range(B.n): # Applied Linear Algebra by Olver p.6 entry = 0 for k in range(A.n): entry += A.values[row][k] * B.values[k][col] entries.append(entry) values.append(entries) return Matrix(values) # Adding columns, splitting columns def augment(self, b): """ Augments the matrix by adding columns. """ A = self.copy() if not A.m == b.m: raise MatrixException("The matrices do not have the same number of rows") rows = [] for row in range(A.m): # for every row of self newRow = A.values[row] for col in range(b.n): newRow.append(b.values[row][col]) rows.append(newRow) A.n += b.n # increase the number of columns A.values = rows return A def split(self, lastN): """ Splits the matrix into two matrices. One m x (n - N) One m x N """ A = self.copy() rows1 = [] rows2 = [] for row in range(A.m): newRow1 = [] for col in range(A.n - lastN): newRow1.append(A.values[row][col]) rows1.append(newRow1) newRow2 = [] for col in range(A.n - lastN, A.n): newRow2.append(A.values[row][col]) rows2.append(newRow2) return (Matrix(rows1), Matrix(rows2)) class MatrixException(Exception): pass # Stand - Alone Function def takeNspaces(string, N): """ Makes sure a string takes up N spaces. """ l = len(string) s = N - l # The number of blank spaces needed newString = "" for i in range(s): newString += " " newString += string return newString
# -*- coding: utf-8 -*- name = str(raw_input('What\'s your name? ')) print('Hello, ' + name + '!!')
##print("What is your name?") ##name = input() ##print("Hello " + name + "!") ## ##print("How many states are in the USA?") ##answer = input() ##if answer == "50": ## print("Correct!") ##else: ## print("WRONG!!!!!") ## ##print("How old are you?") ##age = input() ##if age == "18": ## print("You are an adult now! Yay!") ##print("Cool!") # This is an example of a while loop correct_number = 7 print("I'm thinking of a number between 1 and 10! Guess it!") guess_number = int(input()) while guess_number != correct_number: if guess_number < correct_number: print("Too low. Try again!") else: print("Too high. Try again!") guess_number = int(input()) print("You got it!") name = "Aaron" print("Hello {}! How are you today?".format(name)) print("Hello world!")
#!/usr/bin/python3 """Test this host's Internet connection. Returns 0 if Internet is reachable""" import requests def test_web(url): """Return True if a HTTP GET request of the URL returns a 200 code.""" r = requests.get(url) return r.status_code == requests.codes.OK def test_ping(host): """Return True if ping to the host is successful.""" return True def test_dns(hostname, server): """Return True if the hostname is resolved by the dns server.""" return True def test_webs(): """Test a number of websites.""" urls = ( 'http://www.msftncsi.com/ncsi.txt', 'http://www.something.com', 'https://eff.org', ) #Start with the number of URLs to test and subtract 1 for each successful test. success = len(urls) for url in urls: if test_web(url): success -= 1 if success == 0: return True def test_pings(): hosts = ( 'www.something.com', ) return True def test_dnss(): hostnames = ( 'www.something.com', ) servers = ( '8.8.8.8', ) return True def main(): # All tests must pass test = test_webs() and test_pings() and test_dnss() if test: exit(0) else: exit(1) if __name__ == "__main__": main()
import sys numeralValues = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } def numeralToDecimal(numeral): total = 0 lastValue = 0 for symbol in reversed(numeral): currentValue = numeralValues[symbol] if lastValue > currentValue: total -= currentValue else: total += currentValue lastValue = currentValue return total descendingNumerals = ['M','D','C','L','X','V','I'] validPrecedingCharacters = { 'I': [], 'V': ['I'], 'X': ['I'], 'L': ['V','X'], #I'm going to assume V is a valid preceding character of L 'C': ['X'], #it wasn't clear in the spec 'D': ['L','C'], 'M': ['C'] } def decimalToNumeral(decimal): finalString = '' i = 0 while decimal > 0: currentNumeral = descendingNumerals[i] #First try subtracting the whole value of the current numeral if decimal - numeralValues[currentNumeral] >= 0: finalString += currentNumeral decimal -= numeralValues[currentNumeral] else: #Try subtracting partial values of the current numeral. For example IX or XC addedToString = False for character in validPrecedingCharacters[currentNumeral]: if decimal - (numeralValues[currentNumeral] - numeralValues[character]) >= 0: finalString += character + currentNumeral decimal -= (numeralValues[currentNumeral] - numeralValues[character]) addedToString = True #if we did not add to the string, move on to the next smallest numeral if not addedToString: i += 1 return finalString def testFunctions(): for i in range(10000): if i != numeralToDecimal(decimalToNumeral(i)): print("Conversion did not work with number " + str(i) + "!") def isRomanNumeral(testString): for character in testString: if character not in descendingNumerals: return False return True if __name__ == '__main__': if len(sys.argv) <= 1: print("Please enter a valid positive integer or Roman numeral as an argument") exit(0) if sys.argv[1].isnumeric(): number = int(sys.argv[1]) print("Roman Numeral- ") print(decimalToNumeral(number)) elif isRomanNumeral(sys.argv[1]): print("Decimal- ") print(numeralToDecimal(sys.argv[1])) else: print("Please enter a valid positive integer or a Roman numeral (MDCLXVI)")
def my_min(*args): result = args[0] for num in args: if num < result: result = num return result print(my_min(4, 3, 2, 1))
import pandas as pd import numpy as np import plotly.express as px class DrawManager(): def __init__(self): pass def create_fig(self,df,df_attribute = []): if df_attribute == []: df_melt = df.melt(id_vars=["Datum", "Tid (UTC)"], value_vars=df.columns[2]) #supposed the first column is day and second is time, the thrid, or [2], is the first with data in it fig = px.line(df_melt, x="Time", y="value") else: df_melt = df.melt(id_vars=["Datum", "Tid (UTC)"], value_vars=df_attribute) fig = px.line(df_melt, x="Time" , y="value") return fig if __name__ == __main__: pass
# PPHA 30535 # Spring 2021 # Homework 1 # Zachary Obstfeld # ZacharyObstfeld # Due date: Sunday April 11th before midnight # Write your answers in the space between the questions, and commit/push only this file to your repo. # Note that there can be a difference between giving a "minimally" right answer, and a really good # answer, so it can pay to put thought into your work. ############# # Question 1: Using a for loop, write code that takes in any list of objects, then prints out: # "The value at position __ is __" for every element in the loop, where the first blank is the # index location and the second blank the object at that index location. my_list = ['a', 'b', 'C'] index = 0 for item in my_list: print('The value at position ' + str(index) + ' is ' + str(item)) index += 1 # Question 2: A palindrome is a word or phrase that is the same both forwards and backwards. Write # code that takes a variable of any string, then tests to see whether it qualifies as a palindrome. # Make sure it counts the word "radar" and the phrase "A man, a plan, a canal, Panama!", while # rejecting the word "Apple" and the phrase "This isn't a palindrome". Print the results. my_string = 'Hanna' my_string = 'Hannah' palindrome = my_string.lower()[::-1] if palindrome == my_string.lower(): print('This is a palindrome') else: print("This isn't a palindrome") # Question 3: The code below pauses to wait for user input, before assigning the user input to the # variable. Beginning with the given code, check to see if the answer given is an available # vegetable. If it is, print that the user can have the vegetable and end the bit of code. If # they input something unrecognized by our list, tell the user they made an invalid choice and make # them pick again. Repeat until they pick a valid vegetable. available_vegetables = ['carrot', 'kale', 'radish', 'pepper'] choice = input('Please pick a vegetable I have available: ') while choice != 'carrot' or choice != 'kale' or choice != 'radish' or choice != 'pepper': if choice == 'carrot' or choice == 'kale' or choice == 'radish' or choice == 'pepper': print('nice veggie, you can have it') break else: print('You have made an invalid choice!') choice = input('Please pick a vegetable I have available: ') # Question 4: Write a list comprehension that starts with any list of strings, and returns a new # list that contains each string in all lower-case letters, but only if the string begins with the # letter "a" or "b". my_list = ['aH', 'B'] lower_and_conditional= [item.lower() for item in my_list if item[0] == 'a' or item[0] == 'b'] lower_and_conditional # Question 5: Beginning with the list below, write a single list comprehension that turns it into # the following list: [26, 22, 18, 14, 10, 6] #Source: https://www.geeksforgeeks.org/python-double-each-list-element/ #learn difference between .reverse() method and reversed() function start_list = [3, 5, 7, 9, 11, 13] rlist = [item * 2 for item in reversed(start_list)] # Question 6: Beginning with the two lists below, write a single dictionary comprehension that # turns them into the following dictionary: {'IL':'Illinois', 'IN':'Indiana', 'MI':'Michigan', 'OH':'Ohio'} # Source: https://www.geeksforgeeks.org/python-dictionary-comprehension/ short_names = ['IL', 'IN', 'MI', 'OH'] long_names = ['Illinois', 'Indiana', 'Michigan', 'Ohio'] new_dict = { k:v for (k,v) in zip(short_names, long_names)}
''' Finding the longest common prefix ''' def LCP(arr): if arr is None: return "" pre = arr[0] for i in range(1, len(arr)): while arr[i].find(pre) != 0: pre = pre[0: len(pre) - 1] if len(pre) == 0 : return "" return pre def findDuplicate(nums): """ :type nums: List[int] :rtype: int """ low = 1 high = len(nums)-1 while low < high: mid = low+(high-low)//2 count = 0 for i in nums: if i <= mid: count+=1 if count <= mid: low = mid+1 else: high = mid return low if __name__ == "__main__": print(LCP(["flow", "Glower", "flight"])) print(findDuplicate([1,4,6,6,6,2,3]))
''' Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example: Input: 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 https://leetcode.com/problems/happy-number/discuss/56913/Beat-90-Fast-Easy-Understand-Java-Solution-with-Brief-Explanation ''' class Solution: def isHappy(self, n: int) -> bool: if n == 0: return False h_set = set() while n not in h_set: h_set.add(n) sq_sum = 0 while n > 0: r = n % 10 sq_sum += (r * r) n //= 10 if sq_sum == 1: return True else: n = sq_sum return False def reverseBits(self, n): res = 0 for _ in range(32): res = (res<<1) + (n&1) n>>=1 return res
# Course Schedule # A collection of courses at a University has prerequisite courses that must be taken first. Given an # array of course pairs [a, B] where A is the prerequisite of B, determine a valid sequence of courses # a student can take to complete all the courses # Parameters # Input: courses [[String]] # Output: [String] # Examples # [[a, b], [a, c], [b, d], [c, d]] --> [a, b, c, d] || [a, c, b, d] # # Example: # # Input: [["a","b"],["a","c"],["b","d"],["c","d"]] # Output: ["a","b","c","d"] or ["a","c","b","d"] # # Input: [["a","b"],["b","c"],["c","d"]] # Output: ["a","b","c","d"] """ - B - D a / - C Take a before B Take C take a first Take course D, take either B or C A: B or C - use my input to build a graph using adjacent list vertex: all the courses {a:[b, c], b:[d], c:[d], d:[]} ------------------------------------- wrapper(input) helper(dfs) callhelper(startvertex) results = [] visited = set() start vertex(a) call dfs(a) resutls = [d, c, b, a] (reverse) """ def dfs(vertex, graph, visited, results): if vertex in visited: return visited.add(vertex) for child in graph[vertex]: dfs(child, graph, visited, results) results.append(vertex) # [[a, b], [a, c], [b, d], [c, d]] def convertgraph(lists_courses): graph = {} for courses in lists_courses: vertex = courses[0] nei = courses[1] if vertex not in graph: graph[vertex] = [] if nei not in graph: graph[nei] = [] graph[vertex].append(nei) # graph ={'a':[b], 'b' = []} return graph def topologicalsort(graph): visited = set() results = [] for vertex in graph: dfs(vertex, graph, visited, results) # reverse the order of the sort seq = [] while len(results) > 0: seq.append(results.pop()) return seq if __name__ == "__main__": L = [['a', 'b'], ['a', 'c'], ['b', 'd'], ['c', 'd']] g = convertgraph(L) r = topologicalsort(g) print(r) G = [('a', 'd'), ('f', 'b'), ('b', 'd'), ('f', 'a'), ('d', 'c')] graph = topologicalsort(convertgraph(G)) print(graph)
def generatePascalTriangle(numRows): if numRows == 0: return [] S =[[1]] if numRows == 1: return S for i in range(1, numRows): temp = [1] for j in range(1, i): print(temp) val = S[i - 1][j - 1] + S[i - 1][j] temp.append(val) temp.append(1) S.append(temp) print(S) return S if __name__ == "__main__": generatePascalTriangle(6)
class HashTable: '''Hashtable implementation with python list using linear probing. Attributes: -_size: number of key-value entries in hashtable. -_slots: size allocated for key-value entries. Default value is 11 (integer). -_keys: list for key entries. -_values: list for value entries. ''' def __init__(self, slots=11): self._size = 0 self._slots = slots # should be treated as immutable self._keys = [None] * self._slots self._values = [None] * self._slots def _alpha(self): '''Computes the load factor of the Hashtable. Returns: load factor (float). ''' return self._size / self._slots # load factor n/m def _prehash(self, word): '''Computes the ascii equivalent of a String or character. Args: word: String/character to be converted Returns: Ascii equivalent (Integer) ''' sum = 0 for char in word: sum += ord(char) return sum def _hash(self, key): '''Computes the hash using the division method Args: key: String/Integer/Character. Should be immutale. Returns: Hash of the key (Integer) ''' if type(key) == str: val = self._prehash(key) return val % self._slots return key % self._slots def _rehash(self, oldhash): ''' Computes new hash when collision occurs. Uses linear probing. Args: oldhash: Previous hash (Integer) Returns: New hash (Integer) ''' return (oldhash + 1) % self._slots def add(self, key, value): '''Adds new key - value pair to map. Args: key: String/Integer/Character. Should be immutable. value: String/Integer/Character ''' hashVal = self._hash(key) # case 1: key doesn't exist if self._keys[hashVal] is None: self._keys[hashVal] = key self._values[hashVal] = value self._size += 1 else: # case 2: key exists; we update value if self._keys[hashVal] == key: self._values[hashVal] = value # case 3: key slot is occupied with another key; rehash until # you find new / rightful slot else: nHashVal = self._rehash(hashVal) while self._keys[nHashVal] is not None and \ self._keys[nHashVal] != key: nHashVal = self._rehash(nHashVal) if self._keys[nHashVal] == key: self._values[nHashVal] = value else: self._keys[nHashVal] = key self._values[nHashVal] = value self._size += 1 if self._alpha() >= 0.7: self._resize() def exists(self, key): '''Checks if key exists in Hashtable. Args: key: Immutable object (Integer/String/Character) Returns: Boolean - True if key exists and False if otherwise ''' success, hashVal = self._search(key) if success: return True else: return False def _search(self, key): '''Finds key in the hashtable. This is a helper method. Args: key: Immutable object (Integer/String/Character) Returns: Returns a tuple of a boolean and key's associated hashValue ''' hashVal = self._hash(key) stop = False data = None pos = hashVal while self._keys[pos] is not None and not stop: if self._keys[pos] == key: stop = True data = pos else: pos = self._rehash(pos) if pos == hashVal: stop = True if data: return stop, data else: return stop, data def get(self, key, default=None): '''Get the value associated to the key Args: key: Immutable object (Integer/String/Character) default: Value to return if Key not found. Default is None Returns: Value associated with key or default arg ''' success, hashVal = self._search(key) if success: return self._values[hashVal] else: return default def remove(self, key): ''' Deletes a key from the hashtable. Raises a KeyError if key doesn't exist ''' success, hashVal = self._search(key) if success: self._keys[hashVal] = False self._values[hashVal] = None self._size -= 1 elif self._alpha() <= 1 / 3: self._resize(True) else: raise KeyError('{0} not found'.format(key)) def __getitem__(self, key): '''Get the value associated to the key Args: key: Immutable object (Integer/String/Character) Returns: Value associated with key or raise a KeyError ''' success, hashVal = self._search(key) if success: return self._values[hashVal] else: raise KeyError('{0} not found'.format(key)) def __setitem__(self, key, value): '''Adds new key - value pair to map. Args: key: String/Integer/Character. Should be immutable. value: String/Integer/Character ''' self.add(key, value) def __delitem__(self, key): ''' Deletes a key from the hashtable. Raises a KeyError if key doesn't exist ''' self.remove(key) def _resize(self, shrink=False): '''Resize hashtable. Either expand or shrink. Args: shrink: Flag to indicate reduce hashtable slots ''' if shrink: self._slots = self._slots // 2 else: self._slots = self._slots * 2 oldKeys = self._keys oldVals = self._values self._keys = [None] * self._slots self._values = [None] * self._slots self._size = 0 for i, key in enumerate(oldKeys): if key is not None: self.add(key, oldVals[i]) else: continue def size(self): '''Returns the size of the hashtable ''' return self._size def __len__(self): '''Returns the size of the hashtable ''' return self._size # TODO: test methods, __repr__, __str__ methods
class Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ def findMid(start, end, nums): if start <= end: mid = (start + end) // 2 root = TreeNode(nums[mid]) root.left = findMid(start, mid - 1, nums) root.right = findMid(mid + 1, end, nums) return root import pdb; pdb.set_trace() return findMid(0, len(nums) - 1, nums) if __name__ == "__main__": print()
''' CTCI Q8.3: Finding the magic index in a sorted array ''' def magicIndex(arr): ''' Arr has no dupes. Time: O(n) ''' return getIndex(arr, 0, len(arr) - 1) def getIndex(arr, start, end): if end < start: return -1 mid = (start + end) // 2 if arr[mid] == mid: return mid elif arr[mid] > mid: return getIndex(arr, start, mid - 1) else: return getIndex(arr, mid + 1, end) def magic_index(arr): ''' arr has dupes ''' return get_index(arr, 0, len(arr) - 1) def get_index(arr, start, end): if end < start: return -1 mid = (start + end) // 2 if arr[mid] == mid: return mid left_index = min(mid - 1, arr[mid]) left = get_index(arr, start, left_index) if left >= 0: return left right_index = max(mid + 1, arr[mid]) return get_index(arr, right_index, end) if __name__ == "__main__": print(magicIndex([-40,-20,-1,1,2,3,5,7,9,12,13])) print(magic_index([-10,-5,2,2,2,3,4,5,9,12,13]))
def narcissistic(value): sum = 0 power = len(str(value)) for i in str(value): sum += int(i)**power if sum == value: return True else: return False
def to_weird_case(string): string_list = string.split(" ") weird_case = "" for word in string_list: for i in range(0,len(word)): if i%2 == 0: weird_case += word[i].upper() else: weird_case += word[i].lower() weird_case += " " return weird_case[:-1]
def ackermann(m, n): print('A({},{})'.format(m, n)) if m == 0: return n + 1 if n == 0: return ackermann(m - 1, 1) n2 = ackermann(m, n - 1) return ackermann(m - 1, n2) print(ackermann(2,2))
# This python file creates classes and methods to perform operations on vectors import math class Vectors: def __init__(self, coordinates): """ Initializing a vector with coordinates :param coordinates: represent the coordinates of the vector """ try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError("The coordinates must be non empty") except TypeError: raise TypeError("The coordinates must be an iterable") def __str__(self): return "Vector : {}".format(self.coordinates) def __eq__(self, v): return self.coordinates == v.coordinates @staticmethod def add_vectors(*all_vectors): """ Function to perform addition of vectors :param all_vectors: are all the vectors that have to be added up :return: a vector after performing the numerical addition """ new_vector_dimension = all_vectors[0].dimension new_vector = [0] * new_vector_dimension # Performing tuple addition for vector in all_vectors: new_vector = [x + y for x, y in zip(list(vector.coordinates), new_vector)] return Vectors(new_vector) @staticmethod def subtract_vectors(*all_vectors): """ Function to perform addition of vectors :param all_vectors: are all the vectors that have to be added up :return: a vector after performing the numerical addition """ sub_new_vector = list(all_vectors[0].coordinates) # Performing tuple addition for vector in all_vectors[1:]: sub_new_vector = [x - y for x, y in zip(sub_new_vector, list(vector.coordinates))] return Vectors(sub_new_vector) @staticmethod def scalar_multiply(input_vector, scalar): """ Function to perform scalar multiplication :param scalar: the scalar value with which the vector has to be multiplied with :param input_vector: the input vector :return: a new vector after the input vector is multiplied with the scalar value """ return Vectors(list(scalar * coordinate for coordinate in input_vector.coordinates)) def vector_magnitude(self): """ Function to compute a vector's magnitude :return: the magnitude of the vector """ return math.sqrt(sum([dimension ** 2 for dimension in self.coordinates])) def normalized_vector(self): """ Function to calculate and return a normalized vector for the given vector :return: a vector like this vector with unit magnitude and in the same direction """ return self.scalar_multiply(self, 1 / self.vector_magnitude()) def dot_product_two_vectors(self, input_vector): """ Function that calculates the dot product between this vector and the input vector :param input_vector: is a vector :return: the dot product ( a number ) """ return sum([x * y for x, y in zip(self.coordinates, input_vector.coordinates)]) def angle_between_two_vectors_radians(self, input_vector): """ Function to calculate the angle between 2 vectors :param input_vector: a vector :return: the angle this vector and the input vector in radians """ return math.acos(self.dot_product_two_vectors(input_vector) / (self.vector_magnitude() * input_vector.vector_magnitude())) def angle_between_two_vectors_in_degrees(self, input_vector): """ Function to calculate the angle between 2 vectors :param input_vector: a vector :return: the angle this vector and the input vector in degrees """ return math.degrees(self.angle_between_two_vectors_radians(input_vector)) def check_two_vectors_parallel(self, input_vector): """ Function to check if this vector is parallel to the input vector :param input_vector: a Vector :return: true, iff the input vector is parallel to this vector false, otherwise """ scalar = input_vector.coordinates[0] / self.coordinates[0] for self_coord, input_coord in zip(self.coordinates[1:], input_vector.coordinates[1:]): if input_coord / self_coord == scalar: continue else: return False return True def check_two_vectors_orthogonal(self, input_vector, tolerance=1e-10): """ Function to check if the given vector(input vector) is orthogonal with this vector :param tolerance: Check against a tolerance level to avoid wrong answers due to precision values :param input_vector: a Vector :return: true, iff the 2 vectors are orthogonal false, otherwise """ return abs(self.dot_product_two_vectors(input_vector)) < tolerance def projection_along_basis_vector(self, basis_vector): """ This function calculates the projection of this vector along the given basis vector :param basis_vector: is the basis vector which is assumed to be emanating from the origin :return: a projection of this vector along the basis vector """ # Note: that projection of this vector is same as v parallel # which is then equal to normalized basis vector multipled by magnitude of this vector normalized_basis_vector = Vectors.normalized_vector(basis_vector) weight = self.dot_product_two_vectors(normalized_basis_vector) return self.scalar_multiply(normalized_basis_vector, weight) def orthogonal_projection(self, basis_vector): """ Function to calculate the component of this vector along the orthogonal component of basis vector :param basis_vector: is the basis vector which is assumed to be emanating from the origin :return: component of this vector along the orthogonal component of basis vector """ return Vectors.subtract_vectors(self, self.projection_along_basis_vector(basis_vector)) def decompose_vectors(self, basis_vector): """ Function to decompose this vector into parallel and orthogonal vectors :param basis_vector: the given basis vector assumed to be emanating from the origin :return: 2 decomposed vectors """ return self.projection_along_basis_vector(basis_vector), self.orthogonal_projection(basis_vector) def cross_product_of_two_vectors(self, input_vector): """ Function to find the cross product of this vector with the input vector passed as parameter :param input_vector: a vector :return: a Vector after performing cross product """ x1, y1, z1 = self.coordinates[0], self.coordinates[1], self.coordinates[2] x2, y2, z2 = input_vector.coordinates[0], input_vector.coordinates[1], input_vector.coordinates[2] cross_list = [y1 * z2 - y2 * z1, x2 * z1 - x1 * z2, x1 * y2 - x2 * y1] return Vectors(cross_list) def area_of_parallelogram(self, input_vector): """ Function which returns the area of the parallelogram spanned by the 2 vectors :param input_vector: a vector :return: the area of the parallelogram """ return self.vector_magnitude() * Vectors.vector_magnitude(input_vector) * \ math.sin(self.angle_between_two_vectors_radians(input_vector)) def area_of_traingle_spanned(self, input_vector): """ Function which returns the area of the triangle spanned by the 2 vectors :param input_vector: a vector :return: the area of the triangle """ return 0.5 * self.area_of_parallelogram(input_vector) v1 = Vectors([8.218, -9.341]) v2 = Vectors([-1.129, 2.111]) v3 = Vectors([7.119, 8.215]) v4 = Vectors([-8.223, 0.878]) v5 = Vectors([1.671, -1.012, -0.318]) scalar_multiplier = 7.41 # print(Vectors.add_vectors(v1, v2)) # print(Vectors.subtract_vectors(v3, v4)) # print(Vectors.scalar_multiply(v5, scalar_multiplier)) v6 = Vectors([-0.221, 7.437]) v7 = Vectors([8.813, -1.331, -6.247]) # print(v6.vector_magnitude()) # print(v7.vector_magnitude()) v8 = Vectors([5.581, -2.136]) v9 = Vectors([1.996, 3.108, -4.554]) # print(v8.normalized_vector()) # print(v9.normalized_vector()) v10 = Vectors([7.887, 4.138]) v11 = Vectors([-8.802, 6.776]) # print(v10.dot_product_two_vectors(v11)) v12 = Vectors([-5.955, -4.904, -1.874]) v13 = Vectors([-4.496, -8.755, 7.103]) # print(v12.dot_product_two_vectors(v13)) v14 = Vectors([3.183, -7.627]) v15 = Vectors([-2.668, 5.319]) # print(v14.angle_between_two_vectors_radians(v15)) v16 = Vectors([7.35, 0.221, 5.188]) v17 = Vectors([2.751, 8.259, 3.985]) # print(v16.angle_between_two_vectors_in_degrees(v17)) v18 = Vectors([-7.579, -7.88]) v19 = Vectors([22.737, 23.64]) # print(v18.check_two_vectors_parallel(v19)) # print(v18.check_two_vectors_orthogonal(v19)) v20 = Vectors([-2.029, 9.97, 4.172]) v21 = Vectors([-9.231, -6.639, -7.245]) # print(v20.check_two_vectors_parallel(v21)) # print(v20.check_two_vectors_orthogonal(v21)) v22 = Vectors([-2.328, -7.284, -1.214]) v23 = Vectors([-1.821, 1.072, -2.94]) # print(v22.check_two_vectors_parallel(v23)) # print(v22.check_two_vectors_orthogonal(v23)) v24 = Vectors([3.039, 1.879]) b01 = Vectors([0.825, 2.036]) # print(v24.projection_along_basis_vector(b01)) v25 = Vectors([-9.88, -3.264, -8.159]) b02 = Vectors([-2.155, -9.353, -9.473]) # print(v25.orthogonal_projection(b02)) v26 = Vectors([3.009, -6.172, 3.692, -2.51]) b03 = Vectors([6.404, -9.144, 2.759, 8.718]) decomposed_vectors = v26.decompose_vectors(b03) parallel_component = decomposed_vectors[0] orthogonal_component = decomposed_vectors[1] # print(parallel_component.coordinates) # print(orthogonal_component.coordinates) v27 = Vectors([8.462, 7.893, -8.187]) v28 = Vectors([6.984, -5.975, 4.778]) # print(v27.cross_product_of_two_vectors(v28)) v29 = Vectors([-8.987, -9.838, 5.031]) v30 = Vectors([-4.268, -1.861, -8.866]) # print(v29.area_of_parallelogram(v30)) v31 = Vectors([1.5, 9.547, 3.691]) v32 = Vectors([-6.007, 0.124, 5.772]) # print(v31.area_of_traingle_spanned(v32)) v33 = Vectors([5, 5, 5]) v34 = Vectors([20, 30, 40]) print(v33.orthogonal_projection(v34))
#!python3 from prefixtreenode import PrefixTreeNode class PrefixTree: """PrefixTree: A multi-way prefix tree that stores strings with efficient methods to insert a string into the tree, check if it contains a matching string, and retrieve all strings that start with a given prefix string. Time complexity of these methods depends only on the number of strings retrieved and their maximum length (size and height of subtree searched), but is independent of the number of strings stored in the prefix tree, as its height depends only on the length of the longest string stored in it. This makes a prefix tree effective for spell-checking and autocompletion. Each string is stored as a sequence of characters along a path from the tree's root node to a terminal node that marks the end of the string. """ # Constant for the start character stored in the prefix tree's root node START_CHARACTER = '' def __init__(self, strings=None): """Initialize this prefix tree and insert the given strings, if any.""" # Create a new root node with the start character self.root = PrefixTreeNode(PrefixTree.START_CHARACTER) # Count the number of strings inserted into the tree self.size = 0 # Insert each string, if any were given if strings is not None: for string in strings: self.insert(string) def __repr__(self): """Return a string representation of this prefix tree.""" return f'PrefixTree({self.strings()!r})' def is_empty(self): """Return True if this prefix tree is empty (contains no strings). Runtime Complexity: O(1), because the lookup and comparision operations do not change in duration. """ return (self.size == 0) def contains(self, string): """Return True if this prefix tree contains the given string. Runtime Complexity: O(m), where m is the length of the string being searched. The runtime of this method scales asymptotically on the time it takes to traverse the tree, down the path of its longest string. """ node, length = self._find_node(string) return length == len(string) and node.is_terminal() def insert(self, string): """Insert the given string into this prefix tree. Runtime Complexity: O((nm) + (np)), where n is the size of the trie, m is the length of string being searched as we look for a duplicate, and p is the length of the string being nserted. This runtime depends on calling the contains() method. In the average case it will then also insert the new string, an operation which the runtime depends on thethe size of the trie (i.e. the number of strings already being stored) because will increase the time we spend looking amongst the children of the root node. Also, this second step depends on the length of the new string being added. """ # make sure the string not already in the tree if self.contains(string) is False: # find the node to start adding new letters from current_node, index = self._find_node(string) # for each index position in the string greater than index for i in range(index, len(string)): # returned, add a new child node of the node returned next_char = string[i] new_node = PrefixTreeNode(next_char) current_node.add_child(next_char, new_node) # then move the current node to its child current_node = new_node # mark the last node to be added as terminal current_node.terminal = True # increment size of the tree self.size += 1 def _find_node(self, string): """Return a pair containing the deepest node in this prefix tree that matches the longest prefix of the given string and the node's depth. The depth returned is equal to the number of prefix characters matched. Search is done iteratively with a loop starting from the root node. Runtime Complexity: The runtime of the is method linearly with the size of the string being search. This can be expressed as O(m), where m is the length of the longest string stored in the trie. """ # Match the empty string if len(string) == 0: return self.root, 0 # Start with the root node node = self.root # loop through the letters in string index = 0 # on each iteration see it that letter is a child of node while index < len(string) and node.has_child(string[index]) is True: # if it is, then move node to that child, and move to next char node = node.get_child(string[index]) index += 1 # return the pair of the node and the index return node, index def complete(self, prefix): """Return a list of all strings stored in this prefix tree that start with the given prefix string. Runtime Complexity: The runtime of this method depends on the length of the prefix given. If there are many possible strings to form based off the prefix, then the runtime depends on O(n * (m - prefix)), where n is the number of retrieved for completion, and (m - prefix) represents the number of strings that are yet to be found in each completed word. In the best case we are given a long prefix for the longest string in the trie, so there less strings we need to create completions of - in this case the runtime tends towards O(m - prefix). """ # Create a list of completions in prefix tree completions = [] # Make sure user is not looking for all strings if prefix == '': return self.strings() # init node to start traversal from node = self._find_node(prefix)[0] # if node has an empty string, there are no completions if node.character != '': self._traverse(node, prefix, completions.append) # add remove words equal to the prefix return completions def strings(self): """Return a list of all strings stored in this prefix tree. Runtime Complexity: This method performs a depth first traversal from the root, meaning that will have to visit all the nodes. This number will depend on the number of strings we have stored in the trie, as well as their lengths. This runtime will therefore grow asymptotically on the order of O(n * m), where n is the size of the trie, and m average length of the strings. """ # Create a list of all strings in prefix tree all_strings = [] self._traverse(self.root, '', all_strings.append) return all_strings def _traverse(self, node, prefix, visit): """Traverse this prefix tree with recursive depth-first traversal. Start at the given node with the given prefix representing its path in this prefix tree and visit each node with the given visit function. Runtime Complexity: The runtime of this method grows with respect to the number of strings we need to traverse, as well as the length of each of the strings. This will be give or take O(m * n), where m is the length of the longest string, and n is the number of retrieved strings. In the best case, the prefixes in the longest string will actually be the other, smaller strings, which will decrease the runtime by reducing the number of times we need to recursively invoke this method. In that scenario, the runtime tends towards O(m). """ if node.is_terminal() is True and len(node.children) == 0: # add the prefix phrase we've built so far visit(prefix) elif node.is_terminal() is True: # add the prefix phrase we've built so far, and keep moving down visit(prefix) for char in node.children.keys(): # move to the child node, continually build the string in traversal child = node.get_child(char) string = self._traverse(child, prefix + char, visit) def delete(self, key): """Removes all nodes containing letters of the given key to delete. Other keys whose keys are destroyed in the process are then re-inserted. Parameters: key(str): the entry being deleted from the trie. Returns: None Complexity Analysis: The runtime of this method asymptotically increases with the time it takes to check all strings in the tree, so that we know that the key is even a valid input. After that, we must also traverse the key to set the .terminal property of its last node to False, so that the whole string will no longer be found during depth first searches. The runtime of the second step asymptotically grows with the length of the key being deleted. Overall the runtime of this method can be expressed as O(k + (n * m)), where k is the length of the string being deleted, and (n * m) represents the time it takes to check if the input string is contained within the trie. In the worst case scenario, the key (aka string) being deleted is also the longest string in the data structure. """ if self.contains(key) is True: # O(m * n) # set the node at the end of key no longer signal end of a node last_node, depth = self._find_node(key[-1]) # O(m) last_node.terminal = False # decrement size of tree self.size -= 1 else: # key is not actually in the prefix tree raise ValueError('Word is not found and cannot be deleted.') def create_prefix_tree(strings): print(f'strings: {strings}') tree = PrefixTree() print(f'\ntree: {tree}') print(f'root: {tree.root}') print(f'strings: {tree.strings()}') print('\nInserting strings:') for string in strings: tree.insert(string) print(f'insert({string!r}), size: {tree.size}') print(f'\ntree: {tree}') print(f'root: {tree.root}') print('\nSearching for strings in tree:') for string in sorted(set(strings)): result = tree.contains(string) print(f'contains({string!r}): {result}') print('\nSearching for strings not in tree:') prefixes = sorted(set(string[:len(string)//2] for string in strings)) for prefix in prefixes: if len(prefix) == 0 or prefix in strings: continue result = tree.contains(prefix) print(f'contains({prefix!r}): {result}') print('\nCompleting prefixes in tree:') for prefix in prefixes: completions = tree.complete(prefix) print(f'complete({prefix!r}): {completions}') print('\nRetrieving all strings:') retrieved_strings = tree.strings() print(f'strings: {retrieved_strings}') matches = set(retrieved_strings) == set(strings) print(f'matches? {matches}') def main(): # Simpe test case of string with partial substring overlaps strings = ['ABC', 'ABD', 'A', 'XYZ'] create_prefix_tree(strings) # Create a dictionary of tongue-twisters with similar words to test with tongue_twisters = { 'Seashells': 'Shelly sells seashells by the sea shore'.split(), 'Peppers': 'Peter Piper picked a peck of pickled peppers'.split(), 'Woodchuck': ('How much wood would a wood chuck chuck' ' if a wood chuck could chuck wood').split() } # Create a prefix tree with the similar words in each tongue-twister for name, strings in tongue_twisters.items(): print(f'{name} tongue-twister:') create_prefix_tree(strings) if len(tongue_twisters) > 1: print('\n' + '='*80 + '\n') class RadixTree(PrefixTree): '''A compact prefix tree.''' pass if __name__ == '__main__': main()
#Matthew Beer #28/09/2014 #Revision exercise 4 - Selection num1 = int(input("Please enter a number ")) num2 = int(input("Please enter asecond number ")) if num1 > num2: print("The biggest number is {0}.".format(num1)) else: print("The biggest number is {0}.".format(num2))
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import matplotlib.pyplot as plt print('-'*10 + "Welcome to Data Vault" + '-'*10) print("\nThis is the original data") df=pd.read_csv("Data_Vault_Final1.csv") df # In[45]: # targetting only products # print("The below data only shows PRODUCTS column\n\n" ,df['products']) # Defining the variables x=df['type'] #df = pd.DataFrame(x) plt.xticks(rotation=45) plt.title('products vs type graph') plt.xlabel('TYPE') plt.ylabel('PRODUCTS') y = df['products'] # Plotting a graph of type vs products plt.plot(x,y, ) # In[26]: # targetting price and type x=df.loc[:,'type'] plt.xticks(rotation=45) plt.title('price vs type graph') plt.xlabel('TYPE') plt.ylabel('PRICE') y = df.loc[:,'price'] # Plotting a graph of type vs products plt.plot(x,y) print("The below data only shows TYPE vs PRICE columns\n\n" ,df[['price','type'] ]) # In[36]: # targetting type and quantity x=df.loc[:,'type'] plt.xticks(rotation=45) plt.title('type vs quantity graph') plt.xlabel('TYPE') plt.ylabel('quantity') y = df.loc[:,'quantity'] # Plotting a graph of type vs products plt.plot(x,y, 'g*-') print("The below data only shows PRODUCTS, type and quantity\n\n" ,df[['products','type', 'quantity'] ]) # In[90]: print(x[:3]) # this is a slice function to target #print(y[:3]) #plt.plot(x[:3]) # In[43]: # All data # print("The below data only shows PRODUCTS column\n\n" ,df['products']) # Defining the variables #x=df['type'] plt.xticks(rotation=45) plt.title('products vs type graph') plt.xlabel('TYPE') plt.ylabel('PRODUCTS') y = df['price'] # Plotting a graph of type vs products plt.hist(y, color='purple') #plt.plot(x,y) # In[32]: import pandas as pd import matplotlib.pyplot as plt import numpy as np #print('-'*10 + "Welcome to Data Vault" + '-'*10) print("\nThis is the original data") df=pd.read_csv("Data_Vault_Final.csv") #for index,row in df.iterrows(): #print(index,row) # In[8]: df.columns print(df[['type','price']]) # In[59]: df=pd.read_csv("Data_Vault_Final.csv") df1 = pd.DataFrame(df,index = [0,1,2,], columns = ['type', 'quantity', ]) plt.xticks(rotation=45) plt.title('TYPE vs QUANTITY graph') plt.xlabel('TYPE') plt.ylabel('QUANTITY') print(df1) x=df1.loc[:,'type'] y=df1.loc[:,'quantity'] plt.plot(x,y) # In[49]: df.columns # In[38]: df=pd.read_csv("Data_Vault_Final.csv") df1 = pd.DataFrame(df,index = [0,1,2,], columns = ['type', 'price', ]) df1.columns plt.xticks(rotation=45) plt.title('TYPE vs PRICE graph') plt.xlabel('TYPE') plt.ylabel('PRICE') print(df1) x=df1.loc[:,'type'] y=df1.loc[:,'price'] plt.grid('.') plt.plot(x,y) # In[93]: df=pd.read_csv("Data_Vault_Final.csv") #print(df) df2 = pd.DataFrame(df,index = [3,4,5,], columns = ['type', 'price', ]) print(df1.columns) plt.xticks(rotation=45) plt.title('TYPE vs PRICE graph') plt.xlabel('TYPE') plt.ylabel('PRICE') print(df1) x=df2.loc[:,'type'] y=df2.loc[:,'price'] df2['price'].plot(kind='bar') # In[41]: df=pd.read_csv("Data_Vault_Final.csv") #print(df) df2 = pd.DataFrame(df,index = [3,4,5,], columns = ['type', 'price', ]) plt.xticks(rotation=45) plt.title('TYPE vs PRICE bar graph') plt.xlabel('TYPE') print(df1) x=df2.loc[:,'type'] y=df2.loc[:,'price'] df2['price'].plot(kind='bar', color='purple') # In[46]: df=pd.read_csv("Data_Vault_Final.csv") df2 = pd.DataFrame(df,index = [9,10,11,], columns = ['type', 'price', ]) plt.xticks(rotation=45) plt.title('TYPE vs PRICE bar graph') plt.xlabel('TYPE') plt.ylabel('PRICE') print(df2) x=df2.loc[:,'type'] y=df2.loc[:,'price'] plt.grid('.') plt.scatter(x,y) # In[12]: import pandas as pd import matplotlib.pyplot as plt df=pd.read_csv("Data_Vault_Final.csv") df # In[45]: df3 = pd.DataFrame(df,index = [9,10,11,], columns = ['type','quantity' ]) plt.title('TYPE vs PRICE bar graph') plt.xlabel('TYPE') plt.ylabel('PRICE') x=df3.loc[:,'type'] y=df3.loc[:,'quantity'] #z=df3.loc['quantity'] plt.plot(x,y) # In[50]: import pandas as pd import matplotlib.pyplot as plt import numpy as np print('-'*10 + "Welcome to Data Vault" + '-'*10) print("\nThis is the original data") df=pd.read_csv("Data_Vault_Final.csv") x=df['type'] plt.xticks(rotation=45) plt.xlabel("TYPE") plt.ylabel("PRICE") y=df['price'] color = np.random.rand(15) plt.scatter(x,y, c=color) # In[48]: import pandas as pd import matplotlib.pyplot as plt df=pd.read_csv("Data_Vault_Final.csv") df3 = pd.DataFrame(df,index = [9,10,11,], columns = ['type','quantity' ]) plt.title('TYPE vs PRICE bar graph') plt.xlabel('TYPE') plt.ylabel('PRICE') x=df3.loc[:,'type'] y=df3.loc[:,'quantity'] plt.plot(x,y) # In[ ]:
import gspread from google.oauth2.service_account import Credentials SCOPE = [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive" ] CREDS = Credentials.from_service_account_file('livehealthy_creds.json') SCOPED_CREDS = CREDS.with_scopes(SCOPE) GSPREAD_CLIENT = gspread.authorize(SCOPED_CREDS) SHEET = GSPREAD_CLIENT.open('livehealthy') sales = SHEET.worksheet('p1') listsheet=SHEET.getsheet() print(listsheet) # worksheet = SHEET.add_worksheet(title="B worksheet", rows="100", cols="20") data = sales.get_all_values() print(data) print("\n\tHello") # def get_sales_data(): # """ # Get sales figures input from the user. # """ # print("Please enter sales data from the last market.") # print("Data should be six numbers, separated by commas.") # print("Example: 10,20,30,40,50,60\n") # data_str = input("Enter your data here: ") # print(f"The data provided is {data_str}") # get_sales_data() # def get_sales_data(): # """ # Get sales figures input from the user. # Run a while loop to collect a valid string of data from the user # via the terminal, which must be a string of 6 numbers separated # by commas. The loop will repeatedly request data, until it is valid. # """ # while True: # """ # Get sales figures input from the user. # """ # print("Please enter sales data from the last market.") # print("Data should be six numbers, separated by commas.") # print("Example: 10,20,30,40,50,60\n") # data_str = input("Enter your data here: ") # sales_data = data_str.split(",") # # validate_data(sales_data) # if validate_data(sales_data): # print("Data is valid!") # break # return sales_data # def validate_data(values): # """ # Inside the try, converts all string values into integers. # Raises ValueError if strings cannot be converted into int, # or if there aren't exactly 6 values. # """ # try: # [int(value) for value in values] # if len(values) != 6: # raise ValueError( # f"\nExactly 6 values required, \n\tyou provided {len(values)} \n\t\t \ # or \n\t\t\tthere is no (,) between the values" # ) # except ValueError as e: # print(f"Invalid data: {e}, please try again.\n") # return False # return True # def update_sales_worksheet(data): # """ # Update Sales Worksheet()add new row with the list provided # """ # print("Updating sales Worksheet\n") # sales_worksheet = SHEET.worksheet("measurements") # sales_worksheet.append_row(data) # print("Sales worksheet update successfully") # def main(): # """ # run all functions # """ # data = get_sales_data() # sales_data=[int(num) for num in data] # print(type(data)) # print(sales_data) # update_sales_worksheet(sales_data) # print("\nWelcome\n") # main()
import numpy as np import matplotlib.pyplot as plt import csv def estimate_coef(x,y): n=np.size(x) mean_x=np.mean(x) mean_y=np.mean(y) mean_xy=np.mean(x*y) mean_xx=np.mean(x*x) #ss_xy=np.sum(y*x-n*mean_x*mean_y) #ss_xx=np.sum(x*x-n*mean_x*mean_x) ss_xy=mean_x*mean_y-mean_xy ss_xx=mean_x*mean_x-mean_xx c_1=ss_xy/ss_xx c_0=mean_y - c_1*mean_x return(c_0,c_1) def plot_line(x,y,b): plt.scatter(x,y,color="m",marker="o",s=30) y_prediction=b[0] + b[1]*x plt.plot(x,y_prediction,color="g") plt.xlabel('Engine_size') plt.ylabel('Price') plt.show() def pred_err(x,y,b): y_pred=b[0]+b[1]*x pred=((y-y_pred)/y)*100 return np.mean(pred) def main(): #x=np.array([65.04851,63.25094,64.95532,65.75250,61.13723,63.02254]) #y=np.array([59.77827,63.21404,63.34242,62.79238,64.28113,64.24221]) #file=open("E:\Programming\Python\Learning\Automobile.csv","r") #f=file.read() #m=f.split(",") #with open('E:\Programming\Python\Learning\Automobile.csv', newline='') as f: # m = csv.reader(f) #m=[] # for x in f: # m.append(x.split(',')) #m.append(x.split(',')[1]) #file.close() #print(m) #eng_size = [] #price = [] #for d in csv.DictReader(open('E:\Programming\Python\Learning\Automobile.csv'), delimiter='\t'): #eng_size.append(int(d["Engine_size"])) #price.append(int(d["Price"])) f=open("E:\Programming\Python\Learning\Datasets\Automobile.csv","r") csv_f=csv.reader(f) p=[] q=[] for row in csv_f: p.append(float(row[0])) q.append(float(row[1])) x=np.array(p) y=np.array(q) #print(x) b=estimate_coef(x,y) print("The estimated price is ",b[0]+b[1]*s) print("Estimated coefficients:\nb_0 = {} \ \nb_1 = {}".format(b[0], b[1])) print("The prediction error rate is ",abs(pred_err(x,y,b)) ) plot_line(x,y,b) if __name__ == "__main__": main()
import numpy as np import pandas as pd from sklearn import linear_model df =pd.read_csv('E:\\Programming\\Python\\Machine Learning\\Linear regression\\Datasets\\housepricing.csv') # Read file reg = linear_model.LinearRegression() # Linear regression model reg.fit(df[['area','bedrooms','age']],df.price) # Defining the features of the model print(reg.coef_) # Regression coefficients of the model print(reg.intercept_) # Intercept of the equation print(reg.predict([[3000,3,40]])) # Predicted value of the user entered value
from enum import Enum from typing import List, NamedTuple class SongInfo(NamedTuple): '''Represents a minimal tuple of the necessary song info.''' level: int name: str difficulty: int class NoteDirection(str, Enum): '''Enum of possible `FFRNote` direction values''' LEFT = 'L' DOWN = 'D' UP = 'U' RIGHT = 'R' class FFRNote(NamedTuple): '''Represents a note in a beatbox.''' direction: NoteDirection frame: int class Chart: '''Represents a FFR chart with its basic info and its notes.''' info: SongInfo beatbox: List[FFRNote] def __init__(self, info: SongInfo, beatbox: List[FFRNote]): self.info = info self.beatbox = beatbox
# Cian Doyle # G00335783 # Graph Theory def followes(state): """Return set of states that can be reached from state following e arrows.""" # Create a new set with state as it's only member states = set() states.add(state) # Check if state has arrows labelled e from it. if state.label is None: # Check if edge1 is a state if state.edge1 is not None: # If there's an edge1, follow it. states |= followes(state.edge1) # Check if state 2 is a state if state.edge2 is not None: # if there's an edge2, follow it. states |= followes(state.edge2) return states def match(infix, string): """Matches string to infix regular expression""" # Shunt and compile the regular expression postfix = shunt(infix) nfa = compile(postfix) # The current set of states current = set() next = set() # Add the initial state to the current set current |= followes(nfa.initial) # Loop through each character for s in string: # Loop Through current set of states for c in current: # Check if that state is labelled s. if c.label == s: # Add the edge1 state to the next set. next |= followes(c.edge1) #set current to next and clear out next current = next next = set() # Check if the accept state is in the set of current states return (nfa.accept in current) # Tests infixes = ["a.b.c*", "a.(b|d).c*", "(a.(b|d))*", "a.(b.b)*.c"] strings = ["", "abc", "abbc", "abcc", "abad", "abbbc"] for i in infixes: for s in strings: print(match(i,s), i, s)
# The sum of the squares of the first ten natural numbers is, # 1**2 + 2**2 + ... + 10**2 = 385 # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)**2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. def square_each(numbers): total = 0 for i in numbers: total += i**2 return total def square_total(numbers): total = 0 for i in numbers: total += i return total**2 total1 = square_each(range(1,101)) total2 = square_total(range(1,101)) print(total2-total1)
# -*- coding: utf-8 -*- import itertools import operator import statistics def join_list(l, separator=u", ", last_separator=u" и "): if len(l) == 0: return "" if len(l) == 1: return l[0] return separator.join(l[:-1]) + last_separator + l[-1] def tweet_with_list(tweet_variant_wo_list, tweet_variant_w_list, list_, *args, **kwargs): return tweet_with_lists({(False,): tweet_variant_wo_list, (True,): tweet_variant_w_list}, [list_], *args, **kwargs) def tweet_with_lists(tweet_variants, lists, *args, **kwargs): tweets = [] """ Например, lists = [[1, 2, 3], [1, 2]] Мы можем взять 3 элемента из первого списка и 2 из второго, или 3 элемента из первого списка и 1 из второго, или 3 элемента из первого списка и 0 из второго, или 2 элемента из первого списка и 2 из второго, или 2 элемента из первого списка и 1 из второго и т.п. Это цикл по кортежам из количеств элементов, которые мы будем брать из списков. Для вышеописанного примера lists_counts будет перебирать значения (3, 2), (3, 1), (3, 0), (2, 2), (2, 1), ... """ for lists_counts in itertools.product(*[range(len(list_), -1, -1) for list_ in lists]): """ Ключи словаря tweet_variants — кортежи булевых значений длиной, равной размеру lists. i'ый элемент кортежа равен True, если текст твита предполагает, что i'ый список будет непустой. Пример: { (False, False): "Голодный день :(", (False, True): "Пью %s", (True, False): "Ем %s", (True, True): "Ем %s и пью %s" } """ tweet_variant = tweet_variants.get(tuple(map(lambda count: count > 0, lists_counts))) if tweet_variant is None: continue lists_slices = map(lambda list_, count: list_[:count], lists, lists_counts) tweet = tweet_variant % tuple(map(lambda list_: join_list(list_, *args, **kwargs), filter(None, lists_slices))) tweets.append((tweet, lists_counts)) """ Всё хорошо, но твиты должны быть отсортированы по приоритету (максимально информативные — впереди), а у нас получается так, что сначала мы урезаем первый список до нуля и наверняка получаем твит меньше 140 символов; отправляем его без единого элемента первого списка, зато с двумя элементами второго. Поэтому отсортируем твиты, сравнивая их следующим образом: """ def cmp(tweet1_counts1, tweet2_counts2): (tweet1, counts1) = tweet1_counts1 (tweet2, counts2) = tweet2_counts2 "1. Из твитов с разным количеством элементов списков более информативен тот, в котором элементов больше" if sum(counts1) > sum(counts2): return -1 elif sum(counts2) > sum(counts1): return 1 """ 2. Из твитов с одинаковой суммой количеств элементов список выбираем тот, где количества элементов более сбалансированы (например, [1, 1] лучше, чем [2, 0]) """ std1 = statistics.stdev(counts1) std2 = statistics.stdev(counts2) if std1 < std2: return -1 elif std2 < std1: return 1 "И, наконец, наиболее информативен твит большей длины" if len(tweet1) > len(tweet2): return -1 elif len(tweet2) > len(tweet1): return 1 return 0 return map(operator.itemgetter(0), sorted(tweets, cmp))
# Simple input parser based on ConfigParser # Only additions are echoing. # ConfigParser follows format of common INI files with substitutions. import configparser class InputParser(configparser.SafeConfigParser): def __init__(self): # super(InputParser, self).__init__(self) configparser.SafeConfigParser.__init__(self) self._param = dict() def read(self, fname): """ Read an input file """ configparser.SafeConfigParser.read(self, [fname]) for section in self.sections(): if section != "env": for key, value in self.items("env"): if not self.has_option(section, key): self.set(section, key, value) for key, value in self.items(section): self._param[key] = value return self._param def write(self, fname): """ Write a file after substitution """ # Create a new ConfigParser with substitution config_out = configparser.ConfigParser() for section in self.sections(): config_out.add_section(section) for name, value in self.items(section): config_out.set(section, name, value) with open(fname, 'w') as f: config_out.write(f)
#prints print "mary had a little lamb" #prints print "its fleece was white as %s." % 'red' #prints print "and everywhere that she went" #prints the letter a 10 times print "a" * 10 #prints the word test 10 times print "test" * 10 #variables end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "e" #prints variables. , ensures they are on the same line print end1 + end2 + end3 + end4 + end5, print end1 + end2 + end3 + end4 + end5
""" THE NUMPY ARRAY OJECT: """ import numpy as np # The numpy array object """ Numpy Library is the data structures for representing multidimentional arrays of homogenious data Homogeneous referes to all the elements in the array having the same data type In addition to data stored in the array it contains the metadata about its shape, size, data type and other attributes """ # Finding information about the array help(np.ndarray) # Creating the array array_attribute = np.array([[1,2],[3,4],[5,6]]) # Checking the type type(array_attribute) # Checking the dimentions array_attribute_dim = array_attribute.ndim # Checking the shape of the array array_attribute_shape = array_attribute.shape # Checking the size of the array array_attribute_size = array_attribute.size # Checking the data type of the array array_attribute.dtype # Checking the number of bytes array_attribute.nbytes """ DATA TYPES: Since Numpy Arrays are homogeneous all elements have same type For numerical work most importdant data types are int float and complex they come in different sizes as int32 int 64 """ # How to use the dtype attribute to generate arrays of integer, float and # Complex valued elements array_int = np.array([1, 2, 3], dtype=np.int) array_float = np.array([1, 2, 3], dtype=np.float) array_complex = np.array([1, 2, 3], dtype=np.complex) """ TYPE CASTING: Once created the datatype cannot be changed but creating a copy is valid with the type casted array values METHODS: 1. Using the np.array function 2. Using astype method of the ndarray clas """ # Type casting an array for method 1 tobecasted = np.array([1, 2, 3], dtype=np.float) tobecasted.dtype tobecasted2 = np.array(tobecasted, dtype=np.int) tobecasted2.dtype # Type Casting using method 2 casting = np.array([1, 2, 3,], dtype=np.float) casting2 = casting.astype(np.int) # Promotion of datatype if required by the operation promotion = np.array([1, 2, 3], dtype=float) promotion2 = np.array([1, 2, 3], dtype=complex) (promotion + promotion2).dtype # Approprite to set data type either int or complex default is float # You cant take a squareroot of a negative number square_root = np.sqrt(np.array([-1, 0, 1])) # Squareroot of complex number complex_sqrt = np.sqrt(np.array([-1, 0, 1], dtype=complex)) """ REAL AND IMAGINARY PARTS: All numpy array instance have attributes real and imag for extracting real and imaginary parts of the array """ realimaginary = np.array([1, 2, 3], dtype=complex) # Extracting the real realimaginary.real # Extracting the imaginary realimaginary.imag
# -*- coding: utf-8 -*- """ Created on Sun Feb 14 21:34:33 2021 @author: ASUS """ #plotting basic #import pyplot from matplotlib import matplotlib.pyplot as plt x_day =[1,2,3,4,5] y_price1 =[9,9.5,10.1,10,12] y_price2 =[11,12,10.5,11.5,12.5] #define chart element plt.title("stock movement") plt.xlabel("week days") plt.ylabel("prices in USD") plt.plot(x_day,y_price1,label='stock1') plt.plot(x_day,y_price2,label='stock2') plt.legend(loc=2, fontsize =8) plt.show()
#集合set 无序,唯一性 #定义集合 ss=set() l=[1,23,4,45,65,77] s1=set(l) #print(s)# {65, 1, 4, 45, 77, 23} s2={1,3,2} s3={1,2,4} #交集 '''print(s2.intersection(s3))#{1, 2} print(s2&s3) #{1, 2}''' #并集 '''print(s2.union(s3))#{1, 2, 3, 4} print(s2|s3) #{1, 2, 3, 4}''' #差集 '''print(s2-s3) #{3} print(s3-s2) #{4} print(s2.difference(s3))#{3} # ^ s2,s3先合并,再去除两个集合都有的 print(s2^s3) #{3, 4} ''' # add update remove clear '''s3={2,1,4,55} s3.add(34) #只添加一个 s3.update((15,36,46)#添加多个 参数为迭代器iterable print(s3) #s3.remove(3) #s3.clear()'''
########类型转换 a=int(5.9) # 直接取整,不会四舍五入 float(1) #1.0 bool(-5)#True bool(5)#True bool(0)#False bool(None)#False b="hello" print(list(b)) #['h', 'e', 'l', 'l', 'o'] tuple(b) # ('h', 'e', 'l', 'l', 'o') ####################333 ####运算符 ### b**2=b*b b**3=b*b*b ### in 、 not in 、is \is not
# -*- coding: utf-8 -*- #!/usr/bin/python import sys import twitter from settings import * print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nestablish the twitter object') # see "Authentication" section below for tokens and keys api = twitter.Api(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token_key=OAUTH_TOKEN, access_token_secret=OAUTH_SECRET, sleep_on_rate_limit=True ) print('twitter object established') print(api) #doit(api) # print("\033[93m Something went wrong establishing the Twitter Object.\e[0m") print(api.InitializeRateLimit()) ##print(api.rate_limit) #print( 'Number of arguments:', len(sys.argv), 'arguments.') #print('Argument List:', str(sys.argv)) print("Getting followers for", str(sys.argv[1])) try: users = api.GetFriends(screen_name=str(sys.argv[1]), total_count=10, skip_status=True) for u in users: print(u.name) print(u.screen_name) print(u.id) print() except: print("\nCheck your assumptions, beginning with the identity of", str(sys.argv[1]), "who doesn't seem to exist on Twitter.")
""" No.1 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def twoSum(self, nums, target): """ 暴力解法 - time: 5600 ms - men: 14.8 MB """ n = len(nums) for i in range(0,n-1): for j in range(i+1,n): if nums[i]+nums[j] == target: return [i,j] def twoSum_1(self, nums, target): """ 找num2=target-num1是否在list中,这样只计算一次 - time: 1260 ms - men: 14.8 MB """ n = len(nums) for i in range(0,n-1): num2 = target-nums[i] if num2 in nums: if (nums.count(num2) == 1)&(num2 == nums[i]): #避免num2是num1本身 continue else: j = nums.index(num2,i+1) break if j>0: return [i,j] else: return [] def twoSum_2(self, nums, target): """ 找num2从之后的nums查找 - time: 1076 ms - men: 14.7 MB """ n = len(nums) for i in range(0,n-1): num2 = target-nums[i] temp = nums[i+1:] # 之后的nums,这里是引用不会赋值 if num2 in temp: j = nums.index(num2,i+1) break if j>0: return [i,j] else: return [] def twoSum_3(self, nums, target): """ 字典模拟哈希求解 - time: 72 ms - men: 14.9 MB """ hashmap={} for i,num in enumerate(nums): if hashmap.get(target-num) is not None: return [i,hashmap.get(target-num)] hashmap[num] = i # 建立 num:index 字典 if __name__ == "__main__": nums = [2,7,11,15] target = 9 s = Solution() print(s.twoSum(nums,target))
#IMPUT cateto_uno=float(input("ingrese cateto uno:")) cateto_dos=float(input("ingrese cateto dos:")) #PROCESSING hipotenusa=(cateto_uno**2+cateto_dos**2)**(1/2) #VERIFICADOR triangulo_grande=(hipotenusa>100) #OUTPUT print("##########################################") print("#### calcular la hipotenusa ####") print("##########################################") print("#### cateto uno:",cateto_uno," ######") print("#### cateto dos:",cateto_dos," #####") print("#### hipotenusa:",hipotenusa ," #####") print("##########################################") print("triamgulo grande:",triangulo_grande)
masa=float(input("ingrese masa:")) longitud=float(input("ingrese longitud:")) tiempo=float(input("ingrese tiempo:")) presion=masa/(longitud*tiempo**2) print("####################################") print("#### calcular presion ########") print("####################################") print("#### longitud =", longitud," ###") print("#### tiempo=",tiempo," ###") print("####masa=",masa," ###") print("#### presion=",presion,"###") print("####################################")
longitud=float(input("ingrese longitud:")) tiempo=float(input("ingrese tiempo:")) aceleracion=longitud/tiempo**2 print("#################################") print("#### calcular aceleracion ###") print("#################################") print("#### tiempo:",tiempo," ###") print("#### aceleracion:",aceleracion," ###") print("#### distancia:",longitud," ###") print("#################################")
#Input numero1=float(input("Ingresar el numero1:")) numero2=float(input("Ingresar el numero2:")) #Processing raiz=(numero1/numero2)**(1/2) #Verificador raiz_correcta=(raiz>=5) #Ouput print("###########################################################") print("# Algoritmo para hallar la raiz cuadrada de una division #") print("###########################################################") print("# numero1 :",numero1," #") print("# numero2 :",numero2," #") print("# raiz :",raiz," #") print("###########################################################") print("#raiz correcta:",raiz_correcta," #")
#INPUT trabajador=input("ingrese nombre de trabajador:") pago_por_horas_extras=float(input("ingrese el pago por horas extras:")) horas_extras_trabajadas=float(input("ingrese horas extras trabajadas:")) #PROCESSING pago_total_de_horas_extras_trabajadas=pago_por_horas_extras*horas_extras_trabajadas #VERIFICADORES pago_total_por_horas_extras_alta=(pago_total_de_horas_extras_trabajadas>120) #OUTPUT print("###################################################") print("#### calcular el pago tota por horas extras ###") print("###################################################") print("####trbajador:",trabajador," ###" ) print("#### pago por horas extras:",pago_por_horas_extras," #######") print("#### horas extras trabajadas:",horas_extras_trabajadas," #####") print("#### pago total de horas extras trabajadas:",pago_total_de_horas_extras_trabajadas ,"###") print("##########################################") print("pago total por horas extras alta:",pago_total_por_horas_extras_alta)
""" Con JavaScript function MyFirstFunction() { console.log("Hola Mundo"); } console.log("Hola Mundo 2"); MyFirstFunction() """ # Para Python def MyFirstFunction(): print("Hola Mundo") print("Hola Mundo") print("Hola Mundo") print("Hola Mundo 2") MyFirstFunction() ''' var miNombre = "Felipe"; var nombre = "Juan"; function escribirBienvenida2(nombre, colorTexto) { document.write("<font color='" + colorTexto + "'>"); document.write("<h1>Hola " + nombre + "</h1>"); document.write("</font>"); } var miColor = "red"; escribirBienvenida2("Sebastian", "blue"); escribirBienvenida2(miNombre); document.write(nombre); ''' miNombre = "Felipe" nombre = "Juan" def escribirBienvenida2(nombre, colorTexto = None): print("<font color='" + str(colorTexto) + "'>") print("<h1>Hola " + nombre + "</h1>") print("</font>") miColor = "red" escribirBienvenida2("Sebastian", "blue") escribirBienvenida2(miNombre) print(nombre + str(3)) """ function areatriangulo(base, altura) { var resultado; resultado = (base * altura) / 2 return resultado resultado = 10; return resultado } var areademitriangulo; areademitriangulo = areatriangulo(2, 8); """ def areatriangulo(base, altura): resultado = (base * altura) / 2 return resultado resultado = 10 return resultado areademitriangulo = areatriangulo(2, 8)
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] for row in a: for elem in row: print(elem, end=' ') print()
def stupid_sort(data): i, size = 1, len(data) while i < size: if data[i - 1] > data[i]: data[i - 1], data[i] = data[i], data[i - 1] i = 1 else: i += 1 return data
Capitals = {'Russia': 'Moscow', 'Ukraine': 'Kiev', 'USA': 'Washington'} Capitals = dict(Russia = 'Moscow', Ukraine = 'Kiev', USA = 'Washington') Capitals = dict([("Russia", "Moscow"), ("Ukraine", "Kiev"), ("USA", "Washington")]) Capitals = dict(zip(["Russia", "Ukraine", "USA"], ["Moscow", "Kiev", "Washington"])) print(Capitals)
def encryption (plainText,key): cipherText = [] # 1. Generate Key Matrix keyMatrix = generateKeyMatrix(key) # 2. Encrypt According to Rules of playfair cipher i = 0 while i < len(plainText): # 2.1 calculate two grouped characters indexes from keyMatrix n1 = indexLocator(plainText[i],keyMatrix) n2 = indexLocator(plainText[i+1],keyMatrix) # 2.2 if same column then look in below row so # format is [row,col] # now to see below row => increase the row in both item # (n1[0]+1,n1[1]) => (3+1,1) => (4,1) # (n2[0]+1,n2[1]) => (4+1,1) => (5,1) # but in our matrix we have 0 to 4 indexes only # so to make value bound under 0 to 4 we will do %5 # i.e., # (n1[0]+1 % 5,n1[1]) # (n2[0]+1 % 5,n2[1]) if n1[1] == n2[1]: i1 = (n1[0] + 1) % 5 j1 = n1[1] i2 = (n2[0] + 1) % 5 j2 = n2[1] cipherText.append(keyMatrix[i1][j1]) cipherText.append(keyMatrix[i2][j2]) cipherText.append(", ") # same row elif n1[0]==n2[0]: i1= n1[0] j1= (n1[1] + 1) % 5 i2= n2[0] j2= (n2[1] + 1) % 5 cipherText.append(keyMatrix[i1][j1]) cipherText.append(keyMatrix[i2][j2]) cipherText.append(", ") # if making rectangle then # [4,3] [1,2] => [4,2] [3,1] # exchange columns of both value else: i1 = n1[0] j1 = n1[1] i2 = n2[0] j2 = n2[1] cipherText.append(keyMatrix[i1][j2]) cipherText.append(keyMatrix[i2][j1]) cipherText.append(", ") i += 2 return cipherText Weird_Snow — Today at 8:14 PM def bubble_sort(nums): # We set swapped to True so the loop looks runs at least once swapped = True while swapped: swapped = False for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: # Swap the elements nums[i], nums[i + 1] = nums[i + 1], nums[i] # Set the flag to True so we'll loop again swapped = True # Verify it works random_list_of_nums = [5, 2, 1, 8, 4] bubble_sort(random_list_of_nums) print(random_list_of_nums)
"""1. Дан зашифрованный русский текст. Каждая буква заменяется на следующую за ней (буква я заменяется на а). Получить новый текст, содержащий расшифровку данного текста. letters = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'""" a = "теперь моя пора я не люблю весны" def f (x): letters = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' n='' for i in x: index_ = 0 while True: if i == letters[index_]: #маленькие буквы n += letters[index_+1] break if i == 'я': #последняя буква n += 'а' break if i == ' ': #пробел n += ' ' break if i == '.': #точка n += '.' break if i == '!': #восклицательный знак n += '!' break if i == ',': #кома n += ',' break if i == '?': #знак вопроса n += '?' break if i == '-': #дефис n += '-' break if i == ':': #двоеточие n += ':' break if i == ';': #точка с комой n += ';' break index_ += 1 print(n) f(a)
import socket def connection(message): print('Begin') # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening #208.103.44.151 is the router address that will forward 10000 # to the computer running the server server_address = ('208.103.44.151', 10000) print('connecting to %s port %s' % server_address) sock.connect(server_address) try: # Encode data message_as_bytes = str.encode(message) type(message_as_bytes) # ensure it is byte representation # Decode data, not needed for now my_decoded_str = message_as_bytes.decode() type(my_decoded_str) # Print and send all data print('Transmitting From Client Transport"%s"' % message) sock.sendall(message_as_bytes) # Look for server response data_received = 0 data_expected = len(message) while data_received < data_expected: data = sock.recv(16) data_received += len(data) print('received "%s"' % data) finally: print('closing socket') sock.close()
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): def test_max_interger(self): """Test output of max_interger() """ self.assertAlmostEqual(max_integer([1, 2, 5, 4, 7]), 7) self.assertAlmostEqual(max_integer([-7, 2, -1, 3, 5]), 5) self.assertAlmostEqual(max_integer([0]), 0) self.assertAlmostEqual(max_integer([2, 2, 2]), 2) self.assertAlmostEqual(max_integer([-1, 0, 1]), 1) self.assertAlmostEqual(max_integer([]), None) self.assertAlmostEqual(max_integer([1]), 1) self.assertAlmostEqual(max_integer([1, 2, 6, 4, 5]), 6) self.assertAlmostEqual(max_integer([6, 2, 4, 4, 5]), 6)
#!/usr/bin/python3 """ This is he module Text indetation """ def text_indentation(text): """ print a text with 2 new lines after each of these characters """ if type(text) is not str: raise TypeError('text must be a string') else: replace_dot1 = text.replace('. ', '.') replace_dot2 = replace_dot1.replace('.', '.\n\n') replace_sigQ1 = replace_dot2.replace('? ', '?') replace_sigQ2 = replace_sigQ1.replace('?', '?\n\n') replace_2dot1 = replace_sigQ2.replace(': ', ':') replace_2dot2 = replace_2dot1.replace(':', ':\n\n') print(replace_2dot2.strip(), end='')
#!/usr/bin/python3 """ Module Write to a file """ def write_file(filename="", text=""): """ function that writes a string to a text file Return: number od characters written """ with open(filename, mode='w', encoding='utf-8') as myfile: myfile.write(text) return myfile.tell()
#!/usr/bin/python3 """ this is Module Append to a file""" def append_write(filename="", text=""): """Function that appends s tring at the end of a text file Return: the number of character added """ with open(filename, mode='a', encoding='utf-8') as myfile: return myfile.write(text)
#!/usr/bin/python3 """ Module Student to Json with filter """ class Student: """ class that defines a student """ def __init__(self, first_name, last_name, age): """ Constructor Args: first_name (str): first name of a student last_name (str):last name of student age (int): age of the student """ self.first_name = first_name self.last_name = last_name self. age = age def to_json(self, attrs=None): """ retrieves a dictionary representation of a student instance """ if type(attrs) is not list: return self.__dict__ else: return dict((_key, self.__dict__[_key]) for _key in attrs if _key in self.__dict__)
#!/usr/bin/python3 def uniq_add(my_list=[]): # obtenemos los elementos de la lista sin repetir uniq_idx = list(set(my_list)) # sumamos esos unicos elementos result = sum(uniq_idx) return result
#coding:utf-8 import dns.resolver domain = input('请输入域名地址') # 请输入域名地址www.baidu.com #1. A 记录,将主机转换为IP地址 A = dns.resolver.query(domain,'A') for i in A.response.answer: for j in i.items: if j.rdtype == 1: print(j.address) print(A) print(i) print(i.items) print(j) print(j.rdtype) print(j.address) print(A.response.answer) print(dns.resolver.query('www.baidu.com','A'))
""" LCHS Python Walkthrough Aug 2021 """ from beach import Beach from forest import Forest from person import Person class Game: """ The game! """ def __init__(self): """ Construct the game with default person """ self.player = Person() def setup(self): """ Set up the player's details """ username = input("What is your name?") fav_animal = input("What's your favourite animal?") self.player = Person(username, fav_animal) print(f"Hi {self.player.name}! I love {self.player.fav_animal} too! Let's go on an adventure!") def start(self): """ Start the game and go to the beach or the forest """ adventure = input("Would you like to go to the beach or the forest?") if adventure == "beach": Beach(self.player).start() elif adventure == "forest": Forest(self.player).start() else: print("Hmmm, I don't know where that is. Let's try again") self.start() if self.continue_game(): self.start() @staticmethod def continue_game() -> bool: """ Ask the user whether they want to keep playing :return: True if they want to keep playing """ continue_game = input("Do you want to continue game?") if continue_game == "yes": return True else: return False if __name__ == "__main__": game = Game() game.setup() game.start()
#! /usr/bin/python """ Module for handling the conversion of character sequences (strings or file-like object, including text files, all referred hereafter as 'stream') into python objects, by implementing some custom functions for parsing streams into (arrays or scalar) of floats, ints, booleans, or more generally for parsing a stream into tokens of different types (numbers strings, boolean or user defined) Note that the module is compatible in both PY2 and PY3 The module first defines three "base" parse functions ('low' level): _default_parseint (same as builtin int, but floats raise exceptions) _default_parsefloat (same as builtin float, but NaNs raise exceptions) _default_parsebool ("1", 1, True or "true" - case insensitive, return True, "0", 0, False or "false" -case insensitive, return False, otherwise raises Exception) Then, the module defines some utility function for parsing a stream. Note that the parse is done by first splitting the stream into tokens, according to space characters, separator characters and quote characters. For each token, the 'low level' parse function is applied, and an array or a scalar (depending on the input) is returned. Any value which is not valid (NaN, not parsable, not within a specified range) raises an exception. The user can also control the range of the returned array dimension, or choose a rounding factor for floats to be applied to any value of the returned array. These functions are parsefloat (calls by default _default_parsefloat) parseint (calls by default _default_parseint) parsebool (calls by default _default_parsebool) and additionally: parsetime (parses strings in various forms with given separator chars) parsedate (parses strings in various forms with given separator chars) Finally, there are two more general utilities which can be applied in more general cases for any stream: parsefield (which is used by all five functions above), which returns the tokens of a text field (the name stems from an hypotetic text input field) which accepts a parsefunction to be applied to any token to check its validity (or change its value), and token: a generator which yields each token of a parsed stream (c) 2014, GFZ Potsdam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. For more information, see http://www.gnu.org/ """ from __future__ import print_function from numpy import isscalar __author__="Riccardo Zaccarelli, PhD (<riccardo(at)gfz-potsdam.de>, <riccardo.zaccarelli(at)gmail.com>)" __date__ ="$Oct 22, 2014 11:55:47 AM$" #import json #,re from math import isnan #, isinf import sys # This module is standalone, therefore we write PY3 compatibility code here PY3 = sys.version_info[0] == 3 if PY3: def isstring(v): return isinstance(v, str) from io import StringIO #from builtins import round as builtin_round #import default float else: def isstring(v): return isinstance(v, basestring) from StringIO import StringIO #here has been tested that cStringIO StringIO module is "good": #see http://www.skymind.com/~ocrow/python_string/ #However, cStringIO does not support seek and truncate, therefore use StringIO #https://docs.python.org/2/library/stringio.html#module-cStringIO range = xrange #from __builtin__ import round as builtin_round #import default float chr = unichr #from __builtin__ import map as builtin_map #import default float def _apply(val, func): """ Same as map, but val can be also scalar (returns func(val) in that case) """ return tuple(map(func,val)) if type(val) == tuple else map(func,val) if not isscalar(val) else func(val) def _default_parseint(val): """ Internal "private" parseint. same as int(val) except that val needs to be an integer and cannot be a float (an exception is thrown in case) """ vi = int(val) vf = float(val) if vi != vf: raise Exception("%s is not an integer " % str(val)) return vi def _default_parsefloat(val): """ Internal "private" parsefloat. same as float(val) except that val needs to be nor infinite (positive or negative) neither NaN (an exception is thrown in case) If max_decimal_digits is a number greater than zero, rounds the float to the given decimal precision so for instance _parsefloat(1.45, 1) = _parsefloat(" 1.45 ", 1) = 1.5 """ vf = float(val) if isnan(vf): raise Exception("value is NaN") return vf _type_float = type(5.0) _type_int = type(5) def _default_parsenum(val, decimals=None): """ General purpose parse number function. decimals controls the type of the number returned: None (default if missing): smart guess. val is returned if already float or int. Otherwise, val is parsed to both float (val_float) and int (val_int) by using _default_parsefloat and _default_parseint (the former raises exceptions if the parse value is NaN). If val is not parseable to float and int, raises the corresponding exception, if parsable either to float or int, returns the parsed value, if parsable to both, returns val_int if val_int == val_float and val is string with no '.' characters or the 'e' character present. In any other cases, returns the parsed float number < -1: parses to float number == -1: parses to int number >= 0: parses to float rounded to the specified number of decimal digits (0 means: round to int, although floats are returned) """ valf= None vali = None exc = None if decimals is None or decimals!=-1: try: if _type_float == type(val): return val #check if already float valf = _default_parsefloat(val) if decimals >=0 : valf = round(valf, decimals) except Exception as e: exc = e valf= None if decimals is None or decimals==-1: try: if _type_int == type(val): return val #check if already int vali = int(valf) if valf is not None else _default_parseint(val) except Exception as e: if exc == None: exc = e vali= None if exc is not None: raise exc #either vali, or valf or both are None #Now either vali, or valf, or both are NON None if valf is None and not vali is None: return vali elif valf is not None and vali is None: return valf #if vali == valf then decimals is None (see above) so we can avoid the check in the if if vali == valf and isstring(val): if val.find('.') < 0 or val.find('e')>=0 or val.find('E')>=0: return vali return valf def _default_parsebool(val): """ Parses val to boolean. True is returned if val is the string "true" (case insensitive), "1" or using _default_parseint it evaluates to 1 False is returned if val is the string "false" (case insensitive), "0" or using _default_parseint it evaluates to 0 """ if (val==True or val==False): return val try: it = _default_parseint(val) if it==1 : return True elif it==0: return False except: if isstring(val): v = val.lower() if (v=='true' or v=='1'): return True elif (v=='false' or v=='0'): return False raise Exception("%s not boolean-parsable" % str(val)) def _intervalExc(ret, interval): def str_interval(interval): return "in the specified range of values (given as function)" if hasattr(interval,"__call__") else \ ("equal to " if isscalar(interval) else "in ") + str(interval) return Exception( "{0} {1} {2}" .format(str(ret) if isscalar(ret) else "array", "not" if isscalar(ret) else "elements not all", str_interval(interval)) ) def _dimExc(ret, interval): if interval == -1: interval = "-1 (scalar)" ret = str(ret)+" has dimension (-1)" if isscalar(ret) else "array has dimension (python 'len')" return _intervalExc(ret, interval) def _quoteExc(ret, quote_char, type_=None): return Exception( "'{0}' {1} {2}" .format(str(ret),"(quoted string) cannot be parsed to", "number" if type_ is None else type_)) pinf = float("infinity") #positive infinity def numinterval(interval): """ Converts an interval to a numeric interval, replacing None elements with -infinity and +infinity, so that the open (type(interval)=tuple) and closed (type(interval)=list) cases are consistent: -float("infinity") must be considered in [None, 3] but not in (None,3) """ if interval is None or isscalar(interval): return interval try: t = type(interval) if t== tuple: interval = list(interval) if interval[0] is None: interval[0] = -pinf if interval[1] is None: interval[1] = pinf if t==tuple: interval = tuple(interval) return interval except: return interval def parseint(val, interval=None, dim=None, parsefunc = None): """ Parses val (either a string or file-like object) into tokens according to _default_sep (default: {',',';'}) _default_quote (default: {'"',"'"}) _default_ws = (default: set([chr(i) for i in range(33)])) (see module-level token function) and then converts each token to int acccording to parsefunc Returns either an int (e.g. val="12"), a tuple (val = "(1, 3)") or a list (val="[1e5]" but also val = "1 3 4") Raises an exception if - interval is specified as a 2 elements tuple (open interval) or list (closed interval) and any token is not in the interval - dim is specified as a 2 elements tuple (open interval) or list (closed interval) and the returned element length is not int dim NOTE: interval and dim can also be functions: in case, they must accept a single argument and return True or False (argument inside or outside interval). - if parsefunc raises an exception. parsefunc accepts two arguments: the token string, and its type (None for any token except quoted strings, in that case it is the quoted character). By default (missing or None), it uses the module-level function _default_parseint which raises exceptions if a token is a non-integer float, is not parsable to int or represents a quoted string token (interpreted as a user will of specifying a string type only) """ if parsefunc is None: #default parse function def parsefcn(val, quote_char): if quote_char: raise _quoteExc(val, quote_char, "integer") return _default_parseint(val) parsefunc = parsefcn interval = numinterval(interval) def pfcn(val, quote_char): val = parsefunc(val, quote_char) if not isin(val, interval): raise _intervalExc(val, interval) return val val = parsefield(val, parsefunc=pfcn) if dim is not None and not isdim(val, dim): raise _dimExc(val, dim) return val def parsefloat(val, decimals=None, interval=None, dim=None, parsefunc = None): """ Parses val (either a string or file-like object) into tokens according to _default_sep (default: {',',';'}) _default_quote (default: {'"',"'"}) _default_ws = (default: set([chr(i) for i in range(33)])) (see module-level token function) and then converts each token to float acccording to parsefunc Returns either an int (e.g. val="12.1"), a tuple (val = "(1, 3.3)") or a list (val="[1e-10]" but also val = "1.2 3.001 4") Raises an exception if - interval is specified as a 2 elements tuple (open interval) or list (closed interval) and any token is not in the interval. - dim is specified as a 2 elements tuple (open interval) or list (closed interval) and the returned element length is not int dim. If the element is "scalar" (it does not have an "__iter__" method) then its length is assumed to be -1 NOTE: interval and dim can also be functions: in case, they must accept a single argument and return True or False (argument inside or outside interval). interval and dim can be None to specify "skip the check". interval values which are None default to -infinity (index 0) and + infinity (index 1) decimals is the number of decimal digits each float must be rounded to. It can be greater or equal to zero, otherwise it is ignored - if parsefunc raises an exception. parsefunc accepts two arguments: the token string, and its type (None for any token except quoted strings, in that case it is the quoted character). By default (missing or None), it uses the module-level function _default_parsefloat which raises exceptions if a token is NaN, is not parsable to float or represents a quoted string token (interpreted as a user will of specifying a string type only) """ if parsefunc is None: #default parse function def parsefcn(val, quote_char): if quote_char: raise _quoteExc(val, quote_char, "float") return _default_parsefloat(val) parsefunc = parsefcn interval = numinterval(interval) def pfcn(val, quote_char): val = parsefunc(val, quote_char) if not isin(val, interval): raise _intervalExc(val, interval) return val if decimals < 0 else round(val, decimals) val = parsefield(val, parsefunc=pfcn) if dim is not None and not isdim(val, dim): raise _dimExc(val, dim) return val def parsenum(val, decimals=None, interval=None, dim=None): """ Parses val (either a string or file-like object) into tokens according to _default_sep (default: {',',';'}) _default_quote (default: {'"',"'"}) _default_ws = (default: set([chr(i) for i in range(33)])) (see module-level token function) and then converts each token to numbers acccording to _default_parsenum Returns either an int (e.g. val="12.1"), a tuple (val = "(1, 3.3)") or a list (val="[1e-10]" but also val = "1.2 3.001 4") Raises an exception if - interval is specified as a 2 elements tuple (open interval) or list (closed interval) and any token is not in the interval. - dim is specified as a 2 elements tuple (open interval) or list (closed interval) and the returned element length is not int dim NOTE: interval and dim can also be functions: in case, they must accept a single argument and return True or False (argument inside or outside interval). - if _default_parsenum raises an exception. _default_parsenum is a function which controls how numbers are returned, and uses the argument decimals, which is therefore more powerful than the decimals argument in the parsefloat module-level function. If decimals is: None (default if missing): smart guess: Each token is returned if already float or int. Otherwise, it is parsed to both float (val_float) and int (val_int) by using _default_parsefloat and _default_parseint (the former raises exceptions if the parse value is NaN). If the token is not parseable to float and int, raises the corresponding exception, if parsable either to float or int, returns the parsed value, if parsable to both, returns val_int if val_int == val_float and val is string with no '.' characters or the 'e' character present. In any other cases, returns the parsed float number < -1: parses each token to float number == -1: parses each token to int number >= 0: parses each token to float rounded to the specified number of decimal digits (0 means: round to int, although floats are returned) """ def parsefcn(val, quote_char): if quote_char: raise _quoteExc(val, quote_char, "float") val = _default_parsenum(val, decimals) if not _isin(val, interval): raise _intervalExc(val, interval) return val val = parsefield(val, parsefunc=parsefcn) if dim is not None and not isdim(val, dim): raise _dimExc(val, dim) return val def parsebool(val, parsefunc=None, dim=None): """ Parses val (either a string or file-like object) into tokens according to _default_sep (default: {',',';'}) _default_quote (default: {'"',"'"}) _default_ws = (default: set([chr(i) for i in range(33)])) (see module-level token function) and then converts each token to boolean acccording to parsefunc Returns either an int (e.g. val="true"), a tuple (val = "(1, false)") or a list (val="[True]" but also val = "1 True, false") Raises an exception if parsefunc raises an exception. parsefunc accepts two arguments: the token string, and its type (None for any token except quoted strings, in that case it is the quoted character). By default (missing or None), it uses the module-level function _default_parsebool which raises exceptions if a token is not 1, "1", "true" (case insensitive), 0, "0" or "false" (case insensitive) or represents a quoted string token (interpreted as a user will of specifying a string type only) """ if parsefunc is None: def parsefcn(val, quote_char): if quote_char: raise _quoteExc(val, quote_char) if parsefunc: val = _default_parsebool(val) return val parsefunc = parsefcn val = parsefield(val, parsefunc=parsefcn) if dim is not None and not isdim(val, dim): raise _dimExc(val, dim) return val def parsestr(val, parsefunc=None, dim=None): """ Parses val (either a string or file-like object) into tokens according to _default_sep (default: {',',';'}) _default_quote (default: {'"',"'"}) _default_ws = (default: set([chr(i) for i in range(33)])) (see module-level token function) and then returns each token (quoted strings will be unquoted and unescaped) Returns either a string (e.g. val="a string"), a tuple (val = "(1, 'false')") or a list (val="[True]" but also val = "'my little string', 'false'") Never raises exceptions, as each token is a string, unless the user defines a parse function by means of parsefunc. parsefunc accepts two arguments: the token string, and its type (None for any token except quoted strings, in that case it is the quoted character). As said, by default (missing or None), no function is called and no exception is thrown """ val = parsefield(val,parsefunc = parsefunc) if dim is not None and not isdim(val, dim): raise _dimExc(val, dim) return val _default_datesep = {'-',"/", "."} from datetime import date, datetime, timedelta def _dateexc(val): return Exception("invalid date: '{0}'".format(str(val))) def parsedate(val, separator_chars = _default_datesep, formatting='', round_ceil=False, empty_date_today = False, parsefunc=parseint): """ Parses val (either a string or file-like object) into tokens (see module-level 'token' function) according to: _default_datesep = {'-',"/", "."} as separator characters _default_quote (default: {'"',"'"}) _default_ws = (default: set([chr(i) for i in range(33)])) and then converts the tokens to (and returns) a python datetime (contrarily to the module-level functions parseint, parsefloat and parsebool, this function never returns a list or tuple) separator_chars (_default_datesep) can be customized and denotes the separator characters for each date field (year, month and day). formatting is a string denoting the date formatting (defaults to '' if missing), and round_ceil (false if missing) tells whether the returned datetime should be rounded up or down in all unspecified fields. This means that IN ANY CASE the time of the returned date will be either 00:00:00 (and 0 microseconds) if round_ceil is False or missing (the default), or 23:59.59 (and 999999 microseconds) if round_ceil is True. Months and days might be also rounded acccording to format. Example: Calling Y and M the current year and month (today().year and today().month) and representing heach datetime as year-month-day hours:minutes:seconds.microseconds then the list of tokens t parsed from the input val is returned as: formatting round_ceil=False round_ceil=True (or missing) 'y' or t[0]-1-1 0:0:0.0 t[0]-12-31 23:59.59.999999 missing and len(t)==1 'm' Y-t[0]-1 0:0:0.0 Y-t[0]-X 23:59.59.999999 (X in {31, 30, 28} depending on t[0]) 'd' Y-M-t[0] 0:0:0.0 Y-M-t[0] 23:59.59.999999 'ym' or t[0]-t[1]-1 0:0:0.0 t[0]-t[1]-X 23:59.59.999999 missing and len(t)==2 (X in {31, 30, 28} depending on t[1]) 'my' t[1]-t[0]-1 0:0:0.0 t[1]-t[0]-X 23:59.59.999999 (X in {31, 30, 28} depending on t[0]) 'md' Y-t[0]-t[1] 0:0:0.0 Y-t[0]-t[1] 23:59.59.999999 'dm' Y-t[1]-t[0] 0:0:0.0 Y-t[1]-t[0] 23:59.59.999999 'ymd' or t[0]-t[1]-t[2] 0:0:0.0 t[0]-t[1]-t[2] 23:59.59.999999 missing and len(t)==3 'dmy' t[2]-t[1]-t[0] 0:0:0.0 t[2]-t[1]-t[0] 23:59.59.999999 This function raises an exception if any token is not int-parsable (according to the module-level function _default_parseint, which by default includes the case of float-parsable strings), if any integer is invalid in the specified range (e.g., months or days) or, in case formatting is specified, if the token number does not match the expected token numbers of formatting """ ret = parsefield(val, separator_chars=separator_chars, parsefunc = parsefunc) #which returns ret if val is not a string if isscalar(ret): ret = [ret] if ret else [] if len(ret)==0: if empty_date_today: return datetime.today() raise _dateexc(val) if not formatting: if len(ret)==1: formatting='y' elif len(ret)==2: formatting='ym' elif len(ret) == 3: formatting='ymd' else: raise _dateexc(val) if len(formatting) != len(ret): raise _dateexc(val) #default values: m,d,h,mm,s,ms= (1,1,0,0,0,0) if not round_ceil else (12, 31, 23, 59, 59, 1000000-1) if formatting == 'y': return datetime(ret[0],m,d,h,mm,s,ms) elif formatting == 'dmy': return datetime(ret[2],ret[1],ret[0],h,mm,s,ms) elif formatting == 'ymd': return datetime(ret[0],ret[1],ret[2],h,mm,s,ms) else: ret_date = None if formatting == 'ym': ret_date = datetime(ret[0],ret[1], 1,0,0,0,0) elif formatting == 'my': ret_date = datetime(ret[1],ret[0], 1,0,0,0,0) else: t = date.today() if formatting == 'm': ret_date = datetime(t.year,ret[0],1,0,0,0,0) elif formatting == 'md': return datetime(t.year, ret[0],ret[1], h,mm,s,ms) elif formatting == 'dm': return datetime(t.year, ret[1],ret[0], h,mm,s,ms) elif formatting == 'd': return datetime(t.year, t.month, ret[0], h,mm,s,ms) if ret_date is None: raise _dateexc(val) if round_ceil: #in case we need to go up one month, and then substract one millisecond #Getting till the end of the specified month iss too complex with integers #(what about bisestiles years if we are the 28th of february?) y = ret_date.year+1 if ret_date.month == 12 else ret_date.year m = 1 + (ret_date.month % 12) #basically ret_date.month+1 unless ret_date,month=12 ret_date = datetime(y, m, 1, 0,0,0,0) - timedelta(0,0,1) #1 microsecond return ret_date _default_timesep = {':',"-", "."} from datetime import time def _timeexc(val): return Exception("invalid time: '{0}'".format(str(val))) def parsetime(val, separator_chars = _default_timesep, round_ceil=False, empty_time_now = False, parsefunc = parseint): """ Parses val (either a string or file-like object) into tokens according to _default_timesep = {':',"-", "."} as separator characters _default_quote (default: {'"',"'"}) _default_ws = (default: set([chr(i) for i in range(33)])) (see module-level token function) and then converts the tokens to a python time, returning it (contrarily to the module-level functions parseint, parsefloat and parsebool, this function never returns a list or tuple) separator_chars (_default_timesep) can be customized and denotes the separator characters for each date field (hours, minutes and seconds). Called t the list of parsed tokens (as integers, using the module-level function _default_parseint), time as the python time() function (current time) and denoting the times below in the standard format HH:MM:SS, the returne value is time if no token is found (e.g., empty string) t[0]:M:S.MS if len(t) == 1 t[0]:t[1]:S.MS if len(t) == 2 t[0]:t[1]:t[2].MS if len(t) == 3 where M, S, MS are zero if round_ceil is False, else 59,59, 999999 respectively (set missing fields to their maximum which preserve the given input fields) This function raises an exception if any token is not int-parsable (according to the module-level function _default_parseint, which by default includes the case of float-parsable strings) or if any integer is invalid in the specified range """ m,s,ms = (59, 59, 1000000-1) if round_ceil else (0, 0, 0) ret = parsefield(val, separator_chars=separator_chars, parsefunc = parsefunc) #which returns ret if val is not a string if isscalar(ret): ret = [ret] if ret else [] if len(ret)==0: if empty_time_now: return time() elif len(ret)==1: return time(ret[0],m,s,ms) elif len(ret)==2: return time(ret[0], ret[1], s ,ms) elif len(ret) == 3: return time(ret[0], ret[1], ret[2], ms) raise _timeexc(val) def isscalar(value): """ Returns if value is a scalar value, i.e. it is not an iterable. Thus, numbers, string, dates, times and boolean are scalar, list and tuples not """ return not hasattr(value,"__iter__") def _isin(val, interval): """ Returns true if the number val is in interval. Interval can be: 2-element list (math closed interval), 2-element tuple (math open interval), a "scalar" number N (equivalent to [N,N]) a function: in case, it must accept a single argument and return True or False (argument inside or outside interval). so that interval= lambda x: x>1 and x <3 is equivalent to interval=(1,3) If interval is None, this function returns True. For any other value of interval which is not a 2-element tuple or list, this method returns False. If tuple or list, interval can contain None values, they will default to -Infinity (for interval[0]) or +Infinity (for interval[1]) Examples: isin(7.8, [5, None]) returns True isin(7.8, [7.8, None]) returns True isin(7.8, (7.8, None)) returns False isin(n, (None, None)) = isin(n, None) returns True for any number n """ i = interval #just for less typing afterwards... if i is None: return True if hasattr(interval, "__call__"): return interval(val) if isscalar(interval): return val == interval t = type(i) return (i[0] is None or val > i[0]) and (i[1] is None or val < i[1]) if (t==tuple and len(i)==2) else \ ((i[0] is None or val >= i[0]) and (i[1] is None or val <= i[1]) if (t==list and len(i)==2) else False) def isin(val, interval): """ Returns True if val is in interval. interval can be a 2-element tuple (open interval) or list (closed interval), or a function. In the latter case, it must accept a single argument A and return True (A inside interval) or False (A outside interval). val can also be a generator (including list or tuples), in that case the function iterates over each val element and returns True if all elements are in interval. If interval is None, this function returns True. if any interval element at index 0 or 1 is None, it is skiiped (so that, e.g., for numbers, [None, -3] is basically equivalent to [-infitnity, -3] or to the assertion "val must be <= -3") """ if interval is None: return True if not isscalar(val): for v in val: if not _isin(v, interval): return False return True return _isin(val, interval) def isdim(val, interval): """ Returns True if the val 'dimension' (python len(val) function) is in interval. If val has is an iterable without a length, raises an Exceptions. Otherwise, if val is scalar (e.g., simple number, but also string), then its dimension is considered -1. interval can be a 2-element tuple (open interval) or list (closed interval), or a function. In the latter case, it must accept a single argument A and return True (A inside interval) or False (A outside interval). If interval is None, this function returns True. if any interval element at index 0 or 1 is None, it is skiiped (so that, e.g., for numbers, [None, -3] is basically equivalent to [-infitnity, -3] or to the assertion "val must be <= -3") """ if interval is None: return True dim = -1 if not isscalar(val) and hasattr(val, "__len__"): dim = len(val) return _isin(dim, interval) _default_sep = {',',';'} _default_quote = {'"',"'"} _default_ws = set([chr(i) for i in range(33)]) def parsefield(s, separator_chars = _default_sep, quote_chars=_default_quote, whitespace_chars=_default_ws, parsefunc = None): #Note: parseFunc takes the token (parsed) and the type (None for normal token, the quote char for quoted token) """ Parses a field string (such as an html input value) into tokens, returning the array of tokens. Note that this method is not optimized for parsing long strings. The type of each token can be specified by parsefunc (if None, all tokens will be strings). If s is not a string, iterates over its elements (if iterable) or over s itself, applying parsefunc to any iterated element Retuns a list, a tuple or a single element according to the input value type. With default settings, assuming no parsefunc: s returned value "4" "4" "4 True" or "[4 True]" ["4", "True"] "(4,True)" ("4", "True") Any iterable returns an iterable (tuple if tuple, list in any other case) with the same elements Any other value returns the value By default, this method detects and returns more than one token if commas, or spaces (not whithin quoted strings) are found, or alternatively the string starts and ends with '[' and ']' (a list is returned or '(' and ')' (a tuple is returned). In any other case, a scalar (string, number, boolean or any other object) is returned separator_chars, quote_chars and whitespace_chars are respectively _default_sep, _default_quote and _default_ws, and are documented in the module level function token. Provide sets of characters (1-length strings) to slightly improve performances, if needed. parsefunc is a function accepting two arguments: the token parsed (string) and the type, which is None unless the token is a quoted string (in that case t is the quote character). It will then return the object to be returned. It can raise Exceptions for non parsable tokens: for instance, a parsing process which expects all numbers might rais one surely if the argument t is not None (quoted strings found), or try to parse to int if, for instance, "7.54" has to be considered as number """ t=None if isstring(s): i=0 l = len(s) while i<l and s[i] in whitespace_chars: i+=1 if i<l and (s[i]=='[' or s[i]=='('): j=l-1 while j>i and s[j] in whitespace_chars: j-=1 if (s[i]=='[' and s[j]==']') or (s[i]=='(' and s[j]==')'): t = list if s[i]=='[' else tuple s = StringIO(s) s.seek(i+1) s.truncate(j) else: if isscalar(s): t=None else: t=tuple if type(s)==tuple else list res =[] if parsefunc: for v, q in token(s, separator_chars, quote_chars,whitespace_chars, parse_num=None, parse_bool=None): res.append(parsefunc(v,q)) else: for v, q in token(s, separator_chars, quote_chars,whitespace_chars, parse_num=None, parse_bool=None): res.append(v) if t is None: l = len(res) if l==0: res = '' elif l==1: res = res[0] elif t==tuple: res = tuple(res) return res #adjacent wspaces are ignored if they follow or preceed a separator char, otherwise they are treated as sep char #separator chars simply separate tokens #quote chars def token(s, separator_chars = _default_sep, quote_chars= _default_quote, whitespace_chars=_default_ws, parse_num = _default_parsefloat, parse_bool = _default_parsebool): """ Parses s into tokens, returning a generator which can be used in a loop. The generator returns the tuple (token, quoted) where token can e either string, number or boolean (depending on the parameters) and quoted is non None only for quoted strings, to distinguish them from unquoted strings. Example with default arguments: for v, t in token('a true 1.1e3 "quote with space"'): #will return: #v = 'a' (string), t = None (no quote) #v = True (boolean), t = None #v = 1100 (integer), t = None #v = 'quote with spaces' (string), t = '"' Arguments: s the string or file-like object (i.e., with a read method which, with argument 1, returns a character) to be tokenized separator_chars ({',', ';'} by default): denotes the separator characters, i.e. those characters which separate tokens, and are never included in the latter whitespace_chars ({chr(0), ..., chr(32)} by default): denotes whitespace characters, i.e. "second citizen" separator characters, as they differ from the former in two things: 1) one or more adjacent whitespaces are treated as a single whitespace block 2) any block of whitespaces which preceeds or follows a separator character is simply ignored (as nothing was typed) Thus, with the default settings "a b" and "a , b" both return the tokens 'a' and 'b' quote_chars ({',', "'"} by default): specifies the quote characters, i.e. characters that need to denote strings to be returned as they are, after being unquoted. The characters backslash+'n', backslash+'r' and backslash+'t' are returned as nelwine, carriage return and tab, respectively. End-of-lines ('\r' or '\n') found (or end-of-stream reached) while parsing a quoted string will raise Exceptions parse_num: (default: _default_parse_float), if specified, it must be a function which takes the token and parses into number. For every token found, the function is run and the relative number is returned. If the function raises exceptions or is not specified, all tokens will be returned as strings (unless the parse_bool function is specified, see below) parse_bool: (default: _default_parse_bool), if specified, it must be a function which takes the token and parses into boolean. For every token found, the function is run (AFTER parse_num, if the latter is specified) and the relative boolean is returned. If the function raises exceptions or is not specified, all tokens will be returned as strings (unless the parse_num function is specified, see above) NOTE ON parse_bool and parse_num: Quoted tokens, i.e. tokens parsed as string within quote_chars, will not be affected by the parse process and always returned as strings """ if not isstring(s) and not hasattr(s,"read"): if not hasattr(s, "__iter__"): yield s, None else: for v in s: yield v, None return if isstring(s): s = StringIO(s) if not hasattr(s, "read"): #for safety raise Exception("invalid token argument, must implement the read method") if not isinstance(separator_chars, set): separator_chars = set(separator_chars) if not isinstance(quote_chars, set): quote_chars = set(quote_chars) if not isinstance(whitespace_chars, set): whitespace_chars = set(whitespace_chars) #convert s into a list of strings, where quotes are NOT touched: buf = None found_ws = False last_char_is_sep = False c = s.read(1) quote_char = '' def add(c, buf): if not c: return if not buf: buf = StringIO() #print('adding {}'.format(c)) buf.write(c) return buf def data(quote_char=None): if not buf: return '', quote_char or None v = buf.getvalue() buf.close() if quote_char: return v, quote_char if parse_num: try: return parse_num(v), None except: pass if parse_bool: try: return parse_bool(v), None except: pass return v, None while c: if quote_char: if c==quote_char: quote_char = '' yield data(c) buf = None c = s.read(1) continue elif c=='\\': c = s.read(1) if c=='n': c = '\n' elif c=='r': c = '\r' elif c=='t': c = '\t' elif c=='\n' or c=='\r': raise Exception("Unclosed quoted string '{0}' (end-of-line found)".format(buf.getvalue())) buf = add(c, buf) c = s.read(1) continue if c in whitespace_chars: if not found_ws: found_ws = True c = s.read(1) continue ws_found = found_ws #used below, we can't rely on found_ws cause we need to set it to false now #in order to avoid to set it in all if below. found_ws = False if c in separator_chars: yield data() buf = None c = s.read(1) #was the last character? if not c: #add another token: (e.g., '(4,5,)'. Note that this is not the #Python syntax but if more conistent, and avoids '[,]' to be equal to '[]' yield data() buf = None #we will exit the loop now continue if ws_found: if buf: yield data() buf = None if c in quote_chars and not buf: quote_char = c; c = s.read(1) continue buf = add(c, buf) c = s.read(1) if buf: if quote_char: raise Exception("Unclosed quoted string '{0}' (end-of-stream found)".format(buf.getvalue())) yield data() return def _ps(arr): s = str(type(arr)) +": "+ '|'.join([str(s)+" ("+str(type(s))+")" for s in arr]) if hasattr(arr,"__len__") and not isstring(arr) else \ "'"+str(arr)+"' ("+str(type(arr))+")" if isstring(arr) else str(arr)+" ("+str(type(arr))+")" print(s) if __name__ == "__main__": print(str(parsefield('2014',parsefunc=parseint)))
#!/bin/python3 import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): # start with empty list of unpaired socks (we haven't started looking through them yet!) unpairedSocks = [] pairs = 0 # for each sock, if we've already seen it and it is NOT part of a pair (i.e. in unpairedSocks), then remove it from unpairedSocks (pair it up with the one we're "holding") # and add one to the count of pairs, otherwise put it in the list of unpaired socks for sock in ar: if (sock in unpairedSocks): unpairedSocks.remove(sock) pairs += 1 else: unpairedSocks.append(sock) return pairs if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) ar = list(map(int, input().rstrip().split())) result = sockMerchant(n, ar) fptr.write(str(result) + '\n') fptr.close()
""" File này dùng để chứa đối tượng là khách hàng """ class Customer: """ Dữ liệu của khách hàng gồm có Tên, địa chỉ (tương ứng với điểm trên đồ thị) và loại hàng mà người này đặt""" def __init__(self, name, address, merchan): self.name = name # tên khách hàng self.address = address # địa chỉ khách hàng self.merchan = merchan # loại hàng mà khách đặt def setName(self, name): self.name = name def setAddress(self, address): self.address = address def setMerchan(self, merchan): self.merchan = merchan def getName(self): return self.name def getAddress(self): return (int)(self.address) def getMerchan(self): return self.merchan def toString(self): mer = '' flag = self.merchan if flag == 1: mer = "Bánh gấu" if flag == 2: mer = "Chip Chip" if flag == 3: mer = "Chuppa Chups" return "[ Name= " + self.name + "; Address= "+ (str)(self.address) + "; Merchan= " + mer + " ]"
import re # The common advice about email validation is don't: # send a confirmation code to the email given and look # if the email sender return an error def valid_email(email): regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' if(re.search(regex, email)): return True, None return False, "Invalid email" def valid_password(password): valid_long = len(password) >= 8 & len(password) <= 30 contain_number = bool(re.search('[0-9]', password)) contain_capital_letter = bool(re.search('[A-Z]', password)) print(valid_long, contain_number, contain_capital_letter) if not (valid_long & contain_number & contain_capital_letter): return False, "Your password must contain at least one lowercase letter, one capital letter and one number, 8-30 characters long" return True, None def validate_input(inputs): for input_type, value in inputs.items(): if input_type == "email": is_valid_email, error = valid_email(value) if not is_valid_email: return is_valid_email, error if input_type == "password": is_valid_password, error = valid_password(value) if not is_valid_password: return is_valid_password, error return True, None
import sys import pandas as pd import numpy as np """ The code is theoretically inspired from the following references: Artificial Intelligence: A Modern Approach, 3rd Edition. (From pages 697-707) https://en.wikipedia.org/wiki/Decision_tree Throughout the comments, the said book shall be referred to as AI:AMA """ """ Calculating the entropy, and information gain of an attribute in the decision trees is a primary operation, which tell us that how important a specific attribute is. AI:AMA Page no. 704 explains that how these two functions help in choosing what attribute is placed at the top of the tree, and what goes as the leaf. """ def calc_entropy(df, target): """ :param df: The Pandas DataFrame containing the table data :param target: The attribute for which we're calculating the entropy :return: The entropy of the target attribute """ freq = df[target].value_counts() entropy = sum(-freq * 1.0 / len(df) * np.log2(1.0 * freq / len(df))) return entropy def IG(df, attr, target): #IG: Information Gain """ :param df: Pandas DataFrame data in table form :param attr: Attribute on which the IG has to be calculated :param target: Target attribute :return: Information gain which is calculated by splitting the data based on the attribute attr """ #Counting the number of appearance of the values associated by that attribute attr freq = df[attr].value_counts() sum_counts = sum(freq) subset_entropy = 0.0 # Calculation of sum of entropy for each subset of records weighted by # their probability of occurring in the training set. for value in freq.index: probability = freq.get(value) / sum_counts subset = df[df[attr] == value] #Splitting the data to get the subset subset_entropy += probability * calc_entropy(subset, target) # Calculation of information gain return (calc_entropy(df, target) - subset_entropy) def most_frequent_item(df, target): """ :param df: Input DataFrame :param target: Target classification value (Kind of Owl) :return: Returns the most frequent item in the data frame """ most_frequent_value = df[target].value_counts().idxmax() return most_frequent_value def get_attribute_values(df, attribute): """ :param df: DataFrame :param attribute: Attribute for which the unique items have to be returned :return: All unique values for a specific attribute """ return df[attribute].unique() def best_attribute(df, attributes, target, splitting_heuristic): """ Iterates through all the attributes and returns the attribute with the best splitting_heuristic """ best_value = 0.0 best_gain = 0.0 best_attr = None for attr in attributes: gain = splitting_heuristic(df, attr, target) if (gain >= best_gain and attr != target): best_gain = gain best_attr = attr return best_attr def create_decision_tree(df, attributes, target, splitting_heuristic_func): """ Input : df-Pandas Data Frame, attributes-list of features, target-Target Feature, splitting_heuristic_func-Function to find best feature for splitting Returns a new decision tree based on the examples given. """ vals = df[target] #print ("vals", vals) default = most_frequent_item(df, target) #print ("default", default) # If the dataset is empty or there are no independent features if target in attributes: attributes.remove(target) if df.empty or len(attributes) == 0: return default # If all the target values are same, return that classification value. elif len(vals.unique()) == 1: return default else: # Choose the next best attribute to best classify our data based on heuristic function best_attr = best_attribute(df, attributes, target, splitting_heuristic_func) #print ("best_attr", best_attr) # Create an empty new decision tree/node with the best attribute and an empty # dictionary object tree = {best_attr: {}} # Create a new decision tree/sub-node for each of the values in the best attribute field for val in get_attribute_values(df, best_attr): #print ("tree", tree) #print ("val", val) # Create a subtree for the current value under the "best" field data_subset = df[df[best_attr] == val] subtree = create_decision_tree(data_subset, [attr for attr in attributes if attr != best_attr], target, splitting_heuristic_func) # Add the new subtree to the empty dictionary object in our new # tree/node we just created. #print ("subtree {} being added to tree {}".format(subtree, tree)) tree[best_attr][val] = subtree print ("now the tree looks like: {}".format(tree)) return tree def get_prediction(data_row, decision_tree): """ This function recursively traverses the decision tree and returns a classification for the given record. """ # If the current node is a string or integer, then we've reached a leaf node and we can return the classification if type(decision_tree) == type("string") or type(decision_tree) == type(1): return decision_tree # Traverse the tree further until a leaf node is found. else: #print("dtreekeys", decision_tree.keys()) attr = list(decision_tree.keys())[0] dattr = attr sarg = data_row[dattr] darg = decision_tree[attr] # print("attr, dattr", dattr) # print("sarg", sarg) # print("darg", darg) #print ("attr ", attr) #print ("Got ", decision_tree[attr]) #print ("Got ", data_row[attr]) if data_row[attr] in decision_tree[attr]: #print ("trying to get ", decision_tree[attr][data_row[attr]]) t = decision_tree[attr][data_row[attr]] else: t = 'NotIdentified' #print("err", t) #print(attr, decision_tree[attr], data_row[attr], t) return get_prediction(data_row, t) def predict(tree, predData): """ Input : tree-Tree Dictionary created by create_decision_tree function, predData-Pandas DataFrame on which predictions are made Returns a list of predicted values of predData """ predictions = [] for index, row in predData.iterrows(): predictions.append(get_prediction(row, tree)) return predictions def read_file(filename): """ Tries to read csv file using Pandas """ try: data = pd.read_csv(filename, header=0, dtype=str) except IOError: print("Error: The file {} was not found on this system.".format(filename)) sys.exit(0) return data def print_tree(tree, str): """ This function recursively crawls through the d-tree and prints it out in a more readable format than a straight print of the Python dict object. """ if type(tree) == dict: print ("%s%s" % (str, list(tree.keys())[0])) for item in tree.values()[0].keys(): print ("%s\t%s" % (str, item)) print_tree(tree.values()[0][item], str + "\t") else: print ("%s\t->\t%s" % (str, tree)) def build_tree(data): """ This function builds tree from Pandas Data Frame with last column as the dependent feature """ attributes = list(data.columns.values) target = attributes[-1] return create_decision_tree(data,attributes,target,IG) def shuffle_data(data): return data.sample(frac=1).reset_index(drop=True) def split_data(data): train_amount = int(len(data)*0.67) train_data = data[:train_amount] test_data = data[train_amount:] return train_data, test_data def validate(test, pred): total = len(test) match = 0 test = test.values for i in range(total): print("Expected: {}\tCalculated: {}".format(test[i][4], pred[i])) if test[i][4] == pred[i]: match += 1 return (float(match)*100)/total if __name__ == "__main__": avg_acc = 0 for i in range(10): acc = 0 print ("Cycle no {}".format(i)) data = read_file("owls15.csv") data = shuffle_data(data) train, test = split_data(data) #print("data", data) #print ("train", train) #print ("test", test) print("Data Read and Loaded\n") print("Building Decision Tree\n") tree = build_tree(train) #print(print_tree(tree,"")) predictions = predict(tree, test) acc = validate(test, predictions) avg_acc += acc print("Accuracy: {}".format(acc)) print ("Total average accuracy: {}".format(avg_acc/10.0))
#!/usr/bin/python -tt # Script by - Rishab Saraf # Github profile: rishabsaraf93 import re import sys def breakdate(date): """ breakdate takes a date as an argument in the format '1 Jan 2010' and returns a tuple of size 3 The tuple contains three integer values (day,month,year) """ match = re.search(r'(\d+)\s(\w+)\s(\d+)',date) day = 0 month = '' year = 0 if not match: sys.stderr.write('\nError in reading date!!!\n') sys.exit(1) day = int(match.group(1)) month = match.group(2) year = int(match.group(3)) month = month.lower() if month[:3] == 'jan': month = 1 elif month[:3] == 'feb': month = 2 elif month[:3] == 'mar': month = 3 elif month[:3] == 'apr': month = 4 elif month[:3] == 'may': month = 5 elif month[:3] == 'jun': month = 6 elif month[:3] == 'jul': month = 7 elif month[:3] == 'aug': month = 8 elif month[:3] == 'sep': month = 9 elif month[:3] == 'oct': month = 10 elif month[:3] == 'nov': month = 11 elif month[:3] == 'dec': month = 12 return (day,month,year) def compare(date1,date2): """ compare takes two dates as agruments (date1,date2) in the format '1 Jan 2014' and returns an integer value. The value returned is -1 if date1 is older, 0 if both are same and 1 if date1 is newer. """ d1,m1,y1 = breakdate(date1) d2,m2,y2 = breakdate(date2) if y2>y1: return -1 elif y1>y2: return 1 else: if m2>m1: return -1 elif m1>m2: return 1 else: if d2>d1: return -1 elif d1>d2: return 1 else: return 0 def main(): first = input('enter date : ') second = input('enter date : ') res = compare(first,second) if res==-1: print second + ' is later' elif res==0: print 'both are same' else: print first + ' is later' if __name__ == '__main__': main()
notas = [] res = "si" while res=="si": no=int(input("ingrese nota: ")) notas.append(no) res=input("desea continuar si/no: ") nota = open("notasguardadas.txt","w") for no in notas : nota.write(str(notas) nota.write("\n") nota.close()
import numpy as np #for Numerical function import matplotlib #for ploting graph import matplotlib.pyplot as plt from matplotlib import style import pandas as pd #for different data frame xs=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] ys=[10,12,20,22,21,25,30,21,32,34,35,30,50,45,55,60,66,64,67,72,74,80,79,84] len(xs),len(ys) #slope=(mean(x) * mean(y) – mean(x*y)) / ( mean (x)^2 – mean( x^2)) #intercept(c)=mean(y) – mean(x) * m def slope_intercept(x_val,y_val): x=np.array(x_val) y=np.array(y_val) m=(((np.mean(x)*np.mean(y))-np.mean(x*y))/((np.mean(x)*np.mean(x))-np.mean(x*x))) m=round(m,2) b=(np.mean(y) - np.mean(x)*m) b =round(b,2) return m,b slope_intercept(xs,ys) m,b=slope_intercept(xs,ys) reg_line = [(m*x)+b for x in xs] plt.scatter(xs,ys,color="red") plt.plot(xs,reg_line) plt.ylabel("dependent variable") plt.xlabel("Independent variable") plt.title("Regression Line") plt.show()
# Learn how to get the current hour of your computer import datetime now = datetime.datetime.now() print (now.year, now.month, now.day, now.hour, now.minute, now.second)
# Write a function that extracts the even items in a given integer list, named get_even_list, # takes 1 parameter: l, where l is the given integer list ([1, 4, 5, -1, 10] for example), # returns a new list contains only even numbers ([4, 10] if the given list is [1,4,5,-1,10]) newl = [] def get_even_list(l): for i in range(0,len(l)): if l[i] % 2 == 0: newl.append(l[i]) return(newl) print(get_even_list([1, 2, 5, -10, 9, 6]))
x = int(input("x = ")) op = input("Operation(+, -, *, /): ") y = int(input("y = ")) print("* " * 20) res = 0 if op == "+": res = x + y elif op == "-": res = x - y elif op == "*": res = x * y elif op == "/": res = x / y else: print("Buzz") break # nên rút print ra ngoài print("{0} {1} {2} = {3}".format(x, op, y, res)) # def calc
import numpy as np import cv2 #numpy.ones reshapes the array--width600,height 800 rect=np.ones((600,800,3),dtype=np.uint8)*255 #bgr--red color below one #10 is the thickness cv2.rectangle(rect,(0,int(600/2)),(int(800/2),599),(0,0,255),10) cv2.imshow("image",rect) cv2.waitKey() cv2.destroyAllWindows() #bgr below in green #-1 so no border cv2.rectangle(rect,(int(800/2),0),(799,int(600/2)),(0,255,0),9) cv2.imshow("image",rect) cv2.waitKey() cv2.destroyAllWindows() #image: It is the image on which rectangle is to be drawn. #start_point: It is the starting coordinates of rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). #end_point: It is the ending coordinates of rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). #color: It is the color of border line of rectangle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color. #thickness: It is the thickness of the rectangle border line in px. Thickness of -1 px will fill the rectangle shape by the specified color. #Return Value: It returns an image.
#!/usr/bin/env python # -*- coding: utf-8 -*- '格式转化工具' __author__='haipenge' class FormatUtil(object): #驼峰命名格式转下划线命名格式 def camel_to_underline(self,camel_format): underline_format='' if isinstance(camel_format, str): for _s_ in camel_format: underline_format += _s_ if _s_.islower() else '_'+_s_.lower() while underline_format[0] == '_': underline_format = underline_format[1:] return underline_format #将下划线命名转化为驼峰命名 def underline_to_camel(self,underline_format): camel_format = '' if isinstance(underline_format, str): for _s_ in underline_format.split('_'): camel_format += _s_.capitalize() return camel_format #首字母小写 def lower_start(self,str): res = '' if str is not None: res = str[0].lower() + str[1:] return res #首字母大写 def upper_start(self,str): res = '' if str is not None: res = str[0].upper() + str[1:] return res if __name__ == "__main__": print 'start format util...'
#Dispalys the tic tac toe board def display_board(board): print('\n'*100) print(board[7]+' | '+board[8]+'|'+board[9]) print('-----------') print(board[4]+' | '+board[5]+'|'+board[6]) print('-----------') print(board[1]+' | '+board[2]+'|'+board[3]) #Takes in the players input to ask if X or O def player_input(): marker = '' while marker != 'X' and marker != 'O': marker = input('Player 1, choos X or O: ').upper() if marker == 'X': return ('X', 'O') else: return ('O', 'X') print('Welcome to Tic Tac Tow') while True: the_board = [' ']*10 player1_marker,player2_marker = player_input()
from art import logo, stages from allwords import word_list import random lives=6 chosenWord= random.choice(word_list) print(logo) #Generar la lista en blanco print(chosenWord) list=[] for i in range(len(chosenWord)): list += "_" end_of_game=False while not end_of_game: userGuess=input('Guess a letter: ').lower() if userGuess in list: print(f'Ya has intentado la letra:{userGuess}') for x in range(len(chosenWord)): letter = chosenWord[x] if letter == userGuess: list[x]= letter print(list) if "_" not in list: end_of_game=True print('You Win!') if userGuess not in chosenWord: lives-=1 print(f'The letter: {userGuess}, is not in the word') print(stages[lives]) #lives aplica como index porque son Int. if lives==0: end_of_game=True print('You lose!')
''' Author : Nikhil Gabhane Date : Sept 20, 2016 ''' class encryption(object): def __init__(self): self.letters = "acdegilmnoprstuw" def reverse_hash(self,hash_code): res = [] if hash_code == 7: return "It's an Empty String" if hash_code <259: return "Invalid hash code" try: tmp = hash_code % 37 hash_code = hash_code - tmp res.insert(0,self.letters[tmp]) while hash_code != 37 * 7 and hash_code > 0: hash_code = hash_code/37 tmp = hash_code % 37 res.insert(0,self.letters[tmp]) hash_code = hash_code - tmp except: return "Invalide hash code" res = "".join(res) if hash_code < 0: print "Invalid hash code" else: return res if __name__ == "__main__": #This try block will ensure entered hash code doesn't contain characters try: hash_code = int(raw_input("Please enter hash code: ")) enc = encryption() res = enc.reverse_hash(hash_code) print "Output :", res except: print "Output : Invalid hash code"
# __dict__ class DictDemo(object): def __init__(self): self.name = "li" self.age = 18 def __setattr__(self, key, value): print("__setattr__ is running") super().__setattr__(key, value) def __delattr__(self, item): print("__delattr__ is running ") if item == "name": raise AttributeError("name 属性不允许删除") elif item == "age": super().__delattr__(item) if __name__ == '__main__': print(DictDemo.__dict__) print(DictDemo().__dict__) obj = DictDemo() obj.name = "陈" print(obj.name) del obj.age print(obj.age)
class MyClass(object): pass def study(): pass def __init__(self, name): self.name = name def hello(self): print(f'My name is{self.name}') # 所有累都是type创建的对象 # 'Student'类名 ‘(object,)继承的对象’,后面字典内为类中的属性 Student = type('Student', (object,), { '__init__': __init__, 'say': hello }) if __name__ == '__main__': stu = Student("小明") stu.say() print("hello")
""" This is the Language gramatic. The first block determine how sentences are built. The second block determines what each token on a sentece is. SENTENCES: S = [Expressao]+ Expressao = (declaracao | operacao | forloop | print | ifbloco ) fimDeExpressao declaracao = (declaradorVariavel|null) variavel (operadorDeclaracao (valor | variavel | operacao) | null) null = operacao = operacaoBinaria | operacaoUnaria operacaoBinaria = (variavel | operacao | valor) operador (variavel | operacao | valor) operacaoUnaria = (variavel) operador operador forloop = inicializadorFor AbreParenteses (declaracao | null) ; (condicao) ; (declaracao | null) FechaParenteses Bloco Bloco = aberturaBloco [Expressao]+ fechamentoBloco ifbloco = inicializadorIf AbreParenteses condicao FechaParenteses Bloco condicao = (variavel | operacao | valor) operadorBooleano (variavel | operacao | valor) valor = valorNumerico | valorString | valorBooleano TOKENS: aberturaBloco = '{' fechamentoBloco = '}' operadorBooleano = == | != | > | < | >= | <= | || | && operadorDeclaracao = = operador = + | - | / | * declaradorVariavel = var inicializadorFor = for inicializadorIf = if fimDeExpressao = ; variavel = [a-zA-Z]+ valorNumerico = [0-9]+ valorString = '.' valorBooleano = true | false AbreParenteses = ( FechaParenteses = ) """ """ This code is responsible to convert written code to a list of Tokens """ # (token_name, token_value) tokens = [] # The following lists contain characters that end other tokens: # For example '10>5', the character '>' marks the end of the '10' token # while still being a token itself # Another example '10 > 5' the empty space ' ' marks the end of the '10' token # though this time the empty space is not a valid token endskipchars = [' ','\n'] endnotskipchars = [';','(',')','','+','-','/','*','}','=','!','>','<','|','&',] # Text is the string that will be parsed into tokens text = "" with open('code.y', 'r') as file: text = file.read() # Buffer is a string of charactes. # Since some tokens are multiple characters in length it's necessary # to store them while being read buffer = "" # This function takes the buffer after receiving a end-token-character # and tries to match it to any of the possible existing tokens def attempt_token(char): global buffer if buffer == '': return try: # Tries to convert the token into a numerical value value = float(buffer) tokens.append( ('valorNumerico',value) ) buffer = "" except: # If the buffer starts with single quotes, treat it as a string if not (buffer.startswith('\'') or buffer.endswith('\'')): ## not numerical tokens cannot start with numbers if buffer[0] in list(map(lambda a: str(a),range(10))): raise ValueError(f'Invalid token {idx}') # Since both tokens = and == have the same starting value # and the = is a end-token-character, this makes sure # == is not interpreted as 2 different tokens if buffer == "=" and char != "=": tokens.append( ('operadorDeclaracao',buffer)) buffer = "" # The above is also true for the tokens <= >= < and > elif buffer in ['>','<'] and char != '=': tokens.append( ('operadorBooleano',buffer)) # In case the next char is a = and the buffer was any of the above # Continue the process (stop trying to match the current buffer to a token) elif (buffer == "=" or buffer in ['>','<']) and char == "=": return else: # if none of the other options was correct # Attemp these final methods of matching the first # Chars as specific tokens and then re-run the Matching Algorithm if buffer.startswith("=="): tokens.append( ('operadorBooleano',buffer[0:2])) buffer = buffer[2:] attempt_token(char) elif buffer.startswith('>') or buffer.startswith('<'): tokens.append( ('operadorBooleano',buffer[0])) buffer = buffer[1:] attempt_token(char) elif buffer.startswith("="): tokens.append( ('operadorDeclaracao',buffer[0])) buffer = buffer[1:] attempt_token(char) else: ## If none of the above matching worked, then this token is a valid variable tokens.append( ('variavel',buffer) ) else: tokens.append( ('valorString',buffer) ) # Empty the buffer to read another Token buffer = "" # This loop will go through all characters in the code for idx, char in enumerate(text): # If this character is a end-token-character call the function to match it if char in endskipchars or char in endnotskipchars: if buffer != "": attempt_token(char) if not char in endnotskipchars: continue buffer += char # These if-elif chains try to match the current buffer to the following tokens # The tokens that are missing here are attempted to be matched in the `attempt_token` function if buffer == "var": tokens.append( ('declaradorVariavel','var') ) buffer = "" elif buffer == "for": tokens.append( ('inicializadorFor','for') ) buffer = "" elif buffer == "if": tokens.append( ('inicializadorIf','if') ) buffer = "" elif buffer == ";": tokens.append( ('fimDeExpressao',';') ) buffer = "" elif buffer == "(": tokens.append( ('AbreParenteses','(') ) buffer = "" elif buffer == ")": tokens.append( ('FechaParenteses',')') ) buffer = "" elif buffer == "true": tokens.append( ('valorBooleano',buffer)) buffer = "" elif buffer in ['==','!=','>=','<=','||','&&']: tokens.append( ('operadorBooleano',buffer)) buffer = "" elif buffer in ['+','-','/','*']: tokens.append( ('operador',buffer)) buffer = "" elif buffer == '{': tokens.append( ('aberturaBloco',buffer)) buffer = "" elif buffer == '}': tokens.append( ('fechamentoBloco',buffer)) buffer = "" # One final call to match what was left in the buffer attempt_token(' ') # This loop will save the token list with open('code.t','w') as file: for p in tokens: file.write(f'{p[0]}<>{p[1]}\n')
"""IP Validation check. Fundamental checks for: 1. Whether or not a cidr is listed within the cidr field. 2. Cidr blocks larger than a /13 3. Leading zero's within network ip address. 4. Checks for a valid Network Address. """ import os import ipaddress import re import logging def out_log(loggs, logfile): """Updates log file: Log File name: -- validation check log.txt """ with open(logfile, 'w') as file: for log in loggs: file.write(log) file.write('\n') def validation_check(check, logfile): """Performs the following actions: 1. Checks to make sure there is a "/" within network address. 2. Checks for leading zero's within each octet of the network address. 3. Checks to see if the network address has host bits set. Creates a log and updates the following arg for logfile creation: Argument: -- erroredlist """ error_list = [] for item in check: _ip = item[0].value if _ip == 'CIDR': continue if '/' not in _ip: error_list.append(str(_ip + ' does not appear to contain a CIDR')) continue if int(_ip.strip().split('/')[1]) not in list(range(13, 33)): error_list.append(str(_ip + ' out of range CIDR')) continue # if not re.match(regex, str(ip.strip().split('/')[0])): # erroredlist.append(str(ip + ' Failed Regex Match')) # continue octets = re.findall(r"[\d']+", _ip) leadzerostate = "" for octs in octets: # Beggining check for lead zero if len(octs) > 1 and octs.startswith('0'): leadzerostate = True break if leadzerostate: octets[:] = [str(int(x)) for x in octets] octets[3:] = ['/'.join(octets[3:])] new_octets = '.'.join(octets[:]) error_list.append(str(_ip + " Leading zero's in IP please update to: " + new_octets)) try: if ipaddress.ip_network(_ip.strip()): pass except ValueError as err: error_list.append(str(err).replace("'", "")) for index, i in enumerate(error_list): if 'has host bits set' in i: error_list[index] = i + ' Network is: ' + \ str(ipaddress.IPv4Interface((i.strip()).split(' ') [0]).network) continue if error_list: out_log(error_list, logfile) return 'Unclean' return True if __name__ == '__main__': # getting root directory PROJECT_DIR = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir) # setup logger LOG_FMT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(level=logging.INFO, format=LOG_FMT)
import random def roll_at_max_M_times(numbers, M): value = 0 for _ in range(M): value = random.choice(numbers) if random.random() <= (1.0 / M): break return value def roll_experiment(n, M, numbers): sum_win_amount = 0 for _ in range(n): sum_win_amount += roll_at_max_M_times(numbers, M) expected_win_amount = sum_win_amount / n return expected_win_amount def expected_winnings(N, M): # list of numbers numbers = list(range(1, N + 1)) # roll M times at max # and either stop at a value and take it as a dollar amount or # roll once again # repeat the experiment a large number of times n = 100000 expected_win = roll_experiment(n, M, numbers) return expected_win if __name__ == "__main__": N = 100 M = 5 expected_win = expected_winnings(N, M) print("expected win amount =", expected_win)
class FormattingException(Exception): pass def format_int(input_string): try: result = int(input_string) except ValueError: raise FormattingException("Couldn't parse as int.") return result def format_positive_int(input_string): result = format_int(input_string) if result >= 0: return result else: raise FormattingException("Couldn't parse as positive int.") def format_float(input_string): try: result = float(input_string) except ValueError: raise FormattingException("Couldn't parse as float.") return result def format_list(input_string): try: result = [int(curr) for curr in input_string.split(" ") if len(curr) > 0] except ValueError: raise FormattingException("Couldn't parse the numbers entered.\n\ Please make sure you entered a list on numbers with spaces as separators.") return result def list_to_str(input_list): return " ".join([str(val) for val in input_list])
#-*- coding: utf-8 -*- ''' # =========================================================== # from Python » Documentation » The Python Standard Library » 25. Development Tools » import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(),'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(),['hello','world']) with self.assertRaises(TypeError): s.split(2) if __name__ == '__main__': unittest.main() ''' # =========================================================== ''' # 测试 def test.py def sum(x,y): return x+y def sub(x,y): return x-y import unittest import myclass class Test(unittest.TestCase): def setUp(self): ##初始化工作 pass def tearDown(self): #退出清理工作 pass # 具体的测试用例,一定要以test开头 def testsum(self): self.assertEqual(myclass.sum(2,3),5) def testsub(self): self.assertEqual(myclass.sub(3,2),2,'False 3-2=1 !!!') if __name__ == '__main__': unittest.main() ''' # =========================================================== ''' # 测试 class class Myclass(object): def __init__(self): pass def sum(self,x,y): return x+y def sub(self,x,y): return x-y import unittest import myclass class Test(unittest.TestCase): def setUp(self): self.tclass = myclass.Myclass() def testsum(self): self.assertEqual(self.tclass.sum(1,3),4) def testsub(self): self.assertEqual(self.tclass.sub(3,1),2) if __name__ == '__main__': unittest.main() ''' # =========================================================== ''' 加载测试套件 from http://www.jb51.net/article/65856.htm >>import unittest >>dir(unittest) >>memblist = ['FunctionTestCase', 'TestCase', 'TestLoader', 'TestProgram', 'TestResult',\ 'TestSuite','TextTestRunner', 'defaultTestLoader','findTestCases', 'getTestCaseNames', \ 'main', 'makeSuite'] >>for memb in memblist: .. cur = getattr(unittest, memb) .. print help(cur) 'FunctionTestCase':函数测试用例,即给一个函数作为参数,返回一个testcase实例,可选参数有set-up,tear-down方法 'TestCase':所有测试用例的基本类,给一个测试方法的名字,返回一个测试用例实例 'TestLoader':测试用例加载器,其包括多个加载测试用例的方法。返回一个测试套件 loadTestsFromModule(self, module)--根据给定的模块实例来获取测试用例套件 loadTestsFromName(self, name, module=None) --根据给定的字符串来获取测试用例套件,字符串可以是模块名,测试类名,测试类中的测试方法名,或者一个可调用的是实例对象 这个实例对象返回一个测试用例或一个测试套件 loadTestsFromNames(self, names, module=None) --和上面功能相同,只不过接受的是字符串列表 loadTestsFromTestCase(self, testCaseClass)--根据给定的测试类,获取其中的所有测试方法,并返回一个测试套件 'TestProgram':命令行进行单元测试的调用方法,作用是执行一个测试用例。其实unittest.main()方法执行的就是这个命令, 而这个类实例时默认加载当前执行的作为测试对象, 原型为 __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=xx, testLoader=xx) 其中module='__main__'就是默认加载自身 'TestResult':测试用例的结果保存实例,通常有测试框架调用 'TestSuite':组织测试用例的实例,支持测试用例的添加和删除,最终将传递给testRunner进行测试执行 'TextTestRunner':进行测试用例执行的实例,其中Text的意思是以文本形式显示测试结果。显示测试名称,即完成的测试结果,其过同执行单元测试脚本时添加-v参数 'defaultTestLoader':其实就是TestLoader 'findTestCases', 'getTestCaseNames':这个2个就不用解释了 'main': 其实就是TestProgram 'makeSuite':通常是由单元测试框架调用的,用于生产testsuite对象的实例 整个单元测试框架 分三步走: testloader --> makesuite组装成testsuite --> testrunner执行 详解:第一步testloader根据传入的参数获得相应的测试用例,即对应具体的测试方法, 然后makesuite在把所有的测试用例组装成testsuite,最后把testsiute传给testrunner进行执行 【测试用例文件必须为test开头,如:testxxx.py, 当然这个文件本身是一个单元测试的文件】 import unittest import myclass import re,os,sys def testAllinCurrent(): path = os.path.abspath(os.path.dirname(sys.argv[0])) files = os.listdir(path) test = re.compile("test\.py{1}quot;", re.IGNORECASE) files = filter(test.search, files) filenameToModuleName = lambda f: os.path.splitext(f)[0] moduleNames = map(filenameToModuleName, files) modules = map(__import__, moduleNames) load = unittest.defaultTestLoader.loadTestsFromModule return unittest.TestSuite(map(load, modules)) if __name__ == "__main__": unittest.main(defaultTest="regressionTest") ''' # =========================================================== ''' Python之自动单元测试之一(unittest使用实例) from http://www.tuicool.com/articles/263m22 myclass.py文件 class Widget(): def __init__(self,size=(40,40)): self._size = size def getSize(self): return self._size def resize(self,width,height): if width < 0 or height < 0: raise ValueError,'illegal size' self._size = (width,height) from myclass import Widget import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.lxf = Widget() def tearDown(self): self.lxf.dispose() self.lxf = None def testSize(self): self.assertEqual(self.lxf.getSize(),(40,40)) # 对Widget类中getSize()方法的返回值和预期值进行比较,确保两者是相等的 def testResize(self): self.lxf.resize(100, 100) self.assertEqual(self.lxf.getSize(), (100, 100)) def suite(): suite = unittest.TestSuite() suite.addTest(WidgetTestCase("testSize")) suite.addTest(WidgetTestCase("testResize")) return suite if __name__ == "__main__": unittest.main(defaultTest = 'suite') #------------------------------------- TestSuit 测试用例集 from http://www.tuicool.com/articles/263m22 完整的单元测试很少只执行一个测试用例,开发人员通常都需要编写多个测试用例才能对某一软件功能进行比较完整的测试,这些相关的测试用例称为一个测试用例集,在PyUnit中是用TestSuite类来表示的。 在创建了一些TestCase子类的实例作为测试用例之后,下一步要做的工作就是用TestSuit类来组织它们。PyUnit测试框架允许Python程序员在单元测试代码中定义一个名为suite()的全局函数,并将其作为整个单元测试的入口,PyUnit通过调用它来完成整个测试过程。 ''' from myclass import Widget import unittest class WidgetTestCase(unittest.TestCase): #def __init__(self): # unittest.TestSuite.__init__(self,map(WidgetTestCase,("testSize","testResize"))) def setUp(self): self.lxf = Widget() def tearDown(self): pass #self.lxf.dispose() #self.lxf = None def testSize(self): self.assertEqual(self.lxf.getSize(),(40,40)) def testResize(self): self.lxf.resize(100, 100) self.assertEqual(self.lxf.getSize(), (100, 100)) if __name__ == "__main__": suite = unittest.TestSuite() suite.addTest(WidgetTestCase("testSize")) suite.addTest(WidgetTestCase("testResize")) runner = unittest.TextTestRunner() runner.run(suite) 如果Python程序员能够按照约定(以test开头)来命名所有的测试方法,那就只需要在测试模块的最后加入如下几行代码即可: if __name__ == "__main__": unittest.main() 图形界面测试脚本unittestgui.py 将其复制到当前目录后,可以执行下面的命令来启动该测试工具,对main_runner.py脚本中的所有测试用例进行测试: python unittestgui.py main_runner # =========================================================== # =========================================================== # =========================================================== # =========================================================== # =========================================================== # =========================================================== # =========================================================== # =========================================================== # =========================================================== # ===========================================================
#-*- coding: utf-8 -*- # 两个对象 共享参数(非继承) class Lxf1(object): session = 200 def __init__(self): self.__x = r'This is "class lxf1 -- def __init__" ' def lxf1_print(self): lxf = 100 lxf1 = 200 return lxf #,lxf1 class Lxf2(object): def __init__(self): self.lxf1 = Lxf1() def print_anying(self): print self.lxf1.lxf1_print() # print Lxf1对象 lxf1_print函数的 lxf和lxf1 print self.lxf1.session # print Lxf1对象 session a = self.lxf1.lxf1_print() b = a+1000 print b lxf = Lxf2() lxf.print_anying()
class Node: def __init__(self, key): self.left = None self.right = None self.data = key def inorder(temp): if not temp: return # LVR inorder(temp.left) print(temp.data) inorder(temp.right) def mirror(rootnode): if not rootnode: return q = [] q.append(rootnode) while len(q): root = q.pop(0) if root.left and root.right: temp = root.left root.left = root.right root.right = temp q.append(root.left) q.append(root.right) elif root.left: root.right = root.left root.left = None q.append(root.right) elif root.right: root.left = root.right root.right = None q.append(root.left) return rootnode if __name__ == "__main__": root = Node(10) root.left = Node(11) root.left.left = Node(7) root.left.right = Node(12) root.right = Node(9) root.right.left = Node(15) root.right.right = Node(8) print("Original Tree:") inorder(root) root = mirror(root) print() print("Mirrored Tree:") inorder(root)
# Python lab assignment 3 # AuthorL: Sunny Kriplani # Student ID: 119220438 # This program prints the possible match of two persons from a marriage # record data import re f1 = open("mary_roche.txt") f2 = open("nicholas.txt") mary = f1.read() nicho = f2.read() mary_l = re.split("Marriage of ", mary) nicho_l = re.split("Marriage of ", nicho) # Remove the first list element as it is splitted on "Marriage of" so 1st # element will always be empty of not required text mary_l.remove(mary_l[0]) nicho_l.remove(nicho_l[0]) # Regex to fetch the year, quarter, location, page and Volume from a user data regex_yr = re.compile(r"Returns Year.*") regex_qtr = re.compile(r"Returns Quarter.*") regex_loc = re.compile(r"SR District/Reg Area.*") regex_pg = re.compile(r"Returns Page No.*") regex_vol = re.compile(r"Returns Volume No.*") for i in mary_l: yr_m = regex_yr.search(i).group().split("\t")[1] qtr_m = regex_qtr.search(i).group().split("\t")[1] loc_m = regex_loc.search(i).group().split("\t")[1] page_m = regex_pg.search(i).group().split("\t")[1] vol_m = regex_vol.search(i).group().split("\t")[1] for j in nicho_l: yr_n = regex_yr.search(j).group().split("\t")[1] qtr_n = regex_qtr.search(j).group().split("\t")[1] loc_n = regex_loc.search(j).group().split("\t")[1] page_n = regex_pg.search(j).group().split("\t")[1] vol_n = regex_vol.search(j).group().split("\t")[1] # Two persons are marriad if their location, volume, page, quarter # and year of marriage record matches if(yr_m == yr_n and qtr_m == qtr_n and page_m == page_n and loc_m == loc_n and vol_m == vol_n): print() bride = i.split("\n")[0] groom = j.split("\n")[0] print("Possible Match!") print(groom + " and " + bride + " in " + loc_m + " in " + yr_m) print("Quarter = " + qtr_m + ", Volume = " + vol_m + ", Page = " + page_m)