text
stringlengths
37
1.41M
# Input: An integer k and a string Text. # Output: DeBruijnk(Text), in the form of an adjacency list. from collections import defaultdict def DeBruijn(Text, k): deBruijn = defaultdict(list) t = len(Text) for i in range(0, t - k + 1): kmer = Text[i:i+k-1] deBruijn[kmer].append(Text[i+1:i+k]) return deBruijn # print(DeBruijn('ACTGCTA', 3)) # result = DeBruijn('ACTGCTA', 3) # Fetch Input inputDirectory = '/Users/tleis/PycharmProjects/BioInformaticsI/03_GenomeSequencing/dataset_199_6.txt' inputFile = open(inputDirectory, 'r') k = int(inputFile.readline()) text = str(inputFile.readline()) text = text.replace('\n','') text = 'TAATGGGATGCCATGTT' k = 3 inputFile.close() #print(*DeBruijn(str(text),int(k)), sep='\n') result = DeBruijn(text, k) # Change format into XXX->YYY output = [] for key, values in result.items(): line = key for value in values: if '->' in line: line = line + ',' + value else: line = line + ' -> ' + value output.append(line) print(*output, sep='\n')
# Input: A DNA string Genome # Output: A list containing all integers i minimizing Skew(Prefix_i(Text)) over all values of i (from 0 to |Genome|) def MinimumSkew(Genome): positions = [] # output variable array = SkewArray(Genome) print('array, ', array) minimum = min(array) print('minimum', minimum) for i in range(len(array)): if array[i] == minimum: print('i: ', i) positions.append(i) return positions # Input: A String Genome # Output: SkewArray(Genome) # simple implementation, you can also use the separate function that accounts for new lines def SkewArray(Genome): skew = [0] score = {"A":0, "T":0, "C":-1, "G":1} for i in range(len(Genome)): skew.append(score[Genome[i]] + skew[i]) return skew Sequence = "ATGCATGGCCTACGTACTA" m = MinimumSkew(Sequence) print('minimum skew ', m)
import unittest MS = __import__('02_MedianString') class MedianStringCase(unittest.TestCase): # there is actually two solutions for sample dataset def test_sample(self): Dna = ['AAATTGACGCAT','GACGACCACGTT','CGTCAGCGCCTG','GCTGAGCACCGG','AGTACGGGACAG'] expected = 'ACG' expected2= 'GAC' output = MS.MedianString(Dna,3) self.assertEqual((expected or expected2), output) # is the output of correct length? (exactly of length k) def test_dataset1(self): Dna = ['ACGT','ACGT','ACGT'] k = 3 expected = 'ACG' expected2= 'CGT' output = MS.MedianString(Dna, k) self.assertEqual((expected or expected2), output) # Checks if the code considers k-mer that are not in the input def test_dataset2(self): Dna = ['ATA', 'ACA', 'AGA', 'AAT', 'AAC'] k = 3 expected = 'AAA' output = MS.MedianString(Dna, k) self.assertEqual(expected, output) # check if output contains a single k-mer def test_dataset3(self): Dna = ['AAG', 'AAT'] k = 3 expected = 'AAG' expected2= 'AAT' output = MS.MedianString(Dna, k) self.assertEqual((expected or expected2), output) if __name__ == '__main__': unittest.main()
def main(): Reverse("ATAG") Complement("ATGC") def Complement(Pattern): result = "" for num in range(0,len(Pattern)): if (Pattern[num] == 'A'): result+='T' elif (Pattern[num] == 'T'): result+='A' elif (Pattern[num] == 'G'): result+='C' elif (Pattern[num] == 'C'): result+='G' print(result) def Reverse(Pattern): result="" for num in range(len(Pattern),0,-1): result+=Pattern[num-1] print(result) if __name__ == "__main__": main()
fname=input("Enter a file name : ") f=open(fname,"r") chr=0 words=0 lines=0 for l in f: lines+=1 wordlist=l.split() words+=len(wordlist) chr+=len(l) print("characters :",chr) print("Words : ",words) print("Lines : ",lines)
def func(str): newstr='' for s in str: if s not in "!()-[]{};:''',\,<>/?@#$%^&*_~": newstr+=s return newstr str=input("Enter input : ") print(func(str))
import random def print_mat(n): for i in range(n): for j in range(n): print(random.randint(0,1),end=' ') print() n=int(input("Enter n")) print_mat(n)
def isconsecutive(l): for i in range(len(l)-3): c=[l[i] for j in range(4)] #print(c) if(l[i:i+4]==c[0:4]): return True return False listitem=input("Enter list element") li=listitem.split() print(isconsecutive(li))
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ checker = -1 for cur in range(len(nums)): if checker < 0 and nums[cur] == 0: checker = cur if checker >= 0 and nums[cur] != 0: nums[checker], nums[cur] = nums[cur], nums[checker] checker += 1 test_arr = [1, 3, 12] obj = Solution() obj.moveZeroes(test_arr) print(test_arr)
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ path = path.split('/') result = '' pass_dir = ['', '.'] stack = [] for dir in path: if dir not in pass_dir: if dir == '..': if len(stack) > 0: stack.pop() else: stack.append(dir) else: continue while len(stack) > 0: adder = stack.pop() result = '/' + adder + result if result == '': return '/' return result obj = Solution() path = "/home/..." print(obj.simplifyPath(path))
class Solution(object): def countSegments(self, s): """ :type s: str :rtype: int """ return len(s.split(' ')) input_str = "Hello, my name is John" obj = Solution() print(obj.countSegments(input_str))
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: int """ odd_flag = False length = 0 frequency = [0] * 52 for char in s: if ord(char) >= ord('a'): idx = ord(char) - ord('a') + 26 else: idx = ord(char) - ord('A') frequency[idx] += 1 for freq in frequency: if freq == 0: continue elif freq % 2 == 0: length += freq else: if odd_flag: length += (freq - 1) else: length += freq odd_flag = True if length > 1010: length = 1010 return length in_str = "abccccdd" obj = Solution() print(obj.longestPalindrome(in_str))
# iterative solution # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root is None: return None a = 0 b = 0 cur = root if p.val <= q.val: a, b = p.val, q.val else: a, b = q.val, p.val while not (a <= cur.val <= b): if cur is None: break if b < cur.val: cur = cur.left elif cur.val < a: cur = cur.right return cur test_arr = [6,2,8,0,4,7,9] root = None cur = None queue = [] for i in range(0, len(test_arr), 2): if i == 0: root = TreeNode(test_arr[i]) queue.append(root) else: cur = queue.pop(0) cur.left = TreeNode(test_arr[i-1]) cur.right = TreeNode(test_arr[i]) queue.append(cur.left) queue.append(cur.right) p = TreeNode(2) q = TreeNode(4) obj = Solution() result = obj.lowestCommonAncestor(root, p, q) if result is None: print(result) else: print(result.val)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def helper(self, node, target, before_sum, dict): if node is None: return complement = before_sum + node.val - target if complement in dict: self.result += dict[complement] dict.setdefault(before_sum + node.val, 0) dict[before_sum + node.val] += 1 self.helper(node.left, target, before_sum + node.val, dict) self.helper(node.right, target, before_sum + node.val, dict) dict[before_sum + node.val] -= 1 return def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int """ self.result = 0 self.helper(root, sum, 0, {0: 1}) return self.result
# max heap implementation practice import math class MaxHeap(object): def __init__(self): self.data = [] def get_size(self): return len(self.data) # find parent index of last leaf (parent of last leaf = last parent) # compute by length of array (length) @staticmethod def get_last_parent(length): return int(length / 2) - 1 # for array A, compare i'th (idx'th) element with its children, within range of 0~(length-1)th elements @staticmethod def compare_and_swap(idx, arr, length): # compute index of last leaf's parent (=last parent) last_parent_idx = MaxHeap.get_last_parent(length) # in case of idx is larger than last parent index if idx > last_parent_idx: return None # compute left/right child index of ith element left = (idx+1)*2-1 right = (idx+1)*2 # if idx'th element is last parent and tree's length is even, last leaf must be left child if idx == last_parent_idx and (length % 2) == 0: larger_child = left elif arr[left] > arr[right]: larger_child = left else: larger_child = right # if value of larger child is larger than its parent, swap and return swapped location if arr[larger_child] > arr[idx]: arr[larger_child], arr[idx] = arr[idx], arr[larger_child] return larger_child # in case any statement does not executed return None # heapify(max-heapify) def heapify(self,length): idx = 0 # start from root # compare ith element with its child and swap if larger child is also larger than parent. # and compare/swap again along swapped location, until reach its end continuously... while idx is not None: idx = MaxHeap.compare_and_swap(idx, self.data, length) # add value, attach data at last and then do heapify from its parent to root def add(self,value): self.data.append(value) length = self.get_size() parent_idx = MaxHeap.get_last_parent(length) for j in range(parent_idx, -1, -1): MaxHeap.compare_and_swap(j, self.data, len(self.data)) # remove max value of heap (popping root) def pop(self): last = self.get_size() # if heap is empty, return None if last <= 0: print('no elements in heap') return None # if heap has only root, return root if last == 1: return self.data[0] # swap root and last element, and max-heapify except swapped last one self.data[0], self.data[last-1] = self.data[last-1], self.data[0] self.heapify(last-1) # return and remove last element (max value) return self.data.pop(last-1) # heat sort (return sorted array, swallow copied one) def sorted_array(self): length = self.get_size() if length <= 0: print('no elements in heap') return output = self.data[:] # swallow copy to retain heat tree # for each loop, swap root and last element. # and then heapify swallow copied one, except swapped last element # do it continuously until sorted array completed for last in range(length-1, -1, -1): output[0], output[last] = output[last], output[0] idx = 0 while idx is not None: idx = MaxHeap.compare_and_swap(idx, output, last) return output # print heap data as an array def show_array(self): print(self.data) # print heap tree def show_tree(self): if len(self.data) <= 0: print('no elements in heap') return length = len(self.data) total_row = int(math.log2(length)) # total number of row(level) of tree. starting from 0 for row in range(total_row + 1): # for each row (level) for i in range((2**row-1), 2**(row+1)-1): # deal each item in certain row(level) # if tree is not full binary tree, loop shall be stopped at last element if i == length: break reversed_row = total_row - row # counting row number reversely. first_space = 2**reversed_row - 1 # number of space characters at left end rest_space = 2**(reversed_row+1) - 1 # number of space characters rest for fs in range(first_space): print(' ', end='') print(self.data[i], end='') for rs in range(rest_space): print(' ', end='') print('') # changing row # modify idx'th element of array as x, if user wants to change specific element in specific case def modify_array(self, idx, x): length = self.get_size() if length <= 0: print('no elements in heap') return elif idx < 0 or idx >= length: print('out of index range') return self.data[idx] = x # Max heap implementation test # uncomment each line to test # # print('create empty max heap instance : mh=MaxHeap()\n') # mh = MaxHeap() # print('trying sorting empty heap : mh.sorted_array()') # print(mh.sorted_array(), '\n') # # print('add some elements : 5,3,6,1,2,4,0,4,9') # for idx in [5, 3, 6, 1, 2, 4, 0, 4, 9]: # mh.add(idx) # mh.show_array() # mh.show_tree() # print('number of total elements : ', mh.get_size()) # # print('\ntesting heap sort : mh.sorted_array()') # print(mh.sorted_array(), '\n') # # print('testing heapify : change root as -9') # mh.show_array() # print('to') # mh.modify_array(0, -9) # mh.show_array() # mh.show_tree() # # print('\nnow heapify : mh.heapify()') # mh.heapify(mh.get_size()) # mh.show_array() # mh.show_tree() # # print('\nadd more elements : 89,0,-1,27,44') # for idx in [89, 0, -1, 27, 44]: # mh.add(idx) # mh.show_array() # mh.show_tree() # # print('\ntesting heap sort : mh.sorted_array()') # print(mh.sorted_array(), '\n') # # mh.show_array() # print('pop max (root) test : mh.pop()') # print('popped value is : ', mh.pop()) # print('\nafter pop(), now heap is as below :') # mh.show_array() # mh.show_tree()
class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ if num < 10: return num result = num % 9 if result == 0: return 9 else: return result num = 23 obj = Solution() print(obj.addDigits(num))
class Solution(object): def pattern_checker(self, arr): check_hash = {} cur = 0 result = [] for ch in arr: if ch in check_hash: result.append(check_hash[ch]) else: cur += 1 check_hash[ch] = cur result.append(cur) return result def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ pattern_arr = [] for char in pattern: pattern_arr.append(char) str_arr = str.split() return self.pattern_checker(pattern_arr) == self.pattern_checker(str_arr) pattern = 'abab' str_input = 'dog cat cat dog' obj = Solution() print(obj.wordPattern(pattern, str_input))
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.data = [] self.min_stack = [] self.min_value = 0 def push(self, x): """ :type x: int :rtype: void """ if len(self.data) <= 0 or x < self.min_value: self.min_value = x self.data.append(x) self.min_stack.append(self.min_value) def pop(self): """ :rtype: void """ self.min_stack.pop() last_idx = len(self.min_stack) - 1 if last_idx >= 0: self.min_value = self.min_stack[last_idx] return self.data.pop() def top(self): """ :rtype: int """ last_idx = len(self.data) - 1 return self.data[last_idx] def getMin(self): """ :rtype: int """ last_idx = len(self.min_stack) - 1 return self.min_stack[last_idx]
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def path_by_dfs(self, node, result, path): if node is None: return if node.left is None and node.right is None: result.append(path + str(node.val)) return path = path + str(node.val) + '->' self.path_by_dfs(node.left, result, path) self.path_by_dfs(node.right, result, path) def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ result = [] path = "" self.path_by_dfs(root, result, path) return result test_arr = [] root = None cur = None queue = [] for i in range(0, len(test_arr), 2): if i == 0: root = TreeNode(test_arr[i]) queue.append(root) else: cur = queue.pop(0) cur.left = TreeNode(test_arr[i-1]) cur.right = TreeNode(test_arr[i]) queue.append(cur.left) queue.append(cur.right) obj = Solution() result = obj.binaryTreePaths(root) print(result)
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ if n == 0: return num1_cur_idx = m - 1 num2_cur_idx = n - 1 insert_idx = num1_cur_idx + num2_cur_idx + 1 while num2_cur_idx >= 0: if num1_cur_idx >= 0: if nums1[num1_cur_idx] > nums2[num2_cur_idx]: nums1[insert_idx] = nums1[num1_cur_idx] num1_cur_idx -= 1 insert_idx -= 1 else: nums1[insert_idx] = nums2[num2_cur_idx] num2_cur_idx -= 1 insert_idx -= 1 else: nums1[insert_idx] = nums2[num2_cur_idx] num2_cur_idx -= 1 insert_idx -= 1 sol = Solution() nums1 = [1,2,2,4] m = len(nums1) # m = 0 nums2 = [0,2,3] n = len(nums2) for i in nums2: nums1.append(0) sol.merge(nums1, m, nums2, n) print(nums1)
from pathlib import Path from exceptions import InputRowLengthException, InputColumnLengthException, SolutionFailedException class Helpers: def get_puzzle(self, puzzle_name, directory='puzzles'): """ Inputs: - puzzle_name: 'puzzle1.txt' - directory: 'puzzles' path_in = get_single_puzzle(puzzle_name, directory) -> pathlib Path object Outputs: - split_out: List of Strings read from file * Elements of split_out are the rows of the Sudoku puzzle to be solved - directory: 'puzzles' """ path_in = self.get_single_puzzle(puzzle_name, directory) read_out = path_in.read_text() split_out = read_out.split('\n') return split_out, directory def get_single_puzzle(self, puzzle_name, directory='puzzles'): """ Input: - puzzle_name: 'puzzle1.txt' - directory: 'puzzles' Output: - path_out: Path object of file """ path_out = Path.cwd().joinpath(directory, puzzle_name) return path_out def clean_puzzle(self, puzzle_split): """ Input: - puzzle_split: List of Strings(Rows) Output: - clean_out: List of Lists(Rows of Elements) with empty rows removed """ clean_out = [list(row) for row in puzzle_split if row != ''] return clean_out def check_basic_validity(self, puzzle): """ Input: - puzzle: List of Lists(Rows of Elements) if number of rows (len(puzzle)) is not 9: raise Column Length Exception, msg: 'Solution Failed - Invalid Column Length!' if number of columns (len(row)) is not 9: raise Row Length Exception, msg: 'Solution Failed - Invalid Row Length in Row {Row #} if none of the above conditions are met, returns None and moves on """ if len(puzzle) != 9: raise InputColumnLengthException(f'Solution Failed - Invalid Column Length!') for row_number, row in enumerate(puzzle): if len(row) != 9 and row != '': raise InputRowLengthException(f'Solution Failed - Invalid Row Length in Row {row_number}!') def sudoku_solver(self, puzzle): """ Input: - puzzle: List of Lists(rows of elements) empty = find_empty(puzzle) -> Boolean if False: ** If False, this means no further empty spaces remain and the solution is complete ** Return Puzzle Output else: Get # Row and # Column of first Empty square (row by row, column by column) for # 1-9: guess (1-9) -> str check_for_validity(puzzle, row_number, column_number, guess) -> Boolean if True: Write guess to specified square Re-Enter recursion loop with new Puzzle object if False: Check next guess (1-9) if Recursion finishes and returns False, restore 'X' for the specified square, backtrack recursion one level if none of the (1-9) options are valid for the specified square, backtrack recursion to the previous square """ empty = self.find_empty(puzzle) if not empty: return puzzle else: row_number, column_number = empty for i in range(1, 10): guess = str(i) if self.check_for_validity(puzzle, row_number, column_number, guess): puzzle[row_number][column_number] = guess if self.sudoku_solver(puzzle): return puzzle puzzle[row_number][column_number] = 'X' return False def check_for_validity(self, puzzle, row_number, column_number, guess): """ Input: - puzzle: List of Lists(Rows of Elements) - row_number: y coordinate of guess: int - column_number: x coordinate of guess: int - guess: string version of integer guess (1-9) If all validation checks return True: Return True """ valid_row = self.check_for_row_validity(puzzle, row_number, guess) valid_column = self.check_for_column_validity(puzzle, row_number, column_number, guess) valid_box = self.check_for_box_validity(puzzle, row_number, column_number, guess) if valid_row and valid_column and valid_box: return True def check_for_row_validity(self, puzzle, row_number, guess): """ Input: - puzzle: List of Lists(Rows of Elements) - row_number: y coordinate of guess - guess: string version of integer guess (1-9) for element in row: if guess already exists in row: Return False else: Return True """ for index, value in enumerate(puzzle[row_number]): if puzzle[row_number][index] == guess: return False return True def check_for_column_validity(self, puzzle, row_number, column_number, guess): """ Input: - puzzle: List of Lists(Rows of Elements) - row_number: y coordinate of guess - column_number: x coordinate of guess - guess: string version of integer guess (1-9) for row in puzzle: if value of index of row matches guess: return False else: return True """ for index, value in enumerate(puzzle): if puzzle[index][column_number] == guess and row_number != index: return False return True def check_for_box_validity(self, puzzle, row_number, column_number, guess): """ Input: - puzzle: List of Lists(Rows of Elements) - row_number: y coordinate of guess - column_number: x coordinate of guess - guess: string version of integer guess (1-9) for x coordinate of guess: floor division of coordinate by 3 (division with no remainder), then multiplied by 3: eg: coordinate = 4 // 3 = 1 base_x_value_box = 3 Thus defining the x coordinate "anchor" of the square to be tested for y coordinate of guess: floor division of coordinate by 3, then multiplied by 3 eg coordinate = 7 // 3 = 2 base_y_value_box = 6 for range (coordinate ... coordinate+3): creates the bounding box for the 3*3 grid to be tested if guess is found within bounding box: Return False else: Return True """ base_x_value_box = (column_number // 3)*3 base_y_value_box = (row_number // 3)*3 for i in range(base_y_value_box, base_y_value_box + 3): for j in range(base_x_value_box, base_x_value_box + 3): if puzzle[i][j] == guess and i != row_number and j != column_number: return False return True def find_empty(self, puzzle): """ Input: - puzzle: List of Lists(Rows of Elements) Iterate through elements in each row and Rows within Puzzle if an 'X' is found: return y,x coordinates of empty square else: return None """ for row_num, row in enumerate(puzzle): for col_num, col in enumerate(puzzle[row_num]): if puzzle[row_num][col_num] == 'X': return (row_num, col_num) return None def solution_failed(self, file_split): """Basic error handling function for Failed Solution Error""" raise SolutionFailedException(f'Solution Failed - Unable to find Solution for {file_split[0]}') def write_to_file(self, puzzle, puzzle_file, directory='puzzles'): """ Input: - puzzle: List of Lists(Rows of Elements) or String (Error Response) - puzzle_file: Split name of input file eg. 'puzzle1' - directory: Directory of file If the type of input puzzle is String: * Write the error response to the solution file else: * Join the elements of each row into a string * Join each row into one unified string separated by new line characters * Write the output puzzle to the solution file """ path_out = Path.cwd().joinpath(directory, f'{puzzle_file}.sln.txt') if type(puzzle) == str: Path(path_out).write_text(puzzle) else: write_out = [''.join(row) for row in puzzle] final_out = ''.join([''.join(f'{line}\n' for line in write_out)]) Path(path_out).write_text(final_out) def get_all_files(self, directory='puzzles'): """ Input: directory: Directory of files - eg. 'puzzles' Output: Return list of all path objects of type .txt within specified directory """ all_files = [] all_files.extend(Path(directory).glob('*.txt')) return all_files
class Point: def __init__(self, x = 0, y = 0): self.__x = x; self.__y = y def __checkValue(x): if isinstance(x, int) or isinstance(x, float): return True return False def setCoords(self, x, y): if Point.__checkValue(x) and Point.__checkValue(y) : self.__x = x self.__y = y else: print("Координаты должны быть числами") def getCoords(self): return self.__x, self.__y pt = Point(1,2) print( pt.getCoords() ) print( pt._Point__x )
message = input() alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' h1 = message[:int(len(message)/2)] h2 = message[int(len(message)/2):] decrypted = '' r1, r2 = 0, 0 for i in range(len(h1)): r1 += alphabet.index(h1[i]) r2 += alphabet.index(h2[i]) for i in range(len(h1)): decrypted += alphabet[((alphabet.index(h1[i]) + r1) % 26 + (alphabet.index(h2[i]) + r2) % 26) % 26] print(decrypted)
date = input() if date == 'OCT 31' or date == 'DEC 25': print('yup') else: print('nope')
import numpy as np ## Abstract class for Activation : class Activation(): def forward(self,x): raise NotImplementedError def gradient(self,x): raise NotImplementedError ## Real class for activation : class Identity(Activation): def forward(self,x): return x def gradient(self,input,previous): return previous class Relu(Activation): def forward(self,x): return np.maximum(0,x) def gradient(self,input,previous): previous[input<=0]=0 return previous class SoftMax(Activation): def forward(self,x): x = x/x.std() e = np.exp(x) e = e / np.sum(e, axis=0, keepdims=True) return e / np.sum(e, axis=0, keepdims=True) def gradient(self, x,previous): return previous * (self.forward(x) * (1 - self.forward(x)))
from tkinter import * import tkinter.ttk as ttk import tkinter.messagebox class Screen: '''Game Vars''' # These variables are the basis of the game, and will not be changed by # settings # Screen proportions MAIN_SPLIT = 0.15 # split between Top and Bottom frames BOTTOM_SPLIT = 0.75 # Split between Game_Window and Player_HUD # Dictionary to locate adjacent keys for an item ADJACENT_KEYS = { 'up': lambda location: (location[0] - 1, location[1]), 'down': lambda location: (location[0] + 1, location[1]), 'left': lambda location: (location[0], location[1] - 1), 'right': lambda location: (location[0], location[1] + 1), 'diag_ul': lambda location: (location[0] - 1, location[1] - 1), 'diag_ur': lambda location: (location[0] - 1, location[1] + 1), 'diag_dl': lambda location: (location[0] + 1, location[1] - 1), 'diag_dr': lambda location: (location[0] + 1, location[1] + 1) } '''Messages''' # Text to be displayed on the starting screen INITIAL_TEXT = 'Welcome to our boggle game, press start to display board' RETRY_LABEL = 'Press Start to start again' # Displays at the end of the countdown COUNT_MESSAGE = 'Good Luck!' # Text to be displayed on the ending screen END_TITLE = 'You managed to find {} words!' # Display the player's score END_SCORE = 'Your total score is: {}' # These are the Messagebox messages for all outcomes of the game TIMEUP_TITLE = 'Time\'s Up!' TIMEUP_TEXT = 'The clock has run out!\nLet\'s see how you did' EARLY_TITLE = 'QUITTER ALERT!' EARLY_TEXT = 'The clock did not run out!\nYOU ARE FREAKING WEAK!!!' AFTER_TITLE = 'Going so fast?' AFTER_TEXT = 'Don\'t you want to play again?' DEFAULT_PIC = 'default' # A dictionary to determine which message to show on exit ENDERS = { 'TIMEUP': (TIMEUP_TITLE, TIMEUP_TEXT), 'EARLY': (EARLY_TITLE, EARLY_TEXT), 'AFTER': (AFTER_TITLE, AFTER_TEXT) } SETTING_ERR = ('Game is running!', 'You can\'t change settings midgame!') '''Visual Default Settings''' # These are the default visual settings for the game, the player has an # Option to change some of these from within the game # Default font for all text in the game FONT = 'Helvetica' # Font sizes dictionary SIZES = { 'small': (FONT, 10), # Used for buttons 'medium': (FONT, 15), # Used for non-title text 'large': (FONT, 20), # Used for titles 'gigantic': (FONT, 70) # Used for special text } # Holds sequences of 9 colors that represent a theme THEME = { 'DEFAULT': ('#FBCE3A', '#E0D0B8', '#E0D0B8', '#372F2F', '#FBCE3A', '#372F2F', '#FBCE3A', '#372F2F', '#FBCE3A') } # holds path for specific reactions for words PICS = { 'wrong': "pics/wrong_word.png", 'random': "pics/random_word.png", 'unknown': 'pics/unknown_word.png', 'impressive': 'pics/impressive.png', 'basic': 'pics/basic.png', 'default': 'pics/good_luck.png', 'recycle': 'pics/recycling.png' } RANDOM_WORDS = ['AA', 'AAH', 'AAL', 'AAS', 'AB', 'ABA', 'AX'] # The the theme chosen by the player (can be altered in settings) CHOSEN_THEME = 'DEFAULT' TOP_BAR_COLOR = THEME[CHOSEN_THEME][0] # Background for top frame GAME_WINDOW_COLOR = THEME[CHOSEN_THEME][1] # Background for game window PLAYER_HUD_COLOR = THEME[CHOSEN_THEME][2] # Background for player HUD BUTTONS_BG = THEME[CHOSEN_THEME][3] # Background for buttons BUTTONS_FG = THEME[CHOSEN_THEME][4] # Text color for buttons TILE_BG = THEME[CHOSEN_THEME][5] # Background for board tiles TILE_FG = THEME[CHOSEN_THEME][6] # Text color for board tiles BOX_BG = THEME[CHOSEN_THEME][7] # Background for leaders\found words BOX_FG = THEME[CHOSEN_THEME][8] # Text color for leaders\found words # The base padding for all items on screen - Not alterable PAD = 5 '''Default Game Settings''' # The length of the game - can be changed in settings GAME_TIME = 180 COUNTDOWN = 3 def __init__(self): self.__init_vars() self.__init_screen() # Creates all the screen components def __init_vars(self): self.__score = 0 # Player's score self.__bank = [] # Words found by the player self.__curr_word = '' # The word the player is currently forming self.clock_running = False # The state of the clock self.__player = '' # The players name self.__game_status = False # determines whether a game should end self.press_bank = [] # Letters the player clicked on self.stopclock = False # Should the clock be stopped self.score_bank = {} def __init_screen(self): ''' This function creates the main game screen and base variables associated with it ''' self.__root = Tk() # The base screen # Get's the user's screen size so the game screen size will be # relative self.screen_width = self.__root.winfo_screenwidth() // 2 self.screen_height = self.__root.winfo_screenheight() // 2 # sets a minimum size for the game screen self.__root.minsize(width=self.screen_width + 180, height=self.screen_height + 120) # Initiates the topleven menu self.toplevel_menu() # Adds the top frame self.top_frame() # Adds the bottom frame self.bottom_frame() '''Base Methods''' def set_title(self, title): self.__root.title(title) def set_dict(self, dict): # Should be in boggle.py self.__dict = dict def set_board(self, board): # Should be in boggle.py self.__board = board def start_screen(self): self.__root.mainloop() def set_game_status(self, status): self.__game_status = status '''Toplevel Menu Methods''' def toplevel_menu(self): menubar = Menu(self.__root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Options", command=self.options) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.forcexit) menubar.add_cascade(label="File", menu=filemenu) self.__root.config(menu=menubar) def forcexit(self): if self.clock_running: # user ends early self.stopclock = True self.end(type='EARLY') else: # game is over self.__game_status = 'exit' '''Options window methods''' def options(self): if self.clock_running: tkinter.messagebox.showinfo(self.SETTING_ERR[0], self.SETTING_ERR[1]) return # Creating the toplevel window self.menu = Toplevel() self.menu.title('Options') # Adding the save button self.save_button = ttk.Button(self.menu, text="Save Settings", command=self.options_save) self.save_button.pack(side=BOTTOM, padx=self.PAD, pady=self.PAD) # Creating the containing notebook for the setting tabs self.menu_note = ttk.Notebook(self.menu, height=200, width=250, padding=self.PAD) self.menu_note.pack(side=TOP, fill='both', expand=True) self.game_settings_window() # Creates the Game_Settings Tab # self.visual_settings_window() # Creates the Visual Settings Tab def options_save(self): # Setting the game time self.GAME_TIME = (self.time_min.get()) * 60 + self.time_sec.get() self.COUNTDOWN = self.countdown_duration.get() self.update_text() # Closing the Options menu after saving the changed settings self.menu.destroy() '''Game Settings Methods''' def game_settings_window(self): # Making the notebook Tab for game settings self.game_settings = ttk.Frame(self.menu_note) self.menu_note.add(self.game_settings, text='Game Settings') self.gametime() # adding the game duration setting option self.countdown_timer() def gametime(self): # Container Frame for the Game Duration setting self.gametime_frame = ttk.Frame(self.game_settings) self.gametime_frame.pack(side=TOP) # The label for the duration setting self.gametime_title = ttk.Label(self.gametime_frame, text="Game Duration:") self.gametime_title.pack(side=LEFT) # Making two IntVar objects that will hold the minutes and the seconds # Chosen by the player in the settings menu self.time_min = IntVar(self.gametime_frame) self.time_sec = IntVar(self.gametime_frame) # Making the options menus for the minutes and seconds self.option_minutes = ttk.OptionMenu(self.gametime_frame, self.time_min, 0, *range(11)) # Setting a default value for minutes self.time_min.set(self.GAME_TIME // 60) self.option_minutes.pack(side=LEFT) self.option_seconds = ttk.OptionMenu(self.gametime_frame, self.time_sec, 0, *range(0, 60, 5)) # Setting a default value for minutes self.time_sec.set(self.GAME_TIME % 60) self.option_seconds.pack(side=LEFT) def countdown_timer(self): # Container Frame for the countdown timer setting self.countdown_timer_frame = ttk.Frame(self.game_settings) self.countdown_timer_frame.pack(side=TOP) # The label for the countdown timer setting self.countdown_timer_title = ttk.Label(self.countdown_timer_frame, text="Timer Duration:") self.countdown_timer_title.pack(side=LEFT) # Making an IntVar object that will hold the duration length self.countdown_duration = IntVar(self.countdown_timer_frame) # Making the options menus for the minutes and seconds self.countdown_options = ttk.OptionMenu(self.countdown_timer_frame, self.countdown_duration, 0, *range(6)) self.countdown_duration.set(self.COUNTDOWN) self.countdown_options.pack(side=LEFT) '''Visual Settings Methods''' def visual_settings_window(self): # Making the notebook Tab for visual settings self.visual_settings = ttk.Frame(self.menu_note) self.menu_note.add(self.visual_settings, text='Visual Settings') ''' Top Frame Methods''' def top_frame(self): # Creates the containing frame self.top = Frame(self.__root, bg=self.TOP_BAR_COLOR) self.top.place(rely=0, relheight=self.MAIN_SPLIT, relwidth=1.0) self.start_button() # Creates the Start\Check button self.forming_word() # Creates the forming word box self.clock() # Creates the clock def start_button(self): # creates start button self.main_button = Button(self.top, text='Start', font=self.SIZES['small'], command=self.start, fg=self.BUTTONS_FG, bg=self.BUTTONS_BG, width=10) self.main_button.pack(side=LEFT, padx=self.PAD) def forming_word(self): # Creates the forming word container box self.forming_word_container = Frame(self.top, bg=self.TOP_BAR_COLOR) self.forming_word_container.pack(side=LEFT, padx=self.PAD) # Creates the forming word static title self.forming_word_title = Label(self.forming_word_container, text=f'Forming Word:', font=self.SIZES['small'], bg=self.TOP_BAR_COLOR) self.forming_word_title.pack(side=LEFT, padx=self.PAD) # Creates the forming word dynamic label self.forming_word = Label(self.forming_word_container, text=f'{self.__curr_word}', font=self.SIZES['large'], bg=self.TOP_BAR_COLOR) self.forming_word.pack(side=LEFT, padx=self.PAD) def clock(self): t = divmod(self.GAME_TIME, 60) self.clock_label = Label(self.top, font=self.SIZES['large'], bg=self.TOP_BAR_COLOR, text=f'{t[0]:0>2}:{t[1]:0>2}', bd=1, relief=SUNKEN) self.clock_label.pack(side=RIGHT, padx=self.PAD) ''' Bottom Frame Methods''' def bottom_frame(self): # Main Frame self.bottom = Frame(self.__root) self.bottom.place(rely=self.MAIN_SPLIT, relheight=(1.0 - self.MAIN_SPLIT), relwidth=1.0) self.game_window() self.player_hud() def game_window(self): self.game_window = Frame(self.bottom, bg=self.GAME_WINDOW_COLOR) self.game_window.place(relx=0, relheight=1.0, relwidth=self.BOTTOM_SPLIT) self.initial_label = Label(self.game_window, bg=self.GAME_WINDOW_COLOR, text=self.INITIAL_TEXT, font=self.SIZES['large'], wraplength=self.screen_width // 2, justify=CENTER) self.initial_label.pack(expand=True) def player_hud(self): # Right Subframe - Player HUD self.player_hud = Frame(self.bottom, bg=self.PLAYER_HUD_COLOR) self.player_hud.place(relx=self.BOTTOM_SPLIT, relheight=1.0, relwidth=1.0 - self.BOTTOM_SPLIT) self.score_section() # Holds the found words and leaderboards frames for enduser size # control self.pane = PanedWindow(self.player_hud, orient=VERTICAL) self.pane.pack(side=TOP, fill='both', expand=True, pady=self.PAD, padx=self.PAD) self.found_words_section() self.imageframe = Frame(self.player_hud, bg=self.PLAYER_HUD_COLOR, height=50, relief=SUNKEN, bd=3) self.imageframe.pack(side=BOTTOM, fill='both', expand=True, padx=self.PAD, pady=self.PAD) self.put_picture(self.DEFAULT_PIC) # adds default picture def score_section(self): # Score display self.score_container = Frame(self.player_hud, bg=self.BOX_BG) self.score_container.pack(side=TOP, pady=self.PAD, padx=self.PAD, fill=X) self.score_title = Label(self.score_container, text='Score:', bg=self.BOX_BG, fg=self.BOX_FG, font=self.SIZES['small']) self.score_title.pack(side=TOP, fill=X) self.score_label = Label(self.score_container, text=f'{self.__score}', bg=self.BOX_BG, fg=self.BOX_FG, font=self.SIZES['small']) self.score_label.pack(side=TOP, fill=X) def found_words_section(self): # Found Words self.bank_container = Listbox(self.pane, bg=self.BOX_BG, fg=self.BOX_FG, font=self.SIZES['small']) self.pane.add(self.bank_container) self.bank_container.insert(END, 'Found Words:', '') self.scrollbar = ttk.Scrollbar(self.bank_container, orient=VERTICAL) self.scrollbar.pack(side=RIGHT, fill=Y) self.bank_container.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.bank_container.yview) '''General gameplay - Most should move to boggle.py''' def end(self, type='TIMEUP'): self.end_frame = Frame(self.game_window, bg=self.GAME_WINDOW_COLOR) self.end_frame.pack(expand=True) self.main_button.config(state=DISABLED) tkinter.messagebox.showinfo(self.ENDERS[type][0], self.ENDERS[type][1]) self.board_frame.pack_forget() self.end_title = Label(self.end_frame, text=self.END_TITLE.format(len(self.__bank)), bg=self.GAME_WINDOW_COLOR, font=self.SIZES['large']) self.end_title.pack(side=TOP, fill=X, expand=True) self.end_score = Label(self.end_frame, text=self.END_SCORE.format(self.__score), bg=self.GAME_WINDOW_COLOR, font=self.SIZES['large']) self.end_score.pack(side=TOP, fill=X, expand=True) self.buttonframe = Frame(self.end_frame, bg=self.GAME_WINDOW_COLOR) self.buttonframe.pack(side=TOP, padx=self.PAD, pady=self.PAD) self.exitbtn = ttk.Button(self.buttonframe, text='Exit', command=lambda: self.set_game_status( 'exit')) self.exitbtn.pack(side=LEFT) self.retrybtn = ttk.Button(self.buttonframe, text='Retry', command=lambda: self.set_game_status( 'retry')) self.retrybtn.pack(side=LEFT) def tick_clock(self, time): if not self.clock_running: self.clock_running = True t = divmod(time, 60) now = f'{t[0]:0>2}:{t[1]:0>2}' self.clock_label.config(text=now) if self.stopclock: self.clock_running = False return elif time == 0: self.clock_running = False self.end() else: time -= 1 self.__root.after(1000, self.tick_clock, time) def get_game_status(self): return self.__game_status def get_root(self): return self.__root def countdown(self, counting): if counting == 'start': counting = self.COUNTDOWN self.initial_label.pack_forget() if counting == 0: self.display_board() self.tick_clock(self.GAME_TIME) self.main_button.config(text='Check') return self.countdown_frame = Frame(self.game_window) self.countdown_frame.pack(expand=True) self.countdown_label = Label(self.countdown_frame, text=counting, font=self.SIZES['gigantic'], bg=self.GAME_WINDOW_COLOR, justify=CENTER) self.countdown_label.pack(expand=True) self.__root.after(1000, self.countdown, counting) elif counting > 1: counting -= 1 self.countdown_label.config(text=counting) self.__root.after(1000, self.countdown, counting) elif counting == 1: self.countdown_label.config(text=self.COUNT_MESSAGE) counting -= 1 self.__root.after(1500, self.countdown, counting) else: self.countdown_frame.pack_forget() self.display_board() self.tick_clock(self.GAME_TIME) self.main_button.config(text='Check') def update_bank(self): self.__bank.append(self.__curr_word) self.bank_container.insert(END, self.__curr_word) def check_word(self, undo=False): key = self.picture_key(self.__curr_word) if not undo: # makes sure not to affect image if just unclicking if self.image: # forgets if image is there self.image.pack_forget() Screen.put_picture(self, key) if (self.__curr_word in self.__dict) and (self.__curr_word not in self.__bank): self.__score += len(self.__curr_word) ** 2 self.score_label.config(text=f'{self.__score}') self.update_bank() def clear_word(self, undo=False): self.check_word(undo) self.__curr_word = '' self.press_bank = [] self.forming_word.config(text=f'{self.__curr_word}') for loc in self.__board: self.buttons[loc].config(state=NORMAL) if self.__board[loc].get_status(): self.__board[loc].press() def add_letter(self, letter): self.__curr_word += letter.get_data().upper() self.forming_word.config(text=f'{self.__curr_word}') def press(self, location, re=False): if self.__board[location].get_status(): if len(self.press_bank) == 1: return self.clear_word(True) else: self.__board[self.press_bank.pop()].press() self.__board[self.press_bank[-1]].press() return self.press(self.press_bank.pop(), re=True) self.press_bank.append(location) items = [self.ADJACENT_KEYS[key](location) for key in self.ADJACENT_KEYS] # objects = [self.board[item] if item in self.board for item in items] self.__board[location].press() # self.buttons[location].config(state=DISABLED) for i, j in self.buttons: if (i, j) == location: self.buttons[(i, j)].config(state=NORMAL) continue if (i, j) in items: if self.__board[(i, j)].get_status(): self.buttons[(i, j)].config(state=DISABLED) else: self.buttons[(i, j)].config(state=NORMAL) else: self.buttons[(i, j)].config(state=DISABLED) if re: self.__curr_word = self.__curr_word[:-1] self.forming_word.config(text=f'{self.__curr_word}') return return self.add_letter(self.__board[location]) def display_board(self): # makes a frame for the game tiles self.board_frame = Frame(self.game_window, bg=self.GAME_WINDOW_COLOR) self.board_frame.pack(expand=True) self.buttons = {} # dictionary that will hold the buttons # makes the buttons based on the game board for i, j in self.__board: self.buttons[(i, j)] = ( Button(self.board_frame, text=str(self.__board[(i, j)]), command=lambda item=(i, j): self.press( item), font=self.SIZES['large'], width=5, height=2, fg=self.TILE_FG, bg=self.TILE_BG)) # places each tile in a grid self.buttons[(i, j)].grid(row=i, column=j, padx=self.PAD, pady=self.PAD) def picture_key(self, word): """ returns appropriate key for picture """ if word not in self.__dict: return 'wrong' if word in self.__bank: return 'recycle' if word in Screen.RANDOM_WORDS: return 'random' if len(word) <= 3: return 'basic' if len(word) <= 8: return 'impressive' return 'unknown' def put_picture(self, dic_key): """ adds picture to the screen """ path = Screen.PICS[dic_key] photo = PhotoImage(file=path) photo = photo.subsample(1, 1) self.image = Label(self.imageframe, image=photo, borderwidth=0, highlightthickness=0, bg=self.PLAYER_HUD_COLOR) self.image.image = photo self.image.pack(side=BOTTOM, padx=self.PAD, pady=self.PAD, expand=True, fill='both') def start(self): if self.clock_running: self.clear_word() else: self.countdown('start') def update_text(self): t = divmod(self.GAME_TIME, 60) self.clock_label.config(text=f'{t[0]:0>2}:{t[1]:0>2}') self.forming_word.config(text=f'{self.__curr_word}') self.score_label.config(text=f'{self.__score}') self.bank_container.delete(2, END) self.image.pack_forget() self.put_picture(self.DEFAULT_PIC) def reset_screen(self): self.end_frame.pack_forget() self.initial_label.config(text=self.RETRY_LABEL) self.initial_label.pack(expand=True) self.__init_vars() self.update_text() self.main_button.config(text='Start', state=NORMAL)
#!/usr/bin/python # -*- coding: utf-8 -*- ### Joc de 3 en ratlla. ### Creat per David Noguera contacta@noguerad.es ### Sou lliures de copiar o modificar el codi, ### però siusplau citeu a l'autor. import os import random import time #-----Variables #-----Constants tirs = ['5'] # Començem amb la casella central ja ocupada. moviments = ["x"] # Guardem les tirades. ## Linees del tauler. L1 = [" ", " ", " "] L2 = [" ", "x", " "] L3 = [" ", " ", " "] #-----Funcions def explica(): os.system("clear") print (" ") print (" 1 | 2 | 3 ") print ("---+---+---") print (" 4 | 5 | 6 ") print ("---+---+---") print (" 7 | 8 | 9 \n") print ("El jugador ha de triar una casella segons aquesta numeració.") print ("Començen les x al centre. ") raw_input("Esteu preparats? ") comenca() def comenca(): # Funció principal del programa. #moviments = 1 print ("Començen les x: ") while len(moviments)<9 : tauler() print (" ") #print tirs # Tests de trencament del programa. #print moviments #print len(moviments) if len(moviments)%2==0 : #tira = raw_input("Torn de les x, casella?: ") print ("Torn de les x. ") time.sleep(1) tira = auto() jug = "x" tirast = str(tira) casella(tirast, jug) tirs.append(tira) moviments.append(jug) if guanyador()==1: break else: tira = raw_input("Torn de les o, casella?: ") jug = "o" casella(tira, jug) tirs.append(tira) moviments.append(jug) if guanyador()==1: break felicitats(len(moviments)) def casella(x,jug): # Comprovem si la casella està plena xa = int(x) # i la omplim si no ho està. if x in tirs: y = raw_input("Ocupada, tria de nou: ") casella(y, jug) elif xa==1 : L1[0] = jug elif xa==2 : L1[1] = jug elif xa==3 : L1[2] = jug elif xa==4 : L2[0] = jug elif xa==6 : L2[2] = jug elif xa==7 : L3[0] = jug elif xa==8 : L3[1] = jug elif xa==9 : L3[2] = jug else: z = raw_input("Incorrecte, tria de nou: ") casella(z, jug) def auto(): # L'ordinador tira com a jugador x. if (L1[0]=="x" and L1[1]=="x" and L1[2]==" ") : return "3" elif (L1[0]==" " and L1[1]=="x" and L1[2]=="x") : return "1" elif (L1[0]=="x" and L1[1]==" " and L1[2]=="x") : return "2" elif (L2[0]==" " and L2[1]=="x" and L2[2]=="x") : return "4" elif (L2[0]=="x" and L2[1]=="x" and L2[2]==" ") : return "6" elif (L1[0]=="x" and L2[0]=="x" and L3[0]==" ") : return "7" elif (L1[0]==" " and L2[0]=="x" and L3[0]=="x") : return "1" elif (L1[0]=="x" and L2[0]==" " and L3[0]=="x") : return "4" elif (L1[1]=="x" and L2[1]=="x" and L3[1]==" ") : return "8" elif (L1[1]==" " and L2[1]=="x" and L3[1]=="x") : return "2" elif (L1[0]=="x" and L2[1]=="x" and L3[2]==" ") : return "9" elif (L1[0]==" " and L2[1]=="x" and L3[2]=="x") : return "1" elif (L1[2]==" " and L2[1]=="x" and L3[0]=="x") : return "3" elif (L1[2]=="x" and L2[1]=="x" and L3[0]==" ") : return "7" elif (L1[2]=="x" and L2[2]=="x" and L3[2]==" ") : return "9" elif (L1[2]==" " and L2[2]=="x" and L3[2]=="x") : return "3" elif (L1[2]=="x" and L2[2]==" " and L3[2]=="x") : return "6" elif (L3[0]=="x" and L3[1]=="x" and L3[2]==" ") : return "9" elif (L3[0]==" " and L3[1]=="x" and L3[2]=="x") : return "7" elif (L3[0]=="x" and L3[1]==" " and L3[2]=="x") : return "8" elif (L1[0]=="o" and L1[1]=="o" and L1[2]==" ") : return "3" elif (L1[0]==" " and L1[1]=="o" and L1[2]=="o") : return "1" elif (L1[0]=="o" and L1[1]==" " and L1[2]=="o") : return "2" elif (L1[0]=="o" and L2[0]=="o" and L3[0]==" ") : return "7" elif (L1[0]==" " and L2[0]=="o" and L3[0]=="o") : return "1" elif (L1[0]=="o" and L2[0]==" " and L3[0]=="o") : return "4" elif (L1[2]=="o" and L2[2]=="o" and L3[2]==" ") : return "9" elif (L1[2]==" " and L2[2]=="o" and L3[2]=="o") : return "3" elif (L1[2]=="o" and L2[2]==" " and L3[2]=="o") : return "7" elif (L3[0]=="o" and L3[1]=="o" and L3[2]==" ") : return "9" elif (L3[0]==" " and L3[1]=="o" and L3[2]=="o") : return "7" elif (L3[0]=="o" and L3[1]==" " and L3[2]=="o") : return "8" else: while 1: ran = random.randint(1, 9) ranst = str(ran) if (ranst!="5" and (ranst not in tirs)): return ranst break def tauler(): # Dibuixem el tauler amb les fitxes. os.system("clear") print (" ") print (" "+L1[0]+" | "+L1[1]+" | "+L1[2]) print ("---+---+---") print (" "+L2[0]+" | "+L2[1]+" | "+L2[2]) print ("---+---+---") print (" "+L3[0]+" | "+L3[1]+" | "+L3[2]) def guanyador(): # Comprovem a cada tirada si ha guanyat algú. if (L1[0]=="o" and L1[1]=="o" and L1[2]=="o") : return 1 elif (L2[0]=="o" and L2[1]=="o" and L2[2]=="o") : return 1 elif (L3[0]=="o" and L3[1]=="o" and L3[2]=="o") : return 1 elif (L1[0]=="o" and L2[0]=="o" and L3[0]=="o") : return 1 elif (L1[1]=="o" and L2[1]=="o" and L3[1]=="o") : return 1 elif (L1[2]=="o" and L2[2]=="o" and L3[2]=="o") : return 1 elif (L1[0]=="o" and L2[1]=="o" and L3[2]=="o") : return 1 elif (L3[0]=="o" and L2[1]=="o" and L1[2]=="o") : return 1 elif (L1[0]=="x" and L1[1]=="x" and L1[2]=="x") : return 1 elif (L2[0]=="x" and L2[1]=="x" and L2[2]=="x") : return 1 elif (L3[0]=="x" and L3[1]=="x" and L3[2]=="x") : return 1 elif (L1[0]=="x" and L2[0]=="x" and L3[0]=="x") : return 1 elif (L1[1]=="x" and L2[1]=="x" and L3[1]=="x") : return 1 elif (L1[2]=="x" and L2[2]=="x" and L3[2]=="x") : return 1 elif (L1[0]=="x" and L2[1]=="x" and L3[2]=="x") : return 1 elif (L3[0]=="x" and L2[1]=="x" and L1[2]=="x") : return 1 else: return 0 def felicitats(g): # Un cop ha guanyat un jugador, os.system("clear") # comprovem quin i el felicitem. tauler() if guanyador()==1: if g%2==0 : print ("Felicitats, guanyen les o !!") else: print ("Felicitats, guanyen les x !!") else: print ("No hi ha guanyador...") tornar() def tornar(): # Eliminem tot per tornar a posició inicial. resposta = raw_input("Tornar a jugar? s/n: ") if resposta=="s" : while len(L1)!=0: del L1[0] while len(L2)!=0: del L2[0] while len(L3)!=0: del L3[0] while len(L1)!=3: L1.append(" ") L2.append(" ") L2.append("x") L2.append(" ") while len(L3)!=3: L3.append(" ") while len(moviments)!=1: del moviments[1] while len(tirs)!=1: del tirs[1] comenca() else: os.system("clear") explica()
from csv import Error, DictReader, QUOTE_NONE from typing import Generator, Union from common import MetadataRecord from .exceptions import ExtractionError from .file_extractor import file_extractor def _sanitize_key(column_name: str) -> str: """ Sanitize a column_name read from a CSV file, by removing leading and trailing spaces and quotes. :param column_name: the column_name read from a CSV file :return: sanitized column name """ return column_name.strip('" ') def _sanitize_value(value: str) -> Union[int, str, None]: """ Sanitize a value read from a CSV file as following: * if its equal to 'null' -> None * if starts with quote -> str * otherwise -> int - if casting fails, a ValueError is raised :param value: the value to sanitize :return: sanitized value """ value = value.strip(' ') if value.startswith('"'): # it's a string return value.strip('"') if value.lower() == 'null': return None return int(value) def _perform_extraction(file_path: str) -> Generator[MetadataRecord, None, None]: """ Perform the extraction of records from the given CSV file. The returned generator object produces N * M MetadataRecord for a CSV with N columns and M rows. :param file_path: the path to the file to create records from :return: a generator object that produces MetadataField objects :raises ExtractionError if extraction fails """ with open(file_path, newline='', mode='r') as csv_file: csv_reader = DictReader(csv_file, delimiter=',', quoting=QUOTE_NONE) for row in csv_reader: for key, value in row.items(): try: key = _sanitize_key(key) except AttributeError: raise ExtractionError(f"Missing column name for value {value} at line {csv_reader.line_num}") try: value = _sanitize_value(value) except ValueError: if not value: raise ExtractionError(f"Missing value for column '{key}' at line {csv_reader.line_num}") else: raise ExtractionError(f"Unknown type for value '{value}' (column '{key}') at line " f"{csv_reader.line_num}") yield MetadataRecord(key, value) @file_extractor("csv") def extract_data_from_csv(file_path: str) -> Generator[MetadataRecord, None, None]: """ Perform the extraction of records from the given CSV file. The returned generator object produces N * M MetadataRecord for a CSV with N columns and M rows. :param file_path: the path to the file to create records from :return: a generator object that produces MetadataField objects :raises ExtractionError if extraction fails """ try: yield from _perform_extraction(file_path) except ExtractionError: raise except IOError: raise ExtractionError(f"Could not open file '{file_path}'") except Error: raise ExtractionError(f"The file '{file_path}' is not a valid CSV") except Exception: raise ExtractionError(f"Unexpected error while processing CSV file '{file_path}'")
class Question: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer question_prompts = [ # List of Questions "\nWhich of these is not a core data type in Python? \n (a) List (b) Dictionary \n (c) Tuple (d) Class\n\n" , "\nWhat data type is the object below ? \n L = [1, 23, ‘hello’, 1] \n (a) List (b) Dictionary \n (c) Tuple (d) Class\n\n", "\nWhich of the following statement(s) is TRUE?\nA hash function takes a message of arbitrary length and generates a fixed length code.\nA hash function takes a message of fixed length and generates a code of variable length.\nA hash function may give the same hash value for distinct messages.\n (a) I only (b) II and III only \n (c) I and III only (d) II only\n\n", "\nWhich one of the following is the correct extension of the Python file? \n (a) .py (b) .python \n (c) .p (d) None of these\n\n", "\nWhat do we use to define a block of code in Python language? \n (a) Key (b) Indentation \n (c) Brackets (d) None of these\n\n", "\nWhich character is used in Python to make a single line comment? \n (a) / (b)// \n (c) # (d) !\n\n", "\nWhat is the method inside the class in python language? \n (a) Object (b) Function \n (c) Attribute (d) Arguement\n\n", "\nWhich of the following precedence order is correct in Python? \n (a) Multiplication, Division, Addition, Subtraction, Parentheses, Exponential (b) Division, Multiplication, Addition, Subtraction, Parentheses, Exponential \n (c) Exponential, Parentheses, Multiplication, Division, Addition, Subtraction (d) Parentheses, Exponential, Multiplication, Division, Addition, Subtraction\n\n", "\nWhich of the following is the use of id() function in python? \n (a) Every object doesn't have a unique ID (b) ID returns the identity of the object \n (c) All of these (d) None of these\n\n", "\nWhat will be the output of 7^10 in python? \n (a) 13 (b) 14\n (c)7 (d)11\n\n", ] # Right answers are stored here questions = [ Question(question_prompts[0], "d"), Question(question_prompts[1], "a"), Question(question_prompts[2], "c"), Question(question_prompts[3], "a"), Question(question_prompts[4], "b"), Question(question_prompts[5], "c"), Question(question_prompts[6], "b"), Question(question_prompts[7], "d"), Question(question_prompts[8], "b"), Question(question_prompts[9], "a"), ] def run_quiz(questions): # Score in the quiz is counted here score = 0 for question in questions: answer = input(question.prompt) if answer == question.answer: score += 1 print("\nYour total score is", score, "out of", len(questions)) print("Here's a basic python quiz to test your knowledge....") run_quiz(questions)
## A Watermelon 🍉 # Mubashir is eating a watermelon. # He spits out all watermelon seeds if seeds are more than five. # He can swallow all watermelon seeds if seeds are less than five. # He can eat 1/4 of watermelon each time. # Given a 2D array of watermelon where 0 is representing juicy watermelon while 1 is representing seed, return total number of seeds spit-out. See below example for detailed explanation: # Given a watermelon: # 1, 0, 0, 1, 1, 1, 0, 1 # 1, 0, 1, 0, 1, 1, 0, 0 # 1, 1, 1, 1, 0, 0, 0, 0 # 0, 1, 0, 1, 1, 1, 1, 0 # 0, 0, 0, 1, 0, 1, 0, 0 # 1, 1, 1, 0, 0, 0, 1, 1 # 1, 0, 1, 1, 0, 0, 0, 0 # 0, 0, 0, 0, 0, 0, 0, 0 # seeds = 0 # total seeds = 0 # Mubashir eats 1/4 piece (4x4 matrix) of watermelon : # x, x, x, x, 1, 1, 0, 1 # x, x, x, x, 1, 1, 0, 0 # x, x, x, x, 0, 0, 0, 0 # x, x, x, x, 1, 1, 1, 0 # 0, 0, 0, 1, 0, 1, 0, 0 # 1, 1, 1, 0, 0, 0, 1, 1 # 1, 0, 1, 1, 0, 0, 0, 0 # 0, 0, 0, 0, 0, 0, 0, 0 # seeds = 10 # total seeds = 10 (All seeds were spit-out) # Mubashir eats next 1/4 piece (4x4 matrix) of watermelon : # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # 0, 0, 0, 1, 0, 1, 0, 0 # 1, 1, 1, 0, 0, 0, 1, 1 # 1, 0, 1, 1, 0, 0, 0, 0 # 0, 0, 0, 0, 0, 0, 0, 0 # seeds = 8 # total seeds = 10+8 = 18 (All seeds were spit-out) # Mubashir eats next 1/4 piece (4x4 matrix) of watermelon : # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, 0, 1, 0, 0 # x, x, x, x, 0, 0, 1, 1 # x, x, x, x, 0, 0, 0, 0 # x, x, x, x, 0, 0, 0, 0 # seeds = 7 # total seeds = 18+7 = 25 (All seeds were spit-out) # Mubashir eats last 1/4 piece (4x4 matrix) of watermelon : # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # x, x, x, x, x, x, x, x # seeds = 3 # total seeds = 25+0 = 25 ## Examples # total_seeds(watermelon) ➞ 25 import math import numpy as np from numpy.core.fromnumeric import nonzero def total_seeds(watermelon): # convert to numpy watermelon = np.asarray(watermelon) # variables seeds = 0 pieces = [] # floor to not exceed 1/4 watermelon x_mat = math.floor(len(watermelon)/2) y_mat = math.floor(len(watermelon[0])/2) # add the four pieces that will always be there pieces.append(watermelon[0:x_mat,0:y_mat]) pieces.append(watermelon[0:x_mat,y_mat:2*y_mat]) pieces.append(watermelon[x_mat:2*y_mat,0:y_mat]) pieces.append(watermelon[x_mat:2*x_mat,y_mat:2*y_mat]) # consider the extra pieces if len(watermelon)%2==1 and len(watermelon[0])%2==1: pieces.append(watermelon[-1]) pieces.append(watermelon[:,-1][0:-1]) elif len(watermelon)%2==1: pieces.append(watermelon[-1]) elif len(watermelon[0])%2==1: pieces.append(watermelon[:,-1]) # count the number of seeds for piece in pieces: seeds_in_piece = np.count_nonzero(piece==1) if seeds_in_piece > 5: seeds += seeds_in_piece return seeds watermelon1 = [[1,0,0,1,1,1,0,1], # 8x8 [1,0,1,0,1,1,0,0], [1,1,1,1,0,0,0,0], [0,1,0,1,1,1,1,0], [0,0,0,1,0,1,0,0], [1,1,1,0,0,0,1,1], [1,0,1,1,0,0,0,0], [0,0,0,0,0,0,0,0]] watermelon2 = [[1,1,1,0,0,1,1,1,0], # 7x9 [1,1,0,1,1,0,1,0,1], [1,1,1,1,1,0,0,1,1], [1,1,0,1,0,1,0,0,0], [0,0,0,0,0,0,0,0,0], [1,0,1,1,0,0,0,0,1], [1,0,0,0,1,0,0,1,0]] watermelon3 = [[1,0,1,0,0,1,1], # 8x7 [0,0,0,1,1,1,0], [1,1,1,1,1,0,1], [1,1,1,1,0,0,0], [0,0,0,0,0,0,1], [1,0,1,1,0,1,1], [1,1,1,1,1,1,1], [0,0,0,0,0,0,0]] watermelon4 = [[1,0,1,0,0,1,1,1], # 7x8 [0,0,0,1,1,0,1,0], [1,1,1,1,1,0,0,0], [1,1,1,1,0,0,0,0], [0,0,0,0,0,1,0,0], [1,0,1,1,0,1,0,0], [1,0,0,0,1,0,0,1]] print(total_seeds(watermelon1)) print(total_seeds(watermelon2)) print(total_seeds(watermelon3)) print(total_seeds(watermelon4))
"""Test module hangman.""" from hangman import check_format_answer, generate_random_word, \ get_wrong_message, get_correct_message, check_answer def test_check_format_answer(): """Test check_format_answer.""" assert check_format_answer("a"), \ "Check format answer don't see one char like correct answer." assert not check_format_answer("5"), \ "Check format answer don't check numbers." def test_generate_random_word() -> None: """Test generate_random_word.""" assert isinstance(generate_random_word(), str), \ "Generate word is not string." assert generate_random_word().isalpha(), \ "There are extraneous characters." def test_get_wrong_message(): """Test get_wrong_message.""" assert isinstance(get_wrong_message(0, 5, "wo**"), str), \ "Wrong message is not string." def test_get_correct_message(): """Test get_correct_message.""" assert isinstance(get_correct_message("wo**"), str), \ "Correct message is not string." def test_check_answer(): """Test check_answer.""" assert check_answer("word", "wo**", "r") == "wor*", \ "Incorrect check answer for existed char" assert check_answer("word", "wo**", "x") == "wo**", \ "Incorrect check answer for not existed char"
"""TimeSpecification""" from __future__ import absolute_import import types from species import Species from six.moves import range def floatRange(start, stop, step, epsilon=0.001): """Like range, but for floats. The last step is adjusted to fall into stop, all the while avoiding a step smaller than epsilon*step """ eps = epsilon * step res = [] if start + eps > stop: return res last = start while last + eps <= stop: res.append(last) last += step pass res.append(stop) return res def extendFloatRange(float_range, stop, step, epsilon=0.001): """It extend an existing float range.""" extension = floatRange(float_range[-1], stop, step, epsilon) float_range.extend(extension[1:]) return float_range def _count_args(*args): iargs = 0 for arg in args: if arg: iargs += 1 pass pass return iargs def verifyNbArguments(nb, *args): nb_args = _count_args(*args) if nb_args < nb: raise Warning("At least " +repr(nb)+ " arguments must be provided") if nb_args > nb: raise Warning("At most " +repr(nb)+ " arguments can be provided") class TimeSpecification: """ Several ways to specify the output time : by frequency, by period or by a times list """ def __init__(self, frequency=None, period=None, times=None, unit='s'): """TimeSpecification initialisation with (ALL OPTIONAL): - a frequency (integer) - a period (a float) - a times (list of float) - a unit (default value is second) """ self._setArgs(frequency, period, times, unit) return def _setArgs(self, frequency, period, times, unit): verifyNbArguments(1, frequency, period, times) if frequency: self.setFrequency(frequency) pass elif period: self.setPeriod(period) pass elif times: self.setTimes(times) pass else: raise RuntimeError self.setUnit(unit) return def setFrequency(self, frequency): self.frequency = None if frequency: self.frequency = int(frequency) self.specification = 'frequency' pass return def setPeriod(self, period): self.period = float(period) self.specification = 'period' return def setTimes(self, times): self.specification = 'times' self.times = TimeSequence(times) return def setUnit(self, unit): if self.getFrequency(): self.unit = None pass else: if unit not in ['s','year']: raise Exception(" check the time specification unit") self.unit = unit pass return def getSpecification(self): """It can be 'frequency', 'period' or 'times'""" return self.specification def getFrequency(self): try: return self.frequency except AttributeError: return None def getPeriod(self): try: return self.period except AttributeError: return None def getTimes(self): try: return self.times except AttributeError: return None def getUnit(self): """get TimeSpecification unit""" return self.unit pass class MyTimeSpecification(TimeSpecification): def setUnit(self, unit): if unit not in ['s','year']: raise Exception(" check the time specification unit") self.unit = unit return def getUnit(self): return self.unit class PeriodTimeSpecs(MyTimeSpecification): def __init__(self, period, unit='s'): self.setPeriod(period) self.setUnit(unit) return def setPeriod(self, period): self.period = float(period) return def getPeriod(self): return self.period class FrequencyTimeSpecs(MyTimeSpecification): def __init__(self, frequency=1): self.setFrequency(frequency) return def setFrequency(self, frequency): self.frequency = int(frequency) return def getFrequency(self): return self.frequency class SequenceTimeSpecs(MyTimeSpecification): def __init__(self, sequence, unit='s'): self.setSequence(sequence) self.setUnit(unit) return def setSequence(self, sequence): self.sequence = TimeSequence(sequence) return def getSequence(self): return self.sequence def _float_list(list): new = [] for item in list: new.append(float(item)) return new def _verify_order(list): new = list[:] new.sort() if new != list: raise ValueError("Time list is not ordered") return def _floatRange(start, stop, step, epsilon=0.001): """Like range, but for floats. The last step is adjusted to fall into stop, all the while avoiding a step smaller than epsilon*step """ eps = epsilon * step res = [] if start + eps > stop: return res last = start while last + eps <= stop: res.append(last) last += step pass res.append(stop) return res def _extendFloatRange(float_range, stop, step, epsilon=0.001): """It extend an existing float range.""" extension = _floatRange(float_range[-1], stop, step, epsilon) float_range.extend(extension[1:]) return float_range class TimeSequence(list): """A list of times. Verifications: - all items are convertible to floats - items are in non-decreasing order. """ def __init__(self, a_list, unit='s'): self.unit = unit new = _float_list(a_list) _verify_order(new) list.__init__(self, new) return def insert(self, time): if time not in self: self.append(time) self.sort() return def merge(self, other): list = self + other list.sort() return TimeSequence(list) def extract(self, time_specification): ts_class = time_specification.__class__ if ts_class == FrequencyTimeSpecs: return self.extractFromFrequency(time_specification.getFrequency()) elif ts_class == PeriodTimeSpecs: return self.extractFromPeriod(time_specification.getPeriod()) elif ts_class == SequenceTimeSpecs: return time_specification.getSequence() def extractFromPeriod(self, period): times = _floatRange(self[0], self[-1], period) return TimeSequence(times) def extractFromFrequency(self, jump): times = [] nb = len(self) n_out = nb / jump for i in range(n_out): times.append(self[i*jump]) pass if nb%jump != 0: # always include last time times.append(self[-1]) pass return TimeSequence(times)
"""Algebraic Operations with List of FLoats.""" import math import numpy as npy from operator import __and__ as AND from operator import add as addition from operator import mul as multiplication from types import ListType,TupleType def toList(x): """ Direkt von der ZauberFloete returns a list type object made of x element or elements """ if type(x) in [ListType,TupleType]: return list(x) else: return [x] def _checkListLength(lst1, lst2): if len(lst1) != len(lst2): raise Exception, "check arguments length" def isListOfLists(x): if not isinstance(x, ListType): return False return reduce(AND, map(lambda z: isinstance(z, ListType), x)) def printList(lst,str): """print a list""" ind=0 for i in lst : print str,ind,i ind+=1 pass print "end of printlist ",len(lst) return None def _add(x, y): return x + y def _sub(x, y): return x - y def addLists(lst1, lst2): return map(_add, lst1, lst2) def subtractLists(lst1, lst2): return map(_sub, lst1, lst2) def amultList(a, lst1): return map(lambda x: a*x , lst1) def dot( a, b ): return reduce(addition, map( multiplication, a, b)) def normMaxList(liste): return max(abs(min(liste)), abs(max(liste))) def normL1List(list): return npy.sum(npy.absolute(list)) normL1 = normL1List def norm2List(list): return (npy.sum(npy.absolute(list)**2))**0.5 norm2L = norm2List def normMaxListComparison(lst1, lst2): """ Returns normMax(lst1 - lst2) / normMax(lst2). """ return normMaxList(subtractLists(lst1, lst2)) / normMaxList(lst2) def norm2ListComparison(lst1, lst2): """ Returns norm2(l1 - l2) / norm2(l2). """ return norm2L(subtractLists(lst1, lst2)) / norm2L(lst2) def elimCommonElementsInList(liste,epsilon): """returns a new list made of all single elements in list liste (single test is made at epsilon)""" liste.sort() l_temp = [liste[0]] li = range(len(liste)) for i in li[1:]: time = liste[i] if type(time) != TupleType: if abs(time - l_temp[-1]) > epsilon: l_temp.append(time) pass pass else: # if element is a tuple, we keep it! l_temp.append(time) pass pass return l_temp def toFloatList(l): """ convert int list to float list """ return map(float,l) def extractIndex(l,index): """ Extract from the list l the value corrresponding to list index """ new_l = [] len_l = len(l) for i in index: if i<=len_l: new_l.append(l[i]) pass else: mess = "index %i output of range of list l"%i raise IncorrectValue(mess) pass return new_l
import random value = random.randint(1,100) count = 0 print('Proposer un nombre entre 1 et 100!') guess = input("Votre valeur: ") while guess != value: count += 1 if guess.isnumeric(): guess = int(guess) else: print("Ce n'est pas un nombre entier, veuillez entrer un nombre entier entre 1 et 100") guess = input() if int(guess) > int(value): print('Votre proposition est trop grande, retentez votre chance!') guess = input() elif int(guess) < int(value): print('Votre proposition est trop petite, retentez votre chance!') guess = input() continue print(f'Bien joué {guess} était la valeur à trouver et vous l\'avez trouvé en {count} tentatives!')
import pandas as pd import sys import os from datetime import date # fileloc = sys.argv[1] locinput = input("Paste the directory of the xlsx file ") # read the excel file df = pd.read_excel(locinput) # strip unecessary columns and leaving whats needed df = df[['DSM', 'Util %']] # remove NaN's df = df.dropna() # Removes any rows that have inapplicable data df = df[(~df['DSM'].str.contains('ARCHIVE|INACTIVE|EXPIRED|CUST DEFERRED')) & (~df['Util %'].str.contains("NaN|Inactive"))] # Sliced all objects in the 'Util %' column leaving only the first two characters df['Util %'] = df['Util %'].str.slice(stop=2) # Peaked Util was sliced to Pe and "Peaked Util" == 100 df['Util %'] = df['Util %'].replace("Pe", 100) # Since all values in 'Util %' are integers, we can convert it to a int series df['Util %'] = df['Util %'].astype(int) # Create a new dataframe that groups by the DSM names and take the mean of each DSM utilization newdf = df.groupby('DSM', as_index=False).mean() # Rename the columns of the new dataframe newdf.columns = ['DSM', 'AVG Util %'] # Retrieve today's date date = date.today() # Format the location of the new xlsx and its date # Have to use old formatting method due to python 2.7 (Default MacOS Python ver.) cwdfinal = "AVGUTIL %s.xlsx" % (date) newdf.to_excel(cwdfinal, index=False) # print for debugging print('done!')
print("********************************") print("Star Pattern") print("********************************") print("Number of Stars you want to see in galaxy") num = int(input()) + 1 print("You want to print reverse or straight (0(Yes)/1(NO))") optionReverse = int(input()) if optionReverse == 0: Reverse = True elif optionReverse == 1: Reverse = False else: print("Provide option 0 or 1") if Reverse: for i in range(num): for j in range(i): print("*", end=" ") print("\n") else: for i in reversed(range(num)): for j in range(i): print("*", end=" ") print("\n")
#Taking cost of 1 Tile cost = int(input("Enter the cost of 1 Tile:" )) print(f"Cost of 1 Tile is {cost}Rs") #floor height and width f_width = 11 f_height = 10 print('Floor width is 11 Feet and height is 10 Feet ') #Tile Height and width t_width = 60 t_height = 60 print('Tile width is 60 cm and height is 60 cm ') #Total Area of Floor f_area = f_width * f_height print(f'Total area of floor is {f_area} sq ft') #Total area of Tile t_area = t_width * t_height print(f'Total area of tile is {t_area} cm^2') # COnverting cm to sq feet to equal unit 1cm^2 = 0.001sq feet t_area_sqft = t_area * 0.001 print(f'Total area of 1 tile in sq feet is {t_area_sqft} sq ft') #Calcualting Total Number of Tiles Required no_of_Tile_Required = round(f_area / t_area_sqft) print(f'Number of tiles required is {no_of_Tile_Required} tiles') print(f'Total cost of Tile to cover{f_area} sq feet is {no_of_Tile_Required * cost} Rs')
#!/usr/bin/python from ingredient import Ingredient class Meal: """The Meal class contains the name of the meal as well as a list of required Ingredients. """ def __init__(self, options): self.ingredients = [] self.hydrate(options) def hydrate(self, options): self.name = options['name'] if 'ingredients' in options.keys(): for ingredient_data in options['ingredients']: ingredient = Ingredient(ingredient_data) self.ingredients.append(ingredient) def show(self, string): string = string + self.name + ':' + '\n' for ingredient in self.ingredients: string = ingredient.show(string) return string
# 숨겨진 카드의 수를 맞추는 게임입니다. 1-100까지의 임의의 수를 가진 카드를 한 장 숨기고 이 카드의 수를 맞추는 게임입니다. # 아래의 화면과 같이 카드 속의 수가 57인 경우를 보면 수를 맞추는 사람이 40이라고 입력하면 "더 높게", # 다시 75이라고 입력하면 "더 낮게" 라는 식으로 범위를 좁혀가며 수를 맞추고 있습니다. 게임을 반복하기 위해 y/n이라고 묻고 n인 경우 종료됩니다. import random min, max = 1, 100 while True: randomnum = random.randrange(max) + min count = 1 print(randomnum) print('수를 결정하였습니다. 맞추어 보세요.') minnum = min maxnum = max while True: print(minnum, '-', maxnum) inputnum = int(input(str(count) + '>>')) if randomnum > inputnum: print('더 높게') minnum = inputnum count += 1 elif randomnum < inputnum: print('더 낮게') maxnum = inputnum count += 1 else: print('맞았습니다.') break if 'n' == input('다시 하시겠습니까(y/n)>>'): break
#!/usr/bin/python3 matriz = [ [1,2,3], [4,5,6], [7,8,9] ] for x in range(0,len(matriz),1): for y in range(0,len(matriz),1): print(matriz[x][y])
# O mesmo professor do desafio 19 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada. # import random from random import shuffle import os import time listaOrdemAlunos = list(range(4)) i = 0 while i < len(listaOrdemAlunos): listaOrdemAlunos[i] = input('Entre com o nome do aluno: ') i += 1 os.system('clear') or None shuffle(listaOrdemAlunos) # print(listaOrdemAlunos) x = 0 print(50 * '-') print('Ordem de apresentação será:') while x <len(listaOrdemAlunos): print('{}º {}\n'.format(x+1,listaOrdemAlunos[x])) x += 1 time.sleep(5) # os.system('clear') or None
""" Leia um numero inteiro e mostre na tela o seu sucessor e antecessor """ numero = int(input('Entre com um numero inteiro: ')) print('O antecessor de {} é : {}'.format(numero, (numero-1))) print(' e o sucessor é {} '.format(numero+1))
# Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. # import math from math import tan, sin,cos, radians angulo = int(input('Entre com ângulo: ')) print('O seno de {} é {:.2f},\nO Cosseno de {} é {:.2f},\nA tangente de {} é {:.2f}'.format(angulo, sin(radians(angulo)), angulo, cos(radians(angulo)), angulo, tan(radians(angulo))))
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido. # import random from random import choice import os import time lista = list(range(4)) i = 0 while i < len(lista): lista[i] = str(input('Entre com o nome:')) i +=1 print('Por favor {}, poderia apagar o quadro!'.format(choice(lista))) time.sleep(3) os.system('clear') or None
def levenstein_dist(str1, str2): dist = [i for i in range((len(str1) + 1))] for idx2 in range(1, len(str2)+1): next_dist = [0] * (len(str1) + 1) next_dist[0] = idx2 for idx1 in range(1, len(str1)+1): if str1[idx1-1] == str2[idx2-1]: substitution_cost = 0 else: substitution_cost = 1 next_dist[idx1] = min(dist[idx1] + 1, next_dist[idx1-1] + 1, dist[idx1-1] + substitution_cost) dist = next_dist return dist print(levenstein_dist("sitten", "sitting"))
# 两个栈实现一个队列 def stacktoqueue(size): stack1 = [] stack2 = [] for i in range(size): inqueue(i) def inqueue(data): pass def outqueue(): pass def transdata(stack1, stack2): pass
nums = [23,2,4,6,2,5,1,6,13,54,8] def select_sort(nums): # 时间复杂度O(n^2) if not nums: return [] for i in range(len(nums)-1): smallest = i for j in range(i, len(nums)): if nums[j] < nums[smallest]: smallest = j nums[i], nums[smallest] = nums[smallest], nums[i] return nums print(select_sort(nums))
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def preordertraversal(self, root): res = [] def dfs(root): if not root: return res.append(root.val) dfs(root.left) dfs(root.right) dfs(root) return res def preorder(self, root): # 用栈来代替递归 if not root: return [] res = [] stack = [] while stack or root: if root: res.append(root.val) stack.append(root.val) root = root.left else: root = stack.pop() root = root.right return res def levelordertraversal(self, root): from collections import deque # 层序遍历(广度优先遍历)基本上是由deque队列实现的 queue = deque() queue.append(root) res = [] while queue: level = [] for _ in range(len(queue)): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(level) return res def levelorder(self, root): # 时间复杂度O(n), 空间复杂度O(n) if not root: return [] res = [] queue = [root] while queue: root = queue.pop(0) res.append(root.val) if root.left: queue.append(root.left) if root.right: queue.append(root.right) return res # 二叉树的后序遍历, 非递归版本: 非递归的后序遍历是 hard 难度, 所以专门在这里写一下。有下面几种思路: # 前序遍历是“根-左-右”, 稍微改一下, 就可以变成“根-右-左”, # 而将最后的结果倒序输出, 就是后序遍历“左-右-根”的顺序了。时间复杂度依然为 O(n): def postorder_1(root): if not root: return [] res = [] stack = [] while stack or root: if root: res.append(root.val) stack.append(root.val) root = root.right else: root = stack.pop() root = root.left # res1 用来存放 res 的倒序输出, 也可以直接使用 res[::-1] res1 = [] for i in range(len(res)): res1.append(res.pop()) return res1 # 使用两个栈实现, 这个思路也比较易于理解。后序遍历是“左-右-根”, # 所以对于一个栈来说,应该先push根结点,然后push右结点,最后push左结点: def postorder_2(root): if not root: return [] res = [] stack = [root] while stack: root = stack.pop() res.append(root) if root.left: stack.append(root.left) if root.right: stack.append(root.right) # 此时res中存放了倒序的结点, 使用res1将其倒序输出并取结点的值 res1 = [] for i in range(len(res)): res1.append(res.pop().val) return res1
from operator import itemgetter def check(string , checksum): dic = {} numbers = '' for i in string : if i.isalpha() : if i in dic : dic[i] += 1 else : dic[i] = 1 elif i.isdigit() : numbers += i temp = sorted(dic.items()) temp.sort(key=itemgetter(1) , reverse = True) c = ''.join([temp[i][0] for i in range(5)]) #print temp ,c ,checksum if (c == checksum) : return int(numbers) return 0 file = open("input.txt" , "r") li = file.readlines() li = [[i[:-8] , i[-7:-2]] for i in li] count = 0 for i in li : count += check(i[0] , i[1]) print count
import csv # with open('names.csv', 'w') as file: # fieldnames = ['question', 'title'] # writer = csv.DictWriter(file, fieldnames=fieldnames) # writer.writeheader() questionid = 100000 with open('01_01_2014-12_31_2014_1_.csv') as csvfile: spamreader = csv.DictReader(csvfile) for row in spamreader: questionid += 1 type = row['type'] title = row['title'] content = row['content'] text = row['text'] code= row['code'] user_id = row['user_id'] time = row['time'] upvote = row['vote'] reputation = row['reputation'] accept_rate = row['accept_rate'] tags = row['tag'].split() print(tags) if type == "question": with open('question_details.csv', 'a') as file: writer = csv.writer(file) writer.writerow([questionid,user_id,time,text,title,content,tags,upvote,tags]) #Here tags is array! We want to have different tag. How will we do that? if (type == "answer") | (type == "accepted-answer"): # Remove following and do answer schema here. Field as per discussion in whatsapp group. with open('answer_details.csv', 'a') as file: writer = csv.writer(file) writer.writerow([questionid,user_id,time,text,title,content,tags,upvote,tags]) password = user_id with open('users.csv','a') as file: # Remove following and do answer schema here . Put Password == user id. Login/Logout History. Include Tags and the weight. writer = csv.writer(file) writer.writerow([questionid, user_id, time, text, title, content, tags, upvote, tags])
# pylint: disable-msg=anomalous-backslash-in-string """ Clock object ============ The :class:`Clock` object allows you to schedule a function call in the future; once or repeatedly at specified intervals. It's heavily based on Kivy's Clock object. (Almost 100% identical.) An instance of the clock is available in MPF set `self.machine.clock`. You can get the time elapsed between the scheduling and the calling of the callback via the `dt` argument:: # dt means delta-time def my_callback(self, dt): pass # call my_callback every 0.5 seconds self.machine.clock.schedule_interval(my_callback, 0.5) # call my_callback in 5 seconds self.machine.clock..schedule_once(my_callback, 5) # call my_callback as soon as possible (usually next frame.) self.machine.clock..schedule_once(my_callback) .. note:: If the callback returns False, the schedule will be removed. If you want to schedule a function to call with default arguments, you can use the `functools.partial <http://docs.python.org/library/functools.html#functools.partial>`_ python module:: from functools import partial def my_callback(value, key, *largs): pass self.machine.clock.schedule_interval(partial(my_callback, 'my value', 'my key'), 0.5) Conversely, if you want to schedule a function that doesn't accept the dt argument, you can use a `lambda <http://docs.python.org/2/reference/expressions.html#lambda>`_ expression to write a short function that does accept dt. For Example:: def no_args_func(): print("I accept no arguments, so don't schedule me in the clock") self.machine.clock..schedule_once(lambda dt: no_args_func(), 0.5) .. note:: You cannot unschedule an anonymous function unless you keep a reference to it. It's better to add \*args to your function definition so that it can be called with an arbitrary number of parameters. .. important:: The callback is weak-referenced: you are responsible for keeping a reference to your original object/callback. If you don't keep a reference, the ClockBase will never execute your callback. For example:: class Foo(object): def start(self): self.machine.clock..schedule_interval(self.callback, 0.5) def callback(self, dt): print('In callback') # A Foo object is created and the method start is called. # Because no reference is kept to the instance returned from Foo(), # the object will be collected by the Python Garbage Collector and # your callback will be never called. Foo().start() # So you should do the following and keep a reference to the instance # of foo until you don't need it anymore! foo = Foo() foo.start() .. _schedule-before-frame: Schedule before frame --------------------- Sometimes you need to schedule a callback BEFORE the next frame. Starting from 1.0.5, you can use a timeout of -1:: self.machine.clock.schedule_once(my_callback, 0) # call after the next frame self.machine.clock.schedule_once(my_callback, -1) # call before the next frame The Clock will execute all the callbacks with a timeout of -1 before the next frame even if you add a new callback with -1 from a running callback. However, :class:`Clock` has an iteration limit for these callbacks: it defaults to 10. If you schedule a callback that schedules a callback that schedules a .. etc more than 10 times, it will leave the loop and send a warning to the console, then continue after the next frame. This is implemented to prevent bugs from hanging or crashing the application. If you need to increase the limit, set the :attr:`max_iteration` property:: self.machine.clock.max_iteration = 20 .. _triggered-events: Triggered Events ---------------- A triggered event is a way to defer a callback exactly like schedule_once(), but with some added convenience. The callback will only be scheduled once per frame even if you call the trigger twice (or more). This is not the case with :meth:`Clock.schedule_once`:: # will run the callback twice before the next frame self.machine.clock.schedule_once(my_callback) self.machine.clock.schedule_once(my_callback) # will run the callback once before the next frame t = self.machine.clock.create_trigger(my_callback) t() t() Before triggered events, you may have used this approach in a widget:: def trigger_callback(self, *largs): self.machine.clock.unschedule(self.callback) self.machine.clock.schedule_once(self.callback) As soon as you call `trigger_callback()`, it will correctly schedule the callback once in the next frame. It is more convenient to create and bind to the triggered event than using :meth:`Clock.schedule_once` in a function:: class Foo(object): def __init__(self, **kwargs): self._trigger = self.machine.clock.create_trigger(self.cb) def cb(self, *largs): pass .. note:: :meth:`ClockBase.create_trigger` also has a timeout parameter that behaves exactly like :meth:`ClockBase.schedule_once`. Threading ---------- Often, other threads are used to schedule callbacks with MPF's main thread using :class:`ClockBase`. Therefore, it's important to know what is thread safe and what isn't. All the :class:`ClockBase` and :class:`ClockEvent` methods are safe with respect to MPF's thread. That is, it's always safe to call these methods from a single thread that is not the main thread. However, there are no guarantees as to the order in which these callbacks will be executed. Calling a previously created trigger from two different threads (even if one of them is the main thread), or calling the trigger and its :meth:`ClockEvent.cancel` method from two different threads at the same time is not safe. That is, although no exception will be raised, there no guarantees that calling the trigger from two different threads will not result in the callback being executed twice, or not executed at all. Similarly, such issues might arise when calling the trigger and canceling it with :meth:`ClockBase.unschedule` or :meth:`ClockEvent.cancel` from two threads simultaneously. Therefore, it is safe to call :meth:`ClockBase.create_trigger`, :meth:`ClockBase.schedule_once`, :meth:`ClockBase.schedule_interval`, or call or cancel a previously created trigger from an external thread. The following code, though, is not safe because it calls or cancels from two threads simultaneously without any locking mechanism:: event = self.machine.clock.create_trigger(func) # in thread 1 event() # in thread 2 event() # now, the event may be scheduled twice or once # the following is also unsafe # in thread 1 event() # in thread 2 event.cancel() # now, the event may or may not be scheduled and a subsequent call # may schedule it twice Note, in the code above, thread 1 or thread 2 could be the main thread, not just an external thread. """ from sys import platform from functools import partial from queue import PriorityQueue, Empty import itertools import time import logging from mpf.core.weakmethod import WeakMethod # pylint: disable-msg=anomalous-backslash-in-string """ Clock object ============ The :class:`Clock` object allows you to schedule a function call in the future; once or repeatedly at specified intervals. You can get the time elapsed between the scheduling and the calling of the callback via the `dt` argument:: # dt means delta-time def my_callback(dt): pass # call my_callback every 0.5 seconds Clock.schedule_interval(my_callback, 0.5) # call my_callback in 5 seconds Clock.schedule_once(my_callback, 5) # call my_callback as soon as possible (usually next frame.) Clock.schedule_once(my_callback) .. note:: You can also add a priority to any callback that ensures that callbacks with higher priority values are called before ones with lower priorities when both will be called in the same frame. The default priority value is 1. # call my_callback every 0.5 seconds with a priority of 100 Clock.schedule_interval(my_callback, 0.5, 100) If the callback returns False, the schedule will be removed. If you want to schedule a function to call with default arguments, you can use the `functools.partial <http://docs.python.org/library/functools.html#functools.partial>`_ python module:: from functools import partial def my_callback(value, key, *largs): pass Clock.schedule_interval(partial(my_callback, 'my value', 'my key'), 0.5) Conversely, if you want to schedule a function that doesn't accept the dt argument, you can use a `lambda <http://docs.python.org/2/reference/expressions.html#lambda>`_ expression to write a short function that does accept dt. For Example:: def no_args_func(): print("I accept no arguments, so don't schedule me in the clock") Clock.schedule_once(lambda dt: no_args_func(), 0.5) .. note:: You cannot unschedule an anonymous function unless you keep a reference to it. It's better to add \*args to your function definition so that it can be called with an arbitrary number of parameters. .. important:: The callback is weak-referenced: you are responsible for keeping a reference to your original object/callback. If you don't keep a reference, the ClockBase will never execute your callback. For example:: class Foo(object): def start(self): Clock.schedule_interval(self.callback, 0.5) def callback(self, dt): print('In callback') # A Foo object is created and the method start is called. # Because no reference is kept to the instance returned from Foo(), # the object will be collected by the Python Garbage Collector and # your callback will be never called. Foo().start() # So you should do the following and keep a reference to the instance # of foo until you don't need it anymore! foo = Foo() foo.start() .. _schedule-before-frame: Schedule before frame --------------------- .. versionadded:: 1.0.5 Sometimes you need to schedule a callback BEFORE the next frame. Starting from 1.0.5, you can use a timeout of -1:: Clock.schedule_once(my_callback, 0) # call after the next frame Clock.schedule_once(my_callback, -1) # call before the next frame The Clock will execute all the callbacks with a timeout of -1 before the next frame even if you add a new callback with -1 from a running callback. However, :class:`Clock` has an iteration limit for these callbacks: it defaults to 10. If you schedule a callback that schedules a callback that schedules a .. etc more than 10 times, it will leave the loop and send a warning to the console, then continue after the next frame. This is implemented to prevent bugs from hanging or crashing the application. If you need to increase the limit, set the :attr:`max_iteration` property:: from kivy.clock import Clock Clock.max_iteration = 20 .. _triggered-events: Triggered Events ---------------- .. versionadded:: 1.0.5 A triggered event is a way to defer a callback exactly like schedule_once(), but with some added convenience. The callback will only be scheduled once per frame even if you call the trigger twice (or more). This is not the case with :meth:`Clock.schedule_once`:: # will run the callback twice before the next frame Clock.schedule_once(my_callback) Clock.schedule_once(my_callback) # will run the callback once before the next frame t = Clock.create_trigger(my_callback) t() t() Before triggered events, you may have used this approach in a widget:: def trigger_callback(self, *largs): Clock.unschedule(self.callback) Clock.schedule_once(self.callback) As soon as you call `trigger_callback()`, it will correctly schedule the callback once in the next frame. It is more convenient to create and bind to the triggered event than using :meth:`Clock.schedule_once` in a function:: from kivy.clock import Clock from kivy.uix.widget import Widget class Sample(Widget): def __init__(self, **kwargs): self._trigger = Clock.create_trigger(self.cb) super(Sample, self).__init__(**kwargs) self.bind(x=self._trigger, y=self._trigger) def cb(self, *largs): pass Even if x and y changes within one frame, the callback is only run once. .. note:: :meth:`ClockBase.create_trigger` also has a timeout parameter that behaves exactly like :meth:`ClockBase.schedule_once`. Threading ---------- .. versionadded:: 1.9.0 Often, other threads are used to schedule callbacks with kivy's main thread using :class:`ClockBase`. Therefore, it's important to know what is thread safe and what isn't. All the :class:`ClockBase` and :class:`ClockEvent` methods are safe with respect to kivy's thread. That is, it's always safe to call these methods from a single thread that is not the kivy thread. However, there are no guarantees as to the order in which these callbacks will be executed. Calling a previously created trigger from two different threads (even if one of them is the kivy thread), or calling the trigger and its :meth:`ClockEvent.cancel` method from two different threads at the same time is not safe. That is, although no exception will be raised, there no guarantees that calling the trigger from two different threads will not result in the callback being executed twice, or not executed at all. Similarly, such issues might arise when calling the trigger and canceling it with :meth:`ClockBase.unschedule` or :meth:`ClockEvent.cancel` from two threads simultaneously. Therefore, it is safe to call :meth:`ClockBase.create_trigger`, :meth:`ClockBase.schedule_once`, :meth:`ClockBase.schedule_interval`, or call or cancel a previously created trigger from an external thread. The following code, though, is not safe because it calls or cancels from two threads simultaneously without any locking mechanism:: event = Clock.create_trigger(func) # in thread 1 event() # in thread 2 event() # now, the event may be scheduled twice or once # the following is also unsafe # in thread 1 event() # in thread 2 event.cancel() # now, the event may or may not be scheduled and a subsequent call # may schedule it twice Note, in the code above, thread 1 or thread 2 could be the kivy thread, not just an external thread. """ """ --------------------- MPF v0.30 This file was adapted from Kivy for use in MPF. The following changes have been made for use in MPF: 1) Support proper event callback order in a frame based on scheduled callback time (earliest first), priority (highest first), and finally the order in which the callback was added to the clock. This involved adding triggered events to a priority queue and then executing all the callbacks in the queue during each frame. 2) The 5ms look-ahead for activating events has been removed. 3) next_event_time and last_event_time properties have been added. 4) Clock is not used as a global singleton in MPF, but rather as an instantiated object. Multiple clock objects could be used in a single program if desired. 5) max_fps is now a parameter in the Clock constructor (defaults to 60) that controls the maximum speed at which the MPF main loop/clock runs. """ __all__ = ('ClockBase', 'ClockEvent') _default_time = time.perf_counter '''A clock with the highest available resolution. ''' try: # pylint: disable-msg=wrong-import-position # pylint: disable-msg=wrong-import-order import ctypes if platform in ('win32', 'cygwin'): # Win32 Sleep function is only 10-millisecond resolution, so # instead use a waitable timer object, which has up to # 100-nanosecond resolution (hardware and implementation # dependent, of course). _kernel32 = ctypes.windll.kernel32 class _ClockBase(object): def __init__(self): self._timer = _kernel32.CreateWaitableTimerA(None, True, None) def usleep(self, microseconds): delay = ctypes.c_longlong(int(-microseconds * 10)) _kernel32.SetWaitableTimer( self._timer, ctypes.byref(delay), 0, ctypes.c_void_p(), ctypes.c_void_p(), False) _kernel32.WaitForSingleObject(self._timer, 0xffffffff) else: if platform == 'darwin': _libc = ctypes.CDLL('libc.dylib') else: # pylint: disable-msg=wrong-import-position # pylint: disable-msg=wrong-import-order from ctypes.util import find_library _libc = ctypes.CDLL(find_library('c'), use_errno=True) def _libc_clock_gettime_wrapper(): from os import strerror class StructTv(ctypes.Structure): _fields_ = [('tv_sec', ctypes.c_long), ('tv_usec', ctypes.c_long)] _clock_gettime = _libc.clock_gettime _clock_gettime.argtypes = [ctypes.c_long, ctypes.POINTER(StructTv)] if 'linux' in platform: _clockid = 4 # CLOCK_MONOTONIC_RAW (Linux specific) else: _clockid = 1 # CLOCK_MONOTONIC tv = StructTv() def _time(): if _clock_gettime(ctypes.c_long(_clockid), ctypes.pointer(tv)) != 0: _ernno = ctypes.get_errno() raise OSError(_ernno, strerror(_ernno)) return tv.tv_sec + (tv.tv_usec * 0.000000001) return _time _default_time = _libc_clock_gettime_wrapper() _libc.usleep.argtypes = [ctypes.c_ulong] _libc_usleep = _libc.usleep class _ClockBase(object): @classmethod def usleep(cls, microseconds): _libc_usleep(int(microseconds)) except (OSError, ImportError, AttributeError): # ImportError: ctypes is not available on python-for-android. # AttributeError: ctypes is now available on python-for-android, but # "undefined symbol: clock_gettime". CF #3797 # OSError: if the libc cannot be readed (like with buildbot: invalid ELF # header) _default_sleep = time.sleep class _ClockBase(object): @classmethod def usleep(cls, microseconds): _default_sleep(microseconds / 1000000.) def _hash(cb): if hasattr(cb, '__self__') and cb.__self__ is not None: return (id(cb.__self__) & 0xFF00) >> 8 return (id(cb) & 0xFF00) >> 8 # pylint: disable-msg=too-many-instance-attributes class ClockEvent(object): """ A class that describes a callback scheduled with kivy's :attr:`Clock`. This class is never created by the user; instead, kivy creates and returns an instance of this class when scheduling a callback. .. warning:: Most of the methods of this class are internal and can change without notice. The only exception are the :meth:`cancel` and :meth:`__call__` methods. """ # pylint: disable-msg=too-many-arguments def __init__(self, clock, loop, callback, timeout, starttime, cid, priority=1, trigger=False): self.clock = clock self.cid = cid self.id = next(clock.counter) self.loop = loop self.weak_callback = None self.callback = callback self.timeout = timeout self._is_triggered = trigger self._last_dt = starttime self._next_event_time = starttime + timeout self._last_event_time = 0 self._dt = 0. self._priority = priority self._callback_cancelled = False if trigger: clock.events[cid].append(self) def __call__(self, *largs): """ Schedules the callback associated with this instance. If the callback is already scheduled, it will not be scheduled again. """ # if the event is not yet triggered, do it ! del largs if self._is_triggered is False: self._is_triggered = True # update starttime self._last_dt = self.clock.get_time() self.clock.events[self.cid].append(self) return True def get_callback(self): callback = self.callback if callback is not None: return callback callback = self.weak_callback if callback.is_dead(): return None return callback() @property def is_triggered(self): return self._is_triggered @property def next_event_time(self): return self._next_event_time @property def last_event_time(self): return self._last_event_time @property def priority(self): return self._priority @property def callback_cancelled(self): return self._callback_cancelled def cancel(self): """ Cancels the callback if it was scheduled to be called. """ if self._is_triggered: self._is_triggered = False try: self.clock.events[self.cid].remove(self) except ValueError: pass self._callback_cancelled = True def release(self): self.weak_callback = WeakMethod(self.callback) self.callback = None def tick(self, curtime, remove): # Is it time to execute the callback (did timeout occur)? The # decision is easy if this event's timeout is 0 or -1 as it # should be called every time. if self.timeout > 0 and curtime < self._next_event_time: return True # calculate current time-diff for this event self._dt = curtime - self._last_dt self._last_dt = curtime loop = self.loop if self.timeout > 0: self._last_event_time = self._next_event_time self._next_event_time += self.timeout else: self._last_event_time = curtime self._next_event_time = curtime # get the callback callback = self.get_callback() if callback is None: self._is_triggered = False try: remove(self) except ValueError: pass return False # Make sure the callback will be called by resetting its cancelled flag self._callback_cancelled = False # Do not actually call the callback here, instead add it to the clock # frame callback queue where it will be processed after all events are processed # for the frame. The callback queue is prioritized by callback time and then # event priority. self.clock.add_event_to_frame_callbacks(self) # if it's a trigger, allow to retrigger inside the callback # we have to remove event here, otherwise, if we remove later, the user # might have canceled in the callback and then re-triggered. That'd # result in the removal of the re-trigger if not loop: self._is_triggered = False try: remove(self) except ValueError: pass def __repr__(self): return '<ClockEvent callback=%r>' % self.get_callback() # pylint: disable-msg=too-many-instance-attributes class ClockBase(_ClockBase): """A clock object with event support. """ __slots__ = ('_dt', '_last_fps_tick', '_last_tick', '_fps', '_rfps', '_start_tick', '_fps_counter', '_rfps_counter', 'events', '_frame_callbacks', '_frames', '_frames_displayed', '_max_fps', 'max_iteration', '_log') MIN_SLEEP = 0.005 SLEEP_UNDERSHOOT = MIN_SLEEP - 0.001 counter = itertools.count() def __init__(self, max_fps): super(ClockBase, self).__init__() try: self._max_fps = float(max_fps) except ValueError: self._max_fps = 30.0 self._dt = 0.0001 self._start_tick = self._last_tick = self.time() self._fps = 0 self._rfps = 0 self._fps_counter = 0 self._rfps_counter = 0 self._last_fps_tick = None self._frames = 0 self._frames_displayed = 0 self.events = [[] for dummy_iterator in range(256)] self._frame_callbacks = PriorityQueue() self._log = logging.getLogger("Clock") self._log.debug("Starting clock (maximum frames per second=%s)", self._max_fps) #: .. versionadded:: 1.0.5 #: When a schedule_once is used with -1, you can add a limit on #: how iteration will be allowed. That is here to prevent too much #: relayout. self.max_iteration = 10 @property def max_fps(self): return self._max_fps @property def frametime(self): """Time spent between the last frame and the current frame (in seconds). .. versionadded:: 1.8.0 """ return self._dt @property def frames(self): """Number of internal frames (not necessarily drawn) from the start of the clock. .. versionadded:: 1.8.0 """ return self._frames @property def frames_displayed(self): """Number of displayed frames from the start of the clock. """ return self._frames_displayed def tick(self): """Advance the clock to the next step. Must be called every frame. The default clock has a tick() function called by the core Kivy framework.""" self._release_references() # do we need to sleep ? if self._max_fps > 0: min_sleep = self.MIN_SLEEP sleep_undershoot = self.SLEEP_UNDERSHOOT fps = self._max_fps usleep = self.usleep sleeptime = 1 / fps - (self.time() - self._last_tick) while sleeptime - sleep_undershoot > min_sleep: usleep(1000000 * (sleeptime - sleep_undershoot)) sleeptime = 1 / fps - (self.time() - self._last_tick) # tick the current time current = self.time() self._dt = current - self._last_tick self._frames += 1 self._fps_counter += 1 self._last_tick = current # calculate fps things if self._last_fps_tick is None: self._last_fps_tick = current elif current - self._last_fps_tick > 1: d = float(current - self._last_fps_tick) self._fps = self._fps_counter / d self._rfps = self._rfps_counter self._last_fps_tick = current self._fps_counter = 0 self._rfps_counter = 0 # process event self._process_events() # now process event callbacks self._process_event_callbacks() return self._dt def tick_draw(self): """Tick the drawing counter. """ self._process_events_before_frame() self._process_event_callbacks() self._rfps_counter += 1 self._frames_displayed += 1 def get_fps(self): """Get the current average FPS calculated by the clock. """ return self._fps def get_rfps(self): """Get the current "real" FPS calculated by the clock. This counter reflects the real framerate displayed on the screen. In contrast to get_fps(), this function returns a counter of the number of frames, not the average of frames per second. """ return self._rfps def get_time(self): """Get the last tick made by the clock.""" return self._last_tick def get_boottime(self): """Get the time in seconds from the application start.""" return self._last_tick - self._start_tick def create_trigger(self, callback, timeout=0, priority=1): """Create a Trigger event. Check module documentation for more information. :returns: A :class:`ClockEvent` instance. To schedule the callback of this instance, you can call it. .. versionadded:: 1.0.5 """ ev = ClockEvent(self, False, callback, timeout, 0, _hash(callback), priority) ev.release() return ev def schedule_once(self, callback, timeout=0, priority=1): """Schedule an event in <timeout> seconds. If <timeout> is unspecified or 0, the callback will be called after the next frame is rendered. :returns: A :class:`ClockEvent` instance. As opposed to :meth:`create_trigger` which only creates the trigger event, this method also schedules it. .. versionchanged:: 1.0.5 If the timeout is -1, the callback will be called before the next frame (at :meth:`tick_draw`). """ if not callable(callback): raise ValueError('callback must be a callable, got %s' % callback) event = ClockEvent( self, False, callback, timeout, self._last_tick, _hash(callback), priority, True) self._log.debug("Scheduled a one-time clock callback (callback=%s, timeout=%s, priority=%s)", str(callback), timeout, priority) return event def schedule_interval(self, callback, timeout, priority=1): """Schedule an event to be called every <timeout> seconds. :returns: A :class:`ClockEvent` instance. As opposed to :meth:`create_trigger` which only creates the trigger event, this method also schedules it. """ if not callable(callback): raise ValueError('callback must be a callable, got %s' % callback) event = ClockEvent( self, True, callback, timeout, self._last_tick, _hash(callback), priority, True) self._log.debug("Scheduled a recurring clock callback (callback=%s, timeout=%s, priority=%s)", str(callback), timeout, priority) return event def unschedule(self, callback, all_events=True): """Remove a previously scheduled event. :parameters: `callback`: :class:`ClockEvent` or a callable. If it's a :class:`ClockEvent` instance, then the callback associated with this event will be canceled if it is scheduled. If it's a callable, then the callable will be unscheduled if it is scheduled. `all`: bool If True and if `callback` is a callable, all instances of this callable will be unscheduled (i.e. if this callable was scheduled multiple times). Defaults to `True`. .. versionchanged:: 1.9.0 The all parameter was added. Before, it behaved as if `all` was `True`. """ if isinstance(callback, ClockEvent): callback.cancel() else: if all_events: for ev in self.events[_hash(callback)][:]: if ev.get_callback() == callback: ev.cancel() else: for ev in self.events[_hash(callback)][:]: if ev.get_callback() == callback: ev.cancel() break def _release_references(self): # call that function to release all the direct reference to any # callback and replace it with a weakref events = self.events for events in self.events: for event in events[:]: if event.callback is not None: event.release() del events def _process_events(self): for events in self.events: remove = events.remove for event in events[:]: # event may be already removed from original list if event in events: event.tick(self._last_tick, remove) def _process_events_before_frame(self): found = True count = self.max_iteration events = self.events while found: count -= 1 if count == -1: self._log.warning( 'Clock: Warning, too much iteration done before' ' the next frame. Check your code, or increase' ' the Clock.max_iteration attribute') break # search event that have timeout = -1 found = False for events in self.events: remove = events.remove for event in events[:]: if event.timeout != -1: continue found = True # event may be already removed from original list if event in events: event.tick(self._last_tick, remove) del events def add_event_to_frame_callbacks(self, event): """ Adds an event to the priority queue whose callback will be called in the current frame. Args: event: The event whose callback will be called (in priority order) during the current frame. """ self._frame_callbacks.put((event.last_event_time, -event.priority, event.id, event)) def _process_event_callbacks(self): """ Processes event callbacks that were triggered to be called in the current frame. """ while True: try: event = self._frame_callbacks.get(block=False)[3] except Empty: return # Call the callback if the event has not been cancelled during the current frame if not event.callback_cancelled: callback = event.get_callback() if callback: ret = callback(self.frametime) else: ret = False # if the user returns False explicitly, remove the event if event.loop and ret is False: event.cancel() time = staticmethod(partial(_default_time)) ClockBase.time.__doc__ = '''Proxy method for :func:`~kivy.compat.clock`. '''
#Graph BFS traversal def dfs(G,n,V): queue = [n] while queue: e = queue.pop(0) print "{0}->".format(e), for item in G[e]: if not V.get(item,False): queue.append(item) V[item] = True def main(): G = { 1:[2,11,8], 2:[1,14,7], 11:[1,17,6], 8:[1], 14:[2], 7:[2], 17:[11], 6:[11] } V = {1:True} head_node = 1 dfs(G,head_node,V) if __name__ == "__main__": main()
import time import picamera import os import datetime def nameProject(cam): name = str(input("\n\nEnter project name: ")) date = datetime.datetime.now() now = date.strftime("%Y-%m-%d") mypath = "/home/pi/camera/"+now+"-"+name if not os.path.isdir(mypath): os.makedirs(mypath) else: pass print("\nProject folder made successfully.\n") return mypath #put def takePicture here #put def preview here def display(num): if num == 0: print("\nWelcome to the image capture program for year 10s.") elif num == 1: print("\nBefore beginning please create your project file.") elif num == 2: print("\nOptions\n\n1. Preview camera view\n2. Start taking pictures\n3. Quit") def choice(): valid = False while not valid: try: option = int(input("\nEnter option: ")) if 1 <= option <= 3: valid == True else: print("\n\nOption not valid. Please enter option again.\n") except ValueError: print("\n\nOption not valid. Please enter option again.\n") return option def main(): cam = picamera() display(0) display(1) path = nameProject(cam) valid = False while not valid: display(2) x = choice() if x == 1: #preview(cam) print('1') elif x == 2: #takePicture(cam) print('2') elif x == 3: valid = True print("\n\nProgram ended.")
n = input('請輸入西元年') n = int(n) def is_leap(n): if n%4 != 0: print('平年') return False elif n%100 == 0 and n%400 != 0: print('閏年') return True elif n%100 == 0 and n%400 != 0: print('平年') return False elif n%400 == 0 and n%3200 !=0 : print('閏年') return True else : print('MD') is_leap(n)
import numpy as np import matplotlib.pyplot as plt def cross(set_list): '''Given a list of sets, return the cross product.''' # By associativity of cross product, cross the first two sets together # then cross that with the rest. The big conditional in the list # comprehension is just to make sure that there are no nested lists # in the final answer. if len(set_list) == 1: ans = [] for elem in set_list[0]: # In the 1D case, these elements are not lists. if type(elem) == list: ans.append(np.array(elem)) else: ans.append(np.array([elem])) return ans else: A = set_list[0] B = set_list[1] cross_2 = [a+b if ((type(a) == list) and (type(b) == list)) else \ (a+[b] if type(a) == list else ([a]+b if type(b) == list else \ [a]+[b])) for a in A for b in B] remaining = set_list[2:] remaining.insert(0,cross_2) return cross(remaining) def point_list(node): '''Return the list of lists containing the numbers, in order, of the indeces that must be looked at in the interpolation. node is a coordinate.''' ans = [] for coord in node: ans.append([coord-1,coord,coord+1,coord+2]) return ans def left_interpolation_node(pnt, x0, step_sizes): '''Suppose pnt (list of coordinates in each dimension) is where the sampled data is to be interpolated. Then pnt must be between two consecutive interpolation nodes (in each dimension), x_j and x_(j+1). Return x_j. The first point x0 and the step size in each dimension is needed for x_j to be found. Note: all parameters must have same dimensions. Note: returns the node in indeces, not actual units.''' pnt = np.array(pnt, dtype=float) left_node = np.floor((pnt - x0)/step_sizes) return np.array(left_node,dtype=int) def get_value(arr,node): '''Get the value of n-dimensional array arr at n-coordinate index node. Note node is a 1D array in pixels, not actual units.''' # Copy node since we needed it later and shouldn't mess with it. node_copy = node.copy() # The max index possible for each dimension of arr. max_indeces = np.array(arr.shape) - 1 # Initialize the bad_index. If it's stll -99 after looking through # all the coordinates of pnt, then pnt is in arr. bad_index = -99 # True if one coordinate of pnt is under the min possible (0) and # false if one coordinate of pnt is over the max possible. under = False # Find any index out of bounds (lower). for i in range(len(node)): if node[i] < 0: bad_index = i under = True elif node[i] > max_indeces[i]: bad_index = i under = False if bad_index == -99: # No bad indeces so just return the value of array at that point. return arr[tuple(node)] elif under: # There is a bad index and it is -1. Use method similar to set of # equations on page 1158 of article to find value. node_copy[bad_index] += 1 fst_node = node_copy.copy() node_copy[bad_index] += 1 snd_node = node_copy.copy() node_copy[bad_index] += 1 thd_node = node_copy.copy() return 3.*get_value(arr,fst_node) - 3.*get_value(arr,snd_node) + \ get_value(arr,thd_node) else: # There is a bad index and it is one more than the max possible. # Note there cannot be any other cases. node_copy[bad_index] -= 1 fst_node = node_copy.copy() node_copy[bad_index] -= 1 snd_node = node_copy.copy() node_copy[bad_index] -= 1 thd_node = node_copy.copy() return 3.*get_value(arr,fst_node) - 3.*get_value(arr,snd_node) + \ get_value(arr,thd_node) def u(s): '''Return the cubic convolution interpolation kernel given the pixel distance. See equation 15 from Robert G. Keys 1981 article.''' # Note: the s==0 and else cases are put in for correctness but # these should never be reached since this function does not need # to be called in those cases. s = abs(s) if 0 < s < 1: return 3./2.*s**3 - 5./2.*s**2 + 1. elif 1 < s < 2: return -1./2.*s**3 + 5./2.*s**2 - 4.*s + 2. elif s == 0: return 1. else: return 0. def u_product(pnt, node, x0, step_sizes): '''Return the product of the "u" in each dimension. Want to get the equivalent of the u part of the equation on pg 1157. pnt and node are arrays containing the point we wish to interpolate and the points with known values in the array, respectively. pnt is in actual units while node is in indeces. x0 is the initial point in n-dimensions. step_sizes is the distance between pixels in each dimension.''' step_sizes = np.array(step_sizes, dtype='float') node_pixel = x0 + node*step_sizes return np.product(map(u,(pnt-node_pixel)/step_sizes)) def reassign_weights(points, weights, max_inds): '''Return new points and weights such that the value and weight of any out of bound point is spread over in-bound points. max_ind is an array containing the max index allowed for each axis.''' # Keep track of bad points so that they can be assigned fake # inbound point indices afterwards. bad_points = [] for i in range(len(points)): spread = find_weight_spread(points[i],points,max_inds) # If the point is bad, redistribute the weights. if not (np.sum(spread**2) == 1): bad_points.append(i) # Note that this can be done concurrently with finding the # bad points since the weights are only going to change for # in bound points and these points will never have their # weights spread over anything else. weights += spread*weights[i] # Assign fake indeces to bad points. Since the 0th index always exists # for an array, assign it that with a weight of zero. zero_index = np.zeros(len(max_inds),dtype='int') for j in bad_points: points[j] = zero_index weights[j] = 0.0 return points,weights def find_point_in_list(point, point_list): '''Return the index of a point in a point_list (or array). Note that point must occur once and only once in point_list.''' index = 0 for i in range(len(point_list)): if tuple(point) == tuple(point_list[i]): index = i return index def find_weight_spread(point, points, max_inds): '''Given a point "point" and the list of points needed for cubic interpolation, "points," return how much weight needs to be multiplied in each point in "points." max_ind is an array containing the max index allowed for each axis.''' point = np.array(point) min_inds = np.zeros(len(point)) # Point is in bounds. if (False not in (point <= max_inds).tolist()) and \ (False not in (point >= min_inds).tolist()): # Point should not spread its value around. So return # its location with a value of 1 and all other points # a value of 0. add_weights = np.zeros(len(points)) one_index = find_point_in_list(point,points) add_weights[one_index] = 1.0 return add_weights # Point is under bounds on at least one axis. elif (False in (point >= min_inds).tolist()): # Find the bad axis. for i in range(len(point)): if point[i] < 0: under_axis = i # Split its weight based on eqn 19. Note recursion # is to take care of points out of bounds on muliple axes. point_1 = np.copy(point) point_1[under_axis] += 1 point_2 = np.copy(point) point_2[under_axis] += 2 point_3 = np.copy(point) point_3[under_axis] += 3 weights_1 = find_weight_spread(point_1, points, max_inds) weights_2 = find_weight_spread(point_2, points, max_inds) weights_3 = find_weight_spread(point_3, points, max_inds) return 3.0*weights_1 - 3.0*weights_2 + 1.0*weights_3 # Point is over bounds on at least one axis. elif (False in (point <= max_inds).tolist()): # Find the bad axis. for i in range(len(point)): if point[i] > max_inds[i]: over_axis = i # Split its weight based on eqn 25. Note recursion # is to take care of points out of bounds on muliple axes. point_N = np.copy(point) point_N[over_axis] -= 1 point_N1 = np.copy(point) point_N1[over_axis] -= 2 point_N2 = np.copy(point) point_N2[over_axis] -= 3 weights_N = find_weight_spread(point_N, points, max_inds) weights_N1 = find_weight_spread(point_N1, points, max_inds) weights_N2 = find_weight_spread(point_N2, points, max_inds) return 3.0*weights_N - 3.0*weights_N1 + 1.0*weights_N2 else: print "You shouldn't be here..." def interpolate_weights(axes, pnt, x0, step_sizes, max_inds): '''Return the points and weights of all non-zero weighted points needed in the cubic interpolation. 'axes' is the list of axes to be interpolated over. Only the dimensions in axes will be looked at to get the appropriate nodes and all other dimensions will be ignored. See interpolate for description of other parameters. In the new interpolate, points that are out of the boundaries are split amongst points that are inboundaries so map maker doesn't crash. max_ind is an array containing the max index allowed for each axis. Now needed to be able to tell what an out of bound point is.''' # Get only the needed axes out of the info we have to be able to # call the code already written. new_pnt = [] new_x0 = [] new_step_sizes = [] for i in range(len(axes)): new_pnt.append(pnt[i]) new_x0.append(x0[i]) new_step_sizes.append(step_sizes[i]) new_pnt = np.array(new_pnt) new_x0 = np.array(new_x0) new_step_sizes = np.array(new_step_sizes) # Get the closest node to the "left". left_node = left_interpolation_node(new_pnt, new_x0, new_step_sizes) # Get the list of nodes that we need. needed_nodes = cross(point_list(left_node)) # Get the corresponding list of weights. weights = [] for node in needed_nodes: weights.append(u_product(new_pnt,node,new_x0,new_step_sizes)) weights = np.array(weights,dtype=float) points = np.array(needed_nodes) points,weights = reassign_weights(points,weights,max_inds) return points,weights def interpolate(axes, arr, pnt, x0, step_sizes): '''Return cubic convolution interpolation at m-coordinate point pnt. Note pnt is in the actual units of the axes. arr is the n-dimentional array that contains the known discrete values to be interpolated. x0 is a 1D m-element array that contains the first value of every dimension in actual units. step_sizes is a 1D m-element array that contains the step size between pixels in each dimension. axes is the list of axes (length m) to interpolate on. If m==n, then the estimated value of arr at point pnt is returned else, an interpolated array with shape of the axes not in 'axes' is returned.''' # Check if axes is a subset of all the axes. if len(axes) == arr.ndim: return interpolate_one_step(arr,pnt,x0,step_sizes) else: # Get the maximum possible index in each dimension in axes. max_inds = np.array(arr.shape) - 1 max_needed_inds = [] for ax in axes: max_needed_inds.append(max_inds[ax]) max_inds = np.array(max_needed_inds) # Get the points we want to look at and their associated weights. points, weights = interpolate_weights(axes, pnt, x0, step_sizes, max_inds) all_slices = [] # Since a point no longer represent one node, we have to make # the array it represents, assign the weights to each of these # arrays, then sum up these arrays for the final answer. for node in points: # Get lists of the indices of each axis not in axes. indices_lists = [] sub_arr_shape = [] for dim in range(arr.ndim): if dim not in axes: indices = range(arr.shape[dim]) indices_lists.append(indices) sub_arr_shape.append(arr.shape[dim]) # Now put in the indices of node in the proper place # based on its axis. for j in range(len(axes)): indices_lists.insert(axes[j], [node[j]]) # Get the slice of the array we want to return. This contains # the indices we need to look at, not the values yet. This also # is flattened (1D) but can be made the right shape # with sub_arr_shape. slice = cross(indices_lists) # Get the values at each index. Note we must use the "c" # business since some of our node may be out of bounds. values_slice = [] for index in slice: values_slice.append(get_value(arr,index)) # Put out slice with the proper values into the proper shape. values_slice = np.array(values_slice) values_slice.shape = tuple(sub_arr_shape) all_slices.append(values_slice) # Now that we have all the slices (and their weights from before), # Multiply by their weights and add. interpol_sum = 0. for i in range(len(all_slices)): interpol_sum += all_slices[i] * weights[i] return interpol_sum def interpolate_one_step(arr, pnt, x0, step_sizes): '''Return cubic convolution interpolation at n-coordinate point pnt. Note pnt is in the actual units of the axes. arr is the n-dimentional array that contains the known discrete values to be interpolated. x0 is a 1D n-element array that contains the first value of every dimension in actual units. step_sizes is a 1D n-element array that contains the step size between pixels in each dimension.''' # Get one of the nodes that surround the point we wish to interpolate. left_node = left_interpolation_node(pnt, x0, step_sizes) # Get the list of the 4 closest nodes (in each dimension) around the # interpolation point. needed_nodes = cross(point_list(left_node)) # Do the n-dimensional equivalent to the formula on page 1157. total = 0. for node in needed_nodes: c_node = get_value(arr,node) u_node = u_product(pnt, node, x0, step_sizes) total += c_node * u_node return total if __name__ == '__main__': # Make sure the kernel is right. x = np.arange(-3,3,0.001); ux = []; for i in x: ux.append(u(i)); plt.plot(x,ux); plt.plot(x,np.zeros(len(x)),'k'); plt.xlabel('s (pixel distance)'); plt.ylabel('kernel'); plt.title('Interpolation Kernel. Figure 1.(d)'); plt.show(); ## Some tests. print '\nx**2 with x from -5 to 5' print 'Point ..... Expected ..... Interpolation' # # 1D quadratic function. arr = np.array([25,16,9,4,1,0,1,4,9,16,25]); x0 = np.array([-5]); step_sizes = np.array([1]); # Some obvious points. pnt = np.array([0]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '0 ..... 0 ..... ' + str(ans) pnt = np.array([-1]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '-1 ..... 1 ..... ' + str(ans) pnt = np.array([3]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '3 ..... 9 ..... ' + str(ans) # Some real tests. pnt = np.array([0.5]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '0.5 ..... 0.25 ..... ' + str(ans) pnt = np.array([2.5]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '2.5 ..... 6.25 ..... ' + str(ans) pnt = np.array([-3.456]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '-3.456 ..... 11.943936 ..... ' + str(ans) pnt = np.array([4.34]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '4.34 ..... 18.8356 ..... ' + str(ans) pnt = np.array([-4.78]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '-4.78 ..... 22.8484 ..... ' + str(ans) print '\nx**3 with x from -5 to 5' print 'Point ..... Expected ..... Interpolation' # # 1D cubic function. arr = np.array([125,64,27,16,1,0,1,16,27,64,125]); x0 = np.array([-5]); step_sizes = np.array([1]); # Some obvious points. pnt = np.array([0]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '0 ..... 0 ..... ' + str(ans) pnt = np.array([-3]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '-3 ..... 27 ..... ' + str(ans) # Real tests. Watch how the approximation is not as good for non quadratics pnt = np.array([0.9]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '0.9 ..... 0.729 ..... ' + str(ans) pnt = np.array([1.17]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '1.17 ..... 1.601613 ..... ' + str(ans) pnt = np.array([3.65]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '3.65 ..... 48.627125 ..... ' + str(ans) pnt = np.array([-4.5]); ans = interpolate([0], arr, pnt, x0, step_sizes); print '-4.5 ..... 91.125 ..... ' + str(ans) def f(x,y): return x**2 + 4.*x*y + 6.*y**2 print '\nx**2 + 4xy + 6y**2 with x from -5 to 5, y from -5 to 5' print 'Point ..... Expected ..... Interpolation' # # 2D quadratic function. # mesgrid does what I want backwards. y,x = np.meshgrid(np.arange(-5,5),np.arange(-5,5)); arr = f(x,y); x0 = np.array([-5,-5]); step_sizes = np.array([1,1]); # Simple cases pnt = np.array([2,-1]); ans = interpolate([0,1], arr, pnt, x0, step_sizes); print '(2,-1) ..... 2 ..... ' + str(ans) pnt = np.array([-3,4]); ans = interpolate([0,1], arr, pnt, x0, step_sizes); print '(-3,4) ..... 57 ..... ' + str(ans) # Real tests. pnt = np.array([3.7,-2.3]); ans = interpolate([0,1], arr, pnt, x0, step_sizes); print '(3.7,-2.3) ..... 11.39 ..... ' + str(ans) pnt = np.array([4.001,3.999]); ans = interpolate([0,1], arr, pnt, x0, step_sizes); print '(4.001,3.999) ..... 175.960003 ..... ' + str(ans) pnt = np.array([4.75,-4.23]); ans = interpolate([0,1], arr, pnt, x0, step_sizes); print '(4.75,-4.23) ..... 49.5499 ..... ' + str(ans) # # Interpolation of sub axes. print '\nSame setup as before but doing interpolation on one axes.' print 'Using first axis and point 3.7' print interpolate([0],arr,np.array([3.7]),np.array([-5]),np.array([1])); print '\nCheck by doing full interpolation on points (3.7,x)' print 'where x are all the values from the second axis.' for i in range(-5,5): print interpolate([0,1],arr,np.array([3.7,i]),x0,step_sizes); # x_large = np.arange(0,1,0.01); # f_large = x_large; # f = np.arange(0,1,0.05); # plt.plot(f_large,f_large,'rx'); # plt.plot(f,f,'g+'); # plt.show();
n1 = 15 n2 = 25 print "maximum of "+ n1 +"and " + n2 +"is " +max(n1,n2) #maximum of 15 and 25 is 25 print "maximum of {0} and {1} is {2}".format(n1,n2,max(n1,n2)) #maximum of 15 and 25 is 25 print "maximum of %i and %i is %d" % (n1,n2,max(n1,n2)) #maximum of 15 and 25 is 25 """ where %i and %d are placeholders for integer and digit respectively """ """ from line 6 those {0},{1} ad {2} are called tuple indexes which should match count of the arguments to `format()`. order of those indexed can be changed""" print "maximum of {1} and {0} is {2}".format(n1,n2,max(n1,n2)) #maximum of 25 and 15 is 25
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '''对象的引用''' ''' import sys print(sys.getrefcount('aa')) print(sys.version) print(sys.version_info) import platform print(platform.version()) print(platform.python_version()) ''' '''OOP面向对象编程''' ''' class Person(): def __init__(self,name): self.Name=name print('I am Dr.%s'%self.Name) @staticmethod def show(): print('staticmethod') @classmethod def pp(cls): print(cls,'classmethod') doctor = Person('Aaron') # print(Person.__dict__) # print(doctor.__dict__) doctor.pp() Person.pp() Person.show() doctor.show() doctor.ss() ''' import time class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day # @classmethod @staticmethod def now(): # 用Date.now()的形式去产生实例,该实例用的是当前时间 t = time.localtime() # 获取结构化的时间格式 return Date(t.tm_year, t.tm_mon,t.tm_mday) # 上面的意思是 新建一个实例,实例名没有起,但是返回了,也就是,当调用 now() 时,就会得到一个新的实例 @staticmethod def tomorrow(): # 用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间 t = time.localtime(time.time() + 86400) return Date(t.tm_year, t.tm_mon, t.tm_mday) a = Date('1987', 11, 27) # 自己定义时间 b = Date.now() # 采用当前时间 c = Date.tomorrow() # 采用明天的时间 print(a.year, a.month, a.day) print(b.year, b.month, b.day) print(c.year, c.month, c.day) class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): print('name : ', self.name) print('url : ', self.__url) def __foo(self): # 私有方法 print('这是私有方法') def foo(self): # 公共方法 print('这是公共方法') self.__foo() x = Site('菜鸟教程', 'www.runoob.com') x.who() # 正常输出 x.foo() # 正常输出 # x.__foo() # 报错 ''' class A(): x=1 y=1 # def __init__(self): # self.x=2 # self.y=2 def show(self): print('X:',self.x,'Y:',self.y) # a=A() # print(a.show()) ''' '''python内部类''' ''' class outerclass: msg = "I am outer class" class interclass: msg = "I am inter class" o1 = outerclass() print(o1.msg) i1 = o1.interclass() print(i1.msg) i2 = outerclass.interclass() print(i2.msg) ''' '''python类的重载''' ''' class Person: def __init__(self, name='Bob', age=20, sex=1): self.name = name self.age = age self.sex = sex def printInfo(self): print("Person class:name:" + self.name + " age:" + str(self.age) + " sex:" + str(self.sex)) class Student(Person): def learn(self): print("Student class:learning...") class collegeStudent(Student): def printInfo(self): print("collegeStudent class:college student information...") def learn(self): print("collegeStudent class:add the transaction before calling the super method...") super().learn() print("collegeStudent class:add the transaction after calling the super method...") if __name__ == '__main__': stu = Student() stu.printInfo() stu.learn() col = collegeStudent() col.printInfo() col.learn() ''' '''类的继承''' ''' class MyType(type): def __init__(cls,*args,**kwargs): print('MyType.__init__',cls,*args,**kwargs) def __call__(cls, *args, **kwargs): print('MyType.__init__', cls, *args, **kwargs) obj=cls.__new__(cls) cls.__init__(obj,*args,**kwargs) obj.age=22 return obj def __new__(typ, *args, **kwargs): print('MyType.__new__',typ,*args,**kwargs) obj=type.__new__(typ,*args,**kwargs) return obj class Foo(object,metaclass=MyType): def __init__(self,name): self.name=name print("Foo.__init__") def __call__(self, *args, **kwargs): print("call....") f=Foo('aaron') print(f.name,f.age) ''' ''' class Animal(object): def run(self): print('Animal is running…') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running…') # if __name__ == '__main__': # cc=Cat() # cc.run() '''
#!/usr/bin/env python # -*- coding:utf-8 -*- from cryptography.fernet import Fernet class Crypto(object): def __init__(self): self.c_key = b'YrrndDCGiZjuYaIKtDq0bt1cNRqOMgtbcCGQBwtNwuo=' # 生成带密钥的实例对象 self.fernet_obj = Fernet(self.c_key) def encryption(self, text): # 调用实例对象的加密方法,对明文进行加密 encrypted_text = self.fernet_obj.encrypt(text.encode('utf-8')) return encrypted_text.decode('utf-8') def decrypt(self, encrypted_text): decrypted_text = self.fernet_obj.decrypt(encrypted_text.encode('utf-8')) return decrypted_text.decode('utf-8')
a = 1, 2.3, 4.1, "sadas" print(a) print(a[1]) for x in a: print(x) x, y = divmod(15, 2) # 商,余数 print(x, y) # 元组是不可变类型,这意味着你不能在元组内删除或添加或编辑任何值。 # a[1] = 1 # TypeError: 'tuple' object does not support item assignment # 要创建只含有一个元素的元组,在值后面跟一个逗号。 b = (12,) print(type(b)) # <class 'tuple'>
# 在 python 中 我们不需要为变量指定数据类型。所以你可以直接写出 abc = 1 ,这样变量 abc 就是整数类型。如果你写出 abc = 1.0 ,那么变量 abc 就是浮点类型。 # python 也能操作字符串,它们用单引号或双引号括起来,就像下面这样。 abc = 1 b = 1.3 c = 'a' e = "da" 的 = 'ada' h = 'dadasdasdasdsadas' print(type(e)) number = 5 # int(input("请输入一个整数:")) if number < 200: print("%d < 200" % number) else: print("%d >= 200" % number) inrate = 1 value = 12.13545 # 字符串格式化,大括号和其中的字符会被替换成传入 str.format() 的参数,也即 year 和 value。其中 {:.2f} 的意思是替换为 2 位精度的浮点数。 print("year {} haha {:.2f}".format(inrate, value)) # 更多字符串格式化内容:https://docs.python.org/3/library/string.html#formatstrings # 求n个数的平均值 sum = 0 for num in range(1, 100): sum += num print("{:.2f}".format(sum / 100)) # 温度转换 fahrenheit = 0 while fahrenheit <= 250: celsius = (fahrenheit - 32) / 1.8 # 转换为摄氏度 # {:5d} 的意思是替换为 5 个字符宽度的整数,宽度不足则使用空格填充。 print("{:5d} {:7.2f}".format(fahrenheit, celsius)) fahrenheit += 25 # 单行定义多个变量和赋值 aa, bb = 12, 45 print(aa) print(bb) # 交换2个数的值 aa, bb = bb, aa print(aa) print(bb) # 元组 # 元组封装 data = {"aaaaa", "bbbbb", "ccccc"} # 元组拆封 这里拆封的时候,赋值是无序的 比如name可能是aaaaa,也可能是bbbbb,也可能是ccccc name, coun, langt = data print(name) print(coun) print(langt)
import logging ''' try: r = 10/int('a') print('result:',r) #上面有错,这句不会执行 except ValueError as e: print('ValueError:',e) logging.exception(e) except ZeroDivisionError as e: print('ZeroDivisionError:',e) else: print('no error') # 此外,如果没有错误发生,可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句: finally: # finally模块和java一样,不管是否有错误发生,都会被执行 print('finally...') print('END') ''' # 常见错误类型:https://docs.python.org/3/library/exceptions.html#exception-hierarchy # 所有错误类型都继承自BaseException # 出错的时候,一定要分析错误的调用栈信息,才能定位错误的位置。 # 如果不捕获错误,自然可以让Python解释器来打印出错误堆栈,但程序也被结束了。既然我们能捕获错误,就可以把错误堆栈打印出来,然后分析错误原因,同时,让程序继续执行下去。 # Python内置的logging模块可以非常容易地记录错误信息: # 因为错误是class,捕获一个错误就是捕获到该class的一个实例。因此,错误并不是凭空产生的,而是有意创建并抛出的。Python的内置函数会抛出很多类型的错误,我们自己编写的函数也可以抛出错误。 # 如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例: class FooError(ValueError): pass def foo(s): n = int(s) if n==0: # raise FooError('invalid value: %s' % s) raise ValueError('invalid value: %s' % s) return 10/n #foo('0') # raise语句如果不带参数,就会把当前错误原样抛出。此外,在except中raise一个Error,还可以把一种类型的错误转化成另一种类型: ''' try: 10 / 0 except ZeroDivisionError: raise ValueError('input error!') ''' # 练习 from functools import reduce def str2num(s): return int(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 76') print('99 + 88 + 76 =', r) main() ''' Python内置的try...except...finally用来处理错误十分方便。出错时,会分析错误信息并定位错误发生的代码位置才是最关键的。 程序也可以主动抛出错误,让调用者来处理相应的错误。但是,应该在文档中写清楚可能会抛出哪些错误,以及错误产生的原因。 '''
# 只要有任意一个操作数是浮点数,结果就会是浮点数。 a = 1 + 2 b = 1.0 + a print(type(a)) # <class 'int'> print(type(b)) # <class 'float'> # 进行除法运算时若是除不尽,结果将会是小数 这很自然?自然个毛啊,C语言可不是这样的 c = 14 / 3 print(c) # 4.666666666666667 # 整除 d = 14 // 3 print(d) # 4 # 取余 % # 小栗子 days = 265 ''' # divmod(num1, num2) 返回一个元组,这个元组包含两个值,第一个是 num1 和 num2 相整除得到的值,第二个是 num1 和 num2 求余得到的值,然后我们用 * 运算符拆封这个元组,得到这两个值。 ''' print("{}月 {}日".format(*divmod(days, 30))) print(divmod(days, 30)) # (8, 25) # 对于逻辑 与,或,非,我们使用 and,or,not 这几个关键字。 # 类型转换 ''' 类型转换函数 转换路径 float(string) 字符串 -> 浮点值 int(string) 字符串 -> 整数值 str(integer) 整数值 -> 字符串 str(float) 浮点值 -> 字符串 ''' # 小栗子 # 这个程序计算数列 1/x+1/(x+1)+1/(x+2)+ ... +1/n,我们设 x = 1,n = 10。 sum1 = 0 for x in range(1,10): sum1 += 1/x print(x) # 这里出了for循环也还可以访问x print(sum1) # 另外 Python 是强类型语言,所以必要的时候需要手动进行类型转换。
# ASCII编码是1个字节,而Unicode编码通常是2个字节 # 本着节约的精神,又出现了把Unicode编码转化为“可变长编码”的UTF-8编码。UTF-8编码把一个Unicode字符根据不同的数字大小编码成1-6个字节,常用的英文字母被编码成1个字节,汉字通常是3个字节,只有很生僻的字符才会被编码成4-6个字节。如果你要传输的文本包含大量英文字符,用UTF-8编码就能节省空间: a = 'aaa' # 字符串 str Unicode编码 a = b'aaa' # bytes 每个字符都只占用一个字节 # 如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法: b'asv'.decode('utf-8') print(b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')) #中 # 字符串长度 a = 'abc' print(len(a)) # 格式化 占位符 和C语言一样, # %d %f %s %x(16进制) # %s可以把任何数据转换为字符串 print('Hi, %s, you have $%d. 我可以借$%.2f吗?' % ('小明', 100, 1.3)) # Hi, 小明, you have $100. 我可以借$1.30吗? print('%2d %02d' % (2, 3)) # 2 03 # format格式化 保留小数时是四舍五入 print('Hello ,{0} 成绩提升了{1:.1f}'.format('小明',15.56)) #Hello ,小明 成绩提升了15.6 print('%.20f' % 3.1415926) ''' Python 3的字符串使用Unicode,直接支持多语言。 当str和bytes互相转换时,需要指定编码。最常用的编码是UTF-8。Python当然也支持其他编码方式,比如把Unicode编码成GB2312: >>> '中文'.encode('gb2312') b'\xd6\xd0\xce\xc4' 但这种方式纯属自找麻烦,如果没有特殊业务要求,请牢记仅使用UTF-8编码。 格式化字符串的时候,可以用Python的交互式环境测试,方便快捷。 '''
# 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问 class Student(object): def __init__(self, name, score): self._name = name self.__score = score # 这个self参数必须有,调用时不用传 def print_score(self): print("%s: %s" % (self.__name, self.__score)) def get_name(self): return self.__name def get_score(self): return self.__score def set_name(self, name): self.__name = name def set_score(self,score): if 0<=score<=100: self.__score = score else: raise ValueError('bad score') self.__score = score std = Student('xfhy', 100) # print(std.__name) error 无法访问 ''' py中方法名是_分隔单词,也有getter和setter嘛 哈哈 ''' std.set_name('xfhy2') std.set_score(99) print(std.get_name(),std.get_score()) # 但是强烈建议你不要这么干,因为不同版本的Python解释器可能会把__name改成不同的变量名。 print(std._Student__name) # 居然可以通过这种方式访问私有属性 666 ''' 最后注意下面的这种错误写法: >>> bart = Student('Bart Simpson', 59) >>> bart.get_name() 'Bart Simpson' >>> bart.__name = 'New Name' # 设置__name变量! >>> bart.__name 'New Name' 表面上看,外部代码“成功”地设置了__name变量,但实际上这个__name变量和class内部的__name变量不是一个变量!内部的__name变量已经被Python解释器自动改成了_Student__name,而外部代码给bart新增了一个__name变量。不信试试: >>> bart.get_name() # get_name()内部返回self.__name 'Bart Simpson' ''' class Student2(object): def __init__(self, name, gender): self.__name = name self.__gender = gender def get_gender(self): return self.__gender def set_gender(self,gender): if gender!='male' and gender!='female': raise ValueError('性别错误') self.__gender = gender bart = Student2('Bart', 'male') if bart.get_gender() != 'male': print('测试失败!') else: bart.set_gender('female') if bart.get_gender() != 'female': print('测试失败!') else: print('测试成功!')
# for..in 循环 names = ['dada', '小米', '小明'] for name in names: print(name) # 计算1+2+3+4 # 方式1 sum = 0 for x in [1, 2, 3, 4]: sum += x print(sum) # 方式2 # range()函数,可以生成一个整数序列,再通过list()函数可以转换为list。比如range(5)生成的序列是从0开始小于5的整数(0,1,2,3,4): sum = 0 for x in range(101): sum += x print(sum) # while # 计算100以内所有奇数之和 sum = 0 x = 0 while x <= 100: if x % 2 != 0: sum += x x += 1 print(sum) L = ['Bart', 'Lisa', 'Adam'] for name in L: print("hello,", name) # break n=1 while n<=100: print(n) if n>10: break n+=1 # continue 和java一样的 for i in [1,2,3]: if i==2: continue print(i)
''' Becoming a black belt with dictionaries ''' from pprint import pprint # How to make a dictionary ######################### d = {} # dictionary literal d = dict() # dict contructor # Five ways to prepopulate a dictionary ############# d = { # dictionary literal 'raymond': 'red', 'rachel': 'blue', 'matthew': 'yellow', } d = dict(raymond='red', rachel='blue', matthew='yellow') lot = [('raymond', 'red'), ('rachel', 'blue')] d = dict(lot) names = 'raymond rachel matthew'.split() colors = 'red blue yellow'.split() d = dict(zip(names, colors)) d = dict.fromkeys(names, 0) # How to override the just the behavior for missing keys ### # d[k] --> d.__getitem__(k) # return v if k is found # if not found, it calls d.__missing__(k) # |--> __missing__(k) raises KeyError class AngryDict(dict): def __missing__(self, key): print 'I am so mad!' print '%r is missing!' % key raise KeyError(key) class ZeroDict(dict): def __missing__(self, key): return 0 colors = 'red green red blue red green'.split() d = ZeroDict() for color in colors: d[color] += 1 # How to group data in python ########################## # mapping group_key to a list of things in the group class ListDict(dict): def __missing__(self, key): self[key] = [] return self[key] names = 'davin raymond rachel matthew randal darron mary ' \ 'susan billy sherry beatrice bill marty betty sheldon'.split() # Group these names by their first letter d = ListDict() for name in names: key = name[0] d[key].append(name) pprint(d); print '-' * 20 + '\n' * 2 # Group these names by their last letter d = ListDict() for name in names: key = name[-1] d[key].append(name) pprint(d); print '-' * 20 + '\n' * 2 # Group these names by the length of their name d = ListDict() for name in names: key = len(name) d[key].append(name) pprint(d); print '-' * 20 + '\n' * 2 # Group these names by the number of vowels in the name # a e i o u y d = ListDict() for name in names: key = sum(name.count(v) for v in 'aeiouy') d[key].append(name) pprint(d); print '-' * 20 + '\n' * 2 ################################################## # Show how to do partial substitution in templates class FormatDict(dict): def __missing__(self, key): return '%%(%s)s' % key d = FormatDict(old=10) s = 'The answer is %(new)s today but was %(old)s yesterday' % d print s print s % dict(new=20) ################################################## # Show how to chain dictionaries together class ChainDict(dict): def __init__(self, fallback, **kwds): self.fallback = fallback self.update(kwds) def __missing__(self, key): return self.fallback[key] window_defaults = dict(foreground='cyan', background='white', border=2, width=200) text_window = ChainDict(window_defaults, foreground='blue', border=4) warning_window = ChainDict(window_defaults, background = 'red', border = 10, width = 100) pprint(d); print '-' * 20 + '\n' * 2 ##################################################### # How you could have created the __missing__ yourself class MissingDict(dict): '''What if you had an old version of Python without __missing__? Answer: Build any behavior you want and inherit from it ''' def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.__missing__(key) def __missing__(self, key): raise KeyError(key) class ZeroDict(MissingDict): def __missing__(self, key): return 0 d = ZeroDict() print d['roger']
n_fizz = int(input("Hello!\nPlease input fizz number: ")) n_buzz = int(input("Hello!\nPlease input buzz number: ")) n_main_number = int(input("Hello!\nPlease input main number: ")) main_str="" i=1 while i<=n_main_number: if i % n_fizz == 0 and i % n_buzz == 0: main_str+='FB' elif i % n_fizz == 0: main_str+='F' elif i % n_buzz == 0: main_str+='B' else: main_str+=str(i) main_str+=" " i+=1 print(main_str)
#coding=utf-8 class InventoryItem(object): def __init__(self, title, description, price, store_id): self.title = title self.description = description self.price = price self.store_id = store_id def __str__(self): return self.title def __eq__(self, other): if self.store_id == other.store_id: return True else: return False def change_description(self, description = ""): if not description: description = raw_input("Please give me a description: ") self.description = description def change_price(self, price = -1): while price<0: price = raw_input("Please give me the new price [x.xx]: ") try: price = float(price) break except: print "I'm sorry. but {} is not valid.".format(price) self.price = price def change_title(self, title = ""): if not title: title = raw_input("Please give me a new title:") self.title = title class Software(InventoryItem): def __init__(self, title, description, price, store_id, os, ESRB): super(Software,self).__init__(title = title, description = description, price = price, store_id = store_id) self.os = os self.ESRB = ESRB def __str__(self): software_info = "{} for {} with {}".format(self.title, self.os, self.ESRB) return software_info def __eq__(self, other): if self.title == other.title and self.os == other.os and self.ESRB == other.ESRB: return True else: return False def change_os(self,os = ""): if not os: os = raw_input("Please give me the osinfo:") self.os = os def change_ESRB(self,ESRB = ""): if not ESRB: ESRB = raw_input("Please give the ESRB:") self.ESRB = ESRB def main(): pycharm = Software(title = "pycharm", description="a python IDE", price=5, store_id= "55555555", os="windows", ESRB="A") pycharm2 = Software(title="pycharm", description="a python IDE", price=20, store_id="1111111", os="windows",ESRB="A") pyIDE = Software(title = "pycharm", description="a python IDE", price=20, store_id= "6666666", os="linux", ESRB="B") print pycharm print pycharm2 print pyIDE print pycharm == pycharm2 print pycharm == pyIDE pycharm2.change_os() print pycharm2 pyIDE.change_ESRB() print pyIDE if __name__ == "__main__": main()
#!/usr/bin/env python ''' Solution file for PA03 Maze. Uses longest distance algorithm. ''' import rospy from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan # constants SAFE_DISTANCE = 0.3 # meters MAX_RANGE = 10 # meters INDEX_THRESHOLD = 10 # degrees MOVE = True # bool # get scan values of 180 degree cone in front of the robot # add comment def range_ahead(ranges): return list(reversed(ranges[0:22])) + list(reversed(ranges[336:359])) # scan callback to update longest/shortest range and the index (angle) # of the longest range in front of the robot def scan_cb(msg): global driving_forward; global max_range_index; global remove_inf_ranges # use forward facing scan to check for collisions ranges_ahead = range_ahead(list(msg.ranges)) # get max range index as the new direction max_range = max(msg.ranges) max_range_index = msg.ranges.index(max_range) # set 0 ranges to max range # comment lambda remove_inf_ranges = map(lambda x: MAX_RANGE if x == 0 else x, ranges_ahead) # check if we are facing in the direction of the maximum free range def facing(): return max_range_index < INDEX_THRESHOLD - 1 or max_range_index > 360 - INDEX_THRESHOLD - 1 # subscriber/publisher declarations scan_sub = rospy.Subscriber('scan', LaserScan, scan_cb) cmd_vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1) rospy.init_node('maze_runner') # starting movement parameters driving_forward = False remove_inf_ranges = [] max_range_index = 0 # update at 10 hz rate = rospy.Rate(10) # control loop while not rospy.is_shutdown(): # drive forward or turn accordingly twist = Twist() if driving_forward: # check if safe to move forward # add comment here twist.linear.x = 0.2 if remove_inf_ranges: driving_forward = min(remove_inf_ranges) > SAFE_DISTANCE else: # keep spinning until facing correct direction twist.angular.z = 1.0 driving_forward = facing() # publish at 10z if MOVE: cmd_vel_pub.publish(twist) rate.sleep()
def minDeletionSize(A): """ :type A: List[str] :rtype: int Input: ["cba","daf","ghi"] Output: 1 Explanation: After choosing D = {1}, each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order. If we chose D = {}, then a column ["b","a","h"] would not be in non-decreasing sorted order. """ if len(A) == 0: return 0 columns = len(A[0]) min_del = 0 #锁定列, 比较每行字母的大小 for column_index in range(columns): for row_index in range(len(A)-1): if A[row_index][column_index] > A[row_index+1][column_index]: min_del += 1 break return min_del if __name__== '__main__': lst = ["cba","daf","ghi"] print(minDeletionSize(lst))
#!/usr/bin/env python class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root: root.right, root.left = self.invertTree(root.left), self.invertTree(root.right) return root if __name__ == '__main__': root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.left = TreeNode(6) root.right.right = TreeNode(7) print ("before:" ,root.val, root.left.val, root.right.val, root.left.left.val, root.left.right.val, root.right.left.val, root.right.right.val) root.invertTree(root) print ("after :" ,root.val,root.left.val,root.right.val,root.left.left.val,root.left.right.val,root.right.left.val,root.right.right.val)
#!/usr/bin/env python def Unique_Email_Add(email_list): unique_email = set() for str in email_list: host, _, domain = str.partition('@') if '+' in host: host = host[:host.index('+')] unique_email.add(host.replace(".","") + '@' + domain) return (unique_email) if __name__ == "__main__": email = ["aaa@163.com","aaa.@163.com","aaa+@163.com","aaa+aa@126.com"] print(Unique_Email_Add(email))
#!/usr/bin/env python import random import time def bubble_sort(listarry): for i in range(len(listarry)): for j in range(i, len(listarry)): if listarry[i] > listarry[j]: listarry[i], listarry[j] = listarry[j], listarry[i] return listarry def select_sort(listarry): for i in range(len(listarry)): temp = i for j in range(i+1, len(listarry)): if listarry[temp] > listarry[j]: temp = j listarry[i], listarry[temp] = listarry[temp], listarry[i] return listarry def quick_sort(listarry): if len(listarry) == 0 or len(listarry) == 1: return listarry temp = listarry[0] left = [i for i in listarry if i < temp] right = [j for j in listarry if j > temp] return quick_sort(left) + [temp] + quick_sort(right) def insert_sort(listarry): for i in range(len(listarry)): j = i temp = listarry[i] while j > 0 and listarry[j-1] > temp: listarry[j] = listarry[j - 1] j -= 1 listarry[j] = temp return listarry def insert_sort2(lst): for i in range(len(lst)): index = i value = lst[i] #如果前面一个数比这个大 索引就减一 while lst[index-1] > value and index > 0: index -=1 res = lst.pop(i) lst.insert(index, res) return lst def merge(left, right): i = 0 j = 0 newlst = [] while i <len(left) and j < len(right): if left[i] > right[j]: newlst.append(right[j]) j+=1 else: newlst.append(left[i]) i+=1 if i==len(left): newlst.extend(right[j:]) elif j == len(right): newlst.extend(left[i:]) return newlst def merge_sort(lst): if len(lst) <= 1: return lst mid = len(lst)//2 left = merge_sort(lst[:mid]) right = merge_sort(lst[mid:]) newlst = merge(left, right) return newlst if __name__ == '__main__': arry = [] i=0 while i<20000: i+=1 arry.append(random.randint(-9999,9999)) start = time.clock() #arry = [-1, 2, 41,-3,-10,-199 ,199,4, 5, 7, 6] #print(insert_sort(arry)) print(quick_sort(arry)) #print(select_sort(arry)) #print(bubble_sort(arry)) #print(merge_sort(arry)) #print(insert_sort2(arry)) cost = time.clock()-start print(cost)
import sqlite3 connection = sqlite3.connect('banter.db') cursor = connection.cursor() #sql = """CREATE TABLE Userdetails (id INTEGER PRIMARY KEY AUTOINCREMENT,fname TEXT,lname TEXT,uname TEXT UNIQUE,passwd TEXT )""" #sql = "INSERT INTO Userdetails (fname,lname,uname,passwd ) VALUES ('vijesh', 'v','vijay','catfoss')" #sql = "INSERT INTO Settings (setting, value) VALUES ('display_molecule_name', 'True')" #sql = "UPDATE Userdetails SET lanme='vv' WHERE fanme='vijesh'" #sql = "DELETE FROM Userdetails WHERE id=1" sql = "SELECT * FROM Userdetails" cursor.execute(sql) #print cursor.lastrowid # get the autoincremented id from the previously inserted record data = cursor.fetchall() print data connection.commit() connection.close()
import numpy as np import matplotlib.pyplot as plt def read_report_data(csv): train = [] validation = [] with open(csv, 'r') as f: next(f) # skip csv header title(step,loss,acc) last = -1 for line in f: step, loss, acc = line.rstrip('\n').split(',') step = int(step) loss = float(loss) acc = float(acc) row = [step, loss, acc] if step == last: validation.append(row) else: train.append(row) last = step return train, validation def extract_data(data): data = np.array(data) step = data[:, 0] loss = data[:, 1] acc = data[:, 2] return step, loss, acc def test_extract_data(): data = [[1, 2, 3], [4, 5, 6]] step, loss, acc = extract_data(data) print step print loss print acc def plot_demo(): x = np.arange(0, 5, 0.1); y = np.sin(x) plt.plot(x, y) plt.show() def subplot_demo(): # plot a line, implicitly creating a subplot(111) plt.plot([1,2,3]) # now create a subplot which represents the top plot of a grid # with 2 rows and 1 column. Since this subplot will overlap the # first, the plot (and its axes) previously created, will be removed plt.subplot(211) plt.title('s1') plt.plot(range(12)) plt.subplot(212, axisbg='y') # creates 2nd subplot with yellow background plt.title('s2') plt.show() if __name__ == '__main__': # subplot_demo() train, validation = read_report_data('mnist_alexnet_train_report.csv') train_step, train_loss, train_acc = extract_data(train) plt.subplot(221) plt.title('loss') plt.xlabel('step') plt.ylabel('loss') plt.plot(train_step, train_loss) plt.subplot(222) plt.title('acc') plt.xlabel('step') plt.ylabel('acc') plt.plot(train_step, train_acc) step, loss, acc = extract_data(validation) plt.subplot(223) plt.title('loss') plt.xlabel('step') plt.ylabel('loss') plt.plot(step, loss) plt.subplot(224) plt.title('acc') plt.xlabel('step') plt.ylabel('acc') plt.plot(step, acc) plt.show()
import function x=input("enter the numer") y=input("enter the numer") a=function.add(int(x),int(y)) print(a)
from . import Arm from . import Optimizer class Instruction: CNTR = 0 def __init__(self, optimizer: Optimizer, arm: Arm, x1: int, y1: int, x2: int, y2: int): self.O = optimizer self.No = Instruction.CNTR self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.arm = arm if abs(x1-x2) > 1 or abs(y1-y2) > 1: print("ERROR: instructions unclear :) diff > 1 (%d,%d,%d,%d)" % (x1,x2,y1,y2)) def __gt__(self, other): return self.No > other.No def __repr__(self): return str(self) def __str__(self): return self.__move__() def __move__(self): if self.x1-self.x2 > 0: return "L" elif self.x1-self.x2 < 0: return "R" elif self.y1-self.y2 > 0: return "D" elif self.y1-self.y2 < 0: return "U" else: return "W"
toni = 100 rani = 87 jaka = 90 diah = 69 print("nilai toni = "+str(toni)+ " dan nilai rani = " +str(rani)+ \ " dan nilai jaka = " +str(jaka)+ " dan nilai diah = "+str(diah)) print("nilai toni = {} dan nilai rani = {} dan nilai jaka = {} dan nilai diah = {}" \ .format(toni, rani, jaka, diah)) print("nilai toni = "+str(toni), end='') print(" dan nilai rani = "+str(rani), end='') print(" dan nilai jaka = "+str(jaka), end='') print(" dan nilai diah = "+str(diah))
#!/usr/bin/env python3 # simulates an enigma machine with 1 rotor and 1 plug in a plugboard # known: if x = 'axe' and k = (3, 'a', 'f') then ans = 'UOX'. rotor = [6, 14, 7, 8, 12, 17, 9, 13, 20, 23, 16, 21, 25, 15, 24, 18, 0, 19, 5, 4, 22, 2, 10, 1, 11, 3] def main(): # parameters: s = "axed" key = [3, 'a', 'f'] # convert key to all ints key[1] = ord(key[1]) - 97 key[2] = ord(key[2]) - 97 # encrypt and then decrypt s ans = encrypt(s, key) print(ans) ans = decrypt(ans, key) print(ans) # TODO: do this by using the fact that "weather" # is known to be in it print("\nPart1:") s = "PVGEQDETJWZBESHP" hack(s) print("\nPart2:") s = "ERXYTXLKWLBCVIFUPJRZLHNQHTCUORTXRBZHNGD" hack(s) # return new letter after running through plugboard def plug(x, key): if x == key[1]: return key[2] if x == key[2]: return key[1] return x # encrypt string with key def encrypt(s, key): s = s.lower() i = 0 ans = "" for x in s: x = ord(x) - 97 # convert to int val = (plug(x, key) + key[0] + i) % 26 val = rotor[val] ans += chr(plug(val, key) + 97) i = i+1 return ans.upper() # decrypt string with key def decrypt(s, key): s = s.lower() ans = "" # traverse string backwards for i in range(len(s)-1, -1, -1): val = ord(s[i]) - 97 val = plug(val, key) for k in range(0, len(rotor)): if val == rotor[k]: val = k break # find param for plug that gives leads to val val = (val - key[0] - i) % 26 val = plug(val, key) ans += chr(val + 97) return ans.upper()[::-1] # reverse string # attempt to decrypt a string # try all possible keys, look for an output that looks english def hack(s): s = s.lower() best = [0, [0,0,2]] key = [0, 0, 2] while key != [0, 0, 1]: guess = decrypt(s, key) m = M(guess) if m > best[0]: best[0] = m best[1] = list(key) key = advanceKey(key) print("best guess: key=" + str(best[1]) + ", m=" + str(best[0])) print(decrypt(s, best[1])) # estimate probability of the string being english # TODO: make sure this is implemented correctly def M(s): s = s.lower() p = [.082,.015,.028,.043,.127,.022,.02,.061,.07,.002,.008,.04, .024,.067,.075,.019,.001,.06,.063,.091,.028,.01,.023, .001,.02,.001] count = [0] * 26 # number of occurences of each letter for c in s: count[ord(c) - 97] += 1 sum = 0 for i in range(0, 26): sum += p[i] * count[i] return sum / len(s) # advance a key (where a key is a set of 3 integers < 26) # TODO: this could be more efficient the last two numbers # represent a COMBINATION of letters not a PERMUTATION def advanceKey(key, pos=2): key[pos] += 1 if key[pos] == 26: key[pos] = 0 return advanceKey(key, pos-1) # last 2 values shouldn't be equal (can't plug letter into itself) if key[1] == key[2]: return advanceKey(key) return key if __name__ == "__main__": main()
# Define our variables Wage = float(input("What is your Hourly Wage?")) Hours = int(input("Regularly, how many Hours do you receive in a week?")) Overtime = float(input("Do you have any Overtime Hours?")) Pay = float(Wage * Hours) Overpay = float(Overtime * (Wage * 1.5)) Total = (round(Overpay + Pay, 2)) # Have program print total as employee's weekly pay print ("Your weekly pay is: $", Total)
#名字管理器 #打印功能 print("="*50) print('Name System') print('1: add new name') print('2: delet name') print('3: revise name') print('4: search name') print('5: quite') print("="*50) name = [] #獲取用戶的選擇 #根據選擇,執行相印功能 while True: num = int(input("please enter the option: ")) if num == 1: new_name = input("enter the name: ") name.append(new_name) print(name) elif num == 2: de_name = input("enter the name you want to remove: ") name.remove(de_name) print(name) elif num == 3: a = input("enter the name you want to change: ") if a in name: b = input("enter the correct name: ") loc = name.index(a) name[loc] = b print(name) else: print("not in list") elif num == 4: find_name = input("enter the name you want to find: ") if find_name in name: print("in list") else: print("not in list") elif num == 5: break else: print("wrong option, enter again")
# not allowed to import any libraries so can't use time # can't even import regex, god damn # helper fucntion to split out time and duration into hours and minutes def stringloop(string): # split out time into 3 vars. can't use regex so looping through chars loopstage = "hour" hour = "" minute = "" ampm = "" for char in string: if loopstage == "hour": try: int(char) hour += char except: loopstage = "minute" elif loopstage == "minute": try: int(char) minute += char except: loopstage = "ampm" elif loopstage == "ampm": if char >= "A" and char <= "z": ampm += char # conver to number for later calcs hour = int(hour) minute = int(minute) # convert hours to 24 hours based on ampm if ampm.lower() == "pm": hour += 12 return hour, minute # function to add time def add_time(start, duration, weekday=None): hour, minute = stringloop(start) durhour, durmin = stringloop(duration) # calc number of days in duration... can't import math days = durhour / 24 # can't floor so reuse stringloop, first element will be the floored number days = stringloop(str(days))[0] # subtract the number of days from the duration hour durhour -= 24 * days # add minutes minute += durmin # if minutes over 60 then add to hour if minute >= 60: hour += 1 minute -= 60 # add hours together hour += durhour # if hours are over 24 then add to days if hour >= 24: days += 1 hour -= 24 # now convert back to ampm if hour >= 12: ampm = "PM" hour -= 12 else: ampm = "AM" # now if hours are 0 we want to show 12am, convert to string here too if hour == 0: hour = "12" else: hour = str(hour) # if minutes are less than 10 we need to add a leading zero if minute < 10: minute = "0"+str(minute) else: minute = str(minute) # format time as a string new_time = hour + ":" + minute + " " + ampm # if weekday is not None then we need to figure out which weekday if weekday is not None: # weekday dict weekdict = { "monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3, "friday": 4, "saturday": 5, "sunday": 6 } # swap dict around so we can lookup the number weekdictlookup = {} weeklist = sorted([(v, k) for k, v in weekdict.items()]) for entry in weeklist: weekdictlookup[entry[0]] = entry[1] # look up weekday in list weeknum = weekdict[weekday.lower()] # add number of days calculated earlier weeknum += days # divide by 7 so we can look back up in list if weeknum >= 7: tempnum = weeknum/7 # reuse strinloop to floor the week number tempnum = stringloop(str(tempnum))[0] weeknum -= tempnum*7 weekday = weekdictlookup[weeknum] # now we have the new weekday we need to re-capitalise weekday = weekday[0].upper() + weekday[1:] # and then append to the new_time string new_time += ", " + weekday # now add the number of days past if days == 1: new_time += " (next day)" elif days > 1: new_time += " ("+str(days)+" days later)" return new_time
mystring="hello" #string myfloat=10 #floating point myint=20 #integer print #Printing on Screen print mystring print myfloat print myint print print mystring, "I am,", myfloat," I will be", myint, "in ten years." print #Mathematical operations print (4+8)*19/6 print 65*9/3 print 89*1999/9 print 500/8*2 print 88817/1919*5
import unittest # function to return the factorial of a number # Add comments def factorial(num): ans = 1 if num < 0: return None elif num < 2: return ans else: for i in range(1, num + 1): ans = ans * i return ans # function to check if the input year is a leap year or not def check_leap_year(year): isLeap = False if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: isLeap = True else: isLeap = True return isLeap print("factorial(0): {}".format(factorial(0))) print("factorial(1): {}".format(factorial(1))) print("factorial(5): {}".format(factorial(5))) print("factorial(-3): {}".format(factorial(-3))) print("check_leap_year(2000): {}".format(check_leap_year(2000))) print("check_leap_year(1990): {}".format(check_leap_year(1990))) print("check_leap_year(2012): {}".format(check_leap_year(2012))) print("check_leap_year(2100): {}".format(check_leap_year(2100))) ##### test cases ##### class TestFactorial(unittest.TestCase): def test_int_accept(self): self.assertTrue(type(factorial(1)) == type(1)) def test_return_fact1(self): self.assertEqual(factorial(0), 1) def test_return_fact2(self): self.assertEqual(factorial(1), 1) def test_return_fact3(self): self.assertEqual(factorial(5), 120) def test_return_fact4(self): self.assertEqual(factorial(-3), None) class TestLeapYear(unittest.TestCase): def test_year1(self): self.assertTrue(check_leap_year(2000) == True) def test_year2(self): self.assertTrue(check_leap_year(1990) == False) def test_year3(self): self.assertEqual(check_leap_year(2012) == True) def test_year4(self): self.assertTrue(check_leap_year(2100) == False) unittest.main(verbosity=2)
""" CSC464 Assignment 1 Producer Consumer Classical Problem in Python Thor Reite V00809409 10/11/2018 """ import threading pc_cond = threading.Condition() item_buffer = 0; ##tracks items in buffer def main(): producer().start() consumer().start() producer().join() consumer().join() exit(1) class producer(threading.Thread): def run(self): for i in range(1000): pc_cond.acquire() ##lock item item_buffer while item_buffer: pc_cond.wait() #wait until buffer empties global item_buffer item_buffer = i pc_cond.notify() pc_cond.release() class consumer(threading.Thread): def run(self): for i in range(1000): pc_cond.acquire() ##lock item item_buffer while item_buffer is 0: pc_cond.wait() #wait until buffer has item global item_buffer item_buffer = 0 pc_cond.notify() pc_cond.release() if __name__ == '__main__': main()
max_palindrome = 0 for i in range(100, 999): for j in range(i, 999): mult = i * j mult_str = str(mult) if mult_str == mult_str[::-1] and int(mult) > max_palindrome: max_palindrome = mult print (max_palindrome) print(max([i * j for i in range(100, 999) for j in range(i, 999) if str(i*j) == str(i*j)[::-1]]))
import unittest from pairing import Pairing from result import Result #It's an open question whether we want a separate TestCase class for each Guidewords class we are testing. Result and pairing can be tested in the same test case, since Result inherits from pairing and doesn't override anything. But should tournament, player, and result all be in the same test case? Maybe. What about the various pairings functions. class GuidewordsResultsTestCase(unittest.TestCase): def setUp(self): global resultA, resultB, resultC resultA = Result(3, 3, 375, 4, 275) resultB = Result(3, 5, 375, 6, 475) resultC = Result(3, 7, 400, 8, 400) def tearDown(self): pass def test_winner_function(self): self.assertTrue(resultA.winner() == 3) self.assertTrue(resultB.winner() == 6) self.assertTrue(resultC.winner() == None) def test_is_p1_function(self): self.assertTrue(resultA.is_p1(3)) self.assertFalse(resultA.is_p1(4)) with self.assertRaises(KeyError): resultA.is_p1(5) def test_other_player_function(self): self.assertTrue(resultA.other_player(3) == 4) self.assertTrue(resultA.other_player(4) == 3) with self.assertRaises(KeyError): resultA.other_player(5) #Shouldn't need a 'test_is_p1_function', because Result will end up inheriting from Pairing. If this ends up changing, perhaps we should make a test here. def test_spread_function(self): self.assertTrue(resultA.spread() == 100) self.assertTrue(resultB.spread() == -100) self.assertTrue(resultC.spread() == 0) if __name__ == '__main__': unittest.main() """def run_player_tests(): all_tests_passed = True amalan = Player("Amalan") noah = Player("Noah", 1, [2, 4, 630, 730]) amalan.enter_round([3, 3, 400, 450]) amalan.enter_round([1, 5, 340,230]) noah.enter_round([1, 6, 440, 440]) noah.enter_round([3, 3, 530, 8]) amalan.enter_round([2, 2, 430, 430]) if amalan.name() != "Amalan": all_tests_passed = False if noah.name() != "Noah": if amalan.seed() != 0: if noah.seed() != 0: if amalan.results() != [[1,5,340,230],[2,2,430,430],[3,3,400,450]]: if noah.results() != [[1,6,440,440],[2,4,630,730], """
a=int(input("enter number :")) b=int(input("enter number :")) c=(input("enter name :")) d=[a,b,c] print(d) for h in d: print("the values are :",h)
class cal4: def setdata(self,num): self.num = radius def display(self): return num**2 num = int(input("enter the number : ")) obj.cal4() obj.setdata(num) square = obj.display() print(f'square of {num} is {square}.')
import sqlite3 import pprint import sys from knn_utils import * def manhattan_distance(x1,x2): ''' Returns a tuple of the Manhattan distance between a pair of attribute vectors and a tuple of the three attributes on which the two vectors are the most similar. ''' relevant_attributes = [] if len(x1) != len(x2): return -1 distance = 0 for i in xrange(len(x1)): distance += abs(x1[i] - x2[i]) if x1[i] != 0 or x2[i] != 0: if len(relevant_attributes) < 3: relevant_attributes.append((i, abs(x1[i] - x2[i]))) relevant_attributes.sort(key=lambda x: x[1]) else: if abs(x1[i] - x2[i]) < relevant_attributes[2][1]: relevant_attributes[2] = (i, abs(x1[i] - x2[i])) relevant_attributes.sort(key=lambda x: x[1]) return (distance, tuple(relevant_attributes)) def nearest_neighbors(k, query, dataset): ''' Returns a list of the k most similar beers to the input beer in terms of Manhattan distance. ''' neighbors = [] for example in dataset: vector = dataset[example]['attributes'] dist, relevant_attributes = manhattan_distance(vector, query) if len(neighbors) < k: neighbors.append((example, dist, relevant_attributes)) neighbors.sort(key=lambda x: x[1]) else: if dist < neighbors[k-1][1] and dist != 0: neighbors[k-1] = (example, dist, relevant_attributes) neighbors.sort(key=lambda x: x[1]) return neighbors def important_attributes(vector): """ Given a vector representing a beer's attributes, returns a list of the most relevant ones. """ atts = [] for i in xrange(len(vector)): if len(atts) < 3: atts.append((attributes[i], vector[i])) atts.sort(key=lambda x: x[1], reverse = True) else: if vector[i] > atts[2][1]: if attributes[i] in ('score', 'a_b_v'): continue atts[2] = (attributes[i], vector[i]) atts.sort(key=lambda x: x[1], reverse = True) return atts def main(): # Grab the beer names and attribute vectors from the database. connection = sqlite3.connect('../processing/breweries-db.sql') cursor = connection.cursor() cursor.execute('select * from beers') beers = {} item = cursor.fetchone() while item is not None: beername = unicode(item[0].strip()) brewery = unicode(item[1].strip()) beers[beername] = {'brewery': brewery, 'attributes': item[2:]} item = cursor.fetchone() connection.close() # Ask the user for an input beer. input_beer = raw_input(u'Please enter the name of a beer that you like: ') # If the input beer isn't in our database, give the user some similar beer names. if input_beer not in beers: print("That's not a beer I know. Lemme check for similar ones...") possibilities = similar_beernames(input_beer, beers) while not possibilities: input_beer = raw_input(u'We could not recognize this beer. Please enter another: ') possibilities = similar_beernames(input_beer, beers) for i, possibility in enumerate(possibilities): print(u'%d. Did you mean %s? (y/n) ' % (i + 1, possibility)), feedback = raw_input('') if u'y' in feedback: input_beer = possibility break if input_beer not in beers: print(u'We could not find the beer you were looking for. Please try again.') quit() # Ask the user for k. k = int(raw_input(u'How many similar beers would you like to see?: ')) search_attributes = important_attributes(beers[input_beer]['attributes']) print('\nSearching for beers with attributes like:'), print(', '.join(map(lambda x: x[0], search_attributes))) nearest_beers = nearest_neighbors(k, beers[input_beer]['attributes'], beers) print '\nYou might like:' rank = 1 for beer in nearest_beers: print('%s. %s -- %s (similar attributes: %s)' % (rank, beer[0], beers[beer[0]]['brewery'], ', '.join(map(lambda x: attributes[x[0]], beer[2])))) rank += 1 if __name__ == '__main__': main()
#!/usr/bin/env python """From flight data, gather info about distance between airports and check for consistency. Then write to distance.csv""" from sets import Set import numpy as np import pandas as pd pd.options.mode.chained_assignment = None #Suppress overwrite error. def get_distancefreq(): #Empty dataframe to accumulate frequency, based on Origin, Dest, and Distance. freqdf=pd.DataFrame({ 'OriginAirportId':[], 'DestAirportId':[], 'Distance':[], 'Freq':[]}) freqdf.set_index(['OriginAirportId', 'DestAirportId', 'Distance'], inplace=True) for year in range(1987, 2016): if(year == 1987): startmonth = 10 else: startmonth = 1 for month in range(startmonth, 13): flightfile='../data/%d_%d.csv' %(year, month) df = pd.read_csv(flightfile)[['OriginAirportId', 'DestAirportId', 'Distance']] #Create a freq column and calculate frequency for a given month. df['Freq'] = np.nan df['Freq'] = df.groupby(['OriginAirportId', 'DestAirportId', 'Distance']).transform(len) df.drop_duplicates(inplace=True) df.set_index(['OriginAirportId', 'DestAirportId', 'Distance'], inplace=True) #Align rows by index, and sum frequencies. freqdf, df = freqdf.align(df, fill_value=0) freqdf += df return freqdf.reset_index(level=2) def checkdistance(distdf): #Input dataframe has index=Origin, Dest; columns = Distance, Freq. #Freq = frequency of each distance given origin, dest. flights = list(distdf.index.unique()) roundtrips = [x for x in flights if (x[1], x[0]) in flights and x[0] < x[1]] #Check, store, and print various errors. print "Same Origin and Dest Airports:" same_origindest = [x[0] for x in flights if x[0] == x[1]] print same_origindest print "Multiple Distance Errors:" multipledist = [(x[0], x[1]) for x in flights if distdf.Distance[x[0], x[1]].size > 1] for x in multipledist: print "Flight: ", x print "Distances: ", list(distdf.Distance[x]) print "Frequency: ", list(distdf.Freq[x]) print "Round Trip Errors:" roundtriperrors = [x for x in roundtrips if (True if distdf.Distance[x].size != distdf.Distance[x[1], x[0]].size else (distdf.Distance[x] != distdf.Distance[x[1], x[0]]) if (distdf.Distance[x].size == 1) else (Set(distdf.Distance[x]) != Set(distdf.Distance[x[1], x[0]])))] for x in roundtriperrors: print "Flight: ", x print "Distance to: ", list(distdf.Distance[x]) print "Distance back: ", list(distdf.Distance[x[1], x[0]]) return [same_origindest, multipledist, roundtriperrors] def getdistance(): #Get distance info from flight data and check for errors. distfreq_df = get_distancefreq() errors = checkdistance(distfreq_df) #Remove same origin/dest flights. distfreq_df.drop([(x,x) for x in errors[0]], inplace=True) #Choose distance which occurs more than half the time. distfreq_df.reset_index(inplace=True) distfreq_df['TotalFreq'] = distfreq_df.groupby(['OriginAirportId', 'DestAirportId']).Freq.transform(sum) distfreq_df = distfreq_df[distfreq_df.Freq/distfreq_df.TotalFreq > 0.5] #Write to csv. distfreq_df.drop(['Freq', 'TotalFreq'], axis=1, inplace=True) distfreq_df.to_csv('../data/distance.csv', index=False)
first_number = 0 second_number = 1 for i in range(10): third_number = first_number + second_number first_number = second_number second_number = third_number print(first_number)
class Menu(): """ Simple representation of a menu: one state of the state machine created by Candela. Consists of a series of Commands One Shell instance may have one or more menus. """ def __init__(self, name): self.name = name self.title = '' self.commands = [] def options(self): """ Return the string representations of the options for this menu """ ret = "" for command in self.commands: ret += "%s\n" % str(command) return ret
import math def root(n, base=9): return n % base or n and base def root_with_factor(n, base=9): base_factor = math.floor((n/base)) root = n % base or n and base if get_factor: return root, base_factor return root
"""Method 1 a=input() b=len(a) count=0 for i in a: if(i=="i" or i=="I"): count+=1 print("number of i is",count) print("length of input is",b) """ #Method 2 a=input() count=0 b=0 for i in a: count+=1 if(i=="i" or i=="I"): b+=1 print("number of i is",b) print("length of input is",count)
# -*- coding: utf-8 -*- """ Created on Wed Jul 11 00:23:53 2018 @author: atulr """ import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model import pandas as pd df= pd.read_csv('./Stockdata/ethi.csv') X=df["Open"] Y=df["Close"] dim= df.shape[0] print(dim) per=( .7 *dim) print(per) # Split the data into training/testing sets X_train = X[:0,1] X_test = X[:,1] # Split the targets into training/testing sets Y_train = Y[:,18] Y_test = Y[:,18] regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(X_train, Y_train) # Plot outputs p=regr.predict(X_test)
class member: #type should have 3 options #generic, important, personal #generic means simple automated message #important means complex automated message #personal means should be sent a personal message #consturctor def __init__(self, name, age = 0, birthdate = " ", phone = " ", ptype = "generic"): self.name = name self.age = age self.birthdate = birthdate self.phone = phone self.ptype = ptype self.info = [name, age, birthdate, phone, ptype] #functions def get_name(self): return self.name def get_age(self): return self.get_age def get_birthdate(self): return self.birthdate def get_phone(self): return self.phone def get_type(self): return self.ptype #setters def set_name(self, name): self.name = name def set_age(self, age): self.age = age def set_birthdate(self, birthdate): self.birthdate = birthdate def set_phone(self, phone): self.phone = phone def set_ptype(self, ptype): self.ptype = ptype #format informaiton to be serialized def write_format(self): #make everything strings # name = self.name # age = str(self.age) # birthdate = self.birthdate # phone = str(self.phone) # ptype = self.ptype #Then add values to a list info = [self.name, self.age, self.birthdate, self.phone, self.ptype] # sentence = name + " " + age + " " + birthdate + " " + phone + " " + ptype # return sentence return info
import matplotlib.pyplot as plt import numpy as np class lr(): """ Linear regression using least squares method """ def fit(self, x, y): """ Fit model Parameters ---------- X : array_like, shape (n_samples, n_features) Training data y : array_like, shape (n_samples, ) Target value Return ---------- self : returns an instance of self """ x2 = np.power(x, 2) xy = x * y.reshape((-1,1)) sum_x = np.sum(x) sum_y = np.sum(y) sum_x2 = np.sum(x2) sum_x_2 = np.power(sum_x, 2) sum_xy = np.sum(xy) self.n_samples = np.count_nonzero(x) self.slope_ = ((self.n_samples * sum_xy) - (sum_x * sum_y)) / ((self.n_samples * sum_x2) - sum_x_2) self.intercept_ = (sum_y - (self.slope_ * sum_x)) / self.n_samples return self def predict(self, x): """ Predict using the linear model Parameters ---------- X : array_like or spare matrix, shape (n_samples, n_features) Sample Returns ---------- C : array, shape (n_samples, ) Returns predicted value """ self.y_pred = (self.slope_ * x) + self.intercept_ return self.y_pred def visual(self, x, y, y_pred): plt.plot(x,y,'o',color='blue') plt.plot(x, y_pred, color='red', linewidth=2) plt.xlabel('X - feature') plt.ylabel('Y - label') plt.title('Regression Graph') plt.show()
''' Rounding to get plot instead of interpolating. Future work will use interpolation instead of rounding. Creates a plot of the change in a desired weather variable vs. distance as altitude and location above the Continental US changes. ''' import pickle import copy import csv import matplotlib.pyplot as plt from bisect import bisect_left from mpl_toolkits.basemap import Basemap # Get all_data from pickle DAY = '30' all_data = pickle.load(open("Pickle_Data_Files/file" + DAY + ".p", "rb")) # get flight plan from csv height = [] lat = [] lon = [] dist = [] flightplan = 'MMMX-CYQB' filename = 'Flight_Plan_Files' + flightplan + '.csv' with open(filename, 'rb') as f: reader = csv.reader(f) for row in reader: height.append(row[2]) lat.append(row[3]) lon.append(row[4]) dist.append(row[5]) lat_rounded = [] lon_rounded = [] # changing flight plan data to floats and making height meters for comparisons for i in range(len(height)): height[i] = float(height[i]) height[i] = 0.3048 * height[i] lat[i] = float(lat[i]) lon[i] = float(lon[i]) dist[i] = float(dist[i]) # rounding lat and lon to nearest whole number to compare with GFS data lat_rounded.append(round(lat[i])) lon_rounded.append(round(lon[i])) # creating searchable double list of lat-lon from flight plan latlon = [] for i in range(len(lat_rounded)): lat_rounded[i] = str(lat_rounded[i])+'000' lon_rounded[i] = str(lon_rounded[i])+'000' latlon.append([lat_rounded[i], lon_rounded[i]]) # creating searchable double list of lat-lon from weather data w_lat = all_data['latitude'] w_lon = all_data['longitude'] w_latlon = [] for i in range(len(w_lat)): w_latlon.append([w_lat[i], w_lon[i]]) # intitializing height and variable from weather data w_height = all_data['height'] w_relh = all_data['humidity'] relh = [] num = 0 # loop to find variable at all locations for j in range(len(latlon)): wnum_height = [] wnum_relh = [] # first element in temporary vectors num = w_latlon.index(latlon[j]) wnum_height.append(w_height[num]) wnum_relh.append(w_relh[num]) num += 1 # creating temporary height and variable vectors for each location while w_latlon[num] == ['', '']: wnum_height.append(w_height[num]) wnum_relh.append(w_relh[num]) num += 1 # converting to float for i in range(len(wnum_height)): wnum_height[i] = float(wnum_height[i]) # modifying height so that it is above ground level, not sea level height[j] = height[j] + wnum_height[0] # getting index of desired variable from temporary height vector and appending hToIndex = bisect_left(wnum_height,height[j]) if hToIndex > len(wnum_relh)-1: hToIndex -= 1 relh.append(wnum_relh[hToIndex]) # Converting Height back to feet for i in range(len(height)): height[i] = height[i] / 0.3048 # Plotting Variable and Height vs. Distance plt.subplot(2, 1, 1) plt.plot(dist,relh) plt.title('Relative Humidity for %s' % flightplan) # degree_sign = u'\N{DEGREE SIGN}' plt.ylabel('Relative Humidity (%)') plt.subplot(2, 1, 2) plt.plot(dist,height) plt.xlabel('Distance (nmi)') plt.ylabel('Height (ft)') # Plotting flight path plt.figure(2) m = Basemap(projection='merc',llcrnrlat=13,urcrnrlat=58, llcrnrlon=-144,urcrnrlon=-53,resolution='c') m.drawstates() m.drawcountries(linewidth=1.0) m.drawcoastlines() map_x, map_y = m(lon, lat) m.plot(map_x,map_y) plt.title('%s' % flightplan) plt.show()
# guessing game secret_word = "lion" guess = "" attempts = 0 attempt_limit = 2 out_of_guesses = False while guess != secret_word and not(out_of_guesses): if attempts < attempt_limit: attempts += 1 guess = input("Enter guess: ") if attempts < attempt_limit: print("You have one guess left") else: out_of_guesses = True if out_of_guesses: print("Out of Guesses, YOU LOSE! The answer was " + secret_word) else: print("You Win!")