blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
494772ce01dc269ae05814a6669d2a5638b49e4d
alesamv/Estructura-de-Datos-y-Algoritmos-I
/Practicas/Practica13/ejercicio3.py
377
4.25
4
#Serie de Fibonacci Iterativa """Programa que calcula la serie de Fibonacci, utilizando una función Iterativa.""" def FibonacciIterativo(numero): f1=0 f2=1 for i in range(1, numero-1): f1,f2=f2,f1+f2 return f2 print("Ingresa la posicion para obtener el correspondiente numero de la serie:") numero=int(input()) print(f"{FibonacciIterativo(numero)}")
298d4980ed2959c7be84981595db0e3d77518175
larry-dario-liu/Learn-python-the-hard-way
/ex2.py
566
3.53125
4
cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven=cars-drivers cars_driven=drivers carpool_capacity=cars_driven*space_in_a_car average_passengers_per_car=passengers/cars_driven # hahahahahah# print "there %s are",cars,"cars %s available." print "there are only",drivers,"drivers available." print "there will be",cars_not_driven,"empty cars today" print "we can transport",carpool_capacity,"people today" print "we have",passengers,"to carpool today." print "we need to put about",average_passengers_per_car,"in each car"
19d8299b8356915d1b62b5c655dbc28779626da1
harryw1/cs_python
/CS121/rainfall_database_v2.py
8,920
4.375
4
""" Harrison Weiss homework_02 Program that implements a class called RainfallTable that builds a dictionary of years and rainfall totals from njrainfall.txt. Implements different functions that allow the user to determine different traits of this data. """ import statistics class RainfallTable(): # Dictionary where everything will be stored rain_table = dict() months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] historical_median_rainfall = list() def build_historical_median(self): for x in range(1, 13): self.historical_median_rainfall.append( self.get_median_rainfall_for_month(x)) def __init__(self, path): self.build_table(path) # Builds the table by appending new keys (year) # and their associated values (rainfall) to the rain_table being # stored in our instance of the RainfallTable def build_table(self, path): rain_file = open(path, 'r') for line in rain_file: tokens = line.split() year = int(tokens[0]) rainfall_list = list() for item in tokens[1:]: rainfall_list.append(float(item)) self.rain_table[year] = rainfall_list def get_rainfall(self, year, month): """ Returns the rainfall associated with the given year and month. Both values are assumed to be integers (month given as 1-12, year as a four digit year). Raises an exception if the year/month combination are not found """ if type(year) != int or type(month) != int: raise TypeError # once we clear the above, we know were dealing with an int, so we can do math on it month -= 1 # Index of months starts at 0 if year < min(self.rain_table.keys()) or year > max(self.rain_table.keys()): raise ValueError elif month < 0 or month > 11: raise ValueError # gets and returns the data we want for key in self.rain_table: if key == year: rainfall = self.rain_table[key][month] return rainfall def get_average_rainfall_for_month(self, month): """ Returns the average rainfall associated with the given month across all years in the table. Month is assumed to be an integer (1-12. Raises an exception if the month is not valid. """ if type(month) != int: raise TypeError month -= 1 # Index starts at 0 if month < 0 or month > 11: raise ValueError # calculates and returns the value we want total_rain = float() all_years = [self.rain_table[year][month] for year in self.rain_table] for x in all_years: total_rain += x return round(total_rain / len(all_years), 2) def get_min_year(self): """ Returns the minimum year in the table """ return min(self.rain_table.keys()) def get_max_year(self): """ Returns the maximum year in the table """ return max(self.rain_table.keys()) def get_median_rainfall_for_month(self, month): """ Returns the median rainfall associated with the given month across all years in the table. Month is assumed to be an integer (1-12. Raises an exception if the month is not valid. """ if type(month) != int: raise TypeError month -= 1 # Index starts at 0 if month < 0 or month > 11: raise ValueError # calculates and returns the value we want total_rain = float() all_years = [self.rain_table[year][month] for year in self.rain_table] for x in all_years: total_rain += x # Using the statistics module, we dont have to sort the list # rainfall data: median() does this for us, likely by calling # sort() and then calculating the median. return round(statistics.median(all_years), 2) def get_average_rainfall_for_year(self, year): """ Returns the average rainfall in the given year across all months. Raises exception if year is not in table """ if year not in self.rain_table.keys(): raise KeyError avg_rain = float() for item in self.rain_table[year]: avg_rain += item avg_rain = avg_rain / len(self.rain_table[year]) return round(avg_rain, 2) def get_median_rainfall_for_year(self, year): """ Returns the median rainfall in the given year across all months. Raises exception if year is not in table. """ if year not in self.rain_table.keys(): raise KeyError temp_rain = self.rain_table[year].copy() return round(statistics.median(temp_rain), 2) def get_all_by_year(self, year): """ Returns the rainfall values for each month in the given year. Raise exception if year is not found. """ if year not in self.rain_table.keys(): raise KeyError for rain in self.rain_table[year]: yield rain def get_all_by_month(self, month): """ Returns the rainfall values for each year during the given month. Raise exception if month is not valid """ month -= 1 # index starts at 0 if month < 0 or month > 11: raise ValueError for key in self.rain_table: yield self.rain_table[key][month] def get_droughts(self): """ returns a list of strings, representing date (month/year) ranges where three or more months in a row had at least 5% less rainfall than their historical monthly medians """ which_month = 0 # to iterate over the months of the year start_drought = "" # for being appended later end_drought = "" # same as above month_count = 0 # for counting how many months we've seen 5% less than the median rainfall self.build_historical_median() for key in self.rain_table: which_month = 0 # every year we start at month 0 for value in self.rain_table[key]: # calculate 5% less than the median if value < (self.historical_median_rainfall[which_month] * 0.95): month_count += 1 # we've found a drought month so we can increment the count if month_count == 1: # this is the first drought start_drought = str( self.months[which_month]) + " " + str(key) elif month_count > 1: # otherwise, we've been in a drought end_drought = str( self.months[which_month]) + " " + str(key) else: # for when the rainfall was not less than 5% of the median if month_count > 3: # for when we meet the condition of being a drought for three months # we can yield the drought time period yield str(start_drought + " to " + end_drought) # reset the values to their initals month_count = 0 start_drought = "" end_drought = "" else: month_count = 0 start_drought = "" end_drought = "" which_month += 1 # iterate to the next month """ MAIN PROGRAM """ table = RainfallTable("njrainfall.txt") print(table.get_rainfall(1993, 's')) print(table.get_average_rainfall_for_month(6)) for year in range(table.get_min_year(), table.get_max_year()+1) : print("Average rainfall in ", year, "=", table.get_average_rainfall_for_year(year)) print("Median rainfall in ", year, "=", table.get_median_rainfall_for_year(year)) print("===========") for rain in table.get_all_by_year(year): print(rain, end='\t') print("\n===========") for month in range(1, 13) : print("Average rainfall in month", month, "=", table.get_average_rainfall_for_month(month)) print("Median rainfall in month", month, "=", table.get_median_rainfall_for_month(month)) print("===========") for rain in table.get_all_by_month(month): print(rain, end='\t') print("\n===========") for d in table.get_droughts() : print("Drought: ", d)
45a2e63632863c04d8b351b5c850f8b551cbd36c
siddalls3135/cti110
/Functions.py
1,709
4.9375
5
# -*- coding: utf-8 -*- """ Created on Wed Oct 9 12:00:03 2019 @author: sidda """ # In Python a function is defined using the def keyword: def my_function(): print("Hello from a function") # To call a function, use the function name followed by parenthesis: def my_function(): print("Hello from a function") my_function() # The following example has a function with one parameter (fname). When the # function is called, we pass along a first name, which is # used inside the function to print the full name: def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus") # If we call the function without parameter, # it uses the default value: def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") # E.g. if you send a List as a parameter, # it will still be a List when it reaches the function: def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits) # To let a function return a value, use the return statement: def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9)) # This way the order of the arguments does not matter. def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") # If the number of arguments are unknown, # add a * before the parameter name: def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus")
5c1d627e827fcada39f7975cfb45894a9aa6312c
ashwiniwagh2296/python
/add3.py
270
3.734375
4
a = int(input("Enter your no a : ")) b = int(input("Enter your no b: ")) c = a+b d = int(input("Enter your no d : ")) e = int(input("Enter your no e : ")) f = d+e g = int(input("Enter your no g: ")) h = int(input("Enter your no h: ")) i = g+h print(c) print(f) print(i)
bbc1ce0a0a7f88f06f2efcd3b0575a9af9d3287c
dreamroshan/Code_examples
/if Elif Example.py
216
4.125
4
''' @author :CreativeCub ''' z = 3 if z == 1: print 'z is equal to 1' elif z == 2: print 'z is equal to 2' elif z == 3: print 'z is equal to 3' else: print 'z is not equal to 1 or 2 or 3'
60f674124d4a480fe0c334229594cd9036cbadc7
gaurav1116/Practicing-Python
/stringreverser.py
175
4.40625
4
entered_string = raw_input("Please enter a string: ") reversed = "" for item in range(len(entered_string) -1, -1, -1): reversed += entered_string[item] print(reversed)
dd922f28ae272b938183d247db66f512c1e404b2
panscoding/leetcode
/4.Top K Elements/findKthSmallest.py
2,190
3.96875
4
""" iven an unsorted array of numbers, find Kth smallest number in it. Please note that it is the Kth smallest number in the sorted order, not the Kth distinct element. Note: For a detailed discussion about different approaches to solve this problem, take a look at Kth Smallest Number. Example 1: Input: [1, 5, 12, 2, 11, 5], K = 3 Output: 5 Explanation: The 3rd smallest number is '5', as the first two smaller numbers are [1, 2]. """ from heapq import * class Solution: def findKthSmallest(self, nums, k: int) -> int: """ implement the max_heap use push -nums[i] to the heap 1. Solution: THis solution use the maximum heap which root is the biggest element in the max heap. Since we want track of the K smallest numbers, we can compare each number with the root while iterating throught all numbers. If it is smaller than root, we will take out the root and insert the smaller number. 2. Time Complexity The time complexity of readjust the heap is O(Log(N)) where N is element of input nums. The heap is a binary tree, each time insert a new element, the tree rebalance will cost O(Log(N)). The time complexity of this solution is O(N*Log(N)) where N is the element of nums. 3. Space Complexity The algorithm runs in constant space O(1) The space complexity will be O(K) bacause we ned to store K smallest numbers in the heap :param nums: :param k: :return: """ max_heap = [] #1. insert first k number into the maximum heap. for i in range(k): heappush(max_heap, -nums[i]) #2. Go throught the rest of number, if the current number smaller than the root, take out the root and push the current number. for j in range(k, len(nums)): if nums[j] < -max_heap[0]: heappop(max_heap) heappush(max_heap, -nums[j]) #3. return the root as Kth element. return -max_heap[0] def main(): nums = [3, 2, 1, 5, 6, 4] k = 3 a = Solution() ret = a.findKthSmallest(nums, k) print(ret) if __name__ == "__main__": main()
5c5d4c52e327b9ea67205ea8be00bca97619214c
MatheusEwen/Exercicios_Do_CursoDePython
/ExPython/CursoemVideo/ex113.py
951
3.890625
4
def leiafloat(msg): while True: try: n = float(input(msg)) except (ValueError, TypeError): print('\033[0;31mERRO, por favor, digite um numero interio valido\033[m') continue except(KeyboardInterrupt): print('\033[0;31mO usuario preferiu não digitar esse número \033[m') return 0 else: return n def leiaint(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('\033[0;31mERRO, por favor, digite um numero interio valido\033[m') continue except(KeyboardInterrupt): print('\033[0;31mO usuario preferiu não digitar esse número \033[m') return 0 else: return n n1 = leiaint('digite um valor inteiro:') n2 = leiafloat('digite um valor real:') print(f'O valor digitado foi {n1} e o valor real foi {n2}')
cade7b92d7fee6c28b6226475c77f8c356d19991
schlerp/schlerpnn
/NENNN.py
18,696
3.984375
4
#!/usr/bin/python # Patty's neural network # ---------------------- # # a bunch of shit for me to fuck around with and learn # neural networks. # currently idea is: # * pick a non linear # # * initialise a network with the amount of input, # hidden, and output nodes that you want for the # data # # * train the network with training x and y # # * test it using nn.guess(x) with a known y # # * if happy, test with real world data :P # # example 6 layer nn for solving mnist # i -h -h -h -h -h -o # 784-2500-2000-1500-1000-500-10 import numpy as np import numexpr as ne import struct import os # ============================================================= # classes class NENonlinear(object): """ Nonlinear --------- this is used to set up a non linear for a network. The idea is you can instantiate it and set what type of non linear function it will be for that particular neaural network """ _FUNC_TYPES = ('sigmoid', 'softmax', 'relu', 'tanh', 'softplus') def __init__(self, func_type='sigmoid'): if func_type in self._FUNC_TYPES: if func_type == self._FUNC_TYPES[0]: # sigmoid self._FUNCTION = self._FUNC_TYPES[0] elif func_type == self._FUNC_TYPES[1]: # softmax self._FUNCTION = self._FUNC_TYPES[1] elif func_type == self._FUNC_TYPES[2]: # relu self._FUNCTION = self._FUNC_TYPES[2] elif func_type == self._FUNC_TYPES[3]: # tanh self._FUNCTION = self._FUNC_TYPES[3] elif func_type == self._FUNC_TYPES[4]: # softplus self._FUNCTION = self._FUNC_TYPES[4] else: # default to sigmoid on invalid choice? print("incorrect option `{}`".format(func_type)) print("defaulting to sigmoid") self._init_sigmoid() def __call__(self, x, derivative=False): ret = None if self._FUNCTION == self._FUNC_TYPES[0]: # sigmoid if derivative: ret = ne.evaluate('x*(1-x)') else: try: ret = ne.evaluate('1/(1+exp(-x))') except RuntimeWarning: ret = 0.0 elif self._FUNCTION == self._FUNC_TYPES[1]: # softmax if derivative: # from below + http://www.derivative-calculator.net/ ret = ne.evaluate('2*(exp(x)/sum(exp(x)))') else: # from: https://gist.github.com/stober/1946926 #e_x = np.exp(x - np.max(x)) #ret = e_x / e_x.sum() # from: http://peterroelants.github.io/posts/neural_network_implementation_intermezzo02/ ret = ne.evaluate('exp(x)/sum(exp(x), axis=0)') elif self._FUNCTION == self._FUNC_TYPES[2]: # relu if derivative: # from below + http://www.derivative-calculator.net/ ret = ne.evaluate('2*(abs(x))') else: ret = ne.evaluate('x*(abs(x))') elif self._FUNCTION == self._FUNC_TYPES[3]: # tanh if derivative: # from my own memory of calculus :P ret = ne.evaluate('1.0-x**2') else: ret = ne.evaluate('tanh(x)') elif self._FUNCTION == self._FUNC_TYPES[3]: # softplus if derivative: # from wikipedia ret = ne.evaluate('1.0/(1+exp(-x))') else: ret = ne.evaluate('log(1+exp(x))') return ret class NENNN(object): """NumExpr N-layered neural network""" def __init__(self, inputs, weights, outputs, alpha): self.trained_loops_total = 0 self.train_loops = [] self.inputs = inputs self.outputs = outputs self._ALPHA = alpha self._num_of_weights = len(weights) self._LAYER_DEFS = {} self.WEIGHT_DATA = {} self.LAYER_FUNC = {} self.LAYERS = {} for i in range(self._num_of_weights): #(in, out, nonlin) self._LAYER_DEFS[i] = {'in': weights[i][0], 'out': weights[i][1], 'nonlin': weights[i][2]} print(self._LAYER_DEFS) self._init_layers() def _init_layers(self): for i in range(self._num_of_weights): _in = self._LAYER_DEFS[i]['in'] _out = self._LAYER_DEFS[i]['out'] _nonlin = self._LAYER_DEFS[i]['nonlin'] self.WEIGHT_DATA[i] = np.random.randn(_in, _out) self.LAYER_FUNC[i] = _nonlin def reset(self): self._init_layers() def update_alpha(self, alpha=1): self._ALPHA = alpha def _do_layer(self, prev_layer, next_layer, nonlin): """Does the actual calcs between layers :)""" ret = nonlin(np.dot(prev_layer, next_layer)) return ret def train(self, x, y, train_loops=100): for j in range(train_loops): # set up layers prev_layer = x prev_y = y next_weight = None l = 0 self.LAYERS[l] = x for i in range(self._num_of_weights): l += 1 next_weight = self.WEIGHT_DATA[i] nonlin = self.LAYER_FUNC[i] current_layer = self._do_layer(prev_layer, next_weight, nonlin) self.LAYERS[l] = current_layer prev_layer = current_layer last_layer = current_layer #print(last_layer) # #layer2_error = y - layer2 #layer2_delta = layer2_error * self.non_lin(layer2, derivative=True) #layer1_error = layer2_delta.dot(self.w_out.T) #layer1_delta = layer1_error * self.non_lin(layer1, derivative=True) #self.w_out += self._ALPHA * layer1.T.dot(layer2_delta) #self.w_in += self._ALPHA * layer0.T.dot(layer1_delta) # calculate errors output_error = ne.evaluate('y - last_layer') output_nonlin = self.LAYER_FUNC[self._num_of_weights - 1] output_delta = output_error * output_nonlin(last_layer, derivative=True) prev_delta = output_delta prev_layer = last_layer for i in reversed(range(self._num_of_weights)): weight = self.WEIGHT_DATA[i] current_weight_error = prev_delta.dot(weight.T) current_weight_nonlin = self.LAYER_FUNC[i] current_weight_delta = current_weight_error * current_weight_nonlin(self.LAYERS[i], derivative=True) # backpropagate error self.WEIGHT_DATA[i] += self._ALPHA * self.LAYERS[i].T.dot(prev_delta) prev_delta = current_weight_delta # increment the train counter, so i can see how many # loops my pickled nets have trained self.trained_loops_total += 1 # output important info if (j % (train_loops/10)) == 0: print("loop: {}".format(j)) #print("Layer1 Error: {}".format(np.mean(np.abs(layer1_error)))) #print("Layer2 Error: {}".format(np.mean(np.abs(layer2_error)))) for i in range(3): #print("Guess: ") #print(last_layer[i]) #print("output delta: ") #print(np.round(output_delta, 2)) #print("Guess (rounded), Actual: ") #guess = tuple(zip(np.round(last_layer[i], 1), y[i])) #j = 0 #for item in guess: #if item[1] == 1.0: #print("**ACTUAL") #if item != (0.0, 0.0): #print("number: {}".format(j)) #print(" {}".format(item)) #j += 1 #print(str(guess)) print("===================") print("Guess (rounded): ") random = np.random.randint(0, len(x) - 2) print(np.round(last_layer[random + i], 0)) print("Actual: ") print(y[random + i]) self.train_loops.append({'loops': train_loops, 'cases': len(y), 'alpha': self._ALPHA}) def guess(self, x): prev_layer = x prev_y = y next_weight = None l = 0 self.LAYERS[l] = x for i in range(self._num_of_weights): l += 1 next_weight = self.WEIGHT_DATA[i] nonlin = self.LAYER_FUNC[i] current_layer = self._do_layer(prev_layer, next_weight, nonlin) self.LAYERS[l] = current_layer prev_layer = current_layer last_layer = current_layer return last_layer def print_stats(self): print("total trained loops: ") print(self.trained_loops_total) print("trained loops layout: ") print(self.train_loops) print("inputs: ") print(self.inputs) print("outputs: ") print(self.outputs) print("alpha: ") print(self._ALPHA) print("layers: ") print(self._LAYER_DEFS) # ============================================================= # DEFS def normalize(vals, ranges): """ Normalize --------- Will take a an array of data and a tuple of tuples contains the mins and maxes for each val. This will transforma ll data to a score of 0 to 1""" def norm(val, v_min, v_max): return (val-v_min)/(v_max - v_min) if len(vals[0]) != len(ranges): print("Error, values and ranges dont match!!") return None d_struct = [] for row in vals: temp_row = zip(row, ranges) d_struct.append(temp_row) ret = [] for row in d_struct: temp_row = [] for col in row: #print(col) temp = norm(col[0]*1.0, col[1][0]*1.0, col[1][1]*1.0) temp_row.append(temp) ret.append(temp_row) return ret def make_mnist_np(l_items=None): if l_items == None: l_items = [100, 500, 1000, 2000, 5000, 10000, 20000] for items in l_items: print("grabbing {} data...".format(items)) t_in, t_out = get_flat_mnist(items=items, normalize=True) print(" got nmist array!") print(' {}x{}'.format(len(t_in), len(t_in[0]))) x = np.array(t_in, dtype=np.float) y = np.array(t_out, dtype=np.float) with open('mnist/tx{}'.format(items), 'wb+') as f: pickle.dump(x, f) with open('mnist/ty{}'.format(items), 'wb+') as f: pickle.dump(y, f) # from: https://gist.github.com/akesling/5358964 # Loosely inspired by http://abel.ee.ucla.edu/cvxopt/_downloads/mnist.py # which is GPL licensed. def read(dataset="training", path="./data"): """ Python function for importing the MNIST data set. It returns an iterator of 2-tuples with the first element being the label and the second element being a numpy.uint8 2D array of pixel data for the given image. """ if dataset is "training": fname_img = os.path.join(path, 'train-images.idx3-ubyte') fname_lbl = os.path.join(path, 'train-labels.idx1-ubyte') elif dataset is "testing": fname_img = os.path.join(path, 't10k-images.idx3-ubyte') fname_lbl = os.path.join(path, 't10k-labels.idx1-ubyte') else: raise(ValueError, "dataset must be 'testing' or 'training'") # Load everything in some numpy arrays with open(fname_lbl, 'rb') as flbl: magic, num = struct.unpack(">II", flbl.read(8)) lbl = np.fromfile(flbl, dtype=np.int8) with open(fname_img, 'rb') as fimg: magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16)) img = np.fromfile(fimg, dtype=np.uint8).reshape(len(lbl), rows, cols) get_img = lambda idx: (lbl[idx], img[idx]) # Create an iterator which returns each image in turn for i in range(len(lbl)): yield get_img(i) def get_flat_mnist(dataset="training", path="./mnist", items=60000, normalize=False): images = tuple() labels = tuple() i = 0 for image in read(dataset, path): images += (image[1],) labels += (image[0],) i += 1 if i == items: break flat_images = tuple() for image in images: flat_image = np.ndarray.flatten(image) flat_images += (flat_image,) #del images out_labels = tuple() # [0,1,2,3,4,5,6,7,8,9] for item in labels: if item == 0: out_labels += ([1,0,0,0,0,0,0,0,0,0],) elif item == 1: out_labels += ([0,1,0,0,0,0,0,0,0,0],) elif item == 2: out_labels += ([0,0,1,0,0,0,0,0,0,0],) elif item == 3: out_labels += ([0,0,0,1,0,0,0,0,0,0],) elif item == 4: out_labels += ([0,0,0,0,1,0,0,0,0,0],) elif item == 5: out_labels += ([0,0,0,0,0,1,0,0,0,0],) elif item == 6: out_labels += ([0,0,0,0,0,0,1,0,0,0],) elif item == 7: out_labels += ([0,0,0,0,0,0,0,1,0,0],) elif item == 8: out_labels += ([0,0,0,0,0,0,0,0,1,0],) elif item == 9: out_labels += ([0,0,0,0,0,0,0,0,0,1],) return flat_images, out_labels def show(image): """ Render a given numpy.uint8 2D array of pixel data. """ from matplotlib import pyplot import matplotlib as mpl fig = pyplot.figure() ax = fig.add_subplot(1,1,1) imgplot = ax.imshow(image, cmap=mpl.cm.Greys) imgplot.set_interpolation('nearest') ax.xaxis.set_ticks_position('top') ax.yaxis.set_ticks_position('left') pyplot.show() def reshape(image_array): i = 0 temp_image = [] temp_row = [] for item in image_array: temp_row.append(item) if i == 27: temp_image.append(temp_row) temp_row = [] i = 0 else: i += 1 return np.array(temp_image, dtype=np.int32) if __name__ == '__main__': #------------------------------------------- # MNIST attempt 2 # ``````````````` # TURNING INTO STANDALONE TOOL! # neural network with 784 inputs, for flattened input of # mnist data. # need to do: # * add a more menu like system to make this into a machine # learning aid try: import cPickle as pickle except: import pickle # get data if raw_input("load mnist training data? (y/N): ").lower() == 'y': load_d = raw_input(" enter filename (eg. 500 = tx-500, ty-500): ") with open("mnist/tx{}".format(load_d), 'rb') as f: x = pickle.load(f) with open("mnist/ty{}".format(load_d), 'rb') as f: y = pickle.load(f) else: print("grabbing data...") t_in, t_out = get_flat_mnist(items=1000, normalize=False) print(" got nmist array!") print(' {}x{}'.format(len(t_in), len(t_in[0]))) x = np.array(t_in, dtype=np.float) y = np.array(t_out, dtype=np.float) # load/init network load = raw_input("load network? (y/N): ") net_loaded = False if load.lower() == 'y': fname = raw_input("network filename: ") with open('nets/{}'.format(fname), 'rb') as f: nnn = pickle.load(f) net_loaded = True else: # set hypervariables i_input = 784 # this is how many pixel per image (they are flat) i_out = 10 #even shrink weights = ((784, 512, NENonlinear('sigmoid')), (512, 256, NENonlinear('sigmoid')), (256, 128, NENonlinear('sigmoid')), (128, 64, NENonlinear('sigmoid')), (64, 32, NENonlinear('sigmoid')), (32, 16, NENonlinear('sigmoid')), (16, 10, NENonlinear('sigmoid'))) # smaller #weights = ((784, 256, NENonlinear('sigmoid')), #(256, 64, NENonlinear('sigmoid')), #(64, 10, NENonlinear('sigmoid'))) # initialise network print("initialising network...") #nn = NeuralNetwork(i_input, i_hidden, i_out, Nonlinear('sigmoid'), False, 0.1) nnn = NENNN(inputs=i_input, weights=weights, outputs=i_out, alpha=0.1) print(" network initialised!") if net_loaded: stats = raw_input("print stats about current net? (y/N): ") if stats.lower() == 'y': nnn.print_stats() # train network alpha = raw_input("change alpha ({}): ".format(nnn._ALPHA)) if alpha not in (0, "", None): nnn.update_alpha(np.float(alpha)) loops = raw_input("how man training loops? (100): ") if loops in (0, "", None): loops = 100 else: loops = int(loops) batches = raw_input("process in batches of? (0 = all at once): ") if batches in (0, "", None): batches = 0 else: batches = int(batches) if batches == 0: print("training network for {} loops, all samples at once".format(loops)) nnn.train(x, y, loops) else: print("training network for {} loops, in batches of {} samples".format(loops, batches)) split = int(np.ceil(len(x) / batches)) for i in range(split): _from = batches*i _to = batches*(i+1) _x = x[_from: _to] _y = y[_from: _to] nnn.train(_x, _y, train_loops=loops) print(" training using samples from {} to {} of {}".format(_from, _to, len(x))) #show_image = input("Show image (x[0])? (y/N): ") #if show_image.lower() == "y": ##print(reshape(x[0])) #show(reshape(x[0])) # save network save = raw_input("save network? (y/N): ") if save.lower() == 'y': fname = raw_input("save network as: ") with open('nets/{}'.format(fname), 'wb+') as f: pickle.dump(nnn, f)
2ac4da68f38bd5f8a22d67a22ada09f50085f7dd
sharonLuo/LeetCode_py
/longest-valid-parentheses.py
3,665
4.03125
4
""" Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. """ ###### Solution 1 class Solution: # @param s, a string # @return an integer def longestValidParentheses(self, s): maxlen = 0 stack = [] last = -1 for i in range(len(s)): if s[i]=='(': stack.append(i) # push the INDEX into the stack!!!! else: if stack == []: last = i else: stack.pop() if stack == []: maxlen = max(maxlen, i-last) else: maxlen = max(maxlen, i-stack[len(stack)-1]) return maxlen ### solution 1.1 class Solution: # @param s, a string # @return an integer def longestValidParentheses(self, s): maxlen = 0 stack = [] last = -1 for inx in range(len(s)): if s[inx] == "(": stack.append(inx) elif s[inx] == ")" and len(stack) == 0: last = inx else: stack.pop() if stack == []: maxlen = max(maxlen, inx-last) else: maxlen = max(maxlen, inx-stack[len(stack)-1]) return maxlen ##### Solution 2 Dynamic Programming (很多边界问题要注意) class Solution: # @param s, a string # @return an integer def longestValidParentheses(self, s): if len(s) < 2: return 0 dp = [0]*len(s) for inx in range(len(s)): ### 如果没有inx-1 >= 0, 则")("输出为2 if s[inx] == ")" and inx-1 >=0 and s[inx-1] == "(": dp[inx] = dp[inx-2]+2 ### 同样这里需要保证 inx-dp[inx-1]-2 >= 0 elif s[inx]==")" and s[inx-1] == ")" and (inx-dp[inx-1]-1 >= 0) and s[inx-dp[inx-1]-1]== "(": if inx - dp[inx-1] - 2 >=0 : dp[inx] = dp[inx-1]+2+dp[inx-dp[inx-1]-2] else: dp[inx] = dp[inx-1]+2 return max(dp) #### Solution 3: 两边扫描法 class Solution: # @param s, a string # @return an integer def longestValidParentheses(self, s): answer = 0 depth = 0 ### 完成对出现多余")"情况的查找 start = -1 for inx in range(len(s)): if s[inx] == "(": depth += 1 else: depth -= 1 if depth < 0: start = inx depth = 0 elif depth == 0: ### 仅当depth == 0时才计算并更新max length answer = max(answer, inx-start) ### 完成对出现多余"("情况的查找 depth = 0 start = len(s) for inx in range(len(s)-1, -1, -1): if s[inx] == ")": depth += 1 else: depth -= 1 if depth < 0: start = inx depth = 0 elif depth == 0: ### 仅当depth == 0时才计算并更新max length answer = max(answer, start-inx) return answer
507acf567b8442d7c9200bacad0037f0b01f7f6c
daniel-reich/ubiquitous-fiesta
/zgu7m6W7i3z5SYwa6_3.py
177
3.578125
4
def is_equal(lst): num1=str(lst[0]) num2=str(lst[1]) total1=0 total2=0 for i in num1: total1+=int(i) for i in num2: total2+=int(i) return total1==total2
5cee3bccc5d9546d6f24a330f6e389af4e82e161
horeilly1101/naive-fibonacci
/fib.py
286
4.03125
4
''' contains a naive recursive implementation of the fibonacci sequence ''' def fib(num): ''' returns the ith element of the fibonacci sequence kw args: num -- an integer greater than or equal to zero ''' return 1 if (num == 1 or num == 0) \ else fib(num-1) + fib(num-2)
c2257f3ed88f15d9f4628d08e168abe86b36e20a
mihaeladimovska1/interview_practice
/problem_01_01.py
427
3.90625
4
'''ord(character) returns an integer between 0...127 from a single unicode character''' def are_all_chars_unique(s): all_chars = [0 for i in range(128)] for character in s: if not all_chars[ord(character)]: all_chars[ord(character)]=1 else: return False return True test1 = "mihaela" test2 = "zlatko" print(are_all_chars_unique(test1)) print(are_all_chars_unique(test2))
71b2c875306a0164af9fb93af75f02b84c23a0a1
kowshik448/python-practice
/python codes/factorial.py
294
4.0625
4
n = int(input()) def recursive_factorial(n): if n==1: return n else: return n*recursive_factorial(n-1) if n < 0: print('invalid nmber , please enter positive num ber') elif n==0: print('factoeial of 0 is 1') else: print(recursive_factorial(n))
a1624a983b6adf49330a7ac3a3af64903d958e80
Gilbert-van-Lierop/Python
/09_dictionaries.py
823
3.53125
4
#word= key(dit is de unieke identifier in de dicttionairy) en value is de echte definitei #wij gaan een programma maken die een maand van 2 letters omzet naar de volle maand naam #dus jan => Januery | feb omzet naar FEbruaie #dicttionairy wordt altijd gemaak met open en closing{} maand_conversie = { "Jan" : "Januari", "Feb" : "Februari", "May" : "May", "Jun" : "Juni", "Jul" : "Juli", "Aug" : "Augustus", "Sep" : "September", "Oct" : "October", "Nov" : "November", "Dec" : "Decemeber", } #nu hebben key value pairs print(maand_conversie["Nov"]) #ik kan referen aan de key en het geeft me de volledige naam #print(maand_conversie["liefde"]) print(maand_conversie.get("Liefde", "geen valide sleutel")) #keys kunnen ook nummers zijn, zolang ze uniek zien
72b8c72b69d1ca360c3beaf56edca08526724752
suraj1ly/AI-Vs-2048
/Programming_Assignment/Assignment2/pa2.py
8,684
3.59375
4
import copy import math countz=0 def check(tic): if (tic[0]==tic[1] and tic[1]==tic[2] and tic[0]=='X') or (tic[3]==tic[4] and tic[4]==tic[5] and tic[4]=='X') or(tic[6]==tic[7]and tic[7]==tic[8]and tic[8]=='X'): return -1 if (tic[0]==tic[1] and tic[1]==tic[2] and tic[0]=='O') or (tic[3]==tic[4] and tic[4]==tic[5] and tic[4]=='O') or(tic[6]==tic[7]and tic[7]==tic[8]and tic[8]=='O'): return 1 if (tic[0]==tic[3] and tic[3]==tic[6] and tic[0]=='X') or (tic[1]==tic[4] and tic[4]==tic[7] and tic[1]=='X') or (tic[2]==tic[5] and tic[5]==tic[8] and tic[2]=='X'): return -1 if (tic[0]==tic[3] and tic[3]==tic[6] and tic[0]=='O') or (tic[1]==tic[4] and tic[4]==tic[7] and tic[1]=='O') or (tic[2]==tic[5] and tic[5]==tic[8] and tic[2]=='O'): return 1 if (tic[0]==tic[4] and tic[4]==tic[8] and tic[0]=='X') or (tic[2]==tic[4]and tic[4]==tic[6] and tic[2]=='X'): return -1 if (tic[0]==tic[4] and tic[4]==tic[8] and tic[0]=='O') or (tic[2]==tic[4]and tic[4]==tic[6] and tic[2]=='O'): return 1 count1=0 for i in range(9): if tic[i]==' ': count1=count1+1 if count1>0: return -10 else: return 0 def recerminmax1(tic2,flag,a,b):#used third return value as dummy global countz countz=countz+1 if check(tic2)==1: return (1,copy.deepcopy(tic2),[],1,math.inf) if check(tic2)==0 and flag==1: return (0,copy.deepcopy(tic2),[],-math.inf,0) if check(tic2)==0 and flag==0: return (0,copy.deepcopy(tic2),[],0,math.inf) if check(tic2)==-1: return (-1,copy.deepcopy(tic2),[],-math.inf,-1) #print("Iteration") #print(tic2) #print("For each state Alpha :",a) #print("For each state Beta: ",b) power=[] node=[] for i in range(9): if tic2[i]==' ': if flag==1: tic2[i]='O' #print("Isme1") t,s,f,c,d=recerminmax1(copy.deepcopy(tic2),0,a,b) #print("Alpha :",a) #print("Beta: ",b) power.append(t) node.append(s) if t>=b: #print("Pruning is done 1") q=power.index(max(power)) g=node[q] if t>a: a=t return max(power),tic2,g,a,b if t>a: a=t #print("Updation in alpha 1") #print("Completed 1") #print(s) tic2[i]=' ' flag=1 #print(" S : ",s) else: tic2[i]='X' #print("Isme2") t,s,f,c,d=recerminmax1(copy.deepcopy(tic2),1,a,b) #print("Alpha :",a) #print("Beta: ",b) power.append(t) node.append(s) if t<=a: #print("Pruning is done 2") q=power.index(min(power)) g=node[q] if t<b: b=t return min(power),tic2,g,a,b if t<b: b=t #print("Updation in beta 1") #print("Completed 2") tic2[i]=' ' #print(" S :",s) flag=0 #print("Power :",power) #print("Node : ",node[power.index(max(power))]) if flag==1: q=power.index(max(power)) g=node[q] return max(power),tic2,g,a,b else: q=power.index(min(power)) g=node[q] return min(power),tic2,g,a,b def recerminmax(tic2,flag): #used third return value as dummy global countz countz=countz+1 if check(tic2)==1: return (1,copy.deepcopy(tic2),[]) if check(tic2)==0: return (0,copy.deepcopy(tic2),[]) if check(tic2)==-1: return (-1,copy.deepcopy(tic2),[]) #print("Iteration") #print(tic2) power=[] node=[] for i in range(9): if tic2[i]==' ': if flag==1: tic2[i]='O' #print("Isme1") t,s,f=recerminmax(copy.deepcopy(tic2),0) #print("Completed 1") #print(s) tic2[i]=' ' flag=1 #print(" S : ",s) power.append(t) node.append(s) else: tic2[i]='X' # print("Isme2") t,s,f=recerminmax(copy.deepcopy(tic2),1) # print("Completed 2") tic2[i]=' ' #print(" S :",s) flag=0 power.append(t) node.append(s) #print("Power :",power) #print("Node : ",node[power.index(max(power))]) if flag==1: q=power.index(max(power)) g=node[q] return max(power),tic2,g else: q=power.index(min(power)) g=node[q] return min(power),tic2,g def newstate(tic4,flag): tic3=copy.deepcopy(tic4) m,n,b=recerminmax(copy.deepcopy(tic3),flag) return b def minimax(tic): global countz tic1=copy.deepcopy(tic) sum=0 count=0 while (check(tic1)!=1 and check(tic1)!=-1 and check(tic1)!=0 and count<=8): if count%2==0: #Chance of User print("Enter the move ") move=int(input()) if (tic1[move-1]=='X' or tic1[move-1]=='O' or move<1 or move>9 or tic1[move-1]=='O'): print("Invalid move or Already occupied Space") continue tic1[move-1]='X' print("Move By User") for i in range(3): print("|",tic1[3*i],"|",tic1[3*i+1],"|",tic1[3*i+2],"|") count=count+1 else: flag=1 # print("Bug") tic1=newstate(copy.deepcopy(tic1),flag) print("Node traced : ") print(countz-sum) sum=countz # print("Bug2") print("Move By System") for i in range(3): print("|",tic1[3*i],"|",tic1[3*i+1],"|",tic1[3*i+2],"|") count=count+1 if check(tic1)==-1: print("User Win ") elif(check(tic1)==1): print("Computer Win") elif(check(tic1)==0): print("Draw") else: print("Some Error Occured") def newstate1(tic4,flag): tic3=copy.deepcopy(tic4) a=-math.inf b=math.inf #print("Original Alpha :",a) #print("Original Beta: ",b) m,n,f,a,b=recerminmax1(copy.deepcopy(tic3),flag,a,b) return f def alphabeta(tic): tic1=copy.deepcopy(tic) count=0 sum=0 global countz while (check(tic1)!=1 and check(tic1)!=-1 and check(tic1)!=0 and count<=8): if count%2==0: #Chance of User print("Enter the move ") move=int(input()) if (tic1[move-1]=='X' or tic1[move-1]=='O' or move<1 or move>9 or tic1[move-1]=='O'): print("Invalid move or Already occupied Space") continue tic1[move-1]='X' print("Move By User") for i in range(3): print("|",tic1[3*i],"|",tic1[3*i+1],"|",tic1[3*i+2],"|") count=count+1 else: flag=1 #print("Bug") tic1=newstate1(copy.deepcopy(tic1),flag) #print("Bug2") print("Nodes Traced : ") print(countz-sum) sum=countz print("Move By System") for i in range(3): print("|",tic1[3*i],"|",tic1[3*i+1],"|",tic1[3*i+2],"|") count=count+1 if check(tic1)==-1: print("User Win ") elif(check(tic1)==1): print("Computer Win") elif(check(tic1)==0): print("Draw") else: print("Some Error Occured") pass def nothing(): print("Error in choosing choice ") if __name__ == "__main__": print(".........Tic Tac Toe...........") tic=[] j=0 tic=[' ',' ',' ',' ',' ',' ',' ',' ',' '] for i in range(3): print("|",tic[3*i],"|",tic[3*i+1],"|",tic[3*i+2],"|") print("Start Play by entering the Choice ") print("1. Using Minimax") print("2. AlphaBeta Pruning") choice = int(input()) if choice == 1: minimax(tic) pass elif choice == 2: alphabeta(tic) pass else: nothing()
3de4fe8558dd71a29a9d01b62f3263265dd4d1d6
osamadel/Hacker-Rank
/Implementation/designer_PDF_viewer.py
1,115
3.953125
4
''' PROBLEM LINK: https://www.hackerrank.com/challenges/designer-pdf-viewer/problem ''' import math import os import random import re import sys # Complete the designerPdfViewer function below. def designerPdfViewer(h, word): alphabet = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26 } word_heights = [] for c in word: word_heights.append(h[alphabet[c] - 1]) max_height = max(word_heights) return max_height * len(word) if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') h = list(map(int, input().rstrip().split())) word = input() result = designerPdfViewer(h, word) print(str(result)) # fptr.write(str(result) + '\n') # fptr.close()
c1c2fe07ea583801d28cb1746b587900e9e5ba6f
BICpen12/pihat
/hat_message.py
388
3.5625
4
#!usr/bin/env python3 #needs to run on python3 from sense_hat import SenseHat sense = SenseHat() color= (255, 0, 0) speed = 0.05 x = input('Enter your name: ') #imput allows for input from user message = ('Hello, ' + str (x) ) #str converts x into a string print (message) sense.show_message(message, speed, text_colour=color) #tells sense.show_message what variables you need
00e0a5b9c2cfc41a06f1de0fd50e2d4ac5669719
nightjuggler/puzzles
/dragon.py
1,277
3.5625
4
#!/usr/bin/python # Is minMoves = 2 * (numCaves - 2) for all numCaves > 2? (True at least for numCaves = 3 thru 7) numCaves = 5 allCaves = range(numCaves) maxCave = numCaves - 1 moves = [] prevStates = set() minMoves = None def solve(dragonCaves): global minMoves if minMoves is not None and len(moves) >= minMoves: return state = tuple(dragonCaves) if state in prevStates: return prevStates.add(state) for move in allCaves: moves.append(move) nextCaves = set() for cave in dragonCaves: if cave > 0: if move != cave - 1: nextCaves.add(cave - 1) if cave < maxCave: if move != cave + 1: nextCaves.add(cave + 1) if nextCaves: solve(nextCaves) else: if minMoves is None or len(moves) <= minMoves: minMoves = len(moves) print minMoves, moves moves.pop() prevStates.remove(state) if __name__ == '__main__': import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('number_of_caves', nargs='?', default=numCaves, type=int) args = parser.parse_args() if args.number_of_caves < 1: sys.exit("The number of caves must be a positive integer.") if args.number_of_caves != numCaves: numCaves = args.number_of_caves allCaves = range(numCaves) maxCave = numCaves - 1 solve(allCaves)
f12a1255662029cde2f4371c8b190d466dbb2961
RunhuaGao/LeetCode
/75_SortColors/75_version1.py
694
3.6875
4
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ size = len(nums) if size < 2:return red,white,blue = 0,0,0 for n in nums: if n==0:red+=1 elif n==1:white+=1 else:blue+=1 threshold_red = red threshold_white = red+white for i in range(size): if i < threshold_red:nums[i] = 0 elif i < threshold_white:nums[i] = 1 else:nums[i] = 2 # Straight Forward Two pass algorithm # Iterate the array first, count the number of red,white,red # Then directly overwrite the array
77d96d49aaf351f4b057b81eafbb3ef079022cd5
Nimisha-V-Arun/Interview-Prep
/Arrays/Python/numForm.py
569
3.828125
4
def factorial(no): f = 1 if(no == 0 or no == 1): return 1 else: return(no*factorial(no-1)) def getSum(n): arr = [4,5,6] fact = factorial(n) digSum = 0 for i in range(len(arr)): digSum += arr[i] digSum = digSum * (fact // n) i =1 k =1 res = 0 while(i<=n): res += digSum * k k = k * 10 i = i+1 print(res) return res def numForm(arr): total =0 for i in range(1,len(arr)+1): total += getSum(i) print(total) numForm([4,5,6])
03d2efe25e91d4fc3ba16bdf5bd9e598405d684e
diligentaura/oldpypractice
/pracTrue.py
244
3.796875
4
import random number = input ("Your Number:") x = 0 while True: num = random.randint (1,100000) print (num) x=x+1 print if num == int (number): break print ("Number of Times:") print ("") print (x)
41354043ffe2349f4915d3e5fb1cafc0603a3892
Etv500/Python-Basics-to-make-and-break
/max of a column numpy.py
223
3.640625
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 27 17:59:11 2017 @author: elvis """ import numpy a = numpy.array([[10, 2], [3, 4], [5, 6]]) xmax = numpy.max(a[0:-1,0]) ymax = numpy.max(a[0:-1,1]) print(xmax, ymax)
8f1895d912bbe0a8c8c8c3b442445d501ea10bc2
Vasyl0206/orests_homework
/cw28.py
320
3.65625
4
class Ball(object): def __init__(self,ball_type = None): self.ball_type = ball_type if self.ball_type is None: self.ball_type = 'regular' elif: self.ball_type = ball_type ball1 = Ball() ball2 = Ball("super") ball1.ball_type #=> "regular" ball2.ball_type #=> "super"
be3eb151487e790ba5cd9da8c81888e0601cfec7
Doldge/MyFirstGame
/tree_span.py
2,936
3.59375
4
#! /usr/bin/python #Tree spanning Alg # Currently unused. # Could be used for generating efficient connections between points. # And navigating units around the map / etc import sys import heapq class Vertex(object): def __init__(self, node): self.id = node self.adjacent = {} # Distance to infinity for all nodes self.distance = sys.maxint self.visited = False self.previous = None def addNeighbor(self, neighbor, weight=0): self.adjacent[neighbor] = weight def getConnections(self): return self.adjacent.keys() def getId(self): return self.id def getWeight(self, neighbor): return self.adjacent[neighbor] def setDistance(self, dist): self.distance = dist def getDistance(self): return self.distance def setPrevious(self, prev): self.previous = prev def getPrevious(self): return self.previous def setVisited(self): self.visited = True def __str__(self): return str(self.id) + ' adjacent: '+str([x.id for x in self.adjacent]) class Graph(object): def __init__(self): self.vert_dict = {} self.num_vertices = 0 def __iter__(self): return iter(self.vert_dict.values()) def addVertex(self, node): self.num_vertices += 1 new_vertex = Vertex(node) self.vert_dict[node] = new_vertex return new_vertex def getVertex(self, n): if n in self.vert_dict: return self.vert_dict[n] return None def addEdge(self, frm, to, cost=0): if frm not in self.vert_dict: self.addVertex(frm) if to not in self.vert_dict: self.addVertex(to) self.vert_dict[frm].addNeighbor(self.vert_dict[to], cost) self.vert_dict[to].addNeighbor(self.vert_dict[frm], cost) def getVertices(self): return self.vert_dict.keys() def shortest(v, path): if v.previous: path.append(v.previous.getId()) shortest(v.previous, path) return def dijkstra(graph, start): #Sets start node distance 0 start.setDistance(0) #create priority heap/queue unvisited_queue = [(v.getDistance(), v) for v in graph] heapq.heapify(unvisited_queue) while len(unvisited_queue): # Get smallest vertex uv = heapq.heappop(unvisited_queue) current = uv[1] current.setVisited() for next in current.adjacent: if next.visited: continue new_dist = current.getDistance() + current.getWeight(next) if new_dist < next.getDistance(): next.setDistance(new_dist) next.setPrevious(current) while len(unvisited_queue): heapq.heappop(unvisited_queue) unvisited_queue = [ (v.getDistance(), v) for v in graph if not v.visited ]
592f40b5ac73a601cc2178815ab9e72df45dde6c
Jane620/fluentPython
/tests/ut/chapter2/test_nametuple.py
449
3.6875
4
# -*- coding:utf-8 -*- from src.chapter2.nametuple_list import exec_city_info, make_city_info def test_city(): """ function main 我是函数说明 """ detail = exec_city_info() assert detail.name == "HZ" def test_make(): """ nametuple._make(iterator) == nametuple(*iterator) :return: """ city_info = ("HZ", "ZJ", 100, (101,200)) details = make_city_info(city_info) assert details.name == "HZ"
a6e06759e894d7b9607175e1b84377b5f9255c35
bmarkwalder/csc594
/hw_01/text_pre_processing.py
8,741
4
4
""" Brandon Markwalder CSC 594 Spring 2018 Homework 01 Text pre-processing This program will tokenize a corpus such that words, leading and trailing punctuation and expanded contractions are converted to tokens. Punctuation found in the middle of a word is ignored. The program outputs the number of: Sentences, paragraphs, tokens, types, and the token frequencies. To run the program: Save text_pre_processing.py and the input file to the same directory. Open text_pre_processing.py in the Python interpreter and run the module. By default, the program will look for sample.txt as the input file and write output.txt as output file to the same directory in which text_pre_processing.py is stored. The program will accept input and output file arguments from an IDE, however if the arguments are malformed or the input file cannot be found, the program will exit. Optionally the program can be run from the command line and supplied input and output filearguments. Error checking has been kept to a minimum so again, the program will exit if the argumentsare malformed or if the input file cannot be found. To run the program from the command line on a windows machine: Save the input file to the top level directory in which python.exe is located and execute the following command: text_pre_processing.py -i <inputfile> -o <outputfile> """ import sys import getopt from nltk.tokenize import sent_tokenize import string #Open and read the input file def read_file(path): words = [] with open(path, 'r') as f: for line in f: for word in line.split(): words.append(word) return words #Recurrsively strip and tokenize punctuation from the end of each word def process_end(words, pun): for word in words: if word[-1] in pun and len(word) > 1: words[(words.index(word))] = word[0:-1] words.append(word[-1]) process_end(words, pun) return words #Recurrsively strip and tokenize punctuation from the beginning of each word def process_start(words, pun): for word in words: if word[0] in pun and len(word) > 1: words[(words.index(word))] = word[1:] words.append(word[0]) process_end(words, pun) return words #Process special case contractions '''Check each word. If it exists in the dictionary, split the returned value Replace the special case contraction with the leading split result and append the trailing result to the list''' def process_special(words): dict = {"Can't": "can not", "can't": "can not", "He's": "He is", "he's": "he is", "Here's": "Here is", "here's": "here is", "I'm": "I am","i'm": "i am", "It's": "It is", "it's": "it is", "She's": "She is", "she's": "she is", "That's": "That is", "that's": " that is", "There's": "There is", "there's": "there is", "Won't": "Will not", "won't": "will not"} for word in words: if word in dict: split = dict.get(word).split() words[(words.index(word))] = split[0] words.append(split[1]) return words #Process compound contractions by stripping the trailing contraction '''Replace the compound contraction with the singular contraction in place Do a dictionary lookup for the trialing contraction and append the value to the list''' def process_compounds(words): dict = {'ll': 'will', "n't": 'not', 've': 'have', 'd': 'would', 're': 'are'} for word in words: if word.find("'") != -1 and len(word) > 1: split = word.split("'") if len(split) > 2: words[(words.index(word))] = word[0:(len(word)-(len(split[2]))-1)] words.append(dict.get(split[2])) return words #Process single contractions and possesives '''Check each word and split if a possessive or contraction is found. If the trailing split is equal to the string literal s, we replace the word in place with the leading split and append the trailing split with a joined apostrophe because we lost it in the split operation. If the trialing split is equal to the string literal t, slice the word such that we remove the sting literal n and replace the word in place in the list. Then we append the resulting value of the dictionary lookup to the list. All other split cases fall to the else block where the word is replaced with the leading split dictionary lookup and the trailing split dictionary lookup is appended to the list''' def process_contractions(words): dict = {'ll': 'will', "t": 'not', 've': 'have', 'd': 'would', 're': 'are'} for word in words: if word.find("'") != -1 and len(word) > 1: split = word.split("'") if split[1] == 's': words.append(split[0]) words[(words.index(word))] = ('' .join(["'", split[1]])) elif split[1] == 't': words[(words.index(word))] = (split[0])[:-1] words.append(dict.get(split[1])) else: words[(words.index(word))] = split[0] words.append(dict.get(split[1])) return words #Count the number of paragraphs def find_paragraphs(lines): p_count = [line for line in lines if (line != '\n')] return p_count #Count the number of sentences def find_sentences(paragraphs): sentences = sent_tokenize(''.join(paragraphs)) return sentences #Compute word frequencies '''Iterate through the tokenized list and add each item to the dictionary. If the key exists, update the value by 1. If the key does not exists, it is added to the dictionary with an initial value of 1.''' def get_frequencies(words): freq = {} for item in words: if item in freq: freq[item] += 1 else: freq[item] = 1 return freq #Read the file and tokenize the contents. def tokenize(path): words = read_file(path) #Apply set() to String's puncuation list pun = set(string.punctuation) words = process_end(words, pun) words = process_start(words, pun) words = process_special(words) words = process_compounds(words) words = process_contractions(words) return words #Gather outputs, sort the tokens, and write to disk def write_to_file(words, INPUT_FILE_NAME, OUTPUT_FILE_NAME): lines = open(INPUT_FILE_NAME) paragraphs = find_paragraphs(lines) sentences = find_sentences(paragraphs) num_tokens = len(words) num_types = len(set(words)) frequencies = get_frequencies(words) #Convert the frequency dictionary to a lexicographically sosrted list in ascending order frequencies = (sorted(frequencies.items(), key=lambda x: (x[0]))) #Resort the list by frequency in decending order frequencies.sort(key=lambda x: (x[1]), reverse=True) f = open(OUTPUT_FILE_NAME, 'w') f.write('# of paragraphs = ' + str(len(paragraphs)) + '\n') f.write('# of sentences = ' + str(len(sentences)) + '\n') f.write('# of tokens = ' + str(num_tokens) + '\n') f.write('# of types = ' + str(num_types) + '\n') f.write('================================' + '\n') for key, value in frequencies: f.write(str(key) + " " + str(value) + '\n') f.close() #Main function '''Takes .txt input and outputs .txt If run in the Python interpreter and no arguments are passed, the program defaults to the following arguments: input=sample.txt and output=output.txt Main has limited error checking and will exit on malformed arguments or missing files Main modifed from: https://www.tutorialspoint.com/python3/python_command_line_arguments.htm''' def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print ('text_pre_processing.py -i <inputfile> -o <outputfile>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('text_pre_processing.py -i <inputfile> -o <outputfile>') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg if len(inputfile) != 0: INPUT_FILE_NAME = inputfile else: INPUT_FILE_NAME = 'sample.txt' if len(outputfile) != 0: OUTPUT_FILE_NAME = outputfile else: OUTPUT_FILE_NAME = 'output.txt' print('Tokenizing ' + INPUT_FILE_NAME) print('Output written to ' + OUTPUT_FILE_NAME) tokens = tokenize(INPUT_FILE_NAME) write_to_file(tokens, INPUT_FILE_NAME, OUTPUT_FILE_NAME) if __name__ == "__main__": main(sys.argv[1:])
c3856fcea61038a17abd456c2f343576de95fb8b
DanielRJohnson/Neural-Networks-From-Scratch
/main.py
3,752
3.78125
4
''' # Name: Daniel Johnson # File: main.py # Date: 1/3/2021 # Brief: This script creates uses neural_network to train # and evaluate the network using XOR as an example ''' import numpy as np import matplotlib.pyplot as plt from neural_network import Neural_Network def main(): #make a neural network with set architecture arch = (2,4,1) nn = Neural_Network(arch) #XOR input data X_train = np.array( [ [0,0], [0,1], [1,0], [1,1] ] ) #XOR output data y_train = np.array( [[0],[1],[1],[0]] ) #set max iterations, learning rate, and convergence threshold iters, lr, threshold = 5000, 1, 0.00001 #train the network J_Hist = nn.train(X_train, y_train, alpha = lr, maxIter = iters, convergenceThreshold = threshold) #forward propagate to get a prediction from the network result = nn.forwardProp(X_train) #print some nice information print("\nUnfiltered Prediction:\n", result) print("Final Prediction:\n", result >= 0.5, '\n') print("Random init cost: ", round(J_Hist[0], 5), ", Final cost: ", round(J_Hist[-1], 5)) print("Cost reduction from random init: ", round(J_Hist[0] - J_Hist[-1], 5), '\n') #set up subplots for the cost history and decision boundary figure, plots = plt.subplots(ncols=2) figure.suptitle('Neural Network Learning of XOR') #supertitle figure.tight_layout(pad=2.5, w_pad=1.5, h_pad=0) #fix margins drawCostHistory(J_Hist, plots[0]) drawDecisionBoundary(nn, plots[1], seperation_coefficient = 50, square_size = 1, allowNegatives = False) #show the cool graphs :) plt.show() ''' # @param: J_Hist: a list of costs to plot over iterations # plot: a matplotlib plot # @post: a curve is plotted showing cost over iterations ''' def drawCostHistory(J_Hist: list, plot): plot.plot(J_Hist) plot.set_ylabel('Cost') plot.set_xlabel('Iterations') plot.set_title('Cost vs. Iterations') plot.axis([0, len(J_Hist), 0, max(J_Hist)]) plot.set_aspect(len(J_Hist)/max(J_Hist)) ''' # @param: nn: a Neural_Network object # plot: a matplotlib plot # seperation_coefficient: a measure of how many points there are per 1 unit # square_size: length and width of area plotted # allowNegatives: if true, it will shift the data into four quadrants instead of just positive positive # @post: points are plotted to the plot with color depending on their nn result ''' def drawDecisionBoundary(nn, plot, seperation_coefficient: int = 50, square_size: int = 1, allowNegatives: bool = False): #create a 2d array of input values depending on the parameters X_Test = [] for i in range(seperation_coefficient + 1): X_Test.append([]) for j in range(seperation_coefficient + 1): xVal = i*square_size/seperation_coefficient yVal = j*square_size/seperation_coefficient if allowNegatives: xVal -= square_size/2.0 yVal -= square_size/2.0 X_Test[i].append([xVal, yVal]) #get the results from the range of values and plot them test_result = nn.forwardProp(X_Test) for i in range(len(test_result)): for j in range(len(test_result)): xVal = X_Test[i][j][0] yVal = X_Test[i][j][1] clr = (1 - test_result[i][j][0],0,test_result[i][j][0]) #this other line plots the >= .5 binary predictions instead of range of purples #clr = "blue" if test_result[i][j] >= 0.5 else "red" plot.plot(xVal, yVal, color=clr, marker="s") plot.set_ylabel('X2') plot.set_xlabel('X1') plot.set_title('Decision Boundary [X1, X2] -> Y\nBlue = 1, Red = 0') plot.set_aspect('equal') if __name__ == "__main__": main()
19a72e26387fe2b6887657361ba27443a9113461
haoknowah/OldPythonAssignments
/Gaston_Noah_NKN328_Hwk18/008_sequenceOfNumbers.py
1,416
3.984375
4
def sequenceOfNumbers(m, n): ''' sequenceOfNumbers()=counts off numbers between m and n recursively @param m=starting number @param n=ending number prints m ''' try: if m==n: print(m) else: print(m) sequenceOfNumbers(m+1, n) except: print("Unhandled exception.") if __name__=="__main__": def test_sequenceOfNumbers(): ''' tests sequenceOfNumbers method @param cont=determines if loop repeats @param m=first input @param n=second input flair=ensures that n is greater than m ''' try: cont=True while cont==True: try: m=int(input("Type an integer: ")) while True: n=int(input("Type another one: ")) if n<m: print("Needs to be higher than first input.") else: break sequenceOfNumbers(m, n) end=input("Continue? y or n") if end=="n": cont=False except ValueError as exc: print(exc) end=input("Continue? y or n ") if end=="n": cont=False except: print("Unhandled exception.") test_sequenceOfNumbers()
b09649e263977e8648c5f8f7477d394d32a7314e
Gexeg/lessons
/OOAP/second course/InheritanceCategory(3)11.py
4,037
3.875
4
""" Задание 20. Приведите пример кода, где выполняется наследование реализации и льготное наследование. Отправьте выполненное задание на сервер. """ # Наследование реализации (implementation inheritance) # вернемся к классу "Существо". class Creature(): def __init__(self, hp): self.hp = hp self.resistances = {} self.statuses = [] def end_turn(self): for status in self.statuses.copy(): status.tick(self) if status.duration <= 0: self.statuses.remove(status) # Предположим мы захотим создать новое существо. Геймдизайнер решил, что идеальной будет раса, которая накапливает # статусы и не расходует их перенося в своем теле. В какой-то момент они могут "переключить рубильник" и начать получать # позитивные и негативные эффекты class AnotherCreature(Creature): def __init__(self, hp): super().__init__(hp) self.suppress = True def end_turn(self): if not self.suppress: super().end_turn # реализация достаточно ужасна, но вроде передает смысл. # вместе с характеристиками мы притащили за собой реализацию хранилища статусов в виде стандартного Python list. # Это будет накладывать определенные ограничения и на количество переносимых статусов. Если такой герой всю игру # будет собирать различные статусы, а под конец просто их активирует, то мы будем ооочень долго ждать их отработку. # возможным решением была бы смена реализации например накопления статусов (собирать их в стеки по типам хотя бы). """ Комментарий: Если хранилище статусов требует доп.операции к обычному списку (явные операции над его содержимым), то его надо оформить как АТД, это верный признак. Об этом на 3-м курсе по проектированию будет. """ # Льготное наследование (facility inheritance) # Возможно подходящим примером будет класс-концовка игры. Мы создаем класс-событие, вызывающее концовку игры и можем # наследоваться от неё, задавая новое описание. Таким образом, если потребуется создать тупиковую ветку приводящую к # концу игры, мы просто отнаследуемся от корневого завершения и зададим описание. Возможно тут подойдут атрибуты класса, # т.к. у нас не подразумевается несколько экземпляров разных концовок с разными описаниями. class GameOver(): same_text = '' def __init__(self): print(self.same_text) print('Game Over!') class HappyEnding(GameOver): same_text = 'And they lived happily ever after' class BadEnding(GameOver): same_text = 'And died on the same day. Today.' """ >>> first = HappyEnding() And they lived happily ever after Game Over! >>> second = BadEnding() And died on the same day. Today. Game Over! """
15424d868853c0d3bc18d4d299239ce4742bfe65
robertruhiu/learn
/slices.py
252
3.984375
4
nums=[1,2,3,4,5,6] # for i in range (1,len(nums),2): # print(nums[i]) print(nums[3:6:2]) print (nums[::-2]) print (nums[::-1]) print (nums[5:0:-1]) #they itterate on the index that starts from 0 not the numbers # in the list[start:stop:incriment]
42f5b50cac004ddb4c8cd35ed68062283db41083
amelia98/level3_NCEA
/auction.py
1,447
3.984375
4
def get_reserve(reserve): print("Auction Manager") print("Reserve must be greater than or equal to $0.00") reserve = (read_int("What is the auction reserve?")) def get_bids(names, bids): print("\nAuction has started") name="" while name.upper() !='F': print("Highest bid is ${:.2f}".format(float(max(bids)))) name = input("What is your name (\"F\" to finish)") if name.upper() !='F': names.append(name) bid=(read_int("What is you bid?")) if bid <= max(bids): print("You will need to make a higher bid.") bids.append(bid) def show_bids(names, bids): print("\nBidding History") for i in range (1,len(names)): print("{} bid ${:.2f}".format(names[i], bids[i])) def show_report(bids): if len(names) == 1: print("No bids, Auction did not meet reserve price.") if max(bids) >= reserve: print("Auction won by " + names[bids.index(max(bids))] + " with a bid of ${:.2f}".format(float(max(bids)))) else: print("Auction did not meet reserve price") def read_int(prompt): choice = -1; while choice < 0: try: choice = float(input(prompt)) except ValueError: print("Not a valid integer") return choice #main routine names = [0,] bids = [0.00,] reserve = 0 get_reserve(reserve) get_bids(names, bids) show_report(bids) show_bids(names, bids)
f5d53ae2aeee2dd7ecf33207533c514c0df62f63
Javed69/Python
/HackerRank-30DaysofChallenge/day-3-Conditional-Statement.py
185
3.84375
4
#!/bin/python3 import sys N = int(input().strip()) if N % 2 == 1: print('Weird') elif N < 5: print('Not Weird') elif N <= 20: print('Weird') else: print('Not Weird')
1307ce915f4021a60aeeea1ab0b385b8bbd433b7
zzcbetter01/pythonProject
/python学习/python编程从入门到实践/第五章、用户输入和while循环.py
3,709
4.4375
4
#### 5.1 函数input的工作原理 ## input接受一个参数,即要向用户显示的提示和说明,让用户知道该如何做 # message = input('Tell me somthing, and I will repeat it back to you: ') # print(message) ## 如果提示超过一行,可能需要将提示储存在一个变量中 # prompt = "If you tell us who you are, we can personalize the messages you see." # prompt += "\nWhat is your first name?" # name = input(prompt) # print("\nHello, "+ name + '!') ## 使用int来获取数值输入 # age = input('How old are you ?') # age = int(age) # print(age >= 18) ## 求模运算符 ## % 是一个很有用的工具,将两个数相除并返回余数。 ## 判断一个数是偶数还是奇数。 # number = input('Enter a number, and I will tell you if it is even or odd: ') # number = int(number) # if number % 2 == 0: # print('\nThe number '+ str(number) + ' is even.') # else: # print('\nThe number '+ str(number) + ' is odd.') #### 5.2 While 循环 ## for循环是针对集合中的每个元素的一个代码块,而While循环不断地运行,直到指定的条件满足为止。 # current_number = 1 # while current_number <= 5: # print(current_number) # current_number += 1 ## 让用户自己选择何时退出 # prompt = "Tell me something , and I will repeat it back to you:" # prompt += "\nEnter 'quit' to end the program." # message = '' # while message != 'quit': # message = input(prompt) # if message != 'quit': # print(message) ## 使用标志 ## 在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志。 # prompt = "Tell me something , and I will repeat it back to you:" # prompt += "\nEnter 'quit' to end the program." # active = True # while active: # message = input(prompt) # # if message == 'quit': # active = False # else: # print(message) ## 使用break退出循环 # prompt = "Tell me something , and I will repeat it back to you:" # prompt += "\nEnter 'quit' to end the program." # active = True # while active: # message = input(prompt) # # if message == 'quit': # break # else: # print(message) ## 在循环中使用continue # current_number = 0 # while current_number < 10: # current_number += 1 # if current_number % 2 == 0: # continue # 如果结果为0,就执行continue语句,让python忽略余下的代码,并返回循环的开头;否则,执行循环中余下的代码。 # print(current_number) #### 5.3 While 循环处理列表和字典 ## for循环是一种遍历列表的方式,但是不应该修改列表。而要在遍历列表的同时对其修改,可使用while循环。 ## 5.3.1 在列表间移动元素 # 首先创建一个待验证的用户列表 # 和一个用于储存已验证用户的列表 # unconfirmed_users = ['alice', 'brain', 'candace'] # confirmed_users = [] # # # 验证每个用户,直到没有未验证用户为止,将每个经过验证的列表都已到已验证的列表之中 # while unconfirmed_users: # current_user = unconfirmed_users.pop() # print('Verifying user: ' + current_user.title()) # confirmed_users.append(current_user) # # 显示所有已验证的用户 # print('The following users have been confirmed:') # for confirmed_user in confirmed_users: # print(confirmed_user.title()) ## 5.3.2 删除包含特定值的所有列表元素 pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: # 删除所有这些元素,可执行一个while循环 pets.remove('cat') print(pets)
771e8e3d343396f78454e15bc028c07b6c72608e
pigmonchu/Earth_Mars
/inputs.py
574
3.921875
4
def Input(message, options): result = input("{}: ".format(message)).upper() while result not in options: print("Opción incorrecta") result = input("{}: ".format(message)).upper() return result def valida_number(value): try: float(value) return True except ValueError: return False def input_number(message): result = input("{}: ".format(message)).upper() while not valida_number(result): print("No es un número") result = input("{}: ".format(message)).upper() return result
15178eb8f498369c6e101a7737fa7b68733feaf7
sontaku/learning_python
/01_basic/a_datatype_class/Ex07_tuple.py
986
3.546875
4
""" #---------------------------------------------------------- [튜플 자료형] 1- 리스트와 유사하지만 튜플은 값을 변경 못한다. 2- 각 값에 대해 인덱스가 부여 3- 변경 불가능 (*****) 4- 소괄호 () 사용 """ # (1) 튜플 생성 print('------------------- 1. 튜플 생성-----------------') t = (1,2,3) print(t) print(t[0]) t2 = 1,2,3 print(t2) print(t[0]) # (2) 튜플은 요소를 변경하거나 삭제 안됨 print('------------------- 2 -----------------') # t[1] = 0 # 블럭이 생기면서 실행 안됨 # del t[1] # 에러 발생 # (3) 하나의 요소를 가진 튜플 print('------------------- 3 -----------------') t3 = (1,) print(t3) # print(t3[0]) print(type(t3)) # (4) 인덱싱과 연산자 print('------------------- 4 -----------------') t4 = (1,2,3) # 1번째요소 추출 # 1번째부터 끝까지 요소 추출 # t3과 t4 합치기 # t4 3번 반복 print(t4[0]) print(t4) print(t3 + t4) print(t4 * 3)
fb4abda6554847c4d35c0a0d4ccb57b7c03b457b
RBEGamer/HACK4TK_HACKATHON_2018
/src/Case_Class_structure.py
2,258
3.59375
4
from enum import Enum class Passengers_Together: def __init__(self, num=0, list_passenger = [], time_stamp=0, start_point = [0,0], end_point = [0,0] ): self.id = id self.time_stamp = time_stamp self.num = num self.list_passenger = list_passenger self.start_point = start_point self.end_point = end_point def add_passenger(self, passenger): self.num += 1 self.list_passenger.append(passenger) return def del_passenger(self, passenger): if self.list_passenger.contains(passenger): self.num -= 1 self.list_passenger.remove(passenger) return True else: print ("no such passenger, something is wrong") return False def start_passenger(self, start_point): self.start_point = start_point return def end_passeger(self, end_point): self.end_point = end_point return class Cabin: oritation = Enum('oritation', ('go_up', 'go_down', 'go_left', 'go_right')) cabin_Count = 0 def __init__(self, id, oritation = oritation.go_down, velocity = 0, position = [0,0], list_of_passengers = Passengers_Together() ): self.id = id self.oritation = oritation self.velocity = velocity self.position = position self.list_of_passengers = list_of_passengers Cabin.cabin_Count += 1 def set_oritation(self, oritation): self.oritation = oritation return def set_velocity(self, velocity): self.velocity = velocity return def set_position(self, position): self.position = position return def get_oritation(self): return self.oritation def get_velocity(self): return self.velocity def get_position(self): return self.position def get_list_of_passengers(self): return self.list_of_passengers def __del__(self): Cabin.cabin_Count -= 1 print ("__del__") #class Floor: #class Passenger: cabin0 = Cabin(0) print (cabin0.oritation) cabin0.set_oritation(Cabin.oritation.go_up) print (cabin0.position) cabin0.set_position([1,2]) print (cabin0.position)
26f5f7f18cc166d95bb17aabc6dd4706fab16e16
mthlongwane/plylexerandparser
/parser.py
2,388
3.578125
4
# ------------------------------------------------------------ # Parser.py # MT Hlongwane 2021 # Compilers Assignment 3 # Adapted from PLY Documentation https://ply.readthedocs.io/en/latest/ply.html#lex-example # ------------------------------------------------------------ import sys import lex as lex import yacc as yacc # Step 1: Lexer work. # List of token names. This is always required tokens = ( 'NAME', 'NUMBER', 'PLUS', 'LPAREN', 'RPAREN', 'EQUALS', ) # Regular expression rules for simple tokens t_PLUS = r'\+' t_LPAREN = r'\(' t_RPAREN = r'\)' t_EQUALS = r'\=' t_NAME = r'\_?[A-Za-z]+(\_|[A-Za-z]|[0-9])*' # A regular expression rule with some action code def t_NUMBER(t): r'[0-9]+' t.value = int(t.value) return t # Define a rule so we can track line numbers def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) # A string containing ignored characters (spaces and tabs) t_ignore = ' \t' # Error handling rule def t_error(t): #print("Illegal character '%s'" % t.value[0]) print("Error in input") exit(0) t.lexer.skip(1) # Build the lexer mylexer = lex.lex() file_data = "" while True: input_ = sys.stdin.readline() if input_ == '#\n': break file_data += input_ #mylexer.input(file_data) # Step 2: Parser. # dictionary of names names = {} #def p_statement_expression(p): # '''statement : assignment ''' # p[0] = p[1] def p_statement_assign(p): '''statement : NAME EQUALS expression''' names[p[1]] = p[3] def p_expression_term(p): 'expression : term' p[0] = p[1] def p_expression_plus(p) : 'expression : expression PLUS expression' p[0] = p[1] + p[3] def p_expression_group(p): 'expression : LPAREN expression RPAREN' p[0] = p[2] def p_expression_name(p): 'term : NAME' if p[1] not in names: print("Error in input") exit(0) else: p[0] = names[p[1]] def p_term_num(p): 'term : NUMBER' p[0] = p[1] # Error rule for syntax errors #acceptanceFlag = false def p_error(p): if p or p is None : print("Error in input") exit(0) if not p: return # Build the parsser parser = yacc.yacc(debug=False, write_tables=False) for i in file_data[:-1].split('\n'): yacc.parse(i, lexer= mylexer) print ("Accepted")
b978890cb86092e1218d315e3769951b91f94250
snake1597/Leetcode
/Array/MonotonicArray.py
612
3.625
4
class Solution: def isMonotonic(self, A: List[int]) -> bool: flag = True current = A[0] if A[-1] > A[0]: for i in range(1,len(A)): if A[i] >= current: current = A[i] flag = True else: flag = False break else: for i in range(1,len(A)): if A[i] <= current: current = A[i] flag = True else: flag = False break return flag
9c865434188c07ef269d126e15bb1669909f719f
mschae94/Python
/Day13/Ex01.py
376
4.34375
4
# 리스트는 인덱스의 표현이 정수로만 가능하다 lst = ['a' ,'b' , 'c'] print(lst[0]) #반면 , 딕셔너리는 대부분의 타입이 적용가능하다. dic = {1:"hello" , 2:"world" , "python" : 3} print(dic) print(dic[1]) print(dic["python"]) dic = {"first": ['a', 'b' , 'c']} print(dic["first"]) dic[3] = "하이" print(dic)
ddf815ac376e981b53ddb5f2936c51aab4324e1f
vimiix/scripts
/yaml_to_json.py
768
3.609375
4
#!/usr/bin/python2 #coding=utf-8 ''' usage: yaml_to_json.py [-h] [-f FILE] optional arguments: -h, --help show this help message and exit -f FILE, --file FILE input yaml filename(include path) ''' __author__ = 'Vimiix' import json import yaml import argparse def yaml_to_json(path): with open(path) as f: txt=yaml.load(f) return json.dumps(txt) except yaml.YAMLError as e: print(e) if __name__ == '__main__': parser = argparse.ArgumentParser(prefix_chars='-+/') parser.add_argument("-f", "--file",required=True, help="input yaml filename(include path)") args = parser.parse_args() json_txt = yaml_to_json(args.file) print "Output:", json_txt # ...Something to handling with the json data
71a7cdd76b470450b44fd410eecf61915ca29d28
m8ko/BlackjackAnalysis
/Deck.py
661
3.671875
4
''' Creates a standard deck of 52 playing cards ''' import Card import random class Deck: def __init__(self, size=1): self.all_cards = [] for _ in range(size): for suit in Card.suits: for rank in Card.ranks: created_card = Card.Card(suit, rank) self.all_cards.append(created_card) def shuffle(self): random.shuffle(self.all_cards) def print_deck(self): for x in self.all_cards: print(x) def deal_one(self): return self.all_cards.pop() def __str__(self): return f"The deck has {len(self.all_cards)} cards"
38ec990466f4834fb573ae7f9b25a4d1fff81042
PJ71194/DSA
/Graph/charOrderInAlienLang.py
1,105
3.578125
4
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) self.vertices = set() def addEdge(self, u, v): self.graph[u].append(v) self.vertices.add(u) self.vertices.add(v) def topoUtil(self, node, visited, stack): visited[node] = 1 for child in self.graph[node]: if child not in visited: self.topoUtil(child, visited, stack) stack.append(node) def topologicalSort(self): visited = {} stack = [] for vertex in self.vertices: if vertex not in visited: self.topoUtil(vertex, visited, stack) stack.reverse() return stack class Solution: def __init__(self, dictionary): self.graph = Graph() n = len(dictionary) for i in range(n-1): word1 = dictionary[i] word2 = dictionary[i+1] l,r = 0, 0 while l < len(word1) and r < len(word2): if word1[l] != word2[r]: self.graph.addEdge(word1[l], word2[r]) l += 1 r += 1 def getCharOrder(self): charOrder = self.graph.topologicalSort() print(charOrder) dictionary = input().split() soln = Solution(dictionary) soln.getCharOrder()
f8dcb0c0759911bd479cc8ccc02ef36b6dbdcdf2
KacperKubara/hackerrank_sols
/common_child.py
873
3.609375
4
def commonChild(s1, s2): result = [] result_string = "" word_length = len(s1) for i in range(0, word_length): result.append(0) last_found = -1 for count1, char1 in enumerate(s1): if count1 >= i: for count2, char2 in enumerate(s2): if count2 > last_found: if char1 is char2: result[i] += 1 result_string += char1 last_found = count2 print("Char: {0}, Count1: {1}, Last Found: {2}".format(char1, count1, last_found)) break print('\n') print(result_string) result_string = "" return max(result) if __name__ == "__main__": s1 = "ELGGYJWKTDHLXJRBJLRYEJWVSUFZKYHOIKBGTVUTTOCGMLEXWDSXEBKRZTQUVCJNGKKRMUUBACVOEQKBFFYBUQEMYNENKYYGUZSP" s2 = "FRVIFOVJYQLVZMFBNRUTIYFBMFFFRZVBYINXLDDSVMPWSQGJZYTKMZIPEGMVOUQBKYEWEYVOLSHCMHPAZYTENRNONTJWDANAMFRX" print(commonChild(s1, s2))
685259aac8726bd49a4c91644b0ec0028707ddfe
marikaswanberg1/CS-591-Privacy-In-Machine-Learning-
/Hw1_reconstruction_attack.py
5,908
3.703125
4
import numpy as np import random import matplotlib.pyplot as plt def generate_data(n): ''' n : int specifying the size of the dataset returns a uniformly random bit vector of size n (which will be the data) ''' data = np.random.randint(low=0, high=2, size=n) return data def generate_noise(n): ''' n : int specifying the size of the dataset returns a uniformly random bit vector of size n (which will be the random coins) ''' noise = np.random.randint(low=0, high=2, size=n) return noise def generate_queries(data, noise): ''' takes as input equal-length data and noise vectors and returns the answer vector where a_i = x_1 + x_2 + ... + x_i + z_i ''' if (len(data) != len(noise)): print("length mismatch") return 0 responses = np.zeros((len(data),), dtype=int) true_running_sum = 0 for i in range(0, len(data)): true_running_sum += data[i] responses[i] = true_running_sum + noise[i] return responses def responses_diffs(responses): ''' Takes the responses as input and outputs a_{i+1} - a_i for each index. Can be useful for determining what x_{i+1} is. ''' diff = np.zeros((len(responses),), dtype=int) diff[0] = responses[0] for i in range(1, len(responses)): diff[i] = responses[i] - responses[i-1] return diff def guess_data(responses_diff): ''' The "trivial" attack, which is accurate with probability 3/4. ''' guess = np.zeros((len(responses_diff),), dtype=int) for i in range(len(responses_diff)): if (-1 == responses_diff[i]): guess[i] = 0 if (2 == responses_diff[i]): guess[i] = 1 if (0 == responses_diff[i]): guess[i] = 0 if (1 == responses_diff[i]): guess[i] = 1 return guess def guess_data2(responses): ''' A slightly more sophisticated attack. It runs the basic attack for x_i's that we can be certain about. It does a more sophisticated analysis of the sums to deduce more values for certain. For example: if we've established that the real sum at position i is 5 and the real sum at position i-5 is also 5, then we know that x_{i-4}....x_{i-1} are all 0. ''' # initialize with -1's guess = np.zeros((len(responses),), dtype=int) guess = np.full_like(guess, -1, dtype=int) # initialize with -1's noise = np.zeros((len(responses),), dtype=int) noise = np.full_like(noise, -1, dtype=int) # keep track of the real sums that we can deduce for sure real_sums = np.zeros((len(responses),), dtype=int) real_sums = np.full_like(real_sums, 2*len(responses), dtype=int) real_sum_indices = [] responses_diff = responses_diffs(responses) for i in range(len(responses_diff)): if (-1 == responses_diff[i]): guess[i] = 0 noise[i] = 0 real_sums[i] = responses[i] if (i not in real_sum_indices): real_sum_indices.append(i) if (i >= 1): noise[i-1] = 1 real_sums[i-1] = responses[i-1] - 1 if (i-1 not in real_sum_indices): real_sum_indices.append(i-1) if (2 == responses_diff[i]): guess[i] = 1 noise[i] = 1 real_sums[i] = responses[i] - 1 if (i not in real_sum_indices): real_sum_indices.append(i) if (i >= 1): noise[i-1] = 0 real_sums[i-1] = responses[i-1] if (i-1 not in real_sum_indices): real_sum_indices.append(i-1) # separate case for x_0 if ((noise[0] == 0) | (noise[0] == 1)): guess[0] = responses[0] - noise[0] real_sums[0] = responses[0] - noise[0] if 0 not in real_sum_indices: real_sum_indices.append(0) for i in real_sum_indices: for j in real_sum_indices: if real_sums[i] - real_sums[j] == i - j: # all the x's in between are 1 with noise 0 for k in range(j+1, i): guess[k] = 1 noise[k] = 0 if (k not in real_sum_indices): real_sum_indices.append(k) real_sums[k] = responses[k] if real_sums[i] - real_sums[j] == 0: # all the x's in between are 0 with noise 0 for k in range(j+1, i): guess[k] = 0 noise[k] = 0 if (k not in real_sum_indices): real_sum_indices.append(k) real_sums[k] = responses[k] # run the old attack for the indices we've yet to deduce. # these will (independently) be correct w.p. 3/4 for i in range(len(guess)): if (guess[i] == -1): if (0 == responses_diff[i]): guess[i] = 0 if (1 == responses_diff[i]): guess[i] = 1 return guess def recon_attack(responses): ''' this function runs the attack using responses input only ''' recon = guess_data2(responses) return recon def percent_correct(guess, true): ''' this function returns the percentage of correct bits in the reconstruction attack. ''' diff = abs(guess - true) return (len(guess) - sum(diff))/len(diff) def simulate(length, num_iters): ''' this runs num_iters number of independent simulations on databases of length length. It keeps track of the accuracy, mean, and standard deviation ''' accuracy = np.zeros((num_iters,), dtype=float) for i in range(num_iters): data = generate_data(length) noise = generate_noise(length) queries = generate_queries(data, noise) recon = recon_attack(queries) accuracy[i] = percent_correct(data, recon) mean = np.mean(accuracy) std = np.std(accuracy) print("mean :", mean) print("std :", std) return (accuracy, mean, std) def plot_data(accuracy, mean, std, length, num_iters): ''' creates a histogram of the accuracies with the mean and standard deviation labeled. ''' plt.title("Accuracy histogram for reconstruction attack \n n = " + str(length) + " Iterations = " + str(num_iters)) plt.hist(accuracy) plt.axvline(x=0.75, color="red", label="0.75 accuracy basic attack") plt.axvline(x = mean, color="green", label="non-basic attack accuracy: "+ str(round(mean, 4)) + u"\u00B1" + str(round(std, 4))) plt.xlabel("Accuracy") plt.ylabel("Frequency") plt.legend() plt.show() data_size = 50000 num_iters = 20 simulation =simulate(data_size, num_iters) plot_data(simulation[0], simulation[1], simulation[2], data_size, num_iters)
63e5b343f49cbe174dfc3f9e1d35722aeb7739c8
yeasellllllllll/bioinfo-lecture-2021-07
/0708_theragenbio/bioinformatics_4_4.py
1,791
3.734375
4
#! /usr/bin/env python # Op1) Read a FASTA format DNA sequence file # and make a reverse sequence file. # Op2) Read a FASTA format DNA sequence file # and make a reverse complement sequence file. # Op3) Convert GenBank format file to FASTA format file. a = "sequence.nucleotide.fasta" # Op1) Read a FASTA format DNA sequence file # and make a reverse sequence file. with open(a, "r") as handle1: title = "" seq_list = [] for line in handle1.readlines(): line = line.strip() if line == "": continue elif line.startswith(">") != True: seq_list.append(line) else: title = line seq = "".join(seq_list) r_seq = seq[::-1] rr_seq = f"{title}\n {r_seq}" with open("r_sequence.nucleotide.fasta", "w") as handle2: handle2.write(rr_seq) # Op2) Read a FASTA format DNA sequence file # and make a reverse complement sequence file. with open("r_sequence.nucleotide.fasta", "r") as handle3: title = "" seq_list = [] cseq_list = [] d_seq = {"A": "T", "T": "A", "G": "C", "C": "G"} for line in handle3.readlines(): line = line.strip() if line == "": continue elif line.startswith(">") != True: seq_list.append(line) else: title = line seq = "".join(seq_list) for i in seq: cseq_list.append(d_seq[i]) rc_seq = "".join(cseq_list) rrc_seq = f"{title}\n {rc_seq}" with open("rc_sequence.nucleotide.fasta", "w") as handle4: handle4.write(rrc_seq) # Op3) Convert GenBank format file to FASTA format file. b = "sequence.nucleotide.gb" with open(b, "r") as handle5: lines = handle5.readlines() with open("new.sequence.nucleotide.fasta", "w") as handle6: for line in lines: handle6.write(line)
c7a501881504bebcd33e345a031495ac183e160c
YeeyingTan/Workspace
/rtest.py
546
3.640625
4
def check_productID(isbn): remainingDigits = isbn[3:] #print(remainingDigits) assert len(remainingDigits) == 9 sum = 0 for i in range(len(remainingDigits)): number = int(remainingDigits[i]) value = i + 1 sum += value * number #print(sum) result = sum % 11 #print(result) #print(value) if result == 10: print(str(remainingDigits)+'X') else: print(str(remainingDigits)+str(result)) isbn = input("ISBN : ") check_productID(isbn)
1f3c72902e27a7bc81fb367823f78941836cbfa9
naivor/PythonPractice
/ifelse.py
137
4.09375
4
#!/usr/bin/env python3 age=3 if age>=18: print('your age is',age) print('adult') else: print('your age is',age) print('teenager')
cfb0a1e40fa0c15c1001bb54f781bbb547f62aa4
tohkyr/daily-practice
/Python/Day 1/program2.py
484
4.125
4
while True: try: a = int(input("Enter a number for variable A: ")) b = int(input("Enter a number for variable B: ")) except ValueError: print("The value you entered is not valid, please enter a number.") continue else: break def compare(x, y): if x < y: print("A is smaller than B") if x > y: print("A is bigger than B") if x == y: print("A is equal to B") compare(a, b)
08d700d8ca20ad4ecbc328295e5bc1d27d92d2d5
kelva99/sudoku_solver
/code/generate.py
4,622
3.90625
4
# reference Creating a Sudoku Puzzle in https://www.sudokuwiki.org/Sudoku_Creation_and_Grading.pdf import random from validate import validate from Solver import Sudoku_Solver, Sudoku_Solver_1 class Level(object): EASY = 0 # 35-40 MIDDLE = 1 # 30-36 HARD = 2 # 25-33 EXPERT = 3 # 20-28 class Generator(object): def __init__(self): self.lst_test = list(list(range(1, 10))) self.len_lst = len(self.lst_test) # data of popping numbers from complete board self.NUM_TO_POP = [(41, 46),(45,51),(48,56),(53,61)] self.MAX_NUM_PER_LINE = [6, 5, 4, 3] def index_of_not_filled(self, lst): out = [] for i in range(self.len_lst): if lst[i] == 0: out.append(i) return out def check_row_col(self, g, row, col, candidate): for i in range(self.len_lst): if g[row][i] == candidate or g[i][col] == candidate: return False return True def check_box(self, g, row, col, candidate): row_start = row // 3 * 3 col_start = col // 3 * 3 for r in range(row_start, row_start + 3): for c in range(col_start, col_start + 3): if g[r][c] == candidate: return False return True def pretty_print_wrap(self, g, pretty_print=True): out = "" for r in g: out += ''.join(list(map(str, r))) if pretty_print: Sudoku_Solver.pretty_print(out) return out def remove_node(self, g): mini, maxi = self.NUM_TO_POP[self.level] iteration = random.randint(mini, maxi) print(iteration) def count(r, c): counter = 0 for i in range(9): if g[r*9 + i] != '0': counter += 1 if g[i*9 + c] != '0': counter += 1 return counter lst_all_pos = list(range(81)) for i in range(iteration): whichbox = i%9 num = -1 if (i//9)* 9 + 9 >= iteration: # make last few bits random num = random.sample(lst_all_pos, 1)[0] else: min_pair = [] min_sum = -1 r0 = whichbox // 3 * 3 c0 = whichbox % 3 * 3 for r in range(r0, r0 + 3): for c in range(c0, c0 + 3): if g[r*9+c]=='0': continue res = count(r, c) if (res < min_sum): continue elif res == min_sum: min_pair.append((r, c)) else: # res < min_sum min_pair = [(r, c)] min_sum = res r, c = random.sample(min_pair, 1)[0] num = r*9 + c g = g[:num] + "0" + g[num+1:] lst_all_pos.remove(num) self.pretty_print_wrap(g) # generate full valid board def generate(self, level, outfile=None): out = [] self.level = level # ten tries for attempt in range(10): g = [] # init grid for i in range(self.len_lst): g.append([]) for j in range(self.len_lst): g[i].append(0) fail = False for r in range(3): num_rand = random.sample(self.lst_test, self.len_lst) for c in range(self.len_lst): for num in num_rand: if self.check_row_col(g, r, c, num) and self.check_box(g, r, c, num): g[r][c] = num num_rand.remove(num) break if 0 in g[r]: fail = True break if not fail: out = g break if out == []: print("Cannot generate base board") return [] for c in range(3): rand_order = random.sample(list(range(3)), 2) rand_dest = random.sample(list(range(1, 3)), 2) for r in range(2): which_col = rand_order[r] + 3 * c dest_row = rand_dest[r] * 3 out[dest_row][which_col] = out[0][which_col] out[dest_row + 1][which_col] = out[1][which_col] out[dest_row + 2][which_col] = out[2][which_col] out[0][which_col] = 0 out[1][which_col] = 0 out[2][which_col] = 0 str_incomplete_board = self.pretty_print_wrap(out, pretty_print=False) lst_baords = Sudoku_Solver_1().solve(str_incomplete_board, silent=True) is_good_result = False # randomly pop one candidate_idx = random.randint(0, len(lst_baords) - 1) candidate = lst_baords.pop(candidate_idx) while (not is_good_result) and lst_baords != []: invalid_board, err_posn = validate(lst_inputboard=lst_baords) if invalid_board == "" and err_posn == []: is_good_result = True break candidate_idx = random.randint(0, len(lst_baords)) candidate = lst_baords.pop(candidate_idx) if not is_good_result: print("Failed to fill the board") return [] # a valid board is obtained by now # self.pretty_print_wrap(candidate) board_to_play = self.remove_node(candidate) if outfile != None: f = open("../test/"+outfile + "_soln.txt",'w') f.write(candidate) f.close() f = open("../test/"+outfile + ".txt",'w') f.write(board_to_play) f.close() return board_to_play if __name__ == '__main__': g = Generator() grid = g.generate(Level.EXPERT)
04e9e4fb09c851d37c5d660d0a16562f04a87549
jrussell416/Rock-Paper-Scissors
/game.py
1,330
4.59375
5
#importing random module for ability to randomize computer's choice import random winner = "" #How a "random" choice is selected randomChoice = random.randint(0,2) #Assigning the numbers from the random choice into a string so it can be used for a comparison to the user's choice if randomChoice == 0: computerChoice = "Rock" elif randomChoice == 1: computerChoice = "Paper" else: computerChoice = "Scissors" #Prompt to get the user's choice to eventually compare to the computer's choice userChoice = "" while (userChoice != "Rock" and userChoice != "Paper" and userChoice != "Scissors"): userChoice = input("Rock, Paper or Scissors") #Comparison and evalution of choices to determine whether the computer wins or the game ends in a tie if computerChoice == userChoice: winner="Tie" elif computerChoice == "Paper" and userChoice == "Rock": winner="Computer" elif computerChoice == "Rock" and userChoice == "Scissors": winner="Computer" elif computerChoice == "Scissors" and userChoice == "Rock": winner="Computer" else: winner="User" if winner == "Tie": print("We both chose", computerChoice + ", play again.") else: print(winner, "won. The computer chose", computerChoice + ".") #Closing satement declaring the winner (or tie) along with the computer's choice
09528b41d584e20bf47d2f48595367e08743d41f
yusheng88/RookieInstance
/Rookie073.py
1,370
4.1875
4
# -*- coding = utf-8 -*- # @Time : 2020/8/16 21:21 # @Author : EmperorHons # @File : Rookie073.py # @Software : PyCharm """ https://www.runoob.com/python3/python-heap-sort.html Python 堆排序 堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。 堆积是一个近似完全二叉树的结构, 并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。 堆排序可以说是一种利用堆的概念来排序的选择排序。 """ import pysnooper @pysnooper.snoop() def heapify(arr, n, i): largest = i l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 if l < n and arr[i] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest) @pysnooper.snoop() def heapSort(arr): n = len(arr) # Build a maxheap. for i in range(n, -1, -1): heapify(arr, n, i) # 一个个交换元素 for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # 交换 heapify(arr, i, 0) def main(): arr = [12, 11, 13, 5, 6, 7] heapSort(arr) n = len(arr) print("排序后") for i in range(n): print("%d" % arr[i]), if __name__ == '__main__': main()
c41d7a60fca8f163e5eb49142dbe79045e17fdd2
lkhphuc/HugoLarochelle_NN_Exercises
/Restricted Boltzmann Machine/nnet.py
16,610
3.71875
4
from mlpython.learners.generic import Learner import numpy as np class NeuralNetwork(Learner): """ Neural network for classification. Option ``lr`` is the learning rate. Option ``dc`` is the decrease constante for the learning rate. Option ``sizes`` is the list of hidden layer sizes. Option ``L2`` is the L2 regularization weight (weight decay). Option ``L1`` is the L1 regularization weight (weight decay). Option ``seed`` is the seed of the random number generator. Option ``tanh`` is a boolean indicating whether to use the hyperbolic tangent activation function (True) instead of the sigmoid activation function (True). Option ``parameter_initialization`` is a pair of lists, giving the initializations for the biases (first list) and the weight matrices (second list). If ``None``, then a random initialization is used. Option ``n_epochs`` number of training epochs. **Required metadata:** * ``'input_size'``: Size of the input. * ``'targets'``: Set of possible targets. """ def __init__(self, lr=0.001, dc=0, sizes=[200,100,50], L2=0, L1=0, seed=1234, tanh=False, parameter_initialization=None, n_epochs=10): self.lr=lr self.dc=dc self.sizes=sizes self.L2=L2 self.L1=L1 self.seed=seed self.tanh=tanh self.parameter_initialization = parameter_initialization self.n_epochs=n_epochs # internal variable keeping track of the number of training iterations since initialization self.epoch = 0 def initialize(self,input_size,n_classes): """ This method allocates memory for the fprop/bprop computations (DONE) and initializes the parameters of the neural network (TODO) """ self.n_classes = n_classes self.input_size = input_size n_hidden_layers = len(self.sizes) ############################################################################# # Allocate space for the hidden and output layers, as well as the gradients # ############################################################################# self.hs = [] self.grad_hs = [] for h in range(n_hidden_layers): self.hs += [np.zeros((self.sizes[h],))] # hidden layer self.grad_hs += [np.zeros((self.sizes[h],))] # ... and gradient self.hs += [np.zeros((self.n_classes,))] # output layer self.grad_hs += [np.zeros((self.n_classes,))] # ... and gradient ################################################################## # Allocate space for the neural network parameters and gradients # ################################################################## self.weights = [np.zeros((self.input_size,self.sizes[0]))] # input to 1st hidden layer weights self.grad_weights = [np.zeros((self.input_size,self.sizes[0]))] # ... and gradient self.biases = [np.zeros((self.sizes[0]))] # 1st hidden layer biases self.grad_biases = [np.zeros((self.sizes[0]))] # ... and gradient for h in range(1,n_hidden_layers): self.weights += [np.zeros((self.sizes[h-1],self.sizes[h]))] # h-1 to h hidden layer weights self.grad_weights += [np.zeros((self.sizes[h-1],self.sizes[h]))] # ... and gradient self.biases += [np.zeros((self.sizes[h]))] # hth hidden layer biases self.grad_biases += [np.zeros((self.sizes[h]))] # ... and gradient self.weights += [np.zeros((self.sizes[-1],self.n_classes))] # last hidden to output layer weights self.grad_weights += [np.zeros((self.sizes[-1],self.n_classes))] # ... and gradient self.biases += [np.zeros((self.n_classes))] # output layer biases self.grad_biases += [np.zeros((self.n_classes))] # ... and gradient ######################### # Initialize parameters # ######################### self.rng = np.random.mtrand.RandomState(self.seed) # create random number generator if self.parameter_initialization is not None: self.biases = [ b.copy() for b in self.parameter_initialization[0] ] self.weights = [ w.copy() for w in self.parameter_initialization[1] ] if len(self.biases) != n_hidden_layers + 1: raise ValueError("Biases provided for initialization are not compatible") for i,b in enumerate(self.biases): if i == n_hidden_layers and len(b.shape) == 1 and b.shape[0] != self.n_classes: raise ValueError("Biases provided for initialization are not of the expected size") if i < n_hidden_layers and len(b.shape) == 1 and b.shape[0] != self.sizes[i]: raise ValueError("Biases provided for initialization are not of the expected size") if len(self.weights) != n_hidden_layers+1: raise ValueError("Weights provided for initialization are not compatible") for i,w in enumerate(self.weights): if i == n_hidden_layers and len(w.shape) == 2 and w.shape != (self.sizes[-1],self.n_classes): raise ValueError("Weights provided for initialization are not of the expected size") if i == 0 and len(w.shape) == 2 and w.shape != (self.input_size,self.sizes[i]): raise ValueError("Weights provided for initialization are not of the expected size") if i < n_hidden_layers and i > 0 and len(w.shape) == 2 and w.shape != (self.sizes[i-1],self.sizes[i]): raise ValueError("Weights provided for initialization are not of the expected size") else: self.weights = [(2*self.rng.rand(self.input_size,self.sizes[0])-1)/self.input_size] # input to 1st hidden layer weights for h in range(1,n_hidden_layers): self.weights += [(2*self.rng.rand(self.sizes[h-1],self.sizes[h])-1)/self.sizes[h-1]] # h-1 to h hidden layer weights self.weights += [(2*self.rng.rand(self.sizes[-1],self.n_classes)-1)/self.sizes[-1]] # last hidden to output layer weights self.n_updates = 0 # To keep track of the number of updates, to decrease the learning rate def forget(self): """ Resets the neural network to its original state (DONE) """ self.initialize(self.input_size,self.targets) self.epoch = 0 def train(self,trainset): """ Trains the neural network until it reaches a total number of training epochs of ``self.n_epochs`` since it was initialize. (DONE) Field ``self.epoch`` keeps track of the number of training epochs since initialization, so training continues until ``self.epoch == self.n_epochs``. If ``self.epoch == 0``, first initialize the model. """ if self.epoch == 0: input_size = trainset.metadata['input_size'] n_classes = len(trainset.metadata['targets']) self.initialize(input_size,n_classes) for it in range(self.epoch,self.n_epochs): for input,target in trainset: self.fprop(input,target) self.bprop(input,target) self.update() self.epoch = self.n_epochs def fprop(self,input,target): """ Forward propagation: - fills the hidden layers and output layer in self.hs - returns the training loss, i.e. the regularized negative log-likelihood for this (input,target) pair Argument ``input`` is a Numpy 1D array and ``target`` is an integer between 0 and nb. of classe - 1. """ if self.tanh: def compute_h(input,weights,bias): exptwoact = np.exp(-2*(bias+np.dot(input,weights))) return (1-exptwoact)/(exptwoact+1) else: def compute_h(input,weights,bias): act = bias+np.dot(input,weights) return 1./(1+np.exp(-act)) self.hs[0][:] = compute_h(input,self.weights[0],self.biases[0]) for h in range(1,len(self.weights)-1): self.hs[h][:] = compute_h(self.hs[h-1],self.weights[h],self.biases[h]) def softmax(act): act = act-act.max() expact = np.exp(act) return expact/expact.sum() self.hs[-1][:] = softmax(self.biases[-1]+np.dot(self.hs[-2],self.weights[-1])) return self.training_loss(self.hs[-1],target) def training_loss(self,output,target): """ Computation of the loss: - returns the regularized negative log-likelihood loss associated with the given output vector (probabilities of each class) and target (class ID) """ l = -np.log(output[target]) if self.L2 != 0: for h in range(len(self.weights)): l += self.L2*(self.weights[h]**2).sum() if self.L1 != 0: for h in range(len(self.weights)): l += self.L1*(np.abs(self.weights[h])).sum() return l def bprop(self,input,target): """ Backpropagation: - fills in the hidden layers and output layer gradients in self.grad_hs - fills in the neural network gradients of weights and biases in self.grad_weights and self.grad_biases - returns nothing Argument ``input`` is a Numpy 1D array and ``target`` is an integer between 0 and nb. of classe - 1. """ if self.tanh: def compute_grad_h(input,weights,bias,h,grad_weights,grad_bias,grad_h): grad_act = (1-h**2) * grad_h grad_weights[:,:] = np.outer(input,grad_act) grad_bias[:] = grad_act return np.dot(grad_act,weights.T) else: def compute_grad_h(input,weights,bias,h,grad_weights,grad_bias,grad_h): grad_act = h*(1-h)*grad_h grad_weights[:,:] = np.outer(input,grad_act) grad_bias[:] = grad_act return np.dot(grad_act,weights.T) # Output layer gradients self.grad_hs[-1][:] = self.hs[-1] self.grad_hs[-1][target] -= 1 self.grad_weights[-1][:,:] = np.outer(self.hs[-2],self.grad_hs[-1]) self.grad_biases[-1][:] = self.grad_hs[-1] self.grad_hs[-2][:] = np.dot(self.grad_hs[-1],self.weights[-1].T) # Hidden layer gradients for h in range(len(self.weights)-2,0,-1): self.grad_hs[h-1][:] = compute_grad_h(self.hs[h-1],self.weights[h],self.biases[h], self.hs[h],self.grad_weights[h],self.grad_biases[h], self.grad_hs[h]) compute_grad_h(input,self.weights[0],self.biases[0], self.hs[0],self.grad_weights[0],self.grad_biases[0],self.grad_hs[0]) # Add regularization gradients for h in range(len(self.weights)): if self.L2 != 0: self.grad_weights[h] += 2*self.L2*self.weights[h] if self.L1 != 0: self.grad_weights[h] += self.L1*np.sign(self.weights[h]) def update(self): """ Stochastic gradient update: - performs a gradient step update of the neural network parameters self.weights and self.biases, using the gradients in self.grad_weights and self.grad_biases """ for h in range(len(self.weights)): self.weights[h] -= self.lr /(1.+self.n_updates*self.dc) * self.grad_weights[h] self.biases[h] -= self.lr /(1.+self.n_updates*self.dc) * self.grad_biases[h] self.n_updates += 1 def use(self,dataset): """ Computes and returns the outputs of the Learner for ``dataset``: - the outputs should be a Numpy 2D array of size len(dataset) by (nb of classes + 1) - the ith row of the array contains the outputs for the ith example - the outputs for each example should contain the predicted class (first element) and the output probabilities for each class (following elements) """ outputs = np.zeros((len(dataset),self.n_classes+1)) t=0 for input,target in dataset: self.fprop(input,target) outputs[t,0] = self.hs[-1].argmax() outputs[t,1:] = self.hs[-1] t+=1 return outputs def test(self,dataset): """ Computes and returns the outputs of the Learner as well as the errors of those outputs for ``dataset``: - the errors should be a Numpy 2D array of size len(dataset) by 2 - the ith row of the array contains the errors for the ith example - the errors for each example should contain the 0/1 classification error (first element) and the regularized negative log-likelihood (second element) """ outputs = self.use(dataset) errors = np.zeros((len(dataset),2)) t=0 for input,target in dataset: output = outputs[t,:] errors[t,0] = output[0] != target errors[t,1] = self.training_loss(output[1:],target) t+=1 return outputs, errors def verify_gradients(self): """ Verifies the implementation of the fprop and bprop methods using a comparison with a finite difference approximation of the gradients. """ print 'WARNING: calling verify_gradients reinitializes the learner' rng = np.random.mtrand.RandomState(1234) self.seed = 1234 self.sizes = [4,5] self.initialize(20,3) example = (rng.rand(20)<0.5,2) input,target = example epsilon=1e-6 self.lr = 0.1 self.decrease_constant = 0 self.fprop(input,target) self.bprop(input,target) # compute gradients import copy emp_grad_weights = copy.deepcopy(self.weights) for h in range(len(self.weights)): for i in range(self.weights[h].shape[0]): for j in range(self.weights[h].shape[1]): self.weights[h][i,j] += epsilon a = self.fprop(input,target) self.weights[h][i,j] -= epsilon self.weights[h][i,j] -= epsilon b = self.fprop(input,target) self.weights[h][i,j] += epsilon emp_grad_weights[h][i,j] = (a-b)/(2.*epsilon) print 'grad_weights[0] diff.:',np.sum(np.abs(self.grad_weights[0].ravel()-emp_grad_weights[0].ravel()))/self.weights[0].ravel().shape[0] print 'grad_weights[1] diff.:',np.sum(np.abs(self.grad_weights[1].ravel()-emp_grad_weights[1].ravel()))/self.weights[1].ravel().shape[0] print 'grad_weights[2] diff.:',np.sum(np.abs(self.grad_weights[2].ravel()-emp_grad_weights[2].ravel()))/self.weights[2].ravel().shape[0] emp_grad_biases = copy.deepcopy(self.biases) for h in range(len(self.biases)): for i in range(self.biases[h].shape[0]): self.biases[h][i] += epsilon a = self.fprop(input,target) self.biases[h][i] -= epsilon self.biases[h][i] -= epsilon b = self.fprop(input,target) self.biases[h][i] += epsilon emp_grad_biases[h][i] = (a-b)/(2.*epsilon) print 'grad_biases[0] diff.:',np.sum(np.abs(self.grad_biases[0].ravel()-emp_grad_biases[0].ravel()))/self.biases[0].ravel().shape[0] print 'grad_biases[1] diff.:',np.sum(np.abs(self.grad_biases[1].ravel()-emp_grad_biases[1].ravel()))/self.biases[1].ravel().shape[0] print 'grad_biases[2] diff.:',np.sum(np.abs(self.grad_biases[2].ravel()-emp_grad_biases[2].ravel()))/self.biases[2].ravel().shape[0]
f5a36c40c96e7060925076784fddea7763508056
ursulenkoirina/courses
/homework3/issue3_3.py
211
3.78125
4
# 3.1 a = 0 while a <= 10: print(a) a += 1 # 3.2 a = 20 while a >= 1: print(a, end=' ') a -= 1 # 3.3 a = 1024 i = 0 while a%2 == 0: a = a//2 i += 1 print('\nNumber of divisions: ', i)
3b8b712736790baacbc46b1ecadd27993df6939f
mohsinz99/Password_Generator
/userInterface.py
1,849
3.796875
4
import tkinter from tkinter import * from algorithms import algorithms class user_interface: def __init__(self, master): frame = Frame(master) frame.pack() self.labelUpper = Label(frame, text = "How many uppercase letters:") self.labelUpper.grid(row = 0, column = 0, padx = 20, pady = 20) self.entUpper = Entry(frame, width = 22) self.entUpper.grid(row = 0, column = 1, padx = 20, pady = 20, sticky = W) self.labelMid = Label(frame, text = "How many lowercase letters:") self.labelMid.grid(row = 1, column = 0, padx = 20, pady = 20, sticky = W) self.entMid = Entry(frame, width = 22) self.entMid.grid(row = 1, column = 1, padx = 20, pady = 20, sticky = W) self.labelThird = Label(frame, text = "How many digits:") self.labelThird.grid(row = 2, column = 0, padx = 20, pady = 20, sticky = W) self.entThird = Entry(frame, width = 22) self.entThird.grid(row = 2, column = 1, padx = 20, pady = 20, sticky = W) self.labelBot = Label(frame, text = "How many special characters:") self.labelBot.grid(row = 3, column = 0, padx = 20, pady = 20, sticky = W) self.entBot = Entry(frame, width = 22) self.entBot.grid(row = 3, column = 1, padx = 20, pady = 20, sticky = W) self.buttonExecute = Button(frame, text = 'Generate Password', command = self.getAnswers) self.buttonExecute.grid(row = 4, column = 0, padx = 5, pady = 18, sticky = W) self.entPas = Entry(frame, width = 22) self.entPas.grid(row = 4, column = 1, padx = 20, pady = 20, sticky = W) def getAnswers(self): arr = [] arr.append(self.entUpper.get()) arr.append(self.entMid.get()) arr.append(self.entThird.get()) arr.append(self.entBot.get()) algorithm = algorithms(arr) password = algorithm.randoms() self.entPas.delete(0, END) self.entPas.insert(0, password)
2f5b25b48921e2b131fd2fdc88f1a7b4a724f2c6
dudrill/Coursera_ML
/1 неделя/task11.py
400
3.59375
4
import pandas import re from scipy import stats df = pandas.read_csv("C:\Users\Adele\Desktop\\titanic.csv") # 1. Какое количество мужчин и женщин ехало на корабле? В качестве # ответа приведите два числа через пробел. male = df[df['Sex'] == 'male'] female = df[df['Sex'] == 'female'] print(len(male), len(female))
5a57de98f121623b6e0937ee4a2cb7939c98d0b1
marcelovca90-inatel/C210
/search-puzzle-python/algorithms/greedy_search.py
3,514
4.25
4
import heapq class GreedySearch(object): ''' This class implements the greedy search algorithm. ''' def __init__(self, problem): ''' Constructor Any instance of this class must receive a ``problem`` parameter that is responsible for controlling the problem evaluation and the next possible states. This parameter have two mandatory functions: - ExpandState(current): a function that returns all possible states from a given ``current`` state. - EqualityTest(current,target): a function that evaluates if a given ``current`` state corresponds to the ``target`` state, i.e., it compares the states. ''' self.problem = problem def __isNotIn(self, current_state, visited_states): ''' This method is responsible for checking if a ``current_state`` was already visited during search. If true, it is necessary to compare ``current_state`` to all states in ``visited_states`` list, one by one. In order to compare, the user must provide the ``EqualityTest`` function inside problem object. ''' Test = True for state in visited_states: # if state is already in visited_states, return False if self.problem.EqualityTest(state,current_state) == True: Test = False break return Test def search(self, start, target): ''' This method performs the greedy search, where the order of the visited states is controlled by a priority queue data structure. The priority of an element is given by its heuristic cost. ''' # create an empty priority queue frontier = [] # insert ``start`` state in the priority queue heapq.heappush(frontier, (0,0,start)) # initialize control variables state_id = 0 solution_found = False visited_states = [] visit_count = 0 # repeat while there are states eligible to be visited while not len(frontier) == 0: # take the first candidate state current = heapq.heappop(frontier)[2] visited_states.append(current) # evaluate is the current state matches the objective if self.problem.EqualityTest(current,target) == True: # if true, then the search is over solution_found = True break else: visit_count += 1 print("Visit # %d" % visit_count) # compute the new possible states given the current state new_states = self.problem.ExpandState(current) # iterate over the new states for state in new_states: # check if each new state was already visited if self.__isNotIn(state, visited_states) == True: # if not, evaluate the associated heuristic state_id += 1 priority = self.problem.HeuristicCost(state,target) print("%s" % state) print("h = %d" % priority) # and add it to the priority queue for evaluation heapq.heappush(frontier,(priority,state_id,state)) return solution_found,visited_states,visit_count
2a7effa0f6e9bc9551bfa017bb3ef99f42e7a70a
ruchi2ch/Python-Programming-Assignment
/week 3/3.4.py
1,570
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 11 12:18:24 2020 7/17/2016 @author: HP FOLIO 9480M """ '''Problem 3_4: Write a function that is complementary to the one in the previous problem that will convert a date such as June 17, 2016 into the format 6/17/2016. ''' def problem3_4(mon, day, year): months = {"January":1,"February":2,"March":3,"April":4,"May":5,"June":6,"July":7,"August":8,"Septemper":9,"October":10,"November":11,"December":12} #for x in months: if mon=="January": print(str(months["January"])+'/'+str(day)+'/'+str(year)) elif mon=="February": print(str(months["February"])+'/'+str(day)+'/'+str(year)) elif mon=="March": print(str(months["March"])+'/'+str(day)+'/'+str(year)) elif mon=="April": print(str(months["April"])+'/'+str(day)+'/'+str(year)) elif mon=="May": print(str(months["May"])+'/'+str(day)+'/'+str(year)) elif mon=="June": print(str(months["June"])+'/'+str(day)+'/'+str(year)) elif mon=="July": print(str(months["July"])+'/'+str(day)+'/'+str(year)) elif mon=="August": print(str(months["August"])+'/'+str(day)+'/'+str(year)) elif mon=="September": print(str(months["September"])+'/'+str(day)+'/'+str(year)) elif mon=="October": print(str(months["October"])+'/'+str(day)+'/'+str(year)) elif mon=="November": print(str(months["November"])+'/'+str(day)+'/'+str(year)) elif mon=="December": print(str(months["December"])+'/'+str(day)+'/'+str(year))
8115ebe869bb82ec14aa65892d8e70894297504c
weguri/python
/oop/curso_2/Polimorfismo/audiofile.py
664
3.640625
4
class AudioFile: def __init__(self, filename): if not filename.endswith(self.ext): raise Exception('Formato invalido') self.filename = filename class MP3File(AudioFile): ext = 'mp3' def play(self): print('Tocando arquivo MP3') class WavFile(AudioFile): ext = 'wav' def play(self): print('Tocando arquivo WAV') class OggFile(AudioFile): ext = 'ogg' def play(self): print('Tocando arquivo Ogg') try: """ Validação da extensão do arquivo é feito na Classe AudioFile """ mp3 = MP3File('musica.mp3') mp3.play() except Exception as err: print(err)
a20eb4910dd9a7478a5d30647b82826e647afdff
marshall1996/-Python-for-Beginners-Giraffe-Course
/For loops.py
389
4.03125
4
for letter in "Giraffe Academy": print(letter) friends = ["May", "Minnie", "Marshall"] for friend in friends: print(friend) for index_of_list in range(len(friends)): print(friends[index_of_list]) for index in range(3, 10): print(index) for i in range (5): if i == 0: print("First iteration") else: print("Not first iteration")
3e40d70060e2ad8d4b829db6d30b80a79ff6f998
brrcrites/PySchool
/56_dictionary.py
74
3.828125
4
numbers = {1: "one", 2: "two", 3: "three"} for x in numbers: print(x)
74cf7ac6bb03854966d18c70471e3bf4d01962c3
acse-jt321/modern-programming-methods
/lectures/lecture04/tests/unittest_example.py
821
3.5
4
import unittest import foo def expensive_function(): """Pretend this uses a lot of resources.""" return (1, 0, -1) def make_safe(val): """This might clean up memory or free up resources""" pass class TestSolveQuadratic(unittest.TestCase): def setUp(self): """Runs first.""" # Can create values stored in the class instance self self.val = expensive_function() def test_solve_quadratic_part_one(self): self.assertEqual(foo.solve_quadratic(*self.val), (-1.0, 1.0)) self.assertEqual(foo.solve_quadratic(1, 0, 0), 0.0) def test_solve_quadratic_part_two(self): self.assertEqual(foo.solve_quadratic(1, 0, 1), None) def tearDown(self): """Called at the end if we need to clean up.""" make_safe(self.val) unittest.main()
f01385b155b89ff04d71f8fb290bfe295d754d16
kapil23vt/Python-Codes-for-Software-Engineering-Roles
/unique characters in string.py
297
3.515625
4
def unique(s): d = dict() for i in range(len(s)): d[s[i]] = 0 for i in range(len(s)): d[s[i]] += 1 print(d) if (len(s) == len(d)): return True else: return False s = 'xyzw' #prints False print(unique(s))
552b859596cd8e05861b632ef16de633477a30f5
Jeetendranani/yaamnotes
/os/introduction.py
52,709
3.796875
4
""" 1. Introduction A modern computer consists of one or more processors, some main memory, disk, printers, a keyboard, a mouse, a display, network interfaces, and various other input/output devices. All n all, a complex system.oo if every application programmer had to understand how all these things work in detail, no code would ever get written. Furthermore, managing all these components and using them optimally is an exceedingly challenging job. For this reason, computers are equipped with a layer of software called the operating system, whose job is to provide user programs with a better, simpler, cleaner, model of the computer and to handle managing all the resources just mentioned. Operating systems are the subject of this book. Most readers will have had some experience with an operating system such as Windows, Linux, FreeBSD, or OSX, but appearances can e deceiving. The program that users interact with, usually called the shell when it is text based and the GUI (Graphical User Interface) - which is pronounced "gooey" - when it uses icons, is actually not part of the operating system, although it uses the operating system to get its work done. A simple overview of the main components under discussion here is given in Fig 1-1. Here we see the hardware at the bottom. The hardware consists of chips, boards, disks, a keyboard, a monitor, and similar physical objects. On top of the hardware is the software. most computers have two modes of operation: kernel mode and user mode. The operating system, the most fundamental piece of software, runs in kernel mode (also called supervisor mode). In this mode it has complete access to all the hardware and can execute any instruction the machine is capable to executing. The rest of the software runs in user mode, in which only a subset of teh machine instructions is available. In particular, those instructions that affect control of the machine or do i/o "input/output" are forbidden to user-mode programs. We will come back to the difference between kernel mode and user mode repeatedly throughout this book. It plays a crucial role in how operating systems work. This user interface program, shell or GUI, is hte lowest level of user-mode software, and allows the user to start other programs, such as a web browser, email reader, or music player. These programs, too, make heavy use of the operating system. The placement of the operating system is shown in Fig 1-1. It runs on the bare hardware and provides the base for all the other software. An important distinction between the operating system and normal (user mode) software is that if a user does not like a particular email reader, here is free to get a different one or write his own if he so chooses; he is not free to write his own clock interrupt handler, which is part of the operating system and it protected by hardware against attempts by users to modify it. This distinction, however, is sometimes blurred in embedded systems (which may not have kernel mode) or interpreted systems (such as Java-based systems that use interpretation, not hardware, to separate the components). Also, in many systems there are programs that run in user mode but help the operating system or perform privileged functions. For example, there is often a program that allows users to change their passwords. It is not part of the operating system and does not run in kernel mode, but it clearly carries out a sensitive function and has to be protected in a special way. In some systems, this idea is carried to an extreme, and pieces of what is traditionally considered to be the operating system (such as the file system) run in user space. In such systems, it is difficult to draw a clear boundary. Everything running in kernel mode is clearly part of the operating system, but some programs running outside it are arguably also part of it, or at least closely associated with it. Operating systems differ from user (i.e., application) programs in ways other than where they reside. In particular, In they are huge, complex, and long-lived. The source code of the heart of an operating system like linux or Windows is on the order of five million lines of code or more. To conceive of what this means, think of printing out five million lines in book from, with 50 lines per page and 1000 pages per volume (larger than this book). It would take 100 volumes to list an operating system of this size - essentially an entire bookcase, Can you imagine getting a job maintaining an operating system and on the first day having your boss bring you to a bookcase with the code and say: "Go learn that." And this is only for the part runs in the kernel. When essential shared libraries are included, Windows is well over 70 million lines of code or 10 or 20 bookcases. And this excludes basic application software (things like windows explore, windows media player, and so on). It should be clear now why operating systems live a long time - they are very hard to write, and having written one, the owner is loath to throw it out and start again. Instead, such system evolve over long periods of time. Windows 95/98/Me was basically one operating system and windows nt/2000/xp/vista/windows 7 is a different one. They look similar to the users because microsoft made very sure that the user interface of windows 2000/xp/vista/windows 7 was quite similar to that of the system it was replacing, mostly windows 98. nevertheless, there were very good reasons why microsoft got rid of windows 98. We will come to these when we study windows in detail in chap. 11. Besides windows, the other main example we will use throughout this book is unix and its variants and clones. It, too, has evolved over the years, with versions like system v, solaris, and freeBSD being derived from the original system, whereas Linux is a fresh code base, although very closely modeled on Unix and highly compatible with it. We will use examples from UNIX throughout this book and look at Linux in the detail in chapter 10. In this chapter we will briefly touch on a number of key aspects of operating systems, including what they are, their history, what kinds are around, some of the basic concepts, and their structure. We will come back to many of these important topics in later chapters in more detail. 1.1 What is an operating system? It is hard to pin down what an operating system is other than saying it is the software that runs in kernel mode - and even that is not always true, part of the problem is that operating system perform two essentially unrelated functions: providing application programmers (and application programs, naturally) a clean abstract set of resources. Depending on who is doing the talking, you might hear mostly about one function or other. Lets now look at both. 1.1.1 The operating system as an extended machine The architecture (instruction set, memory organization, i/o, and bus structure) of most computers at the machine language level is primitive and awkward to program, especially for input/output. To make this point more concrete, consider modern sata (serial ata) hard disks used on most computers. A book (anderson, 2007) describing an early version of the interface to the disk - what a programmer would have to know to use the disk - ran over 450 pages. Since then teh interface has been revised multiple times and its more complicated than it was in 2007. Clearly no sane programmer would want to deal with this disk at teh hardware level, instead, a piece of software, called a disk driver, deals with the hardware and the provides an interface to read and write disk blocks, without getting into the details. Operating systems contains many drivers for controlling i/o devices. but even this level is much too low for most applications. For this reason, all operating systems provide yet another layer of abstraction for using disks: files. using this abstraction, programs can create, write, and read files, without having to deal with the messy details of how the hardware actually works. This abstraction is the key to managing all this complexity. good abstractions turn a nealy impossible task into two manageable ones. The first is defining and implementing the abstractions. The second is using these abstractions to solve the problem at hand. One abstraction that almost every computer user understands is the file, as mentioned above. It is a useful piece of information, such as digital photo, saved email message, song, or web page. It is much easier to deal with photos, emails. songs, and web pages than with the detail of sata (or other) disks. The job of the operating system is to create good abstractions and then implement and mange the abstract objects thus created. This point is so important that it is worth repeating in different words. with all due respect to the industrial engineers who so carefully designed the macintosh, hardware is ugly, real processors, memories, disks, and other devices are very complicated and present difficult, awkward, idiosyncratic, and inconsistent interfaces to the people who have to write software to sue them. sometimes this is due to the need for backward compatibility with older hardware. Other times it is attempt to save money. Often, however, teh hardware designers do not realize (or care) how much trouble they are causing for the software. One of the major tasks of the operating system is to hide the hardware and present programs (and their programmers) with nice, clean, elegant, consistent, abstractions to work with instead. Operating systems turn teh ugly into the beautiful. as shown in Fig. 1-2. It should be noted that the operating system's real customers are the application programs (via the application programmers, of course). They ar the ones who deal directly with the operating system and its abstractions. In contrast, end users deal with the abstractions provided by the user interface, either a command line shell or a graphical interface. While the abstractions at the user interface may be similar to the ones provided by the operating system, this is not always the case. To make this point clearer, consider the normal windows desktop and the line-oriented command-line prompt. both are programs running on the windows operating system and use the abstractions windows provides, but they offer very different user interfaces. Similarly, a linux user running Gnome or KDE sees a very different interface than a Linux user working directly on top of the underlying X windows System, but the underlying operating system abstractions are the same in both cases. In this book, we will study the abstractions provided to application programs in great detail, but say rather little about user interfaces. That is a large and important subject, but one only peripherally related to operating systems. 1.1.2. the operating system as a resource manager the concept of an operating system as primarily providing abstractions to application programs is a top down view. An alternative bottom up, view holds that teh operating system is there to manage all teh pieces of a complex system. Modern computers consist of processors, memories timers, mice, network interfaces, printers, and wide variety of other devices. In the bottom up view, the job of the operating system is to provide for an orderly and controlled allocation of the processors, memories, and i/o devices among the various programs wanting them. Modern operating systems allow multiple programs to be in memory and run at the same time. Imagine what would happen if three programs running on the some computer all tried to print there output simultaneously on the sam printer. The first few lines of printout might be from program 1, teh next few from program 2, then some from program 3, and so forth. The result would be utter chaos. The operating system can bring order to the potential chaos by buffering all the output destined for the printer on the disk. When one program is finished, the operating system can then copy its output from the disk file where it has been stored from the printer, while at the same time the other program can continue generating more output, oblivious to the fact that the output is not really going to the printer (yet). When a computer (or network) has more than one user, the need for managing and protecting the memory, i/o devices, and other resources is even more since the user might otherwise interface with one another. In addition, users often need to share not only hardware, but information (files, databases, etc.) as well. In short, this view of the operating system holds that its primary task is to keep track of which programs are using which resource, to grant resource requests, to account for usage, and to mediate conflicting requests from different programs and users. Resource management includes multiplexing (sharing) resources in two different ways: in time and space. When a resource is time multiplexed, different programs or users take turns using it. First one of them gets to use the resource, then another, and so on. For example, with only one CPU and multiple programs that want to run on it. The operating system first allocates the CPU to one program, then after it has run long enough, another program gets to use the CPU, then another, and then eventually the first one again. Determining how the resource is time multiplexed = who goes next and for how long - is the task of the operating system. Another example of time multiplexing is share the printer. When multiple print jobs are queued up for printing on a single printer, a decision has to be made about which one is to be printed next. The other kind of multiplexing is space multiplexing. Instead of the customers taking turns, each one gets part of the resource. For example, main memory is normally divided up among several running programs, so each one can be resident at the same time (for example, in order to take turns using the CPU). Assuming there is enough memory to hold multiple programs, it is most efficient to hold several programs in memory at once rather than give on eof them all of it, especially if it only needs a small fraction fo the total. Of course, this raises issues of fairness, protection, and so on, and it is up to the operating system to solve them. Another resource that is space multiplexed is the disk. In many systems a single disk can hold files from many users at the same time. Allocating disk space and keeping track of who is using which disk blocks is a typical operating system task. 1.2 history of operating systems Operating systems have been evolving through the years. in the following sections we will briefly look at the few of the highlights. Since operating systems have historically been closely tied to the architecture of the computers on which they run, we will look at successive generations of computers to see what their operating system were like. This mapping of operating system generations to computer generations is crude, but it does provide some structure where there would otherwise be none. The progression given below is largely chronological, but it has been a bumpy ride. Each development did not wait until the previous one nicely finished before getting started. There was a lot of overlap, not to mention many false starts and dead ends. Take this as a guide, not as the last word. The first true digital computer was designed by the English mathematician Charles Babbage (1792 - 1871). Although Babbage spend most of his life and fortune trying to build his "analytical engine," he never got it working properly because it was purely mechanical, and the technology of his day could not produce the required wheels, gears, and cogs to the high precision that he needed. Needless to say, the analytical engine did not have an operating system. As an interesting historical aside, Babbage realized that he would need software for his analytical engine, so he hired a young woman named Ada Lovelace, who was the daughter of the famed British peot Lord Byron, as the world's first programmer, the programming language Ada is named after her. 1.2.1 The first generation (1945-55): Vacuum Tubes After Babbage's unsuccessful efforts, little progress was made in constructing digital computers until the word war II period, which stimulated an explosion of activity. Professor John Atanasoff and his graduate student Clifford Berry built what is now regarded as the first functioning digital computer at Iowa State University. It used 300 vacuum tubes. At roughly the same time, Konrad Zuse in Berlin built the Z3 computer out of electromechanical relays. in 1944, the Colossus was built and programmed by a group if scientists (including Alan Turing) at Bletchley Park, England, the mark I was built by Howard Aiken at Harvard, and teh ENIAC was built by William Mauchley and this graduate student J. Presper Eckert at teh University of Pennsylvania. Some were binary, some used vacuum tubes, some were programmable, but all were very primitive and took seconds to perform even the simplest calculation. In these early days, a single group of people (usually engineers) designed, built, programmed, operated, and maintained each machine. All programming was done in absolute machine language, or even worse yet, by wiring up electrical circuits by connecting thousands of cables to plug boards to control the machine's basic functions. Programming languages were unknown (even assembly language was unknown). Operating systems were unheard of. The usual mode of operation was for the programmer to sing up for a block of time using the signup sheet on the wall, then come down to the machine room, insert his or her plug board into the computer, and spend the next few hours hoping that none of 20000 or so vacuum tubes would burn out during the run. Virtually all the problems were simple straightforward mathematical and numerical calculations, such as grinding out tables sines, cosines, and logarithms, or computing artillery trajectories. By the early 1950s, the routine had improved somewhat with the introduction of punched cards. it was now possible to write programs on cards and read them in instead of using plug boards; otherwise, the procedure was the same. 1.2.2 The second generation 1955-65): Transistors and Batch Systems The introduction of the transistor in the mid-1950s changed teh picture radically. Computers became reliable enough that they could be manufactured and sold to paying customers with the expectation that they would continue to function long enough to get some useful work down. For the first time, there was a clear separation between designers, builders, operators, programmers, and maintenance personal. These machines, now called mainframes, were locked away in large, specially are-conditioned computer rooms, with staffs of professional operators to run them. Only large corporations or major government agencies or universities could afford the multi million dollar price tag. To run a job (i.e., a program or set of programs), a programmer would first write the program on paper (in Fortran or assembler), then punch it on the cords. He would then bring the card deck down to the input room and hand it to one of hte operators and go drink coffee until the output was ready. When the computer finished whatever job it was currently running, an operator would go over the printer and tear off the output and carry it over to the output room, so that the programmer could collect it later. Then he would take one of the card decks that had been brought from the input rand read it in. If the fortran compiler was needed, the operator would have to get it from a file cabinet and read it in. Much computer time was wasted while operators were walking around the machine room. Given the high cost of the equipment, it is not surprising that people quickly looked for ways to reduce the wasted time. The solution generally adopted was the batch system. The idea behind it was to collect a tray full of jobs in the input room and then read them onto a magnetic tape using a small (relatively) inexpensive computer, such as IBM 1401, which was quite good at readign cards, copying tapes, and printing output, but not at all good at numerical calculations Other, much more expensive machines, such as the IBM 7094, were used for the real computing. This situation is shown in Fig. 1-3. After about an hour of collecting a batch of jobs, the cards were read onto a magnetic tape. which was carried into the machine room. Where it was mounted on a tape drive. The operator then loaded a special program (the ancestor of today's operating system), which read the first job from tape and run it. The output was written onto a second tap, instead of being printed. After each job finished, the operating system automatically read the next job from the tape and began running it. When the whole batch was done, the operator removed the input and output tapes, replaced the input tape with the next batch, and brought the output tape to a 1401 for printing offline (ie.g, not connected to the main computer.) The structure of a typical input job is shown in Fig. 1-4. It started out with a $JOB card, specifying the maximum run time in minutes, the account number to be charged, and the programmer's name. Then came a $FORTRAN card, telling the operating system to load the FORTRAN compiler from the system tape. It was directly followed by the program to be compiled, and then a $LOAD card, directing the operating system to load the object program just compiled. (Compiled programs were often written on scratch tapes and had to be loaded explicitly.) Next came the $RUN card, telling the operating system to run the program with the data following it. Finally, the $END card marked the end of the job. These primitive control cards were teh forerunners of modern shells and command-line interpreters. Large second-generation computers were used mostly for scientific and engineering calculations, such as solving the partial differential equations that often occur in physics and engineering. They were largely programmed in Fortran and assembly language. Typical operating systems were FMS (the Fortran Monitor System) and IBSYS, IBM's operating system for the 7094. 1.2.3 The third generation (1965-80): ICs and multiprogramming By teh early 1960s, most computer manufacturer had two distinct, incompatible, product lines. On the one hand, there were the word-oriented, large-scale scientific computers, such as the 7094, which were used for industrial-strength numerical calculations in science and engineering. On the other hand, there were the character-oriented, commercial computers, such as the 1401, which were widely used for tape sorting and printing by banks and insurance companies. Developing and maintaining two completely different product lines was expensive proposition for the manufacturers. In addition, many new computer customers initially needed a small machine but later outgrew it and wanted a bigger machine that would run all their old programs, but faster. IBM attempted to solve both of these problems at a single stroke by introducing the system/360. The 360 was a series of software-compatible machines ranging from 1401-sized models to much larger ones, more powerful then the mighty 7094. The machines differed only in price and performance (maximum memory, processor speed, number of i/o devices permitted, and so forth). Since they all had the same architecture and instruction set, programs written for one machine could run on all the others - at least in theory. (But as yogi Berra reputedly said: "In theory, theory and practice are the same; in practice, they are not." Since the 360 was designed to handle both scientific (i.e., numerical) anc commercial computing, a single family of machines could satisfy the needs of all customers. In subsequent years, IBM came out with backward compatible successors to the 360 line, using more modern technology, known as the 370, 4300, 3080, and 3090. The zSeries is the most recent descendant of this line, although it has diverged considerably from the original. The IBM 360 was the first major computer line to sue (small-scale) ics (integrated circuits), thus providing a major price/performance advantage over the second generation machines, which were built up from individual transistors. it was an immediate success, and the idea of a family of compatible computers was soon adopted by all the other major manufacturers. The descendants of these machines are still in use at computer centers today. Nowadays they are often used for managing huge databases (e.g., for airline reservation systems) or as servers for World Wide Web sites that must process thousands of requests per second. The greatest strength of the "single-family" idea was simultaneously its greatest weakness. The original intention was that all software, including the operating system, OS/360, had to work on all models. It had to run on small systems, which often just replaced 1401s for copying cards to tape, and on very large systems, which often replaced 7094s for doing weather forecasting and other heavy computing. It had to be good on systems with few peripherals and on systems with many peripherals. It had to work in commercial environments and in scientific environments. Above all, it had to be efficient for all of these different uses. There was no way that IBM (or anybody else for that matter) could write a piece of software to meet all those conflicting requirements. The result was an enormous and extraordinarily complex operating system, probably two to three orders of magnitude large than FMS. It consisted of millions of lines of assembly language written by thousands of programmers, and contained thousands upon thousands of bugs, which necessitated a continuous stream of new releases in an attempt to correct them. Each new release fixed some bugs and introduced new ones, so the number of bugs probably remained constant over time. One of the designers of OS/360, Fred Brooks, subsequently wrote a witty and incisive book (Brooks, 1995) describing his experiences with OS/360. While it would be impossible to summarize the book here, suffice it to say that the cover shows a herd of prehistoric beasts stuck in a tar pit. The cover of Silberschatz et al. (2012) makes a similar point about operating systems being dinosaurs. Despite its enormous sie and problems, OS/360 and the similar third-generation operating systems produced by other computer manufacturers actually satisfied most of their customers reasonably well. They also popularized several key techniques absent in second-generation operationg systems. Probably the most important of these was multiprogramming. On the 7094, when the current job paused to wait for a tape or other i/o operation to complete, the CPU simply stay idle until the i/o finished. With heavily cpu bound scientific calculation, i/o is infrequent, so this wasted time is not significant. With commercial data processing, the i/o wait time can often 80% or 90% of the total time, so something had to be done to avoid having the (expensive) CPU be ideal so much. The solution that evolved was to partition memory into several pieces, with a different job in each partition, as shown in Fig 1-5. While one job was waiting for i/o to complete, another job could be suing the CPU. If enough jobs could be hold in memory at once, the CPU could be kept busy nearly 100% of the time. Having multiple jobs safely in memory at once requires special hardware to protect each job against snooping and mischief by other ones, but the 360 and other third-generation systems were equipped with this hardware. Another major feature present in third-generation operating systems was the ability to read jobs from cards onto the disk as soon as they were brought to the computer room. Then, whenever a running job finished, the operating system could load a new job from the disk into the now-empty partition and run it. This technique is called spooling (from Simultaneous Peripheral Operation On Line) and was also used for output. With spooling, the 1401s wre no longer needed, and much carrying of tapes disappeared. Although third-generation operating systems were well suited for big scientific calculations and massive commercial data-processing runs, they were still basically batch system. many programmers pined fro the first-generation days when they had the machine all to themselves for a few hours, so they could debug their programs quickly. With third-generation systems, the time between submitting a job and getting back the output was often several hours, so a single misplaced comma could cause a compilation to fail, and the programmer to waste half a day. Programmers did not like that very mch. This desire for quick response time paved teh way for timesharing, a variant of multiprogramming, in which each user has an online terminal. In a timesharing system, if 20 users are logged in and 17 of them are thinking or talking or drinking coffee, the CPU can be allocated in turn to the tree jobs that want services. Since people debugging programs usually issue short commands (e.g., compile a five page procedure) rather than long ones (e.g. sort a million-record file), the computer can provide fast, interactive service to number of users and perhaps also work on big batch jobs in the background when the CPU is otherwise idle. The first general-purpose timesharing system. CTSS (Compatible Time Sharing System), was developed at MIT on a specially modified 7094. However, timesharing did not really become popular until the necessary protection hardware became widespread during the third generation. After teh success fo the CTSS system, MIT Bell labs, and general Electric ( at that time a major computer manufacturer) decided to embark on the development of a "computer utility," that is, a machine that would support some hundreds of simultaneous timesharing users. Their model was the electricity system - when you need electric power, you just stick a plug in the wall, and within reason, as much power as you need will be there. The designers of this system, known as MULTICS (MULTIplexed Information and Computing Service), envisioned one huge machine providing computing power for everyone in teh Boston area. The idea that machines 10,000 times faster than their GE-645 mainframe would be sold (for well under $1000) by the millions only 40 years later was pure science fiction. Sort of like the idea of supersonic trans-Atlantic undersea trains now. MULTICS was a mixed success. It was designed to support hundreds of users on a machine only slightly more powerful than an Intel 386-based PC, although it had much more i/0 capacity. This is not quite as crazy as it sounds, since in those days people knew how to write small, efficient programs, a skill that has subsequently been completely lost. There were many reason that MULTICS did not take over the world, not the least of which is that it was written in the PL/I programming language, and the PL/I compiler was years late and barely worked at all when it finally arrived. In addition, MULTICS was enormously ambitious for its time, much like Charles Babbage's analytical engine in the nineteenth century. To make a long story short, MULTICS introduced many seminal ideas into the computer literature, but turning it into a serious product and major commercial success was a lot harder than anyone had expected. Bell labs dropped out the project, and General Electric quit the computer business altogether. However, MIT persisted and eventually got MULTICS working. It was ultimately sold as a commercial product by teh company (Honeywell) that bought GE's computer business and was installed by about 80 major companies and universities worldwide. While their numbers were small, MULTICS users were fiercely loyal. General Motors, Ford, and US National Security Agency, for example, shut down their MULTICS system only in late 1990s, 30 years after MULTICS was released, after years of trying to get Honeywell to update the hardware. By teh end of the 20th century, the concept of computer utility had fizzled out, but it may well come back in the form of cloud computing, in which relatively small computers (including smartphones, tablets, and the like) are connected to services in vast and distant data centers where all the computing is done, with the local computer just handling the user interface. The motivation here is that most people do not want to administrate an increasingly complex and finicky computer system and would prefer to have that work done by a team of professionals, for example, people working for the company running the data center. E-commerce is already evolving in this direction with various companies running emails on multiprocessor servers to which simple client machines connect, very much in the spirit of the MULTICS design. Despite its lack of commercial success, MULTICS had a huge influence on subsequent operating systems (especially Unix and its derivatives, FreeBSD, Linux, iOS, and android). It is described in several papers and a book. It also has an active website, located at www.multicians.org, with much information about the system. Its designers, and its users. Another major development during the third generation was the phenomenal growth of minicomputers, starting with the DEC PDP-1 in 1961. The PDP-1 had only 4K of 18-bit words, but at $120,000 per machine (less then 5% of the price of a 7094), it sold like hotcakes. For certain kinds of nonnumerical work, it was almost as fast as the 7094 and gave birth to a whole new industry. It was quickly followed by a series of other PDPs (unlike IBM's family, all incompatible) culminating in the PDP-11. One of the computer scientists at Bell labs who had worked on the MULTICS project, Ken Thompson, subsequently found a small PDP-7 minicomputer that no one was using and set out to write a stripped-down, one-user version of MULTiCS. This work later developed into the UNIX operating system, which became popular in teh academic world, with government agencies, and with many companies. The history of UNIX has been told elsewhere (e.g. Salus, 1994). Part of that story wil be given in Chapter 10. For now, suffice it to say that because the source code was widely available, various organizations developed their own (incompatible) versions, which led to chaos. Two major version developed, System V, from AT&T, and BSD (Berkeley Software Distribution) from the university of california at berkeley. These had minor variants as well. To make it possible to write programs that could run on any UNIX system. IEEE developed a standard for UNIX, called POSIX, that most versions of UNIX now support. POSIX defines a minimal system-call interface that conformant UNIX system must support. In fact, some other operating systems now also support the POSIX interface. As an aside, it is worth mentioning that in 1987, the author released a small clone of UNIX, called MINIX, for educational purposes. Functionally, MINIX is very similar to UNIX, including POSIX support. Since that time, the original version has evolved into MINIX 3, which is highly modular and focused on very high reliability. It has the ability to detect and and replace faulty or even crashed modules (such as i/o device drivers) on the fly without a reboot and without disturbing running programs. it focus is on providing very high dependability and availability. A book describing its internal operation and listing the source code in an appendix is also available (Tanenbaum and Woodhull, 2006). The MINIX 3 system is available for free (including al lthe source code) over the internet at www.minix3.org. The desire for a free production (as opposed to educational) version of MINIX led a finnish student, Linus Torvalds, to write Linux. This system was directly inspired by and developed on MINIX and originally supported various MINIX feature (e.g., the MINIX file system). It has since been extended in many ways by many people but still retains some underlying structure common to MINIX and to UNIX. Readers interested in a detailed history of Linux and the open source movements might want to read Glyn Moody's (2001) book. Most of what will be said about UNIX in this book thus applies to System V, MINIX, Linux and other versions and clone of UNIX as well. 1.2.4 The fourth generation (1980-present): Personal Computers With the development of LSI (Large Scale Integration) circuits - chips containing thousands of transistors on a square centimeter of silicon - the age of personal computer dawned. In terms of architecture, personal computers (initially called microcomputers) were not all that different from minicomputers of the PDP-11 class, but in terms of price they certainly were different. Where the minicomputer make it possible for a department in a company or university to have its own computer, the microprocessor chip made it possible for a single individual to have his or her own personal computer. In 1974, when intel came out with the 8080, the first general-purpose 8-bit CPU, it wanted an operating system for the 8080, in part to be able to rest it. Intel asked one of its consultants, Gary Kildall, to write one. kildall and a friend first built a controller for the newly released Shugart Associates 8-inch floppy disk and hooked the floppy disk up to the 8080, thus producing the first microcomputer with a disk. Kildall then wrote a disk-based operating system called CP/M (Control Program for Microcomputers) for it. Since intel did not think that disk-based microcomputers had much of a future, when Kildall asked for teh rights to CP/M, Intel granted his request. Kildall then formed a company, Digital Research, to further develop and sell CP/M. In 1977, Digital Research rewrote CP/M to make it suitable for running on the many microcomputers using the 8080, Zilog Z80, and other CPU chips. Many application programs were written to run on CP/M, allowing it to completely dominate the world of micro-computing for about 5 years. In the early 1980s, IBM designed the IBM PC and looked around for software to run on it. People from IBM contacted Bill Gates to license his BASIC interpreter. They also asked him if he knew of an operating system to run on the PC. Gates suggested that IBM contact Digital Research, then the world's dominant operating systems company. Making what was surely the worst business decision in recorded history, Kildall refused to meet with IBM, sending a subordinate instead. To make mattes even worse, his lawyer even refused to sign IBM's nondisclosure agreement covering the not-yet-announced PC. Consequently, IBM went back to Gates asking if he could provided the with an operating system. When IBM came back, Gates realized that a local computer manufacturer, Seattle Computer Products, had a suitable operating system, DOS (Disk Operating system). He approached them and asked to buy it (allegedly for %75,000), which they readily accepted. Gates then offered IBM a DOS/BASIC package, which IBM accepted. IBM wanted certain modifications, so Gates hired teh person who wrote DOS, Tim paterson, as an employee of Gates fledgling company, Microsoft, to make them. The revise system was renamed MS-DOS (Microsoft Disk Operating System) and quickly came to dominate the IBM PC market. A key factor here was Gate's (in retrospect, extremely wise) decision to sell MS-DOS to computer companies for bundling with their hardware, compared to Kildall's attempt to sell CP/M to end users one at a time (at least initially) After all this transpired, Kildall died suddenly and unexpectedly from causes that have not been fully disclosed. By the time teh successor to the IMB PC, the IBM PC/AT, came out in 1983 with the intel 80286 CPU, MS-DOS was firmly entrenched and CP/M ws on its last legs. MS-DOS was later widely used on the 80386 and 80486. Although the initial version of MS-DOS was fairly primitive, subsequent versions included more advanced features, including many taken from UNIX. (Microsoft was well aware of UNIX, even selling a microcomputer version of it called XENIX during the company's early years.) CP/M, MS-DOS, and other operating systems for early microcomputers were all based on users typing in commands from the keyboard. That eventually changed due to research done by Doug Engelbart at Stanford Research Institute in the 1960s. Engelbart invented teh Graphical User Interface, complete with windows, icons, menus, and mouse. These ideas were adopted by researchers at Xerox PARC and incorporated into machines they built. One day, Steve Jobs, who con-invented the Apple computer in this garage, visited PARC, saw a GUI, and instantly realized its potential value, something Xerox management famously did not. This strategic blunder of gargantuan proportions led to a blook entitled Fumbling the Future (Smith and Alexander, 1988). jobs then embarked on building an Apple with GUI. This project led to the Lisa, which was too expensive and failed commercially. Jobs' second attempt, the Apple Macintosh, was a huge success, not only because it was much cheaper than Lisa, but also because it was user friendly, meaning that it was intended for users who not only knew nothing about computers but furthermore had absolutely no intention whatsoever of learning. In the creative world of graphic design, professional digital photography, and professional digital video production, Macintoshes are very widely used and their users are very enthusiastic about them. In 1999, Apple adopted a kernel derived from Carnegie Mellon University's Mach micro kernel which was originally developed to replace the kernel of BSD UNIX. Thus, Mac OSX is a unix-based operating system, albeit with a very distinctive interface. When Microsoft decided to build a successor to MS-DOS, it was strongly influenced by teh success of teh Macintosh. It produced a GUI-based system called Windows, which originally run on top of MS-DOS (e.g., it was more like a shell then a true operating system). For about 10 years, from 1985 to 1995, windows was jut a graphical environment on top of MS-DOS However, starting in 1995 a freestanding version, Windows 95, was released that incorporated many operating system features into it, using the underlying MS-DOS system only for booting and running old MS-DOS programs. In 1998, a slightly modified version of this system, called windows 98 was released. nevertheless, both windows 95 and windows 98 still contained a large amount of 16-bit intel assembly language. Another microsoft operating system, windows nt (where the nt stands for new technology), which was compatible with windows 95 at a certain level, but a complete rewrite from scratch internally. it was a full 32-bit system. The lead designer for windows nt was David Cutler, who was also one of the designers fo the VAX VMS operating system, so some ideas from VMS are present in NT. In fact, so many ideas form VMS were present in it that the owner of VMS, DEC, sued Microsoft. The case was settled out of court for an amount of money requiring many digits to express. Microsoft expected that teh first version of NT would kill off MS-DOS and all other version of windows since it was a vastly superior system, but it fizzled. only with Windows NT 4.0 did it finally catch on the big way, especially on corporate networks. Version 5 of windows nt was renamed windows 2000 in early 1999. It was intended to be the successor to both windows 98 and windows nt 4.0. That did not quite work out either, so Microsoft came out with yet another version of windows 98 called windows me ( Millennium Edition). In 2001, a slightly upgraded version of windows 2000, called windows xp was released. That version had a much longer run (6 years), basically replacing all previous version of windows. Still the spawning of versions continued unabated. After widows 2000, Microsoft broke up the windows family into a client and a server line. The client line was based on xp and tis successors, while the server line included windows server 2003 and windows 2008. A third line, for the embedded world, appeared a little later. All of these versions of Windows forked off their variations, in the form of service packs. It was enough to drive some administrators (and writers of operating systems textbooks) balmy. Then in January 2007, Microsoft finally released the successor to windows xp, called vista. It came with a new graphical interface, improved security, and many new or upgraded user programs. Microsoft hoped it would replace windows xp completely, but it never did. instead, it received much criticism and a bad press, mostly due to the high system requirements, restrictive licensing terms, and support for digit rights management techniques that made it harder for users to copy protected material. With the arrival of windows 7, a new and much less resource hungry version of teh operating system, many people decide to skip vista altogether, windows 7 did not introduce too many new features, but it was relatively small and quite stable. in less than tree weeks, windows 7 had obtained more market share than vista in seven months. In 2012, Microsoft launched its successor, Windows 8, an operating system with a completely new look and feel. geared for touch screens, The company hopes that the new design will become the dominant operating system on a much wider variety of devices: desktops, laptops, notebooks, tables, phones, and home theater PCs. So far, however, te market penetration is slow compared to Windows 7. The other major contender in personal computer world is UNIX (and its various derivatives). UNIX is strongest on network and enterprise servers but is also often present on desktop computers, notebooks, tablets, and smartphones. On x86-based computers, Linux is becoming a popular alternative to windows for student and increasingly many corporate users. As an aside, throughout this book we will use the term x98 to refer to all modern processors based on teh family of instruction-set architectures that started with the 8086 in the 1970s. There are many such processors, manufactured by companies like AMD and Intel, and under the hood they often differ considerably: Processors may be 32 bits or 64 bits with few or many cores and pipelines that may be deep or shallow, and so on. Nevertheless, to teh programmer, they all look quite similar and tehy can all still run 8086 code that was written 35 years ago. Where the difference is important. we will refer to explicit models instead - and use x86-32 and x86-64 to indicate 32-bit and 64-bit variants. FreeBSD is also a popular UNIX derivative, originating from the BSD project at Berkeley. All modern macintosh computers run a modified version of freeBSD. unix is also standard on workstations powered by high-performance RISC chips. Its derivatives are widely used on mobile devices, such a those running iOS 7 and android. Many UNIX users, especially experienced programmers, prefer a command based interface to a GUI. so nearly all UNIX systems support a windowing system called X windows system (also know as X11) produced at MIT this system handles the basic windows management, allowing users to create, delete, move and resize windows using a mouse. Often a complete GUI, such as Gnome or KDE, is available to run on top of X11, giving UNIX a look and feel something like the macintosh or microsoft windows, for those UNIX users who want to such a thing. An interesting development that began taking place during the mid-1980s is teh growth of networks of personal computers running network operating systems and distributed operating systems (Tanenbaum and Van Steen, 2007). In a network operating system, teh users are aware of th existence of multiple computers and log in to remote machines and copy files from one machine to another. Each machine runs its own local operating system and ahs its own local (or users). Network operating systems are not fundamentally different from single-processor operating system. They obviously need a network interface controller and some low-level software to driver it, as well as programs to achieve remote login and remote file access, but these additions do not change the essential structure of the operating system. A distributed operating system, in contrast, is one that appears to its users as traditional uniprocessor system, even though it is actually composed of multiple processors. The users should not be aware of where their programs are being run or where their files are located; that should all be handled automatically and efficiently by the operating system. True distributed operating systems require more than just adding a little code to a uniqprocessor operating system, because distributed and centralized system differ in certain critical ways. Distributed systems, for example, often allow applications to run on several processors at teh same time, thus requiring more complex processor scheduling algorithms in order to optimize the amount of parallelism. Communication delays within the network often mean that these (and other) algorithms must run with incomplete, outdated, or even incorrect information. This situation differs radically from that in a single processor system in which the operating system has complete information about the system sate. 1.2.5. The fifth generation (1990-present): mobile computers Ever since detective Dick tracy started talking to his "two-way radio wrist watch" in teh 1940s comic strip, people have craved a communication device they could carry around wherever they went. The first real mobile phone appeared in 1946 and weighed some 40 kilos. you could take it wherever you went as long as you had a car in which to carry it. The first true handheld phone appeared in teh 1970s and, at roughly one kilogram, was positively featherweight, It was affectionately know as "the brick." Pretty soon everybody wanted one. Today, mobile phone penetration is close to 90% of teh global population. We can make calls not jsut with our portable phones and wrist watches, but soon with eyeglasses and other wearable items. Moreover, the phone part is no longer that interesting. We receive email, surf the Web, text our friends, play games, navigate around heavy traffic - and do not even think twice about it. While the idea of combining telephony and computing in a phone-like device has been around since the 1970s also, the first real smartphone did not appear until the mid-1990s when Nokia released the N9000, which literally combined two, mostly separate device: a phone and a PDA (Personal Digital Assistant). In 1997, Ericsson coined teh term smartphone for its GS88 "Penelope." Now that smartphones have become ubiquitous, the competition between the various operating system is fierce and the outcome is even less clear than the PC world. At the time of writing, Google's Android is the dominant operating system with Apple's iOS a clear second, but this was not always teh case and all many be different again in just a few years. If anything is clear in the world of smartphones, it is that it is not easy to stay king of the mountain for long. After all, most smartphones in the first decade after their inception were running Symbian OS. It was the operating system of choice for popular brands like Samsung, Sony Ericsson, Motorola, and especially Nokia. However, other operating systems like RIM's balckberry OS (introduced for smartphones in 2002) and Apple's iOS (released for teh first iPhone in 2007) started eating into symbian's market share. many expected that rim would dominate the business market, while ios would be the king of the consumer devices. Symbian's market share plummeted. In 2011, nokia ditched Symbian and announced it would focus on windows Phone as its primary platform. For some time, Apple and RIM were the toast of the town (although not nearly as dominant as symbian had been), but it did not take very long for Android. A linux-based operating system released by Google in 2008, to overtake all its rivals. For phone manufacturers, Android had the advantage that it was open source and available under a permissive license. As a result, they could tinker with it and adapt it to their own hardware with ease. Also, it has a huge community of developers writing apps, mostly in the familiar Java programming language. Even so, the past years have shown that the dominance may not last, and Android's competitors are eager to claw back some of ti market share. We will look at android in detail in sec 10.8. """
83257bb8fb0e2147f534752fbdfb373b67717acc
zakircuet/Python
/if.py
327
3.9375
4
indian=["somosa","dal","naan"] chinese=["soup","fried rice","egg role"] italian=["pizza","pasta","risotto"] dish=input("Please enter a dish name:") dish=str.lower(dish) if dish in indian: print("indian") elif dish in chinese: print("chinese") elif dish in italian: print("italian") else: print("No knowledge")
ddfeddb6a76f082e3c408d980860e2f4e964eba0
davidokun/Python
/fundamentals/5-methods-and-functions/7-homework-exercises.py
3,289
4.09375
4
import string # Write a function that computes the volume of a sphere given its radius. print("# VOLUME OF A SPHERE\n") def vol(rad): volume = (rad**3 * 3.141592) * (4/3) return "Volume of Sphere with radius {1} is = {0:1.5f} m3".format(volume, rad) print(vol(2)) print(vol(8)) # Write a function that checks whether a number is in a given range (inclusive of high and low) print("\n# NUMBER IS IN RANGE\n") def ran_check(num, low, high): if num in range(low, high + 1): return '{0} is in the range between {1} and {2}'.format(num, low, high) else: return '{0} is NOT in the range between {1} and {2}'.format(num, low, high) print(ran_check(5, 2, 7)) print(ran_check(3, 1, 10)) print(ran_check(10, 1, 10)) print(ran_check(1, 1, 10)) print(ran_check(50, 15, 30)) print(ran_check(0, 15, 31)) # Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters. print("\n# CALCULATES THE NUMBER OF UPPER CASE LETTERS AND LOWER CASE LETTERS\n") def up_low(sentence): upper = 0 lower = 0 for s in sentence: if s.islower(): lower += 1 if s.isupper(): upper += 1 print('No. of Upper case characters : {}'.format(upper)) print('No. of Lower case characters : {}'.format(lower)) s = 'Hello Mr. Rogers, how are you this fine Tuesday?' up_low(s) s2 = 'May the Force Be with YoU!' up_low(s2) # Write a Python function that takes a list and returns a new list with unique elements of the first list. print("\n# RETURNS A NEW LIST WITH UNIQUE ELEMENTS\n") def unique_list(my_lst): return list(set(my_lst)) print(unique_list([1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5])) print(unique_list([1, 2, 3, 3, 4, 5, 6, 6, 6, 7, 8, 8, 9, 0, 0])) # Write a Python function to multiply all the numbers in a list. print("\n# MULTIPLY ALL THE NUMBERS IN A LIST\n") def multiply(numbers): result = 1 for n in numbers: result *= n return result print(multiply([1, 2, 3, -4])) print(multiply([4, 0, 5, 10, 2])) print(multiply([4, 3, 5, 10, 2])) # Write a Python function that checks whether a passed in string is palindrome or not. print("\n# CHECKS WHETHER A PASSED IN STRING IS PALINDROME OR NOT\n") def palindrome(word): lower_word = word.lower().replace(' ', '') return lower_word == lower_word[::-1] print(palindrome('helleh')) print(palindrome('madam')) print(palindrome('May the force be with you')) print(palindrome('nurses run')) print(palindrome('Sometamos o matemos')) print(palindrome('Yo dono rosas oro no doy')) print(palindrome('Do or do not there is no try')) # Write a Python function to check whether a string is pangram or not. print("\n# CHECK WHETHER A STRING IS PANGRAM OR NOT\n") def ispangram(str1, alphabet=string.ascii_lowercase): lower_sentence = str1.lower().replace(' ', '') for n in alphabet: if n in lower_sentence: continue else: return False return True print(ispangram("The quick brown fox jumps over the lazy dog")) # True print(ispangram("Pack my box with five dozen liquor jugs")) # True print(ispangram("How quickly daft jumping zebras vex")) # True print(ispangram("Hate leads to the Dark Side of the Force")) # False
861b5f91f88f313e2425b6675dea3625a4f6ba63
sunnystory/Algorithm_2021
/algory lecture/multi_algori/06큐1.py
393
4.0625
4
queue=[None for _ in range(3)] front=rear=-1 rear+=1;queue[rear]='A' rear+=1;queue[rear]='B' rear+=1;queue[rear]='C' print(queue) front+=1;print(queue[front]);queue[front]=None #안해되 되는데 확실히 하려고 front+=1;print(queue[front]);queue[front]=None front+=1;print(queue[front]);queue[front]=None print(queue) rear+=1;queue[rear]='D' #이런 한계 때문에 원형큐 사용
86fef75ec95e68e5a9ed49c0696ea2c1b92fee1e
IceMIce/LeetCode
/Array/485_Max Consecutive Ones.py
494
3.59375
4
class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ i = 0 max_num_list = [] for num in nums: if num == 1: i = i + 1 max_num_list.append(i) else: i = 0 if len(max_num_list) == 0: return 0 return max(max_num_list) solution = Solution() print solution.findMaxConsecutiveOnes([1])
5f1d92406f44e20655686f2380c9db195bb87a73
WWTprojects/Python
/School/Lab 1 by Wesley Thomas.py
1,716
4.15625
4
# Wesley Thomas # Lab 1 #Declare variables for grocery item item1 = "" item2 = "" item3 = "" item4 = "" item5 = "" item6 = "" item7 = "" item8 = "" #Declare variable # s for the price for each item price1 = 0.0 price2 = 0.0 price3 = 0.0 price4 = 0.0 price5 = 0.0 price6 = 0.0 price7 = 0.0 price8 = 0.0 #Ask for inputs for the groceries and their price using the variables above print("Type in the 1st grocery item: ") item1 = input() print("Type in the 1st grocery item's price: ") price1 = input() print("Type in the 2nd grocery item: ") item2 = input() print("Type in the 2nd grocery item's price: ") price2 = input() print("Type in the 3rd grocery item: ") item3 = input() print("Type in the 3rd grocery item's price: ") price3 = input() print("Type in the 4th grocery item: ") item4 = input() print("Type in the 4th grocery item's price: ") price4 = input() print("Type in the 5th grocery item: ") item5 = input() print("Type in the 5th grocery item's price: ") price5 = input() print("Type in the 6th grocery item: ") item6 = input() print("Type in the 6th grocery item's price: ") price6 = input() print("Type in the 7th grocery item: ") item7 = input() print("Type in the 7th grocery item's price: ") price7 = input() print("Type in the 8th grocery item: ") item8 = input() print("Type in the 8th grocery item's price: ") price8 = input() #Print out the list print("Below is your list of groceries and their respective prices") print(item1," ",price1) print(item2," ",price2) print(item3," ",price3) print(item4," ",price4) print(item5," ",price5) print(item6," ",price6) print(item7," ",price7) print(item8," ",price8)
90d4aec5f7ccc48bad55bb2d9d8ffc2330478007
edmanf/Cryptopals
/src/cryptopals/convert.py
861
4.1875
4
""" This class contains methods for converting from one format to another """ import base64 def hex_string_to_bytes(hex_str): """ Convert the hex string to a bytes object and return it. Keyword arguments: hex_str -- a String object comprised of hexadecimal digits """ return bytes.fromhex(hex_str) def hex_to_b64(hex_bytes): """ Convert the hex to base64 and return it. Keyword arguments: hex_bytes -- a bytes object """ return base64.b64encode(hex_bytes) def hex_string_to_b64(hex_str): """ Convert the hex string to a base64 encoded byte string and return it. Keyword arguements: hex_str -- a String of hexadecimal digits """ return hex_to_b64(hex_string_to_bytes(hex_str)) def b64_string_to_hex(b64_str): return hex_string_to_bytes(base64.b64decode(b64_str).hex())
171b998e32a6fde1dd5b037ee117c863026c12e8
josedoneguillen/python-profesional
/anotaciones/comprehension.py
457
3.640625
4
#lista = [] # #for x in range(0, 101): # lista.append(x) # #print(lista) estructura_lista = [ "indice-" + str(x) for x in range(0, 100) ] print(estructura_lista) estructura_tupla = tuple(( x for x in range(0, 100) if x % 2 == 0) ) print(estructura_tupla) estructura_diccionario = { indice:valor for indice, valor in enumerate(estructura_lista) } print(estructura_diccionario)
d3c421b81e2347ba608153664d399c906a1a0b53
arsaltariq/Detailed-Assignment-3.17-3.44
/3.33.py
92
4.15625
4
#Exercise 3.33: #Reverse string: x=input("Input three letter string:") print(x[::-1])
9e979cfaa7e3ca1bc5a7a25d5dba1ddb19868838
edubd/uff2020
/progs/p14_normalizacao.py
761
4.0625
4
#P14: Normalização import pandas as pd #(1)-Importa a base de dados para um DataFrame df_lojas = pd.read_csv('lojas.csv') #(2)-Normaliza o “salario” sal_max = max(df_lojas['salario']) sal_min = min(df_lojas['salario']) df_lojas['sal_norm'] = (df_lojas['salario'] - sal_min) / (sal_max - sal_min) #(3)-Normaliza o “po” po_max = max(df_lojas['po']) po_min = min(df_lojas['po']) df_lojas['po_norm'] = (df_lojas['po'] - po_min) / (po_max - po_min) #(4)-Após a normalização, remove os atributos originais df_lojas = df_lojas.drop(columns=['po','salario']) #(5)-Imprime o DataFrame transformado print('-----------------------------------') print('DataFrame após a normalização das variáveis numéricas') print(df_lojas)
11526f44e85f59ddcb204482a70d08faf5b88dd6
1cedsoda/py-equalculator
/solve.py
14,778
3.65625
4
from type import getType import re def replaceVars(equasion_as_list, variables={}): equasion = equasion_as_list.copy() # >>> replace vars <<< for n in range(len(equasion)): if equasion[n] in variables: equasion[n] = variables[equasion[n]] return equasion def solveEquasion(equasion_as_list): # solving an equasion (recursive, because of brackets) equasion = equasion_as_list.copy() # code will look cleaner with shorter variables # >>> solve brackets <<< bracket = 0 for n in range(len(equasion)): # every entry in the equasionlist will be checked for brackets if equasion[n] == "(": bracket = bracket + 1 if equasion[n] == ")": bracket = bracket + 1 if bracket > 0: # if there are brackets for missions in range(bracket // 2): # In every mission one bracket pair will be solved missionCompleted = False leftBracket = 0 rightBracket = 0 subequasion = [] for index in range(len(equasion)): # checking every entry in the equasionlist if missionCompleted: # the program should not keep sereaching in the equasion whis in this mission already one bracket pair was solved continue else: # when the mission is still searching for one bracket pair if equasion[index] == "(": # when it's a left bracket... leftBracket = index # ...the index will be saved elif equasion[index] == ")": # if it's a right bracket it will solve the part in between the last left bracket and the current one rightBracket = index # the index will be saved if leftBracket + 1 == rightBracket - 1: subequasion.append(equasion[leftBracket + 1]) else: for n in range(leftBracket + 1, rightBracket): # every entry in between will be appendet to list, which will be recursed tho the solveEquasion() funcion subequasion.append(equasion[n]) subresult = solveEquasion(subequasion) # recusing the subequasion to the solveEquasion() funcion equasion[rightBracket] = (subresult)[0] # replacing the result with the right bracket for n in range(leftBracket + 1, rightBracket + 1): # poping the left bracket and everything inbetween the two brackets equasion.pop(leftBracket) missionCompleted = True # One bracket pair was solved so the next scanned indexed (above) will be skipped # >>> analyse the equasion <<< minus = 0 # declaring the variables vor each action char plus = 0 # with every found action char in the equasion the accordingly variable will get +1 multiply = 0 divide = 0 percent = 0 power = 0 for n in range(len(equasion)): # every entry in the equasionlistwill be checked if equasion[n] == "%": # from here if there is a matching char the accordingly variable will get +1 percent = percent + 1 if equasion[n] == "^": power = power + 1 if equasion[n] == "*": multiply = multiply + 1 if equasion[n] == "/": divide = divide + 1 if equasion[n] == "+": plus = plus + 1 if equasion[n] == "-": minus = minus + 1 # >>> solver percent % <<< >>> solve PERCENT % <<< if percent > 0: # Every mission will solve one compute-sign for missions in range(percent): # for every counted percent char missionCompleted = False # declaring for index in range(len(equasion)): # check every entry of the equasion if missionCompleted: # skipping if the compute-sign was already found in the current mission continue else: # when this mission still have to find one compute-sign if equasion[index] == "%": # executed when a percent char was found subresult = float(equasion[index - 1]) * 0.01 # multiply the entry of the equasion before the percent equasion[index] = str(subresult) # replace the percent char with the subresult equasion.pop(index - 1) # remove the number entry which was in the calculation above missionCompleted = True # the compute-sign was solved so the next scanned indexed (above) will be skipped # >>> solve POWER ^ <<< >>> solve POWER ^ <<< if power > 0: # Every mission will solve one compute-sign for missions in range(power): # for every counted power char missionCompleted = False # declaring for index in range(len(equasion)): # check every entry of the equasion if missionCompleted: # skipping if the compute-sign was already found in the current mission continue else: # when this mission still have to find one compute-sign if equasion[index] == "^": # executed when a power char was found subresult = float(equasion[index - 1]) ** float(equasion[index + 1]) # potentiates the entry before and after the multiplication char equasion[index] = str(subresult) # replace the power char with the subresult equasion.pop(index - 1) # remove the number entry which was in the calculation above equasion.pop(index) # remove the number entry which was in the calculation above missionCompleted = True # the compute-sign was solved so the next scanned indexed (above) will be skipped # >>> solve MULTIPLICATION * <<< >>> solve MULTIPLICATION * <<< if multiply > 0: # Every mission will solve one compute-sign for missions in range(multiply): # for every counted multiplication char missionCompleted = False # declaring for index in range(len(equasion)): # check every entry of the equasion if missionCompleted: # skipping if the compute-sign was already found in the current mission continue else: # when this mission still have to find one compute-sign if equasion[index] == "*": # executed when a multiplication char was found subresult = float(equasion[index - 1]) * float(equasion[index + 1]) # multiplies the entry before and after the multiplication char equasion[index] = str(subresult) # replace the multiplication char with the subresult equasion.pop(index - 1) # remove the number entry which was in the calculation above equasion.pop(index) # remove the number entry which was in the calculation above missionCompleted = True # the compute-sign was solved so the next scanned indexed (above) will be skipped # >>> solve DIVIDATION / <<< >>> solve DIVIDATION / <<< if divide > 0: # Every mission will solve one compute-sign for missions in range(divide): # for every counted dividation char missionCompleted = False # declaring for index in range(len(equasion)): # check every entry of the equasion if missionCompleted: # skipping if the compute-sign was already found in the current mission continue else: # when this mission still have to find one compute-sign if equasion[index] == "/": # executed when a dividation char was found subresult = float(equasion[index - 1]) / float(equasion[index + 1]) # divides the entry before and after the dividation char equasion[index] = str(subresult) # replace the dividation char with the subresult equasion.pop(index - 1) # remove the number entry which was in the calculation above equasion.pop(index) # remove the number entry which was in the calculation above missionCompleted = True # the compute-sign was solved so the next scanned indexed (above) will be skipped # >>> solve PLUS + <<< >>> solve PLUS + <<< if plus > 0: # Every mission will solve one compute-sign for missions in range(plus): # for every counted plus missionCompleted = False # declaring for index in range(len(equasion)): # check every entry of the equasion if missionCompleted: # skipping if the compute-sign was already found in the current mission continue else: # when this mission still have to find one compute-sign if equasion[index] == "+": # executed when a plus char was found subresult = float(equasion[index - 1]) + float(equasion[index + 1]) # adds the entry before and after the plus equasion[index] = str(subresult) # replace the plus with the subresult equasion.pop(index - 1) # remove the number entry which was in the calculation above equasion.pop(index) # remove the number entry which was in the calculation above missionCompleted = True # the compute-sign was solved so the next scanned indexed (above) will be skipped # >>> solve MINUS - <<< >>> solve MINUS - <<< if minus > 0: # Every mission will solve one compute-sign for missions in range(minus): # for every counted dividation char missionCompleted = False # declaring for index in range(len(equasion)): # check every entry of the equasion if missionCompleted: # skipping if the compute-sign was already found in the current mission continue else: # when this mission still have to find one compute-sign if equasion[index] == "-": # executed when a minus char was found subresult = float(equasion[index - 1]) - float(equasion[index + 1]) # subsracts the entry before and after the dividation char equasion[index] = str(subresult) # replace the dividation char with the subresult equasion.pop(index - 1) # remove the number entry which was in the calculation above equasion.pop(index) # remove the number entry which was in the calculation above missionCompleted = True # the compute-sign was solved so the next scanned indexed (above) will be skipped return equasion
c369e076ba5d2b3764a0040238c6c7631d439eff
akashrai80/python-programs
/question-5.py
726
4.21875
4
file = input("enter file name :") # function for word count def count_word(file_name): # open file f = open(file_name, "r") total_words = 0 # reterive lines from file for line in f: word = True # reterive letters from line for letter in line: # count words if (letter != " " and letter != "," and letter != ", ") and word == True: total_words+=1 word = False # check for spaces, commas in line elif letter == " " or letter == "," or letter == ", ": word = True return ("Total words in {} : {}".format(file_name, total_words)) print(count_word(file))
d59e88f4e83a44b12b1cf0a4e9bde20cd13093ac
pellungrobe/SimulatedPrivacyAnnealing
/PSA/datetime_util.py
3,644
3.640625
4
from datetime import datetime, timedelta def weekend_weekdays(zero_at_day=0, number_of_days=31): day_dict = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", 0: "Sunday"} day = 24 day_num = zero_at_day weekdays, weekend = list(), list() for i in range(0, number_of_days+1): curr_day = day_dict[(day_num + i) % 7] for t in range(0, 24): timeslot = (i * 24) + t if curr_day in ["Sunday", "Saturday"]: weekend.append(timeslot) else: weekdays.append(timeslot) return weekend, weekdays def morning_midday_afternoon_night(number_of_days=31): morning, midday, afternoon, night = list(), list(), list(), list() for i in range(0, number_of_days+1): for t in range(0, 24): timeslot = (i * 24) + t if t in range(0, 3) or t in range(21, 24): night.append(timeslot) elif t in range(3, 9): morning.append(timeslot) elif t in range(9, 15): midday.append(timeslot) else: afternoon.append(timeslot) return morning, midday, afternoon, night def timeslot_partition(zero_at_day=0, number_of_days=31): weekend, weekdays = weekend_weekdays(zero_at_day, number_of_days) morning, midday, afternoon, night = morning_midday_afternoon_night(number_of_days) results = dict() for timeslot in range(0,(number_of_days*24)+1): if timeslot in morning: if timeslot in weekend: results[timeslot] = "morning_weekend" else: results[timeslot] = "morning_weekdays" elif timeslot in midday: if timeslot in weekend: results[timeslot] = "midday__weekend" else: results[timeslot] = "midday_weekdays" elif timeslot in afternoon: if timeslot in weekend: results[timeslot] = "afternoon__weekend" else: results[timeslot] = "afternoon_weekdays" else: if timeslot in weekend: results[timeslot] = "night__weekend" else: results[timeslot] = "night_weekdays" return results def extract_all_times(time_string): year = int(time_string[:4]) month = int(time_string[:6][-2:]) day = int(time_string[:8][-2:]) hour = int(time_string[:10][-2:]) minute = int(time_string[:12][-2:]) second = int(time_string[:14][-2:]) return year, month, day, hour, minute, second def add_0_before(str_time): if len(str_time) == 1: return '0' + str_time else: return str_time def string_to_datetime(time_string): year, month, day, hour, minute, second = extract_all_times(time_string) return datetime(year, month, day, hour, minute, second) def datetime_to_string(dt): str_second = add_0_before(str(dt.second)) str_minute = add_0_before(str(dt.minute)) str_hour = add_0_before(str(dt.hour)) str_day = add_0_before(str(dt.day)) str_month = add_0_before(str(dt.month)) str_year = add_0_before(str(dt.year)) return str_year + str_month + str_day + str_hour + str_minute + str_second def int_to_datetime(time_int): return string_to_datetime(str(time_int)) def datetime_to_int(dt): return int(datetime_to_string(dt)) def nearest_timeslot(dt, timeslot_length): td = timedelta(seconds=timeslot_length) timeslot = datetime(dt.year, dt.month, 1, 0, 0, 0) while (dt > timeslot): timeslot += td return timeslot
ae34bc98b1af2b240f325c7b2f0a0aa84adbf924
YaminiNarayanan-359/guvi
/codekata/printnearest.py
57
3.640625
4
h=int(input()) if(h%2==1): print(h-1) else: print(h)
ebdd4a56abd2702ee5a120be792b35a56fb0b340
ko9ma7/cse_project
/coding practice/Judge/1114.py
1,154
3.515625
4
''' 1114. 나무 쌓기 1 초등학교에 입학한 한기대는 격자 모양의 바닥에 나무 쌓기 놀이를 하고 있습니다. 정육면체 도형을 격자 모양에 쌓으면서 놀던 기대는 문득 바라보는 방향에 따라서 쌓인 나무의 모양이 달라 보인다는 걸 깨달았습니다. 쌓인 나무를 위에서 볼때, 오른쪽에서 볼때, 앞쪽에서 볼 때의 개수가 서로 다르다는 걸 깨달은 기대는 그 총 합을 구하고 싶어졌습니다. 한기대를 도와서 각각의 면에 보이는 나무의 개수의 총합을 구하는 프로그램을 구현해 주세요. ''' X, Y = map(int, input().split()) block = [[int(x) for x in input().split()] for y in range(Y)] top = 0 front = 0 side = 0 for y in range(Y): for x in range(X): if block[y][x] != 0: top += 1 for x in range(X): max = 0 for y in range(Y): if max < block[y][x]: max = block[y][x] front += max for y in range(Y): max = 0 for x in range(X): if max < block[y][x]: max = block[y][x] side += max print(top+front+side)
fa072e45b87e2330046453538d7c894110414ae4
ThomasBrouwer/project_euler
/problem_42.py
714
3.84375
4
import string def calc_triangle(n): return n*(n+1)/2 def calc_number(word): result = 0 for char in word: result += string.lowercase.index(char.lower())+1 return result # First we establish the longest word, and then compute the triangle 4 # numbers until that length * 26 words = open('words.txt','r').read().split("\",\"") words[0] = words[0].split("\"")[1] words[-1] = words[-1].split("\"")[0] max_triangle_value = 26 * max([len(word) for word in words]) triangle_numbers = [1] n = 2 while triangle_numbers[-1] < max_triangle_value: triangle_numbers.append(calc_triangle(n)) n += 1 no_triangles = 0 for word in words: if calc_number(word) in triangle_numbers: no_triangles += 1 print no_triangles
fdf955064f3567b583963be2126b369fca6e9120
madeibao/PythonAlgorithm
/PartB/Py两个有序数组的中位数.py
2,729
3.625
4
# nums1 = [-1,1,3,5,7,9] # nums2 = [2,4,6,8,10,12,14,16] 思路: 这道题如果时间复杂度没有限定在 O(log(m+n))O(log(m+n))O(log(m+n)),我们可以用 O(m+n)O(m+n)O(m+n) 的算法解决,用两个指针分别指向两个数组,比较指针下的元素大小,一共移动次数为 (m+n + 1)/2,便是中位数。 首先,我们理解什么中位数:指的是该数左右个数相等。 比如:odd : [1,| 2 |,3],2 就是这个数组的中位数,左右两边都只要 1 位; even: [1,| 2, 3 |,4],2,3 就是这个数组的中位数,左右两边 1 位; 那么,现在我们有两个数组: num1: [a1,a2,a3,...an] nums2: [b1,b2,b3,...bn] [nums1[:left1],nums2[:left2] | nums1[left1:], nums2[left2:]] 只要保证左右两边 个数 相同,中位数就在 | 这个边界旁边产生。 如何找边界值,我们可以用二分法,我们先确定 num1 取 m1 个数的左半边,那么 num2 取 m2 = (m+n+1)/2 - m1 的左半边,找到合适的 m1,就用二分法找。 当 [ [a1],[b1,b2,b3] | [a2,..an],[b4,...bn] ] 我们只需要比较 b3 和 a2 的关系的大小,就可以知道这种分法是不是准确的! 例如:我们令: nums1 = [-1,1,3,5,7,9] nums2 =[2,4,6,8,10,12,14,16] 当 m1 = 4,m2 = 3 ,它的中位数就是median = (num1[m1] + num2[m2])/2 时间复杂度:O(log(min(m,n)))O(log(min(m,n)))O(log(min(m,n))) 对于代码中边界情况,大家需要自己琢磨。 #============================================================================== from typing import List class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n1 = len(nums1) n2 = len(nums2) if n1 > n2: # 默认的是第一个列表比较短. return self.findMedianSortedArrays(nums2, nums1) k = (n1 + n2 + 1)//2 left = 0 right = n1 while left < right: m1 = left + (right - left)//2 m2 = k - m1 # nums1 = [-1,1,3,5,7,9] # nums2 = [2,4,6,8,10,12,14,16] # print(m1) # print(m2) if nums1[m1] < nums2[m2-1]: left = m1 + 1 else: right = m1 m1 = left m2 = k - m1 c1 = max(nums1[m1-1] if m1 > 0 else float("-inf"), nums2[m2-1] if m2 > 0 else float("-inf")) if (n1 + n2) % 2 == 1: return c1 c2 = min(nums1[m1] if m1 < n1 else float("inf"), nums2[m2] if m2 < n2 else float("inf")) return (c1 + c2) / 2 if __name__ == '__main__': s = Solution() nums1 = [-1, 1, 3, 5, 7, 9] nums2 =[2, 4, 6, 8, 10, 12, 14, 16] print(s.findMedianSortedArrays(nums1, nums2))
d53608043488ec1046245376194e78732ab2945e
pyvista/pyvista
/examples/02-plot/vector-component.py
1,303
3.625
4
""" Plot Vector Component ~~~~~~~~~~~~~~~~~~~~~ Plot a single component of a vector as a scalar array. We can plot individual components of multi-component arrays with the ``component`` argument of the ``add_mesh`` method. """ import pyvista as pv from pyvista import examples ############################################################################### # Download an example notched beam stress mesh = examples.download_notch_displacement() ############################################################################### # The default behavior with no component specified is to use the # vector magnitude. We can access each component by specifying the # component argument. dargs = dict( scalars="Nodal Displacement", cmap="jet", show_scalar_bar=False, ) pl = pv.Plotter(shape=(2, 2)) pl.subplot(0, 0) pl.add_mesh(mesh, **dargs) pl.add_text("Normalized Displacement", color='k') pl.subplot(0, 1) pl.add_mesh(mesh.copy(), component=0, **dargs) pl.add_text("X Displacement", color='k') pl.subplot(1, 0) pl.add_mesh(mesh.copy(), component=1, **dargs) pl.add_text("Y Displacement", color='k') pl.subplot(1, 1) pl.add_mesh(mesh.copy(), component=2, **dargs) pl.add_text("Z Displacement", color='k') pl.link_views() pl.camera_position = 'iso' pl.background_color = 'white' pl.show()
67f47a10fa00d30d42cf8408055a4664edc24532
bnitish101/Python-Practice
/OOPs In Python/inheritance single, multilevel, multiple.py
1,025
4.1875
4
# Type of Inheritance # 1. Single Inheritance # 2. Multiple Inheritance # 3. Multiple Inheritance class A: # Super/Parent Class def feature1(self): print('Feature One is working.') def feature2(self): print('Feature Two is working.') class B(A): # Sub/Child Class of class A [Multilevel Inheritance] def feature3(self): print('Feature Three is working.') def feature4(self): print('Feature Four is working.') class C: # Super/Parent Class def feature5(self): print('Feature Five is working.') def feature6(self): print('Feature Six is working.') class D(A, C): # Sub/Child Class of Class A and Class C [Multiple Inheritance] def feature7(self): print('Feature Seven is working.') def feature8(self): print('Feature Eight is working.') a1 = A() a1.feature1() print('Multilevel Inheritance', '\n') b1 = B() b1.feature1() b1.feature3() print('Multiple Inheritance', '\n') d1 = D() d1.feature2() d1.feature8()
b8da0b84656533024918762e17b2e2cec4469926
fabriciogonzalez06/cursos-practicas-old
/Ejemplos python/cicloFor.py
806
3.859375
4
for i in [1,2,3,4,5,6,7,8,9,10]: lista=["hola"] print("1)Agregar 2)Buscar 3)eliminar 4)Ver lista 5)Ver tamaño") opc=int(input("\n Ingrese una opción a realizar >")) if opc==1: agregar=input("\n Ingrese una cadena a agregar >") lista.extend([agregar]) print(lista) elif opc==2: buscar=input("\n Ingrese la cadena a buscar >") verificar=buscar in lista if verificar==True: print(buscar + "Si se encuentra y esta en la posición " + str(lista.index(buscar))) else: print(buscar + "No se encuentra ") elif opc==3: eliminar=input("\nIngrese la cadena a eliminar >") if eliminar in lista == True: lista.remove(eliminar) else: print("No existe el elemento") elif opc==4: print(lista[:]) elif opc==5: print("El tamaño de la lista es " + str(len(lista)))
b617c60b700d4243d79158fbe9ab8c5ddddec6d8
yunieyuna/Solutions-for-Leetcode-Problems
/python_solutions/155-min-stack.py
1,096
3.8125
4
# https://leetcode.com/problems/min-stack/ class MinStack: def __init__(self): """ initialize your data structure here. """ # 数据栈 self.data = [] # 辅助栈 self.helper = [] def push(self, x: int) -> None: self.data.append(x) if len(self.helper) == 0 or x <= self.helper[-1]: self.helper.append(x) else: self.helper.append(self.helper[-1]) def pop(self) -> None: if self.data: self.helper.pop() return self.data.pop() def top(self) -> int: if self.data: return self.data[-1] def getMin(self) -> int: if self.helper: return self.helper[-1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin() """ Runtime: 64 ms, faster than 80.96% of Python3 online submissions for Min Stack. Memory Usage: 16.5 MB, less than 85.71% of Python3 online submissions for Min Stack. """
4fe3e1725b8431e00cd05676e39c3d96ab73db3e
NecmettinCeylan/Py_Works
/0_Completed_Introduction_to_Computer_Science_and_Programming_in_Python_MIT_6.0001/10.1.py
1,008
3.6875
4
# import time # def c_to_f(c): # return c*9/5 + 32 # t0 = time.clock() # c_to_f(100000) # t1 = time.clock() - t0 # print("t = ", t, ":", t1, "s,") # linear search on unsorted list # def linear_search(L, e): # found = False # for i in range(len(L)) # if e == L[i] # found = True # return found # # linear search on sorted list # def search(L, e): # for i in range(len(L)) # if L[i] == e: # return True # if L[i] > e: # return False # return False # linear complexity def addDigits(s): val = 0 for c in s: val += int(c) return val # this nested loop O(n^2) def isSubset(L1, L2): for el in L1: matched = False for e2 im L2: if el == e2: matched = True break if not matched: return False return True #len(L1)* len(L2) and O(n^2) def intersect(L1, L2): tmp = [] for e1 in L1: for e2 in L2: if e1 == e2: tmp.append(e1) res = [] for e in tmp: if not(e in res): res.append(e) return res
e048db29d3e2fe3211048a104afef3c28c98f728
Joydata/Opteeq
/Google_vision.py
5,369
3.59375
4
import io import os import math import pandas as pd # Imports the Google Cloud client library from google.cloud import vision # Environment variable must be set before the function can be used # Terminal command : set GOOGLE_APPLICATION_CREDENTIALS=<KEY_FILE_PATH> def generate_annotations(input_file, output_file): """Procedure to generate a csv file with the output of googlevision API text detection Parameters ---------- input_file : string Path of the picture file to be annotated output_file : string Path of the output csv file Output file content ------- index : index of the box text : string the text of the given box box_x : int the x coordinate of the top left corner of the given box box_y : int the y coordinate of the top left corner of the given box box_width : int the width of the given box box_height : int the height of the given box """ # Instantiates a client client = vision.ImageAnnotatorClient() # Loads the image into memory with io.open(input_file, 'rb') as image_file: content = image_file.read() image = vision.Image(content=content) # Performs text detection on the image file response = client.text_detection(image=image) # Initialize a Dictionnary to store the results result = {'text':[],'box_x':[],'box_y':[],'box_width':[],'box_height':[]} #loop over the boxes for box in response.text_annotations: #Text content of the box text_content = box.description #Initialize the minimum and maximum coordinates of the box min_x = math.inf max_x=0 min_y = math.inf max_y=0 # Loop over the corners of the box to get the minimum and maximum coordinates of # the corners of the box for corner in box.bounding_poly.vertices: if corner.x < min_x: min_x = corner.x if corner.x > max_x: max_x = corner.x if corner.y < min_y: min_y = corner.y if corner.y > max_y: max_y = corner.y # Calculate the coordinates, width and height of the box box_width = max_x - min_x box_height = max_y - min_y box_x = min_x box_y = min_y # Store the results in the Dictionnary result['text'].append(text_content) result['box_x'].append(box_x) result['box_y'].append(box_y) result['box_width'].append(box_width) result['box_height'].append(box_height) # Store the results in the output file result_df = pd.DataFrame(result) result_df.to_csv(output_file) def convert_annotations(input_image, input_annotations, output_file): """Procedure to convert an annotation file for further import into VIA Parameters ---------- input_image : string Path of the image file input_annotations : string Path of the csv file with annotations generated with generate_annotations function output_file : string Path of the output csv file Output file ------- csv file with the right format to import in VIA """ # Load the annotations in a DataFrame annotations = pd.read_csv(input_annotations) # Initialize a Dictionnary to store the results result={'filename':[],'file_size':[],'file_attributes':[],'region_count':[],'region_id':[],'region_shape_attributes':[],'region_attributes':[]} # Prepare the file information file_size = os.path.getsize(input_image) file_attributes = '{"caption":"","public_domain":"no","image_url":""}' # Prepare the count of annotations region_count = len(annotations) # Loop over annotations for idx in annotations.index: # Get coordinates of the box X = int(annotations.iloc[idx]['box_x']) Y = int(annotations.iloc[idx]['box_y']) WIDTH = annotations.iloc[idx]['box_width'] HEIGHT = annotations.iloc[idx]['box_height'] # Get the text inside the box. New-line characters are replaced by space characters TEXT = annotations.iloc[idx]['text'].replace('\n',' ') # Prepare the region_shape attributes and region attributes region_shape_attributes = f'{{"name":"rect","x":{X},"y":{Y},"width":{WIDTH},"height":{HEIGHT}}}' region_attributes = f'{{"name":"{TEXT}","type":"unknown","image_quality":{{"good":true,"frontal":true,"good_illumination":true}}}}' # Store all information in the dictionnary result['filename'].append(input_image) result['file_size'].append(file_size) result['file_attributes'].append(file_attributes) result['region_count'].append(region_count) result['region_id'].append(idx) result['region_shape_attributes'].append(region_shape_attributes) result['region_attributes'].append(region_attributes) # Store the results in the output file result_df = pd.DataFrame(result) result_df.to_csv(output_file, header=True, index=False) # To Test of the functions, uncomment the following lines #file_name = '1193-receipt.jpg' #generate_annotations(file_name, 'annotations.csv') #convert_annotations(file_name, 'annotations.csv', 'via_csv.csv')
12360595d0f0a842be33984f347e43b1d3af01ff
tazbingor/learning-python2.7
/python-exercise/1-number-and-string/py021_multiplication_table.py
598
3.75
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/11/7 下午4:08 # @Author : Aries # @Site : # @File : py021_multiplication_table.py # @Software: PyCharm ''' for循环打印9*9乘法表,要求输出格式如下。 1 2 3 4 5 6 7 8 9 ----------------------------------- 1|1 2 3 4 5 6 7 8 9 2|2 4 6 8 10 12 14 16 18 ........ ''' print '\t1 2 3 4 5 6 7 8 9' print '-' * 40 i = 1 while i < 11: print str(i) + '|', j = 1 while j < 11: print str(i * j) + "\t", j += 1 i += 1 print
e730561d74f73604381fe9b8c9bb03520863c755
lightmen/leetcode
/python/tree/maximum-depth-of-binary-tree.py
535
3.78125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def depth(self,root,cur_h): if root is None: return cur_h += 1 if cur_h > self.max_h: self.max_h = cur_h self.depth(root.left,cur_h) self.depth(root.right,cur_h) def maxDepth(self, root): self.max_h = 0 self.depth(root,0) return self.max_h
5b510b36ac0e341283429abcb4e235a9ae9c0127
chenglinyue/Maplestory
/MapleStory.py
37,186
3.78125
4
'''Author: Cheng Lin Date: June 5th, 2012 Description: This program is a mini version of the 2D game Maplestory. It is a one player game and will be using the same images and similar sprites as the original but the game will be implemented differently overall. The game will be both keyboard and mouse controlled. The left and right arrow keys will move the player left and right, respectively. The x key will allow the user to jump and the z key will allow the user to attack. The objective of the game is to kill a bunch of monsters and to collect the gold coins that they will drop in random amounts; a NPC will be there to aid the player by restoring their HP. The game will end once all four stages are complete or when the player�s health points reach zero. ''' # I - Import and Initialize import pygame, Sprites, random pygame.init() pygame.mixer.init() screen = pygame.display.set_mode([1024, 670]) def game(cursor, gender): '''This function is the main game. It will take a cursor sprite and a gender as parameters. The gender parameter will determine the sex of the player''' # Display pygame.display.set_caption("Mini MapleStory :)") # Entities background = pygame.Surface(screen.get_size()).convert() background.fill((0,0,0)) screen.blit(background, (0,0)) #Create Sprite objects for the game boss = Sprites.BossMonster(screen) #The player will be either a male or female character depending on the #gender parameter player = Sprites.Player(screen, gender) effect = Sprites.Attack(screen) label = Sprites.Label(screen, 5000, 0, 1) npc = Sprites.NPC() maps = Sprites.Map(screen) border = Sprites.Border() #Create a text sprite that shows the changes in the amount of gold for the player tracker = Sprites.Button('',(screen.get_width()-100,30),24,(255,255,255),True) #Create a health point bar for the boss monster healthPointBar = Sprites.HPBar(screen) portal = Sprites.Portal(screen) reminder = Sprites.Reminder() #Create 8 monster sprites that will be recycled for each stage monsters = [] for i in range(8): monsters.append(Sprites.Monster(screen,random.randrange(-1,2))) #Create 8 gold sprites; one associated with each monster golds = [] for i in range(8): golds.append(Sprites.Gold(screen,False)) #Create a 9th gold sprite associated with the boss golds.append(Sprites.Gold(screen,True)) #Create multiple damage sprites damages = [] #The first 8 damage sprites will be assosiated with the 8 monsters for i in range(8): damages.append(Sprites.Damage(1)) #The 9th damage sprite will be assosiated for the boss collisions with player damages.append(Sprites.Damage(0)) #The 10th damage sprite will be assosiated monster collisions with player damages.append(Sprites.Damage(0)) #The 11th damage sprite will be player's attack on boss damages.append(Sprites.Damage(2)) # Create Sprite Groups #Group all monsters, boss, golds, npc, damages, portal and player into a #group to move them with the map mapMovementGroup = pygame.sprite.Group(monsters, player, golds, \ npc, damages, boss, portal) #Group for resetting purposes after each stage resetGroup = pygame.sprite.Group\ (healthPointBar, boss, maps, player, npc, label, monsters, portal) #Put all sprites into a group for easy updating allSprites = pygame.sprite.OrderedUpdates(maps, border, tracker, \ healthPointBar, boss,\ monsters,player, effect, damages,\ golds, label, npc, portal, reminder, cursor) # Load sound effects #Load monster sound effects monster1 = pygame.mixer.Sound('./Sound Effects/OrangeMushroomDie.wav') monster1.set_volume(0.4) monster2 = pygame.mixer.Sound('./Sound Effects/Leprechaun1Die.wav') monster2.set_volume(0.2) monster3 = pygame.mixer.Sound('./Sound Effects/JrBalrogDie.wav') monster3.set_volume(0.3) monster4 = pygame.mixer.Sound('./Sound Effects/WyvernDie.wav') monster4.set_volume(0.4) #Put the sound effects for the monster in a list for easy playing monster_sound_effects = [monster1,monster2,monster3,monster4] #Load sound effects of boss boss_sound_effects = [] for i in range(1,5): boss_sound = pygame.mixer.Sound('./Sound Effects/boss'+str(i)+'.wav') boss_sound.set_volume(1.0) #Put the sound effects of the bosses in a list for easy playing boss_sound_effects.append(boss_sound) #Load sound effect for the attack attack_sound = pygame.mixer.Sound('./Sound Effects/DarkImpaleUse.wav') attack_sound.set_volume(0.15) #Load other sound effects heal = pygame.mixer.Sound('./Sound Effects/Red Potion.wav') heal.set_volume(0.8) gold_sound = pygame.mixer.Sound('./Sound Effects/Gold.wav') gold_sound.set_volume(0.6) enter = pygame.mixer.Sound("./Sound Effects/GameIn.wav") enter.set_volume(0.5) click = pygame.mixer.Sound("./Sound Effects/MouseClick.wav") click.set_volume(0.6) mouse_over = pygame.mixer.Sound("./Sound Effects/MouseOver.wav") mouse_over.set_volume(0.4) #Load first background music pygame.mixer.music.load('./Background music/music1.mp3') pygame.mixer.music.set_volume(0.3) #Play the first background music until the next stage pygame.mixer.music.play(-1) # ACTION (broken into ALTER steps) # Assign clock = pygame.time.Clock() keepGoing = True #Create a list of False boolean values for updating Gold and damage #Sprite purposes false_list = [False] * 10 gold_list = false_list[:] attack_list = false_list[:] #Variable to keep track of whether the player is moving or not player_moving_right = False player_moving_left = False #Used for collision detection counter = 0 #Keep track of how much time has passed. time = 0 #Variable used for indexing the list of sound effects current_stage = 0 #Variable to keep track whether or not to play sound effect play_sound = True #Keep track of whether the player won or lost game_over = False winner = False # Hide the mouse pointer pygame.mouse.set_visible(False) # Loop while keepGoing: # Time clock.tick(30) # Events for event in pygame.event.get(): #Check if player quit the game if event.type == pygame.QUIT: keepGoing = False #Check if the player pressed any game keys, if so handle them accordingly elif event.type == pygame.KEYDOWN: keyName = pygame.key.name(event.key) if keyName == 'x': player.jump() if keyName == 'left': player.moving(-6) player_moving_left = True if keyName == 'right': player.moving(6) player_moving_right = True if keyName == 'z': #The following lines of code avoids the player from #spamming the attack key if effect.finish(): player.attacking(player.attack_finished()) #Animate attack effect.start(player.get_direction(),player.rect.center) #Play sound effect attack_sound.play() #Check if player entered the portal (clicked the up key) #If so, move onto the next stage if keyName == 'up' and player.rect.collidepoint(portal.rect.center): #Play sound effect enter.play() if current_stage < 3: #Move onto the next stage gold_list = false_list[:] play_sound = True current_stage += 1 #Fadeout the current background music pygame.mixer.music.fadeout(3000) #Load next background music pygame.mixer.music.load\ ('./Background music/music'+str(current_stage+1) + '.mp3') pygame.mixer.music.set_volume(0.3) #Play the new background music until the next stage pygame.mixer.music.play(-1) #Reset the HP bar, boss, map, player, npc, label, #portal and monsters for sprite in resetGroup: sprite.reset() #Reset the position of each gold for gold in golds: gold.reset((-100,-100), True) #Terminate loop when the player wins else: keepGoing = False winner = True if keyName == 'space': #If the player has enough gold, the following will occur: if label.spend_gold(): #Recover the player's HP player.recover() #Play sound effect heal.play() label.set_health_points(5000) #Show that 1000 gold was spent in exchange for recovery tracker.set_text('-1000') #Check if the player released keys on the keyboard elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: player.moving(0) player_moving_right =False if event.key == pygame.K_LEFT: player.moving(0) player_moving_left = False #Check for mouse events elif event.type == pygame.MOUSEBUTTONDOWN: #Play sound effect of mouse clicking click.play() cursor.click() #Check to see if the mouse clicked on the NPC if npc.rect.collidepoint(pygame.mouse.get_pos()): #Play sound effect mouse_over.play() #Check to see if the player has enough gold to recover HP if label.spend_gold(): #Recover the player's HP player.recover() #Play the sound effect of potion heal.play() label.set_health_points(5000) #Show that 1000 gold was spent in exchange for recovery tracker.set_text('-1000') elif event.type == pygame.MOUSEBUTTONUP: cursor.release() #Check for collisions between player and boss if player.rect.colliderect(boss.rect) and counter % 30 == 0: damages[8].update_damage(player.rect.center, player.take_boss_damage()) label.set_health_points(player.get_health_points()) #Check for collisions between player and monster #Using elif statement to avoid damaging the player twice in one frame elif pygame.sprite.spritecollide(player, monsters, False) and\ counter % 30 == 0: damages[9].update_damage(player.rect.center, player.take_damage()) label.set_health_points(player.get_health_points()) #Check for collisions between boss and attack of player if boss.rect.colliderect(effect.rect) and not attack_list[8]: damage_boss = boss.take_damage() damages[10].update_damage(boss.rect.center, damage_boss) #Avoids multiple collisions within a second attack_list[8] = True #Update Boss's HP Bar healthPointBar.take_damage(damage_boss) #Check if boss is dead (HP <= 0) if boss.get_status(): #Play sound effect while the monster is in its animation of dying boss_sound_effects[current_stage].play() #Check for collisions between attack of player and monsters #This way I can easily update other things like damage or gold because #the monster, damage and gold sprites share a common index for index in range(len(monsters)): if monsters[index].rect.colliderect(effect.rect)\ and not attack_list[index]: #Update damage damages[index].update_damage(monsters[index].get_position(), \ monsters[index].take_damage()) #Avoids multiple collisions within a second attack_list[index] = True #If the monster died, reset the position of the gold to the position #Of where the monster died if monsters[index].dead() and not gold_list[index]: #If the monster died, play sound effect monster_sound_effects[current_stage].play() #Position the gold where the monster died golds[index].reset(monsters[index].get_position(), False) #Change the item in the list of boolean variables to True #This avoids the gold from re-appearing gold_list[index] = True #Check for collisions between player and gold for index in range(len(golds)): if player.rect.colliderect(golds[index].rect): gold_sound.play() value = golds[index].get_value() #Position the gold outside of the screen once the player reaches it golds[index].reset((-100,-100), True) label.set_gold(value) #Show how much the gold was worth in the tracker tracker.set_text("+"+str(value)) # Update the reminder sprite if boss.dead(): #If the stage is clear, remind the player that they can move on reminder.show(1) #Have the portal appear in the game if play_sound: enter.play() play_sound = False #Drop gold golds[8].reset(boss.get_position(),False) portal.boss_killed() #Check how much HP the player has, if it is under 1500 remind the player #that their HP is running low elif player.get_health_points() <=1500: reminder.show(0) else: reminder.reset() #Move the map if the player reaches the centre of the screen if player.rect.centerx > screen.get_width()/2 and player_moving_right\ and not maps.move(True): #move the player, monster, golds, damages and boss in the opposite #direction if the map is moving and player are moving right for sprite in mapMovementGroup: sprite.map_moving(-6) elif player.rect.centerx < screen.get_width()/2 and player_moving_left\ and not maps.move(False): #move the player, monster, damages, gold and #boss if the map and player are moving left for sprite in mapMovementGroup: sprite.map_moving(6) #Check if player died if player.get_health_points() <= 0: keepGoing = False game_over = True #The purpose of the following lines of code is so that the monsters/boss #are not getting attacked 30 times a second, but rather every second #when the attack and monster or boss are colliding if counter % 30 == 0: attack_list = false_list[:] #Add one to counter and time counter += 1 time += 1 # Refresh screen allSprites.clear(screen, background) allSprites.update() allSprites.draw(screen) pygame.display.flip() #If the player won or lost go to hall of fame if winner: return hallOfFame(True, label.get_gold(), time/30, cursor) elif game_over: return hallOfFame(False, label.get_gold(), time/30,cursor) #Otherwise, exit the game else: return 'quit' def menu(cursor): '''This function defines a main menu screen for the game. It will take a cursor sprite as a parameter''' # Display pygame.display.set_caption("MapleStory Selection Screen") #Entities background = pygame.image.load('./Backgrounds/HomeScreen.jpg').convert() screen.blit(background,(0,0)) #Create buttons that will lead to different pages button1 = Sprites.Button('START !', (523, 172), 56, (150,150,170),False) button2 = Sprites.Button('Controls', (376, 357), 36,(150,150,170),False) button3 = Sprites.Button('About', (615, 360), 36,(150,150,170),False) button4 = Sprites.Button('Quit', (153, 403), 36, (150,150,170),False) #Put the buttons into a list for easy collision detections with the mouse buttonlist = [button1, button2,button3, button4] #Group the sprites allSprites = pygame.sprite.OrderedUpdates(buttonlist, cursor) #Load sound effect enter = pygame.mixer.Sound("./Sound Effects/GameIn.wav") enter.set_volume(0.5) click = pygame.mixer.Sound("./Sound Effects/MouseClick.wav") click.set_volume(0.6) mouse_over = pygame.mixer.Sound("./Sound Effects/MouseOver.wav") mouse_over.set_volume(0.4) page_flip = pygame.mixer.Sound("./Sound Effects/WorldSelect.wav") page_flip.set_volume(0.6) # ACTION # Assign clock = pygame.time.Clock() keepGoing = True # Hide the mouse pointer pygame.mouse.set_visible(False) # Loop while keepGoing: # Time clock.tick(30) # Events for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False elif event.type == pygame.MOUSEBUTTONDOWN: cursor.click() click.play() #If the user clicked the start button, return start to main() #To start the game if button1.rect.collidepoint(pygame.mouse.get_pos()): enter.play() return 'start' #If the user clicked the instructions button, return instructions elif button2.rect.collidepoint(pygame.mouse.get_pos()): page_flip.play() return 'instructions' #If the user clicked the about button, return about elif button3.rect.collidepoint(pygame.mouse.get_pos()): page_flip.play() return 'about' #If the user clicked the quit button, exit the loop elif button4.rect.collidepoint(pygame.mouse.get_pos()): keepGoing = False elif event.type == pygame.MOUSEBUTTONUP: cursor.release() elif event.type == pygame.MOUSEMOTION: #Highlight the button that the mouse is hovering over for index in range(len(buttonlist)): if buttonlist[index].rect.collidepoint\ (pygame.mouse.get_pos()): buttonlist[index].highlight() mouse_over.play() else: buttonlist[index].normal() #Refresh screen allSprites.clear(screen, background) allSprites.update() allSprites.draw(screen) pygame.display.flip() #Unhide mouse pointer pygame.mouse.set_visible(True) #return quit (quits the game) return 'quit' def about(cursor): '''This function creates a page for the game that provides background information about the game. It will take a cursor sprite as a parameter''' # D - Display configuration pygame.display.set_caption("About MapleStory") # E - Entities background = pygame.image.load('./Backgrounds/AboutScreen.jpg').convert() screen.blit(background, (0,0)) #Create a back_button that will lead back to the main menu of the game back_button = Sprites.Button('Back to Menu', (800,360),29,(61,61,70),False) #Group the back button and cursor sprites allSprites = pygame.sprite.Group(back_button, cursor) #Load sound effect click = pygame.mixer.Sound("./Sound Effects/MouseClick.wav") click.set_volume(0.6) mouse_over = pygame.mixer.Sound("./Sound Effects/MouseOver.wav") mouse_over.set_volume(0.4) page_flip = pygame.mixer.Sound("./Sound Effects/WorldSelect.wav") page_flip.set_volume(0.6) # A - Action (broken into ALTER steps) # A - Assign values to key variables clock = pygame.time.Clock() keepGoing = True # Hide the mouse pointer pygame.mouse.set_visible(False) # L - Loop while keepGoing: # T - Timer to set frame rate clock.tick(30) # E - Event handling for event in pygame.event.get(): #Check if the player quit the game if event.type == pygame.QUIT: keepGoing = False #Check for mouse events elif event.type == pygame.MOUSEMOTION: #If the mouse is hovering over the backbutton, change the #colour of the back button (highlight) if back_button.rect.collidepoint(pygame.mouse.get_pos()): back_button.highlight() mouse_over.play() else: #Return the colour of the text on the back button back to #normal once the mouse is no longer colliding with it back_button.normal() elif event.type == pygame.MOUSEBUTTONDOWN: cursor.click() click.play() #If the player clicked the back button, return to the menu if back_button.rect.collidepoint(pygame.mouse.get_pos()): page_flip.play() return 'menu' elif event.type == pygame.MOUSEBUTTONUP: cursor.release() # R - Refresh display allSprites.clear(screen, background) allSprites.update() allSprites.draw(screen) pygame.display.flip() #Unhide mouse pointer pygame.mouse.set_visible(True) return 'quit' def instructions(cursor): '''This function creates an instruction screen for the game. It will take a cursor sprite as a parameter.''' # Display pygame.display.set_caption("Instructions") # Entities background = pygame.image.load('./Backgrounds/InstructionScreen.jpg').convert() screen.blit(background,(0,0)) #Create a back button that leads to the menu back_button = Sprites.Button('Back to Menu', (860,580),29,(61,61,70),False) #Create a player that the user can practice with before starting the game player = Sprites.Player(screen, 1) #Group the sprites allSprites = pygame.sprite.OrderedUpdates(back_button, cursor, player) #Load sound effect click = pygame.mixer.Sound("./Sound Effects/MouseClick.wav") click.set_volume(0.6) mouse_over = pygame.mixer.Sound("./Sound Effects/MouseOver.wav") mouse_over.set_volume(0.4) page_flip = pygame.mixer.Sound("./Sound Effects/WorldSelect.wav") page_flip.set_volume(0.6) # ACTION # Assign clock = pygame.time.Clock() keepGoing = True # Hide the mouse pointer pygame.mouse.set_visible(False) # Loop while keepGoing: # Time clock.tick(30) # Events for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False #Checking if the user clicked the backbutton elif event.type == pygame.MOUSEBUTTONDOWN: cursor.click() click.play() if back_button.rect.collidepoint(pygame.mouse.get_pos()): page_flip.play() #Return to main menu return 'menu' elif event.type == pygame.MOUSEBUTTONUP: cursor.release() #Check to see if the cursor is colliding with the back button #If so, highlight the text on the button elif event.type == pygame.MOUSEMOTION: if back_button.rect.collidepoint(pygame.mouse.get_pos()): back_button.highlight() mouse_over.play() else: back_button.normal() #Change the animation of the player elif event.type == pygame.KEYDOWN: keyName = pygame.key.name(event.key) if keyName == 'x': player.jump() if keyName == 'left': player.moving(-5) if keyName == 'right': player.moving(+5) if keyName == 'z': player.attacking(True) elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: player.moving(0) if event.key == pygame.K_LEFT: player.moving(0) #Refresh screen allSprites.clear(screen, background) allSprites.update() allSprites.draw(screen) pygame.display.flip() #Unhide mouse pointer pygame.mouse.set_visible(True) return 'quit' def selection(cursor): '''This function creates a page for the game that allows the user to choose the sex of their character. It will take a cursor sprite as a parameter''' # D - Display configuration pygame.display.set_caption("Character Selection") # E - Entities background = pygame.image.load\ ('./Backgrounds/CharacterSelection.jpg').convert() screen.blit(background, (0,0)) #Load sound effects enter = pygame.mixer.Sound("./Sound Effects/AWizetWelcome.wav") enter.set_volume(0.7) click = pygame.mixer.Sound("./Sound Effects/MouseClick.wav") click.set_volume(0.6) mouse_over = pygame.mixer.Sound("./Sound Effects/MouseOver.wav") mouse_over.set_volume(0.4) #Create two buttons male_button = Sprites.Button('Male', (312,407),29,(61,61,70),False) female_button = Sprites.Button('Female', (775,408),29,(61,61,70),False) #Group the buttons and cursor sprites allSprites = pygame.sprite.Group(male_button, female_button, cursor) # A - Action (broken into ALTER steps) # A - Assign values to key variables clock = pygame.time.Clock() keepGoing = True # Hide the mouse pointer pygame.mouse.set_visible(False) # L - Loop while keepGoing: # T - Timer to set frame rate clock.tick(30) # E - Event handling for event in pygame.event.get(): #Check if the user quit the progam if event.type == pygame.QUIT: keepGoing = False #Check if the mouse is colliding with the buttons #If so highglight the text of the button elif event.type == pygame.MOUSEMOTION: if male_button.rect.collidepoint(pygame.mouse.get_pos()): male_button.highlight() mouse_over.play() else: male_button.normal() if female_button.rect.collidepoint(pygame.mouse.get_pos()): female_button.highlight() mouse_over.play() else: female_button.normal() #Check if the player clicked the buttons elif event.type == pygame.MOUSEBUTTONDOWN: cursor.click() click.play() if male_button.rect.collidepoint(pygame.mouse.get_pos()): #Fadeout music pygame.mixer.music.fadeout(8000) enter.play() #Return 2 so that the main game will know to load #The images of the male character return 2 elif female_button.rect.collidepoint(pygame.mouse.get_pos()): #Fadeout music pygame.mixer.music.fadeout(8000) enter.play() #Return 1 so that the main game will know to load #The images of the female character return 1 elif event.type == pygame.MOUSEBUTTONUP: cursor.release() # R - Refresh display allSprites.clear(screen, background) allSprites.update() allSprites.draw(screen) pygame.display.flip() #Unhide mouse pointer pygame.mouse.set_visible(True) return 'quit' def hallOfFame(winner, gold_collected, new_time, cursor): '''This function displays an end game screen. It takes a winner boolean variable, gold_collected, and new_time as parameters. It will show how much gold the player collected and how long it took for them to finish the adventure/how long they lasted. It will also take a cursor sprite as a parameter''' # D - Display configuration pygame.display.set_caption("Hall of Fame") # E - Entities background = pygame.image.load('./Backgrounds/HallofFame.jpg').convert() screen.blit(background, (0,0)) #Open and read the hall of fame file hall_of_fame = open('HallofFame.txt', 'r') fastest, most_gold = hall_of_fame.readline().strip().split() fastest = int(fastest) most_gold = int(most_gold) #Check if the player won or lost if winner: text = 'Brave explorer, thank you for saving maple Island!' text2 = 'You finished your adventure in %ds and with %d gold!' %\ (new_time, gold_collected) #If the player won, check if they set a new high score if new_time < fastest: fastest = new_time if gold_collected > most_gold: most_gold = gold_collected #Rewrite the hall of fame hall_of_fame = open('HallofFame.txt', 'w') hall_of_fame.write(str(fastest) + ' ' + str(most_gold)) hall_of_fame.close() else: text = 'Thank you for your attempt to save Maple Island.' text2 = 'You managed to collect %d gold, and survived for %ds'%\ (gold_collected,new_time) #Create labels to display the player's score label1 = Sprites.Button(text, (514,200),23,(61,61,70),False) label2 = Sprites.Button(text2, (514,250), 23, (61,61,70),False) #Display the fastest time label3 = Sprites.Button("Fastest time: %ss" % fastest,\ (514,350),26,(61,61,70),False) #Display the most gold ever collected label4 = Sprites.Button("Most gold collected: %d" % most_gold,\ (514,400), 26, (61,61,70), False) #Create buttons menu_button = Sprites.Button('Back to Menu', (824,620),29,(31,31,40),False) #Group the labels, button and cursor sprites allSprites = pygame.sprite.OrderedUpdates(menu_button, label1, \ label2, label3, label4, cursor) #Load sound effect click = pygame.mixer.Sound("./Sound Effects/MouseClick.wav") click.set_volume(0.6) mouse_over = pygame.mixer.Sound("./Sound Effects/MouseOver.wav") mouse_over.set_volume(0.4) #Play backgorund music pygame.mixer.music.load('./Background music/HallofFame.mp3') pygame.mixer.music.set_volume(0.3) #Play the first background music until the next stage pygame.mixer.music.play(-1) # A - Action (broken into ALTER steps) # A - Assign values to key variables clock = pygame.time.Clock() keepGoing = True # Hide the mouse pointer pygame.mouse.set_visible(False) # L - Loop while keepGoing: # T - Timer to set frame rate clock.tick(30) # E - Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False #Check if mouse is overlapping with the menu button #if so highlight the text elif event.type == pygame.MOUSEMOTION: if menu_button.rect.collidepoint(pygame.mouse.get_pos()): menu_button.highlight() mouse_over.play() else: menu_button.normal() #Check if the player clicked the menu button elif event.type == pygame.MOUSEBUTTONDOWN: cursor.click() click.play() #If so, return to the menu if menu_button.rect.collidepoint(pygame.mouse.get_pos()): return 'menu' elif event.type == pygame.MOUSEBUTTONUP: cursor.release() # R - Refresh display allSprites.clear(screen, background) allSprites.update() allSprites.draw(screen) pygame.display.flip() #Unhide mouse pointer pygame.mouse.set_visible(True) return 'quit' def main(): '''This function defines the 'mainline logic' for our game.''' # Create a custom cursor #The purpose of creating the cursor here is because it is used in all the #different screens of the game cursor = Sprites.Mouse() #Initialize finish to False finish = False while finish != 'quit': #Load Background Music pygame.mixer.music.load("./Background music/WelcometoMapleStory.mp3") pygame.mixer.music.set_volume(0.3) pygame.mixer.music.play(-1) #Call the main menu finish = menu(cursor) #If the user clicks the about button in the main menu, go to that page if finish == 'about': #If the user clicks the back button, return to main menu finish = about(cursor) if finish == 'menu': finish = menu(cursor) #If user clicks the controls button, go to the instructions page if finish == 'instructions': #If the user clicks the back button, return to menu finish = instructions(cursor) if finish == 'menu': finish = menu(cursor) #If the user clicked the start button, go to the selection screen if finish == 'start': #Choose the gender of their player finish = selection(cursor) if finish in [1,2]: #Pass in an integer to the main game. #The integer will be used to identify the sex of the player finish = game(cursor, finish) pygame.quit() # Call the main function main()
cf4e927ed359f1c3ac0bcc95620167773077052d
AdamZhouSE/pythonHomework
/Code/CodeRecords/2153/60870/248216.py
362
3.78125
4
num_str = input() if(num_str[0] == '-'): num_str = (num_str[1:])[::-1] for i in range(0, len(num_str) - 1): if num_str[i] is not '0': print('-' + num_str[i:]) break else: num_str = num_str[::-1] for i in range(0, len(num_str) - 1): if num_str[i] is not '0': print(num_str[i:]) break
6380f3d5afda61376b3aceffd9e382c35fa8562e
mbocaneg/Leetcode-Submissions
/88_merge_sorted_array/main.py
665
3.671875
4
class Solution: def merge(self, nums1, m, nums2, n): m -= 1 n -= 1 tail = len(nums1) - 1 while tail >= 0: if m < 0: nums1[tail] = nums2[n] n -= 1 elif n < 0: nums1[tail] = nums1[m] m -= 1 else: if nums1[m] > nums2[n]: nums1[tail] = nums1[m] m -= 1 else: nums1[tail] = nums2[n] n -= 1 tail -= 1 sol = Solution() nums1 = [1,2,10,11,0,0,0,0] nums2 = [1,5,6,12] sol.merge(nums1, 4, nums2, 4) print(nums1)
f6c5a155a4cfba766364d0487eec012aa9c99bef
mkhalil7625/capstone-week1
/greetings.py
317
4.40625
4
from datetime import date name = input("What is your name? ") birth_month=input("What month were you born in? ") print(f"Greetings, {name}") if birth_month == 'August': print("Happy birthday month!") # today = date.today() # current_month = today.month print(f"There are {len(name)} letteres in your name")
a630b0d37d77dce7f7f65ac9661211aa19dd9e8a
suvrajeet01/python
/04.26.51_1920.1080_421M/15.py
578
3.9375
4
#Return Statement #using return statement in python functions #return keyword allows the program to return information from a function #after return keyword no new code can be added too the next line as the interpreter will skip it since return breaks back out of the function #parameter is used to give information to the function and a return keyword is used to get information back from the function #using return keyword any data type be it a string, array, boolean can be returned def cube(num): return num*num*num cube(4) print(cube(4)) result = cube(4) print(result)
fc116dc7c14e3582cdeb570c15a6d1253be36299
jmmedel/Python-Reference
/11_Python_Conditions/02_Conditions.py
867
4.25
4
""" Author: Kagaya john Tutorial 10 : Conditions """ """ Elif The elif keyword is pythons way of saying "if the previous conditions were not true, then do this condition".""" a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") """ In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal".""" """ Else The else keyword catches anyting which isn't caught by the preceding conditions.""" a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") """ In this example a is greater to b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b"."""
66fbe59a2102452774343b58fd393f4525853191
ivanCodegod/guess-the-number-game
/game.py
1,096
4.03125
4
from text import * from colorama import Fore intro() # How to play low, high = None, None # tmp values attempt = 5 # Default value level = int(input(" Choose complexity of the game:\n\t1 - easy\n\t2 - medium\n\t3 - hardcore\n")) print(f'You chose the <<{level}>> level of complexity, GOOD LUCK') if level == 1: low, high = 1, 10 elif level == 2: low, high, attempt = 1, 50, 4 elif level == 3: low, high = 1, 1000 print(f'Try to guess the number between <<{low}>> and <<{high}>>\n You have only {attempt} attempt') hide_number = random_number(low, high) number = int(input()) while number != hide_number and attempt: if number > hide_number: number = int(input('Number is too high, try again: ')) attempt -= 1 if attempt: print(f'You have {attempt} more attempt') elif number < hide_number: number = int(input('Number is too low, try again: ')) attempt -= 1 if attempt: print(f'You have {attempt} more attempt') print(Fore.GREEN + f'You guess the number, good job!!!' if attempt else Fore.RED + f'You lose')
0df1decfba15bde489e1ecbc428e1d6d3ba819f4
matt-fielding8/ODI_Cricket
/src/data/gather_data.py
4,400
3.5625
4
""" All the scripts required to gather missing data from https://www.espncricinfo.com/ """ from bs4 import BeautifulSoup import requests import numpy as np def getSoup(url): ''' Returns soup for url response object. ''' r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") return soup def getMatchid(soup): ''' (html) -> list of str Return match_id as list of string from soup. ''' try: return soup.find(lambda tag: tag.name == 'a' and 'ODI no' in tag.get_text()).contents except Exception as e: print("Match ID Extraction Error\n", e, '\n', url) return ['-'] # Gather missing score data def getMissingData(url): ''' str -> dct Uses requests and bs4 libraries to extract and parse html data from url. Returns a dct with 'match_id', 'country', 'score', 'detailed_score' keys. ''' soup = getSoup(url) # Extract match_id try: match_id = soup.find(lambda tag: tag.name == 'a' and 'ODI no' in tag.get_text()).contents except Exception as e: print("Match ID Extraction Error\n", e, '\n', url) match_id = [np.NaN] print(match_id) # Extract score data from soup score = soup.find_all(class_='cscore_score') try: score_lst = [i.contents[0] for i in score] except Exception as e: print("Score Extraction Error\n", e, '\n', match_id, url) score_lst = [np.NaN]*2 # Extract country data from soup country = soup.find_all(class_='cscore_name--long') try: country_lst = [i.contents[0] for i in country] except Exception as e: print("Country Extraction\n", e, '\n', e, url) country_lst = [np.NaN]*2 # Extract detailed score data from soup ## Find tags containg "TOTAL" tot_tags = soup.find_all(lambda tag: tag.name == 'div' and \ tag.get('class')==['cell'] and tag.get_text()=='TOTAL') if len(tot_tags) == 2: try: detailed_score = [i.findNext().contents[0] for i in tot_tags] except Exception as e: print("detailed_score Extraction Error\n", e, '\n', url) detailed_score = [np.NaN]*2 else: print("No result likely", url) detailed_score = [np.NaN]*2 # Write information to dct score_dct = {'match_id':match_id*2, 'country':country_lst[:2], 'score':score_lst[:2], 'detailed_score':detailed_score} return score_dct # Get page links directing to all results per year def yearPageLinks(soup): ''' wb -> list of str Extracts relative links in "QuoteSummary" class from soup. Returns relative url's as a list of str. ''' link_list = [] try: for i in soup.find_all(class_='QuoteSummary'): link_list.append(i['href']) except: print('Class "QuoteSummary" does not exist') return link_list # Filter links based on criteria def filterLinks(links, lst): """ (list of str, list of str) -> list of str Filters elements in links which contain elements in lst as a substring. Returns filtered elements as a list. """ filt_links = ([(list(filter(lambda x: i in x, links))) for i in lst]) # Flatten filt_links list return [i for link in filt_links for i in link] # Turn relative url to absolute using prefix def absoluteUrl(prefix, relative): ''' Joins prefix with relative. Returns an absolute url. ''' prefix = prefix.rstrip('/') return [prefix + link for link in relative] # Get scorecard links def scorecardLinks(year_links, match_ids): ''' (lst of str, list of str) -> list of str Loops through year_links and returns a list of relative links for all id's in match_ids. ''' # Generate soup for all year_links soups = [getSoup(link) for link in year_links] # Retrieve all links within each soup raw_links = [soup.find_all(['tr', 'td','a'], class_=['data-link'], attrs=['href']) for soup in soups] # Extract all links associated with elements in match_ids sc_links_found = [] for year_page in raw_links: for link in year_page: if link.contents[0] in match_ids: sc_links_found.append(link['href']) return sc_links_found def flattenList(lst): ''' (lst of lst) -> lst Flattens elements of lst. ''' return [j for i in lst for j in i]
f2c1a4a31264c21388b83b973f13bae8aeb426cd
ivanmmarkovic/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
/trees/avl-tree.py
9,015
3.71875
4
class TreeNode: def __init__(self, key=None, value=None, parent=None, left=None, right=None, left_subtree_height: int = 0, right_subtree_height: int = 0, balance_factor: int = 0): self.key = key self.value = value self.parent = parent self.left = left self.right = right self.left_subtree_height: int = left_subtree_height self.right_subtree_height: int = right_subtree_height self.balance_factor : int = balance_factor def has_left_child(self) -> bool: return self.left is not None def has_right_child(self) -> bool: return self.right is not None def has_both_children(self) -> bool: return self.has_left_child() and self.has_right_child() def is_leaf(self) -> bool: return not self.has_left_child() and not self.has_right_child() def is_root(self) -> bool: return self.parent is None def has_parent(self) -> bool: return self.parent is not None def is_left_child(self) -> bool: return self.parent.left == self def is_right_child(self) -> bool: return self.parent.right == self def find_min(self): if self is None: return None if self.has_left_child(): return self.left.find_min() else: return self def find_max(self): if self is None: return None node = self while node.right is not None: node = node.right return node class AVLTree: def __init__(self): self.root: TreeNode = None self.elements: int = 0 def size(self) -> int: return self.elements def is_empty(self) -> bool: return self.root is None def put(self, key, value): if self.is_empty(): self.root = TreeNode(key, value) self.elements += 1 else: self._put(self.root, key, value) def _put(self, root: TreeNode, key, value): if root.key == key: root.value = value elif key < root.key: if root.has_left_child(): self._put(root.left, key, value) else: root.left = TreeNode(key, value, root) self.elements += 1 self._update_balance_factor(root) else: if root.has_right_child(): self._put(root.right, key, value) else: root.right = TreeNode(key, value, root) self.elements += 1 self._update_balance_factor(root) def get(self, key) -> TreeNode: if self.is_empty(): return None else: return self._get(self.root, key) def _get(self, root: TreeNode, key) -> TreeNode: if root.key == key: return root elif key < root.key: if root.has_left_child(): return self._get(root.left, key) else: return None else: if root.has_right_child(): return self._get(root.right, key) else: return None def contains(self, key) -> bool: if self.is_empty(): return None found: bool = False node: TreeNode = self.root while node is not None and not found: if node.key == key: found = True elif key < node.key: node = node.left else: node = node.right return found def delete(self, key): node_to_delete: TreeNode = self.get(key) if node_to_delete is None: return if node_to_delete.is_root(): if node_to_delete.is_leaf(): self.root = None self.elements -= 1 elif node_to_delete.has_both_children(): max_node: TreeNode = node_to_delete.left.find_max() tmp_key = max_node.key tmp_value = max_node.value self.delete(tmp_key) # keep pointer to that node, not root, root might change node_to_delete.key = tmp_key node_to_delete.value = tmp_value else: if node_to_delete.has_left_child(): self.root = node_to_delete.left else: self.root = node_to_delete.right self.root.parent = None self.elements -= 1 else: parent: TreeNode = None if node_to_delete.is_leaf(): parent = node_to_delete.parent if node_to_delete.is_left_child(): node_to_delete.parent.left = None else: node_to_delete.parent.right = None self.elements -= 1 elif node_to_delete.has_both_children(): max_node: TreeNode = node_to_delete.left.find_max() tmp_key = max_node.key tmp_value = max_node.value self.delete(tmp_key) node_to_delete.key = tmp_key node_to_delete.value = tmp_value elif node_to_delete.has_left_child(): parent = node_to_delete.parent self.elements -= 1 if node_to_delete.is_left_child(): node_to_delete.parent.left = node_to_delete.left else: node_to_delete.parent.right = node_to_delete.left node_to_delete.left.parent = node_to_delete.parent else: parent = node_to_delete.parent self.elements -= 1 if node_to_delete.is_left_child(): node_to_delete.parent.left = node_to_delete.right else: node_to_delete.parent.right = node_to_delete.right node_to_delete.right.parent = node_to_delete.parent if parent is not None: self._update_balance_factor(parent) def find_min(self) -> TreeNode: if self.is_empty(): return None node: TreeNode = self.root while node.left is not None: node = node.left return node def find_max(self) -> TreeNode: if self.is_empty(): return None node: TreeNode = self.root while node.right is not None: node = node.right return node def _update_balance_factor(self, root: TreeNode): old_balance_factor: int = root.balance_factor if root.has_left_child(): root.left_subtree_height = max(root.left.left_subtree_height, root.left.right_subtree_height) + 1 else: root.left_subtree_height = 0 if root.has_right_child(): root.right_subtree_height = max(root.right.left_subtree_height, root.right.right_subtree_height) + 1 else: root.right_subtree_height = 0 root.balance_factor = root.left_subtree_height - root.right_subtree_height if root.balance_factor < -1 or root.balance_factor > 1: self._rebalance(root) return if root.balance_factor != old_balance_factor and root.has_parent(): self._update(root.parent) def _rebalance(self, root: TreeNode): if root.balance_factor < 0: if root.right.balance_factor > 0: self._rotate_right(root.right) else: self._rotate_left(root) else: if root.left.balance_factor < 0: self._rotate_left(root.left) else: self._rotate_right(root) def _rotate_left(self, root: TreeNode): old_root: TreeNode = root new_root: TreeNode = old_root.right old_root.right = new_root.left if new_root.has_left_child(): new_root.left.parent = old_root new_root.parent = old_root.parent if old_root.has_parent(): if old_root.is_left_child(): old_root.parent.left = new_root else: old_root.parent.right = new_root else: self.root = new_root old_root.parent = new_root new_root.left = old_root self._update_balance_factor(old_root) def _rotate_right(self, root: TreeNode): old_root: TreeNode = root new_root: TreeNode = old_root.left old_root.left = new_root.right if new_root.has_right_child(): new_root.right.parent = old_root new_root.parent = old_root.parent if old_root.has_parent(): if old_root.is_left_child(): old_root.parent.left = new_root else: old_root.parent.right = new_root else: self.root = new_root old_root.parent = new_root new_root.right = old_root self._update_balance_factor(old_root)
8c3384bc99b200394f11505904f39b2b8c4ea60f
ILiterallyCannot/script-programming
/script-programming/task9.py
279
4
4
list1 = [1,2,3,5,4] #the function should return 5 list2 = [1,4,9,2] #the function should return 9 def listmax(numList): theMax = 0 for i in numList: if i > theMax: theMax = i return theMax print(listmax(list1)) print(listmax(list2))
a9a79c5f2036fa97ff964241b14e9015f522446e
MinasMayth/BitsandBobs
/Maze Game.py
1,089
4.34375
4
# program written by Sue Sentance import time def main(): print("You are trying to find your way through a maze to the centre where ") print("there is a pot of gold!") print("What you don't know is that this is a dangerous maze with traps and hazards.") print() print("Starting maze game ...") print() print("You enter the maze...") time.sleep(2) # time.sleep is just used to build up the suspense! print("You reach a opening in the wall and go through it...") print() time.sleep(2) print("You can go left (L) or right (R)") answer = input("Make your choice ... ").upper() print("You chose",answer,"... what will happen? ...") time.sleep(2) print("You turn the corner...") time.sleep(2) print("You walk forward a few steps...") time.sleep(2) if answer == "R": print("...and fall down a trap door and are never seen again....") else: print("...and see a beautiful grassy path lined with trees with a pot of gold at the end!") print (main()) # end of program