text
stringlengths
37
1.41M
class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: if not matrix or not matrix[0]: return 0 self.res = 0 memo = {} def longestFromStart(matrix, i, j): # print("position:", (i, j), "=", matrix[i][j]) if (i, j) in memo: return memo[(i, j)] else: tmp = 0 if i + 1 < len(matrix) and matrix[i + 1][j] > matrix[i][j]: tmp = max(tmp, longestFromStart(matrix, i + 1, j)) if i - 1 >= 0 and matrix[i - 1][j] > matrix[i][j]: tmp = max(tmp, longestFromStart(matrix, i - 1, j)) if j + 1 < len(matrix[0]) and matrix[i][j + 1] > matrix[i][j]: tmp = max(tmp, longestFromStart(matrix, i, j + 1)) if j - 1 >= 0 and matrix[i][j - 1] > matrix[i][j]: tmp = max(tmp, longestFromStart(matrix, i, j - 1)) memo[(i, j)] = 1 + tmp self.res = max(self.res, memo[(i, j)]) return memo[(i, j)] for i in range(len(matrix)): for j in range(len(matrix[0])): # print("--------------------") longestFromStart(matrix, i, j) return self.res
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if not head or not head.next: return True fast = head.next slow = head while fast and fast.next: fast = fast.next.next slow = slow.next mid = slow if mid == mid.next: p = mid.next.next else: p = mid.next q = self.reverseList(p) p = head while p and q: if p.val == q.val: p = p.next q = q.next else: return False return True def reverseList(self, head): pre = None cur = head while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre
class Monoqueue: """ Implements a queue with the monotonic decreasing invariant. Nameley: for all i,k i < k: queue[i] >= queue[k] This invariant is enforced by truncating the tail of the queue when inserting a new element. For example, If the new element is strictly greater than all existing elements, all other elements will be truncated before insertion and the new element will be the only element in the queue. """ def __init__(self): self.items = [] def push(self, item): """ Adds a new element to the queue, truncating the tail of the queue to maintain the monotonic invariant. """ while len(self.items) > 0 and self.items[-1] < item: self.items.pop(-1) self.items.append(item) def front(self): """ Allows "peeking" at the maximum value in the queue. """ return self.items[0] def pop(self, item): """ Removes the maximum value in the queue if it is equal to `item` """ if item == self.items[0]: self.items.pop(0)
# Practice: Writing While Loops # #a x = 1 while x < 6: print(x) x += 1 print() #b x = 2 while x <12: print(x) x += 3 print() #c x = -10 while x < 1: print(x, end=" ") x += 2 print() print() #d x = 0 while x < 4: print(4 * "*") x += 1 print() for x in range(4): print("****") print() string = "Art!" i = 0 while i < len(string): print(string,i) i += 1 print() for x in range(1): print("Art")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( "--your-name", type=str, help="Test param", required=True ) args = parser.parse_args() name = args.your_name print("Hello, {name}!".format(name=name)) print("Bye, {name}!".format(name=name))
#My first Project #Returns the username name = input("Give me your name: ") print("Your Name is " + name) #The Program returns a information "Your Name is + name" age = int(input("Please give me your age / how old are you?: ")) print("You are " + str(age) + " years old") #Returns the date after 100 years year = str((2018 - age) + 100) print(name + " will be 100 years old in " + year)
# With this concept of default parameters in mind, the goal of this assignment is to write a single function, randInt() that takes up to 2 arguments. # If no arguments are provided, the function should return a random integer between 0 and 100. # If only a max number is provided, the function should return a random integer between 0 and the max number. # If only a min number is provided, the function should return a random integer between the min number and 100 # If both a min and max number are provided, the function should return a random integer between those 2 values. # Here are a couple of important notes about using random.random() and rounding. (Create this function without using random.randInt() -- we are trying to build that method ourselves for this assignment!) # random.random() returns a random floating number between 0.000 and 1.000 # random.random() * 50 returns a random floating number between 0.000 and 50.000 # random.random() * 25 + 10 returns a random floating number between 10.000 and 35.000 # round(num) returns the rounded integer value of num # BONUS: account for any edge cases (eg. min > max, max < 0) import random def randInt(min=0, max=100): range = max - min num = round(random.random()*range + min) if max < 0: print ("Max cannot be less than zero.") elif min > max: print("Min value cannot be greater than Max Value") else: return num print(randInt()) print(randInt(max=50)) print(randInt(min=50)) print(randInt(min=50, max=500))
from binascii import b2a_hex, a2b_hex from Crypto.Cipher import DES import sys #key = '12345678' while 1: key = raw_input('Please input the key(8 bytes): ') if key == '12345678': file = open('history', 'r') try: text = file.read() finally: file.close() obj = DES.new(key) get_cryp = a2b_hex(text) after_text = obj.decrypt(get_cryp) print '\nChat History: \n' + after_text break; else: result = raw_input("Wrong!Input anything try again!(If you won't try another time, just input 'no') Your Answer is: ") if result == 'no': break;
from typing import Tuple from .base import ConfigBase """参考https://pytorch.org/docs/stable/optim.html""" class OptimizerConfig(ConfigBase): # learning rate for embedding layer embedding_lr: float = 1e-3 # learning rate for other layer lr: float = 1e-3 # embedding层在前static_epoch将不会进行训练 # 在static_epoch之后,embedding将会以embedding_lr作为学习率进行训练 static_epoch: int = 0 class AdamConfig(OptimizerConfig): """ Adam algorithm. It has been proposed in Adam: A Method for Stochastic Optimization. """ # coefficients used for computing running averages of gradient # and its square(default: (0.9, 0.999)) betas: Tuple[float, float] = (0.9, 0.999) # term added to the denominator to improve numerical stability(default: 1e-8) eps: float = 1e-8 # weight decay(L2 penalty)(default: 0) weight_decay: float = 0. # whether to use the AMSGrad variant of this algorithm from the paper # On the Convergence of Adam and Beyond amsgrad: bool = False class AdadeltaConfig(OptimizerConfig): """ Adadelta algorithm. It has been proposed in ADADELTA: An Adaptive Learning Rate Method. """ # coefficient used for computing a running average of squared gradients(default: 0.9) rho: float = 0.9 # term added to the denominator to improve numerical stability(default: 1e-6) eps: float = 1e-6 # weight decay(L2 penalty)(default: 0) weight_decay: float = 0. class AdagradConfig(OptimizerConfig): """ Adagrad algorithm. It has been proposed in Adaptive Subgradient Methods for Online Learning and Stochastic Optimization. """ # learning rate decay (default: 0) lr_decay: float = 0.0 # weight decay (L2 penalty) (default: 0) weight_decay: float = 0.0 # term added to the denominator to improve numerical stability (default: 1e-10) eps: float = 1e-10 class AdamWConfig(OptimizerConfig): """ AdamW algorithm. The original Adam algorithm was proposed in Adam: A Method for Stochastic Optimization. The AdamW variant was proposed in Decoupled Weight Decay Regularization. """ # coefficients used for computing running averages of gradient and its square(default: (0.9, 0.999)) betas: Tuple[float, float] = (0.9, 0.999) # term added to the denominator to improve numerical stability(default: 1e-8) eps: float = 1e-8 # weight decay coefficient(default: 1e-2) weight_decay: float = 1e-2 # whether to use the AMSGrad variant of this algorithm from the paper # On the Convergence of Adam and Beyond(default: False) amsgrad: bool = False class AdamaxConfig(OptimizerConfig): """ Adamax algorithm (a variant of Adam based on infinity norm). It has been proposed in Adam: A Method for Stochastic Optimization. """ # coefficients used for computing running averages of gradient and its square(default: (0.9, 0.999)) betas: Tuple[float, float] = (0.9, 0.999) # term added to the denominator to improve numerical stability(default: 1e-8) eps: float = 1e-8 # weight decay coefficient(default: 1e-2) weight_decay: float = 1e-2 class ASGDConfig(OptimizerConfig): """ Averaged Stochastic Gradient Descent. It has been proposed in Acceleration of stochastic approximation by averaging. """ # decay term (default: 1e-4) lambd: float = 1e-4 # power for eta update (default: 0.75) alpha: float = 0.75 # point at which to start averaging (default: 1e6) t0: float = 1e6 # weight decay (L2 penalty) (default: 0) weight_decay: float = 0 class RMSpropConfig(OptimizerConfig): """ RMSprop algorithm. Proposed by G. Hinton in his course. """ # momentum factor(default: 0) momentum: float = 0.0 # smoothing constant(default: 0.99) alpha: float = 0.99 # term added to the denominator to improve numerical stability(default: 1e-8) eps: float = 1e-8 # if True, compute the centered RMSProp, the gradient is normalized by an estimation of its variance centered: bool = False # weight decay(L2 penalty)(default: 0) weight_decay: float = 0. class RpropConfig(OptimizerConfig): """ The resilient backpropagation algorithm. """ # pair of (etaminus, etaplis), that are multiplicative increase and decrease factors (default: (0.5, 1.2)) etas: Tuple[float, float] = (0.5, 1.2) # a pair of minimal and maximal allowed step sizes (default: (1e-6, 50)) step_sizes: Tuple[float, float] = (1e-6, 50) class SGDConfig(OptimizerConfig): """ stochastic gradient descent (optionally with momentum). Nesterov momentum is based on the formula from On the importance of initialization and momentum in deep learning. """ # momentum factor (default: 0) momentum: float = 0. # weight decay (L2 penalty) (default: 0) weight_decay: float = 0. # dampening for momentum (default: 0) dampening: float = 0. # enables Nesterov momentum (default: False) nesterov: bool = False
"""各种模型的设置""" from typing import Union, Optional, Dict from .base import ConfigBase class MLModelConfig(ConfigBase): pass class LogisticRegressionConfig(MLModelConfig): """参考:https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html""" # penalty{‘l1’, ‘l2’, ‘elasticnet’, ‘none’} Used to specify the norm used in the penalization. penalty: str = "l2" # Dual or primal formulation. Dual formulation is only implemented # for l2 penalty with liblinear solver. Prefer dual=False when n_samples > n_features. dual: bool = False # Tolerance for stopping criteria. tol: float = 1e-4 # Inverse of regularization strength # must be a positive float. Like in support vector machines, smaller values specify stronger regularization. C: float = 1.0 # Specifies if a constant(a.k.a. bias or intercept) should be added to the decision function. fit_intercept: bool = True # Useful only when the solver ‘liblinear’ is used and self.fit_intercept is set to True. intercept_scaling: float = 1 # dict or ‘balanced’ or None, default="balanced" # Weights associated with classes in the form {class_label: weight}. # If not given, all classes are supposed to have weight one. # The “balanced” mode uses the values of y to automatically adjust weights # inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)). class_weight: Union[str, None, Dict[str, float]] = "balanced" # {‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’} # Algorithm to use in the optimization problem. # For small datasets, ‘liblinear’ is a good choice, whereas ‘sag’ and ‘saga’ are faster for large ones. solver: str = 'sag' # Maximum number of iterations taken for the solvers to converge. max_iter: int = 1000 # multi_class{‘auto’, ‘ovr’, ‘multinomial’} =’auto’ multi_class: str = 'ovr' # For the liblinear and lbfgs solvers set verbose to any positive number for verbosity. verbose: int = 0 # The seed of the pseudo random number generator to use when shuffling the data. # If int, random_state is the seed used by the random number generator # If None, the random number generator is the RandomState instance used # by np.random. Used when solver == ‘sag’ or ‘liblinear’. random_state: int = None # Number of CPU cores used when parallelizing over classes if multi_class =’ovr’”. T n_jobs: int = None # The Elastic-Net mixing parameter, with 0 <= l1_ratio <= 1. l1_ratio: Optional[float] = None class LinearSVMConfig(MLModelConfig): # dict or ‘balanced’ or None, default="balanced" # Weights associated with classes in the form {class_label: weight}. # If not given, all classes are supposed to have weight one. # The “balanced” mode uses the values of y to automatically adjust weights # inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)). class_weight: Union[str, None, Dict[str, float]] = "balanced" # The penalty (aka regularization term) to be used. Defaults to ‘l2’ which is the standard regularizer for linear # SVM models. ‘l1’ and ‘elasticnet’ might bring sparsity to the model (feature selection) not achievable with ‘l2’. penalty: str = 'l2' # Constant that multiplies the regularization term. Defaults to 0.0001. # Also used to compute learning_rate when set to ‘optimal’. alpha: float = 0.0001 # The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. l1_ratio = 0 corresponds to # L2 penalty, l1_ratio = 1 to L1. Defaults to 0.15. l1_ratio: float = 0.15 # Whether the intercept should be estimated or not. If False, the data is assumed to be already centered. fit_intercept: bool = True # The maximum number of passes over the training data(aka epochs). # It only impacts the behavior in the fit method, and not the partial_fit method. max_iter: int = 1000 # The stopping criterion. If it is not None, the iterations will stop when(loss > best_loss - tol) # for n_iter_no_change consecutive epochs. tolfloat = 1e-3 # Whether or not the training data should be shuffled after each epoch. shufflebool = True # The verbosity level. verboseint = 0 # The number of CPUs to use to do the OVA(One Versus All, for multi-class problems) computation. None means 1 # unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. n_jobs: int = None # The seed of the pseudo random number generator to use when shuffling the data. If int, random_state is the # seed used by the random number generator # If RandomState instance, random_state is the random number generator # If None, the random number generator is the RandomState instance used by np.random. random_state: Optional[int] = None # Number of iterations with no improvement to wait before early stopping. n_iter_no_change: int = 5
num = 0 def adding(a): a += 1 return a def using_global(): global num num += 1 print(adding(num)) print(num) using_global() print(num)
# count_0 = 0 # count_1 = 0 # def fibonacci(N): # if(N==0): # #print("0") # global count_0 # count_0 += 1 # return 0 # elif(N==1): # #print("1") # global count_1 # count_1 += 1 # return 1 # else: # return(fibonacci(N-1)+ fibonacci(N-2)) # T = int(input()) # for i in range(T): # N = int(input()) # fibonacci(N) # print(count_0, count_1) # count_0 = 0 # count_1 = 0 a = int(input()) zero = [1, 0, 1] one = [0, 1, 1] def fibonacci(N): length = len(zero) if(N>=length): for i in range(length, N+1): zero.append(zero(N-1)+zero(N-2)) one.append(one(N-1)+one(N-2)) print("%d %d"%(zero[N],one[N])) #print("%d %d"%(zero[N],one[N)) for i in range(a): k = int(input()) fibonacci(k)
""" Fetches the API response from the interview scheduler application """ import os,sys,time sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from conf import fetch_api_interviewscheduler_conf as conf import requests import urllib import json from utils.results import Results url="http://3.219.215.68//get-schedule" date=conf.date start_time_list=[] end_time_list=[] class fetch_api_response(Results): """ Class contains methods to connect to the Interview scheduler website and fetch the free time slots from the api response """ def connect_to_website(self): #method to for api call to fetch response from webpage self.config_details={'date':date} self.api_call=requests.post(url,data=self.config_details) self.free_timeslot_list=self.api_call.json()['free_slots_in_chunks'] return self.free_timeslot_list def get_free_slots(self,free_timeslot_list): #method to seperate out only the start and end times of the events from the API response #iterate through the dictionaries in the list and store the values of the key 'start' and 'end' into separate lists for each_time_dict in free_timeslot_list: start_time_list.append(str(each_time_dict['start'])) end_time_list.append(str(each_time_dict['end'])) #Join the end time and start times in the list self.api_free_slots=[start_time_list[i]+"-"+end_time_list[i] for i in range(0,len(end_time_list))] return self.api_free_slots
import GridFunctions import heapq from queue import Queue, LifoQueue as stack class Node: def __init__(self, value, par, search_type): self.value = value self.parent = par self.g = 0 # path cost self.h = 0 # heuristic cost self.f = self.g + self.h # A* self.priority = self.h if search_type else self.f def __lt__(self, other): return self.priority < other.priority def get_neighbors(self, grid): v = self.value up = [v[0]-1, v[1]] down = [v[0]+1, v[1]] left = [v[0], v[1]-1] right = [v[0], v[1]+1] neighbors = [] if grid[up[0]][up[1]] != 0: neighbors.append(up) if grid[down[0]][down[1]] != 0: neighbors.append(down) if grid[left[0]][left[1]] != 0: neighbors.append(left) if grid[right[0]][right[1]] != 0: neighbors.append(right) return neighbors def main(): filename = "grid.txt" grid = GridFunctions.readGrid(filename) start = [1, 1] goal = [5, 6] print("Please enter a search type. 0 for A*. 1 for Greedy. /n") search_type = bool(input()) path = informed_search(grid, start, goal, search_type) print("Hi") path_filename = "path.txt" if path is None: print("No path was found.") else: GridFunctions.outputGrid(grid, start, goal, path) print("Hello") def expand_node(grid, node, open_list, closed_list, goal, search_type): def in_explored(loc, q): return loc in [each.value for each in q] def in_visited(loc, l): return loc in [each.value for each in l] for each in node.get_neighbors(grid): if not in_visited(each, closed_list) and not in_explored(each, open_list): temp_node = Node(each, node, search_type) temp_node.g = node.g + grid[each[0]][each[1]] temp_node.h = heuristic(node.value, goal) temp_node.f = node.g + node.h heapq.heappush(open_list, temp_node) def informed_search(grid, start, goal, search_type): current_loc = Node(start, '', search_type) current_loc.g = 0 # print(current_loc) current_loc.h = heuristic(current_loc.value, goal) closed_list, path = [], [] open_list = [] heapq.heappush(open_list, current_loc) return search(grid, current_loc, goal, open_list, closed_list, path, search_type) def heuristic(current_loc, goal): manhattan_distance = abs(current_loc[0] - goal[0]) + abs(current_loc[1] - goal[1]) return manhattan_distance def search(grid, node, goal, open_list, closed_list, path, search_type): closed_list.append(node) print(node.value) if node.value == goal: return set_path(node, path) else: expand_node(grid, node, open_list, closed_list, goal, search_type) if open_list: return None else: return search(grid, open_list.get(), goal, open_list, closed_list, path, search_type) def set_path(node, path): path.append(node.value) if node.parent == '': return path else: return set_path(node.parent, path) main()
import math def unoReverse(x): return x[::-1] def findMaxIndex(x): return x.index(max(x)) def odds(x): return [odd for odd in x if odd % 2 != 0] def euclidianDistance(coor1, coor2): return math.sqrt(sum([(x-y)**2 for x, y in zip(coor1, coor2)])) def fileLineFinder(file): lines = [] with open(file, 'r') as filehandler: contents = filehandler.readlines() for line in contents: indexPostions = line[:-1] lines.append(indexPostions) return print(lines) def fileWriter(file, list): with open(file, 'w') as filehandler: for listItems in list: filehandler.write('%s\n' % listItems) return filehandler class BankAccount: ID = "" deposit = 0 balance = 0 withdraw = 0 def __init__(self, name, current_balance): self.ID = name self.balance = current_balance self.deposit = 0 self.withdraw = 0 def deposit_money(self, money): self.deposit = money self.balance = self.deposit + self.balance print("Your current balance is: ") print(self.balance) return self.balance def withdraw_money(self, money): self.withdraw = money self.balance = self.balance - self.withdraw print("Your current balance is: ") print(self.balance) return self.balance obj_1 = BankAccount("Cameron", 1000) obj_2 = BankAccount("Dave", 500) obj_1.withdraw_money(500) obj_2.deposit_money(500)
from tkinter import * from quiz_brain import QuizBrain THEME_COLOR = "#375362" class QuizInterface: def __init__(self, quiz_brain: QuizBrain): self.quiz = quiz_brain self.window = Tk() self.window.title("Quiz") self.window.config(padx=20, pady=20, bg=THEME_COLOR) self.text = Label(text="Score:", bg= THEME_COLOR, padx = 20 , pady = 20, fg="white") self.text.grid(row=0,column=1) self.canvas = Canvas(width=300, height=250) self.canvas.grid(row=1, column=0, columnspan=2) self.question_text = self.canvas.create_text(150,125, text="Some Question Text", fill=THEME_COLOR, width = 280, font=("Ariel", 20, "italic")) true_img = PhotoImage(file="images/true.png") self.button_1 = Button(image=true_img, highlightthickness=0, command=self.true_pressed) self.button_1.grid(row=2,column=0, pady = 50) false_img = PhotoImage(file="images/false.png") self.button_2 = Button(image=false_img, highlightthickness=0, command=self.false_pressed) self.button_2.grid(row=2,column=1) self.get_next_question() self.window.mainloop() def get_next_question(self): self.canvas.config(bg="white") if self.quiz.still_has_questions(): self.text.config(text= f"Score: {self.quiz.score}") q_text = self.quiz.next_question() self.canvas .itemconfig(self.question_text, text=q_text) else: self.canvas.itemconfig(self.question_text, text = f"You've reached the end: {self.quiz.score}") self.button_1.config(state = "disabled") self.button_2.config(state = "disabled") def true_pressed(self): is_right = self.quiz.check_answer("True") self.give_feedback(is_right) def false_pressed(self): is_right = self.quiz.check_answer("False") self.give_feedback(is_right) def give_feedback(self, is_right): if is_right: self.canvas.config(bg = "green") else: self.canvas.config(bg="red") self.window.after(1000, self.get_next_question)
""" Tests for trends in time series data Nonparametric Trend Tests ------------------------- Nonparametric tests should be used where one or more of the following conditions exist in the data. 1. The data are nonnormal. 2. There are missing values in the data. 3. The data are censored. Censored data are those observations report at as being less than or greater than some threshold value. In some cases, it may be remove the affect of covariates from a trend test. With such methods, the variable under consideration is adjusted by one or several covariates by building a regression model and applying the trend test to the residuals. A common example of this approach is flow-normalization, which attempts to remove the effect of natural variablity in flow on the concentration of a particular constituent in a stream. Nonparametric procedures cannot be applied to flow-adjusted records containing censored data since regression residuals cannot be computed for censored values (Hirsch et al., 1991). References ---------- .. [1] Hirsch, R.M., R.B. Alexander, R.A. Smith. 1991. Selection of Methods for the Detection and Estimation of Trends in Water Quality Data. Water Resources Research. Resources ---------- .. [1] https://up-rs-esp.github.io/mkt/# .. [2] https://cran.r-project.org/web/packages/trend/vignettes/trend.pdf """ import pandas as pd import numpy as np from scipy.stats import mannwhitneyu, norm, rankdata def sens_diff(x): n = len(x) N = int(n*(n-1)/2) # number of slope estimates s = np.zeros(N) i = 0 for j in np.arange(1, n): s[i:j+i] = (x[j] - x[0:j])/np.arange(1, j+1) i += j return s def sens_slope(x, alpha=None): """A nonparametric estimate of trend. Background ---------- Helsel and Hirsch (1995) show how to compute a nonparametric estimate of a linear line using the Kendall-Theil method when there are no seasonal differences in the trend. This method does not require that the residuals about the line be normally distributed. The estimate of the slope for the line was first developed by Theil (1950) and is discussed by Sen (1968) and illustrated in Gilbert (1987, pages 217-218). The intercept of the line is estimated using the method in Conover (1999, page 336). Neither the estimate of the slope or intercept is strongly affected by outliers. It is possible to estimate the slope if there are missing data or when less than 20% of the measurements are reported as less than the detection limit (Helsel and Hirsch 1995, page 371). - From [1] Resources --------- .. [1] https://vsp.pnnl.gov/help/vsample/nonparametric_estimate_of_trend.htm """ s = sens_diff(x) s.sort() if alpha: # calculate confidence limits C_alpha = norm.ppf(1-alpha/2)*np.sqrt(np.nanvar(x)) U = int(np.round(1 + (N + C_alpha)/2)) L = int(np.round((N - C_alpha)/2)) return np.nanmedian(s), s[L], s[U] else: return np.nanmedian(s) def seasonal_sens_slope(x, period=12, alpha=None): """ """ s = sens_diff(x[0::period]) for season in np.arange(1, period): x_season = x[season::period] s = np.append(s, sens_diff(x_season)) s.sort() if alpha: # XXX This code needs to be verified N = len(s) # calculate confidence limits C_alpha = norm.ppf(1-alpha/2)*np.sqrt(np.nanvar(x)) U = int(np.round(1 + (N + C_alpha)/2)) L = int(np.round((N - C_alpha)/2)) return np.nanmedian(s), s[L], s[U] else: return np.nanmedian(s) def pettitt(x, alpha=0.05): """Pettitt's change-point test A nonparameteric test for detecting change points in a time series. Parameters ---------- x : array_like Return ------ Formula ------- The non-parametric statistic is defined as .. math:: K_t = \max\abs{U_{T,j}} where .. math:: U_{T,j} = \sum_sum{i=1}^{t}\sum_{j=t+1}^{T} sgn(X_i - X_j) The change point of the series is located at K_t, provided that the statistic is significant. """ U_t = np.zeros_like(x) n = len(x) r = rankdata(x) for i in np.arange(n): U_t[i] = 2 * np.sum(r[:i+1]) - (i+1)*(n-1) t = np.argmax(np.abs(U_t)) K_t = U_t[t] p = 2.0 * np.exp((-6.0 * K_t**2)/(n**3 + n**2)) if p > alpha: return t else: return np.nan def partial_mann_kendall(x,y): """Partial Mann-Kendall Trend Test A nonparametric test for a monotonic trend, which accounts for the influences of a covariate. Paramters --------- x : array A chronologically ordered sequence of observations. y : arrayG Coincident observations of a covariate. Returns ------- Note ---- Does not yet account for ties. """ pass # test that x and y are the same length # coumpute MK scores s_x = mk_score(x) s_y = mk_score(y) def pmk_k(x,y): """Calculate the K term of the Partial Mann Kendall test. Parameters ---------- x : array y : array Returns ------- K term of the PMK test. """ n = len(x) k = 0 for i in np.arange(1, n-1): pass # TODO def pmk_r(x): """Calculate the R term of the Partial Mann Kendall test. Parameters ---------- x : array A chronologically ordered sequence of observations. Returns ------- An array of R values used in determing conditional covariance. """ n = len(x) r = np.zeroes_like(x) for j in np.arange(1, n): s = 0 for i in np.arange(1, n): s += np.sum(np.sign(x[j] - x[i])) r[j] = (n+1+s)/2 return r def ar1_trend_correction(rho, n=None): """Coefficient to correct trend statistics for autocorrelation. Used to adjust the variance or standard deviation of the trend statistic in MDC or variaous trend tests. Only appropriate for data exhibiting AR(1) structure, which is typical for water quality data collected at weekly, biweekly, or mothly intervals. Higher-frequency data should be tested for higher-order AR terms, and may require aggregation. To apply the correction, multiply the variance by coefficient, or mulitply the standard deviation by the square root of the coefficient. Parameters ---------- rho : float Autocorrelation coefficient at lag 1. n : int Sample size. Can be ignored for large sample sizes. Returns ------- Correction coefficient. Take the square root when used to correct standard deviation. References ---------- .. [1] Spooner et al. 2011. Tech Notes 6: Statistical Analysis for Monotonic Trends. USEPA. .. [2] Fuller, W.A. 1976. Introduction to Statistical Time Series. John Wiley & Sons, Inc. New York. .. [3] Matalas, N.C. and W.B. Langbein. 1962. Information content of the mean. Journal of Geophysical Research 67(9):3441-34498 """ c = (1+rho)/(1-rho) if n is not None: # apply correction for sample size c -= (2/n)*(rho*(1-rho**n))/((1-rho)**2) return c def mk_z(s, var_s): """Compoutes the MK test statistic, Z. Parameters ---------- s : float The MK trend statistic, S. var_s : float Variance of S. Returns ------- MK test statistic, Z. """ # calculate the MK test statistic if s > 0: z = (s - 1)/np.sqrt(var_s) elif s < 0: z = (s + 1)/np.sqrt(var_s) else: z = 0 return z def mk_score(x): """Computes S statistic used in Mann-Kendall tests. Parameters ---------- x : array_like Chronologically ordered array of observations. Returns ------- MK trend statistic (S). Formula ------- The MK statistic is defined as .. math:: S = \sum_{i<j} (x_i - x_j) where ..math:: sgn(x_i - x_j) &= \begin{cases} 1, & x_i - x_j > 0\\ 0, & x_i - x_j = 0\\ -1, & x_i - x_j < 0 \end{cases}, which tells us whether the difference between the measurements at time :math:`i` and :math:`j` are positive, negative or zero. """ n = len(x) s = 0 for j in np.arange(1, n): s += np.sum(np.sign(x[j] - x[0:j])) return s def mk_score_variance(x): """Computes corrected variance of S statistic used in Mann-Kendall tests. Equation 8.4 from Helsel and Hirsch (2002). Also see XXX Parameters ---------- x : array_like Returns ------- Variance of S statistic Formula ------- The variance :math:`Var(S)` is often given as: .. math:: VAR(S) = \frac{1}{18} \Big( n(n-1)(2n+5) - \sum_{k=1}^p q_k(q_k-1)(2q_k+5) \Big), where :math:`p` is the total number of tie groups in the data, and :math:`q_k` is the number of data points contained in the :math:`k`-th tie group. Note that this might be equivalent to: See page 728 of Hirsch and Slack References ---------- .. [1] Helsel and Hirsch, R.M. 2002. Statistical Methods in Water Resources. """ n = len(x) # calculate the unique data unique_x = np.unique(x) # calculate the number of tied groups g = len(unique_x) # calculate the var(s) if n == g: # there is no tie var_s = (n*(n-1)*(2*n+5))/18 else: # there are some ties in data tp = np.zeros_like(unique_x) for i in range(len(unique_x)): tp[i] = sum(x == unique_x[i]) var_s = (n*(n-1)*(2*n+5) - np.sum(tp*(tp-1)*(2*tp+5)))/18 return var_s def kendall(x, alpha=0.05): """Mann-Kendall (MK) is a nonparametric test for monotonic trend. Parameters ---------- x : array Data in the order it was collected in time. Returns ------- z : float normalized MK test statistic. p : float Background ---------- The purpose of the Mann-Kendall (MK) test (Mann 1945, Kendall 1975, Gilbert 1987) is to statistically assess if there is a monotonic upward or downward trend of the variable of interest over time. A monotonic upward (downward) trend means that the variable consistently increases (decreases) through time, but the trend may or may not be linear. The MK test can be used in place of a parametric linear regression analysis, which can be used to test if the slope of the estimated linear regression line is different from zero. The regression analysis requires that the residuals from the fitted regression line be normally distributed; an assumption not required by the MK test, that is, the MK test is a non-parametric (distribution-free) test. Hirsch, Slack and Smith (1982, page 107) indicate that the MK test is best viewed as an exploratory analysis and is most appropriately used to identify stations where changes are significant or of large magnitude and to quantify these findings. Examples -------- >>> x = np.random.rand(100) + np.linspace(0,.5,100) >>> z,p = kendall(x) References ---------- Attribution ----------- Background authored by Sat Kumar Tomer, available at https://vsp.pnnl.gov/help/Vsample/Design_Trend_Mann_Kendall.htm Modified from code by Michael Schramn available at https://github.com/mps9506/Mann-Kendall-Trend/blob/master/mk_test.py """ n = len(x) s = mk_score(x) var_s = mk_score_variance(x) z = mk_z(s, var_s) # calculate the p_value p_value = 2*(1-norm.cdf(abs(z))) # two tail test return p_value def seasonal_kendall(x, period=12): """ Seasonal nonparametric test for detecting a monotonic trend. Parameters ---------- x : array A sequence of chronologically ordered observations with fixed frequency. period : int The number of observations that define period. This is the number of seasons. Background ---------- The purpose of the Seasonal Kendall (SK) test (described in Hirsch, Slack and Smith 1982, Gilbert 1987, and Helsel and Hirsch 1995) is to test for a monotonic trend of the variable of interest when the data collected over time are expected to change in the same direction (up or down) for one or more seasons, e.g., months. A monotonic upward (downward) trend means that the variable consistently increases (decreases) over time, but the trend may or may not be linear. The presence of seasonality implies that the data have different distributions for different seasons (e.g., months) of the year. For example, a monotonic upward trend may exist over years for January but not for June. The SK test is an extension of the Mann-Kendall (MK) test. The MK test should be used when seasonality is not expected to be present or when trends occur in different directions (up or down) in different seasons. The SK test is a nonparametric (distribution-free) test, that is, it does not require that the data be normally distributed. Also, the test can be used when there are missing data and data less that one or more limits of detection (LD). The SK test was proposed by Hirsch, Slack and Smith (1982) for use with 12 seasons (months). The SK test may also be used for other seasons, for example, the four quarters of the year, the three 8-hour periods of the day, and the 52 weeks of the year. Hirsch, Slack and Smith (1982) showed that it is appropriate to use the standard normal distribution to conduct the SK test for monthly data when there are 3 or more years of monthly data. For any combination of seasons and years they also show how to determine the exact distribution of the SK test statistic rather than assume the exact distribution is a standard normal distribution. Assumptions ----------- The following assumptions underlie the SK test: 1. When no trend is present the observations are not serially correlated over time. 2. The observations obtained over time are representative of the true conditions at sampling times. 3. The sample collection, handling, and measurement methods provide unbiased and representative observations of the underlying populations over time.abs 4. Any monotonic trends present are all in the same direction (up or down). If the trend is up in some seasons and down in other seasons, the SK test will be misleading. 5. The standard normal distribution may be used to evaluate if the computed SK test statistic indicates the existence of a monotonic trend over time. There are no requirements that the measurements be normally distributed or that any monotonic trend, if present, is linear. Hirsch and Slack (1994) develop a modification of the SK test that can be used when serial correlation over time is present. References ---------- Gilbert, R.O. 1987. Statistical Methods for Environmental Pollution Monitoring. Wiley, NY. Helsel, D.R. and R.M. Hirsch. 1995. Statistical Methods in Water Resources. Elsevier, NY. Hirsch, R.M. and J.R. Slack. 1984. A nonparametric trend test for seasonal data with serial dependence. Water Resources Research 20(6):727-732. Hirsch, R.M., J.R. Slack and R.A. Smith. 1982. Techniques of Trend Analysis for Monthly Water Quality Data. Water Resources Research 18(1):107-121. Attribution ----------- Text copied from https://vsp.pnnl.gov/help/vsample/Design_Trend_Seasonal_Kendall.htm """ # Compute the SK statistic, S, for each season #s = np.zeros(period) s = 0 var_s = 0 for season in np.arange(period): x_season = x[season::period] s += mk_score(x_season) var_s += mk_score_variance(x_season) # Compute the SK test statistic, Z, for each season. z = mk_z(s, var_s) # calculate the p_value p_value = 2*(1-norm.cdf(abs(z))) # two tail test return p_value def seasonal_rank_sum(): """Seasonal rank-sum test for detecting a step trend. Parameters ---------- Background ---------- The seasonal rank-sum test is an extension of the rank-sum test described in Helsel and Hirsch (1992). The rank-sum test is a nonparametric test to determine whether two independent sets of data are significantly different from one another. The results of the test indicate the direction of the change from the first dataset to the second dataset (upward or downward) and the level of significance of this change. References ---------- - https://pubs.usgs.gov/sir/2016/5176/sir20165176.pdf """ pass def rank_sum(x, y): """ Rank-sum test described in Helsel and Hirsch (1992). In its most general form, the rank-sum test is a test for whether one group tends to produce larger observations than the second group. Parameters ---------- x : array_like First group of observations. y : array_like Second group of observations. Background ---------- The rank-sum test goes by many names. It was developed by Wilcoxon (1945), and so is sometimes called the Wilcoxon rank-sum test. It is equivalent to a test developed by Mann and Whitney near the same time period, and the test statistics can be derived one from the other. Thus the Mann-Whitney test is another name for the same test. The combined name of Wilcoxon-Mann-Whitney rank-sum test has also been used. Nonparametric tests possess the very useful property of being invariant to power transformations such as those of the ladder of powers. Since only the data or any power transformation of the data need be similar except for their central location in order to use the rank-sum test, it is applicable in many situations. The exact form of the rank-sum test is given below. It is the only form appropriate for comparing groups of sample size 10 or smaller per group. When both groups have samples sizes greater than 10 (n, m > 10), the large-sample approximation may be used. Remember that computer packages report p-values from the large sample approximation regardless of sample size. References ---------- .. [1] Helsel, D.R. and R.M. Hirsch. 1995. Statistical Methods in Water Resources. Elsevier, NY. Attribution ----------- Text copied from Helsel and Hirsch 1995. """ pass def mannwhitney(x, y, use_continuity=True, alternative=None): """ Compute the Mann-Whitney rank test on samples x and y. Parameters ---------- x, y : array_like Array of samples, should be one-dimensional. use_continuity : bool, optional Whether a continuity correction (1/2.) should be taken into account. Default is True. alternative : None (deprecated), 'less', 'two-sided', or 'greater' Whether to get the p-value for the one-sided hypothesis ('less' or 'greater') or for the two-sided hypothesis ('two-sided'). Defaults to None, which results in a p-value half the size of the 'two-sided' p-value and a different U statistic. The default behavior is not the same as using 'less' or 'greater': it only exists for backward compatibility and is deprecated. Returns ------- statistic : float The Mann-Whitney U statistic, equal to min(U for x, U for y) if `alternative` is equal to None (deprecated; exists for backward compatibility), and U for y otherwise. pvalue : float p-value assuming an asymptotic normal distribution. One-sided or two-sided, depending on the choice of `alternative`. Notes ----- Use only when the number of observation in each sample is > 20 and you have 2 independent samples of ranks. Mann-Whitney U is significant if the u-obtained is LESS THAN or equal to the critical value of U. This test corrects for ties and by default uses a continuity correction. References ---------- .. [1] https://en.wikipedia.org/wiki/Mann-Whitney_U_test .. [2] H.B. Mann and D.R. Whitney, "On a Test of Whether one of Two Random Variables is Stochastically Larger than the Other," The Annals of Mathematical Statistics, vol. 18, no. 1, pp. 50-60, 1947. """ return mannwhitneyu(x, y, use_continuity, alternative)
def apply_tax(price, tax): return price + price * tax / 100 def apply_discount(price, discount): return price - price * discount / 100 def basket(basket, tax=15): subtotal = 0 for price, discount in basket.items(): subtotal += apply_discount(price, discount) total = apply_tax(subtotal, tax) return subtotal, total if __name__ == "__main__": shopping_cart = {1000:20,500: 10,100: 1} subtotal, total = basket(shopping_cart, 12) print(f'Price before tax: ${subtotal}') print(f'Final price: ${total}')
# 문자 출력 print('Hello, Python !!') print('반갑습니다. \n파이썬세계로 온것을 환영합니다.') # '\n' 은 줄바꿈 print("문자는 반드시 인용부호(' ' 혹은 \" \")로 감싸야 합니다.") # '\'는 명령 문자앞에 붙이면 그 문자를 그대로 문자로 출력 # 숫자 출력 print(100) print(150 + 200) print(150 - 200) # 기본연산 x = 50 y = 4. print("x = ", x) print("y = ", y) print("x + y = ", x+y) print("x * y = ", x*y) print("x / y = ", x/y) print("-x = ", -x) print("+x = ", +x) print("x ** y = ", x**y) print("pow(x,y) = ", pow(x, y)) # 변수에 문자담기 name = '홍길동' greeting = '안녕' print(name, greeting) print(greeting, name) text = name + '님, ' + greeting + '하세요' print(text) # 변수에 숫자담기 coffee1_name = '카페라떼'; coffee1_val = 4000; coffee2_name = '카푸치노'; coffee2_val = 4500; coffee3_name = '마끼야또'; coffee3_val = 5000; # Case 1 # print('손님, ' + coffee1_name + coffee2_name + coffee3_name + '를 주문하셨습니다.') # print('가격은 ' + coffee1_val + coffee2_val + coffee3_val + '원 입니다.') # TypeError 발생 # Case 2 # print('손님, ' + coffee1_name + coffee2_name + coffee3_name + '를 주문하셨습니다.') # print('가격은 ' + str(coffee1_val + coffee2_val + coffee3_val) + '원 입니다.') # Case 3 coffee_val = coffee1_val + coffee2_val + coffee3_val print('손님, \n%s, %s %s를 주문하셨습니다.' % (coffee1_name, coffee2_name, coffee3_name)) print('가격은 %d원 입니다.' % coffee_val)
from math import sqrt import sys def Input(line): is_error = True while is_error: is_error = False try: coeff = int(line) except ValueError: try: coeff = float(line) except ValueError: is_error = True line = input("Некорректный ввод, повторите попытку: ") return coeff def A_Input(arg): try: coeff = int(arg) except ValueError: try: coeff = float(arg) except ValueError: coeff = "e" return coeff print("|Аникин Филипп Автандилович, ИУ5-53Б|\n") A_incorrect = True if len(sys.argv)>1: print("<Режим принятия аргументов из КС>") if len(sys.argv) == 4: A = A_Input(sys.argv[1]) B = A_Input(sys.argv[2]) C = A_Input(sys.argv[3]) A_incorrect = False if A == "e" or B == "e" or C == "e": print("*Некорректные аргументы, переход на ручной ввод*") A_incorrect = True else: print("*Некорректное количество аргументов, переход на ручной ввод*") A_incorrect = True if A_incorrect == True: print("<Введите коэффициенты биквадратного уравнения>") line = input("A = ") A = Input(line) line = input("B = ") B = Input(line) line = input("C = ") C = Input(line) print("======================================================") print("A = ", A, "; B = ", B, "; C = ", C, sep='') D = B*B - 4*A*C if D-int(D) == 0: D = int(D) print("Дискриминант =",D) print("------------------------------------------------------") if A != 0: if D >= 0: B = -B A = A + A D = sqrt(D) Q1 = (B+D)/A Q2 = (B-D)/A if D == 0: Q2 = -1 D = -1 if Q1 > 0: D = 1 Q1 = sqrt(Q1) if Q1-int(Q1) == 0: Q1 = int(Q1) print("X", D, " = ", Q1, ", X", D+1, " = ", -Q1, sep='') D = D + 2 elif Q1 == 0: D = 1 Q1 = int(Q1) print("X", D, " = ", Q1, sep='') D = D + 1 if Q2 >= 0: Q2 = sqrt(Q2) if Q2-int(Q2) == 0: Q2 = int(Q2) if D == -1: D = 1 print("X", D, " = ", Q2, ", X", D+1, " = ", -Q2, sep='') elif Q2 == 0: if D == -1: D = 1 Q2 = int(Q2) print("X", D, " = ", Q2, sep='') if D == -1: print("Действительных корней нет") else: print("Действительных корней нет") else: if B!= 0: Q = -C/B if Q >= 0: Q = sqrt(Q) if Q-int(Q) == 0: Q = int(Q) print("X1 = ", -Q, ", X2 = ", Q, sep='') else: print("Действительных корней нет") else: if C != 0: print("Действительных корней нет") else: print("Решение - любое число") print("======================================================")
# -*- coding: utf-8 -*- # "\"用来转义,输入特殊符号 print('I\'m OK.') print('I\'m learning \nPython.') print('\\\n\\') # '''...'''表示多行内容 print('''line1 line2 line3''') print(r'''line1 line2 line3''') # 变量 a = 1 t_007 = 't007' Answer = True # 等号=是赋值语句,可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可## 以是不同类型的变量 a = 111 # a是整数 print(a) a = 'abc' # a变为字符串 print(a)
# -*- coding: utf-8 -*- # 排序算法 # 排序的核心是s比较两个元素的大小 # 如果是数字,我们可以直接比较,但如果是字符串或者两个dict,直接比较数学上的大小没有意义,因此比较过程必须通过函数抽象出来。 # Python内置的sorted()函数就可以对list进行排序(升序) sortedList = sorted([28, 1, 39, -9, 0]) print(sortedList) # sorted()函数是一个高阶函数,它还可以接收一个key函数来自定义排序,例如按绝对值大小排序: absSorted = sorted([39, 9, -12, 23, 29, -76, 0, 12], key=abs) print(absSorted) # 对字符串排序 strSorted = sorted(['beijing', 'shanghai', 'guangzhou', 'shenzhen', 'wuhan']) print(strSorted) # 对tuple按名字排序 L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_name(t): return t[0].lower() sortedL = sorted(L, key=by_name) print(sortedL)
# A snake must know how hiss ... or sometimes rattle # Normally we can just use echo to print out message during execution # However: # It is mandatory to *hiss* when there is error # also, *rattle* is needed when a snake meet something ... at the beginning # or at the end of an execution. import click def echo(message): click.echo(message) def sub_echo(message): click.echo(' ' + message) def hiss(message): click.secho('Error: ' + message, fg='red') return False def rattle(message): click.secho(message, blink=True, bold=True, fg='white', bg='blue')
# Temperature/Humidity analysis program to read in data from a spreadsheet # Plot the data in a static HTML output file # Author: Lucretia Field # Date: July 2018 import pandas as pd import matplotlib as plt import numpy as np from datetime import datetime, timedelta as dt from pathlib import Path from bokeh.plotting import figure, output_file, show from bokeh.layouts import row, widgetbox, gridplot from bokeh.models import HoverTool from bokeh.models.widgets import Select, RangeSlider my_data = pd.DataFrame() # create empty data frame to populate with read in values my_input = input('Enter folder name or exit: ') # ask user to pick folder or exit pathlist = Path(my_input).glob('**/*.csv') # gather all files in folder # iterate through the provided folder and load all files to my_data for path in pathlist: path_in_str = str(path) my_file = pd.read_csv(path, parse_dates=['Timestamp for sample frequency every 15 min']) # read in data from chosen folder my_file.set_index(keys='Timestamp for sample frequency every 15 min', drop=True, inplace=True) # set time as index my_data = my_data.append(my_file) # append the data to dataframe 'my_data' my_data = my_data.sort_values(['Timestamp for sample frequency every 15 min'], ascending=True) # sort the data print(my_data) # define temperature and humidity data temp = my_data[my_data.columns[0]] humidity = my_data[my_data.columns[1]] # output to static HTML file output_file("output.html") # create two new plots with a title and axis labels p1 = figure(title="Temperature over Time", plot_width=800, x_axis_type='datetime', x_axis_label='Date and Time', y_axis_label='Temperature (deg F)') p1.xaxis[0].ticker.desired_num_ticks = 20 #set number of marks in graphs p1.yaxis[0].ticker.desired_num_ticks = 20 p2 = figure(title="Humidity over Time", plot_width=800, x_axis_type='datetime', x_axis_label='Date and Time', y_axis_label='Humidity (%)', x_range=p1.x_range) p2.xaxis[0].ticker.desired_num_ticks = 20 p2.yaxis[0].ticker.desired_num_ticks = 20 # add a line renderer with legend and line thickness p1.line(x=my_data.index, y=temp, line_width=2) p2.line(x=my_data.index, y=humidity, line_width=2) select = Select(title="Choose Lab and Sensor:", value="Demo Sensor 1", options=["Demo Sensor 1", "Demo Sensor 2", "Eng Sensor 1", "Eng Sensor 1"]) range_slider = RangeSlider(start=0, end=10, value=(1,9), step=.1, title="Date") grid = gridplot([[p1,p2],[widgetbox(select),widgetbox(range_slider)]]) # show the results show(grid)
class Node(object): def __init__(self, data): self.data = data self.height = 0 self.leftChild = None self.rightChild = None class AVLTree(object): traversedData = [] def __init__(self): self.root = None def calculate_height(self, node): if not node: return -1 else: node.height = max(self.calculate_height(node.leftChild), self.calculate_height(node.rightChild))+1 return max(self.calculate_height(node.leftChild), self.calculate_height(node.rightChild))+1 def calcBalance(self, node): """ If returns < 0, a tree is heavier on the right side If returns > 0, a tree is heavier on the left side :param node: :return: integer """ if not node: return 0 return self.calculate_height(node.leftChild) - self.calculate_height(node.rightChild) def rotateRight(self, node): print("Rotating right on the node", node.data) tempLeftChild = node.leftChild t = tempLeftChild.rightChild tempLeftChild.rightChild = node node.leftChild = t node.height = self.calculate_height(node) tempLeftChild.height = self.calculate_height(tempLeftChild) return tempLeftChild def rotateLeft(self, node): print("Rotating left on the node", node.data) tempRightChild = node.rightChild t = tempRightChild.leftChild tempRightChild.leftChild = node node.rightChild = t node.height = self.calculate_height(node) tempRightChild.height = self.calculate_height(tempRightChild) return tempRightChild def insert(self, data): self.root = self.insert_node(data, self.root) def insert_node(self, data, node): if not node: print("inserted", data) return Node(data) if data < node.data: print("node to left", node.data) node.leftChild = self.insert_node(data, node.leftChild) else: print("node to right", node.data) node.rightChild = self.insert_node(data, node.rightChild) node.height = self.calculate_height(node) balance = self.calcBalance(node) while balance < -1 or balance > 1: tmpnode = self.settle_violation(data, node) print("checking balance") print(tmpnode.data) balance = self.calcBalance(tmpnode) node = tmpnode print("balance is good on", node.data) return node def settle_violation(self, data, node): balance = self.calcBalance(node) if balance < -1 and not node.rightChild.leftChild: print("Rotating left") node = self.rotateLeft(node) print("returning-settled-node", node.data) return node if balance > 1 and not node.leftChild.rightChild: print("Rotating right") node = self.rotateRight(node) print("returning-settled-node", node.data) return node if balance > 1 and node.leftChild and data > node.leftChild.data: print("left-right heavy") node.leftChild = self.rotateLeft(node.leftChild) return self.rotateRight(node) if balance < -1 and node.rightChild and data < node.rightChild.data: print("Right-left heavy") node.rightChild = self.rotateRight(node.rightChild) return self.rotateLeft(node) return node def traverse_in_order(self): if self.root: self.in_order_traverse(self.root) tempTraversedData = self.traversedData self.traversedData = [] print(tempTraversedData) return tempTraversedData def in_order_traverse(self, node): if node.leftChild: self.in_order_traverse(node.leftChild) self.traversedData.append(node.data) if node.rightChild: self.in_order_traverse(node.rightChild) def get_min(self): if self.root: return self.min_get(self.root) def min_get(self, node): if node.leftChild: return self.min_get(node.leftChild) return node def get_max(self): if self.root: return self.max_get(self.root) def max_get(self, node): if node.rightChild: return self.max_get(node.rightChild) return node def remove_node(self, data): self.root = self.node_remove(self.root, data) def node_remove(self, node, data): print("im at node", node.data, "using", data) if data > node.data: node.rightChild = self.node_remove(node.rightChild, data) if data < node.data: node.leftChild = self.node_remove(node.leftChild, data) if data == node.data: if node.leftChild and node.rightChild: print("Deleting a parent node with both children", node.data) tmpNode = self.max_get(node.leftChild) node.data = tmpNode.data node.leftChild = self.node_remove(node.leftChild, node.data) return node if not node.leftChild and not node.rightChild: print("Deleting a leaf node", node.data) del node return None if node.leftChild: print("Deleting a node with a left child", node.data) tmpNode = node.leftChild del node return tmpNode if node.rightChild: print("Deleting a node with a right child", node.data) tmpNode = node.rightChild del node return tmpNode print("about to calculate balance on", node.data, "using", data) node.height = self.calculate_height(node) balance = self.calcBalance(node) while balance < -1 or balance > 1: tmpnode = self.settle_violation(data, node) print("checking balance") print(tmpnode.data) balance = self.calcBalance(tmpnode) node = tmpnode print("balance is good on", node.data) return node
#Program to calculate the volume of the sphere with radius 5 cm. Solution: π = 3.14 r= 5 V= (4/3)*π* r**3 print('The volume of the sphere with radius 5 is: ',V)
Q. Write a function called cumulative_sum that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. Solution: def cummulative_sum(n): new_list = [] sum_1ist = 0 for each in n: sum_1ist += each new_list.append(sum_1ist) return new_list t = [1, 2, 3] print(f"original list: {t}") print(f"Cummulative sum list: {cummulative_sum(t)}")
def marriage_point_calculator(): a = str(input("Have you seen the joker or not? (Y/N)")) if a.lower()=="y": x = int(input("Your Maal: ")) y = int(input("Total Maal: ")) z = int(input("Total number of players:")) if x * z > y: return "You Win:", (x * z) - (y + 3) elif x * z < y: return "Your net loss is:", (y + 3) - (x * z) else: y = int(input("Total Maal: ")) return "Your net loss is", (y + 10) print(marriage_point_calculator())
Q. Program to sort a dictionary by key. Solution: info = {'Name':'Nishesh Thakuri', 'Address':'Gothatar', 'Course name':'Python',} for key in sorted(info): print("%s: %s" % (key, info[key]))
Q. Python script to sort (ascending and descending) a dictionary by value Solution: import operator d = {8: 9, 3: 4, 4: 3, 2: 1, 1: 0} print('Original dictionary :',d) sort_d = sorted(d.items(), key=operator.itemgetter(0)) print('Dictionary in ascending order by value : ',sort_d) sort_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True) print('Dictionary in descending order by value : ',sort_d)
Q.Program to calculate a dog's age in dog's years. Note: For the first two years, a dog year is equal to 10.5 human years. After that, each dog year equals 4 human years. Solution: human_age = int(input("Input a dog's age in human years: ")) if human_age < 0: print("Age must be positive number.") exit() elif human_age <= 2: dog_age = human_age * 10.5 else: dog_age = 21 + (human_age - 2)*4 print("The dog's age in dog's years is", dog_age)
Q. Program to check whether an element exists within a tuple. Solution: tup = ("a", "e", "i", "o", "u") print("o" in tup) print(4 in tup)
Q.Program to add an item in a tuple. Solution: tup = (4, 6, 2, 8, 3, 1) print(tup) tup = tup + (9,) print(tup) tup = tup[:5] + (15, 20, 25) + tup[:5] print(tup)
Q.Function to find the Max of three numbers. Solution: def max_of_two( x, y ): if x > y: return x return y def max_of_three( x, y, z ): return max_of_two( x, max_of_two( y, z ) ) print(max_of_three(12, 10, 9))
#IMPORTS import matplotlib.pyplot as plt import numpy as np #FIRST EXAMPLE #Days of the week: days = [1, 2, 3, 4, 5, 6,7] # Your Money: money_spent = [1000, 1200, 1500, 1080, 1400, 1650, 1350] # Your Friend's Money: money_spent_2 = [900, 1500, 1200, 1050, 950, 1250, 1000] # Create figure: fig = plt.figure(figsize=(15,8)) # Plot first week expenses: plt.plot(days, money_spent) # Plot second week expenses plt.plot(days, money_spent_2) # Display the result: plt.title('Company Expenditure Comparison') plt.legend(['First week', 'Second week']) plt.savefig('Visualizations Basics Plots/plot_1.jpg') plt.show() #SECOND EXAMPLE # Create figure: fig2 =plt.figure(figsize=(15,8)) # Plot your money: plt.plot(days, money_spent,color='purple', linestyle='--', marker='o') # Plot your friend's money: plt.plot(days, money_spent_2,color='#045a71', linestyle=':', marker='o') # Display the result: ax = plt.subplot() ax.set_xticks(range(1,8)) ax.set_xticklabels(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday',' Sunday']) plt.title('Company Expenditure Comparison') plt.legend(['First week', 'Second week']) plt.savefig('Visualizations Basics Plots/plot_2.jpg') plt.show() #THIRD EXAMPLE # Create figure: fig3 = plt.figure(figsize=(15,8)) # Plot your money: plt.plot(days, money_spent,color='purple', linestyle='--', marker='o') # Plot your friend's money: plt.plot(days, money_spent_2,color='#045a71', linestyle=':', marker='o') # Display the result: ax = plt.subplot() ax.set_xticks(range(1,8)) ax.set_xticklabels(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday',' Sunday']) plt.title('Monday-Wednesday Company Expenditure') plt.legend(['First week', 'Second week']) plt.axis([1,3,900,1600]) plt.savefig('Visualizations Basics Plots/plot_3.jpg') plt.show() #SUBPLOTS => PARAMETERS (number of rows of subplots, number of columns of subplots, index of subplot) x = [1,2,3,4] y = [2,5,6,3] plt.figure(figsize=(15,8)) plt.subplot(1,2,1) plt.plot(x,y,color='red',linestyle='--') plt.axis([0,5,0,7]) # PRIMEROS DOS SON DE Y, SEGUNDOS 2 SON DE X plt.title('First Plot') plt.figure(figsize=(15,8)) plt.subplot(1,2,2) plt.plot(x,y, color='steelblue', linestyle=':') plt.axis([0,5,0,7]) plt.title('Second Plot') plt.savefig('Visualizations Basics Plots/Plots_4.jpg') plt.show() #TEMPERATURE AND FLIGHTS EXAMPLE from matplotlib import pyplot as plt months = range(12) temperature = [37, 38, 40, 53, 62, 71, 78, 74, 69, 56, 47, 48] flights_to_hawaii = [1100, 1300, 1200, 1400, 800, 700, 450, 500, 450, 900, 950, 1100] # Create figure: fig4 = plt.figure(figsize=(15,8)) # Display the result: plt.subplot(1,2,1) plt.plot(months,temperature,color='steelblue',linestyle='--') plt.xlabel('Months') plt.ylabel('Temperature') plt.title('Temperature Representation') plt.subplot(1,2,2) plt.plot(months,flights_to_hawaii,color='red',marker='o') plt.xlabel('Month') plt.ylabel('Flights Summary') plt.title('Flights per month') plt.savefig('Visualizations Basics Plots/plot_5.jpg') plt.show() #SUBPLOTS ADJUSTMENT """ We can customize the spacing between our subplots to make sure that the figure we create is visible and easy to understand. To do this, we use the plt.subplots_adjust() command. .subplots_adjust() has some keyword arguments that can move your plots within the figure: - left — the left-side margin, with a default of 0.125. You can increase this number to make room for a y-axis label - right — the right-side margin, with a default of 0.9. You can increase this to make more room for the figure, or decrease it to make room for a legend - bottom — the bottom margin, with a default of 0.1. You can increase this to make room for tick mark labels or an x-axis label - top — the top margin, with a default of 0.9 - wspace — the horizontal space between adjacent subplots, with a default of 0.2 - hspace — the vertical space between adjacent subplots, with a default of 0.2 """ from matplotlib import pyplot as plt x = range(7) straight_line = [0, 1, 2, 3, 4, 5, 6] parabola = [0, 1, 4, 9, 16, 25, 36] cubic = [0, 1, 8, 27, 64, 125, 216] plt.figure(figsize=(15,8)) plt.subplot(2,1,1) plt.plot(x,straight_line,color='purple',linestyle='--') plt.xlabel('Range') plt.ylabel("Line") plt.title('Example Graph') plt.savefig('Visualizations Basics Plots/plot_6.jpg') plt.subplot(2,2,3) plt.plot(x,parabola, color='green',linestyle=':') plt.xlabel("Range 1") plt.ylabel("Line") plt.savefig('Visualizations Basics Plots/plot_7.jpg') plt.subplot(2,2,4) plt.plot(x,cubic, color='red', linestyle='--') plt.xlabel("Range 2") plt.ylabel("Line 2") plt.grid() plt.subplots_adjust(hspace=0.35,bottom=0.2,wspace=0.35) plt.show() plt.savefig('Visualizations Basics Plots/plot_8.jpg') #LEGENDS AND LABELING """ When we have multiple lines on a single graph we can label them by using the command plt.legend(). plt.legend() can also take a keyword argument loc, which will position the legend on the figure ('BEST', 'UPPER RIGHT', 'LOWER CENTER', ETC). """ months = range(12) hyrule = [63, 65, 68, 70, 72, 72, 73, 74, 71, 70, 68, 64] kakariko = [52, 52, 53, 68, 73, 74, 74, 76, 71, 62, 58, 54] gerudo = [98, 99, 99, 100, 99, 100, 98, 101, 101, 97, 98, 99] plt.figure(figsize=(15,8)) plt.plot(months, hyrule) plt.plot(months, kakariko) plt.plot(months, gerudo) plt.savefig('Visualizations Basics Plots/plot_9.jpg') # LEGEND EXAMPLE legend_labels = ["Hyrule", "Kakariko", "Gerudo Valley"] plt.legend(legend_labels, loc=8) plt.show() plt.figure(figsize=(15,8)) #MODIFY X AND Y TICKS AND LABELS ax = plt.subplot() plt.plot([1, 3, 3.5], [0.1, 0.6, 0.8], 'o') ax.set_xticks([1, 2, 4]) ax.set_yticks([0.1, 0.6, 0.8]) ax.set_yticklabels(['10%', '60%', '80%']) plt.savefig('Visualizations Basics Plots/plot_10.jpg') #EXAMPLE OF TICKS AND LABELS from matplotlib import pyplot as plt month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"] months = range(12) conversion = [0.05, 0.08, 0.18, 0.28, 0.4, 0.66, 0.74, 0.78, 0.8, 0.81, 0.85, 0.85] ax = plt.subplot() ax.set_xticks(months) ax.set_xticklabels(month_names) ax.set_yticks([0.1,0.25,0.5,0.75]) ax.set_yticklabels(['10%', '25%', '50%','75%']) plt.xlabel("Months") plt.ylabel("Conversion") plt.plot(months, conversion) plt.show() plt.savefig('Visualizations Basics Plots/plot_11.jpg') #FIGURES """ Previously, we learned how to put two sets of axes into the same figure. Sometimes, we would rather have two separate figures. We can use the command plt.figure() to create new figures and size them how we want. We can add the keyword figsize=(width, height) to set the size of the figure, in inches. - plt.figure(figsize=(4, 10)) Once we’ve created a figure, we might want to save it so that we can use it in a presentation or a website. We can use the command plt.savefig() to save out to many different file formats, such as png, svg, or pdf. After plotting, we can call plt.savefig('name_of_graph.png') """ from matplotlib import pyplot as plt word_length = [8, 11, 12, 11, 13, 12, 9, 9, 7, 9] power_generated = [753.9, 768.8, 780.1, 763.7, 788.5, 782, 787.2, 806.4, 806.2, 798.9] years = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009] plt.close('all') plt.figure() plt.plot(years, word_length) plt.savefig('Visualizations Basics Plots/plot_14.jpg') plt.figure(figsize=(15,8)) plt.plot(years, power_generated) plt.savefig('Visualizations Basics Plots/plot_12.jpg') #GENERALIZING SUBPLOTS months = range(12) temperature = [36, 36, 39, 52, 61, 72, 77, 75, 68, 57, 48, 48] flights_to_hawaii = [1200, 1300, 1100, 1450, 850, 750, 400, 450, 400, 860, 990, 1000] plt.figure(figsize=(15,8)) plt.plot(months,temperature,color='steelblue',linestyle='--') plt.xlabel('Month') plt.ylabel('Temperature') plt.title('Temperature per month') plt.savefig('Visualizations Basics Plots/plot_13.jpg') plt.show() ;
import queue import collections #Queue O(1) insert, O(1) remove, FIFO. data = queue.Queue() data.put(3) data.get() data.qsize() data.empty() #stack, O(1) insert, O(1) remove, LILO. Can just use list. #PriorityQueue, O(1) find min/max, O(logn) insert, delete/extract min/max, lookup/delete O(n) #lowest valued entries are retrieved first. q = queue.PriorityQueue() q.put((100, 'a not agent task')) q.put((5, 'a highly agent task')) q.put((10, 'an important task')) q.get() #Deque, O(1) insert and remove data = collections.deque() #append, appendleft, pop, popleft, clear, count(x), support indexing, extendleft, remove(value), reverse, rotate(n): rotate n step. #collections.defaultdict(int) #collections.OrderedDict(), Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. # When iterating over an ordered dictionary, the items are returned in the order their keys were first added. #a = collections.OrderedDict() #a.popitem(last = True), last = True: LILO, otherwise FIFO. #Counter, Counter([iterable-or-mapping]), can counter list or string, dict, etc. #Setting a count to zero does not remove an element from a counter. Use del to remove it entirely counter = collections.Counter() #c = Counter(a=4, b=2, c=0, d=-2) #c.elements() -> ['b', 'b', 'a', 'a', 'a', 'a'] #Counter('abracadabra').most_common(3), return most common 3 items with its count. #c.substract(d) #c & d, c | d, get the min or max. #c.clear() #c += Counter(), remove all 0 and negative counters.
""" Generate collections of scattered points in Cartesian coordinates. """ import numpy as np def scatter_circular(size, R1=3, R2=None, angle=0, reset_random=True): """ Generate a collection of random points distributed in a circle or elipse. Parameters ---------- size : int Number of points R1 : float Radius of the circle R2 : float If not the same as R1, then the output is an elipse angle : 0, float, optional Angle to rotate the coordinates of all the points, should be [0, 180) Returns ------- 2d array A collection of scattered points with the shape of 2xsize. """ if reset_random: np.random.seed(0) _a = np.random.random_sample(size) _b = np.random.random_sample(size) points = np.zeros((2, size)) for i in range(size): a = min(_a[i], _b[i]) b = max(_a[i], _b[i]) points[0, i] = b*R1*np.cos(2*np.pi*a/b) points[1, i] = b*R2*np.sin(2*np.pi*a/b) radian = angle/180*np.pi rotate_mat = np.array([[np.cos(radian), -np.sin(radian)], [np.sin(radian), np.cos(radian)]]) points = rotate_mat @ points return points def scatter_3D(size, **kwargs): """ Generate a collection of random points in a 3-D Cartesian coordinate. Parameters ---------- size : int Number of points Other Parameters ---------------- **kwargs This method takes keyward arguments from ``scatter_circle`` Returns ------- 2d array A collection of scattered points with the shape of 3xsize. """ points = scatter_circular(size, **kwargs) _z = np.random.random_sample(size) return np.vstack((points, _z))
word = input() for i in word: print("'{}'".format(i))
nums = [0,1,2] a = 0 b = 1 c = 2 ordersList = [] while len(ordersList) < 1: for a in nums: for b in nums: if b == a: continue for c in nums: if c == a or c == b: continue #print(str(a) + str(b) + str(c)) ordersList.append(str(a) + str(b) + str(c)) print(ordersList)
day = 0 month = 1 year = 1901 dayIndex = 1 days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] sundays = 0 while year < 2001: day += 1 dayIndex += 1 if dayIndex > 6: dayIndex = 0 if month == 1: if day > 31: day = 1 month += 1 elif month == 2: if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): if day > 29: day = 1 month += 1 else: if day > 28: day = 1 month += 1 elif month == 3: if day > 31: day = 1 month += 1 elif month == 4: if day > 30: day = 1 month += 1 elif month == 5: if day > 31: day = 1 month += 1 elif month == 6: if day > 30: day = 1 month += 1 elif month == 7: if day > 31: day = 1 month += 1 elif month == 8: if day > 31: day = 1 month += 1 elif month == 9: if day > 30: day = 1 month += 1 elif month == 10: if day > 31: day = 1 month += 1 elif month == 11: if day > 30: day = 1 month += 1 elif month == 12: if day > 31: day = 1 month += 1 if month > 12: month = 1 year += 1 if day == 1 and dayIndex == 0: sundays += 1 print(day, month, year, days[dayIndex]) print(sundays)
import unittest from lib.checkers import input_type_checker, card_checker, convert_case, is_list_unique class TestCheckers(unittest.TestCase): """ Unit tests for checker methods """ def test_valid_input_true(self): """ Checks if the input is a list of len > 2 for board and len == 2 for hand :return: """ board = ['As', 'Ac', 'Ad'] hand = ['Ah', 'Kd'] self.assertTrue(input_type_checker(board, hand)) def test_valid_input_false_board_wrong(self): """ Checks if the method can detect wrong input :return: """ board = ['As', 'Ac'] hand = ['Ah', 'Kd'] self.assertFalse(input_type_checker(board, hand)) def test_valid_input_false_hand_wrong(self): """ Checks if the method can detect wrong input :return: """ board = ['As', 'Ac', 'Ad'] hand = ['Ah'] self.assertFalse(input_type_checker(board, hand)) def test_convert_case(self): """ Checks is casing is properly converted :return: """ board = ['aS', 'ad', 'Ac'] self.assertEqual(['As', 'Ad', 'Ac'], convert_case(board)) def test_valid_card_true(self): """ Checks if valid cards are passed :return: """ list_of_cards = ['aS', 'Ac'] self.assertTrue(card_checker(list_of_cards)) def test_valid_card_false(self): """ Checks if invalid cards are caught :return: """ list_of_cards = ['Z3', 'Ax'] self.assertFalse(card_checker(list_of_cards)) def test_is_list_unique(self): """ Checks if the list is unique :return: """ list_1 = [1,2,3,4,5] list_2 = [1,2,2,3,3,4,5] list_3 = ['Ac', 'Ah', 'Ad', 'As'] list_4 = ['Ac', 'Ac', 'Ah'] self.assertTrue(is_list_unique(list_1)) self.assertTrue(is_list_unique(list_3)) self.assertFalse(is_list_unique(list_2)) self.assertFalse(is_list_unique(list_4)) if __name__ == '__main__': unittest.main()
#!/usr/bin/python3 ''' This program defines functions that can be used to collect data on a movie from a given title and date. The information is collected from imdb and also provides functions to retrieve the rotten tomato score and imdb score ''' from urllib.request import Request, urlopen import urllib from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.firefox.options import Options from unidecode import unidecode import time import re import logging import socket logging.basicConfig(filename='/var/log/movieScrape/output.log', format='%(asctime)s:%(message)s', level=logging.INFO) timeout = 120 socket.setdefaulttimeout(timeout) # This function retrieves a movies url on IMDB using a title with a date year # It will use IMDB advance search feature and show only movies within the date # range of plus or minus one year. The movie will be found by searching for a # link that has the same text as the movie title. def getIMDBURL(title): logging.info(f'Retrieving imdb url for: {title}') date = title[-5:-1] title = title[:-6] if date == '(TBA': logging.info(f'{title} has not been released yet. Writing to file and ' f'skipping.') with open('/var/log/movieScrape/unreleased.log', 'w') as f: f.write(f'{title}\n') return None # This removes the foreign title in parenthesis of any foreign movies title = re.sub(r'\([^)]*\)', '', title) title = title.replace(' ', '%20') url = (f'http://www.imdb.com/search/title?adult=include&release_date=' f'{str(int(date)-1)},{str(int(date)+1)}&title={title}&' f'title_type=feature,short,documentary') # For foreign characters in movie title url = unidecode(url) logging.info(f'Constructed search url for {title}: {url}') headers = {"Accept-Language":"en-US,en;q=.5"} try: req = Request(url, headers = headers) title = title.replace('%20', ' ').strip() page = urlopen(req) soup = BeautifulSoup(page, 'html.parser') movie_link = soup.find('a', text = title) if movie_link: logging.info(f'Page link for {title} found: {movie_link}') movie_link = movieLink['href'] movie_link = movieLink.split('/')[2] return movie_link else: logging.info(f'Page link not found for {title}.') return None except urllib.error.URLError as e: logging.ERROR(f'URLError for {title}. \n URL: {url}') logging.ERROR(e) with open('/var/log/movieScrape/URLerror.log', 'w') as f: f.write(f'{title}: {url}\n') except urllib.error.HTTPError as e: logging.ERROR(f'HTTPError for {title}. \n URL: {url}') logging.ERROR(e) with open('/var/log/movieScrape/HTTPError.log', 'w') as f: f.write(title + ': HTTPError') def getBudget(soup): budget = soup.find('h4', text = 'Budget:') if budget: budget = budget.parent.contents[2].strip() budget = budget.replace(',','')[1:] budget = list(filter(str.isdigit, budget)) budget = int(''.join(budget)) return budget else: return None def getRevenue(soup): gross = soup.find('h4', text = 'Gross:') if gross: gross = gross.parent.contents[2].strip().replace(',','')[1:] return int(gross) else: return None # RT rating was challenging because the raw html did not contain the data. # The data I needed was generated by javascrip after the page was loaded def getRTRating(title, date): logging.INFO(f'Retrieving RT Rating for {title}') title.replace(' ', '%20') options = Options() options.add_argument("--headless") binary = FirefoxBinary('/usr/lib/firefox/firefox') browser = webdriver.Firefox(firefox_options=options, firefox_binary=binary) url = f'https://www.rottentomatoes.com/search/?search={title}' try: browser.get(url) time.sleep(1) html = browser.page_source browser.quit() soup = BeautifulSoup(html, 'lxml') results = soup.find('section', id = 'movieSection') if not results: logging.INFO(f'Could not find RT rating for {title}') return None results = results.find_all('div', class_ = 'details') if not results: logging.INFO(f'Could not find RT rating for {title}') return None # Search all returned movies on the page and only return the information # if the date and title match for result in results: searchTitle = unidecode(result.span.a.contents[0]) if not searchTitle: logging.INFO(f'Could not find RT rating for {title}') return None searchDate = result.find('span', class_ = 'movie_year') if not searchDate: logging.INFO(f'Could not find RT rating for {title}') return None searchDate = searchDate.contents[4] title = title.replace('%20', ' ') title = title.strip() # If the date plus or minus 1 of search results is within movie date AND # the title matches or is within the title then it is a match if (((str(searchDate) == date) or (str(searchDate) == str(int(date) -1)) or (str(searchDate) == str(int(date) + 1))) and ((searchTitle.lower()) == title.lower() or (title in searchTitle))): rating = result.parent rating = rating.find('span', class_ = 'tMeterScore') if not rating: logging.INFO(f'Could not find RT rating for {title}') return None rating = rating.contents[1] return int(rating) break except socket.error as socketerror: logging.ERROR(f"Timeout for {title}") logging.ERROR(socketerror) with open('/var/log/movieScrape/timeoutError.log', 'w') as f: f.write(f'{title}') # A function that collects all movie titles and dates on any specific list of # imdb (like top horror movies) def getimdbTopList(url): page = urlopen(url) soup = BeautifulSoup(page, "html.parser") titles = soup.find_all('td', class_='titleColumn') dates = soup.find_all('span', class_='secondaryInfo') ids = soup.find_all('div', class_='wlb_ribbon') titleList = [] dateList = [] linkList = [] for i, movies in enumerate(titles): titleList.append(movies.a.contents[0]) dateList.append(str(dates[i].contents[0])) linkList.append(ids[i]['data-tconst']); return titleList, dateList, linkList def getimdbList(url, date=None): page = urlopen(url) soup = BeautifulSoup(page, "html.parser") title_headers = soup.find_all('div', class_='lister-item-content') titles = [] links = [] for title in title_headers: movie_title = title.h3.a.contents[0] year = title.h3.find('span', class_='lister-item-year').contents[0] titles.append(f'{movie_title} {year}') links.append(title.div.find('div', class_='ratings-user-rating').span['data-tconst']) return titles, links # A function that gets all movie titles and dates from any given RT list # (like top 100 movies of 2016) def getRTList(url): movieList = [] page = urlopen(url) soup = BeautifulSoup(page, 'html.parser') titles = soup.find('table', class_ = 'table').find_all('a') for i, movies in enumerate(titles): title = str(movies.contents[0]) title = title.strip() movieList.append(title) return movieList # A function that gets all movie titles and dates from any given metacritic list # (like top thrillers of all time) def getMetaList(url): movieList = [] req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) page = urllib.request.urlopen(req) soup = BeautifulSoup(page, 'html.parser') titles = soup.find_all('div', class_ = 'title') dates = soup.find_all('td', class_ = 'date_wrapper') del titles[0] for i, movies in enumerate(titles): title = movies.a.contents[0] date = dates[i].span.contents[0].split(' ') date = f'({date[len(date)-1]})' title = title + " " + date movieList.append(title) return movieList
import copy # The algorithms work by swapping the values of the blocks with the empty areas to move the block # For example, when the "red" function is called with the direction set to 'down', it swaps the top 2 values (4, 4) # with the two zeros below it # Controls the movement of the red block def red(direction, position, state): row, col = position # Position is a tuple containing the row and column of the block state_copy = copy.deepcopy(state) if direction == 'down': state_copy[row][col] = state[row+2][col] state_copy[row + 2][col] = state[row][col] state_copy[row][col+1] = state[row+2][col+1] state_copy[row+2][col+1] = state[row][col+1] return state_copy elif direction == 'up': state_copy[row-1][col] = state[row + 1][col] state_copy[row + 1][col] = state[row-1][col] state_copy[row-1][col + 1] = state[row + 1][col + 1] state_copy[row + 1][col + 1] = state[row - 1][col + 1] return state_copy elif direction == 'left': state_copy[row][col+1] = state[row][col-1] state_copy[row][col - 1] = state[row][col+1] state_copy[row+1][col + 1] = state[row+1][col - 1] state_copy[row+1][col - 1] = state[row+1][col + 1] return state_copy elif direction == 'right': state_copy[row][col + 2] = state[row][col] state_copy[row][col] = state[row][col + 2] state_copy[row+1][col + 2] = state[row+1][col] state_copy[row + 1][col] = state[row+1][col + 2] return state_copy # Controls the movement of a blue block def blue(direction, position, state): row, col = position state_copy = copy.deepcopy(state) if direction == 'down': state_copy[row][col] = state[row+1][col] state_copy[row+1][col] = state[row][col] return state_copy elif direction == 'up': state_copy[row][col] = state[row - 1][col] state_copy[row - 1][col] = state[row][col] return state_copy elif direction == 'right': state_copy[row][col] = state[row][col+1] state_copy[row][col+1] = state[row][col] return state_copy elif direction == 'left': state_copy[row][col] = state[row][col - 1] state_copy[row][col - 1] = state[row][col] return state_copy # Controls the movement of the horizontal green block def horizontal_green(direction, position, state): row, col = position state_copy = copy.deepcopy(state) if direction == 'up': state_copy[row][col] = state[row-1][col] state_copy[row-1][col] = state[row][col] state_copy[row][col+1] = state[row-1][col+1] state_copy[row-1][col+1] = state[row][col+1] return state_copy elif direction == 'down': state_copy[row][col] = state[row + 1][col] state_copy[row + 1][col] = state[row][col] state_copy[row][col + 1] = state[row + 1][col + 1] state_copy[row + 1][col + 1] = state[row][col + 1] return state_copy elif direction == 'right': state_copy[row][col] = state[row][col+2] state_copy[row][col+2] = state[row][col] return state_copy elif direction == 'left': state_copy[row][col + 1] = state[row][col - 1] state_copy[row][col - 1] = state[row][col + 1] return state_copy # Controls the movement of teh vertical green block def vertical_green(direction, position, state): row, col = position state_copy = copy.deepcopy(state) if direction == 'up': state_copy[row+1][col] = state[row-1][col] state_copy[row-1][col] = state[row+1][col] return state_copy elif direction == 'down': state_copy[row][col] = state[row+2][col] state_copy[row+2][col] = state[row][col] return state_copy elif direction == 'right': state_copy[row][col] = state[row][col+1] state_copy[row][col + 1] = state[row][col] state_copy[row+1][col] = state[row+1][col+1] state_copy[row + 1][col + 1] = state[row+1][col] return state_copy elif direction == 'left': state_copy[row][col] = state[row][col - 1] state_copy[row][col - 1] = state[row][col] state_copy[row + 1][col] = state[row + 1][col - 1] state_copy[row + 1][col - 1] = state[row + 1][col] return state_copy # Move block given a color def move(color, direction, position, state, axis=None): if color == 'red': return red(direction, position, state) elif color == 'blue': return blue(direction, position, state) elif color == 'green' and axis == 'horizontal': return horizontal_green(direction, position, state) elif color == 'green' and axis == 'vertical': return vertical_green(direction, position, state)
# This program converts Fahrenheit to Calsius fahr_temp = float(input("Fahrenheit temperature: ")) celc_temp = (fahr_temp - 32.0) * ( 5.0 / 9.0) print("Celsius temperature: ", celc_temp)
import sys from print import printErr, help def checkArgs(args): if (len(args) != 3): if(len(args) == 1 and args[0] == "-h"): help() else: printErr("Not enough arguments. Check ./209poll -h for more informations.") else: try: args[0] = int(args[0]) args[1] = int(args[1]) args[2] = float(args[2]) if (args[0] <= 0 or args[1] <= 0): printErr("Population size or sample size must be positive.") if (args[1] > args[0]): printErr("Sample size cannot be greater than Population size.") if (args[2] < 0 or args[2] > 100): printErr("Percentage of voting intentions must be between 0 and 100") except ValueError: printErr("Wrong type of arguments. int, int, float must be used.") return args
import sys def help(): print("USAGE\n ./202unsold a b\n") print("DESCRIPTION") print("\t a\tconstant computed from the past results") print("\t b\tconstant computed from the past results") def checkPiece(): if(len(sys.argv)!= 3): if (len(sys.argv) == 2 and sys.argv[1] == "-h"): help() else: print("The number of args should be equal to 3.") exit(84) else: try: a = int(sys.argv[1]) b = int(sys.argv[2]) if (a <= 50 or b <= 50): print("a and b should be greater than 50.") exit(84) except ValueError: print("a and b must be integers greater than 50.") exit(84) return (1)
from math import * def printResult(combinaison, value, res): print("chances to get a " + value + " " + combinaison + ": %0.2f%%" % (res)) def binomiale(a, b): res = (factorial(a) / (factorial(b) * factorial(a-b))) * pow(1/6, b) * pow(5/6, a-b) return (res) def calcProba(list, c, nb): res = 0 times = list.count(int(nb)) if (times >= c): res = 1 else: for i in range(c - times, 5 - times + 1): res += binomiale(5 - times, i) return (res * 100) def calcProbaFull(x, y): c = factorial(5 - x - y) / (factorial(3 - y) * factorial((5 - y - x) - (3 - x))) return (c) / 6**(5 - x - y) * 100
import sys from combinaisons import launchGame def help(): print("USAGE\n ./201yams d1 d2 d3 d4 d5 c\n") print("DESCRIPTION") print("\t d1\t value of the first die (0 if not thrown)") print("\t d2\t value of the second die (0 if not thrown)") print("\t d3\t value of the third die (0 if not thrown)") print("\t d4\t value of the fourth die (0 if not thrown)") print("\t d5\t value of the fifth die (0 if not thrown)") print("\t c\t expected combination") def checkDices(): a = 0 if (len(sys.argv) > 1 and sys.argv[1] == "-h"): help() return (0) elif(len(sys.argv) != 7): print("The number of args should be equal to 7.") exit(84) else: for i in range(1, 6): if (int(sys.argv[i]) < 0 or int(sys.argv[i]) > 6): print("Dice number " + str(i) + " should be an integer between 1 and 6.") exit(84) return (1) def checkCombi(dices): list = [] list = sys.argv[6].split('_') combinations = ["pair", "three", "four", "full", "straight", "yams"] if (len(list) == 1 or len(list) > 3): print("The combination should be written as follows: <combination>_A_B") exit(84) elif (len(list) == 2): if(int(list[1]) < 0 or int(list[1]) > 6): print("The first number in expected combination should be an integer between 1 and 6.") exit(84) elif (len(list) == 3): if (list[0] != "full"): print("Only <full> can have two numbers.") exit(84) if(int(list[2]) < 0 or int(list[2]) > 6): print("The second number in expected combination should be an integer between 1 and 6.") exit(84) if list[0] in combinations: launchGame(dices, list) else: print("Combination type should be only one of those : pair, three, four, full, straight, yams") exit(84)
def n_queen(k): global count for i in range(k - 1): # 判斷是否可放置皇后的條件 judge = queen[i] - queen[k - 1] if judge == 0 or abs(k - 1 - i) == abs(judge): return if k == n: print(queen) # 輸出皇后放置序列 count += 1 # 解的個數 return for i in range(n): # 放置皇后 queen[k] = i n_queen(k + 1) count = 0 n = 8 # 此處的n為幾,則為幾皇后問題 queen = [0 for _ in range(n)] n_queen(0) print(count)
""" FACTORY: Problem: Uncertainties in types of bjects decisions to be made at runtime regarding what classes to use """ class Dog: """ A simple Dog Class""" def __init__(self, name): self.name = name def speak(self): return 'woof!' class Cat: """ A simple Dog Class""" def __init__(self, name): self.name = name def speak(self): return 'meow!' def get_pet(pet='dog'): """ The factory method.""" pets = {'dog' : Dog('Hope'), 'cat': Cat('Peace')} return pets[pet] d = get_pet('dog') print(d.speak()) c = get_pet('cat') print(c.speak())
# input number as string print ("Please input a number:") x = input() print("Your input:", x) # convert into integer xint = int(x) print("as integer:", xint) # add calculation xsquare = xint * xint print("and squared:", xsquare)
# tax rate 18% # input brutto salary print("please input your brutto salary:") brutto = input() brutto = int(brutto) # calc individual netto & tax with high income statements for higher tax classes if brutto <= 2500: netto = brutto * 0.82 tax = brutto * 0.18 elif brutto <= 4000: netto = brutto * 0.78 tax = brutto * 0.22 else: netto = brutto * 0.74 tax = brutto * 0.26 # output print("Your brutto salary:", brutto) print("Your netto income:", int(netto)) print("paid taxes:", int(tax))
# interupt loop with break for i in 12, -4, 20, 7: if i*i > 200: break print("Number:", i, "square:", i*i) print("end")
#### rng import random random.seed() #### define calcualtion task def task(): a = random.randint(1,100) b = random.randint(1,100) asw = a+b print("The task:", a, "+", b) return asw ### define comment function def comment(ipt, asw): if ipt == asw: print(ipt, "is correct, you Matherfucker!") else: print(ipt, "is the wrong answer, Fuckface!") ##### task c = task() #### init loop & counter n = c+1 count = 0 ###### while loop while n != c: ### add to counter count = count+1 ### input print("Your answer:") i = input() ### integer check try: n = int(i) except: print("Thats not a number, Fuckface!") continue ### comment comment(n, c) ### final summary print("Correct answer:", c) print("You needed", count, "tries!")
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 1: Data Collection df = pd.read_csv("creditcard.csv") print("Data read from file") # 2: Feature Engineering from sklearn.preprocessing import StandardScaler df["normAmount"] = StandardScaler().fit_transform(np.array(df["Amount"]).reshape(-1,1)) df = df.drop(["Time", "Amount"], axis=1) print("Features selected") # 3: Training and Testing Split from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.33, random_state=42) X_train = train.drop("Class", axis=1) y_train = train["Class"] X_test = test.drop("Class", axis=1) y_test = test["Class"] print("Training and Testing Sets Created") # 4: Minority Class Oversampling from imblearn.over_sampling import SMOTE sm = SMOTE(random_state=42) X_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel()) print("Minority Class Oversampled") # 5: Hyperparameter search from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import recall_score, log_loss # 5a: learning rate search learning_rates = [1, 0.5, 0.25, 0.1, 0.05, 0.01] lr_df = pd.DataFrame(columns=["learning_rate", "score", "type"]) loss_df = pd.DataFrame(columns=["learning_rate", "score", "type"]) for lr in learning_rates: print("Learning Rate:", lr) clf = GradientBoostingClassifier(n_estimators=100, learning_rate=lr, max_depth=1, random_state=0) clf.fit(X_train_res, y_train_res) y_train_pred = clf.predict(X_train) y_test_pred = clf.predict(X_test) y_train_score = clf.decision_function(X_train) y_test_score = clf.decision_function(X_test) train_recall = recall_score(y_train, y_train_pred) test_recall = recall_score(y_test, y_test_pred) train_loss = log_loss(y_train, y_train_score) test_loss = log_loss(y_test, y_test_score) print("Train recall:", train_recall) print("Test recall:", test_recall) print("Train loss:", train_loss) print("Test loss:", test_loss, "\n") lr_df = lr_df.append({ "learning_rate": lr, "score": train_recall, "type": "train_recall", }, ignore_index=True) lr_df = lr_df.append({ "learning_rate": lr, "score": test_recall, "type": "test_recall", }, ignore_index=True) loss_df = loss_df.append({ "learning_rate": lr, "score": train_loss, "type": "train_loss", }, ignore_index=True) loss_df = loss_df.append({ "learning_rate": lr, "score": test_loss, "type": "test_loss", }, ignore_index=True) print(lr_df.head()) sns.lineplot(x="learning_rate", y="score", hue="type", data=lr_df) plt.show() sns.lineplot(x="learning_rate", y="score", hue="type", data=loss_df) plt.show() # 5b: n_estimators search estimators = [1, 2, 4, 8, 16, 32, 64, 100] ne_df = pd.DataFrame(columns=["n_estimators", "score", "type"]) ne_loss_df = pd.DataFrame(columns=["n_estimators", "score", "type"]) for ne in estimators: print("n_estimators:", ne) clf = GradientBoostingClassifier(n_estimators=ne, learning_rate=0.5, max_depth=1, random_state=0) clf.fit(X_train_res, y_train_res) y_train_pred = clf.predict(X_train) y_test_pred = clf.predict(X_test) y_train_score = clf.decision_function(X_train) y_test_score = clf.decision_function(X_test) train_recall = recall_score(y_train, y_train_pred) test_recall = recall_score(y_test, y_test_pred) train_loss = log_loss(y_train, y_train_score) test_loss = log_loss(y_test, y_test_score) print("Train recall:", train_recall) print("Test recall:", test_recall) print("Train loss:", train_loss) print("Test loss:", test_loss, "\n") ne_df = ne_df.append({ "n_estimators": ne, "score": train_recall, "type": "train_recall", }, ignore_index=True) ne_df = ne_df.append({ "n_estimators": ne, "score": test_recall, "type": "test_recall", }, ignore_index=True) ne_loss_df = ne_loss_df.append({ "n_estimators": ne, "score": train_loss, "type": "train_loss", }, ignore_index=True) ne_loss_df = ne_loss_df.append({ "n_estimators": ne, "score": test_loss, "type": "test_loss", }, ignore_index=True) sns.lineplot(x="n_estimators", y="score", hue="type", data=ne_df) plt.show() sns.lineplot(x="n_estimators", y="score", hue="type", data=ne_loss_df) plt.show() # Best parameters: learnign_rate = 0.5, n_estimators = s100
# -*- coding: latin-1 -*- from connectfourboard import ConnectFourBoard import unittest class BoardTests(unittest.TestCase): """Test the ConnectFourBoard class""" def setUp(self): """Instantiate a ConnectFourBoard for testing""" self.board = ConnectFourBoard() def playmoves(self, moves): """For each move in moves, play that move on the board.""" for move in moves: self.board.play(move) def verifyboard(self, blacklocations=[], whitelocations=[]): """Verify that the board reflects the expected plays. All verification is done through asserts, no return value. blacklocations and whitelocations are the (row,column) coordinates of each expected piece. Any location not listed in these collections is expected to be empty.""" for location in blacklocations: self.assertEqual(self.board._board[location[0]][location[1]], ConnectFourBoard.blackpiece) for location in whitelocations: self.assertEqual(self.board._board[location[0]][location[1]], ConnectFourBoard.whitepiece) otherlocations = [] for col in range(0,ConnectFourBoard._columns): for row in range(0,ConnectFourBoard._rows): if ([row, col] not in blacklocations) and ([row, col] not in whitelocations): otherlocations.append([row, col]) for location in otherlocations: self.assertEqual(self.board._board[location[0]][location[1]], ConnectFourBoard.emptyspace) def test_one_move(self): """Create a board and play one move""" self.board.play(0) self.verifyboard([[5,0]]) if __name__ == '__main__': unittest.main()
import pandas as pd import numpy as np #Importing DataSet dataset = pd.read_csv("DataSetnanda.csv") X=dataset.iloc[:,1:-1].values y=dataset.iloc[:,-1].values #LabelEncoder and OneHotEncoder from sklearn.preprocessing import LabelEncoder,OneHotEncoder from sklearn.externals import joblib labelencoder=LabelEncoder() X[:,1]=labelencoder.fit_transform(X[:,1]) joblib.dump(labelencoder,'LabelEncoderCategories') onehotencoder=OneHotEncoder(categorical_features=[-2]) X=onehotencoder.fit_transform(X).toarray() joblib.dump(onehotencoder,'OneHotEncoderCategories') #Spliting: from sklearn.model_selection import train_test_split X_train,X_test,Y_train,Y_test=train_test_split(X,y,test_size=0.25,random_state=1348882) #MLModel Training: from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors = 3).fit(X_train, Y_train) joblib.dump(knn,'MLModelKNN') x=np.asarray([0,0,0,0,1,25]).reshape(1,-1) print(knn.predict_proba(x)) """Score is .78,.72,.74,.75,.8,.71,.81,.78"""
from package import Package class HashTable: # This hash table is of the chaining variety # which requires all buckets to be lists def __init__(self, initial_capacity=10): # Initialization involves creating empty buckets # Buckets are initialized as empty lists self.table = [] for i in range(initial_capacity): self.table.append([]) # O(1) time # O(1) space # Insert function def insert(self, item): # Use hash function to return bucket index for insertion bucket = hash(item.id) % len(self.table) # Get the list at the bucket index bucket_list = self.table[bucket] # Append bucket list with new item bucket_list.append(item) # O(n) time # O(1) space # Lookup function def search(self, key): # Use hash function to return bucket index for initial lookup bucket = hash(key) % len(self.table) # Get the list at the bucket index bucket_list = self.table[bucket] # If the id exists in the bucket list, let's get the whole item for item in bucket_list: if item.id == key: # Find the index of the item in the bucket list item_index = bucket_list.index(item) # Return that item! return bucket_list[item_index] # Sad times, the item was not found return None # O(n) time # O(1) space # Removes an item with matching key from the hash table. def remove(self, key): # get the bucket list where this item will be removed from. bucket = hash(key) % len(self.table) bucket_list = self.table[bucket] # remove the item from the bucket list if it is present. for item in bucket_list: if item.id == key: bucket_list.remove(item) # O(n) time # O(n) space # Returns the total number of items in the hash table def __len__(self): length = 0 for i in range(len(self.table)): length += len(self.table[i]) return length
import math def is_prime(n): if n < 2: return False elif n == 2: return True else: for i in range(2, int(math.sqrt(n)+1)): if n % i == 0: return False break return True def twin_prime(n): l = 10 ** (n-1) u = 10 ** n twins = [] for i in range(l, u-2): if is_prime(i) and is_prime(i+2): twins.append(str(i) + ' ') twins.append(str(i+2)) twins.append('\n') return twins n = int(input()) file = open("myFirstFile.txt","w") file.writelines(twin_prime(n)) file.close()
""" Datetime utils. """ from datetime import datetime DT_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" def datetime_to_str(datetime): """ Serialize datetime provided as simplified ISO 8601 (without timezone) string :type datetime: datetime :param datetime: datetime object to convert to string :return: serialized datetime :rtype: str """ return datetime.strftime(DT_FORMAT) def datetime_from_str(str): """ Deserialize datetime from simplified ISO 8601 (without timezone) :type str: str :param str: string to deserialize :return: datetime created of the string provided :rtype: datetime """ return datetime.strptime(str, DT_FORMAT)
from random import shuffle import copy class Sudoku_generator(): def generate_solution(self, grid): """generates a full solution with backtracking""" number_list = [1,2,3,4,5,6,7,8,9] for i in range(0,81): row=i//9 col=i%9 #find next empty cell if grid[row][col]==0: shuffle(number_list) for number in number_list: if self.valid_location(grid,row,col,number): self.path.append((number,row,col)) grid[row][col]=number if not self.find_empty_square(grid): return True else: if self.generate_solution(grid): #if the grid is full return True break grid[row][col]=0 return False def remove_numbers_from_grid(self): """remove numbers from the grid to create the puzzle""" #get all non-empty squares from the grid non_empty_squares = self.get_non_empty_squares(self.grid) non_empty_squares_count = len(non_empty_squares) rounds = 3 while rounds > 0 and non_empty_squares_count >= 17: #there should be at least 17 clues row,col = non_empty_squares.pop() non_empty_squares_count -= 1 #might need to put the square value back if there is more than one solution removed_square = self.grid[row][col] self.grid[row][col]=0 #make a copy of the grid to solve grid_copy = copy.deepcopy(self.grid) #initialize solutions counter to zero self.counter=0 self.solve_puzzle(grid_copy) #if there is more than one solution, put the last removed cell back into the grid if self.counter!=1: self.grid[row][col]=removed_square non_empty_squares_count += 1 rounds -=1 return
from math import sqare print("quadratic function :(a*x^2)+b*x+c") a=float(input("a:")) a=float(input("a:")) b=float(input("b:")) c=float(input("c:")) r=b^2-4*a*c if(r>0): num_roots=2 x1=(((-b)+sqrt(r))/(2*a)) x2=(((-b)-sqrt(r))/(2*a)) print("there are 2 roots:"%fand%f %(x1,x2) elif(r==0): num_roots=1 x=(-b)/2*a print("there is 1 root :",x) else: num_roots=0 print(" no roots ,discriminant<0")
__author__ = 'Lexie Infantino' import random import string def main(*args): #for counting iterations, not important iteration = 0 str = 'Hello, World' # gen string alpha/numeric/puntuation/whitespace ranStr = ''.join([random.choice(string.ascii_letters + string.digits + string.punctuation+ string.whitespace) for n in range(len(str))]) fitLvl = fitness(str, ranStr) # if fit level of new evolution is better, keep new string, other wise ignore. while ranStr != str: tempStr = evolve(ranStr) if fitLvl < fitness(str, tempStr): pass if fitLvl > fitness(str, tempStr): ranStr = tempStr fitLvl = fitness(str, tempStr) iteration += 1 # print every 100th iteration if iteration %100 == 0: print('Iteration ', iteration, ': '+ranStr) print('Iteration ', iteration, ': '+ranStr) ''' generate fitness of randomized string compare to original. square numbers to remove negatives ''' def fitness(str, ranStr): x = 0 tfit = 0 while x != len(str): strx = ord(str[x])**2 rstr = ord(ranStr[x])**2 if(strx > rstr): fit = strx - rstr else: fit = rstr - strx tfit = tfit+fit x = x+1 return tfit ''' pick a random char from random string and turn it into another random char ''' def evolve(str): index = random.randint(0, len(str) - 1) strLst = list(str) strLst[index] = (random.choice(string.ascii_letters + string.digits + string.punctuation + string.whitespace)) str = ''.join(strLst) return str main()
class User: #User:(string, string) def __init__ (self, name, email): self.name = name self.email = email self.friends = [] #void -> string def getName (self): return self.name #void -> string def getEmail(self): return self.email #void -> list of Users def getFriends(self): return self.friends #string -> void def setName (self, newName): self.name = newName #string -> void def setEmail(self, newEmail): self.email = newEmail #list of users -> void def setFriends (self, newFriends): self.friends = newFriends #user -> void def addFriend (self, friend): self.friends.append(friend) friend.friends.append(self) #user -> Boolean def isFriend(self, friend): if friend in self.friends: return True else: return False #void -> str def strOfFriends (self): if self.friends == []: return "Friends: none" else: acc = "Friends: " for i in range (0, len(self.friends)): acc = acc + ((self.friends[i]).getName()) + ", " return acc #void -> str def __str__(self): return (self.name + " (" + self.email + ")\n" + self.strOfFriends())
# !/usr/bin/env python # encoding: utf-8 """ https://leetcode-cn.com/problems/min-stack/ """ class MinStack: def __init__(self): """ initialize your data structure here. """ self.data = [] self.min_stack = [math.inf] def push(self, x: int) -> None: self.data.append(x) self.min_stack.append(min(self.min_stack[-1], x)) def pop(self) -> None: self.data.pop() self.min_stack.pop() def top(self) -> int: return self.data[-1] def getMin(self) -> int: return self.min_stack[-1]
# !/usr/bin/env python # encoding: utf-8 """ https://leetcode-cn.com/problems/merge-two-sorted-lists/ """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1 or l2 and l1.val > l2.val: l1, l2 = l2, l1 if l1: l1.next = self.mergeTwoLists(l1.next, l2) return l1
# !/usr/bin/env python # encoding: utf-8 """ https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/ """ class Solution: def reverseList(self, head: ListNode) -> ListNode: prev, curr = None, head while curr: temp = curr.next curr.next = prev prev = curr curr = temp return prev
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 16 12:40:15 2018 @author: adanayi """ """ Note: This is only a test sample function. the structure must be followed. """ import time def f(FER): print("Hey! I am a function!") print("You have called me with this args: {}".format(FER['x'])) print("And this metadata: {}".format(FER['m'])) print("So! For now, you have to wait for 1 sec!") t = time.time() while True: if time.time() - t > 1: break print("Then I echo it back to yourself!!!") return FER['x']
import sqlite3 import csv sql_insert_stage = """ INSERT INTO stage (name, id) VALUES (?, ?); """ sql_insert_takeover = """ INSERT INTO takeover (name_key, name) VALUES (?, ?); """ sql_insert_artist = """ INSERT or IGNORE INTO artist (name, name_key, takeover_name_key) VALUES (?, ?, ?); """ sql_insert_artist_to_stage = """ INSERT INTO artistToStage (artist_name_key, stage_id) VALUES (?, ?); """ sql_select_stages = """ SELECT * FROM stage; """ sql_select_takeovers = """ SELECT * FROM takeover; """ sql_select_artists = """ SELECT * FROM artist; """ sql_select_artist_to_stage = """ select * from artistToStage; """ sql_read_table_names = """ PRAGMA table_info(table_name); """ def execute_command_vals(conn, command, vals): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ c = conn.cursor() c.execute(command, vals) def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = sqlite3.connect(db_file) return conn def print_select(conn, command): c = conn.cursor() c.execute(command) results = c.fetchall() print(command) for result in results: print(result) def create_artist_vals(): values = [] with open('Artist.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: if row[4] == "none": val = (row[0], row[1], None) else: val = (row[0], row[1], row[4]) values.append(val) return values def create_artist_to_stage_vals(): values = [] with open('Artist.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: val = (row[1], row[3]) values.append(val) return values def create_stages(conn): values = [ ("Pagoda", 1), ("Village", 2), ("Fractal Forest", 3), ("Amp", 4), ("Living Room", 5), ("Grove", 6) ] for val in values: execute_command_vals(conn, sql_insert_stage, val) def create_takeovers(conn): values = [ ("Jungle Cakes", "jungle_cakes"), ("Wakaan", "wakkan"), ("Sunrise Sessions", "sunrise_sessions"), ("Ragga Jungle Rinse Out", "ragga_rinse_out"), ("Cosmic Bridge", "cosmic_bridge"), ("Deep Dark and Dangerous", "deep_dark") ] for val in values: execute_command_vals(conn, sql_insert_takeover, val) def create_artists(conn): values = create_artist_vals() for val in values: execute_command_vals(conn, sql_insert_artist, val) def create_artist_to_stage(conn): values = create_artist_to_stage_vals() for val in values: execute_command_vals(conn, sql_insert_artist_to_stage, val) if __name__ == '__main__': conn = create_connection("../database.db") if conn is not None: create_stages(conn) create_takeovers(conn) create_artists(conn) create_artist_to_stage(conn) conn.commit() else: print("Error! cannot create the database connection.")
# -*- coding: utf-8 -*- from textblob import Word from spacy.lemmatizer import Lemmatizer from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES def lemmatize_word(word): """ Assign the base form of words Input: word (plural, capital letters) return: word (singular, lower letters) """ palabra=word palabra=Word(str(palabra).lower() ) palabra=palabra.lemmatize() if palabra==word: lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES) palabra = lemmatizer(word, u'NOUN') palabra=palabra[0] return palabra print (lemmatize_word("dogs")) print (lemmatize_word("CATS")) print (lemmatize_word("men")) print (lemmatize_word("children")) print (lemmatize_word("knives")) print (lemmatize_word("feet")) print (lemmatize_word("people")) print (lemmatize_word("teeth")) print (lemmatize_word("sheep")) print (lemmatize_word("gokussj")) lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES) lemmas = lemmatizer(u'ducks', u'NOUN') print (lemmas) lemmas = lemmatizer(u'men', u'NOUN') print (lemmas) lemmas = lemmatizer(u'people', u'NOUN') print (lemmas) lemmas = lemmatizer(u'sheep', u'NOUN') print (lemmas)
# funtions # create a function def sayHello(name = 'stephen'): print('hello', name) sayHello('john') # return a value def getSum(num1, num2): total = num1 + num2 return total numSum = getSum(1, 2) print(numSum) def addOneToNum(num): num = num + 1 print('value inside function:', num) return num = 5 addOneToNum(num) print('value outside function:', num) def addOneToList(myList): myList.append(4) print('value inside function:', myList) return myList = [1, 2, 3] addOneToList(myList) print('value outside function:', myList)
# single line comment #print sub strings print("Hello"[1:4]) # print numbers print(6) # Print on same line print(1,2,3,"hello") # new line print('line1\nline2\nline3') # raw text print(r'c:\\somewhere')
import os class Node (object): def __init__ (self, data): self.data = data self.lchild = None self.rchild = None class Tree (object): def __init__ (self): self.root = None # insert data into the tree def insert (self, data): new_node = Node (data) if (self.root == None): self.root = new_node return else: current = self.root parent = self.root while (current != None): parent = current if (data < current.data): current = current.lchild else: current = current.rchild # found location now insert node if (data < parent.data): parent.lchild = new_node else: parent.rchild = new_node # Returns true if two binary trees are similar def is_similar (self, fNode, pNode): if fNode == None and pNode == None: return True elif fNode.data == pNode.data and self.is_similar(fNode.lchild, pNode.lchild) and self.is_similar(fNode.rchild, pNode.rchild): return True return False # Prints out all nodes at the given level def print_level (self, aNode, level): if aNode == None: return elif level == 1: print(aNode.data, end=" ") self.print_level(aNode.lchild, level - 1) self.print_level(aNode.rchild, level - 1) # Returns the height of the tree def get_height (self, aNode): if aNode == self.root: return max(0 + self.get_height(aNode.lchild), 0 + self.get_height(aNode.rchild)) elif aNode != None: #print("add") return max(1 + self.get_height(aNode.lchild), 1 + self.get_height(aNode.rchild)) else: return 0 # Returns the number of nodes in tree which is # equivalent to 1 + number of nodes in the left # subtree + number of nodes in the right subtree def num_nodes (self, aNode): if aNode != None: return 1 + self.num_nodes(aNode.lchild) + self.num_nodes(aNode.rchild) else: return 0 def printTree(self, aNode): if aNode != None: self.printTree(aNode.lchild) print(aNode.data) self.printTree(aNode.rchild) def main(): nodes = input().strip().split() tree1 = Tree() nodes2 = input().strip().split() tree2 = Tree() for i in nodes: tree1.insert(i) for j in nodes2: tree2.insert(j) print("The Trees are similar:", tree1.is_similar(tree1.root, tree2.root)) print("") #print(tree1.num_nodes(tree1.root)) #tree1.printTree(tree1.root) #print(tree1.get_height(tree1.root)) print("Levels of Tree 1:", end="") for i in range(tree1.get_height(tree1.root)+2): tree1.print_level(tree1.root, i) print("") print("") print("Levels of Tree 2:", end="") for i in range(tree2.get_height(tree2.root)+2): tree2.print_level(tree2.root, i) print("") print("") print("Height of Tree 1:", tree1.get_height(tree1.root)) print("Nodes in Tree 1:", tree1.num_nodes(tree1.root)) print("Height of Tree 2:", tree2.get_height(tree2.root)) print("Nodes in Tree 2:", tree2.num_nodes(tree2.root)) main()
import os # list of operators (tree parents) operators = ['+','-','*','/','//','%','**'] class Stack (object): def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): return self.stack.pop() def peek(self): return self.stack[-1] def is_empty(self): return (len(self.stack) == 0) def size(self): return (len(self.stack)) class Node (object): def __init__(self, data): self.data = data self.l_child = None self.r_child = None #self.parent = None #self.visited = False class Tree (object): def __init__ (self): self.root = Node(None) def create_tree (self, expr): s = Stack() expr = expr.split() #print(expr) current = self.root #current = Node(current) for i in expr: if i.isdigit(): current.data = i current = s.pop() elif i == '(': s.push(current) current.l_child = Node(None) current = current.l_child elif i in operators: current.data = i s.push(current) current.r_child = Node(None) current = current.r_child elif i == ')': if s.size() > 0: current = s.pop() else: print(i) current.data = i if not s.is_empty(): current = s.pop() def evaluate (self, aNode): #['+','-','*','/','//','%','**'] #print(type(aNode.data)) if aNode.data == '+': return (self.evaluate(aNode.l_child) + self.evaluate(aNode.r_child)) elif aNode.data == '-': return (self.evaluate(aNode.l_child) - self.evaluate(aNode.r_child)) elif aNode.data == '*': return (self.evaluate(aNode.l_child) * self.evaluate(aNode.r_child)) elif aNode.data == '/': return (self.evaluate(aNode.l_child) / self.evaluate(aNode.r_child)) elif aNode.data == '//': return (self.evaluate(aNode.l_child) // self.evaluate(aNode.r_child)) elif aNode.data == '%': return (self.evaluate(aNode.l_child) % self.evaluate(aNode.r_child)) elif aNode.data == '**': return (self.evaluate(aNode.l_child) ** self.evaluate(aNode.r_child)) elif aNode.data.isdigit(): #print(aNode.data) return (int(aNode.data)) else: return (float(aNode.data)) def pre_order (self, aNode, strg): if (aNode != None): #print (aNode.data, end=" ") strg += str(aNode.data) + " " strg = self.pre_order (aNode.l_child, strg) strg = self.pre_order (aNode.r_child, strg) return strg def post_order (self, aNode, strg): if (aNode != None): strg = self.post_order (aNode.l_child, strg) strg = self.post_order (aNode.r_child, strg) strg += str(aNode.data) + " " #print (aNode.data, end=" ") #print("aNode.data:",aNode.data) #print(strg) return strg def main(): fptr = open(os.environ['OUTPUT_PATH'], 'w') expr = input().strip() tree1 = Tree() tree1.create_tree(expr) fptr.write(str(expr)) fptr.write(" = ") fptr.write(str(float(tree1.evaluate(tree1.root)))) fptr.write("\n") fptr.write("\nPrefix Expression: ") fptr.write(tree1.pre_order(tree1.root, "")) fptr.write("\n") fptr.write("\nPostfix Expression: ") fptr.write(tree1.post_order(tree1.root, "")) main()
import os class Node(object): def __init__ (self, data = None): self.data = data self.rchild = None self.lchild = None class Tree (object): # the init() function creates the binary search tree with the # encryption string. If the encryption string contains any # character other than the characters 'a' through 'z' or the # space character drop that character. def __init__ (self, encrypt_str): self.root = None self.en_str = encrypt_str # the insert() function adds a node containing a character in # the binary search tree. If the character already exists, it # does not add that character. There are no duplicate characters # in the binary search tree. def insert (self, ch): chn = 0 if ch.isalpha(): ch = ch.lower() #convert to lowercase chn = ord(ch) #convert to ascii value new_n = Node(chn) #makes a node out of ch if self.root == None: #if tree is empty, become the root self.root = new_n else: if self.search_dupes(new_n.data) == None: #search for duplicates, duplicates are not added curr = self.root parent = self.root while curr != None: parent = curr if chn < curr.data: curr = curr.lchild else: curr = curr.rchild if chn < parent.data: parent.lchild = new_n else: parent.rchild = new_n # the search() function will search for a character in the binary # search tree and return a string containing a series of lefts # (<) and rights (>) needed to reach that character. It will # return a blank string if the character does not exist in the tree. # It will return * if the character is the root of the tree. def search (self, ch): cstr = "*" curr = self.root if curr.data != ch: cstr = "" while (curr != None) and (curr.data != ch): if ch < curr.data: curr = curr.lchild cstr += "<" else: curr = curr.rchild cstr += ">" return cstr + "!" # looks for duplicates given a character value def search_dupes (self, ch): curr = self.root while (curr != None) and (curr.data != ch): if ch < curr.data: curr = curr.lchild else: curr = curr.rchild return curr # the traverse() function will take string composed of a series of # lefts (<) and rights (>) and return the corresponding # character in the binary search tree. It will return an empty string # if the input parameter does not lead to a valid character in the tree. def traverse (self, st): curr = self.root #print(self.search(ord(" "))) for i in st: if i == "<": curr = curr.lchild elif i == ">": curr = curr.rchild return curr.data # the encrypt() function will take a string as input parameter, convert # it to lower case, and return the encrypted string. It will ignore # all digits, punctuation marks, and special characters. def encrypt (self, st): new_st = [] for i in st: if i.isalpha(): i = i.lower() #convert to lowercase #self.insert(i) new_st.append(i) encryption = "" for k in new_st: #print(k) if k.isalpha(): encryption += self.search(ord(k)) elif k == " ": encryption += self.search(ord(k)) return encryption[:-1] # the decrypt() function will take a string as input parameter, and # return the decrypted string. def decrypt (self, st): new_str = "" st = st.split("!") for i in st: #print(i)#cypher version of char #print((self.traverse(i))) if self.traverse(i) == 32: new_str += " " else: new_str += chr(self.traverse(i)) return new_str def printTree(self, aNode): if aNode != None: self.printTree(aNode.lchild) print(chr(aNode.data)) self.printTree(aNode.rchild) def main(): fptr = open(os.environ['OUTPUT_PATH'], 'w') key = input().strip() #print(key) #print(ord(" ")) encrypt_string = input().strip() decrypt_string = input().strip() #print(encrypt_string, decrypt_string) tree1 = Tree(key) for i in key: tree1.insert(i) #tree1.printTree(tree1.root) fptr.write(tree1.encrypt(encrypt_string)) fptr.write("\n") fptr.write(tree1.decrypt(decrypt_string)) #tree1.traverse(tree1.root) main()
def tower_of_hanoi(number, source, aux_1, aux_2, destiny): if (number == 0): return 0 if (number == 1): print("Deslocando disco", number, "de", source, "para", destiny) return 0 tower_of_hanoi(number - 2, source, aux_2, destiny, aux_1) print("deslocando disco", number-1, "de", source, "para", aux_2) print("deslocando disco", number, "de", source, "para", destiny) print("deslocando disco", number-1, "de", aux_2, "para", destiny) tower_of_hanoi(number - 2, aux_1, aux_2, source, destiny) number = 3 tower_of_hanoi(number, 'X', 'Y', 'W', 'Z')
# Problem: https://leetcode.com/problems/validate-binary-search-tree/ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from typing import Optional class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: def valid(node, maxVal, minVal): if not node: return True if (maxVal is not None and node.val >= maxVal) or (minVal is not None and node.val <= minVal): return False return valid(node.left, node.val, minVal) and valid(node.right, maxVal, node.val) return valid(root, None, None)
import sys from typing import List # Problem: https://leetcode.com/problems/coin-change/ class Solution: def coinChange(self, coins: List[int], amount: int) -> int: memo = {} def minCoinChange(currAmount): shorted = None if currAmount == 0: return [] if currAmount < 0: return None if currAmount in memo: return memo[currAmount] for coin in coins: reminderCombination = minCoinChange(currAmount - coin) if reminderCombination is not None: combination = reminderCombination.copy() combination.append(coin) if not shorted or len(combination) < len(shorted): shorted = combination memo[currAmount] = shorted return shorted result = minCoinChange(amount) return len(result) if result is not None else -1
import unittest from leetcode.letter_combinations_of_phone_num_17.letter_combinations_of_phone_num import Solution class TestLetterCombinationsOfPhoneNumber(unittest.TestCase): def test_letter_combinations_of_phone_num(self): self.assertListEqual(["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"], Solution().letterCombinations(digits="23")) self.assertListEqual([], Solution().letterCombinations(digits="")) self.assertListEqual(["a", "b", "c"], Solution().letterCombinations(digits="2"))
# Problem: https://leetcode.com/problems/unique-paths/ # Solution memoization: https://www.youtube.com/watch?v=oBt53YbR9Kk&t=2320s # Solution tabulation: https://youtu.be/oBt53YbR9Kk?t=12137 class Solution: def uniquePaths(self, m: int, n: int) -> int: return self.with_dynamic_programming(m, n) def union_path_with_memoization(self, m: int, n: int, memo={}) -> int: if m == 1 and n == 1: return 1 if m == 0 or n == 0: return 0 key = str(m) + "," + str(n) if key in memo: return memo[key] path_count = self.union_path_with_memoization(m - 1, n, memo) + self.union_path_with_memoization(m, n - 1, memo) memo[key] = path_count return memo[key] def with_dynamic_programming(self, row: int, col: int): dp = [[0 for i in range(col+1)] for j in range(row+1)] dp[1][1] = 1 for i in range(row+1): for j in range(col+1): if j+1 <= col: dp[i][j+1] += dp[i][j] if i+1 <= row: dp[i+1][j] += dp[i][j] print(dp) return dp[row][col]
import sys import subsets class Solution: """ @param S: A set of numbers. @return: A list of lists. All valid subsets. """ def subsetsWithDup(self, S): # write your code here s = subsets.Solution() xs = s.subsets(S) unique = [] for i in range(0, len(xs)): if xs[i] not in xs[i + 1:]: unique.append(xs[i]) return unique sol = Solution() l = sys.argv[1].split(',') l = map(lambda x: int(x), l) print sol.subsetsWithDup(l)
import sys def sum_with_no_arith(a, b): """ sum two 32 bit numbers without using + return a + b """ carry = 0 bit_sum = 0 for i in range(0,32): a_bit = a >> i a_bit = a_bit & 0b1 b_bit = b >> i b_bit = b_bit & 0b1 if a_bit and b_bit: if carry: #one and carry bit_sum = bit_sum | (1 << i) carry = 1 elif a_bit: if carry: #zero and carry carry = 1 else: #one bit_sum = bit_sum | (1 << i) elif b_bit: if carry: #zero and carry carry = 1 else: #one bit_sum = bit_sum | (1 << i) else: #use carry bit bit_sum = bit_sum | (carry << i) carry = 0 return bit_sum a = int(sys.argv[1]) b = int(sys.argv[2]) print sum_with_no_arith(a,b)
import bs import sys import unittest class Solution: """ @param matrix, a list of lists of integers @param target, an integer @return a boolean, indicate whether matrix contains target """ def searchMatrix(self, matrix, target): # write your code here bso = bs.Solution() l = [] start = 0 end = len(matrix) - 1 if end < 0: return False while start <= end: middle = (start + end) / 2 if target >= matrix[middle][0] and target <= matrix[middle][len(matrix[middle]) - 1]: l = matrix[middle] break elif target < matrix[middle][0]: end = middle - 1 else: # > start = middle + 1 index = bso.binarySearch(l, target) return index != -1 class Test(unittest.TestCase): def setUp(self): self.sol = Solution() self.m = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]] def test_3(self): self.assertTrue(self.sol.searchMatrix(self.m, 3)) def test_35(self): self.assertFalse(self.sol.searchMatrix(self.m, 35)) def test_60(self): self.assertFalse(self.sol.searchMatrix(self.m, 60)) def test_22(self): self.assertFalse(self.sol.searchMatrix(self.m, 22)) if __name__ == '__main__': unittest.main()
""" Definition of TreeNode: """ class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: def recurseDFS(self, node): if node is None: return "#" else: return str(node.val) + "," + self.recurseDFS(node.left) + "," + self.recurseDFS(node.right) def deRecurseDFS(self, data): if len(data) > 0: val = data.pop(0) #get and remove first item in list if val == '#': return None else: node = TreeNode(int(val)) node.left = self.deRecurseDFS(data) node.right = self.deRecurseDFS(data) return node else: return None def encodeBFS(self, node): nodes = [] nodes.append(node) encodeStr = '' while len(nodes) > 0: node = nodes.pop(0) if node is None: encodeStr += '#' else: encodeStr += str(node.val) nodes.append(node.left) nodes.append(node.right) encodeStr += ',' return encodeStr[:-1] #skip trailing comma def decodeBFS(self, data): root = TreeNode(int(data[0])) parents = [] parents.append(root) child = 1 while len(parents) > 0: parent = parents.pop(0) if child >= len(data) or data[child] == '#': parent.left = None else: parent.left = TreeNode(int(data[child])) parents.append(parent.left) child += 1 if child >= len(data) or data[child] == '#': parent.right = None else: parent.right = TreeNode(int(data[child])) parents.append(parent.right) child += 1 return root ''' @param root: An object of TreeNode, denote the root of the binary tree. This method will be invoked first, you should design your own algorithm to serialize a binary tree which denote by a root node to a string which can be easily deserialized by your own "deserialize" method later. ''' def serialize(self, root): # write your code here return self.encodeBFS(root) ''' @param data: A string serialized by your serialize method. This method will be invoked second, the argument data is what exactly you serialized at method "serialize", that means the data is not given by system, it's given by your own serialize method. So the format of data is designed by yourself, and deserialize it here as you serialize it in "serialize" method. ''' def deserialize(self, data): # write your code here if data[0] == '#': return None return self.decodeBFS(data.split(",")) if __name__ == "__main__": sol = Solution() tree = TreeNode(3) tree.left = TreeNode(9) tree.right = TreeNode(20) tree.right.left = TreeNode(15) tree.right.right = TreeNode(7) serStr = sol.serialize(tree) print serStr desTree = sol.deserialize(serStr) #serialize result to check correctness ser2Str = sol.serialize(desTree) tree = None empty = sol.serialize(tree) sol.deserialize(empty) print ser2Str
class User(): def __init__(self,first_name , last_name): self.first_name = first_name self.last_name = last_name self.login_attempts = 0 def describe_user(self): print("User: "+ self.first_name.titile() + self.last_name.title()) def greet_user(self): full_name = self.first_name + ' ' + self.last_name print("Hello! "+ full_name.title()) def increment_login_attempts(self): self.login_attempts += 1 def reset_login_attempts(self): self.login_attempts = 0 class Privilege(): def __init__(self): self.privileges = ["can add post", "can delete post", "can ban user"] def show_privileges(self): print(self.privileges) class Admin(User): def __init__(self, first_name, last_name): super().__init__(first_name, last_name) self.privileges = Privilege()
from time import * def sumsquare(n): """Calculate the sum of the squares of 1~n.""" sq = 0 for i in range(n): sq += (i+1) **2 return sq # begin_time = time() # for i in range(1000000): # print(sumsquare(12)) # end_time = time() # run_time = end_time - begin_time # print(run_time) squares = [k*k for k in range(1, 13)] print(squares) factors = [k for k in range(1,13) if 12%k == 0] print(factors) sumsquares = sum(k*k for k in range(1,13)) begin_time = time() for i in range(1000000): print(sumsquares) end_time = time() run_time = end_time - begin_time print(run_time)
print("Enter marks in DATA STRUCTURES, COMPUTER NETWORKS, DIGITAL ELECTRONICS, MICROPROCESSOR, OPERATING SYSTEM respectively (out of 50 each) : ") a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) percentage = ((a+b+c+d+e)/250)*100 if a > 50 or b > 50 or c > 50 or d > 50 or e > 50: print("Please enter valid marks") elif percentage == 100: print("Are you a Robot???") elif percentage >= 80: print("Impressive!!! That's an A grade with", percentage, "%") elif 60 <= percentage < 80: print("Good!!! That's a B grade with", percentage, "%") elif 40 <= percentage < 60: print("Poor!!! That's a C grade with", percentage, "%") else: print("Sorry!!! You failed...Better luck next time!!!")
a=list(input()) if a[0]=='-': print('Negative') else: print('Positive')
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, left, right): if left <= right: midpoint = (right + left) //2 if arr[midpoint] == target: return midpoint elif arr[midpoint] > target: return binary_search(arr, target, left, midpoint - 1) else: return binary_search(arr, target, midpoint + 1, right) else: return -1 def binary_search_it(arr, target): # Your code here left = 0 right = len(arr) - 1 while left <= right: midpoint = (right + left) // 2 if arr[midpoint] == target: return midpoint elif arr[midpoint] > target: right = midpoint - 1 else: left = midpoint + 1 return -1 # not found def binary_search_it_oppo(arr, target): # Your code here left = len(arr) - 1 right = 0 while left >= right: midpoint = (right + left) // 2 if arr[midpoint] == target: return midpoint elif arr[midpoint] < target: left = midpoint - 1 else: right = midpoint + 1 return -1 # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively def ace_dec(arr): if len(arr) <= 1: return "Array contain only one variable or it is empty!" else: if arr[0] > arr[1]: return "DEC" if arr[1] > arr[0]: return "ACE" def agnostic_binary_search(arr, target): if ace_dec(arr) != "ACE" and ace_dec(arr) != "DEC": return "Array contain only one variable or it is empty!" if ace_dec(arr) == "ACE": return binary_search_it(arr, target) if ace_dec(arr) == "DEC": return binary_search_it_oppo(arr,target)
def sumar(num1, num2): resultado = num1 + num2 return resultado def restar(num1, num2): resultado = num1-num2 return resultado def multiplicar(num1, num2): resultado = num1 * num2 return resultado def dividir(num1, num2): resultado = num1 / num2 return resultado
miCadena = "EsTa Cadema EsTa AlGo RaRa" miLista = miCadena.split(" ") for palabra in miLista: palabra = palabra.upper() print("analizando la palabra:",palabra) print("\tLa palabra tiene"+ str(len(palabra))+ "caracteres de largo") if len(palabra)%2==0: print("\tLa cantidad de letras es un numero par") else: print("\tLa cantidad de letras es un numero impar") print("\tLa primera letra de la palabra es:", palabra[0]) print("\tLa ultima letra dela palabra es:", palabra[-1])
#conversiones.py # miercoles 28 de febrero del 2018 #cristopher jose rodolfo barrios solis #ejercicio de funciones #variables de la ecuacion a = 9/5 e = 5/9 c = 32 menu = input("que desea hacer?\n\n" "1. convertir de grados farenheit a centigrados\n" "2. convertir de grados centigrados a farenheit\n" "3. salir\n\n")#pregunta para el centinela menu = str(menu)#valor de menu en string while (menu!="3"): from conversiones import convertir_centigrados_farenheit, convertir_farenheit_centigrados#llamando las funciones if menu == "1":#condicion para farenheit para converit a centigrados d = input("\n""ingrese grados farenheit para convertir a centigrados:\n\n") d = int(d) valor = convertir_farenheit_centigrados(d,c,e)#uso de la funcion print ("\n",valor, "Celsius\n") if menu == "2":#condicion para convertir de centigrados a farentheit b = input("\n""ingrese grados centigrados para convertir a farenheit:\n\n") b = int(b) valor2 = convertir_centigrados_farenheit(a,b,c)#uso de la funcion print ("\n",valor2,"Farenheit\n") menu = input("\n""que desea hacer?\n\n" "1. convertir de grados farenheit a centigrados\n" "2. convertir de grados centigrados a farenheit\n" "3. salir\n\n")#pregunta final para el centinela print("\n""adios")#el programa se despide
a = (1, 2, 3, 2, "哈哈哈", "嘻嘻嘻", True, False) print(a) # 二维元组 b = (a, "嘟嘟", "噜噜") # 取哈哈哈 print(b[0][2]) # 取3的下标 print(a.index(3)) # 取2的个数 print(a.count(2)) # 切片 print(a[0:4]) # 左闭右开 print(a[4:6]) print(a[6:8])
""" De una lista de N cantidad de estaturas de personas se desea saber lo siguiente 1) El promedio 2) El punto medio 3) Cuantos son menores a 1.70 4) Cuantos son mayores a 1.70 """ def check_number_height(number, min_number, max_number, text_error): list_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] condition_while = True while condition_while: condition_one = False condition_two = False list_of_number = [] for item in number: list_of_number.append(item) if len(list_of_number) == 1: if list_of_number[0] in list_numbers: condition_one = True elif len(list_of_number) == 3: if list_of_number[0] in list_numbers and list_of_number[1] == "." and list_of_number[2] in list_numbers: condition_one = True elif len(list_of_number) == 4: if list_of_number[0] in list_numbers and list_of_number[1] == "." and\ list_of_number[2] in list_numbers and list_of_number[3] in list_numbers: condition_one = True if condition_one: number = float(number) if number <= max_number and number >= min_number: condition_two = True if condition_one and condition_two: condition_while = False else: number = input(text_error) return number def check_number_height_key(number, min_number, max_number, key, text_error): list_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] condition_while = True while condition_while: condition_one = False condition_two = False list_of_number = [] for item in number: list_of_number.append(item) if len(list_of_number) == 1: if list_of_number[0] in list_numbers: condition_one = True elif len(list_of_number) == 3: if list_of_number[0] in list_numbers and list_of_number[1] == "." and list_of_number[2] in list_numbers: condition_one = True elif len(list_of_number) == 4: if list_of_number[0] in list_numbers and list_of_number[1] == "." and\ list_of_number[2] in list_numbers and list_of_number[3] in list_numbers: condition_one = True if condition_one: number = float(number) if number <= max_number and number >= min_number: condition_two = True if (condition_one and condition_two): condition_while = False elif not condition_one: if number.lower() == key: condition_while = False else: number = input(text_error) else: number = input(text_error) return number list_height = [] higher = [] less = [] average = 0 mid_point = 0 height = input("\nIngrese su estatura: ") height = check_number_height(height, 1, 3.5, "Ingrese una estatura válida: ") list_height.append(height) height = input("Ingrese su estatura: ") height = check_number_height(height, 1, 3.5, "Ingrese una estatura válida: ") list_height.append(height) main_condition = True while main_condition: height = input("Ingrese su estatura o ingrese listo para continuar: ") height = check_number_height_key(height, 1, 3.5, "listo", "Ingrese una estatura válida: ") if height == "listo": main_condition = False else: list_height.append(height) # Average for number in list_height: average += number average = average / len(list_height) # Mid Point mid_point = list_height[0] + list_height[(len(list_height) - 1)] mid_point = mid_point / 2 # Higher 1.70 for number in list_height: if number >= 1.70: higher.append(number) # Less 1.70 for number in list_height: if number < 1.70: less.append(number) print("\n------------------------------------------------------") print("\nEl promedio de las estaturas es: {}" "\nEl punto medio es: {}" "\nLos mayores a 1.70 son: {}" "\nLos menores a 1.70 son: {}".format(average, mid_point, higher, less))
print("") usu_sent = input("Ingrese una oración: ") print("") list_a = ["A", "a"] mod_sent = usu_sent.replace("A", "VACA") mod_sent = mod_sent.replace("a", "VACA") print(mod_sent)
import datetime print("") print("Ingrese una fecha pasada.") year = int(input("Año: ")) month = int(input("Mes: ")) day = int(input("Día: ")) usu_date = datetime.datetime(year=year, month=month, day=day) now_date = datetime.datetime.now() past = now_date - usu_date print("") print("Han pasado {} horas desde ese día.".format(int(past.total_seconds()/3600))) print("")
def correct(list): new_list = [] for item in list: reset = 0 new_item = "" for letter in item: if reset != 0: letter = letter.lower() new_item += letter reset += 1 if letter == " ": reset = 0 else: new_item += letter reset += 1 new_list.append(new_item) return new_list new_list = [] random_list = ["ALO", "COCA COLA"] new_list = correct(random_list) print(new_list)
import getpass number_2 = 0 print("") number_1 = getpass.getpass(input("Ingrese un número para adivinar: ")) print("") print("") while number_1 != number_2: number_2 = input("¡Ingrese un número para ganar su premio!: ") if number_1 != number_2: print("¡Has perdido") print("") print("") print("¡Has ganado una palmadita en la espalda!") print("") print("")
"""CSC110 Fall 2020 Final Project, Main Description =============================== This module is the graphical user interface that allows the user to access all the components of our project. To display a map, the interface prompts the user to enter a valid year, which creates three maps. To display a graph, the user needs to select a station that could be filtered out by province as well as by the search bar. Copyright and Usage Information =============================== This file is provided solely for the personal and private use of TA's and professors teaching CSC110 at the University of Toronto St. George campus. All forms of distribution of this code, whether as given or with any changes, are expressly prohibited. For more information on copyright for CSC110 materials, please consult our Course Syllabus. This file is Copyright (c) 2020 Dana Alshekerchi, Nehchal Kalsi, Rachel Kim, Kathy Lee. """ from tkinter import Button, Entry, Label, StringVar, mainloop, Tk, Toplevel from tkinter import ttk import json import ast from PIL import ImageTk, Image import data_reading import combine import maps # Creates the main window ROOT = Tk() # Opens the image for the title TITLE_IMAGE = Image.open('title_image.png') # Resizes the image SMALLER = TITLE_IMAGE.resize((300, 300), Image.ANTIALIAS) # (300, 255) NEW_TITLE = ImageTk.PhotoImage(SMALLER) # Displays the image as a label TITLE_LABEL = Label(ROOT, image=NEW_TITLE, borderwidth=0) TITLE_LABEL.grid(row=1, column=1, columnspan=4) def window(main) -> None: """ Sets the main window up to be in the middle of the screen as well as determines the size of the screen """ main.title('Effects of Greenhouse Gases in Canada') main.update_idletasks() width = 575 height = 550 x = (main.winfo_screenwidth() // 2) - (width // 2) y = (main.winfo_screenheight() // 2) - (height // 2) main.geometry('{}x{}+{}+{}'.format(width, height, x, y)) # Creates an icon ROOT.iconbitmap('leaf.ico') # Background colour ROOT.config(bg='#FFE4AE') # From Assignment 2 Part 4 def read_temp_data(file: str) -> dict: """Return a dictionary mapping course codes to course data from the data in the given file. In the returned dictionary: - each key is a string representing the course code - each corresponding value is a tuple representing a course value, in the format descried in Part 3 of the assignment handout. Note that the implementation of this function provided to you is INCOMPLETE since it just returns a dictionary in the same format as the raw JSON file. It's your job to implement the functions below, and then modify this function body to get the returned data in the right format. Preconditions: - file is the path to a JSON file containing course data using the same format as the data in data/course_data_small.json. file is the name (or path) of a JSON file containing course data using the format in the sample file course_data_small.json. """ with open(file) as json_file: data_input = json.load(json_file) return data_input # Retrieving data needed UNFILTERED_DATA = read_temp_data('data.json') DATA = {x: UNFILTERED_DATA[x] for x in UNFILTERED_DATA if UNFILTERED_DATA[x] != {}} CITIES = [ast.literal_eval(x)[0] for x in DATA.keys()] PROVINCE = [ast.literal_eval(x)[1] for x in DATA.keys()] ABB_TO_PROVINCE = {'BC': 'British Columbia', 'MAN': 'Manitoba', 'ALTA': 'Alberta', 'NFLD': 'Newfoundland and Labrador', 'PEI': 'Prince Edward Island', 'YT': 'Yukon', 'NB': 'New Brunswick', 'SASK': 'Saskatchewan', 'NU': 'Nunavut', 'ONT': 'Ontario', 'NS': 'Nova Scotia', 'NWT': 'Northwest Territories', 'QUE': 'Quebec'} def map_open() -> None: """ Opens three maps on different browsers based on the year inputted when the map button is clicked Precondition: - 1990 < YEAR_SELECT.get() <= 2018 """ # Retrieves data needed from files province_geojson_file_name = 'canada_provinces.geojson' weather_stations_geojson = 'weather_stations.geojson' daily_temps_geojson = 'data_for_maps_since_1990.json' emissions_csv_file_name = 'GHG_IPCC_Can_Prov_Terr.csv' province_id_map = maps.format_province_id_map(province_geojson_file_name) emissions_data_frame = data_reading.read_ghg_emissions_for_maps(emissions_csv_file_name) emissions_difference_data_frame = maps.calculate_emissions_difference(emissions_data_frame) temperatures_difference_data_frame = maps.calculate_temp_difference( maps.format_temps(weather_stations_geojson, daily_temps_geojson)) # This occurs when the the correct input (a year between 1991-2018) try: year = int(YEAR_SELECT.get()) if 1991 <= year <= 2018: maps.plot_emissions_map(province_geojson_file_name, 'Raw Data', emissions_data_frame, province_id_map, year) maps.plot_emissions_map(province_geojson_file_name, 'Difference', emissions_difference_data_frame, province_id_map, year) maps.plot_temperatures_map(province_geojson_file_name, 'Difference', temperatures_difference_data_frame, year) # If the year is not between 1991 and 2018 else: raise ValueError except ValueError: YEAR_RANGE_LABEL.config(text='Wrong input. \n Enter year \n(1991 - 2018)', bg='#FFE4AE', fg='#800000') def province_filter(event) -> None: """ Enables the search button when the province is selected Filters out stations, only those in the province chosen appear """ SEARCH_BUTTON['state'] = 'normal' cities_in_province = [ast.literal_eval(x)[0] for x in DATA.keys() if ABB_TO_PROVINCE[ast.literal_eval(x)[1]] == PROVINCE_COMBO.get()] # Changes the city back to its original format sorted_cities = [x.replace('_', ' ').title() for x in cities_in_province] sorted_cities.sort() CITY_COMBO['values'] = sorted_cities def selected(event) -> None: """ Opens a new browser with the plotly graph of the station selected Graph compares temperature anomaly of station and CO2 emission of the province """ province = '' city_chosen = CITY_COMBO.get().upper().replace(' ', '_') # Gets the province in which the city is located in for item in CITIES: if city_chosen == item: province = PROVINCE[CITIES.index(item)] break ghg_data = data_reading.read_ghg_emissions('GHG_IPCC_Can_Prov_Terr.csv') key = "('" + city_chosen + "', '" + province + "')" combine.combine_plots(ghg_data, DATA[key], ABB_TO_PROVINCE[province], CITY_COMBO.get()) def search() -> None: """ Searches for the station located in the province selected based on the characters written in the search entry box """ search_values = CITY_TYPE.get().lower() cities_in_province = [ast.literal_eval(x)[0] for x in DATA.keys() if ABB_TO_PROVINCE[ast.literal_eval(x)[1]] == PROVINCE_COMBO.get()] if search_values in ('', ' '): CITY_COMBO['values'] = [x.replace('_', ' ').title() for x in cities_in_province] else: display_values = [] for value in [x.replace('_', ' ').title() for x in cities_in_province]: if search_values in value.lower(): display_values.append(value) display_values.sort() CITY_COMBO['values'] = display_values def creators_page() -> None: """ Opens another window which showcases a picture of the creators """ creators_window = Toplevel(ROOT) creators_window.title('Creators') creators_window.update_idletasks() width = 575 height = 350 x = (creators_window.winfo_screenwidth() // 2) - (width // 2) y = (creators_window.winfo_screenheight() // 2) - (height // 2) creators_window.geometry('{}x{}+{}+{}'.format(width, height, x, y)) creators_window.iconbitmap('leaf.ico') creators_window.config(bg='#FFE4AE') introduction_label = Label(creators_window, text='This project was created by...', font=('Helvetica', 10, 'bold'), bg='#FFE4AE', fg='#800000', borderwidth=0) introduction_label.grid(row=1, column=1, columnspan=4, pady=(10, 20)) # Opens the image for the title creator_image = Image.open('creator_image.png') # Resizes the image resized = creator_image.resize((600, 250), Image.ANTIALIAS) new_creator = ImageTk.PhotoImage(resized) # Displays the image as a label creator_label = Label(creators_window, image=new_creator, borderwidth=0) creator_label.photo = new_creator creator_label.grid(row=2, column=1, columnspan=4) why_label = Label(creators_window, text='for the CSC110 Final Project', font=('Helvetica', 10, 'bold'), bg='#FFE4AE', fg='#800000', borderwidth=0) why_label.grid(row=3, column=1, columnspan=4, pady=(10, 0)) def instructions_page() -> None: """ Opens a new window on to of the original window to display further instructions as to what the user should expect when the buttons are clicked """ instructions_window = Toplevel(ROOT) instructions_window.title('Instructions') instructions_window.update_idletasks() width = 575 height = 250 x = (instructions_window.winfo_screenwidth() // 2) - (width // 2) y = (instructions_window.winfo_screenheight() // 2) - (height // 2) instructions_window.geometry('{}x{}+{}+{}'.format(width, height, x, y)) instructions_window.iconbitmap('leaf.ico') instructions_window.config(bg='#FFE4AE') map_instructions_title = Label(instructions_window, text='Map Instructions', font=('Helvetica', 10, 'bold', 'underline'), bg='#FFE4AE', fg='#800000', borderwidth=0) map_instructions_title.pack() map_instructions = Label(instructions_window, text='1. Enter a year between 1991 and 2018.\n' ' 2. Upon ' 'clicking Map with a valid year, following ' 'three maps appear, ' 'displaying:\n a. CO2 equivalent of GHG ' 'emissions across ' 'Canada for the given year \n b. ' 'Difference in CO2 equivalent output ' 'across Canada, for the given year ' 'and 1990\n c. Difference in mean ' 'temperatures for each weather station, ' 'for a given year compared to 1990 ', bg='#FFE4AE', fg='#800000', borderwidth=0) map_instructions.pack() graph_instructions_title = Label(instructions_window, text='Graph Instructions', font=('Helvetica', 10, 'bold', 'underline'), bg='#FFE4AE', fg='#800000', borderwidth=0) graph_instructions_title.pack(pady=(15, 0)) graph_instructions = Label(instructions_window, text='1. Select a province or territory' ' in the Province/Territory dropdown ' 'menu.\n 2. Enter keywords of the ' 'weather station under Search ' 'Station and click Search. \n Select ' 'the station in the Station dropdown ' 'menu.\n ' '3. Once a weather station selected,' ' a graph will display in ' 'your browser.This displays\n the ' 'temperature anomaly and CO2 ' 'equivalent of GHG emissions for\n ' 'your selected weather ' 'station. ', bg='#FFE4AE', fg='#800000', borderwidth=0) graph_instructions.pack() # Labels for all the buttons and entry boxes for user friendliness # Map Widgets VIEW_MAP_LABEL = Label(ROOT, text='View Map', font=('Helvetica', 10, 'bold', 'underline'), bg='#FFE4AE', fg='#800000', borderwidth=0) VIEW_MAP_LABEL.grid(row=2, column=1, columnspan=4) YEAR_RANGE_LABEL = Label(ROOT, text='Enter year\n(1991 - 2018)', bg='#FFE4AE', fg='#800000') YEAR_RANGE_LABEL.grid(row=3, column=2) YEAR_SELECT = Entry(ROOT, width=7) YEAR_SELECT.grid(row=4, column=2) MAP_BUTTON = Button(ROOT, text='Map', command=map_open, bg='#800000', fg='#FFE4AE') MAP_BUTTON.grid(row=4, column=3, padx=15) # Graph Widgets VIEW_GRAPH_LABEL = Label(ROOT, text='View Graph', font=('Helvetica', 10, 'bold', 'underline'), bg='#FFE4AE', fg='#800000', borderwidth=0) VIEW_GRAPH_LABEL.grid(row=5, column=1, columnspan=4, pady=(15, 0)) PROVINCE_LABEL = Label(ROOT, text='1. Province/Territory', bg='#FFE4AE', fg='#800000') PROVINCE_LABEL.grid(row=6, column=1, padx=15) PROVINCE_OPTIONS = [ABB_TO_PROVINCE[x] for x in ABB_TO_PROVINCE] PROVINCE_OPTIONS.sort() PROVINCE_COMBO = ttk.Combobox(ROOT, value=PROVINCE_OPTIONS) PROVINCE_COMBO.current(0) PROVINCE_COMBO.bind('<<ComboboxSelected>>', province_filter) PROVINCE_COMBO.grid(row=7, column=1, padx=15) SEARCH_LABEL = Label(ROOT, text='2. Station Search', bg='#FFE4AE', fg='#800000') SEARCH_LABEL.grid(row=6, column=2, padx=15) CITY_TYPE = StringVar() SEARCH_TEXT = Entry(ROOT, text=CITY_TYPE) SEARCH_TEXT.grid(row=7, column=2, padx=15) SEARCH_BUTTON = Button(ROOT, text='Search', command=search, bg='#800000', fg='#FFE4AE') SEARCH_BUTTON['state'] = 'disabled' SEARCH_BUTTON.grid(row=7, column=3, padx=15) STATION_LABEL = Label(ROOT, text='3. Station', bg='#FFE4AE', fg='#800000') STATION_LABEL.grid(row=6, column=4, padx=15) CITY_OPTIONS = [x.replace('_', ' ').title() for x in CITIES] CITY_OPTIONS.sort() CITY_COMBO = ttk.Combobox(ROOT, value=[x.replace('_', ' ').title() for x in CITY_OPTIONS]) CITY_COMBO.bind('<<ComboboxSelected>>', selected) CITY_COMBO.grid(row=7, column=4, padx=15) INSTRUCTIONS_BUTTON = Button(ROOT, text='Instructions', command=instructions_page, bg='#800000', fg='#FFE4AE') INSTRUCTIONS_BUTTON.grid(row=8, column=1, pady=(30, 0)) CREATORS_BUTTON = Button(ROOT, text='Creators', command=creators_page, bg='#800000', fg='#FFE4AE') CREATORS_BUTTON.grid(row=8, column=4, pady=(30, 0)) window(ROOT) mainloop() if __name__ == '__main__': import python_ta python_ta.check_all(config={ # the names (strs) of imported modules 'extra-imports': ['tkinter', 'json', 'python_ta', 'python_ta.contracts', 'ast', 'PIL', 'data_reading', 'combine', 'maps'], # the names (strs) of functions that call print/open/input 'allowed-io': ['read_temp_data'], 'max-line-length': 100, 'disable': ['R1705', 'C0200'] }) import python_ta.contracts python_ta.contracts.DEBUG_CONTRACTS = False python_ta.contracts.check_all_contracts() import doctest doctest.testmod()
#file 006.py def F(n): if(n==1 or n==2): return 1 else: return (F(n-1) + F(n-2)) n = int(input("input the month:")) total = F(n); print("total rabbit number is ", total)