text
stringlengths
37
1.41M
class BucketList(object): # Defining static variables bucket_list = dict() goal_status = ['Active', 'Completed'] category_list = [ 'Nature', 'Health', 'Fashion', 'Food', 'Travel', 'Business', 'Education', 'Family', ] # Initializing class instance variables def __init__(self): self.title = None self.description = None self.category = None self.location = None self.date = None self.check_list = dict() self.status = 'Active' self.user_id = None # defining method to add bucket list def add_bucket_list(self, title, category, location, date, desc, user_id): msg = { 'error': "Fill all Fields" } if title is not None and title != '' and category is not None and category != '' and desc is not None: if desc != '' and location is not None and location != '' and date != '' and date is not None: self.title = title self.category = category self.location = location self.date = date self.description = desc self.user_id = user_id msg = self.save_data() return msg return msg # defining method to update bucket list def update_bucket_list(self, title, category, location, date, desc, user_id): msg = { 'error': "Fill all Fields" } if title is not None and title != '' and category is not None and category != '' and desc is not None: if desc != '' and location is not None and location != '' and date != '' and date is not None: self.title = title self.category = category self.location = location self.date = date self.description = desc self.user_id = user_id msg = self.update_bucket_data() return msg return msg # defining method to update bucket list def update_bucket_list_status(self, bucket_list, status): msg = { 'error': "Sorry, status could not be updated" } if bucket_list in self.bucket_list.keys(): if status in self.goal_status: # confirm all step status are correct if self.bucket_list[bucket_list]['check_list']: msg = { 'success': "Status updated successfully" } for item in self.bucket_list[bucket_list]['check_list']: if self.bucket_list[bucket_list]['check_list'][item]['status'] == 'Active': msg = { 'error': 'All steps are not completed' } if 'success' in msg.keys(): self.bucket_list[bucket_list]['status'] = status return msg # defining helper method to save bucket list data def save_data(self): msg = { 'error': "Category provided does not exist" } if self.category in self.category_list: if self.title not in self.bucket_list.keys(): self.bucket_list[self.title] = { 'title': self.title, 'description': self.description, 'category': self.category, 'check_list': None, 'status': 'Active', 'date': self.date, 'location': self.location, 'user_id': self.user_id, } msg = { 'success': "Bucket list added successfully" } else: msg = { 'error': "Title already taken" } return msg # defining method to update bucket list data def update_bucket_data(self): msg = { 'error': "Could not update bucketlist" } if self.category in self.category_list: # if self.title in self.bucket_list.keys(): self.bucket_list[self.title] = { 'title': self.title, 'description': self.description, 'category': self.category, 'check_list': None, 'status': 'Active', 'date': self.date, 'location': self.location, 'user_id': self.user_id, } msg = { 'success': "Bucket list updated successfully" } return msg # defining method to add item checklists to a bucket list def add_step(self, bucket_list, title): msg = { 'error': 'Step could not be added' } if title not in self.check_list.keys(): if bucket_list in self.bucket_list.keys(): self.check_list[title] = { 'title': title, 'status': self.status, 'bucket_list': bucket_list, } self.bucket_list[bucket_list]['check_list'] = self.check_list msg = { 'success': 'Step added successfully' } return msg # defining method to update bucket list checklist status def update_step_status(self, bucket_list, title, status): msg = { 'error': "Sorry, step could not be updated" } if bucket_list in self.bucket_list.keys(): if title in self.bucket_list[bucket_list]['check_list'].keys(): if status in self.goal_status: self.bucket_list[bucket_list]['check_list'][title]['status'] = status self.update_bucket_list_status(bucket_list, status) msg = { 'success': "Step status updated successfully" } return msg # defining method to delete bucket list checklist def del_step(self, bucket_list, title): msg = { 'error': "Sorry, step could not be deleted" } if bucket_list in self.bucket_list.keys(): if title in self.bucket_list[bucket_list]['check_list'].keys(): self.bucket_list[bucket_list]['check_list'].pop(title) msg = { 'success': "Step deleted successfully" } return msg # defining method to get all bucket lists def get_bucket_list(self): return self.bucket_list # defining method to get all bucket list checklists def get_checklist(self): return self.check_list # defining method to delete a specific bucket list def del_bucket_list(self, title): msg = { 'error': 'Bucketlist could not be deleted' } if title in self.bucket_list.keys(): self.bucket_list.pop(title) msg = { 'success': 'Bucketlist deleted successfully', } return msg
from Algorithm import Algorithm class Flowchart: def __init__(self): self.ListAlgorithms = [] def setAlghoritm(self, id, name): if (self.algExist(id)): print("An algorithm with ID = " + str(id) + " exists, id changed ID = " + str(id + 1) + ';') self.setAlghoritm(id + 1, name) else: algorithm = Algorithm(id, name) self.ListAlgorithms.append(algorithm) def addBlock(self, idAlg, idBlock, name, text, way): if (self.algExist(idAlg) == False): print("Algorithm not found") elif (self.blockExist(idAlg, idBlock)): print("ID = " + str(idBlock) + " for block busy, id changed ID = " + str(idBlock + 1)) self.addBlock(idAlg, idBlock + 1, name, text, way) else: self.ListAlgorithms[self.findAlgorithmByID(idAlg)].addBlock(idBlock, name, text, way) def findAlgorithmByID(self, id): for i in range(len(self.ListAlgorithms)): if (self.ListAlgorithms[i].id == id): return i return -1 def blockExist(self, algId, blockId): bE = False index = self.findAlgorithmByID(algId) if (index == -1): return False return (self.algExist(algId) and self.ListAlgorithms[index].blockExist(blockId)) def algExist(self, algId): for i in range(len(self.ListAlgorithms)): if (self.ListAlgorithms[i].id == algId): return True return False def getState(self, i, j): i = self.findAlgorithmByID(i) if (i == -1): print("Algorithm not found") return print(self.ListAlgorithms[i].getBlokToString(j)) if __name__ == "__main__": f = Flowchart() f.setAlghoritm(0, "tits") f.addBlock(0, 0, "one", "sosi", [1, 2]) f.addBlock(0, 1, "two", "sam sosi", [-1]) f.addBlock(0, 1, "3", "ok", [-1]) f.getState(11, 10)
#Ussless facts by PFK name = input("Привет, как тебя зовут?: ") age = int(input("\nСколько Вам лет?: ")) weight = int(input("\nСколько Вы весите?: ")) print("Если бы трамвайный хам писал Вам в чате, \ он бы обратился так: " , name.lower()) print("А после небольшого спора так: ", name.upper()) fiveTimes = name * 5 print("Если бы маленький ребёнок решил привлечь ваше внимание, \ он произнёс бы Ваше имя так: " + fiveTimes) age_seconds = age * 365 * 24 * 60 * 60 print("Возраст в секундах: ", age_seconds) moon_weight = weight / 6 sun_weight = weight * 27.1 print("\nЗнaeтe ли вы. что на Луне вы весили бы всего", moon_weight, "кг?") print( "\nА вот находясь на Солнце. вы бы весили", sun_weight, "кг. \ (Но. увы. это продолжалось бы недолго.)") input("\n\nНажми Enter, чтобы выйти")
#chapter 10 - simple GUI from tkinter import * #creation and starting window root_window = Tk() root_window.title("Окошко в кокошнике:)") root_window.geometry("444x333") #creationg frame and objects main_frame = Frame(root_window) main_frame.grid() #менеджер размещения, без него не выводится на экран btn1 = Button(main_frame, text="Кнопка1") btn1.grid() lb = Label(main_frame, text="Просто метка, ничего больше") lb.grid() btn2 = Button(main_frame) btn2.configure(text="AHAHAHAHAH!") btn2.grid() btn3 = Button(main_frame) btn3["text"] = "Я помню чудное...." btn3.grid() btn2.grid() #starting mainloop - execute window and do smthng root_window.mainloop()
#Dependencies import os import csv # Create the path name toa ccess the bank data in a csv file with open('PyBank_Resources_budget_data.csv', 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') for row in csvreader: row num = row_num +1 Date = [] Profit = [] row_num = 0 total month = row_num-1 print(f"Total_months: {total_month}") # txt file with open('main2.txt', 'w')as txt: txt.write("Financial Analysis"='\n') txt.write(f"Total months: {total_month}"+'\n') txt.write(f"Total: {total}"'\n') final
# -*- coding: utf-8 -*- """ K Nearest Neighbor Classification --------------------------------- This function is built especially for a learned metric parameterized by the matrix A where this function takes the matrix M such that A = M * M' """ # Author: John Collins <johnssocks@gmail.com> def knn(ytr, Xtr, M, k, Xte): """K Nearest Neighbors classifier y_hat = knn(y, X, M, k, Xt) Perform knn classification on each row of Xt using a learned metric M M is the factor matrix : A = M * M' Parameters ---------- ytr: vector of labels, string or int The known responses upon which to train our classifier Xtr: 2D n*p array of numbers The data matrix where rows are observations and columns are features M: The p*p factor matrix of the (assumedly) learned matrix A k: The number of nearest neighbors to use Xt: The new data from which to predict responses Attributes ---------- `centroids_` : array-like, shape = [n_classes, n_features] Centroid of each class Examples -------- >>> import numpy as np >>> X = np.array([[1,1], [7,7], [1,2], [7,8], [2,1], [8,7], [1,0], [8,9], [11, -4], [14, 1]]) >>> y = np.array([1, 2, 1, 2, 1, 2, 1, 2, 2, 2]) >>> M = np.eye(X.shape[1]) >>> k = 4 >>> Xtr, Xte = X[:8,:], X[8:,:] >>> ytr, yte = y[:8], y[8:] >>> print Xtr.shape >>> print Xte.shape >>> print 'Simple Test' >>> print '--------------' >>> print 'predictions' >>> print knn(ytr, Xtr, M, k, Xte) >>> print 'actual' >>> print yte >>> print '\n' [1] References ---------- Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of multiple cancer types by shrunken centroids of gene expression. Proceedings of the National Academy of Sciences of the United States of America, 99(10), 6567-6572. The National Academy of Sciences. """ import numpy as np add1 = 0 if min(ytr) == 0: ytr += 1 add1 = 1 (n, m) = Xtr.shape (nt, m) = Xte.shape K = np.dot(np.dot(Xtr, M), np.dot(M.T, Xte.T)) l = np.zeros((n)) for i in xrange(n): l[i] = np.dot(np.dot(Xtr[i, :], M), np.dot(M.T, Xtr[i, :].T)) lt = np.zeros((nt)) for i in xrange(nt): lt[i] = np.dot(np.dot(Xte[i, :], M), np.dot(M.T, Xte[i, :].T)) D = np.zeros((n, nt)); for i in xrange(n): for j in xrange(nt): D[i, j] = l[i] + lt[j] - 2 * K[i, j] inds = np.argsort(D, axis = 0) preds = np.zeros((nt), dtype = int) for i in xrange(nt): counts = [0 for ii in xrange(2)] for j in xrange(k): if ytr[inds[j, i]] > len(counts): counts.append(1) else: counts[ytr[inds[j, i]] - 1] += 1 v, preds[i] = (max(counts), int(np.argmax(counts) + 1)) if add1 == 1: preds -= 1 return preds if __name__ == "__main__": """ Simple Test """ import numpy as np X = np.array([[1,1], [7,7], [1,2], [7,8], [2,1], [8,7], [1,0], [8,9], [11, -4], [14, 1]]) y = np.array([1, 2, 1, 2, 1, 2, 1, 2, 2, 2]) M = np.eye(X.shape[1]) k = 4 Xtr, Xte = X[:8,:], X[8:,:] ytr, yte = y[:8], y[8:] #print Xtr.shape #print Xte.shape print 'Simple Test' print '--------------' print 'predictions' print knn(ytr, Xtr, M, k, Xte) print 'actual' print yte """ Elaborate Test """ import numpy as np import os X = np.genfromtxt(os.path.join('data', 'test_X.csv'), delimiter = ',', dtype = float) y = np.genfromtxt(os.path.join('data', 'test_y.csv'), delimiter = ',', dtype = int) M = np.eye(X.shape[1]) k = 1 inds = np.genfromtxt(os.path.join('data', 'test_inds.csv'), delimiter = ',', dtype = int) inds_tr = np.where(inds == 1)[0] inds_te = np.where(inds == 0)[0] Xtr = X[inds_tr, :] Xtr, Xte = X[inds_tr, :], X[inds_te, :] ytr, yte = y[inds_tr], y[inds_te] ypred = knn(ytr, Xtr, M, k, Xte) print 'Elaborate Test' print '--------------' print 'predictions' print ypred print 'actual' print yte matlab_accuracy = 0.958333 accuracy = float(sum(yte == ypred)) / len(yte) if np.abs(matlab_accuracy - accuracy) > 0.00001: print 'Problem' else: print 'Perfect'
""" Global and local variables: Variable n is defined as global """ n = 3 """ Function func1 uses global variable 'n' because there is no local variable 'n' """ def func1(): print("In function1 variable n is: ", n) #In function func2 variable 'n' is redefined as local variable def func2(): n = 20 n = n/10 print("In function2 variable n is: ",n) #In function func3 global keyword used to modify global variable 'n' def func3(): global n n = 50 print("In function3 variable n is: ",n) """Global scope of variable n""" print("global variable: ",n) func1() print("global variable: ",n) func2() print("global variable: ",n) func3() print("global variable: ",n) ''' OUTPUT: global variable: 3 In function1 variable n is: 3 global variable: 3 In function2 variable n is: 2.0 global variable: 3 In function3 variable n is: 50 global variable: 50 '''
""" Writing to a file Creating a new file and writing into it "x" - will create a file f = open("python.txt", "x") # a new empty file is created """ # "w" -write mode will create a file if it does not exist f = open("python.txt", "w") """After creating now writing to an existing file """ # "a" - will append to the end of the file f = open("pyhton.txt","a") f.write("Python 75 Challenge - Remote Hackathon - Pilot") f.write("Procedure:") f.write("1. Fork this code: https://github.com/teamtact/python-75-hackathon") f.write("2. Start coding and commit often") f.write("3. Update your github repository link in the challenge input") f.close() """ OUTPUT Document file : C:\Users\Meenu\AppData\Local\Programs\Python\Python36\py programs\py75\python.txt Python 75 Challenge - Remote Hackathon - Pilot Procedure: 1. Fork this code: https://github.com/teamtact/python-75-hackathon 2. Start coding and commit often 3. Update your github repository link in the challenge input """ # "w" method will overwrite the entire file f = open("python.txt","w") f.write("Woops! I have deleted the content!!!!!") f.close() ''' OUTPUT: C:\Users\Meenu\AppData\Local\Programs\Python\Python36\py programs\py75\python.txt Woops! I have deleted the content!!!!! '''
""" Classes and objects """ #to create class use keyword class class val: a = 10 #to create an object obj for class val and print value of a obj = val() print("Value of a is : ",obj.a) #Class student use __init__() function to assign values for name and regno #classes have init function which is executed when class is initiated class Student: def __init__(self,name,regno): self.name = name self.regno = regno obj1 = Student("Jenny", 59787) print("Student name : ",obj1.name) print("Student register number : ",obj1.regno) #self parameter-reference to class instance itself & used to access variables that belongs to the class #create a method myname in class that is accessed by the object class Student: def __init__(self,name,regno): self.name = name self.regno = regno def myname(self): print("Hello,this is",self.name,"and my regno is",self.regno) obj1 = Student("Jenny", 59787) obj1.myname() #Modify object #modify the regno of ob1 to 59866 obj1.regno = 59866 print("Modified object regno : ",obj1.regno) #Delete the name property from object del obj1.name #print(obj1.name) #AttributeError: 'Student' object has no attribute 'name' #to delete object del obj1 #print(obj1) #NameError: name 'obj1' is not defined ''' OUTPUT: Value of a is : 10 Student name : Jenny Student register number : 59787 Hello,this is Jenny and my regno is 59787 Modified object regno : 59866 '''
words = ["one", "two", "three"] for word in words: print word print word + " has " + str(len(word)) + " letters"
#To reverse a string def reversed_string(inputstring): return inputstring[::-1] output = reversed_string("hello") print output
#Length of last word inputstring = raw_input("Enter a string:") inputstring = inputstring.strip(" ") split = inputstring.split(" ") if len(split)==0: print 0 elif len(split)==1: print len(split[0]) else: print len(split[-1])
test_dict_1 = {'YEAR':'2010', 'MONTH':'1', 'DAY':'20'} print(test_dict_1) print('=================================') for key, value in test_dict_1.items(): print(key, value)
print("[0]*10:", ['']*10) aaa = list(range(5)) print(("aaa = range(5) :", aaa)) aaa = list(range(5)) print(("aaa = list(range(5)) :", aaa)) aaa.extend(list(range(5, 0, -1))) print(('aaa.extend(range(5, 0, -1))', aaa)) aaa.append(None) print(('aaa.append(6):%s'%aaa.append(6))) print(('aaa after append:%s'%aaa)) print(('aaa.pop(6) =%d'%aaa.pop(6))) print(('aaa :', aaa)) print(("aaa.index(1)", aaa.index(1))) print(('aaa.index(2, 5)', aaa.index(2, 5))) aaa = [3, 4, 2, 6, 8 ,7 , 1, 0] print(('aaa unsorted:%s' % aaa)) aaa.sort() print(('aaa after sort():%s' % aaa))
from __future__ import print_function import numpy as np import cv2 import matplotlib.pyplot as plt # Goal # To find the different features of contours, like area, perimeter, centroid, bounding box etc # You will see plenty of functions related to contours. # http://docs.opencv.org/master/dd/d49/tutorial_py_contour_features.html img = cv2.imread('data/j.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thr = cv2.threshold(gray, 127, 155, 0) img2, contours, hierarchy = cv2.findContours(thr, 1, 2) # for cnt in contours: # cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2) # cv2.imshow('img', img) # cv2.waitKey(0) # # cv2.waitKey(0) # cv2.destroyAllWindows() cnt = contours[0] # Moments # https://en.wikipedia.org/wiki/Image_moment M = cv2.moments(cnt) print(M) # Centroid cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) # Contour Area area = cv2.contourArea(cnt) print(area) # Contour Perimeter perimeter = cv2.arcLength(cnt, True) print(perimeter) # Contour Approximation # https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm epsilon = .05 * cv2.arcLength(contours[2], True) approx = cv2.approxPolyDP(contours[2], epsilon, True) # cv2.drawContours(img, [approx], 0, (255, 0, 0), 2) # cv2.imshow('img', img) # cv2.waitKey(0) # cv2.destroyAllWindows() print(approx) # Convex Hull hull = cv2.convexHull(contours[2]) # cv2.drawContours(img, [hull], 0, (0, 0, 255), 2) # cv2.imshow('img', img) # cv2.waitKey(0) # cv2.destroyAllWindows() print(hull) # Checking Convexity k = cv2.isContourConvex(cnt) print(k) # cnt = contours[2] # Straight Bounding Rectangle x,y,w,h = cv2.boundingRect(cnt) # cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) # cv2.imshow('img', img) # cv2.waitKey(0) # cv2.destroyAllWindows() # Rotated Rectangle rec = cv2.minAreaRect(cnt) box = cv2.boxPoints(rec) box = np.int0(box) # cv2.drawContours(img, [box], 0, (0, 0, 255), 2) # cv2.imshow('img', img) # cv2.waitKey(0) # cv2.destroyAllWindows() # Minimum Enclosing Circle (x, y), radius = cv2.minEnclosingCircle(cnt) center = (int(x), int(y)) radius = int(radius) # cv2.circle(img, center, radius, (0, 255, 0), 2) # cv2.imshow('img', img) # cv2.waitKey(0) # cv2.destroyAllWindows() # Fitting an Ellipse ellipse = cv2.fitEllipse(cnt) # cv2.ellipse(img, ellipse, (0, 0, 255), 2) # cv2.imshow('img', img) # cv2.waitKey(0) # cv2.destroyAllWindows() # Fitting a Line rows,cols = img.shape[:2] [vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01) lefty = int((-x*vy/vx) + y) righty = int(((cols-x)*vy/vx)+y) # cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2) # cv2.imshow('img', img) # cv2.waitKey(0) # cv2.destroyAllWindows() # Here we will learn to extract some frequently used properties of objects like Solidity, Equivalent Diameter, Mask image, Mean Intensity etc. More features can be found at Matlab regionprops documentation. # http://www.mathworks.com/help/images/ref/regionprops.html # http://docs.opencv.org/master/d1/d32/tutorial_py_contour_properties.html # Aspect Ratio x,y,w,h = cv2.boundingRect(cnt) aspect_ratio = float(w)/h print(aspect_ratio) # Extend = obj area / bounding rect area area = cv2.contourArea(cnt) x,y,w,h = cv2.boundingRect(cnt) bounding_area = w*h extend = float(area)/bounding_area print(extend) # Solidity = obj area / convex hull area area = cv2.contourArea(cnt) hull = cv2.convexHull(cnt) hull_area = cv2.contourArea(hull) solidity = float(area)/bounding_area print(solidity) # Equivalent Diameter is the diameter of the circle whose area is same as the contour area. area = cv2.contourArea(cnt) equi_diameter = np.sqrt(4*area/np.pi) print(equi_diameter) # Orientation is the angle at which object is directed. Following method also gives the Major Axis and Minor Axis lengths. (x,y),(MA, ma),angle = cv2.fitEllipse(cnt) # Mask and Pixel Points mask = np.zeros(gray.shape,np.uint8) cv2.drawContours(mask,[cnt],0,255,-1) pixelpoints = np.transpose(np.nonzero(mask)) # pixelpoints = cv2.findNonZero(mask) # Numpy gives coordinates in **(row, column)** format, while OpenCV gives coordinates in **(x,y)** format. print(pixelpoints) # Maximum Value, Minimum Value and their locations min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(gray, mask = mask) print(min_val, max_val, min_loc, max_loc) # Mean Color or Mean Intensity mean_val = cv2.mean(img, mask = mask) print(mean_val) # Extreme Points leftmost = tuple(cnt[cnt[:,:,0].argmin()][0]) rightmost = tuple(cnt[cnt[:,:,0].argmax()][0]) topmost = tuple(cnt[cnt[:,:,1].argmin()][0]) bottommost = tuple(cnt[cnt[:,:,1].argmax()][0]) print(leftmost, rightmost, topmost, bottommost) # Goal # Convexity defects and how to find them. # Finding shortest distance from a point to a polygon # Matching different shapes
# # Python Version: 3.5 # Creator - GGbits # Set: 2 # Challenge: 9 # https://cryptopals.com/sets/2/challenges/9 # # Description: # A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of plaintext into ciphertext. # But we almost never want to transform a single block; we encrypt irregularly-sized messages. # One way we account for irregularly-sized messages is by padding, # creating a plaintext that is an even multiple of the blocksize. The most popular padding scheme is called PKCS#7. # So: pad any block to a specific block length, by appending the number of bytes of padding to the end of the block. # For instance: # "YELLOW SUBMARINE" # ... padded to 20 bytes would be: # "YELLOW SUBMARINE\x04\x04\x04\x04" def pad_text(text, byte_length): if type(text) is str: binary_text = text.encode('UTF-8') else: binary_text = text trail = byte_length - len(binary_text) % byte_length if trail != byte_length: count = 0 while count < trail: binary_text += b'\x04' count += 1 return binary_text if __name__ == '__main__': bin_data = pad_text("YELLOW SUBMARINE", 20) print(bin_data)
s=input("enter string,") s1=input("enter string2") for i in range(0,len((s)): if s[i]==s1[i]: print(s[i])
#aleks calderon #4.23.2019 #list reversal - iterative wordList = ["Sunday", "Monday", "Tuesday"] reverseList = wordList[::-1] print(reverseList)
import random import paramiko def convert(currency1,currency2,amount): dollar = 1; euro = 0.91; shekel = 3.43 if currency1 == "1": currency1 = dollar elif currency1 == "2": currency1 = euro else: currency1 = shekel if currency2 == "1": currency2 = dollar elif currency2 == "2": currency2 = euro else: currency2 = shekel print("%.2f" % (amount/(currency1/currency2))) while(True): while(True): print("menu:\n1.convert Dollar/Euro/Shekel\n2.find your friend's id" "\n3.2 times in a row (game)\n4.paramiko") menu_input = input("choose 1-4 option:") if menu_input != "1" and menu_input != "2" and menu_input != "3" and menu_input != "4": print("please choose 1-4 option\n") else: break ##option 1 if menu_input == "1": while(True): currency = input("choose first:\n1.dollar\n2.euro\n3.shekel\n") if currency != "1" and currency != "2" and currency != "3": print("please choose 1-3 option\n") else: amount = int(input("enter the amount:\n")) break while(True): currency2 = input("choose second:\n1.dollar\n2.euro\n3.shekel\n") if currency2 != "1" and currency2 != "2" and currency2 != "3": print("please choose 1-3 option") else: break convert(currency,currency2,amount) ## option 2 elif menu_input == "2": dicts = {} flag = 0 file = open("file.txt", "w") #reset the txt file file.close() file = open("file.txt", "a") for i in range(2): name = input("enter your friend name:") dicts[name] = input("enter your friend id:") file.write(name + " " + dicts[name] + "\n") file.close() friend_id = (input("enter the id of the friend you want so search:")) file = open("file.txt", "r") for line in file: single_line = line.split() if friend_id == single_line[1]: print("your friend is in the list") flag = 1 break if flag == 0: print("your friend isn't on the list") ## option 3 elif menu_input == "3": x1=0 ; sum=0 ; x=0 for i in range(10): x1 = x x=random.randrange(1,6)#here i likened the range to a dice throw print(x) if x1 == x: sum += 10 print("you earnd :" + str(sum) + " dollars") ## option 4 elif menu_input == "4": ip = input("enter the ip of the remote machine:") client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(ip, username='matan', password='rootroot') #here you should change the username and the passward to your own client.exec_command("touch /home/matan/Desktop/done_paramiko.txt") #here you hould change the path as you wish client.close() exit = input("do you want to exit the program? press any key other then \"Y/y\" to exit") if exit != "y" or exit != "Y": break
import pandas as pd import numpy as np ########## Specify the name of excel with the data ########## fileData=pd.read_excel('Sample DataSet.xlsx') ########## Removes last 2 characters ########## for loop in range(0,fileData['Section'].count()): temp_String=str(fileData['Section'].iloc[loop]) temp_String=temp_String[:-2] fileData['Section'].iloc[loop]=temp_String ########## Add the extra Row here ######### title_list=[['Points Possible','','','10','10','10','10','10','10']] ########## Add the column headers here ########## title_DataFrame=pd.DataFrame(title_list, columns=['Student','Course','Section','Assignment 1 Marks', 'Assignment 2 Marks','Assignment 3 Marks','Assignment 4 Marks','Assignment 5 Marks','Total']) ########## Specify the name of the column based on which the split needs to be performed ########## for section in fileData['Section'].unique(): temp_DataFrame=(fileData[fileData['Section']==section]) ########## Columns Whose average you want to calculate ########## Sum1=np.sum(fileData.where(fileData['Section']==section)['Assignment 1 Marks']) Sum2=np.sum(fileData.where(fileData['Section']==section)['Assignment 2 Marks']) Sum3=np.sum(fileData.where(fileData['Section']==section)['Assignment 3 Marks']) Sum4=np.sum(fileData.where(fileData['Section']==section)['Assignment 4 Marks']) Sum5=np.sum(fileData.where(fileData['Section']==section)['Assignment 5 Marks']) Sum=np.sum(fileData.where(fileData['Section']==section)['Total']) Count=np.count_nonzero(temp_DataFrame.where(temp_DataFrame['Section']==section)['Total']) if Count==0: average=0 average1=0 average2=0 average3=0 average4=0 average5=0 else: average=Sum/Count average1=Sum1/Count average2=Sum2/Count average3=Sum3/Count average4=Sum4/Count average5=Sum5/Count ########## Specify the name of the column based on which the sort needs to be performed ########## result=temp_DataFrame.sort(['Total'], ascending=0) result=pd.concat([title_DataFrame,result]) df_length=len(result['Student']) ########## Add spaces for columns with average ########## result.loc[df_length]=['Average','','',average1,average2,average3,average4,average5,average] Filename=str(temp_DataFrame['Section'].iloc[0])+'.xlsx' writer = pd.ExcelWriter(Filename, engine='xlsxwriter') result.to_excel(writer,'Sheet1') writer.save() print('File '+Filename+' created succesfully')
class SquareTwo(): square_list = [] def __init__(self, s2): self.s2 = s2 self.square_list.append(self) def calculate_perim(self): return self.s2 * 4 def __repr__(self): return "{} by {} by {} by {}".format(self.s2, self.s2, self.s2, self.s2) sq_four = SquareTwo(29) print(sq_four) class Square(): sqrs = [] def __init__(self, s): self.s = s self.sqrs.append(self) def calculate_perim(self): return self.s * 4 def __repr__(self): return "{} by {}" .format(self.s, self.s) sq_one = Square(4) print(Square.sqrs) sq_two = Square(9) print(Square.sqrs) sq_three = Square(12) print(Square.sqrs)
num1= [8, 19, 148, 4] num2= [9, 1, 33, 83] list3 = [] for i in num1: for j in num2: mult = i*j list3.append(i*j) print(list3) num4= [8, 19, 148, 4] num5= [9, 1, 33, 83] mult2 = [] for i in num4: for j in num5: mult2.append(i*j) print(mult2) numbers = [11, 32, 33, 15, 1] while True: answer = input("Guess a number or type q to quit.") if answer == "q": break try: answer = int(answer) except ValueError: print("please type a number or q to quit.") if answer in numbers: print("You guessed correctly!") else: print("You guessed inccorrectly!")
randomstring = "Camus" print(randomstring[0]) print(randomstring[1]) print(randomstring[2]) print(randomstring[3]) print(randomstring[4]) questions = "Where now?", "Who now?", "When now?" edited = "," .join(questions) print(edited) correctthis = "aldous Huxley was born in 1894." .capitalize() print(correctthis) fixthis = "A screaming comes across the sky." fixthis = fixthis.replace("s", "$") print(fixthis) first_index = "Hemingway" .index("H") print(first_index) threestring = "three" + " " result = threestring * 3 print(result) print("three " + "three " + "three ") print("three " * 3) firstentry = input("What did you write yesterday?") secondentry = input("Where did you go yesterday?") newstring = "Yesterday I wrote a {}. I sent it to {}." .format(firstentry, secondentry) print(newstrong)
# define a function that take list of word as a argument and return list with reverse of every element in the list def rr(l): rl=[] for i in l: rl.append(i[::-1]) return rl numbr=["word","tanmay","anuradha","gopal","shyam"] print(rr(numbr))
name=input("enter your name:->") def add(n,m): return n+m def sub(n,m): return n-m def multiply(n,m): return n*m def divide(n,m): return n/m print("welecome to my calculator") while True: menu=input("a:add , s:subtraction , m:multiply , d:divide ::--->>> ") if menu in('a','s','m','d'): n1=float(input("enter a first number:->")) n2=float(input("enter a second number:->")) if menu=='a': print(n1,'+',n2,'=',add(n1,n2)) break if menu=='s': print(n1,'-',n2,'=',sub(n1,n2)) break if menu=='m': print(n1,'*',n2,'=',multiply(n1,n2)) break if menu=='d': print(n1,'/',n2,'=',divide(n1,n2)) break else: print("any error is present") break print("thankyou",name)
number_one=int(input("enter number one")) number_two=int(input("enter number two")) number_three=int(input("enter number three")) total=((number_one + number_two + number_three)/3) print(total)
#99 bottles code #Written by Dylan Webb on 1.23.17 i = 99 while i > 0: if i == 1 : print(i, "bottle of an undefined beverage on the wall") print(i, "bottle of an undefined beverage") else : print(i, "bottles of an undefined beverage on the wall") print(i, "bottles of an undefined beverage") print("Take one down & pass it around") i -= 1 if i == 1 : print(i, "bottle of an undefined beverage on the wall\n") else : print(i, "bottles of an undefined beverage on the wall\n")
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import numpy as np import scipy.io as sio import random from sklearn import linear_model # The data is from Coursera Machine Learning course/week4/ex3data1.mat # There are 5000 training examples, each is a 20x20 pixels grayscale # image of digit 0-9. data = sio.loadmat('../data/data5.mat') X = data['X'] # The 20x20 grid of pixels is unrolled into a 400-dimensional vector. # Thus X.shape = (5000, 400). y = data['y'] # The label for 5000 training examples. # Note: digit '0' is labeled as '10' # Some useful variables m, n = X.shape num_labels = len(np.unique(y)) # Number of labels # Randomly select 100 data points to display sel = X[random.sample(range(0, m), 100), :] def display_data(X): # Specify figsize to avoid unexpected gap between cells fig = plt.figure(figsize = (6, 6)) # Compute size of grid m, n = X.shape display_rows = int(np.floor(np.sqrt(m))) display_cols = int(np.ceil(m / display_rows)) grid = gridspec.GridSpec(display_rows, display_cols, wspace = 0.0, hspace = 0.0) for i in range(m): ax = plt.Subplot(fig, grid[i]) img_size = int(np.sqrt(n)) ax.imshow(X[i, :].reshape((img_size, img_size)).T, cmap = 'gray') ax.set_xticks([]) ax.set_yticks([]) fig.add_subplot(ax) print('Displaying data...') display_data(sel) plt.show() # C is the inverse of lambda: the higher C is, the more # the algorithm will focus on the fitting data term logreg = linear_model.LogisticRegression(C = 1) print('Training model (this may take a while)...') logreg.fit(X, y.ravel()) # Predict and compute accuracy y_pred = logreg.predict(X) y_pred = y_pred.reshape((m, 1)) print('Accuracy: ', np.mean((y_pred == y).astype(float)) * 100)
''' ###################################################################### Author: Srikanth Peetha [@srikanthpeetha262] About: Implementating Genetic algorithm & Roulette wheel algorithms ###################################################################### ''' import random from math import exp import numpy import matplotlib.pyplot as plt out = [] fit = [] fit_prob = [] newGen = [] currentGene = [] probb_sum = 0 """ Define the count of the population required!!! """ pop_count = 100 val_count = 3 # number of variables in o/p equation #~~~ Begin Genetic Algorithm Function def gen_alg(inputt): gain1 = [] del gain1[:] #Clear all the ellements of the gain1 array gain1_check = 0 gain2 = [] del gain2[:] #Clear all the ellements of the gain2 array gain2_check = 0 #~~~ Generate random numbers between 0 & 1 a = random.uniform(0.0,0.9) #~~~ Roulette wheel Algorithm probb_sum = 0 for i in range(0,pop_count): probb_sum = probb_sum + fit_prob[i] if a < probb_sum : #comparing random number 'a' with the 'prob_sum' upto the i'th element of the fit_probb array. gain1 = inputt[i] gain1_check = 1 break if i == (pop_count -1) and gain1_check == 0: gain1 = inputt[i] break b = random.uniform(0.0,0.9) probb_sum = 0 for j in range(0,pop_count): probb_sum = probb_sum + fit_prob[j] if b < probb_sum : #comparing random number 'a' with the 'prob_sum' upto the i'th element of the fit_probb array. gain2 = inputt[j] gain2_check = 1 break if j == (pop_count -1) and gain2_check == 0: gain2 = inputt[j] break #~~~ Generating index for crossover variables temp1 = int(round(random.uniform(0,20) / 10)) temp2 = int(round(random.uniform(0,20) / 10)) cross = [] #~~~ Create crossover array del cross[:] #~~~ empty the crossover array cross = gain1 cross[temp1] = gain2[temp1] cross[temp2] = gain2[temp2] #~~~ possibility of mutated variable generation chance = random.uniform(0.00,0.09) if chance < 0.02: increment = random.uniform(-0.09,0.09) index = int(round(random.uniform(0,20) / 10)) cross[index] = cross[index] + increment return cross #~~~ End Genetic Algorithm Function ''' The input 'inputt' we are considering are in the 2D array format, like shown below inputtArray = { [x1-1,x1-2,x1-3.....x1-10] [x2-1,x2-2,x2-3.....x2-10] [x3-1,x3-2,x3-3.....x3-10] . . . [x10-1,x10-2,x10-3.....x10-10] } where, input-1 values are ---> (x1-1,x1-2,x1-3.....x1-10) input-2 values are ---> (x2-1,x2-2,x2-3.....x2-10) for understanding purposes the elements of the array are viewed as Matrix elements x1-1 x1-2 x1-3 ... x1-10 x2-1 x2-2 x2-3 ... x2-10 x3-1 x3-2 x3-3 ... x3-10 . . . x10-1 x10-2 x10-3 ... x10-10 ''' def main(): old_gen_count = 0 global inputt inputt = [] global out out = [] for i in range(0,pop_count): inputt.append([]) #creates a new row in a matrix for j in range(0,val_count): #val_count is the number of variables in the o/p equation x = random.uniform(0.00,3.00) inputt[i].append(x) #add j'th element in the row-i repeat = 1 egg = 10 count = 0 while (count < 20): fit_sum = 0 i = 0 #~~~ Output(y) and Fitness(f) calculation out = [] del out[:] fit = [] del fit[:] for i in range(0,pop_count): #~~~ In the below line of code, by mentioning gen[i][0], inputt[i][1] .... and so on I am accessing all 10 elements (in this case) of the i-th row of the matrix. Because elements of the rows are our input values a = ((inputt[i][0] - 1)**2) + ((inputt[i][1] - 2)**2 ) + ( (inputt[i][2] - 3)**2 ) + 1 out.append(a) fit.append( exp(-out[i]) ) # Describe fitness function fit_sum = sum(fit)# Claculate fitness sum #~~~ Calculating the Fitness Probability Array for p in range(0,pop_count): if fit_sum == 0: fit_sum = 1 fit_prob.append( fit[p]/fit_sum ) else: fit_prob.append( fit[p]/fit_sum ) i = 0 j = 0 call = [] del call[:] newGen = [] del newGen[:] #~~~ Begin: Creating a new generation of inputs for i in range(0,pop_count): call = gen_alg(inputt) #~~~ Calling the genetic algorithm function newGen.append( call ) #~~~ End: Created new generation of inputs inputt = newGen count += 1 j = 0; i = 0; a = [] b = [] c = [] A = [] for i in range(0,pop_count): a.append( inputt[i][0] ) b.append( inputt[i][1] ) c.append( inputt[i][2] ) A.append( numpy.mean(a) ) A.append( numpy.mean(b) ) A.append( numpy.mean(c) ) print "done" print A print "\n" main()
"""Write a python program which will keep adding stream of numbers inputted by User. The adding stops as soon as user presses q key on the keyboard""" sum = 0 while True: userInput = input("Enter the item price or press 'q' to quit: ") if userInput != 'q': sum = sum + int(userInput) print(f"Your order total so far {sum}") else: print(f"Your total bill is {sum}. Thanks for coming") break """checking git """
names = ['kole','bajo','zelje','dugi',] print(names) popped_name = names.pop() print(names) print(popped_name) zadnji_frend = names.pop(0) print("zadnji s kim sa se druzio bio je " + zadnji_frend.title() + ".") names.remove('zelje') print(names)
pizzas = ['bijela', 'slavonska', 'mozzarela',] for pizza in pizzas: print(pizza) print("\n") for pizza in pizzas: print("Ja volim " + pizza.title() + " pizzu.") print("\n") print("ja volim sve pizze.")
#!/usr/bin/env python3 # HW05_ex09_01.py # Write a program that reads words.txt and prints only the # words with more than 20 characters (not counting whitespace). ############################################################################## # Imports import re # Body def read_file(): file_name = input("Please enter the file name with extention: ") data = open(file_name, "r") for line in data: if len(line.strip()) > 20: print (line, end = "") ############################################################################## def main(): read_file() # Call your functions here. if __name__ == '__main__': main()
# Problem 5 Smallest multiple # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def isprime(a): # bir sayının asal olup olmadığını kontrol eden fonksiyon i = 3 if(a < 2): return False if a != 2 and a % 2 == 0: return False while i <= a ** (1 / 2): if a % i == 0: return False i += 2 return True sayi = 1 for i in range(1, 20): if(isprime(i)): sayi *= i for j in range(2, 21): if(sayi % j == 0): continue else: for k in range(2, j): if(j % k == 0): sayi *= k break print(sayi)
# Problem 9 Special Pythagorean triplet # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. for i in range(200,500): for j in range(200,500): if(i>=j): continue for k in range(200,500): if(j>=k): continue if(i**2+j**2==k**2): if(i+j+k==1000): print(i,j,k) print(i*j*k)
# Problem 34 Digit factorials # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. # Find the sum of all numbers which are equal to the sum of the factorial of their digits. # Note: As 1! = 1 and 2! = 2 are not sums they are not included. def faktoriyel(n): toplam = 1 for a in range(1, n + 1): toplam *= a; return toplam t = 0 for i in range(3, 50000): s = 0 for j in str(i): s += faktoriyel(int(j)) if(s == i): t += s print(t)
count=0 def check(x,y,board): for i in range(x): if board[i][y]==1: #print('Y',board) return False for ix in range(8): for iy in range(8): if (ix+iy==x+y or ix-iy==x-y)and(board[ix][iy]==1): #print('X',board) return False return True def rec(x,y,board): global count if x==7: count=count+1 print('Display',board) return else: for i in range(8): #board[x+1][i]=1 if check(x+1,i,board): board[x+1][i]=1 rec(x+1,i,board) board[x+1][i]=0 board=[[0 for i in range(8)]for i in range(8)] for i in range(8): board[0][i]=1 rec(0,i,board) board[0][i]=0 print(count)
class ModelEx1: def __init__(self, month, num): self.month = month self.num = num class ModelEx1P2: def __init__(self, model1, media): self.model1 = model1 self.num = media class N1: def bubble_sort(self, lista): elements = len(lista) - 1 ordenado = False while not ordenado: ordenado = True for i in range(elements): obj1 = lista[i] obj2 = lista[i + 1] if obj1.num > obj2.num: lista[i], lista[i + 1] = lista[i + 1], lista[i] ordenado = False return lista def calc_media(self, list): n1Class = N1() sizeList = len(list) print(sizeList) media = 0 index = 0 for item in list: media = media + item.num media = media / len(list) print("Media: " + str(media)) min = list[0] max = list[sizeList - 1] print("Minimo\n mes:" + str(min.month) + "\nnum: " + str(min.num)) print("Maximo\n mes:" + str(max.month) + "\nnum: " + str(max.num)) listAux = [] for item in list: valor = item.num - media print(abs(valor)) modelAux = ModelEx1P2(item, abs(valor)) listAux.append(modelAux) listOrdernada = n1Class.bubble_sort(listAux) obj = listOrdernada[0] print("\n\nValor mais proximo da média") print("Mes" + str(obj.model1.month)) print("Num" + str(obj.model1.num)) def printList(self, list): var = list for obj in var: print(obj.month) print(obj.num) def exercicio_1(self): n1Class = N1() list = [] run = True while run == True: month = input("Informe o mes: ") num = int(input("Informe a quantidade de rebeldes presos")) obj = ModelEx1(month, num) list.append(obj) opc = input("Deseja inserir um novo registro? <S> ou <N> ") if opc.upper() != 'S': run = False for item in list: print("-" * 30) print("mes:" + str(item.month)) print("quantidade: " + str(item.num)) print("-" * 30) newList = n1Class.bubble_sort(list) for item in newList: print("-" * 30) print("mes:" + str(item.month)) print("quantidade: " + str(item.num)) print("-" * 30) n1Class.calc_media(newList) def aplicacao(self): print("iniciando aplicacao") n1Class = N1() n1Class.exercicio_1() N1().aplicacao()
#Reverse Words in String in its own place. s=raw_input("Enter a String: ") def reverse_words(s): reverseWord = " " list = s.split() for word in list: word= word[::-1] reverseWord = reverseWord + word + " " print reverseWord.strip() reverse_words(s)
""" 5) Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle.""" class Circle(): def __init__(self, r): self.radius = r def area(self): return self.radius**2*3.14 def perimeter(self): return 2*self.radius*3.14 c=input("Enter Radius: ") NewCircle = Circle(c) print(NewCircle.area()) print(NewCircle.perimeter())
# 9) To print out the first n rows of Pascal's triangle rows=input("Enter Rows of pascal triangle : ") def pascal_triangle(n): f = [1] y = [0] for x in range(max(n,0)): print(f) f=[l+r for l,r in zip(f+y, y+f)] return n>=1 pascal_triangle(rows)
lst = [x for x in range(1,10)] for each in lst: if each == 1: print('1st') elif each == 2: print('2nd') elif each == 3: print('3rd') else: print('%dth' % each)
import unittest from employee import Employee class EmployeeTest(unittest.TestCase): def setUp(self): self.em = Employee('Wang', 'Ming', 10000) def test_give_default_raise(self): self.em.give_raise() self.assertEqual(self.em.salary, 15000) def test_give_custom_raise(self): """self.em的状态不会发生改变,和初始化状态一样""" self.em.give_raise(10000) self.assertEqual(self.em.salary, 20000) if __name__ == '__main__': unittest.main()
favorite_places = { 'Tom': ['Beijing', 'London', 'Paris'], 'Jack': ['GuangZhou', 'Shanghai', 'Tokyo'], 'Sarah': ['NewYork', 'Paris', 'Moscow'] } for name in favorite_places: print(name + ':') for place in favorite_places[name]: print(place, end=' ') print('\n')
dog = { 'type': 'dog', 'master': 'Tom' } cat = { 'type': 'cat', 'master': 'Sam' } turtle = { 'type': 'turtle', 'master': 'Sarah' } pets = [dog, cat, turtle] for pet in pets: print('Pet type: ' + pet['type']) print('Pet\'s master: ' + pet['master'] + '\n')
class Node: def __init__(self, value=None, next_node=None): # the value at this linked list node self.value = value # reference to the next node in the list self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): # set this node's next_node reference to the passed in node self.next_node = new_next class LinkedList: def __init__(self): # reference to the head of the list self.head = None def printNode(self): curr = self.head arr = [] while curr: arr.append(curr.value) curr = curr.get_next() print(arr) def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False # get a reference to the node we're currently at; update this as we # traverse the list current = self.head # check to see if we're at a valid node while current: # return True if the current value we're looking at matches our # target value if current.get_value() == value: return True # update our current node to the current node's next node current = current.get_next() # if we've gotten here, then the target node isn't in our list return False def reverse_list(self, node, prev): # You must use recursion for this solution, and break my brain doing so... #If the pointer is none, return, this is for empty lists. if node == None: return #If the pointer next node is none, change the head of the list to the current pointer, this starts the reverasal elif node.get_next() == None: self.head = node return #Otherwise: else: #Recursion on the next item in the list self.reverse_list(node.get_next(), None) #Then get the next node, and set its next to the current one, this starts reversing the list node.get_next().set_next(node) #Then kill the old connection node.set_next(None) # Lets pretend we have a list that goes 1->2->3->X, our goal is to get 3->2->1->X # We have to do this recursivly, so ideally in just one pass # We will want a pointer called current, that points at the head to start # It checks the first 2 rules and finds neither will run, so then runs recursion on the next element. # This continues until the pointer is pointing at 3. in which case it can run the 2nd argument, and turns 3 into the head # then we go back up the call stack, where we grab the next node and set its next to the current node, in this case # setting three to point to 2, and then we kill the connection of two pointing to three, finish the whole stack and its reversed! #Lingering questions: why does reverse list call for previous? The tests never use it. list = LinkedList() list.add_to_head(1) list.add_to_head(2) list.add_to_head(3) list.add_to_head(4) list.add_to_head(5) list.printNode() list.reverse_list(list.head, None) list.printNode()
# ------------------------11111111------------------------- num1, num2, num3= input('Enter three number ').split() print(f'{(int(num1) + int(num2) + int(num3))/3}') # ----------------------------2222222222-------------------- name= input('what is your name: ') print(name[-1::-1]) # -------------------------------333333333--------------------- name,char = input(r"what's your name & input a character in your name :").split(",") print(f'lenght of your name : {len(name)}') # print(f'number of char :{name.lower().count(char.lower())}') print(f'number of char{name.strip().lower().count(char.strip().lower())}')
l1= [1,3,5,7] l2 = [2,4,6,8] new_list= [] l = {(1,2),(3,4),(5,6)} print(list(zip(*l))) for pair in zip(l1,l2): new_list.append(max(pair)) print(new_list)
# s ={1:1 , 2:4 , 3:9} # dictionary = {num:num**2 for num in range(1,11)} # print(dictionary) # dictionary2 = {f"key value is {num}" : num**2 for num in range(1,11)} # print(dictionary) string = 'jitshil' count = {i:string.count(i) for i in string} print(count)
# something more about tuple ,list, str new = tuple(range(1,11)) print(new) new1 = list((1,2,3,4,5,6,4)) print(new1) new2 = str((1,2,3,4,4,5)) print(new2) print(type(new2))
# generate list with range #pop method # index method # function list number = list(range(1,21)) # print(number) # num = number.pop() # print(number) # print(number.index(2)) # list =[1,2,3,4,5,6,7,8,9,1] # print(list.index(1, 3, 11)) # def nagetive_list(l): # nagetive = [] # for i in l: # nagetive.append(-i) # return nagetive # print(nagetive_list(number))
user_info = { 'name' : 'jitshil', 'age' : 21, 'fav_movie' : ['coco' , 'moco'], 'fav_singer' : ['arijit','miner'], } # ---------------------------------------------------------------- # d = dict.fromkeys(['name','age'], 'pagla') # # d = dict.fromkeys(range(1,11),'unknown') # print(d) # ---------------------------------------------------------- # print(user_info['name']) # print(user_info.get('name')) #that's better # ----------------------------------------------------------------- # if 'name' in user_info: # print('present') # else: # print('not present') # if user_info.get('name'): # print('present') # else: # print('not present') # ------------------------------------------------------------ d = user_info.copy() print(d) user_info.clear() print(user_info)
# numbers = [1,2,3,4,5,6,7,8,9] # num=[] # for i in numbers: # if i%2 == 0: # num.append(i) # print(num) # num1 = [i for i in numbers if i%2 == 0] num2 = [i for i in range(1,11) if i%2 == 0] # print(num1) print(num2) odd_num = [i for i in range(1,11) if i%2 != 0] print(odd_num)
fruit1 = ['pinaple','mango','apple'] fruit1.sort() print(fruit1) fruit2 = ('pinaple','mango','apple') print(sorted(fruit2)) guiter=[ {'name': 'yamha','price':8000}, {'name': 'singnature','price':6000}, {'name': 'electric','price':22000} ] print(sorted(guiter, key=lambda item:item.get('price'),reverse = True))
example = [[1,2,3],[1,2,3],[1,2,3]] nested = [[i for i in range(1,100)] for j in range(20)] print(nested) new_nested = [] for i in range(1,4): new_nested.append([1,2,3]) print(new_nested)
class Animal: def __init__(self): pass def make_a_sound(self, species): if species == "cat": print("meow") elif species == "dog": print("woof, woof") elif species == "fox": print("timtirimtim") else: print("Don't know that animal") my_animal = Animal() my_animal.make_a_sound("cat")
from datetime import datetime #get nth letter of a string, 0 based #output: L print "HELLO"[3] #return length of a string parrot = "Norwegian Blue" print len(parrot) #Lower & upper case print "HELLO".lower() print "hello".upper() #String conversion pi = 3.14 print str(pi) #check for alpha #output: true print "FEFRE".isalpha() #floor division, remove the last digit from number print 1234 // 10 #string concatination print "spam" + " and " + "eggs" #print with c like variable replacement string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." %(string_1, string_2) #Simple IO name = raw_input("What is your name?") quest = raw_input("What is your quest?") color = raw_input("What is your favorite color?") print "Ah, so your name is %s, your quest is %s, and your favorite color is %s." %(name, quest, color) now = datetime.now() print now print now.year print now.month print now.day
#merging list tuples with zip first = ['ben', 'daniel', 'bob'] last = ['hanks', 'swift', 'pitt'] names = zip(first, last) #will look something like #[('ben', 'hanks'), ('daniel', 'swift'), ('bob', 'pitt')] for a, b in names: print (a, b)
""" A basic example of controlling a motor via smbus """ import smbus2 BUS = smbus2.SMBus(1) ADDRESS = 0x04 MODE_FLOAT = 0 MODE_BRAKE = 1 MODE_FWD = 2 MODE_BKW = 3 def set_motor(motor_id: int, speed: int) -> None: """Sets a motor to spin. Any positive value is forwards, any negative one is backwards. """ mode = MODE_FWD if speed >= 0 else MODE_BKW msg = smbus2.i2c_msg.write(ADDRESS, [motor_id << 5 | mode << 1 | 24, abs(speed)]) BUS.i2c_rdwr(msg) def stop_motor(motor_id: int) -> None: """Stops the given motor""" # Mode 0 floats the motor. BUS.write_byte(ADDRESS, motor_id << 5 | MODE_BRAKE << 1) def float_motors() -> None: """Stops all motors and allows them to coast.""" # The motor board stops all motors if bit 0 is high. BUS.write_byte(ADDRESS, 0x01) def stop_motors() -> None: """Stops all motors. Like, really hard.""" for i in range(6): BUS.write_byte(ADDRESS, i << 5 | MODE_BRAKE << 1)
import random k = 0 for x in range(0,8): num = random.randint(1,2) num3 = random.randint(1,9) num2 = str(0.1) + str(num) + str(num3) content = float(num2) print(content) k +=content print(k)
import random alphabets= """abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'""" def encrypt(message): global shift_generator encrypted=[] embeded=[] for shift in message: shift_generator = random.randint(1, 26) print("Shift: ", shift_generator) if shift in alphabets and shift.isalpha() and alphabets.index(shift)!=-1: old_position=alphabets.index(shift) new_position=old_position+shift_generator encrypted+=alphabets[old_position : new_position+1] else:encrypted += list(shift) return encrypted[-1] def decrypt(encrypted): decrypted=[] for shift in encrypted: if shift in alphabets and shift.isalpha(): old_position = alphabets.index(shift) new_position = old_position - shift_generator decrypted += alphabets[new_position] return decrypted if "__name__==main": message = input("Type message: ") encryption=encrypt(message) print("Encrypted Message: ", encryption, end="") print("Decrypted Message: ",decrypt(encryption), end="")
n = 42 f = 7.03 s = "cheese" print("The value of n is {}, f is {} and s is {}".format(n, f, s)) # format passes postional args print("s = {2}, n is {0} and f is {1}".format(n, f, s)) # using the postional args # or use a dictionary d = {"n": 21, "f": 14.06, "s":"mac"} print("Using dict, n={0[n]}, f={0[f]} and s={0[s]}".format(d)) # cast or format print("Casting {0:12d}, {1:0.3f}, {2:s}".format(n,f,s))
# here we declare reusable functions in our module # e.g. take a bunch of numbers and return the sum def addStuff (*args): #print(args) total = 0 for num in args: if type(num) == int or type(num) == float: total += num #print(total) return total if __name__ == "__main__": # following code will run only if this file is being run standalone # e.g. for unit testing of functions in this module # print(addStuff (1,2,3,4,5)) # print(addStuff(1.5,2.5,3.5,4.5,5.5)) # nums = list(range(45,48)) nums = [] for i in range(45,48): nums.append(i) # print(addStuff(nums)) print (nums) print("total=",addStuff(nums))
# more accurate time capabilities are avl using timeit # timeit ignores non-python time delays, ie only counts time taken by python to execute code import random import time import timeit # a function to decorate a function we need to accurately time def timethis(func): def func_timer(*args, **kwargs): start_time = timeit.default_timer() value = func(*args, **kwargs) run_time = timeit.default_timer() - start_time print('Function {} took {}sec'.format(func.__name__, run_time)) return value return func_timer @timethis def long_runner(): for x in range(9): sleep_time = random.choice(range(1,3)) time.sleep(sleep_time) @timethis def count_up(): for i in range(1, 100): x = i @timethis def count_down(): for j in range(100, 1, -1): y = j if __name__ == '__main__': long_runner() count_down() count_up()
from threading import Thread import time import random import sys # create a runnable class which inherits from Thread class class MyThreadClass(Thread): def __init__(self, name): Thread.__init__(self) self.name = name #override the run method of Thread class def run(self): # do a time-consuming operation for i in range(1,5): time.sleep(random.random()*0.9) sys.stdout.write(self.name+'\n') if __name__ == '__main__': tc1 = MyThreadClass('My Thread Class 1') tc2 = MyThreadClass('My Thread Class 22') tc3 = MyThreadClass('My Thread Class 333') tc4 = MyThreadClass('My Thread Class 4444') # start threads tc1.start() tc2.start() tc3.start() tc4.start() # rejoin to the main thread __main__ tc1.join() tc2.join() tc3.join() tc4.join()
# imports go at the top # define functions here def document_it(func): def new_func(*args, **kwargs): # here is the code to document any function we might want to know about print("The running function is called", func.__name__) print("The docstring is", func.__doc__) if len(args)> 0: print("The positional arguments are", args) else: print("No positional arguments") if len(kwargs)> 0: print("The keyword arguments are", kwargs) else: print("No keyword arguments") result = func(*args, **kwargs) print("Result of the function is", result) return result return new_func # since we're returning the function, not calling the function def square_it(func): def new_function(*args, **kwargs): """ This is the doc string for new_function """ result = func(*args, **kwargs) return result * result return new_function @document_it # decorator @square_it def add_ints(a, b, x=0): return a+b # immediate code if __name__ == "__main__": # eg = document_it(add_ints) # pass the target function as param # # eg (5, 6) # eg (5, 6, x=True) newVar=add_ints(2,3,x=False) # print (newVar)
# iterators l = [5, 4, 3, True, (1,), 'hi'] i=0 #print('i is', i) # for iteration for item in l: # colon indicates starts of a code block #print(item) #each line of the code block is indented #print(type(item)) i = i+1 #print('i is', i) # code block ends when indentation ends # range object can also be used for iteration r = range (99) #print(r, type(r)) #for i in range(-9,10,3): # start, stop before, step #print(i) # iterating over collections s = 'not long until lunch time' d = {'name':'Ada', 'age':35, 'vaxed':True} #for c in s: #print(c) #for item in d: #print(item) #print(item, d[item]) #for key, value in d.items(): #print(key, value) # we can generate members as we need them #my_gen = ( num**0.5 for num in range(-10*10, 10*10) ) # a tuple generator for sq root of all nums -110 to 110 #print(type(my_gen)) #for r in my_gen: #print(r) # generates the numbers as needed, then discarded, not stored # mini-challenge - generate all even nums 0-100 without using step evens = ( num*2 for num in range (0,51)) for r in evens: print(r) # we can combine 'if' logic in custom generators odds = ( num for num in range (0,100) if num%2 != 0) for r in odds: print(r)
# we can always check the data type s = 'almost done' print(type(s)) num = 3.2 print(type(num)) if isinstance(s, str): print(s, ' is a string') if isinstance(num, (int, float)): # check data type against a tuple of possibilities print(num, ' is a number')
from swapi import Swapi class SwapiPlanets (Swapi): def __init__(self, cat, name, climate, terrain, pop): super().__init__(cat, name) self.climate = climate self.terrain = terrain self.pop = pop @property def climate(self): return self.__climate @climate.setter def climate(self, new_climate): self.__climate = new_climate @property def terrain(self): return self.__terrain @terrain.setter def terrain(self, new_terrain): self.__terrain = new_terrain @property def pop(self): return self.__pop @pop.setter def pop(self, new_pop): self.__pop = new_pop def __str__(self): self.appendData('{} has {} climate with {} terrain and a population of {}!\n'.format(self.name, self.climate, self.terrain, self.pop)) if __name__ == '__main__': s_planets = SwapiPlanets('cat', 'name', 'climate', 'terrain', 'pop') print(s_planets)
# class and methods for extending weather data when it is windy or rainy from weather import Weather class WeatherExtended(Weather): def __init__(self, temp, desc, moreInfo): super().__init__(temp, desc) self.moreInfo = moreInfo def __str__(self): prn = super().__str__() if self.desc == 'rainy': prn += ' with a {}% chance of rain'.format(self.moreInfo) elif self.desc == 'snowy': prn += ' with a {}% chance of snow'.format(self.moreInfo) elif self.desc == 'windy': prn += ' with a windpeed of {} mph'.format(self.moreInfo) else: pass return prn if __name__ == '__main__': we1 = WeatherExtended(15, 'rainy', 68) we2 = WeatherExtended(2, 'snowy', 80) we3 = WeatherExtended(12, 'windy', 20) print(we1) print(we2) print(we3)
""" Write a new top-level module which asks the user for a 'project title', a 'number range (min/max)' and a 'mathematical technique (sum, mean, squares)' Import the 'sanitize' module and use it to make sure the 'project title' is a title-case string Also ensure the min and max values are cast as integers and the chosen technique matches one of the options (sum, mean or squares) Write other modules to contain the functions which will: - generate a range of numbers, given min and max - return the mean of those numbers - return a tuple of the squares of those numbers Use your existing 'addStuff' method to return the sum of the range of numbers Make use of imports for your new modules so they can be used to implement the chosen mathematical technique upon the range the user asked for Write brief descriptive docstrings for each of your functions Consider using if __name__ == '__main__': to write code-exercising lines within your new sub modules Optional -------- Find a way to ask for a 'step' value for the range, with a default of 1 Let the user provide more than one technique, so they might want both sum and mean Let the user choose what power (rather than just 'squares') Find a way to chain operations, so they might find powers of 3 then sum those results and then find the mean Write a function which will become a decorator for other functions. The purpose of this new function is to make all the parametes into integers, or else ignore them Apply this function as a decorator to the mean and square methods you have written You could also alter the addStuff method to make use of this new decorator Decide on a way to tell users what your project is capable of. For example, if they type 'h' you could return a nicely formatted bit of text explaining how they can use the code to find sum, mean or squares. Even better if you can make use of docstrings! """ from modules import sanitize # existing from modules import my_module # existing from modules import mathop # new module for this project print ("WELCOME TO THE MATHS PROJECT\n\n") title = input ("Enter your project title: ") #title = sanitize.cleanup(title) #print(title) num1 = int (input ("\nEnter a number : ")) num2 = int (input ("Enter another : ")) nums = range (num1, num2) sq = [] op = 0 while op < 1 or op > 4: print ("\nFor all numbers between", num1, "and", num2, "select the operation you want to do") print ("1 - sum of all numbers in that range") print ("2 - mean of all numbers in that range") print ("3 - square of all numbers in that range") op = int (input("Your choice (-1 to quit): ")) if op == -1: break print("\n***\n\nProject Title: ",sanitize.cleanup(title)) if op == 1: print("\nSum of all numbers between", num1, "and", num2, ":", my_module.addStuff(*nums)) if op == 2: print("\nMean of all numbers between", num1, "and", num2, ":", mathop.findMean(num1,num2)) if op == 3: print ("\nSquare of all numbers between", num1, "and", num2, ":", mathop.squareNums(num1,num2)) print ("\n\n***\n\n")
# ask user to input n and print sqrt from 1 to n # ask user to input n and check if it is a square # use show_args to decorate each method from my_helper import my_helper def getAllSqrt(n): sqrtList = list(map(my_helper.getSqrt, range(1,n))) print (sqrtList) if __name__ == '__main__': num = input('Enter a number (-100 to 100):') if isinstance(num) == 'int': pass else: num = 1 getAllSqrt(int(float(num)))
# Scope - What variables do I have access to? # Scope Rules # 1 - Start with local # 2 - Parent local? # 3 - Global # 4 - built-in python functions # nonlocal keyword def outer(): x = "local" def inner(): # nonlocal x x = "nonlocal" print("inner:", x) inner() print("outer:", x) outer() # Dependency Injection # total = 0 # def count(total): # total += 1 # return total # print(count(count(count(total)))) # Not a recommended way to use global keyword # total = 0 # def count(): # global total # total += 1 # return total # count() # count() # print(count()) # a = 1 # def parent(): # # a = 10 # def confusion(): # # a = 5 # return sum #a # return confusion() # print(parent()) # print(a) # def some_func(): # total = 1000 # print(total) # Traceback (most recent call last): # File "test.py", line 5, in <module> # print(total) # NameError: name 'total' is not defined
# Inheritance class User(): def __init__(self, email): self.email = email def sign_in(self): print('Logged in') class Wizard(User): def __init__(self, name, power, email): # User.__init__(self, email) super().__init__(email) self.name = name self.power = power def attack(self): User.attack(self) print(f'Attacking with power of {self.power}') class Archer(User): def __init__(self, name, num_arrows): self.name = name self.num_arrows = num_arrows def attack(self): print(f'Attacking with arrows: arrows left- {self.num_arrows}') wizard1 = Wizard('Merlin', 50, 'merlin@gmail.com') print(wizard1.email) # Object Introspection # The ability to determine the type of the object at runtime print(dir(wizard1))
print('Aswin Barath') name = input('What is your name? Your Answer:') print(name) print('Helllloooo ' + name)
import sys import random beg = int(sys.argv[1]) end = int(sys.argv[2]) number = random.randint(beg, end) while True: try: guess = int(input(f'Enter a number b/w {beg} & {end}:')) if beg <= guess <= end: if number > guess: print(f'Oh no, {guess} is lesser than the number') elif number < guess: print(f'Oh no, {guess} is greater than the number') else: print(f'Congrats, you won the game!!\nYour guess {guess} is correct') break else: print(f'Hey bozo, I told you to enter a number b/w {beg} & {end}, so') continue except ValueError: print('Hello mister, please enter a number') continue
# Dictionary (in other langs, also called hashtables, maps, objects) dictionary = { 'a': [1, 2, 3], 'b': 'hello', 'x': True } # dictionary is an unordered key value pair DataStrucure print(dictionary['b']) print(dictionary) my_list = [ { 'a': [1, 2, 3], 'b': 'hello', 'x': True }, { 'a': [4, 5, 6], 'b': 'hello', 'x': True } ] print(my_list[0]['a'][2]) # Dictionary keys - Immutable dictionary2 = { 123: [1, 2, 3], True: 'hello', '123': True } # List are mutable so we cannot use it as keys print(dictionary2[123]) print(dictionary2[True]) print(dictionary2['123']) # Dictionary methods user = { 'basket': [1, 2, 3], 'greet': 'hello', 'age': 20 } print('Get method') print(user.get('age', 55)) # Another way to create dictionary user2 = dict(name='John Doe') print(user2) print('keys method') print('basket' in user.keys()) print('values method') print('hello' in user.values()) print('Items method') print(user.items()) # print('clear method') # print(user.clear()) # print(user) user3 = user.copy() print('copy method') print(user.clear()) print(user3) print('pop method') print(user3.pop('age')) print(user3.popitem()) print(user3) print('update method') print(user2.update({'name': 'Aswin'})) print(user2) print(user2.update({'names': 'Aswin Barath'})) print(user2)
#симулятор телевизора(почти) class Zombiebox(object): """Виртуальный телевизор""" def __init__(self, channel=0 , volume=0 ): self.volume = volume self.channel = channel def channels(self, choice_to_watch = None): try: self.channel = ["Вечно не работающий канал","Пропаганда киселёва","Пропаганда госдепа","Либеральная пропаганда","Иллюминаты и жидомасоны","Т(лишняя хромосома)НТ-ТВ","Вырвиглаз-ТВ(российский футбол 24x7!)","Страх и ненависть в Тропарёво(21+)","Канал, запрещённый в РФ","Канал, на который всем насрать"] print("Доступен следующий список каналов(всего 10): ") print(self.channel[0:3]) print(self.channel[3:7]) print(self.channel[7:10]) choice_to_watch = int(input("Выберите канал: ")) print("Вы включили канал: ", self.channel[choice_to_watch]) self.channel = self.channel[choice_to_watch] except (ValueError, IndexError): if choice_to_watch not in range(0 , 10): print("У телевизора нет канала под этой цифрой! Пожалуйста, выберите канал из доступного диапазона.") choice_to_watch = 0 self.channel = self.channel[choice_to_watch] def sound(self, regulir = None): regulir = input("Введите + или - для увеличения\уменьшения громкости: ") if regulir == "-": self.volume -= 1 if self.volume <0: print("Вы полностью выключили звук") self.volume = 0 elif regulir == "+": self.volume += 1 if self.volume > 15: print("Вы включили максимальную громкость") self.volume = 15 else: print("Такой кнопки нет") regulir = input("Введите + или - для увеличения\уменьшения громкости: ") def __str__(self): rep = "На данный момент у вас включён: " +str(self.channel) +".\n" rep += "Уровень громкости телевизора сейчас составляет: " +str(self.volume) +" единиц." return rep def main_part(): print("Вы включили телевизор") zombiebox_name = input("Кстати, какая марка у вашего телевизора? ") if zombiebox_name == "": print("Так и скажите, что китайский") tvisor = Zombiebox(zombiebox_name) turn = None while turn != "0": print \ (""" Симулятор телевизора 0 - Выключить 1 - Выбрать канал 2 - Изменить громкость 3 - Узнать, какой канал и громкость на данный момент """) turn = input("Ваш выбор: ") if turn == "1": tvisor.channels() elif turn == "2": tvisor.sound() elif turn == "3": print(tvisor) elif turn == "0": print("Выключение...") else: print("В меню нет такого пункта") main_part() input("Press Enter key to exit")
from math import floor, sqrt # Beatty's sequence with sqrt(2) # General form would be for n wanted instances # sum of floor(sqrt(2)*k) for k to n # Even more general # S(a, n) where a is the irrational and n is the amount of inputs # S(a,n) = summation k=1 to n floor(a*k) # https://mathworld.wolfram.com/BeattySequence.html # https://math.stackexchange.com/questions/2052179/how-to-find-sum-i-1n-left-lfloor-i-sqrt2-right-rfloor-a001951-a-beatty-s # 1<sqrt(2)<2 so the formula a^-1 + b^-1 = 1 applies # floor(an) and floor(bn) partition all counting numbers # To sum all counting numbers up to n # let m = floor(a*n) # S(a, n) + S(b, floor(m/b)) = sum of k=1 to n = m(m+1)/2 # S(a, n) = m(m+1)/2 - s(b, floor(m/b)) # Have to use this so it is not cut off by rounding in computer. Equal to sqrt(2)-1 * 10**100 minus_sqrt2 = 4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727 # Has to handle up to 10^100 as an input, so brute force won't work def solution(s): return str(solver(s)) def solver(s): # Number of iterations n = int(s) # If 0 iterations just return 0 if n == 0: return 0 # If 1 iteration just return 1 if n == 1: return 1 # N prime n_prime = (minus_sqrt2 * n) // 10**100 # Sum sum_of_beatty = n*n_prime + n*(n+1)/2 - n_prime*(n_prime+1)/2 sum_of_beatty -= solver(n_prime) return int(sum_of_beatty) print(solution('5'))# 19 print(solution('77'))# 4208 print(solution(str(10**100)))
import obtain_symbols import finlib import backtesters import pandas as pd import sys import os from pandas_datareader import data class SymbolsHelper: """ A class that holds important information for calculating misc. commands, or that holds information so that it doesn't need to be redownloaded and thus increasing function speeds. """ def __init__(self): # This dictionary holds a dataframe of historical information for # each symbol that needs it. This dict looks like this: # {'symbol1': dataframe1, 'symbol2': dataframe2, ...} self.symbol_data_dict = {} # This dictionary holds the relevant backtesters that have last been # used for each symbol. This is in part necessary because it helps # the program realize what type of backtester (Hodl, MACD, SMA, etc) # the portfolio used before so that previously finalized backtesters # don't change. All of these backtesters are classess that are built # in the file backtesters.py. This dict looks like this: # {'symbol1': backtester1, 'symbol2': backtester2, ...} self.symbol_backtesters_dict = {} # This dictionary holds all industries used in the main portfolio, as # well as all symbols used in each industry. This dict looks like this: # {'industry1': ['sym1', 'sym2'...], 'industry2': ['sym3'...]...} self.obtained_symbols_dict = None def run_backtester(backtester, symbol_data): """ This function uses the data in symbol_data, as well as the buying/selling/ holding conditions in backtester, to run through historical data on a symbol and calculate the performance of this backtester over the days of stock info in symbol_data. :param backtester: An initialized backtester class from backtesters.py :param symbol_data: A dataframe obtained from yahoo finance containing information on a stock's historical trade data :return: The backtester in the input stores all of the information, so this function does not need to return anything. """ for i in range(len(symbol_data)): # Read in symbol data # Daily information, consolidated into a dictionary. price_info = {'Date': symbol_data.index[i], 'Adj Close': float(symbol_data['Adj Close'][i]), 'High': float(symbol_data['High'][i]), 'Low': float(symbol_data['Low'][i]), 'Open': float(symbol_data['Open'][i]), 'Close': float(symbol_data['Close'][i]), 'Volume': float(symbol_data['Volume'][i])} # The action that the backtester decides to do, given the price # information. This can be 'buy', 'sell', or 'hold'. action = backtester.on_market_data_received(price_info) # Running this action back into the backtester to simulate market # actions. backtester.buy_sell_or_hold(price_info, action) # Create the dataframe that will hold all the symbol's and trading # data. backtester.create_dataframe() return def examine_backtesters(symbol_data, cash, backtester_names=None): """ This function initializes and runs (through the helper function run_backtester) one/multiple backtesters, and returns the backtester with the highest sharpe ratio. :param symbol_data: A dataframe obtained from yahoo finance containing information on a stock's historical trade data :param cash: Int; the amount of money that we can use inside one backtester :param backtester_names: A list of strings containing the names of backtesters that the programmer wants to initialize to test. If None, this function initializes a preset list of backtesters (see backtesters.backtesters(cash)) :return: The backtester that obtained the higehst sharpe ratio over the symbol_data. """ # First, we have to initialize all of the backtesters that we have. if backtester_names is not None: list_of_backtesters = [] for name in backtester_names: list_of_backtesters.append(backtesters.find_backtester(name, cash)) else: list_of_backtesters = backtesters.backtesters(cash) # Return the best backtester, where best = highest sharpe ratio res_backtester = None res_backtester_sharpe = None for backtester in list_of_backtesters: run_backtester(backtester, symbol_data) backtesters.organize_backtester(backtester) sharpe_ratio = finlib.tangency_summary(backtester.historical_data) if res_backtester_sharpe is None or \ res_backtester_sharpe < sharpe_ratio: res_backtester = backtester res_backtester_sharpe = sharpe_ratio print("Backtester chosen:", res_backtester.name) return res_backtester def run_tangency_portfolio(wts_tangency, cash, symb_help): """ This function calculates the excess returns of a single-industry tangency portfolio by running previously chosen backtesters with updated cash allotments. :param wts_tangency: A pandas series that contains the respective weight for each symbol inside of an industry. The symbol's weight * cash = the amount of money allocated to that symbol. :param cash: Int; amount of money allocated across the entire industry, to be distributed in different weights to each symbol. :param symb_help: Initialized SymbolHelper class that contains information on the symbols being used + their backtesters. :return: tangency_res, a dataframe that holds net cash + holdings per day for the industry as a total, after weighing each symbol. """ tangency_res = None # A dataframe holding cash + holdings per day # Let's loop through all symbols in the tangency portfolio we found, run # their respective backtester, and append to tangency_res their cash + # holdings per day. for symbol, weight in wts_tangency.iteritems(): allocation = cash * weight bt_name = symb_help.symbol_backtesters_dict[symbol].name bt = backtesters.find_backtester(bt_name, allocation) symbol_data = symb_help.symbol_backtesters_dict[symbol].historical_data run_backtester(bt, symbol_data) backtesters.organize_backtester(bt) if tangency_res is None: tangency_res = pd.DataFrame(data=bt.list_total, index=bt.historical_data.index, columns=['Total']) else: tangency_res['Total'] = tangency_res['Total'] + \ bt.list_total # Calculating excess return finlib.excess_returns(tangency_res, risk_free_rate=0.05/252, column_name='Total') return tangency_res def run_final_tangency_portfolio(main_wts, industry_wts, cash, symb_help): """ This function calculates the excess returns of a multi-industry tangency tangency portfolio by running previously chosen backtesters with updated cash allotments. :param main_wts: A pandas series that contains the respective weight for each industry inside of the main portfolio. The industry's weight * cash = the amount of money allocated to that industry :param industry_wts: A pandas series that contains the respective weight for each symbol inside of an industry. The symbol's weight * industry's cash = the amount of money allocated to that symbol. :param cash: Int; amount of money allocated across the entire portfolio, to be distributed in different weights to each industry, and further distributed in different weights to each symbol. :param symb_help: initialized SymbolHelper class that contains information on the symbols being used + their backtesters. :return: daily_total, a dataframe that holds net cash + holdings per day for the portfolio as a total, after weighing each industry and symbol. """ print("\n\n*** Running backtest of main tangency portfolio to see its results") daily_total = None # A dataframe holding cash + holdings per day # Let's loop through all industries in the tangency portfolio we found, run # the function 'run_tangency_portfolio on each industry, and append to # tangency_res each industry's cash + holdings per day. for industry, weight in main_wts.iteritems(): industry_cash = cash * weight print("Running tangency portfolio for (" + industry + ") with $" + str(industry_cash)) tangency_res = run_tangency_portfolio(industry_wts[industry], industry_cash, symb_help) if daily_total is None: daily_total = pd.DataFrame(data=tangency_res['Total'], index=tangency_res.index, columns=['Total']) else: daily_total['Total'] = daily_total['Total'] + tangency_res['Total'] # Calculating excess return finlib.excess_returns(daily_total, risk_free_rate=0.05/252, column_name='Total') # Summary statistics print("\nInitial investment in main tangency portfolio:", cash) print("Total profit:", round(daily_total.iloc[-1]['Total'] - cash, 2)) print("Annualized sharpe ratio:", round(finlib.get_annualized_sharpe_ratio_df(daily_total), 3)) return daily_total def run_out_of_sample(main_wts, industry_wts, cash, start_date, end_date, symb_help): """ This function organizes the functions necessary to run a finished portfolio out of sample. :param main_wts: Pandas series; how each industry is weighted. :param industry_wts: Dictionary where the key is a string of an industry, and the value is a pandas series holding how each series in the industry is weighted. :param cash: Int; the amount of cash to be invested across all industries. :param start_date: String; the starting date for running out of sample data. YYYY-mm-dd. :param end_date: String; the ending date for running out of sample data. YYYY-mm-dd. :param symb_help: Initialized SymbolHelper class that contains information on the symbols being used + their backtesters. :return: daily_total, a dataframe holding cash + holdings per day for the entire portfolio. """ print("\n\n*** Now running the portfolio on out-of-sample data") print("Start date: " + start_date + ", end date: " + end_date) daily_total = None # A dataframe holding cash + holdings per day for industry, industry_wt in main_wts.iteritems(): industry_cash = cash * industry_wt print("Running tangency portfolio for (" + industry + ") with $" + str(industry_cash)) for symbol, symbol_wt in industry_wts[industry].iteritems(): # print('Calculating investment in', symbol) symbol_cash = industry_cash * symbol_wt # Initialize new 'backtester' that is acting as out-of-sample data # First, find what kind of backtester we used in-sample: bt_name = symb_help.symbol_backtesters_dict[symbol].name bt = backtesters.find_backtester(bt_name, symbol_cash) # Then, run the backtester on out-of-sample data symbol_data = \ symb_help.symbol_data_dict[symbol].loc[start_date:end_date, :] run_backtester(bt, symbol_data) backtesters.organize_backtester(bt) # Finally, put the info we got into daily_total if daily_total is None: daily_total = pd.DataFrame(data=bt.list_total, index=bt.historical_data.index, columns=['Total']) else: daily_total['Total'] = daily_total['Total'] + bt.list_total # Calculating excess returns finlib.excess_returns(daily_total, risk_free_rate=0.05 / 252, column_name='Total') # Summary stats print("\nInitial investment in main tangency portfolio:", cash) print("Total profit:", round(daily_total.iloc[-1]['Total'] - cash, 2)) print("Annualized sharpe ratio:", round(finlib.get_annualized_sharpe_ratio_df(daily_total), 3)) return daily_total def get_symbol_data(start_date, end_date, num_symbols, symb_help, testing=False): """ This function gets all of the symbols for the soon-to-be-created portfolio, as well as downloading all of the data necessary for each of those symbols. :param start_date: String; the starting date for information that should be downloaded for each symbol. YYYY-mm-dd :param end_date: String; the ending date for information that should be downloaded for each symbol. YYYY-mm-dd :param num_symbols: Int; the number of symbols to find for each industry. :param symb_help: Initialized SymbolHelper class that contains information on the symbols being used + their backtesters. :param testing: Bool; a variable that helps speed up the function when testing. If True, instead of finding symbols for each industry, only the first two industries are used. Default is False. :return: Nothing; all information needed is saved into symb_help """ print("\n*** Getting relevant data for every symbol used.") # Getting symbols from each GICS industry. # It looks like such: {'industry1': ['sym1', 'sym2'], 'industry2': ['sym3']} symb_help.obtained_symbols_dict = obtain_symbols.obtain_symbols( num_symbols=num_symbols, testing=testing) # Get data for each symbol print("\nDownloading financial data from yahoo for each symbol") for industry in symb_help.obtained_symbols_dict: # A list of symbols to be removed in case there is something wrong with # yahoo finance; see the if statement below for more info. removed_symbols = [] for symbol in symb_help.obtained_symbols_dict[industry]: print("Working with:", symbol) symbol_data = finlib.load_financial_data(symbol=symbol, start_date=start_date, end_date=end_date, save=True) # Correct number of trading days, to check if dataframe has all info num_trading_days = finlib.num_nyse_trading_days(start_date, end_date) # Collected number of trading days symbol_days = symbol_data.loc[start_date:end_date, :].shape[0] if symbol_days < num_trading_days: # It's possible the symbol data isn't lining up because the # downloaded data we have is not up to date. As such, let's # check if downloading the data online fixes that. test_df = data.DataReader(symbol, 'yahoo', start=start_date, end=end_date) if test_df.loc[start_date:end_date, :].shape[0] == \ num_trading_days: print("The data we downloaded is not up to date, so " "it should be redownloaded.") # In this case it's because the downloaded data we have is # not up to date. As such, let's redownload all of it and # redo our info that we got. file_path = '../symbol_data/' + symbol + '.pkl' os.remove(file_path) symbol_data = finlib.load_financial_data(symbol, file_path, start_date, None, True) symbol_days = symbol_data.loc[start_date:end_date, :].shape[0] if symbol_days < num_trading_days: # We couldn't find all of the required data for that symbol # becasue of an error in Yahoo Finance. As such, we're going # to remove that symbol from our list and get a different # symbol from the same industry. print(symbol + " doesn't have full yahoo finance info, toss and" " get new symbol") new_symbol = obtain_symbols.new_symbol( symbol, industry, symb_help.obtained_symbols_dict[industry]) if new_symbol is None: # This happens when the program tries to find a new symbol, # but there aren't new symbols in the S&P500 to use (aka all # other symbols are already in the list). print("No new symbol found b/c all others are being used") else: # Found a new symbol print("New symbol: " + new_symbol) symb_help.obtained_symbols_dict[industry].append(new_symbol) removed_symbols.append(symbol) continue # We might have more info than we need, so only get info # past the starting date. symb_help.symbol_data_dict[symbol] = symbol_data.loc[start_date:, :] for symbol in removed_symbols: # We do this at the end so that we don't mess up the for loop above. symb_help.obtained_symbols_dict[industry].remove(symbol) def get_backtester_data(start_date, end_date, cash, symb_help): """ This function loops through all symbols listed in symb_help in order to initialize their backtesters and run them as well. :param start_date: String; the starting date for the backtester's data. :param end_date: String; the ending date for the backtester's data. :param cash: Int; the amount of cash to use in the backtester. :param symb_help: Initialized SymbolHelper class that contains information on the symbols being used + their backtesters. :return: Nothing; all relevant information is saved into symb_help. """ print("\n*** Initializing and running backtesters for each symbol") for symbol in symb_help.symbol_data_dict: symbol_data = \ symb_help.symbol_data_dict[symbol].loc[start_date:end_date, :] print("Running backtesters for", symbol) best_backtester = examine_backtesters(symbol_data, cash=cash) symb_help.symbol_backtesters_dict[symbol] = best_backtester def compare_against_spy(tangency_res, cash, start_date, end_date): """ This function helps compare both in-sample and out-of-sample portfolio data against holding SPY, the comparison benchmark used for this trading strategy. It figures out how well SPY did profit-wise on its own, as well as running a regression analysis between SPY and tangency_res. :param tangency_res: A dataframe holding cash + holdings per day; the results of the portfolio that will be comapred against SPY. :param cash: Int; the amount of cash to be used when holding SPY. :param start_date: String; the starting date for holding SPY. YYYY-mm-dd. :param end_date: String; the ending date for holding SPY. YYYY-mm-dd. :return: 1) spy_backtester: The backtester used when testing how well SPY did in the timeframe given. It holds information that can be useful for further computations. 2) regression_summary: A dictionary holding information pertaining to the regression computed between SPY and tangency_res. """ print("\n\n*** Comparing results against spy") # Download the data for the regressor print("Working with: SPY") spy = finlib.load_financial_data('SPY', start_date=start_date, end_date=end_date) spy = spy.loc[start_date:end_date, :] # Now let's compare profits spy_backtester = examine_backtesters(spy, cash, backtester_names=['HODL']) summary = finlib.backtester_summary(spy_backtester) print('Initial investment:', summary['Initial Investment']) print('Profit:', round(summary['Profit'], 2)) print('Annualized sharpe ratio:', round(summary['Annualized Sharpe Ratio'], 3)) # Running a regression against SPY excess_returns = pd.DataFrame(data=tangency_res['Excess Return'], index=tangency_res.index, columns=['Excess Return']) finlib.excess_returns(spy, 0.05 / 252, column_name='Adj Close') regression_summary = finlib.regression_analysis( excess_returns, spy) return spy_backtester, regression_summary def setup_backtesters(cash, num_symbols, start_date, end_date, testing=False): """ The main function that helps create and analyze the randomly generated portfolio. All functions above are used in this function. :param cash: Int; the amount of money to be invested in the portfolio. :param num_symbols: Int; the number of symbols to use in each industry. :param start_date: String; the starting date for in-sample data. YYYY-mm-dd. :param end_date: String; the ending date for in-sample data. YYYY-mm-dd. :param testing: Bool; a variable that helps speed up the function when testing. If True, instead of finding symbols for each industry, only the first two industries are used. Default is False. :return: 1) wts_tangency_final: A dataframe holding the weights of each industry for the final portfolio. 2) industry_wts: A dictionary, where each key is an industry, and each value is the industry's weighing for their symbols. 3) tangency_res_final: a dataframe that holds net cash + holdings per day for the portfolio as a total, after weighing each industry and symbol. 4) spy_res: The backtester used when testing how well SPY did in the timeframe given. 5) symbol_helper: Initialized SymbolHelper class that contains information on the symbols being used + their backtesters. 6) spy_summary: A dictionary holding information pertaining to the regression computed between SPY and the portfolio's results. """ symbol_helper = SymbolsHelper() # Getting relevant data for every symbol used # End date is none because we want to download all data available get_symbol_data(start_date=start_date, end_date=None, num_symbols=num_symbols, testing=testing, symb_help=symbol_helper) # Initializing and running backtesters for each symbol get_backtester_data(start_date=start_date, end_date=end_date, cash=cash, symb_help=symbol_helper) print("\n*** Computing tangency portfolios for each industry") industry_wts = {} # {industry: industry_weight (% of cash to allocate)} for industry in symbol_helper.obtained_symbols_dict: excess_returns = None # Dataframe holding excess returns for each ind. sharpe_ratio_dict = {} for symbol in symbol_helper.obtained_symbols_dict[industry]: # Get historical data from each symbol's backtester hist_data = \ symbol_helper.symbol_backtesters_dict[symbol].historical_data if excess_returns is None: # Initializing the dataframe excess_returns = pd.DataFrame(index=hist_data.index) excess_returns[symbol] = hist_data['Excess Return'] sharpe_ratio_dict[symbol] = \ finlib.get_annualized_sharpe_ratio_df(hist_data) # Compute tangency portfolio wts_tangency, mu_tilde, sigma = \ finlib.compute_tangency(excess_returns, diagonalize=False) sharpe = finlib.get_annualized_sharpe_ratio_wts(wts_tangency, mu_tilde, sigma) print("Theoretical Sharpe ratio for " + industry + ":", round(sharpe, 3)) industry_wts[industry] = wts_tangency industry_excess_returns = None print("\n*** Getting excess returns from each industry portfolio") for industry in industry_wts: print("\nRunning tangency portfolio for (" + industry + ") with $" + str(cash)) tangency_res = run_tangency_portfolio(industry_wts[industry], cash, symbol_helper) profit = tangency_res.iloc[-1]['Total'] - cash annualized_sharpe_ratio = \ finlib.get_annualized_sharpe_ratio_df(tangency_res) print("Total profit:", round(profit, 2)) print("Annualized sharpe ratio:", round(annualized_sharpe_ratio, 3)) series_data = pd.Series(tangency_res['Excess Return'], index=tangency_res.index, name=industry) if industry_excess_returns is None: # Initializing the dataframe industry_excess_returns = pd.DataFrame(data=series_data, index=tangency_res.index) else: industry_excess_returns = pd.concat([industry_excess_returns, series_data], axis=1) # Compute tangency portfolio wts_tangency_final, mu_tilde, sigma = finlib.compute_tangency( industry_excess_returns, diagonalize=False) sharpe = finlib.get_annualized_sharpe_ratio_wts(wts_tangency_final, mu_tilde, sigma) print("\nTheoretical sharpe ratio for the main tangency portfolio:", round(sharpe, 3)) # Running backtest of main tangency portfolio to see its results tangency_res_final = run_final_tangency_portfolio( wts_tangency_final, industry_wts, cash, symbol_helper ) # Comparing in-sample results against spy spy_res, spy_summary = compare_against_spy(tangency_res_final, cash, start_date=start_date, end_date=end_date) return wts_tangency_final, industry_wts, tangency_res_final, spy_res, \ symbol_helper, spy_summary def run_backtesters_out_of_sample(port_wts, indust_wts, cash, start_date, end_date, symb_help): """ This function runs a created portfolio on data between start_date and end_date with those dates typically being out of sample. It also runs these results against how well SPY did in the same time period. :param port_wts: Pandas series; how each industry is weighted across the entire portfolio. :param indust_wts: Dictionary where the key is a string of an industry, and the value is a pandas series holding how each series in the industry is weighted. :param cash: Int; The amount of money to invest into the portfolio; an equal amount is also invested into SPY. :param start_date: String; the starting date to analyze the portfolio/SPY. YYYY-mm-dd. :param end_date: String; The ending date to analyze the portfolio/SPY. YYYY-mm-dd. :param symb_help: Initialized SymbolHelper class that contains information on the symbols being used + their backtesters. :return: 1) tangency_res: a dataframe that holds net cash + holdings per day for the portfolio as a total, after weighing each industry and symbol. 2) spy_res: SPY's backtester that was run on data between start_date and end_date. """ # Running the portfolio on out of sample data tangency_res = run_out_of_sample(port_wts, indust_wts, cash, start_date, end_date, symb_help) # Comparing out of sample results against spy spy_res, _ = compare_against_spy(tangency_res, cash, start_date=start_date, end_date=end_date) return tangency_res, spy_res
def seats(data): for line in data: row_min = 0 row_max = 128 col_min = 0 col_max = 8 for c in line: if c == "F": row_max -= (row_max - row_min) // 2 elif c == "B": row_min += (row_max - row_min) // 2 elif c == "L": col_max -= (col_max - col_min) // 2 elif c == "R": col_min += (col_max - col_min) // 2 else: yield row_min * 8 + col_min def part1(data): return max(seats(data)) def part2(data): found = set(i for i in seats(data)) for i in range(min(found), max(found)): if i not in found: return i if __name__ == "__main__": import sys #print(part1(sys.stdin)) print(part2(sys.stdin))
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ # Base conditions if haystack is None or needle is None: return -1 # Special case if haystack == needle: return 0 # Length of the needle needleLength = len(needle) # Loop through the haystack and slide the window for i in range(len(haystack) - needleLength + 1): if haystack[i:i + needleLength] == needle: return i return -1
v = 25 u = 0 t = 10 a = (v-u)/t print("We have,\n\t v = u + at") print("or, {0} = {1} + a{2}".format(v, u, t)) print("or, a = ({0}-{1})/{2}".format(v, u, t)) print("hence, a = {0}".format(a))
import numpy as np def get_gradient(data, m_slope, b_intercept, learning_rate): slope_sum = 0 intercept_sum = 0 len_data = float(len(data)) for i in range(len(data)): slope_sum += (-data[i][0]) * (data[i][1] - (m_slope * data[i][0] + b_intercept)) * (2/len_data) intercept_sum += (data[i][1] - (m_slope * data[i][0] + b_intercept)) * (-2/len_data) return [(m_slope - (learning_rate * slope_sum)), (b_intercept - (learning_rate * intercept_sum))] def run_linear_regression(data, m_slope, b_intercept, learning_rate, num_iters): print "Initial values m - %f, b - %f" %(m_slope, b_intercept) for i in range(num_iters): print "Iteration %d, m - %f, b - %f" %(i, m_slope, b_intercept) m_slope, b_intercept = get_gradient(data, m_slope, b_intercept, learning_rate) print "Final values m - %f, b - %f" %(m_slope, b_intercept) def main(): data = np.genfromtxt("data.csv", delimiter=",") # Initializing hyperparameters m_slope = 0 b_intercept = 0 learning_rate = 0.0001 num_iters = 200 run_linear_regression(data, m_slope, b_intercept, learning_rate, num_iters) if __name__ == "__main__": main()
import sys int = int(sys.argv[1]) if int % 2 == 0: print "even" else: print "odd" if int < 50 and int > 0: print "Minor" elif int >= 50 and int < 1000: print "Major" else: print "Severe"
def fibo(n: int) -> int: if n <= 1: return 1 if n == 2: return 1 return fibo(n - 1) + fibo(n - 2) num = int(input("Enter number of fibonacci to print ")) for i in range(1, num + 1): print(fibo(i))
#!/usr/bin/env python3 import sys #print(sys.argv) try: salary = int(sys.argv[1]) except: print("Parameter Error") exit() if salary<3500: salary_need = 0 else: salary_need = salary-3500 if salary_need<=1500: salary_push = salary_need*0.03 elif 1500<salary_need<=4500: salary_push = salary_need*0.1-105 elif 4500<salary_need<=9000: salary_push = salary_need*0.2-555 elif 9000<salary_need<=35000: salary_push = salary_need*0.25-1005 elif 35000<salary_need<55000: salary_push = salary_need*0.3-2755 elif 55000<salary_need<80000: salary_push = salary_need*0.35-5505 elif salary_need>80000: salary_push = salary_need*0.45-13505 print(format(salary_push,".2f"))
#!/usr/bin/env python3 import sys #print(sys.argv) def salary_calculate(salary_raw): salary = salary_raw*(1-0.165) if salary<3500: salary_need = 0 else: salary_need = salary-3500 if salary_need<=1500: salary_push = salary_need*0.03 elif 1500<salary_need<=4500: salary_push = salary_need*0.1-105 elif 4500<salary_need<=9000: salary_push = salary_need*0.2-555 elif 9000<salary_need<=35000: salary_push = salary_need*0.25-1005 elif 35000<salary_need<55000: salary_push = salary_need*0.3-2755 elif 55000<salary_need<80000: salary_push = salary_need*0.35-5505 elif salary_need>80000: salary_push = salary_need*0.45-13505 return (format((salary-salary_push),'.2f')) if __name__=='__main__': try: num_salary = sys.argv[1:] name_dict={} for i in num_salary: temp=i.split(':') name_dict[temp[0]]=int(temp[1]) for i in name_dict.keys(): print(str(i)+':'+str(salary_calculate(name_dict[i]))) except: print('Parameter Error') exit() ''' try: salary = int(sys.argv[1]) except: print("Parameter Error") exit() '''
# This is a library of regression model implementations. import numpy as np # Ridge regression - i.e. L2 regularised linear regression # X_ are features, y are targets. Both should be numpy arrays. # C is the regularisation constant. # If X_ already contains a bias column (a column of 1s) you can set add_bias to False. # Note X_ must be shaped so that the columns are features, and the rows are samples of the data. # This function relies on numpy for linear algebra. def ridge_regression(X,y, C=0, add_bias = True): if(C<0): raise ValueError("Regularisation must be non-negative.") if(add_bias): X_ = np.ones((X.shape[0], X.shape[1]+1)) X_[:,:-1] = X else: X_ = X Xt = np.matrix.transpose(X_) XtX = np.dot(Xt,X_) I = np.identity(XtX.shape[0]) regularised = XtX + C*I try: inverse = np.linalg.inv(regularised) except np.linalg.LinAlgError as err: if("Singular matrix" in str(err)): print("Product of feature matrix and its transpose is non-invertible.") print("Try setting regularisation to a non-zero value.") return else: raise inverseXt = np.dot(inverse, Xt) return np.dot(inverseXt, y) # Lp regularised regression. With p = 1 this is known as Lasso. # Note this relies on scipy's optimize.minimize function. # This optimisation could be achieved with gradient descent. # Note this only works with 1-dimensional targets. # It is simple to extend to n-dimensional targets by applying this on each dimension. # i.e. To predict y = (y1,y2) as a linear function of X, predict y1 and y2 individually. def lp_regression(X,y, C = 1.0, p = 1.0, add_bias = True, max_iter = 1000): if(C<0): raise ValueError("Regularisation must be non-negative.") if(add_bias): X_ = np.ones((X.shape[0], X.shape[1]+1)) X_[:,:-1] = X else: X_ = X Xt = np.transpose(X_) XtX = np.dot(Xt,X) Xty = np.dot(Xt,y) W = np.random.normal(size = (X_.shape[1], 1)) lpnorm = np.power(np.sum(np.power(np.absolute(W),p)),1/p) def loss(W): return np.linalg.norm(y - np.dot(X_,W)) + C * lpnorm from scipy.optimize import minimize return minimize(loss, W, options = {'maxiter':max_iter}).x # K-nearest neighbours regression. # Take the average of the k nearest neighbours as a prediction. # This can also be implemented with weighting, e.g. based on a kernel. # This would require knns to return the distances between neighbours. # Note this is defined to only regress one point at a time. # To regress multiple points you can simply iterate this function. from mathematics import euclidean_metric def knn_regression(x,k, X, y, metric = euclidean_metric): from classification import knns knn = knns(x,k, X, y, metric = metric) return np.mean(knn)
class Contact: def __init__(self, name, surename, phone, favorite=False, *args, **kwargs): self.name = name self.surename = surename self.phone = phone self.favorite = favorite self.args = args self.kwargs = kwargs def __str__(self): if self.favorite is True: self.favorite = 'Да' else: self.favorite = 'Нет' def kwarg(x): kwarg_list = list() for x_name, x_text in x.items(): kwarg_list.append(f' {x_name}: {x_text}') return '\n'.join(kwarg_list) info = f'Имя: {self.name}\nФамилия: {self.surename}\nТелефон: {self.phone}\nВ избранных: {self.favorite}\n' \ f'Дополнительная информация:\n{kwarg(self.kwargs)}' return info class PhoneBook: contact_list = list() def __init__(self, phonebook): self.phonebook = phonebook def new_contact(self, name, surename, phone, favorite=False, *args, **kwargs): new_contact_class = Contact(name, surename, phone, favorite, *args, **kwargs) self.contact_list.append(new_contact_class) return 'Контакт добавлен' def print_contact(self, contact_list_index): result = print(PhoneBook.contact_list[int(contact_list_index)]) return result def delete_contact_by_phone_number(self, phonenumber): for contact in self.contact_list: if contact.phone == phonenumber: self.contact_list.remove(contact) result = print(f'Контакт с телефонным номером "{phonenumber}" удален из телефонной книги') return result def all_favorite_contacts(self): favorite_contact_list = list() for contact in self.contact_list: if contact.favorite is True: favorite_contact_list.append(contact.phone) str_list = '\n'.join(favorite_contact_list) result = print(f'Список избранных номеров:\n{str_list}') return result def contact_by_name_surename(self, cname, csurename): i = 1 print(f'Список контактов с именем {cname} и фамилией {csurename}:') for contact in self.contact_list: if contact.name == cname and contact.surename == csurename: print(f'{i}\n{contact}') i += 1 # Создание телефонной книги phonebook = PhoneBook('Справочник') # Создание контактов phonebook.new_contact('Vladimir', 'Simigin', '+79141785435', telegram='@simigin', email='v_mail@gmail.com') phonebook.new_contact('Anastasia', 'Plazova', '+79238765789', favorite=True, telegram='@plazova', email='pl_mail@gmail.com') phonebook.new_contact('Nikolai', 'Novikov', '+79140987878', favorite=True, telegram='@novikov', email='n_mail@gmail.com') phonebook.new_contact('Artemiy', 'Lebedev', '+79152334555', favorite=True, telegram='@lebedev', email='l_mail@gmail.com') phonebook.new_contact('Vladimir', 'Polskiy', '+79169008776', telegram='@polskiy', email='po_mail@gmail.com') phonebook.new_contact('Artemiy', 'Lebedev', '+79152339875', favorite=True, telegram='@lebedev123', email='lebed_mail@gmail.com') # Вывод всех избранных номеров phonebook.all_favorite_contacts() # Вывод информации по контакту phonebook.print_contact(0) # Удаление контакта по номеру телефона phonebook.delete_contact_by_phone_number('+79141785435') # Вывод информации по контакту phonebook.print_contact(0) # Вывод списка кнтактов по имени, фамилии phonebook.contact_by_name_surename('Artemiy', 'Lebedev')
#!/usr/bin/python # -*- coding: UTF-8 -*- # @date: 2017/9/14 9:03 # @name: K-MeansPractice # @author:vickey-wu # practice of K-Means algorithm import pandas as pd from sklearn.cluster import KMeans input_flie = "E:/pythonProcess/chapter5/demo/data/consumption_data.xls" output_file = "E:/pythonProcess/chapter5/demo/data/consumption_result.xls" # cluster category k = 3 # iteration os cluster iteration = 500 data = pd.read_excel(input_flie, index_col="Id") # standardization data data_zs = 1.0 * (data-data.mean())/data.std() # separate as "k" clusters and "4" erupt simultaneously and iteration equal to "iteration" model = KMeans(n_clusters=k, n_jobs=4, max_iter=iteration) # begin to cluster model.fit(data_zs) # count nums of each category category_num = pd.Series(model.labels_).value_counts() # find cluster center cluster_center = pd.DataFrame(model.cluster_centers_) # horizontal connect data to get num of category of cluster center r = pd.concat([category_num, cluster_center], axis=1) r.columns = list(data.columns) + ["category_num"] # print each sample's category r = pd.concat([data, pd.Series(model.labels_, index=data.index)], axis=1) r.columns = list(data.columns) + ["category_cluster"] r.to_excel(output_file) # # #使用K-Means算法聚类消费行为特征数据 # # import pandas as pd # # # def k_means(): # #参数初始化 # inputfile = 'E:/pythonProcess/chapter5/demo/data/consumption_data.xls' #销量及其他属性数据 # outputfile = 'E:/pythonProcess/chapter5/demo/data/data_type.xls' #保存结果的文件名 # k = 3 #聚类的类别 # iteration = 500 #聚类最大循环次数 # data = pd.read_excel(inputfile, index_col='Id') #读取数据 # data_zs = 1.0*(data - data.mean())/data.std() #数据标准化 # # from sklearn.cluster import KMeans # model = KMeans(n_clusters = k, n_jobs = 4, max_iter = iteration) #分为k类,并发数4 # model.fit(data_zs) #开始聚类 # # #简单打印结果 # r1 = pd.Series(model.labels_).value_counts() #统计各个类别的数目 # r2 = pd.DataFrame(model.cluster_centers_) #找出聚类中心 # r = pd.concat([r2, r1], axis = 1) #横向连接(0是纵向),得到聚类中心对应的类别下的数目 # r.columns = list(data.columns) + [u'类别数目'] #重命名表头 # print(r) # # #详细输出原始数据及其类别 # r = pd.concat([data, pd.Series(model.labels_, index = data.index)], axis = 1) #详细输出每个样本对应的类别 # r.columns = list(data.columns) + [u'聚类类别'] #重命名表头 # r.to_excel(outputfile) #保存结果 # # density_plot(data, k) # # pic_output = 'E:/pythonProcess/chapter5/demo/data/pd_' # 概率密度图文件名前缀 # for i in range(k): # density_plot(data[r[u'聚类类别'] == i], k).savefig(u'%s%s.png' % (pic_output, i)) # # # def density_plot(data, k): #自定义作图函数 # import matplotlib.pyplot as plt # plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签 # plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号 # p = data.plot(kind='kde', linewidth = 2, subplots = True, sharex = False) # [p[i].set_ylabel(u'密度') for i in range(k)] # plt.legend() # return plt # # # if __name__ == '__main__': # k_means()
import sys import datetime import time import logging import postgres_db import twitter # The limits on how many tweets back we can go are not well documented. It appears # that we can never get more than 200. So might as well ask for more. NUMBER_OF_TWEETS_TO_REQUEST = 300 # This fetches recent tweets and persists them, meaning stores them in the database. def persist_tweets(raw_tweet_table_name, persistence_run_table_name): run_start = datetime.datetime.utcnow() postgres_client = postgres_db.postgres_client() postgres_client.begin() # Find the last (highest-id) old tweet, meaning of a tweet we've already persisted. answer = postgres_client.get_max_id() print ("answer for max id = " + str(answer)) if answer == None: # Special case of empty table. Use an arbitrary old tweet id. last_old_tweet_id = '1386138077077381121' else: last_old_tweet_id = answer; logging.info ("last_old_tweet_id = " + str(last_old_tweet_id)) # We want to get all new tweets, that is, all tweets that we don't # already have. The normal way to accomplish this would be to pass # last_old_tweet_id. However, this is not guaranteed to get *all* # new tweets, as Twitter limits your lookback. For example, suppose # you got the first 1000 tweets. Later, after 2000 more tweets have # been added, you ask for all new tweets. Instead of providing all # of them (#1001-3000), it might provide only the last part of that # set, e.g. #1573-3000. # There is nothing we can do after the fact about those missing tweets. # To prevent/reduce the problem, we can run this more frequently. What we # can do in this code is to *detect* the problem. The basic method is to # ask for every tweet from last_old_tweet_id forward, then to see if we # the ones we get back include that last_old_tweet, an overlap of 1 tweet. We # check for the old one, note whether it was present, and delete it if it is. # There is a twist; the Twitter interface is inflexible on the strictness # of the inequality. That is, it uses "greater than" and doesn't support # "greater than or equal to". Therefore we pass an id slightly earlier # than the last id. To get this, we just subtract 1. This almost certainly # is not a legitimate id, but works in Twitter's filters and doesn't violate # anything in the interface. last_old_tweet_id_as_int = int(last_old_tweet_id) tweet_id_to_pass = last_old_tweet_id_as_int - 1 #print ("tweet_id_to_pass = " + str(tweet_id_to_pass)) tweet_list = ta.get_tweets(NUMBER_OF_TWEETS_TO_REQUEST, tweet_id_to_pass) # Determine the highest and lowest ids and times, and look for the overlapped one discussed above. highest_id = 0 lowest_id = sys.maxsize lowest_datetime = datetime.datetime.strptime('9999-01-01','%Y-%m-%d') highest_datetime = datetime.datetime.strptime('2000-01-01','%Y-%m-%d') copy_of_tweet_list = [] overlap_tweet_count = 0 for tweet in tweet_list: id = tweet.get_id() dtime = tweet.get_datetime() if id == last_old_tweet_id_as_int: overlap_tweet_count = overlap_tweet_count + 1 else: copy_of_tweet_list.append(tweet) if id > highest_id: highest_id = id if id < lowest_id: lowest_id = id if dtime > highest_datetime: highest_datetime = dtime if dtime < lowest_datetime: lowest_datetime = dtime # At this point, overlap_tweet_count will be 1 in the good case and 0 in the bad case (in which we missed data). if overlap_tweet_count > 1: logging.error("overlap_tweet_count too high: %s", overlap_tweet_count) exit() for tweet in copy_of_tweet_list: # Left-pad the id with zeros, so that in the unlikely event that the length in digits ever changes, the alphabetical MAX we uses # in the query for the highest value will match the numerical max. padded_id = format(tweet.get_id(),'022d') # FIXME magic number dtime = tweet.get_datetime() # example: '2001-09-28 01:00:00' date_string = dtime.strftime('20%y-%m-%d:%H:%M:%S') print ("date_string = " + date_string) dict = { "author_name": tweet.get_author_name(), \ "author_screen_name": tweet.get_author_screen_name(), \ "datetime": date_string, \ "id": padded_id, \ "full_text": tweet.get_full_text() \ } postgres_client.insert_into_raw_tweet(dict) logging.info("%s length of copy is %d, overlap_tweet_count = %d", str(datetime.datetime.today()), len(copy_of_tweet_list), overlap_tweet_count) # Having persisted the tweet data, persist a little data about this run. dict = {"datetime": run_start, \ "tweet_count": len(copy_of_tweet_list), \ "overlap_count": overlap_tweet_count, \ "min_tweet_datetime": lowest_datetime, \ "max_tweet_datetime": highest_datetime, \ "min_tweet_id": lowest_id, \ "max_tweet_id": highest_id, \ } postgres_client.insert_into_persistence_run (dict) postgres_client.commit() return overlap_tweet_count # This main routine runs persist_tweets, possibly repeatedly. logging.basicConfig(level=logging.INFO) if len(sys.argv) < 2 or len(sys.argv) > 4: print(len(sys.argv)) print("Usage: {0} sleep_seconds [raw_tweet_table_name [persistence_run_table_name]]".format(sys.argv[0])) exit() raw_tweet_table_name = 'raw_tweet' persistence_run_table_name = 'persistence_run' sleep_seconds = sys.argv[1] if len(sys.argv)>2: raw_tweet_table_name = sys.argv[2] if len(sys.argv)>3: persistence_run_table_name = sys.argv[3] logging.info ("args are sleep_seconds = {0}, raw_tweet_table_name = {1}, persistence_run_table_name = {2}".format(sleep_seconds,raw_tweet_table_name,persistence_run_table_name)) ta = twitter.TwitterAccount("twitter_config.private.json") while True: overlap_tweet_count = persist_tweets(raw_tweet_table_name, persistence_run_table_name) if int(sleep_seconds) == 0: break time.sleep(int(sleep_seconds))
# Na sequência de fibonacci é dado 0 e 1 como primeiros termos da sequência # e todos os demais termos são calculados em base destes primeiros, somando # os termos anteriores def fibonacci(termo): if termo == 0: return 0 if termo == 1: return 1 return fibonacci(termo - 1) + fibonacci(termo - 2) resultado = fibonacci(3) print(resultado)
# Neste exercício você deve criar um programa que abra o arquivo # "alunos.csv" e imprima o conteúdo do arquivo linha a linha. # Note que esse é o primeiro exercício de uma sequência, então o # seu código pode ser reaproveitado nos exercícios seguintes. # Dito isso, a recomendação é usar a biblioteca CSV para ler o # arquivo mesmo que não seja realmente necessário para esse primeiro item. arquivo = open("aula-7/exercicios/alunos.csv", "r") linha = "antes de ler arquivo" while linha: linha = arquivo.readline().split('\n')[0] if linha: print(linha)
# contador = 0 # while contador < 100: # print(contador) # contador = contador + 1 for contadorFor in range(100): print(contadorFor)
numero1 = int(input('Entre com um número: ')) numero2 = int(input('Entre com um número: ')) numero3 = int(input('Entre com um número: ')) numero4 = int(input('Entre com um número: ')) media = (numero1 + numero2 + numero3 + numero4)/4 print(media)
# Quero fazer um programa que torne a primeira letra de cada nome # do meu usuário em maiscúla # frutas = 'morango; uva; banana; pêra' # lista_com_frutas = frutas.split('; ') # print(lista_com_frutas) nome = 'fulano siLVa DE SouSA' nome_correto = '' # Método split está disponível em strings e fornece uma lista com o # separador fornecido # string.split(separador) lista_com_nomes = nome.split(' ') print(lista_com_nomes) for nome in lista_com_nomes: # print('Valor atual do nome', nome_correto) # print('Nome retirado da lista', nome) if nome.lower() == 'de': nome_correto = nome_correto + ' ' + nome.lower() else: nome_correto = nome_correto + ' ' + nome.capitalize() print(nome_correto.strip())
class Pessoa: def __init__(self, nome, idade, altura): self.nome = nome self.idade = idade self.altura = altura self.permissoes = [] def listaPermissoes(self): if len(self.permissoes) == 0: print('A pessoa não tem permissões') class Aluno(Pessoa): def __init__(self, nome, idade, altura, indice_academico, presenca): super().__init__(nome, idade, altura) self.indice_academico = indice_academico self.presenca = presenca class Professor(Pessoa): def __init__(self, nome, idade, altura): super().__init__(nome, idade, altura) self.permissoes.append('corrige prova') self.permissoes.append('dá presença') def listaPermissoes(self): permissoes = ' e '.join(self.permissoes) print(f'As permissões de um professor são: {permissoes}') class ProfessorSubstituto(Professor): def __init__(self, nome, idade, altura): super().__init__(nome, idade, altura) cleber = Pessoa('Cleber', 33, 1.55) regina = Aluno('Regina', 24, 1.7, 840, 0.8) felipe = Professor('Felipe', 29, 1.8) bruno = ProfessorSubstituto('Bruno', 22, 1.8) print(cleber.idade) print(regina.idade) print(regina.indice_academico) regina.listaPermissoes() felipe.listaPermissoes() bruno.listaPermissoes() print("="*50) print(isinstance(regina, Pessoa)) print(isinstance(regina, Aluno)) print(isinstance(regina, Professor)) print("="*50) print(isinstance(cleber, Pessoa)) print(isinstance(cleber, Aluno)) print("="*50) print(isinstance(bruno, Pessoa)) print(isinstance(bruno, Aluno)) print(isinstance(bruno, Professor)) print(isinstance(bruno, ProfessorSubstituto))
# Faça um programa que recebe um número inteiro do # usuário e imprime na tela a quantidade de divisores # desse número e quais são eles. divisor = 1 numero = int(input('Entre com um número: ')) while divisor <= numero/2: if numero % divisor == 0: print(divisor) divisor = divisor + 1
ultimo = int(input('Entre com um número: ')) contador = 1 while contador <= ultimo: print(contador) contador = contador + 1