blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
5b5b2327e84313fca65952be1f103454b6f63797
annatjohansson/complex_dynamics
/Python scripts/M_DEM.py
2,566
3.8125
4
def M_Dist(cx, cy, max_it, R): """Computes the distance of a point z = x + iy from the Mandelbrot set """ """Inputs: c = cx + cy: translation max_it: maximum number of iterations R: escape radius (squared)""" x = 0.0 y = 0.0 x2 = 0.0 y2 = 0.0 dist = 0.0 it = 0 # List to store the orbit of the origin X = [0]*(max_it + 1) Y = [0]*(max_it + 1) # Iterate p until orbit exceeds escape radius or max no. of iterations is reached while (it < max_it) and (x2 + y2 < R): temp = x2 - y2 + cx y = 2*x*y + cy x = temp x2 = x*x y2 = y*y # Store the orbit X[it] = x Y[it] = y it = it + 1 # If the escape radius is exceeded, calculate the distance from M if (x2 + y2 > R): x_der = 0.0 y_der = 0.0 i = 0 flag = False # Approximate the derivative while (i < it) and (flag == False): temp = 2*(X[i]*x_der - Y[i]*y_der)+1 y_der = 2*(Y[i]*x_der + X[i]*y_der) x_der = temp flag = max(abs(x_der),abs(y_der)) > (2 ** 31 - 1) i = i+1 if (flag == False): dist = np.log(x2 + y2)*np.sqrt(x2 + y2)/np.sqrt(x_der*x_der + y_der*y_der) return dist def M_DEM(M, nx, ny, x_min, x_max, y_min, y_max, max_it, R, threshold): """Computes an approximation of the Mandelbrot set via the distance estimation method""" """Inputs: M: an output array of size nx*ny nx, ny: the image resolution in the x- and y direction x_min, x_max: the limits of the x-axis in the region y_min, y_max: the limits of the y-axis in the region max_it: the maximum number of iterations R: escape radius (squared) threshold: critical distance from the Mandelbrot set (in pixel units)""" # Calculate the threshold in terms of distance in the complex plane delta = threshold*(x_max-x_min)/(nx-1) # For each pixel in the nx*ny grid, calculate the distance of the point for iy in range(0, ny): cy = y_min + iy*(y_max - y_min)/(ny - 1) for ix in range(0, nx): cx = x_min + ix*(x_max - x_min)/(nx - 1) #Determine whether distance is smaller than critical distance dist = M_Dist(cx, cy, max_it, R) if dist < delta: M[ix][iy] = 1 else: M[ix][iy] = 0 return M
bb975ed0ea6680a8f09e4f7307c3cc56bde2d83d
NguyenThienBao/SE_Python
/Lab01/Demo02.py
274
3.859375
4
def main(): a = 10 print(a) b = int(input("Plz enter a number: ")) print(b) c = float(input("Plz enter a float number: ")) print(c) d = b + c print("b + c = d - ", str(b) + " + " + str(c) + " = ", d) if __name__ == '__main__': main()
be63345a6c6a052fa14e442f14548633f118a34f
MurliCSE/LearningPython
/Learning.py
2,697
4
4
# Singe line comment ''' Multi Line comment ''' #Welcome to Python! ''' Python is a high-level programming language, with applications in numerous areas, including web programming, scripting, scientific computing, and artificial intelligence. It is very popular and used by organizations such as Google, NASA, the CIA, and Disney. Python is processed at runtime by the interpreter. There is no need to compile your program before executing it. Q1. Python is a: * It of editing tools * Programming language * Development environment ''' #Welcome to Python! ''' The three major versions of Python are 1.x, 2.x and 3.x. These are subdivided into minor versions, such as 2.7 and 3.3. Code written for Python 3.x is guaranteed to work in all future versions. Both Python Version 2.x and 3.x are used currently. This course covers Python 3.x, but it isn't hard to change from one version to another. Python has several different implementations, written in various languages. The version used in this course, CPython, is the most popular by far. An interpreter is a program that runs scripts written in an interpreted language such as Python. Q2. Which of these statements is true? *Python code must be always compiled *Python 1.7 is the most widely used version *CPython is an implementation of Python ''' #Your First Program ''' Let's start off by creating a short program that displays "Hello world!". In Python, we use the print statement to output text: >>> print('Hello world!') Hello world! Try It Yourself Congratulations! You have written your first program. Run, save, and share your Python code on our Code Playground without installing any additional software. When using a computer, you will need to download and install Python from www.python.org. Note the >>> in the code above. They are the prompt symbol of the Python console. Python is an interpreted language, which means that each line is executed as it is entered. Python also includes IDLE, the integrated development environment, which includes tools for writing and debugging entire programs. Q3. Fill in the blanks to print "Hi". >>> _____("Hi") Ans. print Printing Text The print statement can also be used to output multiple lines of text. For Example: >>> print('Hello world!') Hello world! >>> print('Hello world!') Hello world! >>> print('Spam and eggs...') Spam and eggs... Try It Yourself Python code often contains references to the comedy group Monty Python. This is why the words, "spam" and "eggs" are often used as placeholder variables in Python where "foo" and "bar" would be used in other programming languages. Q4. Fill in the blank to output "ni ni ni". >>> _____('ni ni ni'_ '''
811d54bfdd3d88b7b048218cde9aae2d35c643ce
TheMellyBee/udacity-projects
/support-classes/linear-alg/quiz1.py
317
3.609375
4
from vector import Vector vector1 = Vector([8.218,-9.341]) vector2 = Vector([-1.129, 2.111]) print "One" print vector1.plus(vector2) print "Two" vector3 = Vector([7.119, 8.215]) print vector3.minus(Vector([-8.223, 0.878])) print "Three" vector4 = Vector([1.671, -1.012, -0.318]) print vector4.scalar_mult(7.41)
0232446325b58ecb878807316e3007eff77940fe
lalitp20/Python-Projects
/Self Study/Basic Scripts/IF_STATEMENT.py
213
4.34375
4
# Example for Python If Statement number = int(input(" Please Enter any integer Value: ")) if number >= 1: print(" You Have Entered Positive Integer ") else: print(" You Have Entered Negative Integer ")
c60128013d7e1ae2ccbf729b611e3135b51ed40e
lalitp20/Python-Projects
/Self Study/Basic Scripts/Comparison Operator.py
298
3.96875
4
a = 9 b = 4 print(" The Output of 9 > 4 is : ", a > b ) print(" The Output of 9 < 4 is : ", a < b ) print(" The Output of 9 <= 4 is : ", a <= b ) print(" The Output of 9 >= 4 is : ", a >= b ) print(" The Output of 9 Equal to 4 is : ", a == b ) print(" The Output of 9 Not Equal To is : ", a != b )
5f3d608227e523bb63f4a45e60bd9f9a120ef346
lalitp20/Python-Projects
/Self Study/Basic Scripts/Bit Wise Operators.py
347
3.90625
4
a = 10 b = 12 print("Bitwise AND Operator On 9 and 65 is = ", a & b) print("Bitwise OR Operator On 9 and 65 is = ", a | b) print("Bitwise EXCLUSIVE OR Operator On 9 and 65 is = ", a ^ b) print("Bitwise NOT Operator On 9 is = ", ~a) print("Bitwise LEFT SHIFT Operator On 9 is = ", a << 1) print("Bitwise RIGHT SHIFT Operator On 65 is = ", b >> 1)
c0597e939d13b6fdecd2e374868a4547128ee79a
lalitp20/Python-Projects
/Self Study/Basic Scripts/String Indexing_1.py
377
4.125
4
x = (11, 21, 31, 41, 51, 61, 71, 81, 91) # Positive Indexing print(x[0]) print(x[3]) print(x[6]) print('=======\n') # Negative Indexing print(x[-1]) print(x[-5]) print(x[-7]) print('=======\n') # Accessing Nested Tuple Items Mixed_Tuple = ((1, 2, 3), [4, 5, 6], 'Lalit') print(Mixed_Tuple[0][0]) print(Mixed_Tuple[1][0]) print(Mixed_Tuple[2][0]) print(Mixed_Tuple[2][4])
b203678db14a642b6da0446d34aa0223a7010718
lalitp20/Python-Projects
/Self Study/Basic Scripts/For_ELSE Statement.py
263
4.25
4
number = int(input(" Please Enter any integer below 100: ")) for i in range(0, 100): if number == i: print(" User entered Value is within the Range (Below 100)") break else: print(" User entered Value is Outside the Range (Above 100)")
5c0159a664bbc98b445b9e652e8b00dbc079a21b
lalitp20/Python-Projects
/Self Study/Basic Scripts/Iteration.py
103
3.5625
4
x = [1, 2, 3, 4, 5, 6, 7, 8, 9] for Number in range(len(x)): x[Number] = x[Number] * 10 print(x)
7b70d150000739cb2e83695b2908f09c6e1e13bf
hfyeomans/python-100days-class
/day_13_debugging/debugging fizzbuzz.py
1,094
4.15625
4
# # Orginal code to debug # for number in range(1, 101): # if number % 3 == 0 or number % 5 == 0: # print("FizzBuzz") # if number % 3 == 0: # print("Fizz") # if number % 5 == 0: # print("Buzz") # else: # print([number]) for number in range(1, 101): if number % 3 == 0 and number % 5 == 0: # <-- problem resolved print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: # <-- problem resolved print("Buzz") else: print([number]) # In this debug exercise we put it into a debugger. We see it count 1, 2, but from the first if statement it prints Fizz. but then it continues to evalulate all the if statements below. so it also prints Fizz. Then the last if is false, so it hits the else and prints the number. These ifs have to be indented. The first if statement is or so every time its either or it prints fizz, buzz, but also goes through the other statements and prings fizz and buzz and catches else. # The resolution was the or statement to and and also the third if statement to elif
8358d64850f1a3a442ea174daf52cedc451ca7f6
NazeerBZ/Pic-Simias
/MorphologicalTransformation.py
3,120
3.640625
4
from PyQt5 import QtCore, QtGui, QtWidgets # Import the PyQt5 module we'll need import numpy as np import cv2 #Morphological transformations are some simple operations based on the image shape. #It is normally performed on binary images. It needs two inputs, one is our original image, #second one is called structuring element or kernel. Two basic morphological operators are #Erosion and Dilation. Then its variant forms like Opening, Closing, Gradient etc class MorphologicalTransformation: def __init__(self, erosionSlider, dilationSlider, openingSlider, closingSlider): self.erosionSlider = erosionSlider self.dilationSlider = dilationSlider self.openingSlider = openingSlider self.closingSlider = closingSlider def erosion(self, img, writeImage, setImage): # The kernel slides through the image (as in 2D convolution). A pixel in the original # image (either 1 or 0) will be considered 1 only if all the pixels under the kernel is 1, # otherwise it is eroded (made to zero). So what happends is that, all the pixels near # boundary will be discarded depending upon the size of kernel. So the thickness or # size of the foreground object decreases or simply white region decreases in the image. # It is useful for removing small white noises kernel = np.ones((self.erosionSlider.value(),self.erosionSlider.value()), dtype='uint8') erosion = cv2.erode(img, kernel, iterations = 1) writeImage('./sys_img/temp.jpg', erosion) setImage() def dilation(self, img, writeImage, setImage): # It is just opposite of erosion. Here, a pixel element is ‘1’ if atleast one pixel # under the kernel is ‘1’. So it increases the white region in the image or size of # foreground object increases. Normally, in cases like noise removal, erosion is followed # by dilation. Because, erosion removes white noises, but it also shrinks our object. # So we dilate it. Since noise is gone, they won’t come back, but our object area # increases. kernel = np.ones((self.dilationSlider.value(),self.dilationSlider.value()), dtype='uint8') dilation = cv2.dilate(img, kernel, iterations = 1) writeImage('./sys_img/temp.jpg', dilation) setImage() def opening(self, img, writeImage, setImage): # Opening is just another name of erosion followed by dilation. kernel = np.ones((self.openingSlider.value(), self.openingSlider.value()), dtype='uint8') opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) writeImage('./sys_img/temp.jpg', opening) setImage() def closing(self, img, writeImage, setImage): # Closing is reverse of Opening, Dilation followed by Erosion. kernel = np.ones((self.closingSlider.value(), self.closingSlider.value()), dtype='uint8') closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) writeImage('./sys_img/temp.jpg', closing) setImage()
f1e22a69bf09af636894cd4497bca7f998c764ec
hanyun2019/Machine-Learning-with_Python
/ch01/OverviewSample.py
13,181
3.75
4
# Introduction to Machine Learning with Python # Chapter 1: Overview # Refreshed by Haowen Huang import numpy as np from scipy import sparse import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier # # Versions Used in your environment # import sys # print("Python version:", sys.version) # # import pandas as pd # print("pandas version:", pd.__version__) # import matplotlib # print("matplotlib version:", matplotlib.__version__) # # import numpy as np # print("NumPy version:", np.__version__) # import scipy as sp # print("SciPy version:", sp.__version__) # import IPython # print("IPython version:", IPython.__version__) # import sklearn # print("scikit-learn version:", sklearn.__version__) # import tensorflow # print("\nTensorflow version:", tensorflow.__version__) # from tensorflow import keras # print("\nKeras version:", keras.__version__) if __name__ == '__main__': x = np.array([[1,2,3],[4,5,6]]) print("\nx:\n{}".format(x)) # create a 2d numpy array with a diagonal of ones, and zeros everywhere else eye = np.eye(4) print("\nNumpy array:\n%s" % eye) # sparse matrix: 稀疏矩阵 - 矩阵中的元素大部分是0的矩阵 # convert the numpy array to a scipy sparse matrix in CSR format # only the non-zero entries are stored # CSR format: Compressed Sparse Row format sparse_matrix = sparse.csr_matrix(eye) print("\nScipy sparse CSR matrix:\n%s" % sparse_matrix) # COO representation data = np.ones(4) row_indices = np.arange(4) col_indices = np.arange(4) eye_coo = sparse.coo_matrix((data, (row_indices, col_indices))) print("\nCOO representation:\n", eye_coo) # Generate a sequence of integers x1 = np.arange(20) # create a second array using sinus y = np.sin(x1) # The plot function makes a line chart of one array against another plt.plot(x1, y, marker="x") # plt.show() # create a simple dataset of people data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location' : ["New York", "Paris", "Berlin", "London"], 'Age' : [24, 13, 53, 33] } # IPython.display allows "pretty printing" of dataframes # in the Jupyter notebook # data_pandas = pd.DataFrame(data) # display(data_pandas) print("\nSimple dataset of people:\n{}".format(data)) ######################################################################################### ## Classifying Iris Species # The data we will use for this example is the iris dataset, a classical dataset in machine learning an statistics. # It is included in scikit-learn in the dataset module. # Iris plants dataset # -------------------- # **Data Set Characteristics:** # :Number of Instances: 150 (50 in each of three classes) # :Number of Attributes: 4 numeric, predictive attributes and the class # :Attribute Information: # - sepal length in cm # - sepal width in cm # - petal length in cm # - petal width in cm # - class: # - Iris-Setosa # - Iris-Versicolour # - Iris-Virginica # :Summary Statistics: # ============== ==== ==== ======= ===== ==================== # Min Max Mean SD Class Correlation # ============== ==== ==== ======= ===== ==================== # sepal length: 4.3 7.9 5.84 0.83 0.7826 # sepal width: 2.0 4.4 3.05 0.43 -0.4194 # petal length: 1.0 6.9 3.76 1.76 0.9490 (high!) # petal width: 0.1 2.5 1.20 0.76 0.9565 (high!) # ============== ==== ==== ======= ===== ==== # :Missing Attribute Values: None # :Class Distribution: 33.3% for each of 3 classes. # The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. # One class is linearly separable from the other 2; the latter are NOT linearly separable from each other. print("\n--------'Sample - Classifying Iris Species' starts here--------") ## Meet the Data # from sklearn.datasets import load_iris iris_dataset = load_iris() print("\nKeys of iris_dataset:\n", format(iris_dataset.keys())) # The value to the key DESCR is a short description of the dataset. # We show the beginning of the description here. # print(iris_dataset['DESCR'][:9993] + "\n...") # Target names: # The value with key target_names is an array of strings, # containing the species of flower that we want to predict. # Target names: ['setosa' 'versicolor' 'virginica'] print("\nTarget names:\n", iris_dataset['target_names']) # Feature names: # The feature_names are a list of strings, giving the description of each feature. print("\nFeature names:\n", iris_dataset['feature_names']) # Data: # The data itself is contained in the target and data fields. # The data contains the numeric measurements of sepal length, sepal width, petal length, # and petal width in a numpy array. print("\nType of iris data:\n", type(iris_dataset['data'])) # Type of data: <class 'numpy.ndarray'> print("\nShape of iris data:\n", iris_dataset['data'].shape) # The rows in the data array correspond to flowers, # while the columns represent the four measurements that were taken for each flower. # Shape of data: (150, 4) # 150: The data contains measurements for 150 different flowers. # 40: Each flower has 4 measurements: sepal length, sepal width, petal length, and petal width # Here are the feature values for the first five samples. print("\nFirst five rows of data:\n", iris_dataset['data'][:5]) # The target array contains the species of each of the flowers that were measured, also as a numpy array: print("\nType of target:\n", type(iris_dataset['target'])) # The target is a one-dimensional array, with one entry per flower. (一维数组 每朵花对应其中一个数据) print("\nShape of target:\n", iris_dataset['target'].shape) # The species are encoded as integers from 0 to 2: # The meaning of the numbers are given by the iris['target_names'] array: # 0 means Setosa, 1 means Versicolor and 2 means Virginica. print("\nIris Target:\n", iris_dataset['target']) ###################################################################################### ## Measuring Success: Training and Testing Data # Scikit-learn contains a function that shuffles the dataset and splits it for you, # the train_test_split function. # This function extracts 75% of the rows in the data as the training set, # together with the corresponding labels for this data. # The remaining 25% of the data, together with the remaining labels are declared as the test set. # To make sure that we will get the same output if we run the same function several times, # we provide the pseudo random number generator with a fixed seed using the random_state parameter. # This will make the outcome deterministic, so this line will always have the same outcome. # from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( iris_dataset['data'], iris_dataset['target'], random_state=0) # The output of the train_test_split function are X_train, X_test, y_train and y_test, which are all numpy arrays. # X_train contains 75% of the rows of the dataset, and X_test contains the remaining 25%. print("\nX_train shape:\n", X_train.shape) print("\ny_train shape:\n", y_train.shape) print("\nX_test shape:\n", X_test.shape) print("\ny_test shape:\n", y_test.shape) ######################################################################################### ## First things first: Look at your data # Before building a machine learning model, it is often a good idea to inspect the data, # to see if the task is easily solvable without machine learning, # or if the desired information might not be contained in the data. # Additionally, inspecting your data is a good way to find abnormalities and peculiarities. # In the real world, inconsistencies in the data and unexpected measurements are very common. # One of the best ways to inspect data is to visualize it. # One way to do this is by using a scatter plot(散点图). # A scatter plot of the data puts one feature along the x-axis, one feature along the y- axis, and draws a dot for each data point. # Unfortunately, computer screens have only two dimensions, which allows us to only plot two (or maybe three) features at a time. # It is difficult to plot datasets with more than three features this way. # One way around this problem is to do a pair plot(散点图矩阵), # which looks at all pairs of two features. # create dataframe from data in X_train # label the columns using the strings in iris_dataset.feature_names iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names) # create a scatter matrix from the dataframe, color by y_train pd.plotting.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o', hist_kwds={'bins': 20}, s=60, alpha=.8) ######################################################################################### ## Building Your First Model: k-Nearest Neighbors # The k nearest neighbors classification algorithm is implemented in the KNeighborsClassifier class in the neighbors module. # Before we can use the model, we need to instantiate the class into an object. This is when we will set any parameters of the model. # The single parameter of the KNeighbor sClassifier is the number of neighbors, which we will set to one. # from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=1) # The knn object encapsulates the algorithm to build the model from the training data, # as well the algorithm to make predictions on new data points. # It will also hold the information the algorithm has extracted from the training data. # In the case of KNeighborsClassifier, it will just store the training set. # To build the model on the training set, we call the fit method of the knn object, # which takes as arguments the numpy array X_train containing the training data and # the numpy array y_train of the corresponding training labels: knn.fit(X_train, y_train) print("\nknn:\n", knn) ######################################################################################### ## Making Predictions # Imagine we found an iris in the wild with a sepal length of 5cm, a sepal width of 2.9cm, # a petal length of 1cm and a petal width of 0.2cm. What species of iris would this be? # We can put this data into a numpy array, again with the shape number of samples (one) times number of features (four). X_new = np.array([[5, 2.9, 1, 0.2]]) print("\nX_new.shape:\n", X_new.shape) # To make prediction we call the predict method of the knn object. prediction = knn.predict(X_new) print("\nPrediction:\n", prediction) print("\nPredicted target name:\n", iris_dataset['target_names'][prediction]) ######################################################################################### ## Evaluating the model # We can make a prediction for an iris in the test data, and compare it against its label (the known species). # We can measure how well the model works by computing the accuracy, # which is the fraction of flowers for which the right species was predicted. y_pred = knn.predict(X_test) print("\nIris test data set predictions:\n", y_pred) print("\nIris test data set predicted target name:\n", iris_dataset['target_names'][y_pred]) print("\nTest set score(using np.mean(y_pred == y_test)): {:.2f}\n".format(np.mean(y_pred == y_test))) # We can also use the score method of the knn object, which will compute the test set accuracy. print("\nTest set score(using knn.score(X_test, y_test)): {:.2f}\n".format(knn.score(X_test, y_test))) ########################################################################################## ## Summary # This snippet contains the core code for applying any machine learning algorithms using scikit-learn. # The fit, predict and score methods are the common interface to supervised models in scikit-learn. X2_train, X2_test, y2_train, y2_test = train_test_split( iris_dataset['data'], iris_dataset['target'], random_state=0) knn2 = KNeighborsClassifier(n_neighbors=1) knn2.fit(X2_train, y2_train) print("\nSummary - Test set score: {:.2f}\n".format(knn2.score(X2_test, y2_test)))
624ed7131931046800119d8e23316bebc34c16cc
sshillyer/cs325-projects
/project4/City.py
599
3.578125
4
# from Edge import * class City(object): def __init__(self, label, x, y): self.label = str(label) self.index = int(label) self.x = int(x) self.y = int(y) # self.adj = set() def __str__(self): ''' Override string method for easy printing of city information :return: ''' return str(self.label) + " " + str(self.x) + " " + str(self.y) def get_label(self): return self.label # def set_adjacent_city(self, adj_city): # ''' Untested code ''' # self.adj.add(Edge(self, adj_city))
31f0e7e8706c96b4cfec85332b5ed4ca517e9bc3
sshillyer/cs325-projects
/project4/TspGraphMatrix.py
1,175
3.5
4
import tsp_helper_functions class TspGraphMatrix(object): def __init__(self, vertices): self.V = vertices # Vertices (cities) self.v_count = n = len(vertices) # Number of vertices (cities) # Initialize and fill in the adjacency matrix # See stackoverflow.com/questions/6667201 for initialization line, rest is my logic self.AdjMatrix = [[-1 for x in range(n)] for y in range(n)] # go through every pair of vertices and calculate the distances, sotring in the AdjMatrix for vertex_u in vertices: for vertex_v in vertices: u = vertex_u.index v = vertex_v.index self.AdjMatrix[u][v] = tsp_helper_functions.euc_distance(vertex_u, vertex_v) def __str__(self): return "Graph has " + str(self.v_count) + " vertices" def print_matrix(self): x, y = 0, 0 for i in range(self.v_count): print (str(i) + '\t') for row in self.AdjMatrix: print(row) def get_distance_between_vertices(self, v, u): u = u.index v = v.index return self.AdjMatrix[u][v]
5bf7b52e8961a49b3667ae1731295ae1719a0900
aishtel/Prep
/solutions_to_recursive_problems/geometric_progression.py
655
4.34375
4
# Geometric progression using recursion # starting term = a = 1 # factor = r = a2/a1 # Find the nth term - 8th term # 1, 3, 9, 27, ... def geo_sequence(a, r, n): if r == 0 or r == 1: raise Exception("Sequence is not geometric") if n < 1: raise Exception("n should be >= 1") if a == 0: return 0 if n == 1: return a else: return r * geo_sequence(a, r, n-1) print "The geometric sequence is", geo_sequence(6, 2, 9) print "The geometric sequence is", geo_sequence(1, 3, 8) print "The geometric sequence is", geo_sequence(10, 3, 4) # print "The geometric sequence is",geo_sequence(2, 4, -1)
219c903dc87a29cd0c9b2fc8fa91ef7570f8a60e
aishtel/Prep
/solutions_to_recursive_problems/gcd_lcm.py
963
4
4
# Greatest common divisor and least common multiple in python using recursion # This can also be found by importing math function and using math.gcd and math.lcm def gcd(a, b): try: if b == 0: return a elif a == 0: return b else: return gcd(b, a % b) except TypeError: print "Cannot find greatest common divisor" def lcm(a, b): try: if b == 0: return b elif a == 0: return a else: return (a * b) / gcd(a, b) except TypeError: print "Cannot find least common multiple" print "The greatest common divisor is" print gcd(60, 48) print gcd(48, 60) print gcd(0, 0) print gcd(4, 4) print gcd("a", 7) print "*****************" print "The least common multiple is" print lcm(1, 56) print lcm(34, 1) print lcm(0, 22) print lcm(13, 0) print lcm(35, 5) print lcm(15, 20) print lcm(60, 48) print "*****************"
f5dab06d3a74c77757d299124fbe8bcabbfa3c07
aishtel/Prep
/solutions_to_recursive_problems/factorial_recursive.py
465
4.5
4
# Return the factorial of a given number using recursive method. # Example: # n = 6 # fact = 6*5*4*3*2*1 = 720 def factorial(n): if n < 0: raise Exception("n should be >= 0") elif n == 0: return 1 elif n == 1: return 1 else: return n * factorial(n - 1) print "The factorial is", factorial(4) print "The factorial is", factorial(0) print "The factorial is", factorial(1) # print "The factorial is", factorial(-4)
b5773b810b4844e9868ff5ab63ba156aad500f59
yayaysya/wxpython_learning
/xml_python/main.py
893
3.53125
4
#!/usr/bin/env python # coding=gbk ''' this is a python file about how to use xml in python pyhton prase the xml with the ElementTree Way ''' try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET def xml_prase(xml_file): tree = ET.ElementTree(file=xml_file) # xmlļ root = tree.getroot() print root.tag, root.attrib, root.text print len(root.tag), len(root.text), root.text for RootChrildren in root: print len(RootChrildren.tag), RootChrildren.tag, RootChrildren.attrib,\ len(RootChrildren.text) for RootChrildrenChrildren in RootChrildren: print RootChrildrenChrildren.tag,\ RootChrildrenChrildren.attrib,\ RootChrildrenChrildren.text def main(): xml_prase('bookstore.xml') if __name__ == '__main__': main()
d5d66badeefb003f0d8356f94586ed89d869fc5e
Andrew-Callan/linux_academy_python
/age
248
4.15625
4
#!/usr/bin/env python3.7 name = input("What is your name? ") birthdate = input("What is your birthday? ") age = int(input("How old are you? ")) print(f"{name} was born on {birthdate}") print(f"Half your age is {age/2}") print(f"Fuck you {name}")
fc5e925c08e8addecc17de1e671eba8ef9d8df3f
jonathanFielder/slither_into_python_exercises
/ch3_test.py
399
3.828125
4
#calculates total amount of rabbits over a specified time based on begining number of rabbits input by user while True: rabbits = int(input('enter num of rabbits:')) years = 4 months_in_year = 12 months_to_double = 3 x = years * months_in_year / months_to_double print(x) while x > 0: x = x - 1 rabbits = rabbits * 2 print(rabbits)
db1447bcef8c170aa18b59d1cda27f06e15762ed
jonathanFielder/slither_into_python_exercises
/decimal_rounder.py
174
3.609375
4
e = 2.7182818284590452353602874713527 while True: x = int(input('Enter how many decimals to display for e: ')) print('{:.{}f}'.format(e,x))
64b553e710743d6fb559d203e78448217345511a
jonathanFielder/slither_into_python_exercises
/slither_ch3.py
267
3.984375
4
x=7 y=5 z=x-y radius_of_earth=6371 pi=3.14 surface_area=4*pi*(radius_of_earth**2) print(surface_area) name = input('Enter your name:') print('hi ' + name) number = int(input('what number would you like squared ' + name + '?')) print(number ** 2)
090a887aad10757f23fc4bb57813a28c341b48fa
jonathanFielder/slither_into_python_exercises
/ch11_question4.py
344
3.796875
4
d1 = {"k1": True, "k2": True, "k3": True, "k4": True} d2 = {"k6": True, "k2": True, "k5": True, "k1": True, "k8": True, "k4": True} intersection = {} for i in d1: #print(i) if i in d2: #print('check') if d1[i] == d2[i]: #print('ok') intersection[i] = d1[i] print(intersection)
04aa5f70291ca7680c993b748b5ff45b2de58a17
jonathanFielder/slither_into_python_exercises
/arithmetic.py
904
4
4
def add(*a): result = 0 for arg in a: result += arg return(result) def subtract(*a): result = a[0] i = 1 if len(a) >= 2: while i < len(a): result = result - a[i] i += 1 else: result = -a[0] return(result) def multiply(*a): result = 1 for arg in a: result = result * arg return(result) def divide(*a): if len(a) == 2: result = a[0]/a[1] return(result) else: return('Must divide 2 numbers.') def main(): print('add example:', add(5,3,6,4,6)) print('subtract example:', subtract(5,3,6,4,6)) print('multiply example:', multiply(5,3,6,4,6)) print('divide example:', divide(5,3,6,4,6)) print('dividing only the first two numbers:', divide(5,3)) if __name__=='__main__': main()
f16732c11385a1746c3b47319f0adcb9a26d1880
jonathanFielder/slither_into_python_exercises
/ch15_question5.py
760
4.0625
4
import sys def file_set(): #open file and create word list split try: with open(sys.argv[1], 'r') as file: words = {word.strip() for word in file} return(words) except: with open('words_alpha.txt', 'r') as file: words = {word.strip() for word in file} return(words) def comp_list(words): #takes list and builds new list with only words greater than 18 for_rev = [x for x in words if x[::-1] in words] return(for_rev) def main(): reversables = comp_list(file_set()) print(reversables) print('Amount of words that also have backwards counterparts is:', len(reversables)) if __name__ == '__main__': main()
2b36e068233b1b3026fdea662d98b4219f4f354d
jaghen/python-test
/main.py
6,968
3.59375
4
# Prueba tecnica para el proceso de carga ETL de un archivo # Desarrollado por Sergio Silis import glob import pandas as pd from pandas.api.types import is_numeric_dtype from pandas.api.types import is_string_dtype from datetime import datetime from datetime import date import os import sqlite3 as sql # Funciones auxiliares def norm_data(df): num_cols = [cols for cols in df.columns if is_numeric_dtype(df[cols]) and len(df[cols].dropna())>0] iter_len_num = len(num_cols) string_cols = [cols for cols in df.columns if is_string_dtype(df[cols]) and len(df[cols].dropna())>0] iter_len_string = len(string_cols) df.dropna(how = 'all') #para campos numericos print('Normalizacion de campos numericos:') for x,col_name in enumerate(num_cols): #En campos numericos, reemplazar valores nulos por 0 df[col_name] = df[col_name].fillna(0) df[col_name] = pd.to_numeric(df[col_name]) df[col_name] = df[col_name].astype(int) print(x+1,' of ',iter_len_num,' completado ',col_name) #para campos de tipo string print('Normalizacion de campos de tipo cadena:') for x,col_name in enumerate(string_cols): #Eliminar espacios en blanco al inicio y al final para cadenas df[col_name] = df[col_name].str.strip() #Strings en MAYUSCULAS df[col_name] = df[col_name].str.upper() print(x+1,' of ',iter_len_string,' completado ',col_name) return df def calcula_edad(fecha_nac): fecha_nac = datetime.strptime(fecha_nac, "%Y-%m-%d").date() today = date.today() return today.year - fecha_nac.year - ((today.month, today.day) < (fecha_nac.month, fecha_nac.day)) #extract def extract(ruta): df_union=[] files = glob.glob(os.path.join(ruta, '*.txt')) for f in files: header = ['rut', 'dv', 'nombre', 'apellido', 'genero', 'fecha_nacimiento', 'fecha_vencimiento', 'deuda', 'direccion', 'ocupacion', 'altura', 'peso', #Clientes 'correo', 'estatus_contacto', 'telefono','prioridad' #Emails y Telefonos ] widths = [7,1,20,25,9,10,10,6,50,30,4,2, #Clientes 50,8,9,1 #Emails y Telefonos ] tipo_dato = {'rut': str, 'dv': str,'telefono': str} df = pd.read_fwf(f, names=header, header=None, widths=widths, dtype=tipo_dato) df_union.append(df) data = pd.concat(df_union,sort=False,ignore_index=True) return data #transform def transform(data): data = norm_data(data) data = data[['rut','dv','nombre','apellido', 'genero', 'fecha_nacimiento','fecha_vencimiento','deuda','direccion','ocupacion','correo','telefono','estatus_contacto','prioridad']] data['age'] = data['fecha_nacimiento'].apply(calcula_edad) data['age_group'] = pd.cut(x=data['age'], bins=[0,20, 30, 40, 50,60,200], labels=[1,2,3,4,5,6]) data['delinquency'] = (datetime.now() - pd.to_datetime(data['fecha_vencimiento'])).dt.days #Crear catalogo de clientes con el mayor numero de telefonos validos por ocupacion bco_cat = data.loc[data['estatus_contacto'] == 'VALIDO',['ocupacion','rut']].value_counts().reset_index().sort_values(['ocupacion', 0], ascending = (False, False)).drop_duplicates('ocupacion', keep='first') #Asignar el valor booleano para clientes tomando en cuenta el catalogo antes creado. data = data.assign(best_contact_ocupation=data.rut.isin(bco_cat.rut).astype(int)) del bco_cat data['fiscal_id'] = data.rut.astype(str) + data.dv.astype(str) ## Customer customers = data[['fiscal_id','nombre','apellido', 'genero','fecha_nacimiento','age', 'age_group','fecha_vencimiento','delinquency', 'deuda','direccion','ocupacion', 'best_contact_ocupation']].rename(columns = {'nombre': 'first_name', 'apellido': 'last_name', 'genero': 'gender', 'fecha_nacimiento': 'birth_date', 'fecha_vencimiento': 'due_date', 'deuda': 'due_balance', 'direccion': 'address', 'ocupacion': 'ocupation', }) # Emails emails = data[['fiscal_id','correo','estatus_contacto','prioridad']].rename(columns = {'correo': 'email', 'estatus_contacto': 'status', 'prioridad': 'priority', }) emails.dropna(subset=['email'],inplace = True) # Telefonos phones = data[['fiscal_id','telefono','estatus_contacto','prioridad']].rename(columns = {'telefono': 'phone', 'estatus_contacto': 'status', 'prioridad': 'priority', }) phones.dropna(subset=['phone'],inplace = True) del data return customers,emails,phones #load def load(customers,emails,phones): output_dir = 'output/' if not os.path.exists(output_dir): os.makedirs(output_dir) customers.to_excel(output_dir + 'customers.xlsx',index=False) emails.to_excel(output_dir + 'emails.xlsx',index=False) phones.to_excel(output_dir + 'phones.xlsx',index=False) conn = sql.connect('database.db3') customers.to_sql('customers', conn, if_exists='replace',index=False) emails.to_sql('emails', conn, if_exists='replace',index=False) phones.to_sql('phones', conn, if_exists='replace',index=False) conn.close() del customers del emails del phones if __name__ == "__main__": print('Por favor capture la ruta donde se encuentran los archivos a procesar:') ruta = input() print('Inicia lectura de archivo de entrada desde: ' + ruta) data = extract(ruta) print('Lectura de archivo concluida.\n') print('Inicia proceso de transformacion...') customers,emails,phones = transform(data) print('Proceso de transformacion concluido.\n') print('Inicia proceso de carga...') load(customers,emails,phones) print('Proceso de carga concluido.')
f1d5ec6176f52201257698fcbcc0aa69b1921f5e
kkhamutou/WikiBase_UW_Project
/gui/main_gui.py
3,565
4.03125
4
# main_gui.py python3 """ This module is design to run the GUI main application. The GUI is written in tkinter library. """ import tkinter as tk import tkinter.font as tkfont from gui.wiki_window import WikiMain from gui.game_window import GameMain from gui.stat_window import StatMain class Application(tk.Tk): """This class runs the GUI tkinter application.""" def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic") self.container = tk.Frame(self) self.container.pack(side="top", fill="both", expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) self.show_frame(StartPage) def show_frame(self, cls): """Show a frame for the given page name""" frame = cls(parent=self.container, controller=self) frame.grid(row=0, column=0, sticky="nsew") frame.tkraise() class StartPage(tk.Frame): """This is the menu page that redirects to thw following windows: 1. Wiki - wiki window that allows you to search, view, delete and add new words from WikiMedia 2. Start Game - open and initialize game 3. Statistics - show the game statistics 4. Quit - terminate the application """ def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label_start = tk.Label(self, text="Welcome to WikiBase!", font=controller.title_font) label_start.pack(side='top', fill='x', padx=15, pady=10) helv36 = tkfont.Font(family='Helvetica', size=12, weight='bold') btn_wiki = tk.Button(self, text="Wiki", command=lambda: controller.show_frame(WikiPage)) btn_wiki.configure(heigh=3, width=20, font=helv36) btn_game = tk.Button(self, text="Start Game", command=lambda: controller.show_frame(GamePage)) btn_game.configure(heigh=3, width=20, font=helv36) btn_stat = tk.Button(self, text="Statistic", command=lambda: controller.show_frame(StatPage)) btn_stat.configure(heigh=3, width=20, font=helv36) btn_quit = tk.Button(self, text="Exit", command=self.quit) btn_quit.configure(heigh=3, width=20, font=helv36) btn_wiki.pack(anchor=tk.CENTER, padx=10, pady=10) btn_game.pack(anchor=tk.CENTER, padx=10, pady=10) btn_stat.pack(anchor=tk.CENTER, padx=10, pady=10) btn_quit.pack(anchor=tk.CENTER, padx=10, pady=10) class WikiPage(WikiMain): """Initialize and open Wiki window.""" def __init__(self, parent, controller): WikiMain.__init__(self, parent) self.controller = controller self.btn_home['command'] = lambda: controller.show_frame(StartPage) class GamePage(GameMain): """Initialize and open Game window.""" def __init__(self, parent, controller): GameMain.__init__(self, parent) self.controller = controller self.btn_home['command'] = lambda: controller.show_frame(StartPage) if self.exit_game_window() is True else None class StatPage(StatMain): """Initialize and open Statistics window.""" def __init__(self, parent, controller): StatMain.__init__(self, parent) self.controller = controller self.btn_home['command'] = lambda: controller.show_frame(StartPage) if __name__ == '__main__': app = Application() app.geometry('600x600') app.title('WikiBase') app.mainloop()
880cd28be0e59af032da250f2605afa8e35c67b5
WannJJ/Maze-Generation-Python
/generate_maze.py
2,899
3.984375
4
# -*- coding: utf-8 -*- """ Created on Mon May 3 15:58:45 2021 @author: dell Maze generation Idea: use Prim's Algorithm http://weblog.jamisbuck.org/2011/1/10/maze-generation-prim-s-algorithm.html """ import random """ w, h are even """ def generate_board(w: int=9, h: int=9): assert w%2!=0 and h%2!=0 board = [[0 if i*j%2 != 0 else 1 for j in range(w) ] for i in range(h)] return board def count_zeros(board): count = 0 for row in board: count += row.count(0) return count def union(x, y): global parent x, y = find(x), find(y) if x == y: return x parent[y] = x def find(x): global parent, board root = x while True: p = parent[root] if p == root: break root = p current = x while current != root: next_elem = parent[current] parent[current] = root current = next_elem return root def generate_maze(w=9, h=9): global parent, board board = generate_board(w, h) parent = [i for i in range(w*h)] x = w+1 merged = [x] #number of 'nodes' in the 'spanning tree' N = count_zeros(board) while len(merged) < N: idx = random.randint(0, len(merged)-1) x = merged[idx] i, j = x//w, x%w direction = random.randint(0,3) if direction == 0 and i>1: y = (i-2)*w + j x_, y_ = find(x), find(y) if x_ != y_: board[i-1][j] = 0 merged.append(y) parent[y_] = x_ continue direction = random.randint(1,3) if direction == 1 and i+2 < h: y= (i+2)*w + j x_, y_ = find(x), find(y) if x_ != y_: board[i+1][j] = 0 merged.append(y) parent[y_] = x_ continue direction = random.randint(2,3) if direction == 2 and j > 1: y = i*w + j-2 x_, y_ = find(x), find(y) if x_ != y_: board[i][j-1] = 0 merged.append(y) parent[y_] = x_ continue direction = 3 if direction == 3 and j+2 < w: y= i*w + j+2 x_, y_ = find(x), find(y) if x_ != y_: board[i][j+1] = 0 merged.append(y) parent[y_] = x_ continue return board generate_maze(19, 11) #board = generate_board(5, 11) for i in range(len(board)): for j in range(len(board[0])): print(board[i][j], end=' ') print() #%%
7d808d9f82b601e1d26fd70fb91c2dcfb9b9c970
shivam-gh/dsa_using_python
/Searching algorithms/binary_search.py
613
3.984375
4
# binary search can be implemented only on sorted array/list # <----time complexity----> # best average worst # O(1) O(log n) O(log n) def binary(arr,beg,end,key): if beg<=end: mid=(beg+end)//2 if arr[mid]==key: return 1 elif arr[mid]>key: return binary(arr,beg,mid-1,key) else: return binary(arr,mid+1,end,key) else: return -1 if __name__=="__main__": n=int(input()) arr=list(map(int,input().split())) key=int(input()) if binary(arr,0,n-1,key)==1: print("YES") else: print("NO")
9d26d08fdd825e1b6644c1cb70bda6daeba0f33a
ToshimichiYamada/python_code_for_research
/robust_regressuion.py
1,958
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 19:17:08 2016 Robust nonlinear regression in scipy """ import numpy as np import matplotlib.pyplot as plt # Define data generator: def generate_data(t, A, sigma, omega, noise=0, n_outliers=0, random_state=0): y = A * np.exp(-sigma * t) * np.sin(omega * t) rnd = np.random.RandomState(random_state) error = noise * rnd.randn(t.size) outliers = rnd.randint(0, t.size, n_outliers) error[outliers] *= 35 return y + error # Define model parameters: A = 2 sigma = 0.1 omega = 0.1 * 2 * np.pi x_true = np.array([A, sigma, omega]) noise = 0.1 t_min = 0 t_max = 30 # Data for fitting the parameters will contain 3 outliers: t_train = np.linspace(t_min, t_max, 30) y_train = generate_data(t_train, A, sigma, omega, noise=noise, n_outliers=4) # Define the function computing residuals for least-squares minimization: def fun(x, t, y): return x[0] * np.exp(-x[1] * t) * np.sin(x[2] * t) - y # Use all ones as the initial estimate. x0 = np.ones(3) from scipy.optimize import least_squares # Run standard least squares: res_lsq = leastsq(fun, x0, args=(t_train, y_train)) # Run robust least squares with loss='soft_l1', set loss_scale to 0.1 which means that inlier residuals are approximately lower than 0.1. res_robust = leastsq(fun, x0, loss='soft_l1', loss_scale=0.1, args=(t_train, y_train)) # Define data to plot full curves. t_test = np.linspace(t_min, t_max, 300) y_test = generate_data(t_test, A, sigma, omega) # Compute predictions with found parameters: y_lsq = generate_data(t_test, *res_lsq.x) y_robust = generate_data(t_test, *res_robust.x) # plot plt.plot(t_train, y_train, 'o', label='data') plt.plot(t_test, y_test, label='true') plt.plot(t_test, y_lsq, label='lsq') plt.plot(t_test, y_robust, label='robust lsq') plt.xlabel('$t$') plt.ylabel('$y$') plt.legend() plt.show()
fdcea0d9ce3a4687a06f1ae43ee2a92d6b03a59f
vinaykumarlodari/Python
/Turtlerace.py
904
4.0625
4
import turtle # import the modules from random import randint # to make the random movement of turtles use ranindt() from random module wn = turtle.Screen() # Create a screen wn.bgcolor('cyan') t = turtle.Turtle() t.penup() t.goto(-70,100) t.pendown() for i in range(11): t.hideturtle() t.speed(100) t.write(i) t.right(90) t.forward(200) t.write(i) t.right(180) t.forward(200) t.right(90) t.penup() t.forward(20) t.pendown() lance = turtle.Turtle() # Create two turtles andy = turtle.Turtle() lance.color('red') andy.color('blue') lance.shape('turtle') andy.shape('turtle') andy.up() # Move the turtles to their starting point lance.up() andy.goto(-100,30) lance.goto(-100,0) for i in range(80): andy.forward(randint(1,5)) lance.forward(randint(1,5)) wn.exitonclick()
0a35c766c3abc007843fd3b54396023eaf37ca57
trishamrkt/csc326-assignment2
/q3.py
832
3.71875
4
def my_map(func, iterable): result_map = []; # Iterate through all the elements in iterable # Apply func to each element for elem in iterable: new_elem = func(elem) result_map.append(new_elem) return result_map def my_reduce(func, iterable): if len(iterable) == 1: return iterable[0] else: prev = iterable[0] for elem in iterable: if iterable.index(elem) != 0: new_val = func(prev, elem) prev = new_val return new_val; def my_filter(func, iterable): return [elem for elem in iterable if func(elem)] if __name__ == "__main__": print my_map(lambda x: x**2, range(10)) print my_reduce(lambda x,y: x*y, [1,2,3,4]) print my_filter(lambda x: x > 10, [2,1,64,7,2,3,43,13])
8edc09c1324db50aee3b81e4640546619607109b
faisalkhan91/RSA-Algorithm
/RSA.py
5,402
4.09375
4
#!/usr/bin/python3 ############################################################################################# # Program by Mohammed Faisal Khan # # Email: faisalkhan91@outlook.com # # Created on November 6, 2017 # ############################################################################################# # Importing modules import random # Function Definitions ''' Reference: https://linuxconfig.org/function-to-check-for-a-prime-number-with-python Function to validate if the number is prime ''' def check_prime(x): if x >= 2: for y in range(2, x): if not (x % y): return False else: return False return True ''' Euclid's algorithm for determining the greatest common divisor ''' def gcd(a, b): while b != 0: a, b = b, a % b return a ''' Euclid's extended algorithm for finding the multiplicative inverse of two numbers ''' def multiplicative_inverse(a, b): """ Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb """ # r = gcd(a,b) i = multiplicitive inverse of a mod b # or j = multiplicitive inverse of b mod a # Neg return values for i or j are made positive mod b or a respectively # Iterateive Version is faster and uses much less stack space x = 0 y = 1 lx = 1 ly = 0 oa = a # Remember original a/b to remove ob = b # negative values from return results while b != 0: q = a // b (a, b) = (b, a % b) (x, lx) = ((lx - (q * x)), x) (y, ly) = ((ly - (q * y)), y) if lx < 0: lx += ob # If neg wrap modulo orignal b if ly < 0: ly += oa # If neg wrap modulo orignal a # return a , lx, ly # Return only positive values return lx ''' Reference : https://stackoverflow.com/questions/40578553/fast-modular-exponentiation-help-me-find-the-mistake Fast modular exponentiation function ''' def get_mod_expo(base, exponent, modulus): result = 1 while exponent: exponent, d = exponent // 2, exponent % 2 if d: result = result * base % modulus base = base * base % modulus return result ''' Function to generate a public and private key pair ''' def generate_keypair(p, q): if not (check_prime(p) and check_prime(q)): raise ValueError('Both numbers must be prime.') elif p == q: raise ValueError('p and q cannot be equal!') # n = p * q n = p * q print("Value of n (where, n = p * q) is: ", n) # Phi is the totient of n phi = (p-1)*(q-1) print("Value of phi(n) (where, phi(n) = (p-1)*(q-1)) is: ", phi) # Choose an integer e such that e and phi(n) are co-prime # e = random.randrange(1, phi) print("Enter e such that is co-prime to ", phi, ": ") e = int(input()) # Use Euclid's Algorithm to verify that e and phi(n) are co-prime g = gcd(e, phi) if g != 1: print("The number you entered is not co-prime, Please enter e such that is co-prime to ", phi, ": ") e = int(input()) print("Value of e entered is: ", e) # Use Extended Euclid's Algorithm to generate the private key d = multiplicative_inverse(e, phi) print("Value of d is: ", d) # Return public and private key-pair # Public key is (e, n) and private key is (d, n) return (e, n), (d, n) ''' Function to Encrypt the message ''' def encrypt(public_key, to_encrypt): # Unpack the key into it's components key, n = public_key # To get the encrypted message using Fast Modular Exponentiation cipher = get_mod_expo(to_encrypt, key, n) # Return the array of bytes return cipher ''' Function to Decrypt the message ''' def decrypt(private_key, to_decrypt): # Unpack the key into its components key, n = private_key # To get the decrypted message using Fast Modular Exponentiation decrypted = get_mod_expo(to_decrypt, key, n) # Return the array of bytes as a string return decrypted ############################################################################################# # Main Program # RSA Encryption/Decryption Algorithm print("\n######## RSA Encryption/Decryption Algorithm #########\n") p = int(input("Enter a prime number (p: 7, 11, 23, etc): ")) q = int(input("Enter another prime number (q: 5, 13, 19, etc [Not same as above]): ")) print("Prime numbers entered, p: ", p, " and q: ", q) print("Generating Public/Private key-pairs!") public, private = generate_keypair(p, q) print("Your public key is ", public, " and your private key is ", private) message = int(input("Enter the message to be encrypted: ")) print("Message to be encrypted (M): ", message) encrypted_msg = encrypt(public, message) print("Encrypted message (C): ", encrypted_msg) decrypted_msg = decrypt(private, encrypted_msg) print("Message decrypted (M'): ", message) ############################################################################################# # End of Program # # Copyright (c) 2017 # #############################################################################################
63ed1d0fbf3fa9c775dd82e2e0b512e2fb86440d
jayshreevyas/programming-test
/program-4.py
213
3.671875
4
Problem-4: Get the total count of number list in the dictionary which is multiple of [1,2,3,4,5,6,7,8,9] sol: n=int(input("Input a number ")) d = dict() for x in range(1,n+1): d[x]=x*x print(d)
041d83dfbfac46f9a32967341dde6cd14833d269
sidhant-khamankar/Guessing-Game
/GuessingGame.py
1,366
3.78125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: from random import randint num=randint(1,100) guesses=[] count=1 print("Guessing Game \nGuess should be less than 1 or greater than 100 \nOn Your first turn, if guess is within 10 of the number, output WARM \nfarther than 10 away from the number, output COLD \nOn all subsequent turns, if a guess is closer to the number than the previous guess output 'WARMER' \nfarther from the number than the previous guess, output 'COLDER' \n") while True: guesses.append(int(input('Enter Guess: '))) if guesses[-1] in range(1,101): if num in guesses: print(f'Guessed in {count} guesses') break elif abs(guesses[0]-num)<10 and len(guesses)==1: a=abs(guesses[-1]-num) print('WARM') count+=1 continue elif abs(guesses[0]-num)>10 and len(guesses)==1: a=abs(guesses[-1]-num) print('COLD') count+=1 continue elif abs(guesses[-1]-num)<a: a=abs(guesses[-1]-num) print('WARMER') count+=1 continue elif abs(guesses[-1]-num)>a: a=abs(guesses[-1]-num) print('COLDER') count+=1 continue else: print('OUT OF BOUNDS') guesses.pop(-1) continue
1755a8601c2c67c1dfebe58f715ec25d5495932d
raphrueda/Python2Perl
/test01.py
121
3.828125
4
#!/bin/usr/python #Complex expressions in for loops a = 10 b = 20 for i in range(a/b*2, a/b*2 + b*b*b/a): print i
7c80f1c15b2ab31c0ca7018bc618ec2d5bf3403a
raphrueda/Python2Perl
/demo05.py
284
3.984375
4
#!/bin/usr/python #Prints the prime number up to the given number #Written by Raphael Rueda import sys print "enter a number" num = int(sys.stdin.readline()) if num > 2: print "2" for n in range(1, num+1): for x in range(2, n): if n % x == 0: break if x == n-1: print n
220af404ec0e6cb9f0ca0ad6403d266cf8e85f17
PushkarGarg02/HowToAutomateStuffRepo
/Practice/inventory_update.py
367
3.5625
4
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby'] inventory = {'gold coin': 38, 'dagger': 20} def addToInventory(inventory, addedItems): for newItem in dragonLoot: inventory.setdefault(newItem, 0) inventory[newItem] += 1 addToInventory(inventory,dragonLoot) for k,v in inventory.items(): print(str(v)+ ' ' +k)
e667936801cbfe626f5e21ffa9e87fa233842370
SweetyTugz/ReminderApplication
/alarm.py
472
3.515625
4
import winsound from win10toast import ToastNotifier def timer(reminder,seconds): notify=ToastNotifier() notify.show_toast("Reminder",f" ""Alarm will go off in (seconds) Seconds""",duration=10) notify.show_toast(f"Reminder",reminder,duration=10) frequency=2000 duration=1000 winsound.MessageBeep(frequency,duration) if __name__=="__main__": words=input("What would you remind of:") sec=int(input("Enter Seconds:")) timer(words,sec)
9bf6c7c21571ea0745e9e816b9aade5b0f1f305c
Amritpal-001/100-days-of-code
/EulerProject-solvedExamples/Problem 41.py
1,045
3.53125
4
#problem 41 import random n = [1,2,3,4,5,6,7,8,9] def randnumgeneratorXdigitNum(x): b = '' a = n[:x] for i in range(0,len(a)): random_num = random.choice(a) a.remove(random_num) b += str(random_num) print(b) #randnumgeneratorXdigitNum(4) x = 4 def factorial(x): a = 1 for i in range(1, x+1): a *= i #print(a) return(a) factorial(4) def randnumgeneratorXdigitNum(x): Allpossibilites = [] #while (len(Allpossibilites)) <= factorial(x): while (len(Allpossibilites)) <= (factorial(x) - 1): b = '' a = n[:x] for i in range(0,len(a)): random_num = random.choice(a) a.remove(random_num) b += str(random_num) #print(b) if b not in Allpossibilites: Allpossibilites.append(b) print(Allpossibilites) return(Allpossibilites) randnumgeneratorXdigitNum(8) ''' b = [] for i in range(1,8): a = randnumgeneratorXdigitNum(i+1) b += a print(len(b)) '''
2392e97ec210f3bc9e21cd0214ccaee564e682ae
Amritpal-001/100-days-of-code
/EulerBase/Euler_solutions/Getting primes .py
1,820
4.03125
4
def getPrimesBelowN(n=1000000): """Get all primes below n with the sieve of Eratosthenes. @return: a list 0..n with boolean values that indicate if i in 0..n is a prime. """ from math import ceil primes = [True] * n primes[0] = False primes[1] = False primeList = [] roundUp = lambda n, prime: int(ceil(float(n) / prime)) for currentPrime in range(2, n): if not primes[currentPrime]: continue primeList.append(currentPrime) for multiplicant in range(2, roundUp(n, currentPrime)): primes[multiplicant * currentPrime] = False return primes def isCircularPrime(primes, number): """Check if number is a circular prime. Keyword arguments: primes -- a list from 0..n with boolean values that indicate if i in 0..n is a prime number -- the integer you want to check """ number = str(number) for i in range(0, len(number)): rotatedNumber = number[i:len(number)] + number[0:i] if not primes[int(rotatedNumber)]: return False return True if __name__ == "__main__": print("Start sieving.") primes = getPrimesBelowN(1000000) print("End sieving.") numberOfPrimes = 2 print(2) # I print them now, because I want to skip all primes print(5) # that contain one of those digits: 0,2,4,5,6,8 for prime, isPrime in enumerate(primes): if (not isPrime) or ("2" in str(prime)) or \ ("4" in str(prime)) or ("6" in str(prime)) or \ ("8" in str(prime)) or ("0" in str(prime)) or \ ("5" in str(prime)): continue if isCircularPrime(primes, prime): print(prime) numberOfPrimes += 1 print("Number of circular primes: %i" % numberOfPrimes)
342b1c5a3e23bf4d3f698a88a9d2f87dffe9e9f4
Wyuchen/python_hardway
/16.py
1,036
4
4
#!/usr/bin/python #coding=utf-8 #笨办法学 Python-第十六题 #文件的相关操作 from sys import argv script,file_name=argv print 'the read of file name is %s' %file_name #打开一个文件 file=open(file_name,'rw+') print ''' 文件操作的命令: 1.close – 关闭文件。跟你编辑器的 文件->保存.. 一个意思。 2.read – 读取文件内容。你可以把结果赋给一个变量。 3.readline – 读取文本文件中的一行。 4.truncate – 清空文件,请小心使用该命令。 5.write(stuff) – 将 stuff 写入文件。 ''' #打印文件内容 print file.read() #由于文件在读取文件之后指针已经在文章的最后了,在清空文档是不成功的. #移动指针位置 file.seek(0,0) #清空文件内容 file.truncate() #对该文件进行写操作 file.write('line1\n') file.write('line2\n') file.write('line3\n') #返回文章当前位置 print file.tell() #读取文件内容 file.seek(0,0) #返回文章当前位置 print file.tell() print file.read() #关闭文件 file.close()
1c84b38bb37582851c05603793f51697860ac906
Wyuchen/python_hardway
/48.py
929
4.125
4
#/usr/bin/python #encoding=utf8 #笨方法学python-第四十八题 #目的:编辑出一个能够扫描出用户输入的字,并标注是那种类型的程序 #定义初始化的数据: Direction=['Direction','north','south','east','west'] Verb=['Verb','go','stop','kill','eat'] Adjective=['Adjective','the','in','of','from','at','it'] Noun=['Noun','door','bear','pricess','cabine'] print '用户可以输入的词有:' print Direction[1:-1] print Verb[1:-1] print Adjective[1:-1] print Noun[1:-1] #收集用户输入的命令 stuff=raw_input(">") #将用户的命令分割(按照空格符进行分割) words=stuff.split() #定义一个列表存放这些单词 scentence=[] #遍历用户给出的单词的意思: for word in words: for date in (Direction,Verb,Adjective,Noun): if word in date: scentence.append((date[0], word)) else: continue print "扫描结果:" print scentence
e5de3dc1d18e6f517f24b58851dd96d88b007999
Wyuchen/python_hardway
/29.py
484
4.28125
4
#!/usr/bin/python #coding=utf-8 #笨办法学 Python-第二十九题 #条件判断语句if people=20 cats=30 dogs=15 if people < cats: print 'too many cats!too little people' if people > cats: print 'too many people,too little cats' if people < dogs: print 'the world is drooled on' if people > dogs: print 'the world is dry' dogs+=5 if people >dogs: print 'people > dogs' if people <dogs: print 'people <dogs' if people == dogs: print 'people are dogs'
ec373f840dc1d23a69be556df07d3f4b4cc3bf9c
Wyuchen/python_hardway
/20.py
797
4.03125
4
#!/usr/bin/python #coding=utf-8 # 笨办法学 Python-第二十题 #函数和文件结合 from sys import argv script,file=argv #读取文件内容 def read(f): print f.read() #指针回到开头 def rewind(f): f.seek(0,0) #读取一行文件内容 def read_a_line(line_count,f): print line_count,f.readline() #关闭文件 def close(f): f.close() current_file=open(file) print 'read all file:' read(current_file) print '指针回到开头完成!' rewind(current_file) current_line=1 print '打印出一行的内容:' read_a_line(current_line,current_file) print '打印出二行的内容:' current_line+=1 read_a_line(current_line,current_file) print '打印出三行的内容:' current_line+=1 read_a_line(current_line,current_file) print '关闭文件' close(current_file)
3e7b21d4fc0b9776ec7990f6aff7e5ae7abe7d1c
dianeGH/working-on-python
/menu/main.py
1,100
4.53125
5
#Write a program that allows user to enter their favourite starter, main course, dessert and drink. Concatenate these and output a message which says – “Your favourite meal is .........with a glass of....” def function_1(): user_name = input("Hi there, what's your name? \n") #print ("Nice to meet you " + user_name + ". Let's find out some more about you.\n") starter = input("I'd like to take you out for dinner. \nLet's go to your favourite restaurant! \nWhat is your favourite starter?\n") main_meal = input("That's awesome, I love " + starter + " too!\nWhat is your favourite main meal?\n") dessert = input("Cool, well " + main_meal+ " isn't my favourite, but I still like it!, What would your favourite dessert be? \n") drink = input("Now a drink, I like a good Merlot, but I'm pretty easy going. What is your favourite drink?\n") print("Well, I think we're going to have a great time! You'll have " + starter + " to start, followed by " + main_meal + " and " + dessert + " to finish, with a glass or two of " + drink + ". Shall we say Friday night? \n Great I'll book the table!!" )
a832cb2734d37c5c81297b7d5ced47d5eb8c568a
dianeGH/working-on-python
/18112020-classwork/main.py
804
3.78125
4
import pandas as pd data = pd.read_csv("ign.csv") print(data.shape) # how may rows and columns print(data.head(3)) #prints the first (number) of rows () auto retireves 5 rows print(data.tail(4)) #prints the last (number) of rows as above for auto number print(data["platform"]) print(data["score"].mean()) # mean of the column print(data.mean()) #mean of all columns print(data["score"]/2) #divides each item in column print(data["score"]*10) print(data.describe()) #gives statistical data for the table #applies a boolean test against data in the column specified myfilter= data["score"]>8 print(myfilter) #selecting rows where the boolean test returns true highscore = data[myfilter] print(highscore.head()) #using multiple conditions to filter print(data[(data.score > 8) & (data.platform == "iPad")])
09b28c6215e30d68fe17becca9b4495559ccb9de
dianeGH/working-on-python
/depreciation/main.py
349
4.28125
4
#A motorbike costs £2000 and loses 10% of its value every year. Using a loop, print the value of the bike every following year until it falls below £1000. print("Today, Jim bought a motorbike for £2000.00") year = 1 cost = 2000 while cost >1000: print("At the end of year ",year,", Jim's bike is worth £", cost) year+=1 cost=cost*.9
977e03b90cb992afed1d1aa5cdba8c24f831a27e
binzecai/CS6476
/sift/harris.py
7,561
3.765625
4
import cv2 import numpy as np import matplotlib.pyplot as plt def get_interest_points(image, feature_width): """ Implement the Harris corner detector (See Szeliski 4.1.1) to start with. You can create additional interest point detector functions (e.g. MSER) for extra credit. If you're finding spurious interest point detections near the boundaries, it is safe to simply suppress the gradients / corners near the edges of the image. Useful in this function in order to (a) suppress boundary interest points (where a feature wouldn't fit entirely in the image, anyway) or (b) scale the image filters being used. Or you can ignore it. By default you do not need to make scale and orientation invariant local features. The lecture slides and textbook are a bit vague on how to do the non-maximum suppression once you've thresholded the cornerness score. You are free to experiment. For example, you could compute connected components and take the maximum value within each component. Alternatively, you could run a max() operator on each sliding window. You could use this to ensure that every interest point is at a local maximum of cornerness. Args: - image: A numpy array of shape (m,n,c), image may be grayscale of color (your choice) - feature_width: integer representing the local feature width in pixels. Returns: - x: A numpy array of shape (N,) containing x-coordinates of interest points - y: A numpy array of shape (N,) containing y-coordinates of interest points - confidences (optional): numpy nd-array of dim (N,) containing the strength of each interest point - scales (optional): A numpy array of shape (N,) containing the scale at each interest point - orientations (optional): A numpy array of shape (N,) containing the orientation at each interest point """ confidences, scales, orientations = None, None, None ############################################################################# # TODO: YOUR HARRIS CORNER DETECTOR CODE HERE # ############################################################################# n = 15000 limited_r = 1 local_maximum = 1 B = cv2.getGaussianKernel(ksize = 3, sigma = 0.5) image = cv2.filter2D(image, -1, B) image = cv2.filter2D(image, -1, B.T) x_gradient = np.array([[-1,0,1], [-1,0,1], [-1,0,1]]) y_gradient = x_gradient.T Ix = cv2.filter2D(image, -1, x_gradient) Iy = cv2.filter2D(image, -1, y_gradient) G = cv2.getGaussianKernel(ksize = 3, sigma = 1.6) G = np.dot(G, G.T) Ixx = cv2.filter2D(Ix**2, -1, G) Iyy = cv2.filter2D(Iy**2, -1, G) Ixy = cv2.filter2D(Ix*Iy, -1, G) # calculate the corner response. alpha: 0.04~0.06 alpha = 0.06 R = Ixx * Iyy - Ixy * Ixy - alpha * (Ixx + Iyy)**2 # response ############################################################################# # END OF YOUR CODE # ############################################################################# ############################################################################# # TODO: YOUR ADAPTIVE NON-MAXIMAL SUPPRESSION CODE HERE # # While most feature detectors simply look for local maxima in # # the interest function, this can lead to an uneven distribution # # of feature points across the image, e.g., points will be denser # # in regions of higher contrast. To mitigate this problem, Brown, # # Szeliski, and Winder (2005) only detect features that are both # # local maxima and whose response value is significantly (10%) # # greater than that of all of its neighbors within a radius r. The # # goal is to retain only those points that are a maximum in a # # neighborhood of radius r pixels. One way to do so is to sort all # # points by the response strength, from large to small response. # # The first entry in the list is the global maximum, which is not # # suppressed at any radius. Then, we can iterate through the list # # and compute the distance to each interest point ahead of it in # # the list (these are pixels with even greater response strength). # # The minimum of distances to a keypoint's stronger neighbors # # (multiplying these neighbors by >=1.1 to add robustness) is the # # radius within which the current point is a local maximum. We # # call this the suppression radius of this interest point, and we # # save these suppression radii. Finally, we sort the suppression # # radii from large to small, and return the n keypoints # # associated with the top n suppression radii, in this sorted # # orderself. Feel free to experiment with n, we used n=1500. # # # # See: # # https://www.microsoft.com/en-us/research/wp-content/uploads/2005/06/cvpr05.pdf # or # # https://www.cs.ucsb.edu/~holl/pubs/Gauglitz-2011-ICIP.pdf # ############################################################################# threshold = np.mean(R) R[R < threshold] = 0.0 ordered_R = np.sort(R.ravel())[::-1][:n] interest_points = [] x = [] y = [] # global_maximum idx = np.where(R == ordered_R[0]) interest_points.append([int(idx[1]), int(idx[0]), min(image.shape[0], image.shape[1])]) x.append(int(idx[1])) y.append(int(idx[0])) j = 1 for i in range(1, len(ordered_R)): idx = np.where(R == ordered_R[i]) if (np.size(idx,1) == 1): x.append(int(idx[1])) y.append(int(idx[0])) curr_x, curr_y = int(x[j]), int(y[j]) prev_x, prev_y = np.array(x[:j]), np.array(y[:j]) dis = np.sqrt((prev_x - curr_x)**2 + (prev_y - curr_y)**2) radii = int(np.amin(dis)) j += 1 R[curr_y, curr_x] = 0 if radii<limited_r or curr_x-radii<0 or curr_x+radii>image.shape[1] or curr_y-radii<0 or curr_y+radii>image.shape[0]: # reach the boundary continue elif ordered_R[i] > local_maximum*R[curr_y-radii:curr_y+radii, curr_x-radii:curr_x+radii].max(): # make sure curr_R is the maximum in the neighbor interest_points.append([curr_x, curr_y, radii]) interest_points = np.array(interest_points) interest_points = interest_points[interest_points[:,2].argsort()][::-1] interest_points = interest_points[0:2000] x = interest_points[:,0] y = interest_points[:,1] x = np.array(x) y = np.array(y) ############################################################################# # END OF YOUR CODE # ############################################################################# return x,y, confidences, scales, orientations
e9e5866348ea57eefce86a2ae22b23990c4bb6fc
andreas-anhaeuser/py_utils_igmk
/test/test_chronometer.py
3,754
3.515625
4
#!/usr/bin/python3 """Testing suite for chronometer.Chronometer.""" import unittest from time import sleep from misc.chronometer import Chronometer ################################################### # TESTING # ################################################### class ContextManager(unittest.TestCase): def test_in_context(self): N = 3 print('-----') print('Test context management') with Chronometer(N) as chrono: for n in range(N): print('Inside context, loop %i/%i' % (n+1, N)) chrono.loop_and_show() print('Outside context.') chrono.resumee() print('Outside context.') sleep(1) def test_exit_function(self): N = 3 print('-----') print('Test exit function') chrono = Chronometer(N) for n in range(N): print('Inside context, loop %i/%i' % (n+1, N)) chrono.loop() print('Inside context.') chrono.exit() print('Outside context.') sleep(1) def test_exit_via_resumee(self): N = 3 print('-----') print('Test exit function') chrono = Chronometer(N) for n in range(N): print('Inside context, loop %i/%i' % (n+1, N)) chrono.loop() print('Inside context.') chrono.resumee() print('Outside context.') sleep(1) class BasicFunctionality(unittest.TestCase): def setUp(self): pass def test_loop_and_show(self): N = 1000 header = 'Initialized with integer' chrono = Chronometer(N, header=header) for i in range(N): if i % 100 == 0: chrono.issue(i) sleep(0.005) chrono.loop_and_show() chrono.resumee() def test_init_with_iterable(self): N = 1000 items = '*' * N header = 'Initialized with Iterable' chrono = Chronometer(items, header=header) self.assertEqual(chrono.get_total_count(), N) for i in range(N): if i % 100 == 0: chrono.issue(i) sleep(0.005) chrono.loop_and_show() chrono.resumee() class Colors(unittest.TestCase): def setUp(self): self.N = 300 self.sleep_time = 0.005 self.chrono = Chronometer(self.N) def sleep(self): sleep(self.sleep_time) def test_color(self): chrono = self.chrono chrono.header = 'With colors' for i in range(self.N): if i % 100 == 0: chrono.issue(i) chrono.loop_and_show() self.sleep() chrono.resumee() def test_no_color(self): chrono = self.chrono chrono.header = 'Without colors' chrono.print_colors = False for i in range(self.N): if i % 100 == 0: chrono.issue(i) chrono.loop_and_show() self.sleep() chrono.resumee() class Wrap(unittest.TestCase): def setUp(self): self.N = 300 self.sleep_time = 0.005 self.chrono = Chronometer(self.N) def sleep(self): sleep(self.sleep_time) def test_wrap(self): chrono = self.chrono chrono.header = 'Text wrapping' for i in range(self.N): if i % 100 == 0: print( 'Long string' + '(should be wrapped according to screen width): ' + ('*' * 10 + ' ') * 25 ) chrono.loop_and_show() self.sleep() chrono.resumee() if __name__ == '__main__': unittest.main()
2ec1ad5a217e098c695451ed5588f574920d56c4
andreas-anhaeuser/py_utils_igmk
/datetime_intervals.py
43,190
3.75
4
#!/usr/bin/python """Implentations of time intervals, daytime periods and a seosons.""" import datetime as dt from collections import Iterable class Interval(object): """A time interval. Each bound may be inclusive or exclusive. Default is inclusive for lower bound and exclusive for upper bound. Intervals in reverse direction are not allowed. """ def __init__(self, start, end, start_inclusive=True, end_inclusive=False): """A time interval. Parameters ---------- start : datetime.datetime end : datetime.datetime must not be smaller than `start` start_inclusive : bool, optional Default: True end_inclusive : bool, optional Default: False `start` must not be larger than `end`. if `start` == `end`, the interval cannot be left-open and right-closed. """ <<<<<<< HEAD:datetime_intervals.py # convert Iterable -> datetime if isinstance(start, Iterable): start = dt.datetime(*start) if isinstance(end, Iterable): end = dt.datetime(*end) # convert date -> datetime if type(start) == dt.date: start = dt.datetime.combine(start, dt.time()) if type(end) == dt.date: end = dt.datetime.combine(end, dt.time()) ||||||| merged common ancestors def __init__(self, start, end, start_inclusive=True, end_inclusive=False): ======= >>>>>>> 414d5d43f8709fcbfc337667ff2a35f604a2523f:datetime_intervals.py # input check if not isinstance(start, dt.datetime): raise TypeError('`start` must be datetime.datetime.') if not isinstance(end, dt.datetime): raise TypeError('`end` must be datetime.datetime.') # Do not allow intervals in reverse direction if end < start: raise ValueError('Reverse intervals not implemented') elif end == start and end_inclusive and not start_inclusive: raise ValueError('Reverse intervals not implemented') self.start = start self.end = end self.start_inclusive = start_inclusive self.end_inclusive = end_inclusive def __eq__(self, other): """Return a bool.""" if not isinstance(other, Interval): return False if other.start != self.start: return False if other.end != self.end: return False if other.start_inclusive != self.start_inclusive: return False if other.end_inclusive != self.end_inclusive: return False return True def __lt__(self, other): """Return True if strictly before, False otherwise. Parameters ---------- other : Interval or datetime.datetime Returns ------- bool True if self is strictly before other, False otherwise. """ if isinstance(other, Interval): return self._completely_earlier(other) elif isinstance(other, dt.datetime): return self._ends_before(other) else: raise TypeError('Cannot compare to %s.' % other.__class__) def __gt__(self, other): """Return True if strictly after, False otherwise. Parameters ---------- other : Interval or datetime.datetime Returns ------- bool True if self is strictly after other, False otherwise. """ if isinstance(other, Interval): return other < self elif isinstance(other, dt.datetime): return self._starts_after(other) else: raise TypeError('Cannot compare to %s.' % other.__class__) def __str__(self): """Return a str.""" if self.start_inclusive: lower_par = '[' else: lower_par = '(' if self.end_inclusive: upper_par = ']' else: upper_par = ')' lower_bound = str(self.start) upper_bound = str(self.end) s = '%s%s, %s%s' % (lower_par, lower_bound, upper_bound, upper_par) return s def __repr__(self): """Return a str.""" return 'Interval %s' % str(self) def __contains__(self, other): """Return a bool or a list of such.""" if isinstance(other, Interval): return self._contains_interval(other) if isinstance(other, dt.datetime): return self._contains_datetime(other) if isinstance(other, DaytimePeriod): return self._contains_daytime_period(other) if isinstance(other, Season): return self._contains_season(other) raise TypeError('Cannot compare to %s' % type(other)) def contains(self, other): """Alias for backward compatibility.""" if isinstance(other, Iterable): return [self.contains(item) for item in other] return self.__contains__(other) def length(self): """Return a datetime.timedelta.""" return self.end - self.start def center(self): """Return the center of the interval as datetime.time.""" return self.start + 0.5 * self.length() def get_bounds(self): """Return a pair of datetime.datetime.""" return (self.start, self.end) def overlaps(self, other): """Return True if intervals overlap, False otherwise.""" if not isinstance(other, Interval): raise TypeError('other must be Interval.') if self < other: return False if self > other: return False return True <<<<<<< HEAD:datetime_intervals.py def is_continued_by(self, other): """Return True if other is a seamless continuation of self. Returns True if and only if both these are True: - `other` starts exactly where `self` ends - the upper bound of `self` or the lower bound of `other` or both are inclusive Parameters ---------- other : Interval Returns ------- bool """ if self.end != other.start: return False if self.end_inclusive: return True if other.start_inclusive: return True return False def is_addable_to(self, other): """Return True if the intervals overlap or touch, False otherwise.""" if not isinstance(other, Interval): raise TypeError('other must be Interval.') if self.overlaps(other): return True if self.is_continued_by(other): return True if other.is_continued_by(self): return True return False def is_subtractable(self, other): """Return True if the intervals are subtractable, False, otherwise.""" if self._overhangs_left(other): return True if other._overhangs_left(self): return True return False def intersect(self, other): """Return the intersection interval. The intersect exists if the intervals overlap. """ if not isinstance(other, Interval): raise TypeError('other must be Interval.') if not self.overlaps(other): message = 'Intervals do not overlap: %s, %s' % (self, other) raise ValueError(message) # start if self.start == other.start: start = self.start start_inclusive = self.start_inclusive and other.start_inclusive elif self.start > other.start: start = self.start start_inclusive = self.start_inclusive else: start = other.start start_inclusive = other.start_inclusive # end if self.end == other.end: end = self.end end_inclusive = self.end_inclusive and other.end_inclusive elif self.end < other.end: end = self.end end_inclusive = self.end_inclusive else: end = other.end end_inclusive = other.end_inclusive return Interval( start=start, end=end, start_inclusive=start_inclusive, end_inclusive=end_inclusive, ) def add(self, other): """Return the union interval.""" if not isinstance(other, Interval): raise TypeError('other must be Interval.') if not self.is_addable_to(other): raise ValueError('Intervals not unitable: %s, %s' % (self, other)) # start if self.start == other.start: start = self.start start_inclusive = self.start_inclusive or other.start_inclusive elif self.start < other.start: start = self.start start_inclusive = self.start_inclusive else: start = other.start start_inclusive = other.start_inclusive # end if self.end == other.end: end = self.end end_inclusive = self.end_inclusive or other.end_inclusive elif self.end > other.end: end = self.end end_inclusive = self.end_inclusive else: end = other.end end_inclusive = other.end_inclusive return Interval( start=start, end=end, start_inclusive=start_inclusive, end_inclusive=end_inclusive, ) def subtract(self, other): """Return the difference interval.""" if not isinstance(other, Interval): raise TypeError('other must be Interval.') if not self.overlaps(other): raise ValueError( 'Intervals do not overlap: %s, %s' % (self, other) ) if other._overhangs_left(self): return other.subtract(self) if not self._overhangs_left(other): raise ValueError('Result would not be and Interval.') # when this line is reached, self overhangs other on the left start = self.start start_inclusive = self.start_inclusive end = other.start end_inclusive = not other.start_inclusive return Interval(start, end, start_inclusive, end_inclusive) ||||||| merged common ancestors ======= def is_continued_by(self, other): """Return True if other is a seamless continuation of self. Returns True if and only if both these are True: - `other` starts exactly where `self` ends - the upper bound of `self` or the lower bound of `other` or both are inclusive Parameters ---------- other : Interval Returns ------- bool """ if self.end != other.start: return False if self.end_inclusive: return True if other.start_inclusive: return True return False def is_addable_to(self, other): """Return True if the intervals overlap or touch, False otherwise.""" if not isinstance(other, Interval): raise TypeError('other must be Interval.') if self.overlaps(other): return True if self.is_continued_by(other): return True if other.is_continued_by(self): return True return False def is_subtractable(self, other): """Return True if the intervals are subtractable, False, otherwise.""" if self._overhangs_left(other): return True if other._overhangs_left(self): return True return False def intersect(self, other): """Return the intersection interval. The intersect exists if the intervals overlap. """ if not isinstance(other, Interval): raise TypeError('other must be Interval.') if not self.overlaps(other): message = 'Intervals do not overlap: %s, %s' % (self, other) raise ValueError(message) # start if self.start == other.start: start = self.start start_inclusive = self.start_inclusive and other.start_inclusive elif self.start > other.start: start = self.start start_inclusive = self.start_inclusive else: start = other.start start_inclusive = other.start_inclusive # end if self.end == other.end: end = self.end end_inclusive = self.end_inclusive and other.end_inclusive elif self.end < other.end: end = self.end end_inclusive = self.end_inclusive else: end = other.end end_inclusive = other.end_inclusive return Interval( start=start, end=end, start_inclusive=start_inclusive, end_inclusive=end_inclusive, ) def add(self, other): """Return the union interval.""" if not isinstance(other, Interval): raise TypeError('other must be Interval.') if not self.is_addable_to(other): raise ValueError('Intervals not unitable: %s, %s' % (self, other)) # start if self.start == other.start: start = self.start start_inclusive = self.start_inclusive or other.start_inclusive elif self.start < other.start: start = self.start start_inclusive = self.start_inclusive else: start = other.start start_inclusive = other.start_inclusive # end if self.end == other.end: end = self.end end_inclusive = self.end_inclusive or other.end_inclusive elif self.end > other.end: end = self.end end_inclusive = self.end_inclusive else: end = other.end end_inclusive = other.end_inclusive return Interval( start=start, end=end, start_inclusive=start_inclusive, end_inclusive=end_inclusive, ) def subtract(self, other): """Return the difference interval.""" if not isinstance(other, Interval): raise TypeError('other must be Interval.') if not self.overlaps(other): raise ValueError( 'Intervals do not overlap: %s, %s' % (self, other) ) if other._overhangs_left(self): return other.subtract(self) if not self._overhangs_left(other): raise ValueError('Result would not be and Interval.') start = self.start start_inclusive = self.start_inclusive start = other.start end_inclusive = not other.start_inclusive return Interval(start, end, start_inclusive, end_inclusive) >>>>>>> 414d5d43f8709fcbfc337667ff2a35f604a2523f:datetime_intervals.py ############################################################ # helpers # ############################################################ def _overhangs_left(self, other): """Return True if `self` overhangs to the left of `other`.""" if not isinstance(other, Interval): raise TypeError('other must be Interval.') if self == other: return False # start if self.start > other.start: return False if self.start == other.start: if (not self.start_inclusive) and other.start_inclusive: return False # end if self.end > other.end: return False if self.end == other.end: if self.end_inclusive and not other.end_inclusive: return False return True def _contains_interval(self, other): """Return a bool.""" if self.start_inclusive or (not other.start_inclusive): lower_cond = self.start <= other.start else: lower_cond = self.start < other.start if self.end_inclusive or (not other.end_inclusive): upper_cond = other.end <= self.end else: upper_cond = other.end < self.end return (lower_cond and upper_cond) def _contains_datetime(self, time): """Return a bool. Check whether `time` is in the interval. Parameters ---------- time : datetime.datetime Returns ------- bool """ if self.start_inclusive: lower_cond = self.start <= time else: lower_cond = self.start < time if self.end_inclusive: upper_cond = time <= self.end else: upper_cond = time < self.end return (lower_cond and upper_cond) def _contains_daytime_period(self, period): """Return a bool.""" if self.length() >= dt.timedelta(days=1): return True speriod = DaytimePeriod.from_interval(self) return speriod.__contains__(period) def _contains_season(self, season): """Return a bool.""" length = self.length() if length >= dt.timedelta(days=366): return True elif length > dt.timedelta(days=365): raise NotImplementedError('Not straightforward due to leap years.') s = Season.from_interval(self) return s.__contains__(season) def _ends_before(self, time): """Return a bool. Parameters ---------- time : datetime.datetime Returns ------- bool True if `self` ends before `time`, False otherwise. """ if not isinstance(time, dt.datetime): raise TypeError('time must be datetime.datetime.') if self.end_inclusive: return self.end < time else: return self.end <= time def _starts_after(self, time): """Return a bool. Parameters ---------- time : datetime.datetime Returns ------- bool True if `self` start after `time`, False otherwise. """ if not isinstance(time, dt.datetime): raise TypeError('time must be datetime.datetime.') if self.start_inclusive: return self.start > time else: return self.start >= time def _completely_earlier(self, other): """Return a bool.""" if self.end_inclusive and other.start_inclusive: return self.end < other.start else: return self.end <= other.start class DaytimePeriod(object): """A portion of the day cycle. This type is unaware of its absolute (calendar) date. It can extend beyond midnight, e. g. 23:00 to 01:00. Examples -------- >>> import datetime as dt >>> lon = 6.9 >>> lat = 50.9 >>> now = dt.datetime.now() >>> SR, SS = utc_sunrise_sunset(now, lon, lat) >>> day_period = DaytimePeriod(SR, SS) >>> if day_period.contains(now): >>> print 'It is day.' >>> else: >>> print 'It is night' # absolute dates do not matter: >>> SR_new = SR + dt.timedelta(days=100) >>> SS_new = SS + dt.timedelta(day=-2) >>> day_period = DaytimePeriod(SR_new, SS_new) >>> if day_period.contains(now): >>> print 'It is day.' >>> else: >>> print 'It is night' """ def __init__(self, dt_start=None, dt_end=None, allow_whole_day=True): """dt_start and dt_end must be dt.datetime or dt.time objects. The absolute calendar dates of the input arguments are ignored. This means that calling this function with dt_start 1st Jan 1970 23:00 and dt_end 30th Mar 1970 01:00 is equivalent to calling it with dt_start 1st Jan 2014 23:00 and dt_end 30th Mar 1789 01:00. Both will result in a time period between 23:00 and 01:00. Boundaries: The lower end dt_start is inclusive, the upper end dt_end is exclusive. Parameters ---------- dt_start : dt.datetime or dt.time, optional default: midnight dt_end : dt.datetime or dt.time, optional default: midnight allow_whole_day : bool, optional applies only if start and end are equal (or equivalent) see Note below. Default: True. Note ---- In case, dt_start == dt_end * if allow_whole_day is True, the time period will contain the whole day. * if allow_whole_day is False, the time period will not contain anything. In all other cases allow_whole_day is ignored. """ # default ------------------------------------ if dt_start is None: dt_start = dt.datetime(1, 1, 1) if dt_end is None: dt_end = dt.datetime(1, 1, 1) # input check -------------------------------- for d in (dt_start, dt_end): if not isinstance(d, (dt.time, dt.datetime)): raise TypeError( 'dt_start and dt_end must be instances of ' + 'datetime. datetime or datetime.time.' ) if not isinstance(allow_whole_day, bool): raise TypeError('allow_whole_day must be a boolean.') # convert to dt.datetime # -------------------------------------------- if isinstance(dt_start, dt.time): start = dt.datetime.combine(dt.date(1, 1, 1), dt_start) else: start = dt_start if isinstance(dt_end, dt.time): end = dt.datetime.combine(dt.date(1, 1, 1), dt_end) else: end = dt_end # shift to year 1 # -------------------------------------------- # self.start will be on Jan 1st 0001 CE. # self.end will be between 0 and 1 day later than self.end, all will # thus be on Jan 1st or Jan 2nd in year 0001 CE. start = start.replace(1, 1, 1) end = end.replace(1, 1, 1) # check sequence # -------------------------------------------- # make sure that end is not earlier that start: if end < start: end = end.replace(day=2) if end == start and allow_whole_day: end = end.replace(day=2) # create fields ------------------------------ self.start = start self.end = end @classmethod def from_interval(cls, interval, allow_whole_day=None): """Construct a Season from an Interval. interval : Interval allow_whole_day : bool or None if None, True is assumed for intervals of finite length """ if not isinstance(interval, Interval): raise TypeError('Expected Interval, got %s' % interval.__class__) if allow_whole_day is None: allow_whole_day = interval.length() != 0 bounds = interval.get_bounds() return cls(*bounds, allow_whole_day=allow_whole_day) def __repr__(self): """Return a str.""" return 'DaytimePeriod ' + str(self) def __str__(self): """Return a str.""" s = self.start.time() e = self.end.time() if s != e: return '[%s, %s)' % (s, e) if self.start == self.end: return '(empty)' return '(full day)' def __contains__(self, other): """Return a bool or a list of such.""" if isinstance(other, dt.time): return self._contains_time(other) if isinstance(other, dt.datetime): return self._contains_time(other) if isinstance(other, DaytimePeriod): return self._contains_daytime_period(other) if isinstance(other, Interval): return self._contains_interval(other) raise TypeError('Cannot compare to %s' % other.__class__) def __eq__(self, other): """return a bool.""" if not isinstance(other, DaytimePeriod): return False if other.start != self.start: return False if other.end != self.end: return False return True def contains(self, other): """Alias for backward compatibility.""" return self.__contains__(other) def is_full_day(self): """Return a bool.""" return self.length() == dt.timedelta(days=1) def length(self): """Return an instance of datetime.timedelta.""" return self.end - self.start def overlaps(self, other): """Return a bool.""" if not isinstance(other, DaytimePeriod): raise TypeError( 'Expected DaytimePeriod, got %s' % other.__class__ ) if self.start in other: return True if self.end in other: return True if other.start in self: return True if other.end in self: return True return False ############################################################ # helpers # ############################################################ def _contains_daytime_period(self, other): """Return a bool.""" if self.start > other.start: return False if self.end < other.end: return False return True def _contains_interval(self, interval): """Return a bool.""" if interval.length() > self.length(): return False if interval.end_inclusive and interval.end == self.end: return False period = DaytimePeriod.from_interval(interval) return self.__contains__(period) def _contains_time(self, d): """Check whether d is within DaytimePeriod or not. Parameters ---------- d : dt.datetime or dt.time or Iterable of such Returns ------- bool or list of such """ #################################### # CONVERT TO dt.datetime # #################################### if d.__class__ is dt.time: dd = dt.datetime.combine(dt.date(1, 1, 1), d) else: dd = d.replace(1, 1, 1) #################################### # CHECK RELATIVE POSITIONS # #################################### # make sure that dd is later than self.start: if dd < self.start: dd = dd.replace(day=2) # check whether dd is earlier than self.end: if dd < self.end: return True return False class Season(object): """A section of the year cycle. This type is unaware of its absolute year number. It can extend beyond New Year, e. g. Nov 2nd to Jan 10th. Examples -------- >>> import datetime as dt >>> lon = 6.9 >>> lat = 50.9 >>> now = dt.datetime.now() >>> beg = dt.datetime(1, 6, 21) >>> end = dt.datetime(1, 9, 23) # instantiate with beg and end: >>> season = Season(beg, end) >>> if season.contains(now): >>> print 'It is summer!' >>> else: >>> print 'It is not summer.' # alternatively, instantiate with months: >>> season = Season(months='DJF') >>> if season.contains(now): >>> print 'It is meteorological winter.' >>> else: >>> print 'It is not meteorological winter' # show length of season: >>> print season.length() # special case: beg == end >>> season = Season(beg, beg) >>> print season.length() 365 days, 0:00:00 >>> season = Season(beg, beg, allow_whole_year=False) >>> print season.length() 0:00:00 # the function is unaware of the absolute year, so pay attention in # leap years! >>> beg = dt.datetime(2016, 2, 1) >>> end = dt.datetime(2016, 3, 1) >>> season = Season(beg, end) >>> print season.length() 28 days, 0:00:00 # the function is microsecond-precise: >>> beg = dt.datetime(1, 6, 1) >>> end = dt.datetime(1, 6, 30, 12) >>> instant1 = end - dt.timedelta(microseconds=2) >>> instant2 = end + dt.timedelta(microseconds=2) >>> season = Season(beg, end) >>> print season.contains(instant1) True >>> print season.contains(instant2) False """ def __init__( self, dt_start=dt.datetime(1, 1, 1), dt_end=dt.datetime(1, 1, 1), months='', allow_whole_year=True, ): """dt_start and dt_end must be dt.datetime or dt.date objects. The absolute year numbers of the input arguments are ignored. This means that calling this function with dt_start 1st Jan 1970 and dt_end 30th Mar 1970 is equivalent to calling it with dt_start 1st Jan 2014 and dt_end 30th Mar 1789. Parameters ---------- dt_start : dt.datetime, optional lower boundary, inclusive dt_end : dt.datetime, optional upper boundary, exclusive months : str, optional This overrides `dt_start` and `dt_end`. Valid values are: 1. three-char abbreviation of one month, such as {'jan', 'feb', ...} or 2. sequence of chars of consecutive month initials, such as {'djf', 'mam', ...}, but also {'fm', 'jjaso', ...} (first and last months are inclusive) or 3. 'year' for the whole year or 4. '' to disable and use `dt_start` and `dt_end` instead (default) `months` is not case-sensitive allow_whole_year : bool, optional only applies if `dt_start` and `dt_end` are identical and, in this case, determines whether Season contains the whole year or nothing. Special cases ------------- 1. dt_start == dt_end * if allow_whole_year : Season contains the whole year. * else : Season does not contain anything. 2. February 29th If the date of dt_start and/or dt_end is Feb 29th, they are treated as Mar 1st 00:00. """ ################################################### # INPUT CHECK # ################################################### for d in (dt_start, dt_end): assert isinstance(d, dt.date) assert isinstance(allow_whole_year, bool) # months: if months.lower() == 'year': mon = 'jfmamjjasond' else: mon = months.lower() allowed_month_seqs = 'jfmamjjasondjfmamjjasond' allowed_months = ( 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', ) if not isinstance(mon, str): raise TypeError('months must be str.') if len(mon) == 1: msg = 'months must be a str of at least two month initial letters.' raise ValueError(msg) if len(mon) > 12: raise ValueError('months must not contain more than 12 letters.') if mon not in allowed_months: if mon[:3].lower() not in allowed_month_seqs: msg = 'Not a sequence of month initial letters: %s' % mon raise ValueError(msg) ################################################### # INITIALIZE # ################################################### # self.start will be in year 1 # self.end will be between 0 and 1 year later than self.end, and will # thus be in year 1 or 2 if mon == '': start = year_one(dt_start) end = year_one(dt_end) elif mon in allowed_month_seqs: first_month = allowed_month_seqs.find(mon) + 1 last_month = (first_month + len(mon)) % 12 if last_month == 0: last_month = 12 start = dt.datetime(1, first_month, 1) end = dt.datetime(1, last_month, 1) elif mon[:3].lower() in allowed_months: first_month = allowed_months.index(mon) + 1 last_month = (first_month + 1) % 12 if last_month == 0: last_month = 12 start = dt.datetime(1, first_month, 1) end = dt.datetime(1, last_month, 1) # make sure that end is not earlier than start: if end < start: end = end.replace(year=2) if end == start and allow_whole_year: end = end.replace(year=2) self.start = start self.end = end @classmethod def from_interval(cls, interval, allow_whole_year=True): """Construct a Season from an Interval.""" bounds = interval.get_bounds() return cls(*bounds, allow_whole_year=allow_whole_year) <<<<<<< HEAD:datetime_intervals.py @classmethod def from_tuple(cls, beg, end, allow_whole_year=True): """Shorthand constructer using datetime args as tuples. beg : tuple, length >= 2 interpreted as month, day, [hour, minute, second, microsecond] end : tuple, length >= 2 interpreted as month, day, [hour, minute, second, microsecond] allow_whole_day : bool or None if None, True is assumed for intervals of finite length """ dt_beg = dt.datetime(1, *beg) dt_end = dt.datetime(1, *end) return cls(dt_beg, dt_end, allow_whole_year=allow_whole_year) ||||||| merged common ancestors ======= @classmethod def from_tuple(cls, beg, end, allow_whole_year=True): """Shorthand constructer using datetime args as tuples. beg : tuple, length >= 2 interpreted as month, day, [hour, minute, second, microsecond] end : tuple, length >= 2 interpreted as month, day, [hour, minute, second, microsecond] allow_whole_day : bool or None if None, True is assumed for intervals of finite length """ dt_beg = dt.datetime(1, *beg) dt_end = dt.datetime(1, *end) return cls(dt_beg, dt_end, allow_whole_year=allow_whole_year) >>>>>>> 414d5d43f8709fcbfc337667ff2a35f604a2523f:datetime_intervals.py def __repr__(self): """Return a str.""" return 'Season ' + str(self) def __str__(self): """Return a str.""" s = self.start.replace(year=1900) e = self.end.replace(year=1900) fmt = '%d %b' add = '' if s.hour != 0 or e.hour != 0: add = ' %H:%M' if s.second != 0 or e.second != 0: add = ' %H:%M:%S' if s.microsecond != 0 or e.microsecond != 0: add = ' %H:%M:%S.%f' fmt = fmt + add beg_str = s.strftime(fmt) end_str = e.strftime(fmt) if s != e: text = '[%s, %s)' % (beg_str, end_str) elif self.start == self.end: text = '(empty)' else: text = '(full year)' return text def __eq__(self, other): """return a bool.""" if not isinstance(other, Season): return False if other.start != self.start: return False if other.end != self.end: return False return True def __contains__(self, other): """Return a bool or a list of such.""" if isinstance(other, Season): return self._contains_season(other) if isinstance(other, Interval): return self._contains_interval(other) if isinstance(other, dt.date): return self._contains_datetime(other) raise TypeError('Cannot compare to %s' % other.__class__) def contains(self, other): """Alias for backward compatibility.""" return self.__contains__(other) def months(self): """Return a string in the form of 'JJA' of 'Jun'. A month is considered to be 'covered' if at least 15 of its days are within the season. If the season covers more than one month, a sequence of capitals, such as 'JJA' (June-August) or 'NDJFMA' (November-April) is returned. If the season covers one month, than the first three characters of its name are returned. If the season covers less than 15 days in any month, '' is returned. """ raise NotImplementedError('') def length(self): """Return an instance of datetime.timedelta.""" return self.end - self.start ############################################################ # helpers # ############################################################ def _contains_season(self, other): """Return a bool.""" if self.start > other.start: return False if self.end < other.end: return False return True def _contains_interval(self, interval): """Return a bool.""" if interval.length() > self.length(): return False if interval.end_inclusive and interval.end == self.end: return False season = Season.from_interval(interval) return self.__contains__(season) def _contains_datetime(self, time): """Check whether time is within Season or not. Parameters ---------- time : dt.datetime or dt.date or Iterable of such Returns ------- bool or list of such """ ################################################### # INPUT CHECK # ################################################### if not isinstance(time, dt.date): raise TypeError( 'Argument must be datetime.datetime or datetime.date.' ) # make time_yo be after self.start time_yo = year_one(time) if time_yo < self.start: time_yo = time_yo.replace(year=2) # check whether time_yo is earlier than self.end: if time_yo < self.end: return True else: return False ################################################################ # helper functions # ################################################################ def year_one(d): """Return a datetime.datetime in year 1 CE. This is designed as a helper function for the Season class. Parameters ---------- d : an instance of datetime.datetime or datetime.date Returns ------- A datetime.datetime object. Date and time is be the same as of the input object, only the year is set to 1. Note ---- Dates on 29th Feb will are converted to 1st Mar 00:00. Tested ------ Intensively. Bug-free. """ # input check if not isinstance(d, dt.date): raise TypeError('Expected dt.date or dt.datetime, got %s' % type(d)) # Feb 29th if d.month == 2 and d.day == 29: return dt.datetime(1, 3, 1) # dt.datetime if isinstance(d, dt.datetime): return d.replace(year=1) # dt.date return dt.datetime.combine(d.replace(year=1), dt.time()) def daytimediff(minuend, subtrahend, mode=None): """Return the difference in daytime regardless of the absolute date. Parameters ---------- minuend, subtrahend : datetime.datime or datetime.time Returns ------- datetime.timedelta mode: (None, 'abs', 'pos', 'neg') * None: a value between -12h and + 12h is returned * 'abs': a value between 0 and 12h is returned. The absolute difference * 'pos': a value between 0 and 24h is returned. * 'neg': a value between -24h and 0 is returned. Example ------- >>> minuend = datetime.datetime(2015, 1, 1, 12, 0, 0) >>> subtrahend = datetime.datetime(1970,12,16, 8, 0, 0) >>> diff = daytimediff(minuend, subtrahend) >>> print(repr(diff)) datetime.timedelta(0, 14400) >>> print diff 4:00:00 Reliability ----------- Moderately tested. """ ################################### # RECURSIVELY CALL FUNCTION # ################################### if isinstance(minuend, list): return [daytimediff(m, subtrahend) for m in minuend] if isinstance(subtrahend, list): return [daytimediff(minuend, s) for s in subtrahend] ################################### # INPUT CHECK # ################################### for d in (minuend, subtrahend): if not isinstance(d, (dt.time, dt.datetime)): raise TypeError( 'Arguments must be datetime.datime or datetime.time.' ) if isinstance(minuend, dt.datetime): m = minuend.replace(1, 1, 1) else: hour = minuend.hour minute = minuend.minute second = minuend.second microsec = minuend.microsecond m = dt.datetime(1, 1, 1, hour, minute, second, microsec) if isinstance(subtrahend, dt.datetime): s = subtrahend.replace(1, 1, 1) else: hour = subtrahend.hour minute = subtrahend.minute second = subtrahend.second microsec = subtrahend.microsecond s = dt.datetime(1, 1, 1, hour, minute, second, microsec) diff = m - s if mode is None: while diff.total_seconds() > 86400/2: diff -= dt.timedelta(days=1) while diff.total_seconds() < -86400/2: diff += dt.timedelta(days=1) if mode == 'abs': diff = abs(diff, -diff) if mode == 'pos': while diff.total_seconds() < 0: diff += dt.timedelta(days=1) if mode == 'neg': while diff.total_seconds() > 0: diff -= dt.timedelta(days=1) return diff
2d2f09051efb89e1616e745a7e8beb433a9fca9d
MoisanuStefan/PyBackgammon
/dice.py
1,226
4
4
import random import arcade class Dice: """ Dice is used to mimic a dice that generates random rolls from 1 to 6 ... Attributes ---------- faces(): List List containing the textures for dice faces roll() Returns random number in [1,6] double_roll() Return 2 random numbers in [1,6] Duplicates each roll if they coincide Methods ---------- place_back_to_origin() Puts checker back if user moves it to an invalid destination """ def __init__(self): self.faces = [] def load_textures(self): self.faces.append(None) for i in range(1,7): self.faces.append(arcade.load_texture("resources/dice-" + str(i) + ".png")) def get_face(self, value): return self.faces[value] def roll(self): """Returns random number in [1,6]""" return random.randint(1, 6) def double_roll(self): """ Return 2 random numbers in [1,6] Duplicates each roll if they coincide """ roll1 = random.randint(1, 6) roll2 = random.randint(1, 6) if roll1 == roll2: return roll1, roll1, roll1, roll1 return roll1, roll2
55b4e104dc532534f9a5c48fc06c4ff441fab21b
appigeeta/PythonRevise
/Pythonrevise/eventPlaner.py
1,045
3.78125
4
#!usr/bin/python #general sketch for for organising an event. class booking: def __init__(self,date,time): self.date=date self.time=time #printing just to make sure print date print time class place: def place_sele(self,indoor,outdoor): self.indoor=indoor self.outdoor=outdoor class attendees: def att(self,headcount): self.headcount=headcount class food: def food_choice(self,veg,nonveg): self.veg=veg self.nonveg=nonveg class party_type: def type(self,name): self.name=name print name #selection from..bday,graduation,anniversary,wedding,company event..etc def bday(self,packages,theme,entertainment): self.packages=packages self.theme=theme self.entertainment=entertainment self.headcount=headcount def packages(self,A,B,C,): self.A="only decoration" self.B="A+cake+food" self.C="B+goodiebags" def entertainment(self,ch,mg,ba,fp): self.ch="character" self.mg="magician" self.ba="balloonmaker" self.fp="face painting" def costEstimation(self,attendees): print self.attendees()
fa4df0ac57ff1d00717b64cb9217e2691ec22195
DavidKenyon96/Various-Python-Programs
/NQueensProblem.py
1,200
3.84375
4
# NQueensA_DBK.py import random from itertools import permutations NQ_solutions = 0 NQ_conflicts = 0 iterations = 0 N = int (input("Input an 'N' value (must be larger than 3): ")) while (NQ_solutions is 0): cols = [random.randint(0,N-1) for cols in range(N)] # Generate a candidate NQ solution [random.randint(0,n-1) for x in range(n)] for combo in permutations(cols): #Row conflicts if (NQ_solutions is 0): if N==len(set(combo[i]+i for i in cols))==len(set(combo[i]-i for i in cols)): # Diagonal conflicts NQ_solutions += 1 # How many solutions? iterations += 1 # How many iterations? print('Solution '+str(NQ_solutions)+': '+str(combo)+'\n') print("\n".join(' - ' * i + ' Q ' + ' - ' * (N-i-1) for i in combo) + "\n\n\n\n") else: NQ_conflicts += 1 # How many conflicts? iterations += 1 # How many iterations? if (N <= 3): print("Your number needs to be greater than 3 to make a reasonable board size") print("The # of solutions was: ", NQ_solutions) print("The # of conflicts was: ", NQ_conflicts) print("The # of iterations was: ", iterations)
e86148fcf758aba045541d4d006191a187c8a6e6
jiyoungkimcr/Python_Summer_2021_2
/HW6_Bank.py
4,001
3.984375
4
class Customer: last_id = 0 def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname Customer.last_id += 1 self.id = Customer.last_id def __repr__(self): return 'Customer[{},{},{}]'.format(self.id, self.firstname, self.lastname) class Account: last_id = 0 def __init__(self, customer): Account.last_id += 1 self.id = Account.last_id self.customer = customer self._balance = 0 def deposit(self, amount): if amount > 0: self._balance += amount print('New deposit updated as: ' + str(self._balance)) else: print('The amount is negative') def charge(self, amount): if amount > self._balance: raise NotEnoughBalanceException("You don't have enough Balance. Your Current Balance is " + str(self._balance)) if amount <= 0: raise NegativeAmountException("The amount is negative. Please input the positive amount") else: self._balance -= amount print("Charge amount is: " + str(amount)) print("New Balance updated as: " + str(self._balance)) def get_balance(self): print("Current balance is: " + str(self._balance)) return self._balance def __repr__(self): return 'Account[{},{},{}]'.format(self.id, self.customer.lastname, self._balance) class SavingsAccount(Account): interest_rate = 0.01 def calc_interest(self): self._balance += self.interest_rate * self._balance class CheckingAccount(Account): pass class BankException(Exception): pass class NegativeAmountException(BankException): pass class NotEnoughBalanceException(BankException): pass class Bank: def __init__(self): self.customers = [] self.accounts = [] # Customer Factory def new_customer(self, first_name, last_name): c = Customer(first_name, last_name) #TODO add customer to a list self.customers.append(c) return c # Add account factory to bank def new_account(self, customer): a = Account(customer) self.accounts.append(a) return a # Implement transfer def transfer(self, from_acc_id, to_acc_id, amount): #TODO implement if from_acc_id not in self.accounts: print("The sender account id you input doesn't exist") return if amount <= 0: print("The transfer amount is negative. Please input the positive amount") return balance_from_acc_id = from_acc_id.get_balance() if amount > balance_from_acc_id: print("You don't have enough Balance in your account to transfer this amount") return else: print("Your transfer is successful") from_acc_id.charge(amount) to_acc_id.deposit(amount) def __repr__(self): return 'Bank[{},{}]'.format(self.customers, self.accounts) bank = Bank() bank_2 = Bank() c1 = bank.new_customer('John', 'Smith') print(c1) c2 = bank.new_customer('Anne', 'Brown') print(c2) a1 = bank.new_account(c1) print(a1) a2 = bank.new_account(c2) print(a2) a3 = bank_2.new_account(c2) a1.deposit(300) a2.deposit(20) a3.deposit(500) # Transferred well case bank.transfer(a1,a2,50) a1.get_balance() a2.get_balance() print() # a1, a2 customer's balance changed # Exception case (NotEnoughBalanceTransferException) bank.transfer(a1,a2,500) a1.get_balance() a2.get_balance() print() # a1, a2 customer's balance didn't change due to exceptional case # Exception case (NegativeAmountTransferException) bank.transfer(a1,a2,-100) a1.get_balance() a2.get_balance() print() # a1, a2 customer's balance didn't change due to exceptional case # Exception case (AccountIDNotAvailable) bank.transfer(a3,a2,60) a3.get_balance() a2.get_balance() print() # a3, a2 customer's the balance didn't change due to exceptional case
d5697b02306cb0afaaa174e48441b13f75c85a62
Nacho114/python_course
/course/chapter3/example_for.py
847
3.8125
4
def int_from_cmd(prompt): return int(input(prompt)) def print_member(member): print('Name: ', member[0], ', age: ', member[1]) def print_member_list(member_list): print('Members:') for member in member_list: print_member(member) def mean(numbers): mean_value = 0 for nber in numbers: mean_value += nber return mean_value / len(numbers) nb_people = int_from_cmd('Insert number of people: ') members = [] print('-'*25) for _ in range(nb_people): name = input('Insert member name: ') age = int_from_cmd('Insert memeber age: ') member_data = [name, age] members.append(member_data) print('-'*25) print_member_list(members) # Calculate mean of users ages = [] for mber in members: ages.append(mber[1]) print('-'*25) mean_age = mean(ages) print('Mean age:', mean_age)
8dc3bbc8fa1f7a1dc7d517cf330c2bfa2028abc6
redhotcode/secthing
/solution.py
3,573
3.5625
4
#!/usr/bin/env python from lxml import html, etree import requests import re import json class SECFiling: ''' Simple class for parsing SEC Filings obtained from the internet into plain text paragraphs and splits the "financial" paragraphs (a.k.a. those paragraphs containing a dollar sign) into its own list. ''' __slots__ = ['filing_url', 'paragraphs', 'financial_paragraphs'] def __init__(self, filing_url, **kwargs): '''Creates a new SECFiling instance with the given SEC Filing URL as a string.''' self.filing_url = filing_url @property def page(self): '''The Response object containing the page obtained from the SEC filing URL.''' return requests.get(self.filing_url) @property def tree(self): '''Yields a tree of Elements from the HTML obtained from the page property.''' return html.document_fromstring(self.page.text) @property def paragraph_elements(self): '''Yields only those elements that contain text bodies.''' PARAGRAPH_SELECTOR = "//document/type/sequence/filename/description/text/div" return self.tree.xpath(PARAGRAPH_SELECTOR) def parse_paragraphs(self): ''' Yields a dictionary with the text, paragraph start, and paragraph end position of each paragraph within the document. Strips text of invalid characters and ensures no tables are parsed. Also marks header texts (as denoted by their bold font weight) with a pound sign, making them valid Markdown headers. ''' seq = self.paragraph_elements char_count, par_start, par_end = 0, 0, 0 HEADING_SELECTOR = ".//font[contains(@style, 'font-weight:bold')]" TABLE_SELECTOR = ".//table" LINE_MIN_LEN = 5 def filter_checkboxes(in_str): new_str = re.sub(r'[\xFD]+', r'X', in_str) new_str = re.sub(r'[\xA0]+', r'', new_str) return re.sub(r'[\xA8]', r'-', new_str) def filter_headers(in_str, element): return "# %s" % in_str if \ len(element.xpath(HEADING_SELECTOR)) is not 0 else in_str for e in seq: if len(e.xpath(TABLE_SELECTOR)) is 0: text = filter_checkboxes(e.text_content()) text = filter_headers(text, e) par_start, char_count, par_end = \ char_count, char_count + len(text), char_count if len(text) > LINE_MIN_LEN: yield {'text': text, 'start': par_start, 'end': par_end} def target_paragraphs(self): '''Generator yielding only the paragraphs containing a dollar sign ($). Yields dictionaries.''' for p in self.parse_paragraphs(): if "$" in p['text']: yield p def save_plaintext(self, filename='document.txt'): '''Writes the plain text version of the SEC Filing to a text file.''' with open(filename, 'w') as f: for p in self.parse_paragraphs(): f.write(p['text'] + "\n") def save_paragraphs(self, filename='paragraphs.txt'): '''Writes the paragraphs containing a dollars sign to a text file.''' with open(filename, 'w') as f: json.dump(list(self.target_paragraphs()), f) def main(): filing = SECFiling('http://www.sec.gov/Archives/edgar/data/9092/000000909214000004/bmi-20131231x10k.htm') filing.save_plaintext() filing.save_paragraphs() if __name__ == "__main__": main()
3824fb27aa0a6a84ccc0349a32f685504c11040c
logansmithbayarea/Draw-flower
/turtle_drawusaflower.py
1,277
4.0625
4
import turtle def draw_square(s_turtle): for s in range(1,5): s_turtle.forward(110) s_turtle.right(90) def draw_circle(f_turtle): for f in range(1,5): f_turtle.circle(80) def draw_triangle(t_turtle): for t in range(1,3): t_turtle.left(60) t_turtle.forward(90) def draw_shapes(): window = turtle.Screen() window.bgcolor("black") Kevin = turtle.Turtle() Kevin.shape("square") Kevin.color("white") Kevin.speed(100) for L in range(1,37): draw_square(Kevin) Kevin.right(10) Alice = turtle.Turtle() Alice.shape("circle") Alice.color("red") Alice.speed(100) for H in range(1,37): draw_circle(Alice) Alice.right(10) Stef = turtle.Turtle() Stef.shape("arrow") Stef.color("blue") Stef.speed(60) for T in range(1,37): Stef.penup() Stef.setpos(0,0) Stef.pendown() draw_triangle(Stef) Stef.right(10) Stef.penup() Stef.setpos(0,0) Stef.pendown() Stef.right(90) Stef.setpos(0,-165) Stef.color("green") Stef.pensize(10) Stef.forward(250) window.exitonclick() draw_shapes()
5361bceaf8f580c2855c45a3396525a7a326bffa
shubhneetkumar/python-lab
/anagram,py.py
203
4.15625
4
#anagram string s1 = input("Enter first string:") s2 = input("Enter second string:") if(sorted(s1) == sorted(s2)): print("string are anagram") else: print("strings are not anagram")
da3e9563e8338fbd61e1701c497bdbd8ad015f28
shubhneetkumar/python-lab
/frequency.py
150
4
4
strA = input("Enter a string") res = {} for keys in strA: res[keys] = res.get(keys, 0) + 1 print("Frequency of each character : \n",res)
adcc60b82032aded3ad04e4ea075eee27665d854
tonib/tokens-rnn-tensorflow
/tests/rnnnumbers.py
4,299
3.640625
4
import tensorflow as tf import tensorflow.feature_column as feature_column from tensorflow.contrib.estimator import RNNClassifier import tensorflow.contrib.feature_column as contrib_feature_column import test_utils from typing import List # Test to make a char RNN predictor # Simple sample text to learn: repetitions of "0123456789" text="" for _ in range(10): text += "0123456789" # Sequence length that will be feeded to the network SEQUENCE_LENGHT = 7 # The real vocabulary: vocabulary = list( set(text) ) # As far I know, Tensorflow RNN estimators don't support variable length sequences, so I'll use the char "_" as padding # Maybe it's supported, right now I dont' know how vocabulary.append('_') # Important! Otherwise, with different executions, the list can be in different orders (really) vocabulary.sort() def pad_sequence( text_sequence : str ) -> List[str]: """ Pads the text_sequence lenght to a minimum length of SEQUENCE_LENGHT, and returns it as a List of characters As far I know, Tensorflow RNN estimators don't support variable length sequences, so I'll use the char "_" as padding. If text_sequence has a len(text_sequence) < SEQUENCE_LENGHT, the text will be padded as "_...text_sequence", up to SEQUENCE_LENGHT characters. Args: text_sequence: The text to pad Retunrs: The "text_sequence", padded with "_" characters, as a characters List """ l = len(text_sequence) if l < SEQUENCE_LENGHT: # Pad string: "__...__text_sequence" text_sequence = text_sequence.rjust( SEQUENCE_LENGHT , '_') # Return the text as a characters list return list(text_sequence) # Train input and outputs inputs = { 'character': [] } outputs = [] def prepare_train_sequences_length(seq_length : int): """ Prepare sequences of a given length Args: lenght: Length of sequences to prepare """ for i in range(0, len(text) - seq_length): sequence = text[i : i + seq_length] sequence_output = text[i + seq_length : i + seq_length+1] inputs['character'].append( pad_sequence(sequence) ) outputs.append(sequence_output) # Prepare sequences of a range of lengths from 1 to 7 characters for sequence_length in range(1, 8): prepare_train_sequences_length(sequence_length) print("N. train sequences: ", len(inputs['character'])) def input_fn(n_repetitions = 1) -> tf.data.Dataset: """ Returns the text as char array Args: n_repetitions: Number of times to repeat the inputs """ # The dataset ds = tf.data.Dataset.from_tensor_slices( (inputs,outputs) ) # Repeat inputs n times if n_repetitions > 1: ds = ds.repeat(n_repetitions) ds = ds.shuffle( 1000 ) ds = ds.batch(4) return ds # The single character sequence character_column = contrib_feature_column.sequence_categorical_column_with_vocabulary_list( 'character' , vocabulary_list = vocabulary ) indicator_column = feature_column.indicator_column( character_column ) feature_columns = [ indicator_column ] # The estimator estimator = RNNClassifier( sequence_feature_columns=feature_columns, num_units=[7], cell_type='lstm', model_dir='./model', n_classes=10, label_vocabulary=vocabulary) # Traing until all train set is learned while test_utils.accuracy(estimator, input_fn) < 1.0: print("Training...") estimator.train(input_fn=input_fn) def predict( text : str ): """ Predicts and print the next character after a given sequence Args: text: The input sequence text """ result = estimator.predict( input_fn=lambda:tf.data.Dataset.from_tensors( ({ 'character' : [ pad_sequence(text) ] }) ) ) print("-----") print("Input sequence: " , text ) for r in result: #print("Prediction: " , r) print('Class output: ', r['class_ids']) print("-----") # Some predictions in the train set (memory) predict( '0123456' ) predict( '1234567' ) predict( '2345678' ) predict( '3456789' ) predict( '4567890' ) predict( '3' ) predict( '5678' ) # Some predictions out the train set (generalization) predict( '2345678901' ) predict( '6789012345678' ) predict( '9012345678901234567890123456789012' ) predict( '0123456789012345678901234567890123456789' )
fa1cd0af3edd4227793b74655a2e370e38f242fb
tonib/tokens-rnn-tensorflow
/input_data.py
1,457
3.609375
4
from enum import Enum import os from typing import List class InputData: """ The train data: A text file """ #def __init__(self, data_file_path : str , token_mode : TokenMode , sequence_length : int ): def __init__(self, args : object ): # Input file file path = os.path.join( args.data_dir , 'input.txt' ) # The text to train / predict print("Reading", path) with open( path , 'r', encoding='utf-8') as file: self.text = file.read() self.word_mode = False if args.mode == 'word': # Words vocabulary. Store the text as a words list self.word_mode = True self.text = self.text.split() # Text vocabulary self.vocabulary = list( set(self.text) ) # Important! self.vocabulary.sort() print( "Vocabulary length:", len(self.vocabulary) ) print( "Text length:", len(self.text) , "tokens") #print( self.vocabulary ) def get_sequence( self, sequence_start_idx : int , sequence_length : int ) -> List[str]: return list( self.text[sequence_start_idx : sequence_start_idx + sequence_length] ) def get_sequence_output( self, sequence_start_idx : int , sequence_length : int ) -> str: output = self.text[sequence_start_idx + sequence_length : sequence_start_idx + sequence_length+1] if self.word_mode: output = output[0] return output
553e6ab87a793c2335c2330f29e9fb07be7f75b7
Bhumireddysravani/sravani
/armstrong.py
159
3.859375
4
num=int(input()) sum=0 temp=num while temp>0: digital=temp%10 sum=digital**3 temp//=10 if num==sum: print("yes") else: print("no")
c69eda975eaa6a5d7da163d458845a1e4a9e3366
iloveyii/tut-python
/loop.py
259
4.15625
4
# For loop fruits = ['banana', 'orange', 'banana', 'orange', 'grapes', 'banana'] print('For loop:') for fruit in fruits: print(fruit) # While loop count = len(fruits) print('While loop') while count > 0: print(count, fruits[count-1]) count -= 1
e0e96d3e2e2c7cf3b4418c0f971e8b7fa1a60d7c
iloveyii/tut-python
/classes/c1.py
330
3.828125
4
class Employee: def __init__(self, firstName, lastName): self.firstName = firstName self.lastName = lastName def fullName(self): return '{} {}'.format(self.firstName, self.lastName) emp_1 = Employee('Alex', 'Kan') emp_2 = Employee('John', 'Doe') print(emp_1.fullName()) print(emp_2.fullName())
a309771759a1a85fd999d6b8234a167dc770bc76
kungming2/translator-BOT
/code/zh_processing.py
46,564
3.53125
4
#!/usr/bin/env python3 """ CHARACTER/WORD LOOKUP FUNCTIONS Ziwen uses the regular code-formatting in Markdown (`) as a syntax to define words for it to look up. The most supported searches are for Japanese and Chinese as they account for nearly 50% of posts on r/translator. There is also a dedicated search function for Korean and a Wiktionary search for every other language. For Chinese and Japanese, the main functions are `xx_character` and `xx_word`, where xx is the language code (ZH or JA). Specific language lookup functions are prefixed by the function whose data they return to. (e.g. `zh_word`) More general ones are prefixed by `lookup`. """ # Chinese Lookup Functions import csv import random import re import time from code._config import ( FILE_ADDRESS_OLD_CHINESE, FILE_ADDRESS_ZH_BUDDHIST, FILE_ADDRESS_ZH_CCCANTO, FILE_ADDRESS_ZH_ROMANIZATION, logger, ) from typing import Dict, Tuple import requests from bs4 import BeautifulSoup from korean_romanizer.romanizer import Romanizer from lxml import html from mafan import simplify, tradify class ZhProcessor: def __init__(self, zw_useragent) -> None: self.zw_useragent = zw_useragent def zh_character(self, character): """ This function looks up a Chinese character's pronunciations and meanings. It also ties together a lot of the other reference functions above. :param character: Any Chinese character. :return: A formatted string containing the character's information. """ multi_character_dict = {} multi_character_list = list(character) # Whether or not multiple characters are passed to this function multi_mode = len(multi_character_list) > 1 eth_page = requests.get( f"https://www.mdbg.net/chinese/dictionary?page=chardict&cdcanoce=0&cdqchi={character}", timeout=15, headers=self.zw_useragent, ) tree = html.fromstring(eth_page.content) # now contains the whole HTML page pronunciation = [ div.text_content() for div in tree.xpath('//div[contains(@class,"pinyin")]') ] # Note that the Yue pronunciation is given as `['zyun2, zyun3']` cmn_pronunciation, yue_pronunciation = pronunciation[::2], pronunciation[1::2] if ( len(pronunciation) == 0 ): # Check to not return anything if the entry is invalid logger.info(f"ZH-Character: No results for {character}") return ( f"**There were no results for {character}**. Please check to make sure it is a valid Chinese " "character. Alternatively, it may be an uncommon variant that is not in " "online dictionaries." ) if not multi_mode: # Regular old-school character search for just one. cmn_pronunciation = " / ".join(cmn_pronunciation) yue_pronunciation = tree.xpath( '//a[contains(@onclick,"pronounce-jyutping")]/text()' ) yue_pronunciation = " / ".join(yue_pronunciation) # Add superscript to the numbers. Wrapped in paragraphs so that # it displays the same on both New and Old Reddit. for i in range(0, 9): yue_pronunciation = yue_pronunciation.replace(str(i), f"^({str(i)} ") yue_pronunciation = yue_pronunciation.replace(str(i), f"{str(i)})") meaning = tree.xpath('//div[contains(@class,"defs")]/text()') meaning = "/ ".join(meaning).strip() if tradify(character) == simplify(character): logger.debug( f"ZH-Character: The two versions of {character} are identical." ) lookup_line_1 = str( "# [{0}](https://en.wiktionary.org/wiki/{0}#Chinese)".format( character ) ) lookup_line_1 += ( "\n\nLanguage | Pronunciation\n---------|--------------\n" ) lookup_line_1 += f"**Mandarin** | *{cmn_pronunciation}*\n**Cantonese** | *{yue_pronunciation[:-1]}*" else: logger.debug( f"ZH-Character: The two versions of {character} are *not* identical." ) lookup_line_1 = ( "# [{0} ({1})](https://en.wiktionary.org/wiki/{0}#Chinese)".format( tradify(character), simplify(character) ) ) lookup_line_1 += ( "\n\nLanguage | Pronunciation\n---------|--------------\n" ) lookup_line_1 += f"**Mandarin** | *{cmn_pronunciation}*\n**Cantonese** | *{yue_pronunciation[:-1]}*" # Hokkien and Hakka Data min_hak_data = self.__zh_character_min_hak(tradify(character)) lookup_line_1 += min_hak_data # Old Chinese try: # Try to get old chinese data. ocmc_pronunciation = self.__zh_character_oc_search(tradify(character)) if ocmc_pronunciation is not None: lookup_line_1 += ocmc_pronunciation except IndexError: # There was an error; character has no old chinese entry pass # Other Language Readings other_readings_data = self.__zh_character_other_readings(tradify(character)) if other_readings_data is not None: lookup_line_1 += "\n" + other_readings_data calligraphy_image = zh_character_calligraphy_search(character) if calligraphy_image is not None: lookup_line_1 += calligraphy_image lookup_line_1 += f'\n\n**Meanings**: "{meaning}."' else: # It's multiple characters, let's make a table. # MULTIPLE Start iterating over the characters we have if tradify(character) == simplify(character): duo_key = f"# {character}" else: # Different versions, different header. duo_key = f"# {tradify(character)} ({simplify(character)})" duo_header = "\n\nCharacter " duo_separator = "\n---|" duo_mandarin = "\n**Mandarin**" duo_cantonese = "\n**Cantonese** " duo_meaning = "\n**Meanings** " for wenzi in multi_character_list: # Got through each character multi_character_dict[wenzi] = {} # Create a new dictionary for it. # Get the data. character_url = ( "https://www.mdbg.net/chindict/chindict.php?page=chardict&cdcanoce=0&cdqchi=" + wenzi ) new_eth_page = requests.get( character_url, timeout=15, headers=self.zw_useragent ) # now contains the whole HTML page new_tree = html.fromstring(new_eth_page.content) pronunciation = [ div.text_content() for div in new_tree.xpath('//div[contains(@class,"pinyin")]') ] cmn_pronunciation, yue_pronunciation = ( pronunciation[::2], pronunciation[1::2], ) # Format the pronunciation data cmn_pronunciation = "*" + " ".join(cmn_pronunciation) + "*" yue_pronunciation = new_tree.xpath( '//a[contains(@onclick,"pronounce-jyutping")]/text()' ) yue_pronunciation = " ".join(yue_pronunciation) for i in range(0, 9): yue_pronunciation = yue_pronunciation.replace(str(i), f"^{str(i)} ") yue_pronunciation = "*" + yue_pronunciation.strip() + "*" multi_character_dict[wenzi]["mandarin"] = cmn_pronunciation multi_character_dict[wenzi]["cantonese"] = yue_pronunciation # Format the meaning data. meaning = new_tree.xpath('//div[contains(@class,"defs")]/text()') meaning = "/ ".join(meaning) meaning = '"' + meaning.strip() + '."' multi_character_dict[wenzi]["meaning"] = meaning # Create a randomized wait time. wait_sec = random.randint(3, 12) time.sleep(wait_sec) # Now let's construct the table based on the data. for key in multi_character_list: # Iterate over the characters in order character_data = multi_character_dict[key] if tradify(key) == simplify(key): # Same character in both sets. duo_header += ( " | [{0}](https://en.wiktionary.org/wiki/{0}#Chinese)".format( key ) ) else: duo_header += " | [{0} ({1})](https://en.wiktionary.org/wiki/{0}#Chinese)".format( tradify(key), simplify(key) ) duo_separator += "---|" duo_mandarin += f" | {character_data['mandarin']}" duo_cantonese += f" | {character_data['cantonese']}" duo_meaning += f" | {character_data['meaning']}" lookup_line_1 = ( duo_key + duo_header + duo_separator + duo_mandarin + duo_cantonese + duo_meaning ) # Format the dictionary links footer lookup_line_2 = ( "\n\n\n^Information ^from " "[^(Unihan)](https://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint={0}) ^| " "[^(CantoDict)](https://www.cantonese.sheik.co.uk/dictionary/characters/{0}/) ^| " "[^(Chinese Etymology)](https://hanziyuan.net/#{1}) ^| " "[^(CHISE)](https://www.chise.org/est/view/char/{0}) ^| " "[^(CTEXT)](https://ctext.org/dictionary.pl?if=en&char={1}) ^| " "[^(MDBG)](https://www.mdbg.net/chinese/dictionary?page=worddict&wdrst=1&wdqb={0}) ^| " "[^(MoE DICT)](https://www.moedict.tw/'{1}) ^| " "[^(MFCCD)](https://humanum.arts.cuhk.edu.hk/Lexis/lexi-mf/search.php?word={1})" ) lookup_line_2 = lookup_line_2.format(character, tradify(character)) logger.info( f"ZH-Character: Received lookup command for {character} in " "Chinese. Returned search results." ) return lookup_line_1 + lookup_line_2 def zh_word(self, word: str) -> str: """ Function to define Chinese words and return their readings and meanings. A Chinese word is one that is longer than a single character. :param word: Any Chinese word. This function is used for words longer than one character, generally. :return: Word data. """ alternate_meanings = [] alternate_pinyin = () alternate_jyutping = None eth_page = requests.get( "https://www.mdbg.net/chinese/dictionary?page=worddict&wdrst=0&wdqb=c:" + word, timeout=15, headers=self.zw_useragent, ) tree = html.fromstring(eth_page.content) # now contains the whole HTML page word_exists = str( tree.xpath('//p[contains(@class,"nonprintable")]/strong/text()') ) cmn_pronunciation = tree.xpath('//div[contains(@class,"pinyin")]/a/span/text()') # We only want the pronunciations to be as long as the input cmn_pronunciation = cmn_pronunciation[0 : len(word)] # We don't need a dividing character per pinyin standards cmn_pronunciation = "".join(cmn_pronunciation) # Check to not return anything if the entry is invalid if "No results found" in word_exists: # First we try to check our specialty dictionaries. Buddhist dictionary first. Then the tea dictionary. search_results_buddhist = self.__zh_word_buddhist_dictionary_search( tradify(word) ) search_results_tea = self.__zh_word_tea_dictionary_search(simplify(word)) search_results_cccanto = self.__zh_word_cccanto_search(tradify(word)) # If both have nothing, we kick it down to the character search. if ( search_results_buddhist is None and search_results_tea is None and search_results_cccanto is None ): logger.info( "ZH-Word: No results found. Getting individual characters instead." ) # This will split the word into character chunks. if len(word) < 2: to_post = self.zh_character(word) else: # The word is longer than one character. to_post = "" search_characters = list(word) for character in search_characters: to_post += "\n\n" + self.zh_character(character) return to_post # Otherwise, let's try to format the data nicely. if search_results_buddhist is not None: alternate_meanings.append(search_results_buddhist["meaning"]) alternate_pinyin = search_results_buddhist["pinyin"] if search_results_tea is not None: alternate_meanings.append(search_results_tea["meaning"]) alternate_pinyin = search_results_tea["pinyin"] if search_results_cccanto is not None: alternate_meanings.append(search_results_cccanto["meaning"]) alternate_pinyin = search_results_cccanto["pinyin"] alternate_jyutping = search_results_cccanto["jyutping"] logger.info( f"ZH-Word: No results for word {word}, but results are in specialty dictionaries." ) if len(alternate_meanings) == 0: # The standard search function for regular words. # Get alternate pinyin from a separate function. We get Wade Giles and Yale. Like 'Guan1 yin1 Pu2 sa4' try: py_split_pronunciation = tree.xpath( '//div[contains(@class,"pinyin")]/a/@onclick' ) py_split_pronunciation = re.search( r"\|(...+)\'\)", py_split_pronunciation[0] ).group(0) # Format it nicely. py_split_pronunciation = py_split_pronunciation.split("'", 1)[0][ 1: ].strip() alt_romanize = self.__zh_word_alt_romanization(py_split_pronunciation) except IndexError: # This likely means that the page does not contain that information. alt_romanize = ("---", "---") meaning = [ div.text_content() for div in tree.xpath('//div[contains(@class,"defs")]') ] # This removes any empty spaces or commas that are in the list. meaning = [x for x in meaning if x not in [" ", ", "]] meaning = "/ ".join(meaning) meaning = meaning.strip() # Obtain the Cantonese information. yue_page = requests.get( "https://cantonese.org/search.php?q=" + word, timeout=15, headers=self.zw_useragent, ) yue_tree = html.fromstring( yue_page.content ) # now contains the whole HTML page yue_pronunciation = yue_tree.xpath( '//h3[contains(@class,"resulthead")]/small/strong//text()' ) # This Len needs to be double because of the numbers yue_pronunciation = yue_pronunciation[0 : (len(word) * 2)] yue_pronunciation = iter(yue_pronunciation) yue_pronunciation = [ c + next(yue_pronunciation, "") for c in yue_pronunciation ] # Combines the tones and the syllables together yue_pronunciation = " ".join(yue_pronunciation) for i in range(0, 9): # Adds Markdown syntax yue_pronunciation = yue_pronunciation.replace(str(i), f"^({str(i)}) ") yue_pronunciation = yue_pronunciation.strip() else: # This is for the alternate search with the specialty dictionaries. cmn_pronunciation = self.__zh_word_decode_pinyin(alternate_pinyin) alt_romanize = self.__zh_word_alt_romanization(alternate_pinyin) if alternate_jyutping is not None: yue_pronunciation = alternate_jyutping else: yue_pronunciation = "---" # The non-Canto specialty dictionaries do not include Jyutping pronunciation. meaning = "\n".join(alternate_meanings) # Format the header appropriately. if tradify(word) == simplify(word): lookup_line_1 = str( "# [{0}](https://en.wiktionary.org/wiki/{0}#Chinese)".format(word) ) else: lookup_line_1 = ( "# [{0} ({1})](https://en.wiktionary.org/wiki/{0}#Chinese)".format( tradify(word), simplify(word) ) ) # Format the rest. lookup_line_1 += "\n\nLanguage | Pronunciation\n---------|--------------" lookup_line_1 += ( f"\n**Mandarin** (Pinyin) | *{cmn_pronunciation}*\n**Mandarin** (Wade-Giles) | *{alt_romanize[1]}*" f"\n**Mandarin** (Yale) | *{alt_romanize[0]}*\n**Cantonese** | *{yue_pronunciation}*" ) # Add Hokkien and Hakka data. lookup_line_1 += self.__zh_character_min_hak(tradify(word)) # Format the meaning line. if len(alternate_meanings) == 0: # Format the regular results we have. lookup_line_2 = f'\n\n**Meanings**: "{meaning}."' # Append chengyu data if the string is four characters. if len(word) == 4: chengyu_data = self.__zh_word_chengyu(word) if chengyu_data is not None: logger.info("ZH-Word: >> Added additional chengyu data.") lookup_line_2 += chengyu_data # We append Buddhist results if we have them. mainline_search_results_buddhist = ( self.__zh_word_buddhist_dictionary_search(tradify(word)) ) if mainline_search_results_buddhist is not None: lookup_line_2 += mainline_search_results_buddhist["meaning"] else: # This is for the alternate dictionaries only. lookup_line_2 = "\n" + meaning # Format the footer with the dictionary links. lookup_line_3 = ( "\n\n\n^Information ^from " "[^CantoDict](https://www.cantonese.sheik.co.uk/dictionary/search/?searchtype=1&text={0}) ^| " "[^MDBG](https://www.mdbg.net/chinese/dictionary?page=worddict&wdrst=0&wdqb=c:{0}) ^| " "[^Yellowbridge](https://yellowbridge.com/chinese/dictionary.php?word={0}) ^| " "[^Youdao](https://dict.youdao.com/w/eng/{0}/#keyfrom=dict2.index)" ) lookup_line_3 = lookup_line_3.format(word) # Combine everything together. to_post = lookup_line_1 + lookup_line_2 + "\n\n" + lookup_line_3 logger.info( f"ZH-Word: Received a lookup command for {word} in Chinese. Returned search results." ) return to_post def __zh_character_oc_search(self, character: str) -> str | None: """ A simple routine that retrieves data from a CSV of Baxter-Sagart's reconstruction of Middle and Old Chinese. For more information, visit: http://ocbaxtersagart.lsait.lsa.umich.edu/ :param character: A single Chinese character. :return: A formatted string with the Middle and Old Chinese readings if found, None otherwise. """ # Main dictionary for readings mc_oc_readings = {} # Iterate over the CSV with open(FILE_ADDRESS_OLD_CHINESE, encoding="utf-8-sig") as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=",") for row in csv_reader: my_character = row["zi"] # It is normally returned as a list, so we need to convert into a string. mc_reading = row["MC"] oc_reading = row["OC"] if "(" in oc_reading: oc_reading = oc_reading.split("(", 1)[0] # Add the character as a key with the readings as a tuple mc_oc_readings[my_character] = (mc_reading.strip(), oc_reading.strip()) # Check to see if I actually have the key in my dictionary. if character not in mc_oc_readings: # Character not found. return None # Character exists! character_data = mc_oc_readings[character] # Get the tuple return f"\n**Middle Chinese** | \\**{character_data[0]}*\n**Old Chinese** | \\*{character_data[1]}*" def __zh_character_min_hak(self, character: str) -> str: """ Function to get the Hokkien and Hakka (Sixian) pronunciations from the ROC Ministry of Education dictionary. This actually will accept either single-characters or multi-character words. For more information, visit: https://www.moedict.tw/ :param character: A single Chinese character or word. :return: A string. If nothing is found the string will have zero length. """ # Fetch Hokkien results min_page = requests.get( f"https://www.moedict.tw/'{character}", timeout=15, headers=self.zw_useragent, ) min_tree = html.fromstring(min_page.content) # now contains the whole HTML page # The annotation returns as a list, we want to take the first one. try: min_reading = min_tree.xpath( '//ru[contains(@class,"rightangle") and contains(@order,"0")]/@annotation' )[0] min_reading = f"\n**Southern Min** | *{min_reading}*" except IndexError: # No character or word found. min_reading = "" # Fetch Hakka results (Sixian) hak_page = requests.get( f"https://www.moedict.tw/:{character}", timeout=15, headers=self.zw_useragent, ) hak_tree = html.fromstring(hak_page.content) # now contains the whole HTML page try: hak_reading = hak_tree.xpath( 'string(//span[contains(@data-reactid,"$0.6.2.1")])' ) if len(hak_reading) != 0: # Format the tones and words properly with superscript. # Wrap in parentheses for consistency hak_reading_new = [] # Add spaces between words. hak_reading = re.sub(r"(\d{1,4})([a-z])", r"\1 ", hak_reading) hak_reading = hak_reading.split(" ") for word in hak_reading: new_word = re.sub(r"([a-z])(\d)", r"\1^(\2", word) new_word += ")" hak_reading_new.append(new_word) hak_reading = " ".join(hak_reading_new) hak_reading = f"\n**Hakka (Sixian)** | *{hak_reading}*" except IndexError: # No character or word found. hak_reading = "" # Combine them together. return min_reading + hak_reading def __zh_character_other_readings(self, character: str) -> str | None: """ A function to get non-Chinese pronunciations of characters (Sino-Xenic readings) from the Chinese Character API. We use the Korean, Vietnamese, and Japanese readings. This information is attached to single-character lookups for Chinese and integrated into a table. For more information, visit: https://ccdb.hemiola.com/ :param character: Any Chinese character. :return: None or a string of several table lines with the readings formatted in Markdown. """ to_post = [] # Access the API u_url = f"http://ccdb.hemiola.com/characters/string/{character}?fields=kHangul,kKorean,kJapaneseKun,kJapaneseOn,kVietnamese" unicode_rep = requests.get(u_url, timeout=15, headers=self.zw_useragent) try: unicode_rep_json = unicode_rep.json() unicode_rep_jdict = unicode_rep_json[0] except (IndexError, ValueError): # Don't really have the proper data. return None if "kJapaneseKun" in unicode_rep_jdict and "kJapaneseOn" in unicode_rep_jdict: ja_kun = unicode_rep_jdict["kJapaneseKun"] ja_on = unicode_rep_jdict["kJapaneseOn"] if ja_kun is not None or ja_on is not None: # Process the data, allowing for either of these to be None in value. # A space is added since the kun appears first ja_kun = ja_kun.lower() + " " if ja_kun is not None else "" ja_on = ja_on.upper() if ja_on is not None else "" # Recombine the readings ja_total = ja_kun + ja_on ja_total = ja_total.strip().split(" ") ja_total = ", ".join(ja_total) ja_string = f"**Japanese** | *{ja_total}*" to_post.append(ja_string) if "kHangul" in unicode_rep_jdict and "kKorean" in unicode_rep_jdict: ko_hangul = unicode_rep_jdict["kHangul"] # We apply RR romanization to this. if ko_hangul is not None: ko_latin = Romanizer(ko_hangul).romanize().lower() ko_latin = ko_latin.replace(" ", ", ") # Replace spaces with commas ko_hangul = ko_hangul.replace(" ", ", ") # Replace spaces with commas ko_total = f"{ko_hangul} / *{ko_latin}*" ko_string = f"**Korean** | {ko_total}" to_post.append(ko_string) if "kVietnamese" in unicode_rep_jdict: vi_latin = unicode_rep_jdict["kVietnamese"] if vi_latin is not None: vi_latin = vi_latin.lower() vi_string = f"**Vietnamese** | *{vi_latin}*" to_post.append(vi_string) if len(to_post) > 0: return "\n".join(to_post) # pylint: disable=C0103 def __zh_word_decode_pinyin(self, s: str) -> str: """ Function to convert numbered pin1 yin1 into proper tone marks. CC-CEDICT's format uses numerical pinyin. This code is courtesy of Greg Hewgill on StackOverflow: https://stackoverflow.com/questions/8200349/convert-numbered-pinyin-to-pinyin-with-tone-marks :param s: A string of numbered pinyin (e.g. pin1 yin1) :return result: A string of pinyin with the tone marks properly applied (e.g. pīnyīn) """ pinyintonemark = { 0: "aoeiuv\u00fc", 1: "\u0101\u014d\u0113\u012b\u016b\u01d6\u01d6", 2: "\u00e1\u00f3\u00e9\u00ed\u00fa\u01d8\u01d8", 3: "\u01ce\u01d2\u011b\u01d0\u01d4\u01da\u01da", 4: "\u00e0\u00f2\u00e8\u00ec\u00f9\u01dc\u01dc", } s = s.lower() result = "" t = "" for c in s: if "a" <= c <= "z": t += c elif c == ":": assert t[-1] == "u" t = t[:-1] + "\u00fc" else: if "0" <= c <= "5": tone = int(c) % 5 if tone != 0: m = re.search("[aoeiuv\u00fc]+", t) if m is None: t += c elif len(m.group(0)) == 1: t = ( t[: m.start(0)] + pinyintonemark[tone][ pinyintonemark[0].index(m.group(0)) ] + t[m.end(0) :] ) else: if "a" in t: t = t.replace("a", pinyintonemark[tone][0]) elif "o" in t: t = t.replace("o", pinyintonemark[tone][1]) elif "e" in t: t = t.replace("e", pinyintonemark[tone][2]) elif t.endswith("ui"): t = t.replace("i", pinyintonemark[tone][3]) elif t.endswith("iu"): t = t.replace("u", pinyintonemark[tone][4]) else: t += "!" result += t t = "" result += t return result # pylint: enable=C0103 # TODO handle overlap with __zh_word_buddhist_dictionary_search def __zh_word_buddhist_dictionary_search( self, chinese_word: str ) -> None | Dict[str, str]: """ Function that allows us to consult the Soothill-Hodous 'Dictionary of Chinese Buddhist Terms.' For more information, please visit: https://mahajana.net/texts/soothill-hodous.html Since the dictionary is saved in the CC-CEDICT format, this also serves as a template for entry conversion. :param chinese_word: Any Chinese word. This should be in its *traditional* form. :return: None if there is nothing that matches, a dictionary with content otherwise. """ general_dictionary = {} # We open the file. with open(FILE_ADDRESS_ZH_BUDDHIST, encoding="utf-8") as f: existing_data = f.read().split("\n") relevant_line = None # Look for the relevant word (should not take long.) for entry in existing_data: traditional_headword = entry.split(" ", 1)[0] if chinese_word == traditional_headword: relevant_line = entry break if relevant_line is not None: # We found a matching word. # Parse the entry (code courtesy Marcanuy at https://github.com/marcanuy/cedict_utils, MIT license) hanzis = relevant_line.partition("[")[0].split(" ", 1) keywords = { "meanings": relevant_line.partition("/")[2] .replace('"', "'") .rstrip("/") .strip() .split("/"), "traditional": hanzis[0].strip(" "), "simplified": hanzis[1].strip(" "), # Take the content in between the two brackets "pinyin": relevant_line.partition("[")[2].partition("]")[0], "raw_line": relevant_line, } # Format the data nicely. if len(keywords["meanings"]) > 2: # Truncate if too long. keywords["meanings"] = keywords["meanings"][:2] keywords["meanings"][-1] += "." # Add a period. formatted_line = '\n\n**Buddhist Meanings**: "{}"'.format( "; ".join(keywords["meanings"]) ) formatted_line += ( " ([Soothill-Hodous]" "(https://mahajana.net/en/library/texts/a-dictionary-of-chinese-buddhist-terms))" ) general_dictionary["meaning"] = formatted_line general_dictionary["pinyin"] = keywords["pinyin"] return general_dictionary def __zh_word_tea_dictionary_search(self, chinese_word): """ Function that searches the Babelcarp Chinese Tea Lexicon for Chinese tea terms. :param chinese_word: Any Chinese word in *simplified* form. :return: None if there is nothing that matches, a formatted string with meaning otherwise. """ general_dictionary = {} # Conduct a search. web_search = f"http://babelcarp.org/babelcarp/babelcarp.cgi?phrase={chinese_word}&define=1" eth_page = requests.get(web_search, headers=self.zw_useragent, timeout=15) try: tree = html.fromstring(eth_page.content) # now contains the whole HTML page word_content = tree.xpath('//fieldset[contains(@id,"translation")]//text()') except BaseException: return None # Get the headword of the entry. try: head_word = word_content[2].strip() except IndexError: return None if chinese_word not in head_word: # If the characters don't match: Exit. This includes null searches. return None else: # It exists. try: pinyin = re.search(r"\((.*?)\)", word_content[2]).group(1).lower() except AttributeError: # Never mind, it does not exist. return None meaning = word_content[3:] meaning = [item.strip() for item in meaning] # Format the entry to return formatted_line = f'\n\n**Tea Meanings**: "{" ".join(meaning)}."' formatted_line = formatted_line.replace(" )", " ") formatted_line = formatted_line.replace(" ", " ") formatted_line += f" ([Babelcarp]({web_search}))" # Append source general_dictionary["meaning"] = formatted_line general_dictionary["pinyin"] = pinyin return general_dictionary def __zh_word_cccanto_search(self, cantonese_word: str) -> None | Dict[str, str]: """ Function that parses and returns data from the CC-Canto database, which uses CC-CEDICT's format. More information can be found here: https://cantonese.org/download.html :param cantonese_word: Any Cantonese word. This should be in its *traditional* form. :return: None if there is nothing that matches, a dictionary with content otherwise. """ general_dictionary = {} # We open the file. with open(FILE_ADDRESS_ZH_CCCANTO, encoding="utf-8") as f: existing_data = f.read().split("\n") relevant_line = None # Look for the relevant word (should not take long.) for entry in existing_data: traditional_headword = entry.split(" ", 1)[0] if cantonese_word == traditional_headword: relevant_line = entry break if relevant_line is not None: # Parse the entry (based on code from Marcanuy at https://github.com/marcanuy/cedict_utils, MIT license) hanzis = relevant_line.partition("[")[0].split(" ", 1) keywords = { "meanings": relevant_line.partition("/")[2] .replace('"', "'") .rstrip("/") .strip() .split("/"), "traditional": hanzis[0].strip(" "), "simplified": hanzis[1].strip(" "), # Take the content in between the two brackets "pinyin": relevant_line.partition("[")[2].partition("]")[0], "jyutping": relevant_line.partition("{")[2].partition("}")[0], "raw_line": relevant_line, } formatted_line = '\n\n**Cantonese Meanings**: "{}."'.format( "; ".join(keywords["meanings"]) ) formatted_line += ( f" ([CC-Canto](https://cantonese.org/search.php?q={cantonese_word}))" ) for i in range(0, 9): keywords["jyutping"] = keywords["jyutping"].replace( str(i), f"^{str(i)} " ) # Adds syntax for tones keywords["jyutping"] = ( keywords["jyutping"].replace(" ", " ").strip() ) # Replace double spaces general_dictionary["meaning"] = formatted_line general_dictionary["pinyin"] = keywords["pinyin"] general_dictionary["jyutping"] = keywords["jyutping"] return general_dictionary def __zh_word_alt_romanization(self, pinyin_string: str) -> Tuple[str, str]: """ Takes a pinyin with number item and returns version of it in the legacy Wade-Giles and Yale romanization schemes. This is only used for zh_word at the moment. We don't deal with diacritics for this. Too complicated. Example: ri4 guang1, becomes, jih^4 kuang^1 in Wade Giles and r^4 gwang^1 in Yale. :param pinyin_string: A numbered pinyin string (e.g. pin1 yin1). :return: A tuple. Yale romanization form first, then the Wade-Giles version. """ # Get the corresponding pronunciations into a dictonary. corresponding_dict = {} with open(FILE_ADDRESS_ZH_ROMANIZATION, encoding="utf-8-sig") as csv_file: csv_reader = csv.reader(csv_file, delimiter=",") for row in csv_reader: pinyin_p, yale_p, wadegiles_p = row corresponding_dict[pinyin_p] = [yale_p.strip(), wadegiles_p.strip()] yale_list = [] wadegiles_list = [] # Process each syllable. for syllable in pinyin_string.split(" "): tone = syllable[-1] syllable = syllable[:-1].lower() yale_equiv = f"{corresponding_dict[syllable][0]}" wadegiles_equiv = f"{corresponding_dict[syllable][1]}" # Make exception for null tones. if tone != "5": # Add tone as superscript yale_equiv += f"^({tone})" wadegiles_equiv += f"^({tone})" yale_list.append(yale_equiv) wadegiles_list.append(wadegiles_equiv) # Reconstitute the equivalent parts into a string. return " ".join(yale_list), " ".join(wadegiles_list) def __zh_word_chengyu(self, chengyu: str) -> str | None: """ Function to get Chinese information for Chinese chengyu, including literary sources and explanations. Note: this is the second version. This version just adds supplementary Chinese information to zh_word. :param chengyu: Any Chinese idiom (usually four characters) :return: None if no results, otherwise a formatted string. """ headers = { "Content-Type": "text/html; charset=gb2312", "f-type": "chengyu", "accept-encoding": "gb2312", } chengyu = simplify(chengyu) # This website only takes simplified chinese r_tree = None # Placeholder. # Convert Unicode into a string for the URL, which uses GB2312 encoding. chengyu_gb = str(chengyu.encode("gb2312")) chengyu_gb = chengyu_gb.replace("\\x", "%").upper()[2:-1] # Format the search link. search_link = ( f"http://cy.51bc.net/serach.php?f_type=chengyu&f_type2=&f_key={chengyu_gb}" ) # Note: 'serach' is intentional. logger.debug(search_link) try: # We run a search on the site and see if there are results. results = requests.get( search_link.format(chengyu), headers=headers, timeout=15 ) results.encoding = "gb2312" r_tree = html.fromstring(results.text) # now contains the whole HTML page chengyu_exists = r_tree.xpath('//td[contains(@bgcolor,"#B4D8F5")]/text()') except ( UnicodeEncodeError, UnicodeDecodeError, requests.exceptions.ConnectionError, requests.exceptions.ChunkedEncodingError, ): # There may be an issue with the conversion. Skip if so. logger.error("ZH-Chengyu: Unicode encoding error.") chengyu_exists = ["", "找到 0 个成语"] # Tell it to exit later. if not chengyu_exists: return if "找到 0 个成语" in chengyu_exists[1]: # There are no results... logger.info(f"ZH-Chengyu: No chengyu results found for {chengyu}.") return None if r_tree is not None: # There are results. # Look through the results page. link_results = r_tree.xpath('//tr[contains(@bgcolor,"#ffffff")]/td/a') try: actual_link = link_results[0].attrib["href"] except IndexError: return None logger.info(f"> ZH-Chengyu: Found a chengyu. Actual link at: {actual_link}") # Get the data from the actual link try: eth_page = requests.get(actual_link, timeout=15, headers=headers) eth_page.encoding = "gb2312" tree = html.fromstring( eth_page.text ) # now contains the whole HTML page except ( requests.exceptions.ChunkedEncodingError, requests.exceptions.ConnectionError, ): return # Grab the data from the table. zh_data = tree.xpath('//td[contains(@colspan, "5")]/text()') # Assign them to variables. chengyu_meaning = zh_data[1] chengyu_source = zh_data[2] # Format the data nicely to add to the zh_word output. cy_to_post = f"\n\n**Chinese Meaning**: {chengyu_meaning}\n\n**Literary Source**: {chengyu_source}" cy_to_post += f" ([5156edu]({actual_link}), [18Dao](https://tw.18dao.net/成語詞典/{tradify(chengyu)}))" logger.info( f"> ZH-Chengyu: Looked up the chengyu {chengyu} in Chinese. Returned search results." ) return cy_to_post def zh_character_calligraphy_search(character: str) -> str | None: """ A function to get an overall image of Chinese calligraphic search containing different styles from various time periods. :param character: A single Chinese character. :return: None if no image found, a formatted string containing the relevant URLs and images otherwise. """ character = simplify(character) # First get data from http://sfds.cn (this will be included as a URL) # Get the Unicode assignment (eg 738B) unicode_assignment = hex(ord(character)).upper()[2:] gx_url = f"http://www.sfds.cn/{unicode_assignment}/" # Secondly, get variant data from the MoE dictionary. variant_link = zh_character_variant_search(tradify(character)) if variant_link: variant_formatted = f"[YTZZD]({variant_link})" else: variant_formatted = ( "[YTZZD](https://dict.variants.moe.edu.tw/variants/rbt/" "query_by_standard_tiles.rbt?command=clear)" ) # Next get an image from Shufazidian. # Form data to pass on to the POST system. formdata = {"sort": "7", "wd": character} try: rdata = requests.post("http://www.shufazidian.com/", data=formdata, timeout=15) tree = BeautifulSoup(rdata.content, "lxml") tree = str(tree) tree = html.fromstring(tree) except requests.exceptions.ConnectionError: # If there's a connection error, return None. return None images = tree.xpath("//img/@src") complete_image = "" image_string = None if images is not None: for url in images: if len(url) < 20 or "gif" in url: # We don't need short links or GIFs. continue if "shufa6" in url: # We try to get the broader summation image instead of the thumbnail. complete_image = url.replace("shufa6/1", "shufa6") if len(complete_image) != 0: logger.debug( f"ZH-Calligraphy: There is a Chinese calligraphic image for {character}." ) image_string = ( f"\n\n**Chinese Calligraphy Variants**: [{character}]({complete_image}) (*[SFZD](http://www.shufazidian.com/)*, " f"*[SFDS]({gx_url})*, *{variant_formatted}*)" ) else: image_string = None return image_string def zh_character_variant_search(search_term: str, retries: int = 3) -> str | None: """ Function to search the MOE dictionary for a link to character variants, and returns the link if found. None if nothing is found. """ search_term = search_term.strip() entry_url = None timeout_amount = 4 session = requests.Session() base_url = "https://dict.variants.moe.edu.tw/variants/rbt" try: initial_resp = session.get( f"{base_url}/query_by_standard_tiles.rbt", timeout=0.5, ) except (requests.exceptions.ReadTimeout, requests.exceptions.ConnectionError): logger.info("Issue with gathering session for variant search.") return try: rci = re.search("componentId=(rci_.*_4)", initial_resp.text).group(1) cookies = session.cookies.get_dict() # sets JSESSIONID except AttributeError: return search_params = { "rbtType": "AJAX_INVOKE", "componentId": rci, } data = {"searchedText": search_term} try: search_response = requests.post( f"{base_url}/query_by_standard.rbt", params=search_params, cookies=cookies, data=data, timeout=1, ) fetch_id = BeautifulSoup(search_response.text, "lxml").findAll("a")[0].get("id") except (IndexError, requests.exceptions.ReadTimeout): return fetch_params = {"quote_code": fetch_id} # Regular function iteration. for _ in range(retries): try: response = requests.get( f"{base_url}/word_attribute.rbt", params=fetch_params, cookies=cookies, timeout=timeout_amount, ) # Note that the full HTML of the page is response.text. entry_url = response.url if "quote_code" not in entry_url: entry_url = None return entry_url except (ConnectionError, requests.exceptions.ReadTimeout): logger.info("Timed out for variant search, trying again.") timeout_amount += 2 return entry_url
da5e5e77eda1eceea51353b30b518c06519fad9d
dmcnavish/adventOfCode
/advent_of_code/day5.py
803
3.65625
4
__author__ = 'davidmcnavish' from util import get_input def process_instructions(jumps, use_strange_jump=False): steps = 0 current_idx = 0 total_jumps = len(jumps) while current_idx < total_jumps: next_move = jumps[current_idx] if use_strange_jump and next_move >= 3: jumps[current_idx] -= 1 else: jumps[current_idx] += 1 current_idx += next_move steps += 1 return steps def main(): jumps_input = get_input('../input/day5.in') jumps = map(int, jumps_input) steps = process_instructions(jumps, False) print "part1 steps: " + str(steps) jumps = map(int, jumps_input) steps = process_instructions(jumps, True) print "part2 steps: " + str(steps) if __name__ == "__main__": main()
c37c206e3f151d4f32742604a24209182aa8864c
geryglez777/personal-budget-calculator
/personal_budget_calc.py
373
3.84375
4
item_dict = {} def data_entry(): item = '' cost = 0.0 end_entry = '' while end_entry[0:1].lower() <> 'y': item = input('Enter Item: '\n) cost = input('Enter Cost for: {}\n'.format(item)) end_entry = input('Would you like to add another item, y/n\n') return item, cost data_entry() print('This is {}, {}'.format(item, cost))
18d042cf54ea62744b7123a97d89d121cd7af889
eugenemonnier/data-structures-and-algorithms
/code_challenges/insertion_sort/insertion_sort.py
264
3.96875
4
def insertion_sort(arr): for index, num in enumerate(arr): idx = index while idx > 0 and num < arr[idx - 1]: arr[idx] = arr[idx - 1] idx -= 1 arr[idx]= num return arr print(insertion_sort([2,3,5,7,13,11]))
c2df88b5db78abb930acafb4af0f9649ac5612d8
eugenemonnier/data-structures-and-algorithms
/code_challenges/get_edges/get_edges.py
329
3.546875
4
from code_challenges.breadth_first_graph.breadth_first_graph import BFG class GE(BFG): def get_edges(self, node_a, node_b): neighbor_list = self.adj_map.get(node_a) for neighbor in neighbor_list: if neighbor['node'] == node_b: return 'true, ' + str(neighbor['weight']) return 'false, 0'
4d0444b4b444424d6587b0b55e935857cc69953a
Louis-Mont/Sudoku
/Core/utils.py
441
3.625
4
def sq_o(n): return (n // 3) * 3 def tryremove(c, v): try: c.remove(v) except ValueError: pass except KeyError: # TODO : Not Good Sudoku pass return c def rm_coll(r_items, items): """ :param r_items: the items you want to be removed from the list :param items: the list where the items are removed """ for i in r_items: tryremove(items, i) return items
9cf29f133f30226c91d3a462366ead5e6d0eca18
geekmichael/python-learning
/mindstorms.py
3,006
4.15625
4
import turtle def initWindow(title = "Welcome to the turtle zoo!", bgColor = "white", delay = 10): # Initialises the window for drawing window = turtle.Screen() window.setup(width=600, height=500, startx=0, starty=0) window.title(title) window.bgcolor(bgColor) # Slow down the drawing speed window.delay(delay) return window def initTurtle(shape = "turtle", strokeColor = "darkgreen"): # Initialises the turtle # Shape, size and strokeColor brad = turtle.Turtle() brad.shape(shape) brad.color(strokeColor) return brad def moveTurtle(myTurtle, x = 0, y = 0): myTurtle.penup() myTurtle.setpos(x, y) myTurtle.pendown() def draw_shape(myTurtle, shape = "line", length = 10, strokeColor = "blue", fillColor = ""): currentHeading = myTurtle.heading() myTurtle.color(strokeColor) if (fillColor): myTurtle.fillcolor(fillColor) myTurtle.fill(True) if shape == "square": for i in range(4): myTurtle.forward(length) myTurtle.right(90) elif shape == "circle": myTurtle.circle(length) elif shape == "triangle": # After 3 times back to the start point for i in range(3): myTurtle.left(120) myTurtle.forward(length) elif shape == "rhombus": for i in range(4): myTurtle.forward(length) myTurtle.right(60 + 60 * (i % 2)) else: # draw a line as default myTurtle.forward(length) myTurtle.fill(False) myTurtle.setheading(currentHeading) def draw_flower(myTurtle, shape, length = 10, petals = 36, strokeColor = "red"): myTurtle.speed("fastest") angle = 360 / (petals) for i in range(1, petals + 1): draw_shape(myTurtle, shape, length, strokeColor) myTurtle.right(angle) # Reset Turtle's heading to the south myTurtle.setheading(270) myTurtle.speed("slowest") myTurtle.forward(150) def draw_pyradmin(myTurtle, shape, edge = 100, length = 5, strokeColor = "black", fillColor = "yellow"): preEdge = edge newEdge = edge / 2 for i in range(1,4): if (newEdge <= length): newEdge = 2 * newEdge preEdge = 2 * preEdge break draw_shape(myTurtle, "triangle", newEdge) draw_pyradmin(myTurtle, "triangle", newEdge, length) myTurtle.left(120) myTurtle.forward(preEdge) myWindow = initWindow() myTurtle = initTurtle() moveTurtle(myTurtle, -200, 0) # A flower with 36 rhombuses draw_flower(myTurtle, "rhombus", 30, 36, "red") # A flower with 18 triangles moveTurtle(myTurtle, -100, 0) draw_flower(myTurtle, "triangle", 30, 18, "green") # A flower with 72 squares moveTurtle(myTurtle, 50, 0) draw_flower(myTurtle, "square", 50, 72, "blue") # A pyradmin myTurtle.speed("fastest") myTurtle.setheading(0) moveTurtle(myTurtle, 250, -50) draw_pyradmin(myTurtle, "triangle", 100, 5, "black", "yellow") # Click the window to exit myWindow.exitonclick()
ee5f15707242184f822ab27a6e05f93b3c296344
thiagocosta-dev/Gerador_senha_simples
/senha_para_filas.py
806
4.125
4
# AUTOR: Thiago Costa Pereira # Email: thiago.devpython@gmail.com print('=-' * 20) print('-- GERADOR DE SENHA --'.center(40)) print('=-' * 20) senhas_comuns = [0] senhas_pref = [0] while True: print() print('--' * 20) print('[1] SENHA COMUM') print('[2] SENHA PREFERENCIAL') print('[3] SAIR') print() senha = int(input('Escolha sua senha: ')) print('--' * 20) print() if senha == 1: senhas_comuns.append(int(senhas_comuns[-1]) + 1) print(f'Sua senha é: Senha Comum {senhas_comuns[-1]}') elif senha == 2: senhas_pref.append(int(senhas_pref[-1]) + 1) print(f'Sua senha é: Senha Preferencial {senhas_pref[-1]}') elif senha == 3: print('<< FINALIZADO >>') break else: print('ERRO! Digite um valor válido.') print()
485a5ce7d9571ba75380e4ec104873ab981ef331
adhansu/Calculator
/FinalCalc.py
3,506
3.8125
4
from tkinter import * root = Tk() root.geometry('500x500+450+150') root.title('Calculator') root.config(bg='#223441') root.resizable(width=False, height=False) def button_click(number): enter.insert(END, number) def button_clear(): enter.delete(0, END) def button_add(): first_number = enter.get() global f_num global math math = "addition" f_num = int(first_number) enter.delete(0, END) def button_equal(): second_number = enter.get() enter.delete(0, END) if math == "addition": enter.insert(0, f_num + int(second_number)) if math == "subtraction": enter.insert(0, f_num - int(second_number)) if math == "multiplication": enter.insert(0, f_num * int(second_number)) if math == "division": enter.insert(0, f_num / int(second_number)) def button_sub(): first_number = enter.get() global f_num global math math = "subtraction" f_num = int(first_number) enter.delete(0, END) def button_mul(): first_number = enter.get() global f_num global math math = "multiplication" f_num = int(first_number) enter.delete(0, END) def button_div(): first_number = enter.get() global f_num global math math = "division" f_num = int(first_number) enter.delete(0, END) enter = Entry(root, width=60, font=('arial', 8, 'bold'), borderwidth=5) enter.grid(row=0, column=0, columnspan=4, padx=10, pady=10) button_1 = Button(root, text="1", font=14, padx=40, pady=30, command=lambda : button_click(1)) button_2 = Button(root, text="2", font=14, padx=40, pady=30, command=lambda : button_click(2)) button_3 = Button(root, text="3", font=14, padx=40, pady=30, command=lambda : button_click(3)) button_4 = Button(root, text="4", font=14, padx=40, pady=30, command=lambda : button_click(4)) button_5 = Button(root, text="5", font=14, padx=40, pady=30, command=lambda : button_click(5)) button_6 = Button(root, text="6", font=14, padx=40, pady=30, command=lambda : button_click(6)) button_7 = Button(root, text="7", font=14, padx=40, pady=30, command=lambda : button_click(7)) button_8 = Button(root, text="8", font=14, padx=40, pady=30, command=lambda : button_click(8)) button_9 = Button(root, text="9", font=14, padx=40, pady=30, command=lambda : button_click(9)) button_0 = Button(root, text="0", font=14, padx=40, pady=30, command=lambda : button_click(0)) button_add = Button(root, text="+", font=14, padx=40, pady=30, command=button_add) button_subtract = Button(root, text="-", font=14, padx=40, pady=30, command=button_sub) button_multiply = Button(root, text="*", font=14, padx=40, pady=30, command=button_mul) button_division = Button(root, text="/", font=14, padx=40, pady=30, command=button_div) button_equals = Button(root, text="=", font=14, padx=40, pady=30, command=button_equal) button_clear = Button(root, text="C", font=14, padx=40, pady=30, command=button_clear) # put the buttons on the screen button_1.grid(row=3, column=0) button_2.grid(row=3, column=1) button_3.grid(row=3, column=2) button_4.grid(row=2, column=0) button_5.grid(row=2, column=1) button_6.grid(row=2, column=2) button_7.grid(row=1, column=0) button_8.grid(row=1, column=1) button_9.grid(row=1, column=2) button_0.grid(row=4, column=1) button_add.grid(row=4, column=3) button_subtract.grid(row=3, column=3) button_multiply.grid(row=2, column=3) button_division.grid(row=1, column=3) button_equals.grid(row=4, column=2) button_clear.grid(row=4, column=0) root.mainloop()
44faead1ab49742364d7e795c81aee7829517e81
Ironeer/ProgrammingTasks
/Python/expert/multiprocessing/primParallel.py
4,465
3.515625
4
import os import math import time from multiprocessing import Process,Queue,Manager def timed(function): '''timing decorator''' def wrapper(*args, **kwargs): # we don't know about arguments... start = time.time() result = function(*args, **kwargs) # ...so we just pass what we got runtime = time.time() - start print('%s took %s seconds' % (function.__name__, runtime)) return result return wrapper @timed def turbo(LIMIT): '''super turbo version''' result = [] for number in range(2, LIMIT): isprime = True for divisor in result: # we only have to check for prime numbers! if divisor ** 2 > number: # we can also stop checking here! break # such divisors cannot occur in factorization if number % divisor == 0: isprime = False break # we can stop checking here! if isprime: result.append(number) return result def turboNoTime(LIMIT): '''super turbo version''' result = [] for number in range(2, LIMIT): isprime = True for divisor in result: # we only have to check for prime numbers! if divisor ** 2 > number: # we can also stop checking here! break # such divisors cannot occur in factorization if number % divisor == 0: isprime = False break # we can stop checking here! if isprime: result.append(number) return result def turboRange(bekannte_prims,start,limit,num): '''super turbo version''' result = [] for number in range(start, limit): isprime = True for divisor in bekannte_prims: # we only have to check for prime numbers! if divisor ** 2 > number: # we can also stop checking here! break # such divisors cannot occur in factorization if number % divisor == 0: isprime = False break # we can stop checking here! if isprime: bekannte_prims.append(number) result.append(number) return_vals[num] = result return result @timed def turboPrallel(limit): needed_prims = int(math.ceil(math.sqrt(limit))) bekannte_prims = turboNoTime(needed_prims) start = len(bekannte_prims) process_count = 10 missing_prim_count = start prims_per_process = int(math.floor((limit - missing_prim_count) / process_count)) processes=[] for i in range(0,process_count): if i == process_count-1: processes.append(Process(target=turboRange,args = (bekannte_prims, start,int(limit),i))) break processes.append(Process(target=turboRange,args = (bekannte_prims, start,start+prims_per_process,i))) start+=prims_per_process for i in range(0,process_count): processes[i].start() for i in range(0,process_count): processes[i].join() bekannte_prims.extend(return_vals[i]) return bekannte_prims @timed def sumMethod(n): prim = [2,3] primSum = [0,0]; check = 5 while check <n: primIndex=0 bound = math.sqrt(check) #print("Check:"+str(check)) while prim[primIndex] <= bound: #print("Test:"+str(prim[primIndex])) if primSum[primIndex] == check: #print("=>teilbar durch"+str(prim[primIndex])+"\n") break elif primSum[primIndex] > check: #print("->nicht teilbar durch"+str(prim[primIndex])) primIndex+=1 continue else: while primSum[primIndex]< check: primSum[primIndex] += prim[primIndex] #print("PrimSum:"+str(primSum[primIndex])) if primSum[primIndex] == check: break if primSum[primIndex] > check: #print("->nicht teilbar durch"+str(prim[primIndex])) primIndex+=1 break else: prim.append(check); #print("=>Primzahl"+"\n") primSum.append(check) check+=1 return prim manager = Manager() return_vals = manager.dict() limit = input("Obere Schranke fuer Primzahlenberechnung eingeben") turboPrallel(limit) turbo(limit) sumMethod(limit)
c17c07f5a342dca4d8d895f27b775185762682b2
xingyue1124/py-test
/test/士兵射击.py
1,960
3.984375
4
# 二、需求: # 1)士兵瑞恩有一把AK47 # 2)士兵可以开火(士兵开火扣动的是扳机) # 3)枪 能够 发射子弹(把子弹发射出去) # 4)枪 能够 装填子弹 --增加子弹的数量 class Gun: # 创建构造方法,给对象的属性赋值(型号,弹夹中子弹数目) def __init__(self,model,bullet_count): self.model = model self.bullet_count = bullet_count # 自定义实例输出方法,替换默认的输出操作 def __str__(self): return "%s,它还有%d颗子弹" %(self.model,self.bullet_count) # 创建实例方法,若弹夹中子弹为0输出无子弹,若不为0则数量递减 def shoot(self): if self.bullet_count == 0: print("没有子弹了!!!") return else: self.bullet_count -= 1 print("正在射击...已经射中目标!") return # 创建实例方法,填充子弹 def add_bullet(self,count): self.bullet_count += count print("已经填充了%d颗子弹" % count) return class Soldier: # 创建构造方法,给对象的属性赋值(士兵姓名) def __init__(self,name): self.name = name self.gun = None # 士兵目前没枪,Null是一个类,代表空 # 自定义实例输出方法,替换默认的输出操作 def __str__(self): return "%s有一把%s" % (self.name,self.gun) # 创建实例方法,射击 def fire(self): if self.gun == None: print(f'{self.name}没有枪支!!!') return else: self.gun.add_bullet(10) # 给枪填充10颗子弹 self.gun.shoot() # 射击 return B = Gun("ak47",30) # 将枪实例化,ak47且有30颗子弹 A = Soldier("瑞恩") # 将士兵实例化 A.gun = B # 将实例化的枪给士兵 # 调用实例方法 A.fire() print(A)
879ea4bff00a9594f284cb1f4325762ba6e241af
brunokiyoshi/Nanodegree-MLE-capstone-project
/train/model.py
1,190
3.5
4
import torch.nn as nn import torch class LSTM(nn.Module): """ This is the simple RNN model we will be using to perform Financial Time-series Analysis. """ def __init__(self, input_dim, hidden_dim, num_layers, output_dim): """ Initialize the model by settingg up the various layers. """ super(LSTM, self).__init__() self.hidden_dim = hidden_dim self.num_layers = num_layers self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True, dropout=0.2) self.fc = nn.Linear(hidden_dim, output_dim) def forward(self, x): """ Perform a forward pass of our model on some input. """ # Initialize hidden state with zeros device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_().to(device) # Initialize cell state c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_().to(device) out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach())) out = self.fc(out[:, -1, :]) return out
383f97c5f7b3964fd73f85177a2232b303563f7f
lumafragoso/Funcoes_Analise_Funcao_Randint
/main.py
501
3.671875
4
import random def principal(): lista = [] inicial = int(input('Inteiro inicial do intervalo? ')) final = int(input('Inteiro final do intervalo? ')) n = int(input('Quantidade de escolhas? ')) for i in range(n): elemento = random.randint(inicial, final) lista.append(elemento) for j in range(inicial, final+1): print('{} - {}'.format(j, quantidadeNumeros(lista,j))) def quantidadeNumeros(lista, j): quant = lista.count(j) return quant principal()
023ce95c7722201b119e0e049201c5bc56365837
dlftls38/college
/python/sumrange.py
513
3.625
4
def sumrange(m,n): if m<n: return n+sumrange(m,n-1) elif m==n: return m else: return 0 return sumrange(m,n) def sumrange2(m,n): sum=0 while m<=n: sum = n + sum n = n-1 return sum #교수님이 한 방법 def sumrange3(m,n): if m <= n: return m + sumrange(m+1,n) else: return 0 def sumrange4(m,n): sum = 0 while m <= n: sum = sum + m m = m + 1 return sum
beeb7a8ffd745aadadca0ca356f3c2ad5a605b07
dlftls38/college
/python/fill_Triangle.py
1,264
3.609375
4
from tkinter import* tk = Tk() canvas = Canvas(tk, width=210, height=210) canvas.pack() canvas.create_polygon(10,10,50,10,50,50,fill="red",outline='black') canvas.create_polygon(50,10,100,10,50,50,fill="yellow",outline='black') canvas.create_polygon(100,10,150,10,150,50,fill="green",outline='black') canvas.create_polygon(150,10,200,10,150,50,fill="purple",outline='black') canvas.create_polygon(10,50,50,50,50,100,fill="gold",outline='black') canvas.create_polygon(50,50,100,50,50,100,fill="silver",outline='black') canvas.create_polygon(100,50,150,50,150,100,fill="blue",outline='black') canvas.create_polygon(150,50,200,50,150,100,fill="pink",outline='black') canvas.create_polygon(10,100,50,100,50,150,fill="red",outline='black') canvas.create_polygon(50,100,100,100,50,150,fill="yellow",outline='black') canvas.create_polygon(100,100,150,100,150,150,fill="green",outline='black') canvas.create_polygon(150,100,200,100,150,150,fill="purple",outline='black') canvas.create_polygon(10,150,50,150,50,200,fill="gold",outline='black') canvas.create_polygon(50,150,100,150,50,200,fill="silver",outline='black') canvas.create_polygon(100,150,150,150,150,200,fill="blue",outline='black') canvas.create_polygon(150,150,200,150,150,200,fill="pink",outline='black')
a2568e0e474ef4de9bc33af502fd30f89782e72b
Spaqin/AAL-2017L
/datastructures/treasure.py
318
3.78125
4
class Treasure(object): def __repr__(self): return self.__str__() def __str__(self): return "value: {} size: {}, city: {}".format(self.value, self.size, self.city) def __init__(self, value=0, size=0, city=None): self.value = value self.size = size self.city = city
e50da950e23d03141c4e4f548ac23e6feec49748
James-Cristini/bot_o_matic
/src/utils.py
2,307
3.984375
4
from __future__ import print_function from builtins import input import os import pickle def clear_console(): """ Simply runs the clear/cls command on the console to make it easier to read what is going on. """ os.system('cls' if os.name == 'nt' else 'clear') def press_enter_to_continue(): """ Simply 'pauses' the console and waits for user to hit enter to continue. """ input('\nPress enter to continue\n') def get_user_choice(choices_dict, message="Please choose from the list of optiions."): """ Takes in an 'enumerated' dict object (preferably an OrdereDict), lists the choices then gets (and validates) the user's input. returns the chosen key and value from the dict. """ # Breaks only when a valid choice is made via returning it while True: print(message) # Print out the key/value pairs for a user to choose from for k, v in choices_dict.items(): print('{0} : {1}'.format(k, v)) # Accept user input to be evaluated below choice = input('Your choice: ') try: # Check that the input matches a key in the choices dict choices_dict[choice] except KeyError: # If it is not a valid selection, let the user know and let the loop continue clear_console() print('*** Not a valid option! ***\n') else: # Return a valid choice return choice, choices_dict[choice] def load_from_pickle(fn='robot_save.pkl'): """ Loads objects from pickle file and stores them in a list to send back. """ # List to store all saved robot objects objs = [] with open(fn, 'rb') as pkl_file: # Iterate through and load all objects until EOF (signifies no more objects to load) while pkl_file: try: r = pickle.load(pkl_file) objs.append(r) except EOFError: break return objs def save_to_pickle(objs, fn='robot_save.pkl'): """ Saves a list of objects to a pickle file. """ # Dump each object in the list to the .pkl with open(fn, 'wb') as pkl_file: for obj in objs: pickle.dump(obj, pkl_file, protocol=2) return True # Not necessary but could leverage the return value to confirm success
580c275bc2bd3394aae13f831d36e0b588bc2024
MariomcgeeArt/CS2.1-sorting_algorithms-
/iterative_sorting2.py
2,069
4.34375
4
#funtion returns weather items are sorted or not boolean #creating the function and passing in items def is_sorted(items): # setting variable copy to equal items copy = items[:] #calling sort method on copy copy.sort() # if copy is equal to items it returns true return copy == items def bubble_sort(items): #set is sorted to true is_sorted = True # set a counter to 0 counter = 0 # while items_is_sorted we want to then change is sorted to false while(is_sorted): #set is sorted to false is_sorted = False # this is the for loop to loop trhough the items for i in range(len(items) - counter - 1): #if the item we are looking at is larger thane the item to its right we want to swap them if items[i] > items[i+1]: # swap the items positioins items[i], items[i+1] = items[i+1], items[i] # is sorted now becomes troue is_sorted = True # incremantation of the counter to move though the array counter += 1 def selection_sort(items): #finding the minimum item and swaping it with the first unsorted item and repeating until all items are in soreted order #for loop to loop throught the items items_length = range(0, len(items)-1) for i in items_length: #set min value to i min_value = i #nested for loop to set j value for j in range(i+1, len(items)): if items[j] < items[min_value]: min_value = j items[min_value], items[i] = items[i], items[min_value] return items def insertion_sort(items): item_length = range(1, len(items)) for i in item_length: #element to be compared unsorted_value = items[i] #comparing the current element with the sorted portion and swapping while items[i-1] > unsorted_value and i > 0: items[i], items[i-1] = items[i-1], items[i] i -= 1 #returning items return items
c02fe6cb5e797f479d276743eab662a55f8160b3
Roberto117/twenty-one
/twenty-one.py
8,309
3.828125
4
from Player.player import Player from Deck.deck import Deck from Player.hand import Hand players = []#list to store the players currently playing deck = Deck()#The Deck being used for the game bank = Hand("Bank")#the bank HIT_INPUT = "H" STAND_INPUT = "S" SPLIT_INPUT = "$" def addPlayers(): #add new players to the game num_of_players = 0 while num_of_players <1 or num_of_players > 3: #get the number of players being added try: num_of_players = int(input("How many players will play today? 1-3:")) if num_of_players <1 or num_of_players > 3: print("Invalid number of players") except ValueError: print("Not a Number!") #create all new players for new_player in range(num_of_players): createPlayer() def createPlayer(): #create a new player money = 0 new_player = Player("P"+ str(len(players)+1))#create a player with a new label while money <= 0: #set the money on the player try: money = int(input("How much money does %s have " % new_player.label)) #get input from the user if new_player.setMoney(money):break#try to put the money in the Player Objecet if it meets parameters except ValueError: print("Not a Number!")#money value must be some integer players.append(new_player) def play(): firstPass() while checkIfCanPlay(): # if there is at least one player that has a not busted or standing hand the game continues for player in players: playersTurn(player)#do the players turn if not checkIfCanPlay(): if haveStandingPlayer(): banksTurn() if bank.isBusted(): bankBusted() else: bankStanding() else: allPlayerslose() playAgain() def firstPass(): #the first pass when the game will deal one card to each player deck.shuffle() print("Dealing cards to all players\n") for player in players: #deal each player a card hit(player.hands[0]) print(playerStatusString(player)) askForBets()#Ask the players for bets def playerStatusString(player, hand = None): #get the player and all their hands status string = "-"*40 +"\n" string +=str(player) + "\n" if hand == None: for h in player.hands: string+= "\n"+str(h) else: string += "\n" + str(hand) return string def askForBets(): #make each player make a bet for player in players: makeBet(player) def makeBet(player): bet = 0 # the bet the player will make print(playerStatusString(player)) while True: try: bet = int(input("%s how much will you bet? if you bet 0 you won't play this round:" %player.label))#ask for input if player.makeBet(bet):break #if the bet mets all constrains we can break out of the loop except ValueError: print("Invalid Number!") def checkIfCanPlay(): for player in players: if player.havePlayableHand(): return True return False def playersTurn(player): #the players turn where they can choose their next action if not player.havePlayableHand(): return #if the player does not have any avaiable hand to play the player is unavailable for hand_index ,hand in enumerate(player.hands): if not hand.atPlay():continue #if the hand is busted or standing then we skip this hand print(playerStatusString(player, hand)) i = getPlayerInput(hand) #do the action ask by the player if i == HIT_INPUT: hit(hand) print(playerStatusString(player,hand)) print("HIT") if(hand.isBusted()):print("Busted!") elif i == STAND_INPUT: print(playerStatusString(player,hand)) stand(hand) print("STAND") elif i == SPLIT_INPUT: player.split(hand_index) print(playerStatusString(player,hand)) print("SPLIT") else:print("Invalid Input!") def getPlayerInput(hand): #get the player input based on the hands content input_string = "What would you like to do?\n | %s: Hit | %s: Stand |" %(HIT_INPUT, STAND_INPUT) i = "" if hand.hasPair(): #if the hand has a pair give the player the choice to split input_string += "%s: Split |\n" %SPLIT_INPUT #if the hand has a pair the player can split this hand: while True: i = input(input_string).upper() if i not in [HIT_INPUT, STAND_INPUT, SPLIT_INPUT]: #if the input is not valid announce it to the player print("Invalid input") else: break else: input_string += "\n" while True: i = input(input_string).upper() if i not in [HIT_INPUT, STAND_INPUT]: #if the input is not valid announce it to the player print("Invalid input") else: break return i def hit(hand): hand.hit(deck.deal())#deal the hand a new card def stand(hand):#simple function to make a hans"stand" hand.stand() def haveStandingPlayer(): #returns true if there is at least one player with a hand standing for player in players: if player.isStanding(): return True return False def banksTurn(): #play the banks turn while bank.atPlay(): hit(bank)#hit the bank #if the banks value is over or equal to 17 the bank stansa if bank.value >= 17 and not bank.isBusted(): stand(bank) print(bank) print("-"*40) def bankBusted(): #if the bank does not play this round, the winner is determined by who is left standing for player in players: if player.bet == 0: continue if player.isStanding(): player.win() else: player.lose() print(playerStatusString(player)) def bankStanding(): for player in players: if player.bet == 0: continue compareAgainstBank(player) def compareAgainstBank(player): #check if there is at least one hand that wins against the bank for hand in player.hands: print(playerStatusString(player, hand)) if handWinsAgainstBank(hand): player.win() return player.lose() def handWinsAgainstBank(hand): #compare a hand with the bank to determine if player won if hand.isBusted(): print("Hand is Busted.") return False elif hand.value == bank.value: #if players hand has the same value as the bank, this hand loses print("Hand %s scored the same as the bank" % hand.label) return False elif hand.value < bank.value: #if the player has a lower value than the bank, this hand loses print("Hand %s scored lower than the bank" %hand.label) return False elif hand.value > bank.value: #if the player has a higher value than the bank, the player wins print("Hand %s scored Higher than the bank!" %hand.label) return True return False def resetGame(): #reset all players to their starting positions for player in players: player.reset() bank.reset() deck.reset() def allPlayerslose(): for player in players: if player.bet == 0: continue print(playerStatusString(player)) player.lose() def playAgain(): #ask the players if they will like to play again #if yes then all players hands get reset and the everyone is dealt one card while True: i = input("Would You like to play again? Y: yes | N: no|\n").upper() if i =="Y": resetGame() print(bank) firstPass() return True elif i == "N": return False def game_exit(): print('Thank you for playing, hope to see you soon!') exit() def main(): print("-------------Welcome to Twenty One-------------") addPlayers() play() game_exit() if __name__ == "__main__": main()
0c9b2ce66f583d96d5f8aa5dba43f3c17a73dd4a
igorsteinmacher/pythonCI_class
/v0/prime.py
198
3.921875
4
def is_prime(number): if (not type(number) is int): return False if (number <= 1): return False for element in range(2,number): if (number % element == 0): return False return True
d55991c851bb45a0bb03a9ddee2eacee52e8c934
shanico91/Gene_Block_data_mining_in_bacterial_genomes
/tree_node.py
724
3.640625
4
class TreeNode: def __init__(self, name_value, num_occur, parent_node): self.name = name_value # gene cog number self.count = num_occur # in how many genomes this gene appeared in a valid window self.parent = parent_node self.children = {} self.last_update = 0 # the last genome that updated this node in the creation of the tree # increments the count variable with a given amount def inc(self, num_occur): self.count += num_occur # display tree in text. Useful for debugging. def disp(self, ind=1): print(' ' * ind, self.name, ' ', self.count) for child in self.children.values(): child.disp(ind + 1)
527694235d23a867f3d195b18db55b53ec167bd4
jdjake/CompetitiveProgramming
/Euler/40_champernownes_constant.py
214
3.578125
4
listed = [] x = 0 while len(listed) < 1000101: for digit in list(str(x)): listed.append(digit) x += 1 product = 1 i = 1 while i < 10000000: product*=int(listed[i]) i *= 10 print(product)
dde799471aedad88a2e5ec0a79dbf586d2f9fa8e
jdjake/CompetitiveProgramming
/Euler/31_coin_sums.py
509
3.8125
4
coin_sum_hash = {} british_coins = (1,2,5,10,20,50,100,200) def coin_sum(amount, coins): if (amount, coins) in coin_sum_hash.keys(): return coin_sum_hash[(amount, coins)] if (amount == 0): return 1 elif (not coins): return 0 current = coins[0] possible = [coin_sum(amount - current*x, coins[1:]) for x in range(0,amount//current + 2)] coin_sum_hash[(amount, coins)] = sum(possible) return coin_sum_hash[(amount, coins)] print(coin_sum(200, british_coins))
b40a434cf49126560b59272992e223eed3b78d22
ppfenninger/ToolBox-WordFrequency
/frequency.py
1,918
4.21875
4
""" Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string from pickle import load, dump def getWordList(fileName): """ Takes raw data from project Gutenberg and cuts out the introduction and bottom part It also tranfers the entire text to lowercase and removes punctuation and whitespace Returns a list >>> s = 'A***H ***1234@&().ABCab c***' >>> f = open('text.txt', 'w') >>> dump(s, f) >>> f.close() >>> get_word_list('text.txt') ['abcab', 'c'] """ inputFile = open(fileName, 'r') text = load(inputFile) l = text.split('***') #marker for stop and end of text in gutenberg try: #returns none in case there is something strange with the project gutenberg text mainText = l[2] #main text is the third block of text except: return None mainText = mainText.lower() #changes everything to lowercase mainText = mainText.replace("\r\n", "") mainText = mainText.translate(string.maketrans("",""), string.punctuation) #removes punctuation mainText = mainText.translate(string.maketrans("",""), string.digits) #removes numbers mainList = mainText.split() return mainList def getTopNWords(wordList, n): """ Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring. word_list: a list of words (assumed to all be in lower case with no punctuation n: the number of words to return returns: a list of n most frequently occurring words ordered from most frequently to least frequently occurring """ d = {} for word in wordList: d[word] = d.get(word, 0) d[word] += 1 l = [] for i in d: l.append((d[i], i)) l.sort(reverse = True) mostCommon = l[0:(n-1)] words = [x[1] for x in mostCommon] return words if __name__ == "__main__": # import doctest # doctest.testmod() l1 = getWordList('odyssey.txt') l2 = getTopNWords(l1, 100) print l2
a6cfc0ffa58b6d4c86b5148e0c7807de9c02f018
LeehXD/Python-Basic
/Exercicios Basicos Python/Exercicio 13.py
268
3.703125
4
nome = input('Digite seu nome:') salario = float(input('Digite seu salário R$')) resultado = salario + (salario * 15 / 100) print('Sr(a){}\n' 'Parabéns ouve um aumento de 15% em seu salário.\n' 'Salário atualizado R${}' .format(nome,resultado))
211156d74abe03579f4d44b0201d4837cce8c25b
Masachusets/Tuples
/tuples.py
238
3.6875
4
def tupl(a): b = [] for i in range(0, len(a)): if i % 2 == 0: b.append(a[i] * 2) else: b.append(a[i] - 2) b = tuple(b) print(b) a = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0) tupl(a)
4785fc7a6bfb4111687fe2b21a41a08b2b353ea1
lucas54neves/algorithms-in-python
/src/trees/binary_search_tree.py
2,042
3.671875
4
class BinarySearchTree(): def __init__(self, root_value): self.root = Node(root_value) def add_node(self, value): node = Node(value) if self.root is None: self.root = node else: old_node = self.root current_node = old_node.left if node.value <= old_node.value else old_node.right while current_node is not None: old_node = current_node current_node = current_node.left if node.value <= current_node.value else current_node.right if node.value <= old_node.value: old_node.left = node else: old_node.right = node return True @property def height(self): return self.root.height() def search_value(self, value): return self.root.search_value(value) def in_order(self): return self.root.in_order() class Node(): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def __repr__(self): return str(self.value) def search_value(self, value): if value == self.value: return True if value <= self.value: return self.left.search_value(value) if self.left is not None else False return self.right.search_value(value) if self.right is not None else False def height(self): height_left = self.left.height() if self.left is not None else 0 height_right = self.right.height() if self.right is not None else 0 return max(height_left, height_right) + 1 def in_order(self): list_in_order = [] if self.left is not None: list_in_order.extend(self.left.in_order()) list_in_order.append(self.value) if self.right is not None: list_in_order.extend(self.right.in_order()) return list_in_order
c127da0e7bf2078aa65dfcbec441b1c6dd6e7328
Habibur-Rahman0927/1_months_Python_Crouse
/Python All Day Work/05-05-2021 Days Work/Task_2_error_exception.py
2,582
4.34375
4
# Python Error and Exception Handling """ try: your code except: message """ # try: # with open('test.txt', mode='r') as open_file: # openFlie = open_file.read() # print(data) # except: # print("File is not found") # print('Hello, its working') """ try: your code except ExceptionName: your message """ # try: # with open('test.txt', mode='r') as my_new_file: # data_file = my_new_files.read() # print(data_file) # except NameError: # print('Name not found') # print('Hello, Its working.') """ try: your code except ExceptionName1: message except ExceptionName2: message """ # try: # with open('test.txt', mode='r') as my_file: # data = my_file.read() # print(data) # except NameError: # print('Name not found') # except FileNotFoundError: # print('Oops!!, File not found.') # print('Hello, Its working.') """ try: your code except (ExceptionName1, ExceptionName2...) message """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except (NameError, FileNotFoundError): # print('Errors Found! Please check') # print('Hello, Its working.') """ try: your code except ExceptionName as msg: msg """ # try: # with open('test.txt', mode='r') as my_new_file: # print('Yes') # data = my_new_file.read() # print(data) # except FileNotFoundError as msg: # print(msg) # print('Please ensure that required file is exist') # print('Hello, Its working.') """ try: your code except ExceptionName: message else: message """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except FileNotFoundError: # print("File not found.") # else: # print('No errors found :') # print('Hello, Its working.') """ try: your code except ExceptionName: message else: message finally: your code """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except FileNotFoundError: # print(" File not found.") # else: # print('No errors found :') # finally: # print('Finally') # print('Hello, Its working.') """ try: raise NameError('Hello, It is user defined error msg.') except NameError as msg: message """ try: raise NameError('Hello, It is user defined error msg.') except NameError as msg: print(msg)
e3c9317f8306debacbe45ddee534ee74aad30723
Habibur-Rahman0927/1_months_Python_Crouse
/Python All Day Work/23-05-2021 Days Work/OOP_1.py
3,661
3.96875
4
""" Syntax: class Pencil: <statement-1> . . . <statement-N> Properties of class: class ClassName: ''' This class or design help us to create a pencil ''' Attributes - Variables Behabiours - Methods (Functions) Pillar of OOP: - Class & Object - Discussion topic - Abstruction - Private and Public - Encapsulation - Polymorphism - Inheritance """ # # Design/Class for Pencil Object # class Pencil: # """ This class is designed for creating pens """ # # Attributes - Variables # name = '' # color = '' # size = 0 # model = '' # # Methods # def write(self): # print('Writting something by this pencil is done!') # def erase(self): # print('Erased!') # def details(self): # print('%s\n%s\n%s\n%d' % (self.name, self.model, self.color, self.size)) # # Creating Pencils Objects # pencil_1 = Pencil() # pencil_1.name = 'Matador Pluto' # pencil_1.color = 'Blue' # pencil_1.size = 5 # pencil_1.model = 'HB' # pencil_1.details() # class Pen: # """ This class is designed for creating pen """ # name = '' # color = '' # model = '' # def write(self): # print('Writting something by this pen is done!') # def erase(self): # print('Erased!') # def details(self): # print('%s\n%s\n%s' % (self.name, self.model, self.color)) # pen_1 = Pen() # pen_1.name = 'Matador Pinpoint' # pen_1.color = 'green' # pen_1.model = 'Bolpen' # pen_1.details() # class Dog: # def __init__(self, name, age): # self.name = name # self.age = age # def bark(self): # print("bark bark!") # def doginfo(self): # print(self.name + " is " + str(self.age) + " years old.") # ozzy = Dog("Ozzy", 2) # ozzy.doginfo() # skippy = Dog("Skippy", 12) # skippy.doginfo() # filou = Dog("Filou", 8) # filou.doginfo() # class Dog: # def __init__(self, name, age): # self.name = name # self.age = age # def bark(self): # print("bark bark!") # def doginfo(self): # print(self.name + " is " + str(self.age) + " year(s) old.") # def birthday(self): # self.age +=1 # ozzy = Dog("Ozzy", 2) # print(ozzy.age) # ozzy.birthday() # print(ozzy.age) # ozzy.birthday() # print(ozzy.age) # class Dog: # def __init__(self, name, age): # self.name = name # self.age = age # def bark(self): # print("bark bark!") # def doginfo(self): # print(self.name + " is " + str(self.age) + " year(s) old.") # def birthday(self): # self.age +=1 # def setBuddy(self, buddy): # self.buddy = buddy # buddy.buddy = self # ozzy = Dog("Ozzy", 2) # filou = Dog("Filou", 8) # ozzy.setBuddy(filou) # print(ozzy.buddy.name) # print(ozzy.buddy.age) # print(filou.buddy.name) # print(filou.buddy.age) # class Snake: # def __init__(self, name): # self.name = name # def change_name(self, new_name): # self.name = new_name # python = Snake("python") # anaconda = Snake("anaconda") # print(python.name) # python # print(anaconda.name) # anaconda #our cls practice class Pencil: model = '2B' def __init__(self): self.name = 'Matador' self.color = 'Blue' def details(self): pass pencil_1 = Pencil() pencil_2 = Pencil() pencil_3 = Pencil() pencil_4 = Pencil() Pencil.model = '4B' print(pencil_4.name, pencil_4.color[3], pencil_4.model) print(pencil_1.name, pencil_1.color[2], pencil_1.model) #pencil_2.color = 'Yellow' print(pencil_2.name, pencil_2.color[1], pencil_2.model) print(pencil_3.name, pencil_3.color[0], pencil_3.model)
8d6d3111419da58aff1fac7ad9ca9068bc631c6b
Habibur-Rahman0927/1_months_Python_Crouse
/HackerRank problem solving/problem_no_1.py
377
4.0625
4
num = int(input()) if (1<num and num<100 or num>0): if (num%2)!= 0: print(num,"Weird") elif (num%2) == 0 : if (2<num and num<5): print(num,"Not Weird") elif (6<num and num<20): print(num,"Weird") elif num>20: print(num,"Not Weird") elif num>0: print(num,"Not Weird") else: print("Not weird")
466d6300151c9f00a57c9b10fbcea58fd9278149
Habibur-Rahman0927/1_months_Python_Crouse
/Python All Day Work/30-05-2021 Days Work/debugging.py
162
3.65625
4
def square(num): result = num**2 print(result) return def main(): for i in range(1, 11): square(i) if __name__=='__main__': main()
ebc54a6955ebe113dad58dd0eed16b3caff2ce89
Habibur-Rahman0927/1_months_Python_Crouse
/HackerRank problem solving/problem_no_6.py
1,101
4.21875
4
def leapYears(years): leap = False if(years%400 == 0): leap = True elif years%4 == 0 and years%100 != 0: leap = True return leap years = int(input()) print(leapYears(years)) """ years = int(input()) if (years%4 == 0): if(years%100 == 0): if(years%400 == 0): print("This years is leap year ") else: print("This years is not leap year") else: print("This years is not leap year") else: print("This years is not leap year") """ """ def leapYears(years): leap = False if (years%4 == 0): if(years%100 == 0): if(years%400 == 0): leap = True else: leap= False else: leap= False else: leap = False return leap years = int(input()) leapYears(years) """ """ def is_leap(year): leap = False if (year%4 == 0): leap = True if(year%100 ==0): leap = False if(year%400 == 0): leap = True return leap is_leap(year) year = int(input()) """
0263169bc533086f5e606db5f7d1ba8a2e65de2c
NeelRa/NR
/PRIME NUMBER.py
195
4.125
4
a=int(input("ENTER A NUMBER ")) for x in range(2,a): if a%x==0: print "IT IS A COMPOSITE NUMBER" break else: print "IT IS A PRIME NUMBER"
88a224e472293b2f74bb70282ef658a44d84e1a3
641i130/vocaloid-speech-generator
/create-save.py
1,372
3.5
4
""" _ _ _ | \ | | ___ | |_ ___ ___ _ | \| | / _ \ | __| / _ \ / __| (_) | |\ | | (_) | | |_ | __/ \__ \ _ |_| \_| \___/ \__| \___| |___/ (_) There are two possible ways we could go about solving this problem. We could make the user input a vpr file for the program to extract, edit then change ___ _ __ / _ \ | -___| | (_) | | | \___/ |_| We could get the program to create its own json file then compress it into its own folder, naming it as a .vpr file. The next problem would be to figure out how to make a monotone string of syllables into a realistic string of audio. Which would be easiest with ai. """ # First you need to generate a json file. # Then put it into a folder named Project. # Next you would add the contents to it that generates the speech. # Lastly you would compress the file and name the zip file as a .vpr file. This process is for Vocaloid 5 """ Example of a note or syllable for Vocaloid 5 """ """ { "lyric": "st", "phoneme": "a", "isProtected": false, "pos": 1920, "duration": 960, "number": 62, "velocity": 64, "exp": {"opening": 127}, "singingSkill": { "duration": 316, "weight": { "pre": 64, "post": 64 } }, "vibrato": { "type": 0, "duration": 0 } }, """ import json from zipfile import ZipFile