text
stringlengths
37
1.41M
for x in range(5): print(x) for x in range(3,5): print(x) for x in range(3,8,3): print(x)
def square_definer(width: int, length: int) -> int: """Returns the size of the smallest square side possible in area""" while width != length: if width > length: width -= length return square_definer(width, length) elif length > width: length -= width return square_definer(width, length) return width your_width = int(input('Put a width: ')) your_length = int(input('Put a length: ')) print(square_definer(your_width, your_length))
set_1 = set() for number in range(5): set_1.add(input('Put int or float number: ')) set_1 = list(set_1) min_num = set_1[0] max_num = set_1[0] for i in set_1: if min_num > i: min_num = i if max_num < i: max_num = i print('Min num = ', min_num) print('Max num = ', max_num)
def calculator() -> print: """Calculates input formula""" print('Welcome to Calculator!' '\nProceed with formula input (with spaces), use only "+, -, *, /" as operators, example: "2 * 2"' '\nTo exit enter "exit"') user_input = str(input('Please enter formula: ')) if user_input == 'exit': exit(0) list_input = user_input.split(' ') if len(list_input) != 3: raise ValueError('Please, put spaces and one operator "+, -, *, /" in formula') try: number_1 = float(list_input[0]) operator = list_input[1] number_2 = float(list_input[2]) except ValueError: print('Please use numbers/digits in formula and operator') raise ValueError if not(operator == '+' or operator == '-' or operator == '*' or operator == '/'): raise IOError('Please input correct operator with spaces.') if operator == '/' and number_2 == 0: raise ZeroDivisionError('You cannot divide into zero') if operator == '+': print(number_1 + number_2) if operator == '-': print(number_1 - number_2) if operator == '*': print(number_1 * number_2) if operator == '/': print(number_1 / number_2)
""" A module to perform SVD decompostion on a given training dataset. """ from __future__ import division import numpy as np from scipy.sparse import csr_matrix import scipy.linalg as linalg import csv import os from math import sqrt import time total_users = 943 total_movies = 1682 def get_data(): """ A function to read data from test file, and return a sparse matrix. :return: A sparse user - movie rating matrix """ matrix_a = np.zeros(shape=(total_users, total_movies)) with open("u.csv", "r") as File: reader = csv.reader(File) for row in reader: row = row[0].split("\t") matrix_a[(int(row[0]) - 1), (int(row[1]) - 1)] = float(row[2]) return csr_matrix(matrix_a) def split_matrix(matrix_a): """ A function to perform svd decomposition on the matrix given to it.The algorithm to peform the SVD decomposition for a matrix A is as follows: - Calculate x = A * A.transpose() - find all eigen values of x, and find corresponding eigen vectors - Construct matrix U by arragning eigen vectors, in decreasing order of their eigen value magnitude, as columns. - Similarly construct V from matrix y = A.transpose() * A - Construct the matrix sigma by placing square roots of eigen values of x in decreasing order of their magnitudes along principal diagonal of a zero square matrix of appropriate dimensions - return U, Sigma, V :param matrix_a: (scipy.sparse.csr_matrix) A sparse matrix that is to be decomposed via svd :return: the three matrices, U, Sigma, and V that are the result of SVD decomposition """ transpose_a = csr_matrix.transpose(matrix_a) matrix_u = np.dot(matrix_a, transpose_a) matrix_v = np.dot(transpose_a, matrix_a) # scipy.linalg.eigh() is a function that returns two values - a list of of # all its eigen values, and corresponding, normalized eigen vectors # arranged as columns in increasing order of the magnitudes of corresponding # eigen values. Eigen values are returned in increasing order of their # magnitude. vals_u, vecs_u = linalg.eigh(matrix_u.todense()) vals_v, vecs_v = linalg.eigh(matrix_v.todense()) eig_vals = list(vals_u) # we need eigen values in decreasing order of their magnitudes. eig_vals.reverse() # construct matrix sigma. matrix_sigma = np.zeros(shape=(total_users, total_movies)) for i in xrange(total_users): try: matrix_sigma[i, i] = sqrt(eig_vals[i]) except ValueError: matrix_sigma[i, i] = sqrt(-1*eig_vals[i]) except IndexError as e: print e matrix_sigma = csr_matrix(matrix_sigma) # we need to reverse the order of columns because we need them arranged in # decreasing order of corresponding eigen values, not increasing order. # to accomplish this, we transpose our numpy.ndarray, convert to a list # of lists, perform list reverse operation, construct a numpy.nd array # from the obtained list and then transpose it back. # >>> [1,2] # [3,4] # >>> (after step 1)[1, 3] # [2, 4] # >>> (after list reverse) [2 ,4] # [1, 3] # >>> after final transpose, [2, 1] # >>> [4, 3] vecs_u = vecs_u.transpose() temp = list(vecs_u) temp.reverse() matrix_u = np.array(temp).transpose() # do the same for matrix_v vecs_v = vecs_v.transpose() temp1 = list(vecs_v) temp1.reverse() matrix_v = np.array(temp1) return matrix_u, matrix_sigma, matrix_v def rmse(matrix_a, matrix_u, matrix_sigma, matrix_v): """ A function to calculate rmse on original matrix. :param matrix_a: (scipy.sparse.csr_matrix) the original matrix which we have decomposed. :param matrix_u: (numpy.ndarray) U in SVD decomposition of matrix_a :param matrix_sigma: (numpy.ndarray) sigma in SVD decomposition of matrix_a :param matrix_v: (numpy.ndarray) V in SVD decomposition of matrix_a :return: (double) rmse error """ error = 0 for user in xrange(total_users): user_vector = matrix_a[user, :].toarray()[0] temp_u = matrix_u[user] temp_s = temp_u * matrix_sigma temp_v = csr_matrix(temp_s) * matrix_v error_vector = temp_v - user_vector for i in error_vector[0]: error += i*i error = error / (943 * 1682) return error ** 0.5 def get_energy(matrix_sigma): """ A function to calculate energy of a SVD decomposition. Energy of a SVD decomposition is sum of squares of diagonal values in matrix sigma of the decomposition :param matrix_sigma: (numpy.ndarray) The matrix sigma of svd decomposition :return: (double) the energy of svd decomposition (list) list of eigen values (diagonal elements) of matrix sigma """ energy = 0 eigen_list = [] for i in xrange(matrix_sigma.shape[0]): eigen = matrix_sigma[i, i] eigen_list.append(eigen) energy += eigen ** 2 return energy, eigen_list def minimize_sigma(matrix_u, matrix_sigma, matrix_v): """ To make our decomposition more efficent we can minimize our matrices until the energy of our decomposition is 90% of energy of original decomposition. This function accompolishes that. We minimize our matrices the following way: - get energy of original matrix as energy - iteratively eliminate the least eigen value from eigen value list until the energy of new eigen value list is 90% of original energy - eliminate correspnding columns from matrix_sigma, and corresponding columns from matrix_u, corresponding rows from matrix_v - return the three minimized matrices :param matrix_u: (numpy.ndarray) U in SVD decomposition :param matrix_sigma: (numpy.ndarray) sigma in SVD decomposition :param matrix_v: (numpy.ndarray) V in SVD decomposition :return: the three matrices minimized. """ energy, eigen_list = get_energy(matrix_sigma) new_energy = energy count = 0 while new_energy > 0.9 * energy: count += 1 del(eigen_list[len(eigen_list) - 1]) new_energy = sum([i * i for i in eigen_list]) final_length = len(eigen_list) count = -1 * count # eliminate columns corresponding to deleted eigen values from matrix_sigma matrix_sigma = np.delete(matrix_sigma.todense().transpose(), np.s_[final_length:], 0).transpose() # eliminate corresponding rows as well, to get square matrix_sigma again matrix_sigma = np.delete(matrix_sigma, np.s_[final_length:], 0) # eliminate corresponding rows from transpose of matrix u and then perform # transpose again to get original matrix back matrix_u = np.delete(matrix_u.transpose(), np.s_[count:], 0).transpose() count = matrix_sigma.shape[0] # delete rows from matrix v matrix_v = np.delete(matrix_v, np.s_[count:], 0) return matrix_u, matrix_sigma, matrix_v def preprocess(matrix, store=True): """ A function to preprocess the matrix. In this step, from every user's rating, we subtract that user's average rating. :param matrix: (scipy.sparse.csr_matrix) the matrix to be processed :param store: (Boolean) if store == true, this function also stores averages of each user rating in a numpy array. Otherwise, it just performs pre-processing of matrix a :return: (scipy.sparse.csr_matrix) preprocessed matrix """ if store: averages = np.zeros(matrix.shape[0]) matrix = matrix.todense() for i in xrange(matrix.shape[0]): ave = average(matrix[i]) averages[i] = ave for j in xrange(matrix[i].shape[1]): if not matrix[i][0, j] == 0: matrix[i][0, j] -= ave np.save("averages.npy", averages) return csr_matrix(matrix), averages else: averages = np.load("averages.npy") matrix = matrix.todense() for i in xrange(matrix.shape[0]): ave = averages[i] for j in xrange(matrix[i].shape[1]): if not matrix[i][0, j] == 0: matrix[i][0, j] -= ave return csr_matrix(matrix), averages def average(vector): """ calculates average of non zero values of vector - >>> vector = [1,1,1,0,0,0] - >>> average(vector) = (3/3) = 1 :param vector: (numpy.ndarray) The array whose average is to be calculated :return: (double) average of vector """ sum = 0 count = 0 for i in xrange(vector.shape[1]): if not vector[0, i] == 0: sum += vector[0, i] count += 1 if count == 0: return 0 return sum/count def predict_singular(row, matrix_u, matrix_sigma, matrix_v, averages, column): """ This function predicts the rating a user gives to a movie, based on the matrices obtained from SVD decomposition. :param row: (int) Id of user :param column:(int) Id of movie, whose rating from user we have to determine :param matrix_u:(scipy.sparse.csr_matrix) U in SVD decopmosition :param matrix_sigma: (np.ndarray) sigma in SVD decomposition :param matrix_v:(scipy.sparse.csr_matrix) v in svd decomposition :param averages: (numpy.ndarray) array which contains average rating of each user. :return: (int) predicted rating """ now = time.clock() row = int(row) column = int(column) # for a user 'row' all his predictions can be calculated by taking the row # corresponding to the user from matrix_u as r and performing r # * sigma * v.transpose(). Now rating for a particular movie can be # obtained by r[movie] temp_u = matrix_u[row] temp_s = temp_u * matrix_sigma temp_v = csr_matrix(temp_s) * matrix_v prediction = temp_v[0, int(column)] + averages[row] print time.clock() - now return prediction def save_test_data(testfile): """ A function to read the testfile and store users and movies, and their corresponding ratings into numpy arrays. :param testfile: (String) the name of test file. :return: None """ test_rows = np.zeros(20000) test_columns = np.zeros(20000) test_ratings = np.zeros(20000) count = 0 with open(testfile, "r") as f: for line in f: line = [int(word) for word in line.strip().split(",")] test_rows[count] = int(line[0]) - 1 test_columns[count] = int(line[1]) - 1 test_ratings[count] = int(line[2]) count += 1 np.save("test_rows.npy", test_rows) np.save("test_columns.npy", test_columns) np.save("test_ratings.npy", test_ratings) def save_predictions(matrix_u, matrix_sigma, matrix_v, db="predictions.npy"): """ To not run the entire algorithm every time, we can save our predictions for a given test data. This function does that. :param matrix_u:(numpy.ndarray) U in SVD decompoistion of given matrix :param matrix_sigma: (numpy.ndarray) Sigma in SVD decomposition of given matrix :param matrix_v: (numpy.ndarray) V in SVD decomposition of given matrix :param db: (String) name of numpy array containing actual predictions. :return: """ prediction = np.zeros(20000) test_rows = np.load("test_rows.npy") test_columns = np.load("test_columns.npy") averages = np.load("averages.npy") for i in xrange(20000): predicted = predict_singular(test_rows[i], matrix_u, matrix_sigma, matrix_v, averages, test_columns[i]) prediction[i] = predicted np.save(db, prediction) def brute_rmse(data="predictions.npy"): """ Calculate rmse error over test data. The test data and training data are disjoint so as to better evaluate the recommender system. Rmse error is calculated by the formula, sqrt(summation( (predicted - actual) ^ 2)/n :param data: (String) the name of the numpy array that contains our predictions. :return: (double) rmse error """ test_ratings = np.load("test_ratings.npy") prediction = np.load(data) rmse = 0 for i in xrange(20000): actual = test_ratings[i] predicted = prediction[i] rmse += (predicted - actual) ** 2 return (rmse/20000)**0.5 def precision_at_top_k(db="predictions.npy", k=300): """ A function to calculate precision for top_k ratings. we calculate the precision the following way: - Get top K entries from our predicted values - Get threshold for these top K entries - Get the number of entries amongst these K entries whose actual rating is greater than threshold as c - precision = c/k :param db: (String) name of the numpy array where our predictions are stored. :param k: (int) k in top K entries :return: (double) precision """ predicted = np.load(db) test_ratings = np.load("test_ratings.npy") relevant_entries = predicted.argsort()[::-1][0:k] threshold = int(predicted[relevant_entries[relevant_entries.shape[0] - 1]]) relevant_count = 0 for entry in relevant_entries: if test_ratings[entry] >= threshold: relevant_count += 1 precision = relevant_count / k return precision def spearman_correlation(db="predictions.npy"): """ Function to calculate spearman correlation. It is calculated by the following formula: 1 - ((6 * sum((predicted - actual) ^ 2)/( n ( n^2 - 1)), where n is the number of entries we are checking against. Spearman correaltion gives how similar two vectors are. How strongly they are correlated is determined by the magnitude of correlation. The closer they are to 1, the stronger they are related. :param db: (String) name of the numpy array where our predictions are stored :return: (double) spearman correaltion """ predicted = np.load(db) test_ratings = np.load("test_ratings.npy") d = 0 n = test_ratings.shape[0] for i in xrange(n): d += (predicted[i] - test_ratings[i]) ** 2 coeff = (6 * d) / (n * (n ** 2 - 1)) return 1 - coeff def main(): """ The main function. It does the following: - reads data from training file and converts it to a user movie matrix - performs preprocessing - performs SVD decomposition, and calculates rmse, precision on top k and spearman correlation - Performs minimzation until 90% of energy, and calculates them again. :return: None """ matrix_a = get_data() matrix_a, averages = preprocess(matrix_a) print "starting to split" matrix_u, matrix_sigma, matrix_v = split_matrix(matrix_a) if "predictions.npy" not in os.listdir("."): print "saving predictions" save_predictions(matrix_u, matrix_sigma, matrix_v) print "rmse before minimimization", brute_rmse() print "precision at top k before minimization", precision_at_top_k( db="predictions.npy") print "spearman correlation before minimzation", spearman_correlation( db="predictions.npy") matrix_u, matrix_sigma, matrix_v = minimize_sigma(matrix_u, matrix_sigma, matrix_v) if "min_predictions.npy" not in os.listdir("."): print "here" save_predictions(matrix_u, matrix_sigma, matrix_v, db="min_predictions.npy") print "rmse after minimisation", brute_rmse(data="min_predictions.npy") print "precision at top k after minimization", precision_at_top_k( db="min_predictions.npy") print "spearman correlation after minimization", spearman_correlation( db="min_predictions.npy") if __name__ == "__main__": main() # rmse before minimimization 1.2227316644 # precision at top k before minimization 0.686666666667 # spearman correlation before minimzation 0.999999977574 # rmse after minimisation 1.21357348695 # precision at top k after minimization 0.673333333 # spearman correlation after minimization 0.999999977909
############# GENERAL TREE ######## class TreeNode: def __init__(self,data): self.data=data self.children=[] self.parent=None def add_child(self,child): child.parent=self self.children.append(child) def get_level(self): level=0 iterator=self.parent while iterator: iterator=iterator.parent level+=1 return level def print_tree(self): spaces=" "*self.get_level()*3 prefix=spaces+"|__" if self.parent else "" print(prefix,self.data) if self.children: for child in self.children: child.print_tree() if __name__ == "__main__": root=TreeNode('Electronics') Tv=TreeNode("Tv") phones=TreeNode("Phones") laptops=TreeNode("Laptops") Tv.add_child(TreeNode("LG")) Tv.add_child(TreeNode("Sony")) Tv.add_child(TreeNode("Sumsang")) phones.add_child(TreeNode("Mi")) phones.add_child(TreeNode("GOME")) phones.add_child(TreeNode("Vivo")) laptops.add_child(TreeNode("Lenvovo")) laptops.add_child(TreeNode("Apple")) laptops.add_child(TreeNode("Accer")) root.add_child(Tv) root.add_child(phones) root.add_child(laptops) root.print_tree() ########## BINARY TREE ############# class Binary_Tree: def __init__(self,data): self.data=data self.left=None self.right=None def add_child(self,data): if data==self.data: return "data is already exists" if data<self.data: if self.left: self.left.add_child(data) else: self.left= Binary_Tree(data) if data>self.data: if self.right: self.right.add_child(data) else: self.right= Binary_Tree(data) def search(self,data): if data==self.data: return True if data<self.data: if self.left: return self.left.search(data) else: return False else: if self.right: return self.right.search(data) else: return False def in_order_traversal(self): array=[] if self.left: array+=self.left.in_order_traversal() array.append(self.data) if self.right: array+=self.right.in_order_traversal() return array def min(self): if self.left: return self.left.min() else: return self.data def max(self): if self.right: return self.right.max() else: return self.data def sum(self): total=0 if self.left: total+=self.left.sum() total+=self.data if self.right: total+=self.right.sum() return total def delete(self,data): if data<self.data: if self.left: self.left=self.left.delete(data) elif data>self.data: if self.right: self.right=self.right.delete(data) else: if self.right==None and self.left==None: return None if self.right: return self.right if self.left: return self.left else: max_val=self.left.max() self.data=max_val self.left=self.left.delete(max_val) return self if __name__ == "__main__": a=Binary_Tree(56) a.add_child(45) a.add_child(4) a.add_child(5) a.add_child(450) a.add_child(8) print(a.search(450)) a.delete(8) print(a.in_order_traversal()) print(a.min()) print(a.max()) print(a.sum())
import math def solution(n, m): answer = [] answer.append(math.gcd(n, m)) answer.append(int((n * m) / answer[0])) return answer n = 3 m = 12 print(solution(n, m))
def solution(nums): answer = 0 tmp = len(nums) / 2 nums = list(set(nums)) nums = len(nums) if(tmp < nums) : answer = int(tmp) else : answer = nums return answer num = [3, 1, 2, 3] print(solution(num))
import random import sys import time def setze_zeitstempel(): return time.time() * 1000 def stelle_aufgabe(): i = 0 while True: i += 1 print(" --- Aufgabe %d --- " % (i)) rechne(0) def rechne(mode = 0): answer_correct = False try: a = random.randint(0,9) b = random.randint(0,9) start = setze_zeitstempel() if mode == 0: print("%d x %d = ?" % (a, b)) c = int(input()) if (a * b) == c: 56 answer_correct = True elif mode == 1: print("%d + %d = ?" % (a, b)) c = int(input()) if (a + b) == c: answer_correct = True stop = setze_zeitstempel() if ((stop - start) < 5000) and answer_correct: print("Sehr gut") elif ((stop -start) < 10000) and ((stop - start) >= 5000) and answer_correct: print("Weiter so!") elif ((stop - start) >= 10000) and ((stop - start) < 15000) and answer_correct: print("Das geht doch schneller, oder?") elif ((stop - start) >= 15000 and answer_correct): print("Das war zu langsam") elif answer_correct is False: print("Antwort ist falsch") except ValueError as e: print("Falsche Eingabe") if __name__ == "__main__": stelle_aufgabe()
# def choice_to_number(choice): # """Convert choice to number.""" # if choice == 'Usain': # return 1 # elif choice == 'Me': # return 2 # elif choice == 'Aybek': # return 3 # else: # return choice def choice_to_number(choice): return {'Usain': 1, 'Me': 2, 'Qazi': 3}[choice] def number_to_choice(number): return {1: 'Usain', 2: 'Me', 3: 'Qazi'}[number] def test_choice_to_number(): assert choice_to_number('Usain') == 1 assert choice_to_number('Me') == 2 assert choice_to_number('Aybek') == 3 def test_number_to_choice(): assert number_to_choice(1) == 'Usain' assert number_to_choice(2) == 'Me' assert number_to_choice(3) == 'Aybek' def test_all(): try: test_choice_to_number() test_number_to_choice() except AssertionError: print(‘WRONG’) else: print(‘SUCCESS’) test_all()
def fib(n): if (n is 0 or n is 1): return 1 return fib(n - 1) + fib(n - 2) if __name__ == "__main__": print("Im here") print(fib(50))
#!/usr/bin/env python # coding: utf-8 # # Linear Regression # In[1]: import matplotlib.pyplot as plt import pandas as pd import plotly.express as px from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split # In[2]: # load the data from scikit-learn (a bunch is returned) boston = load_boston() # required components data = boston["data"] target = boston["target"] cols = boston["feature_names"] # In[3]: def get_var(df, var_name): globals()[var_name] = df # fmt:on ( pd.DataFrame(data, columns=cols) .assign(target=target) .dropna(axis=1) .rename(str.lower, axis=1) .pipe(get_var, "df1") ) Y = df1["target"] X = df1.drop(columns="target", axis=1) # In[4]: print(X.shape) print(Y.shape) # In[5]: (X_train, Y_train, X_test, Y_test,) = train_test_split( X, Y, test_size=0.3, random_state=42, shuffle=False, ) # In[6]: print(X_train.shape) print(Y_test.shape)
""" 使用生成器函数实现可迭代类 """ import math class PrimeNumbers(object): """ 实现正向迭代 实现 __iter__ 或 __getitem__ 方法 实现反向迭代 实现 __reversed__ 方法 """ def __init__(self, start, end): self.start = start self.end = end def isParimeNum(self, k): if k < 2: return False for i in range(2,int(math.sqrt(k) + 1)): if k % i == 0: return False return True def __iter__(self): for k in range(self.start, self.end + 1): if self.isParimeNum(k): yield k def __reversed__(self): for k in range(self.end, self.start - 1, -1): if self.isParimeNum(k): yield k def main(): for i in PrimeNumbers(1, 10): print(i) for i in reversed(PrimeNumbers(1, 10)): print(i) if __name__ == '__main__': main()
""" 对迭代器进行切片操作 """ # 使用itertools.islice,返回一个迭代对象切片的生成器 from itertools import islice def file_slice(): f = open('aaa') # islice(f, 1, 100) # islice(f, 500) for i in islice(f, 1, None): print(i) def list_slice(): l = [i for i in range(0, 20)] i = iter(l) # start=4表示列表中取索引4开始到14结束 for x in islice(i, 4, 14): print(x) if __name__ == '__main__': # file_slice() list_slice()
b=16 for mani in range(int(pow(b,1/2)),1,-1): if(b%mani==0): print(mani) print(int(b/mani))
import random from abc import ABC class Listas_Frutas(ABC): _frutas_lista = ['banana', 'jabuticaba', 'pitanga', 'mirtilo', 'morango', 'abacaxi', 'cereja' ] def escolher_fruta(self): return self._frutas_lista.pop(0) def tamanho_fruta(self): return '_' * len(self._frutas_lista.pop(0)) fruta_escolhida = Listas_Frutas().tamanho_fruta() fruta_len = Listas_Frutas().escolher_fruta() for i in range(0, len(fruta_len)): if 'a' == fruta_len[i]: fruta_escolhida = fruta_escolhida[:i] + 'a' + fruta_escolhida[i + 1:] #pt = len(fruta_escolhida) #print(pt) #for i in range(0, len(fruta_escolhida)): # if 'a' == fruta_escolhida[i]: # palavra_descoberta = palavra_descoberta[:i] + 'a' + palavra_descoberta[i + 1:]
"""This script makes the search to wikipedia by passing the search keyword as the only argument.""" import sys from elasticsearch import Elasticsearch import config def title_to_url(title): """Takes the article title and turns it into a wikipedia URL""" title = title.replace(' ', '_') return config.WIKIPEDIA_URL + title.encode('utf-8') def search(keyword): """Performs the search against elasticsearch.""" es = Elasticsearch() result = es.search(index=config.ELASTIC_SEARCH_INDEX, body={ 'query': { 'multi_match': { 'query': keyword, 'fuzziness': 1, 'prefix_length': 1, 'fields': ['title^10', 'body'] } } }) results = [] for hit in result['hits']['hits']: results.append((hit['_score'], title_to_url(hit['_source']['title']))) return results def search_and_print(keyword): """Used for calling the search function and printing the results.""" print "Searched for:", keyword for score, url in search(keyword): print score, url print if __name__ == "__main__": if len(sys.argv) < 2: print "Keyword at positional argument 1 is required." sys.exit(1) keyword = sys.argv[1] search_and_print(keyword)
''' Given a sorted list of disjoint intervals, each interval intervals[i] = [a, b] represents the set of real numbers x such that a <= x < b. We remove the intersections between any interval in intervals and the interval toBeRemoved. Return a sorted list of intervals after all such removals. Example 1: Input= 3 0 2 3 4 5 7 1 6 Output= [[0, 1], [6, 7]] Example 2: Input= 1 0 5 2 3 Output= [[0, 2], [3, 5]] ''' sz=1000 a=[0]*sz n=int(input()) for i in range(n): x,y=map(int,input().split()) for j in range(x,y): a[j]+=1 x,y=map(int,input().split()) for j in range(x,y): a[j]=0 cur=0 ans=[] x=-1 while(cur<sz): if(x==-1 and a[cur]>0): x=cur if(x!=-1 and a[cur]==0): ans.append([x,cur]) x=-1 cur+=1 print(ans)
import operator from datetime import datetime class Person(): def __init__(self, last_name='', first_name='', gender='', fav_color='', dob=''): self.last_name = last_name self.first_name = first_name gender = gender if gender == 'M' or gender == 'Male': self.gender = 'Male' elif gender == 'F' or gender == 'Female': self.gender = 'Female' else: self.gender = 'Unknown' self.fav_color = fav_color self.dob = datetime.strptime(dob, '%m/%d/%Y') def generate_line(self): line = [self.last_name, self.first_name, self.gender, self.dob, self.fav_color] for item in line: str(item) return line def parse_text(): ''' Parses three text files with different formats. Adds all lines to common list. Orders lines and formats data for printing. ''' comma_lines = process_file("comma.txt", ',') processed_comma_lines = process_comma_file(comma_lines, ',') pipe_lines = process_file("pipe.txt", '|') processed_pipe_lines = process_pipe_file(pipe_lines, '|') space_lines = process_file("space.txt", ' ') processed_space_lines = process_space_file(space_lines, ' ') persons_list = processed_comma_lines + processed_pipe_lines + processed_space_lines output_1_sorted = [] output_2_sorted = [] output_3_sorted = [] output_1_sorted = sorted(persons_list, key=operator.itemgetter(2, 0)) output_2_sorted = sorted(persons_list, key=operator.itemgetter(3, 0)) output_3_sorted = sorted(persons_list, key=operator.itemgetter(0), reverse=True) for line in output_1_sorted: line[3] = datetime.strftime(line[3], '%-m/%-d/%Y') output_1 = [] output_2 = [] output_3 = [] for line in output_1_sorted: output_1.append(' '.join(line)) for line in output_2_sorted: output_2.append(' '.join(line)) for line in output_3_sorted: output_3.append(' '.join(line)) output = {} output['output_1'] = output_1 output['output_2'] = output_2 output['output_3'] = output_3 write_output_file(output) return output def process_file(file, delimiter): ''' read text and split into a list of a list of strings ''' raw_data = [] with open(file, "r") as file: raw_data = [line.split(delimiter) for line in file] return raw_data def process_comma_file(raw_data, delimiter): list = [] for word in raw_data: line = [x.strip() for x in word] list.append(Person(last_name=line[0], first_name=line[1], gender=line[2], fav_color=line[3], dob=line[4]).generate_line()) return list def process_pipe_file(raw_data, delimiter): list = [] for word in raw_data: line = [x.strip() for x in word] line[5] = line[5].replace("-", "/") list.append(Person(last_name=line[0], first_name=line[1], gender=line[3], fav_color=line[4], dob=line[5]).generate_line()) return list def process_space_file(raw_data, delimiter): list = [] for word in raw_data: line = [x.strip() for x in word] line[4] = line[4].replace("-", "/") list.append(Person(last_name=line[0], first_name=line[1], gender=line[3], dob=line[4], fav_color=line[5]).generate_line()) return list def write_output_file(output): output_1 = output['output_1'] output_2 = output['output_2'] output_3 = output['output_3'] with open("output.txt", "w") as text_file: text_file.write('Output 1:') text_file.write('\n') for line in output['output_1']: text_file.write(line) text_file.write('\n') text_file.write('\n') text_file.write('Output 2:') text_file.write('\n') for line in output['output_2']: text_file.write(line) text_file.write('\n') text_file.write('\n') text_file.write('Output 3:') text_file.write('\n') for line in output['output_3']: text_file.write(line) text_file.write('\n') text_file.close() if __name__ == '__main__': parse_text()
import sys sys.stdin = open('sample_input.txt') T = int(input()) for tc in range(1,T+1): card = input() card_list = [card[idx:idx+3] for idx in range(0,len(card),3)] card_type = ['S','D','H','C'] card_cnt = {key:[] for key in card_type} for card in card_list: key, value = card[0], card[1:] if value in card_cnt[key]: answer = "ERROR" break else: card_cnt[key].append(value) else: answer = [13 - len(card_cnt[key]) for key in card_type] if type(answer) == list: print(f'#{tc}',*answer) else: print(f'#{tc}',answer)
N = int(input("Please write a count of students: ")) #студенти K = int(input("Please write a count of apples: ")) #яблуки count_apples = K//N apples_left = K%N print("every student receiped", count_apples,"apples") #виводимо результат print("apples left:",apples_left) #виводимо результат input()
#!/usr/bin/env python3 class Employee(object): def __init__(self, name, title): self.name = name self.title = title self.salary_table = { 'manager': 50000, 'director': 20000, 'staff': 10000 } def salary(self): return self.salary_table[self.title] def introduce(self): print('Hi,all. My name is {}'.format(self.name)) print('My title is {}, and my salary is a secret...'.format(self.title)) print('OK, salary is {}'.format(self.salary())) staffInfo = { 'sonic': 'manager', 'tom': 'director', 'jerry': 'director', 'amanda': 'staff', 'Bella': 'staff', 'Carry': 'staff', 'Dolce': 'staff', 'Emma': 'staff' } def conference_a(): for name in staffInfo: employee = Employee(name, staffInfo[name]) employee.introduce() def what_will_happen(): return 'sonic', 'male', 34 def main(): print('This is Sonics homework2.') conference_a() name, gend, age = what_will_happen() print('name={}, gender={}, age={}'.format(name, gend, age)) #name2, gend2, age2, title2 = what_will_happen() #print('name2={}, gender2={}, title2={}'.format(name2, gend2, title2)) if __name__ == '__main__': main()
import csv file_to_load = "C:/Users/David/Desktop/GTATL201908DATA3/02 - Homework/03-Python/Instructions/PyPoll/Resources/election_data.csv" file_to_output= "Resources/election_data.txt" #variables vote_total = 0 candidates = [] candidate_votes = {} winner = " " winner_votes = {} #csv format from class activities with open(file_to_load) as election_data: reader = csv.DictReader(election_data) #go throw each row, receiving error in "reader" for row in reader #total votes vote_total = vote_total + 1 #select candidate name candidate_name = row[2] #if candidate name does not equal other names if candidate_name not in candidates: #add to list candidates.append(candidate_name) #count votes for the candidate candidate_votes[candidate_name] = 0 #add up votes for the candidates candidate_votes[candidate_name] = candidate_votes[candidate_name] + 1 #go throw votes to get winner for candidate in candidate_votes #get votes an percents for candidates votes = candidate_votes.get(candidate) vote_percent = votes / vote_total *100 #winner votes if (votes > winner_votes): winner_votes = votes winner = candidate print() print() print() print("Election Results") print("-------------------------") print("Total Votes: " + str(vote_total)) print("-------------------------") for i in range(len(candidate)): print(candidate[i] + ": " + str(round(vote_percent[i],3)) +"% (" + str(round(candidate_votes[i],3)+ ")")) print("Winner: ") + str(winner)) with open("C:/Users/David/Desktop/GTATL201908DATA3/02 - Homework/03-Python/Instructions/PyPoll/Resources/election_data.csv", "w") as text: text.write("Election Results") text.write("-------------------------") text.write("Total Votes: " + str(vote_total)) text.write("-------------------------") for i in range(len(candidate)): print(candidate[i] + ": " + str(round(vote_percent[i],3)) +"% (" + str(round(candidate_votes[i],3)+ ")")) text.write("Winner: ") + str(winner))
#!/usr/bin/env python #Set python environment in the first line as written above ''' This script is written to do the following: a) Read a .rnt file and save the Location, Strand and Product columns to another file called filename_LocStrPro.txt b) Split the Location into two parts and save the Strand and Location into another file filename_StrLoc1Loc2.txt c) Based on the strand either increase or decrease the Loc1 and Loc2 numbers and save the changed file to filename_Upstream_StrLoc1Loc2.txt d) Open the filename.fna file and get the genome presented in both of the above locations i.e. at original locations and changed locations. ''' import pandas as pd import numpy as np import sys import collections # Read the file. Modify the below to check for the file and ask the # user to specify the filename after the script. Also need to store # the filename (without the extension) and use it save other files. # try: # inp_file = sys.argv[1] # except ValueError: # print("No valid integer in line.") inp_file = sys.argv[1] #inp_file = 'NC_004061.rnt' filename=inp_file.split('.')[0] print(inp_file, filename) # Read the file as a data frame but Skip the first two rows df1=pd.read_csv(inp_file,skiprows=2,sep='\t') print(df1.head()) print(df1.columns) print(df1.dtypes) # Store those first two lines (in case they are required) inp=open(inp_file) firstline=inp.readline() secondline=inp.readline() inp.close() # Read the gnome file and save it as a string (to slice later) genomefile=filename+".fna" with open(genomefile, 'r') as gf: trash=gf.readline() genome=gf.read().replace('\n', '') #print(genome) #print(trash) # Save only "Location", "Strand", "Product" columns to a separate # dataframe df2=df1[["Location", "Strand", "Product"]].copy() # Split the Location column into startLoc and endLoc. Finally, add # these columns to the df2 and remove the Location column from the df2 dfTemp = df2["Location"].str.split("\.\.", n = 1, expand=True) print(dfTemp.head()) df2["startLoc"] = dfTemp[0] df2["endLoc"] = dfTemp[1] print(df2.head()) #df2.drop(columns=['Location'], inplace=True) df2.drop(['Location'], axis=1, inplace=True) #Change the type of startLoc and endLoc df2[["startLoc", "endLoc"]] = df2[["startLoc", "endLoc"]].astype(int) #Change the order of columns df2 = df2[["Strand", "startLoc", "endLoc", "Product"]] df_length=len(df2.index) #Create a numpy array to store product, AT_geneome_percent, #AT_upstream_percent product=[] at_array =np.zeros((df_length,2)) # Print the Genome from start to end location genefna='gene_'+filename+'.fna' gfna=open(genefna,'w') count=0 for index, row in df2.iterrows(): this_gene=genome[row['startLoc']:row['endLoc']+1] atgc_count = collections.Counter(this_gene) at_count = atgc_count['A'] + atgc_count['T'] gene_length = len(this_gene) at_percent = 100*(at_count/gene_length) product.append(row['Product']) at_array[count,0] = at_percent gfna.write("%a %a %i %i %a %6.3f\n" % (str('>').strip(''), row['Strand'], row['startLoc'], row['endLoc'], row['Product'], at_percent)) gfna.write("%a \n" % (genome[row['startLoc']:row['endLoc']+1])) count = count + 1 print(this_gene) print(at_percent) print(gene_length) # Write df2 to separate file with space as the separator. LSPfile="LSP_gene_"+filename+".txt" df2.to_csv(LSPfile, sep="\t", index=False) print(df2.head()) print(df2.columns) print(df2.dtypes) # If Strand is -, change startLoc to endLoc and endLoc to endLoc + 50 # If Strand is +, change endLoc to startLoc and startLoc to endLoc - 50 df2.loc[df2.Strand == "-", ['startLoc']] = df2.loc[:,'endLoc'] df2.loc[df2.Strand == "-", ['endLoc']] = df2.loc[:,'endLoc']+50 df2.loc[df2.Strand == "+", ['endLoc']] = df2.loc[:,'startLoc'] df2.loc[df2.Strand == "+", ['startLoc']] = df2.loc[:,'startLoc']-50 print(df2.head()) # Write df2 to separate file with space as the separator. LSPfile="LSP_upstream_"+filename+".txt" df2.to_csv(LSPfile, sep="\t", index=False) # Print the upstream Genome from start to end location upfna='upstream_'+filename+'.fna' ufna=open(upfna,'w') count=0 for index, row in df2.iterrows(): this_gene=genome[row['startLoc']:row['endLoc']+1] atgc_count = collections.Counter(this_gene) at_count = atgc_count['A'] + atgc_count['T'] gene_length = len(this_gene) at_percent = 100*(at_count/gene_length) at_array[count,1] = at_percent ufna.write("%a %a %i %i %a %6.3f\n" % (str('>').strip(''), row['Strand'], row['startLoc'], row['endLoc'], row['Product'], at_percent)) ufna.write("%a \n" % (genome[row['startLoc']:row['endLoc']+1])) count = count + 1 # Print the both the genome's AT percentage atPercent='atPercent_'+filename+'.txt' atp=open(atPercent,'w') atp.write("%a %a\t %a\n" % ('genAT%', 'upstreamAT%', 'Product')) for i in range(0,len(product)): atp.write("%6.3f\t %6.3f\t %a \n" % (at_array[i,0], at_array[i,1],str(product[i]).strip("\'")))
#!/usr/bin/env python3 import random arr = list(range(20)) random.shuffle(arr) print('Original Array: ' + str(arr)) # QUICKSORT def partition(A, low, high): pivot = low for j in range(low, high): if A[j] <= A[high]: A[pivot], A[j] = A[j], A[pivot] pivot+=1 A[pivot], A[high] = A[high], A[pivot] return pivot def quicksort(a, low, high): if low > high: return i = partition(a, low, high) quicksort(a, low, i-1) quicksort(a, i+1, high) quicksort(arr, 0, len(arr)-1) print('Sorted Array: ' + str(arr))
import csv def create_record(number_of_rec): while number_of_rec: install_date = raw_input("Enter the Install Date: ") device_number = raw_input("Enter the Device Number: ") serv_address = raw_input("Enter the Service Address: ") serv_city = raw_input("Enter Service City : ") if install_date and device_number and serv_address and serv_city: record_list = [install_date, device_number, serv_address, serv_city] with open("C:\Path\to\File", "ab") as wf: writer = csv.writer(wf) writer.writerow(record_list) number_of_rec -= 1 def display_record(option): with open("C:\Path\to\File", "r") as rf: reader = csv.reader(rf) if option == 2: for row in reader: print " ".join(row) elif option == 3: search_feild = raw_input("Search by Install Date, Device Number, Service Address,City,or State :") for row in reader: if search_feild in row: print " ".join(row) def main(): print("1. Add to the file") print("2. Display all the data from the file") print("3. Search for particular data") print("0. To Exit") choice = True while choice: your_choice = input("Enter your choice:") if your_choice == 1: number_of_rec = input("Enter number of records you want to enter:") create_record(number_of_rec) if your_choice == 2: display_record(2) if your_choice == 3: display_record(3) if your_choice == 0: choice = False if __name__ == "__main__": main()
""" This script will try to convert pdfs to text files using pdftotext """ import pdftotext import glob import os import csv def convert(path, outfolder, pattern="*.pdf"): """convert files in path with pattern and save to outfolder """ filelist = glob.glob(os.path.join(path, pattern)) meta = [] if not os.path.isdir(outfolder): os.mkdir(outfolder) for file in filelist: outfile = os.path.join(outfolder, os.path.splitext(os.path.split(file)[-1])[0] + ".txt") if os.path.isfile(outfile): meta.append({"pdf" : file, "txt" : outfile}) continue try: with open(file, "rb") as f: pdf = pdftotext.PDF(f) text = "\n\n".join(pdf) npages = len(pdf) with open(outfile, "w", encoding="utf8") as fout: fout.writelines(text) meta.append({"pdf" : file, "txt" : outfile, "npages" : npages}) except: print("cannot process %s"%file) with open(os.path.join(outfolder, "converted.csv"), "w") as fout: writer = csv.DictWriter(fout, fieldnames=["pdf", "txt", "npages"]) writer.writeheader() writer.writerows(meta) if __name__ == "__main__": convert("./pdf", "./txt", pattern="*.pdf")
""" If else, elseif are supported, space delimited like the rest of python Brutespray examples https://github.com/x90skysn3k/brutespray/blob/master/brutespray.py#L161 """ protocols = {"postgressql":"sql", "pop3": "email"} # Trying a get a protocol that does exist print(protocols["pop3"]) # Trying to get a protocol that doesn't exist # This raises what's called an exception # Comment this line out to see how the rest of the code works print(protocols["telnet"]) # This can be managed through try except try: print(protocols["telnet"]) except KeyError: print("Telnet is not an option") # In conjunction with the rest of the program people_protocol = [["Steve", "postgressql"], ["Alice", "pop3"], ["Alice", "telnet"]] for person, protocol in people_protocol: try: print("Hacking {0} with {1}".format(person, protocols[protocol])) except KeyError: print("Protocol {} is not an option. Failed hack on {}".format(protocol, person))
""" If else, elseif are supported, space delimited like the rest of python Brutespray examples Not in Brutespray but really needs to be """ protocols = {"postgressql":"sql", "pop3": "email"} people_protocol = [["Steve", "postgressql"], ["Alice", "pop3"], ["Alice", "sql"]] for person, protocol in people_protocol: if person == "Alice": # .format string formatting/interpolation. Use this instead of + signs print("Hacking {0} with {1} even harder".format(person, protocol)) else: # Python 2 style, no longer fashionable print("Hacking %s with %s" % (person, protocol))
#bring in file types import os import csv # import the file i'm working on budgetData_csv = os.path.join('PyBank','Resources', 'budget_data.csv') # what am I looking for - Total (months) totalMonths = [] #print(totalMonths) # net total of profit/losses - totalAmount = [] # past Amount - amountVariance = 0 # amount variance monthVariance = 0 profitLoss = int(budget_data.csv[1]) # create my loop so it continues to calculate through the data with open(budgetData_csv) as bankData: csvreader = csv.reader(bankData, delimiter=',') csvheader = next(csvreader) for row in csvreader: # Add the months totalMonths.append(row[0]) print(f'Total Months: {len(totalMonths)}') # Add the amounts totalAmount.append(row[1]) print(f'Total Amount: {sum(totalAmount)}')
def isAmbiguous(inputDateString): dateStringArray = inputDateString.split('/') first = int(dateStringArray[0]) second = int(dateStringArray[1]) if first <= 12 and second <= 12: return True else: return False inputDateString = input() if isAmbiguous(inputDateString): print("Date is ambiguous") else: print("Date is not ambiguous")
DIR = {"N" :(0, 1),"S" :(0, -1) ,"E" :(1, 0) ,"W":(-1,0) ,"NE" :(1,1) ,"NW" :(-1, 1) ,"SE" :(1,-1) ,"SW" :(-1,-1)} def termino(coordinate, directions) : x = coordinate[0] y = coordinate[1] for i in directions : dir = "" digit = 0 for j in range(len(i)) : if ord(i[j]) >= 48 and ord(i[j]) <= 57 : digit = digit*10 + int(i[j]) else : dir += i[j] x1 , y1 = DIR[dir] x = x + x1*digit y = y + y1*digit return x , y li = ["1N" , "3NW"] x , y = termino((1, 1),li ) print((x , y))
class ArrayStack: """ LIFO Stack implementation using a Python list as underlying storage. """ def __init__(self): """Create an empty stack""" self._data = [] def __len__(self): """ Return the number of elements in the stack. """ return len(self._data) def is_empty(self): """ Return True if stack is empty. """ return len(self._data) == 0 def push(self, e): """ Add element to the top of the stack. """ self._data.append(e) def top(self): """ Return (but do not remove) the element at the top of the stack. Raise exception if empty. """ if self.is_empty(): raise Exception('Stack is empty') return self._data[-1] def pop(self): """ Remove and return the element from top of the stack. (LIFO) Raise exception if stack is empty """ if self.is_empty(): raise Exception('Stack is empty') return self._data.pop() # remvoe last item of list obj = ArrayStack() obj.push(4) obj.push(6) print(obj.pop()) obj.top()
class Calculator(): def dodaj(self, a, b): wynik = a + b print("Twój wynik dodawania to {}".format(wynik)) def odejmij(self, a, b): wynik = a - b print("Twój wynik odejmowania to {}".format(wynik)) def mnozenie(self, a, b): wynik = a * b print("Twój wynik mnożenia to {}".format(wynik)) def dzielenie(self, a, b): wynik = a / b print("Twój wynik dzielenia to {}".format(wynik)) calc = Calculator() print("Podaj jakie chcesz wykonać działanie:") print("Naciśnij 1 jeśli chcesz dododać ") print("Naciśnij 2 jeśli chcesz odejmować") print("Naciśnij 3 jeśli chcesz pomnożyc") print("Naciśnij 4 jeśli chcesz podzielić") c = int(input()) if c == 1 or c == 2 or c == 3 or c == 4: print("Podaj pierwszą liczbę") a = float(input()) print("Podaj drugą liczbę") b = float(input()) if c == 1: calc.dodaj(a, b) if c == 2: calc.odejmij(a, b) if c == 3: calc.mnozenie(a, b) if c == 4: calc.dzielenie(a, b) else: print("Nie ma takiego działania. Program zatrzymany.") print("Podaj jakie chcesz wykonać działanie:") print("Naciśnij 1 jeśli chcesz dododać ") print("Naciśnij 2 jeśli chcesz odejmować") print("Naciśnij 3 jeśli chcesz pomnożyc") print("Naciśnij 4 jeśli chcesz podzielić") c = int(input()) if c == 1 or c == 2 or c == 3 or c == 4: print("Podaj pierwszą liczbę") a = float(input()) print("Podaj drugą liczbę") b = float(input()) if c == 1: calc.dodaj(a, b) if c == 2: calc.odejmij(a, b) if c == 3: calc.mnozenie(a, b) if c == 4: calc.dzielenie(a, b)
import Clases as c def convertir_texto_numero(mensaje, min, max): num = int(mensaje) if num < min: raise c.ValorMenorMin() if num > max: raise c.ValorMayorMax() return num def ingresa_numero(mensaje, min, max): numero = 0 while True: try: texto = input(mensaje) numero = convertir_texto_numero(texto, min, max) return numero except ValueError: print("Debe ingresar un número") except c.ValorMenorMin: print(f"El valor es menor a {min}") except c.ValorMayorMax: print(f"El valor es mayor a {max}")
from dataclasses import dataclass from typing import List @dataclass class Fecha: dia : int mes : int anio : int @dataclass class Direccion: calle : str altura : int localidad : str @dataclass class Persona: nombre : str apellido : str direcciones : List[Direccion] fecha_nacimiento : Fecha class Servicio: def __init__(self, nombre, costo): # Constructor de la clase self.nombre = nombre self.costo = costo def __repr__(self) -> str: return f"Servicio(nombre = {0}, costo = {1})".format # Falta copiar def imprimir_servicio(srv: Servicio): # srv: Nombre del parámetro print(srv.nombre, srv.costo) def main(): cable = Servicio("Cablevisión", 1000) luz = Servicio("Calp", 500) imprimir_servicio(cable) imprimir_servicio(luz) direc1 = Direccion("Bunge", 1200, "Pinamar") direc2 = Direccion("Bunge", 1300, "Pinamar") direcciones = [direc1, direc2] print(direc1) p = Persona("Carlos", "Perez", direcciones, Fecha(1, 1, 2001)) print(p.fecha_nacimiento.anio) r = Persona("Gastón", "Dominguez", direcciones, Fecha(4, 4, 1980)) print(r. nombre , r.apellido, r.fecha_nacimiento) main()
from PIL import Image import os import sys # directory = "B:\mozakra\\fourth year\\semester1\\machine learning\\project\\sawery" directory = raw_input("What is your name? ") for file_name in os.listdir(directory): print("Processing %s" % file_name) image = Image.open(os.path.join(directory, file_name)) x,y = image.size new_dimensions = (32, 32) output = image.resize(new_dimensions, Image.ANTIALIAS) output_file_name = raw_input("What is your name? ") #output_file_name = os.path.join(directory, "small_" + file_name) output.save(output_file_name, "JPEG", quality = 95) print("All done")
slides=[] slides.append("Hello. Press Enter.") slides.append("How are you?") slides.append("This is slide number 3") slides.append("Yes, this is indeed a cli slideshow presentation") slides.append(r""" ______________________________________ < This is how you do multi-line slides > -------------------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || """) slides.append(r""" _____ _ _ _ _ _ _ _ |_ _| |__ (_)___ (_)___ __ _ | |_(_) |_| | ___ | | | '_ \| / __| | / __| / _` | | __| | __| |/ _ \ | | | | | | \__ \ | \__ \ | (_| | | |_| | |_| | __/ |_| |_| |_|_|___/ |_|___/ \__,_| \__|_|\__|_|\___| Stuff like this can be easily added in vim if you call external programs. `:read ! figlet "This is a title"` """) slides.append("All it needs is the slides and six lines of python") slides.append("Infact, I believe it is better than powerpoint.") slides.append("Thank you for using KraftaNet.") clear='\033[2J\033[1;1H' print(clear) for slide in slides: print(slide) input("") print(clear)
print (63832+750) print ((20+50+80+120+160+200)*2-20+822) ''' 1,进入各种老虎机,显示账号是吃肉的小花 2,点击hud的齿轮,就回到了大厅 3,水果机进不去 4,没有任务 ''' for i in range(1,10,2): print (i) if i%5==4: print ('bbbb') break else: print (i) def myaddstr(x): 'str+str' return(x+x) print (myaddstr.__doc__)#用来查看函数说明文字的 print (myaddstr(1))
def get_number(): numberlist=[] numbers=open("a.txt",'r').readlines() for number in numbers: number.strip('\n') numberlist.append(number) list=[] i=0 for i in xrange(len(numberlist)): w={'phone':numberlist[i].strip('\n')} list.append(w) i+=1 return list if __name__=="__main__": print get_number() def get_number(n): numberlist=[] numbers=open("a.txt",'r').readlines() for number in numbers: number.strip('\n') numberlist.append(number) list=[] i=0 for i in xrange(len(numberlist)): w={'phone':numberlist[i].strip('\n')} list.append(w) i+=1 return list[n] if __name__=="__main__": print get_number(0) print get_number(-1)
import csv import re class Navigate: # away to get the line number of something we want @staticmethod def get_line(word='Why', filename="sample.txt"): with open(filename) as file: for num, line in enumerate(file, 1): if word in line: return num @staticmethod def get_column_number(filename="sample.txt"): with open(filename) as file: reader = csv.reader(file, delimiter=' ', skipinitialspace=True) first_row = next(reader) num_cols = len(first_row) print(num_cols) @staticmethod def get_specific_column_number(word="do", filename="sample.txt"): file = open(filename,"r") list = [] for line in file: fields = line.split(" ") list.append(fields) for i in range(0, len(list)): j = 0 for item in list[i]: if word in item: return j j += len(item) + 1
def function_quarter(x,y): # x,y = input(), input() if x > 0: if y > 0: print("I quarter") else: print("IV quarter") else: if y > 0: print("II quarter") else: print("III quarter") function_quarter(3, 4) function_quarter(-3.5, 8) function_quarter(-3.5, -8) function_quarter(3, -4)
num = raw_input("Enter a number:") num = int(num) if num%2 == 0: print("Even number.") else: print("Odd number.")
"""Manipulates path.""" import os import typing as t # NOQA def get_path_seperator(): # type: () -> str """Returns character that seperates directories in the PATH env variable""" if 'nt' == os.name: return ';' else: return ':' class PathUpdater(object): def __init__(self, path_seperator): # type: (str) -> None self._path_seperator = path_seperator self._case_sensitive = 'nt' != os.name def _arg_to_list(self, path): # type: (t.Union[str, t.List[str], None]) -> t.List[str] if not path: return [] elif isinstance(path, str): return [path] else: return [p for p in path] def _normalize_path_value(self, path): # type: (str) -> str """Makes path lower case on Windows, stays the same otherwise.""" if self._case_sensitive: return path else: return path.lower() def _normalize_path_arg(self, path_arg): # type: (t.Union[str, t.List[str], None]) -> t.List[str] return [self._normalize_path_value(p) for p in self._arg_to_list(path_arg)] def _remove_matching_elements(self, new_path, old_path): # type: (t.Union[str, t.List[str], None], t.Union[str, t.List[str], None]) -> t.Tuple[t.List[str], t.List[str]] # NOQA """Removes elements found in both lists, preserves order.""" norm_old_path = self._normalize_path_arg(old_path) new_path_list = self._arg_to_list(new_path) norm_new_path = [self._normalize_path_value(p) for p in new_path_list] for i in range(len(norm_old_path)): while i < len(norm_old_path) and norm_old_path[i] in norm_new_path: while norm_old_path[i] in norm_new_path: delete_index = norm_new_path.index(norm_old_path[i]) del norm_new_path[delete_index] del new_path_list[delete_index] del norm_old_path[i] return new_path_list, norm_old_path def update_paths(self, path_var_name, new_path=None, old_path=None): # type: (str, t.Union[str, t.List[str], None], t.Union[str, t.List[str], None]) -> str # NOQA """ Given the name of an environment variables that stores a list of paths, return a value where, optionally one path is added and optionally one may be removed. Also updates the environment variable. """ new_path, old_path = self._remove_matching_elements( new_path, old_path) original_value = os.environ.get(path_var_name, '') original_list = original_value.split(self._path_seperator) modified_list = self._update_paths(original_list, new_path, old_path) modified_value = self._path_seperator.join(modified_list) return modified_value def _update_paths(self, original_list, new_path, old_path): # type: (t.List[str], t.List[str], t.List[str]) -> t.List lc_list = [self._normalize_path_value(e) for e in original_list] remove_indices = [] # type: t.List[int] for op in old_path: if op in lc_list: # Remove only once remove_indices.append(lc_list.index(op)) filtered_list = [original_list[i] for i in range(len(original_list)) if i not in remove_indices] modified_list = new_path + filtered_list return modified_list
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ ans = [] final = [] parent = [root] children = [] while parent : for p in parent : if p : ans.append(p.val) children.append(p.left) children.append(p.right) if ans : final.append(sum(ans)/float(len(ans))) parent = children children = [] ans = [] return final
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ '''So basically we are trying to first find the position from where the reversal will begin''' '''And then start reversing till required''' if not head or not head.next or n == m : return head dummy = ListNode(0) dummy.next = head prev = dummy '''Remember to find the value of k here only! We are reducing the value of m later in the code.''' k = n-m while m-1 : prev = prev.next m -= 1 curr = prev.next one = prev two = curr while k+1 : nextnode = curr.next curr.next = prev prev, curr = curr, nextnode k -= 1 one.next = prev two.next = curr return dummy.next
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if not head or not head.next : return None prev = last = head while n : last = last.next n -= 1 if not last : return head.next while last.next : last = last.next prev = prev.next prev.next = prev.next.next return head
# how to use argparse? # https://docs.python.org/3/library/argparse.html import argparse # I - The first step in using the argparse is creating an ArgumentParser object: parser = argparse.ArgumentParser(description='Process some integers.') # II - Filling an ArgumentParser with information about program arguments is done by making calls to the add_argument() method. parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
# Non Abundant Sum # A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the # proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. # A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. # As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant # numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two # abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest # number that cannot be expressed as the sum of two abundant numbers is less than this limit. # Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. import math import functools as ft import timeit @ft.lru_cache(maxsize=None) def abundant(num): sumdivs = 1 for i in range(2,math.floor(num/2)+1): if num%i == 0: sumdivs += i if sumdivs > num: return True return False total = 0 start=timeit.default_timer() for num in range(1,28124): flag = True for j in range(1,math.floor(num/2)+1): if abundant(j) and abundant(num-j): flag = False break if flag: total += num end = timeit.default_timer() print(total) print('total time:') print(end-start)
""" Brainfuck to python compiler. Example: $ cat mul.bf read a and b ,>,< | a | b | c | d | compute c = a*b using d as temp (pointer starts and ends and a) [ sum b to c and copy in d (ends in b) >[->+>+<<] move d in b (ends in d) >>[-<<+>>] back on a <<<- ] print c >>. $ python bpc.py --comments --memory 5 --optimizations 2 --output a.py mul.bf $ cat a.py # -*- coding: UTF-8 -*- m = [ 0 ] * 5 p = 0 # read a and b m[p] = int(raw_input("Insert a number: ") or 0) m[p + 1] = int(raw_input("Insert a number: ") or 0) # | a | b | c | d | # compute c = a*b using d as temp (pointer starts and ends and a) while m[p]: # sum b to c and copy in d (ends in b) p = (p + 1) % 5 while m[p]: m[p] -= 1 m[p + 1] += 1 m[p + 2] += 1 # move d in b (ends in d) p = (p + 2) % 5 while m[p]: m[p] -= 1 m[p - 2] += 1 # back on a m[p - 3] -= 1 p = (p - 3) % 5 # print c print m[p + 2] $ python a.py Insert a number: 5 Insert a number: 3 15 $ """ import click import re class CodeBuilder(object): """ Builds the code by incrementally adding statements to it, automatically managing code indentation. """ def __init__(self, indent_size=4, indent_char=' '): self.code = list() self.indent = 0 self.indent_size = indent_size self.indent_char = indent_char def start_block(self): self.indent += self.indent_size def end_block(self): self.indent -= self.indent_size assert self.indent >= 0 def append(self, statements): self.code += [self.indent_char * self.indent + s for s in statements.split('\n')] def stream_code(self): comment, first_line = False, True for row in self.code: if re.match(r'^\s*#', row): if not comment and not first_line: yield '' comment = True else: comment = False yield row first_line = False def get_code(self): return '\n'.join(c for c in self.stream_code()) class Tokenizer(object): """ Splits the code into tokens (either instructions or comments). Generates an event for each token and when the process has finished. """ instruction_set = set(['+', '-', '<', '>', '.', ',', ']', '[']) def __init__(self): self.handlers = { 'finish': list(), 'instruction': list(), 'comment': list(), } def _invoke_handlers(self, handler_type, *args, **kwargs): for handler in self.handlers[handler_type]: handler(handler_type, *args, **kwargs) def register_handler(self, message_type, handler): assert message_type in self.handlers.keys() self.handlers[message_type].append(handler) def tokenize(self, code): i, code_length = 0, len(code) while i < code_length: if code[i] in self.instruction_set: self._invoke_handlers('instruction', code[i], i) i += 1 else: start = i while i < code_length and not code[i] in self.instruction_set: i += 1 self._invoke_handlers('comment', code[start:i], start, i) self._invoke_handlers('finish') class Compiler0(object): """ Simple and direct translation of brainfuck instructions into their python equivalent. """ def __init__(self, tokenizer, builder, memory_size, comments, dump_memory): self.memory_size = memory_size self.dump_memory = dump_memory self.comments = comments self.builder = builder self.tokenizer = tokenizer self.tokenizer.register_handler('instruction', self.on_instruction) self.tokenizer.register_handler('finish', self.on_finish) if self.comments: self.tokenizer.register_handler('comment', self.on_comment) self.write_incipit() def write_incipit(self): self.builder.append('# -*- coding: UTF-8 -*-') self.builder.append('m = [ 0 ] * %d' % self.memory_size) self.builder.append('p = 0') def on_instruction(self, _type, instruction, *args, **kwargs): if instruction == '+' or instruction == '-': self.builder.append('m[p] %s= 1' % instruction) elif instruction == '<': self.builder.append('p = (p - 1) %% %d' % self.memory_size) elif instruction == '>': self.builder.append('p = (p + 1) %% %d' % self.memory_size) elif instruction == ',': self.builder.append('m[p] = int(raw_input("Insert a number: ") or 0)') elif instruction == '.': self.builder.append('print m[p]') elif instruction == '[': self.builder.append('while m[p]:') self.builder.start_block() elif instruction == ']': self.builder.end_block() def on_comment(self, _type, comment, *args, **kwargs): for comment in (c.strip() for c in comment.split('\n')): if comment: self.builder.append('# ' + comment) def on_finish(self, _type, *args, **kwargs): assert self.builder.indent == 0, 'Some loops are not closed' if self.dump_memory: self._write_dump_memory() def _write_dump_memory(self): if self.comments: self.builder.append('# dump the memory') self.builder.append( "print '\\n~~~ Program Terminated ~~~'\n" "print 'Pointer:', p\n" "print 'Memory:'\n" "m += [ 0 ] * ({dump_step} - {memory_size} % {dump_step})\n" "dump = ('{{:4d}}' * {dump_step}).format\n" "for i in range(0, {memory_size}, {dump_step}):\n" " print '{{:7d}} | {{}}'.format(i, dump(*m[i:i + {dump_step}]))\n" "".format(memory_size=self.memory_size, dump_step=16)) class Compiler1(Compiler0): """ Compiles the code and aggregates similar operations to a single macro instruction. For example, '+++' becomes 'm[p]+=3', '<<<<' becomes 'p-=4' and so on. """ def __init__(self, *args, **kwargs): super(Compiler1, self).__init__(*args, **kwargs) self.operation, self.times = None, 0 self.accumulated = set(['+', '-', '<', '>']) def _flush(self): if self.operation == '+' or self.operation == '-': self.builder.append('m[p] %s= %d' % (self.operation, self.times)) elif self.operation == '<': self.builder.append('p = (p - %d) %% %d' % (self.times, self.memory_size)) elif self.operation == '>': self.builder.append('p = (p + %d) %% %d' % (self.times, self.memory_size)) def on_finish(self, *args, **kwargs): self._flush() super(Compiler1, self).on_finish(*args, **kwargs) def on_instruction(self, _type, instruction, *args, **kwargs): if instruction in self.accumulated: if instruction == self.operation: self.times += 1 else: self._flush() self.times, self.operation = 1, instruction else: self._flush() self.times, self.operation = 0, None super(Compiler1, self).on_instruction(_type, instruction, *args, **kwargs) class Compiler2(Compiler0): """ Caches the pointer movements and uses relative offsets to index memory whenever possible. Also aggregates identical brainfuck instructions into a single python statement. """ def __init__(self, *args, **kwargs): super(Compiler2, self).__init__(*args, **kwargs) self.operation = None self.times = self.pointer_move = self.pointer_position = 0 self.accumulated = set(['+', '-', '<', '>']) def _get_relative_pointer_string(self): if self.pointer_move: return 'p %s %d' % (['-', '+'][self.pointer_move > 0], abs(self.pointer_move)) else: return 'p' def _flush(self): if self.operation == '+' or self.operation == '-': self.builder.append('m[%s] %s= %d' % (self._get_relative_pointer_string(), self.operation, self.times)) elif self.operation == '<': self.pointer_move -= self.times elif self.operation == '>': self.pointer_move += self.times def _commit_pointer(self): if self.pointer_move: self.builder.append('p = (%s) %% %d' % (self._get_relative_pointer_string(), self.memory_size)) self.pointer_move = 0 def on_instruction(self, _type, instruction, *args, **kwargs): if instruction in self.accumulated and instruction == self.operation: self.times += 1 return self._flush() self.times, self.operation = 1, instruction if instruction == ',': self.builder.append('m[%s] = int(raw_input("Insert a number: ") or 0)' % self._get_relative_pointer_string()) elif instruction == '.': self.builder.append('print m[%s]' % self._get_relative_pointer_string()) elif instruction == '[': self._commit_pointer() self.builder.append('while m[%s]:' % self._get_relative_pointer_string()) self.builder.start_block() elif instruction == ']': self._commit_pointer() self.builder.end_block() def compile(code, memory, comments, dump, indent, tab_indent, optimizations): """ Compiles the given brainfuck code into python. """ assert memory > 0, 'Memory must be larger than 0' assert indent > 0, 'Indentation width must be larger than 0' assert optimizations in set([0, 1, 2]), 'Optimization level must be 0, 1 or 2' builder = CodeBuilder(indent_size=indent, indent_char='\t' if tab_indent else ' ') tokenizer = Tokenizer() compiler_cls = (Compiler0 if optimizations == 0 else Compiler1 if optimizations == 1 else Compiler2) compiler = compiler_cls(tokenizer, builder, memory, comments, dump) tokenizer.tokenize(code) return builder.get_code() @click.command() @click.argument('input', type=click.File('r')) @click.option('--output', '-o', type=click.File('w'), default='a.py', help='Compiled python file name or \'-\' for stdout.') @click.option('--memory', '-m', default=1024, help='The size of the memory used by the program.') @click.option('--comments/--no-comments', '-c', default=False, help='Include comments in generated file.') @click.option('--dump/--no-dump', '-d', default=False, help='Dump the memory and the pointer at the end of the program') @click.option('--indent', '-i', default=4, help='Number of characters used to indent the code.') @click.option('--tab-indent/--space-indent', '-t', default=False, help='Indent with tabs or spaces.') @click.option('--optimizations', '-O', default=2, help='Optimization level (0, 1, 2)') # aggiungere dimensione celle # aggiugere stile di memoria (extend-on-overflow, wrap-around, throw-exception) def main_cli(input, output, *args, **kwargs): code = input.read() compiled = compile(code, *args, **kwargs) output.write(compiled) if __name__ == '__main__': main_cli()
""" Blackbody temperature calculations """ import numpy as np import ChiantiPy.tools.constants as const class blackStar: """ Calculate blackbody radiation Parameters ---------- temperature : `~numpy.ndarray` Temperature in Kelvin radius : `~numpy.ndarray` Stellar radius in cm Attributes ---------- Temperature : `~numpy.ndarray` Temperature in Kelvin Radius : `~numpy.ndarray` Stellar radius in cm Incident : `~numpy.ndarray` Blackbody photon distribution """ def __init__(self, temperature, radius): self.Temperature = temperature self.Radius = radius def incident(self, distance, energy): """ Calculate photon distribution times the visible cross-sectional area. Parameters ---------- distance : `~numpy.ndarray` Distance to the stellar object in cm energy : `~numpy.ndarray` Energy range in erg Notes ----- This function returns the photon distribution instead of the distribution times the cross-sectional area. Is this correct? Why is the incident photon distribution calculated at all? """ print((' distance %10.2e energy '%(energy))) bb = blackbody(self.Temperature, energy) out = const.pi*(self.Radius/distance)**2*bb['photons'] self.Incident = bb def blackbody(temperature, variable, hnu=1): """ Calculate the blackbody photon distribution as a function of energy (`hnu` = 1) or as a function of wavelength (`hnu` = 0) in units of :math:`\mathrm{photons}\,\mathrm{cm}^{-2}\,\mathrm{s}^{-1}\,\mathrm{str}^{-1}\,\mathrm{erg}^{-1}` Parameters ---------- temperature : `~numpy.float64` Temperature at which to calculate the blackbody photon distribution variable : `~numpy.ndarray` Either energy (in erg) or wavelength (in angstrom) hnu : `int` If 1, calculate distribution as a function of energy. Otherwise, calculate it as a function of wavelength Returns ------- {'photons', 'temperature', 'energy'} or {'photons', 'temperature', 'wvl'} : `dict` """ if hnu: energy = variable bb =(2./(const.planck*(const.hc**2)))*energy**2/(np.exp(energy/(const.boltzmann*temperature)) - 1.) return {'photons':bb, 'temperature':temperature, 'energy':energy} else: wvl = 1.e-8*variable bb = ((2.*const.pi*const.light)/wvl**4)/(np.exp(const.hc/(wvl*const.boltzmann*temperature)) - 1.) return {'photons':bb, 'temperature':temperature, 'wvl':wvl}
#Numpy 2-D array import numpy as np np_2d=np.array([[1.73,1.68,1.93,1.44], [65.2,59.7,63.0,66.9]]) print(np_2d) print(np_2d.shape) print(np_2d[0][2]) print(np_2d[0,2]) print(np_2d[:,1:3]) print(np_2d[1:])
"""Functions to handle currency exchange.""" import requests from django.conf import settings class CurrencyRates: """Fetch current exchange rates for USD conversion.""" ENDPOINT = "http://api.exchangeratesapi.io/v1/latest" def __init__(self): """Create request and fetch.""" url = ( f"{self.ENDPOINT}?access_key={settings.EXCHANGERATESAPI_KEY}" "&symbols=USD,GBP,AUD" "&format=1" ) print(f"Request URL: {url}") response = requests.get(url) if response.status_code != 200: raise ValueError( "FX API request refused (https://api.exchangeratesapi.io)" f" (HTTP status {response.status_code})" ) self.rates = response.json()['rates'] def get_rate(self, currency): """Get conversion rate from USD to given currency.""" usd = self.rates['USD'] return self.rates[currency] / usd def USD_to_USD(usd): """Blank function to return USD unaltered.""" return round(usd, 2) def GBX_to_USD(pence): """Convert GBP pence to USD.""" c = CurrencyRates() rate = c.get_rate('GBP') return round((pence / 100) / rate, 2) def GBP_to_USD(gbp): """Convert GBP to USD.""" c = CurrencyRates() rate = c.get_rate('GBP') return round(gbp / rate, 2) def AUD_to_USD(aud): """Convert AUD to USD.""" c = CurrencyRates() rate = c.get_rate('AUD') return round(aud / rate, 2) exchange = { "USD": USD_to_USD, "GBX": GBX_to_USD, "GBP": GBP_to_USD, "AUD": AUD_to_USD, }
import turtle n = 1 a = 30 x = -100 y = 0 turtle.shape('turtle') turtle.left(90) for i in range(8): turtle.penup() turtle.goto(x,y) turtle.pendown() for i in range(360): turtle.left(1) turtle.forward(n/4) for i in range(360): turtle.right(1) turtle.forward(n / 4) n+=0.5 turtle.mainloop()
# Explanation # Bubble sort, sorts the array elements by repeatedly moving the largest element to the highest index position. # In bubble sorting, consecutive adjacent pairs of elements in the array are compared with each other. # If the element at the lower index is greater than the element at the higher index then the two elements are interchanged # so that the element is placed before the bigger one. # NOTE: At the end of first pass, the largest element in the arr will be placed it's proper position # Worst Case Time Complexity [ Big-O ]: O(n2) # Best Case Time Complexity [Big-omega]: O(n) # Average Time Complexity [Big-theta]: O(n2) # Space Complexity: O(1) arr = list(map(int,input().split())) n = len(arr) status = False for i in range(n): for j in range(n-i-1): if arr[j] > arr[j+1]: arr[j],arr[j+1] = arr[j+1], arr[j] status = True if status == False: # if the arr is already sorted then break break print(*arr)
# Video Reference : https://www.youtube.com/watch?v=QN9hnmAgmOc&t=376s # Quick Sort is based on the concept of Divide and Conquer, just like merge sort # 1. Select an element pivot from the array element # 2. Rearrange the element in the array in such a way that all elements that # are less than the pivot appear before the pivot and all elements greater than the pivot element come after it. # 3. After such a partitioning, the pivot is placed in it's final position. # 4. Recursively sort the two sub-array. # Worst Case Time Complexity [ Big-O ]: O(n2) # Best Case Time Complexity [Big-omega]: O(n*log n) # Average Time Complexity [Big-theta]: O(n*log n) # Space Complexity: O(n*log n) def partition(arr, start, end): pivot = arr[(start + end) // 2] low = start - 1 high = end + 1 while True: low += 1 while arr[low] < pivot: low += 1 high -= 1 while arr[high] > pivot: high -= 1 if low >= high: return high # If an element at low (on the left of the pivot) is larger than the # element at high (on right right of the pivot), then swap them arr[low], arr[high] = arr[high], arr[low] def quick_sort(arr): def _quick_sort(arr, start, end): if start < end: split_index = partition(arr, start, end) _quick_sort(arr, start, split_index) _quick_sort(arr, split_index + 1, end) _quick_sort(arr, 0, len(arr) - 1) arr = list(map(int, input().split())) quick_sort(arr) print(*arr)
# Problem Statement Link : https://leetcode.com/problems/power-of-two/ def powerOfTwo(n): if n < 0: return False ans = 0 while n: ans += 1 n = n & (n - 1) if ans == 1: return True else: return False n = int(input()) print(powerOfTwo(n))
""" Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview """ x = 5 print(type(x))
### imports ### import face_recognition as fr import os import cv2 import face_recognition import numpy as np ### encode all the face images ### def encoded_faces(): #looks through the facee_iamges folder and encodes all the faces ### # returns a dict of (name, image encoded) encoded = {} for dirpath, dnames, fnames in os.walk("./face_images"): # look through each image in face_iamges folder for f in fnames: if f.endswith(".jpg") or f.endswith(".png"): face = fr.load_image_file("face_images/" + f) # load each file encoding = fr.face_encodings(face)[0] # get the face encoding encoded[f.split(".")[0]] = encoding # split encoding add to dict return encoded ### encode image from file name ### def unknown_image(img): face = fr.load_image_file("face_images/" + img) # load the image file encoding = fr.face_encodings(face)[0] # get the face encoding return encoding ### find the faces and label in known ### def search_face(im): # param 'im' is str of file path # returns a list of face names face_names = [] # create a list for the face names found faces = encoded_faces() # set the function faces_encoded = list(faces.values()) # create a list of the encoded faces values known_face_names = list(faces.keys()) # creat a list of the faces key values img = cv2.imread(im, 1) # read in the image face_locations = face_recognition.face_locations(img) # find the face locations from the image unknown_face_encodings = face_recognition.face_encodings(img, face_locations) # find the unkown face encodings for face_encoding in unknown_face_encodings: # loop through unkown face encodings # See if the face is a match for the known face(s) match_list = face_recognition.compare_faces(faces_encoded, face_encoding) # see if the face is a match name = "Unknown" face_distances = face_recognition.face_distance(faces_encoded, face_encoding) # find face distances best_match = np.argmin(face_distances) # find the smallest distance from known face to new face if match_list[best_match]: # if a match name = known_face_names[best_match] # set the name face_names.append(name) # add the name to the list ### create the visual face boxes and text ### for (top, right, bottom, left), name in zip(face_locations, face_names): # loop through face_locations and face_names # Draw a box around the face cv2.rectangle(img, (left-20, top-20), (right+20, bottom+40), (0, 255, 0), 1) # set the box parameters font = cv2.FONT_HERSHEY_DUPLEX # set the font cv2.putText(img, name, (left -20, bottom +75), font, 1.0, (0, 0, 255), 2) # set the text parameters ### return the image with face names if found ### while True: cv2.imshow('Face Recgonition Results', img) # show the title and image if cv2.waitKey(1) & 0xFF == ord('q'): # set wait key and q exit command return face_names ### run the function on the image to search ### # print(search #_face('Barak_Joe.jpg')) # alternative example print(search_face('test_images/Jumanji_Cast.jpg'))
import sys import warnings import matplotlib.pyplot as plt import numpy as np from bokeh.plotting import figure, show from scipy import integrate class PressureMatrix: r"""This class calculates the pressure matrix of the object with the given parameters. It is supposed to be an attribute of a bearing element, but can work on its on to provide graphics for the user. Parameters ---------- Grid related ^^^^^^^^^^^^ Describes the discretization of the problem nz: int Number of points along the Z direction (direction of flow). ntheta: int Number of points along the direction theta. NOTE: ntheta must be odd. nradius: int Number of points along the direction r. length: float Length in the Z direction (m). Operation conditions ^^^^^^^^^^^^^^^^^^^^ Describes the operation conditions. omega: float Rotation of the rotor (rad/s). p_in: float Input Pressure (Pa). p_out: float Output Pressure (Pa). load: float Load applied to the rotor (N). Geometric data of the problem ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Describes the geometric data of the problem. radius_rotor: float Rotor radius (m). radius_stator: float Stator Radius (m). eccentricity: float, optional Eccentricity (m) is the euclidean distance between rotor and stator centers. The center of the stator is in position (0,0). beta: float, optional Attitude angle. Angle between the origin and the eccentricity (rad). Fluid characteristics ^^^^^^^^^^^^^^^^^^^^^ Describes the fluid characteristics. viscosity: float Viscosity (Pa.s). density: float Fluid density(Kg/m^3). Returns ------- An object containing the pressure matrix and its data. Attributes ---------- ltheta: float Length in the theta direction (rad). dz: float Range size in the Z direction. dtheta: float Range size in the theta direction. ntotal: int Number of nodes in the grid., ntheta, nradius, n_interv_z, n_interv_theta, n_interv_z: int Number of intervals on Z. n_interv_theta: int Number of intervals on theta. n_interv_radius: int Number of intervals on r. p_mat_analytical : array of shape (nz, ntheta) The analytical pressure matrix. p_mat_numerical : array of shape (nz, ntheta) The numerical pressure matrix. xi: float Eccentricity (m) (distance between rotor and stator centers) on the x-axis. It is the position of the center of the rotor. The center of the stator is in position (0,0). yi: float Eccentricity (m) (distance between rotor and stator centers) on the y-axis. It is the position of the center of the rotor. The center of the stator is in position (0,0). re : array of shape (nz, ntheta) The external radius in each position of the grid. ri : array of shape (nz, ntheta) The internal radius in each position of the grid. z : array of shape (1, nz) z along the object. It goes from 0 to lb. xre : array of shape (nz, ntheta) x value of the external radius. xri : array of shape (nz, ntheta) x value of the internal radius. yre : array of shape (nz, ntheta) y value of the external radius. yri : array of shape (nz, ntheta) y value of the internal radius. eccentricity : float distance between the center of the rotor and the stator. difference_between_radius: float distance between the radius of the stator and the radius of the rotor. eccentricity_ratio: float eccentricity/difference_between_radius bearing_type: str type of structure. 'short_bearing': short; 'long_bearing': long; 'medium_size': in between short and long. if length/radius_stator <= 1/4 it is short. if length/radius_stator > 8 it is long. radial_clearance: float Difference between both stator and rotor radius, regardless of eccentricity. analytical_pressure_matrix_available: bool True if analytically calculated pressure matrix is available. numerical_pressure_matrix_available: bool True if numerically calculated pressure matrix is available. Examples -------- >>> from ross.fluid_flow import fluid_flow as flow >>> import numpy as np >>> from bokeh.plotting import show >>> nz = 8 >>> ntheta = 64 >>> nradius = 11 >>> length = 0.01 >>> omega = 100.*2*np.pi/60 >>> p_in = 0. >>> p_out = 0. >>> radius_rotor = 0.08 >>> radius_stator = 0.1 >>> viscosity = 0.015 >>> density = 860. >>> eccentricity = 0.001 >>> beta = np.pi >>> my_fluid_flow = flow.PressureMatrix(nz, ntheta, nradius, length, ... omega, p_in, p_out, radius_rotor, ... radius_stator, viscosity, density, ... beta=beta, eccentricity=eccentricity) >>> my_fluid_flow.calculate_pressure_matrix_analytical() # doctest: +ELLIPSIS array([[-0.00000... >>> my_fluid_flow.calculate_pressure_matrix_numerical() # doctest: +ELLIPSIS array([[... >>> # to show the plots you can use: >>> # show(my_fluid_flow.plot_eccentricity()) >>> # show(my_fluid_flow.plot_pressure_theta(z=int(nz/2))) >>> my_fluid_flow.matplot_pressure_theta(z=int(nz/2)) # doctest: +ELLIPSIS <matplotlib.axes._subplots.AxesSubplot object at... """ def __init__( self, nz, ntheta, nradius, length, omega, p_in, p_out, radius_rotor, radius_stator, viscosity, density, beta=None, eccentricity=None, load=None, ): if load is None and eccentricity is None: sys.exit("Either load or eccentricity must be given.") self.nz = nz self.ntheta = ntheta self.nradius = nradius self.n_interv_z = nz - 1 self.n_interv_theta = ntheta - 1 self.n_interv_radius = nradius - 1 self.length = length self.ltheta = 2.0 * np.pi self.dz = length / self.n_interv_z self.dtheta = self.ltheta / self.n_interv_theta self.ntotal = self.nz * self.ntheta self.omega = omega self.p_in = p_in self.p_out = p_out self.radius_rotor = radius_rotor self.radius_stator = radius_stator self.viscosity = viscosity self.density = density self.radial_clearance = self.radius_stator - self.radius_rotor self.difference_between_radius = radius_stator - radius_rotor self.bearing_type = "" if self.length / self.radius_stator <= 1 / 4: self.bearing_type = "short_bearing" elif self.length / self.radius_stator >= 8: self.bearing_type = "long_bearing" else: self.bearing_type = "medium_size" self.eccentricity = eccentricity self.eccentricity_ratio = None self.load = load if self.eccentricity is None: self.eccentricity = ( self.calculate_eccentricity_ratio() * self.difference_between_radius ) self.eccentricity_ratio = self.eccentricity / self.difference_between_radius if self.load is None: self.load = self.get_rotor_load() if beta is None: self.beta = self.calculate_attitude_angle() else: self.beta = beta self.xi = self.eccentricity * np.cos(2 * np.pi - self.beta) self.yi = self.eccentricity * np.sin(2 * np.pi - self.beta) self.re = np.zeros([self.nz, self.ntheta]) self.ri = np.zeros([self.nz, self.ntheta]) self.z = np.zeros([1, self.nz]) self.xre = np.zeros([self.nz, self.ntheta]) self.xri = np.zeros([self.nz, self.ntheta]) self.yre = np.zeros([self.nz, self.ntheta]) self.yri = np.zeros([self.nz, self.ntheta]) self.p_mat_analytical = np.zeros([self.nz, self.ntheta]) self.c1 = np.zeros([self.nz, self.ntheta]) self.c2 = np.zeros([self.nz, self.ntheta]) self.c0w = np.zeros([self.nz, self.ntheta]) self.M = np.zeros([self.ntotal, self.ntotal]) self.f = np.zeros([self.ntotal, 1]) self.P = np.zeros([self.ntotal, 1]) self.p_mat_numerical = np.zeros([self.nz, self.ntheta]) self.gama = np.zeros([self.nz, self.ntheta]) self.calculate_coefficients() self.analytical_pressure_matrix_available = False self.numerical_pressure_matrix_available = False def calculate_attitude_angle(self): """Calculates the attitude angle based on the eccentricity. Returns ------- float Attitude angle Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_attitude_angle() # doctest: +ELLIPSIS 1.5... """ return np.arctan(np.pi * (1 - self.eccentricity_ratio ** 2) / (4 * self.eccentricity_ratio)) def calculate_pressure_matrix_analytical(self, method=0, force_type=None): """This function calculates the pressure matrix analytically. Parameters ---------- method: int Determines the analytical method to be used, when more than one is available. In case of a short bearing: 0: based on the book Tribology Series vol. 33, by Frene et al., chapter 5. 1: based on the chapter Linear and Nonlinear Rotordynamics, by Ishida and Yamamoto, from the book Flow-Induced Vibrations. In case of a long bearing: 0: based on the Fundamentals of Fluid Flow Lubrification, by Hamrock, chapter 10. force_type: str If set, calculates the pressure matrix analytically considering the chosen type: 'short' or 'long'. Returns ------- p_mat_analytical: matrix of float Pressure matrix of size (nz x ntheta) Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_pressure_matrix_analytical() # doctest: +ELLIPSIS array([[... """ if self.bearing_type == "short_bearing" or force_type == 'short': if method == 0: for i in range(0, self.nz): for j in range(0, self.ntheta): # fmt: off self.p_mat_analytical[i][j] = ( ((-3 * self.viscosity * self.omega) / self.difference_between_radius ** 2) * ((i * self.dz - (self.length / 2)) ** 2 - (self.length ** 2) / 4) * (self.eccentricity_ratio * np.sin(j * self.dtheta)) / (1 + self.eccentricity_ratio * np.cos(j * self.dtheta)) ** 3) # fmt: on if self.p_mat_analytical[i][j] < 0: self.p_mat_analytical[i][j] = 0 elif method == 1: for i in range(0, self.nz): for j in range(0, self.ntheta): # fmt: off self.p_mat_analytical[i][j] = (3 * self.viscosity / ((self.difference_between_radius ** 2) * (1. + self.eccentricity_ratio * np.cos( j * self.dtheta)) ** 3)) * \ (-self.eccentricity_ratio * self.omega * np.sin( j * self.dtheta)) * \ (((i * self.dz - (self.length / 2)) ** 2) - ( self.length ** 2) / 4) # fmt: on if self.p_mat_analytical[i][j] < 0: self.p_mat_analytical[i][j] = 0 elif self.bearing_type == "long_bearing" or force_type == 'long': if method == 0: for i in range(0, self.nz): for j in range(0, self.ntheta): self.p_mat_analytical[i][j] = (6 * self.viscosity * self.omega * (self.ri[i][j] / self.difference_between_radius) ** 2 * self.eccentricity_ratio * np.sin(self.gama[i][j]) * (2 + self.eccentricity_ratio * np.cos(self.gama[i][j]))) / ( (2 + self.eccentricity_ratio ** 2) * (1 + self.eccentricity_ratio * np.cos( self.gama[i][j])) ** 2) + \ self.p_in if self.p_mat_analytical[i][j] < 0: self.p_mat_analytical[i][j] = 0 elif self.bearing_type == "medium_size": raise ValueError("The pressure matrix for a bearing that is neither short or long can only be calculated " "numerically. Try calling calculate_pressure_matrix_numerical or setting force_type " "to either 'short' or 'long' in calculate_pressure_matrix_analytical.") self.analytical_pressure_matrix_available = True return self.p_mat_analytical def calculate_coefficients(self): """This function calculates the constants that form the Poisson equation of the discrete pressure (central differences in the second derivatives). It is executed when the class is instantiated. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_coefficients() >>> my_fluid_flow.c0w # doctest: +ELLIPSIS array([[... """ for i in range(0, self.nz): zno = i * self.dz self.z[0][i] = zno plot_eccentricity_error = False position = -1 for j in range(0, self.ntheta): # fmt: off self.gama[i][j] = j * self.dtheta + (np.pi - self.beta) [radius_external, self.xre[i][j], self.yre[i][j]] = \ self.external_radius_function(self.gama[i][j]) [radius_internal, self.xri[i][j], self.yri[i][j]] = \ self.internal_radius_function(zno, self.gama[i][j]) self.re[i][j] = radius_external self.ri[i][j] = radius_internal w = self.omega * self.ri[i][j] k = (self.re[i][j] ** 2 * (np.log(self.re[i][j]) - 1 / 2) - self.ri[i][j] ** 2 * (np.log(self.ri[i][j]) - 1 / 2)) / (self.ri[i][j] ** 2 - self.re[i][j] ** 2) self.c1[i][j] = (1 / (4 * self.viscosity)) * ((self.re[i][j] ** 2 * np.log(self.re[i][j]) - self.ri[i][j] ** 2 * np.log(self.ri[i][j]) + (self.re[i][j] ** 2 - self.ri[i][j] ** 2) * (k - 1)) - 2 * self.re[i][j] ** 2 * ( (np.log(self.re[i][j]) + k - 1 / 2) * np.log( self.re[i][j] / self.ri[i][j]))) self.c2[i][j] = (- self.ri[i][j] ** 2) / (8 * self.viscosity) * \ ((self.re[i][j] ** 2 - self.ri[i][j] ** 2 - (self.re[i][j] ** 4 - self.ri[i][j] ** 4) / (2 * self.ri[i][j] ** 2)) + ((self.re[i][j] ** 2 - self.ri[i][j] ** 2) / (self.ri[i][j] ** 2 * np.log(self.re[i][j] / self.ri[i][j]))) * (self.re[i][j] ** 2 * np.log(self.re[i][j] / self.ri[i][j]) - (self.re[i][j] ** 2 - self.ri[i][j] ** 2) / 2)) self.c0w[i][j] = (- w * self.ri[i][j] * (np.log(self.re[i][j] / self.ri[i][j]) * (1 + (self.ri[i][j] ** 2) / (self.re[i][j] ** 2 - self.ri[i][j] ** 2)) - 1 / 2)) # fmt: on if not plot_eccentricity_error: if abs(self.xri[i][j]) > abs(self.xre[i][j]) or abs( self.yri[i][j] ) > abs(self.yre[i][j]): plot_eccentricity_error = True position = i if plot_eccentricity_error: self.plot_eccentricity(position) sys.exit( "Error: The given parameters create a rotor that is not inside the stator. " "Check the plotted figure and fix accordingly." ) def mounting_matrix(self): """This function assembles the matrix M and the independent vector f. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.mounting_matrix() >>> my_fluid_flow.M # doctest: +ELLIPSIS array([[... """ # fmt: off count = 0 for x in range(self.ntheta): self.M[count][count] = 1 self.f[count][0] = self.p_in count = count + self.nz - 1 self.M[count][count] = 1 self.f[count][0] = self.p_out count = count + 1 count = 0 for x in range(self.nz - 2): self.M[self.ntotal - self.nz + 1 + count][1 + count] = 1 self.M[self.ntotal - self.nz + 1 + count][self.ntotal - self.nz + 1 + count] = -1 count = count + 1 count = 1 j = 0 for i in range(1, self.nz - 1): a = (1 / self.dtheta ** 2) * (self.c1[i][self.ntheta - 1]) self.M[count][self.ntotal - 2 * self.nz + count] = a b = (1 / self.dz ** 2) * (self.c2[i - 1, j]) self.M[count][count - 1] = b c = -((1 / self.dtheta ** 2) * ((self.c1[i][j]) + self.c1[i][self.ntheta - 1]) + (1 / self.dz ** 2) * (self.c2[i][j] + self.c2[i - 1][j])) self.M[count, count] = c d = (1 / self.dz ** 2) * (self.c2[i][j]) self.M[count][count + 1] = d e = (1 / self.dtheta ** 2) * (self.c1[i][j]) self.M[count][count + self.nz] = e count = count + 1 count = self.nz + 1 for j in range(1, self.ntheta - 1): for i in range(1, self.nz - 1): a = (1 / self.dtheta ** 2) * (self.c1[i, j - 1]) self.M[count][count - self.nz] = a b = (1 / self.dz ** 2) * (self.c2[i - 1][j]) self.M[count][count - 1] = b c = -((1 / self.dtheta ** 2) * ((self.c1[i][j]) + self.c1[i][j - 1]) + (1 / self.dz ** 2) * (self.c2[i][j] + self.c2[i - 1][j])) self.M[count, count] = c d = (1 / self.dz ** 2) * (self.c2[i][j]) self.M[count][count + 1] = d e = (1 / self.dtheta ** 2) * (self.c1[i][j]) self.M[count][count + self.nz] = e count = count + 1 count = count + 2 count = 1 for j in range(self.ntheta - 1): for i in range(1, self.nz - 1): if j == 0: self.f[count][0] = (self.c0w[i][j] - self.c0w[i][self.ntheta - 1]) / self.dtheta else: self.f[count][0] = (self.c0w[i, j] - self.c0w[i, j - 1]) / self.dtheta count = count + 1 count = count + 2 # fmt: on def resolves_matrix(self): """This function resolves the linear system [M]{P}={f}. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.mounting_matrix() >>> my_fluid_flow.resolves_matrix() >>> my_fluid_flow.P # doctest: +ELLIPSIS array([[... """ self.P = np.linalg.solve(self.M, self.f) def calculate_pressure_matrix_numerical(self): """This function calculates the pressure matrix numerically. Returns ------- p_mat_numerical: matrix of float Pressure matrix of size (nz x ntheta) Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_pressure_matrix_numerical() # doctest: +ELLIPSIS array([[... """ self.mounting_matrix() self.resolves_matrix() for i in range(self.nz): for j in range(self.ntheta): k = j * self.nz + i if self.P[k] < 0: self.p_mat_numerical[i][j] = 0 else: self.p_mat_numerical[i][j] = self.P[k] self.numerical_pressure_matrix_available = True return self.p_mat_numerical def internal_radius_function(self, z, gama): """This function calculates the radius of the rotor given the radius and the position z. Parameters ---------- z: float Distance along the z-axis. gama: float Gama is the distance in the theta-axis. It should range from 0 to 2*np.pi. Returns ------- radius_internal: float The size of the internal radius at that point. xri: float The position x of the returned internal radius. yri: float The position y of the returned internal radius. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> radius_internal, xri, yri = my_fluid_flow.internal_radius_function(z=0, gama=0) >>> radius_internal 0.079 """ if (np.pi - self.beta) < gama < (2 * np.pi - self.beta): alpha = np.absolute(2 * np.pi - gama - self.beta) radius_internal = np.sqrt(self.radius_rotor ** 2 - (self.eccentricity * np.sin(alpha)) ** 2) + self.eccentricity * np.cos(alpha) xri = radius_internal * np.cos(gama) yri = radius_internal * np.sin(gama) else: alpha = self.beta + gama radius_internal = np.sqrt(self.radius_rotor ** 2 - (self.eccentricity * np.sin(alpha)) ** 2) + self.eccentricity * np.cos(alpha) xri = radius_internal * np.cos(gama) yri = radius_internal * np.sin(gama) return radius_internal, xri, yri def external_radius_function(self, gama): """This function calculates the radius of the stator. Parameters ---------- gama: float Gama is the distance in the theta-axis. It should range from 0 to 2*np.pi. Returns ------- radius_external: float The size of the external radius at that point. xre: float The position x of the returned external radius. yre: float The position y of the returned external radius. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> radius_external, xre, yre = my_fluid_flow.external_radius_function(gama=0) >>> radius_external 0.1 """ radius_external = self.radius_stator xre = radius_external * np.cos(gama) yre = radius_external * np.sin(gama) return radius_external, xre, yre def get_rotor_load(self): """Returns the load applied to the rotor, based on the eccentricity ratio. Suitable only for short bearings. Returns ------- float Load applied to the rotor. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.get_rotor_load() # doctest: +ELLIPSIS 1.5... """ if not self.bearing_type == "short_bearing": warnings.warn( "Function get_rotor_load suitable only for short bearings. " "The ratio between the bearing length and its radius should be less or " "equal to 0.25. Currently we have " + str(self.length / self.radius_stator) + "." ) return ( ( np.pi * self.radius_stator * 2 * self.omega * self.viscosity * (self.length ** 3) * self.eccentricity_ratio ) / ( 8 * (self.radial_clearance ** 2) * ((1 - self.eccentricity_ratio ** 2) ** 2) ) ) * (np.sqrt((16 / (np.pi ** 2) - 1) * self.eccentricity_ratio ** 2 + 1)) def modified_sommerfeld_number(self): """Returns the modified sommerfeld number. Returns ------- float The modified sommerfeld number. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.modified_sommerfeld_number() # doctest: +ELLIPSIS 6... """ return ( self.radius_stator * 2 * self.omega * self.viscosity * (self.length ** 3) ) / (8 * self.load * (self.radial_clearance ** 2)) def sommerfeld_number(self): """Returns the sommerfeld number. Returns ------- float The sommerfeld number. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.sommerfeld_number() # doctest: +ELLIPSIS 805... """ modified_s = self.modified_sommerfeld_number() return (modified_s / np.pi) * (self.radius_stator * 2 / self.length) ** 2 def calculate_eccentricity_ratio(self): """Calculate the eccentricity ratio for a given load using the sommerfeld number. Suitable only for short bearings. Returns ------- float The eccentricity ratio. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_eccentricity_ratio() # doctest: +ELLIPSIS 0.0... """ if not self.bearing_type == "short_bearing": warnings.warn( "Function calculate_eccentricity_ratio suitable only for short bearings. " "The ratio between the bearing length and its radius should be less or " "equal to 0.25. Currently we have " + str(self.length / self.radius_stator) + "." ) s = self.modified_sommerfeld_number() coefficients = [ 1, -4, (6 - (s ** 2) * (16 - np.pi ** 2)), -(4 + (np.pi ** 2) * (s ** 2)), 1, ] roots = np.roots(coefficients) for i in range(0, len(roots)): if 0 <= roots[i] <= 1: return np.sqrt(roots[i].real) sys.exit("Eccentricity ratio could not be calculated.") def get_analytical_stiffness_matrix(self): """Returns the stiffness matrix calculated analytically. Suitable only for short bearings. Returns ------- list of floats A list of length four including stiffness floats in this order: kxx, kxy, kyx, kyy Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.get_analytical_stiffness_matrix() # doctest: +ELLIPSIS [... """ if not self.bearing_type == "short_bearing": warnings.warn( "Function get_analytical_stiffness_matrix suitable only for short bearings. " "The ratio between the bearing length and its radius should be less or " "equal to 0.25. Currently we have " + str(self.length / self.radius_stator) + "." ) # fmt: off f = self.get_rotor_load() h0 = 1.0 / (((np.pi ** 2) * (1 - self.eccentricity_ratio ** 2) + 16 * self.eccentricity_ratio ** 2) ** 1.5) a = f / self.radial_clearance kxx = a * h0 * 4 * ((np.pi ** 2) * (2 - self.eccentricity_ratio ** 2) + 16 * self.eccentricity_ratio ** 2) kxy = (a * h0 * np.pi * ((np.pi ** 2) * (1 - self.eccentricity_ratio ** 2) ** 2 - 16 * self.eccentricity_ratio ** 4) / (self.eccentricity_ratio * np.sqrt(1 - self.eccentricity_ratio ** 2))) kyx = (-a * h0 * np.pi * ((np.pi ** 2) * (1 - self.eccentricity_ratio ** 2) * (1 + 2 * self.eccentricity_ratio ** 2) + (32 * self.eccentricity_ratio ** 2) * (1 + self.eccentricity_ratio ** 2)) / (self.eccentricity_ratio * np.sqrt(1 - self.eccentricity_ratio ** 2))) kyy = (a * h0 * 4 * ((np.pi ** 2) * (1 + 2 * self.eccentricity_ratio ** 2) + ((32 * self.eccentricity_ratio ** 2) * (1 + self.eccentricity_ratio ** 2)) / (1 - self.eccentricity_ratio ** 2))) # fmt: on return [kxx, kxy, kyx, kyy] def get_analytical_damping_matrix(self): """Returns the damping matrix calculated analytically. Suitable only for short bearings. Returns ------- list of floats A list of length four including stiffness floats in this order: cxx, cxy, cyx, cyy Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.get_analytical_damping_matrix() # doctest: +ELLIPSIS [... """ if not self.bearing_type == "short_bearing": warnings.warn( "Function get_analytical_damping_matrix suitable only for short bearings. " "The ratio between the bearing length and its radius should be less or " "equal to 0.25. Currently we have " + str(self.length / self.radius_stator) + "." ) # fmt: off f = self.get_rotor_load() h0 = 1.0 / (((np.pi ** 2) * (1 - self.eccentricity_ratio ** 2) + 16 * self.eccentricity_ratio ** 2) ** 1.5) a = f / (self.radial_clearance * self.omega) cxx = (a * h0 * 2 * np.pi * np.sqrt(1 - self.eccentricity_ratio ** 2) * ((np.pi ** 2) * ( 1 + 2 * self.eccentricity_ratio ** 2) - 16 * self.eccentricity_ratio ** 2) / self.eccentricity_ratio) cxy = (-a * h0 * 8 * ( (np.pi ** 2) * (1 + 2 * self.eccentricity_ratio ** 2) - 16 * self.eccentricity_ratio ** 2)) cyx = cxy cyy = (a * h0 * (2 * np.pi * ( (np.pi ** 2) * (1 - self.eccentricity_ratio ** 2) ** 2 + 48 * self.eccentricity_ratio ** 2)) / (self.eccentricity_ratio * np.sqrt(1 - self.eccentricity_ratio ** 2))) # fmt: on return [cxx, cxy, cyx, cyy] def calculate_oil_film_force(self, force_type=None): """This function calculates the forces of the oil film in the N and T directions, ie in the opposite direction to the eccentricity and in the tangential direction. Parameters ---------- force_type: str If set, calculates the pressure matrix analytically considering the chosen type: 'short' or 'long'. Returns ------- normal_force: float Force of the oil film in the opposite direction to the eccentricity direction. tangential_force: float Force of the oil film in the tangential direction Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_oil_film_force() # doctest: +ELLIPSIS (... """ if force_type != 'numerical' and (force_type == 'short' or self.bearing_type == 'short_bearing'): normal_force = 0.5 * self.viscosity * (self.radius_rotor / self.difference_between_radius) ** 2 * \ (self.length ** 3 / self.radius_rotor) * ((2 * self.eccentricity_ratio ** 2 * self.omega) / (1 - self.eccentricity_ratio ** 2) ** 2) tangential_force = 0.5 * self.viscosity * (self.radius_rotor / self.difference_between_radius) ** 2 * \ (self.length ** 3 / self.radius_rotor) * ( (np.pi * self.eccentricity_ratio * self.omega) / (2 * (1 - self.eccentricity_ratio ** 2) ** (3. / 2))) elif force_type != 'numerical' and (force_type == 'long' or self.bearing_type == 'long_bearing'): normal_force = 6 * self.viscosity * (self.radius_rotor / self.difference_between_radius) ** 2 * \ self.radius_rotor * self.length * ((2 * self.eccentricity_ratio ** 2 * self.omega) / ((2 + self.eccentricity_ratio ** 2) * (1 - self.eccentricity_ratio ** 2))) tangential_force = 6 * self.viscosity * (self.radius_rotor / self.difference_between_radius) ** 2 * \ self.radius_rotor * self.length * ((np.pi * self.eccentricity_ratio * self.omega) / ((2 + self.eccentricity_ratio ** 2) * (1 - self.eccentricity_ratio ** 2) ** 0.5)) else: p_mat = self.p_mat_numerical a = np.zeros([self.nz, self.ntheta]) b = np.zeros([self.nz, self.ntheta]) g1 = np.zeros(self.nz) g2 = np.zeros(self.nz) theta_list = np.zeros(self.ntheta) z_list = np.zeros(self.nz) for i in range(self.nz): z_list[i] = i * self.dz for j in range(self.ntheta): theta_list[j] = j * self.dtheta + (np.pi - self.beta) gama = j * self.dtheta + (np.pi - self.beta) a[i][j] = p_mat[i][j] * np.cos(gama) b[i][j] = p_mat[i][j] * np.sin(gama) for i in range(self.nz): g1[i] = integrate.simps(a[i][:], theta_list) g2[i] = integrate.simps(b[i][:], theta_list) integral1 = integrate.simps(g1, z_list) integral2 = integrate.simps(g2, z_list) normal_force = - self.radius_rotor * integral1 tangential_force = self.radius_rotor * integral2 return normal_force, tangential_force def plot_eccentricity(self, z=0): """This function assembles pressure graphic along the z-axis. The first few plots are of a different color to indicate where theta begins. Parameters ---------- z: int, optional The distance in z where to cut and plot. Returns ------- Figure An object containing the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> fig = my_fluid_flow.plot_eccentricity(z=int(my_fluid_flow.nz/2)) >>> # to show the plots you can use: >>> # show(fig) """ p = figure( title="Cut in plane Z=" + str(z), x_axis_label="X axis", y_axis_label="Y axis", ) for j in range(0, self.ntheta): p.circle(self.xre[z][j], self.yre[z][j], color="red") p.circle(self.xri[z][j], self.yri[z][j], color="blue") p.circle(0, 0, color="blue") p.circle(self.xi, self.yi, color="red") p.circle(0, 0, color="black") return p def plot_pressure_z(self, theta=0): """This function assembles pressure graphic along the z-axis for one or both the numerically (blue) and analytically (red) calculated pressure matrices, depending on if one or both were calculated. Parameters ---------- theta: int, optional The theta to be considered. Returns ------- Figure An object containing the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_pressure_matrix_numerical() # doctest: +ELLIPSIS array([[... >>> fig = my_fluid_flow.plot_pressure_z(theta=int(my_fluid_flow.ntheta/2)) >>> # to show the plots you can use: >>> # show(fig) """ if ( not self.numerical_pressure_matrix_available and not self.analytical_pressure_matrix_available ): sys.exit( "Must calculate the pressure matrix. " "Try calling calculate_pressure_matrix_numerical() or calculate_pressure_matrix_analytical() first." ) x = [] y_n = [] y_a = [] for i in range(0, self.nz): x.append(i * self.dz) y_n.append(self.p_mat_numerical[i][theta]) y_a.append(self.p_mat_analytical[i][theta]) p = figure( title="Pressure along the Z direction (direction of flow); Theta=" + str(theta), x_axis_label="Points along Z", ) if self.numerical_pressure_matrix_available: p.line(x, y_n, legend="Numerical pressure", color="blue", line_width=2) if self.analytical_pressure_matrix_available: p.line(x, y_a, legend="Analytical pressure", color="red", line_width=2) return p def plot_shape(self, theta=0): """This function assembles a graphic representing the geometry of the rotor. Parameters ---------- theta: int, optional The theta to be considered. Returns ------- Figure An object containing the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> fig = my_fluid_flow.plot_shape(theta=int(my_fluid_flow.ntheta/2)) >>> # to show the plots you can use: >>> # show(fig) """ x = np.zeros(self.nz) y_re = np.zeros(self.nz) y_ri = np.zeros(self.nz) for i in range(0, self.nz): x[i] = i * self.dz y_re[i] = self.re[i][theta] y_ri[i] = self.ri[i][theta] p = figure( title="Shapes of stator and rotor along Z; Theta=" + str(theta), x_axis_label="Points along Z", y_axis_label="Radial direction", ) p.line(x, y_re, line_width=2, color="red") p.line(x, y_ri, line_width=2, color="blue") return p def plot_pressure_theta(self, z=0): """This function assembles pressure graphic in the theta direction for a given z for one or both the numerically (blue) and analytically (red) calculated pressure matrices, depending on if one or both were calculated. Parameters ---------- z: int, optional The distance along z-axis to be considered. Returns ------- Figure An object containing the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_pressure_matrix_numerical() # doctest: +ELLIPSIS array([[... >>> fig = my_fluid_flow.plot_pressure_theta(z=int(my_fluid_flow.nz/2)) >>> # to show the plots you can use: >>> # show(fig) """ if ( not self.numerical_pressure_matrix_available and not self.analytical_pressure_matrix_available ): sys.exit( "Must calculate the pressure matrix. " "Try calling calculate_pressure_matrix_numerical() or calculate_pressure_matrix_analytical() first." ) theta_list = [] for theta in range(0, self.ntheta): theta_list.append(theta * self.dtheta) p = figure( title="Pressure along Theta; Z=" + str(z), x_axis_label="Points along Theta", y_axis_label="Pressure", ) if self.numerical_pressure_matrix_available: p.line( theta_list, self.p_mat_numerical[z], legend="Numerical pressure", line_width=2, color="blue", ) elif self.analytical_pressure_matrix_available: p.line( theta_list, self.p_mat_analytical[z], legend="Analytical pressure", line_width=2, color="red", ) return p def matplot_eccentricity(self, z=0, ax=None): """This function assembles pressure graphic along the z-axis using matplotlib. The first few plots are of a different color to indicate where theta begins. Parameters ---------- z: int, optional The distance in z where to cut and plot. ax : matplotlib axes, optional Axes in which the plot will be drawn. Returns ------- ax : matplotlib axes Returns the axes object with the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> ax = my_fluid_flow.matplot_eccentricity(z=int(my_fluid_flow.nz/2)) >>> # to show the plots you can use: >>> # plt.show() """ if ax is None: ax = plt.gca() for j in range(0, self.ntheta): ax.plot(self.xre[z][j], self.yre[z][j], "r.") ax.plot(self.xri[z][j], self.yri[z][j], "b.") ax.plot(0, 0, "r*") ax.plot(self.xi, self.yi, "b*") ax.set_title("Cut in plane Z=" + str(z)) ax.set_xlabel("X axis") ax.set_ylabel("Y axis") plt.axis("equal") return ax def matplot_pressure_z(self, theta=0, ax=None): """This function assembles pressure graphic along the z-axis using matplotlib for one or both the numerically (blue) and analytically (red) calculated pressure matrices, depending on if one or both were calculated. Parameters ---------- theta: int, optional The distance in theta where to cut and plot. ax : matplotlib axes, optional Axes in which the plot will be drawn. Returns ------- ax : matplotlib axes Returns the axes object with the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_pressure_matrix_numerical() # doctest: +ELLIPSIS array([[... >>> ax = my_fluid_flow.matplot_pressure_z(theta=int(my_fluid_flow.ntheta/2)) >>> # to show the plots you can use: >>> # plt.show() """ if ( not self.numerical_pressure_matrix_available and not self.analytical_pressure_matrix_available ): sys.exit( "Must calculate the pressure matrix. " "Try calling calculate_pressure_matrix_numerical() or calculate_pressure_matrix_analytical() first." ) if ax is None: ax = plt.gca() x = np.zeros(self.nz) y_n = np.zeros(self.nz) y_a = np.zeros(self.nz) for i in range(0, self.nz): x[i] = i * self.dz y_n[i] = self.p_mat_numerical[i][theta] y_a[i] = self.p_mat_analytical[i][theta] if self.numerical_pressure_matrix_available: ax.plot(x, y_n, "b", label="Numerical pressure") if self.analytical_pressure_matrix_available: ax.plot(x, y_a, "r", label="Analytical pressure") ax.set_title( "Pressure along the Z direction (direction of flow); Theta=" + str(theta) ) ax.set_xlabel("Points along Z") ax.set_ylabel("Pressure") return ax def matplot_shape(self, theta=0, ax=None): """This function assembles a graphic representing the geometry of the rotor using matplotlib. Parameters ---------- theta: int, optional The theta to be considered. ax : matplotlib axes, optional Axes in which the plot will be drawn. Returns ------- ax : matplotlib axes Returns the axes object with the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> ax = my_fluid_flow.matplot_shape(theta=int(my_fluid_flow.ntheta/2)) >>> # to show the plots you can use: >>> # plt.show() """ if ax is None: ax = plt.gca() x = np.zeros(self.nz) y_ext = np.zeros(self.nz) y_int = np.zeros(self.nz) for i in range(0, self.nz): x[i] = i * self.dz y_ext[i] = self.re[i][theta] y_int[i] = self.ri[i][theta] ax.plot(x, y_ext, "r") ax.plot(x, y_int, "b") ax.set_title("Shapes of stator and rotor along Z; Theta=" + str(theta)) ax.set_xlabel("Points along Z") ax.set_ylabel("Radial direction") return ax def matplot_pressure_theta_cylindrical(self, z=0, from_numerical=True, ax=None): """This function assembles cylindrical pressure graphic in the theta direction for a given z, using matplotlib. Parameters ---------- z: int, optional The distance along z-axis to be considered. from_numerical: bool, optional If True, takes the numerically calculated pressure matrix as entry. If False, takes the analytically calculated one instead. If condition cannot be satisfied (matrix not calculated), it will take the one that is available and raise a warning. ax : matplotlib axes, optional Axes in which the plot will be drawn. Returns ------- ax : matplotlib axes Returns the axes object with the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_pressure_matrix_numerical() # doctest: +ELLIPSIS array([[... >>> ax = my_fluid_flow.matplot_pressure_theta_cylindrical(z=int(my_fluid_flow.nz/2)) >>> # to show the plots you can use: >>> # plt.show() """ if ( not self.numerical_pressure_matrix_available and not self.analytical_pressure_matrix_available ): sys.exit( "Must calculate the pressure matrix. " "Try calling calculate_pressure_matrix_numerical() or calculate_pressure_matrix_analytical() first." ) if from_numerical: if self.numerical_pressure_matrix_available: p_mat = self.p_mat_numerical else: p_mat = self.p_mat_analytical warnings.warn( "Plotting from analytically calculated pressure matrix, as numerically calculated " "one is not available." ) else: if self.analytical_pressure_matrix_available: p_mat = self.p_mat_analytical else: p_mat = self.p_mat_numerical warnings.warn( "Plotting from numerically calculated pressure matrix, as analytically calculated " "one is not available." ) if ax is None: fig, ax = plt.subplots(subplot_kw=dict(projection="polar")) r = np.arange( 0, self.radius_stator + 0.0001, (self.radius_stator - self.radius_rotor) / self.nradius, ) theta = np.arange(-np.pi * 0.25, 1.75 * np.pi + self.dtheta / 2, self.dtheta) pressure_along_theta = np.zeros(self.ntheta) for i in range(0, self.ntheta): pressure_along_theta[i] = p_mat[0][i] min_pressure = np.amin(pressure_along_theta) r_matrix, theta_matrix = np.meshgrid(r, theta) z_matrix = np.zeros((theta.size, r.size)) inner_radius_list = np.zeros(self.ntheta) pressure_list = np.zeros((theta.size, r.size)) for i in range(0, theta.size): inner_radius = np.sqrt( self.xri[z][i] * self.xri[z][i] + self.yri[z][i] * self.yri[z][i] ) inner_radius_list[i] = inner_radius for j in range(0, r.size): if r_matrix[i][j] < inner_radius: continue pressure_list[i][j] = pressure_along_theta[i] z_matrix[i][j] = pressure_along_theta[i] - min_pressure + 0.01 ax.contourf(theta_matrix, r_matrix, z_matrix, cmap="coolwarm") ax.set_title("Pressure along Theta; Z=" + str(z)) return ax def matplot_pressure_theta(self, z=0, ax=None): """This function assembles pressure graphic in the theta direction for a given z, using matplotlib. Parameters ---------- z: int, optional The distance along z-axis to be considered. ax : matplotlib axes, optional Axes in which the plot will be drawn. Returns ------- ax : matplotlib axes Returns the axes object with the plot. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.calculate_pressure_matrix_numerical() # doctest: +ELLIPSIS array([[... >>> ax = my_fluid_flow.matplot_pressure_theta(z=int(my_fluid_flow.nz/2)) >>> # to show the plots you can use: >>> # plt.show() """ if ( not self.numerical_pressure_matrix_available and not self.analytical_pressure_matrix_available ): sys.exit( "Must calculate the pressure matrix. " "Try calling calculate_pressure_matrix_numerical() or calculate_pressure_matrix_analytical() first." ) if ax is None: ax = plt.gca() list_of_thetas = [] for t in range(0, self.ntheta): list_of_thetas.append(t * self.dtheta) if self.numerical_pressure_matrix_available: ax.plot( list_of_thetas, self.p_mat_numerical[z], "b", label="Numerical pressure" ) if self.analytical_pressure_matrix_available: ax.plot( list_of_thetas, self.p_mat_analytical[z], "r", label="Analytical pressure", ) ax.set_title("Pressure along Theta; Z=" + str(z)) ax.set_xlabel("Points along Theta") ax.set_ylabel("Pressure") return ax def pressure_matrix_example(): """This function returns an instance of a simple pressure matrix. The purpose is to make available a simple model so that doctest can be written using it. Parameters ---------- Returns ------- An instance of a pressure matrix object. Examples -------- >>> my_fluid_flow = pressure_matrix_example() >>> my_fluid_flow.eccentricity 0.001 """ my_pressure_matrix = PressureMatrix(nz=8, ntheta=64, nradius=11, length=0.01, omega=100. * 2 * np.pi / 60, p_in=0., p_out=0., radius_rotor=0.08, radius_stator=0.1, viscosity=0.015, density=860., eccentricity=0.001, beta=np.pi) return my_pressure_matrix
import ctypes class Array : """Implements the Array ADT using array capabilities of the ctypes module.""" def __init__( self, size ): """Creates an array with size elements.""" assert size > 0, "Array size must be > 0" self._size = size # Create the array structure using the ctypes module. PyArrayType = ctypes.py_object * size self._elements = PyArrayType() # Initialize each element. self.clear( None ) def __len__( self ): """Returns the size of the array.""" return self._size def __getitem__( self, index ): """Gets the contents of the index element.""" assert index >= 0 and index < len(self), "Array subscript out of range" return self._elements[ index ] def __setitem__( self, index, value ): """Puts the value in the array element at index position.""" assert index >= 0 and index < len(self), "Array subscript out of range" self._elements[ index ] = value def clear( self, value ): """Clears the array by setting each element to the given value.""" for i in range(len(self)): self._elements[i] = value def __iter__( self ): """Returns the array's iterator for traversing the elements.""" return _ArrayIterator( self._elements ) class Array2D : """Implementation of the Array2D ADT using an array of arrays.""" def __init__( self, numRows, numCols ): """Creates a 2-D array of size numRows x numCols.""" # Create a 1-D array to store an array reference for each row. self._theRows = Array( numRows ) # Create the 1-D arrays for each row of the 2-D array. for i in range( numRows ) : self._theRows[i] = Array( numCols ) def numRows( self ): """Returns the number of rows in the 2-D array.""" return len( self._theRows ) def numCols( self ): """Returns the number of columns in the 2-D array.""" return len( self._theRows[0] ) def clear( self, value ): """Clears the array by setting every element to the given value.""" for row in range( self.numRows() ): self._theRows[row].clear( value ) def __getitem__( self, ndxTuple ): """Gets the contents of the element at position [i, j]""" assert len(ndxTuple) == 2, "Invalid number of array subscripts." row = ndxTuple[0] col = ndxTuple[1] assert row >= 0 and row < self.numRows() and col >= 0 and col < self.numCols(), \ "Array subscript out of range." the1dArray = self._theRows[row] return the1dArray[col] def __setitem__( self, ndxTuple, value ): """Sets the contents of the element at position [i,j] to value.""" assert len(ndxTuple) == 2, "Invalid number of array subscripts." row = ndxTuple[0] col = ndxTuple[1] assert row >= 0 and row < self.numRows() and col >= 0 and col < self.numCols(), \ "Array subscript out of range." the1dArray = self._theRows[row] the1dArray[col] = value class Matrix: """A matrix is a collection of scalar values arranged in rows and columns as a rectangular grid of a fixed size. The elements of the matrix can be accessed by specifying a given row and column index with indices starting at 0. """ def __init__(self, rows, cols): """Creates a new matrix containing rows and columns with each element initialized to 0""" self._theGrid = Array2D(rows, cols) self._theGrid.clear(0) def numRows(self): """Returns the number of rows in the matrix""" return self._theGrid.numRows() def numCols(self): """Returns the number of columns in the matrix""" return self._theGrid.numCols() def __getitem__(self, i): """Returns the value stored in the given matrix element. Both row and col must be within the valid range.""" return self._theGrid[i[0], i[1]] def __setitem__(self, i, scalar): """Sets the matrix element at the given row and col to scalar. The element indices must be within the valid range.""" self._theGrid[i[0], i[1]] = scalar def scale_by(self, scalar): """Multiplies each element of the matrix by the given scalar value. The matrix is modified by this operation""" for r in range(self.numRows()): for c in range(self.numCols()): self[r,c] *= scalar def transpose(self): """Returns a new matrix that is the transpose of this matrix""" new_matrix = Matrix(self.numCols(), self.numRows()) for col in range(self.numCols()): for row in range(self.numRows()): new_matrix[col, row] = self._theGrid[row, col] return new_matrix def __add__(self, rhsMatrix): """Creates and returns a new matrix that is the result of adding this matrix to the given rhsMatrix. The size of the two matrices must be the same""" assert rhsMatrix.numRows() == self.numRows() and \ rhsMatrix.numCols == self.numRows(), \ "Matrix sizes are not compatible for the add operation." # Create the new matrix newMatrix = Matrix(self.numRows(), self.numCols()) # Add the corresponding elements in the two matrices for r in range(self.numRows()): for c in range(self.numCols()): newMatrix[r,c] = self[r,c] + rhsMatrix[r,c] return newMatrix def __sub__(self, rhsMatrix): """The same as add() operation but subtracts the two matrices.""" def __mul__(self, rhsMatrix): """Creates and returns a new matrix that is the result of mulitplying this matrix to the given rhsMatrix. The two matrices must be of appropriate sizes as defined for matrix multiplication. """ class _ArrayIterator : """An iterator for the Array ADT.""" def __init__( self, theArray ): self._arrayRef = theArray self._curNdx = 0 def __iter__( self ): return self def __next__( self ): if self._curNdx < len( self._arrayRef ) : entry = self._arrayRef[ self._curNdx ] self._curNdx += 1 return entry else : raise StopIteration
max = 0 num = 0 for i in range(1, 10): a = int(input()) if a > max: max = a num = i print('%d\n%d' %(max, num))
T=int(input()) for _ in range(T): stack=0 ps=input() flag=True#for x in ps를 하면 stack이 음수되면 False for x in ps: if x =='(':stack+=1 elif x ==')':stack-=1 if stack<0:flag=False if flag and stack==0:print('YES') else:print('NO') ''' 1 (()())((())) '''
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 24 09:33:52 2019 @author: owner """ ''' def name(a): print(a) name("yasmin") def my_function(x): for x in x: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits) def y(*num): sum=0 for n in num: sum=sum+n print("sum=", sum) y(1,5,8) y(1,8,9,6) def u(*s,a): print(a) for t in s: print(t) u(1,5,8,a=9) def t(a,s,d): print(a) print(s) print(d) l=[2,8] t(1,*l) def u(**k): for key,value in k.items(): print(key,"==",value) u(e=1,r=6,t=9) x = "awesome" def myfunc(): print("Python is " + x) myfunc() print("Python is " + x) def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) print(factorial(2956)) usm=lambda x,c,v: x+c-v print(usm(5,2,3)) print ((lambda x, y, z=3: x + y + z)(1, 2,2)) MyList = [0,1,2,3,4,10,13,22,25,100,120] print("squared List:", map(lambda x: x**2, MyList[0])) MyList = [0,1,2,3,4,10,13,22,25,100,120] odd_numbers = list(filter(lambda x: x % 2, MyList)) print(odd_numbers) even_numbers = list(filter(lambda x: not(x % 2), MyList)) print(even_numbers) scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65] x= list((lambda y:y>75),scores) print(y) my_strings = ['a', 'b', 'c', 'd', 'e'] my_numbers = [1,2,3,4,5,8] l = [1,2,3,"y","e","w"] results = list(zip(my_strings, my_numbers,l)) print(results) ''' from functools import reduce x= reduce(lambda a,b: a+b,[23,21,45,98]) print(x)
secret = "1" guess = input("Guess the secret number...") match = secret == guess if match: print ("Congratulations, you guessed the right number!") else: print("I'm sorry. This was not the correct number :(")
# I hate trying to figure out 2D space in my brain. import os # Easy function to parse direction and distance and return a point def drawWire(Wire): Points = list() X = 0 Y = 0 for line in Wire: direction = line[0:1] distance = int(line[1:len(line)]) if (direction == "U"): Y += distance elif (direction == "D"): Y -= distance elif (direction == "R"): X += distance else: assert(direction == "L") X -= distance Points.append( (X,Y,distance) ) return Points # This is a simple algorithm to determine instersections # This assumes the line is either horizontal or vertical # If Line A has constant X and B has constant Y, If the X coord of A is between the two X coords of B AND # The Y coord of B is between to the two Y coords of A then they instersect at (A[x],B[y]). Otherwise they do not touch def findIntersection(A1,A2,B1,B2): # A has constant X, B has constant Y if (A1[0] == A2[0] and B1[1] == B2[1]): if ((A1[0] > min(B1[0],B2[0]) and A1[0] < max(B1[0],B2[0])) and (B1[1] > min(A1[1],A2[1]) and B1[1] < max(A1[1],A2[1])) ): return (A1[0],B1[1]) #A has constant Y, B has constant X elif (A1[1] == A2[1] and B1[0] == B2[0]): if ((B1[0] > min(A1[0],A2[0]) and B1[0] < max(A1[0],A2[0])) and (A1[1] > min(B1[1],B2[1]) and A1[1] < max(B1[1],B2[1])) ): return (B1[0],A1[1]) #parallel else: return False # Not parallel but not intersecting return False f = open("{}\\Input.txt".format(os.path.dirname(os.path.realpath(__file__))),"r") Wire1 = f.readline().split(",") Wire2 = f.readline().split(",") # Get the points of my wire Wire1Points = drawWire(Wire1) Wire2Points = drawWire(Wire2) manhattenDistancesFromCenter = list() wireDistancesFromCenter = list() # Go through each pair of points in order they were drawn. # Save all the manhatten distances from (0,0) for i in range(len(Wire1Points)-1): for j in range(len(Wire2Points)-1): doIntersect = findIntersection(Wire1Points[i],Wire1Points[i+1],Wire2Points[j],Wire2Points[j+1]) if (doIntersect): manhattenDistancesFromCenter.append(sum(doIntersect)) # The WireXPoints keep track of distance from last point in the [2] index. Sum all those indexes up to this point and add the distance to the instersect point wire1distance = sum(x[2] for x in Wire1Points[0:i+1]) + max(abs(doIntersect[0]-Wire1Points[i][0]),abs(doIntersect[1]-Wire1Points[i][1])) wire2distance = sum(x[2] for x in Wire2Points[0:j+1]) + max(abs(doIntersect[0]-Wire2Points[j][0]),abs(doIntersect[1]-Wire2Points[j][1])) wireDistancesFromCenter.append(wire1distance+wire2distance) # Print the smallest distance print("Part1:{}".format(min(manhattenDistancesFromCenter))) print("Part2:{}".format(min(wireDistancesFromCenter)))
import os from anytree import Node from anytree.search import findall def getOrbits(node): if (node.parent != None): return 1 + getOrbits(node.parent) else: return 0 def findCommonParent(a,b): commonParent = a while True: res = findall(commonParent, filter_=lambda node: node.name == b.name) if (commonParent.parent == None): return None elif (res): return commonParent commonParent = commonParent.parent def getDistanceFromParent(node,parent): distance = 1 currentNode = node.parent while (currentNode != parent): distance += 1 currentNode = currentNode.parent return distance f = open("{}{}Input.txt".format(os.path.dirname(os.path.realpath(__file__)),os.path.sep),"r") Input = [line.rstrip() for line in f] graph = dict() for line in Input: nodes = line.split(')') for node in nodes: if (node not in graph): graph[node] = Node(node) graph[nodes[1]].parent = graph[nodes[0]] # Count how many parents each node has numberOfOrbits = 0 for n in graph.values(): numberOfOrbits += getOrbits(n) print ("Part 1: {}".format(numberOfOrbits)) # I could just use 'Walker' for the second part but I feel like writing my own commonParent = findCommonParent(graph["YOU"],graph["SAN"]) distance = getDistanceFromParent(graph["YOU"],commonParent) + getDistanceFromParent(graph["SAN"],commonParent) - 2 print ("Part 2: {}".format(distance))
import sys import math import pandas as pd from collections import Counter from sklearn.tree import DecisionTreeClassifier class DecisionNode: # A DecisionNode contains an attribute and a dictionary of children. # The attribute is either the attribute being split on, or the predicted label if the node has no children. def __init__(self, attribute): self.attribute = attribute self.children = {} # Visualizes the tree def display(self, level = 0): if self.children == {}: # reached leaf level print(": ", self.attribute, end="") else: for value in self.children.keys(): prefix = "\n" + " " * level * 4 print(prefix, self.attribute, "=", value, end="") self.children[value].display(level + 1) # Predicts the target label for instance x def predicts(self, x): if self.children == {}: # reached leaf level return self.attribute value = x[self.attribute] subtree = self.children[value] return subtree.predicts(x) # Illustration of functionality of DecisionNode class def funTree(): myLeftTree = DecisionNode('humidity') myLeftTree.children['normal'] = DecisionNode('no') myLeftTree.children['high'] = DecisionNode('yes') myTree = DecisionNode('wind') myTree.children['weak'] = myLeftTree myTree.children['strong'] = DecisionNode('no') return myTree def id3(examples, target, attributes): #tree = funTree() tree = decisionTree(examples, target, attributes) return tree # build the decision tree def decisionTree(examples, target, attributes): bestattribute, baseCase = bestAttribute(examples, target, attributes) root= DecisionNode(bestattribute) if baseCase: return root else: attrWithOutBestAttr= attributes.copy() attrWithOutBestAttr.remove(bestattribute) for attrVal in examples[bestattribute].unique(): dataAttrVal= examples[examples[bestattribute] == attrVal] root.children[attrVal]= decisionTree(dataAttrVal, target, attrWithOutBestAttr) return root # get the best attribute at each level def bestAttribute(examples, target, attributes): targetValues = examples[target].unique() if len(attributes) == 0: # if attributes is empty, return the single-node tree root with # label = most common value of target attribute in examples. return (examples[target].value_counts().idxmax(), True) elif len(targetValues) > 1: entropies = [] for i in attributes: # get current attribute and target value attribute = examples[[i, target]] attributeValues = attribute[i].unique() entropy = getEntropy(examples, target, i, attributeValues, targetValues) entropies.append(entropy) best_Attribute = attributes[entropies.index(max(entropies))] return (best_Attribute, False) else: return (targetValues[0], True) def getEntropy(examples, target, attribute, attributeValues, targetValues): entropy = 0 df_attribute = examples[[attribute, target]] for i in attributeValues: df2 = df_attribute.loc[df_attribute[attribute] == i] targetValues = df2[target].unique() n = df2.shape[0] temp_entropy = 0 counts = df2[str(target)].value_counts().to_dict() for j in range(targetValues.size): if type(targetValues[j]) == type('adf'): fraction = (counts.get(str(targetValues[j])))/(df2.shape[0]) else: fraction = (counts.get(int(targetValues[j])))/(df2.shape[0]) temp_entropy += (fraction) * math.log(fraction) entropy += (n/examples.shape[0]) * temp_entropy return entropy #################### MAIN PROGRAM ###################### # Reading input data #train = pd.read_csv(sys.argv[1]) #test = pd.read_csv(sys.argv[2]) #target = sys.argv[3] train = pd.read_csv('playtennis_train.csv') test = pd.read_csv('playtennis_test.csv') target = 'playtennis' attributes = train.columns.tolist() attributes.remove(target) # Learning and visualizing the tree tree = id3(train,target,attributes) tree.display() # Evaluating the tree on the test data correct = 0 for i in range(0,len(test)): if str(tree.predicts(test.loc[i])) == str(test.loc[i,target]): correct += 1 print("\nThe accuracy is: ", correct/len(test)) # Implementing the actual DecisionTreeClassifier from scikit-learn dtc = DecisionTreeClassifier() print(train.dtypes) #mapping classes to labels outlook_to_int = {'sunny':1, 'overcast':2, 'rainy':3} train['outlook'] = train['outlook'].replace(outlook_to_int) test['outlook'] = test['outlook'].replace(outlook_to_int) temperature_to_int = {'hot':1, 'mild':2, 'cool':3} train['temperature'] = train['temperature'].replace(temperature_to_int) test['temperature'] = test['temperature'].replace(temperature_to_int) humidity_to_int = {'high':1, 'normal':2} train['humidity'] = train['humidity'].replace(humidity_to_int) test['humidity'] = test['humidity'].replace(humidity_to_int) wind_to_int = {'weak':1, 'strong':2} train['wind'] = train['wind'].replace(wind_to_int) test['wind'] = test['wind'].replace(wind_to_int) train_target = train[['playtennis']] print(train) train = train.drop(['playtennis'], axis=1) dtc.fit(train, train_target) test_target = test['playtennis'] test = test.drop(['playtennis'], axis=1) print("Score = {}".format(dtc.score(test, test_target)))
import asyncio def square_distance(n1=2, n2=4): """ distancia cuadrada entre dos números """ x_square = (n1.x - n2.x) ** 2 y_square = (n1.y - n2.y) ** 2 return x_square + y_square def even_odd(n1=0): """ calcula par o impar de un número devuelve True si es par y False si es impar """ try: if n1 % 2 == 0: return True elif n1 == 0: pass else: return False except: pass async def percentaje(n=0, n_max=0, t=0, f=0, action=False): """ n = número actual del porcentaje n_max = número máximo del porcentage t = tiempo f = número que edita el porcentage crea un porcentage y lo edita en el tiempo según la acción, True = creciendo, False = decreciendo """ if action == True: for i in range(n, n_max, f): n = i await asyncio.sleep(t) return n elif action == False: for i in range(n, 0, f): n = i await asyncio.sleep(t) return n def square_vectors(x, y, h, w): """ desde el punto arriba izquierda dando la x y de ese punto, genera el resto de esquinas usando el ancho w y el alto w """ # 1 a_x, a_y = x, y # 2 b_x, b_y = x + w, y # 3 c_x, c_y = x, y + h # 4 d_x, d_y = x + w, y + h a = [a_x, a_y] b = [b_x, b_y] c = [c_x, c_y] d = [d_x, d_y] vectors = [a, b, c, d] return vectors def rectagles_overlapping(parameter_list): """ docstring """ pass
from random import SystemRandom sr = SystemRandom() def generate_password(length, valid_chars = None): if valid_chars == None: valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" valid_chars += valid_chars.lower() + "0123456789" password = "" counter = 0 while counter < length: rnum = sr.randint(0, 128) char = chr(rnum) if char in valid_chars: password += chr(rnum) counter += 1 return password print("Automatically generated password by Python: ", generate_password(15))
from bulls_and_cows.combinatorics import all_colors def inconsistent(p, guesses): """ The function checks, if a permutation p is consistent with the previous colors. Each previous color permutation guess[0] compared with p has to return the same amount of blacks and whites as the corresponding evaluation """ for guess in guesses: res = check(guess[0], p) (rightly_positioned, permutated) = guess[1] if res != [rightly_positioned, permutated]: return True # inconsistent return False # consistent def answer_ok(a): """ Checking of an evaluation given by the human player makes sense. 3 blacks and 1 white make no sense for example. """ (rightly_positioned, permutated) = a if (rightly_positioned + permutated > number_of_positions) \ or (rightly_positioned + permutated < len(colours) - number_of_positions): return False if rightly_positioned == 3 and permutated == 1: return False return True def get_evaluation(): """ Asks the human player for an evaluation """ show_current_guess(new_guess[0]) rightly_positioned = int(input("Blacks: ")) permutated = int(input("Whites: ")) return rightly_positioned, permutated def new_evaluation(current_colour_choices): """ This funtion gets an evaluation of the current guess, checks the consistency of this evaluation, adds the guess together with the evaluation to the list of guesses, shows the previous guesses and creates a new guess """ rightly_positioned, permutated = get_evaluation() if rightly_positioned == number_of_positions: return current_colour_choices, (rightly_positioned, permutated) if not answer_ok((rightly_positioned, permutated)): print("Input Error: Sorry, the input makes no sense") return current_colour_choices, (-1, permutated) guesses.append((current_colour_choices, (rightly_positioned, permutated))) view_guesses() current_colour_choices = create_new_guess() if not current_colour_choices: return current_colour_choices, (-1, permutated) return current_colour_choices, (rightly_positioned, permutated) def check(p1, p2): """ Check() calculates the number of bulls (blacks) and cows (whites) of two permutations """ blacks = 0 whites = 0 for i in range(len(p1)): if p1[i] == p2[i]: blacks += 1 else: if p1[i] in p2: whites += 1 return [blacks, whites] def create_new_guess(): """ A new guess is created, which is consistent to the previous guesses """ next_choice = next(permutation_iterator) while inconsistent(next_choice, guesses): try: next_choice = next(permutation_iterator) except StopIteration: print("Error: Your answers were inconsistent!") return () return next_choice def show_current_guess(new_guess): """ The current guess is printed to stdout """ print("New Guess: ", end=" ") for c in new_guess: print(c, end=" ") print() def view_guesses(): """ The list of all guesses with the corresponding evaluations is printed """ print("Previous Guesses:") for guess in guesses: guessed_colours = guess[0] for c in guessed_colours: print(c, end=" ") for i in guess[1]: print(" %i " % i, end=" ") print() if __name__ == "__main__": colours = ["red", "green", "blue", "yellow", "orange", "pink"] guesses = [] number_of_positions = 4 permutation_iterator = all_colors(colours, number_of_positions) current_colour_choices = next(permutation_iterator) new_guess = (current_colour_choices, (0, 0)) while (new_guess[1][0] == -1) or (new_guess[1][0] != number_of_positions): new_guess = new_evaluation(new_guess[0])
''' Calculate the runtime of the following recursive binary search function. HINT: The function contains a subtle runtime bug due to memory management. This bug causes the runtime to not be O(log n). ''' def binary_search(xs, x): ''' Returns whether x is contained in xs. >>> binary_search([0,1,3,4],1) True >>> binary_search([0,1,3,4],2) False ''' mid = len(xs)//2 if len(xs)==1: return xs[0]==x elif x<xs[mid]: return binary_search(xs[:mid],x) else: return binary_search(xs[mid:],x)
#To make game of hangman def HangManOyy(question,answer): import random from os import system ra=answer.upper() if answer.upper()==answer else answer.lower() take="" turn=3#The tries while(turn>=0): fail=0 print('\nYour question is : ',question) for char in ra: if (char in take.upper()) or (char in take.lower()) or (char in take): print("\t",char,end="") else: print("\t_",end=" ") fail+=1 guess = input("\n\n\tEnter the code: ") system('cls') if(guess=="done" and fail==0): return 3 take += guess if(fail==0): print("\n You completed",) return 3 if guess in ra: print("\nGood Going !!") continue print("\nThe chances are : ",turn-1) if(turn-1==0): print("You surrendered but !! Nice played") print("Also the letters were :-------",ra,"--------") break turn-=1 print("Nice played you have found all the words ",)
lst=[1, 2 ,3, 4, 3, 3, 2, 1] new_lst=list() _min=0 while(lst!=[]): new_lst.append(len(lst)) _min=min(lst) lst=[i for i in lst if i != min(lst)] for i in range(len(lst)): lst[i]= lst[i]-_min print(new_lst)
def to_fahrenheit (temperature): fahrenheit = (temperature * (9 / 5)) + 32 return fahrenheit def to_celsius (temperature): celsius = (temperature - 32) * (5 / 9) return celsius def to_kelvin (temperature): #print("tc") #print(to_celsius(212)) kelvin = temperature + 273.15 return kelvin f = to_fahrenheit(100) c = to_celsius(32) k = to_kelvin(-273.15) m = to_fahrenheit(to_celsius(98.6)) print("fahrenheit: " + str(f)) print("celsius: " + str(c)) print("kelvin: " + str(k)) print("multiconvert: " + str(m))
#do slice to trip the space(method 1) def trim(s): item1 = 0 item2 = -1 while item1 < len(s): if s[item1] == ' ': item1 += 1 else: break while item2 > -len(s): if s[item2] == ' ': item2 -= 1 else: break return s[item1 : len(s) + item2 + 1] if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!')
#判断回数(121,1331,1221等) ''' from functools import reduce digits = {'0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, \ '6' : 6, '7' : 7, '8' : 8, '9' : 9} def str2num(s): return digits[s] def fn(x, y): return 10 * x + y def is_palindrome(n): if n < 10: return True else: s = str(n) L = list(map(str2num, s)) n1 = reduce(fn, L) L.reverse() n2 = reduce(fn, L) return n1 == n2 ''' def is_palindrome(n): return str(n)[:] == str(n)[::-1] #more simple way~~ #[start end step] output = filter(is_palindrome, range(1, 1000)) print('1~1000:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('测试成功!') else: print('测试失败!')
from functools import reduce digits = {'0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, \ '6' : 6, '7' : 7, '8' : 8, '9' : 9} def str2int(s): def chr2num(s): return digits[s] return reduce(lambda x, y: 10 * x + y, map(chr2num, s)) S = input("Input your string:") print(str2int(S)) print(type(str2int(S)))
# -*- coding: utf-8 -*- """ Created on Sun Dec 13 00:46:30 2020 @author: nnath """ #DATA VISUALIZATION FOR DATAT SCIENCE ''' Popular plotting libaries MATPLOTLIB : to create 2D graphs ; uses numpy internally PANDAS VISUALISATION : built on Matplotlib SEABORN : High level interface for attractive and informative statistical graphs GGPLOT : based on R; Grammer Of Graphics PLOTLY : Create interactive plots ''' import pandas as pd import os import numpy as np import matplotlib.pyplot as plt os.chdir(r'D:\GITHUB\PANDAS\Pandas') os.listdir() df_cars = pd.read_csv('CARS.csv',sep=",") df_cars.isnull().sum() df_cars.dropna(axis=0,inplace=True) df_cars.info() #SCATTER PLOT : or Correlation Plot - used to convery relation between 2 numerical variables plt.scatter(df_cars['EngineSize'],df_cars['Weight'],c='red') plt.title('Scatter plot for EngineSize vs Weight') plt.xlabel('EngineSize') plt.ylabel('Weight') plt.show() #Histogram : used to represent frequency distribution of numerical variables #height represent the frequency of each range or bin plt.hist(df_cars['Weight'].head(100)) plt.hist(df_cars['Length'],color='green',edgecolor='white',bins=5) plt.title('Histogram plot for length of cars') plt.xlabel('m') plt.ylabel('Length') #---------------------------------- ''' # Generate data on commute times. ''' #1 size, scale = 1000, 10 commutes = np.random.gamma(scale, size=size) ** 1.5 plt.hist(commutes) #2 size, scale = 1000, 10 commutes = pd.Series(np.random.gamma(scale, size=size) ** 1.5) commutes.plot.hist(grid=True, bins=20, rwidth=0.9, color='#607c8e') plt.title('Commute Times for 1,000 Commuters') plt.xlabel('Counts') plt.ylabel('Commute Time') plt.grid(axis='y', alpha=0.75) #----------------------------------------- #BAR PLOT : distribution of categorial variables df = pd.crosstab(index=df_cars['Make'],columns='count',dropna=True)#returns only count column need 'Make' column df_cars['count']=1 df_cars.groupby(['Make']).count()['count'] df_cars.drop(columns = ['count'], inplace = True) #df of car name and its count to represent in bar graph counts = df_cars['Make'].value_counts()#series returned car_brands = pd.unique(df_cars['Make'])#array returned index = np.arange(len(car_brands)) plt.bar(index , counts , color = 'red') plt.bar(index , counts , color = ['red','blue']) plt.bar(index , counts , color = ['red','blue','yellow','green']) plt.title('Bar plot for cars') plt.xlabel('Car brand') plt.ylabel('Frequency') plt.xticks(index,car_brands) ''' dd_sorted = (df_cars['Make'].head(50)).sort_values(ascending=True) counts = dd_sorted.value_counts().sort_index(ascending=True)#series returned; sort by index ''' #counts = df_cars['Make'].head(50).value_counts() #counts is in descending order and car_brand in random order #in plt.bar() we give array to match with the corresponding count and car_brand counts = df_cars['Make'].head(50).value_counts().sort_index(ascending=True) car_brands = pd.unique(df_cars['Make'].head(50))#array returned counts.sort_values() index = np.arange(len(car_brands)) #plt.bar(index , counts , color = 'red') #plt.bar(index , counts , color = ['red','blue']) plt.bar(index , counts , color = ['red','blue','yellow','green']) plt.title('Bar plot for cars') plt.xlabel('Car brand') plt.ylabel('Frequency') plt.xticks(index,car_brands)#,rotation=70)
import math # Returns the lcm of first n numbers def lcm(n): ans = 1 for i in range(1, n + 1): ans = int((ans * i)/math.gcd(ans, i)) return ans # main n = 20 print (lcm(n))
import json def are_equal_lists(list1, list2): """Check if two lists contain same items regardless of their orders.""" return len(list1) == len(list2) and all(list1.count(i) == list2.count(i) for i in list1) def load_json_data(json_file_path): with open(json_file_path, 'r') as json_file: return json.load(json_file)
from tkinter import * cal= Tk() cal.title("Calculator") expression = "" cal.iconbitmap('E:\calculator.ico') cal.config(bg="gray25") def add(value): global expression expression += value label_display.config(text=expression) def clear(): global expression expression = "" label_display.config(text=expression) def calculate(): global expression result = "" if expression != "": try: result = eval(expression) except: result = "error" expression = "" label_display.config(text=result) label_display = Label(cal,width=13,borderwidth=5,text="",font=('ds-digital',15,'bold'),bg="gray25",fg="khaki1") label_display.grid(row=0, column=0, columnspan=4) button_1 = Button(cal,width=3, text="1", font=('ds-digital',15,'bold'),bg="gray75", command=lambda: add("1")) button_1.grid(row=1, column=0) button_2 = Button(cal,width=3, text="2", font=('ds-digital',15,'bold'),bg="gray75",command=lambda: add("2")) button_2.grid(row=1, column=1) button_3 = Button(cal,width=3, text="3", font=('ds-digital',15,'bold'),bg="gray75",command=lambda: add("3")) button_3.grid(row=1, column=2) button_divide = Button(cal,width=3, text="/",font=('ds-digital',15,'bold'),bg="orange2",fg="white",command=lambda: add("/")) button_divide.grid(row=1, column=3) button_4 = Button(cal,width=3, text="4",font=('ds-digital',15,'bold'),bg="gray75", command=lambda: add("4")) button_4.grid(row=2, column=0) button_5 = Button(cal,width=3, text="5",font=('ds-digital',15,'bold'),bg="gray75",command=lambda: add("5")) button_5.grid(row=2, column=1) button_6 = Button(cal,width=3, text="6",font=('ds-digital',15,'bold'),bg="gray75",command=lambda: add("6")) button_6.grid(row=2, column=2) button_multiply = Button(cal,width=3,text="*",font=('ds-digital',15,'bold'),bg="orange2",fg="white", command=lambda: add("*")) button_multiply.grid(row=2, column=3) button_7 = Button(cal,width=3, text="7", font=('ds-digital',15,'bold'),bg="gray75",command=lambda: add("7")) button_7.grid(row=3, column=0) button_8 = Button(cal,width=3,text="8", font=('ds-digital',15,'bold'),bg="gray75", command=lambda: add("8")) button_8.grid(row=3, column=1) button_9 = Button(cal,width=3, text="9", font=('ds-digital',15,'bold'),bg="gray75",command=lambda: add("9")) button_9.grid(row=3, column=2) button_subtract = Button(cal,width=3, text="-",font=('ds-digital',15,'bold'),bg="orange2",fg="white",command=lambda: add("-")) button_subtract.grid(row=3, column=3) button_clear = Button(cal,width=3, text="C",font=('ds-digital',15,'bold'),bg="orange2",fg="white",command=lambda: clear()) button_clear.grid(row=4, column=0) button_0 = Button(cal,width=3, text="0", font=('ds-digital',15,'bold'),bg="gray75",command=lambda: add("0")) button_0.grid(row=4, column=1) button_dot = Button(cal,width=3, text=".", font=('ds-digital',15,'bold'),bg="gray75",command=lambda: add(".")) button_dot.grid(row=4, column=2) button_add = Button(cal,width=3, text="+",font=('ds-digital',15,'bold'),bg="orange2",fg="white", command=lambda: add("+")) button_add.grid(row=4, column=3) button_equals = Button(cal, text="=", width=22, command=lambda: calculate()) button_equals.grid(row=5, column=0, columnspan=4) mainloop()
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here Node = pHead ppre = None pnext = None # 设置了三个指针 re = None while (Node!= None): if Node.next == None: re = Node pnext = Node.next #四步实现将Node的下一个指向前一个元素 Node.next = ppre ppre = Node Node = pnext return re
class Solution: # array 二维列表 def Find(self, target, array): # write code here row_N = len(array) col = len(array[0]) - 1 if (row_N > 0 and col > 0): # 至少要有一行和一列,才能进行循环 row = 0 while (row < row_N and col >= 0): # 遍历完所有行和列的时候终止循环 if array[row][col] > target: col -= 1 elif array[row][col] < target: row += 1 else: return True return False else: return False
# -*- coding:utf-8 -*- class Solution: min_stack = [] data = [] def push(self, node): # write code here self.data.append(node) if len(self.min_stack)==0 or node < self.min_stack[-1]: #倒数第一个元素 self.min_stack.append(node) else: self.min_stack.append(self.min_stack[-1]) def pop(self): # write code here if len(self.data) > 0: self.data.pop() self.min_stack.pop() def top(self): # write code here return self.data[-1] def min(self): # write code here return self.min_stack[-1]
# -*- coding:utf-8 -*- class Solution: def reOrderArray(self, array): # write code here odd = [] even = [] for num in array: if num&(2-1) == 1: #用位与计算代替求余,判断奇 odd.append(num) if num&(2-1) == 0: #用位与计算代替求余,判断偶 even.append(num) return odd+even
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here r1 = 1 r2 = 2 if number < 3: return number else: for i in range(3,number+1): fn = r1+r2 # 横着放时,必须同时横放两个才不会出现覆盖 r1,r2 = r2,fn return fn
# 13. Escreva um programa que substitua ‘,’ por ‘.’ e ‘.’ por ‘,’ em uma string. Exemplo: 1,000.54 # por 1.000,54. myname = input('Qual é o seu nome? ====>>>: ') print() numantigo = input(myname + ', digite um número com vírgulas para as partes inteiras e ponto para as partes decimais: ') print() numnovo = numantigo.translate({ord(','): '.', ord('.'): ','}) print('Bem, '+ myname +', o valor que você digitou foi transformado para: ' + numnovo) print() print(myname +', obrigado por você ter particiado dessa experiência.')
a=int(input("Digite o Primeiro Número")) #Converte em inteiro, aplicado aos demais tipos da linguagem b=int(input("Digite o Segundo Número")) for x in range(a,b): if (x%4)==0: print(x)
#!/usr/bin/python m_palidromes = [] def isPalindrome(m_num, m_palidromes): if ( str(m_num) == str(m_num)[::-1] ): m_palidromes.append(m_num) return m_palidromes for m_left in xrange(999, 100, -1): for m_right in xrange(999, 100, -1): m_palidromes = isPalindrome(m_left * m_right, m_palidromes) m_palidromes.sort() print m_palidromes[-1]
class Token(): def __init__(self,Tipo,caracter): #Constructor de la clase animal self.Tipo=Tipo #usamos la notacion __ por que lo estamos encapsulando, ninguna subclase puede acceder a el, es un atributo privado self.caracter=caracter def setTipo(self,Tipo): self.__Tipo=Tipo def getTipo(self): return self.__Tipo def setcaracter(self,caracter): self.__caracter=caracter def getcaracter(self): return self.caracter def miestado(self): print("Tipo: ",self.__Tipo,"--------->"+"Token: ",self.__caracter)
#!/usr/bin/env python import sys,os,argparse def main(): it = get_args() try: file = open(it.thefile,'r') except: print "cant open file: ",it.thefile,"." print "we will replace ",it.searcher," with ",it.replacer, \ " in the file ",it.thefile," and output that to the screen" for lines in file: print lines.replace(it.searcher,it.replacer).rstrip() file.close() sys.exit(0) def get_args(): parser = argparse.ArgumentParser(description="This will read in a file and replace a word with another") parser.add_argument("-f","--file",dest="thefile", default="/Users/peltzaj/Desktop/mouse.txt", help="Absolute File Path to file to be manipulated") parser.add_argument("-s","--search",dest="searcher",default="the", help="the word to be replaced") parser.add_argument("-r","--replace",dest="replacer",default="teh", help="the word to replace the searched word with") args = parser.parse_args() return args if __name__ == "__main__": main()
# -*- coding: UTF-8 -*- import time from copy import deepcopy board_size = 0 def read_data(filename): """根据文件名读取board :param filename: :return: """ board = [] # 限制分为大于,小于两部分存,为了后面检查限制的时候更方便 comparison_constraint = [] with open(filename) as f: global board_size board_size = int(f.readline()) for i in range(board_size): line = f.readline() row = [int(num) for num in line.split(' ')] board.append(row) # 读取比较限制 lines = f.readlines() for line in lines: constraint = [int(num) for num in line.split(' ')] comparison_constraint.append(constraint) # print(comparison_constraint) return board, comparison_constraint def initial(board): """根据读出的board信息,初始化值域和赋值情况 :param board: 二维列表 :return: 初始化值域和赋值情况 """ domain = [] assigned = [] for i in range(board_size): row = [] for j in range(board_size): if board[i][j] != 0: row.append(True) else: row.append(False) assigned.append(row) # 初始化值域 for row in board: domain_each_row = [] for grid in row: # 未赋值 if grid == 0: grid_domain = [v for v in range(1, board_size + 1)] domain_each_row.append(grid_domain) else: domain_each_row.append([grid]) domain.append(domain_each_row) return (domain, assigned) def print_board(board): for row in board: for i in row: print(i, end=' ') print('') def MRV(domain, assigned): """寻找值域最小的格子,返回其坐标,若都已赋值则返回 [-1,-1] :param domain: 所有格子的值域 :param assigned: 所有格子的赋值情况 :return: 返回值域最小的格子的坐标,若都已赋值则返回 [-1,-1] """ least_domain_len = 99999 x = -1 y = -1 for r in range(board_size): for c in range(board_size): domain_len = len(domain[r][c]) if not assigned[r][c] and domain_len < least_domain_len: x = r y = c least_domain_len = domain_len return (x, y) def compare_check(domain, comparison, x, y, cur_value): """对比较限制的检查 :param domain: 格子值域,每个格子一个列表,board由一个二维列表构成,故为三维列表 :param comparison: 比较限制列表,二维列表,每一行表示一个大小限制 :param x: 当前坐标 :param y: 当前坐标 :param cur_value: 当前取值 :return: 限制可满足则返回True,否则False """ n = 0 satisfied = 0 # 遍历限制,有多少限制就要满足多少,否则为不满足 for constraint in comparison: if x == constraint[0] and y == constraint[1]: n += 1 for value in domain[constraint[2]][constraint[3]]: if cur_value < value: satisfied += 1 break elif x == constraint[2] and y == constraint[3]: n += 1 for value in domain[constraint[0]][constraint[1]]: if cur_value > value: satisfied += 1 break return n == satisfied def recursive_check(domain, comparison, row_or_col, cur_index, num_checked, visited): """主要为了检查all-diff,也就是该行该列是否能各不相同,因为board_size会变,才写成递归 :param domain: 格子值域,每个格子一个列表,board由一个二维列表构成,故为三维列表 :param comparison: 比较限制列表,二维列表,每一行表示一个大小限制 :param row_or_col: 0或1,指明正在做行检查还是列检查,0表示行检查 :param cur_index: 如果当前在做行检查,作为行坐标,否则为列坐标,检查时,该值不变,另一个坐标会在 0~board_size-1变化 :param num_checked: 该行或该列已检查过的坐标数 :param visited: 该行该列哪些值已经取了,列表 :return: 所有条件都满足时返回 True """ if num_checked == board_size: return True if row_or_col == 0: x = cur_index y = num_checked else: x = num_checked y = cur_index # 检查该行或该列第num_checked格子 for value in domain[x][y]: # 该行或列已经有这个值了,或者未通过大小限制的检查,则继续检查下一个值 compare_satisfied = compare_check(domain, comparison, x, y, value) if visited[value] or not compare_satisfied: continue # 如果通过了大小检查,也保证了该行或列没有相同的值 # 则标记该值已有,继续赋值下一个 visited[value] = True if recursive_check(domain, comparison, row_or_col, cur_index, num_checked + 1, visited): return True visited[value] = False # 如果所有值都不行,则返回上一层,重新赋值,重新检查 return False def constraints_check(domain, comparison, row_or_col, cur_index, x, y, value): """调用递归检查,做all_diff检查和比较限制检查 :param domain: 格子值域,每个格子一个列表,board由一个二维列表构成,故为三维列表 :param comparison: 比较限制列表,二维列表,每一行表示一个大小限制 :param row_or_col: 0或1,指明正在做行检查还是列检查,0表示行检查 :param cur_index: 如果当前在做行检查,作为行坐标,否则为列坐标,检查时,该值不变,另一个坐标会在 0~board_size-1变化 :param x: 坐标 :param y: 坐标 :param value: 当前格子的取值 :return: 如果能找到一些赋值,满足两方面的限制就返回True """ visited = [False for i in range(board_size+1)] domain_copy = deepcopy(domain[x][y]) domain[x][y] = [value] can_be_satisfied = recursive_check(domain, comparison, row_or_col, cur_index, 0, visited) domain[x][y] = deepcopy(domain_copy) return can_be_satisfied def GAC_Enforce(domain, comparison, x, y): """检查限制条件,并去掉不合适的值 :param domain: 格子值域,每个格子一个列表,board由一个二维列表构成,故为三维列表 :param comparison: 比较限制列表,二维列表,每一行表示一个大小限制 :param x: 坐标 :param y: 坐标 :return: 某个坐标值域被删空了就返回True,表示发生了DWO """ GACQueue = [] # 0表示行检查,1表示列检查 # 大小比较每次都会做,所以没有单独再入队。如果反之,每次是大小限制入队的话,会很慢!!! # 因为一个格子的坐标发生了变化,会影响行列,所以都是成对出现的 # 初始入队 (0, x)表示对x行进行行检查,(1, y)表示对y列进行列检查 GACQueue.append((0, x)) GACQueue.append((1, y)) while GACQueue: row_or_col_check, cur_index = GACQueue[0] del(GACQueue[0]) # 检查该行或该列的所有格子 for other_index in range(board_size): if row_or_col_check == 0: x = cur_index y = other_index else: x = other_index y = cur_index cur_domain = domain[x][y] for value in cur_domain: # 如果不能满足条件则去掉该值,这里会做all-diff检查和大小限制检查 if not constraints_check(domain, comparison, row_or_col_check, cur_index, x, y, value): domain[x][y] = [v for v in domain[x][y] if v != value] # 如果值域为空则,返回True,表示发生了 DWO if not domain[x][y]: return True # 如果值域不为空,且相关限制不在队列中则将相关限制加入队列 # r=1,则变化的是[O,C]处, 有 (0,O), (1,C)入队 # r=0,则变化的是[C,O]处, 有 (0,C), (1,O)入队 else: if (row_or_col_check, cur_index) not in GACQueue: GACQueue.append((row_or_col_check, cur_index)) if (1 - row_or_col_check, other_index) not in GACQueue: GACQueue.append((1 - row_or_col_check, other_index)) return False def GAC(domain, comparison, assigned, board): """GAC算法,赋值,调用GAC_Enforce做检查去值,每次调用代表赋值一个格子 :param domain: 格子值域,每个格子一个列表,board由一个二维列表构成,故为三维列表 :param comparison: 比较限制列表,二维列表,每一行表示一个大小限制 :param assigned: 所有格子是否赋值的情况,二维bool列表 :param board: 棋盘,二维列表 :return: 找到解就返回True,否则返回False """ # 找值域最小的赋值 (x, y) = MRV(domain, assigned) # 若全部都完成赋值 if (x, y) == (-1, -1): return True assigned[x][y] = True values = domain[x][y] # 暂存值域 temp_domain = deepcopy(domain) for value in values: board[x][y] = value # 赋值,也就去掉其他的值 domain[x][y] = [value] # 如果没有 DWO if not GAC_Enforce(domain, comparison, x, y): find_solution = GAC(domain, comparison, assigned, board) if find_solution: return True # 恢复值域 domain = deepcopy(temp_domain) assigned[x][y] = False return False def run_test(filename): board, comparison = read_data(filename) print_board(board) print("-----------------------") domain, assigned = initial(board) begin = time.time() GAC(domain, comparison, assigned, board) end = time.time() print_board(board) print('Time cost:', end - begin, 's') if __name__ == '__main__': run_test('4.txt') print('\n') run_test('5.txt') print('\n') run_test('6.txt') print('\n') run_test('7.txt') print('\n') run_test('8.txt')
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt pd.set_option('max_columns', 15) #loading the datasets train = pd.read_csv('train_Df64byy.csv') test = pd.read_csv('test_YCcRUnU.csv') target = 'Response' ID = test['ID'] #First look to the data train.head() #Some basic stats of the dataset train.describe() #We have to remove the ID variable, as it is not going to be part of the study train = train.drop(['ID'], axis = 1) test = test.drop(['ID'], axis = 1) #SOME PLOTS TO ANALYSE THE DATA #We need to divide the data into numerical and categorical variables, in order to #do the proper plots num_variables = train.select_dtypes(include = [np.number]) cat_variables = train.select_dtypes(include = [np.object]) #Boxplots for numerical variables fig = plt.figure(figsize=(12,10)) for i in range(len(num_variables.columns)): fig.add_subplot(2, 4, i+1) sns.boxplot(y=num_variables.iloc[:,i]) plt.tight_layout() plt.show() #Countplots for categorical variables fig2 = plt.figure(figsize = (12,15)) for i in range(len(cat_variables.columns)): fig2.add_subplot(2,3, i+1) sns.countplot(x=cat_variables.iloc[:,i]) plt.tight_layout() plt.show() #With this plots we can have an idea about the distribution of each variable #DATA CLEANING #Analysing the presence of missing values (train.isna().sum()) (test.isna().sum()) #We have missing values in three diferent variables: Health Indicator, Holding_Policy_Type, #and Holding_Policy_and Holding_Policy_Duration #Dealing with missing values #First, we are going to replace missing values by the most common values train['Health Indicator'] = (train['Health Indicator'].fillna(train['Health Indicator'].mode()[0])) test['Health Indicator'] = (test['Health Indicator'].fillna(test['Health Indicator'].mode()[0])) #Before doing the same with Holding Policy variables, we are going to create a new variable #that gets a 1 if the customer has a holding policy and a 0 if not. train['Holding_policy'] = [1 if x>0 else 0 for x in (train['Holding_Policy_Type'])] test['Holding_policy'] = [1 if x>0 else 0 for x in (test['Holding_Policy_Type'])] train['Holding_Policy_Type'] = (train['Holding_Policy_Type'].fillna(train['Holding_Policy_Type'].mode()[0])) test['Holding_Policy_Type'] = (test['Holding_Policy_Type'].fillna(test['Holding_Policy_Type'].mode()[0])) #This variable contain numerical and categorical levels, so first, we have to replace #the categorical level by a number, and then replace na values by the most common one train['Holding_Policy_Duration'] = (train['Holding_Policy_Duration'].replace('14+', 15.0)) test['Holding_Policy_Duration'] = test['Holding_Policy_Duration'].replace('14+', 15.0) train['Holding_Policy_Duration'] = (train['Holding_Policy_Duration'].fillna(train['Holding_Policy_Duration'].mode()[0])).astype('float64') test['Holding_Policy_Duration'] = (test['Holding_Policy_Duration'].fillna(test['Holding_Policy_Duration'].mode()[0])).astype('float64') #Correlation matrix matrix = train.corr().abs() sns.heatmap(matrix, annot= True) plt.show() #We can see correlation between Upper age and Lower age, so we have to remove one of them #First we are going to create a new variable, called dif_age, which is the difference #between upper and lower age train['Dif_age'] = train['Upper_Age'] - train['Lower_Age'] test['Dif_age'] = test['Upper_Age'] - test['Lower_Age'] #Now we can remove Upper or Lower age, cause they are correlated and also included in this #new variable. Upper Age is going to be dropped, cause it is also correlated with Reco_Policy_Premium train = train.drop(['Upper_Age'], axis =1) #try then dropping lower age test = test.drop(['Upper_Age'], axis =1) #LABEL ENCODING #There are some variables that need to be encoded from sklearn.preprocessing import LabelEncoder #This encoding is for variables whose levels dont have a hierarchical order, they are independent train = pd.get_dummies(train, columns = ['City_Code','Accomodation_Type', 'Reco_Insurance_Type', 'Is_Spouse']) test = pd.get_dummies(test, columns = ['City_Code','Accomodation_Type', 'Reco_Insurance_Type', 'Is_Spouse']) #On the other hand, label encoder is used for variables whose levels need a hierarchical order, which means #that distances between levels are important (the model needs to know that) encoder = LabelEncoder() train['Health Indicator'] = encoder.fit_transform(train['Health Indicator']) test['Health Indicator'] = encoder.fit_transform(test['Health Indicator']) train['Holding_Policy_Type'] = encoder.fit_transform(train['Holding_Policy_Type']) test['Holding_Policy_Type'] = encoder.fit_transform(test['Holding_Policy_Type']) #MODEL from sklearn.utils import class_weight from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from lightgbm import LGBMClassifier from sklearn.model_selection import RandomizedSearchCV X_train = train.drop(['Region_Code', 'Response'], axis = 1) Y_train = train['Response'] X_test = test.drop(['Region_Code'], axis = 1) #LIGHT GBM x_train, x_val, y_train, y_val = train_test_split(X_train, Y_train, test_size=0.2) weights = class_weight.compute_class_weight('balanced', np.unique(y_train), y_train) weights = dict(enumerate(weights)) #MODEL #LIGHTGBM from sklearn.model_selection import RepeatedStratifiedKFold model = LGBMClassifier(class_weight=weights, metric = 'roc_auc_score', learning_rate=0.15, max_depth=14, feature_fraction =0.9, num_leaves=2^14) learning_rate = [0.01, 0.02, 0.05, 0.1, 0.12, 0.15,0.2] max_depth = range (1,15) feature_fraction = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] subsample = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) params = dict(learning_rate=learning_rate, max_depth=max_depth, feature_fraction=feature_fraction, subsample=subsample) search = RandomizedSearchCV(model, param_distributions=params, cv=cv, n_jobs=-1, n_iter=10) search.fit(x_train, y_train) print("Best: %f using %s" % (search.best_score_, search.best_params_)) model.fit(X_train, Y_train) prediction = model.predict(x_val) accuracy = roc_auc_score(prediction, y_val) print(accuracy) prediction_bien = model.predict(X_test) complete = pd.DataFrame({'ID': ID, target: prediction_bien}) complete.to_csv(r'E:\MACHINE LEARNING\Python projects\jobathon\lightgbm_bien.csv', index=False)
# Process the word list # Remove the words that has numbers/special characters f = open("words.txt","r") print f myList = [] for line in f: if line.strip().isalpha(): myList.append(line) print len(myList) f = open("english_words.txt",'w') for i in myList: f.write(i)
"""Custom topology example author: Brandon Heller ([email protected]) Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo, Node class MyTopo( Topo ): "Simple topology example." def __init__( self, enable_all = True ): "Create custom topo." # Add default members to class. super( MyTopo, self ).__init__() # Set Node IDs for hosts and switches Host1 = 1 Host2 = 2 Host3 = 3 Host4 = 4 Host5 = 5 Host6 = 6 Host7 = 7 Host8 = 8 Switch1 = 9 Switch2 = 10 Switch3 = 11 Switch4 = 12 Switch5 = 13 Switch6 = 14 # Add nodes self.add_node( Switch1, Node( is_switch=True ) ) self.add_node( Switch2, Node( is_switch=True ) ) self.add_node( Switch3, Node( is_switch=True ) ) self.add_node( Switch4, Node( is_switch=True ) ) self.add_node( Switch5, Node( is_switch=True ) ) self.add_node( Switch6, Node( is_switch=True ) ) self.add_node( Host1, Node( is_switch=False ) ) self.add_node( Host2, Node( is_switch=False ) ) self.add_node( Host3, Node( is_switch=False ) ) self.add_node( Host4, Node( is_switch=False ) ) self.add_node( Host5, Node( is_switch=False ) ) self.add_node( Host6, Node( is_switch=False ) ) self.add_node( Host7, Node( is_switch=False ) ) self.add_node( Host8, Node( is_switch=False ) ) # Add edges self.add_edge( Host1, Switch1 ) self.add_edge( Host2, Switch1 ) self.add_edge( Host3, Switch6 ) self.add_edge( Host4, Switch6 ) self.add_edge( Host5, Switch3 ) self.add_edge( Host6, Switch3 ) self.add_edge( Host7, Switch5 ) self.add_edge( Host8, Switch5 ) self.add_edge( Switch1, Switch2 ) self.add_edge( Switch2, Switch6 ) self.add_edge( Switch2, Switch3 ) self.add_edge( Switch3, Switch4 ) self.add_edge( Switch4, Switch5 ) self.add_edge( Switch4, Switch1 ) # Consider all switches and hosts 'on' self.enable_all() topos = { 'mytopo': ( lambda: MyTopo() ) }
#pragma once #include "Tile.h" class Tile: # char ,char ,Piece* """ The function creates the class variable of the Bishop Input- bishop's x, bishop's y, piece to set on tile Output- none """ def __init__(self, x, y, piece = None): self._x = x self._y = y self._piece = piece """ The function returns the piece on the tile Input- none Output- piec of the tile """ def getPiece(self): return self._piece """ The function delets all of the dynamic variables Input- none Output- none Tile::~Tile() { }""" #Piece* """ The function sets inputed piece as tile piece Input- piece to set Output- none """ def setPiece(self, piece): self._piece = piece """ The function returns the x of the tile Input- none Output- the x of the tile """ def getX(self): return self._x """ The function returns the x of the tile Input- none Output- none """ def getY(self): return self._y
__author__ = 'longqi' ''' import time run = raw_input("Start? > ") mins = 0 # Only run if the user types in "start" if run == "start": # This is saying "while we have not reached 20 minutes running" while mins != 20: print ">>>>>>>>>>>>>>>>>>>>>", mins # Sleep for a minute time.sleep(60) # Increment the minute total mins += 1 # Bring up the dialog box here ''' ''' import sched import time s = sched.scheduler(time.time, time.sleep) def print_time(): print "From print_time", time.time() def print_some_times(): print time.time() s.enter(5, 1, print_time, ()) s.enter(10, 1, print_time, ()) s.run() print time.time() print_some_times() ''' ''' import sched import time def hello(name): print 'hello world, i am %s, Current Time:%s' % (name, time.time()) run(name) def run(name): s = sched.scheduler(time.time, time.sleep) s.enter(3, 2, hello, (name,)) s.run() s = sched.scheduler(time.time, time.sleep) s.enter(3, 2, hello, ('guo',)) s.run() ''' ''' from threading import Event, Thread import time class RepeatTimer(Thread): def __init__(self, interval, function, iterations=0, args=[], kwargs={}): Thread.__init__(self) self.interval = interval self.function = function self.iterations = iterations self.args = args self.kwargs = kwargs self.finished = Event() def run(self): count = 0 while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) count += 1 def cancel(self): self.finished.set() def hello(): print 'hello world, Current Time:%s' % (time.time()) r = RepeatTimer(5.0, hello) r.start() ''' ''' from threading import Timer def hello(): print "hello, world" t.run() t = Timer(1.0, hello) t.start() # after 1 seconds, "hello, world" will be printed ''' import threading; i = 0 def work(): global i threading.Timer(0.01, work).start() print("stackoverflow ", i, end='\r') i += 1 work();
dezena = input("Digite um número inteiro:") dezena = int(dezena) valor = dezena // 10 valor = valor % 10 print("O dígito das dezenas é",valor)
def fatorial(k): '''(int) -> int Recebe um inteiro k e retorna o valor de k! Pre-condicao: supoe que k eh um numero inteiro nao negativo. ''' if k == 0: k_fat = 1 else: k_fat = k * fatorial(k - 1) return k_fat # testes print("0! =", fatorial(0)) print("1! =", fatorial(1)) print("5! =", fatorial(5)) print("6! =", fatorial(6))