text
stringlengths
37
1.41M
from Tkinter import * root = Tk() root.title('Canvas') canvas = Canvas(root, width =400, height=400) xy = 10, 105, 100, 200 canvas.create_arc(xy, start=0, extent=270, fill='gray60') canvas.pack() root.mainloop()
import math class NegativeNumberError( ArithmeticError ): pass def squareRoot( number ): if number < 0: raise NegativeNumberError, "Square root of negative number not permitted" return math.sqrt( number ) while 1: try: userValue = float( raw_input( "\nPlease enter a number: " ) ) print squareRoot( userValue ) # float raises ValueError if input is not numerical except ValueError: print "The entered value is not a number" # squareRoot raises NegativeNumberError if number is negative except NegativeNumberError, exception: print exception else: break
class Fruit: def __init__(self, type): self.type = type class Fruits: def __init__(self): self.types = {} def get_fruit(self, type): if type not in self.types: self.types[type] = Fruit(type) return self.types[type] if __name__ == '__main__': fruits = Fruits() print fruits.get_fruit('Apple') print fruits.get_fruit('Lime')
counters = [1, 2, 3, 4] updated = [] for x in counters: updated.append(x + 10) # add 10 to each item print(updated) def inc(x): return x + 10 # function to be run print(list(map(inc, counters))) # collect results print(list(map((lambda x: x + 3), counters))) # function expression
print("Hello world") print("I have %d cats and %d dogs" %(5,6)) print("Here are the numbers! \n" "The first is {0:d} The second is {1:4d} ".format(7,8)) ##input함수는 String을 반환함-> int로 형변환하여 연산 #salary=int(input("please enter your salary: ")) #bonus=int(input("Please enter your bonus: ")) #payCheck=salary+bonus #print(payCheck) data1=5.1234 data2=round(data1,2) print(data1) print(data2) print(type(data1)) ##program example1 #print("한글"*3) #salary=input("월급 : ") #bonus=input("보너스: ") #print(type(bonus)) name="greenjoa" print(name[0]) print(name[-1]) print(name[-2]) info="201311226greenjoa" sid=info[:9]#0<=info<9 sname=info[9:] print(sid+" "+sname) #문자열은 상수로 수정 불가 a[1]=y 안됨 a="pithon" a=a[:1]+"y"+a[2:] print(a) print("I eat %10s apples." %"five")#왼쪽정렬 print("I eat %-10s apples." %"five")#오른쪽정렬 a="Error is %d%%." %98 print(a) a="I ate{number} apples. so I was sick for {day} days.".format(number=10,day=3) b="{0:>10}".format("hi")#<좌측정렬 >우측정렬 ^ 가운데 정렬 c="{0:=^10}".format("hi")#공백채우기->가운데 정렬에서 빈공간 '='로채우기 print(c) #question #종료할까요? yes YES 소문자로 입력하면 대문자로, 대문자로 입력하면 소문자로 바꾸기 yes=input("종료할까요? ") print(yes.swapcase())
#class A(): # def __init__(self,a): # self.a=a # def show(self): # print('show:',self.a) #class B(A): # def __init__(self,b,**arg): # super().__init__(**arg) # self.b=b # def show(self): # print('show:',self.b) # super().show() #class C(A): # def __init__(self,c,**arg): # super().__init__(**arg) # self.c=c # def show(self): # print('show:',self.c) # super().show() #class D(B,C): # def __init__(self,d,**arg): # super().__init__(**arg) # self.d=d # def show(self): # print('show:',self.d) # super().show() #data=D(a=1,b=2,c=3,d=4) #data.show() #class Mapping: # def __init__(self, iterable): # self.items_list=[] # self.__update(iterable) # def update(self, iterable): # for item in iterable: # self.items_list.append(item) # __update=update #class MappingSubclass(Mapping): # def update(self, keys,values): # for item in zip(keys,values): # self.items_list.append(item) #data=MappingSubclass([1,2,3,4]) #print(data.items_list) #data.update([1],[2]) #print(data.items_list) import sys number1=float(input("enter a number:")) number2=float(input("enter a number:")) try: result=number1/number2 print(result) except ZeroDivisionError as e: print(e) print("The answer is infinity") except: error=sys.exc_info()[0] print(error) sys.exit() #finally ڵ带 ϰ finally: print("Done")
#The following code describes a simple 1D random walk #where the walker can move either forwards or backwards. There is an #equal probability to move either forwards or backwards with each step. #Numeric Python library import numpy as np #Random number library import random #Plotting libary from matplotlib import pyplot as plt #Number of steps. Chosen as 50 in this case. N_steps = 100 #probability of a step going in either direction. #Set to 0.5, meaning that walker is equally likely to move #forwards or backwards with each step. prob = 0.5 #Define the random walk function. N in this case is the number of steps and #p is the probablity threshold of going either forwards or backwards. 'line' is a string #that will describe the marker and line style for a plot of the random walk. def SimpleRandomWalk(N, p, line): #Create an array of positions for the walker. And initialize the first position #to be the origin (zero). The array will be the same size as the number of steps. #A position counter variable is also used, which is initialized to zero as well. position = np.empty(N) position[0] = 0 pos_counter = 0 #Array containing the full range of the number of possible steps taken. steps = np.arange(N) #Start the random walk. for i in range(1,N): #Generate a random probability value between 0 and 1. test = random.random() #Chechk the value of the probability generated. If it is > or equal to 0.5, increment the step forwards. #If it is less than 0.5, increment a step backwards instead. Keep track of the position counter after #updating it. if test >= p: pos_counter += 1 else: pos_counter -= 1 #Fill the current position array index with the current value of the position counter from the loop. position[i] = pos_counter #Generate a plot of walker position vs. the number of steps taken. Line is a string that will describe the #markers and line type used to plot the random walk. plt.plot(steps, position, line) plt.xlabel('Steps taken') plt.ylabel('Distance from Starting Position') return None #Create a new figure to plot the random walk. plt.figure() #Function call to generate and plot the first random walk with circular markers and a dotted line. SimpleRandomWalk(N_steps, prob, line = 'o--') #Hold the first random walk on the plot. plt.hold(True) #Function call to generate and plot a second random walk using a full line. SimpleRandomWalk(N_steps, prob, line = '-') #Show both random walks on the plot. plt.show()
#test.py r = int(input("반지름을 입력하세요")) h = int(input("높이를 입력하세요")) print("r :", r) print("h :", h) p = 3.14 int(p) v =r**2*h*p print("원기둥의 부피 :",v)
""" [21-01-29] 114. Flatten Binary Tree to Linked List https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ # base case def flatten_with_leaf(root: TreeNode): if root is None: return None if root.left is None and root.right is None: return root left_leaf = flatten_with_leaf(root.left) right_leaf = flatten_with_leaf(root.right) if left_leaf: right = root.right root.right = root.left left_leaf.right = right root.left = None return right_leaf if right_leaf else left_leaf flatten_with_leaf(root)
""" [21-01-04] 314. Binary Tree Vertical Order Traversal https://leetcode.com/problems/binary-tree-vertical-order-traversal/ """ class Solution: def verticalOrder(self, root: TreeNode, col = 0) -> List[List[int]]: result = {} def dfs(root: TreeNode, row, col): if root is None: return if col in result: result[col].append((row, root.val)) else: result[col] = [(row, root.val)] dfs(root.left, row + 1, col -1) dfs(root.right, row + 1 , col + 1) dfs(root, 0, 0) f_result = [] for k, v in sorted(result.items()): f_result.append([it[1] for it in sorted(v, key=lambda x: x[0])]) return f_result
""" [21-01-04] 559. Maximum Depth of N-ary Tree https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ """ """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def maxDepth(self, root: 'Node') -> int: def dfs(root): if root is None: return 0 max_d = 0 for c in root.children: max_d = max(max_d, dfs(c)) return max_d + 1 return dfs(root)
""" [21-07-23] 98. Validate Binary Search Tree 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 class Solution: def isValidBST(self, root: TreeNode) -> bool: def validate(root, mini, maxi): if not root: return True if root.val<= mini or root.val >= maxi: return False return validate(root.left, mini, root.val) and validate(root.right, root.val, maxi) return validate(root, float("-inf"), float("inf"))
def lines_are_paralel(l1,l2): if l1[0] == l2[0]: return True else: return False def main(): a, b, c = input ("Digit the values for 'a', 'b' and 'c' of the first line ax + b = c: ").split() d, e, f = input ("Digit the values for 'd', 'e' and 'f' of the second line dx + e = f: ").split() l1 = [a, b, c] l2 = [d, e, f] print (lines_are_paralel(l1, l2)) if __name__ == "__main__": main()
''' Пошук підрядка в рядку ''' a = input('Введіть рядок: ') #вводимо рядок b = input('Введіть шуканий підрядок: ') #вводимо шуканий підрядок i = a.find(b) k = 0 if i >= 0: #функція find поветрає індекс елемента або -1, якщо збігів немає print(f'Збіг знайдено на {i} позиції') k = i+len(b) ''' к-сть перевірок дорівнює: індексу знайденого елеманта + довжина шуканого рядка, тому що програма не зупитається на знаходжені збігу першого елемента ''' if k == 1: print(f'Зроблено {k} перевірку') elif 1 < k < 5: print(f'Зроблено {k} перевірки') else: print(f'Зроблено {k} перевірок') else: print('Збігів немає') print(f'Зроблено {len(a)} перевірок')
# Data.py # # # This will be the module that handles the data we need for testing and training our neural network. # It will also deal with the extracted objects of the actual data # # # load necessary libraries # from scipy import ndimage # from scipy import misc # import matplotlib.pyplot as plt # import os import numpy as np import cPickle import random """ function to open the file containing MNIST data and return training data, test data, and validation data in a tuple def num_load(): (training_data, testing_data, validation_data) # open file containing desired data # load data into variables (np_arrays or similar structures) with cPickle library or similar # reshape data as desired to pass into recognition.py # close the file # return the tuple of variables""" def alpha_load(): # load raw testing and training sets f = open('alphabets2.pkl', 'rb') u_data, l_data = cPickle.load(f) f.close() # use our dividing function to get a training and testing set train_set, test_set = divide_data(u_data, l_data) # init new data sets (list of input arrays, list our output vector) training_data = [] testing_data = [] # reshape training and testing data to fit our neural network better for alph in train_set: for im, ltr in alph: training_data.append((np.reshape(im, (784, 1)), output_vec(ltr))) for test_list in test_set: for array, output in test_list: testing_data.append((np.reshape(array, (784, 1)), output_vec(output))) # return newly formatted data return (training_data, testing_data) def divide_data(u_data, l_data): # define size of data sets test_size = 200 # randomly shuffle random.shuffle(u_data) random.shuffle(l_data) u_test = u_data[1:(test_size-1)] u_train = u_data[test_size:] l_test = l_data[1:(test_size-1)] l_train = l_data[test_size:] test_data = l_test + u_test random.shuffle(test_data) train_data = l_train + u_train random.shuffle(train_data) return train_data, test_data def output_vec(ltr): out = np.zeros((52, 1)) if ord('A') <= ord(ltr) <= ord('Z'): out[ord(ltr) - ord('A')] = 1.0 return out elif ord('a') <= ord(ltr) <= ord('z'): ind_out = 26 + (ord(ltr) - ord('a')) out[ind_out] = 1.0 return out # loading wrapper for extracted (real) data def extracted_load(extracted_data): return [(np.resize(im, (784, 1)), crd) for im, crd in extracted_data]
''' Constraints are a simple library of checks for validating simple attributes in model objects. Created on Oct 24, 2014 @author: vsam ''' # # Constraint checking classes # class ConstraintViolation(ValueError): """Thrown by Constraint objects when the constraint is not true. """ def __init__(self, constraint, args, kwargs): super().__init__(constraint, args, kwargs) self.constraint = constraint self.call_args = args self.call_kwargs = kwargs @property def message(self): msg = "{0} failed".format(self.constraint) if len(self.call_args)==1 and len(self.call_kwargs)==0: msg += " for {0}".format(repr(self.call_args[0])) elif len(self.call_args)+len(self.call_kwargs)>0: alist = [] for a in self.args: alist.append(repr(a)) for k in self.call_kwargs: alist.append("{0}={1}", k, repr(self.call_kwargs[k])) alist.append(")") msgargs = ','.join(alist) msg = "{0} for({1})".format(msg,msgargs) return msg def __str__(self): return self.message class Constraint: """A generic callable class for constraints. A constraint is defined by a predicate (any callable) and an info (a string). Constraints can be combined by the &, | and - operator (conjunction, disjunction and negation respectively). Constraints are callable objects. When applied on some arguments, they invoke their predicate. If the predicate returns false, a ConstraintViolation is raised. Any exceptions thrown by the predicate are propagated. """ def __init__(self, func, info="unlabeled"): """Create a new constraint. func - a callable that implements the check info - a string describing the check """ if not callable(func): raise TypeError("A callable is expected for func") if not isinstance(info, str): raise TypeError("A string is expected for info") self.func=func self.info=info def __call__(self, *args, **kwargs): """Call func with given args. If the result is false, raise ConstraintViolation """ if not self.func(*args, **kwargs): raise ConstraintViolation(self, args, kwargs) def negated(self): """Return a new Constraint object with negated semantics.""" func = lambda *args, **kwargs: not self.func(*args, **kwargs) info = ("NOT "+self.info) if self.info!="unlabeled" else "unlabeled" return Constraint(func, info) def __neg__(self): """Return self.negated()""" return self.negated() def __or__(self, other): """Return a Constraints object for the disjunction of self and other.""" if isinstance(other, Constraint): return Constraints(self, other, any=True) else: return Constraints(self, Constraint(other), any=True) def __and__(self, other): """Return a Constraints object for the conjunction of self and other.""" if isinstance(other, Constraint): return Constraints(self, other) else: return Constraints(self, Constraint(other)) def __str__(self): return "Constraint({0})".format(self.info) def __repr__(self): cls = type(self) return "<{0}.{1} object '{2}' at {3:x}>".format(cls.__module__, cls.__name__, self.info, id(self)) class Constraints(Constraint): """This is a simple class to aggregate constraints. Constraints are aggregated either conjunctively or disjunctively. It takes care of several issues, such as constructing a composite info message from all info messages. """ def __init__(self, *args, any=False): """Initialize a Constraints object with a sequence of args. If any is True, the aggregate constraint is the disjunction of the operands, else it is the conjunction (default). """ self.constraints = [] self.__any = any self.__func = None self.__info = None for a in args: self.add(a) def __changed(self): self.__func = None self.__info = None @property def info(self): def paren(label): if " AND " in label or " OR " in label: return "(%s)" % label else: return label if self.__info is None: infos = [paren(c.info) for c in self.constraints] # parenthesize as needed conn = " OR " if self.any else " AND " self.__info = conn.join(infos) return self.__info @property def any(self): return self.__any @property def func(self): if self.__func is None: # Create an optimized function if len(self.constraints)==0: if self.any: self.__func = lambda *args, **kwargs: False else: self.__func = lambda *args, **kwargs: True elif len(self.constraints)==1: self.__func = self.constraints[0].func else: if self.any: self.__func = lambda *args, **kwargs: any(c.func(*args, **kwargs) for c in self.constraints) else: self.__func = lambda *args, **kwargs: all(c.func(*args, **kwargs) for c in self.constraints) return self.__func def add(self, c, info=None): if isinstance(c, Constraints) and self.any==c.any: self.constraints.extend(c.constraints) elif isinstance(c, Constraint): self.constraints.append(c) elif callable(c): if info is not None: self.constraints.append(Constraint(c, info)) elif hasattr(c, '__name__'): self.constraints.append(Constraint(c, c.__name__)) else: self.constraints.append(Constraint(c)) else: raise TypeError("Cannot add non-callable") self.__changed() def __all(self, *args, **kwargs): for constraint in self.constraints: constraint(*args, **kwargs) def __any(self, *args, **kwargs): for c in self.constraints: if success(c, *args, **kwargs): return True raise ConstraintViolation(self, args, kwargs) def negated(self): negc = Constraints(any=not self.any) for c in self.constraints: negc.add(c.negated()) return negc def __iter__(self): return iter(self.constraints) # # Schema validation # def success(constr, *args, **kwargs): """Return False if the call constr(*args, **kwargs) raises ConstraintViolation, else return True. Other exceptions raised by constr are propagated. """ try: constr(*args, **kwargs) return True except ConstraintViolation: return False # specialization for constraints classes NULL = Constraint(lambda x: x is None, "null") NONNULL = Constraint(lambda x: x is not None, "not null") class HAS_TYPE(Constraint): def __init__(self, *types): info = "instance of " + (" or ".join(t.__name__ for t in types)) super().__init__(lambda x: isinstance(x,types), info) self.types = types class BETWEEN(Constraint): def __init__(self, a,b): info = "between {0} and {1}".format(a,b) super().__init__(lambda x: (x>=a) and (x<=b), info) self.low = a self.high = b class GREATER(Constraint): def __init__(self, val): super().__init__(lambda x: x>val, "greater than {0}".format(val)) self.value = val def negated(self): return LESS_OR_EQUAL(self.value) class GREATER_OR_EQUAL(Constraint): def __init__(self, val): super().__init__(lambda x: x>=val, "greater than or equal to {0}".format(val)) self.value = val def negated(self): return LESS(self.value) class LESS(Constraint): def __init__(self,val): super().__init__(lambda x: x<val, "less than {0}".format(val)) self.value = val def negated(self): return GREATER_OR_EQUAL(self.value) class LESS_OR_EQUAL(Constraint): def __init__(self,val): super().__init__(lambda x: x<=val, "less than or equal to {0}".format(val)) self.value = val def negated(self): return GREATER(self.value) class LENGTH(Constraint): def __check_lengths(self, maximum, minimum): if not (maximum is None or isinstance(maximum, int)): raise TypeError("int or None expected") if not (minimum is None or isinstance(minimum, int)): raise TypeError("int or None expected") if maximum is None and minimum is None: raise ValueError("length limits are both None") if not (maximum is None or minimum is None or maximum>=minimum): raise ValueError("incompatible length limits") def __init__(self, maximum=None, minimum=None): self.__check_lengths(maximum, minimum) info_list = [] if minimum is not None: info_list.append("at least {0}".format(minimum)) if maximum is not None: info_list.append("at most {0}".format(maximum)) info = "length is "+" and ".join(info_list) if minimum is None: func = lambda x: len(x)<=maximum elif maximum is None: func = lambda x: len(x)>=minimum else: func = lambda x: minimum <= len(x) <= maximum super().__init__(func, info) self.minimum = minimum self.maximum = maximum def HAS_ATTR(*attr): if len(attr)>1: info = "has attributes " + (','.join(attr)) elif len(attr)==1: info = "has attribute {0}".format(attr[0]) else: info = "true" return Constraint(lambda x: all(hasattr(x,a) for a in attr) , info) def MISSING_ATTR(a): return Constraint(lambda x: not hasattr(x,a), "missing attribute {0}".format(a)) def NOT(c): if not isinstance(c, Constraint): raise TypeError("Constraint expected") return c.negated() def is_legal_identifier(name): import keyword import re return isinstance(name, str) and re.match("[_A-Za-z][_a-zA-Z0-9]*$",name) \ and not keyword.iskeyword(name) LEGAL_IDENTIFIER = Constraint(is_legal_identifier, "is legal identifier") CALLABLE = Constraint(callable, "is callable")
import numpy as np from scipy import stats class n_armed_bandit(object): ''' Class that simulates a n-armed bandit problem. (https://en.wikipedia.org/wiki/Multi-armed_bandit) On this implementation, all the n armed bandits give rewards generated from normal distributions. ''' def __init__(self, n = 10, vec_mu_std=None): ''' Initiates the n_armed_bandit Parameters: ----------- n: integer, > 0, default=10 The number of armed bandits. vec_mu_std: array of n tuples (mu,std), default None mu is the mean of the normal distribution and std its standard deviation. If None is passed, then an array with uniform values in the intervals [0,1] for mu and [0,1] for std are generated. ''' if n <=0: raise ValueError('\'n\' should be greather than 0') self.n = int(n) self.vec_mu_std = vec_mu_std if self.vec_mu_std is None: self.vec_mu_std = [(np.random.uniform(0,1),np.random.uniform(0,1)) for _ in range(n)] elif n != len(self.vec_mu_std): raise ValueError('Incoherent value of \'n\' and the size of \'vec_mu_std\'') self.vec_armed_bandits = [stats.norm(loc=i[0],scale=i[1]) for i in self.vec_mu_std] def get_mus(self): ''' Returns the real expected value (mu) of each normal distribution ''' return np.array([i[0] for i in self.vec_mu_std]) def query_max(self): ''' Querys the max mean expected reward. Returns: -------- max_: float The maximum expected reward. ''' max_ = -float(inf) for t in self.vec_mu_std: if t[0] > max_: max_ = t[0] return max_ def query(self,i): ''' Query the ith armed_bandit. Parameters: ----------- i: integer > 0 and < n The position of the armed bandith that should be quered. Returns: -------- sample: float A sample from the normal distribution of the ith armed bandith. ''' if i < 0 or i >= self.n: raise ValueError('Wrong value for \'i\'. Should be in the interval 0 < \'i\' < \'n\'.') i = int(i) return self.vec_armed_bandits[i].rvs() def run_step(self): ''' Runs one step of the n-armed bandith problem. Returns: -------- rewards: np.array of floats, [n,] The rewards of each armed bandit. ''' rewards = [self.query(i) for i in range(self.n)] return np.array(rewards) def run_steps(self,n_steps=1000): ''' Run multiple steps of the n-armed bandit. Parameters: ----------- n_steps: integer, >0 The number of steps to be run. Returns: -------- M: np.array, [n_steps,n] A matrix containig the rewards in each step ''' M = np.array([self.run_step() for _ in range(n_steps)]) return M def get_optimal(self,M): ''' Gets the optimal action-reward in all steps of matrix M Parameters: ----------- M: np.array [n_steps,n] Matrix containing the rewards in each step Returns: -------- vec: np.array [n_steps,] Vector of the optimum cummulative reward after each step. ''' vec = np.array([M[i,np.argmax(np.mean(M[:(i+1)],axis=0))] for i in range(M.shape[0])]) return np.cumsum(vec) def get_greedy(self,M): ''' Gets the greedy reward from the steps in M Parameters: ----------- M: np.array [n_steps,n] Matrix containing the rewards in each step Returns: -------- vec: np.array [n_steps,] Vector of th cummulative reward using the greedy strategy. ''' st = [[0] for _ in range(M.shape[1])] dic_st = dict((i,val) for i,val in enumerate(st)) vec = np.zeros((M.shape[0],)) for i in range(M.shape[0]): max_i = max(dic_st.items(), key=operator.itemgetter(1))[0] choice = M[i,max_i] st[max_i].append(choice) dic_st[max_i] = np.mean(st[max_i]) vec[i] = choice return np.cumsum(vec) def get_eta(self,M,eta=0.1): ''' Get the reward from the steps in M using the eta strategy. Parameters: ----------- M: np.array [n_steps,n] Matrix containing the rewards in each step eta: float, 0 > eta < 1 The eta parameter from the strategy. When eta=0 it is the greedy strategy, when eta=1 is the random strategy. Returns: vec: np.array [n_steps,] Vector of th cummulative reward using the eta strategy. ''' pos_greedy = np.argmax(M[0]) vec = np.zeros((M.shape[0])) for i in range(M.shape[0]): if np.random.uniform() < eta: pos_greedy = np.argmax(np.mean(M[:i],axis=0)) vec[i] = M[i,pos_greedy] return np.cumsum(vec) def run_multiple_times(self,n_times=2000,n_steps=1000): ''' Run the steps multiple times Parameters: ----------- n_times: integer, > 0 The number of times that the steps should be runned. n_steps: integer, >0 The number of steps Returns: -------- The optimal and greedy rewards on the steps ''' grd = np.zeros((n_times,n_steps)) opt = np.zeros((n_times,n_steps)) for i in range(n_times): M = self.run_steps(n_steps) grd[i] = self.get_greedy(M) opt[i] = self.get_optimal(M) return grd,opt
""" 题目描述: 依次给出n个正整数A1,A2,… ,An,将这n个数分割成m段,每一段内的所有数的和记为这一段的权重, m段权重的最大值记为本次分割的权重。问所有分割方案中分割权重的最小值是多少? """ #考虑如果最多可以将这n个数分割成n段,最小就先是1段吧,然后就可以开始二分查找了 #利用二分逼近法来求解:用x def S(arr, m): #最小值为max(arr),即分割长度为1 left = max(arr) right = sum(arr) while left < right: mid = (left + right)>>1 sets = 1 cur = 0 for num in arr: #讲数组分段,如果分段长度大于mid,则组数+1,cur重新置为0 if cur + num > mid: sets += 1 cur = 0 cur += num #如果分的集合太多,那么需要增大权重 if sets > m: left = mid+1 #否则集合可能小于等于m,需要减少权重,知道,但是可能包含right这边的情况,所以right是mid,而不是mid-1 else: right = mid return left import sys lines = sys.stdin.readlines() s = [] for line in lines: s.append(list(map(int,line.split()))) n, m = s[0] arr = s[1] print(S(arr,m))
#法一:回溯法,好像时间通不过 class Solution1: def canJump(self, nums:[int]) -> bool: length = len(nums) flag1 =False def backtrace(k): if k >=length-1: return True for i in reversed(range(nums[k])): flag2 = backtrace(k+i+1) if flag2: return True return False flag1 = backtrace(0) return flag1 solution = Solution1() print(solution.canJump([3,2,1,0,4])) #自底向上的动态规划,还是超时了 class Solution: def canJump(self, nums:[int]) -> bool: length = len(nums) dp = [False]*(length-1)+[True] for i in reversed(range(length-1)): for j in range(nums[i]): if dp[j+1+i] ==True: dp[i] =True break return dp[0] solution2 = Solution() print(solution2.canJump([3,2,1,0,4])) class Solution3: def canJump(self, nums:[int]) -> bool: length = len(nums) last = length-1 for i in reversed(range(length-1)): if i+nums[i] >=last: last = i return last ==0
""" 快速排序,paritition 非递归版本实现, """ def quicksort(alist,start,end): #如果只剩一个或0个元素,返回 if start>=end: return m = start for i in range(start+1,end+1): #因为m记录的是从左往右的第一个大于start的下标的前面一个位置 #如果alist[i]小于中枢元素,那么肯定被交换到前面了 if alist[i] <alist[start]: m+=1 alist[i],alist[m] = alist[m],alist[i] alist[start],alist[m] = alist[m],alist[start] quicksort(alist,start,m-1) quicksort(alist,m+1,end) unsortedArray = [6, 5, 3, 1, 8, 7, 2, 4] quicksort(unsortedArray, 0, len(unsortedArray) - 1) print(unsortedArray)
#Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: if not root: return False sum-=root.val if not root.left and not root.right and sum == 0: return True return self.hasPathSum(root.left) or self.hasPathSum(root.right) def hasPathSum2(self,root,sum): if not root: return False de = [(root,sum-root.val)] while de: node,cur_sum = de.pop() if not node.left and not node.right and cur_sum ==0: return True if node.right: de.append((node.right,cur_sum-node.right.val)) if node.left: de.append((node.left,cur_sum-node.left.val)) return False
def pluswithout(num1,num2): while True: sum = num1 ^num2 #一定不要忘记这里的左移一位 carry = (num1 & num2) <<1 num1= sum num2 = carry if num2 ==0: break return num1 print(pluswithout(2,1))
import random class Solution: def __init__(self, nums): self.init = list(nums) self.nums = nums self.length = len(nums) def reset(self) -> [int]: """ Resets the array to its original configuration and return it. """ self.nums = list(self.init) return self.nums def shuffle(self): """ Returns a random shuffling of the array. :rtype: List[int] """ for i in reversed(range(self.length)): index = random.randint(0, i) self.nums[i], self.nums[index] = self.nums[index], self.nums[i] return self.nums """这个题目下面的提示reset和shuffle都赋值了,所以这两个函数是需要返回变量的。""" # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
# class Solution: # def combinationSum(self, candidates, target: int): # result = [] # def backtrace(candidates=candidates,target=target,tmp=[]): # if target == 0: # result.append(tmp) # return # for i in candidates: # if (target-i)>=0: # backtrace(candidates,target-i,tmp+[i]) # else: # break # candidates = sorted(candidates) # backtrace() # return result """ 注意对比我一开始的代码和人家的代码,我的代码中没有排除多余的组合,即2,2,3和3,2,2都返回出去了。 看看人家,就知道了在backtrace时传入i,在利用for j in range(i,n) 那么进行深度优秀搜索的时候就只考虑i下标后的元素。 """ # # class Solution: def combinationSum(self, candidates, target: int): candidates.sort() n = len(candidates) res = [] def backtrack(i, tmp_sum, tmp): if tmp_sum > target or i == n: return if tmp_sum == target: res.append(tmp) return for j in range(i, n): if tmp_sum + candidates[j] > target: break backtrack(j, tmp_sum + candidates[j], tmp + [candidates[j]]) backtrack(0, 0, []) return res """这种模板也比较好,可以参考下,就是说下条路继续走这条路,or下条路走其他选择了""" class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: candidates.sort() n = len(candidates) res = [] def helper(i, tmp_sum, tmp): if tmp_sum > target or i == n: return if tmp_sum == target: res.append(tmp) return helper(i, tmp_sum + candidates[i],tmp + [candidates[i]]) helper(i+1, tmp_sum ,tmp) helper(0, 0, []) return res solution = Solution() print(solution.combinationSum([2,3,6,7],7))
#Función por cada uno de los puntos# ##devolver número elevado al cuadrado def numeroalCuadrado (numero): return numero**2 num1= numeroalCuadrado(6) print (f"El número dado elevado a la dos es {num1}") ##devolver número elevado a la 3 def numeroalCubo (numero): return numero**3 num2= numeroalCubo(6) print (f"El número dado elevado a la tres es {num2}") ##devolver número elevado a la 4 def numeroalaCuatro (numero): return numero**4 num3= numeroalaCuatro(6) print(f"El número dado elevado a la cuatro es {num3}") ##devolver número elevado a la 5 def numeroalaCinco (numero): return numero**5 num4= numeroalaCinco(6) print(f"El número dado elevado a la cinco es {num4}") ##Función dada otra función anterior muestre el resultado de las mismas def operacionNueroElev (operacion, numero): print (operacion(numero)) operacionNueroElev (numeroalCuadrado,5) operacionNueroElev (numeroalCubo,4) operacionNueroElev (numeroalaCuatro,8) operacionNueroElev (numeroalaCinco,9) #Clases# #Doctor class Doctor: def __init__ (self, idIng, nombreIng, sexoIng, universidadIng) : self.id = idIng self.nombre = nombreIng self.sexo = sexoIng self.universidad = universidadIng def atributos(self): print(f"Hola soy el Doctor {self.nombre} de sexo {self.sexo} y soy egresado de la universidad {self.universidad}") def sintomas (self, lista): for elemento in lista: print (elemento) doctor1 = Doctor (21365289, "Felipe", "masculino", "Ces") listaSintomas = ["tos", "dolor de cabeza", "fiebre", "malestar", "dolor de garganta"] doctor1.atributos() doctor1.sintomas(listaSintomas) #Neurologo class Neurologo (Doctor): def __init__ (self, idIng, nombreIng, sexoIng, universidadIng, experienciaIng, consultorioIng, salarioIng) : Doctor.__init__(self, idIng, nombreIng, sexoIng, universidadIng) self.experiencia = experienciaIng self.consultorio = consultorioIng self.salario = salarioIng def atributos (self): print(f"Hola soy el Doctor {self.nombre} de sexo {self.sexo} y soy egresado de la universidad {self.universidad} con experiencia de {self.experiencia}, trabajo en el consultorio {self.consultorio} y tengo un salario de {self.salario}") def pacientes (self, lista): for elemento in lista: print (f"el paciente a seguir es : {elemento}") doctor1= Neurologo (682746834, "Felipe", "masculino", "ces", 5, 107, 7200000 ) listaPacientes = ["Camilo", "Esteban", "Julian", "Mariana"] doctor1.atributos() doctor1.pacientes(listaPacientes) #Cárdiologo class Cardiologo (Doctor): def __init__ (self, idIng, nombreIng, sexoIng, universidadIng, experienciaIng, consultorioIng, salarioIng, habitacionesIng) : Doctor.__init__(self, idIng, nombreIng, sexoIng, universidadIng) self.habitaciones = habitacionesIng self.experiencia= experienciaIng self.salario = salarioIng self.consultorio = consultorioIng def atributos (self): print (f"Hola soy el Doctor {self.nombre} de sexo {self.sexo} mi numero de identificación es {self.id} y soy egresado de la universidad {self.universidad} con experiencia de {self.experiencia}, trabajo en el consultorio {self.consultorio} y tengo un salario de {self.salario}, hay {self.habitaciones} disponibles") def sintomas (self, lista): for elemento in lista: print (elemento) print ("Ya sé que tiene el paciente") doctor3=Cardiologo (654348326, "Pedro", "Masculino", "UPB", 7, 23, 8000000, 7) listaSintomas2 = ["tos", "dolor de cabeza", "fiebre", "malestar", "dolor de garganta"] doctor3.atributos() doctor3.sintomas(listaSintomas2)
def sumar (valor1=0, valor2=0): return valor1+ valor2 def restar (valor1=0, valor2=0): return valor1 - valor2 def multiplicar (valor1=0, valor2=1): return valor1 * valor2 def dividir (valor1=0, valor2=1): return valor1 / valor2 def calculadora (accion, valor1, valor2): print (accion(valor1, valor2))
#https://checkio.org/ #https://www.codewars.com/ #https://ru.khanacademy.org/ #https://ide.c9.io/tolearn/ruby foo=lambda a,b:a+b print foo(10,20) fooKub=lambda a:a*a*a print fooKub(10) print foo print (lambda x:x**3)(10) def foo(n): def foo2(m): return n+m return foo2 f=foo(100) print f(1),f(2),f(200) print foo,foo(2),foo(2)(3) r=round def my(foo,n): return foo(n) print my(r,2.5) print r(1.2) def my2(a,b,n=2): return a+b+n print my2(1,2),my2(1,2,3) def my3(a,b,n=2,m=3): return a+b+n print my3(1,2),my3(1,2,m=10,n=30) def my4(*a): return sum(a) # print (*a) print my4(*[1,2,3]) print sum([1,2,3]) print my4(),my4(1),my4(*range(10)) def my5(*a): a=list(a) a[0]+=10 return sum(a)*2 print my5(2,3,1,22) def d(f): def w(*a): print a rez=f(*a) print rez return rez return w my2=d(my2) print my2(1,2)
l=[1,2,1,3,2] n=[] h=[] for i in l: if not i in n: n.append(i) print n #def foo(): # a,b=10,20 # c=a+b # print c #for i in range(2): # foo() #def foo(a,b): # print a+b #foo(2,4) #foo(5,6) #for k in range(10): # foo(k,k+1) def foo(a,b): return a+b print foo(2,5) def ku(n): return n+n print ku(2) print ku("privet") print foo("la","la")
def recursive_min(nested_num_list): """ >>> recursive_min([2, 9, [1, 13], 8, 6]) 1 >>> recursive_min([2, [[100, 1], 90], [10, 13], 8, 6]) 1 >>> recursive_min([2, [[13, -7], 90], [1, 100], 8, 6]) -7 >>> recursive_min([[[-13, 7], 90], 2, [1, 100], 8, 6]) -13 """ minimum = nested_num_list[0] while type(minimum) == type([]): minimum = minimum[0] for element in nested_num_list: if type(element) == type([]): min_of_elem = recursive_min(element) if min_of_elem < minimum: minimum = min_of_elem else: if element < minimum: minimum = element return minimum if __name__ == '__main__': import doctest doctest.testmod()
def is_divisible_by_n(x, n): if x % n == 0: print "Yes,", x, "is divisible by", n else: print "No," x, "is not divisible by", n
#!/usr/bin/env python from gasp import * PLAYER_1_WINS = 1 PLAYER_2_WINS = 0 QUIT = -1 # def distance(x1, y1, x2, y2): # return ((x2 - x1)**2 + (y2 - y1)**2)**0.5 def hit(bx, by, r, px, py, h): """ >>> hit(760, 100, 10, 780, 100, 100) False >>> hit(770, 100, 10, 780, 100, 100) True >>> hit(770, 200, 10, 780, 100, 100) False >>> hit(770, 210, 10, 780, 100, 100) False """ dis_x = abs(px - bx) <= r dis_y = by <= (py + h / 2) and by >= (py - h / 2) return dis_x and dis_y def play_round(): ball_x = 400 ball_y = 300 ball = Circle((ball_x, ball_y), 10, filled=True, color=color.WHITE) if random_between(0, 1) == 1: dx = 4 else: dx = -4 dy = random_between(-5, 5) mitt1_x = 0 mitt1_y = random_between(20, 280) mitt1 = Box((mitt1_x, mitt1_y), 20, 80, filled=True, color=color.BLUE) mitt2_x = 780 mitt2_y = random_between(20, 280) mitt2 = Box((mitt2_x, mitt2_y), 20, 80, filled=True, color=color.RED) while True: if ball_y >= 590 or ball_y <= 10: dy *= -1 ball_x += dx ball_y += dy if ball_x > 800: remove_from_screen(ball) remove_from_screen(mitt1) remove_from_screen(mitt2) return PLAYER_1_WINS elif ball_x < 0: remove_from_screen(ball) remove_from_screen(mitt1) remove_from_screen(mitt2) return PLAYER_2_WINS move_to(ball, (ball_x, ball_y)) if key_pressed('a') and mitt1_y <= 520: mitt1_y += 5 elif key_pressed('s') and mitt1_y >= 0: mitt1_y -= 5 move_to(mitt1, (mitt1_x, mitt1_y)) if key_pressed('k') and mitt2_y <= 520: mitt2_y += 5 elif key_pressed('j') and mitt2_y >= 0: mitt2_y -= 5 move_to(mitt2, (mitt2_x, mitt2_y)) if key_pressed('q'): return QUIT # if distance(ball_x, ball_y, mitt_x, mitt_y) <= 30: # remove_from_screen(ball) # remove_from_screen(mitt) # return PLAYER_WINS if hit(ball_x, ball_y, 20, mitt1_x, mitt1_y, 80): dx *= -1 elif hit(ball_x, ball_y, 20, mitt2_x, mitt2_y,80): dx *= -1 if ball_x >= 800: remove_from_screen(ball) remove_from_screen(mitt1) remove_from_screen(mitt2) return PLAYER_1_WINS elif ball_x <= 0: remove_from_screen(ball) remove_from_screen(mitt1) remove_from_screen(mitt2) return PLAYER_2_WINS update_when('next_tick') def play_game(): player_1_score = 0 player_2_score = 0 while True: p1msg = Text("Player 1: %d Points" % player_1_score, (10, 570), color=color.WHITE, size=24) p2msg = Text("Player 2: %d Points" % player_2_score, (540, 570), color=color.WHITE, size=24) sleep(3) remove_from_screen(p1msg) remove_from_screen(p2msg) result = play_round() if result == PLAYER_1_WINS: player_1_score += 1 elif result == PLAYER_2_WINS: player_2_score += 1 else: return QUIT if player_1_score == 5: return PLAYER_1_WINS elif player_2_score == 5: return PLAYER_2_WINS begin_graphics(800, 600, title='Catch', background=color.BLACK) set_speed(120) result = play_game() if result == PLAYER_1_WINS: Text("Player 1 Wins!", (340, 290), color=color.WHITE, size=32) elif result == PLAYER_2_WINS: Text("Player 2 Wins!", (340, 290), color=color.WHITE, size=32) sleep(4) end_graphics()
""" This tester script checks if our machine learning model predicts the sentiments accurately or not! Steps: 1. Load the model from the pickle file 2. Get the user input, preprocess it (using helper script) and vectorize using TF-IDF 3. Check the model prediction on the result of step 2 a. Counter keeps the count of positive words in step 3. b. If count > length of words in step 2, sentiment is positive; else negative """ import pickle import math from helper import preprocess # Load the model from pkl files f = open('svm_model.pkl', 'rb') myfiles = pickle.load(f) f.close() # Segregate the model and vectorizer svc_model = myfiles[0] vectorizer = myfiles[1] # Perform prediction print("\n\033[1m\t\tMovie Review's Sentiment Analysis\033[0m\n") while True: count = 0 # This keeps the count of positive sentiments / word sentence = input("\n\033[93mPlease enter the review to get the sentiment evaluated. Enter \"exit\" to quit.\033[0m\n") if sentence == "exit": print("\033[93mexit program ...\033[0m\n") break else: input_features = preprocess(sentence) input_features = vectorizer.transform(input_features) prediction = svc_model.predict(input_features) for i in prediction: if i == 1: count += 1 if count > math.ceil(len(prediction)/2): print("---- \033[92mPositive Review\033[0m\n") else: print("---- \033[91mNegative Review\033[0m\n")
import os import math p = int(input('Enter the perpendicular')) b = int(input('Enter the breadth')) mcb = math.degrees(math.atan(p/b)) print('mcb',mcb)
import networkx as nx graph = nx.Graph() with open("input.txt") as file: edges = int(file.readline().split()[1]) for e in range(edges): u, v = (int(i) for i in file.readline().split()) graph.add_edge(u, v) subgraphs = list(graph.subgraph(c) for c in nx.biconnected_components(graph)) for sub in subgraphs: print(sub.edges()) try: cycle = nx.cycle_basis(graph) print(cycle) except: print("NO") print("")
#!/usr/bin/python3 import sys u = int(sys.argv[1]) v = int(sys.argv[2]) while v: t = u u = v v = t % v if u < 0: u = -u print("The gcd of", sys.argv[1], "and", sys.argv[2], "is", u);
## import modules here ################# Question 0 ################# def add(a, b): # do not change the heading of the function return a + b ################# Question 1 ################# def nsqrt(x): # do not change the heading of the function if x == 1: return 1 start = 1 end = x while start <= end: mid = (start + end) // 2 if mid**2 > x: end = mid - 1 elif mid**2 < x: start = mid + 1 else: return mid if mid**2 > x: return mid - 1 else: return mid # **replace** this line with your code ################# Question 2 ################# # x_0: initial guess # EPSILON: stop when abs(x - x_new) < EPSILON # MAX_ITER: maximum number of iterations ## NOTE: you must use the default values of the above parameters, do not change them def find_root(f, fprime, x_0=1.0, EPSILON = 1E-7, MAX_ITER = 1000): # do not change the heading of the function i = 0 x = x_0 while i < MAX_ITER: x_new = x - f(x)/fprime(x) print(x, x_new) if abs(x - x_new) < EPSILON: return x_new x = x_new i += 1 return x # **replace** this line with your code ################# Question 3 ################# class Tree(object): def __init__(self, name='ROOT', children=None): self.name = name self.children = [] if children is not None: for child in children: self.add_child(child) def __repr__(self): return self.name def add_child(self, node): assert isinstance(node, Tree) self.children.append(node) from collections import deque def make_tree(tokens): # do not change the heading of the function res = [] tokens = deque(tokens) while tokens: token = tokens.popleft() if token != ']': res.append(token) else: tok = res.pop() L = [] while tok != '[': if isinstance(tok, str): tok = Tree(tok) elif isinstance(tok, list): tok = Tree(res.pop(), tok) else: print("Panic") L.append(tok) tok = res.pop() res.append(L[::-1]) res = Tree(res[0], res[1]) return res # **replace** this line with your code def max_depth(root): # do not change the heading of the function if not root.children: return 1 else: depth = 1 for tree in root.children: child_depth = max_depth(tree) if child_depth >= depth: depth = child_depth return 1 + depth # **replace** this line with your code
''' Program for entering tasks into database ''' import sqlite3 from sqlite3 import Error import itertools from os.path import expanduser, join from pprint import pprint print('Enter tasks: ') print(''' ("commit" to commit to db, "clear" to delete tasks in buffer, "print" to show tasks in buffer, Ctrl-C to quit)''') print('') tasks = [] try: while True: line = input('> ') if line == 'commit': try: db_path = join(expanduser('~'),'.priorities.db') connection = sqlite3.connect(db_path) c = connection.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS tasks ( id integer PRIMARY KEY, priority integer NOT NULL, status integer, task text ); ''') for task in tasks: c.execute(''' INSERT INTO tasks (task, priority, status) VALUES (?, 0, 0); ''', (task,)) connection.commit() tasks = [] except Error as e: print(e) finally: connection.close() elif line == 'print': pprint(tasks) elif line == 'clear': while True: choice = input('Clear buffer? (y/n) ') choice = choice.upper() if choice in ['Y', 'N']: if choice == 'Y': tasks = [] break else: print('Invalid input. "y" or "n".') elif line == '': pass else: tasks.append(line) except KeyboardInterrupt: print('') print(tasks) print('')
# url: https://www.coursera.org/learn/programming-in-python/programming/0664k/diekorator-to-json from functools import wraps import json def to_json(func): @wraps(func) def wrapped(*args, **kwargs): result = func(*args, **kwargs) json_result = json.dumps(result) return json_result return wrapped @to_json def get_data(): return { 'data': 42, 'garbage' : [1, "text"], 'map': {1:['one'] }} print(get_data.__name__) result = get_data() print(result)
# -*- coding: utf-8 -*- """ Obtained from: https://gist.github.com/butla/2d9a4c0f35ea47b7452156c96a4e7b12 """ import time import socket def wait_for_port(port, host='localhost', timeout=5.0): """Wait until a port starts accepting TCP connections. Args: port (int): Port number. host (str): Host address on which the port should exist. timeout (float): In seconds. How long to wait before raising errors. Raises: TimeoutError: The port isn't accepting connection after time specified in `timeout`. """ start_time = time.perf_counter() while True: try: with socket.create_connection((host, port), timeout=timeout): break except OSError as ex: time.sleep(0.01) if time.perf_counter() - start_time >= timeout: raise TimeoutError('Waited too long for the port {} on host {} to start accepting ' 'connections.'.format(port, host)) from ex
''' Output ---------------------------------------------- without 0 : The RGB image will get displayed , with 0 : The GrayScale image will get displayed ''' import cv2 import numpy as np from PIL import Image # When the image file is read with the OpenCV function imread(), # the order of colors is BGR (blue, green, red). # On the other hand, in Pillow, the order of colors is assumed to be RGB (red, green, blue). # When reading a color image file, OpenCV imread() reads as a NumPy array ndarray of row (height) x column (width) x color (3). # The order of color is BGR (blue, green, red). img = cv2.imread('../Images and Videos/dog.png') ''' parameters 1. Shape - Height, Width, Color 2. dtype - type 3. type - Numpy ndarray ''' print('Original Image shape:', img.shape) # 3 Channel print('Original Image dtype:', img.dtype) print('Original Image type:', type(img)) # Display image # But when displaying the image, it show the image as RGB image instead BGR cv2.imshow('BGR_Image', img) # The OpenCV function imwrite() that saves an image assumes that the order of colors is BGR, # so it is saved as a correct image i.e. RGB image. cv2.imwrite('Save_Dog.png', img) # Convert RGB to Grayscale (1 Channel) gray = cv2.imread('../Images and Videos/dog.png', 0) print('Grayscale shape:', gray.shape) # Display image - Grayscale cv2.imshow('Grayscale', gray) # Pillow read the image as RGB image Pillow_Image = Image.open('../Images and Videos/dog.png') Pillow_Image.show() # We can not display pillow image using cv.imshow # To verify, whether the cv2.imread reads the image as BGR, we can use Image.fromarray(img) # The B,G,R ndarray value get's converted into Image BGR_Img = Image.fromarray(img) BGR_Img.show() # Save image using Pillow BGR_Img.save('Pillow_BGR.jpg') # Wait until ESC key is pressed cv2.waitKey(0) # Distroy windows that we have created cv2.destroyAllWindows()
import numpy as np # Sigmoid function def sigmoid(Z): A = 1/(1 + np.exp(-Z)) cache = Z return A, cache # Relu function def relu(Z): A = np.maximum(0, Z) cache = Z return A, cache """ Used in backpropagation dA -- post-activation gradient, of any shape dZ -- Gradient of the cost with respect to Z """ # Gradient of Sigmoid function def sigmoid_backward(dA, cache): Z = cache S = 1/(1 + np.exp(-Z)) dZ = dA * S * (1 - S) return dZ # Gradient of Relu function def relu_backward(dA, cache): Z = cache dZ = np.array(dA, copy=True) dZ[Z <= 0] = 0 return dZ
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head _next = head.next _next.next = head head.next = self.swapPairs(_next.next) return _next
from random import random import math TRAIN_LOOP = 3 TIME_PER_NEURON = 100 #time is a social construct. We don't need units! TIME_DIFF = 0.01 LOW_CURR = 2e-3 HIGH_CURR = 5e-3 ON_TRAIN = 1 OFF_TRAIN = -100 case_rates = {} negativeWeightCtr = 0 CTR = 100 def currToRate(curr): m = 3124.674377412921 b = 1.3024903596836612e-05 rate = (m * curr) + b return rate def rateToCurr(rate): m = 3124.674377412921 b = 1.3024903596836612e-05 curr = (rate - b) / m return curr class TrainingNeuron: def __init__(self, student): self.train = [] self.curr = 0 def updateCurrent(self, curr): self.curr = curr #calculate a "constant" current of spikes rate = currToRate(curr) timeDiff = 1/rate #set the spike train self.train = [] self.train.append(0) self.train.append(timeDiff) def updateCurrWithRate(self, rate): #calculate current self.curr = rateToCurr(rate) #calculate a "constant" current of spikes timeDiff = 1/rate #set the spike train self.train = [] self.train.append(0) self.train.append(timeDiff) class Neuron: def __init__(self): self.input = [] #this will contain objects of type "synapse" self.output = [] #this will contain objects of type "synapse" self.time = 0 #this is the neuron's internal clock, aka how all neurons synchronize themselves self.avgRate = 0 self.train = [] def runEulers(self): #get current- run performWeightedSum current = self.performWeightedSum() #Constants from the 1st assignment V_t = -0.040 #threshold voltage R_m = 10e6 #resistance constant C_m = 8e-3 #capacitance constant zeroed_time = 0 while True: V_curr = -0.080 while True: dV_dt = (current - (V_curr / R_m)) / C_m V_curr = V_curr + dV_dt * TIME_DIFF zeroed_time = zeroed_time + TIME_DIFF if V_curr > V_t: #print("spike") self.train.append(self.time + zeroed_time) #this means that a spike happened break if zeroed_time > TIME_PER_NEURON: break if zeroed_time > TIME_PER_NEURON: break def calculateAvgRate(self): if len(self.train) > 1: self.avgRate = 1/(self.train[1] - self.train[0]) else: self.avgRate = 0 def updateWeights(self): for synapse in self.input: if isinstance(synapse.pre, TrainingNeuron): continue #perform oja's rule #constants: L_R = 9e-7 #LEARNING_RATE #get avg rate of curr neuron and avg rate of prev neuron #TODO: switch v_i and v_j v_i = self.avgRate #Current (post-synaptic) v_j = synapse.pre.avgRate #Prev (pre-synaptic) #print("pre-update " + str(synapse.weight)) #run eulers on the synapse weight totalTime = 0 while True: dw_dt = (L_R * ((v_i * v_j) - (synapse.weight * (v_i**2)))) synapse.weight += dw_dt * TIME_DIFF totalTime += TIME_DIFF if totalTime >= TIME_PER_NEURON: break #print("post-update " + str(synapse.weight)) def updateNeuron(self): self.runEulers() self.calculateAvgRate() self.updateWeights() self.time += TIME_PER_NEURON print("avgRate: " + str(self.avgRate)) def performWeightedSum(self): totalCurrent = 0 for synapse in self.input: #LINE CORRESPONDING TO SPIKE RATE vs CURRENT EQUATION #y = 3124.674377412921x + 1.3024903596836612e-05 #is the equation, where y = spike rate, x = current m = 3124.674377412921 b = 1.3024903596836612e-05 if len(synapse.pre.train) > 1: spike_0_time = synapse.pre.train[0] spike_1_time = synapse.pre.train[1] rate = 1/(spike_1_time - spike_0_time) current = (rate - b)/m else: current = 0 current = current * synapse.weight totalCurrent += current return totalCurrent class Synapse: def __init__(self, pre, post): self.pre = pre self.post = post self.weight = random() / math.sqrt(32) def fullyConnect(arr1, arr2): for n1 in arr1: for n2 in arr2: newSynapse = Synapse(n1, n2) n1.output.append(newSynapse) n2.input.append(newSynapse) def makeSynapsesNegative(neur): for syn in neur.output: syn.weight *= -1 def main(): global case_rates layer1 = [] layer2 = [] layer3 = [] #I'M NOT SURE IF WEIGHTS HAVE TO INITIALLY ADD UP TO 1? #create 2 neurons in the 1st layer for i in range(2): layer1.append(Neuron()) #create 8 neurons in the 2nd layer for i in range(8): layer2.append(Neuron()) #create 2 neurons in 3rd layer for i in range(2): layer3.append(Neuron()) #fully connect all layers of NN fullyConnect(layer1, layer2) fullyConnect(layer2, layer3) makeSynapsesNegative(layer2[0]) makeSynapsesNegative(layer2[1]) print("LAYER 1") for neuron in layer1: for synapse in neuron.output: print(synapse.weight) print("LAYER 2") for neuron in layer2: for synapse in neuron.output: print(synapse.weight) #attach "training neurons" to 1st and 3rd layers #LAYER1 #create input neurons trainA = TrainingNeuron(None) trainB = TrainingNeuron(None) #create input synapses synA = Synapse(trainA, layer1[0]) synB = Synapse(trainB, layer1[1]) #set weight for input synapses: #TODO i'm just guessing values for now synA.weight = 1 synB.weight = 1 #attach synapses to postsynaptic neurons layer1[0].input.append(synA) layer1[1].input.append(synB) #LAYER3 #create training neurons trainLow = TrainingNeuron(None) trainHigh = TrainingNeuron(None) for lol in range(1,5): case_rates[lol] = currToRate(6.4e-5) #create training synapses synLow = Synapse(trainLow, layer3[0]) synHigh = Synapse(trainHigh, layer3[1]) print("TESTING") runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow, trainHigh, case=3, ctr=1) #attach synapses to postsynaptic neurons layer3[0].input.append(synLow) layer3[1].input.append(synHigh) #neural net time with training neurons! for r in range(3): runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow,trainHigh,case=4,ctr=1) runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow,trainHigh,case=3,ctr=1) runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow,trainHigh,case=2,ctr=1) runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow,trainHigh,case=1,ctr=1) #pop the training neurons and see if the net stil works (assuming last on list) for neuron in layer3: neuron.input.pop() print("TRAINED:") #neural net time without training neurons! runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow,trainHigh,case=3,ctr=1) runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow,trainHigh,case=2,ctr=1) runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow,trainHigh,case=1,ctr=1) def runNet(layer1, layer2, layer3, synLow, synHigh, trainA, trainB, trainLow, trainHigh, case, ctr): #TODO maybe my input weights aren't different enough? experiment global case_rates if case == 1: #A = 1, B = 1 trainA.updateCurrent(HIGH_CURR) trainB.updateCurrent(HIGH_CURR) synLow.weight = ON_TRAIN synHigh.weight = OFF_TRAIN trainHigh.updateCurrWithRate(case_rates[1]) trainLow.updateCurrWithRate(case_rates[1]) print("ASS: " + str(trainHigh.curr)) elif case == 2: #A = 1, B = 0 trainA.updateCurrent(HIGH_CURR) trainB.updateCurrent(LOW_CURR) synLow.weight = OFF_TRAIN synHigh.weight = ON_TRAIN trainHigh.updateCurrWithRate(case_rates[2]) trainLow.updateCurrWithRate(case_rates[2]) elif case == 3: #A = 0, B = 1 trainA.updateCurrent(LOW_CURR) trainB.updateCurrent(HIGH_CURR) synLow.weight = OFF_TRAIN synHigh.weight = ON_TRAIN trainHigh.updateCurrWithRate(case_rates[3]) trainLow.updateCurrWithRate(case_rates[3]) print("HOLE: " + str(trainHigh.curr)) else: #A = 0, B = 0 trainA.updateCurrent(LOW_CURR) trainB.updateCurrent(LOW_CURR) synLow.weight = ON_TRAIN synHigh.weight = OFF_TRAIN trainHigh.updateCurrWithRate(case_rates[4]) trainLow.updateCurrWithRate(case_rates[4]) for i in range(ctr): print("LAYER1") for n in layer1: #print("layer1 neuron") n.updateNeuron() print("LAYER2") for n in layer2: #print("layer2 neuron") n.updateNeuron() print("LAYER3") for n in layer3: #print("layer3 neuron") n.updateNeuron() deleteTrain(layer1) deleteTrain(layer2) deleteTrain(layer3) #update training weights if case == 1: case_rates[1] = max(layer3[0].avgRate,layer3[1].avgRate) * 0.7 #print("CASE1_RATE: " + str(case_rates[1])) elif case == 2: case_rates[2] = max(layer3[0].avgRate,layer3[1].avgRate) * 0.7 #print("CASE3_RATE: " + str(case_rates[2])) elif case == 3: case_rates[3] = max(layer3[0].avgRate,layer3[1].avgRate) * 0.7 #print("CASE3_RATE: " + str(case_rates[3])) elif case == 4: case_rates[4] = max(layer3[0].avgRate,layer3[1].avgRate) * 0.7 #print("CASE3_RATE: " + str(case_rates[4])) #print("TRAIN_WEIGHT: " + str(trainHigh.curr)) #update the training current #print("case " + str(case) + " low: " + str(layer3[0].avgRate) + " high: " + str(layer3[1].avgRate)) def deleteTrain(layer): for neu in layer: neu.train = [] if __name__ == "__main__": main()
# if x > 10: # add 2 to it # else: # multipy by 2 # def random(x) : return x + 2 print(random(10)) def number(x) : return x * 2 print(number(1))
''' Created on Mar 4, 2014 @author: kylerogers ''' class PageHelper: @staticmethod def get_request_count(request, default_count_per_page, max_count_per_page): ''' Finds the requested number of brothers and corrects it if there are any issues If the number is invalid, it will return standard_brothers_per_page ''' brothers_count = request.GET.get('count',str(default_count_per_page)) try: brothers_count = int(brothers_count) if brothers_count > max_count_per_page: brothers_count = max_count_per_page except: brothers_count = default_count_per_page return brothers_count @staticmethod def get_page_number(request): ''' Finds the page number and corrects it if there are any issues If the page number is invalid, it will return 1 ''' page_number = request.GET.get('page','1') try: page_number = int(page_number) if page_number < 1: page_number = 1 except: page_number = 1 return page_number @staticmethod def calculate_page_range(total_pages, page_number, max_pages_listed_on_screen): ''' This determines which page numbers to show at the bottom of the brothers list pages. It returns a list of integers that should be displayed on the page based on the total number of pages and the current page number. ''' if total_pages == 1: # If there is only the one page, there is no need to display page numbers return [] elif total_pages <= max_pages_listed_on_screen: # In this case, just display all of the available pages min_page_number_displayed = 1 max_page_number_displayed = total_pages + 1 elif page_number - max_pages_listed_on_screen / 2 <= 1: # We are near the beginning. In this case, display from page 1 to max_pages_listed_on_screen min_page_number_displayed = 1 max_page_number_displayed = min_page_number_displayed + max_pages_listed_on_screen elif page_number + max_pages_listed_on_screen / 2 >= total_pages: # We are near the end. In this case, display from (end - max_pages_listed_on_screen) to end max_page_number_displayed = total_pages + 1 min_page_number_displayed = max_page_number_displayed - max_pages_listed_on_screen else: # We are somewhere in the middle. In this case, just display some pages on either side min_page_number_displayed = page_number - max_pages_listed_on_screen / 2 max_page_number_displayed = min_page_number_displayed + max_pages_listed_on_screen page_numbers_list = range(min_page_number_displayed,max_page_number_displayed) return page_numbers_list
#!/usr/bin/env python def sink(alist, start, end): root = start while 2*root + 1 <= end: child = 2*root + 1 swap = root if alist[swap] <= alist[child]: swap = child if child+1 <= end and alist[swap] < alist[child+1]: swap = child + 1 if swap != root: alist[root], alist[swap] = alist[swap], alist[root] root = swap else: return def heapify(alist): start = (len(alist) - 2) / 2 while start >= 0: sink(alist, start, len(alist)-1) start -= 1 def heapsort(alist): '''Heapsort implementation.''' if type(alist) != list: raise TypeError, 'Expected list.' heapify(alist) end = len(alist) - 1 while end > 0: alist[end], alist[0] = alist[0], alist[end] end -= 1 sink(alist, 0, end) return alist
# -*- coding: utf-8 -*- """ Created on Sun Dec 8 11:42:04 2019 @author: MaxFelius TOOLBOX function to automatically create latex and csv tables Also flexibel to add and remove rows TODO -finish script -automatically copy the output table to clipboard TODO Class -finish empty function -move contents on self.Print() to self.Create() and let the rest call self.Create() -Add additional function to the latex script (centering, label, caption, first column with text) """ # imports import numpy as np import pyperclip class CreateTable(object): '''This will be an object that creates a table and can print/write the table to the desired format. The formats that are going to be implemented (for now) are csv and latex''' def __init__(self,header,headerC,*row): '''The input for this object should all be lists''' #Check if input is a list assert type(header) == list self.row = list(row) self.header = header self.headerC = headerC def __str__(self): '''This method will print the current object in csv format''' return self.Print('CSV') def Header(): pass def HeaderC(): pass def DeleteRow(): pass def NewRow(): pass def Options(): pass def Create(extension): if extension == 'Latex' or extension == 'latex': pass elif extension == 'csv' or extension == 'CSV': pass else: print('Please select the type of table you want to copy (Latex or CSV).') def Write(self,extension): if extension == 'Latex' or extension == 'latex': pass elif extension == 'csv' or extension == 'CSV': pass else: print('Please select the type of table you want to copy (Latex or CSV).') def Copy(self,extension): if extension == 'Latex' or extension == 'latex': pass elif extension == 'csv' or extension == 'CSV': pass else: print('Please select the type of table you want to copy (Latex or CSV).') def Print(self,extension): if extension == 'Latex' or extension == 'latex': output_object = '\\begin{table}[h!]\n' output_object = output_object + '\\begin{tabular}' numCol = np.shape(self.row)[1] output_object = output_object + '{'+'l'*numCol+'}\n\n' #header for index,item in enumerate(self.header): if index == len(self.header)-1: output_object = output_object + str(item) + '\\\ \n' else: output_object = output_object + str(item) + ' & ' output_object = output_object + '\hline\n' #body dim = np.shape(self.row) for rows in range(dim[0]): for index,item in enumerate(self.row[rows]): if index == len(self.row[rows])-1: output_object = output_object + str(item) + '\\\ \n' else: output_object = output_object + str(item) + ' & ' output_object = output_object + '\\end{tabular}\n' output_object = output_object + '\\end{table}\n' return output_object elif extension == 'csv' or extension == 'CSV': output_object = '#' #header for index,item in enumerate(self.header): if index == len(self.header)-1: output_object = output_object + str(item) + '\n' else: output_object = output_object + str(item) + ',' #body dim = np.shape(self.row) for rows in range(dim[0]): for index,item in enumerate(self.row[rows]): if index == len(self.row[rows])-1: output_object = output_object + str(item) + '\n' else: output_object = output_object + str(item) + ',' else: print('Please select the type of table you want to copy (Latex or CSV).') return output_object def CreateLatexTable(name,*rows): LatexTable =[] #output start = 'nothing' return LatexTable def _test(): header = ['bike','car'] row1 = [1,2] row2 = [3,4] row3 = [5,6] obj = CreateTable(header,None,row1,row2,row3) # print(obj) print(obj.Print('latex')) if __name__ == '__main__': _test()
''' 3-6. 더 많은 손님 식당에서 예약 인원을 늘릴 수 있다 하여 손님을 더 초대할 수 있습니다. 저녁에 초대할 사람을 세 명 더 생각하세요. - 연습문제 3-4나 3-5에서 프로그램을 시작하세요. 프로그램 마지막에 print문을 추가해 사람들에게 더 큰 저녁 식탁을 발견했다고 알리세요. - insert()를 써서 새 손님 한 명을 리스트 맨 앞에 추가하세요. - insert()를 써서 새 손님 한 명을 리스트 중간에 추가하세요. - append()를 써서 새 손님 한 명을 리스트 마지막에 추가하세요. - 리스트에 있는 각 손님 앞으로 새 초대 메시지를 출력하세요. Output: guido van rossum, please come to dinner. jack turner, please come to dinner. lynn hill, please come to dinner. Sorry, jack turner can't make it to dinner. guido van rossum, please come to dinner. gary snyder, please come to dinner. lynn hill, please come to dinner. We got a bigger table! frida kahlo, please come to dinner. guido van rossum, please come to dinner. reinhold messner, please come to dinner. lynn hill, please come to dinner. gary snyder, please come to dinner. elizabeth peratrovich, please come to dinner. '''
''' 4-7. 3배수 3부터 30까지 3의 배수로 리스트를 만드세요. for 루프를 써서 각 숫자를 출력하세요. Output: 3 6 9 12 15 18 21 24 27 30 ''' threes = list(range(3, 31, 3)) for number in threes: print(number)
''' 3-2. 단순한 메시지들 연습문제 3-1의 리스트를 활용합니다. 이번에는 바로 출력하지 말고 문장을 만드세요. 각 문장의 텍스트는 사람 이름만 다르고 나머지는 같게 해봅시다. 예를 들어 다음과 같이 출력하세요. Output: Hello, ron! Hello, tyler! Hello, dani! ''' names = ['ron', 'tyler', 'dani'] msg = 'Hello, ' + names[0] + '!' print(msg) msg = 'Hello, ' + names[1] + '!' print(msg) msg = 'Hello, ' + names[2] + '!' print(msg)
import intCodeProgram import matplotlib.pyplot as plt NORTH = 1 SOUTH = 2 WEST = 3 EAST = 4 DIRECTIONS = [NORTH, SOUTH, WEST, EAST] WALL = 0 MOVED = 1 MOVED_AND_GOAL = 2 def solve(intCode, mazeDict, wasHereDict, correctPathDict, directionIndex, x=0, y=0, ptr=0, relativeBase=0): outputVal, ptr, relativeBase = intCodeProgram.execute(intCode, [DIRECTIONS[directionIndex]], ptr, relativeBase) outputVal = outputVal[0] printMaze(mazeDict) if outputVal == MOVED_AND_GOAL: # if found print('found at %d,%d' % (x, y)) return True elif (x,y) in wasHereDict and wasHereDict[(x,y)] == '#': # if wall print('wall at %d,%d' % (x, y)) return False elif (x,y) in wasHereDict and wasHereDict[(x,y)] == '.': # if visited print('visited at %d,%d' % (x, y)) return False direction = DIRECTIONS[directionIndex] # get current direction if outputVal == WALL: if direction == NORTH: mazeDict[(x,y+1)] = '#' elif direction == SOUTH: mazeDict[(x,y-1)] = '#' elif direction == WEST: mazeDict[(x-1,y)] = '#' elif direction == EAST: mazeDict[(x+1,y)] = '#' directionIndex = directionIndex + 1 if directionIndex < 3 else 0 # change directions solve(intCode, mazeDict, wasHereDict, correctPathDict, directionIndex, x, y, ptr, relativeBase) if outputVal == MOVED: mazeDict[(x,y)] = '.' wasHereDict[(x,y)] = '.' # marked current position as visited if direction == NORTH: y += 1 elif direction == SOUTH: y -= 1 elif direction == WEST: x -= 1 elif direction == EAST: x += 1 mazeDict[(x,y)] = 'D' if solve(intCode, mazeDict, wasHereDict, correctPathDict, directionIndex, x, y, ptr, relativeBase): correctPathDict[(x,y)] = '.' return True directionIndex = directionIndex + 1 if directionIndex < 3 else 0 # change directions if solve(intCode, mazeDict, wasHereDict, correctPathDict, directionIndex, x, y, ptr, relativeBase): correctPathDict[(x,y)] = '.' return True directionIndex = directionIndex + 1 if directionIndex < 3 else 0 # change directions if solve(intCode, mazeDict, wasHereDict, correctPathDict, directionIndex, x, y, ptr, relativeBase): correctPathDict[(x,y)] = '.' return True directionIndex = directionIndex + 1 if directionIndex < 3 else 0 # change directions if solve(intCode, mazeDict, wasHereDict, correctPathDict, directionIndex, x, y, ptr, relativeBase): correctPathDict[(x,y)] = '.' return True # if solve(intCode, mazeDict, wasHereDict, correctPathDict, directionIndex, x, y, ptr, relativeBase): # correctPathDict[(x,y)] = '.' # return True #directionIndex = directionIndex + 1 if directionIndex < 3 else 0 return False def printMaze(mazeDict): # walls xWall = [i[0] for i in mazeDict.keys() if mazeDict[i] == '#'] yWall = [i[1] for i in mazeDict.keys() if mazeDict[i] == '#'] # path xPath = [i[0] for i in mazeDict.keys() if mazeDict[i] == '.'] yPath = [i[1] for i in mazeDict.keys() if mazeDict[i] == '.'] # drone xDrone = [i[0] for i in mazeDict.keys() if mazeDict[i] == 'D'] yDrone = [i[1] for i in mazeDict.keys() if mazeDict[i] == 'D'] plt.plot(xWall, yWall, 'ro', xPath, yPath, 'bo', xDrone, yDrone, 'yo') plt.grid(True) #plt.xticks([i for i in range(43)]) #plt.yticks([i for i in range(25)]) plt.show() def main(): intCode = intCodeProgram.readFile("day15/input.txt") # north = 1 # south = 2 # west = 3 # east = 4 mazeDict = dict() wasHereDict = dict() correctPathDict = dict() mazeDict[(0,0)] = 'D' wasHereDict[(0,0)] = 'D' solve(intCode, mazeDict, wasHereDict, correctPathDict, 0) printMaze(mazeDict) main()
#logistic Regression As a Neural Network #Note: #This is a basic perceptron #perception comes with stimulation. when an eye see the light, eye get stimulated and build the perception called vision #This gets a stimulus and percive value of the summation #What does the logictic regression mean #Logistic regression is a statistical model that in its basic form uses a # logistic function to model a binary dependent variable, although many more # complex extensions exist. In regression analysis, logistic regression (or # logit regression) is estimating the parameters of a logistic model (a form # of binary regression). Mathematically, a binary logistic model has a dependent # variable with two possible values, such as pass/fail which is represented by # an indicator variable, where the two values are labeled "0" and "1". In the logistic # model, the log-odds (the logarithm of the odds) for the value labeled "1" # is a linear combination of one or more independent variables ("predictors"); # the independent variables can each be a binary variable (two classes, coded # by an indicator variable) or a continuous variable (any real value). # The corresponding probability of the value labeled "1" can vary between # 0 (certainly the value "0") and 1 (certainly the value "1"), hence the labeling; # the function that converts log-odds to probability is the logistic function, # hence the name. -wiki import numpy as np import xlrd import math import plotly.graph_objects as go from plotly.subplots import make_subplots n_features = 3 alpha = 0.5 iterations =500 #graphs iterations_for_x = [] accuracy_for_y =[] weight_for_x = [] b_for_y = [] cost_for_z = [] def sigma(x): return 1/(1+np.e ** -x) def run(): # loading data from exel database1 = xlrd.open_workbook("D:/Projects/Git2/Old-School-Logistic-Regression-as-a-Neural-Network/fix_dataset2.xlsx") sheet = database1.sheet_by_index(0) fileds = [] m = sheet.nrows m_traning = math.floor(m*0.75) m_testing = math.floor(m*0.25) training_set = np.zeros((m_traning,sheet.ncols)) testing_set = np.zeros((m_testing,sheet.ncols)) for i in range(0,m_traning): for j in range(0,sheet.ncols): try: training_set[i][j] = sheet.cell_value(i,j) except: fileds.append(sheet.cell_value(i,j)) p=0; for i in range(m_traning,m): p = p + 1 for j in range(0,sheet.ncols): try: testing_set[p][j] = sheet.cell_value(i,j) except: fileds.append(sheet.cell_value(i,j)) training_set = np.delete(training_set,0,0) #Removing the top row testing_set = np.delete(testing_set,0,0) #Removing the top row training_dataset_shape = training_set.shape testing_data_shape = testing_set.shape #Input X_Train = np.transpose(np.delete(training_set,n_features,1)) # Removing output column which is last column X_Test = np.transpose(np.delete(testing_set,n_features,1)) #Output Y_Train = np.reshape(np.transpose(training_set[:,3]), (1,m_traning -1)) Y_Test = np.reshape(np.transpose(testing_set[:,3]), (1,m_testing -1)) print(X_Train.shape) print(X_Test.shape) print(Y_Train.shape) print(Y_Test.shape) #for i in range (0,iterations): def main(): run() if (__name__ == "__main__"): main()
''' Program: quadratic.py Written by: Elayna Ridley Purpose: To calculate the value of x. How to use: Enter three numbers eperated by a comma when prompted. Input: three numbers seperated by a comma. Output: The value x ''' import math print("Type in A, B, C as the coefficients of the quadratic equation.") temp = input("Enter three numbers separated by commas: ") a = float(temp.split(",")[0]) b = float(temp.split(",")[1]) c = float(temp.split(",")[2]) print("a = ",a) print("b = ",b) print("c = ",c) x = (-b + math.sqrt(b ** 2 - 4 * a * c))/(2 * a) z = (-b - math.sqrt(b ** 2 - 4 * a * c))/(2 * a) print ("x is",("%.2f" % x), "or", ("%.2f" % z))
# << Swami Shreeji >> # 4 Jan 2018 # You have a list of integers, and for each index you want to find the product # of every integer except the integer at that index. Write a function # get_products_of_all_ints_except_at_index() that takes a list of integers # and returns a list of the products. # Given: # [1, 7, 3, 4] # your function would return: # [84, 12, 28, 21] # by calculating: # [7 * 3 * 4, 1 * 3 * 4, 1 * 7 * 4, 1 * 7 * 3] ''' import numpy as np def get_products_of_all_ints_except_at_index(raw = []): # Find the product when all elems in list are multiplied together prod = np.prod(raw) # Divide out the unneeded element result = [] for elem in raw: subAns = prod / elem result.append(subAns) return result case1 = [1, 7, 3, 4] answer = get_products_of_all_ints_except_at_index(case1) print answer ''' # Now, redo question and DO NOT DIVIDE def get_products_of_all_ints_except_at_index(intList = []): prodSoFar = 1 prodOfAll_NotCurrent = [] # Find the product of all numbers before the current index for elem in intList: prodOfAll_NotCurrent.append(prodSoFar) prodSoFar *= elem # Get the prod of all numbers after the index, and multiply it by corresponding index # This gives the product of all numbers except at the current index prodSoFar = 1 i = len(intList) - 1 while i >= 0: prodOfAll_NotCurrent[i] *= prodSoFar prodSoFar *= intList[i] i -= 1 print prodOfAll_NotCurrent case1 = [3, 1, 2, 0, 6, 4] case2 = [1, 7, 3, 4] answer = get_products_of_all_ints_except_at_index(case1)
# Swami Shreeji # 7 Feb 2018 # Sorting names, instead of numbers. And get the most frequent name at the start def sortNames(names): # Check if in dict, increment if yes. Else, add to dict myDict = {} for elem in names: if elem in myDict: myDict[elem] += 1 else: myDict[elem] = 1 # Reverse sort and return based on values return sorted(myDict.items(), key = lambda x: x[1], reverse = True) names = ["Nishant", "Anand", "Anand", "Atmiya", "Atmiya", "Atmiya", "Lallu", "Sahaj", "Sahaj", "Sahil", "Hariprasad"] soln = sortNames(names) print soln
# << Swami Shreeji >> # 7 Jan 2018 # TASK: Using 2016_general.csv # Get the candidate with the most votes. # Get the votes of all candidates who ran for president and vp # NOTE: The csv data is raw. This means duplicates of candidates exist. # But those duplicates will have some differences - like votes across rows import csv from collections import defaultdict # Reading from CSV def prework(): # Holds OFFICE, CANDIDATE, and VOTES. Dups exist data = [] with open('2016_general.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: office_Cand_Votes = [ row['OFFICE'], row['CANDIDATE'], int (row['VOTES']) ] data.append(office_Cand_Votes) return data # Return candidate with highest votes def mostVoted(csvData): result = defaultdict(int) # Iterate through all items in csvData and sum candidate's votes. This # ensures that we can sum up votes for that candidate from other rows for item in csvData: office, candidate, votes = item result[candidate] += votes mostVotedCandidate = max(result, key = result.get) return mostVotedCandidate def pAndVPVotes(csvData): result = defaultdict(int) for item in csvData: if item[0] == 'PRESIDENT AND VICE PRESIDENT OF THE UNITED STATES': office, candidate, votes = item result[candidate] += votes return dict(result) csvData = prework() mostVotedCandidate = mostVoted(csvData) candsFor_P_VP = pAndVPVotes(csvData) print mostVotedCandidate print candsFor_P_VP
# << Swami Shreeji >> # 21 Nov 2017 # Algo --> Implementation --> Encryption import sys import string import math # Cases case0 = "ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots" # 54 PASS case1 = "haveaniceday" # 12 PASS case2 = "feedthedog" # 10 PASS case3 = "chillout" # 8 FAILS def encrypt(args): # Step 1: Remove all whitespace args = args.replace(" ","") argsLen = len(args) # Prelim setup cols = 0 rows = int (math.floor(math.sqrt(argsLen))) if rows * rows <= argsLen: cols = rows + 1 # Define rect dimensions rect = [["" for x in range(rows)] for x in range(cols)] # Step 2: Build rect colNum = 0 ; rowNum = 0 while True: for char in args: rect[colNum][rowNum] = char colNum += 1 if colNum == cols: rowNum += 1 colNum = 0 # Filter it. Ugly but works ... Come back to this antiSol = (', '.join(map(str, rect))) antiSol = antiSol.replace("],", "|") antiSol = antiSol.translate(None, '[,\'] ') antiSol = antiSol.replace("|", " ") print antiSol break encrypt(case0) encrypt(case1) encrypt(case2) # encrypt(case3) FAILS HERE
# Swami Shreeji # 7 Feb 2018 # Determine whether a string is a "lovely" string, meaning its characters are not repeated. # i.e. 123 is lovely, but nishant is not # NOTE: The answer is function is case sensitive. Add a lowercase if needed, use a set def lovely(case): answer = {} for elem in case: if len(set(elem)) == len(elem): answer[elem] = True return answer # Prepopulate case with numbers case = ["nishant", "Hariprasad", "Jasmine", "33", "Swami"] lovely = lovely(case) print lovely
''' 对内存操作——有操作字符串和二进制两种 字符串——StringIO 二进制——BytesIO stream position——流位置的概念,当初始化传入字符串的时候stream position的位置是0,当写入字符串的时候stream position的位置是写入字符串的长度 1. 可以通过tell()方法查看stream position的值 2. 可以通过seek(position)方法设置值,当设置position后,则read()方法从该position位置往后读取 3. 当调用write方法写入数据后stream position的值是根据写入的字符串长度变化的 4. 调用read()后stream position的值指向最后 5. 调用getvalue()后stream position的值与调用getvalue()之前相同 ''' from io import StringIO, BytesIO # 未初始化数据 s1 = StringIO() print('Before s1 write, s1\'s stream position is: ', s1.tell()) s1.write('Hello, Python!') print('After s1 write, s1\'s stream position is: ', s1.tell()) # read读取的是stream position之后的内容,写入是position为字符串的长度 if s1.read() == '': print('s1\'s read content is: empty!') else: print('s1\'s read content is: ', s1.read()) if s1.getvalue() == '': print('s1\'s getvalue content is: none') else: print('s1\'s getvalue content is: ', s1.getvalue()) print('+++++++++++++++++++++++++++++++++') b1 = BytesIO() b1.write('Python编程'.encode()) print('b1 getvalue: ', b1.getvalue()) print('Before seek: ') print('b1 read: ', b1.read()) b1.seek(0) print('After seek: ') print('b1 read: ', b1.read()) print('---------------------------------') # 初始化数据 s2 = StringIO('This is first string') print('Before s2 write, but set initial content, s2\'s stream position is: ', s2.tell()) print('I\'m reading the content: ', s2.read()) # read()方法读取完数据后stream position会移到最后 print('After reading, the stream position is: ', s2.tell()) # 固这里的stream position等于初始化字符串的长度 s2.write('This is second string') print('After s2 write, but set initial content, s2\'s stream position is: ',s2.tell()) #s2.seek(0) print('I\'m calling the getvalue function: ', s2.getvalue()) print('After getvalue, the stream position is: ', s2.tell()) s2.write('Test') print('s2 read: ', s2.read()) print('s2 getvalue: ', s2.getvalue()) print('s2 read: ', s2.read()) print('+++++++++++++++++++++++++++++++++') b2 = BytesIO(b1.getvalue()) print(b2.getvalue().decode('utf-8'))
''' 多重继承——一个子类可以同时获得多个父类的所有功能 注意:多重继承时,如果后一个父类中有和前一个父类中同名的属性/方法,最终继承的是前一个父类的属性/方法 ''' class Animal(object): def __init__(self, name): self.name = name class Bird(Animal): def __init__(self, name): Animal.__init__(self, name) def catchWorm(self): print('I\'m catching worms!') class Mammal(Animal): def __init__(self, name): Animal.__init__(self, name) def drinkingMilk(self): print('I\'m drinking milk!') class FlyingMixin(object): def flying(self): print('I\'m flying!') class RunningMixin(object): def running(self): print('I\'m running!') class Dog(Mammal, RunningMixin): # 继承Mammal类和RunningMixin类 def __init__(self, name): Mammal.__init__(self, name) class Magpie(Bird, FlyingMixin): # 继承Bird类和FlyingMixin类 def __init__(self, name): Bird.__init__(self, name) d = Dog('Eddi') d.drinkingMilk() # 调用Mammal类中的方法 d.running() # 调用RunningMixin类中的方法 m = Magpie('Sandi') m.catchWorm() # 调用Bird类中的方法 m.flying() # 调用FlyingMixin类中的方法
#!/usr/bin/env python # coding: utf-8 # In[ ]: import math e= input('Enter e:') e = int(e) x = input('Enter x:') x = int(x) e**(-4)/(5math.tan(x))+math.tan(math.log10(x**3)/3) print(x)
import csv with open('Crew.csv', mode = 'r') as csvfile: readCSV = csv.reader(csvfile, delimiter = ',') ssn = [] employee_list = [] header = next(readCSV) for row in readCSV: ssn = row[0] emp_name = row[1] emp_role = row[2] emp_rank = row[3] emp_licence = row[4] emp_address = row[5] emp_phoneno = row[6] #emp_email = row[7] employee_list.append([ssn, emp_name, emp_role, emp_role, emp_licence, emp_address, emp_phoneno]) for row in employee_list: ssn = row[0] emp_name = row[1] emp_role = row[2] emp_rank = row[3] emp_licence = row[4] emp_address = row[5] emp_phoneno = row[6] #emp_email = row[7] print( 'Name: {}, Role: {}, Rank: {}, License: {}, Address: {}, Phone: {}'.format(emp_name, emp_role, emp_rank,emp_licence,emp_address, emp_phoneno))
import numpy as np import matplotlib.pyplot as plt from matplotlib import style import warnings from collections import Counter import pandas as pd import random style.use( 'fivethirtyeight') # define k nearest neighbors function def k_nearest_neighbors(data, predict, k = 3): if len(data) > k: warnings("The dataset is larger than the K parameter. Increase the size of K") distance = [] for group in data: for feature in data[group]: euclidean_distance = np.linalg.norm(np.array(feature) - np.array(predict)) distance.append([euclidean_distance, group]) for i in sorted(distance)[:k]: votes = i[1] vote_result = Counter(votes).most_common(1)[0][0] return vote_result # Read in the breast cancer dataset cancer_data = pd.read_csv("/Users/Jared/Documents/Programming/Python/Statistical Learning/Classification/breast-cancer-wisconsin.data.txt") cancer_data.replace(to_replace="?", value=-99999, inplace=True) cancer_data.head() cancer_data.drop(["id"], 1, inplace=True)
# Madison Fletcher # 1868748 class ItemToPurchase: def __init__(self, item_name="none", item_quantity=0, item_price=0): self.item_name = item_name self.item_quantity = item_quantity self.item_price = item_price def print_item_cost(self): print(self.item_name, self.item_quantity, "@", '${}'.format(self.item_price), "=", '${}'.format(self.item_quantity * self.item_price)) if __name__ == "__main__": print("Item 1") name = str(input("Enter the item name:\n")) price = int(input("Enter the item price:\n")) quantity = int(input("Enter the item quantity:\n")) items = ItemToPurchase(name, quantity, price) print("\nItem 2") name2 = str(input("Enter the item name:\n")) price2 = int(input("Enter the item price:\n")) quantity2 = int(input("Enter the item quantity:\n")) items2 = ItemToPurchase(name2, quantity2, price2) items3 = ItemToPurchase() print("\nTOTAL COST") items.print_item_cost() items2.print_item_cost() print("\nTotal:", '${}'.format(price * quantity + price2 * quantity2))
# Madison Fletcher # 1868748 class Team: def __init__(self): self.team_name = 'none' self.team_wins = 0 self.team_losses = 0 def get_win_percentage(self): return self.team_wins / (self.team_wins + self.team_losses) if __name__ == "__main__": team = Team() name = str(input()) wins = int(input()) losses = int(input()) if wins > losses: print("Congratulations, Team", name, "has a winning average!") else: print("Team", name, "has a losing average.")
# Madison Fletcher # 1868748 word = input() word2 = word.replace(' ', '') if word2 == word2[::-1]: print(word, "is a palindrome") else: print(word, "is not a palindrome")
# coding: utf-8 """階段を登りつめる方法を考えるプログラム """ CACHE = {} def climbup(nsteps): """再帰でやるその1 """ if CACHE.get(nsteps) is not None: return CACHE[nsteps] if nsteps == 0: return 1 if nsteps < 0: return 0 CACHE[nsteps] = climbup(nsteps-1) + climbup(nsteps-2) + climbup(nsteps-3) return CACHE[nsteps] print climbup(70)
# coding: utf-8 class Node(object): def __init__(self, data): self.data = data self.__left = None self.__right = None def put(self, node): if node.data <= self.data: if self.__left is None: self.__left = node else: self.__left.put(node) else: if self.__right is None: self.__right = node else: self.__right.put(node) def get_cnt(self, data, cnt=0): if data < self.data: if self.__left is not None: return self.__left.get_cnt(data, cnt) else: return cnt elif data > self.data: if self.__right is not None: return self.nodes_left_count() + 1 + self.__right.get_cnt(data, cnt) else: return cnt+1 else: return cnt+self.nodes_left_count() def nodes_left_count(self): left = 0 if self.__left is not None: left = self.__left.nodes_count() return left def nodes_right_count(self): left = 0 if self.__right is not None: left = self.__right.nodes_count() return left def nodes_count(self): left = self.nodes_left_count() right = self.nodes_right_count() return left + right + 1 ROOT = [None] def track(num): if ROOT[0] is None: ROOT[0] = Node(num) else: ROOT[0].put(Node(num)) def get_rank_of_num(num): if ROOT[0] is None: return 0 else: return ROOT[0].get_cnt(num) if __name__ == "__main__": arr = [5, 1, 4, 3, 2, 8, 5, 1, 1,] for elem in arr: track(elem) print get_rank_of_num(4)
# coding: utf-8 def search_rotated_index(rotated, left, right): if left == right: return -1 if rotated[left] > rotated[right]: mid = (left + right) / 2 l = search_rotated_index(rotated, left, mid) r = search_rotated_index(rotated, mid + 1, right) if l == -1 and r == -1: return mid + 1 else: return l if l > r else r else: return -1 def bin_search(arr, x, left, right): if left > right: return -1 mid = (left + right) / 2 if x < arr[mid]: return bin_search(arr, x, left, mid - 1) elif x > arr[mid]: return bin_search(arr, x, mid + 1, right) else: return mid def search_rotated(rotated, x, left, right): rotated_index = search_rotated_index(rotated, 0, len(rotated) - 1) arr = rotated[rotated_index:] + rotated[:rotated_index] print arr index = bin_search(arr, x, left, right) return (rotated_index + index) % len(rotated) if __name__ == "__main__": arr = [5, 0, 1, 2, 3, 4] print search_rotated(arr, 5, 0, len(arr) - 1)
# coding; utf-8 import math all_patterns = [] def add_columns(row, columns): if row == len(columns): all_patterns.append(columns[:]) for col in range(len(columns)): if check_valid(row, col, columns): columns[row] = col add_columns(row + 1, columns) def check_valid(row, col, columns): for r in range(row): col2 = columns[r] if col2 == col: return False if math.fabs(col2 - col) == math.fabs(row - r): return False return True if __name__ == "__main__": add_columns(0, [0] * 8) for k, pat in enumerate(all_patterns): print "PATTERN %d" % k for i in range(8): for j in range(8): ch = " " if pat[i] == j: ch = "Q" print "|%s" % ch, print "|" print " - " * 8 print
def permutation(string1, string2): counts = {} for c in string1: cnt = counts.get(c,0) counts[c] = cnt+1 for c in string2: cnt = counts.get(c, 0) cnt -= 1 if cnt < 0: return False counts[c] = cnt return True if __name__ == "__main__": string1 = "hoge" string2 = "geho" string3 = "hoga" print string1, string2, permutation(string1, string2) print string2, string3, permutation(string2, string3) print string1, string3, permutation(string1, string3)
import scipy # ================================== # === Error function definitions === # ================================== def gradient(x, x_min, x_max): """ Gradient scaling function. The gradient is computed to result in +/-1 scales at x_max and x_min correspondingly. Parameters ---------- x: ndarray An input array, for which to compute the scalings. x_min: float A point, that corresponds to -1 output value. x_max: float A point, that corresponds to +1 output value. Returns ------- ndarray: An array of scales, ranging [-1;1] in [x_min; x_max] range. """ res = (2*x - (x_min + x_max)) / (x_max - x_min) return res def step(x, break_points): """ Step-like scaling function. Parameters ---------- x: ndarray An input array, for which to compute the scalings. break_points: tuple A list of the break points. Each entry should be a tuple of (break_position, break_width). Returns ------- ndarray Array of computed scales in the [-1; 1] range. """ # Applying the first break point break_point = break_points[0] break_x = break_point[0] break_width = break_point[1] res = scipy.tanh((x - break_x) / break_width) sign = 1 # If there are more break points given, applying them as well for break_point in break_points[1:]: # First recalling the previous break point position break_x_old = break_x # New break point data break_x = break_point[0] break_width = break_point[1] # Will fill only points above the transition position trans_x = (break_x + break_x_old) / 2.0 above_trans_x = scipy.where(x >= trans_x) # Flip the sign - above the transition position function behaviour is reversed sign *= -1 res[above_trans_x] = sign * scipy.tanh((x[above_trans_x] - break_x) / break_width) return res
#initializing variables n = 10 i =1 while i <= 10 : summation_of_numbers = 1/(i**2) sum_of_num = summation_of_numbers + 1/(i**2) i = i + 1 print( sum_of_num)
import streamlit as st import pandas as pd from sklearn.model_selection import train_test_split from joblib import load st.image('imagem.png', width=1000) #use_column_width=False, clamp=False, width=1000 st.title("Detectando Fake News de COVID-19") st.subheader("Está em dúvida se a notícia é verdadeira ou não?") st.markdown("**Vamos conferir!**") st.sidebar.image('veritas.png') st.sidebar.header("Mais informações") sidebar_information_1 = st.sidebar.selectbox("Fake News Covid-19", ("Como saber o que é uma fake new", "Perguntas frequentes", "Para conhecer melhor")) st.write(sidebar_information_1) sidebar_information_2 = st.sidebar.selectbox("Conheça mais sobre o projeto", ("Quem somos nós", "Contato")) st.write(sidebar_information_2) st.markdown("---") texto_input = st.text_area("Cole o texto da notícia aqui:") st.markdown("---") #left_column, right_column = st.beta_columns(2) # You can use a column just like st.sidebar: #left_column.button('Analisar!') st.button("Analisar!") #model = load("fake_new_detection.joblib")
""" Game gunting batu kertas sederhana. User vs BOT(random). User akan memasukkan nama dan pilihan tangan(0 = gunting, 1 = batu dan 2 = kertas), sementara BOT akan memilih tangan secara acak(0-2) """ import utils import random print('--------------------------------------') print('Memulai permainan Gunting Batu Kertas!') player_name = input('Masukkan nama Anda: ') print('Pilih tangan: (0: Gunting, 1: Batu, 2: Kertas)') player_hand = int(input('Masukkan nomor (0-2): ')) if utils.validate(player_hand): #tetapkan nilai acak 0-2 ke bot dgn fungsi randint dari modul random computer_hand = random.randint(0, 2) #cetak nama user + pilihan tangan dan bot utils.print_hand(player_hand, player_name) utils.print_hand(computer_hand, 'Bot') #cetak hasil suit result = utils.judge(player_hand, computer_hand) print('Hasil: ' + result) else: print('Mohon masukkan nomor yang benar') print('--------------------------------------')
import random from state import GameState as gameState import math #global variables # q_table = [list([0, 0, 0])] * 10369 # N= [list([0, 0, 0])] * 10369 q_table = {} N = {} epsilon = 0.05 # This function udpates the ball position and checks the bounce/termination conditions. Returns a state def play_game(state, action): #initialize game #check to make sure not terminal state first if state == None or state.special == 1: #print "TERMINAL STATE. GAME OVER" return None reward = 0 paddle_height = 0.2 state.paddle_y = state.paddle_y + state.actions[action] #if paddle goes off the top of the screen if state.paddle_y < 0: state.paddle_y = 0 #if any part of the paddle goes off the bottom of the scr if (state.paddle_y > 0.8): state.paddle_y = 0.8 #at each time step: #increment ball_x by velocity_x and ball_y by velocity_y orig_x = state.ball_x #old points orig_y = state.ball_y state.ball_x = state.ball_x + state.velocity_x state.ball_y = state.ball_y + state.velocity_y new_x = state.ball_x #new points new_y = state.ball_y #bounce #if ball is off the top of the screen if state.ball_y < 0: state.ball_y = -1 * state.ball_y state.velocity_y = -1 * state.velocity_y #if ball is off bottom of screen if state.ball_y > 1: state.ball_y = 2 - state.ball_y state.velocity_y = -1 * state.velocity_y #if ball is off left edge of screen if state.ball_x < 0: state.ball_x = -1 * state.ball_x state.velocity_x = -1 * state.velocity_x if abs(state.velocity_x) <= 0.03: print "VELOCITY_X ERROR" #if ball bounced off paddle: #draw a line along direction ball is moving slope = (new_y - orig_y)/(new_x - orig_x) b = new_y - (slope * new_x) y_intersection= slope + b # y = mx + b, plug in x = 1 paddle_bottom = state.paddle_y + paddle_height #if x>1 and line intersects the x=1 line within paddle range if state.ball_x > 1 and (state.ball_y >= state.paddle_y and state.ball_y <= paddle_bottom): state.ball_x = 2 - state.ball_x reward = 1 while True: U = random.uniform(-0.015, 0.015) V = random.uniform(-0.03, 0.03) state.velocity_x = (-1 * state.velocity_x) + U state.velocity_y = state.velocity_y + V if abs(state.velocity_x) > 0.03: break #if ball passes paddle set state to TERMINAL if state.ball_x > 1 and (state.ball_y > state.paddle_y and state.ball_y < paddle_bottom): state.special = 1 reward = -1 print "w a o w" return (state.ball_x, state.ball_y, state.velocity_x, state.velocity_y, state.paddle_y, reward) #This function takes a game state and discretizes it def discretize(state): #check if terminal state if state.special == 1: return None #add special state for when ball passes paddle with reward -1 #should stay in this state regardless of ball's velocity or paddle's location if state.ball_x > 1: state.special = 1 paddle_height = 0.2 #treat the entire board as a 12x12 grid so there are 144 possible ball locations ball_x = math.floor(12 * state.ball_x) ball_y = math.floor(12 * state.ball_y) #discretize the x velocity if state.velocity_x < 0: velocity_x = -1 elif state.velocity_x >= 0: velocity_x = 1 #discretize the y velocity if abs(state.velocity_y) < 0.015: velocity_y = 0 elif state.velocity_y < 0: velocity_y = -1 elif state.velocity_y >=0: velocity_y = 1 #convert paddle location discrete_paddle = math.floor(12 * state.paddle_y/ (1- paddle_height)) if state.paddle_y == (1- paddle_height): discrete_paddle = 11 paddle_y = discrete_paddle return (ball_x, ball_y, velocity_x, velocity_y, paddle_y) # def maptoidx(state): # ten_thousand = state.ball_x * (10000) # thousand = state.ball_y * (1000) # hundred = state.velocity_x * (100) # ten = state.velocity_y * 10 # final = ten_thousand + thousand + hundred + ten + state.paddle_y # final = hash(final) % 10369 # final = int(final) # return final # This function returns the action you should take given a state def exploration_policy(state, israndom): if state is None or state.special == 1: print "ERROR" return None #with probability e choose randomly if israndom is True: a = random.randint(0, 2) return a else: #with probability (1-e) follow the greedy policy q_max = -10000000000000 for i in range(3): if (discretize(state), i) not in N or (discretize(state), i) not in q_table: a = random.randint(0,2) return a if q_table[(discretize(state), i)] > q_max: q_max = q_table[(discretize(state), i)] a = i #print "chose actual" return a def qmax(state): if state is None or state.special == 1: print "ERROR" return None q_max = -10000000000000 for i in range(3): if (discretize(state), i) not in q_table: temp_value = 0 else: temp_value = q_table[(discretize(state), i)] return max(temp_value, q_max) def qlearning_agent(C, gamma): # IN CASE OF BUGS IMPOSE ADDITIONAL VELOCITY BOUNDS global q_table global N reward = 0 num_bounces = 0 n = 0 # number iterations random_count = 0 #initialize board; board is current game state paddle_height = 0.2 while n < 100000: #print num_bounces num_bounces = 0 #observe current state and convert from continuous to discrete space #start from scratch board = gameState(0.5, 0.5, 0.03, 0.01, 0.5 - paddle_height/2) current_state = board #Terminal state check if current_state == None: print "ERROR" continue if current_state.special == 1: return None continue else: while True: choose_random = False if current_state == None or current_state.special == 1: random_count = 0 break random_count +=1 if random_count > 10: random_count = 1 if random_count/10.0 == 0.3: choose_random = True #choose an action based on exploration policy a = exploration_policy(current_state, choose_random) #given action and current state get successor state temp_tuple= play_game(current_state, a) #final successor state if temp_tuple == None: random_count = 0 break else: successor_state = gameState(temp_tuple[0], temp_tuple[1], temp_tuple[2], temp_tuple[3], temp_tuple[4]) # print "CURRENT: ", (current_state.ball_x, current_state.ball_y, current_state.velocity_x, current_state.velocity_y) # print "SUCCESSOR: ", (successor_state.ball_x, successor_state.ball_y, successor_state.velocity_x, successor_state.velocity_y) reward = temp_tuple[5] if (discretize(current_state), a) not in N: N[(discretize(current_state), a)] = 1 alpha = 1.0 else: N[(discretize(current_state), a)] += 1 alpha = 1.0 * (C/(C + N[(discretize(current_state), a)])) #decay if we have seen before #update q-table with current state and successor state if N[(discretize(current_state), a)] == 1: q_table[(discretize(current_state), a)] = alpha * (reward + gamma * qmax(successor_state)) else: q_table[(discretize(current_state), a)] = q_table[(discretize(current_state), a)] + (alpha * (reward + (gamma * qmax(successor_state)) - q_table[(discretize(current_state), a)])) if reward > 0: num_bounces +=1 #update next game state to successor state current_state = gameState(successor_state.ball_x, successor_state.ball_y, successor_state.velocity_x, successor_state.velocity_y, successor_state.paddle_y) n+=1 def main(): global q_table global N #clear out the qtable and the N table q_table = {} N = {} qlearning_agent(100, 0.7) n = 0 #basically run qlearning again but dont update qtables while n < 1000: board = gameState(0.5, 0.5, 0.03, 0.01, 0.5 - paddle_height/2) current_state = board while True: choose_random = False if current_state == None or current_state.special == 1: random_count = 0 break random_count +=1 if random_count > 10: random_count = 1 if random_count/10.0 == 0.3: choose_random = True #choose an action a = exploration_policy(current_state, False) temp_tuple= play_game(current_state, a) #final successor state if temp_tuple == None: random_count = 0 break else: #update next game state to successor state successor_state = gameState(temp_tuple[0], temp_tuple[1], temp_tuple[2], temp_tuple[3], temp_tuple[4]) reward = temp_tuple[5] if reward > 0: num_bounces += 1 n+= 1 if __name__ == '__main__': main()
""" Sun Class to calculate the approximate position of the sun at a particular time. """ import numpy _deg2rad = numpy.pi/180.0 _rad2deg = 180.0/numpy.pi _MJD2000 = 51544.5 class Sun(): def __init__(self): """Instantiate the Sun object.""" return def getLon(self, mjd): """Calculate the Sun's true longitude only, for the given MJD(s). """ # Using the procedure outlined http://www.stjarnhimlen.se/comp/ppcomp.html # Calculate the days since J2000. days = mjd - _MJD2000 # Calculate the obliquity of the ecliptic at this/these times. ecl = 23.4393 - 3.563E-7 * days # Calculate the 'orbital elements' of the Sun at this/these times. N = 0.0 i = 0.0 w = (282.9404 + 4.70935E-5 * days) % 360.0 a = 1.000000 e = 0.016709 - 1.151E-9 * days M = (356.0470 + 0.9856002585 * days) % 360.0 # Calculate the eccentric anomaly for the sun. E = M + e*(_rad2deg)*numpy.sin(M*_deg2rad)*(1.0 + e * numpy.cos(M*_deg2rad)) # Calculate the distance to the Sun and the true anomaly. xv = numpy.cos(E*_deg2rad) - e yv = numpy.sqrt(1.0 - e*e) * numpy.sin(E*_deg2rad) v = numpy.arctan2( yv, xv ) * _rad2deg # Calculate the true longitude of the Sun. lon = v + w lon = lon % 360.0 return lon def calcPos(self, mjd): """Calculate the Sun's true longitude, distance, and RA/Dec, for the given MJD(s). """ # Using the procedure outlined http://www.stjarnhimlen.se/comp/ppcomp.html self.mjd = numpy.copy(mjd) # Calculate the days since J2000. days = mjd - _MJD2000 # Calculate the obliquity of the ecliptic at this/these times. ecl = 23.4393 - 3.563E-7 * days # Calculate the 'orbital elements' of the Sun at this/these times. N = 0.0 i = 0.0 w = (282.9404 + 4.70935E-5 * days) % 360.0 a = 1.000000 e = 0.016709 - 1.151E-9 * days M = (356.0470 + 0.9856002585 * days) % 360.0 # Calculate the eccentric anomaly for the sun. E = M + e*(_rad2deg)*numpy.sin(M*_deg2rad)*(1.0 + e * numpy.cos(M*_deg2rad)) # Calculate the distance to the Sun and the true anomaly. xv = numpy.cos(E*_deg2rad) - e yv = numpy.sqrt(1.0 - e*e) * numpy.sin(E*_deg2rad) self.dist = numpy.sqrt(xv*xv + yv*yv) v = numpy.arctan2(yv, xv) * _rad2deg # Calculate the true longitude of the Sun. self.lon = v + w self.lon = self.lon % 360.0 # Now translate back to RA/Dec. # Calculate the sun's position in ecliptic x/y/z coordinates. xs = self.dist * numpy.cos(self.lon*_deg2rad) ys = self.dist * numpy.sin(self.lon*_deg2rad) # zs = distance out of ecliptic plane, but this is always 0 for the Sun. # Calculate the sun's position in equatorial x/y/z geocentric coordinates. xe = xs ye = ys * numpy.cos(ecl * _deg2rad) ze = ys * numpy.sin(ecl * _deg2rad) # And convert to RA/Dec coordinates (this is geocentric position). self.ra = numpy.arctan2(ye, xe) * _rad2deg self.dec = numpy.arctan2(ze, numpy.sqrt(xe*xe+ye*ye)) * _rad2deg return def getAltAz(self, skypos): """Get Alt/Az/Airmass information for each observation. Pass an already instantiated SkyPos object.""" self.alt, self.az = skypos.radec2altaz(self.ra, self.dec, self.mjd) return def test_slalib(self, mjd, config): from pyslalib import slalib ra = numpy.zeros(len(mjd), 'float') dec = numpy.zeros(len(mjd), 'float') for i in range(len(mjd)): # Calculate sun's (topocentric) position. #ra_RAD, dec_RAD, diam = slalib.sla_rdplan(mjd[i], 0, # config['longitude']*_deg2rad, config['latitude']*_deg2rad) # Sun's (geocentric?) position. bary_vel, bary_pos, helio_vel, helio_pos = slalib.sla_evp(mjd, 2000) sun_pos = -1 * (bary_pos) ra_RAD, dec_RAD = slalib.sla_dcc2s(sun_pos) ra[i] = ra_RAD * _rad2deg dec[i] = dec_RAD * _rad2deg print "Sun: Test_slalib results" print " ... ra(slalib)" print ra print " ... ra(self)" print self.ra print self.ra.min(), self.ra.max() print " ... dec(slalib)" print dec print " ... dec(self)" print self.dec
# -------------- #Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Reading the file data=pd.read_csv(path) #Code starts here # Step 1 #Reading the file #Creating a new variable to store the value counts loan_status=data['Loan_Status'].value_counts() #Plotting bar plot plt.bar(loan_status.index, loan_status) plt.show() # Step 2 #Plotting an unstacked bar plot property_and_loan=data.groupby(['Property_Area', 'Loan_Status']) property_and_loan=property_and_loan.size().unstack() property_and_loan.plot(kind='bar', stacked=False, figsize=(15,10)) #Changing the x-axis label plt.xlabel('Property_Area') #Changing the y-axis label plt.ylabel('Loan_Status') #Rotating the ticks of X-axis plt.xticks(rotation=45) # Step 3 #Plotting a stacked bar plot education_and_loan=data.groupby(['Education', 'Loan_Status']) education_and_loan=education_and_loan.size().unstack() education_and_loan.plot(kind='bar', stacked=True, figsize=(15,10)) #Changing the x-axis label plt.xlabel('Education Status') #Changing the y-axis label plt.ylabel('Loan Status') #Rotating the ticks of X-axis plt.xticks(rotation=45) # Step 4 #Subsetting the dataframe based on 'Education' column graduate=data[data['Education']=='Graduate'] #Subsetting the dataframe based on 'Education' column not_graduate=data[data['Education']=='Not Graduate'] #Plotting density plot for 'Graduate' graduate['LoanAmount'].plot(kind='density', label='Graduate') #Plotting density plot for 'Graduate' not_graduate['LoanAmount'].plot(kind='density',label='Not Graduate') #For automatic legend display plt.legend() # Step 5 #Setting up the subplots fig, (ax_1, ax_2,ax_3) = plt.subplots(1,3, figsize=(20,8)) #Plotting scatter plot ax_1.scatter(data['ApplicantIncome'],data["LoanAmount"]) #Setting the subplot axis title ax_1.set(title='Applicant Income') #Plotting scatter plot ax_2.scatter(data['CoapplicantIncome'],data["LoanAmount"]) #Setting the subplot axis title ax_2.set(title='Coapplicant Income') #Creating a new column 'TotalIncome' data['TotalIncome']= data['ApplicantIncome']+ data['CoapplicantIncome'] #Plotting scatter plot ax_3.scatter(data['TotalIncome'],data["LoanAmount"]) #Setting the subplot axis title ax_3.set(title='Total Income') print(data['TotalIncome'][1])
import numpy as np def sigmoid(x, deriv=False): if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x)) np.random.seed(1) class TwoLayerNN: """Neural Network with no hidden layers.""" def __init__(self): self.syn0 = 2*np.random.random((3,1)) - 1 #randomly initialise weights with mean 0 def train(self, t_in, t_out): I = t_in O = t_out.T for iter in range(10000): l0 = I #input layer is same as input training matrix l1 = sigmoid(np.dot(l0, self.syn0)) #dotproduct (multiplication) of all inputs with corresponding weights, as a probability (between 0 and 1) l1error = O - l1 #error or difference between expected output and what was generated l1delta = l1error * sigmoid(l1, True) #weighting the error measure of outputs to be higher for outputs closer to 0.5 (on the fence) in order to push them one way or another self.syn0 += np.dot(l0.T, l1delta) #increase or decrease weights by the dotproduct of input and weighted errors self.prediction = l1 class ThreeLayerNN: """Neural Network with one hidden layer.""" def __init__(self): self.syn0 = 2*np.random.random((3,6)) - 1 self.syn1 = 2*np.random.random((6,1)) - 1 #to turn the 6x6 from the hidden layer into a 6x1 array of outputs def train(self, t_in, t_out): I = t_in O = t_out.T for iter in range(10000): l0 = I #input (6x3) l1 = sigmoid(np.dot(l0, self.syn0)) #dotproduct of input (6x3) with weights (3x6) should create 6 outputs per input (for each neuron in l1), a (6x6) matrix l2 = sigmoid(np.dot(l1, self.syn1)) #output (6x1) l2error = O - l2 l2delta = l2error * sigmoid(l2, True) #l2 weighted error l1error = l2delta.dot(self.syn1.T) #the error of the first set of weights is the second set of weights multiplied by the second layer's error, which reverses the #"extra" error created by the second set of weights l1delta = l1error * sigmoid(l1, True) #l1 weighted error self.syn0 += np.dot(l0.T, l1delta) self.syn1 += np.dot(l1.T, l2delta) self.prediction = l2 X = np.array([[0, 0, 1], [1, 0, 1], [0, 1, 0], [1, 1, 1], [0, 1, 0], [1, 1, 0]]) Y = np.array([[1,1,0,1,0,0]]) nn = TwoLayerNN() nn.train(X, Y) print(nn.prediction) print("\n") nn1 = ThreeLayerNN() nn1.train(X, Y) print(nn1.prediction)
def add_my_function(num1,num2): sum1=num1+num2 print(sum1,"=total of sum") add_my_function(67,78) # def my_multiple_function(num,num1): # sum2=num+num1 # print("total sum=",sum2) # my_multiple_function(9,3)
# isEven() # def isEven(): # if(12%2==0): # print("Even Number") # else: # print("Old Number") # isEven() # numbers_list = [1, 2, 3, 4, 5, 6, 7, 10, -2] # print (max(numbers_list)) # a=[1,2,3,4,5,6] # print(len(a)) def say_hello(name): print ("Hello ", name) print ("Aap kaise ho?") say_hello("Aatif")
import unittest import time from src.MyHashMap import MyHashMap class TestHashMap(unittest.TestCase): def test_speed(self): t0 = time.time() hmap = MyHashMap(size=100) for i in range(40): hmap.set("t" + str(i), i) hmap.get("t2") hmap.get("t3") t1 = time.time() print("\nMyHashMap: %f" % (t1 - t0)) def test_get(self): hmap = MyHashMap() with self.assertRaises(KeyError): hmap.get("hi") def test_get_2(self): hmap = MyHashMap() hmap.set("test", 10) hmap.set("hello", 25) hmap.set("watsup", 50) self.assertTrue(hmap.get("test") == 10) def test_get_3(self): hmap = MyHashMap() with self.assertRaises(ValueError): hmap.get(10) def test_get_4(self): hmap = MyHashMap() with self.assertRaises(KeyError): hmap.get(None) def test_get_5(self): hmap = MyHashMap() hmap.set(None, 10) self.assertEqual(hmap.get(None), 10) def test_get_6(self): hmap = MyHashMap(5) for i in range(5): hmap.set("t" + str(i), i) for i in range(5): hmap.get("t" + str(i)) self.assertTrue(True) def test_set(self): hmap = MyHashMap() hmap.set("test", 10) self.assertEqual(len(hmap), 1) def test_set_2(self): hmap = MyHashMap() with self.assertRaises(MemoryError): for i in range(16): hmap.set("t" + str(i), i) def test_set_3(self): hmap = MyHashMap() self.assertFalse(hmap.set(10, 10)) def test_set_4(self): hmap = MyHashMap() hmap.set(None, 10) self.assertIsNotNone(hmap._data[0]) def test_set_5(self): hmap = MyHashMap(5) for i in range(5): hmap.set("t" + str(i), i) self.assertTrue(True) def test_set_6(self): hmap = MyHashMap() for i in range(5): hmap.set("t" + str(i), i) hmap.set(None, 10) def test_delete(self): hmap = MyHashMap() for i in range(8): hmap.set("t" + str(i), i) self.assertEqual(hmap.delete("t2"), 2) def test_delete_2(self): hmap = MyHashMap() for i in range(8): hmap.set("t" + str(i), i) hmap.delete("t2") self.assertEqual(len(hmap), 7) def test_delete_3(self): hmap = MyHashMap() with self.assertRaises(ValueError): hmap.delete(10) def test_delete_4(self): hmap = MyHashMap() with self.assertRaises(KeyError): hmap.delete("test") def test_delete_5(self): hmap = MyHashMap(size=10) for i in range(5): hmap.set("t" + str(i), i) for i in range(5): hmap.delete("t" + str(i)) self.assertTrue(True) def test_load(self): hmap = MyHashMap() hmap.set("test", 10) self.assertEqual(hmap.load(), (1 / hmap._max_size)) def test_len(self): hmap = MyHashMap() for i in range(5): hmap.set("t" + str(i), i) self.assertEqual(len(hmap), 5) def test_repr(self): hmap = MyHashMap() for i in range(5): hmap.set("t" + str(i), i) rep = str(hmap) self.assertTrue(True) if __name__ == "__main__": unittest.main()
import sys def reverse_words(): words = sys.argv[1:] output_words = reverse_words[::-1] print( " ".join(output_words)) if __name__ == '__main__': reverse_words() # SAMPLE STRATEGY # >>> y # [8, 7, 6, 5, 4, 3, 2, 1, 0] # >>> x = range(9) # >>> x # [0, 1, 2, 3, 4, 5, 6, 7, 8] # >>> y=x[::-1] # >>> y # [8, 7, 6, 5, 4, 3, 2, 1, 0]
a = float(input('Quanto de dinheiro você tem? ')) dolar = 3.27 b= a / dolar print('Você tem R$ {:.2f} em carteira e pode comprar $ {:.2f} dolares'. format(a, b))
from player import Player class Detective(Player): def __init__(self, index, start_position, num_taxi_tickets=11, num_bus_tickets=8, num_metro_tickets=4, needs_tickets=True, color='red'): # Call init-function of abstract player to set the current and previous position Player.__init__(self, start_position=start_position, color=color) # Set number of tickets self.tickets = {"taxi": num_taxi_tickets, "bus": num_bus_tickets, "metro": num_metro_tickets} # Create ticket history which gets filled with the used tickets self.ticket_history = [] self.name = "Detective" self.index = index def can_move(self, ticket_type): if ticket_type == "taxi": return self.num_taxi_tickets > 0 elif ticket_type == "bus": return self.num_bus_tickets > 0 elif ticket_type == "metro": return self.num_metro_tickets > 0 else: print("Unknown ticket type detected when moving detective") return False def move(self, new_position, ticket_type="taxi"): if self.can_move(ticket_type): Player.set_new_position(self, new_position) if self.needs_tickets: # Reduce number of tickets if ticket_type == "taxi": self.num_taxi_tickets -= 1 elif ticket_type == "bus": self.num_bus_tickets -= 1 elif ticket_type == "metro": self.num_metro_tickets -= 1 else: self.set_static() def get_status(self): status = "Status detective: \n" \ "Detective index: {} \n" \ "Detective color: {} \n" \ "Current position: {} \n" \ "Previous positions: {} \n" \ "Number of taxi tickets: {} \n" \ "Number of bus tickets: {} \n" \ "Number of metro tickets: {} \n".format(self.index, self.color, self.position, self.prev_positions, self.num_taxi_tickets, self.num_bus_tickets, self.num_metro_tickets) return status def set_static(self): print("Detective {} cannot move because he has not got the required tickets".format(self.get_index())) def get_index(self): return self.index def get_tickets(self): return [self.num_taxi_tickets, self.num_bus_tickets, self.num_metro_tickets]
from collections import defaultdict import sys def is_wall(x, y, n): v = x*x + 3*x + 2*x*y + y + y*y + n o = format(v, "b").count("1") if o % 2 == 0: return False else: return True def get_neighbours(x,y): return [(x-1,y),(x+1,y),(x,y-1),(x,y+1)] def print_grid(grid): for y in range(0,100): for x in range(0,100): if grid[(x,y)]: sys.stdout.write('#') else: sys.stdout.write('.') sys.stdout.write('\n') def search(grid, source, dest, max=50): assert source in grid, 'Starting node does not exist' assert dest in grid, 'Destination node does not exist' inf = float('inf') # record min distance to coord distances = {coord: inf for coord in grid.keys()} distances[source] = 0 # record best parent step to coord parent_node = {coord: None for coord in grid.keys()} # unvisited nodes unvisited = grid.keys() while unvisited: # find next, shortest node to visit next_node = min(unvisited, key=lambda c: distances[c]) neighbours = get_neighbours(next_node[0], next_node[1]) for n in neighbours: # verify neighbour is a valid coord if n not in grid: continue next_dist = distances[next_node] + 1 if next_dist < distances[n]: distances[n] = next_dist parent_node[n] = next_node grid.pop(next_node) # part one - just find shortest path to dest path = [] iternode = dest while parent_node[iternode] is not None: path.append(iternode) iternode = parent_node[iternode] print(f"Part one: {len(path)}") # part two - find all nodes with a distance of 50 fifties = [n for n in distances if distances[n] <= 50] print(f"Part two: {len(fifties)}") n = 1364 # n = 10 grid = defaultdict(bool) for x in range(0,100): for y in range(0,100): if not is_wall(x,y,n): grid[(x,y)] = True start = (1,1) dest = (31,39) # dest = (7,4) search(grid,start,dest)
# using expressions / statements # know slice # with statement # slicing someline[start:end] a list with index # list a = ['a','b','c','d'] # print(a[:]) # slice someindex[start:end:stride] # print(a[3::2]) # enumerate a list over range
""" Dynamic Programming Algorithm (Optimal, inefficient) Held-Harp dynamic programming is an algorithm for finding optimal tours, not approximate ones, so it is not appropriate for large n. But even in its simplest form, without any programming tricks, it can go quite a bit further than alltours. Because, alltouts wastes a lot of time with permutations that can't possibly be optimal tours. Key property: Given a start citt A, an end city C, and a set of middle cities Bs, then out of all the possible segments that starts in A, end in C, and go through all and only the cities in Bs, only the shortest of those segments could ever be part of an optimal tour. """ import numpy as np import matplotlib.pyplot as plt import itertools import functools import urllib from map import * from utils import * def segment_length(segment): """The total of distances between each pair of consecutive cities in the segment.""" # same as tour_length, but without distance(tour[0], tour[-1]) return sum(distance(segment[i],segment[i-1]) for i in range(1,len(segment))) # the decorator @functools.lru_cache makes this a dynamic programming algorithm, # which is a fancy name meaning that we cache the results of sub-computation because # we will re-use them multiple times. # @functools.lru_cache(None) (python 3.2+) def shortest_segment(A, Bs, C): """The shortest segment starting at A, going through all Bs, and ending at C.""" if not Bs: return [A,C] else: segments = [shortest_segment(A, Bs-{B}, B) + [C] for B in Bs] return min(segments, key=segment_length) def dp_tsp(cities): """ The Held-Karp shortest tour of this set of cities. For each end city C, find the shortest segement from A (the start) to C. Out of all these shortest segment, pick the one tat is the shortest tour. """ A = first(cities) return shortest_tour(shortest_segment(A, cities-{A,C},C) for C in cities if C is not A) # main loop if __name__ == '__main__': #cities = USA_landmarks_map() args = get_args() cities = Random_cities_map(args.size) if args.map == "USA": cities = USA_landmarks_map() if args.map == "USA-big": cities = USA_big_map() #plot_tsp(nn_tsp,cities) #plot_tsp(repeated_nn_tsp,cities) #plot_tsp(altered_nn_tsp,cities) plot_tsp(dp_tsp,cities)
# # penggunaan end # print('A', end='') # print('B', end='') # print('C', end='') # print() # print('X') # print('Y') # print('Z') # # pengggunaan separtor # w, d, y, z = 10, 15, 20, 25 # print(w, d, y, z) # print(w, d, y, z, sep='+') # print(w, d, y, z, sep='x') # print(w, d, y, z, sep=':') # print(w, d, y, z, sep='-----') # print(d, z, sep='=' print('{:<30}{:^30}{:>30}'.format('Kiri','Tengah','Kanan')) print('{:<30}{:^30}{:>30}'.format(12,34,56))
def matrix_mul(m_a,m_b): a_row = len(m_a) if a_row < 1: return None a_col = len(m_a[0]) if a_col < 1: return None b_row = len(m_b) if b_row < 1: return None b_col = len(m_b[0]) if b_col < 1: return None if a_col != b_row: return None ans = [] for i in range(a_row): ans.append([0]*b_col) for r in range(a_row): for c in range(b_col): # 内积 ele = 0 for n in range(a_col): ele += m_a[r][n] * m_b[n][c] ans[r][c] = ele return ans a = [[1,2,3,4],[2,3,4,5]] b = [[1,0],[2,1],[2,3],[1,2]] print(matrix_mul(a,b))
def overlap(list1,list2): dict1 = {} for i in list1: dict1[i] = 1 ans = [] for ii in list2: if ii in dict1: ans.append(ii) return ans
def tonydumbdumb(words): if len(words) > 0: print "Oh dear, that was pretty dumb." return True else: print "Bliss!" return False words = raw_input("What did Tonez say? ") tonydumbdumb(words)
import basicdp import math from examples import __build_intervals_set__ from functools import partial # TODO check endpoints of interval along the code def evaluate(data, range_max_value, quality_function, quality_promise, approximation, eps, delta, intervals_bounding, max_in_interval, use_exponential=True): """ RecConcave algorithm for the specific case of N=2 :param data: the main data-set :param range_max_value: maximum possible output (the minimum output is 0) :param quality_function: function that gets a domain-elements and returns its quality (in float) :param quality_promise: float, quality value that we can assure that there exist a domain element with at least that quality :param approximation: 0 < float < 1. the approximation level of the result :param eps: float > 0. privacy parameter :param delta: 1 > float > 0. privacy parameter :param intervals_bounding: function L(data,domain_element) :param max_in_interval: function u(data,interval) that returns the maximum of quality_function(data,j) for j in the interval :param use_exponential: the original version uses A_dist mechanism. for utility reasons the exponential-mechanism is the default. turn to False to use A_dist instead :return: an element of domain with approximately maximum value of quality function """ # step 2 # print "step 2" log_of_range = int(math.ceil(math.log(range_max_value, 2))) range_max_value_tag = 2 ** log_of_range def extended_quality_function(data_base, j): if range_max_value < j <= range_max_value_tag: return min(0, quality_function(data_base, range_max_value)) else: return quality_function(data_base, j) # step 4 # print "step 4" def recursive_quality_function(data_base, j): return min(intervals_bounding(data_base, range_max_value_tag, j) - (1 - approximation) * quality_promise, quality_promise-intervals_bounding(data_base, range_max_value_tag, j + 1)) # step 6 # print "step 6" recursion_returned = basicdp.exponential_mechanism_big(data, range(log_of_range+1), recursive_quality_function, eps) good_interval = 8 * (2 ** recursion_returned) # print "good interval: %d" % good_interval # step 7 # print "step 7" first_intervals = __build_intervals_set__(data, good_interval, 0, range_max_value_tag) second_intervals = __build_intervals_set__(data, good_interval, 0, range_max_value_tag, True) max_quality = partial(max_in_interval, interval_length=good_interval) # step 9 ( using 'dist' algorithm ) # print "step 9" # TODO should I add switch for sparse? # TODO make sure it is still generic!!!!!!!!!!!!!! if use_exponential: first_full_domain = xrange(0, range_max_value, good_interval) second_full_domain = xrange(good_interval / 2, range_max_value, good_interval) first_chosen_interval = basicdp.sparse_domain(basicdp.exponential_mechanism_big, data, first_full_domain, first_intervals, max_quality, eps) second_chosen_interval = basicdp.sparse_domain(basicdp.exponential_mechanism_big, data, second_full_domain, second_intervals, max_quality, eps) else: first_chosen_interval = basicdp.a_dist(data, first_intervals, max_quality, eps, delta) second_chosen_interval = basicdp.a_dist(data, second_intervals, max_quality, eps, delta) if type(first_chosen_interval) == str and type(second_chosen_interval) == str: raise ValueError("stability problem, try taking more samples!") # step 10 # print "step 10" if type(first_chosen_interval) == str: first_chosen_interval_as_list = [] else: first_chosen_interval_as_list = range(first_chosen_interval, first_chosen_interval + good_interval) if type(second_chosen_interval) == str: second_chosen_interval_as_list = [] else: second_chosen_interval_as_list = range(second_chosen_interval, second_chosen_interval + good_interval) return basicdp.exponential_mechanism_big(data, first_chosen_interval_as_list + second_chosen_interval_as_list, extended_quality_function, eps)
""" json解析 ---非json格式不能用json解析 """ import requests import json url = "http://127.0.0.1:8000/api/departments/" num = { "data": [ { "dep_id": "T02", "dep_name": "Test学院", "master_name": "Test-Master", "slogan": "Here is Slogan" } ] } r = requests.post(url, json=num) # nn = {"ConTent-Type": "application/json"} # r = requests.post(url, data=json.dumps(num), headers=nn) print(r.status_code) print(r.text) print(r.json())
# EXERCÍCIO 01 - LISTA 08 - CLASSES print('Classe Bola') print('###########') class Bola(): def __init__(self, cor, circunferencia, material): self.cor = cor self.circunferencia = circunferencia self.material = material def troca_cor(self,nova_cor): self.cor = nova_cor def mostra_cor(self): return 'Cor da bola: ' + self.cor bola = Bola('azul', 10, 'plastico') print(bola.cor) print() bola.troca_cor("preta") print(bola.mostra_cor())
# EXERCÍCIO Nº 38 - LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nReajuste de salários') print('####################\n') ano_atual=1997 salário = float(input('Insira seu salário:R$ ')) while salário<=0: print('O salário deve ser maior que zero') salário = float(input('Insira seu salário:R$ ')) while ano_atual<=1997: ano_atual = float(input('Insira o ano corrente: ')) while (ano_atual) != int(ano_atual) or ano_atual<=0 or ano_atual<=1997: print('O número deve ser inteiro, maior que zero e maior que 1997') ano_atual = float(input('Insira o ano corrente: ')) ano_atual = int(ano_atual) salário_atual=salário for ano in range(1997,ano_atual+1,1): salário_atual*=(1+0.015*2) print('O reajuste até o ano de: ',ano,'foi de: ',round((salário_atual/salário -1)*100,2),'% o que corresponde a: R$ ',round(salário_atual,2))
#EXERCÍCIO Nº 04 - LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nCrescimento Populacional') print('########################\n') habitantes_A=80000 taxa_anual_A=0.03 habitantes_B=200000 taxa_anual_B=0.015 i=1 a=80000 b=200000 while a<=b: a=int(a+a*taxa_anual_A) b=int(b+b*taxa_anual_B) i+=1 print('A população A é de: ',a,' habitantes\n\nA população B é de: ',b,' habitantes') print('\nEste crescimento ocorreu em: ',i,' anos')
# EXERCÍCIO Nº 30- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nPanificadora Pão de Ontem') print('#########################\n') preço_do_pão=0 while preço_do_pão<=0: preço_do_pão=float(input('Insira o preço do pão:R$ ')) if preço_do_pão<=0: print('O preço do pão deve ser maior que zero') print('Panificadora Pão de Ontem - Tabela de Preços') print('--------------------------------------------') print('\tPreço do Pão: R$ ',preço_do_pão) print('--------------------------------------------') for i in range(1,51): print('\t⃝ ', i,' - R$',round(preço_do_pão*i, 2))
# EXERCÍCIO Nº 02- LISTA 06 - STRINGS print('\n Nome ao Contrário') print('##################\n') nome=input('Insira o seu nome: ').upper() print(nome[::-1])
# EXERCÍCIO Nº 47 - LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nCompetição de Ginática') print('######################\n') ginasta='ginasta' while ginasta!='': ginasta = input('Ginasta: ') if ginasta!='': nota1 = float(input('Insira a 1º nota: ')) nota2 = float(input('Insira a 2º nota: ')) nota3 = float(input('Insira a 3º nota: ')) nota4 = float(input('Insira a 4º nota: ')) nota5 = float(input('Insira a 5º nota: ')) nota6 = float(input('Insira a 6º nota: ')) nota7 = float(input('Insira a 7º nota: ')) if nota1>=nota2 and nota1>=nota3 and nota1>=nota4 and nota1>=nota5 and nota1>=nota6 and nota1>=nota7: melhor_nota=nota1 elif nota2>=nota3 and nota2>=nota4 and nota2>=nota5 and nota2>=nota6 and nota2>=nota7: melhor_nota=nota2 elif nota3>=nota4 and nota3>=nota5 and nota3>=nota6 and nota3>=nota7: melhor_nota=nota3 elif nota4>=nota5 and nota4>=nota6 and nota4>=nota7: melhor_nota=nota4 elif nota5 >= nota6 and nota5 >= nota7: melhor_nota = nota5 elif nota6>= nota7: melhor_nota = nota6 else: melhor_nota=nota7 if nota1<=nota2 and nota1<=nota3 and nota1<=nota4 and nota1<=nota5 and nota1<=nota6 and nota1<=nota7: pior_nota=nota1 elif nota2<=nota3 and nota2<=nota4 and nota2<=nota5 and nota2<=nota6 and nota2<=nota7: pior_nota=nota2 elif nota3<=nota4 and nota3<=nota5 and nota3<=nota6 and nota3<=nota7: pior_nota=nota3 elif nota4<=nota5 and nota4<=nota6 and nota4<=nota7: pior_nota=nota4 elif nota5<=nota6 and nota5<=nota7: pior_nota = nota5 elif nota6<=nota7: pior_nota = nota6 else: pior_nota=nota7 soma_das_notas=nota1+nota2+nota3+nota4+nota5+nota6+nota7 media=round((soma_das_notas-melhor_nota-pior_nota)/5,2) print('ginasta: ',ginasta) print('###############################') print('Primeira nota: ',nota1) print('Segunda nota: ',nota2) print('Terceira nota: ',nota3) print('Quarta nota: ',nota4) print('Quinta nota: ',nota5) print('Sexta nota: ', nota6) print('Sétima nota: ', nota7) print('###############################') print('Melhor nota: ',melhor_nota) print('Pior nota: ',pior_nota) print('Média dos demais notas: ',media) print('###############################') print('Resultado Final:') print(ginasta,':',media) print('###############################') else: ginasta=''