text
stringlengths
37
1.41M
from underline_var import * import underline_var # 注意在该程序中underline_var和underline需要在一个路径下 class MyClass(object): def __init__(self): self.__superprivate = "Hello" self._semiprivate = "world!" # print(_a) #NameError: name '_a' is not defined print(underline_var._a) print(b) a = MyClass() print(a._semiprivate) print(a._MyClass__superprivate) print(dir(a))
#print ("Hello World!") name = input ("Enter temperature in celsius: " ) F= (float (name)*9/5)+32; print(str(float(name))+ "° in Celsius is equivalent to " + str(F) + "° Fahrenheit.")
def isPrime(n): prime = True if n < 2: prime = False elif n == 2: prime = True else: i = 2 while i < n/2 + 1: if n%i == 0: prime = False break else: i += 1 return prime print(isPrime(5)) print(isPrime(11)) print(isPrime(119))
name = input("Hello, what is your name?") age = input("How old are you?") year = 100 - int(age) + 2017 print("Nice to meet you " + name + ". On " + str(year) + ", you will be 100 years old. Hope you'll live that long. :)")
def palindrome(a): if a == a[::-1]: print(a + " is palindrome") else: print(a + " is not palindrome") a = "madam" b = "mertkan" palindrome(a) palindrome(b)
import random def intersect(a, b): result = [] init_result = [i for i in a if i in b] for i in init_result: if i not in result: result.append(i) return result a = [random.randrange(1, 10) for i in range(20)] b = [random.randrange(1, 10) for i in range(20)] print(a) print(b) print(intersect(a, b))
#!/usr/bin/python3 """ this is the code to accompany the Lesson 2 (SVM) mini-project use an SVM to identify emails from the Enron corpus by their authors Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() ### make sure you use // when dividing for integer division features_train = features_train[:len(features_train)//100] labels_train = labels_train[:len(labels_train)//100] ######################################################### ### your code goes here ### from sklearn.svm import SVC clf = SVC(kernel="rbf",C=10000) t0 = time() clf.fit(features_train,labels_train) print("Training time:", round(time()-t0, 3), "s") t1 = time() pred = clf.predict(features_test) print("Testing time:", round(time()-t1, 3), "s") from sklearn.metrics import accuracy_score acc = accuracy_score(labels_test,pred) print("Accuracy is ",acc) print("Answer to the 10th,26th and 50th element is {}, {} and {} respectively".format(pred[10],pred[26],pred[50])) ######################################################### ## ACCURACY - 61.60% ## Now, changing the value of C in factors of 10 ## ACCURACY for C =10 -> 61.60% ## ACCURACY for C =100 -> 61.60% ## ACCURACY for C =1000 -> 82.13% ## ACCURACY for C =10000 -> 89.24% ## ACCURACY for C =100000 -> 86.006% ## ACCURACY for C =50000 -> 86.006%
# To pass the test, your code should output "Passed All Dictionary Tests!" # If you get any other error other than the one printed below, google to figure out what you did. Most likely error to encounter is a Key Error (means key doesn't exist in dictionary). def test(value, answer): if value != answer: print('Failed - ' + str(value) + ' should be ' + str(answer)) exit() print('') # Create a blank dictionary called employees employees = {} employees[0] = "Ryan" employees[1] = "Andre" employees[2] = "Ted" employees[3] = "Alex" # Make the Key the employee number, and the Value their name. # Key: 0 Value: 'Ryan' # Key: 1 Value: 'Andre' # Key: 2 Value: 'Ted' # Key: 3 Value: 'Alex' # TEST test(employees[0], 'Ryan') # Sort the employees in alphabetical order. sorted_employees = sorted(employees, key=employees.get, reverse=False) test(sorted_employees[0], 3) test(sorted_employees[1], 1) test(sorted_employees[2], 0) test(sorted_employees[3], 2) # Pop employee number 2 and store name in "name". name = employees.pop(2) test(name, 'Ted') try: employees[2] print('Failed Popping employee') except: print('Passed All Dictionary Tests!') exit()
def get_choice_from_cli(options, repeat_until_correct=True, return_key=False, title="Select one option from the list:", prompt="Selection > ", redo_text="Not a valid selection, try again."): """ lets the user choose one option from the passed list. :param options: A list of options, which are three item tuples with [0]=index, [1]=description/name, [2]=object The index needs to be convertible to string and printable. The description/name needs to be printable. The object doesn't have any requirements on it's type. :param repeat_until_correct: If True: keeps checking until valid option is selected. If False: faulty option key is returned regardless of value of return_key. :param return_key: If true the index for the selected option is returned instead of the third item in the tuple. :param title: The title shown above the option list. (Pass None for no title) :param prompt: The prompt shown below the option list. (Pass None for no prompt(just a new line)) :param redo_text: The text shown when a invalid option is chosen and infinite is set (pass None for no redo text) :return: The callback that is chosen, or the given key if return_key is set """ desired_pad_length = max([len(str(a[0])) for a in options]) while True: if title is not None: print(title) for option in options: print("{}\t{}".format(str(option[0]).ljust(desired_pad_length), option[1])) choice = input(prompt or "") for option in options: if choice == str(option[0]): if return_key: return choice else: return option[2] # choice not in the list if repeat_until_correct: if redo_text is not None: print(redo_text) continue else: return choice
# -*- coding: utf-8 -*- """This module implements Future base class and its subclasses. Future objects are the result of asynchronous functions execution. Their value is unknown at construction, so they offer an interface for gathering this value when it is computed, or wait until it is available.""" import operator import threading from parxe.common import overrides, wait_until_exists PENDING_STATE = "pending" RUNNING_STATE = "running" FINISHED_STATE = "finished" def _cast(obj): """Casts non Future objects to NonFuture.""" if isinstance(obj, Future): return obj else: return NonFuture(obj) def _thread_run_for_result(future, func, *args): """This function executes func(*args) and stores its result by means of future.set_result() method.""" result = func(future, *args) future._set_result(result) class Future(object): """Future class for result of parallel functions execution. Instances of this class execute do_work function given in the constructor using a dedicated Python thread (from threading library). The do_work function has the responsability of indicating the running state of the object by calling set_as_running() method. This do_work function receives as arguments the future object and a variable list of arguments given to __init__ constructor. Example: >>> def square(self, x): ... self.set_as_running() ... return x**2 >>> fut = Future(square, 4) >>> fut.get() 16 """ def __init__(self, do_work, *args): """do_work(self, *args) will be executed in a Python thread.""" self._result = None self._stdout = None self._stderr = None self._state = PENDING_STATE self._err = None self._out = None self._running_condition = threading.Condition() self._do_work_thread = threading.Thread( target=_thread_run_for_result, args=[self, do_work] + list(args), ) self._do_work_thread.run() def set_stdout(self, value): self._stdout = value def set_stderr(self, value): self._stderr = value def set_as_running(self): """Changes the state of the object from pending to running. This method should be called by do_work function.""" with self._running_condition: assert self._state == PENDING_STATE self._state = RUNNING_STATE self._running_condition.notify() def abort(self): """Aborts the computation of this future.""" raise NotImplementedError def get(self): """Waits until the future is finished and returns the result of this execution. If the object is in finished state, this method returns the result without any waiting. """ if not self.finished(): self.wait() return self._result def wait(self, timeout=None): """Waits until the given timeout. If timeout=None, it will wait forever. This function returns a boolean when the result is ready and the future finished. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). Once this method returns True indicating finished state, it cannot be called again. """ self._do_work_thread.join(timeout) return self.finished() def wait_until_running(self, timeout=None): """Waits until the future object is in running state. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method will return False when finishing because of the timeout. """ if self.pending(): with self._running_condition: self._running_condition.wait(timeout) return not self.pending() def _set_result(self, value): """Calling this method stores the result in the future object. Besides, this method sets the future state to finished. This method is called by the thread target function and should not be called by anyone else out of this module. """ self._result = value self._state = FINISHED_STATE def finished(self): """Indicates if the future is in finished state""" return self._state == FINISHED_STATE def running(self): """Indicates if the future is in running state""" return self._state == RUNNING_STATE def pending(self): """Indicates if the future is in pending state""" return self._state == PENDING_STATE def get_stderr(self): """Reads stderr file content or the error state field.""" _ = self.get() # force finished wait if self._stderr is not None: if wait_until_exists(self._stderr): with open(self._stderr) as f: self._err = f.read() return self._err def get_stdout(self): """Reads stdout file content or the output state field.""" _ = self.get() # force finished wait if self._stdout is not None: if wait_until_exists(self._stdout): with open(self._stdout) as f: self._out = f.read() return self._out def __str__(self): """Represents a future with a string as: Future in RUNNING state """ return "Future in {} state".format(self._state.upper()) def after(self, func): """Appends the execution of a function over the output of this Future. The function will be called as func(self.get()) when the result of this Future is ready. """ return ConditionedFuture(func, self) def __add__(self, other): return ConditionedFuture(operator.__add__, self, _cast(other)) def __sub__(self, other): return ConditionedFuture(operator.__sub__, self, _cast(other)) def __mul__(self, other): return ConditionedFuture(operator.__mul__, self, _cast(other)) def __div__(self, other): return ConditionedFuture(operator.__div__, self, _cast(other)) def __pow__(self, other): return ConditionedFuture(operator.__pow__, self, _cast(other)) def __mod__(self, other): return ConditionedFuture(operator.__mod__, self, _cast(other)) def __neg__(self): return ConditionedFuture(operator.__neg__, self) ############################ # CONDITIONED FUTURE CLASS # ############################ def _conditioned_do_work(self, func, *args): self.set_as_running() values = list(args[:]) for i, val in enumerate(values): while isinstance(val, Future): val = val.get() values[i] = val return func(*values) class ConditionedFuture(Future): """A Future class intended to execution of delayed functions. The function computation is delayed until all the arguments given in the constructor are finished. It allow to mix together Future and non Future objects. """ def __init__(self, func, *args): super(ConditionedFuture, self)\ .__init__( _conditioned_do_work, func, *args ) @overrides(Future) def abort(self): raise NotImplementedError ###################### # UNION FUTURE CLASS # ###################### def _union_do_work(self, args_list): self.set_as_running() values = list(args_list[:]) for i, val in enumerate(values): values[i] = _cast(val).get() return values class UnionFuture(Future): """A Future over a list of Futures. The result of this Future is a list of values. """ def __init__(self, args_list): super(UnionFuture, self).__init__(_union_do_work, args_list) self._args_list = args_list @overrides(Future) def get_stdout(self): """The stdout is the concatenation of every Future in the list.""" stdout = [val.get_stdout() for val in self._args_list] return '\n'.join(stdout) @overrides(Future) def get_stderr(self): """The stderr is the concatenation of every Future in the list.""" stderr = [val.get_stderr() for val in self._args_list] return '\n'.join(stderr) @overrides(Future) def abort(self): raise NotImplementedError #################### # NON FUTURE CLASS # #################### def _non_future_do_work(self, value): self.set_as_running() return value class NonFuture(Future): """A fake one wrapping a non future object. This class is useful to mix together Future and NonFuture objects.""" def __init__(self, value): super(NonFuture, self).__init__(_non_future_do_work, value) @overrides(Future) def abort(self): raise NotImplementedError
def canSum(targetSum, numbers): tab = [False for _ in range(targetSum+1)] # seed tab[0] = True for i in range(targetSum+1): if tab[i] is False: continue for num in numbers: if (i+num <= targetSum): tab[i+num] = True return tab[targetSum] print(canSum(7, [2,3])) print(canSum(7, [5,3,4,7])) print(canSum(7, [2,4])) print(canSum(8, [2,3,5])) print(canSum(300, [7,14]))
def bestSum(t, arr, memo=None): """ m: target sum, t n: len(arr) time = O(n^m*m) space = O(m*m) [in each stack frame, I am storing an array, which in worst case would be m] // Memoized complexity time = O(n*m*m) space = O(m*m) """ if memo is None: memo = {} if t in memo: return memo[t] if t == 0: return [] if t < 0: return None shortestCombination = None for ele in arr: r = t - ele rRes = bestSum(r, arr, memo) if rRes is not None: combination = rRes + [ele] # If the combination is shorter than current shortest, update it if (shortestCombination is None or len(combination) < len(shortestCombination)): shortestCombination = combination memo[t] = shortestCombination return memo[t] print(bestSum(7, [5,3,4,7])) print(bestSum(8, [2,3,5])) print(bestSum(8, [1,4,5])) print(bestSum(100, [1,2,5,25]))
# 元组 import random t1 = () ''' 1.定义符号() 2.元组中的内容不可修改 3.关键字 tuple ''' print(type(t1)) # 注意要加,号 t2 = ('hello',) print(type(t2)) t3 = ('hello','world') print(type(t3)) t4 = (2,3,4,5,6) list1 = [] for i in range(10): ran = random.randint(1,20) list1.append(ran) print(list1) t5 = tuple(list1) print(t5) # 查询:下标index 切片[:] print(t5) print(t5[0]) print(t5[-1]) print(t5[0:]) # 最大值 print(max(t5)) # 最小值 print(min(t5)) # 求和 print(sum(t5)) # 求长度 print(len(t5)) print(t5.count(6)) # print(t5.index(6)) # 拆包 t1 =(1,2,3) a,b,c =t1 print(a,b,c) a,b,c = (1,2,3) print(a,b,c) # 变量个数与元组个数不一致 t1 = (1,2,3,4,5,6) a,*_,c =t1 print(a,c,_) a,c,*_ = t1 print(a,c,_) # *c 代表未知的个数0~n a,b,*c =t1 print(a,b,c) print(*[1,2,3])
# -*- coding: utf-8 -*- name = 'Steven J. Moxley' age = 28 height = 72 #inches weight = 185 #lbs eyes = 'Hazel' teeth = 'White' hair = 'Dirty Blonde' #conversion for inches to centimeters inches = 72 centimeters = inches * 2.54 #conversion for lbs to kg pounds = 180 kilos = pounds / 2.2046226218 print "Let's talk about %s." % name print "He's %d inches tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s." % teeth print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight) print "%r inches equals %r centimeters." % (inches, centimeters) print "%s pounds equals %.5s kilos" % (pounds, kilos) #.(any number to round to certain decimal place in python)
import pandas as pd import numpy as np import xlrd df = pd.read_excel('Ey2.xlsx') df.rename(columns={'Unnamed: 0':'Airport','Unnamed: 1':'City','Unnamed: 2':'Month', 'Unnamed: 3':'CarrierID','Unnamed: 4':'Non_of_Flights' }) df1 = df.dropna() df1 # Example on how to read data from excel file #The data in the excel file was clean normally
#Question: '''Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: ''' x=int(input("Enter a number:")) i=1 y=1 if x==0: y=1 else: while i<=x: y=y*i i=i+1 print("The fatcorial is:",y)
''' Question: Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world ''' string=input("Enter string for removing duplicates and sorting seperated by whitespaces:") thislist=[x for x in string.split(" ")] thislist=sorted(list(set(thislist))) for x in thislist: print(x,end=" ")
#1. 데이터 구성 import numpy as np x = np.array([1,2,3]) y = np.array([1,2,3]) x2 = np.array([4,5,6]) #2. 모델구성 from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(100, input_dim = 1, activation = 'relu')) #input_dim(차원) : 1 (input layer) model.add(Dense(28)) # out-put : 100 -> 5 // layer 추가(node 갯수)(hidden layer) model.add(Dense(15)) #hidden layer model.add(Dense(7)) #input = 4 // output = 1 (hidden layer) model.add(Dense(5)) # output layer model.add(Dense(1)) # model.add(Dense(33)) # model.add(Dense(9)) # model.add(Dense(7)) # model.add(Dense(8)) # model.add(Dense(7)) # model.add(Dense(12)) # model.add(Dense(3)) # model.add(Dense(1)) #3. 훈련 model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) model.fit(x, y, epochs = 1000, batch_size=1) #4. 평가 예측 loss, acc = model.evaluate(x, y, batch_size=1) print("acc : ", acc) y_predict = model.predict(x2) print(y_predict)
name = "sam" last_letters = name[::] l = last_letters print (l) l = 'p' + l print (l) x = 'hello world' x = x + "it is bala!" print (x) x1 = "bala is beautiful" x1= x1. split('b') print (x1)
class Rect(object): def __init__(self, x0, y0, x1, y1): if (x0 > x1): t = x0 x0 = x1 x1 = t if (y0 > y1): t = y0 y0 = y1 y1 = t self.value = (x0, y0, x1, y1) def __getitem__(self, key): return self.value[key] def __len__(self): return 4 def __eq__(self,other): return ( other.value == self.value ) def inside(self, point): return ((point[0] >= self.value[0]) and (point[0] <= self.value[2]) and (point[1] >= self.value[1]) and (point[1] <= self.value[3])) def intersects(self, other): # is a point if (len(other) == 2): return self.inside(other) # is another rect if (len(other) == 4): return (not((other[2] < self.value[0]) and (other[0] > self.value[2]) and (other[3] < self.value[1]) and (other[1] > self.value[3])))
from abc import ABCMeta, abstractmethod #иппортируем из модуля abc, то что нам нужно для создания абстрактного базавого класса class IOperator(object): """ Интерфейс, который должны реализовать как декоратор, так и оборачиваемый объект. """ __metaclass__ = ABCMeta """ Используем абстрактный метод, для которого выше велючили метакласс. Этот метод ОБЯЗАТЕЛЬНО переопределяется и реализуется в наслеуемых классах! """ @abstractmethod def operator(self): pass class Component(IOperator): """Компонент программы""" def operator(self): return 10.0 class Wrapper(IOperator): """ Декоратор """ def __init__(self, obj): self.obj = obj def operator(self): return self.obj.operator() + 5.0 comp = Component() comp = Wrapper(comp) print comp.operator() # 15.0
""" UNIT 2: Logic Puzzle You will write code to solve the following logic puzzle: 1. The person who arrived on Wednesday bought the laptop. 2. The programmer is not Wilkes. 3. Of the programmer and the person who bought the droid, one is Wilkes and the other is Hamming. 4. The writer is not Minsky. 5. Neither Knuth nor the person who bought the tablet is the manager. 6. Knuth arrived the day after Simon. 7. The person who arrived on Thursday is not the designer. 8. The person who arrived on Friday didn't buy the tablet. 9. The designer didn't buy the droid. 10. Knuth arrived the day after the manager. 11. Of the person who bought the laptop and Wilkes, one arrived on Monday and the other is the writer. 12. Either the person who bought the iphone or the person who bought the tablet arrived on Tuesday. You will write the function logic_puzzle(), which should return a list of the names of the people in the order in which they arrive. For example, if they happen to arrive in alphabetical order, Hamming on Monday, Knuth on Tuesday, etc., then you would return: ['Hamming', 'Knuth', 'Minsky', 'Simon', 'Wilkes'] (You can assume that the days mentioned are all in the same week.) """ import itertools def logic_puzzle(): "Return a list of the names of the people, in the order they arrive." ## your code here; you are free to define additional functions if needed names =['Hamming', 'Knuth', 'Minsky', 'Simon', 'Wilkes'] jobs = ['programmer', 'writer', 'manager', 'designer', 'other' ] days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'] devices = ['laptop', 'tablet', 'droid', 'iPhone', 'nothing'] week = (monday, tuesday, wednesday, thursday, friday) = range(5) permutations = list(itertools.permutations(week)) result_set = [[(days[d], names[(Hamming, Knuth, Minsky, Simon, Wilkes).index(d)], jobs[(programmer, writer, manager, designer, other).index(d)], devices[(laptop, tablet, droid, iphone, nothing).index(d)],) for d in week] for Hamming, Knuth, Minsky, Simon, Wilkes in permutations for laptop, tablet, droid, iphone, nothing in permutations for programmer, writer, manager, designer, other in permutations if wednesday == laptop if programmer != Wilkes if set([programmer,droid]) ==set([Wilkes,Hamming]) if writer != Minsky if Knuth != manager and tablet != manager if Knuth == Simon + 1 if thursday != designer if friday != tablet if designer != droid if Knuth == manager +1 if monday != writer and set([laptop,Wilkes])==set([monday,writer]) if tuesday in set([tablet,iphone]) ] result = [] for r in result_set[0]: result.append(r[1]) return result
# Unit 5: Probability in the game of Darts """ In the game of darts, players throw darts at a board to score points. The circular board has a 'bulls-eye' in the center and 20 slices called sections, numbered 1 to 20, radiating out from the bulls-eye. The board is also divided into concentric rings. The bulls-eye has two rings: an outer 'single' ring and an inner 'double' ring. Each section is divided into 4 rings: starting at the center we have a thick single ring, a thin triple ring, another thick single ring, and a thin double ring. A ring/section combination is called a 'target'; they have names like 'S20', 'D20' and 'T20' for single, double, and triple 20, respectively; these score 20, 40, and 60 points. The bulls-eyes are named 'SB' and 'DB', worth 25 and 50 points respectively. Illustration (png image): http://goo.gl/i7XJ9 There are several variants of darts play; in the game called '501', each player throws three darts per turn, adding up points until they total exactly 501. However, the final dart must be in a double ring. Your first task is to write the function double_out(total), which will output a list of 1 to 3 darts that add up to total, with the restriction that the final dart is a double. See test_darts() for examples. Return None if there is no list that achieves the total. Often there are several ways to achieve a total. You must return a shortest possible list, but you have your choice of which one. For example, for total=100, you can choose ['T20', 'D20'] or ['DB', 'DB'] but you cannot choose ['T20', 'D10', 'D10']. """ def test_darts(): "Test the double_out function." assert double_out(170) == ['T20', 'T20', 'DB'] assert double_out(171) == None assert double_out(100) in (['T20', 'D20'], ['DB', 'DB']) """ My strategy: I decided to choose the result that has the highest valued target(s) first, e.g. always take T20 on the first dart if we can achieve a solution that way. If not, try T19 first, and so on. At first I thought I would need three passes: first try to solve with one dart, then with two, then with three. But I realized that if we include 0 as a possible dart value, and always try the 0 first, then we get the effect of having three passes, but we only have to code one pass. So I creted ordered_points as a list of all possible scores that a single dart can achieve, with 0 first, and then descending: [0, 60, 57, ..., 1]. I iterate dart1 and dart2 over that; then dart3 must be whatever is left over to add up to total. If dart3 is a valid element of points, then we have a solution. But the solution, is a list of numbers, like [0, 60, 40]; we need to transform that into a list of target names, like ['T20', 'D20'], we do that by defining name(d) to get the name of a target that scores d. When there are several choices, we must choose a double for the last dart, but for the others I prefer the easiest targets first: 'S' is easiest, then 'T', then 'D'. """ ordered_points = sorted(set(range(0,21) + range(22,42,2) + range(21,63,3) + [25,50])) def double_out(total): """Return a shortest possible list of targets that add to total, where the length <= 3 and the final element is a double. If there is no solution, return None.""" # your code here #ordered_points = sorted(set(range(0,21) + range(22,42,2) + range(21,63,3))) #print ordered_points for dart1 in ordered_points: for dart2 in ordered_points: dart3 = total - (dart1 + dart2) if (dart3%2)==0 and dart3 in ordered_points and name_lastdart(dart3) != None: sol = [name(dart1),name(dart2),name_lastdart(dart3)] if dart1 == 0 and dart2 == 0: return [sol[-1]] elif dart1 == 0: return sol[1:] else: return sol #print 'None' return None def name(dart): if dart <= 20: return 'S'+str(dart) elif dart == 50: return 'DB' elif dart == 25: return 'SB' elif dart <=40: if (dart%2)==0: return 'D'+str(dart/2) else: return 'T'+str(dart/3) elif dart <=60: return 'T'+str(dart/3) #print 'name Warning - dart: %s'%(dart) def name_lastdart(dart): 'last dart is already: dart%2 == 0' if 0 < dart <= 20: return 'D'+str(dart/2) elif dart == 50: return 'DB' elif 20 < dart <= 40: return 'D'+str(dart/2) #print 'name_lastdart Warning - dart: %s'%(dart) return None """ It is easy enough to say "170 points? Easy! Just hit T20, T20, DB." But, at least for me, it is much harder to actually execute the plan and hit each target. In this second half of the question, we investigate what happens if the dart-thrower is not 100% accurate. We will use a wrong (but still useful) model of inaccuracy. A player has a single number from 0 to 1 that characterizes his/her miss rate. If miss=0.0, that means the player hits the target every time. But if miss is, say, 0.1, then the player misses the section s/he is aiming at 10% of the time, and also (independently) misses the thin double or triple ring 10% of the time. Where do the misses go? Here's the model: First, for ring accuracy. If you aim for the triple ring, all the misses go to a single ring (some to the inner one, some to the outer one, but the model doesn't distinguish between these). If you aim for the double ring (at the edge of the board), half the misses (e.g. 0.05 if miss=0.1) go to the single ring, and half off the board. (We will agree to call the off-the-board 'target' by the name 'OFF'.) If you aim for a thick single ring, it is about 5 times thicker than the thin rings, so your miss ratio is reduced to 1/5th, and of these, half go to the double ring and half to the triple. So with miss=0.1, 0.01 will go to each of the double and triple ring. Finally, for the bulls-eyes. If you aim for the single bull, 1/4 of your misses go to the double bull and 3/4 to the single ring. If you aim for the double bull, it is tiny, so your miss rate is tripled; of that, 2/3 goes to the single ring and 1/3 to the single bull ring. Now, for section accuracy. Half your miss rate goes one section clockwise and half one section counter-clockwise from your target. The clockwise order of sections is: 20 1 18 4 13 6 10 15 2 17 3 19 7 16 8 11 14 9 12 5 If you aim for the bull (single or double) and miss on rings, then the section you end up on is equally possible among all 20 sections. But independent of that you can also miss on sections; again such a miss is equally likely to go to any section and should be recorded as being in the single ring. You will need to build a model for these probabilities, and define the function outcome(target, miss), which takes a target (like 'T20') and a miss ration (like 0.1) and returns a dict of {target: probability} pairs indicating the possible outcomes. You will also define best_target(miss) which, for a given miss ratio, returns the target with the highest expected score. If you are very ambitious, you can try to find the optimal strategy for accuracy-limited darts: given a state defined by your total score needed and the number of darts remaining in your 3-dart turn, return the target that minimizes the expected number of total 3-dart turns (not the number of darts) required to reach the total. This is harder than Pig for several reasons: there are many outcomes, so the search space is large; also, it is always possible to miss a double, and thus there is no guarantee that the game will end in a finite number of moves. """ def outcome(target, miss): "Return a probability distribution of [(target, probability)] pairs." #your code here dicto = {} if isTriple(target): #p1 <=> ring accuracy ok section accuracy ko or ok #p2 <=> ring accuracy ko section accuracy ko or ok p1 = 1 - miss p2 = miss # keep ring accuracy calculate section accuracy (clockwise and counterclockwise) p11 = p1 * miss * 0.5 p12 = p1 * miss * 0.5 p10 = p1 - (p11 + p12) key_Tcw = 'T' + str(cwTarget(target)) key_Tccw = 'T' + str(ccwTarget(target)) ket_T = target dicto[ket_T] = p10 dicto[key_Tcw] = p11 dicto[key_Tccw] = p12 # keep ring accuracy ko calculate section accuracy (clockwise and counterclockwise) p21 = p2 * miss * 0.5 p22 = p2 * miss * 0.5 p20 = p2 - (p21 + p22) key_Scw = 'S' + str(cwTarget(target)) key_Sccw = 'S' + str(ccwTarget(target)) key_S = 'S' + target[1:] dicto[key_S] = p20 dicto[key_Scw] = p21 dicto[key_Sccw] = p22 elif isDouble(target): hit = 1 - miss # hit ring accuracy hit or miss section pD = hit * hit pDcw = hit * miss * 0.5 pDccw = hit * miss * 0.5 # miss ring acc hit or miss section pOFF = miss * 0.5 pS = miss * 0.5 * hit pScw = miss * 0.5 * miss * 0.5 pSccw = miss * 0.5 * miss * 0.5 #keys key_Dcw = 'D' +str(cwTarget(target)) key_Dccw = 'D' +str(ccwTarget(target)) key_D = target key_Scw = 'S' +str(cwTarget(target)) key_Sccw = 'S' +str(ccwTarget(target)) key_S = 'S' + target[1:] dicto[key_D] = pD dicto[key_Dcw] = pDcw dicto[key_Dccw] = pDccw dicto['OFF'] = pOFF dicto[key_S] = pS dicto[key_Scw] = pScw dicto[key_Sccw] = pSccw elif isSingle(target): miss = miss/5. hit = 1 - miss # hit ring accuracy pS = hit * hit pScw = hit * miss * 0.5 pSccw = hit * miss * 0.5 # miss ring accuracy .5 to double .5 to triple pD = miss * 0.5 * hit pDcw = miss * 0.5 * miss * 0.5 pDccw = miss * 0.5 * miss * 0.5 pT = miss * 0.5 * hit pTcw = miss * 0.5 * miss * 0.5 pTccw = miss * 0.5 * miss * 0.5 #keys key_S = target key_Scw = 'S' + str(cwTarget(target)) key_Sccw = 'S' + str(ccwTarget(target)) key_D = 'D' + target[1:] key_Dcw = 'D' + str(cwTarget(target)) key_Dccw = 'D' + str(ccwTarget(target)) key_T = 'T' + target[1:] key_Tcw = 'T' + str(cwTarget(target)) key_Tccw = 'T' + str(ccwTarget(target)) dicto[key_S] = pS dicto[key_Scw] = pScw dicto[key_Sccw] = pSccw dicto[key_D] = pD dicto[key_Dcw] = pDcw dicto[key_Dccw] = pDccw dicto[key_T] = pT dicto[key_Tcw] = pTcw dicto[key_Tccw] = pTccw elif isSingleBull(target): hit = 1 - miss # hit ring accuracy pSB = hit * hit pS01 = hit * miss # miss ring accuracy #1/4 goes to DB 3/4 goes to S pDB = miss * 0.25 * hit pS02 = miss * 0.25 * miss pS03 = miss * 0.75 * hit pS04 = miss * 0.75 * miss pS = pS01 + pS02 + pS03 + pS04 pS_unit = pS/20. for d in dart_board: dicto['S'+str(d)] = pS_unit dicto['SB'] = pSB dicto['DB'] = pDB elif isDoubleBull(target): hit = 1 - miss #3 times less hits hit = hit / 3. miss = 1 - hit # hit ring accuracy pDB = hit * hit pS01 = hit * miss # miss ring accuracy # 1/3 goes to SB or S; 2/3 goes to S or S pS02 = miss * (2/3.) * hit pS03 = miss * (2/3.) * miss pSB = miss * (1/3.) * hit pS04 = miss * (1/3.) * miss pS = pS01 + pS02 + pS03 + pS04 pS_unit = pS/20. for d in dart_board: dicto['S'+str(d)] = pS_unit dicto['DB'] = pDB dicto['SB'] = pSB else: print 'Error' return dicto dart_board = [20, 1, 18, 4, 13, 6, 10, 15, 2, 17, 3, 19, 7, 16, 8, 11, 14, 9, 12, 5] def cwTarget(target): 'next ClockWise target' index = int(target[1:]) cw = 0 for i in range(len(dart_board)): if dart_board[i] == index: if i + 1 >= len(dart_board): cw = dart_board[0] break else: cw = dart_board[i+1] break return cw def ccwTarget(target): 'next CounterClockWise target' index = int(target[1:]) ccw = 0 for i in range(len(dart_board)): if dart_board[i] == index: ccw = dart_board[i-1] break return ccw def isTriple(target): return target[0] == 'T' def isDouble(target): return target != 'DB' and target[0] == 'D' def isSingle(target): return target[0] == 'S' and not isSingleBull(target) def isDoubleBull(target): return target == 'DB' def isSingleBull(target): return target == 'SB' def best_target(miss): "Return the target that maximizes the expected score." #your code here all_darts = [] for d in dart_board: all_darts.append('S'+str(d)) all_darts.append('D'+str(d)) all_darts.append('T'+str(d)) all_darts.append('SB') all_darts.append('DB') max_darts = {} for d in all_darts: out = outcome(d,miss) expected = 0 for k in out.keys(): expected = expected + dart_score(k,out[k]) max_darts[d] = expected res = max(max_darts, key = lambda x: max_darts[x]) return res def dart_score(dart,p): if isSingleBull(dart): return 25*p elif isDoubleBull(dart): return 50*p elif isTriple(dart): return int(dart[1:])*3*p elif isDouble(dart): return int(dart[1:]) * 2 * p elif isSingle(dart): return int(dart[1:]) * p else:#OFF return 0 def same_outcome(dict1, dict2): "Two states are the same if all corresponding sets of locs are the same." return all(abs(dict1.get(key, 0) - dict2.get(key, 0)) <= 0.0001 for key in set(dict1) | set(dict2)) def test_darts2(): assert best_target(0.0) == 'T20' assert best_target(0.1) == 'T20' assert best_target(0.4) == 'T19' assert same_outcome(outcome('T20', 0.0), {'T20': 1.0}) assert same_outcome(outcome('T20', 0.1), {'T20': 0.81, 'S1': 0.005, 'T5': 0.045, 'S5': 0.005, 'T1': 0.045, 'S20': 0.09}) assert (same_outcome( outcome('SB', 0.2), {'S9': 0.016, 'S8': 0.016, 'S3': 0.016, 'S2': 0.016, 'S1': 0.016, 'DB': 0.04, 'S6': 0.016, 'S5': 0.016, 'S4': 0.016, 'S20': 0.016, 'S19': 0.016, 'S18': 0.016, 'S13': 0.016, 'S12': 0.016, 'S11': 0.016, 'S10': 0.016, 'S17': 0.016, 'S16': 0.016, 'S15': 0.016, 'S14': 0.016, 'S7': 0.016, 'SB': 0.64})) def test_identifiers(): assert isTriple('T20') assert not isDouble('T20') assert isDouble('D15') assert isSingle('S3') assert not isSingle('T2') assert isSingleBull('SB') assert not isSingleBull('DB') assert isDoubleBull('DB') assert not isDoubleBull('D20') print 'all identifier tests passed!' def test_clock(): assert cwTarget('T20') == 1 assert ccwTarget('T20') == 5 assert cwTarget('D16') == 8 assert ccwTarget('D16') == 7 assert cwTarget('S5') == 20 assert ccwTarget('S5') == 12 print 'all clock tests passed!' def test_scores(): assert dart_score('T20',1.0) == 60 assert dart_score('T20',0.9) == 60*0.9 assert dart_score('D10',1.0) == 20 assert dart_score('D10',0.9) == 20*0.9 assert dart_score('S2',1.0) == 2 assert dart_score('S2',0.9) == 2*0.9 assert dart_score('SB',1.0) == 25 assert dart_score('SB',0.9) == 25*0.9 assert dart_score('DB',1.0) == 50 assert dart_score('DB',0.9) == 50 * 0.9 print 'all scores passed!' def test_outcomes(): assert same_outcome(outcome('D20',0.1), {'D20': 0.81, 'S1': 0.0025, 'D5': 0.045, 'S5': 0.0025, 'D1': 0.045, 'S20': 0.045, 'OFF': 0.05}) assert (same_outcome(outcome('DB',0.2), {'S9': 0.0432, 'S8': 0.0432, 'S3': 0.0432, 'S2': 0.0432, 'S1': 0.0432, 'DB': 0.0711, 'S6': 0.0432, 'S5': 0.0432, 'S4': 0.0432, 'S20': 0.0432, 'S19': 0.0432, 'S18': 0.0432, 'S13': 0.0432, 'S12': 0.0432, 'S11': 0.0432, 'S10': 0.0432, 'S17': 0.0432, 'S16': 0.0432, 'S15': 0.0432, 'S14': 0.0432, 'S7': 0.0432, 'SB': 0.0651})) print 'all tests passed!'
class Person: name = 'default name' def __init__(self): print('__init__' ) def print(self): print(self.name) def __del__(self): print('__del__') p1 = Person() p1.print() p1.name = 'wellstone' p1.print()
import unittest def solution(n): answer = '' nums = ['1', '2', '4'] quotient = -1 while quotient != 0: quotient = int((n - 1) / 3) remainder = (n - 1) % 3 answer = nums[remainder] + answer n = quotient return int(answer) class Module1Test(unittest.TestCase): def testCase01(self): self.assertEqual(solution(1), 1) def testCase02(self): self.assertEqual(solution(2), 2) def testCase03(self): self.assertEqual(solution(3), 4) def testCase04(self): self.assertEqual(solution(4), 11) def testCase10(self): self.assertEqual(solution(10), 41) if __name__ == '__main__': unittest.main()
# Zeller's Algorithm # # Zeller's algorithm computes the day of the week on which a given date will # fall (or fell). In this exercise, you will write a program to run Zeller's # algorithm on a specific date. The program should use the algorithm outlined # below to compute the day of the week on which the user's birthday fell in # the year you were born and print the result to the screen. print "Let's find out the day of the week when you're born." print "Enter your date of birth:" month = input("Month? (in number, eg: 3 for March) ") day = input("Day? ") year = input("Year? ") if (3 <= month <= 12): A = month - 2 B = day if (month == 1 or month == 2): A = 10 + month C = (year % 100) - 1 else: C = year % 100 D = year / 100 W = (13 * A - 1) / 5 X = C / 4 Y= D / 4 Z = W + X + Y + B + C - 2 * D R = Z % 7 if R == 0: print "You're born on a Sunday." elif R == 1: print "You're born on a Monday." elif R == 2: print "You're born on a Tuesday." elif R == 3: print "You're born on a Wednesday." elif R == 4: print "You're born on a Thursday." elif R == 5: print "You're born on a Friday." elif R == 6: print "You're born on a Saturday."
def get_bounds(points): """ return bounding box of a list of gpxpy points """ min_lat = None max_lat = None min_lon = None max_lon = None min_ele = None max_ele = None for point in points: if min_lat is None or point.latitude < min_lat: min_lat = point.latitude if max_lat is None or point.latitude > max_lat: max_lat = point.latitude if min_lon is None or point.longitude < min_lon: min_lon = point.longitude if max_lon is None or point.longitude > max_lon: max_lon = point.longitude if min_ele is None or point.elevation < min_ele: min_ele = point.elevation if max_ele is None or point.elevation > max_ele: max_ele = point.elevation if min_lat and max_lat and min_lon and max_lon: return {'min_latitude': min_lat, 'max_latitude': max_lat, 'min_longitude': min_lon, 'max_longitude': max_lon, 'min_elevation': min_ele, 'max_elevation': max_ele, } return None
# This script calculates the walking distance from origin point to destination point included in the dataset using coordinates import pandas as pd import googlemaps # Inserting the API key gmaps = googlemaps.Client(key='XXXXXXXXXXXXXXXXXX') def distance_function(data): df = pd.DataFrame(data) # Setting the Tableau London office coordinates as the origin latitude_origin='51.5062' longitude_origin='-0.0998' origin = (latitude_origin,longitude_origin) # Take the coordinates of each row, use the Google Distance Matrix API to calculate distances for i,Lat,Long in zip(df.index,df['Latitude'],df["Longitude"]): try: destination = (Lat,Long) distance = gmaps.distance_matrix(origin, destination, mode='walking')["rows"][0]["elements"][0]["distance"]["value"] df.at[i,'Distance'] = distance except: pass return df # Defining the output schema for Prep def get_output_schema(): return pd.DataFrame({ 'Address' : prep_string(), 'Latitude' : prep_decimal(), 'Longitude' : prep_decimal(), 'Distance': prep_int(), 'Name' : prep_string(), 'Price Level' : prep_int(), 'Rating' : prep_decimal() })
from fractions import Fraction, gcd import functools # Given numpy is not a standard library to invert a matrix the following functions # are taken from link; transposeMatrix, getMatrixMinor, getMatrixDeternminant, getMatrixInverse # https://stackoverflow.com/questions/32114054/matrix-inversion-without-numpy def transposeMatrix(m): return map(list,zip(*m)) def getMatrixMinor(m,i,j): return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])] def getMatrixDeternminant(m): #base case for 2x2 matrix if len(m) == 2: return m[0][0]*m[1][1]-m[0][1]*m[1][0] determinant = 0 for c in range(len(m)): determinant += ((-1)**c)*m[0][c]*getMatrixDeternminant(getMatrixMinor(m,0,c)) return determinant def getMatrixInverse(m): determinant = getMatrixDeternminant(m) #special case for 2x2 matrix: if len(m) == 2: return [[m[1][1]/determinant, -1*m[0][1]/determinant], [-1*m[1][0]/determinant, m[0][0]/determinant]] #find matrix of cofactors cofactors = [] for r in range(len(m)): cofactorRow = [] for c in range(len(m)): minor = getMatrixMinor(m,r,c) cofactorRow.append(((-1)**(r+c)) * getMatrixDeternminant(minor)) cofactors.append(cofactorRow) cofactors = list(transposeMatrix(cofactors)) for r in range(len(cofactors)): for c in range(len(cofactors)): cofactors[r][c] = cofactors[r][c]/determinant return cofactors def subtractMatrix(A,B): n = len(A) return [[A[i][j] - B[i][j] for j in range(n)] for i in range(n)] def multiplyMatrix(A,B): n = len(A) m = len(B[0]) return [[sum([A[Arow][i] * B[i][Bcol] for i in range(n)]) for Bcol in range(m)] for Arow in range(n)] def LCM(fractions): # LCM of 2 numbers def LCM_(a,b): return a*b // gcd(a,b) # Get denominators dems = [] for frac in fractions: dems.append(frac.denominator) # Get lcm of all denominators lcm = functools.reduce(LCM_,dems) return int(lcm) def formatOutput(probs): output = [] fractions = [] # Convert to fractions for prob in probs: fractions.append(Fraction.from_float(prob).limit_denominator()) # Find LCM lcm = LCM(fractions) # Create output for frac in fractions: output.append(int(frac.numerator * lcm/frac.denominator)) output.append(lcm) return output def relocateState(m, i0, iNew): assert iNew < i0 #only for moving state up and shifting down # shift rows temp = m[i0] for i in range(i0,iNew,-1): m[i] = m[i-1] m[iNew] = temp # shift cols for row in m: temp = row[i0] for i in range(i0,iNew,-1): row[i] = row[i-1] row[iNew] = temp return m def formatMarkovMatrix(m): # Check if termination states are above transition states trans_states = [] trem_states = [] for i,row in enumerate(m): trem_states.append(i) if (sum(row) == 0) else trans_states.append(i) # Move all trans states above trem states, perserving trem state order while max(trans_states) > min(trem_states): j = min(trem_states) i = max(trans_states) m = relocateState(m,i,j) # revaluate matrix trans_states = [] trem_states = [] for i,row in enumerate(m): trem_states.append(i) if (sum(row) == 0) else trans_states.append(i) return m def solution(m): # https://brilliant.org/wiki/absorbing-markov-chains/ # Count state types and normalize rows n_trans = 0 n_trem = 0 for i,row in enumerate(m): if sum(row) == 0: n_trem += 1 else: n_trans += 1 m[i] = [float(elem)/sum(row) for elem in row] # If s0 is a termination state if sum(m[0]) == 0: P0 = [0]*n_trem P0[0] = 1 P0.append(1) return P0 # Ensure proper matrix form, termination states are at bottom m = formatMarkovMatrix(m) # Get Q matrix Q = m[:n_trans] for i in range(n_trans): Q[i] = Q[i][:n_trans] # Get R matrix R = m[:n_trans] for i in range(n_trans): R[i] = R[i][n_trans:] # Get I matrix I = [[1 if i == j else 0 for j in range(n_trans)] for i in range(n_trans)] # Get N matrix N = getMatrixInverse(subtractMatrix(I,Q)) # Get M matrix M = multiplyMatrix(N,R) # Get probabilities assuming starting at s0 I0 = [0]*n_trem I0[0] = 1 P = multiplyMatrix([I0],M) # Format and return probabilities return formatOutput(P[0]) m0 = [ [0,1,0,0,0,1], # s0, the initial state, goes to s1 and s5 with equal probability [4,0,0,3,2,0], # s1 can become s0, s3, or s4, but with different probabilities [0,0,0,0,0,0], # s2 is terminal, and unreachable (never observed in practice) [0,0,0,0,0,0], # s3 is terminal [0,0,0,0,0,0], # s4 is terminal [0,0,0,0,0,0], # s5 is terminal ] m1 = [ [1, 1, 1, 0, 1, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 1, 1, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ] m2 = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ] assert (solution(m0)) == [0, 3, 2, 9, 14] assert (solution(m1)) == [2, 1, 1, 1, 1, 6] assert (solution(m2)) == [1, 1, 1, 1, 1, 5] assert (solution([[0, 2, 1, 0, 0], [0, 0, 0, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0,0], [0, 0, 0, 0, 0]])) == [7, 6, 8, 21] assert (solution([[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0,0], [0, 0, 0, 0, 0]])) == [1, 0, 0, 0, 1] print("All tests passed")
"""level 10 Find len(sequence[30]) Given the sequence = [1, 11, 21, 1211, 111221, ...] This is the 'Look and Say' sequence: https://en.wikipedia.org/wiki/Look-and-say_sequence """ def level_10(num): """Return the next number in the 'see-and-say' sequence, given a number. The next number in the sequence is found by saying the count of each digit, in order, in the current number. """ # ensure the input is a number as a string num_as_str = str(num) count = 0 current_digit = num_as_str[0] next_num_as_str = '' for digit in num_as_str: if digit == current_digit: count += 1 else: next_num_as_str += '{}{}'.format(count, current_digit) count = 1 current_digit = digit else: next_num_as_str += '{}{}'.format(count, current_digit) return next_num_as_str if __name__ == '__main__': sequence = ['1'] for x in range(30): sequence.append(level_10(sequence[x])) print('\n [+] len(sequence[30]): {}'.format(len(sequence[30])))
print("Bem vindo à melhor calculadora de sempre.") print("Por favor insere o primeiro número, a operação a realizar, e depois o segundo número.") print("Sou capaz de fazer somas (+), subtrações (-), multiplicações (*) e divisões (/)") #input de variaveis num1 = float(input("Primeiro número: ")) sinal = input("Operação matemática (+, -, *, /): ") num2 = float(input("Segundo número: ")) #operações matematicas if sinal == "+": num3 = num1 + num2 print(str(num1) + " + " + str(num2) + " = " + str(num3)) elif sinal == "-": num3 = num1 - num2 print(str(num1) + " - " + str(num2) + " = " + str(num3)) elif sinal == "*": num3 = num1 * num2 print(str(num1) + " x " + str(num2) + " = " + str(num3)) elif sinal == "/": num3 = num1 / num2 print(str(num1) + " / " + str(num2) + " = " + str(num3)) else: print("Não escolheste nenhum operador permitido")
# coding=utf-8 # -*- coding:utf-8 -*- ''' Author: Solarzhou Email: [email protected] date: 2019/11/12 22:00 desc: ''' # 方法1:动态规划 # 一般可以使用动态规划求解的问题有如下四个特点: # 1)求一个问题的最优解(可以是最大值或者时最小值) # 2)整体entity的最优解是依赖于各个子问题的最优解 # 3)这些小问题还有相互重叠的更小的问题; # 4)从上往下分析,从下往上求解;即: # 由于子问题在分解大问题的过程中重复出现,为了避免重复求解子问题, # 我们可以用从下往上的顺序先求解子问题的最优解,并存储下来,再以此为基础求去 # 最大问题的最优解。 class Solution: def cutRope(self, number): # write code here if number < 2: return 0 if number == 2: return 1 if number == 3: return 2 products = [0, 1, 2, 3] for i in range(4, number + 1): max_1 = 0 for j in range(1, i // 2 + 1): product = products[j] * products[i - j] max_1 = max(max_1, product) products.append(max_1) return products.pop() if __name__ == '__main__': maxRes = Solution().cutRope(6) print(maxRes) # 方法2: 贪婪算法 def cutRope(number): if number < 2: return 0 if number == 2: return 1 if number == 3: return 2 # 尽可能多地减去长度为3的绳子段 timesOf3 = number // 3 # 当绳子最后剩下的长度为4的时候,不能再剪去长度为3的绳子段。 # 此时更好的方法是把绳子剪成长度为2的两段,因为2 * 2 > 3 * 1。 if number - timesOf3 * 3 == 1: timesOf3 -= 1 timesOf2 = (number - timesOf3 * 3) // 2 return int(pow(3, timesOf3) * pow(2, timesOf2))
# 解题思路: # 对于两棵二叉树来说,要判断B是不是A的子结构,首先第一步在树A中查找与B根节点的值一样的节点。 # 通常对于查找树中某一个节点,我们都是采用递归的方法来遍历整棵树。 # 第二步就是判断树A中以R为根节点的子树是不是和树B具有相同的结构。 # 这里同样利用到了递归的方法,如果节点R的值和树的根节点不相同,则以R为根节点的子树和树B肯定不具有相同的节点; # 如果它们值是相同的,则递归的判断各自的左右节点的值是不是相同。 # 递归的终止条件是我们达到了树A或者树B的叶节点。 # 有地方要重点注意,is_subTree()函数中的两个 if 判断语句 不能颠倒顺序 。 # 因为如果颠倒了顺序,会先判断pRoot1 是否为None, 其实这个时候,pRoot1 的节点已经遍历完成确认相等了, # 但是这个时候会返回 False,判断错误。 class Solution: def HasSubtree(self, pRoot1, pRoot2): result = False if pRoot1 != None and pRoot2 != None: if pRoot1.val == pRoot2.val: result = self.is_subTree(pRoot1, pRoot2) if not result: result = self.HasSubtree(pRoot1.left, pRoot2) if not result: result = self.HasSubtree(pRoot1.right, pRoot2) return result def is_subTree(self, pRoot1, pRoot2): if pRoot2 == None: return True if pRoot1 == None: return False if pRoot1.val != pRoot2.val: return False return self.is_subTree(pRoot1.left, pRoot2.left) and \ self.is_subTree(pRoot1.right, pRoot2.right)
# coding=utf-8 # -*- coding:utf-8 -*- ''' Author: Solarzhou Email: [email protected] date: 2020/1/10 14:45 desc: ''' # 思路: 使用“”“”“"二分法"解决问题 class Solution(object): def getNumberSameAsIndex(self, nums): high = len(nums) - 1 low = 0 while low < high: mid = (low + high) // 2 if nums[mid] < mid: low = mid + 1 else: assert nums[mid] >= mid high = mid return low if nums[low] == low else -1 if __name__ == '__main__': print(Solution().getNumberSameAsIndex([-3, -1, 1, 3, 5]))
# solutions 1 # 使用python内置函数 class Solution: # s 源字符串 def replaceSpace(self, s): # write code here return s.replace(' ', '%20') # solution 2 # 正则表达式 import re class Solution1: # s 源字符串 def replaceSpace(self, s): # write code here # ret = re.compile(' ') # return ret.sub('%20', s) return re.sub(r'\s', lambda m: '%20', s) # 方法3 # 遍历所给列表,当遇到空格时,使用"20%"替换 class Solution3: @staticmethod def replaceSpace(arrStr): arrStr = list(arrStr) for i in range(len(arrStr)): if arrStr[i] == " ": arrStr[i] = "%20" return "".join(arrStr) if __name__ == '__main__': arrStr = "We Are Happy" print(Solution3.replaceSpace(arrStr))
# -*- coding:utf-8 -*- # 方法 1 # 思路:将所给字符串s当做列表进行处理,很容易就能得到左移、右移效果, # 将转换后的字符串存储到列表result中,之后对result中的元素进行拼接。 class Solution: def LeftRotateString(self, s, n): # write code here if not s: return "" lenS = len(s) result = [] if lenS < n: return '' else: result.append(s[n:]) result.append(s[:n]) return ''.join(result) # 方法 2 # 不借助额外空间 # 将所给字符串分为三部分进行逆转排序。首先将前n个逆转,之后将[n:]逆转, # 最后将列表中的所有元素逆转并拼接 class Solution1: def LeftRotateString(self, s, n): # write code here len_s = len(s) if n <= 0 or len_s == 0: return s n = n % len_s s = list(s) self.reverse(s, 0, n - 1) self.reverse(s, n, len(s) - 1) self.reverse(s, 0, len(s) - 1) return ''.join(s) def reverse(self, s, start, end): while start < end: s[start], s[end] = s[end], s[start] start += 1 end -= 1 # 方法3 # 参考程序员面试指南,第五章翻转字符串 p269 class Solution2: def rotate2(self, arr, size): if not arr or size > len(arr): return start = 0 end = len(arr) - 1 lpart = size rpart = len(arr) - size s = min(lpart, rpart) d = lpart - rpart while True: self.exchange(arr, start, end, s) if d == 0: break elif d > 0: start += s lpart = d else: end -= s rpart = -d s = min(lpart, rpart) d = lpart - rpart return arr def exchange(self, arr, start, end, size): i = end - size + 1 while size != 0: arr[start], arr[i] = arr[i], arr[start] start += 1 i += 1 size -= 1 if __name__ == '__main__': arr = list('1234567abcd') size = 7 print(Solution2().rotate2(arr,size))
# coding=utf-8 # -*- coding:utf-8 -*- ''' Author: Solarzhou Email: [email protected] date: 2019/11/7 22:43 desc: ''' # 思路: # 通过两层循环找出符合要求的最大数; # 1)外层循环从第一个数字,依次遍历; # 2)内层循环依次许多size个数,即range(i, i+size),将最大的数字取出来追加到result中。 class Solution: def maxInWindows(self, num, size): # write code here if not num: return [] result = [] # 滑动窗口大于数组长度时返回空列表可以通过调试。 if size > len(num): # result.append(max(num)) return [] if size < 1: return [] for i in range(len(num)): if i + size <= len(num): temp = [] for i in range(i, i + size): temp.append(num[i]) # print(temp) result.append(max(temp)) return result # 同样的思路可以这样解决,代码更简洁 class Solution1: def maxInWindows(self, num, size): # write code here if size <= 0: return [] res = [] for i in range(0, len(num) - size + 1): res.append(max(num[i:i + size])) return res # 方法3 # 使用单调栈 class Solution2: def getMaxWindows(self, arr, size): if not arr or size > len(arr): return None res = [] # 用来存储当前窗口的最大值 qMax = [] for i in range(len(arr)): if qMax and arr[i] >= arr[qMax[-1]]: qMax.pop() qMax.append(i) # 判断qMax队头元素是否过期 if qMax[0] == i - size: qMax.pop(0) if i >= size - 1: res.append(arr[qMax[0]]) return res if __name__ == '__main__': arr = [2, 3, 4, 2, 6, 2, 5] print(Solution().maxInWindows(arr, 3)) print(Solution2().getMaxWindows(arr, 3))
# 解题思路 # 1. 把复制的结点链接在原始链表的每一对应结点后面 # 2. 把复制的结点的random指针指向当前节点random指针的下一个结点 # 3. 拆分成两个链表,奇数位置为原链表,偶数位置为复制链表, # 注意复制链表的最后一个结点的next指针不能跟原链表指向同一个空结点None, # next指针要重新赋值None(判定程序会认定你没有完成复制) class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: def Clone(self, pHead): if not pHead: return None # 复制节点在原节点之后 pCur = pHead while pCur is not None: node = RandomListNode(pCur.label) node.next = pCur.next pCur.next = node pCur = node.next # 复制random 指针 pCur = pHead while pCur is not None: if pCur.random is not None: pCur.next.random = pCur.random.next pCur = pCur.next.next # 将新旧链表分离 head = pHead.next cur = head pCur = pHead while pCur: pCur.next = pCur.next.next if cur.next: cur.next = cur.next.next pCur = pCur.next cur = cur.next return head
import MapReduce import collections import sys """ Count asymmetric friendships """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): person = record[0] friend = record[1] mr.emit_intermediate(person, friend) mr.emit_intermediate(friend, person) def reducer(person, list_of_friends): existing_relationships = [] for friend in list_of_friends: existing_relationships.append(friend) # Since mapped both (friend,person) and (person,friend), # those that exist only once in list of existing relationships are asymmetric friends asymmetric_friends = [x for x, y in collections.Counter(existing_relationships).items() if y==1] for friend in asymmetric_friends: # Only need to emit once. The reducer of the friend will emit # the other to ensure symmetry mr.emit((person,friend)) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) result = open('mr_result.txt','w') result.write(mr.execute(inputdata, mapper, reducer)) result.close()
def numb_input(): input1 = input("give me a number ") input2 = input("give me another number ") input3 = input("third number please ") return int(input1), int(input2), int(input3) def addup(): num1, num2, num3 = numb_input() sum = num1 + num2 + num3 print(sum) def main(): addup() print("ソフトウェア開発の定番ツールとなったGitHubは今や世界中の企業で採用されており、チームでプロジェクトを進めるさいには欠かせないものとなりました。") if __name__ == "__main__": main()
''' print('第一题') l = [] def input_number(): while True: i = int(input('输入数字(-1结束):')) if i < 0: break l.append(i) return l input_number() print('刚才输入的整数是:',l) ''' print('第二题') def isprime(x): if x <= 1: #排除小于2的情况 return False if x == 2: return True for i in range(2,x): if x%i == 0: return False return True if isprime(9): print('素数') else: print('不是素数') print('第三题') def prime_m2n(m,n): l = [] for i in range(m,n): if isprime(i): l.append(i) return l #return list(filter(isprime,range(m,n))) print(prime_m2n(10,20)) print('第四题') def primes(n): l = [] for i in range(n): if isprime(i): l.append(i) return l #return prime_m2n(2,n) print(primes(10))
# -*- coding: utf-8 -*- from __future__ import unicode_literals import functools def f1(x, y): print('f1:', x, y) return x + y a = [1, 2, 3] print(a) b = sum(a) print(b) #c = functools.reduce(f1, a) c = functools.reduce(lambda x, y: x + y, a) print(c)
class FileManage: '''定义一个文件管理员类''' def __init__(self,filename='a.txt'): self.file = open(filename,'w') def writeline(self,string): self.file.write(string) self.file.write('\n') def __del__(self): '''析构方法会在对象销毁前自动调用''' self.file.close() print('文件已关闭') fm = FileManage() fm.writeline('hello world') fm.writeline('fff')
#class_varible.py #此示例示意类变量的用途和使用方法 class Human: total_count = 0 def __init__(self,name): self.name = name self.__class__.total_count += 1 #人数加1 print(name,'对象创建') def __del__(self): self.__class__.total_count -= 1 #总人数减1 print('当前对象的个数是:',Human.total_count) h1 = Human('张飞') h2 = Human('赵云') print('当前对象的个数是:',Human.total_count) del h1 print('当前对象的个数是:',Human.total_count)
#mynumber.py #此程序示意运算符重载 class Mynumber: def __init__(self,v): self.data = v def __repr__(self): return 'Mynumber(%d)' %self.data def __add__(self,other): print('__add__方法被调用') obj = Mynumber(self.data + other.data) return obj def __sub__(self,other): obj = Mynumber(self.data - other.data) return obj def __mul__(self,other): return Mynumber(self.data * other.data) n1 = Mynumber(100) n2 = Mynumber(200) #n3 = n1.__add__(n2) n3 = n1 + n2 #等同于n1.__add__(n2) print(n3) n4 = n1 - n2 print(n4)
n=int(input('输入一个数:')) #方法一 if n > 0: print(n) else: print(-n) #方法二 if n < 0: n = -n print(n) #方法三 print(n if n>0 else -n)
#打印'AaBbCcDd.....YyZz' for i in range(ord('A'),ord('Z')+1): print(chr(i)+chr(i).lower(),end='') print() n = int(input('输入整数:')) for i in range(1,n+1): for j in range(i,i+n): print('%2d' %j,end=' ') print()
''' print('第一题') def mysum(*args): return sum(args) print(mysum(1,3,36,3)) ''' print('第二题') #方法一 def mymax(*args): if len(args) == 1: l = list(*args) l.sort() return l[-1] #return max(args[0]) return max(args) #方法二 def mymax2(a,*args): if len(args) == 0: m = a[0] #先假设第一个数最大 i = 1 while i < len(a):#遍历之后的每一个元素 if a[i] > m: m = a[i] i += 1 return m else: m = a for x in args: if x > m: m = x return m #方法三: def mymax3(a,*args): def _max(*args): m = args[0] i = 1 while i < len(args): if args[i] > m: m = args[i] i += 1 return m if len(args) == 0: return _max(*a) return _max(a,*args) print(mymax([1,2,3])) #print(mymax(100,200)) #print(mymax('abc')) #print(mymax('c','f','g')) #print(mymax([1,23,4],[3,4,5])) #print(mymax(1,[2,3])) ''' print('第三题') def min_max(*args): t = (min(args),max(args)) return t print(min_max(1,2,3,4)) '''
class Biology: def fun(self): self.fun_self() class Animal(Biology): def fun_self(self): print("一类动物") class Dog(Animal): def fun_self(self): print("一条狗") def myfun(s): s.fun_self() s1 = Animal() myfun(s1) # 输出结果: s1 = Dog() myfun (s1) #输出结果: def decdsso(fn): print("decdsso") def f2(): print("f2") return f2 @decdsso def myfunc(): print("myfun!") myfunc() def f1(): v = 200 def f2(): v = 300 def f3(): nonlocal v v = 400 print('f2.v= ',v ) f2() print('f1.v=',v) f1()
s1 = input('请输入第一行字符串:') s2 = input('请输入第二行字符串:') s3 = input('请输入第三行字符串:') l = (max(len(s1),len(s2),len(s3)) + 2) l1 = (l-len(s1))//2 l2 = (l-len(s2))//2 l3 = (l-len(s3))//2 print('+'+'-'*l+'+') print('|'+' '*l1+s1+' '*((l-len(s1))-l1)+'|') print('|'+' '*l2+s2+' '*((l-len(s2))-l2)+'|') print('|'+' '*l3+s3+' '*((l-len(s3))-l3)+'|') print('+'+'-'*l+'+')
#此示例示意for语句的用法: s = 'abcde' for x in s: print('---->',x) else: print('for循环因迭代对象结束而终止')
class Human: count = 0 #类变量 def __init__(self,n,a,addr): self.name = n self.age = a self.id = addr self.__class__.count += 1 #修改类变量 def __del__(self): self.__class__.count -= 1 @classmethod def get_human_count(cls): return cls.count def show_info(self): print('''姓名:%s 年龄:%d 家庭住址:%s''' %(self.name,self.age,self.id)) def updata_age(self): self.age += 1 def input_human(): lst = [] while True: n = input('输入姓名:') if not n: break a = int(input('输入年龄:')) addr = input('请输入地址:') if not addr: addr = '未填写' h = Human(n,a,addr) lst.append(h) return lst def main(): docs = input_human() print('当前的总人数是',Human.get_human_count()) for h in docs: h.show_info() for h in docs: h.updata_age() for h in docs: h.show_info() main()
import time,sys while True: #print('\r %2d:%2d:%2d' %time.localtime()[3:6],end='') print('\r%02d:%02d:%02d' %time.localtime()[3:6],end='') #在cmd内可以看出效果,在IDLE内无法看出效果 time.sleep(1) ''' y=int(input('年:')) m=int(input('月:')) d=int(input('日:')) t=time.mktime((y,m,d,0,0,0,0,0,0)) print(t) time_tuple = time.localtime((t)) week = time_tuple[6] l=[1,2,3,4,5,6,7] print(l[week]) t= time.time()-t day=t//(60*60*24) print(day) '''
import numpy as np import csv f=open('winequality-red.csv', 'r') wines=list(csv.reader(f, delimiter=";")) #print(wines[:3]) qualities = [float(item[-1]) for item in wines[1:]] #print(sum(qualities) / len(qualities)) a=np.array(wines) #print(a.shape) wines = np.genfromtxt("winequality-red.csv", delimiter=";", skip_header=1) ''' Load data from a text file, with missing values handled as specified. Each line past the first skip_header lines is split at the delimiter character ''' #print(wines[2,3]) #print(wines[0:3]) #print(wines[0:3,3]) #print(wines[:,:]) earnings = [ [ [500,505,490], [810,450,678], [234,897,430], [560,1023,640] ], [ [600,605,490], [345,900,1000], [780,730,710], [670,540,324] ] ] earnings = np.array(earnings) #print(earnings[1,0,0]) #print(earnings) rand_array = np.random.rand(12) #print(wines + rand_array) #print(rand_array) high_quality = wines[:,11] > 7 #print(wines[high_quality,:][:3,:]) high_quality_and_alcohol = (wines[:,10] > 10) & (wines[:,11] > 7) #print(wines[high_quality_and_alcohol,10:]) high_quality_and_alcohol = (wines[:,10] > 10) & (wines[:,11] > 7) wines[high_quality_and_alcohol,10:] = 20 #Reshaping NumPy Arrays #print(np.transpose(wines).shape) #print(wines.ravel()) ''' the numpy.ravel function to turn an array into a one-dimensional representation. It will essentially flatten an array into a long sequence of values ''' array_one = np.array( [ [1, 2, 3, 4], [5, 6, 7, 8] ] ) #print(array_one.ravel()) #print(wines[1,:].reshape((2,6))) # Combining NumPy Arrays white_wines = np.genfromtxt("winequality-white.csv", delimiter=";", skip_header=1) #print(white_wines.shape) all_wines = np.vstack((wines, white_wines)) ''' vstack function to combine wines and white_wines ''' print(all_wines.shape) print(np.concatenate((wines, white_wines), axis=0)) ''' link=> https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html#numpy.concatenate numpy.concatenate as a general purpose version of hstack and vstack. If we want to concatenate two arrays, we pass them into concatenate, then specify the axis keyword argument that we want to concatenate along. Concatenating along the first axis is similar to vstack, and concatenating along the second axis is similar to hstack '''
def outer(a): def inner(b): return a*b return inner d=outer(9) print(d(3)) #ax^2+bx+c def outer(x): def inner(a,b,c): return a*x**2+b*x+c return inner p=outer(3) print(p(2,-3,6))
import requests from bs4 import BeautifulSoup page = requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html") ''' Sends a GET request. ''' #print(page) #print(page.status_code) #print(page.content) '''content Content of the response, in bytes. ''' soup = BeautifulSoup(page.content, 'html.parser') #print(soup.prittify) ''' The prettify() method will turn a Beautiful Soup parse tree into a nicely formatted Unicode string, with a separate line for each HTML/XML tag and string ''' #print(list(soup.children)) ''' The BeautifulSoup object itself has children. In this case, the <html> tag is the child of the BeautifulSoup object.: len(soup.contents) # 1 soup.contents[0].name # u'html' ''' html = list(soup.children)[2] #print(list(html.children)) body = list(html.children)[3] #print(list(body.children)) p = list(body.children)[1] #print(p.get_text()) ''' If you only want the text part of a document or tag, you can use the get_text() method. It returns all the text in a document or beneath a tag, as a single Unicode string ''' #Finding all instances of a tag at once #print(soup.find_all('p')) ''' it will find all 'p' tags ''' #print(soup.find_all('p')[0].get_text()) #Searching for tags by class and id page = requests.get("http://dataquestio.github.io/web-scraping-pages/ids_and_classes.html") soup1 = BeautifulSoup(page.content, 'html.parser') #print(soup1.find_all('p', class_='outer-text')) #print(soup1.find_all(id="first")) #print(soup.select("div p")) #Downloading weather data page = requests.get("http://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168") soup = BeautifulSoup(page.content, 'html.parser') seven_day = soup.find(id="seven-day-forecast") ''' ''' forecast_items = seven_day.find_all(class_="tombstone-container") tonight = forecast_items[0] #print(tonight.prettify()) period = tonight.find(class_="period-name").get_text() short_desc = tonight.find(class_="short-desc").get_text() temp = tonight.find(class_="temp").get_text() #print(period) #print(short_desc) #print(temp) img = tonight.find("img") desc = img['title'] #print(desc) period_tags = seven_day.select(".tombstone-container .period-name") periods = [pt.get_text() for pt in period_tags] #print(periods) '''BeautifulSoup has a .select() method which uses SoupSieve to run a CSS selector against a parsed document and return all the matching elements. Tag has a similar method which runs a CSS selector against the contents of a single tag. (Earlier versions of Beautiful Soup also have the .select() method, but only the most commonly-used CSS selectors are supported.) ''' short_descs = [sd.get_text() for sd in seven_day.select(".tombstone-container .short-desc")] temps = [t.get_text() for t in seven_day.select(".tombstone-container .temp")] descs = [d["title"] for d in seven_day.select(".tombstone-container img")] print('short_descs ',short_descs) #print(temps) #print(descs) import pandas as pd weather = pd.DataFrame({ "period": periods, "short_desc": short_descs, "temp": temps, "desc":descs }) print(weather) temp_nums = weather["temp"].str.extract("(?P<temp_num>\d+)", expand=False) weather["temp_num"] = temp_nums.astype('int') #print(temp_nums) #print(weather["temp_num"].mean()) is_night = weather["temp"].str.contains("Low") weather["is_night"] = is_night #print(is_night) #print(weather[is_night])
p=[[]]*3 print(p) p[0].append(5) print(p) q=[[] for i in range(3)] print(q) q[0].append(9) print(q)
#Project Euler Problem 27 biggest = 0 product = 0 hold = [] primes1 = [] primes2 = [] def f(n, a, b): return n*n + a*n + b def isPrime(n): mid = n+1 // 2 if n < 0: return False else: for i in range(2, mid): if n % i == 0: return False return True for i in range(1001): if isPrime(i): primes1.append(i) primes1.append(-i) primes2.append(i) primes2.append(-i) for i in primes1: for j in primes2: n = 0 product = i*j while isPrime(f(n, i, j)): hold.append(f(n, i, j)) n+=1 if len(hold) > biggest: biggest = len(hold) print(product) hold = []
#ac 辗转相除法 a,b的最大公约数 == a-b,b的最大公约数 def common(a,b): if a % b == 0: return b elif b == 1: return 1 else: return common(b,a%b) while True: try: line = input() except EOFError: break line = line.strip().split() x = int(line[0]) y = int(line[1]) if x > y: a = x b = y else: a = y b = x print(common(a,b))
movies =["Holy Grail", "life of brian", "The meaning of life"] count=0 while count < len(movies): print(movies[count]) count=count+1 #this is my first python program import sys print(sys.platform) x=2**10 print x z='SEro' print(z*20) #a=input() #a= input() #b=raw_input()
#Program to print out the grade marks = int(input("ENter Student Marks\n")) if marks>=100 or marks<0: print("Invalid mark, Marks should be between 0-100") else: if marks >=80: print("D1") elif marks >=75: print("D2") elif marks >=65: print("C3") elif marks >=60: print("C4") elif marks >=55: print("c5") elif marks >=50: print("C6") elif marks >=45: print("P7") elif marks >=40: print("P8") else: print("F9")
# Authors: Samwel, Josephine, Modester # GitHub handles: @Sammyiel, @Josephine-uwizeye, @Modester-mw # Question: Implement a basic measure of tracking the time taken to run an algorithm. # Importing modules import time # Identify the starting time start = time.time() # The actual program x = 0 while x < 5000: x += 1 print(x) # Identify the stop time stop = time.time() # Find the difference as the time taken and print print("Runtime: ", (stop - start), "seconds")
''' Ejercicio 2 Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas. ''' def run(): contraseña_guardada = 'nunca pares de aprender' contraseña = input('cual es su contraseña: ') if contraseña == contraseña_guardada: print('la contradeña es correcta.') else: print('la contraseña es incorrecta') if __name__ == '__main__': run()
''' Ejercicio 8 Escribir un programa que lea un entero positivo, n, introducido por el usuario y después muestre en pantalla la suma de todos los enteros desde 1 hasta n. La suma de los n primeros enteros positivos puede ser calculada de la siguiente forma: ''' def suma_de_numero(numero): suma_total = 0 for i in range(numero): suma_total += i+1 return(suma_total) def run(): numero = int(input('digite un numero: ')) if numero > 0: resultado = int(suma_de_numero(numero)) suma = (resultado * (resultado + 1))/2 print(f'el resultado de la operacion es: {suma}') else: print(f'el numero {numero} que digito no es positivo') if __name__ == "__main__": run()
''' Ejercicio 2 Escribir un programa que pregunte al usuario su edad y muestre por pantalla todos los años que ha cumplido (desde 1 hasta su edad). ''' def run(): edad = int(input('digite su edad: ')) print('usted a cumplido todas estas edades') for i in range(0,edad - 1): print(i + 1) if __name__ == '__main__': run()
''' Ejercicio 7 Escribir un programa que muestre por pantalla la tabla de multiplicar del 1 al 10. ''' def tabla(numero): print(f'tabla de multiplicar de el numero {numero}) for i in range(1,10): print(i * numero '\n') def run(): for i in range(1,10): tabla(i) print() if __name__ == '__ main__': run()
'''Ejercicio 4. Escribir un programa que pregunte una fecha en formato dd/mm/aaaa y muestre por pantalla la misma fecha en formato dd de <mes> de aaaa donde <mes> es el nombre del mes.''' def run(): meses = {1:'enero', 2:'febrero', 3:'marzo', 4:'abril', 5:'mayo', 6:'junio', 7:'julio', 8:'agosto', 9:'septiembre', 10:'octubre', 11:'noviembre', 12:'diciembre'} try: fecha_input = input('Introduce una fecha en formato dd/mm/aaaa: ') fecha = fecha_input.split('/') for value in range(len(fecha)): fecha[value] = int(fecha[value]) error = None if fecha[0] < 1 or fecha[0] > 31: print(f'el dia {fecha[0]} no existe') error = True if not fecha[1] in meses: print(f'el mes {fecha[1]} no existe') error = True if not error is True: print(f'{fecha[0]} de {meses[fecha[1]]} del año {fecha[2]}') except: print('Lo siento hubo un error con los datos que me indicas') if __name__ == '__main__': run()
''' Ejercicio 10 La pizzería Bella Napoli ofrece pizzas vegetarianas y no vegetarianas a sus clientes. Los ingredientes para cada tipo de pizza aparecen a continuación. Ingredientes vegetarianos: Pimiento y tofu. Ingredientes no vegetarianos: Peperoni, Jamón y Salmón. Escribir un programa que pregunte al usuario si quiere una pizza vegetariana o no, y en función de su respuesta le muestre un menú con los ingredientes disponibles para que elija. Solo se puede eligir un ingrediente además de la mozzarella y el tomate que están en todas la pizzas. Al final se debe mostrar por pantalla si la pizza elegida es vegetariana o no y todos los ingredientes que lleva. ''' def carnivora(): print('I N G R E D I E N T E S\n C A R N I V O R O S') print('1. Peperoni \n 2. Salmón. \n 3. Jamón. \n') eleccion = int(input('seleccione que llevara su pizza: ')) if eleccion == 1: return('Peperoni') elif eleccion == 2: return('Salmón') elif eleccion == 3: return('Jamón') else: return(break) def vegetariana(): print('I N G R E D I E N T E S\n V E T A R I A N O S') print('1. Pimiento \n 2. Tofu. \n') eleccion = int(input('seleccione que llevara su pizza: ')) if eleccion == 1: return('Pimiento') elif eleccion == 2: return('Tofu') else: return(break) def run(): usuario = input('quiere una pizza vegetariana s/n: ') if usuario == 'n': ingrediente = carnivora() print(f'la pizza no es vegetariana. y los ingredientes son: mozzarella, tomate y {ingrediente}') elif usuario == 's': ingrediente = vegetariana() print(f'la pizza es vegetariana. y los ingredientes son: mozzarella, tomate y {ingrediente}') else: print('Error no digito correctamente.') if __name__ == '__main__': run()
''' Ejercicio 8 En una determinada empresa, sus empleados son evaluados al final de cada año. Los puntos que pueden obtener en la evaluación comienzan en 0.0 y pueden ir aumentando, traduciéndose en mejores beneficios. Los puntos que pueden conseguir los empleados pueden ser 0.0, 0.4, 0.6 o más, pero no valores intermedios entre las cifras mencionadas. A continuación se muestra una tabla con los niveles correspondientes a cada puntuación. La cantidad de dinero conseguida en cada nivel es de 2.400€ multiplicada por la puntuación del nivel. Nivel Puntuación Inaceptable 0.0 Aceptable 0.4 Meritorio 0.6 o más Escribir un programa que lea la puntuación del usuario e indique su nivel de rendimiento, así como la cantidad de dinero que recibirá el usuario. ''' def salario(puntuacion): aumento = 0 if puntuacion == 1: print('el puntaje de la evaluación es Inaceptable.') elif puntuacion == 2: print('el puntaje de la evaluación es Aceptable.') aumento = 2400 * 0.4 elif puntuacion == 3: print('el puntaje de la evaluación es Meritorio.') aumento = 2400 * 0.6 else: print('el numero que que digito es incorrecto.') return(2400 + aumento) def run(): print('nivel de puntuacion \n') print(' 1. 0.0\n 2. 0.4\n 3. 0.6\n') puntuacion = int(input('cula es el puntaje obtenido del empleado: ')) print('su salario actual es de 2400$') dinero = salario(puntuacion) print(f'conforme a la evaluacion, su salario es de {dinero}$') if __name__ == '__main__': run()
nos = [4, 5, 10, 3, 5, 10, 1, 6, 8] # get a new list of only the pointers greater than 5 from the nos list (filtering) '''def greater_than_5(element): return element > 5 iterable = filter(greater_than_5, nos) print(list(iterable))''' iterable = filter(lambda element: element > 5, nos) print(list(iterable)) # get a new list of only the even pointers greater than 3 from nos list(filtering) '''def even_pointers(element): return not element % 2 and element > 3 evens_iterable = filter(even_pointers, nos) print(list(evens_iterable))''' evens_iterable = filter(lambda element: not element % 2 and element > 3, nos) print(list(evens_iterable)) # get a new list of squares of even pointers and cubes of odd pointers from the nos list (mapping) '''def map_even_odd(element): return element ** 3 if element % 2 else element ** 2 even_odd_iterable = map(map_even_odd, nos) print(list(even_odd_iterable))''' even_odd_iterable = map(lambda element: element ** 3 if element % 2 else element ** 2, nos) print(list(even_odd_iterable)) '''def map(func, iterable): l = [] for item in iterable: l.append(func(item)) return l''' '''def filter(func, iterable): filtered_list = [] for item in iterable: if func(item): filtered_list.append(item) return filtered_list'''
''' >= 70 - A >= 60 - B >= 40 - C < 40 - F > 100 or < 0 - I ''' marks = float(input('Enter marks : ')) # module (entire file) - Access the variable (get the value) def get_grade(): # if-elif-elif-elif-else # marks = 90 # get_grade() '''global marks marks = 90 # module (entire file)''' if marks > 100 or marks < 0: # condition can be python truthy and falsy grade = 'I' # enclosing function elif marks >= 70: # condition can be python truthy and falsy grade = 'A' # enclosing function elif marks >= 60: grade = 'B' # enclosing function elif marks >= 40: grade = 'C' # enclosing function else: grade = 'F' # enclosing function return grade print(get_grade()) # no switch statement (cases)
# enforce protocol on its sub classes # 1. It should mark itself as an Abstract class # 2. Along with that, mark the methods that need to be followed as part of the protocol, as abstract methods from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass
class Book: def __init__(self, title, price, pages): self.title = title # self.__price = price # private attribute (two underscores prefixed) self.set_price(price) self.pages = pages # @pages.setter def __str__(self): return 'Title: {0}\nPrice: {1}\nPages: {2}'.format(self.title, self.__price, self.pages) # @property # public mutator function for private attribute price # Encapsulation def set_price(self, price): if price < 0: raise ValueError('Price cannot be negative') # if all is fine self.__price = price # public accessor function for private attribute price def get_price(self): return self.__price # pages now becomes an object property (property is different from an object attribute) @property def pages(self): # emaulate the getter kind of function return self.__pages @pages.setter def pages(self, pages): # emulate the setter kind of functions if pages < 10: raise ValueError('Pages should be more than 10') self.__pages = pages
import cv2 import argparse #This file contains the code to detect faces in an image using OpenCV. #Before we get started, we need to know which file we are looking at. parser = argparse.ArgumentParser(description='Detects faces in an image and reports how many were found.') parser.add_argument('filename', metavar='fn', type=str, nargs=1, help='The file with faces to be detected.') args = parser.parse_args() print('Looking for faces in the file ', args.filename, '\n') #The classification code is here. #First, read the image and convert to grayscale. test1 = cv2.imread(args.filename[0]) test_gray = cv2.cvtColor(test1, cv2.COLOR_BGR2GRAY) #Then, use the haar cascade classification built-in to OpenCV to detect faces haar_human = cv2.CascadeClassifier('/home/pi/opencv-3.0.0/data/haarcascades/haarcascade_frontalface_alt.xml') humanfaces = haar_human.detectMultiScale(test_gray, 1.1, 5) print('human faces: ', len(humanfaces)) for (x, y, w, h) in humanfaces: cv2.rectangle(test1, (x,y), (x+w, y+h), (0, 255, 0), 2) cv2.imwrite("faces_highlighted.jpg", test1)
"""Builds an image classifier for fashion MNIST dataset using a simple sequential network Model (sequential): - flatten (28 x 28 -> 784) - dense (784 -> 300, relu) - dense (300 -> 100, relu) - dense (100 -> 10, softmax) """ from tensorflow import keras if __name__ == "__main__": fashion_mnist = keras.datasets.fashion_mnist (X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data() X_valid, X_train = X_train_full[:5000] / 255.0, X_train_full[5000:] / 255.0 y_valid, y_train = y_train_full[:5000], y_train_full[5000:] class_names = [ "top", "trouser", "pullover", "dress", "coat", "sandal", "shirt", "sneaker", "bag", "ankle-boot", ] model = keras.models.Sequential( [ keras.layers.Flatten(input_shape=[28, 28]), keras.layers.Dense(300, activation="relu"), keras.layers.Dense(100, activation="relu"), keras.layers.Dense(10, activation="softmax"), ] ) model.compile( loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"], ) history = model.fit(X_train, y_train, epochs=30, validation_data=(X_valid, y_valid)) model.evaluate(X_test, y_test)
# 1. TAREA: imprimir "Hola mundo" print( "Hola mundo" ) # 2. imprimir "Hola Noelle!" con el nombre en una variable name = "Noelle" print( "Hola", name ) # con una coma print( "Hola "+ name ) # con un + # 3. imprimir "Hola 42!" con un numero en una variable name = 42 print( "Hola",name ) # con una coma print( "Hola "+str(name) ) # con un + - !Este debería darnos un error! # 4. imprimir "Me encanta comer sushi and pizza." con los alimentos en variables fave_food1 = "sushi" fave_food2 = "pizza" print("Me encanta comer {} y {}".format(fave_food1,fave_food2) ) # con .format() print( f"Me encanta comer {fave_food1} y {fave_food2}" ) # con una cadena f #2a mi_nombre="Patricio" print ("Hola",mi_nombre) #2b print ("Hola "+mi_nombre) #3a num=4 print ("Hola",num) #3b print ("Hola "+ str(num)) #4a food_one="Carbonada" food_two="Charquican" print ("Me encanta comer {} y {}".format(food_one,food_two)) #4b print (f"Me encanta comer {food_one} y {food_two}")
from datetime import datetime import random class Caixa: def __init__(self, nome, conta, saldo=0): self.nome = nome self.conta = conta self.saldo = saldo self.operacao = [] def saque(self, valor): if valor <= self.saldo: self.saldo -= valor data = datetime.now() self.operacao.append(["SAQUE: ", valor, data.ctime()]) print(f'Saque de {valor} realizado com sucesso.') else: print('Saldo insulficiente.') def deposito(self, valor): self.saldo += valor data = datetime.now() self.operacao.append(["DEPÓSITO: ", valor, data.ctime()]) print(f'Depósito de {valor} realizado com sucesso.') def extrato(self): print(f'CC N° {self.conta} {self.nome.title()}') for i in self.operacao: print(i[0], i[1], '.....Data: ', i[2]) print(f'\nSaldo total: {self.saldo}') def escolha(self, acao): if acao == 'saque': entrada = float(input('Qual o valor: ')) x.saque(entrada) elif acao == 'deposito': entrada = float(input('Qual o valor: ')) x.deposito(entrada) elif acao == 'extrato': x.extrato() def nucleo(self): while True: print('>>>SAQUE\n>>>DEPOSITO\n>>>EXTRATO') operacao = str(input('Digite o operação: ')).lower().strip() if operacao == 'sair': break else: x.escolha(operacao) print('>>>ENTRAR\n>>>CRIAR CONTA') inicio = str(input('Digite uma opção: ')) if inicio == 'entrar': conta_numero = int(input('Digite o número da conta: ')) nome = str(input('Digite seu nome: ')) print(f'Seja bem vindo de volta {nome.title()}!') x = Caixa(nome, conta_numero) x.nucleo() else: if inicio == 'criar conta': criar_conta = str(input('Qual o seu nome: ')) criar_numero = random.randint(1, 9999) x = Caixa(criar_conta, criar_numero) print(f'CC Criada com sucesso!\n{criar_conta.title()} N° {criar_numero}') x.nucleo() print('Até a proxima!')
a=float(input("First number:")) b=float(input("Second number:")) operation=(input("Your operatoin:")) result= None if operation == "+": result=a+b elif operation == "-": result = a-b elif operation=="*": result = a*b elif operation=="/": if b == 0: print("you can't do it") else: result= a/b else: print("Unsupported operation") if result is not None : print("Your result",result)
def menu(): while True: print("**Carnet de contact v1**") print("Que souhaiter vous faire ? ") print("A - rechercher") print("B - ajouter") print("C - supprimer") print("D - Quitter") choix = input("Lettre: ").upper() if (choix == "A"): rechercher() elif (choix == "B"): getuserinfo() if(choix == "C"): supprimer() if (choix== "D"): print("/--- Merci de votre visite à bientot ! ---\ ") break def rechercher(): mots = input("/--- Saisissez le nom de votre contact (Bonus : Taper 'tous' pour voir l'ensemble de vos contact) ---\ :") file = open("agenda.csv", "r") res = 0 for line in file : tab = line.split(";") if (mots in tab[0] or mots in tab[1] or mots in tab[2] or mots in tab[3]) : print("Votre contact :", tab[0] ,tab[1], tab[2], tab[3]) res = 1 if (mots == "tous"): print("Vos contact :" ,tab[0]) res = 1 if (res == 0): print("#------ Ce contact n'est pas dans la liste ------#") getuserinfo() def supprimer(): chaine = input("/--- Nom du contact que vous souhaiter supprimer ---\ : ") contenu = "" fichier = open("agenda.csv","r") for ligne in fichier: if not(chaine in ligne): contenu += ligne fichier = open("agenda.csv","w") fichier.write(contenu) print("#------ Votre contact ayant pour nom : " + str(chaine)+ " à été supprimer ! ------# ") def addfile(nom ,prenom,numero,adresse): file = open("agenda.csv","a") file.write("{};{};{};\n".format(nom,prenom,numero,adresse)) file.close() def getuserinfo(): addnew = input("/--- Voulez vous ajouter un nouveau contact ? (oui/non) ---\ :") if (addnew=="non"): menu() elif (addnew=="oui"): nom= input("\nNom:") prenom = input("\nPrénom:") numero= int(input("\nNuméro:")) adresse = input("\nEmail:") addfile(nom, prenom, numero,adresse) else: print("#------ Erreur : Veuillez choisir entre 'oui' ou 'non' ------# ") getuserinfo() menu()
#******************************************************************* # # Program: Project 3 -- 4x4 Tic-Tac-Toe # # Author: Caleb Myers # Email: [email protected] # # Class: CS 3560 (Chelberg) # # Description: This is the Player class file for prog3. # # Date: February 26, 2017 # #******************************************************************* class Player: #******************************************************************* # # Function: __init__ # # Purpose: this is the Player class constructor # # Parameters: name - player name # games_won - games won by player # games_tied - games tied by player # # Member/Global Variables: none # # Pre Conditions: a Player object is assinged # # Post Conditions: a Player object is returned # # Calls: none # #******************************************************************* def __init__(self, name, games_won = 0, games_tied = 0): self.name = name self.games_won = games_won self.games_tied = games_tied class Player1(Player): marker = 'X' class Player2(Player): marker = 'O'
# -*- coding: utf-8 -*- """ Created on Mon May 3 12:32:57 2021 @author: anjal """ import datetime import sqlite3 example_db = '/var/jail/home/team13/final_project/scores.db' def request_handler(request): if (request['method'] == 'POST'): # this is a post request if('user' in request['form']): user = str(request['form']['user']) if('score' in request['form']): score = int(request['form']['score']) conn = sqlite3.connect(example_db) # connect to that database (will create if it doesn't already exist) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS scores (user text, score int, timing timestamp );''') # run a CREATE TABLE command c.execute('''INSERT into scores VALUES (?,?,?);''', (user,score,datetime.datetime.now())) conn.commit() conn.close() return "POST SCORE: Success" else: # this is a get request if 'user' in request['values']: user = request['values']['user'] conn = sqlite3.connect(example_db) # connect to that database (will create if it doesn't already exist) c = conn.cursor() score_for_user = c.execute('''SELECT score FROM scores WHERE user = ? ORDER BY score DESC;''',(user,)).fetchall()[0][0] conn.commit() conn.close() return "GET SCORE: " + str(score_for_user) else: conn = sqlite3.connect(example_db) # connect to that database (will create if it doesn't already exist) c = conn.cursor() scores_for_user = c.execute('''SELECT * FROM scores ORDER BY score DESC;''').fetchall() conn.commit() conn.close() output = "" for score in scores_for_user: output += score[0] + "-" + str(score[1]) + "," return "GET LEADERBOARD: " + output
''' Address class ''' class Address(): ''' Address class ''' def __init__(self, street='UNDEFINED', city='UNDEFINED', state='UNDEFINED', zipcode='UNDEFINED'): self.street = street self.city = city self.state = state self.zipcode = zipcode def get(self): ''' returns address ''' return { 'street': self.street, 'city': self.city, 'state': self.state, 'zipcode': self.zipcode }
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: ''' Solution bitch ''' def mergeTwoLists(self, l1: ListNode, l2: ListNode): l1_ptr = l1 l2_ptr = l2 merge_list = ListNode() merge_ptr = merge_list # set first value, then always update next if l1_ptr.val <= l2_ptr.val: merge_ptr.val = l1_ptr.val l1_ptr = l1_ptr.next else: merge_ptr.val = l2_ptr.val l2_ptr = l2_ptr.next while l1_ptr and l2_ptr: if l1_ptr.val <= l2_ptr.val: merge_ptr.next = ListNode(l1_ptr.val) l1_ptr = l1_ptr.next else: merge_ptr.next = ListNode(l2_ptr.val) l2_ptr = l2_ptr.next merge_ptr = merge_ptr.next while l1_ptr: merge_ptr.next = ListNode(l1_ptr.val) l1_ptr = l1_ptr.next merge_ptr = merge_ptr.next while l2_ptr: merge_ptr.next = ListNode(l2_ptr.val) l2_ptr = l2_ptr.next merge_ptr = merge_ptr.next return merge_list def print_list(self, l): ''' Prints a list ''' p = l while p: print(p.val, end='') if p.next: print('->', end='') p = p.next print("") l1 = ListNode(1, ListNode(2, ListNode(4, ListNode(5, ListNode(7))))) l2 = ListNode(1, ListNode(3, ListNode(4, ListNode(6)))) Solution().print_list(l1) Solution().print_list(l2) Solution().print_list(Solution().mergeTwoLists(l1, l2)) # l1 = ListNode(0, ListNode(1, ListNode(2))) # l2 = ListNode(5) # print(f'l2={l1}, l2.val={l2.val}, l2.next={l2.next}') # print("-----------------------------") # p = l2 # p.next = ListNode(6) # print(f'p={p}, p.val={p.val}, p.next={p.next}') # print(f'l2={l2}, l2.val={l2.val}, l2.next={l2.next}') # print("-----------------------------") # p = p.next # print(f'l2={l2}, l2.val={l2.val}, l2.next={l2.next}') # p.next = ListNode(7) # print(f'l2={l2}, l2.val={l2.val}, l2.next={l2.next}') # # print(f'l1={l1}, l1.val={l1.val}, l1.next={l1.next}') # # l1 = l1.next # # print(f'l1={l1}, l1.val={l1.val}, l1.next={l1.next}') # # l1 = l1.next # # print(f'l1={l1}, l1.val={l1.val}, l1.next={l1.next}') # # l1 = l1.next # # print(f'l1={l1}, l1.val={l1.val}, l1.next={l1.next}') # # print("============================") # # while l1: # # print(f'val={l1.val}') # # l1 = l1.next # print("============================") # while l2: # print(f'val={l2.val}') # l2 = l2.next # print("============================") # while p: # print(f'val={p.val}') # p = p.next # print("============================") # # OUTPUT # # ============================ # # 5 # # 6 # # 7 # # ============================ # # 5 # # 6 # # ============================ # # l2 = ListNode() # # test = Solution().mergeTwoLists(l1, l2) # # print(f'{test}')
from .Utility import guess_types def outlier_count(data, numericals=None, threshold_sigma=2): """ Prints a dictionary which gives a report on outliers per numerical column in format (no:outliers, % outliers) Outliers are defined as the values that fall outside the range of |X-mean|<= threshold*stdev If no numerical list is provided a guess is made Returns a dictionary in the format d[columns] = (number of outliers, percentage of outliers, index_of_outliers) """ if(numericals is None): numericals, s, c, d = guess_types(data) d = {} for i, col in enumerate(data[numericals]): l = [] m = data[col].mean() s = data[col].std() c = 0 for val in data[col]: if abs(m-val) > threshold_sigma*s: c+=1 l = l + [i] if(c != 0): d[col] = (c, c/len(data[col], l)) return d
import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.preprocessing import LabelEncoder def create_top_medalist(): ''' This function is used to create a dataframe of athletes that received medals for countries that received more than 90 medals. ''' df = pd.read_csv('athletes.csv') df.dropna(inplace=True) ''' Below will create a column that contains the total number of medals that athlete won. ''' df['medal_or_nm'] = df['gold'] + df['silver'] + df['bronze'] df = df[df.medal_or_nm >= 1] country_count = pd.DataFrame(df.groupby('nationality')['medal_or_nm'].agg('sum')) country_count.columns = ['country_count'] df = df.merge(country_count, on='nationality') df = df[df.country_count > 90] athlete_count = pd.DataFrame(df.groupby('sport')['name'].agg('count')) athlete_count.columns = ['athlete_count'] df = df.merge(athlete_count, on='sport') df = df[df.athlete_count > 30] ''' DOB to datetime. ''' df.dob = pd.to_datetime(df.dob) # df['sport_enc'] = df['sport'] # encoder = LabelEncoder() # encoder.fit(df.sport) # df.sport_enc = encoder.transform(df.sport) categorical_features = df.dtypes==object categorical_cols = df.columns[categorical_features].tolist() le = LabelEncoder() df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col)) ''' Create columm for approximate age. ''' df['age'] = 2016-df['dob'].dt.year return df
import numpy as np from polygon import Polygon # this function was given in the exercise def euclidean_distance(a, b): array_a = np.array(a) array_b = np.array(b) return np.linalg.norm(array_a - array_b) # Step 3 class Square(Polygon): def area(self): side = euclidean_distance(self.points[0], self.points[1]) return side**2
# 导包 import unittest import requests # 定义测试类 class TestLogin(unittest.TestCase): def setUp(self): # 创建Session对象 self.session = requests.Session() self.verify_url = "http://localhost/index.php?m=Home&c=User&a=verify" self.login_url = "http://localhost/index.php?m=Home&c=User&a=do_login" def tearDown(self): if self.session: self.session.close() # 定义测试方法 # 登录成功 def test_login_success(self): # 获取验证码 response = self.session.get(self.verify_url) # 断言 content_type = response.headers.get("Content-Type") print("content_type=", content_type) self.assertIn("image", content_type) # 登录 login_data = {"username": "13012345678", "password": "123456", "verify_code": "8888"} response = self.session.post(self.login_url, data=login_data) result = response.json() print("login response data=", result) # 断言 self.assertEqual(200, response.status_code) self.assertEqual(1, result.get("status")) self.assertIn("登陆成功", result.get("msg")) # 账号不存在 def test_login_username_is_not_exist(self): # 获取验证码 response = self.session.get(self.verify_url) # 断言 content_type = response.headers.get("Content-Type") print("content_type=", content_type) self.assertIn("image", content_type) # 登录 login_data = {"username": "13088888888", "password": "123456", "verify_code": "8888"} response = self.session.post(self.login_url, data=login_data) result = response.json() print("login response data=", result) # 断言 self.assertEqual(200, response.status_code) self.assertEqual(-1, result.get("status")) self.assertIn("账号不存在", result.get("msg")) # 密码错误 def test_login_pwd_is_error(self): # 获取验证码 response = self.session.get(self.verify_url) # 断言 content_type = response.headers.get("Content-Type") print("content_type=", content_type) self.assertIn("image", content_type) # 登录 login_data = {"username": "13012345678", "password": "error", "verify_code": "8888"} response = self.session.post(self.login_url, data=login_data) result = response.json() print("login response data=", result) # 断言 self.assertEqual(200, response.status_code) self.assertEqual(-2, result.get("status")) self.assertIn("密码错误", result.get("msg"))
"""Python Database API Django DB Models can be used to create schemas for database entities which will then be used to create the physical database. Models: ------- Survey: Survey entity encapsulates basic attributes of a survey including name(survey name) and published_on(date time when the survey is published. Methods: __str__: returns the survey name as metadata reference when objects are accessed. was_published_recently: returns True if the survey was published in the last 24h. The callback is also used by the admin for filtering surveys. Participant: This entity helps keep track of number of successful survey submits. This entity is used to identify the popular survey i.e., the survey with most submissions. The attributes include survey(foreign key referencing Survey) and participation_datetime. Methods: __str__: returns the Participant name as metadata reference when objects are accessed. Question: This entity encapsulates a question in the survey with survey(foreign key referencing Survey), question_text(actual question text) and created_on. Methods: __str__: returns the Question name as metadata reference when objects are accessed. Choice: This entity encapsulates a choice attribute in the survey with Question(foreign key referencing Question), choice_text(actual choice text), votes(to store poll results) and created_on. Methods: __str__: returns the Choice name as metadata reference when objects are accessed. """ from django.db import models from django.utils import timezone import datetime class Survey(models.Model): """Class to encapsulate Survey entity Attributes: name: character field with max_length=200 published_on: datetime field """ name = models.CharField(max_length=200) published_on = models.DateTimeField('Published DateTime') def __str__(self): return self.name def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.published_on <= now was_published_recently.admin_order_field = 'published_on' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Participant(models.Model): """Class to encapsulate Participant entity Attributes: survey: foreign key to Survey participation_datetime: datetime field """ survey = models.ForeignKey(Survey, on_delete=models.CASCADE) participation_datetime = models.DateTimeField('Participation DateTime') def __str__(self): return "Participant "+str(self.participation_datetime) class Question(models.Model): """Class to encapsulate Participant entity Attributes: survey: foreign key to Survey question_text: character field with max_length=200 created_on: datetime field """ survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) created_on = models.DateTimeField('Creation DateTime') def __str__(self): return self.question_text class Choice(models.Model): """Class to encapsulate Participant entity Attributes: survey: foreign key to Question choice_text: character field with max_length=200 created_on: datetime field votes: number with default 0 """ question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) created_on = models.DateTimeField('Creation DateTime') votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ :program name: fwlc :module author: Nicolas Osborne <[email protected]> :date: 2018, Mars :synopsis: REPL for Fun With Lambda Calculus """ import lib.lexpr import lib.lread from string import ascii_uppercase PROMPT = "<°λ°> " DIC = dict() def repl_loop(): """ REPL loop for fwlc. """ while True: command = input(PROMPT).split() # general commands if command[0] == ":q" or command == ":quit": print("Goodbye!") break elif (command[0] in (":h", ":help")) and len(command) == 1: printHelp() # TODO complete function printHelp elif command[0] == ':license': with open("LICENSE", "r") as stream : print(stream.read()) # expression manipulation elif command[0][0] != ":" and len(command) == 3 and command[1] == "=": try: assert set(command[0]).issubset(ascii_uppercase) DIC[command[0]] = lib.lread.read(command[2]) except AssertionError: print("This is not a valid identificator.") except: print("That does not seem to be a correct lambda expression.") elif set(command[0]).issubset(ascii_uppercase) and len(command) == 1: if command[0] in DIC.keys(): print(DIC[command[0]]) else: print("This identificator is not in used at the time being.") elif command[0][0] != ":" and len(command) == 1: try: print(lib.lread.read(command[0])) except: print("That does not seem to be a correct lambda expression.") elif command[0] == ":NOBeval": try: assert command[1] in DIC.keys() traces = DIC[command[1]].betaEvalWithTraces() for exp in traces: print(exp) except AssertionError: print("That is not a valid identificator.") elif command[0] == ":AOBeval": try: assert command[1] in DIC.keys() traces = DIC[command[1]].betaEvalWithTraces(applicative) for exp in traces: print(exp) except AssertionError: print("That is not a valid identificator.") elif command[0] == ":info": try: assert command[1] in DIC.keys() exp = DIC[command[1]] print(exp) if exp.isBetaNormal(): print("Lambda expression in its Beta normal form.") else: print("Lambda expression that can be beta evaluated.") FV = exp.freeVar() if FV == set(): print("This is a combinator.") else: print("This is the set of free variables:") print(FV) except AssertionError: print("This is not a valid identificator.") else: print("I do not understand what you are saying.") def greeting(): """ Print greeting message for repl loop of fwlc. """ print("Greeting.") print("Welcome in Fun With λ Calculus.") print() print("Type :h or :help for help.") print() def printHelp(): """ Print the help of the REPL for Fun With Lambda Calculus. """ print() print("\tDON'T PANIC!") print() print("\tList of commands:") print("\t-----------------") print("\t :h or :help :: print this help.") print("\t :q or :quit :: exit the RELP.") print("\t :NOBeval <Id> :: print all the steps of a Beta-evaluation\n\t\t\ in normal order of the lambda expression attached to the Id") print("\t :AOBeval <Id> :: print all the steps of a Beta-evaluation\n\t\t\ in applicative order of the lambda expression attached to the Id") print("\t :info <Id> :: print some info about the lambda expression\n\t\t\ attached to the <Id>.") print("\t <Id> = <Exp> :: assign the lambda expression <Exp> the the\n\t\t\ identificator <Id>. <Id> must be uppercase.") if __name__ == '__main__': greeting() repl_loop()
#https://leetcode.com/problems/1-bit-and-2-bit-characters/submissions/ class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ if 1 in bits: first_one_index = bits.index(1) del bits[:first_one_index] while(len(bits)>0): if len(bits)==2: if bits[0]==1: return False else: return True elif len(bits)==1: return True if bits[0]==1: bits.pop(0) bits.pop(0) # print(bits) else: bits.pop(0) # print(bits)
# 1 # numero= 1 # cantidad = 0 # suma= 0 # while numero != 0: # numero= int(input("ingrese un numero: ")) # if numero != 0: # suma= suma + numero # cantidad= cantidad + 1 # print(f"usted ingreso {cantidad} y la suma es:{suma} ") #2 # def menu (): # print ("bienvenido al mneú: 1. convertir de celcius a Fahrenheit, 2. converit de dolar a peso, 3. convertir de metros a pies, 4. salir") # menu () # n= int (input ("ingrese el numero de la opcion deseada:")) # while n < 4: # if n == 1 : # x= input ("ingrese el grado en celcius_: ") # print ((int (x) * 9/5) + 32) # menu () # n= int (input ("ingrese el numero de la opcion deseada:")) # elif n== 2: # y= input ("ingrese la cantidad en dolar: ") # print ((int (y) * 58.44)) # menu () # n= int (input ("ingrese el numero de la opcion deseada:")) # else: # n== 3 # z= int(input("ingrese la cantidad en metros: ")) # print ((int (z) * 3.281)) # menu () # n= int (input ("ingrese el numero de la opcion deseada:")) # print ("Gracias por utilizar mi programa") #3 # n = int (input("ingrese el numero deseado: ")) # e= 5 # while e <= 1000 : # print (n * e) # e += 5 # #4 # #calculadora de isr # top1 = 416220.00 # top2 = 624329.00 # top3 = 867123.00 # salario = float ( input ( "ingrese su sueldo mensual:" )) # salario_anual = salario * 12 # isr = 0 # if salario_anual <= top1 : # print( "Excenta" ) # elif salario_anual <= top2 : # excedente = salario_anual - top1 # isr = excedente * 0.15 # elif salario_anual <= top3 : # excedente = salario_anual - top2 # isr = 31216.00 + ( excedente * 0.20 ) # else: # excedente = salario_anual - top3 # isr = 79776.00 + excedente * 0.25 # print ( isr / 1250 ) # ars = salario * 0.0304 # afp= salario* 0.085 # print (f"Se descuenta a su salario mensual {salario}: un isr {isr/ 12},ars {ars}, afp {afp}") #5 carga1000 = 9000 carga500 = 9500 carga100 = 9900 def sacar_dinero(cantidad): global carga1000, carga500, carga100 if cantidad <= 1000: de1000 = int(cantidad / 1000) cantidad = cantidad % 1000 if de1000 >= carga1000: # Si hay suficientes billetes de 50 cantidad = cantidad + (de1000 - carga1000) * 1000 de1000 = carga1000 de500 = int(cantidad / 500) cantidad = cantidad % 500 if de500 >= carga500: # y hay suficientes billetes de 20 cantidad = cantidad + (de20 - carga20) * 20 de500 = carga500 de100 = int(cantidad / 100) cantidad = cantidad % 100 if de100 >= carga100: # y hay suficientes billetes de 10 cantidad = cantidad + (de100 - carga100) * 10 de10 = carga100 # Si todo ha ido bien, la cantidad que resta por entregar es nula: if cantidad == 0: # Así que hacemos efectiva la extracción carga1000 = carga1000 - de1000 carga500 = carga500- de500 carga100 = carga100 - de100 return [de1000, de500, de100] else: # Y si no, devolvemos la lista con tres ceros: return [0, 0, 0] else: return [-1, -1, -1] try: c = int(input('Cantidad a extraer: ')) resultado=sacar_dinero(c) if resultado==[0,0,0]: print ('No hay desglose de billetes para su importe') elif resultado==[-1,-1,-1]: print ('No hay suficientes billetes') else: print ('Billetes de 1000:', resultado[0]) print ('Billetes de 500:', resultado[1]) print ('Billetes de 100:', resultado[2]) except: print ('Importe incorrecto')
# title = 'Book entitled \"The cat in the boots\"' # number = 1 # print(f'Enter a number:{number}') # l = list((range(2,200,-7,)) # print(l) # x = input('Enter removable list item') # ex_1 = ['Cherry', 'Grass', 'Apartment', 'Dog', 'The_Chosen_One'] # if x in list(ex_1): # ex_1.remove(x) # print('Item has been removed from the list') # else: # print('The item you have chosen does not not appear on the list') # ex_2 = ('Dwarf', 'Fort') # print(type(ex_2)) x = 0 while x<10: print(f'Its not ready yet:{x}') x += 2
num = input('Enter your number') if int(num)== 0: print('You are not allowed to divide by 0') elif int(num)%3 == 0 or int(num)%5 == 0 or int(num)%7 == 0: print('Your number can be divided by 3,5 or 7') else: print("Your number can't be divided by 3, 5 or 7")
# class Animal(object): # def __init__(self, name, sex): # self.name = name # self.sex = sex # dog = Animal('Rex', 'male') # print(dog) # # # class Animal(object): # pass # # # class Human(Animal): # pass # # # class Student(Human): # pass class Book(object): def __init__(self, title, author, vat=0.07, sites=100, price=19.99): self.title = title self.sites = sites self.author = author self.price = price self.vat = 0.07 class Ebook(Book): def __init__(self, title, author, vat=0.15, sites=210, price=9.99): super().__init__(title, author, vat, sites, price) self.sites = sites self.price = 9.99 self.vat = 0.15 class Cart(object): def __init__(self, books=0, ebooks=0): self.books = books self.ebooks = ebooks def add_book(self, ebooks0, books0): self.books += books0 self.ebooks += ebooks0 print('Books added') print('You have: ' + str(self.books) + ' books') print('You have: ' + str(self.ebooks) + ' ebooks') def gross_price(self, books, ebooks): gross = books * Book.price() + ebooks * Ebook.price() return gross cart1 = Cart cart1.add_book(Cart, 12, 12)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 19 21:39:50 2018 @author: MariusD """ #%% available_products={"Guitar":"1000", "Pick box":"5", "Guitar Strings":"10"} def checkout(cart): cost=0 if cart==[]: return "Please select an item!" else: for product in cart: cost+=int(available_products[product]) return cost #%%
# Az alábbi mintát jelenítsd meg for ciklus segítségével! # Minta: # 5 4 3 2 1 # 4 3 2 1 # 3 2 1 # 2 1 # 1 list = [1, 2, 3, 4, 5] list_rev = list[::-1] for j in range(5): for i in list_rev[j:]: print(i, end='') print() # oszlop - ez nem megy # fx = [5, 4, 3, 2, 1] # y = [] # for j in range(5): # y.append(x[j:]) # print(y) # for idx, i in enumerate(y): # for k in range(len(i)): # print(y[idx][k], end=' ') # print() # ez megy # x = [5, 4, 3, 2, 1] # y = [] # for j in range(5): # y.append(x[j:]) # for i in y: # print(*i)
graph = {"S": ["A","D"], #Cola sale el primero que ingresamos #Cola: [ S ] → procesar nodo S y desencolarlo. #Cola: [ ] → nodo A desencolado. Visitar todos sus hijos y encolarlos "D": ["S","A","E"], #Cola: [ D ] → nodo D no es visitado. Lo agregamos a la cola. "A": ["S","D", "B"], #Cola: [ ] → nodo S y D no es visitado. Lo agregamos a la cola "E": ["D","B","F"], #Cola: [D] → nodo D no es visitado. Lo agregamos a la cola "B": ["C","E","A"], #Cola: [A,E] → nodo A , E no es visitado. Lo agregamos a la cola "F": ["G","E"], #Cola: [E] → nodo E no es visitado. Lo agregamos a la cola "C": ["B"], #Cola: [ ] → la cola esta vacía "G": ["F"] #Cola: [ ] → la cola esta vacía } # Se puede implementar utilizando una cola primero en entrar primero en salir (FIFO) def recursived_Deep_First_Search(graph, source,path = [] ): if source not in path: path.append(source) if source not in graph: # leaf node, backtrack return path for neighbour in graph[source]: path = recursived_Deep_First_Search(graph, neighbour, path) return path path = recursived_Deep_First_Search(graph, "S") dato1 = (" ".join(path)) print ("[" + str(dato1) + "]")
from room import Room from player import Player from item import Item import textwrap # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."""), } # Link rooms together room['outside'].doors['n'] = room['foyer'] room['foyer'].doors['s'] = room['outside'] room['foyer'].doors['n'] = room['overlook'] room['foyer'].doors['e'] = room['narrow'] room['overlook'].doors['s'] = room['foyer'] room['narrow'].doors['w'] = room['foyer'] room['narrow'].doors['n'] = room['treasure'] room['treasure'].doors['s'] = room['narrow'] # # Main # # Make a new player object that is currently in the 'outside' room. # Is # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. # Every option maps to a function that performs the aciton player1 = Player(name="John", room=room["outside"]) sword = Item("Sting", "Pointy") player1.room.add_item(sword) itemNameHolder = "" runProgram = True choices = [] def killProgram(): global runProgram runProgram = False print("Thanks for playing!") # , "n":travel("n"), "s":travel("s"), "e":travel("e"), "w":travel("w"), "q": killProgram(), "sword":player1.add_item(sword) def print_commands(): commands = ["\ni: inventory\nn: Go North\ns: Go South\ne: Go East\nw: Go West\nq: Quit Game\nlook: See Items Inside Room\ninteract: Interact\ntake [itemName]: Picks up and item\ndrop [itemName]: Drops the item in the room"] for key in commands: print(key) def travel(dir): try: if(player1.room.dir_exists(dir)): player1.room = player1.room.doors[dir] else: print("You can't go that way") except ValueError: print("Invalid Response") def look(): # Prints the current description (the textwrap module might be useful here). print("Room Description: ", textwrap.fill(player1.get_roomDesc())) player1.room.print_items() def interact(): input("Type `get [item]` or drop your item by typing `drop [item]`: \n") # , "drop":drop_item(itemNameHolder) # , "take":take_item(itemNameHolder) #commands={"i":player1.print_items(), "n":travel("n"), "s":travel("s"), "e":travel("e"), "w":travel("w"), "q": killProgram(), "sword":player1.add_item(sword) } def command(command): if command == "i": player1.print_items() elif command == "c": print_commands() elif command == "n": travel("n") elif command == "s": travel("s") elif command == "e": travel("e") elif command == "w": travel("w") elif command == "q": killProgram() elif command == "look": look() elif command == "interact": interact() # elif command =="l": # player1.room.print_items() elif command == "sword": player1.add_item(sword) def longCommand(command, itemName): if command == "take": rem_room_item = player1.room.remove_item(itemName) player1.add_item(rem_room_item) elif command == "drop": rem_player_item = player1.remove_item(itemName) player1.room.add_item(rem_player_item) print(f"you have dropped {itemName}") while runProgram: ''' REPL ''' # print current room name print(f"\n\033[1m{player1.get_room()}\033[0m") # Asks user input for which room to move to next stringIn = input( "\x1B[3mPlease enter a command. Press c for commands\x1B[23m\n") choices = stringIn.split(" ") if len(choices) == 1: command(stringIn) elif len(choices) == 2: longCommand(choices[0], choices[1]) else: print("You use many big words. Me no understand!")
dicts={'a':'apple','c':'cat','b':'ball'} val=lambda x:sorted(x)#sorting keys and then values ok=val(dicts) sortdict={} for j in ok: sortdict[j]=dicts[j] print(sortdict)
input2=int(input("Enter a length of list : ")) ls=[] for i in range(input2): ls.append(int(input())) def largest(val): res=val[0] for j in val: if(j>res): res=j return res print(largest(ls))