blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
d740fee3ec9d099fea72ed5f1306dcb0718f7160
childofthefence/ucsd-algo-python
/venv/fibonacci.py
698
3.828125
4
fib_nums = [0, 1] # place is how many fib numbers, starting at 1. The 10th fib number is thus 34 # indices in fib_nums stars at 0 so to get F19 would use something like fib_nums[19] # and would be the 20th fib number (despite 19 being the index) def calc_fib(place): if place == 0: return 0 elif place == 1: return 1 if place > 1: for vals in range(2, place): fib_nums.append(fib_nums[vals-1] + fib_nums[vals-2]) # print(fib_nums) return fib_nums[len(fib_nums)-1] x_val_pass = 1000 x = calc_fib(x_val_pass) x1 = fib_nums[(x_val_pass-1)] print('Calc fib to {}th place is {} and the index of {} val is {} '.format(x_val_pass, x, (x_val_pass-1), x1)) print(x == x1)
c6fd8cbfe4a6dca8fb433135460f25980a5f1798
dilawarm/TDT4171
/assignments/assignment5/neural_network_skeleton.py
10,061
4.125
4
# Use Python 3.8 or newer (https://www.python.org/downloads/) import unittest # Remember to install numpy (https://numpy.org/install/)! import numpy as np import pickle import os class NeuralNetwork: def __init__(self, input_dim: int, hidden_layer: bool) -> None: """ Initialize the feed-forward neural network with the given arguments. :param input_dim: Number of features in the dataset. :param hidden_layer: Whether or not to include a hidden layer. :return: None. """ # --- PLEASE READ -- # Use the parameters below to train your feed-forward neural network. # Number of hidden units if hidden_layer = True. self.hidden_units = 25 # This parameter is called the step size, also known as the learning rate (lr). # See 18.6.1 in AIMA 3rd edition (page 719). # This is the value of ฮฑ on Line 25 in Figure 18.24. self.lr = 1e-3 # Line 6 in Figure 18.24 says "repeat". # This is the number of times we are going to repeat. This is often known as epochs. self.epochs = 400 # We are going to store the data here. # Since you are only asked to implement training for the feed-forward neural network, # only self.x_train and self.y_train need to be used. You will need to use them to implement train(). # The self.x_test and self.y_test is used by the unit tests. Do not change anything in it. self.x_train, self.y_train = None, None self.x_test, self.y_test = None, None np.random.seed(0) # Setting random seed for reproducibility. self.weights, self.biases = None, None # Initializing weights and biases self.total_layers = ( None # Initializing the number of layers in the neural network. ) """ I have implemented the neural network as two lists, one with the weight matrices between each layer, and the other with the bias vectors. """ if hidden_layer: self.weights = [ np.random.randn(self.hidden_units, input_dim), np.random.randn(1, self.hidden_units), ] self.biases = [np.random.randn(self.hidden_units, 1), np.random.randn(1, 1)] self.total_layers = 3 else: self.weights = [np.random.randn(1, input_dim)] self.biases = [np.random.randn(1, 1)] self.total_layers = 2 self.sigmoid = lambda x: 1.0 / ( 1.0 + np.exp(-x) ) # The sigmoid activation function: 1 / (1 + e^(-x)) self.sigmoid_derivative = lambda x: self.sigmoid(x) * ( 1 - self.sigmoid(x) ) # The derivative of the sigmoid activation function to be used in the backpropagation algorithm. def load_data( self, file_path: str = os.path.join(os.getcwd(), "data_breast_cancer.p") ) -> None: """ Do not change anything in this method. Load data for training and testing the model. :param file_path: Path to the file 'data_breast_cancer.p' downloaded from Blackboard. If no arguments is given, the method assumes that the file is in the current working directory. The data have the following format. (row, column) x: shape = (number of examples, number of features) y: shape = (number of examples) """ with open(file_path, "rb") as file: data = pickle.load(file) self.x_train, self.y_train = data["x_train"], data["y_train"] self.x_test, self.y_test = data["x_test"], data["y_test"] def train(self) -> None: """Run the backpropagation algorithm to train this neural network""" for _ in range(self.epochs): for x, y in zip(self.x_train, self.y_train): weights_gradient = [ None for weight in self.weights ] # Initializing weight gradients for each layer which are going to be used to update the weights in the network. biases_gradient = [ None for bias in self.biases ] # Initializing bias gradients for each layer which are going to be used to update the biases in the network. activation = np.expand_dims(x, axis=1) activations = [ activation ] # A list for storing all the activations when doing forward propagation values = ( [] ) # A list for storing weight * x + bias values without applying the activation function. for weight, bias in zip(self.weights, self.biases): value = np.dot(weight, activation) + bias values.append(value) activation = self.sigmoid(value) activations.append(activation) """ Calculating the error delta from output layer to be propagated backwards in the network. It is calculated by taking the derivative of the loss function, which in our case is MSE, and multiply with derivate of the sigmoid function applied on the value that entered the last layer of the network. """ error_delta = (activations[-1] - y) * self.sigmoid_derivative( values[-1] ) weights_gradient[-1] = np.dot( error_delta, activations[-2].T ) # Setting error delta multiplied with the second last layer activations as weight gradient for last layer. biases_gradient[-1] = error_delta # Setting error delta as bias gradient for last layer. """ This for-loop does the same as the code from line 128 - 136, but for each layer in the network. Thus, the error is propagated backwards in the network, and the gradients for each layer are set. """ for layer in range(2, self.total_layers): error_delta = np.dot( self.weights[-layer + 1].T, error_delta ) * self.sigmoid_derivative(values[-layer]) weights_gradient[-layer] = np.dot( error_delta, activations[-layer - 1].T ) biases_gradient[-layer] = error_delta self.weights = [ weight - self.lr * weight_gradient for weight, weight_gradient in zip(self.weights, weights_gradient) ] # Updating the weights of the network by w_i - learning_rate * nabla w_i (w_i is the weight matrix at layer i, and nabla w_i is weight gradient.) self.biases = [ bias - self.lr * bias_gradient for bias, bias_gradient in zip(self.biases, biases_gradient) ] # Updating the biases of the network by b_i - learning_rate * nabla b_i (b_i is the bias vector at layer i, and nabla b_i is weight gradient.) def predict(self, x: np.ndarray) -> float: """ Given an example x we want to predict its class probability. For example, for the breast cancer dataset we want to get the probability for cancer given the example x. :param x: A single example (vector) with shape = (number of features) :return: A float specifying probability which is bounded [0, 1]. """ # Applying forward propagation by performing weight * x + bias through the whole network. activation = np.expand_dims(x, axis=1) for weight, bias in zip(self.weights, self.biases): activation = self.sigmoid(np.dot(weight, activation) + bias) return activation[0][0] # Probability for the input x belonging to class 1. class TestAssignment5(unittest.TestCase): """ Do not change anything in this test class. --- PLEASE READ --- Run the unit tests to test the correctness of your implementation. This unit test is provided for you to check whether this delivery adheres to the assignment instructions and whether the implementation is likely correct or not. If the unit tests fail, then the assignment is not correctly implemented. """ def setUp(self) -> None: self.threshold = 0.8 self.nn_class = NeuralNetwork self.n_features = 30 def get_accuracy(self) -> float: """Calculate classification accuracy on the test dataset.""" self.network.load_data() self.network.train() n = len(self.network.y_test) correct = 0 for i in range(n): # Predict by running forward pass through the neural network pred = self.network.predict(self.network.x_test[i]) # Sanity check of the prediction assert 0 <= pred <= 1, "The prediction needs to be in [0, 1] range." # Check if right class is predicted correct += self.network.y_test[i] == round(float(pred)) return round(correct / n, 3) def test_perceptron(self) -> None: """Run this method to see if Part 1 is implemented correctly.""" self.network = self.nn_class(self.n_features, False) accuracy = self.get_accuracy() self.assertTrue( accuracy > self.threshold, "This implementation is most likely wrong since " f"the accuracy ({accuracy}) is less than {self.threshold}.", ) def test_one_hidden(self) -> None: """Run this method to see if Part 2 is implemented correctly.""" self.network = self.nn_class(self.n_features, True) accuracy = self.get_accuracy() self.assertTrue( accuracy > self.threshold, "This implementation is most likely wrong since " f"the accuracy ({accuracy}) is less than {self.threshold}.", ) if __name__ == "__main__": unittest.main()
db9f8f1535075c51e4eff02bb8c428eeb14a1d34
saurabh-pandey/AlgoAndDS
/leetcode/arrays/remove_duplicate_sorted_a2.py
990
3.5625
4
from typing import List def _shift_left(nums: List[int], index: int, shift_by: int) -> None: for i in range(index, len(nums) - shift_by): nums[i] = nums[i + shift_by] def remove_elements_1(nums: List[int]) -> int: new_len = len(nums) end_marker = len(nums) dup_count = 0 i = 1 while i < end_marker: if nums[i - 1] == nums[i]: dup_count += 1 new_len -= 1 else: if dup_count > 0: _shift_left(nums, i - dup_count, dup_count) end_marker -= dup_count i -= dup_count dup_count = 0 i += 1 return new_len def remove_elements_2(arr: List[int]) -> int: if not arr: return 0 write_index = 1 read_index = 1 while read_index < len(arr): if arr[read_index - 1] != arr[read_index]: arr[write_index] = arr[read_index] write_index += 1 read_index += 1 return write_index
e79f4bc6a33ba7b4959aa50291042e0843ae9705
Ompragash/python-ex...
/Simple_calculator.py
680
4.15625
4
#Python program to make a simple calculator def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x * y def div(x, y): return x / y print("Select Operation.") print("1.Add") print("2.Subtrac") print("3.Multiply") print("4.Division") choice = input("Enter the choice(1/2/3/4):") n1 = int(input("Enter the first number:")) n2 = int(input("Enter the second number:")) if choice == '1': print(n1,'+',n2,'=', add(n1, n2)) elif choice == '2': print(n1,'-',n2,'=', sub(n1, n2)) elif choice == '3': print(n1,'*',n2,'=', mul(n1, n2)) elif choice == '4': print(n1,'/',n2,'=', div(n1, n2)) else: print("Invalid input")
dca2eaa44133561cb48d950eab7983ad4efd3041
jordymcm/learning-to-code
/python/Stories/hamsterV1.0.0.py
889
3.84375
4
#!/usr/bin/python3 from getch import getch import os answer=0 name=0 answer = input ('You are a hamster what\'s your name? A: Fred B: doggy C: Zoof ') os.system('clear') if answer == 'a' or answer == 'A': name=('fred') print ('Fred, that is a good choice') getch() == ' ' os.system('clear') answer = input ('Now '+ name +' needs a house. you have 2 choises. A: a house B: a flata ') elif answer == 'b' or answer == 'B': name=('doggy') print ('doggy, that is a good choice') getch() == ' ' os.system('clear') answer = input ('Now '+ name +' needs a house. you have 2 choises. A: a house B: a flata ') elif answer == 'c' or answer == 'C': name=('zoof') print ('zoof, that is a good choice') getch() == ' ' os.system('clear') answer = input ('Now '+ name +' needs a house. you have 2 choises. A: a house B: a flata ')
cc6d93c6c4e4027c457d294031e08f8d3ca0f035
edu-athensoft/stem1401python_student
/py200912f_python2m7/day04_201003/file_5_read.py
352
3.6875
4
""" open a file in read mode """ f = open("file5_mode_r.txt",'r') # read the specified length of data in the file print(f.read(8),end="==") print(f.read(8),end="==") # print(f.read(1),end="==") # print("EOF",end="==") # print(f.read(1),end="==") # print("EOF") print(f.read(8),end="==") print(f.read(8),end="==") print(f.read(8),end="==") f.close()
b7a9979f6dfb368954ac3a53a37e2e8d9eb99d91
dongyingname/pythonStudy
/Data Science/np/numpyTrial.py
5,135
4.40625
4
# %% # Numpy is the core library for scientific computing # in Python. It provides a high-performance multidimensional # array object, and tools for working with these arrays. # If you are already familiar with MATLAB, you might find # this tutorial useful to get started with Numpy. # %% # A numpy array is a grid of values, all of the same type, # and is indexed by a tuple of nonnegative integers. # The number of dimensions is the rank of the array; the # shape of an array is a tuple of integers giving the size # of the array along each dimension. # We can initialize numpy arrays from nested Python lists, # and access elements using square brackets: import numpy as np a = np.array([1, 2, 3]) # Create a rank 1 array print(type(a)) # Prints "<class 'numpy.ndarray'>" print(a.shape) # Prints "(3,)" print(a[0], a[1], a[2]) # Prints "1 2 3" a[0] = 5 # Change an element of the array print(a) # Prints "[5, 2, 3]" b = np.array([[1, 2, 3], [4, 5, 6]]) # Create a rank 2 array print(b.shape) # Prints "(2, 3)" print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4" # %% a = np.zeros((2, 2)) # Create an array of all zeros print(a) # Prints "[[ 0. 0.] # [ 0. 0.]]" b = np.ones((1, 2)) # Create an array of all ones print(b) # Prints "[[ 1. 1.]]" c = np.full((2, 2), 7) # Create a constant array print(c) # Prints "[[ 7. 7.] # [ 7. 7.]]" d = np.eye(2) # Create a 2x2 identity matrix print(d) # Prints "[[ 1. 0.] # [ 0. 1.]]" e = np.random.random((2, 2)) # Create an array filled with random values print(e) # Might print "[[ 0.91940167 0.08143941] # [ 0.68744134 0.87236687]]" # %% a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print(a) # Use slicing to pull out the subarray consisting of the first 2 rows # and columns 1 and 2; b is the following array of shape (2, 2): # [[2 3] # [6 7]] b = a[:2, 1:3] # A slice of an array is a view into the same data, so modifying it # will modify the original array. print(a[0, 1]) # Prints "2" b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1] print(a[0, 1]) # Prints "77" print(a) # %% # You can also mix integer indexing with slice indexing. However, # doing so will yield an array of lower rank than the original # array. Note that this is quite different from the way that # MATLAB handles array slicing: a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Two ways of accessing the data in the middle row of the array. # Mixing integer indexing with slices yields an array of lower rank, # while using only slices yields an array of the same rank as the # original array: row_r1 = a[1, :] # Rank 1 view of the second row of a row_r2 = a[1:2, :] # Rank 2 view of the second row of a print(row_r1, row_r1.shape) print(row_r2, row_r2.shape) row_r1[1] = 99 row_r2[0, 0] = 100 print('row_r1', row_r1) print('a', a) print('row_r2', row_r2) print('a', a) # We can make the same distinction when accessing columns of an array: col_r1 = a[:, 1] col_r2 = a[:, 1:2] print(col_r1, col_r1.shape) print(col_r2, col_r2.shape) # %% a = np.array([[1, 2], [3, 4], [5, 6]]) # An example of integer array indexing. # The returned array will have shape (3,) and print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]" # The above example of integer array indexing is equivalent to this: print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]" # When using integer array indexing, you can reuse the same # element from the source array: print(a[[0, 0], [1, 1]]) # Prints "[2 2]" # Equivalent to the previous integer array indexing example print(np.array([a[0, 1], a[0, 1]])) # Prints "[2 2]" # %% a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) print(a) # prints "array([[ 1, 2, 3], # [ 4, 5, 6], # [ 7, 8, 9], # [10, 11, 12]])" # Create an array of indices b = np.array([0, 2, 0, 1]) # Select one element from each row of a using the indices in b print(a[np.arange(4), b]) # Prints "[ 1 6 7 11]" # Mutate one element from each row of a using the indices in b a[np.arange(4), b] += 10 print(a) # %% # Boolean array indexing: Boolean array indexing lets you pick # out arbitrary elements of an array. Frequently this type of # indexing is used to select the elements of an array that # satisfy some condition. Here is an example: a = np.array([[1, 2], [3, 4], [5, 6]]) bool_idx = (a > 2) # Find the elements of a that are bigger than 2; # this returns a numpy array of Booleans of the same # shape as a, where each slot of bool_idx tells # whether that element of a is > 2. print(bool_idx) # Prints "[[False False] # [ True True] # [ True True]]" # We use boolean array indexing to construct a rank 1 array # consisting of the elements of a corresponding to the True values # of bool_idx print(a[bool_idx]) # Prints "[3 4 5 6]" # We can do all of the above in a single concise statement: print(a[a > 2]) # %%
e3c52f6189d7d4d20c845cd0a4e4d791d88e6076
superniaoren/fresh-fish
/python_tricks/dictionary/test_dict_craziest_expression.py
2,542
3.828125
4
# class AlwaysEqual: def __eq__(self, some): return True def __hash__(self): return id(self) class AlwaysConflict: def __hash__(self): return 1 class AlwaysSame: def __eq__(sefl, some): return True def __hash__(self): return 1 if __name__ == '__main__': descrp = 'In python, the keys: $True == 1 == 1.0, ' \ 'The dict conflict happens in key or value, need double check. ' print(descrp) error_prone = {True: 'true?', 1: '1?', 1.0: '1.0?'} print(error_prone) print('Now, to dig the reason !!') key_eq = True == 1 == 1.0 print('key_eqaul: {}'.format(key_eq)) print("The boolean type is a subtype of the integer type, and boolean \n"\ "values behave like the values 0 and 1, respectively, in almost \n"\ "all contexts, the exception being that when converted to a string,\n"\ " the strings 'False' or 'True' are returned, respectively.") no_yes = ['no', 'yes'] print("['no', 'yes'][False] = {}".format(no_yes[True])) print("['no', 'yes'][True] = {}".format(no_yes[False])) # 1.0 float not work here # overwritten, __eq__ or hash conflict ?? find it! print("Find out: ") objects = [AlwaysEqual(), AlwaysEqual(), AlwaysEqual(), ] print([hash(obj) for obj in objects]) print(objects[0] == 43) print(objects[1] == 'shop on line') print(objects[2] == AlwaysEqual()) print("Test if the keys are overwritten: ") key_over = {AlwaysEqual(): 'yes', AlwaysEqual(): 'no'} print('key_overwritten: {}'.format(key_over)) # use is? not __eq__ ?? print('the keys get overwritten effect IS NOT based on their equality comparison result alone') print("Test if the hash values are overwritten: ") a_conf = AlwaysConflict() b_conf = AlwaysConflict() print(a_conf == b_conf) print("hash = {0}, {1}".format(hash(a_conf), hash(b_conf))) value_over = {AlwaysConflict(): 'yes', AlwaysConflict(): 'no'} print("value_overwritten: {}".format(value_over)) print('the keys get overwritten effect IS NOT caused by hash value collisions alone either') print("Test if the equality && hash-value collisions result in overwritten: ") a_same = AlwaysSame() b_same = AlwaysSame() kv_over = {AlwaysSame(): 'yes', AlwaysSame(): 'no'} print(a_same == b_same) print("hash = {0}, {1}".format(hash(a_same), hash(b_same))) print("kv_overwritten: {}".format(kv_over))
0d2bbfe07ddb86cb74eade29586cf9b903e28058
gtxmobile/leetcode
/151. ็ฟป่ฝฌๅญ—็ฌฆไธฒ้‡Œ็š„ๅ•่ฏ.py
162
3.5625
4
class Solution: # @param s, a string # @return a string def reverseWords(self, s): return ' '.join([w for w in s.strip().split() if w][::-1])
7586c98142cc7445da911f2a9fa4bf5f988ea699
Aasthaengg/IBMdataset
/Python_codes/p02880/s118793555.py
154
3.5625
4
N=int(input()) resurt='' for i in range(1,10): if N%i ==0 and N//i<=9: result='Yes' break else: result='No' print(result)
eb708e1ca365e7cde1a32cc0ca71a063d9d67f56
EngineerToBe/python-labs
/008_loops.py
1,308
4.53125
5
# with loops we can perform the set of task for n number of times # for loop pandavas = ['Yudhisthir', 'Arjun', 'Bhim', 'Nakul', "Sahdev"] for pandav in pandavas: print(pandav) # break and continue # The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. # If the break statement is inside a nested loop(loop inside another loop), the break statement will terminate the innermost loop. for pandav in pandavas: if pandav == 'Bhim': print("My fav Pandav") break # The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. kids_age = [10, 9, 12, 14, 18, 13] for age in kids_age: if age < 10: continue else: print(age) # while loop # The while loop performs a set of code until some condition is reached. # While loops can be used to iterate through lists, just like for loops: # List comprehensions are a third way of making lists. # With this elegant approach, you could rewrite the for loop from the first example in just a single line of code: ages = [23, 45, 67, 87, 100, 12, 14] adult_age = [age for age in ages if age >= 18] print(adult_age)
9e5d145529906ea80fa4d575cc9f43a4e72fcc47
Leo-hw/psou
/anal_pro4/deep_learn1/keras2.py
2,106
3.625
4
# Keras ๋ฅผ ์ด์šฉํ•ด OR gate ๋…ผ๋ฆฌ ๋ชจ๋ธ์„ ์ƒ์„ฑํ•œ ํ›„ ๋ถ„๋ฅ˜ ๊ฒฐ๊ณผ ํ™•์ธ import numpy as np from tensorflow.keras.models import Sequential # ์„ ํ˜• ๋„คํŠธ์›Œํฌ ์Šคํ…์„ ์ •์˜ from tensorflow.keras.layers import Dense, Activation from tensorflow.keras.optimizers import SGD, Adam, RMSprop # ์ˆœ์„œ 1 : ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ๋ฐ ๊ฐ€๊ณต x = np.array([[0,0], [0,1],[1,0],[1,1]]) y = np.array([[0],[0],[0],[1]]) #and """ model = Sequential() model.add(Dense(5, input_dim=2)) model.add(Activation('relu')) model.add(Dense(1)) model.add(Activation('sigmoid')) # ์ดํ•ญ ๋ถ„๋ฅ˜์ด๋ฏ€๋กœ ์ถœ๋ ฅ์„ ํ™œ์„ฑํ™” ํ•จ์ˆ˜๋Š” sigmoid """ model = Sequential() model.add(Dense(5, input_dim=2, activation = 'relu')) model.add(Dense(5, input_dim=2, activation = 'relu')) # hidden layer model.add(Dense(1, activation = 'sigmoid')) # ์ถœ๋ ฅํ•  ๋•Œ ์ดํ•ญ์ด๋ฏ€๋กœ sigmoid // ๋‹คํ•ญ์ด๋ฉด softmax print() print(model.summary()) # ์ „์ฒด ๊ตฌ์กฐ์— ๋Œ€ํ•œ parameter print('---------------------------------------') print('input(์ž…๋ ฅ ๊ตฌ์กฐ) : ',model.input) # ์ž…๋ ฅ ๊ตฌ์กฐ print('output(์ถœ๋ ฅ ๊ตฌ์กฐ) : ',model.output) # ์ถœ๋ ฅ ๊ตฌ์กฐ print('weights(๊ฐ€์ค‘์น˜์™€ ํŽธํ–ฅ) : ',model.weights) # ๊ฐ€์ค‘์น˜์™€ ํŽธํ–ฅ print('---------------------------------------') model.compile(optimizer=Adam(0.01), loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(x, y, epochs=1000, batch_size=1, verbose=1) loss_metrics = model.evaluate(x, y) print('loss_metrics : ', loss_metrics) pred = (model.predict(x) > 0.5).astype('int32') print('pred : ', pred.flatten()) print(' ****'*10) print('loss : ', history.history['loss']) print('acc : ', history.history['accuracy']) import matplotlib.pyplot as plt plt.plot(history.history['loss'], label = 'train loss') plt.xlabel('epochs') plt.ylabel('loss') plt.legend(loc = 'best') # 4 ์‚ฌ๋ถ„๋ฉด ์ค‘ ์œ„์น˜๋ฅผ ์žก์•„์ฃผ๋Š” ๊ฒƒ plt.show() import pandas as pd pd.DataFrame(history.history).plot(figsize=(8,5)) plt.show()
e239afa4753e67cf501dcb1ad80117f912fca612
kriti-banka/ml-workshop-wac-1
/day_1/even_odd.py
236
3.9375
4
# If Condition """ if condition_1: code code code elif [optional] condition_2: code ... ... ... else [optional]: code code """ number = int(input()) if number % 2 == 0: print('even') else: print('odd')
1ad42b305455d60ccda9ddd450d79ca2b83b719f
AmandaRH07/PythonUdemy
/1. Bรกsico/26- Exercicio2.py
409
4
4
hora = input("Digite a hora:") if hora.isdigit(): hora = int(hora) if hora < 0 or hora > 23: print("Por favor, digite um horรกrio entre 0 e 23 horas") else: if hora <= 11: print("Bom dia, dia") elif hora <= 17: print("Boa tarde, Brasil,Boa noite Itรกlia") else: print("Boa noite, vรก dormir, vocรช รฉ piranha, nรฃo morcega")
2d57899fae3d3036f3cd7adc0931c5a84d89bc23
boliluce/CodingTest
/programmers/์ง์ˆ˜์™€ ํ™€์ˆ˜.py
134
3.671875
4
def solution(num): #return "Even" if num%2==0 else "Odd" return ["Even", "Odd"][num&1] print(solution(3)) print(solution(4))
27502b0d82a9c38962a414f9e2276e537d300215
zhengfuli/leetcode-in-python
/n044_wildcard_matching.py
954
3.828125
4
class WildCardMatching(object): def wildCardMatching(self, s, p): """ :type s: str :type p: str :rtype: bool """ # sp, and pp are pointers for s and p, star for storing the star position # ss for storing the letter in s corresponding to star in p sp, pp, star, ss = 0, 0, -1, -1 while sp < len(s): print pp, sp if pp < len(p) and (s[sp] == p[pp] or p[pp] == '?'): sp += 1 pp += 1 continue if pp < len(p) and p[pp] == '*': star, ss = pp, sp pp += 1 continue if star != -1: pp = star + 1 ss += 1 sp = ss continue return False while pp < len(p) and p[pp] == '*': pp += 1 if pp == len(p): return True return False
6637ba5feb7e64e4bb6812e88fb0b6721d1e7bf7
UmaAnantharaman/Python_Matplotlib_Numpypandas_ML
/openpyxl_worksheet_aceesscells.py
632
4.09375
4
#Create a workbook using openpyxl library from openpyxl import Workbook wb = Workbook() #Make the current worksheet from the workbook active ws = wb.active #Changing the default title of the worksheet ws.title = "Sample worksheet" #Iterating through the workbook and printing the sheet names for sheet in wb: print(sheet.title) #Creating a copy of the worksheet, copy_worksheet usage source = wb.active target = wb.copy_worksheet(source) #Accessing the cells in worksheet by iterating, iter_rows usage for row in ws.iter_rows(min_row=1, max_col=3, max_row=2): for cell in row: print(cell)
28259266de63cee34702478653c332fe1dc4be84
archu333/python
/list slicing.py
3,382
3.84375
4
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 16:30:00) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> list1=[2,4,6] >>> print(list1[:]) [2, 4, 6] >>> print(list1[-1]) 6 >>> list=["Ajay","Baby","Mommy","Anil","Roshan","Ammu"] >>> print(list[::2]) ['Ajay', 'Mommy', 'Roshan'] >>> print(list[1::2]) ['Baby', 'Anil', 'Ammu'] >>> print(list[2:3:]) ['Mommy'] >>> print(list[-1:4:]) [] >>> archu=[10,20,30,40,50,60,70,80,90] >>> print(archu[0:8:1]) [10, 20, 30, 40, 50, 60, 70, 80] >>> print(archu[0:7:2]) [10, 30, 50, 70] >>> print(archu[-3:]) [70, 80, 90] >>> print(archu[-2:5]) [] >>> print(archu[:-3]) [10, 20, 30, 40, 50, 60] >>> print(archu[1:-3:2]) [20, 40, 60] >>> print(archu[::-1]) [90, 80, 70, 60, 50, 40, 30, 20, 10] >>> a=[10,20,30,40,50] >>> a[:2]=[1,2,3,4,5] >>> print(a) [1, 2, 3, 4, 5, 30, 40, 50] >>> a=[10,20,30,40,50] >>> a[::2]=[1,1,1,1,1,1,1,1,1] Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> a[::2]=[1,1,1,1,1,1,1,1,1] ValueError: attempt to assign sequence of size 9 to extended slice of size 3 >>> a=[10,20,30,40,50] >>> a[::2]=[1,1] Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> a[::2]=[1,1] ValueError: attempt to assign sequence of size 2 to extended slice of size 3 >>> a=[10,20,30,40,50,60,70,80,90] >>> a[::2]=[1,1,1,1,1] >>> print(a) [1, 20, 1, 40, 1, 60, 1, 80, 1] >>> >>> >>> >>> list=["abc","xyz","aba","1221"] >>> s=0 >>> for i in list: if i[0]==i[-1]: s+=1 print(s) 1 2 >>> list=["abc","xyz","aba","1221"] >>> s=0 >>> for i in list: if i[0]==i[-1]: s+=1 print(s) SyntaxError: inconsistent use of tabs and spaces in indentation >>> >>> >>> list=["abc","xyz","aba","1221"] >>> s=0 >>> for i in list: if i[0]==i[-1]: s+=1 >>> print(s) 2 >>> >>> list1=[1,2,3,4,5] >>> list2=[5,6,7,8,9] >>> r=false Traceback (most recent call last): File "<pyshell#55>", line 1, in <module> r=false NameError: name 'false' is not defined >>> r="false" >>> for i in list1: for j in list2: if i==j: r="true" >>> print(r) true >>> >>> >>> list1=[7,8,120,25,44,20,27] >>> list2=[x for x in list1 if x%2!=0] >>> print(list2) [7, 25, 27] >>> list3=[x for x in list1 if x%2==0] >>> print(list3) [8, 120, 44, 20] >>> >>> >>> l=list(input().split()) Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> l=list(input().split()) TypeError: 'list' object is not callable >>> list=["Enjoying","Python"] >>> list.append["good"] Traceback (most recent call last): File "<pyshell#81>", line 1, in <module> list.append["good"] TypeError: 'builtin_function_or_method' object is not subscriptable >>> list=["I","Love","Python"] >>> list2=["it","is","intresting"] >>> list1=list+list2 >>> print(list1) ['I', 'Love', 'Python', 'it', 'is', 'intresting'] >>> print(list1*2) ['I', 'Love', 'Python', 'it', 'is', 'intresting', 'I', 'Love', 'Python', 'it', 'is', 'intresting'] >>> print(list2) ['it', 'is', 'intresting'] >>> print(list1) ['I', 'Love', 'Python', 'it', 'is', 'intresting'] >>> list1.append("programming skills") >>> print(list1) ['I', 'Love', 'Python', 'it', 'is', 'intresting', 'programming skills'] >>>
d994b636467ff4908e1daa64a31b4ce302a14154
leilin-research/Link-Travel-Time-prediction
/filterTaxiDataset.py
1,646
3.59375
4
import dataToGraph def isWithinRange(latitude,longitude,max_suitable_latitude,min_suitable_latitude,max_suitable_longitude,min_suitable_longitude): return (latitude > min_suitable_latitude and latitude < max_suitable_latitude and longitude > min_suitable_longitude and longitude < max_suitable_longitude) def filterDataset(fileIn, fileOut,max_suitable_latitude,min_suitable_latitude,max_suitable_longitude,min_suitable_longitude): ''' From input file, reads all lines and only writes them to output file if the POINT(latitude,longitude) lies within range of max and min latitude and longitude values. A line looks like this: 105;2014-02-01 00:00:21.033058+01;POINT(41.8971435606299 12.4729530904655) ''' with open(fileIn, "r") as fin, open(fileOut, "w") as fout: for line in fin: latitude, longitude = dataToGraph.lineToPoint(line) if isWithinRange(latitude,longitude,max_suitable_latitude,min_suitable_latitude,max_suitable_longitude,min_suitable_longitude): fout.write(line) def main(): fileIn = "/home/aniket/Desktop/BTP/Travel Time Prediction/Map backup/taxi_february.txt" fileOut = "/home/aniket/Desktop/BTP/Travel Time Prediction/filteredTaxiData.txt" # Run dataToGraph.py to get these values max_suitable_latitude = 41.9123147 min_suitable_latitude = 41.7623147 max_suitable_longitude = 12.6046319 min_suitable_longitude = 12.4546319 filterDataset(fileIn,fileOut,max_suitable_latitude,min_suitable_latitude,max_suitable_longitude,min_suitable_longitude) print("done") if __name__=="__main__": main()
6f695b3482fbf84bf4813b1cbc48989e94963d67
MarkLyck/Learning-Python
/for.py
102
3.625
4
foods = ['bacbon', 'tuna', 'ham', 'sausages', 'beef'] for f in foods: print(f) print(len(f))
880e6fd13ed49921215c97107b7aa2681424f863
ricardomartinez4/python
/orientadoObjetos/practica070.py
2,842
3.96875
4
# -*- coding: utf-8 -*- ''' ''' class Rectangulo(): # def __init__(self, base, altura, color='white'): # Ahora en vez de iniciar los atributos se utilizan los mรฉtodos getter self.base = float(base) self.altura = float(altura) self.color = color def __str__(self): return 'Rectรกngulo Dimensiones: ' + str(self.__base) + ', ' + str(self.__altura) # @property def base(self): return self.__base @property def altura(self): return self.__altura # @base.setter def base(self, base): assert(base >= 0), 'La base no puede ser negativa' self.__base = float(base) @altura.setter def altura(self, altura): assert(altura >= 0), 'La altura no puede ser negativa' self.__altura = float(altura) def area(self): return self.__base * self.__altura def perimetro(self): return 2 * self.__base + 2 * self.__altura try: #rectangulo = Rectangulo(-3,2) rectangulo = Rectangulo(3,2) print(rectangulo) print(rectangulo.altura) print(rectangulo.color) rectangulo.color = 'black' print(rectangulo.color) rectangulo.altura = 4 print(rectangulo) print(rectangulo.area()) print(rectangulo.perimetro()) except Exception as e: print('Error: ' + str(e))# -*- coding: utf-8 -*- ''' ''' class Rectangulo(): # def __init__(self, base, altura, color='white'): # Ahora en vez de iniciar los atributos se utilizan los mรฉtodos getter self.base = float(base) self.altura = float(altura) self.color = color def __str__(self): return 'Rectรกngulo Dimensiones: ' + str(self.__base) + ', ' + str(self.__altura) # @property def base(self): return self.__base @property def altura(self): return self.__altura # @base.setter def base(self, base): assert(base >= 0), 'La base no puede ser negativa' self.__base = float(base) @altura.setter def altura(self, altura): assert(altura >= 0), 'La altura no puede ser negativa' self.__altura = float(altura) def area(self): return self.__base * self.__altura def perimetro(self): return 2 * self.__base + 2 * self.__altura try: #rectangulo = Rectangulo(-3,2) rectangulo = Rectangulo(3,2) print(rectangulo) print(rectangulo.altura) print(rectangulo.color) rectangulo.color = 'black' print(rectangulo.color) rectangulo.altura = 4 print(rectangulo) print(rectangulo.area()) print(rectangulo.perimetro()) except Exception as e: print('Error: ' + str(e))
b8b6ef37b7dab583decfb4ab22d149d58191b494
HaoLIU94/lpthw
/Pratice-exos/ex2.py
281
3.671875
4
import random cont=1 while cont==1: dice=[1,2,3,4,5,6] res = random.randint(1,6) print 'The result is',res print 'Would you like to play again' s = raw_input('yes/no\n') if s =='yes': cont=0 elif s=='no' : cont=1 else: pass
171e9b7299ddb13c6e7bb55bdf2889be39d83421
sacki123/django_training
/Python test/thรชm pt vร o tuple.py
380
3.796875
4
tpl1 = ('a', 'b', 'c', 'd') tpl2 = ('e',) tpl3 = tpl1 + tpl2 print(tpl3) lst = [1,2,3,4] print(tuple(lst)) print(list(tpl3)) lst2 = ["Google",(10,20), 15, (40, 50, 60), ["a", "vร ", "e"], (70, 80, 90, 100)] for index, value in enumerate(lst2): if isinstance(value, tuple): lst1 = list(lst2[index]) lst1[-1] = 200 lst2[index] = tuple(lst1) print(lst2)
302930c6fe8b8e3a2deda19a132e839ba981961c
RoshaniPatel10994/-ITCS1140---Python--Practices-
/My Practice/rock collected in loop.py
383
4.1875
4
rocksdays = int() weeks = 0 total = int() days = 0 rocks = int() for weeks in range(0, 2): for days in range(0, 7): rocks = int(input(" Enter the rocks you collected todays: "))+rocks print("You collected: ", rocks, " rocks today") weeks = weeks+ days print(" You collected: ", rocks, " rocks this week.")
15609b2c5898686febdb31ac2dcfd0b19fa251d7
bernardwija/Sir-Jude-Exercise
/1st Semester/Sir Jude's Exercise 7/No.1.py
1,460
4.09375
4
print('Welcome to List Converter!') def removekeys(mydict,keylist): print('Here are your datas: ') print('Your dictionary:',mydict) print('Your List:',keylist) for i in keylist: if i in mydict: del mydict[i] print('Here is your new dictionary:') a=mydict return a def dictionary(): print('Please give us your available dictionary content down below.') mydict = {} while True: dict = input('Please Input The Key Name: ') val = input('Please Input The Key Value: ') mydict[dict] = val ans = input('Do you want to add another content(Yes or No)?: ') if ans == 'Yes': print(mydict) continue else: print(mydict) def list(): print('Now please give us your available list content down below.') keylist =[] while True: list = input('Please Input The Key Name: ') keylist.append(list) ans = input('Do you want to add another content(Yes or No)?: ') if ans == 'Yes': print(keylist) continue else: print(keylist) break print(removekeys(mydict,keylist)) list() break dictionary() print('Thankyou for using our service!')
dac58ea7588cf42c7397afc380f37b748f9032a0
tata-LY/python
/python-100-days/08.้ขๅ‘ๅฏน่ฑก็ผ–็จ‹ๅŸบ็ก€/1.py
853
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2021-1-12 16:08 # @Author : liuyang # @File : 1.py # @Software: PyCharm class Student(object): def __init__(self, name, age): """ __init__ๆ˜ฏไธ€ไธช็‰นๆฎŠๆ–นๆณ•็”จไบŽๅœจๅˆ›ๅปบๅฏน่ฑกๆ—ถ่ฟ›่กŒๅˆๅง‹ๅŒ–ๆ“ไฝœ :param name: ๅˆๅง‹ๅŒ–ๅญฆ็”Ÿๅๅญ— :param age: ๅˆๅง‹ๅŒ–ๅญฆ็”Ÿๅนด้พ„ """ self.name = name self.age = age def study(self, course_name = 'Python'): print('%sๆญฃๅœจๅญฆไน %s.' % (self.name, course_name)) def display_stu_info(self): print('%s: %sๅฒ' % (self.name, self.age)) def main(): stu1 = Student('ๅˆ˜ๆด‹', 29) stu1.study('Golang') stu1.display_stu_info() stu2 = Student('่‚ฅ่‚ฅไป”', 28) stu2.study('Math') stu2.display_stu_info() if __name__ == '__main__': main()
51863239e93ebea22250aecd50d49d5856b577db
Monzillaa/practices-python
/conditionals.py
943
4.3125
4
""" print("ingresa color") color = input() if color == "red" : print("the color is red") elif color == "blue": print("the color is blue") elif color == "yellow": print("the color is yellow") else: print("any color bitch!!") """ """ print("ingresa tu nombre") name = input() print("ingresa tu apellido") lastname = input() if name == "Nini": if lastname == "Morales": print(f"You are {name} {lastname}") elif name == "Mushu" and lastname == "Morales": print(f"You are {name} {lastname}") else: print(f"You are {name} {lastname}") else: print(f"You are {name} {lastname}") """ ##se utiliza para comparaciones and, or y not son comparadores logicos x = 30 y = 5 if x > 2 and x <= 10: print("x is greater than two and less than or equal to ten") if x > 2 or x <= 20 : print("x is geater than two or less or equal to twenty") if(not(x == y)): print("x is not equal y")
49dc7f4165e15937be90a09bd1a04d2cfe79ceb9
daniel-reich/ubiquitous-fiesta
/JmyD5D4KnhzmMPEKz_12.py
511
3.734375
4
def constraint(txt): letters = [i.lower() for i in txt if i.lower().isalpha()] words = txt.split() if len(set(letters)) == 26: return 'Pangram' if len(set(letters)) == len(letters): return 'Heterogram' if len({i.lower()[0] for i in words}) == 1: return 'Tautogram' s = set(words[0].lower()) for i in range(1, len(words)): s.intersection_update(words[i].lower()) if len(s) > 0 or len(words) == 1: return 'Transgram' return 'Sentence'
c40b13afae5d363d1ec2e976f9af5ad667db1f78
blue0712/blue
/demo65.py
287
3.703125
4
class Rectangle: def __init__(self, width, height): self.width = width self.height = height pass def calculate_area(self): return self.width * self.height r1 = Rectangle(5, 7) r2 = Rectangle(2, 9) print(r1.calculate_area(), r2.calculate_area())
12daa5790ccfb0f8a00f66c39d74866112acb4a8
marcosihe/Python_basico
/strings.py
2,145
4.53125
5
# Mร‰TODOS # upper() --> convierte a mayรบsucla # capitalize --> convierte a mayรบscula la primera letra de la palabra # strip() --> elimina los espacios que estรกn de mรกs # lower() --> convierte a minรบscula # replace('a', 'b') --> reemplaza todas las letras 'a' de la cadena por la letra 'b' # รndices --> si nombre == 'Marcos' ENTONCES: nombre[0] --> 'm' # len() --> devuelve el nรบmero de caracteres de la cadena de texto # Slice --> cortar cadenas de caracteres def run(): name = input('Ingrese su nombre: ') print('Su nombre en mayรบsculas: ' + name.upper()) print('Su nombre en minรบsuculas: ' + name.lower()) print('Su nombre escrito de forma correcta: ' + name.capitalize()) print('Cantidad de caracteres que quedaron luego de haber utilizado el mรฉtodo capitalize: ' + str(len(name))) print('El caracter de la posiciรณn 3 en su nombre es: ' + name[2]) sentence = input('Escriba una oraciรณn terminada en un punto: ') print('Cambiando las letras o por la letra "e" en su oraciรณn: ' + sentence.replace('o', 'e')) print('La cantidad de caracteres en la frase ingresada es de: ' + str(len(sentence))) print('\n' + '*** STRIP ***') random_word = input( 'Escriba una palabra con uno o mรกs espacios al final: ') print('Cantidad de caracteres de la cadena ingresada: ' + str(len(random_word))) print('Cantidad de caracteres sin los espacios sobrantes: ' + str(len(random_word.strip()))) print('\n' + '*** SLICE ***') first_name = input('Ingrese su primer nombre: ') print('Estas son las primeras 3 letras de su nombre: ' + first_name[0:3]) # alternativa: fisrt_name[:3] print('Estas son las รบltimas letras que restan de su nombre:' + first_name[3:]) print('Esta es una secuencia de letras de su nombre: ' + first_name[1:4]) aux = "PROGRAMACION" print('\n' + aux) print('Caracteres de la palabra PROGRAMACION, desde la r hasta la o, saltando 2 caracteres: ' + aux[1:10:2]) print('Invertir la palabra PROGRAMACION') print(aux[::-1]) if __name__ == '__main__': run()
4566be4d35f74f7876c10fafdba860feee95379f
ashkhi/Python
/Week1/PrintBasics.py
461
3.875
4
# print can have multiple messages as arguments print("Hello India !", "Hello World !", "Hi from Python class..") # print can have numbers print(5) # print can have decimal values print(20.5) # print can also have multiple different types of messages print("Hello", 5, 20.5) # print accepts only the round brackets # curly, square or angular would give an error #print with (), {}, [], <> # print can have message inside single or double quotes print('Hi')
2bf6151c76f8189b83eedebde63f40ee4a37a843
VineetAhujaX/Team-Automated-Chatbot
/Bonus.py
2,276
3.921875
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 16 04:02:34 2021 @author: USER """ import requests def getWeather(): # Enter your API key here api_key = "9c9623d2c835fb356931d3b0b8d19c4a" # base_url variable to store url base_url = "http://api.openweathermap.org/data/2.5/weather?" # Give city name city_name = "Mandi" # complete_url variable to store # complete url address complete_url = base_url + "q=" + city_name + "&appid=" + api_key # get method of requests module # return response object response = requests.get(complete_url) # json method of response object # convert json format data into # python format data x = response.json() # Now x contains list of nested dictionaries # Check the value of "cod" key is equal to # "404", means city is found otherwise, # city is not found # store the value of "main" # key in variable y y = x["main"] # store the value corresponding # to the "temp" key of y current_temperature = y["temp"] # store the value corresponding # to the "pressure" key of y current_pressure = y["pressure"] # store the value corresponding # to the "humidity" key of y current_humidiy = y["humidity"] # store the value of "weather" # key in variable z z = x["weather"] # store the value corresponding # to the "description" key at # the 0th index of z weather_description = z[0]["description"] # print following values return("The weather at IIT Mandi is:\n Temperature (in Celsius) = " + str(round((current_temperature-273),0)) + "\n Atmospheric Pressure (in kPa) = " + str(current_pressure/10) + "\n Humidity (in %) = " + str(current_humidiy) + "\n Description = " + str(weather_description)) import datetime def getTime(): now = datetime.datetime.now() s= "Current date: " s+= now.strftime("%d-%m-%Y") s+= "\nCurrent time: " s+= now.strftime("%H:%M") return s
f7deec37c47814d6208f670682dffdbc174b34eb
KrolMateusz/Crypto
/Alghoritms/vigenere_cipher.py
1,583
3.796875
4
import pyperclip import string LETTERS = string.ascii_uppercase def main(): file = open('C:\\Users\\Mateusz\\PythonProjects\\Aplikacja_szyfrowanie\\Alghoritms\\message_vigenere.txt') message = file.read() file.close() key = 'ASIMOV' encrypted = encrypt_message(message, key) decrypted = decrypt_message(encrypted, key) print('Encrypted message:\n%s' % encrypted) print('\nCopying encrypted message to clipboard.\n') pyperclip.copy(encrypted) print('Decrypted message:\n%s' % decrypted) def encrypt_message(message, key): message = message.upper() encrypted = [] key_index = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: num = (num + LETTERS.find(key[key_index])) % len(LETTERS) encrypted.append(LETTERS[num]) key_index += 1 if key_index == len(key): key_index = 0 else: encrypted.append(symbol) return ''.join(encrypted) def decrypt_message(message, key): message = message.upper() decrypted = [] key_index = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: num = (num - LETTERS.find(key[key_index])) % len(LETTERS) decrypted.append(LETTERS[num]) key_index += 1 if key_index == len(key): key_index = 0 else: decrypted.append(symbol) return ''.join(decrypted) if __name__ == '__main__': main()
772e6d23d7a4428c788e3bb08974e78f1d62ad25
Kirankumar76k/my-python-programs
/OOPS/PolyGit.py
1,168
4.03125
4
class Artillery(): def __init__(self): self.className = "Artillery Class constructor" def showName(self): shootingRange = "aprox. 1-30 km" return "Artillery" + " " + shootingRange class Mortar(Artillery): def showName(self): shootingRange = "1 km" return "Mortar" + " " + shootingRange class Howitzer(Artillery): def __init__(self): self.className = "Howitzer Class constructor" self.rndMath = 2 * 2 def showName(self, color="Green"): shootingRange = "35 km" return "Howitzer " + color + " " + shootingRange class Cannon(Artillery): def showName(self): shootingRange = "10 km" return "Cannon" + " " + shootingRange a = Artillery(); print(a.className) print(a.showName()) print("\n") m = Mortar(); print(m.className) print(m.showName()) print("\n") h = Howitzer(); print(h.className) print(h.rndMath) print(h.showName()) print("\n") x = Howitzer(); print(x.className) print(x.rndMath) print(x.showName("Blue")) print("\n") c = Cannon(); print(c.className) print(c.showName()) print("\n")
ce4e23ef1c0489bf2d97487416c87e64b1c67b2c
Najoj/advent-of-code
/2022/5/Stack.py
681
3.8125
4
class Stack: def __init__(self): self._stack = [] self._height = 0 def push(self, item, bottom=False): if item and item.strip(): self._height += 1 if bottom: self._stack = [item] + self._stack else: self._stack = self._stack + [item] def pop(self): if not self._stack: return None self._height -= 1 item = self._stack[-1] self._stack = self._stack[:-1] return item def __len__(self): return self._height def __str__(self): string = ' '.join(string for string in self._stack) return string
bf35a78850c08000f95a857195d42c1ffdc9050b
surimLee/Python_study_
/0315_4.py
181
3.59375
4
from tkinter import * window = Tk() canvas = Canvas(window, width=300, height=200) canvas.pack() canvas.create_polygon(10, 10, 150, 110, 250, 20, fill="blue") window.mainloop()
1da3eaaae1aa570c05e330396cc49276fcb3a586
thewritingstew/lpthw
/ex11.py
2,135
4.09375
4
#============================================================ # beginning of original exercise #============================================================ print "How old are you?", age = raw_input() # accepts input with no prompt print "How tall are you?", height = raw_input('--> ') # accepts input with '--> ' prompt print "How much do you weigh?", weight = raw_input() # accepts input with no prompt print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight) #============================================================ # end of original exercise #============================================================ #============================================================ # beginning of extra practice with raw_input() #============================================================ ## variable to store a check for valid entry #is_valid = 0 # ## as long as is_valid is not true #while not is_valid : # # # try the following # try : # # # set choice to the raw_input if it is an integer # choice = int ( raw_input('How old are you (enter integer): ') ) # is_valid = 1 # set to 1 to validate input as integer # # # if an integer isn't entered by the user, then there will be a # # "ValueError" when the code tries to interpret it. The following # # couple lines of code catches that exception and handles it # # by printing another line. Once this has happened, the while loop # # repeats, which means the user will be asked for their age again. # except ValueError, e : # print ("'%s' is not a valid integer." % e.args[0].split(": ")[1]) # ## this if...elif...else sequence takes the integer and prints a response ## based on the value of the integer #if choice <= 12: # print ("You are a child...") #elif choice <= 19: # print ("You are a teenager...") #elif choice > 20: # print ("You are an adult...") #else: # print ("You aren't a teenager or a full adult...") #============================================================ # end of extra practice with raw_input() #============================================================
5122e3c1a8bc3853bee181705c6efc3664e7e1a4
kennedy0597/projects
/Python/fileHandling.py
874
3.9375
4
# writing a file # testtext = "aiosdjioasjodoajdjaso x,comaolsmdokqwokek,samocmoaskdoqmeo" # file_handler = open("test1.txt", "w") # file_handler.write(testtext) # file_handler.close() # reading file method 1 read_handler = open("test1.txt", "r").read() print(read_handler) # reading file method 2 line splitting read_handler = open("test1.txt", "r") for line in read_handler: print('*****', line.rstrip()) read_handler.close() # reading file method 3 word splitting rhandler = open("test1.txt", "r") for line in rhandler: print('*****', line.split()) rhandler.close() # reading file method 4 converting to list rhandler = open("test1.txt", "r") print(rhandler.readlines()) rhandler.close() # writing file file1 = open("test1.txt", "a") file1.write("\nHello nice") file1.close() rhandler = open("test1.txt", "r") print(rhandler.readlines()) rhandler.close()
e0d63f680849e7c642a5e14a7fab2bfe7c6772ba
nigelgomesot/ml
/statistical_methods/random_numbers.py
1,028
3.765625
4
# generate random numbers from random import seed from random import random from random import randint from random import gauss from random import choice from random import sample from random import shuffle print('\nseed ensures random function is deterministic') seed(1) print(random(), random(), random()) seed(1) print(random(), random(), random()) print('\nfloating point values') seed(1) for _ in range(10): value = random() print(value) print('\ninteger values') seed(1) for _ in range(10): value = randint(0, 10) print(value) print('\ngaussian values') seed(1) for _ in range(10): # gauss(mean, sd) value = gauss(0, 1); print(value) print('\nsequence') sequence = [i for i in range(20)] print(sequence) print('\nchoice from a list') seed(1) for _ in range(5): value = choice(sequence) print(value) print('\nsample from a list') seed(1) value = sample(sequence, 5) print(value) print('\nshuffle list') seed(1) print('sequence') print(sequence) value = shuffle(sequence) print('shuffle') print(sequence)
dbd7d68b55411336bc308c6cd28112e2c6c133c0
lvraikkonen/GoodCode
/leetcode/561_array_partition_I.py
428
3.6875
4
""" ็ป™ๅฎšไธ€ไธช้•ฟๅบฆไธบ2n็š„ๆ•ดๆ•ฐๆ•ฐ็ป„๏ผŒๅฐ†ๆ•ฐ็ป„ๅˆ†ๆˆn็ป„๏ผŒๆฑ‚ๆฏ็ป„ๆ•ฐ็š„ๆœ€ๅฐๅ€ผไน‹ๅ’Œ็š„ๆœ€ๅคงๅ€ผใ€‚ ๆ•ดไธชๆ•ฐ็ป„็š„ๆœ€ๅฐๅ€ผxๅ’Œไธ‹ไธ€ไธชๅ€ผ็š„min็ญ‰ไบŽx๏ผŒๆ‰€ไปฅๆฏ็ป„ๅ€ผ็š„ๅ’Œๆœ€ๅคง๏ผŒๅบ”่ฏฅ็ญ‰ไบŽๆŒ‰้กบๅบๆŽ’ๅˆ—ๅŽๅถๆ•ฐไฝ็ฝฎ็š„ๆ•ฐไน‹ๅ’Œ """ class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ return sum(sorted(nums)[::2])
c20138e40ec60d554c2ba8d7094812df3117c6e8
prachipatel2509/Sample-
/Assesment/n.py
279
3.8125
4
def sequence(x): l = [x] if x < 1: return [] while x > 1: if x % 2 == 0: x = x / 2 else: x = 3 * x + 1 l.append(x) return l if __name__=="__main__": n=int(input("Enter a no. :")) print(sequence(n))
5dc798779edd0f61d1b47a8dabe6149bea9d602d
ducoendeman/Introduction-to-Functional-Programming
/scripts/python/lab2.py
1,514
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 4 14:25:16 2019 @author: duco ------------------------------------------------------------------------------------------------------------------------------ -- Lab 2: Validating Credit Card Numbers ------------------------------------------------------------------------------------------------------------------------------ """ def toDigits(n): """ toDigits :: Integer -> [Integer] type n = int rtype = list (of ints) """ return [int(digit) for digit in str(n)] def toDigitsRev(n): """ toDigitRev:: Integer -> [Integer] type n = int retype = list (of ints) """ return list(reversed(toDigits(n))) def doubleSecond(xs): """ doubleSecond :: [Integer] -> [Integer] type xs = list (of integers) rtype = list (of integers) """ return [xs[i] if i%2 == 0 else 2*xs[i] for i in range(len(xs))] def sumDigits(xs): """ sumDigits :: [Integer] -> Integer type xs = list (of integers) rtype = integer """ return sum([int(digit) for number in xs for digit in str(number)]) def isValid(n): """ isValid :: Integer -> Bool type n = int rtype = Bool """ return n % 10 == 0 def creditcardValid(n): """ type n = int rtype = Bool """ return isValid(sumDigits(doubleSecond((toDigitsRev(n)))))
e4adb3621d03f1de0345f03086279ea58941b15b
hemapython/2ndnewlife
/40.py
904
3.9375
4
# writing program for exception handling #fox=[34,2,1,45,76,45,22,45] #print(fox[1:5]) #fox=(46,45,[45,12,34,21]) #print(fox.count(45)) # it will give output of how many times 45 present in tuple #print(fox.index(45)) #it will provide the index number of tuple #print(fox[2][3]) H=8 J=4 try: print(H/J) fox=int(input("enter the name")) print(fox) except ZeroDivisionError: print("it captures all devide by zero errors") except ValueError: print("it captures all invalid value errors") except Exception as e: print("it captures all the error which not comes under above 2 types of errors") else: print("if there is no exception in try block then it will print else no") finally: ("i can speak elegently i will aquire knowledge that is the only way y i have to come out of my fear , i wil do the things which scares me more")
fcdcbaffddc3c6caa7a14a05faadba16c7456f00
ththanhbui/dangerously-raw
/sort_rides.py
478
3.515625
4
def get_distance(row1,col1,row2,col2): return abs(row1-row2) + abs(col1-col2) def get_ride_length(ride): return get_distance(ride["start_col"], ride["start_row"], ride["fin_col"], ride["fin_row"]) def get_latest_possible_start_time(ride): return ride["latest_finish"] - get_ride_length(ride) # Take in a list of unclaimed rides # Return the rides sorted by the latest possible start time def sort_rides(rides): return sorted(rides, key=get_latest_possible_start_time)
06d318e6e265aa5c8cd77e233d4f8dd884dda706
KristianMSchmidt/Algorithms-specialization-stanford-
/Course_1/week3_quick_sort/quick_sort.py
3,203
4.28125
4
""" Implementation of Quick Sort with different strategies for chosing pivots. Random pivots are provably best, though. In particular, this exercise is about counting the number of comparisons when doing quick_sort. """ def partition_l(my_list, l, r): """ Partition subrutine to be used by quick sort. Partitions my_list[l,r] with respect to pivot my_list[l] """ pivot = my_list[l] #print pivot i = l + 1 for j in range(l + 1, r+1): #print i, j if my_list[j] < pivot: if i != j: my_list[i], my_list[j] = my_list[j], my_list[i] i += 1 my_list[l], my_list[i-1] = my_list[i-1], my_list[l] #right_pivot_pos = i-1 return my_list, i-1 def partition_median_of_three(my_list, l, r): """ Partition subrutine to be used by quick sort. Partitions my_list[l,r] where pivot is chosen as median of first, middle and last element """ m = l + (r - l)/2 #find pivot position num_l, num_m, num_r = my_list[l], my_list[m], my_list[r] if (num_l < num_m < num_r) or (num_r < num_m < num_l): pivot_pos = m elif num_m < num_l < num_r or num_r < num_l < num_m: pivot_pos = l else: pivot_pos = r #print "pivot", my_list[pivot_pos] # make pivot the first element my_list[l], my_list[pivot_pos] = my_list[pivot_pos], my_list[l] # use standard partition on new list return partition_l(my_list, l, r) #print partition_median_of_three([3,2,1,0],1,3) def partition_r(my_list, l, r): """ Partition subrutine to be used by quick sort. Partitions my_list[l,r] with respect to pivot my_list[r] """ my_list[l], my_list[r] = my_list[r], my_list[l] return partition_l(my_list, l, r) def test(): result = partition_r([2,3,1,-1,-2,0], 0, 5) print result #test() number_of_comparisons = 0 def quick_sort(my_list, l, r): """ Quick sort """ global number_of_comparisons if r == l: return my_list #choose method for choosing pivot #partitioned, right_pivot_pos = partition_l(my_list, l, r) partitioned, right_pivot_pos = partition_r(my_list, l, r) #partitioned, right_pivot_pos = partition_median_of_three(my_list, l, r) number_of_comparisons += (r-l) left_part = quick_sort(partitioned, l, max(l, right_pivot_pos - 1)) right_part = quick_sort(left_part, min(right_pivot_pos + 1, r), r) return my_list #print quick_sort([9,-1,2,8,18],0,4) #print number_of_comparisons def run_quick_sort(my_list): return quick_sort(my_list, 0, len(my_list)-1) def import_data(): import urllib2 URL = "https://d3c33hcgiwev3.cloudfront.net/_32387ba40b36359a38625cbb397eee65_QuickSort.txt?Expires=1514678400&Signature=UbQM4sANM7dVrQtz0DJ1850w5dkkwl-eJtx0ZC7Jz7KHjiVA4WxrBVeAUIaf76DAvLl7jPjrOrix4mvUu1Noti31wozK~70jT22V-uPuTr2YrWSCW4a1cRgEUcvHMK-necnAB1l5Kon6Bi1dc7N0dU6cywsat3EyPNOdDijaxW0_&Key-Pair-Id=APKAJLTNE6QMUY6HBC5A" data_file = urllib2.urlopen(URL) data = data_file.read() data_lines = data.split('\n') data_lines = data_lines[:-1] data_lines = [int(number) for number in data_lines] print "Data has been loaded and cleaned" print run_quick_sort(data_lines)[-10:] print "Total number of comparisons made under recursive partitioning:", number_of_comparisons import_data()
3245cd7599855b8e7fb391c3eef760395bd6c354
frclasso/CodeGurus_Python_mod2_turma1
/Cap01-sintaxe_especifica/dict_comprehension/script3.py
653
3.890625
4
dict1 = { 'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, } dict1_comp = {k:v for(k,v) in dict1.items() if v > 2} print(dict1_comp) # for k, v in dict1.items(): # if v > 2: # print(k,':', v) dict2_comp = {k:v for(k, v) in dict1.items() if v > 2 if v % 2 == 0} print(dict2_comp) # for k, v in dict1.items(): # # if v > 2: # # if v % 2 == 0: # # print(k,':', v) dict3_comp = {k:v for(k, v) in dict1.items() if v > 2 if v % 2 == 0 if v % 3 == 0} print(dict3_comp) # for k, v in dict1.items(): # if v > 2: # if v % 2 == 0: # if v % 3 == 0: # print(k,':', v)
957dbff70c969826eca5cc9ad954a7cdd7c98e3b
divyavani-gmail/ASSIGNMENT2
/9.py
263
3.65625
4
# 9. Select the rows the age is between 2 and 4(inclusive) import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["divya_db"] mycol = mydb["vani_data"] myquery = mycol.find({"age":{"$gte":2 ,"$lte":4}}) print(list(myquery))
6022befaf5be41b18bf0219cd41afba79e533af0
Franklin-Wu/project-euler
/p109.py
3,883
3.875
4
# Darts # Problem 109 # # In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty. # # (Only 1 of 20 sectors is shown.) # # +--------------------+ # \ [1 - 20] / # +----------------+ # \ double / # +------------+ # | | # | | # | | # | single | # | | # | | # | | # +------------+ # \ triple / # +--------+ # | | # | | # | | # | | # | | # | single | # | | # | | # | | # | | # | | # +--------+ # \ 25 / # +----+ # | 50 | # +----+ # # The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively. # # At the centre of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points. # # There are many variations of rules but in the most popular game the players will begin with a score 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the centre of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust". # # When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). # # There are exactly eleven distinct ways to checkout on a score of 6: # D3 # D1 D2 # S2 D2 # D2 D1 # S4 D1 # S1 S1 D2 # S1 T1 D1 # S1 S3 D1 # D1 D1 D1 # D1 S2 D1 # S2 S2 D1 # Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. # # In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3. # # Incredibly there are 42336 distinct ways of checking out in total. # # How many distinct ways can a player checkout with a score less than 100? import time; start_time = time.time(); def print_execution_time(): print 'Execution time = %f seconds.' % (time.time() - start_time); N = 100; singles = range(1, 21); triples = [x * 3 for x in singles]; singles.append(25); doubles = [x * 2 for x in singles]; aggregate = [0]; aggregate.extend(singles); aggregate.extend(doubles); aggregate.extend(triples); aggregate.sort(); aggregate_count = len(aggregate); doubles_count = len(doubles); count_total = 0; count_less_than_N = 0; for aggregate_index_1 in range(aggregate_count): # This range does not compensate for the S1 T1 D1 / T1 S1 D1 equivalence: # for aggregate_index_2 in range(aggregate_count): # This range compensates for the S1 T1 D1 / T1 S1 D1 equivalence: for aggregate_index_2 in range(aggregate_index_1, aggregate_count): for doubles_index_3 in range(doubles_count): count_total += 1; if (aggregate[aggregate_index_1] + aggregate[aggregate_index_2] + doubles[doubles_index_3]) < N: count_less_than_N += 1; print "Of the %d distinct ways of checking out, %d are with a score less than %d." % (count_total, count_less_than_N, N); print; print_execution_time();
b8690eefe5eae06ad8683af44c4408f9a828f17d
alondavid/Self.Py
/ex535.py
509
4.15625
4
#ex 535 def distance(num1, num2, num3): '''int,int,int > Bool the Function return True if: (num2 - num1 or num3 - num1 = abs(1)) and (num2 - num1 or num2 - num3 or num3 - num1 > abs(2)). >>> distance(1, 2, 10) True >>> distance(4, 5, 3) False ''' if (abs(num3 - num1) == 1 or abs(num2 - num1) == 1) and (abs(num2 - num3) > 2 or abs(num2 - num1) > 2 or abs(num3 - num1) > 2): return True return False
dc9cb6cd006928b9923b0016dfd45a1925a996e3
siimkollane/programm
/uusaastalubadus.py
324
3.5
4
import tkinter as tk def write_slogan(): print("Saan geo perioodihinde positiivse.") root = tk.Tk() frame = tk.Frame(root) frame.pack() button = tk.Button() slogan = tk.Button(frame, text="Vajuta minu peale!", command=write_slogan) slogan.pack(side=tk.LEFT) root.mainloop()
68392a4a749bc340fa76b447ab93cd63fcdecf0b
praveenkumarsrivas/Python-3_Programming
/Hackerrank-Python3/mean_varr_std.py
592
3.921875
4
# Output Format # First, print the mean. # Second, print the var. # Third, print the std. # Sample Input # 2 2 # 1 2 # 3 4 # Sample Output # [1.5 3.5] # [1. 1.] # 1.11803398875 import numpy n, m = input().split() n = int(n) m = int(m) l = list() arr = list() arr = [] x = 0 i = 0 for x in range(n): l = input() l = [int(y) for y in l.split(" ")] arr.append(l) #print(arr) numpy.set_printoptions(legacy='1.13') # np.arr().astype(np.int) print(numpy.mean(arr, axis=1)) print(numpy.var(arr, axis=0)) print(numpy.std(arr, axis=None)) #read about the function set_printoptions
5a2fa7376d2a2ca37f4d29194f5e40a67fb83025
xiasiliang-hit/leetcode
/island_num.py
1,705
3.65625
4
## now work ! import pdb import Queue #visited = [] #matrix = [] #X = 0 #Y = 0 #num = 0 class Solution(object): def __init__(self): global X, Y, visited, num X = len(matrix[0]) Y = len(matrix) visited = [[False for x in range(X) ] for y in range(Y)] self.num = 0 def island_num(self): #X = len(matrix[0]) #Y = len(matrix) for j in range(Y): for i in range(X): if visited[j][i] == False and matrix[j][i] == 1: self.expand(i, j) # elif matrix[j][i] == 0: # visited[j][i] = True # continue print visited return self.num def expand(self, coordx, coordy): # X = len(matrix[0]) # Y = len(matrix) print coordx, coordy q = Queue.Queue() q.put((coordx, coordy)) # visited[coordy][coordx] = True while q.empty() is False: (i, j) = q.get() visited[j][i] = True around = [(i-1, j), (i+1, j), (i, j-1), (i, j+1)] tested = filter(lambda coord : coord[0]>=0 and coord[0]<= X-1 and coord[1] >= 0 and coord[1] <= Y-1, around) for coordxy in tested: print coordxy if visited[coordxy[1]][coordxy[0]] == False and matrix[coordxy[1]][coordxy[0]] == 1: q.put(coordxy) self.num = self.num + 1 if __name__ == "__main__": global matrix matrix = [[0,1],[1,0], [0,1],[1,0]] s = Solution() print s.island_num()
b0322a6833f1563300b1b02745d458b6cdbc1462
fedhere/StatisticalCompass
/main.py
1,156
3.6875
4
import numpy as np import pandas as pd from transform import transform # Load the questions questions = pd.read_csv('questions.csv') # Initialise the position of the user at the origin pos = np.zeros(3) input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): ' # Using a C-style loop over questions without apology for i in range(0, questions.shape[0]): # Check the question satisfies a basic sanity check norm = np.linalg.norm(questions.iloc[i, 1:]) if norm > 2.: print('# WARNING: Very influential question.') elif norm < 0.5: print('# WARNING: Very uninfluential question.') # Print the question print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0])) print(questions.iloc[i, 0] + '\n') # Get the user's response response = None # Placeholder value while response < -2. or response > 2.: response = input(input_text) # Increment the user's position pos += response*questions.iloc[i, 1:].values # Apply some scaling to the position based on how far it was possible # to move in each dimension print(pos) pos = transform(pos, questions)[0] print('Your position in 3D is ' + str(pos) + '.')
3cd369cc0526d0f81349961ce3150c0ef97f83e8
tartaponei/URI
/iniciante/1064positivosmedia.py
165
3.640625
4
p = 0 s = 0 for i in range(6): n = float(input("")) if(n > 0): p += 1 s = s + n print(p, "valores positivos") print("{:.1f}" .format(s / p))
c7c75378f36e39183bd6a9510e405951cfd1c805
CeruleanOwl/Python-Practice
/RockPaperScissors.py
2,612
4.0625
4
'''Global Variables''' rockC = False scissorsC = False paperC = False rockU = False scissorsU = False paperU = False #computer logic def computer_choice(): #import random module import random #request global variables global rockC global paperC global scissorsC #Random int generator between 1-3 computer = random.randint(1,3) #Conditions for which random number is selected if computer == 1: rockC = True print('Computer chose rock.') elif computer == 2: paperC = True print('Computer chose paper.') elif computer == 3: scissorsC = True print('Computer chose scissors.') #player logic def player_choice(): #request global variables global rockU global paperU global scissorsU #default choice to zero and requesting parameters to True choice = 0 requesting = True #Logic for user selecting choice and protecting from bad user selections while requesting: try: while choice not in range(1,4): choice = int(input('Please select Rock(1), Paper(2), or Scissors(3).\n')) except ValueError: print('That wasn\'t a selection. Try again.') if choice in range(1,4): requesting = False #Conditions based on user selection if choice == 1: rockU = True print('You chose rock.') elif choice == 2: paperU = True print('You chose paper.') elif choice == 3: scissorsU = True print('You chose scissors.') #Decides who wins def win_condition(): #request global variables global rockC global rockU global paperC global paperU global scissorsC global scissorsU #Rock user condition against computer conditions. if (rockU == True) and (rockC == True): print('It was a draw.') elif (rockU == True) and (paperC == True): print('You Lose!') elif (rockU == True) and (scissorsC == True): print('You Win!') elif (paperU == True) and (paperC == True): print('It was a draw.') elif (paperU == True) and (rockC == True): print('You win!') elif (paperU == True) and (scissorsC == True): print('You lose!') elif (scissorsU == True) and (scissorsC == True): print('It was a draw.') elif (scissorsU == True) and (paperC == True): print('You win!') elif (scissorsU == True) and (rockC == True): print('You lose!') #game logic def play_game(): player_choice() computer_choice() win_condition() play_game()
a9aded09b71a15dc2be4deabeb1bbd5655c88a27
calvar122/EXUAGO2021-VPE-L1
/0929/jose.benavides/serieFub.py
712
3.90625
4
#!/usr/bin/env python3 # c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil # vi: set shiftwidth=4 tabstop=8 expandtab: # :indentSize=4:tabSize=8:noTabs=true: # # SPDX-License-Identifier: GPL-3.0-or-later #fn = fn-1 + fn-2 #Funcion recursiva para la serie de Fibonacci def fibo(num): if num == 0: return 0 elif num == 1: return 1 else: return fibo(num - 1) + fibo(num - 2) #Se pide al usuario que ingrese un dato n = eval(input("Ingrese un numero y te regresare el elemento correspondiente a la serie de Fibonacci: ")) #Se guarda el retorno de la funcion elemento = fibo(n) #Se imprime el resultado print(f"El {n} corresponde a {elemento} en la serie de Fibonacci")
ac3420ed1d71fbab98b8155a84e77c68262290af
amarinas/algo
/chapter_1_fundamentals/final_countdown.py
396
3.796875
4
# given 4 params # print the multiples of param 1 starting at param 2 and extending to param 3 # if a multiple is equal to param 4 then skip #given( 3,5,17,9) expected (6,12,15) def final_count(param1,param2,param3,param4): count = param3 while count > param2: if count % param1 == 0 and count != param4: print count count = count - 1 final_count(3,5,17,9)
c30f6563e12403ce7de4281da1d7a25e2cad3c58
MsDiala/data-structures-and-algorithms-python
/data_structures_and_algorithms/challenges/array_reverse/array_search.py
317
3.921875
4
def binary_search(arr, key): low = 0 high = len(arr) while len(arr) > 0: middle = (low+high) // 2 if arr[middle] == key: return middle if arr[middle] < key: low= middle if arr[middle] > key: high= middle if middle == 0 or middle == len(arr) - 1: return -1 return -1
4b85eb0e9e1462ab0bd1728f4ed1fba33ee99179
ngpark7/deeplink_public
/2.ReinforcementLearning/MCTS/mcts.py
9,222
3.5
4
# For more information about Monte Carlo Tree Search check out our web site at www.mcts.ai # http://mcts.ai/about/index.html from math import * import random def upper_confidence_bounds(node_value, num_parent_visits, num_node_visits): """ the UCB1 formula """ return node_value + sqrt(2 * log(num_parent_visits) / num_node_visits) class OXOEnv: """ A state of the game, i.e. the game board. Squares in the board are in this arrangement 012 345 678 where 0 = empty, 1 = player 1 (X), 2 = player 2 (O) """ def __init__(self): self.current_player = 1 # At the root pretend the current player 'Player 1' self.board = [0, 0, 0, 0, 0, 0, 0, 0, 0] # 0 = empty, 1 = player 1, 2 = player 2 def clone(self): """ Create a deep clone of this game state. """ env = OXOEnv() env.current_player = self.current_player env.board = self.board[:] return env def do_move(self, location): """ Update a state by carrying out the given move. Must update playerToMove. """ assert 8 >= location >= 0 == self.board[location] and location == int(location) self.board[location] = self.current_player if self.current_player == 1: self.current_player = 2 elif self.current_player == 2: self.current_player = 1 else: assert False def get_possible_locations(self): """ Get all possible moves from this state. """ return [i for i in range(9) if self.board[i] == 0] def get_result(self, player_just_moved): """ Get the game result from the viewpoint of playerjm. Case == 1.0: player 1 win, Case == 2.0: player 2 win, Case == 3.0: both player 1 and 2 win (draw) """ case = 0.0 for (x, y, z) in [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]: if self.board[x] == self.board[y] == self.board[z] == player_just_moved: case += 1 elif self.board[x] == self.board[y] == self.board[z] == (3 - player_just_moved): case += 2 if case == 1: return 1 # player 1 win elif case == 2: return 2 # player 2 win elif case == 3 or not self.get_possible_locations(): print("draw - ", case) return 0 # draw else: return -1.0 # continue assert False # Should not be possible to get here def __repr__(self): s = "" for i in range(9): s += ".XO"[self.board[i]] if i % 3 == 2: s += "\n" return s[0:-1] class Node: """ A node in the game tree. Note wins is always from the viewpoint of current_player. Crashes if state not specified. """ def __init__(self, location=None, parent=None, env=None): self.location = location # "None" for the root node self.parent_node = parent # "None" for the root node self.child_nodes = [] self.wins = 0 self.visits = 0 self.unvisited_locations = env.get_possible_locations() # future child nodes def uct_select_child(self): """ Use the UCB1 formula to select a child node. Often a constant UCTK is applied so we have UCB1 to vary the amount of exploration versus exploitation. """ s = sorted( self.child_nodes, key=lambda c: upper_confidence_bounds(c.wins / c.visits, self.visits, c.visits) )[-1] return s def add_child(self, loc, env): """ Remove loc from untried_locations and add a new child node for the location loc. Return the added child node """ n = Node(location=loc, parent=self, env=env) self.unvisited_locations.remove(loc) self.child_nodes.append(n) return n def update(self, result): """ Update this node - one additional visit and result additional wins. result must be from the viewpoint of current_player. """ self.visits += 1 self.wins += result def to_tree_string(self, indent): s = self.indent_string(indent) + str(self) for c in self.child_nodes: s += c.to_tree_string(indent + 1) return s @staticmethod def indent_string(indent): s = "\n" for i in range(1, indent + 1): s += "| " return s def to_children_string(self): s = "" for c in self.child_nodes: s += str(c) + "\n" return s def __repr__(self): return "[Location: {0}, W/V: {1}/{2}, U: {3}, Child Nodes: {4}]".format( self.location, self.wins, self.visits, str(self.unvisited_locations), str([x.location for x in self.child_nodes]) ) def search_by_uct(env, iter_max, verbose=False): """ Conduct a UCT (Upper Confidence Bounds for Trees) search for itermax iterations starting from rootstate. Return the best move from the root_node. Assumes 2 alternating players (player 1 starts), with game results in the range [1, 2, 0, -1]. """ root_node = Node(location=None, parent=None, env=env) print("[Search By UCT]") for i in range(iter_max): node = root_node env2 = env.clone() # Select while node.unvisited_locations == [] and node.child_nodes != []: # node is fully expanded and non-terminal node = node.uct_select_child() env2.do_move(node.location) print("Iter: {0}, Player {1} selects the best child node {2}".format( i, env2.current_player, node.location )) # Expand if node.unvisited_locations: # if we can expand (i.e. state/node is non-terminal) m = random.choice(node.unvisited_locations) env2.do_move(m) print("Iter: {0}, Player {1} expands to an arbitrary location {2}".format( i, env2.current_player, m )) node = node.add_child(m, env2) # add child and descend tree # Rollout - this can often be made orders of magnitude quicker using a state.GetRandomMove() function j = 0 while env2.get_possible_locations(): # while state is non-terminal m = random.choice(env2.get_possible_locations()) env2.do_move(m) print("Iter: {0} and {1}, Player {2} rolls out to the location {3}".format( i, j, env2.current_player, m )) j += 1 # Backpropagate j = 0 print("{0} - Cloned Env:\n{1}".format(3 - env.current_player, env2)) while node: # backpropagate from the expanded node and work back to the root node node.update(env2.get_result(3 - env.current_player)) # state is terminal. Update node with result from # point of view of 3 - env.current_player print("Iter: {0}, {1}, Evaluate the node {2}: Wins/Visits - {3}/{4}".format( i, j, node.location, node.wins, node.visits )) node = node.parent_node j += 1 print() # Output some information about the tree - can be omitted if verbose: print(root_node.to_tree_string(0)) else: print(root_node.to_children_string()) return sorted(root_node.child_nodes, key=lambda c: c.visits)[-1].location # return the move that was most visited def play_game(verbose=True): """ Play a sample game between two UCT players where each player gets a different number of UCT iterations (= simulations = tree nodes). """ # state = OthelloState(4) # uncomment to play Othello on a square board of the given size env = OXOEnv() # uncomment to play OXO # state = NimState(15) # uncomment to play Nim with the given number of starting chips while env.get_possible_locations(): print("Original Env:\n{0}".format(env)) if env.current_player == 1: m = search_by_uct(env=env, iter_max=2, verbose=verbose) # Player 1 else: m = search_by_uct(env=env, iter_max=2, verbose=verbose) # Player 2 print("Best Move: " + str(m) + "\n") env.do_move(m) print("Original Env:\n{0}".format(env)) if env.get_result(env.current_player) == 1: print("Player " + str(env.current_player) + " wins!") break elif env.get_result(env.current_player) == 2: print("Player " + str(3 - env.current_player) + " wins!") break elif env.get_result(env.current_player) == 0: print("Nobody wins!") break elif env.get_result(env.current_player) == -1: print("Continue...\n") else: assert False if __name__ == "__main__": play_game()
589a566083cb9ffa0f331aed0930d7b0bfae4bdb
Clanrat/adventofcode
/day9.py
1,017
3.953125
4
import sys import itertools def shortest(cities, dest): travel_plans = itertools.permutations(cities, len(cities)) return [calc_distance(travel_plan, dest) for travel_plan in travel_plans] def calc_distance(travel_plan, dest): distance = 0 for i in range(1, len(travel_plan)): distance += int(dest[travel_plan[i - 1]][travel_plan[i]]) return distance def main(): lines = open(sys.argv[1], 'r').readlines() dest = {} cities = [] for line in lines: cp, distance = line.strip('\n').split(' = ') city1, city2 = cp.split(' to ') if city1 not in dest: dest[city1] = {} cities.append(city1) if city2 not in dest: dest[city2] = {} cities.append(city2) dest[city1][city2] = distance dest[city2][city1] = distance traveling_distances = shortest(cities, dest) print(min(traveling_distances)) print(max(traveling_distances)) if __name__ == '__main__': main()
be4022313e80f64fab6e48bbdfb59b439e177bbe
CodedBrackets/python_cricket
/hello.py
685
3.875
4
print("Hello World!") for i in range(10): print("\t",i) print("\tBananazzzzz") mylist=[] mylist.append("Apple") mylist.append("Banana") mylist.append("Grapes") print(mylist) print("Square of 5 is : ",5**2) x = object() y = object() # TODO: change this code x_list = [x] * 10 y_list = [y] * 10 big_list = x_list + y_list print("x_list contains %d objects" % len(x_list)) print("y_list contains %d objects" % len(y_list)) print("big_list contains %d objects" % len(big_list)) # testing code if x_list.count(x) == 10 and y_list.count(y) == 10: print("Almost there...") if big_list.count(x) == 10 and big_list.count(y) == 10: print("Great!")
6d935feba24dec9ef75a85a4e9d81e47419fdbe4
gauravdhmj/Project
/Tuples.py
2,546
4.09375
4
t = "a", "b", "c" print(t) print("a", "b", "c") print(("a", "b", "c")) welcome = "Welcome to my Nightmare", "Alice Cooper", 1975 bad = "Bad Company", "Bad Company", 1974 budgie = "Nightflight", "Budgie", 1981 imelda = "More Mayhem", "Imelda May", 2011 metallica = "Ride the Lightning", "Metallica", 1984 print(metallica) print(metallica[0]) print(metallica[1]) print(metallica[2]) # # metallica[0] = "Master of puppets" imelda = imelda[0], "Imelda May", imelda[2] print(imelda) # A LIST HAS A MUTABLE OBJECT WHILE A TUPLE HAS AN IMMUTABLE OBJECT # metallica2 = ["Ride the Lightning", "Metallica", 1984] print(metallica2) metallica2[0] = "master of puupets" print(metallica2) # # RIGHT HAND ASSIGNMENT IS EVALUATED FIRST THAN THE LEFT HAND SIDE a = b = c = d = 12 print(c) a, b = 12, 13 print(a, b) a, b = b, a print("a is {}".format(a)) print("b is {}".format(b)) # UNPACKING A TUPLE metallica2.append("rock") title, artist, year,n = metallica2 print(title) print(artist) print(year) print(n) # imelda.append("Jazz") welcome = "Welcome to my Nightmare", "Alice Cooper", 1975 bad = "Bad Company", "Bad Company", 1974 budgie = "Nightflight", "Budgie", 1981 imelda = "More Mayhem", "Imilda May", 2011, ( (1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Waltz")) print(imelda) title, artist, year, tracks = imelda print(title) print(artist) print(year) print(tracks) # Given the tuple below that represents the Imelda May album "More Mayhem", write # code to print the album details, followed by a listing of all the tracks in the album. # # Indent the tracks by a single tab stop when printing them (remember that you can pass # more than one item to the print function, separating them with a comma). # imelda = "More Mayhem", "Imelda May", 2011, ( # (1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Waltz")) # print(imelda) title, artist, year, tracks = imelda print(title) print(artist) print(year) for song in tracks: track, title = song print("\tTrack number {}, Title: {}".format(track, title)) # # A TUPLE CONTAINING A LIST imelda = "More Mayhem", "Imelda May", 2011, ( [(1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Waltz")]) print(imelda) imelda[3].append((5, "All For You")) title, artist, year, tracks = imelda tracks.append((6, "Eternity")) print(title) print(artist) print(year) for song in tracks: track, title = song print("\tTrack number {}, Title: {}".format(track, title))
d1882c89bbfb5505bc97fb43f841e902398461ca
LordVendrik/Python-Bot
/Automation/s.py
270
3.6875
4
import pyperclip import re text = str(pyperclip.paste()) ph = re.compile(r'#write what you want to find',re.I) mo = ph.findall(text) if len(mo) > 0: for i in range(len(mo)): print('Mobile NUmber (' +str(i) +')' +mo[i]) else: print('No NUmber found')
593ca9ac9ce2fb37c8b6422acd7b33ba116fd613
CDeividi/CDeividi
/exercicio 2.py
417
3.875
4
while(True): try: codigo=int(input('Insira o cรณdigo que deseja emitir digito verificador: \n')) except ValueError: print('Sรฃo vรกlidos somente nรบmeros inteiros !') continue if(codigo < 10000 or codigo > 30000): print('Suportado apenas valores inteiros menores de 10000 e maiores de 30000') continue
5f693a4306f1583f247405d8e551f15ebdff81ac
tcanfield/web
/sudoku/board.py
5,920
4.03125
4
import math class sudoku_board: #Initialize the board by passing in a string representing the board #positions in order top to bottom, left to right. Use 0 to represent #empty spaces # #arg board: String representation of the board. #Positions listed in order left to right, top to bottom. 0 for empty spaces. # #arg size: The maximum number of the board. e.g. size=9 for a 9x9 board def __init__(self, board_string, size): if len(board_string) != size*size: raise ValueError("Number of board positions does not match board size." +str(len(board_string)) +str(size)) #for i in range(size): # for j in range(size): # self.board_positions[i][j] = board[(i*9)+j] #This loop as a list comprehension: self.board_positions = [[board_string[(i*9)+j] for j in range(size)]for i in range(size)] self.size = size #Getter/setters: def set_cell(self, row, col, val): self.board_positions[row][col] = val def get_cell(self, row, col): return self.board_positions[row][col] def get_board(self): return self.board_positions def get_single_string(self): string = "" for i in range(self.size): for j in range(self.size): string = string + str((self.board_positions[i][j])) return string def __str__(self): string = "" for i in range(self.size): string = string + str((self.board_positions[i])) + "\n" return string class sudoku_solve: #Create a sudoku board to start with def __init__(self, board_string, size): self.starting_board = sudoku_board(board_string, size) self.size = size self.stack = [] def solve(self): return self.solve_dfs(self.starting_board, 0, 0) def solve_dfs(self, board, row=0, col=0): #Base Case if self.is_solved(board): self.solved_board = board return self.solved_board #Find a valid number for a cell and recursively keep going if board.get_cell(row, col) == '0': for i in range(1, self.size+1): if self.valid_cell(board, row, col, str(i)): board.set_cell(row, col, str(i)) self.solve_dfs(board, self.next_row(row, col), self.next_col(col)) if self.is_solved(board): return self.solved_board #If we get here we have backtracked, so set this row/col back to 0 and keep trying board.set_cell(row, col, '0') else: self.solve_dfs(board, self.next_row(row,col), self.next_col(col)) if self.is_solved(board): return self.solved_board def next_row(self, row, col): if col is 8: return row+1 else: return row def next_col(self, col): if col is 8: return 0 else: return col+1 def prev_row(self, row, col): if col is 0: return row-1 else: return row def prev_col(self, col): if col is 0: return 8 else: return col-1 def is_solved(self, board): rows_solved = True for i in range(self.size): row = [] for j in range(self.size): row.append(board.get_cell(i,j)) if j is self.size-1: if not (set(['1','2','3','4','5','6','7','8','9']) <= set(row)): rows_solved = False break cols_solved = True for i in range(self.size): col = [] for j in range(self.size): col.append(board.get_cell(j,i)) if j is self.size-1: if not (set(['1','2','3','4','5','6','7','8','9']) <= set(col)): rows_solved = False break return (rows_solved and cols_solved) def valid_cell(self, board, row, col, value): #Make sure number is not already in this row row_values = [] for i in range(self.size): row_values.append(board.get_board()[row][i]) if value in row_values: return False #Make sure number is not already in this col col_values = [] for i in range(self.size): col_values.append(board.get_board()[i][col]) if value in col_values: return False #Makre sure number is not already in this square. (square is sqrt(size) x sqrt(size) square) total_squares = self.size square_size = int(math.sqrt(total_squares)) #Find which square the row/col is in square_num = (int((row/square_size))*square_size) + int((col/square_size)) #Check each cell in that square and see if the value is already in it for row in range(square_size): for col in range(square_size): cell = board.get_board()[row + (int((square_num/square_size))*square_size)][col + ((square_num%square_size)*square_size)] if value == cell: return False #If none of the checks return false return true return True #start_time = time.time() #board_string = "000037600000600090008000004090000001600000009300000040700000800010009000002540000" #board = sudoku_board(board_string, 9) #solver = sudoku_solve(board_string, 9) #print(solver.solve())
b7942016a2fc747501a19583d7e239063cac29de
flame4ost/Python-projects
/additional tasks x classes/Fraction.py
1,106
3.953125
4
class Fraction: # numerator: int value = 0 def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator print(str(self.numerator) + ' | ' + str(self.denominator)) def calculateSum(self): sum = self.makeSum(self.numerator, self.denominator) print("Sum : " + str(sum)) pass @staticmethod def makeSum(numerator, denominator): return numerator + denominator def showDifference(self): difference = self.numerator - self.denominator print("Difference : " + str(difference)) pass def showProduct(self): product = self.numerator * self.denominator print("Product : " + str(product)) pass def showDivide(self): divide = self.numerator / self.denominator print("Divide : " + str(divide)) pass print("Input denominator: ") newDenominator = int(input()) print("Input nomerator: ") newNumerator = int(input()) f = Fraction(newNumerator, newDenominator) f.calculateSum() f.showDifference() f.showProduct() f.showDivide()
d2dd0e571bfa6da3e1b693fdb54dee89ec8252a1
danae678/techx-appliedds
/Associative Arrays/firstNonrepeated.py
577
4.28125
4
# Find the first non-repeated character in a string. # Some things you can reason from the example: # The return value is the non-repeated character itself, as opposed to the index or some other value # Example: # Input: input_string = "supercalifragilisticexpialidocious" # Output: "f" import collections def first_nonrepeat(word): dictionary = collections.Counter(word) for i in dictionary: if dictionary[i] == 1: return i return None print(first_nonrepeat("hello")) print(first_nonrepeat("supercalifragilisticexpialidocious"))
b85971cf4844976a2469e693f4d15098afc7b3ad
mk270/dot-home
/bin/newmonth
583
3.71875
4
#!/usr/bin/env python import datetime import sys import calendar def run(): try: _, month, year = sys.argv except: print >>sys.stderr, "Usage: newmonth month year" m = int(month) y = int(year) print "\n%s %d\n" % (calendar.month_name[m].upper(), y) for day in xrange(0, calendar.monthrange(y, m)[1]): d = day + 1 date = datetime.datetime(y, m, d) w = date.strftime('%a') sun = {True: "\n", False: ""}[date.weekday() == 6] print "%s %0.2d:%s" % (w, d, sun) if __name__ == '__main__': run()
965b9effdbebe69659fb6418c06c998fca135c23
damodardikonda/Python-Basics
/core2web/Week5/patt.py
308
3.609375
4
''' Program 4: Write a Program to Print following Pattern. A B A C B A D C B A ''' ch="A" for i in range(4): for j in range(4): if j<3-j: print("",end="\t") else: print(ch,end="") ch=(chr(ord(ch))-1) print() ch=(chr(ord('A'))+j+1)
c02abd392e2efc34120880783b208efcdadd3afe
sihyeonn/Sunday
/Python/๋ชจ๋‘์˜ ํŒŒ์ด์ฌ/13B-walk.py
735
3.890625
4
import turtle as t import random MOVE = 10 def turn_right(): t.setheading(0) t.forward(MOVE) def turn_up(): t.setheading(90) t.forward(MOVE) def turn_left(): t.setheading(180) t.forward(MOVE) def turn_down(): t.setheading(270) t.forward(MOVE) def blank(): t.clear() def change_color(): x = random.randint(0, 10) mod = x % 3 if mod == 0: t.color("red") elif mod == 1: t.color("yellow") else: t.color("blue") t.shape("turtle") t.speed(0) t.onkeypress(turn_right, "Right") t.onkeypress(turn_up, "Up") t.onkeypress(turn_left, "Left") t.onkeypress(turn_down, "Down") t.onkeypress(blank, "Escape") t.onkeypress(change_color, "space") t.listen()
afc73f4034232443ae0551f480e34983fef334ba
andrea2910/c4v2020
/code/indicators/dialysis_indicator.py
5,353
4.03125
4
import pandas as pd def dialysis_indicator(df): """ dialysis.py ------------------ This Function calculates the dialysis indicator, a metric that measures whether or not dialysis can be performed in the hospital in that particular state Logic ----- First, the function cleans the variables that is related to dialysis by imputing missing values to 0 or converting necessary categorical columns to numerical values Then it manually classifies the components required for a dialysis into 5 types and their indicator variables: Materials ('materials_surgery'), staff ('staff_surgery'), Reverse Osmosis unit operability ('flag_rrt_reverse_osmosis_unit_operability'), hospital operability('flag_rrt_operability'), and Number of Hemodialysis equipments operability('flag_rrrt_num_hemodialysis_equipments_operability'). Value: 1 would indicate the components required is fulfilled 0 would indicate there is at least one missing component The following variables from the dataset will be classified into 'materials_surgery' 'rrt_hemodialysis_avail_filter', 'rrt_hemodialysis_avail_lines', 'rrt_hemodialysis_avail_kit_hemodialysis', 'rrt_hemodialysis_avail_iron', 'rrt_hemodialysis_avail_b_complex', 'rrt_hemodialysis_avail_calcium', 'rrt_hemodialysis_avail_zemblar', 'rrt_reverse_osmosis_unit_operability' The following variables from the dataset will be classified into 'staff_surgery' 'rrt_staff_nephrology', 'rrt_staff_md', 'rrt_staff_resident', 'rrt_staff_nurse', 'rrt_staff_nurse_nephrologist' Then a status indicator variable is created for these 5 types of data: ('XXXXX') When all 5 of the indicator variables is met, it means that the dialysis can be done Value of ('XXXXX'): 1 = dialysis can be performed 0 = dialysis cannot be performed Input ----- Pandas Dataframe Output ------ Pandas Series """ dialysis = df.copy() # Imputing blank spaces dialysis.replace(r'^\s*$', "Unknown", regex=True, inplace = True) # Imputing nulls with 0 dialysis = dialysis.fillna(0) # Temp column for feature engineering for material dialysis['materials'] = dialysis[[ 'rrt_hemodialysis_avail_filter', 'rrt_hemodialysis_avail_lines', 'rrt_hemodialysis_avail_kit_hemodialysis', 'rrt_hemodialysis_avail_iron', 'rrt_hemodialysis_avail_b_complex', 'rrt_hemodialysis_avail_calcium', 'rrt_hemodialysis_avail_zemblar', 'rrt_reverse_osmosis_unit_operability', ]].sum(axis=1) # Temp Column, can do surgery or no, based on availability of the supplies (filter : zemblar) dialysis['materials_surgery'] = 0 for index, val in dialysis.iterrows(): if dialysis.loc[index,'materials'] == 0: dialysis.loc[index,'materials_surgery'] = 0 else: dialysis.loc[index,'materials_surgery'] = 1 # Temp column for feature engineering for material dialysis['staffs'] = dialysis[[ 'rrt_staff_nephrology', 'rrt_staff_md', 'rrt_staff_resident', 'rrt_staff_nurse', 'rrt_staff_nurse_nephrologist']].sum(axis=1) dialysis['staff_surgery'] = 0 # Temp Column, can do surgery or no, based on availability of the supplies (filter : zemblar) for index, val in dialysis.iterrows(): if dialysis.loc[index,'staffs'] == 0: dialysis.loc[index,'staff_surgery'] = 0 else: dialysis.loc[index,'staff_surgery'] = 1 # Temp feature for RO unit dialysis['flag_rrt_reverse_osmosis_unit_operability'] = 0 for index, val in dialysis.iterrows(): if dialysis.loc[index,'rrt_reverse_osmosis_unit_operability'] == 0: dialysis.loc[index,'flag_rrt_reverse_osmosis_unit_operability'] = 0 else: dialysis.loc[index,'flag_rrt_reverse_osmosis_unit_operability'] = 1 # Temp feature for operatibility dialysis['flag_rrt_operability'] = 0 for index, val in dialysis.iterrows(): if dialysis.loc[index,'rrt_operability'] == 0: dialysis.loc[index,'flag_rrt_operability'] = 0 else: dialysis.loc[index,'flag_rrt_operability'] = 1 # Temp feature for equipment dialysis['flag_rrrt_num_hemodialysis_equipments_operability'] = 0 for index, val in dialysis.iterrows(): if dialysis.loc[index,'rrt_num_hemodialysis_equipments_operability'] == 0: dialysis.loc[index,'flag_rrrt_num_hemodialysis_equipments_operability'] = 0 else: dialysis.loc[index,'flag_rrrt_num_hemodialysis_equipments_operability'] = 1 # Decision Variable dialysis['temp'] = dialysis[['materials_surgery', 'staff_surgery', 'flag_rrt_reverse_osmosis_unit_operability', 'flag_rrt_operability', 'flag_rrrt_num_hemodialysis_equipments_operability']].sum(axis=1) surgery = [] for i in dialysis['temp']: if i == 5: surgery.append(1) else: surgery.append(-1) dialysis['dialysis_indicator'] = pd.Series(surgery) return dialysis['dialysis_indicator']
51d7e6c3f0965fae518a2a346f1f5e9ab555b9e0
SINHOLEE/Algorithm
/python/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/๋ฐฉ๊ธˆ๊ทธ๊ณก.py
1,417
3.5625
4
from datetime import datetime def string_to_minute(start, end): temp1 = datetime.strptime(start, '%H:%M') temp2 = datetime.strptime(end, '%H:%M') temp3 = temp2 - temp1 return temp3.seconds // 60 def string_to_list(string): # ๊ฒ€์ฆ์™„๋ฃŒ lis = [] for s in string: if s == "#": lis[-1] += s else: lis.append(s) return lis def solution(m, musicinfos): # ๋…ธ๋ž˜์ œ๋ชฉ, minutes answer = [] my_melody = string_to_list(m) for musicinfo in musicinfos: start, end, title, music = musicinfo.split(',') minutes = string_to_minute(start, end) radio_melody = string_to_list(music) if len(my_melody) > minutes: continue for i in range(minutes-len(my_melody)+1): for j in range(len(my_melody)): if my_melody[j] != radio_melody[(i+j) % len(radio_melody)]: break else: if len(answer) == 0: answer.append((title, minutes)) else: if answer[0][1] < minutes: answer[0] = (title, minutes) break if len(answer) == 0: return "(None)" print(answer) return answer[0][0] solution("CC#BCC#BCC#BCC#B", ["23:30,00:00,FOO,CC#B", "04:00,04:08,BAR,CC#BCC#BCC#B"]) print(string_to_minute("10:12", "11:01"))
198c7baf4e32bfeaf82f75bc7449871c7a72d325
mandeep-codetresure/python-study1
/classpractise.py
506
3.75
4
class Calculator: def __init__(self, number): self.number = number @staticmethod def greet(): print("welcome user") def square(self): print(f"square of {self.number} is {self.number **2}") def cube(self): print(f"Cuberoot of {self.number} is {self.number **3}") def squareRoot(self): print(f"Squareroot of the number {self.number} is {self.number **0.5}") a = Calculator(5) a.greet() a.square() a.cube() a.squareRoot()
918ec59032e9302215f4458b8db0166cd228a5c1
danyalsaqib/Machine-Learning-Basics
/Code Files/Python, Matlab, and Pandas/exportFile.py
449
3.625
4
# Import Pandas using its common nickname import pandas as pd # Reading test_data.csv as a dataframe df = pd.read_csv('test_data.csv') # Adding another column for average scores df['Average Score'] = (df['Math Score'] + df['Physics Score'] + df['Chemistry Score'] + df['English Score']) / 4 # Short Method df['Short Method Average'] = (df.iloc[:, 2:6].sum(axis=1)) / 4 # Exporting into a separate csv file df.to_csv('modified.csv', index = False)
c0f8adb7cb46ad9e9d258e2458f3c2ee8db75382
Cassio-4/URI-Online-Judge
/python/Begginer/1017.py
108
3.703125
4
hours = int(input()) speed = int(input()) fuelSpent = (hours * speed)/12.0 print('{:.3f}'.format(fuelSpent))
b71c4eb4ca4ab67e9d230c0a00c2c584bb8426d1
benny83324/c_to_f
/c_to_f.py
110
3.796875
4
c = float(input("What is the temperature in C so far:")) f = c * 9 / 5 + 32 print("temperature F is mow:",f)
ab01b29943909262c37078c6769fc5fcf256da66
santhosh-kumar/AlgorithmsAndDataStructures
/python/test/unit/common/test_linked_list.py
1,366
3.8125
4
""" Unit Test for binary_tree """ from unittest import TestCase from common.linked_list import LinkedList from common.linked_list import Node class TestLinkedList(TestCase): """ Unit test for LinkedList """ def test_construct(self): """Test for construct Args: self: TestLinkedList Returns: None Raises: None """ # Given input_linked_list = LinkedList() input_linked_list.append(Node(1)) input_linked_list.append(Node(2)) input_linked_list.append(Node(3)) input_linked_list.append(Node(4)) input_linked_list.append(Node(5)) # Then self.assertEqual(input_linked_list.output_list(), [1, 2, 3, 4, 5]) def test_reverse(self): """Test for reverse Args: self: TestLinkedList Returns: None Raises: None """ # Given input_linked_list = LinkedList() input_linked_list.append(Node(1)) input_linked_list.append(Node(2)) input_linked_list.append(Node(3)) input_linked_list.append(Node(4)) input_linked_list.append(Node(5)) # When input_linked_list.reverse() # Then self.assertEqual(input_linked_list.output_list(), [5, 4, 3, 2, 1])
f93ae3b67ce53447ec7528f0b37b3670895d8ae5
antrijuzar/DDU-sem-4-programs
/SP/Lab 1/P5.py
633
4.1875
4
# first a=-5 if a>0: if a%2==0: print(str(a) + " is positive even number") else: print(str(a) + " is negative number") # Output is : -5 is negative number because the outer if statement is evaluated # and the condition is false so the else statement gets executed. # second a=5 if a>0: if a%2==0 : print(str(a) + " is positive even number") else: print(str(a) + " is odd number") # Output is : 5 is odd number because the outer if statement is evaluated # first and the condition is true so the inner if statement gets executed # abd the condition is false so inner else is evaluated finally
258ccc665fe6922754b0f692476d60d3024f1e03
julianestebanquintana/ladrillos
/videojuego.py
6,356
3.515625
4
import sys import time import pygame ancho = 640 alto = 480 color_azul = (0, 0, 64) color_blanco = (255, 255, 255) pygame.init() # Es necesario para poder usar las fuentes en un juego # ย pygame.font.init() class Bolita(pygame.sprite.Sprite): # Los objetos que se ven en la pantalla en pygame, son sprites def __init__(self): pygame.sprite.Sprite.__init__(self) # Cargar imagen self.image = pygame.image.load('bolita.png') # Cargar el rectรกngulo de la bolita self.rect = self.image.get_rect() # (x,y) : Center x # (0,0) : Esquina superior izquierda # (ancho, alto) : Esquina inferior derecha # Se le da una posiciรณn inicial central: self.rect.centerx = ancho/2 self.rect.centery = alto/2 # Establecer velocidad inicial self.speed = [3, -3] def update(self): # Evitar que se salga por arriba if self.rect.top <= 0: self.speed[1] = -self.speed[1] # Evitar que se salga por los lados if self.rect.right >= ancho or self.rect.left <= 0: self.speed[0] = -self.speed[0] # Mover segรบn posiciรณn actual y velocidad self.rect.move_ip(self.speed) class Raqueta(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) # Cargar imagen self.image = pygame.image.load('paleta.png') # Cargar el rectรกngulo de la raqueta self.rect = self.image.get_rect() # Se le da una posiciรณn inicial centrada en pantalla en X. self.rect.midbottom = (ancho/2, alto - 20) # Establecer velocidad inicial self.speed = [0, 0] def update(self, evento): # Buscar si se presionรณ flecha izquierda if evento.key == pygame.K_LEFT and self.rect.left > 0: self.speed = [-6, 0] # Si se presionรณ flecha derecha elif evento.key == pygame.K_RIGHT and self.rect.right < ancho: self.speed = [6, 0] else: self.speed = [0, 0] # Mover segรบn posiciรณn actual y velocidad self.rect.move_ip(self.speed) class Ladrillo(pygame.sprite.Sprite): def __init__(self, posicion): pygame.sprite.Sprite.__init__(self) # Cargar imagen self.image = pygame.image.load('ladrillo.png') # Cargar el rectรกngulo del ladrillo self.rect = self.image.get_rect() # Se le da una posiciรณn inicial, provista externamente self.rect.topleft = posicion class Muro(pygame.sprite.Group): # Existe un contenedor de sprites que se llama Group # Group permite agregar elementos con el mรฉtodo .add # Group permite dibujar el grupo con el mรฉtodo .draw def __init__(self, cantidad_ladrillos): pygame.sprite.Group.__init__(self) pos_x = 0 pos_y = 20 for i in range(cantidad_ladrillos): ladrillo = Ladrillo((pos_x, pos_y)) self.add(ladrillo) pos_x += ladrillo.rect.width if pos_x >= ancho: pos_x = 0 pos_y += ladrillo.rect.height # Funciรณn llamada tras dejar ir la bolita def juego_terminado(): # all_fonts = pygame.font.get_fonts() fuente = pygame.font.SysFont('Consolas', 72) texto = fuente.render('Game over', True, color_blanco) texto_rect = texto.get_rect() texto_rect.center = [ancho/2, alto/2] pantalla.blit(texto, texto_rect) pygame.display.flip() # Pausa por tres segundos antes de salir time.sleep(5) sys.exit() def mostrar_puntuacion(): fuente = pygame.font.SysFont('Consolas', 20) texto = fuente.render(str(puntuacion).zfill(5), True, color_blanco) texto_rect = texto.get_rect() texto_rect.topleft = [0, 0] pantalla.blit(texto, texto_rect) def mostrar_vidas(): fuente = pygame.font.SysFont('Consolas', 20) cadena = "Vidas: " + str(vidas).zfill(2) texto = fuente.render(cadena, True, color_blanco) texto_rect = texto.get_rect() texto_rect.topright = [ancho, 0] pantalla.blit(texto, texto_rect) # Inicializando pantalla pantalla = pygame.display.set_mode((ancho, alto)) # Adicionando tรญtulo de pantalla pygame.display.set_caption('Juego de Ladrillos') # Para monitorear el tiempo, pygame ofrece el objeto .Clock reloj = pygame.time.Clock() # Ajustar repeticiรณn de evento de tecla presionada pygame.key.set_repeat(30) bolita = Bolita() jugador = Raqueta() muro = Muro(50) puntuacion = 0 vidas = 3 while True: # Establecer los FPS permite determinar la mรกxima velocidad a la que va # a correrse el juego reloj.tick(60) # Se revisan los eventos... for evento in pygame.event.get(): if evento.type == pygame.QUIT: sys.exit() elif evento.type == pygame.KEYDOWN: jugador.update(evento) # Actualizar posiciรณn de la bolita bolita.update() # Colisiรณn bolita - jugador if pygame.sprite.collide_rect(bolita, jugador): bolita.speed[1] = -bolita.speed[1] # Colisiรณn bolita - muro # ย pygame.sprite.spritecollide(bolita, muro, True) # Pide un booleano: ยฟLos sprites tocados deben ser destruรญdos? # Pero esta soluciรณn elimina los ladrillos, pero no cambia la direcciรณn # de la bolita. A continuaciรณn, otra soluciรณn: lista = pygame.sprite.spritecollide(bolita, muro, False) if lista: ladrillo = lista[0] cx = bolita.rect.centerx if cx < ladrillo.rect.left or cx > ladrillo.rect.right: bolita.speed[0] = -bolita.speed[0] else: bolita.speed[1] = -bolita.speed[1] muro.remove(ladrillo) puntuacion += 10 # Revisar si la bolita sale de la pantalla if bolita.rect.top > alto: vidas -= 1 bolita.rect.top -= alto/2 # Se rellena el fondo pantalla.fill(color_azul) # Se muestra la puntuaciรณn y las vidas mostrar_puntuacion() mostrar_vidas() # Dibujar bolita en pantalla # La funciรณn blit dibuja una superficie sobre otra. pantalla.blit(bolita.image, bolita.rect) # Se dibuja la raqueta del jugador pantalla.blit(jugador.image, jugador.rect) # Dibujar el muro muro.draw(pantalla) # Actualizar los elementos en pantalla pygame.display.flip() if vidas <= 0: juego_terminado()
56079c8d71e50abb6f0a10da94512d4bd36957b4
olgaamp/python
/venv/1.py
738
3.515625
4
from math import * nsDict = {'global': None} varDict = {} def create(a, b): nsDict[a] = b def add(a, b): varDict[a] = b def get(prostr, per): # x = varDict.get(a) # print(x) res = False for k in varDict: if (k == prostr and varDict[k] == per): res = True print(k) if (res == False): if (nsDict[prostr] is None): print('None') else: get(nsDict[prostr], per) kol = int(input()) for i in range(kol): cmd, ns, var = input().split() if (cmd == 'create'): create(str(ns), str(var)) if (cmd == 'add'): add(str(ns), str(var)) if (cmd == 'get'): get(str(ns), str(var)) print(nsDict) print(varDict)
3a5242bd6e7dba591b4d0158ed05c236ea01ffc1
heidarinejad/MyNests
/Integrate_and_fire_neuron.py
2,027
3.765625
4
# iaf (integrate_and_fire) neuron example import nest import pylab # for plotting # in this program a DC current is injected to neuron using a current generator device and V_m is recorded by 'spike_detector' # to do so the best way is define a function so called ' build_network' # this function take the resoultion as a input def build_network(dt): nest.ResetKernel() nest.SetKernelStatus({"local_num_threads":1, "resolution": dt}) # number of threads is set to zero neuron=nest.Create("iaf_psc_alpha") nest.SetStatus(neuron, "I_e",376.0) # neuron is received an external current Vm=nest.Create('voltmeter') nest.SetStatus(Vm, 'withtime', True) #times are given in the times vector in events sd=nest.Create('spike_detector') nest.Connect(Vm,neuron) nest.Connect(neuron, sd) # The Voltmeter is connected to the neuron and the neuron to the spikedetector # because the neuron sends spikes to the detector and the voltmeter 'observes' the neuron return Vm,sd # the neuron is stimulated with 3 different dt and voltage is plotted i=1 for dt in [0.1,0.5,1.0]: print("Running simulation with dt=%.2f" %dt) Vm,sd=build_network(dt) nest.Simulate(100.0) # ms # spike detector counts the spike numbers during simulation time potentials=nest.GetStatus(Vm,"events")[0]["V_m"] times=nest.GetStatus(Vm, "events")[0]["times"] # The values of the voltage recorded by the voltmeter are read out and the values for the membrane potential # are stored in potential and the corresponding times in the times array # To print out the results (voltage trace over time) pylab.figure(i) pylab.plot(times,potentials, label="dt=%.2f" %dt) print("Number of spikes: {0}".format(nest.GetStatus(sd, "n_events")[0])) pylab.legend(loc=5) # this is for defining the position of label box 0=<loc=<10 pylab.xlabel("Time (ms)") pylab.ylabel("V_m (mV)") pylab.show() i=i+1 #pylab.plt(times,potentials)
f70f99dbaa4b1574b75ec698a909d2ed8f34a465
mdalton87/python-exercises
/solutions.py
1,504
4.1875
4
# 1. # # Write a function named isnegative. # It should accept a number and return a boolean value # based on whether the input is negative. def isnegative(x): return x < 0 # 2. # Write a function named count_evens. It should accept a list and return the number of even numbers in the list. def count_evens(num_list): count = 0 for number in num_list: if number % 2 == 0: count += 1 return count # 3. # Write a function named increment_odds. # It should accept a list of numbers and return a new list # with the odd numbers from the original list incremented. def increment_odds(myList=[]): new_list = [] for number in myList: # if number is even return number if (number % 2) == 0: return new_list.append(number) # if number is odd return number + 1 else: return new_list.append(number + 1) # 4. def average(list_of_numbers=[]): return float((sum(list_of_numbers) / len(list_of_numbers))) # 5. def name_to_dict(full_name): name = [full_name.split(' ')] return {'first_name': name[0], 'last_name': name[1]} # 6. def capitalize_name(names): for name in names: name['first_name'].append = name['first_name'].capitalize() name['last_name'].append = name['last_name'].capitalize() # 7. def count_vowels(string): count = 0 string = string.lower() for c in string: if c in 'aeiou': count += 1 return count # 8.
2eb514c8cb7d5f90ee35fe62631fa2e35d35dd81
jose-ramirez/project_euler
/problems/p19.py
1,384
4.03125
4
#You are given the following information, but you may prefer #to do some research for yourself. # #1 Jan 1900 was a Monday. #Thirty days has September, April, June and November. #All the rest have thirty-one, Saving February alone, #Which has twenty-eight, rain or shine. #And on leap years, twenty-nine. #A leap year occurs on any year evenly divisible by 4, #but not on a century unless it is divisible by 400. # #How many Sundays fell on the first of the #month during the twentieth century (1 Jan 1901 to 31 Dec #2000)? def is_leap(year): a = (year % 4 == 0 and year % 100 != 0) b = year % 400 == 0 return a or b def p19(): total = 0 start = 1 #jan 1st, 1900 is monday: common = [3, 0, 3, 2, 3, 2, 3, 3, 2, 3, 2] leap = [3, 1, 3, 2, 3, 2, 3, 3, 2, 3, 2] for year in range(1901, 2001): #get first day of the year, 0 is sunday: a = 2 if is_leap(year - 1) else 1 y = leap if is_leap(year) else common start = (start + a) % 7 tmp = start #get first days of year's months: f = [] for d in y: tmp += d tmp %= 7 f.append(tmp) #count sundays: g = [x for x in f if x == 0] #add the count to the total, adding the first day # if it was sunday: t = len(g) if start != 0 else len(g) + 1 total += t return total print(p19())
5bfa906b00b190ec1f28f9e2c586e39704207c77
nishantchaudhary12/w3resource_solutions_python
/Strings/uppercase_str.py
539
4.40625
4
#Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters # in the first 4 characters. def upper_str(sample_string): count = 0 new_string = '' for each in range(0, 4): if sample_string[each].isupper(): count += 1 if count > 1: new_string = sample_string.upper() else: new_string = sample_string return new_string def main(): sample_string = 'HTtp://www.w3resource.com' print(upper_str(sample_string)) main()
c914d570a0fad439482cb03a94c1fba136724e5e
MattAnderson16/Algorithms
/stack.py
1,306
4.21875
4
class stack: """Stack class""" def __init__(self): self.items = [] self.max_size = None self.stack_pointer = None def is_empty(self): if len(self.items) == 0: return True else: return False def push(self,item_to_add): if len(self.items) < self.max_size: self.items.append(item_to_add) if len(self.items) == 1: self.stack_pointer = 0 else: self.stack_pointer += 1 def pop(self): if len(self.items) > 0: item = self.items[self.stack_pointer] self.items.pop(self.stack_pointer) if self.stack_pointer > 0: self.stack_pointer -= 1 else: self.stack_pointer = None return item def peek(self): return self.items[self.stack_pointer - 1] def size(self,max_size): self.max_size = max_size if __name__ == "__main__": stack = stack() print(stack.items) print(stack.is_empty()) stack.size(6) stack.push("a") print(stack.items) print(stack.is_empty()) stack.peek() stack.push("b") print(stack.peek()) print(stack.pop()) print(stack.peek())
85d0abb36fa69b7b6dcbf05634daf2613baeb308
mizhi/project-euler
/python/problem-55.py
1,784
4.15625
4
#!/usr/bin/env python # If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. # # Not all numbers produce palindromes so quickly. For example, # # 349 + 943 = 1292, # 1292 + 2921 = 4213 # 4213 + 3124 = 7337 # # That is, 349 took three iterations to arrive at a palindrome. # # Although no one has proved it yet, it is thought that some numbers, # like 196, never produce a palindrome. A number that never forms a # palindrome through the reverse and add process is called a Lychrel # number. Due to the theoretical nature of these numbers, and for the # purpose of this problem, we shall assume that a number is Lychrel # until proven otherwise. In addition you are given that for every # number below ten-thousand, it will either (i) become a palindrome in # less than fifty iterations, or, (ii) no one, with all the computing # power that exists, has managed so far to map it to a palindrome. In # fact, 10677 is the first number to be shown to require over fifty # iterations before producing a palindrome: # 4668731596684224866951378664 (53 iterations, 28-digits). # # Surprisingly, there are palindromic numbers that are themselves # Lychrel numbers; the first example is 4994. # # How many Lychrel numbers are there below ten-thousand? # # NOTE: Wording was modified slightly on 24 April 2007 to emphasise # the theoretical nature of Lychrel numbers. def palindrome_number(n): ns=str(n) return ns == ns[::-1] def lychrel(n, lychrel_set=set()): wn = n for i in xrange(0, 50): nl = list(str(wn)) nl.reverse() rn = int("".join(nl)) wn = wn + rn if palindrome_number(wn): return False return True num = 0 for i in xrange(1, 10000): if lychrel(i): num += 1 print num
ab9d571dbb0ce77c6c86ae9588e678c7ea134b68
shrishtydayal2304/python
/hackerrank/Sets/Symmetric Difference.py
270
3.71875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from __future__ import print_function a=int(input()) x=set(map(int,input().split())) # print(x) b=int(input()) y=set(map(int,input().split())) w=sorted(x.symmetric_difference(y)) print(*w,sep='\n')
1551c6af7432a330e266cf243dc79de8aa785800
MartaCortes/Repository
/Coding_and_Visualization_Projects/Sklearn Python/sklearn.py
16,673
3.671875
4
#!/usr/bin/env python # coding: utf-8 # ## Assignment 3 Advanced Programming # ### Authors: Rafaela Becerra & Marta Cortรฉs # #### Part I Scikit-Learn # # #### Preprocess # # Some libraries are imported and the solar dataset is read (in cvs format) into a Pandas dataframe # In[1]: import numpy as np from numpy.random import randint import pandas as pd import os os.chdir('/Users/cortesocanamarta/Documents/Marta/MรSTER DATA SCIENCE/Advanced Programming/Third Assignment') os.getcwd() train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') # NIA as randomseed in order to create reproductible results: # In[2]: my_NIA = 1722552880 np.random.seed(my_NIA) # Determine the response variable and atributes for the train and test set # In[3]: X_train=train[train.columns[0:1200]] X_test=test[test.columns[0:1200]] y_train=train['energy'] y_test=test['energy'] # Normalization of the atributes with MinMaxScaler, which allows to transform these features by scaling each to a range between 0 and 1. # In[4]: from sklearn import preprocessing min_max_scaler = preprocessing.MinMaxScaler() X_train_minmax = min_max_scaler.fit_transform(X_train) X_test_minmax = min_max_scaler.transform(X_test) # Selection of the first 75 columns which represent one blue point features # In[5]: X_train_minmax=X_train_minmax[:,0:75] X_test_minmax=X_test_minmax[:,0:75] # Create a validation partition, the first 10 years data for trainning and the rest for the validation process # In[6]: from sklearn.model_selection import PredefinedSplit validation_indices = np.zeros(X_train_minmax.shape[0]) validation_indices[:round(10/12*X_train_minmax.shape[0])] = -1 tr_val_partition = PredefinedSplit(validation_indices) # #### Machine Learning methods with default parameters # # We have selected the mean squared error as a metric for comparing the different kind of machine learning methods. The mean squared error or MSE, simultaneously minimizes the prediction variance and prediction bias, then, it is a good quality measure of an estimator. The lower the MSE, it will mean a closer estimation of the quantity of energy produce compare to the real data. The MSE can be expressed as: # # $$M S E=\sum_{i=1}^{N}\left(y_{i}-\hat{y}_{i}\right)^{2}$$ # # # # ##### Regression Models # # Decision Trees are a non-parametric supervised learning method that can be used for classification and regression. In this case, the goal is to create a model that predicts the value of the target variable which is the amount of energy produce, by learning simple decision rules inferred from the data atributes. # In[7]: from sklearn import tree rgt = tree.DecisionTreeRegressor() rgt.fit(X_train_minmax, y_train) y_test_pred = rgt.predict(X_test_minmax) from sklearn import metrics from sklearn.metrics import mean_squared_error print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred, y_test)) # ##### KNN # # The Neighbors-based regression is used when the data target is continuous rather tha discrete variable, then the variable is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. # In[8]: from sklearn.neighbors import KNeighborsRegressor neigh = KNeighborsRegressor() neigh.fit(X_train_minmax, y_train) y_test_pred_KNN = neigh.predict(X_test_minmax) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred_KNN, y_test)) # ##### SVMs # # Support vector machines are a set of supervised learning methods used for classification, regression and outlier detection. In the case of regression, this method approximates the best values with a given margin called epsilon, that considers the model complexity and error rate. # In[9]: from sklearn import svm svmr = svm.SVR(gamma='auto') svmr.fit(X_train_minmax, y_train) y_test_pred_SVM = svmr.predict(X_test_minmax) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred_SVM, y_test)) # #### Machine Learning methods with tuning hyper-parameters # # Hyperparameter optimization or tuning is the problem of choosing a set of optimal hyperparameters for a learning algorithm. Each method has important parameters that can be change in order to get the best model. It is necesary to define: # # * The search space (the hyper-parameters of the method and their allowed values): these will differ for each method. # * The search method: in this case for all the methods will be a random-search. # * The evaluation method: it will be use a crossvalidation process. # # # ##### Regression Trees # # In regression trees, the parameters that will be optimized are: # * max_depth (default=None):the maximum depth of the tree. # * min_samples_split (default=2): the minimum number of samples required to split an internal node # # Since, both are discrete variables sp_randint is used in order to create a discrete uniform distribution. # Hence, the default parameters are: # * criterion (default=โ€˜mseโ€™). The function to measure the quality of a split. # * splitter (default=โ€˜bestโ€™). The strategy used to choose the split at each node. # * min_samples_leaf (default=1). The minimum number of samples required to be at a leaf node. # * min_weight_fraction_leaf (default=0.). The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. # * random_state (default=None). The random number generator is the RandomState instance used by np.random. # * max_leaf_nodes (default=None). Unlimited number of nodes. # * min_impurity_decrease (default=0.). A node will be split if this split induces a decrease of the impurity greater than or equal to 0. # * min_impurity_split (default=1e-7). Threshold for early stopping in tree growth. # In[10]: from scipy.stats import randint as sp_randint param_grid={'max_depth': sp_randint(2,20), 'min_samples_split':sp_randint(2,20)} from sklearn.model_selection import RandomizedSearchCV rgt_grid = RandomizedSearchCV(rgt, param_grid, scoring='neg_mean_squared_error', cv=tr_val_partition, n_jobs=1, verbose=1) rgt_grid.fit(X_train_minmax, y_train) y_test_pred_rgt_G = rgt_grid.predict(X_test_minmax) print("\n The best parameters across all the searched parameters:\n", rgt_grid.best_params_) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred_rgt_G, y_test)) # ##### KNN # # The hyper-parameter that needs to be optimized at least is the 'n_neighbors'(default = 5), which corresponds to the number of neighbors that will be used set to a maximun of 20. The rest of the parameters will be set as default: # # * weights= โ€˜uniformโ€™ : uniform weights. All points in each neighborhood are weighted equally. # * p= 2 : use of euclidean_distance for calculation. # * algorithm: โ€˜autoโ€™. Decides the most appropriate algorithm based on the values passed to fit method. # * leaf_size= 30 : leaf size passed when BallTree or KDTree algorith are use. # * metric= โ€˜minkowskiโ€™. The distance metric to use for the tree. # * metric_params= None. Zero additional keyword arguments for the metric function. # In[11]: param_grid={'n_neighbors': sp_randint(1,20)} neigh_grid = RandomizedSearchCV(neigh, param_grid, scoring='neg_mean_squared_error', cv=tr_val_partition, n_jobs=1, verbose=1) neigh_grid.fit(X_train_minmax, y_train) y_test_pred_KNN_G = neigh_grid.predict(X_test_minmax) print("\n The best parameters across all the searched parameters:\n", neigh_grid.best_params_) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred_KNN_G, y_test)) # ##### SVMs # # The hyper-parameters choosen to be optimized are: # # * kernel (default=โ€™rbfโ€™): specifies the kernel type to be used in the algorithm. Three types of possible kernels will be consider. These are โ€˜linearโ€™, โ€˜polyโ€™, and โ€˜rbfโ€™. # * degree (default=3): degree of the polynomial kernel function if โ€˜polyโ€™ is consider. This will be set as a integer sequence of possible values, with a maximun of 6. # * C (default=1.0): regularization parameter. It controls the trade off between smooth decision boundary and classifying the training points correctly. C in svm, is not too sensitive, then it is quicker to try different values that come from a logarithmic scale. # * gamma (default=โ€™scaleโ€™): Kernel coefficient for โ€˜rbfโ€™, and โ€˜polyโ€™, it will be optimized as a float, considering a sequence set as a maximum of 0.1. # * epsilon (default=0.1): Epsilon in the epsilon-SVR model. It specifies the epsilon-tube within which no penalty is associated in the training loss function with points predicted within a distance epsilon from the actual value. It will be optimized as a float, considering various options with a maximun set as 0.9. # # In contrast, the parameters set as default for this method are: # # # # # * shrinking (default=True). # * max_iter (default=-1). No limit on iterations within solver. # In[12]: param_grid1={'C': np.logspace(0, 3, num=10000), 'gamma': [1e-7, 1e-1], 'kernel': ('linear', 'rbf','poly'), 'degree' : [0, 1, 2, 3, 4, 5, 6], 'epsilon':[0.1,0.9]} svmr_grid = RandomizedSearchCV(svmr, param_grid1, scoring='neg_mean_squared_error', cv=tr_val_partition, n_jobs=1, verbose=1) svmr_grid.fit(X_train_minmax, y_train) y_test_pred_SVM_G = svmr_grid.predict(X_test_minmax) print("\n The best parameters across all the searched parameters:\n", svmr_grid.best_params_) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred_SVM_G, y_test)) # In[ ]: # # # # From all the results that we got, we can say first that all the models when optimizing its hyper-paremeters, the metrics result better, and give a more accurate model. By comparing the MSE resulting between type of methods, the one that is more accurate is the KNN method, which returned a better metric than the regression tree method and the support vector regressor (Table 1). These results will be much more accurate, if all the data is use and not only the variables from one of the points. # ![Captura%20de%20pantalla%202019-12-27%20a%20las%2019.24.55.png](attachment:Captura%20de%20pantalla%202019-12-27%20a%20las%2019.24.55.png) # #### Part II Scikit-Learn # # # #### Preprocess # # # Selection of the first 300 columns which represent four blue point features # # # In[ ]: # In[13]: X_train=train[train.columns[0:300]] X_test=test[test.columns[0:300]] # Create a validation partition, the first 10 years data for trainning and the rest for the validation process # In[14]: from sklearn.model_selection import PredefinedSplit validation_indices = np.zeros(X_train.shape[0]) validation_indices[:round(10/12*X_train.shape[0])] = -1 tr_val_partition = PredefinedSplit(validation_indices) # Selection of the 10% of attributes and random assignation of 10% of nan for each column in the train and test dataset. # In[15]: np.random.seed(my_NIA) # In[16]: nan_atr=np.random.choice(list(X_train.columns), size=round(len(X_train.columns)*0.1), replace=False) # In[17]: for i in range(0,len(nan_atr)): np.random.seed(i) nan_row=np.random.choice(X_train.index.tolist(), size=round(len(X_train.index)*0.1), replace=False) X_train.loc[nan_row,nan_atr[i]]=np.nan # In[18]: for i in range(0,len(nan_atr)): np.random.seed(i) nan_row=np.random.choice(X_test.index.tolist(), size=round(len(X_test.index)*0.1), replace=False) X_test.loc[nan_row.tolist(),nan_atr[i]]=np.nan # Convertion to numpy array # In[19]: X_train=X_train.to_numpy() X_test=X_test.to_numpy() # #### Pipelines # # #### SelectionKBest # # Default parameters # In[ ]: # In[20]: from sklearn.pipeline import Pipeline from sklearn.neighbors import KNeighborsRegressor from sklearn.impute import SimpleImputer from sklearn.feature_selection import SelectKBest, VarianceThreshold, f_regression from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import GridSearchCV from sklearn import metrics imputer = SimpleImputer(strategy='median') constant = VarianceThreshold(threshold=0.0) #Feature selector that removes all low-variance features. min_max_scaler = MinMaxScaler() selector = SelectKBest(f_regression) knn = KNeighborsRegressor() selectkbest = Pipeline([ ('impute', imputer), ('constant', constant), ('scaler', min_max_scaler), ('select', selector), ('knn_regression', knn)]) selectkbest = selectkbest.fit(X_train, y_train) y_test_pred = selectkbest.predict(X_test) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred, y_test)) # Hyper-parameter tunning of the k number of features # In[21]: param_grid = {'select__k': range(1,40,1)} selectkbest_grid = GridSearchCV(selectkbest, param_grid, scoring='neg_mean_squared_error', cv=tr_val_partition, n_jobs=1, verbose=1) selectkbest_grid = selectkbest_grid.fit(X_train, y_train) y_test_pred = selectkbest_grid.predict(X_test) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred, y_test)) selectkbest_grid.get_params() print(selectkbest_grid.best_params_) # Set the resulting k number after optimization, and look for the n_neighbors number that will give the best model # In[22]: selectkbest = selectkbest.set_params(**{'select__k':12}) param_grid = {'knn_regression__n_neighbors': range(1,20,1)} selectkbest_grid = GridSearchCV(selectkbest, param_grid, scoring='neg_mean_squared_error', cv=tr_val_partition, n_jobs=1, verbose=1) selectkbest_grid = selectkbest_grid.fit(X_train, y_train) y_test_pred = selectkbest_grid.predict(X_test) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred, y_test)) print(selectkbest_grid.best_params_) # #### PCA # # PCA with default parameters # In[23]: from sklearn.decomposition import PCA imputer = SimpleImputer(strategy='median') constant = VarianceThreshold(threshold=0.0) #Feature selector that removes all low-variance features. min_max_scaler = MinMaxScaler() selector = PCA() knn = KNeighborsRegressor() pca = Pipeline([ ('impute', imputer), ('constant', constant), ('scaler', min_max_scaler), ('select', selector), ('knn_regression', knn)]) pca = pca.fit(X_train, y_train) pca.get_params() y_test_pred = pca.predict(X_test) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred, y_test)) # Hyper-parameter tunning of n_components # In[24]: param_grid = {'select__n_components': range(1,40,1)} pca_grid = GridSearchCV(pca, param_grid, scoring='neg_mean_squared_error', cv=tr_val_partition, n_jobs=-1, verbose=1) pca_grid = pca_grid.fit(X_train, y_train) y_test_pred = pca_grid.predict(X_test) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred, y_test)) print(pca_grid.best_params_) # Set parameter n_components, and find the optimal n_neighbors for the best model # In[25]: pca = pca.set_params(**{'select__n_components':7}) param_grid = {'knn_regression__n_neighbors': range(1,20,1)} pca_grid = GridSearchCV(pca, param_grid, scoring='neg_mean_squared_error', cv=tr_val_partition, n_jobs=1, verbose=1) pca_grid = pca_grid.fit(X_train, y_train) y_test_pred = pca_grid.predict(X_test) print("\n The MSE is:\n", metrics.mean_squared_error(y_test_pred, y_test)) print(pca_grid.best_params_) # As the results show, the best model is the one with the PCA as the method for reducting the non important features of the dataset, this is the best result considering also the results from part I. The parameters resulted for the SelectKBest method were k=12 and n_neighbors=6, these means that the selecting method recognized 12 features that were representative from all the 300 variables, in contrast, the PCA identified only 7 components as the ones that had to be mantain and 19 neighbors. # Consequently, the PCA, gave a more accurate prediction and with less information, this is why it is consider as the best method of selection. Finally, the KNN gave the most accurate prediction of the amount of energy with both of the hyper-parameter tunnings. The summary of the MSEs results for the previous method are gathered in the next table: # ![Captura%20de%20pantalla%202019-12-27%20a%20las%2019.27.55.png](attachment:Captura%20de%20pantalla%202019-12-27%20a%20las%2019.27.55.png)
cd22c86f74b78705397305900b50b8dbbfa36fc0
dbwebb-se/python-slides
/oopython/example_code/vt23/kmom04/mock.py
2,043
3.734375
4
""" Gรฅr igenom Mock i unittest. https://docs.python.org/3/library/unittest.mock.html """ from unittest import mock # https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock # Vi kan antingen skapa ett Mock eller MagicMock objekt. # Fรถr att anvรคnda Mock objektet behรถver vi i fรถrvรคg specificera vilka attribut # och metoder som ska ersรคttas och hur de ska bete sig. # MagicMock dรคremot รคr mer automatisk/magisk, det objektet har vissa metoder fรถrskapade. # MagicMock รคr en subklass till Mock. Objekt skapar attribut och metoder # nรคr de anvรคnds pรฅ objektet och sparar hur de har anvรคnts. Det gรฅr รคven # att konfigurera dem fรถr att sรคtta retur vรคrden och assert:a hur de har anvรคnts m = mock.MagicMock() type(m) # Om anropar m som en funktion ska den returnera "magic" m.return_value = "magic" print(m()) def koo(): """ Function used to return value in a Mock """ return "functional magic" # Om side_effect รคr satt till en funktion som returnerar ett vรคrdet kommer # det vรคrdet returneras och inte vรคrdet frรฅn ".return_value". m.side_effect = koo print(m()) # side_effect kan ocksรฅ vara en sekvens m.side_effect = [1, 2, 3] # Dรฅ returneras nรคsta element varje gรฅng mocken anropas. print(m()) print(m()) print(m()) # Kastar StopIteration # print(m()) # Kan ocksรฅ anvรคnda side_effect fรถr att kasta ett exception nรคr en metod anropas. def raise_exception(): """ How to riase an exception in mocked function/method """ raise ValueError() m.side_effect = raise_exception print(m()) # ValueError och iterationsfel m.chaos = raise_exception print(m()) # Vi kan lรคgga till attribut pรฅ Mock objektet ocksรฅ m.something = "magic" print(m.something) # Lรฅtsas skapa funktioner och bestรคmma vad de ska returnera m.boo.return_value = "funcational magic" print(m.boo()) # Vi kan gรถra vรคldigt mycket och dynamiska saker med Mock. # Detta var grunderna i Mock, fรถr att testa input ska vi anvรคnda oss av # Mock.patch. Fortsรคtt kolla i filen patch.py.
1d7ebc1b65ba02e23c43c2750360a2b7d9367cb0
jadamsowers/arc-reactor
/Python/breathe.py
2,174
3.625
4
# breathe.py by J. Adam Sowers # Generates an array of RGB values to make a NeoPixel device appear to # 'breathe', similar to the sleeping MacBook LED indicator. import math import sys import colorsys r,g,b = 0x40,0xD0,0xFF # blue-ish glow numSteps = 128 #colorsys expects RGB values in the range [0,1] r,g,b = [ x / 255.0 for x in r,g,b] # convert to HSV colorspace (hue, saturation, value) # this makes it easier to adjust the values since we only have to # vary the value (brightness) h,s,v = colorsys.rgb_to_hsv (r,g,b) # generate an Arduino-compatible array and store it in PROGMEM (flash memory) # to free up SRAM for other uses. sys.stdout.write("/* this array generated by breathe.py\n" "using LED 'breathing' function by Sean Voisen.\n" "http://sean.voisen.org/blog/2011/10/breathing-led-with-arduino/ */\n" "const uint8_t numSteps = %d;\n" % numSteps ) sys.stdout.write("const uint32_t breath[numSteps] PROGMEM = {") # About the breathing function: # The generic function to simulate breathing appears to be e^(cos(x)). # The inner function [cos(x)] output will be in [-1, 1]. # Therefore the min and max of the 'breathing' function will be [e^-1, e^1] # We want values from [0,1], so we need to offset the min value by 1/e # and scale by 1 / (e - 1/e). min_offset = 1 / math.e scaling_factor = 1 / (math.e - min_offset) pi_over_numSteps = math.pi / numSteps for n in range(numSteps): if not n % 8: sys.stdout.write("\n ") # Calculate the scaling factor. This will output a value from [0,1] # which, when applied to the V in the HSV representation, will scale the # brightness without affecting hue or saturation. scale = ( math.exp( math.cos( pi_over_numSteps * n - math.pi ) ) #breathing function - min_offset ) * scaling_factor # NeoPixels library expects integer RGB values in the range [0,255] r,g,b = [ int(x * 255) for x in colorsys.hsv_to_rgb(h,s,v*scale) ] # pack the r,g,b values into one hex value rgb = str.format('0x{:06X}', (r << 16) + (g << 8) + b) sys.stdout.write("%s" % rgb) if n < numSteps - 1: sys.stdout.write(", ") sys.stdout.write("\n};\n")
8052a046ff59c1bee411e1fe0f6f640ed3eb9eba
goareum93/K-digital-training
/01_Python/18_OOP/01_ํด๋ž˜์Šค๊ตฌํ˜„.py
5,795
4.0625
4
#### ## ํด๋ž˜์Šค ๊ตฌํ˜„ : ๋ฉ”์„œ๋“œ, ํ•„๋“œ ์ •์˜, ์ƒ์„ฑ์ž ์ด์šฉ # ํด๋ž˜์Šค ์„ ์–ธ # class ํด๋ž˜์Šค์ด๋ฆ„ [(์Šˆํผํด๋ž˜์Šค๋ช…)] : # ํ•„๋“œ(์†์„ฑ)1 # ํ•„๋“œ(์†์„ฑ)2 # def method1(self): # ... # def method2(self): # ... # ๋นˆ ํด๋ž˜์Šค ์ •์˜ # class Car: # pass # # car1 = Car() # print(car1) # # <__main__.Car object at 0x0000020491E4F1F0> # # class Car: # # ๋ฉ”์†Œ๋“œ ์ •์˜ # def show(self): # print('์‹œํ—˜์ค‘์ž…๋‹ˆ๋‹ค') # # # ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ # car1 = Car() # car2 = Car() # car3 = Car() # print("------") # car1.show() # ๋ฉ”์†Œ๋“œ ํ˜ธ์ถœ # car2.show() # car3.show() # ํŠน์ • ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค์ธ์ง€ ํ™•์ธ : isinstance(์ธ์Šคํ„ด์Šค๋ช…, ํด๋ž˜์Šค๋ช…) # print(isinstance(car1, Car)) # print(isinstance(car1, int)) # # x = 3 # print(isinstance(x,int)) # # y = list([1,2,3,4]) # print(isinstance(y, list)) # # print(type(x)) # # z = 'Hi, ๋ฐ˜๊ฐ€์›Œ์š”' # print(type(z)) # # a = True # print(type(a)) # # # ํŒŒ์ด์ฌ์—์„œ ๊ธฐ๋ณธ์ œ๊ณตํ•˜๊ณ  ์žˆ๋Š” int, float, bool, str, list, dict, set, tuple # # => ํด๋ž˜์Šค # # print(isinstance(a, int)) # # b = (1,2,3) # print(type(b)) # print(isinstance(b,list)) # # # instance & object # # ๊ฐ™์€ ๊ฒƒ ๊ฐ€๋ฆฌํ‚ค๊ณ  ์žˆ์Œ # # instnace : ํด๋ž˜์Šค์™€ ์—ฐ๊ด€์ง€์–ด ๋งํ•  ๋•Œ # # ์˜ˆ. car1์€ Car ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค์ด๋‹ค # # object :๋‹จ๋…์œผ๋กœ ๋ถ€๋ฅผ ๋•Œ # # ์˜ˆ. car1 ๊ฐ์ฒด ############################################# # ํ•„๋“œ ์ถ”๊ฐ€ : ๋ฉ”์†Œ๋“œ ๋‚ด์—์„œ ์‚ฌ์šฉ # # class Car: # def show(self): # print('์‹œํ—˜์ค‘์ž…๋‹ˆ๋‹ค') # # # def drive(self): # # self.speed=60 # speed ํ•„๋“œ # # print('%d ๋กœ ์ฃผํ–‰์ค‘์ž…๋‹ˆ๋‹ค' % self.speed) # # def drive(self, speed): # self.speed = speed # speed ํ•„๋“œ # print('%d ๋กœ ์ฃผํ–‰์ค‘์ž…๋‹ˆ๋‹ค' % self.speed) # # # ๋ฉ”์ธ : ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ์ด์šฉ # car1 = Car() # car1.drive(70) # print(car1.speed) # car1.drive(50) # # # ์ธ์Šคํ„ด์Šค.ํ•„๋“œ # car1.color = 'red' # print(car1.color) # ํด๋ž˜์Šค์—์„œ ํ•„๋“œ ์„ ์–ธ # class Car: # speed = 0 # color = '' # model = '' # # def show(self): # print('์‹œํ—˜์ค‘์ž…๋‹ˆ๋‹ค') # # def drive(self): # print('%d ๋กœ ์ฃผํ–‰์ค‘์ž…๋‹ˆ๋‹ค' % self.speed) # # mycar = Car() # print(mycar.speed) # mycar.drive() # mycar.speed = 60 # mycar.drive() # ์ƒ์„ฑ์ž(consrutor) : ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ # ๊ธฐ๋ณธ ์ƒ์„ฑ์ž : ์ธ์Šคํ„ด์Šค ํ˜ธ์ถœ => ์ธ์Šคํ„ด์Šค๋ช….ํด๋ž˜์Šค์ด๋ฆ„() # class Car: # def __init__(self): # self.color = 'white' # self.speed = 0 # # def showInfo(self): # print('์ด ์ž๋™์ฐจ์˜ ์ƒ‰์ƒ์€ %s์ž…๋‹ˆ๋‹ค.' % self.color) # # def drive(self): # if self.speed != 0: # print('%d ๋กœ ์ฃผํ–‰์ค‘์ž…๋‹ˆ๋‹ค' % self.speed) # else: # print('์ •์ฐจ์ค‘์ž…๋‹ˆ๋‹ค') # # mycar = Car() # print(mycar.color) # print(mycar.speed) # mycar.showInfo() # mycar.drive() # mycar.speed = 50 # mycar.drive() # ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์žˆ๋Š” ์ƒ์„ฑ์ž __init__(self, ๋งค๊ฐœ๋ณ€์ˆ˜1, ๋งค๊ฐœ๋ณ€์ˆ˜2,...) # => ํ•„๋“œ์˜ ์ดˆ๊ธฐ๊ฐ’ ์ง€์ • # class Car: # def __init__(self, color, speed): # self.color = color # self.speed = speed # # def showInfo(self): # print('์ด ์ž๋™์ฐจ์˜ ์ƒ‰์ƒ์€ %s์ž…๋‹ˆ๋‹ค.' % self.color) # # def drive(self): # if self.speed != 0: # print('%d ๋กœ ์ฃผํ–‰์ค‘์ž…๋‹ˆ๋‹ค' % self.speed) # else: # print('์ •์ฐจ์ค‘์ž…๋‹ˆ๋‹ค') # # mycar = Car('red', 10) # print(mycar.color) # print(mycar.speed) # mycar.showInfo() # mycar.drive() # mycar.speed = 50 # mycar.drive() # # yourcar = Car('blue', 0) # yourcar.showInfo() # ๋””ํดํŠธ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•œ ์ƒ์„ฑ์ž # class Car: # def __init__(self, speed=0, color='white'): # self.speed = speed # self.color = color # # def showInfo(self): # print('์ด ์ž๋™์ฐจ์˜ ์ƒ‰์ƒ์€ %s์ž…๋‹ˆ๋‹ค.' % self.color) # # def drive(self): # if self.speed != 0: # print('%d ๋กœ ์ฃผํ–‰์ค‘์ž…๋‹ˆ๋‹ค' % self.speed) # else: # print('์ •์ฐจ์ค‘์ž…๋‹ˆ๋‹ค') # # car1 = Car() # car2 = Car(color='yellow') # car3 = Car(10, 'blue') # car4 = Car(10) # car5 = Car(color='black', speed=50) # car1.showInfo() # car2.showInfo() # car3.showInfo() # car4.drive() # print(car5.speed) # print(car5.color) # ๋น„๊ณต๊ฐœ ํ•„๋“œ ์ •์˜ : __ํ•„๋“œ๋ช… # ํด๋ž˜์Šค ๋‚ด๋ถ€์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด์„œ ์‚ฌ์šฉ class Car: def __init__(self, speed=0, color='white'): self.speed = speed self.__color = color # ํด๋ž˜์Šค ๋‚ด์—์„œ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๋น„๊ณต๊ฐœ ํ•„๋“œ # def __str__(self): # print('์ด ์ž๋™์ฐจ์˜ ์ƒ‰์ƒ์€ %s์ด๊ณ ,\n ์†๋„๋Š” %d์ž…๋‹ˆ๋‹ค.' % (self.__color, self.speed)) # color ํ•„๋“œ ๊ฐ’์„ ๋ฐ˜ํ™˜๋ฉ”์†Œ๋“œ def getColor(self): return self.__color # color ํ•„๋“œ๊ฐ’์„ ๋ณ€๊ฒฝ๋ฉ”์†Œ๋“œ def setColor(self, color): self.__color = color # ๋น„๊ณต๊ฐœ ๋ฉ”์†Œ๋“œ def __showColor(self): print('์ด ์ž๋™์ฐจ์˜ ์ƒ‰์ƒ์€ %s์ž…๋‹ˆ๋‹ค.' % self.__color) def showInfo(self): self.__showColor() print('์†๋„๋Š” %d์ž…๋‹ˆ๋‹ค.' % self.speed) def drive(self): if self.speed != 0: print('%d ๋กœ ์ฃผํ–‰์ค‘์ž…๋‹ˆ๋‹ค' % self.speed) else: print('์ •์ฐจ์ค‘์ž…๋‹ˆ๋‹ค') def upSpeed(self, up): self.speed += up def downSpeed(self, down): self.speed -= down if self.speed < 0 : self.speed = 0 car1 = Car() print(car1.getColor()) car1.setColor('Red') print(car1.getColor()) # car1.color = 'blue' # ํ•„๋“œ๋ฅผ ์™ธ๋ถ€์— ์ง์ ‘ ์ ‘๊ทผ # car1.__showColor() car1.showInfo() car1.upSpeed(20) car1.drive() car1.upSpeed(20) car1.drive() car1.downSpeed(10) car1.drive()
8bf0d7d753ff517a7547f06698343d2f182f7285
thedeveshpareek/random-simple-polygon-generation
/src-generate/main_naive.py
1,837
3.703125
4
# ----------------------------------------------------------------------------- # Naive polygon generation algorithm # ----------------------------------------------------------------------------- from src.Edge import Edge from src.Polygon import Polygon from src.Math import quickhull import sys import matplotlib.pyplot as plt import time if __name__ == "__main__": # take input from test.txt f = open("test.txt", "r") # start timer start = time.time() # insert input points to list points = [] n = int(f.readline()) for i in range(n): coord = f.readline().split(' ') points.append([float(coord[0]), float(coord[1])]) # initialize the polygon as a convex hull of the points polygon = Polygon(quickhull(points)) # update points set to exclude polygon vertices points = [x for x in points if x not in polygon.vertices] # while the list of available points is not empty while points: # get the closest point and removing edge (e, point) = polygon.findClosest(points) # find the index to insert the vertex and edges in i = polygon.edges.index(e) polygon.vertices.insert(i + 1, point) polygon.edges[i] = Edge(e.start, point) polygon.edges.insert(i + 1, Edge(point, e.end)) # remove newly added vertex from points.remove(point) # print results print() print("---------------- Naive Approach ----------------") print("Number of vertices: %i" % n) print("Execution time: %s seconds" % (time.time() - start)) print("------------------------------------------------") print() # plot the polygon pset = polygon.vertices pset.append(pset[0]) xs, ys = zip(*pset) plt.plot(xs, ys) plt.show() # close test.txt file f.close()
05bf5dfee32b157e534466d0533ffd571c075561
JongSeokJang/Sogang_ConputingThinking
/p3_2.py
168
3.734375
4
a = input(); c_temp = float(a); f_temp = ((9/5) * c_temp) + 32 print ("===============") print ("Celsius : %.1f" %(c_temp) ); print ("Fahrenheit : %.2f" %(f_temp) );
c4528607c93d78a0f7eb730ef62562c5a0ff2cef
piraog/PacketPrioritizing
/Simulation.py
14,869
3.515625
4
import numpy as np import matplotlib.pyplot as plt from Network import * class Simulation: '''This class runs scheduling algorithms for emergency flows over a given network. Args: * network (Network): a network we want to run the simulation on Kwargs: * eFlowDeadLine (int): the deadline of the simulated emergency flow * nExp (int): number of simuations we want to run * runType (str): specify if we want to run each simulation on every node or just at 1 starting point for the emergency flow Attributes: * schedulability : an array of the schedulability ratio for each algorithm and each experiment * nStolenFlows : an array of the average number of flow stolen by each algorithm in each experiment: SFSA, OBSSA * nStolenFlowsScheduled : an array of the average number of flow stolen by each algorithm in each experiment when the packet was scheduled: SFSA, OBSSA ''' def __init__(self, network, eFlowDeadLine=4, nExp=100, runType='average on all nodes' ): self.n = network self.nExp = nExp self.eFlowDeadLine = eFlowDeadLine self.nStolenFlows = np.array([[0 for _ in range(2)] for i in range(nExp)]) self.nStolenFlowsScheduled = np.array([[0 for _ in range(2)] for i in range(nExp)]) self.schedulability = np.array([[0 for _ in range(2)] for i in range(nExp)]) if runType == 'average on all nodes': self.runOnAllNodes() elif runType == 'simple': self.run() elif runType == 'average on all starting points': self.runOnAllStartpoints() self.schedulability = np.around(100*self.schedulability,decimals=0) def runOnAllNodes(self): '''Runs both algorithms using, in turn, each connected node of the network as starting point. Then average the results.''' for i in range(self.nExp): self.n = Network(self.n.nNodes, self.n.nFlows, self.n.nChannels, self.n.eFork, self.n.schedulingMethod) activeNodes = [node for node,w in enumerate(self.n.W) if (w!={} and node!=0)] for node in activeNodes: SFSA = self.runSFSA(node) OBSSA = self.runOBSSA(node) self.schedulability[i][0] += SFSA[0] self.nStolenFlows[i][0] += SFSA[1] self.nStolenFlowsScheduled[i][0] += SFSA[0]*SFSA[1] self.schedulability[i][1] += OBSSA[0] self.nStolenFlows[i][1] += OBSSA[1] self.nStolenFlowsScheduled[i][1] += OBSSA[0]*OBSSA[1] # if OBSSA[0]<SFSA[0]: # print(SFSA) # print(OBSSA) # print(self.n.intersections) # for k,v in enumerate(self.n.W): # print(k, " ", v) for i in range(self.nExp): if self.schedulability[i][0]!=0: self.nStolenFlowsScheduled[i][0] = self.nStolenFlowsScheduled[i][0]/self.schedulability[i][0] else: self.nStolenFlowsScheduled[i][0] = 0 if self.schedulability[i][1]!=0: self.nStolenFlowsScheduled[i][1] = self.nStolenFlowsScheduled[i][1]/self.schedulability[i][1] else: self.nStolenFlowsScheduled[i][1] = 0 self.nStolenFlowsScheduled = np.true_divide(self.nStolenFlowsScheduled.sum(0),(self.nStolenFlowsScheduled!=0).sum(0)) self.schedulability = np.mean(self.schedulability, 0) self.schedulability /= (len(activeNodes)) #*(self.n.globalPeriod-self.eFlowDeadLine) self.nStolenFlows = np.mean(self.nStolenFlows, 0) self.nStolenFlows /= (len(activeNodes)) #*(self.n.globalPeriod-self.eFlowDeadLine) def runOnAllStartpoints(self): '''Runs both algorithms using, in turn, each node at the begining of a regular flow as starting point. Then average the results.''' for i in range(self.nExp): self.n = Network(self.n.nNodes, self.n.nFlows, self.n.nChannels, self.n.eFork, self.n.schedulingMethod) startpoints = [path[0] for path in self.n.H] for node in startpoints: SFSA = self.runSFSA(node) OBSSA = self.runOBSSA(node) self.schedulability[i][0] += SFSA[0] self.nStolenFlows[i][0] += SFSA[1] self.nStolenFlowsScheduled[i][0] += SFSA[0]*SFSA[1] self.schedulability[i][1] += OBSSA[0] self.nStolenFlows[i][1] += OBSSA[1] self.nStolenFlowsScheduled[i][1] += OBSSA[0]*OBSSA[1] # if OBSSA[0]<SFSA[0]: # print(SFSA) # print(OBSSA) # print(self.n.intersections) # for k,v in enumerate(self.n.W): # print(k, " ", v) for i in range(self.nExp): if self.schedulability[i][0]!=0: self.nStolenFlowsScheduled[i][0] = self.nStolenFlowsScheduled[i][0]/self.schedulability[i][0] else: self.nStolenFlowsScheduled[i][0] = 0 if self.schedulability[i][1]!=0: self.nStolenFlowsScheduled[i][1] = self.nStolenFlowsScheduled[i][1]/self.schedulability[i][1] else: self.nStolenFlowsScheduled[i][1] = 0 self.nStolenFlowsScheduled = np.true_divide(self.nStolenFlowsScheduled.sum(0),(self.nStolenFlowsScheduled!=0).sum(0)) self.schedulability = np.mean(self.schedulability, 0) self.schedulability /= (len(startpoints)) #*(self.n.globalPeriod-self.eFlowDeadLine) self.nStolenFlows = np.mean(self.nStolenFlows, 0) self.nStolenFlows /= (len(startpoints)) #*(self.n.globalPeriod-self.eFlowDeadLine) def run(self): '''Runs both algorithm on 1 random connected node of the network.''' for i in range(self.nExp): self.n = Network(self.n.nNodes, self.n.nFlows, self.n.nChannels, self.n.eFork, self.n.schedulingMethod) origine = random.sample([node for node,w in enumerate(self.n.W) if (w!={} and node!=0)],1)[0] # print('-------------------------------------------------') SFSA = self.runSFSA(origine) OBSSA = self.runOBSSA(origine) # print(SFSA) # print(OBSSA) # for k,v in enumerate(self.n.W): # print(k, " ", v) self.schedulability[i][0] += SFSA[0] self.nStolenFlows[i][0] += SFSA[1] self.schedulability[i][1] += OBSSA[0] self.nStolenFlows[i][1] += OBSSA[1] self.nStolenFlowsScheduled = np.multiply(self.schedulability,self.nStolenFlows) self.nStolenFlowsScheduled = np.true_divide(self.nStolenFlowsScheduled.sum(0),(self.nStolenFlowsScheduled!=0).sum(0)) self.schedulability = np.mean(self.schedulability, 0) self.nStolenFlows = np.mean(self.nStolenFlows, 0) def runSFSA(self, origine="random", initialTime=0): '''Our implementation of SFSA, origine is used to specify the origine node (int) if we want to study a specific transmission. initialTime can be used to offset the departure of the emergency flow (the deadline is relative to this departure time).''' if origine == 'random': origine = random.sample([node for node,w in enumerate(self.n.W) if (w!={} and node!=0)],1)[0] #connected origine route = [(initialTime, origine)] #list of time, node the emergency nodes cross D = self.eFlowDeadLine + initialTime scheduability = 1 reachedGateway = 0 stolenFlows = [] while scheduability and not reachedGateway: #print('route ', route, ' time ', time, ' args ', route[-1][1], ' ', time) nextSlot = self.nextSlot(route[-1][1], route[-1][0], D) #select the next available slot to live the node if nextSlot != False: arrivalTime = nextSlot[0]+1 nextNode = nextSlot[1][0] route += [(arrivalTime, nextNode)] stolenFlows += [nextSlot[1][1]] if nextSlot[1][0]==0: reachedGateway = 1 else: #print('last node ', self.n.W[route[-1][1]]) scheduability = 0 return (scheduability, len(set(stolenFlows)), route) #return the schedulability, #nb of stolen flows and route followed def nextSlot(self, node, time, deadLine): #select the next flow exiting a node, if it is within deadlines slots = self.n.W[node] availableSlots = [slot for slot in slots.items() if (deadLine-slot[0]-1)>=0 and slot[0]>=time] if len(availableSlots)>0: nextSlot = min(availableSlots[:]) else: return False return nextSlot def runOBSSA(self, origine = 'random', initialTime=0): '''Our implementation of OBSSA, origine is used to specify the origine node (int) if we want to study a specific transmission. initialTime can be used to offset the departure of the emergency flow (the deadline is relative to this departure time).''' if origine == 'random': origine = random.sample([node for node,w in enumerate(self.n.W) if (w!={} and node!=0)],1)[0] #connected origine route = [(initialTime, origine)] #list of time, node the emergency nodes cross D = self.eFlowDeadLine + initialTime schedulability = 1 reachedGateway = 0 stolenFlows = [] while schedulability and not reachedGateway: if stolenFlows!=[] and self.n.A[route[-1][1]][stolenFlows[-1]][2]+1<self.eFlowDeadLine: #schedulable on the current flow reachedGateway = 1 elif self.goodAvailableStolenFlow(route[-1][0], route[-1][1], stolenFlows)!=[]: #schedulable on a previously stolen flow reachedGateway = 1 elif self.optimalSlot(route[-1][0], route[-1][1])!='false': #finding the optimal path, if it exists flow = self.optimalSlot(route[-1][0], route[-1][1]) #adding the optimal slot to our route arrivalTime = self.n.A[route[-1][1]][flow][0]+1 destination = self.n.A[route[-1][1]][flow][1] route += [(arrivalTime,destination)] stolenFlows.append(flow) if destination == 0: reachedGateway=1 else: schedulability = 0 return (schedulability,len(set(stolenFlows)),route) def goodAvailableStolenFlow(self, time, node, stolenFlows): flows = list(set(stolenFlows)&set([flow for flow,info in self.n.A[node].items() if (info[0]>=time and self.eFlowDeadLine>=info[2])])) if flows!=[]: flow = flows[0] return [flow] return [] def optimalSlot(self,time,node): criterion = [] for flow,info in self.n.A[node].items(): N = info[0] - time if N>=0 and info[0]<self.eFlowDeadLine: a = len([1 for i in self.n.intersections[flow][1] if i[0]<node]) criterion.append((flow,N/(a+1),N)) criterion.sort(key=lambda t:t[2]) if criterion!=[]: optimalFlow = min(criterion,key=lambda t:t[1])[0] return optimalFlow return 'false' if __name__ == '__main__': '''comparison of OBSSA and SFSA, 1000 exp, averaged for each exp on every edge node''' # network = Network(300, 15, nChannels=2, eFork=5, schedulingMethod='FCFS') # simulation = Simulation(network, nExp = 100, eFlowDeadLine=8,runType='average on all starting points') # print(simulation.schedulability, simulation.nStolenFlows, simulation.nStolenFlowsScheduled) '''We have the same results in average for randomly generated networks (the cases where OBSSA presents a real advantage are extremely rare, even with a high forking''' nNodes = [10*i for i in range(2,11)] schedulability1 = [] stolenFlows1 = [] stolenFlowsScheduled1 = [] for n in nNodes: network = Network(n, 15, nChannels=2, eFork=5, schedulingMethod='RoundRobin') simulation = Simulation(network, nExp = 500, eFlowDeadLine=6) schedulability1 += [[simulation.schedulability[0],simulation.schedulability[1]]] stolenFlows1 += [[simulation.nStolenFlows[0],simulation.nStolenFlows[1]]] stolenFlowsScheduled1 += [[simulation.nStolenFlowsScheduled[0],simulation.nStolenFlowsScheduled[1]]] print(schedulability1) print(stolenFlowsScheduled1) schedulability2 = [] stolenFlows2 = [] stolenFlowsScheduled2 = [] # for n in nNodes: # network = Network(n, 15, nChannels=2, eFork=5, schedulingMethod='RoundRobin') # simulation = Simulation(network, nExp = 1000, eFlowDeadLine=i) # schedulability2 += [[simulation.schedulability[0],simulation.schedulability[1]]] # stolenFlows2 += [[simulation.nStolenFlows[0],simulation.nStolenFlows[1]]] # stolenFlowsScheduled2 += [[simulation.nStolenFlowsScheduled[0],simulation.nStolenFlowsScheduled[1]]] # print(schedulability2) plt.plot(nNodes, [i[0] for i in schedulability1]) plt.plot(nNodes, [i[1] for i in schedulability1]) plt.legend(['SFSA RR','OBSSA RR']) plt.title('schedulability versus number of nodes for 15 flows, 2 channels, D=6') plt.xlabel('Number of nodes') plt.ylabel('Schedulability Ratio') plt.show() plt.plot(nNodes, [i[0] for i in stolenFlows1]) plt.plot(nNodes, [i[1] for i in stolenFlows1]) plt.legend(['SFSA RR','OBSSA RR']) plt.title('stolen flows versus number of nodes for 15 flows, 2 channels, D=6') plt.xlabel('Number of nodes') plt.ylabel('Stolen Flows') plt.show() plt.plot(nNodes, [i[0]*100.0 for i in stolenFlowsScheduled1]) plt.plot(nNodes, [i[1]*100.0 for i in stolenFlowsScheduled1]) plt.legend(['SFSA RR','OBSSA RR']) plt.title('stolen flows versus number of nodes for 15 flows, 2 channels, D=6') plt.xlabel('Number of nodes') plt.ylabel('Stolen Flows for scheduled packets') plt.show()
e06e4705afbeb7ba916cb22c5728ea8fbf91cea9
yejinee/Algorithm
/Algorithm Concept/Union_Find.py
1,521
3.890625
4
""" [ ์„œ๋กœ์†Œ ์ง‘ํ•ฉ ์ž๋ฃŒ ๊ตฌ์กฐ ] - ์—ฐ์‚ฐ 1) ํ•ฉ์ง‘ํ•ฉ (Union) - ๋™์ž‘๊ณผ์ • 1. Node ๊ฐฏ์ˆ˜ ํฌ๊ธฐ์˜ ๋ถ€๋ชจํ…Œ์ด๋ธ” ์ดˆ๊ธฐํ™” (์ž๊ธฐ ์ž์‹ ) 2. Unionํ•˜๋ ค๋Š” node๋“ค์˜ ๋ฃจํŠธ๋…ธ๋“œ ์ฐพ๊ธฐ (๋ถ€๋ชจํ…Œ์ด๋ธ” ๊ฑฐ์Šฌ๋Ÿฌ ์˜ฌ๋ผ๊ฐˆ ๊ฒƒ) 3. 2๊ฐœ node์˜ ๋ฃจํŠธ๋…ธํŠธ ์ค‘ ๋” ์ž‘์€ ๋ฒˆํ˜ธ์˜ ๋ฃจํŠธ๋ฅผ ๊ฐ€์ง„ ๋…ธ๋“œ์˜ ๋ฃจํŠธ๋…ธ๋“œ๊ฐ€ ๋‹ค๋ฅธ ๋…ธ๋“œ์˜ ๋ถ€๋ชจ๋…ธ๋“œ ๋Œ => ์—ฐ๊ฒฐ์„ฑ ํ†ตํ•ด ์ง‘ํ•ฉ์˜ ํ˜•ํƒœ ํ™•์ธ ๊ฐ€๋Šฅ( ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ๋ฃจํŠธ๋…ธ๋“œ ํ™•์ธํ•ด๋ณด์•„์•ผํ•จ ) 2) ์ฐพ๊ธฐ (Find) : ๊ฒฝ๋กœ ์••์ถ• ๋ฐฉ๋ฒ•(Findํ•จ์ˆ˜ ์žฌ๊ท€ํ˜ธ์ถœ ๋’ค์— ๋ถ€๋ชจtable ๊ฐ’ ๋ฐ”๋กœ ๊ฐฑ์‹ ) ์‚ฌ์šฉ """ # ๋…ธ๋“œ X์˜ ๋ฃจํŠธ ๋…ธ๋“œ ์ฐพ๋Š” Function def find_parent(parent,x): if parent[x] != x: parent[x]=find_parent(parent,parent[x]) return parent[x] # Union์—ฐ์‚ฐ ์ˆ˜ํ–‰ํ•˜๋Š” Function def union_parent(parent,a,b): a=find_parent(parent,a) b=find_parent(parent,b) if a<b: parent[b]=a else: parent[a]=b print(parent) v,e=map(int,input().split()) parent=[0]*(v+1) #๋ถ€๋ชจ table ์ดˆ๊ธฐํ™” # ๋ถ€๋ชจ ํ…Œ์ด๋ธ”์˜ ๋ถ€๋ชจ๋ฅผ ์ž๊ธฐ์ž์‹ ์œผ๋กœ ์ดˆ๊ธฐํ™” for i in range(1,v+1): parent[i]=i # Union ์—ฐ์‚ฐ ์ˆ˜ํ–‰ํ•˜๊ธฐ for i in range(e): a,b=map(int,input().split()) union_parent(parent,a,b) print("๊ฐ ์›์†Œ๊ฐ€ ์†ํ•œ ์ง‘ํ•ฉ", end=' ') for i in range(1,v+1): print(find_parent(parent,i), end=' ') print() # ๋ถ€๋ชจ ํ…Œ์ด๋ธ” ๋‚ด์šฉ ์ถœ๋ ฅ print("๋ถ€๋ชจ ํ…Œ์ด๋ธ”: ", end=' ') for i in range(1,v+1): print(parent[i],end=' ')
f13e0a842e4b301ac52a671b1b43b850e0cfd64c
JesusMartinezCamps/programacion
/python/yatzy_Refactoring_TDD_Kata/yatzy.py
3,573
3.5625
4
class Yatzy: @staticmethod #Un metodo static no puede recibir un objeto def chance(*dice): total = 0 for die in dice: total += die return total @staticmethod def yatzy(*dice): if dice.count(dice[0]) == 5: return 50 return 0 @staticmethod def ones(*dice): score = 0 for die in dice: if die == 1: score += die return score # ONE = 1 # return dice.count(ONE) * ONE @staticmethod def twos(*dice): score = 0 for die in dice: if die == 2: score += 2 return score """ TWO = 2 return dice.count(TWO) * TWO """ @staticmethod def threes(*dice): score = 0 for die in dice: if die == 3: score += 3 return score def __init__(self, d1, d2, d3, d4, _5): self.dice = [0]*5 self.dice[0] = d1 self.dice[1] = d2 self.dice[2] = d3 self.dice[3] = d4 self.dice[4] = _5 def fours(self): score = 0 for number in range(5): if (self.dice[number] == 4): score += 4 return score def fives(self): score = 0 for number in range(5): if (self.dice[number] == 5): score += 5 return score def sixes(self): score = 0 for number in range(5): if (self.dice[number] == 6): score += 6 return score @staticmethod def pair(*dice): for number in range(6, 0, -1): if dice.count(number) >= 2: return number * 2 return 0 @staticmethod def two_pair(*dice): score = 0 number_of_pairs = 0 for number in range(6, 0, -1): if dice.count(number) >= 4: score += number * 4 number_of_pairs += 2 elif dice.count(number) >= 2: score += number * 2 number_of_pairs += 1 if number_of_pairs >= 2: return score return 0 @staticmethod def three_of_a_kind(*dice): score = 0 for number in range(1, 7, 1): if dice.count(number) >= 3: score += number * 3 return score return 0 @staticmethod def four_of_a_kind(*dice): score = 0 for number in range(1, 7, 1): if dice.count(number) >= 4: score += number * 4 return score return 0 @staticmethod def small_straight(*dice): straight = 0 for number in range(1, 6, 1): if dice.count(number) == 1: straight += 1 if straight == 5: return 15 else: return 0 @staticmethod def large_straight(*dice): straight = 0 for number in range(2, 7, 1): if dice.count(number) == 1: straight += 1 if straight == 5: return 20 else: return 0 @staticmethod def full_house(*dice): score = 0 for number in range(1, 7, 1): if dice.count(number) > 4 or dice.count(number) == 1: return 0 elif dice.count(number) == 3: score += number * 3 elif dice.count(number) == 2: score += number * 2 return score
70fce8052217feb51feb2c40eea8e11c04d69688
gabriellaec/desoft-analise-exercicios
/backup/user_348/ch44_2020_04_08_17_26_59_480524.py
304
3.859375
4
#usando dicionรกrio meses = {'janeiro': 1, 'fevereiro': 2, 'marรงo': 3, 'abril': 4, 'maio': 5, 'junho': 6, 'julho': 7, 'agosto': 8, 'setembro': 9, 'outubro': 10, 'novembro': 11, 'dezembro': 12} numero = input('digite o nome do mes: ') mes = meses[numero] print("O mes de {0} รฉ: {1}".format(numero, mes))
f06d6151b50b2c7508a79ffa22a2d97986266d69
Vinograd17/Python
/HW 6/hw6_task_3.py
595
3.5625
4
# Task 3 class Worker: def __init__(self, name, surname, position, income): self.name = name self.surname = surname self.position = position self.income_wage = income['wage'] self.income_bonus = income['bonus'] class Position(Worker): def get_full_name(self): return f'{self.name} {self.surname} {self.position}' def get_total_income(self): return self.income_wage + self.income_bonus posit = Position('Anton', 'Ivanov', 'CEO', {"wage": 10000, "bonus": 5000}) print(posit.get_full_name()) print(posit.get_total_income())
b9f5bfbeed0832d2a48d43e07735e8b6bf41efde
catliaw/berkeleyext_intro_computers_programming
/Module7/sort_and_mean.py
917
4.40625
4
#!/usr/bin/python3 # This program consists of a user-defined function called sort_and_mean # which takes a list of numbers as an argument and sorts and PRINTS that # list of numbers. The function also calculates and RETURNS the mean value # numberse in the list. # Test input: [3,9,7,4,0,2] def sort_and_mean(nums_list): sorted_list = [] total = None list_length = len(nums_list) while nums_list: minimum = nums_list[0] for num in nums_list: if num < minimum: minimum = num sorted_list.append(minimum) nums_list.remove(minimum) if total is None: total = minimum else: total += minimum average = float(total) / float(list_length) print("Sorted list of numbers:") print(sorted_list) print("\nAverage of numbers:") print(average) return average sort_and_mean([3,9,7,4,0,2])
f5c403e3a80a030d8459377563aaf10d8fbaca04
BThacker/codingbatPYTHON
/list2/List2.py
3,192
4.0625
4
# @Brandon Thacker # www.codingbat.com PYTHON List2 Problems and Solutions # Max of 1 Loop '''COUNT_EVENS Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. count_evens([2, 1, 2, 3, 4]) โ†’ 3 count_evens([2, 2, 0]) โ†’ 3 count_evens([1, 3, 5]) โ†’ 0 ''' def count_evens(nums): counter = 0 for x in range(0, len(nums)): if nums[x] % 2 == 0: counter += 1 return counter '''BIG_DIFF Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values. big_diff([10, 3, 5, 6]) โ†’ 7 big_diff([7, 2, 10, 9]) โ†’ 8 big_diff([2, 10, 7, 2]) โ†’ 8 ''' def big_diff(nums): smallest = 1000 largest = -1000 for x in range(0, len(nums)): if nums[x] < smallest: smallest = nums[x] if nums[x] > largest: largest = nums[x] return largest - smallest '''CENTERED_AVERAGE Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more. centered_average([1, 2, 3, 4, 100]) โ†’ 3 centered_average([1, 1, 5, 5, 10, 8, 7]) โ†’ 5 centered_average([-10, -4, -2, -4, -2, 0]) โ†’ -3 ''' def centered_average(nums): avgCalc = len(nums) - 2 smallest = 1000 largest = -1000 totalsum = 0 for x in range(0, len(nums)): if nums[x] < smallest: smallest = nums[x] if nums[x] > largest: largest = nums[x] totalsum += nums[x] return (totalsum - largest - smallest) / avgCalc '''SUM13 Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count. sum13([1, 2, 2, 1]) โ†’ 6 sum13([1, 1]) โ†’ 2 sum13([1, 2, 2, 1, 13]) โ†’ 6 ''' def sum13(nums): sum = 0; for i in range(len(nums)): if nums[i] == 13: sum += 0 continue if i >= 1 and nums[i - 1] == 13: sum += 0 continue sum += nums[i] return sum '''SUM67 Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers. sum67([1, 2, 2]) โ†’ 5 sum67([1, 2, 2, 6, 99, 99, 7]) โ†’ 5 sum67([1, 1, 6, 7, 2]) โ†’ 4 ''' def sum67(nums): flagged = False sum = 0 if len(nums) == 0: return 0 for i in range(len(nums)): if not flagged and nums[i] == 6: flagged = True continue if flagged and nums[i] == 7: flagged = False continue if not flagged: sum += nums[i] return sum '''HAS22 Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. has22([1, 2, 2]) โ†’ True has22([1, 2, 1, 2]) โ†’ False has22([2, 1, 2]) โ†’ False ''' def has22(nums): for x in range (len(nums)): if x >= 1 and nums[x] == 2 and nums[x - 1] == 2: return True return False