blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
877d9bf193fb488b296ba3666df992ea33bc3dff
as030pc/MisionTIC
/Fundamentos de Programacion - Python/Semana 3_Subprogramas, vectores, POO/metodos.py
3,240
3.59375
4
def esVacio(vec): return vec.V[0] == 0 def esLleno(vec): return vec.V[0] == vec.n def tamagno(vec): return vec.n #agregar un dato(d) al final del Vector. Si esta lleno no agrega el dato def agregarDato(vec, d): if esLleno(vec): return vec.V[0] = vec.V[0] + 1 vec.V[vec.V[0]] = d #asigna un dato (d) en la posición (i). Debe haber un dato en el vector para remplazarlo # def asignaDato(self, d, i): # self.V[i] = d #Retorna un dato dado su indice i # def retornaDato(self, i): # return self.V[i] #intercambia 2 datos. a y b son indices. def intercambiar(vec, a, b): aux = vec.V[a] vec.V[a] = vec.V[b] vec.V[b] = aux #suma los datos de los elementos vector. Retorna la suma def sumarDatos(vec): s = 0 for i in range(1, vec.V[0] + 1): s = s + vec.V[i] return s #ordena el vector de forma descendente. 10,9,8,7... def burbuja(vec): for i in range(1, vec.V[0]): for j in range(1, vec.V[0] - i + 1): if vec.V[j] < vec.V[j + 1]: intercambiar(vec,j, j + 1) #ordena el vector de forma ascendente 1,2,3,4... def seleccion(vec): for i in range(1, vec.V[0]): k = i for j in range(i + 1, vec.V[0] + 1): if vec.V[j] < vec.V[k]: k = j intercambiar(vec,k, i) #retorna el indice del dato mayor, primera ocurrencia def mayor(vec): mayor = 1 for i in range(1, vec.V[0] + 1): if vec.V[i] > vec.V[mayor]: mayor = i return mayor #retorna el indice del mayor, si hay repetidos la ultima ocurrencia def mayorult(vec): mayor = 1 for i in range(1, vec.V[0] + 1): if vec.V[i] >= vec.V[mayor]: mayor = i return mayor #retorna el menor (probar bien) def menor(vec): menor = 1 for i in range(1, vec.V[0] + 1): if vec.V[i] < vec.V[menor]: menor = i return menor #busca un dato(d) y retorna el indice donde esta def buscarDato(vec, d): i = 1 while i <= vec.V[0] and vec.V[i] != d: i = i + 1 if i <= vec.V[0]: return i return -1 #busca donde insertar(d). retorna el indice donde insertar. def buscarDondeInsertar(vec, d): i = 1 while i <= vec.V[0] and vec.V[i] < d: i = i + 1 return i #inserta el dato (d) en posicion i del vector. Debe haber espacio para insertar.#si esta lleno no inserta #si no envía (i), inserta el dato ordenado. El vector debe estar ordenado con algoritmo Seleccion() def insertar(vec, d, i=0): if esLleno(vec): print("\nVector lleno, no se puede insertar") return if i == 0: i = buscarDondeInsertar(vec,d) for j in range(vec.V[0], i - 1, -1): vec.V[j + 1] = vec.V[j] vec.V[i] = d vec.V[0] = vec.V[0] +1 #borra dato en posición dada def borrarDatoEnPosicion(vec, i): if i <= 0 or i > vec.V[0]: print("\nParámetro i inválido") return for j in range(i, vec.V[0]): vec.V[j] = vec.V[j + 1] vec.V[0] = vec.V[0] - 1 #borra dato(d). Si existe lo borra def borrarDato(vec, d): i = buscarDato(vec,d) if i != -1: borrarDatoEnPosicion(vec,i)
fe92f37793f6407b778248e8db66a1d5c17ccaf9
RAMMVIER/Data-Structures-and-Algorithms-in-Python
/Algorithm/2.Binary_search.py
746
3.75
4
# 二分查找:从有序列表的初始候选区list[0:n-1]开始,通过对待查找的值与候选区中间值的比较,使候选区减小一半 # 时间复杂度:O(logn) def binary_search(li, val): left = 0 right = len(li) - 1 while left <= right: # 候选区有值 mid = (left + right) // 2 # 整除用于取整数部分作为下标 if li[mid] == val: return mid elif li[mid] > val: # 待查找的值在mid左侧 right = mid - 1 else: # 待查找的值在mid右侧 left = mid + 1 else: return None # test test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(binary_search(test_list, 7))
a611c802f71433b930f372d61e7ef5a13bbe1b77
J-Chaudhary/dataStructureAndAlgo
/linklist.py
1,305
3.953125
4
# Student : Jignesh Chaudhary, Student id : 197320 # Assignment - 1 (d) import Queue import Stack def main(): linklist = Queue.Queue() def add(): data = input("enter data in to queue: ") linklist.EnQueue(data) def remore(): linklist.DeQueue() def display(): linklist.display() def len(): linklist.size() def rev_display(): temp = Stack.Stack() while not linklist.isEmpty(): data = linklist.DeQueue() temp.push(data) tmpQ = Queue.Queue() while not temp.isEmpty(): x = temp.pop() tmpQ.EnQueue(x) return tmpQ print("===========================================================") print("1 : Entry, 2: display original, 3: display reverse, 4: exit") print("===========================================================") print("") while True: com = input ("Enter command: ") if com == str(1): add() elif com == str(2): display() elif com == str(3): output = rev_display() print(output.display()) elif com == str(4): print ("Thank You for Using Testing Queue ADT") break main()
519f15f55c8272cf53a7b46d67ff5ab661599f82
gabriellaec/desoft-analise-exercicios
/backup/user_305/ch21_2019_03_15_16_02_56_907198.py
101
3.6875
4
a = int(input('Valor da conta:')) a = a * 1.10 print ('Valor da conta com 10%: R$ {0:.2f}'.format(a))
3ff2382ff7f3e14d8f61cac3961734613b6ceb9b
edureimberg/learning_python
/exercicios/ex6.py
257
3.859375
4
print("Programa para calcular o tempo de viagem") distancia = int(input("Digite a distancia a ser percorrida (KM):")) velocidade = int(input("Digite a velocidade do veículo (KM/H):")) print("O tempo da viagem é:", (distancia * 1) / velocidade, "horas")
0ff92bbd8fe1ffb415694ed2ec478b8a0e6a9a79
shoyer/xarray
/xarray/plot/facetgrid.py
21,632
3.765625
4
import functools import itertools import warnings import numpy as np from ..core.formatting import format_item from .utils import ( _infer_xy_labels, _process_cmap_cbar_kwargs, import_matplotlib_pyplot, label_from_attrs, ) # Overrides axes.labelsize, xtick.major.size, ytick.major.size # from mpl.rcParams _FONTSIZE = "small" # For major ticks on x, y axes _NTICKS = 5 def _nicetitle(coord, value, maxchar, template): """ Put coord, value in template and truncate at maxchar """ prettyvalue = format_item(value, quote_strings=False) title = template.format(coord=coord, value=prettyvalue) if len(title) > maxchar: title = title[: (maxchar - 3)] + "..." return title class FacetGrid: """ Initialize the matplotlib figure and FacetGrid object. The :class:`FacetGrid` is an object that links a xarray DataArray to a matplotlib figure with a particular structure. In particular, :class:`FacetGrid` is used to draw plots with multiple Axes where each Axes shows the same relationship conditioned on different levels of some dimension. It's possible to condition on up to two variables by assigning variables to the rows and columns of the grid. The general approach to plotting here is called "small multiples", where the same kind of plot is repeated multiple times, and the specific use of small multiples to display the same relationship conditioned on one ore more other variables is often called a "trellis plot". The basic workflow is to initialize the :class:`FacetGrid` object with the DataArray and the variable names that are used to structure the grid. Then plotting functions can be applied to each subset by calling :meth:`FacetGrid.map_dataarray` or :meth:`FacetGrid.map`. Attributes ---------- axes : numpy object array Contains axes in corresponding position, as returned from plt.subplots col_labels : list list of :class:`matplotlib.text.Text` instances corresponding to column titles. row_labels : list list of :class:`matplotlib.text.Text` instances corresponding to row titles. fig : matplotlib.Figure The figure containing all the axes name_dicts : numpy object array Contains dictionaries mapping coordinate names to values. None is used as a sentinel value for axes which should remain empty, ie. sometimes the bottom right grid """ def __init__( self, data, col=None, row=None, col_wrap=None, sharex=True, sharey=True, figsize=None, aspect=1, size=3, subplot_kws=None, ): """ Parameters ---------- data : DataArray xarray DataArray to be plotted row, col : strings Dimesion names that define subsets of the data, which will be drawn on separate facets in the grid. col_wrap : int, optional "Wrap" the column variable at this width, so that the column facets sharex : bool, optional If true, the facets will share x axes sharey : bool, optional If true, the facets will share y axes figsize : tuple, optional A tuple (width, height) of the figure in inches. If set, overrides ``size`` and ``aspect``. aspect : scalar, optional Aspect ratio of each facet, so that ``aspect * size`` gives the width of each facet in inches size : scalar, optional Height (in inches) of each facet. See also: ``aspect`` subplot_kws : dict, optional Dictionary of keyword arguments for matplotlib subplots """ plt = import_matplotlib_pyplot() # Handle corner case of nonunique coordinates rep_col = col is not None and not data[col].to_index().is_unique rep_row = row is not None and not data[row].to_index().is_unique if rep_col or rep_row: raise ValueError( "Coordinates used for faceting cannot " "contain repeated (nonunique) values." ) # single_group is the grouping variable, if there is exactly one if col and row: single_group = False nrow = len(data[row]) ncol = len(data[col]) nfacet = nrow * ncol if col_wrap is not None: warnings.warn("Ignoring col_wrap since both col and row " "were passed") elif row and not col: single_group = row elif not row and col: single_group = col else: raise ValueError("Pass a coordinate name as an argument for row or col") # Compute grid shape if single_group: nfacet = len(data[single_group]) if col: # idea - could add heuristic for nice shapes like 3x4 ncol = nfacet if row: ncol = 1 if col_wrap is not None: # Overrides previous settings ncol = col_wrap nrow = int(np.ceil(nfacet / ncol)) # Set the subplot kwargs subplot_kws = {} if subplot_kws is None else subplot_kws if figsize is None: # Calculate the base figure size with extra horizontal space for a # colorbar cbar_space = 1 figsize = (ncol * size * aspect + cbar_space, nrow * size) fig, axes = plt.subplots( nrow, ncol, sharex=sharex, sharey=sharey, squeeze=False, figsize=figsize, subplot_kw=subplot_kws, ) # Set up the lists of names for the row and column facet variables col_names = list(data[col].values) if col else [] row_names = list(data[row].values) if row else [] if single_group: full = [{single_group: x} for x in data[single_group].values] empty = [None for x in range(nrow * ncol - len(full))] name_dicts = full + empty else: rowcols = itertools.product(row_names, col_names) name_dicts = [{row: r, col: c} for r, c in rowcols] name_dicts = np.array(name_dicts).reshape(nrow, ncol) # Set up the class attributes # --------------------------- # First the public API self.data = data self.name_dicts = name_dicts self.fig = fig self.axes = axes self.row_names = row_names self.col_names = col_names self.figlegend = None # Next the private variables self._single_group = single_group self._nrow = nrow self._row_var = row self._ncol = ncol self._col_var = col self._col_wrap = col_wrap self.row_labels = [None] * nrow self.col_labels = [None] * ncol self._x_var = None self._y_var = None self._cmap_extend = None self._mappables = [] self._finalized = False @property def _left_axes(self): return self.axes[:, 0] @property def _bottom_axes(self): return self.axes[-1, :] def map_dataarray(self, func, x, y, **kwargs): """ Apply a plotting function to a 2d facet's subset of the data. This is more convenient and less general than ``FacetGrid.map`` Parameters ---------- func : callable A plotting function with the same signature as a 2d xarray plotting method such as `xarray.plot.imshow` x, y : string Names of the coordinates to plot on x, y axes kwargs : additional keyword arguments to func Returns ------- self : FacetGrid object """ if kwargs.get("cbar_ax", None) is not None: raise ValueError("cbar_ax not supported by FacetGrid.") cmap_params, cbar_kwargs = _process_cmap_cbar_kwargs( func, self.data.values, **kwargs ) self._cmap_extend = cmap_params.get("extend") # Order is important func_kwargs = { k: v for k, v in kwargs.items() if k not in {"cmap", "colors", "cbar_kwargs", "levels"} } func_kwargs.update(cmap_params) func_kwargs.update({"add_colorbar": False, "add_labels": False}) # Get x, y labels for the first subplot x, y = _infer_xy_labels( darray=self.data.loc[self.name_dicts.flat[0]], x=x, y=y, imshow=func.__name__ == "imshow", rgb=kwargs.get("rgb", None), ) for d, ax in zip(self.name_dicts.flat, self.axes.flat): # None is the sentinel value if d is not None: subset = self.data.loc[d] mappable = func( subset, x=x, y=y, ax=ax, **func_kwargs, _is_facetgrid=True ) self._mappables.append(mappable) self._finalize_grid(x, y) if kwargs.get("add_colorbar", True): self.add_colorbar(**cbar_kwargs) return self def map_dataarray_line( self, func, x, y, hue, add_legend=True, _labels=None, **kwargs ): from .plot import _infer_line_data for d, ax in zip(self.name_dicts.flat, self.axes.flat): # None is the sentinel value if d is not None: subset = self.data.loc[d] mappable = func( subset, x=x, y=y, ax=ax, hue=hue, add_legend=False, _labels=False, **kwargs, ) self._mappables.append(mappable) _, _, hueplt, xlabel, ylabel, huelabel = _infer_line_data( darray=self.data.loc[self.name_dicts.flat[0]], x=x, y=y, hue=hue ) self._hue_var = hueplt self._hue_label = huelabel self._finalize_grid(xlabel, ylabel) if add_legend and hueplt is not None and huelabel is not None: self.add_legend() return self def map_dataset( self, func, x=None, y=None, hue=None, hue_style=None, add_guide=None, **kwargs ): from .dataset_plot import _infer_meta_data, _parse_size kwargs["add_guide"] = False kwargs["_is_facetgrid"] = True if kwargs.get("markersize", None): kwargs["size_mapping"] = _parse_size( self.data[kwargs["markersize"]], kwargs.pop("size_norm", None) ) meta_data = _infer_meta_data(self.data, x, y, hue, hue_style, add_guide) kwargs["meta_data"] = meta_data if hue and meta_data["hue_style"] == "continuous": cmap_params, cbar_kwargs = _process_cmap_cbar_kwargs( func, self.data[hue].values, **kwargs ) kwargs["meta_data"]["cmap_params"] = cmap_params kwargs["meta_data"]["cbar_kwargs"] = cbar_kwargs for d, ax in zip(self.name_dicts.flat, self.axes.flat): # None is the sentinel value if d is not None: subset = self.data.loc[d] maybe_mappable = func( ds=subset, x=x, y=y, hue=hue, hue_style=hue_style, ax=ax, **kwargs ) # TODO: this is needed to get legends to work. # but maybe_mappable is a list in that case :/ self._mappables.append(maybe_mappable) self._finalize_grid(meta_data["xlabel"], meta_data["ylabel"]) if hue: self._hue_label = meta_data.pop("hue_label", None) if meta_data["add_legend"]: self._hue_var = meta_data["hue"] self.add_legend() elif meta_data["add_colorbar"]: self.add_colorbar(label=self._hue_label, **cbar_kwargs) return self def _finalize_grid(self, *axlabels): """Finalize the annotations and layout.""" if not self._finalized: self.set_axis_labels(*axlabels) self.set_titles() self.fig.tight_layout() for ax, namedict in zip(self.axes.flat, self.name_dicts.flat): if namedict is None: ax.set_visible(False) self._finalized = True def add_legend(self, **kwargs): figlegend = self.fig.legend( handles=self._mappables[-1], labels=list(self._hue_var.values), title=self._hue_label, loc="center right", **kwargs, ) self.figlegend = figlegend # Draw the plot to set the bounding boxes correctly self.fig.draw(self.fig.canvas.get_renderer()) # Calculate and set the new width of the figure so the legend fits legend_width = figlegend.get_window_extent().width / self.fig.dpi figure_width = self.fig.get_figwidth() self.fig.set_figwidth(figure_width + legend_width) # Draw the plot again to get the new transformations self.fig.draw(self.fig.canvas.get_renderer()) # Now calculate how much space we need on the right side legend_width = figlegend.get_window_extent().width / self.fig.dpi space_needed = legend_width / (figure_width + legend_width) + 0.02 # margin = .01 # _space_needed = margin + space_needed right = 1 - space_needed # Place the subplot axes to give space for the legend self.fig.subplots_adjust(right=right) def add_colorbar(self, **kwargs): """Draw a colorbar """ kwargs = kwargs.copy() if self._cmap_extend is not None: kwargs.setdefault("extend", self._cmap_extend) if "label" not in kwargs: kwargs.setdefault("label", label_from_attrs(self.data)) self.cbar = self.fig.colorbar( self._mappables[-1], ax=list(self.axes.flat), **kwargs ) return self def set_axis_labels(self, x_var=None, y_var=None): """Set axis labels on the left column and bottom row of the grid.""" if x_var is not None: if x_var in self.data.coords: self._x_var = x_var self.set_xlabels(label_from_attrs(self.data[x_var])) else: # x_var is a string self.set_xlabels(x_var) if y_var is not None: if y_var in self.data.coords: self._y_var = y_var self.set_ylabels(label_from_attrs(self.data[y_var])) else: self.set_ylabels(y_var) return self def set_xlabels(self, label=None, **kwargs): """Label the x axis on the bottom row of the grid.""" if label is None: label = label_from_attrs(self.data[self._x_var]) for ax in self._bottom_axes: ax.set_xlabel(label, **kwargs) return self def set_ylabels(self, label=None, **kwargs): """Label the y axis on the left column of the grid.""" if label is None: label = label_from_attrs(self.data[self._y_var]) for ax in self._left_axes: ax.set_ylabel(label, **kwargs) return self def set_titles(self, template="{coord} = {value}", maxchar=30, size=None, **kwargs): """ Draw titles either above each facet or on the grid margins. Parameters ---------- template : string Template for plot titles containing {coord} and {value} maxchar : int Truncate titles at maxchar kwargs : keyword args additional arguments to matplotlib.text Returns ------- self: FacetGrid object """ import matplotlib as mpl if size is None: size = mpl.rcParams["axes.labelsize"] nicetitle = functools.partial(_nicetitle, maxchar=maxchar, template=template) if self._single_group: for d, ax in zip(self.name_dicts.flat, self.axes.flat): # Only label the ones with data if d is not None: coord, value = list(d.items()).pop() title = nicetitle(coord, value, maxchar=maxchar) ax.set_title(title, size=size, **kwargs) else: # The row titles on the right edge of the grid for index, (ax, row_name, handle) in enumerate( zip(self.axes[:, -1], self.row_names, self.row_labels) ): title = nicetitle(coord=self._row_var, value=row_name, maxchar=maxchar) if not handle: self.row_labels[index] = ax.annotate( title, xy=(1.02, 0.5), xycoords="axes fraction", rotation=270, ha="left", va="center", **kwargs, ) else: handle.set_text(title) # The column titles on the top row for index, (ax, col_name, handle) in enumerate( zip(self.axes[0, :], self.col_names, self.col_labels) ): title = nicetitle(coord=self._col_var, value=col_name, maxchar=maxchar) if not handle: self.col_labels[index] = ax.set_title(title, size=size, **kwargs) else: handle.set_text(title) return self def set_ticks(self, max_xticks=_NTICKS, max_yticks=_NTICKS, fontsize=_FONTSIZE): """ Set and control tick behavior Parameters ---------- max_xticks, max_yticks : int, optional Maximum number of labeled ticks to plot on x, y axes fontsize : string or int Font size as used by matplotlib text Returns ------- self : FacetGrid object """ from matplotlib.ticker import MaxNLocator # Both are necessary x_major_locator = MaxNLocator(nbins=max_xticks) y_major_locator = MaxNLocator(nbins=max_yticks) for ax in self.axes.flat: ax.xaxis.set_major_locator(x_major_locator) ax.yaxis.set_major_locator(y_major_locator) for tick in itertools.chain( ax.xaxis.get_major_ticks(), ax.yaxis.get_major_ticks() ): tick.label1.set_fontsize(fontsize) return self def map(self, func, *args, **kwargs): """ Apply a plotting function to each facet's subset of the data. Parameters ---------- func : callable A plotting function that takes data and keyword arguments. It must plot to the currently active matplotlib Axes and take a `color` keyword argument. If faceting on the `hue` dimension, it must also take a `label` keyword argument. args : strings Column names in self.data that identify variables with data to plot. The data for each variable is passed to `func` in the order the variables are specified in the call. kwargs : keyword arguments All keyword arguments are passed to the plotting function. Returns ------- self : FacetGrid object """ plt = import_matplotlib_pyplot() for ax, namedict in zip(self.axes.flat, self.name_dicts.flat): if namedict is not None: data = self.data.loc[namedict] plt.sca(ax) innerargs = [data[a].values for a in args] maybe_mappable = func(*innerargs, **kwargs) # TODO: better way to verify that an artist is mappable? # https://stackoverflow.com/questions/33023036/is-it-possible-to-detect-if-a-matplotlib-artist-is-a-mappable-suitable-for-use-w#33023522 if maybe_mappable and hasattr(maybe_mappable, "autoscale_None"): self._mappables.append(maybe_mappable) self._finalize_grid(*args[:2]) return self def _easy_facetgrid( data, plotfunc, kind, x=None, y=None, row=None, col=None, col_wrap=None, sharex=True, sharey=True, aspect=None, size=None, subplot_kws=None, ax=None, figsize=None, **kwargs, ): """ Convenience method to call xarray.plot.FacetGrid from 2d plotting methods kwargs are the arguments to 2d plotting method """ if ax is not None: raise ValueError("Can't use axes when making faceted plots.") if aspect is None: aspect = 1 if size is None: size = 3 elif figsize is not None: raise ValueError("cannot provide both `figsize` and `size` arguments") g = FacetGrid( data=data, col=col, row=row, col_wrap=col_wrap, sharex=sharex, sharey=sharey, figsize=figsize, aspect=aspect, size=size, subplot_kws=subplot_kws, ) if kind == "line": return g.map_dataarray_line(plotfunc, x, y, **kwargs) if kind == "dataarray": return g.map_dataarray(plotfunc, x, y, **kwargs) if kind == "dataset": return g.map_dataset(plotfunc, x, y, **kwargs)
9b7762f5ddc1112ac2ef653904d73be0875062e9
hason123/ironman
/Session 7/Part 2/dash.py
247
3.765625
4
colors = ["blue" , "green","red","yellow"] from turtle import * shape("turtle") speed(1) color(colors[0]) forward(100) color(colors[1]) forward(100) color(colors[2]) forward(100) color(colors[3]) forward(100) mainloop()
20acfe1723b3ac2f1ad04c8f5f1f19a7a32e3332
ZacByrnes/CP1404_Practical
/prac_02/files.py
609
3.96875
4
""" Ask User for Name """ #Start Name = input("What is your name? ") OUTPUT_FILE = Name out_file = open("name.txt", "w") print("Your name is ", file=out_file) out_file.close() #Second Part in_file = open('name.txt', "r") name = in_file.read() print("Your name is", name) in_file.close() #Getting Numbers from a document and adding them together in_file = open('numbers.txt') Number_1 = int(in_file.readline()) Number_2 = int(in_file.readline()) Sum_Of_Num = Number_1 + Number_2 print(Sum_Of_Num) in_file.close() #Helpful Source https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
ef02d189b3c726c0014f476c8fd95aa38d7b9ea5
zxcvbnm123xy/leon_python
/python1808real/day21/day21-2-thread.py
4,237
3.625
4
# 二、线程 # 线程的概念:进程中的基本执行单元。 # 已学过创建线程的方式: #(1) 使用init方法创建线程对象,指定target和args #(2)继承Thread,重写run方法 from threading import Thread #使用Thread完成案例 # IO密集型 10.5s # 计算密集型 1.7s import time def sum(a,b): s=0 for i in range(a,b): s+=i time.sleep(0.5) return s # def sum_1(b1,b2): # t1=Thread(target=sum,args=(0,b1)) # t2=Thread(target=sum,args=(0,b2)) # t1.start() # t2.start() # t1.join() # t2.join() # # if __name__=="__main__": # start = time.time() # sum_1(10000000,20000000) # # sum_1(10,20) # end=time.time() # print("执行的时间{}".format(end - start)) # 1. 使用from multiprocessing.pool import ThreadPool 创建线程 # 进程模块下的线程池,创建方式几乎跟进程池一致 from multiprocessing.pool import ThreadPool # def work(index): # print("第{}任务执行".format(index)) # time.sleep(0.5) # return index # # pool=ThreadPool(5) # for i in range(10): # pool.apply_async(work,args=(i,)) # # print("任务{}执行完毕".format(i)) # pool.close() # pool.join() # 改写之前的案例 # 计算密集型:1.91 # io密集型:10.5 # def sum_2(b1,b2): # pool = ThreadPool(5) # for i in [b1,b2]: # pool.apply_async(sum, args=(0,i)) # pool.close() # pool.join() # if __name__=="__main__": # start=time.time() # # sum_2(10000000,20000000) # sum_2(10,20) # end=time.time() # print("执行的时间{}".format(end - start)) #2. 使用threadpool模块实现线程对象(选讲) # 进程下的线程池直接apply或者applyasync实现线程对象,一次加入一个任务 # threadpool # 任务加入使用putRequest,在此之前需要使用makeRequests形成任务列表。 """ (1)定义线程函数,创建线程池 (2)创建需要线程池处理的任务列表,makeRequest (3)将创建的多个任务put到线程池中,等待cpu分配时间片执行 (4)希望所有任务执行完毕再操作threadpool.wait() """ import threadpool # def work(index): # print("任务{}正在执行".format(index)) # time.sleep(0.5) # return index # # if __name__=="__main__": # pool=threadpool.ThreadPool(5) # # #形成任务列表:threadpool.makeRequests(func,args_list) # # 参数 func:要使用多线程执行的任务,args_list=函数的参数列表 # """ # 如果是单参数,则直接传入多个线程的参数[序列]即可 # 如果是多参数,[((参数1,参数2...),(关键字参数1,关键字参数2)),(),()....] # 要求如果没有对应的参数(位置、关键字),需要None占位 # """ # requests=threadpool.makeRequests(work,args_list=range(10)) # # 将多个任务put到线程池中,需要一个一个put4 # for r in requests: # pool.putRequest(r) # # # 使用wait保证子线程全部在主程序执行完毕之前执行 # pool.wait() # print("主程序执行完毕") # 应用到案例上 # IO密集型:10.6s # 计算密集型:1.74s def sum_3(b1,b2): pool=threadpool.ThreadPool(5) arglist=[((0,b1),None),((0,b2),None)] requests=threadpool.makeRequests(sum,args_list=arglist) for r in requests: pool.putRequest(r) pool.wait() # if __name__=="__main__": # start=time.time() # sum_3(10000000,20000000) # # sum_3(10,20) # end=time.time() # print("执行的时间{}".format(end - start)) # 3.使用concurrent.futures模块下ThreadPoolExecutor创建线程 # 跟进程基本一致 # 计算密集型:1.73s # io密集型:10s from concurrent.futures import ThreadPoolExecutor,as_completed def sum_4(b1,b2): with ThreadPoolExecutor(max_workers=4) as executor: tasks=[executor.submit(sum,x,y) for x,y in [(0,b1),(0,b2)]] for i in as_completed((tasks)): print(i.result()) # results = executor.map(sum, (0, 0), (b1, b2)) # for i in results: # print(i) if __name__=="__main__": start=time.time() # sum_4(10000000,20000000) sum_4(10,20) end=time.time() print("执行的时间{}".format(end - start))
b13eca10427613fd50504e438f6ab566466f0600
MaLei666/practice
/剑指Offer/数组_哈希/04-二维数组中的查找.py
1,322
3.515625
4
# -*- coding:utf-8 -*- # @author : MaLei # @datetime : 2021/2/18 9:38 下午 # @file : 04-二维数组中的查找.py # @software : PyCharm ''' 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 示例: 现有矩阵 matrix 如下: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] 给定 target = 5,返回 true。 给定 target = 20,返回 false。 限制: 0 <= n <= 1000 0 <= m <= 1000 ''' a = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24] ] # 二叉树法,旋转45度 class Solution: def findNumberIn2DArray(self, matrix: list, target: int) -> bool: if not matrix: return False i = len(matrix[0]) - 1 j = 0 while i >= 0 and j < len(matrix): root = matrix[j][i] if target == root: return True elif target < root: i -= 1 elif target > root: j += 1 return False print(Solution().findNumberIn2DArray(a, 5))
e32b14f8f3e60e7c9d88d5f669bb31099a45d3c9
MinnuMariyaJoy/luminarpythoncode
/Advanced/Test/Test 1/q1.py
459
3.671875
4
class Vehicle: def m1(self,registration,cost,mileage): self.registration=registration self.cost=cost self.mileage=mileage def m2(self): print("Registration: ",self.registration) print("Cost: ",self.cost) print("mileage: ",self.mileage) class Bus(Vehicle): bname='Bus' def m3(self): print("Vehicle name : ", Bus.bname) obj=Bus() obj.m3() obj.m1("KL AE 0890",1000000,"50km/ltr") obj.m2()
3ec4c9c3c906bf24cc2538f421bfa6d8af6744ab
amughal2/Portfolio
/python_work/cities.py
691
4.28125
4
the_cities = { 'greensboro': { 'location' : 'nc', 'population' : 300000, 'fact' : 'it is green' }, 'new york' : { 'location' : 'ny', 'population' : 1000000, 'fact' : 'it is the biggest city in america', }, 'chicago' :{ 'location' : 'il', 'population' : 1000000, 'fact' : 'it is the windy city of america', } } for city, city_info in the_cities.items(): print("\nCity: " + city) city_location = city_info['location'] city_population = city_info['population'] city_fact = city_info['fact'] print("\tThe city is located in " + city_location.upper()) print("\tThe cities population is " + str(city_population)) print("\tA fact about this city is " + city_fact)
67ee4ef52f22b3fe0b64d3076cedd11f302209d7
Javiergm18/PREINFORME-DE-LABORATORIO-9
/PREINFORME-DE-LABORATORIO-9/2.py
168
3.8125
4
numero = int( input("ingrese un numero: ")) i = 0 while numero > 0 : i = i+1 resto = numero % 10 numero = int(numero/10) print("%d"%(resto),end ="")
62029f6f9823ca2412225f0184d730dc74f5a776
blehrhof/brian
/better looping and code.py
6,095
3.546875
4
for i in [0,1,2,3,4,5]: print i**2 for i in range(6): print i**2 for i in xrange(6): print i**2 colors = ['a','b','c','d'] for i in range(len(colors)): print(colors[i]) for color in colors: print color for i in range(len(colors)-1,-1,-1): print colors[i] for color in reversed(colors): print color for i in range(len(colors)): print i, '-->', colors[i] for i, color in enumerate(colors): print i, '-->', colors[i] names=['x', 'y','z'] n=min(len(names), lencolors)): for i in range(n): print names[i], '--->', colors[i] for name,color in zip(names, colors): print names[i], '--->', colors[i] # iterator zip for name,color in izip(names, colors): print names[i], '--->', colors[i] # looping in sorted order for color in sorrted(colors): print(colors) for color in sorted(colors, reverse=True): print(colors) # custom sort order def compare_len(c1,c2): if len(c1) < len(c2): return -1 if len(c1) > len(c2): return 1 return 0 print sorted(colors,cmp=compare_length) print sorted(colors, key=len) # call a function until a sentinel value blocks=[] while True: block=f.read(32) if block=='': break blocks.append(block) blocks=[] for block in iter(partial(f.read,32), ''): blocks.append(block) # for loops are really foreach # also makes block iterable # distinguishing multiple exit points in loops def find(seq,target): found=False for i,value in enumerate(seq): if value == tgt: found=True break if not found: return = -1 return i def find(seq,target): for i,value in enumerate(seq): if value == tgt: break else: return = -1 return i # looping over dict keys d={"a":"1","b":"2","c":"3"} for k in d: print k for k in d.keys(): # makes copy of keys if k.startswith('r'): del d[k] d={ k : d[k] for k in d if not k.startswith('r')} for k in d: print k, '-->', d[k] for k,v in d.items(): print k, '-->', d[k] for k,v in d.items(): print k, '-->', d[k] for k,v in d.iteritems(): print k, '-->', d[k] #build a dict from pairs names=['w','x','y','z'] colors = ['a','b','c','d'] d=dict(izip(names,colors)) # counting with dicts color['red','green','red','blue','gree','red'] d={} for color in colors: if color not in d: d[color]=0 d[color] +=1 ('blue':1, 'green':2, 'red':3) # square brackets are conditional, so it can fail d={} for color in colors: d[color] = d.get(color,0) +1 d=defaultdict(int) for color in colors: d[color] +=1 # grouping with dicts names = ['raymond','rachael','matthew', 'roger', 'betty','melissa','judith','charlie'] d={} for name in names: key=len(name) if key not in d: d[key] = [] d[key].append(name) # list of names with len = 7 {5: ['roger', 'betty'], 6:['rachael','judith'], 7: ['raymond','matthew','melissa','charlie']} d={} for name in names: key=len(name) d.setdefault(key,[]).append(name) # setdefault is the same as get but it inserts the missing key d=defaultdict(list) for name in names: key = len(name) d[key].append(name) d={'matthew':'blue','rachael':'green','raymond':'red'} while d: key,value=d.popitem() print key,'--',value # removes item # linking dictionaries together defaults={'color':'red','user':'guest'} parser=argparser.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace=parser.parse_args({}) commane_line_args={k:v for k,v in vars(namespace).items() if v} d=defaults.copy() d.update(os.environ) d.update(command_line_args) d=ChainMap(command_line_args, os.environ, defaults) # clarity function calls twitter_search('@obama',False,20,True) twitter_search('@obama', retweets-False, numtweets=20,popular=True) # claify multiple returns values with names tuples doctest.testmod() (0,4) doctest.testmod() TestResults(failed=0,attempted=4) TestResults = namestuple('TestResults', ['failed','attempted']) # unpacking sequences p='Raymond','Hettinger',0x30,'[email protected]' fname=p[0] lname=p[1] age=p[2] email=p[3] #tuple unpacking fname,lname,age,email = p # updating multiple state variables def f(n): x=0 y=1 for i in range(n): print x t=y y=x+y x=t def f(n): x,y=0,1 for i in range(n) print x x,y = y,x+y #simultaneous state updates tmp_x=x+dx*t tmp_y=y+dy*t tmp_dx=influence(m,x,y,dx,dy,partial='x') tmp_dy=influence(m,x,y,dx,dy,partial='y') x=tmp_x y = tmp_y dx=tmp_dx dy=tmp_dy x,y,dx,dy = (x + dx * t, y + dy * t, influence(m,x,y,dx,dy,partial='x') influence(m,x,y,dx,dy,partial='y')) # concatenating strings s=names[0] for name in names[1:]: s += ', ' + name print s print ', '.join(names) #updating sequences del names[0] names.pop(0) names.insert(0,'mark') names=deque(['raymond','rachael','matthew', 'roger', 'betty','melissa','judith','charlie']) del names[0] names.popleft() names.appendleft('mark') # with great power comes great responsibility # opening and closing files f=open('data.txt') try: data=f.read() finally f.close() with open('data.txt' as f: data=f.read() #locks lock=threading.Lock() lock.acquire() try: print 'critical section 1' print 'critical section 2' finally: lock.relesae() with lock: print 'critical section 1' print 'critical section 2' try: os.remove('somefile.tmp') except OSError: pass with ignored(OSError): os.remove('somefile.tmp') @contextmanager def ignored(*Exceptions): try: yield except Exceptions: pass
2eb13cfac1666d3b86a4b525512133054e98f3f2
mzaldiadithya/Python
/Tugas Pertemuan 3/tugas 1/operator-bitwise.py
1,177
4.09375
4
# ============================= Operator Bitwise =========================== title = "Operator Bitwise" print("\n" + title.upper().center(100)) print("================================\n".center(100)) a = 14 b = 3 # Bitwise AND operation print("a & b =", a & b) print("\n============== Bitwise AND Explanation ================\n") print("a = ", a ,"= 1110 (Binary)") print("a = ", b ,"= 0011 (Binary)") print("\na & b = 1110") print("&".center(20)) print("0011".center(20)) print("= 0010".center(17)) print("= 2 (Decimal)".center(25)) print("\n============== End Bitwise AND Explanation ================") # End Bitwise AND operation # Bitwise OR operation print("\na | b =", a | b) print("\n============== Bitwise OR Explanation ================\n") print("a = ", a ,"= 1110 (Binary)") print("a = ", b ,"= 0011 (Binary)") print("\na | b = 1110") print("|".center(20)) print("0011".center(20)) print("= 1111".center(17)) print("= 15 (Decimal)".center(25)) print("\n============== End Bitwise OR Explanation ================") # End Bitwise OR operation # ============================= End Operator Bitwise ===========================
33715334d1f8f680daeac7f452fc90ecbb8b7553
Gyllm/UNIABCDE
/professor.py
1,100
3.5625
4
from empregado import Employee class Teacher(Employee): def __init__(self,name,phone,email,salary,start_date,course): super().__init__(name,phone,email,salary,start_date) self.course = course def additional_health_hazard(self): if self.course == 'Engenharia': return { 'name': self.name, 'course': self.course, 'adicional': self.salary * (0.3) } elif self.course == 'Direito': return { 'name': self.name, 'course': self.course, 'adicional': self.salary * (0.05) } else: return { 'name': self.name, 'course': self.course, 'adicional': self.salary * (0.15) } def show_info(self): return { 'name': self.name, 'phone': self.phone, 'email': self.email, 'salary': self.salary, 'start_date': self.start_date, 'course': self.course }
68c37568dab6c0e95cb00e2ed289b7af638d66eb
nathanrw/aoc2020
/aoc2020.py
12,573
3.546875
4
import argparse import re import functools import operator def task_1_part_1(): with open('input1.txt') as f: lines = f.readlines() numbers = [ int(line) for line in lines ] def get_number(numbers): for x in numbers: for y in numbers: if x + y == 2020: return x*y return None number = get_number(numbers) assert number is not None print(number) def task_1_part_2(): with open('input1.txt') as f: lines = f.readlines() numbers = [ int(line) for line in lines ] def get_number(numbers): for x in numbers: for y in numbers: for z in numbers: if x + y + z == 2020: return x*y*z return None number = get_number(numbers) assert number is not None print(number) def task_2_read_records(): with open('input2.txt') as f: lines = f.readlines() class Record(object): def __init__(self, line): pattern = "(\\d+)-(\\d+) (\\w): (\\w+)" match = re.search(pattern, line) assert match self.a = int(match.group(1)) self.b = int(match.group(2)) self.c = match.group(3) self.password = match.group(4) return [ Record(line) for line in lines ] def task_2_part_1(): def validate(r): count = r.password.count(r.c) return r.a <= count and count <= r.b count = len([r for r in task_2_read_records() if validate(r)]) print(count) def task_2_part_2(): def validate(r): return (r.password[r.a-1] == r.c) != (r.password[r.b-1] == r.c) count = len([r for r in task_2_read_records() if validate(r)]) print(count) def task_3_read_grid(): with open('input3.txt') as f: lines = f.readlines() class GridRow(object): def __init__(self, line): assert len(line) > 0 self.orig = [c for c in line.strip()] self.line = [] self.set_items = {} def __getitem__(self, i): while len(self.line) <= i: self.line += self.orig return self.line[i] def __setitem__(self, i, val): self.__getitem__(i) self.line[i] = val def print(self, column): self.__getitem__(column) print("".join(self.line[:column])) class Grid(object): def __init__(self, lines): self.lines = [ GridRow(l) for l in lines ] def __len__(self): return len(self.lines) def __getitem__(self, j): assert 0 <= j and j < len(self) return self.lines[j] def print(self, column, nrow=-1): for row in self.lines[:nrow]: row.print(column) return Grid(lines) def task_3_evaluate_slope(dx, dy): print("Evaluate slope:", dx, dy) grid = task_3_read_grid() i = dx j = dy count = 0 print("Before: (80x20 subsection)") grid.print(80, 20) print() while j < len(grid): if grid[j][i] == '#': grid[j][i] = 'X' count += 1 else: grid[j][i] = 'O' i += dx j += dy print("After: (80x20 subsection)") grid.print(80, 20) print("Number of trees hit:", count) return count def task_3_part_1(): task_3_evaluate_slope(3, 1) def task_3_part_2(): slopes = [ [1, 1], [3, 1], [5, 1], [7, 1], [1, 2] ] hit_counts = [task_3_evaluate_slope(slope[0], slope[1]) for slope in slopes] result = functools.reduce(operator.mul, hit_counts, 1) print("Result:", result) def task_4_read_passports(filename): with open(filename) as f: lines = f.readlines() passports = [{}] for line in lines: fields = line.strip().split() if len(fields) == 0: passports.append({}) continue for field in fields: tokens = field.split(":") assert len(tokens) == 2 assert not tokens[0] in passports[-1] passports[-1][tokens[0]] = tokens[1] return [p for p in passports if len(p) > 0] def task_4_validate_height(value_str): value = int(value_str[:-2]) units = value_str[-2:] if units == "cm": return 150 <= value and value <= 193 elif units == "in": return 59 <= value and value <= 76 else: return False def task_4_validate_passport(passport, apply_rules=True): print() ok = True optional = ['cid'] rules = { 'byr': ["\\d{4}", lambda x: 1920 <= int(x) and int(x) <= 2002 ], 'iyr': ["\\d{4}", lambda x: 2010 <= int(x) and int(x) <= 2020 ], 'eyr': ["\\d{4}", lambda x: 2020 <= int(x) and int(x) <= 2030 ], 'hgt': ["\\d+(cm|in)", task_4_validate_height], 'hcl': ["#[0-9a-f]{6}", None], 'ecl': ["amb|blu|brn|gry|grn|hzl|oth", None], 'pid': ["\\d{9}", None], 'cid': [None, None] } for key in rules: # Ensure key is in passport unless optional if not key in passport: if key in optional: continue else: print(key, "missing") ok = False continue # Apply validation rules unless doing quick check if not apply_rules: continue value = passport[key] pattern = rules[key][0] predicate = rules[key][1] matched = True if pattern is not None: match = re.match(pattern, value) if not match: print("R", key, ":", pattern, "!=~", value) ok = False matched = False else: print("R", key, ":", pattern, "=~", value) if matched and predicate is not None: if not predicate(value): print("P", key, ":", value, "predicate failed") ok = False else: print("P", key, ":", value, "OK") # Check for unwanted fields for key in passport: if not key in rules: print(key, "unwanted") ok = False print(ok) return ok def task_4_part_1(): passports = task_4_read_passports("input4.txt") num_valid = len([p for p in passports if task_4_validate_passport(p, False)]) assert num_valid == 204 print(num_valid) def task_4_part_2(): passports = task_4_read_passports("input4.txt") num_valid = len([p for p in passports if task_4_validate_passport(p)]) num_invalid = len([p for p in passports if not task_4_validate_passport(p)]) print(num_valid) print(num_invalid) def task_5_decode_seat_id(code): assert len(code) == 10 row_code = code[:7] column_code = code[7:] assert len(row_code) == 7 def decode_bsp(code, l, r, min, max): assert len(l) == 1 assert len(r) == 1 assert code.count(l) + code.count(r) == len(code) if len(code) == 0: assert min == max return min assert min != max c = code[0] rest = code[1:] if c == l: return decode_bsp(rest, l, r, min, (min+max)//2) elif c == r: return decode_bsp(rest, l, r, (min+max)//2+1, max) else: assert False column = decode_bsp(column_code, 'L', 'R', 0, 7) row = decode_bsp(row_code, 'F', 'B', 0, 127) seat_id = row * 8 + column return seat_id def task_5_read_seat_ids(): with open('input5.txt') as f: lines = f.readlines() return [ task_5_decode_seat_id(line.strip()) for line in lines ] def task_5_part_1(): ids = task_5_read_seat_ids() highest = sorted(ids)[-1] assert highest == 953 print(highest) def task_5_part_2(): my_seat = None ids = sorted(task_5_read_seat_ids()) for i in range(len(ids)-1): if ids[i] != ids[i+1]-1: my_seat = ids[i]+1 break print(my_seat) assert my_seat == 615 def task_6_read_groups(): with open('input6.txt') as f: lines = f.readlines() class Group(object): def __init__(self): self.answers = {} self.count = 0 groups = [Group()] for line in lines: chars = line.strip() if len(chars) == 0: groups.append(Group()) continue groups[-1].count += 1 for char in chars: count = groups[-1].answers.get(char, 0) groups[-1].answers[char] = count+1 return [ g for g in groups if g.count > 0 ] def task_6_part_1(): groups = task_6_read_groups() count = sum([ len(g.answers) for g in groups ]) assert count == 6799 print(count) def task_6_part_2(): groups = task_6_read_groups() count = sum([len([k for k in g.answers if g.answers[k] == g.count]) for g in groups]) print(count) assert count == 3354 def task_7_read_rules(): with open('input7.txt') as f: lines = f.readlines() def parse_rule(line): class Rule(object): def __init__(self, colour, contents): self.colour = colour self.contents = contents comma_split = line.split(",") contain_split = comma_split[0].split("contain") container_str = contain_split[0] contents_strs = [contain_split[1]] + comma_split[1:] container_tokens = container_str.split() container_colour = " ".join(container_tokens[:2]) contents = {} for contents_str in contents_strs: contents_tokens = contents_str.split() if contents_tokens[0] == "no": continue contents_count = int(contents_tokens[0]) contents_colour = " ".join(contents_tokens[1:3]) contents[contents_colour] = contents_count return Rule(container_colour, contents) return [ parse_rule(line) for line in lines ] def task_7_find_possible_containers(rules, colour, seen=set()): direct_parents = [ r.colour for r in rules if colour in r.contents ] for c in direct_parents: if c in seen: continue print(c) seen.add(c) task_7_find_possible_containers(rules, c, seen) return seen def task_7_count_contents(rules, colour): rules_for_colour = [ r for r in rules if r.colour == colour ] assert len(rules_for_colour) == 1 rule = rules_for_colour[0] count = 0 for content_colour in rule.contents: n = rule.contents[content_colour] count += n * (1 + task_7_count_contents(rules, content_colour)) return count def task_7_part_1(): rules = task_7_read_rules() containers = task_7_find_possible_containers(rules, "shiny gold") answer = len(containers) assert answer == 246 print(answer) def task_7_part_2(): rules = task_7_read_rules() answer = task_7_count_contents(rules, "shiny gold") print(answer) assert answer == 2976 def task_8_read_program(): class Instruction(object): def __init__(self, line): tokens = line.split() assert len(tokens) == 2 self.op = tokens[0] self.arg = int(tokens[1]) with open('input8.txt') as f: lines = f.readlines() program = [ Instruction(line) for line in lines ] return program def task_8_execute_program(program): ip = 0 acc = 0 executed = set() while ip < len(program): if ip in executed: print("begin loop") break executed.add(ip) i = program[ip] if i.op == 'nop': pass elif i.op == 'acc': acc += i.arg elif i.op == 'jmp': print("jump from", ip) ip += i.arg continue ip += 1 print("ip:", ip) return acc def task_8_part_1(): program = task_8_read_program() result = task_8_execute_program(program) print(result) assert result == 1801 def task_8_part_2(): program = task_8_read_program() program[210].op = "nop" result = task_8_execute_program(program) print(result) def main(): #task_1_part_1() #task_1_part_2() #task_2_part_1() #task_2_part_2() #task_3_part_1() #task_3_part_2() #task_4_part_1() #task_4_part_2() #task_5_part_1() #task_5_part_2() #task_6_part_1() #task_6_part_2() #task_7_part_1() #task_7_part_2() task_8_part_1() if __name__ == '__main__': main()
d0e8d7ac03d1c927d90e4ec526f3b759248fb255
mikgross/cognitive-developer-training
/hands-on/task-3 - KMeans/plot_cluster_iris.py
3,468
3.84375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= K-means Clustering ========================================================= The plots display firstly what a K-means algorithm would yield using three clusters. It is then shown what the effect of a bad initialization is on the classification process: By setting n_init to only 1 (default is 10), the amount of times that the algorithm will be run with different centroid seeds is reduced. The next plot displays what using eight clusters would deliver and finally the ground truth. """ print(__doc__) # Code source: Gaël Varoquaux # Modified for documentation by Jaques Grobler # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt # Though the following import is not directly being used, it is required # for 3D projection to work from mpl_toolkits.mplot3d import Axes3D from sklearn.cluster import KMeans from sklearn import datasets # seed random in order to get random numbers throughout the process np.random.seed(5) # load the daaset iris from the datasets library imported from sklearn iris = datasets.load_iris() # set X to being the iris data: of structure n_samples, n_features X = iris.data # set y to be the iris target: the ground truth y = iris.target print(y) # different graphs to represent the data structure is # array of ('name', KMeans(arguments)) estimators = [('k_means_iris_8', KMeans(n_clusters=8)), ('k_means_iris_3', KMeans(n_clusters=3)), ('k_means_iris_bad_init', KMeans(n_clusters=3, n_init=1, init='random')), ('test_mik', KMeans(n_clusters=3))] # initiate fignum in order to locate the first figure (starting at 1) fignum = 1 # array of strings for graph titles titles = ['8 clusters', '3 clusters', '3 clusters, bad initialization', 'test Mikael'] # for every estimators --> name every bit of the array with a different target for name, est in estimators: # create the fig plot object taking argument fignum and figsize fig = plt.figure(fignum, figsize=(6, 4)) # ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) est.fit(X) labels = est.labels_ ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float), edgecolor='k') ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') ax.set_title(titles[fignum - 1]) ax.dist = 12 fignum = fignum + 1 # Plot the ground truth fig = plt.figure(fignum, figsize=(4, 3)) ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]: ax.text3D(X[y == label, 3].mean(), X[y == label, 0].mean(), X[y == label, 2].mean() + 2, name, horizontalalignment='center', bbox=dict(alpha=.2, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=y, edgecolor='k') ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') ax.set_title('Ground Truth') ax.dist = 12 fig.show()
15ba84c0279bfe0ffa38412da28b4786873eebc9
hareem-a/Python
/Population.py
862
3.828125
4
""" This program compares the populations of the US and Mexico. Author: Hareem """ US_pop = 328200000 mexico_pop = 127600000 US_rate = 0.53 mexico_rate = 1.06 US_dec = .9947 mexico_inc = 1.0106 years = 0 print("The current population of the US is %d and decreases by %f each year." % (US_pop, US_rate), sep = " ") print("The current population of Mexico is %d and increases by %f each year." % (mexico_pop, mexico_rate), sep = " ") while (US_pop >= mexico_pop): print ("\nYear: ", years + 1) US_pop = US_pop * US_dec print("The new population of the US is roughly %.f." % US_pop, sep = " ") mexico_pop = mexico_pop * mexico_inc print("The new population of Mexico is roughly %.f." % mexico_pop, sep = " ") years += 1 print("\nIt took %d years for the population of Mexico to exceed the population of the US." % (years))
55fcd2137a5fb7536358a687e68539010f424b60
ruslanolkhovsky/utilitypy
/file_str_replace.py
2,332
4.53125
5
"""A simple utility program in python 3 to replace a string all over a file with a new string, and save the result to a new file. Example: `` $ python3 file_str_replace.py -s 'file.txt' -f 'A' -r 'B' -t 'new_file.txt' `` Arguments: --sourcefile, -s Name of the source file (required) --find, -f String to be find and replaced with the new one (required) --replace, -r The new string to replace the existing string (required) --target, -t Name of the target file (optional). If not defined, the program creates a new file with the extension .new in the same location. """ import sys from argparse import ArgumentParser, FileType def CreateParser (): parser = ArgumentParser() parser.add_argument ('--sourcefile', '-s ', type=FileType('r', encoding='UTF-8'), required=True, help='Name of the source file (required)') parser.add_argument ('--find', '-f ', type=str, required=True, help='String to be find and replaced with the new one (required)') parser.add_argument ('--replace', '-r ', type=str, required=True, help='The new string to replace the exsisting string (required)') parser.add_argument ('--target', '-t ', type=FileType('w'), required=False, help='Name of the target file (optional). If not defined, the program creates a new file with the extension .new in the same location.') return parser if __name__ == "__main__": # Parsing arguments parser = CreateParser() params = parser.parse_args(sys.argv[1:]) # Reading the source file to the list with params.sourcefile as file: text = [line.rstrip('\n') for line in params.sourcefile] file.close() # Checking if the name of the target file is defined in the arguments # and set the name by deafault if not if not params.target: targetfile = open(params.sourcefile.name + ".new", "wt") else: targetfile = params.target # Replacing the string and writing the output to the target file with targetfile: for line in text: if params.find in line: targetfile.write(line.replace(str(params.find), str(params.replace)) + '\n') else: targetfile.write(line + '\n') print("Done. Target file: " + targetfile.name) targetfile.close()
87b2b5f91bac4b369886a7ef2773c673058687b1
arkuzya/infa_2019_arkuzya
/lab2/12.py
296
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 12 16:07:29 2019 @author: student """ import turtle t = turtle for r in range(7): for i in range(50): t.forward(1) t.right(3.6) for i in range(50): t.forward(0.3) t.right(3.6)
f71baced225563cf55ca03248cd9a86149431ec5
muzuco/pythonstudy2015
/01_wiki.python.org/15_itertools.py
359
3.5
4
from itertools import groupby lines = ''' this is the first paragraph. this is the second. '''.splitlines() print len(lines) print '-------------' for i, tmp in enumerate(lines): print 'line {num} : {str}'.format(num=i, str=tmp) print '-------------' for has_chars, frags in groupby(lines, bool): if has_chars: print ' '.join(frags)
f0e453cb807e7259cc5e5d8cd2846c36efa29d17
hooong/baekjoon
/Python/10830.py
817
3.640625
4
# 10830번 행렬 제곱 # 행렬 곱셈 def mul(n,matrix1,matrix2): result = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += matrix1[i][k] * matrix2[k][j] result[i][j] %= 1000 return result # 2분할 def devide(n,b,matrix): if b == 1: return matrix elif b == 2: return mul(n,matrix,matrix) else: tmp = devide(n,b//2,matrix) if b%2 == 0: return mul(n,tmp,tmp) else: return mul(n,mul(n,tmp,tmp),matrix) # 입력 n, b = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(n)] result = devide(n,b,a) for row in result: for num in row: print(num%1000, end=' ') print()
d3bb165b0bccc11c90e19a91d5b168080a84efe4
sapnajayavel/FakeReview-Detector
/annotation/shingling.py
1,283
3.5
4
#!/usr/bin/env python2.7 #encoding=utf-8 """ """ def ngram_sequence(n,string): string = list(string) sequence = [] for i in range(len(string)-4): s = string[i]+string[i+1]+string[i+2]+string[i+3] sequence.append(s) return list(set(sequence)) def jaccard_str(s1,s2): seq1 = ngram_sequence(4,s1) seq2 = ngram_sequence(4,s2) return jaccard_seq(seq1,seq2) def jaccard_seq(seq1,seq2): same = [s for s in seq1 if s in seq2] total = set(seq1+seq2) return float(len(same))/len(total) if __name__ == "__main__": s1 = u"非常好,性价比非常高的一个包包,黑色很显档次,旅游休闲购物一个包就搞定,肩带很稳固,柳钉很结实,很好,背了好几天了,全五分!" s2 = u"非常好,性价比非常高的一个包包,黑色很显档次,旅游休闲购物一个包就搞定,肩带很稳固,柳钉很结实,很好,背了好几天了,说28包邮同事们都不相信呢,以后会再来帮衬,全五分!" ss1 = "包包挺好的,姐姐很喜欢,物流很给力,包包和图片上的一样,\(^o^)/~" ss2 = "很好很漂亮,包包挺好的,姐朋友很喜欢,物流很给力,包包和图片上的一样,5分" print jaccard(ss1,ss2)
d46b9f7e91c7d07d152434fd4e9ba8bc54ea666d
OmarGP/Python1
/Secuencia_de_Ejercicio01/Ejercicio H.py
997
4.1875
4
import math #H1. Muestra las siguientes secuencias de número utilizando un WHILE: #H1.1 Secuencia del 1 al 100 a = 1 print(f" >>>> Secuencia del 1 al 100 <<<<") while (a <= 10): print (f"# {a}") a += 1 print("=============================") #H1.2 Los números impares del 51 al 91. print(f" >>>> Secuencia de números impares del 51 al 91 <<<<") b = 51 while(b <= 91): print(f"# {b}") b += 2 print("=============================") #H1.3 Tabla de multiplicar de PI. print(f" >>>> Secuencia de Tabla de multiplicar de PI <<<<") pi = math.pi c = 1 while (c <= 10): print(f"{pi:1.5} x {c} = {pi * c:1.5}") c += 1 print("=============================") #H1.4 Del 20 al 10 multimplicado del 5 a 8, utilizando un FOR print(f" >>>> Secuencia Del 20 al 10 multimplicado del 5 a 8, utilizando un FOR <<<<") d = 20 while (d >= 10): print("") for d1 in range(5, 9): print(f"{d} x {d1} = {d * d1}") d -= 1 print("=============================")
b6dc649684a4bba7e05b1b4e6641da66a7a5e196
hideraldus13/mini_jogos_python
/adivinhe_o_numero.py
1,233
3.875
4
import random def jogador(x): numero_randomico = random.randint(1, x) palpite = 0 print(f'Vamos lá! Adivinhe o número que escolhi. Uma dica: é um número entre 1 e {x}.') while palpite != numero_randomico: palpite = int(input(f'Adivinhe um número entre 1 e {x}: ')) if palpite < numero_randomico: print('Muito baixo. Tente novamente.') elif palpite > numero_randomico: print('Muito alto. Tente novamente') print(f'Parabéns! Você adivinhou o número {numero_randomico} !!') def maquina(x): baixo = 1 alto = x verificacao = '' print(f'Aceito o desafio! Vou adivinhar o número entre {baixo} e {alto} que você pensou.') while verificacao != 'c': if baixo != alto: palpite = random.randint(baixo, alto) else: palpite = baixo # could also be high b/c low = high verificacao = input(f'O valor {palpite} é muito alto (A), muito baixo (B) ou correto (C)?? ').lower() if verificacao == 'a': alto = palpite - 1 elif verificacao == 'b': baixo = palpite + 1 print(f'Uhull! Acertei que o número escolhido é {palpite}.') #jogador(10) #maquina(10)
0d38003408c5c7684635040270f3650d6e1f4989
arunpatala/scala-learn
/SPOJ/py/MIRRORED.py
180
3.6875
4
print "Ready" while(True): s = raw_input() if(s==" "): break else: if(s=="pq" or s=="qp" or s=="db" or s=="bd"): print "Mirrored pair" else: print "Ordinary pair"
6f8f3f9a5432a1e21c8908f06f78979ce645cb53
kmanwar89/ISAT252
/Exercises/Textbook Examples Chapter 10/flip.py
847
4
4
__author__ = 'kadar' # Example of a class and a main function in the same file. Fine for smaller # programs but not good for future expansion/large & complex programs. import random class Coin: def __init__(self): # self.sideup = 'Heads' -- this is not private, the attribute can be directly accessed self.__sideup = 'Heads' # -- use of __ allows the attribute to be private and immutable def toss(self): if random.randint(0, 1) == 0: self.__sideup = 'Heads' else: self.__sideup = 'Tails' def get_sideup(self): return self.__sideup def main(): my_coin = Coin() print('This side is up:', my_coin.get_sideup()) print('I am going to flip the coin 10 times') for count in range(10): my_coin.toss() print(my_coin.get_sideup()) main()
31432e268fe4802aa80cafffb1ef7ca81a5609b2
Novandev/pythonprac
/interview/minimum_swaps.py
981
3.625
4
''' Given an array of increasing numbers (range function in python) find out how many bribes everone had to take to get to thier positions, note that a single person cannot bribe fore than 2 people in from of them the input n is the number of people in line in sorted order ''' def minimum_swaps(n,new_order): num_swaps = 0 orig = list(range(1,n+1)) new_order_dict = {} [new_order_dict.update({item:pos}) for pos,item in enumerate(new_order)] print(orig) print(new_order_dict) for i in range(n): # print(i) num_swaps += new_order[i] - orig[i] print(f'position {i} in new_order holds the value {new_order[i]}') print(f'the original list at this position had the value {orig[i]}') if new_order[i] - orig[i] >2: # print(num_swaps) print('INVALID') break else: num_swaps += new_order[i] - orig[i] print(num_swaps) minimum_swaps(5,[1,5,4,2,3])
08d7fd6bd582dc6e98217435f1e8fd56359128cc
sdzr/cookbook_study
/chapter3/scpt3-7.py
165
3.59375
4
# 无穷大和NaN a = float('-inf') b = float('inf') c = float('NaN') print(a, b, c) print(a+10) print(c+10) import math print(math.isinf(b)) print(math.isinf(c))
b6db70701f6320a230d6b7bbd7e7c01d797fa898
j717273419/python3_test
/List/List1.py
365
4.34375
4
list = ["a","b",3] for item in list: print(item,end=" ") # print 函数的 end 关键参数来表示以空格结束输出,而不是通常的换行。 # python直接获取集合中的指定信息,组合成一个新的List list2 = [item for item in list] print(list2) list2.append(3) print(list2) list3 = [item for item in list2 if item != 3] print(list3)
af8abe1e92094c667010b9e8f70284c317441b1d
sakshisangwan/Python-101
/Basic Practice Code/EvenSum.py
307
4.34375
4
# This program will calculate the sum of all the even numbers upto the given number a = int(input ("Enter a number ")) result = 0 count = 0 while count <= a: if count % 2 == 0: result = result + count count = count + 1 else: count = count + 1 print ("Sum of even numbers upto %d is %d" %(a,result))
dbc97852fde35eb237baf19cea8b59ac6021d087
NichHarris/leet-code
/fizzBuzz.py
954
3.671875
4
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ ans = [] for i in range(1,n+1): if i%5 == 0 and i%3 == 0: ans.append("FizzBuzz") elif i%5 == 0: ans.append("Buzz") elif i%3 == 0: ans.append("Fizz") else: ans.append(str(i)) return ans # Hash Table class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ ans = [] hashTable = {3: "Fizz", 5: "Buzz"} for i in range(1,n+1): numStr = "" for key in hashTable.keys(): if i%key == 0: numStr += hashTable[key] if not numStr: numStr = str(i) ans.append(numStr) return ans
f855f73922f27c7478cc6d79a8dfad5061113021
emmadeeks/CMEECourseWork
/Week2/Code/dictionary.py
1,434
3.75
4
#!/usr/bin/env python3 #Author: Emma Deeks [email protected] #Script: dictionary.py #Desc: Populates a dictionary to map order names to sets of taxa #Arguments: No input #Outputs: Completed dictionary #Date: Oct 2019 """ Populates a dictionary to map order names to sets of taxa """ # Creates a dictionary of taxa taxa = [ ('Myotis lucifugus','Chiroptera'), ('Gerbillus henleyi','Rodentia',), ('Peromyscus crinitus', 'Rodentia'), ('Mus domesticus', 'Rodentia'), ('Cleithrionomys rutilus', 'Rodentia'), ('Microgale dobsoni', 'Afrosoricida'), ('Microgale talazaci', 'Afrosoricida'), ('Lyacon pictus', 'Carnivora'), ('Arctocephalus gazella', 'Carnivora'), ('Canis lupus', 'Carnivora'), ] """ Populates a dictionary to map order names to sets of taxa """ taxa_dic = {} #Empty dictionary set_order= set() #empty set for w in taxa: set_order.add(w[1]) #Adds orders to set, as sets cant repeat words only four orders for y in set_order: set_add = set() for i in taxa: if i[1]==y: #Goes through taxa list and if orders match output the species into dictionary set_add.add(i[0]) taxa_dic[y]=set_add # Adds the sets to be added to the ordered dictionary then loops back throught he sets print("Completed dictionary:", taxa_dic) #Prints completed dictionary
e17b4a1460d8e5c1c34b35dfcef3ea777dea18bc
XiaoMaoBee/PROJECT2_Bulls-Cows
/PROJECT2_Bulls-Cows.py
2,217
3.734375
4
# muj druhy projekt "Bulls and cows" game import random import time ODDELOVAC = '=' * 56 first_rand = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] rest_rand = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] genum = [] a = True while a: first = random.sample(first_rand, 1) rest = random.sample(rest_rand, 3) genum = first + rest # print(genum) if len(set(genum)) == 4 and genum[0:1] != 0: genum = genum a = False print("Hi there!", ODDELOVAC, "I've generated a random 4 digits number for you.", "Let's play \"Bulls and cows\" game.", ODDELOVAC, 'Time is running, good luck !!!', sep='\n', end=f'\n{ODDELOVAC}\n') victory = False guesses = 0 t0 = time.time() while not victory: guesses += 1 NUMBER = input("Enter 4 unique digits: ") if len(NUMBER) < 4 or len(NUMBER) > 4: print('Enter number of exactly FOUR unique digits') break elif NUMBER[:1] == '0': print('The first digit must not be a zero.') break elif not NUMBER.isdecimal(): print('Enter only digits, not characters') print(ODDELOVAC) break elif len(set(NUMBER)) < 4: print('Each of 4 digits must be unique') break bulls = 0 cows = 0 for i, num in enumerate(NUMBER): for i1, num1 in enumerate(genum): if (i, num) == (i1, num1): bulls += 1 if bulls == 4: print(f'Amazing, you have' f' guessed the right number ' f'in {guesses} guesses!') victory = True elif num == num1 and i != i1: cows += 1 print(str(bulls) + ' bulls,' + str(cows) + ' cows' + f'{guesses}. guess'.rjust(36)) print(ODDELOVAC) t1 = (time.time() - t0) if victory and guesses <= 5: print("*** You are THE MAGICIAN !!! ***".center(56)) elif victory and 5 < guesses < 10: print("*** Very good MASTER !!! ***".center(56, '*')) elif victory and guesses > 10: print("You need to practice more :) !!!".center(56)) print(ODDELOVAC) print(f'Time elapsed: {round(t1)} seconds.'.center(56))
28832e1640e11dd68a9837a39f0460caf364adc0
af94080/dailybyte
/spot_diff.py
648
4.21875
4
'''You are given two strings, s and t which only consist of lowercase letters. t is generated by shuffling the letters in s as well as potentially adding an additional random character. Return the letter that was randomly added to t if it exists, otherwise, return ’ ‘. Note: You may assume that at most one additional character can be added to t. Ex: Given the following strings... s = "foobar", t = "barfoot", return 't' s = "ide", t = "idea", return 'a' s = "coding", t "ingcod", return '' ''' def spot_diff(s, t): for char in t: if char not in s: return char else: return ' ' s = "coding" t = "ingcod" print(spot_diff(s, t))
dc593ab701a573a786ea047dcead804846b1d17e
Yycxj/Python3
/ex43_classes.py
1,249
3.71875
4
class Scene(object): def enter(self): pass class Engine(object): def __init__(self,scene_map): print (f"really playing {scene_map.start_scene}") def play(self): print ("Let's go ~") def yes_no (self): while True: put = input("yes or no >> ") if put == 'no': exit() elif put == 'yes': break else: print("plase agent ") def judge_dead(self,life): if life == 0: x = Death() x.enter() class Death(Scene): def enter(self): print (" You are dead! ") class CentralCorridor(Scene): def enter(self): pass class LaserWeponArmory(Scene): def enter(self): pass class TheBridge(Scene): def enter(self): pass class EscapePod(Scene): def enter(self): pass class Map(object): def __init__(self,start_scene): print (f"Now,open map {start_scene}") self.start_scene = start_scene def next_scene(self,scene_name): pass def opening_scene(self): pass a_map = Map('central_corridor') a_game = Engine(a_map) a_game.yes_no() a_game.play() a_game.judge_dead(0)
00f76fd7697464a7667e86e20d524523ca8ad047
buxizhizhoum/leetcode
/construct_binary_tree_from_preorder_and_inorder_traversal.py
1,229
4.15625
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7 """ # 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 buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if not inorder: return index = inorder.index(preorder[0]) root = TreeNode(inorder[index]) inorder_left = inorder[:index] inorder_right = inorder[index + 1:] preorder.pop(0) root.left = self.buildTree(preorder, inorder_left) root.right = self.buildTree(preorder, inorder_right) return root if __name__ == "__main__": preorder = [3, 9, 20, 15, 7] inorder = [9, 3, 15, 20, 7] s = Solution() res = s.buildTree(preorder, inorder) print(res)
79b297a80a219b9715ef818a541ab950cc793c1d
Shrikaran-Kanagaraj/PythonIsEasy
/InstaDataRetriver.py
683
3.65625
4
from instagramy import InstagramUser name = input("Enter user name:") user = InstagramUser(name) followers = user.number_of_followers print('Total followers:', followers) following = user.number_of_followings print('Total followings:', following) posts = user.number_of_posts print('Total posts:', posts) bio = user.biography print('Bio:\n', bio) link_in_bio = user.website print('Link in Bio:', link_in_bio) |--------------------------------------------------| OUTPUT : Enter user name:malini_hariram Total followers: 196 Total followings: 327 Total posts: 1 Bio: First cry on Jan 22😜🎂 Movie freak🤗 Born to shine bright😇 Music addictz 🎶 Link in Bio: None
eb0deedef4a63f7d459e6ae5a9cd7358134018f5
JBello85/Python-For-Beginners
/main.py
1,962
4.3125
4
# Fundamentals: They are four required fundamentals in any language. Those are called key points. 1. Terms, 2. Actions, 3. Data Types and 4. Best Practices. # #Data Types # 1. int (interger. use it for all numbers) # 2. FloatingPointError # 3. bool # 4. Str (String. For all letters) # 5. list # 6. tuple # 7. set # 8. dict (dictionary) # # A data type is a value in Python. # ##classes --custom data types # ##Specialized data types (modules, something like extentions) # ## None - The absence of value. #--- # ##Fundamentals of Data Type # int and float # print(type(6)) # print(type(2 - 4)) # substraction # print(type(2 * 4)) # multiplication # print(type(2 / 4)) # division 0.5 # print(2 ** 3) # exponents # print(5 // 4) # fractions # print(6 % 4) # percentages # ###math functions # print(round(3.9)) # ###abs absolute value. No negative number. For example: # print(abs(-20)) # --- #Floating numbers are like scientific notations. For example 300000000 * 0.00000015 can also be expressed as 3 * 10 ** 8 and 1.5 * 10 ** -7 # In this case the 3 gets multiplied by 1.5 = 4.5 and the exponents get substracted, 10 ** 8 - 10 ** -7 = 10 ** 1 # results: 4.5 * 10 ** 1 or 4.5 * 10 = 45 #--- #How human see mathematical numbers vs computers. # US humans know 100 , 10 , and 1 , in fractions we know 1 / 10 , 1 / 100 and 1 / 1000, in decimals, we see it as 0.1 , 0.01 and 0.001. On the other hand computers see: # 4 , 2 , and 1 # 1 /2 , 1 / 4 , 1 / 6 , 1 / 8 , 1 / 10 #--- # Operator precedence: for example: (20 + 3 * 4) 3 * 4 gets multiplied first, then 20 gets added to 12. # print(20 - 3 * 4) # the result from the above equation is 8 because 3 * 4 gets multiplied first, the 12 gets substracted to 12. # In Python the precendence order is as follow: # () # ** # power of # print((20 - 3) + 2 ** 2) # results 21 because first, we solve the (), then solve the exponent (**). SO again, the precedence is as follow: # () # ** # * / # + - # ---
9bba47e7ddb7756cbc72ece7a3c3f7b885cd66e3
Pablo784/lab-09-functions
/factorial.py
135
3.828125
4
def factorial(n): return n * 4 * 2 * 1 userstring = input("Number Please:") usernum = int(userstring) print(factorial(usernum))
28a8d245a41964266f110f651947959a029625a8
pradeepmaddipatla16/my_problem_solving_approach_leetcode_medium_hard_problems
/strings/robot_return_to_origin.py
259
3.65625
4
def function1(moves): x=y=0 for move in moves: if move=='U':y+=1 elif move == 'D':y-=1 elif move=='R':x+=1 elif move=='L':x-=1 if x==0 and y==0:return True else:return False print(function1(['R','L','D','U']))
5952e6edacf6ba5745712f235ababd53d460053e
Lazcanof/Py4e
/02_Data_Structures/week_06/Assignment_10_2.py
1,142
4.03125
4
# 10.2 Write a program to read through the mbox-short.txt # and figure out the distribution by hour of the day for each of the messages. # You can pull the hour out from the 'From ' line by finding the time and then splitting the string # a second time using a colon. # From [email protected] Sat Jan 5 09:14:16 2008 # Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below. name= input('Enter file:') handle=open(name) counts=dict() for line in handle: line.rstrip() if line.startswith('From '): words=line.split() hora=words[5] #print(hora[:2]) #print(words[5]) #print(words) counts[hora[:2]]=counts.get(hora[:2],0)+1 #print(counts) bigcount=None bigword=None for words,count in counts.items(): if bigcount is None or count > bigcount: bigword=words bigcount=count #print(bigword, bigcount) #print(counts) #lista transformada ordenada lst=list() for key,val in counts.items(): newtup=(key,val) lst.append(newtup) lst=sorted(lst) for val,key in lst[:]: print(val,key)
5ace5228abb4cf0fec28db9bc78007c5f9641380
GeneLiuXe/University-Subject-Library
/Numerical-Analysis/Experiment/Ch1/problem1.py
654
3.625
4
import math def Solution(a, b, c): x1 = x2 = 0 tmp = b * b - 4 * a * c if a == 0: x1 = x2 = -c / b elif tmp < 0: print("No solution.\n") return else: tmp = math.sqrt(tmp) if c == 0: x1 = (-b + tmp) / (2 * a) x2 = (-b - tmp) / (2 * a) elif b > 0: x1 = -2 * c / (b + tmp) x2 = (-b - tmp) / (2 * a) else: x1 = (-b + tmp) / (2 * a) x2 = -2 * c / (b - tmp) print("x1:", x1, ", x2:", x2) Solution(1, -1000.001, 1) Solution(1, -10000.0001, 1) Solution(1, -100000.00001, 1) Solution(1, -1000000.000001, 1)
f2593a8ea609c4bc0677917e088d919382e8796a
rafaelbarretorb/Robotics-Notebook
/PathPlanning/geometry.py
1,040
3.828125
4
""" geometry elements """ import math class Point(object): def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def dist(self, other): return math.sqrt(pow(self.x - other.x, 2) + pow(self.y - other.y, 2)) def dir(self, other): return math.atan2(other.y - self.y, other.x - self.x) def tuple(self): return self.x, self.y class Vector(object): def __init__(self, x, y): self.x = x self.y = y def dir(self): return math.atan2(self.y, self.x) def mod(self): return math.sqrt(pow(self.x, 2) + pow(self.y, 2)) def __mul__(self, other): return Vector(other*self.x, other*self.y) def __add__(self, other): return Vector(self.x+other.x, self.y+other.y) def Polar2Vector(dist, theta): return Vector(dist*math.cos(theta), dist*math.sin(theta))
63a42499a256db8806784794b402163fd7d5cb36
yougooo/epam_training
/Python/day_1/test6.py
247
3.59375
4
#!/usr/bin/python import sys def polindrom_check(word): word = word.lower() word = word.replace(' ','') return 'YES' if word == word[::-1] else 'NO' if __name__=='__main__': word = sys.argv[1] print(polindrom_check(word))
65f01906386543f708d01d2a03e48ee477f1d0c0
sabzi1984/Intro-to-Algorithms
/dijkstra with linear shortest distance.py
1,608
3.890625
4
# look for shortest distance from the "dist_so_far" dictionary #and return the closest node def shortest_dist_node(dist): best_node = None best_value = 1000000 for v in dist: if dist[v] < best_value: (best_node, best_value) = (v, dist[v]) return best_node #add all the neighbour nodes and their distance to the "dist_so_far" dictionary #fix the shrtest distance as the "final distance" dictionary def dijkstra(G,v): dist_so_far = {} dist_so_far[v] = 0 final_dist = {} while len(final_dist) < len(G): w = shortest_dist_node(dist_so_far) final_dist[w] = dist_so_far[w] del dist_so_far[w] for x in G[w]: if x not in final_dist: if x not in dist_so_far: dist_so_far[x] = final_dist[w] + G[w][x] elif final_dist[w] + G[w][x] < dist_so_far[x]: dist_so_far[x] = final_dist[w] + G[w][x] return final_dist #make linke with distanceas as weights def make_link(G, node1, node2, w): if node1 not in G: G[node1] = {} if node2 not in G[node1]: (G[node1])[node2] = 0 (G[node1])[node2] += w if node2 not in G: G[node2] = {} if node1 not in G[node2]: (G[node2])[node1] = 0 (G[node2])[node1] += w return G (a,b,c,d,e,f,g) = ('A', 'B', 'C', 'D', 'E', 'F', 'G') triples = ((a,c,3),(c,b,10),(a,b,15),(d,b,9),(a,d,4),(d,f,7),(d,e,3), (e,g,1),(e,f,5),(f,g,2),(b,f,1)) G = {} for (i,j,k) in triples: make_link(G, i, j, k) dist=dijkstra(G, a) print(dist[e]) print(dist['E'])
31e2183e6a0ad263fff0ce7bb741d41965fc11c8
bradyz/sandbox
/hackerrank/arraysort/insertionsort.py
994
4
4
import sys def print_arr(arr): tmp = "" for x in arr: tmp += str(x) + " " print(tmp) return def insertion_sort(a, s): count = 0 if a == 1: # print_arr(a) return count for x in range(1, s): while x > 0 and a[x] < a[x - 1]: tmp = a[x] a[x] = a[x - 1] a[x - 1] = tmp x -= 1 count += 1 # print_arr(a) return count def insertion_sort1(a, s): n = a[s - 1] is_sorted = False for x in range(s - 1, -1, -1): if not is_sorted: if n < a[x - 1] and x != 0: a[x] = a[x - 1] else: a[x] = n is_sorted = True print_arr(a) if __name__ == "__main__": for i, line in enumerate(sys.stdin): if i == 0: size = int(line.strip("\n")) else: parsed = [int(x) for x in line.split()] print(insertion_sort(parsed, size))
f8f11191f4d8e35f01b6feb43c01cb6853e929bb
choroba/perlweeklychallenge-club
/challenge-207/spadacciniweb/python/ch-1.py
794
4.21875
4
# Task 1: Keyboard Word # Submitted by: Mohammad S Anwar # # You are given an array of words. # Write a script to print all the words in the given array that can be types using alphabet on only one row of the keyboard. # # Let us assume the keys are arranged as below: # Row 1: qwertyuiop # Row 2: asdfghjkl # Row 3: zxcvbnm # # Example 1 # Input: @words = ("Hello","Alaska","Dad","Peace") # Output: ("Alaska","Dad") # # Example 2 # Input: @array = ("OMG","Bye") # Output: () import re import sys if __name__ == "__main__": aclass = {'qwertyuiop', 'asdfghjkl', 'zxcvbnm'} output = set() for word in sys.argv[1:]: if len(list(filter(lambda x: re.search(r'^['+x+']+$', word.lower()), aclass))): output.add(word) print("Output: ({:s})".format(', '.join(output)))
8dccc3a15a95e5d498539b89454a74028324360b
matheuszei/Python_DesafiosCursoemvideo
/0022_desafio.py
523
4.125
4
#Crie um programa que leia o nome completo de uma pessoa e mostre: #O nome com todas as letras maiúsculas e minúsculas. #Quantas letras ao todo sem considerar espaços. #Quantas letras tem o primeiro nome nome = input('Digite o seu nome completo: ') print('Maiusculo: {}'.format(nome.upper())) print('Minusculo: {}'.format(nome.lower())) print('Total de letras (sem contar espaço): {}'.format(len(nome.strip()))) dividido = nome.split() print('Total de letras do primeiro nome: {}'.format(len(dividido[0])))
a7a64beb6f8bf82403924f1222a42524c121d861
longlizl/python
/guess_number.py
951
3.765625
4
real_num = 25 count = 0 for i in range(10): if count < 3: guess_num = input("请输入你猜的数字:").strip() #过滤空格和enter字符 if len(guess_num) == 0: continue if guess_num.isdigit(): #判断是否为数字 guess_num = int(guess_num) else: print("你需要输入一个真正的数字--") continue if guess_num > real_num: print("你猜的数字过大--") elif guess_num < real_num: print("你猜的数字过小--") else: print("恭喜猜对了--") break else: #print("猜的次数过多:") # break continue_confirm = input("请继续输入继续请输入y或者Y:") if continue_confirm == "y" or continue_confirm == "Y" : count = 0 continue else: print("bye") break count += 1
e0ce2e01aa22cab32ca4af6fda8ce775a8a94cd1
microease/Python-Tip-Note
/026ok.py
342
3.84375
4
# 给你一个整数组成的列表L,按照下列条件输出: # 若L是升序排列的,则输出"UP"; # 若L是降序排列的,则输出"DOWN"; # 若L无序,则输出"WRONG"。 L = [1, 2, 32, 421, 242, 1424, 55353, 312421] if L == sorted(L): print("UP") elif L == sorted(L, reverse=True): print("DOWN") else: print("WRONG")
6e0b997e88f53d2782c87003d9ae73b917aa99ea
mohitraj/mohitcs
/Learntek_code/25_Sep_18/for4.py
96
3.984375
4
str1 = "What we think we become" i = 0 for each in str1: if each== 'e': i = i +1 print (i)
c0278c87f8913fd726a6bf9f76f1ac760d574370
yachiwu/python-training
/backup/loop-basic.py
183
3.953125
4
#while迴圈 #1+2+3+..+10 # n = 1 # sum = 0 #紀錄累加的結果 # while n<=10: # sum+=n # n+=1 # print(sum) #for迴圈 sum = 0 for x in range(11): sum+=x print(sum)
42d6c6be72b0d34e6292238c5d3b9bd25ab69342
Bmcentee148/PythonTheHardWay
/ex39.py
1,832
4.0625
4
# create a mapping of state to abbreviation states = { 'Oregon' : 'OR', 'Florida' : 'FL', 'California' : 'CA', 'New York' : 'NY', 'Michigan' : 'MI' } cities = { 'CA' : 'San Francisco', 'MI' : 'Detroit', 'FL' : 'Jacksonville' } cities['NY'] = 'New York' cities['OR'] = 'Portland' #pint out some cities print '-' * 10 print "New York State has: ", cities['NY'] print "Oregon State has: ", cities['OR'] #print some states print '-' * 10 print "Michigan's abbreviation is: ", states['Michigan'] print "Florida's abbreviation is: ", states['Florida'] # do it using the cities and states dicts print '-' * 10 print "Michigan State has: ", cities[states['Michigan']] print "Florida State has: ", cities[states['Florida']] # print every state abbreviation print '-' * 10 for state, abbreviation in states.items() : print "%s is abbreviated as %s." % (state, abbreviation) # print every city in state print '-' * 10 for abbrev, city in cities.items() : print "%s has the city %s" % (abbrev, city) # now do both at the same time print '-' * 10 for state, abbreviation in states.items() : "%s state is abbreviated as %s, and has the city %s" % ( state, abbreviation, cities[abbreviation]) print '-' * 10 # safely get an abbreviation given a state that might not be there state_abbrev = states.get('Texas', None) if not state_abbrev: print "Sorry, no Texas." # get a city with a default value city = cities.get('TX', 'Does not exist') print "The city for the state Texas is: %s" % city # this time we will use get method and succeed print '-' * 10 state_abbrev = states.get("New York") ny_city = cities.get(state_abbrev) if state_abbrev and ny_city : print "The abbreviation for New York state is: %s" % state_abbrev print "New York state has the city: %s" % ny_city
7240e8afe28ed81ca01c1d334f269adeaa89a839
amlanprakash-403/pfa_amlanprakash
/Exercise 3.py
1,602
4.5
4
#!/usr/bin/env python # coding: utf-8 # In[2]: #Write a Python program to check whether the given number is even or not. num = int(input('Enter the number you want to check for even or odd: ')) if num%2 == 0: print('The number entered is even', num) else: print('The number entered is odd', num) # In[5]: #Write a Python program to convert the temperature in degree centigrade to Fahrenheit. Use 30 C to F T = float(input('Enter the temp in degree celcius you want to convert into fahrenheit: ')) F = ((T /100)*180 + 32) print('The temp value you entered after converting into fahrenheit is:', F) # In[7]: #Python program to find the area of a triangle whose sides are given as 4, 3 and 6. #S= (a+b+c)/2 Area = ssqrt(s*(s-a)*(s-b)*(s-c)) import math a = 4 b = 3 c = 6 S = (a+b+c)/2 Area = round(math.sqrt(S*(S-a)*(S-b)*(S-c)),2) print('The area of the triangle is:', Area) # In[8]: #Python program to find the circumference and area of a circle with a given radius import math radius = float(input('Enter the value of radius : ')) area = round(math.pi * (radius **2),2) circumference = round(math.pi * (radius) * 2 ,2) print('The area for the radius you entered is:', area) print('The circumference for the radius you entered is:', circumference) # In[10]: #Python program to check whether the given integer is a multiple of 5 num = int(input('Enter the number you want to check to be a multiple of 5 or not: ')) if num% 5== 0: print('The number you entered is a multiple of 5') else: print('The number you entered is not a multiple of 5') # In[ ]:
d0aa610bcaa9be826bc5701d8dd287de9a8b3001
woongchantonylee/Python-Projects
/Queens.py
2,233
4.0625
4
# File: Queens.py # Description: Simulates old queen puzzle and prints out number of possible solutions depending on size of board # Student Name: Woongchan Lee # Student UT EID: WL8863 # Partner Name: Dohyun Kim # Partner UT EID: DK25659 # Course Name: CS 313E # Unique Number: 85575 # Date Created: 07/12/2019 # Date Last Modified: 07/12/2019 class Queens (object): # initialize the board def __init__(self, n=8): self.board = [] self.n = n self.num_solutions = 0 for i in range(self.n): row = [] for j in range(self.n): row.append('*') self.board.append(row) # print the board def print_board(self): for i in range(self.n): for j in range(self.n): print(self.board[i][j], end=" ") print() print() # check if no queen captures another def is_valid(self, row, col): for i in range(self.n): if (self.board[row][i] == 'Q') or (self.board[i][col] == 'Q'): return False for i in range(self.n): for j in range(self.n): row_diff = abs(row - i) col_diff = abs(col - j) if (row_diff == col_diff) and (self.board[i][j] == 'Q'): return False return True # do a recursive backtracking solution def recursive_solve(self, col): if col == self.n: # Base case # self.print_board() self.num_solutions += 1 else: for i in range(self.n): if self.is_valid(i, col): self.board[i][col] = 'Q' self.recursive_solve(col + 1) self.board[i][col] = '*' # if the problem has a solution print the board def solve(self): self.recursive_solve(0) print('\nNumber of solutions:', self.num_solutions) def main(): num_size = int(input('Enter the size of board: ')) while num_size < 1 or num_size > 16: num_size = int(input('Enter the size of board: ')) # create a chess board game = Queens(num_size) # place the queens on the board game.solve() main()
29b8b8301ad548ab22aa545554aafe7b3d7d5e12
JamesAUre/First-year-of-python
/PythonSem1/firstproject/week2workshop.py
442
4.15625
4
import random def coinflip(): heads = 0 tails = 0 unknown = 0 userinput = int(input("How times would you like to flip the coin? ")) for i in range(0,userinput): x = random.randrange(0, 3) if x == 0: heads = heads + 1 elif x == 1: tails = tails + 1 elif x == 2: unknown = unknown + 1 print(heads, "heads,", tails, "tails and", unknown, "unknowns") return coinflip()
fea9c9a4deb9d09218eb3957ed0a74fe7b760609
DenysZakharovGH/Python-works
/HomeWork4/The_Guessing_Game.py
624
4.15625
4
#The Guessing Game. #Write a program that generates a random number between 1 and 10 and let’s #the user guess what number was generated. The result should be sent back #to the user via a print statement. import random RandomVaried = random.randint(0,10) while True: UserGuess = int(input("try to guess the number from 0 to 10 :")) if UserGuess>=0 and UserGuess <= 10: if UserGuess > RandomVaried: print("Less") elif UserGuess < RandomVaried: print("more") else: print("BINGO") else:print("wrong number") if(input("q for try again") !='q'): break
65c6f5d9baebde5d11a4533c1cb2812032842eea
Khalid-Sultan/Phase-2-Algorithms-Prep
/Leetcode/Stacks,_Queues/2_-_Medium/71._Simplify_Path.py
867
3.703125
4
from collections import deque class Solution: def simplifyPath(self, path: str) -> str: res = "" buffer = deque() start = True l = "" for i in range(1, len(path)): if path[i]=='/': l+='/' if l=="../": if buffer: buffer.pop() elif l=="./" or l=="/": l = "" elif l!="": buffer.append(l) l = "" else: l+=path[i] if l=="..": if buffer: buffer.pop() elif l!="." and l!="": buffer.append(l) if buffer and buffer[-1][-1]=='/': s = buffer.pop() buffer.append(s[:-1]) return "/" + "".join(buffer)
da543c6294648d4b472ea1560d9e4e135673700c
sanju5445/python_program.github.io
/class_abstrac&encap6.py
1,148
3.796875
4
class Employee: company_name='TCS' def __init__(self,name,role,salary): self.name=name self.role=role self.salary=salary def speak(self): return f"hi i am {self.name} , i am {self.role}, and my salary is {self.salary}" @staticmethod def fn(): return "thanks for using me" sanju=Employee("sanju roy","machine learning engineer",555) kali=Employee("kali","hacker",545) sanju.speak() # INHERITANCE INHERITENCE INHERITENCE class Programmer(Employee): def __init__(self,name,role,salary,languages): self.name = name self.role = role self.salary = salary self.languages=languages def spk(self): return f"hi i am {self.name} , i am {self.role}, and my salary is {self.salary} and i know {self.languages} languages" s1=Programmer("rakesh","developer",525,['python','java']) s2=Programmer("rahim","front_end_developer",545,['python','cp']) print(s1.company_name) print(s1.spk()) print(s1.languages) def jj(): for i in (s1.languages): print(i) for j in i: print(j) print(s1.fn())
3e0d97320d3da96e13c880132a1b53c7aa587630
tonberarray/datastructure-and-algrorithm
/线性表操作/链表/双向链表.py
2,168
3.984375
4
# dual_link_List 双向链表 class DualNode(object): """docstring for DualNode""" def __init__(self, val=None): self.val = val self.prior = None self.next = None self.visited = False class DualLinkList(object): """docstring for DualLinkList""" def __init__(self): self.head = None def createList(self,num): """创建num个节点的双向链表""" if isinstance(num, int) == False: print("error: not type:int") return if num <=0: return None head = None val = chr(65) cur = None n = 0 while num > 0: val = chr(65 + n) node = DualNode(val) if head is None: head = node cur = head else: node.next = cur.next node.prior = cur cur.next = node cur = cur.next n += 1 num -= 1 self.head = head return head def createCircleList(self, num): """创建num个节点的双向循环链表""" if isinstance(num, int) == False: print("error: not type:int") return if num <=0: return None head = None val = chr(65) cur = None n = 0 while num > 0: val = chr(65 + n) node = DualNode(val) if head is None: head = node cur = head else: node.next = cur.next node.prior = cur cur.next = node cur = cur.next n += 1 num -= 1 cur.next = head head.prior = cur self.head = head return head def travel(self, head): """遍历链表""" if isinstance(head, DualNode) == False: print('error: This arguement is invalid') return if head is None: print('None') return cur = head while cur.next != head and cur.next != None: print(f'{cur.val}', end='') cur = cur.next print(f'{cur.val}') def caesar(self,n): """Caesar Code加密模式""" if isinstance(n, int) == False: print("error: not type:int") return head = self.createCircleList(26) if n == 0: self.travel(head) elif n < 0: m = n while m < 0: head = head.prior m += 1 self.travel(head) else: for _ in range(n): head = head.next self.travel(head) l = DualLinkList() head = l.createCircleList(26) l.travel(head) l.caesar(-3) print(len('13')) # a = chr(65) # m = ord('A') # print(a,m)
749a57cbdd0b86c771968c279fa9b6e2a7844feb
lockmachine/DeepLearningFromScratch
/ch05/buy_apple_orange.py
1,307
3.5
4
#!/usr/bin/env python # coding: utf-8 from layer_native import * apple = 100 apple_num = 2 orange = 150 orange_num = 3 tax = 1.1 mul_apple_layer = MulLayer() mul_orange_layer = MulLayer() add_apple_orange_layer = AddLayer() mul_tax_layer = MulLayer() apple_price = mul_apple_layer.forward(apple, apple_num) orange_price = mul_orange_layer.forward(orange, orange_num) apple_orange_price = add_apple_orange_layer.forward(apple_price, orange_price) price = mul_tax_layer.forward(apple_orange_price, tax) print("FORWARD---") print("apple_price = {}".format(apple_price)) print("orange_price = {}".format(orange_price)) print("apple_orange_price = {}".format(apple_orange_price)) print("price = {}".format(price)) dprice = 1 dapple_orange_price, dtax = mul_tax_layer.backward(dprice) dapple_price, dorange_price = add_apple_orange_layer.backward(dapple_orange_price) dapple, dapple_num = mul_apple_layer.backward(dapple_price) dorange, dorange_num = mul_orange_layer.backward(dorange_price) print("BACKWARD---") print("dapple, dapple_num = {}, {}".format(dapple, dapple_num)) print("dorange, dorange_num = {}, {}".format(dorange, dorange_num)) print("dapple_price, dorange_price = {}, {}".format(dapple_price, dorange_price)) print("dapple_orange_price, dtax = {}, {}".format(dapple_orange_price, dtax))
f6ce5644a852f6583c217ad10015290c4a36d62d
DFTFFT/DoublePendulum
/double_pendulum.py
3,149
3.625
4
# solve the ODEs for double-pendulum problem import numpy as np from scipy import sin, cos from scipy.integrate import odeint import matplotlib.pyplot as pl class DoublePendulum(object): """Define the double pendulum class""" def __init__(self, m1, m2, l1, l2): self.m1, self.m2, self.l1, self.l2 = m1, m2, l1, l2 self.status = np.array([0.0,0.0,0.0,0.0]) #[th1, th2, v1, v2] def equations(self, w, t): """ return the derivatives for each variable""" # the input argument w is the state of all target varialbes g = 9.8 m1, m2, l1, l2 = self.m1, self.m2, self.l1, self.l2 th1, th2, v1, v2 = w dth1 = v1 dth2 = v2 #eq of th1 a = l1*l1*(m1+m2) # dv1 parameter b = l1*m2*l2*cos(th1-th2) # dv2 paramter c = l1*(m2*l2*sin(th1-th2)*dth2*dth2 + (m1+m2)*g*sin(th1)) #eq of th2 d = m2*l2*l1*cos(th1-th2) # dv1 parameter e = m2*l2*l2 # dv2 parameter f = m2*l2*(-l1*sin(th1-th2)*dth1*dth1 + g*sin(th2)) dv1, dv2 = np.linalg.solve([[a,b],[d,e]], [-c,-f]) return np.array([dth1, dth2, dv1, dv2]) def ode_solve(self, t): """ Solve the system of equations describing the motion of the double pendulum""" track = odeint(self.equations, self.status, t) th1, th2 = track[-1, 0], track[-1, 1] x1 = self.l1*np.sin(th1) y1 = -self.l1*np.cos(th1) x2 = x1 + self.l2*np.sin(th2) y2 = y1 - self.l2*np.cos(th2) self.status = track[-1,:].copy() return [x1, y1, x2, y2, th1, th2] def euler_ode(self, t, dt): """ Euler method to solve the ODEs""" # obtain the derivatives of the angle variables (dth1, dth2, d2th1, d2th2) deri = self.equations(self.status, t) dth1 = deri[0] dth2 = deri[1] d2th1 = deri[2] d2th2 = deri[3] # get values for the new timestep by adding the increment #[th1, th2, v1, v2] self.status[0] += dth1*dt self.status[1] += dth2*dt self.status[2] += d2th1*dt self.status[3] += d2th2*dt # while abs(self.status[0]) > np.pi: if self.status[0] > 0.0: self.status[0] -= 2*np.pi else: self.status[0] += 2*np.pi while abs(self.status[1]) > np.pi: if self.status[1] > 0.0: self.status[1] -= 2*np.pi else: self.status[1] += 2*np.pi # convert the angle to the cartesian coordinates x1 = self.l1*np.sin(self.status[0]) y1 = -self.l1*np.cos(self.status[0]) x2 = x1 + self.l2*np.sin(self.status[1]) y2 = y1 - self.l2*np.cos(self.status[1]) return [x1, y1, x2, y2, self.status[0], self.status[1]] if __name__ == "__main__": """to test the double_pendulum module""" pendulum = DoublePendulum(1.0, 2.0, 1.0, 2.0) th1, th2 = 1.0, 2.0 pendulum.status[:2] = th1, th2 ts = 0.0 te = 30.0 tstep = 0.01 t = np.arange(ts, te, tstep) x1 = [] y1 = [] x2 = [] y2 = [] for tim in t: time = np.array([tim, tim+tstep]) result = pendulum.ode_solve(time) #result = pendulum.euler_ode(tim, tstep) x1.append(result[0]) y1.append(result[1]) x2.append(result[2]) y2.append(result[3]) pl.plot(x1,y1, label = "upper") pl.plot(x2,y2, label = "lower") pl.legend() pl.axis("equal") pl.show()
65d366849476615b466110774c06a282f9eba1c9
shinhermit/simple-regression-demo
/plot_3_lines_crossing_2d.py
2,169
4.0625
4
""" Plot side by side: - 3 lines all crossing at 1 point - 3 lines crossing no more at a single point after a slight change in 1 parameter Used to illustrate the section "Limits of an algebraical solution" of the first article about linear regression. """ import numpy from matplotlib import pyplot from equations import LineParametricEquation def configure_plot(t: numpy.ndarray): """ Configures the drawing. Set the initial reference frame limits, among other settings. :param t: the parameter of the line to draw. """ pyplot.xlim(t.min(), t.max()) pyplot.ylim(t.min(), t.max()) pyplot.xlabel('X') pyplot.ylabel('Y') pyplot.grid() def update_plot_limits(x: numpy.ndarray, y: numpy.ndarray): """ Update the limits of the reference frame given the x and y coordinates of some points drawn in the figure. :param x: x coordinates of the points :param y: y coordinates of the points """ x_max = max(abs(x.max()), abs(x.min())) x_lim = pyplot.xlim() pyplot.xlim(min(-x_max, x_lim[0]), max(x_max, x_lim[1])) y_max = max(abs(y.max()), abs(y.min())) y_lim = pyplot.ylim() pyplot.ylim(min(-y_max, y_lim[0]), max(y_max, y_lim[1])) def draw_line(f: LineParametricEquation, t: numpy.ndarray, **kwargs): """ Plot a line on the figure. :param f: parametric equation of a line. :param t: values of the parameter to use for the plotting. :param kwargs: additional parameters of the plotting function. """ x, y = f(t) pyplot.plot(x, y, **kwargs) update_plot_limits(x, y) def main(): p = numpy.array([2, 1]) f = LineParametricEquation(p, u=numpy.array([1, 1])) g = LineParametricEquation(p, u=numpy.array([1, -1])) h = LineParametricEquation(p, u=numpy.array([.2, -1])) t = numpy.array([-5, 5]) configure_plot(t) draw_line(f, t, color='red') draw_line(g, t, color='green') draw_line(h, t, color='blue', linewidth=1, linestyle='dashed') draw_line(h.update(p=p+0.01), t, color='blue') pyplot.show() if __name__ == "__main__": main()
fb6634d75cca3515e5ceb08419ea3f37cbd58784
MinjeongKim98/Team4
/week2/20171592-김병관-assignment2.py
472
3.875
4
num = 0 test = 0 while True: try: fnum = float(input('input number:')) if fnum % 1 != 0: continue if fnum < 0: if fnum == -1: break else: continue hi = 1 num = int(fnum) for i in range(1,num+1): hi *= i print(hi) except ValueError: print('숫자 아냐')
833cac5dcc2b3c26de3cde9b452a900700a84f25
paulburnz314/Top_ten_python_tricks
/lab_data_qualifiers.py
1,283
3.5625
4
''' When you get a lab report the results somestimes have qualifiers such as '>' or '<' the method detection limit or practical quantitation limit. If you need to use this number in a calculation you will need to strip any non numeric characters. Most likely you will get data from an excel or csv file. ''' def replaceMultiple(mainString, toBeReplaces, newString): # Iterate over the strings to be replaced for elem in toBeReplaces: # Check if string is in the main string if elem in mainString: # Replace the string mainString = mainString.replace(elem, newString) return mainString def remove_q(lab_result): checkstr = isinstance(lab_result, str) # start checking for <, >, empty space or None values if checkstr is True: lab_result = replaceMultiple(lab_result, ['>', '<'], '') if lab_result == ' ': lab_result = 0 elif lab_result is None: lab_result = 0 else: lab_result = float(lab_result) # data is cleaned up and converted to a number return lab_result if __name__ == '__main__': print("Example:") print(remove_q('< 37.1')) assert remove_q('>167') == 167 assert remove_q('<46.6') == 46.6 assert remove_q('<0.10') == 0.10 assert remove_q(' ') == 0 assert remove_q(99.5) == 99.5
92dcf694068b868170d43b5b328bd8d5e91e653e
feliksce/euler
/prob2.py
862
4.09375
4
# Even Fibonacci numbers # Problem 2 # # Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. # first = 1 # second = 2 # # print(first, second, sep="\n") # # for each in range(8): # temp = first + second # first = second # second = temp # print(each+3, second) first = 1 second = 2 term_sum = 2 ran = 4000000 for each in range(ran-2): print("\rIteration {} from {} [{:.1%}]".format(each+1, ran-2, (each+1)/(ran-2)), end="") temp = first + second first = second second = temp if second % 2 == 0: term_sum += (each + 3) print("\nSum: {}".format(term_sum))
7c7765949ca08d4c6ed082247883a19f1992fdb6
andrefacundodemoura/exercicios-Python-brasil
/exercicios_python_brasil/lista02_estrutura_de_decisao/ex02verifica_num.py
313
4.03125
4
''' 02. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. ''' num = float(input('Digie um valor qualquer: ')) if num < 0: print(f'O numero digitado [{num}] é negativo.') elif num == 0: print('0 é nulo') else: print(f'O numero digitado [{num}] é positivo.')
a812bac1c1bc91d3b9b6a4968b2d6fa69a19dde2
vivekjaiswal90/datascience
/game python/keyboardmove.py
2,334
4.375
4
# Sample Python/Pygame Programs # Simpson College Computer Science # http://programarcadegames.com/ # http://simpson.edu/computer-science/ import pygame black = (0,0,0) white = (255,255,255) # This class represents the bar at the bottom that the player controls class Player(pygame.sprite.Sprite): # -- Attributes # Set speed vector change_x=0 change_y=0 # -- Methods # Constructor function def __init__(self,x,y): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Set height, width self.image = pygame.Surface([15, 15]) self.image.fill((white)) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y # Change the speed of the player def changespeed(self,x,y): self.change_x+=x self.change_y+=y # Find a new position for the player def update(self): self.rect.x += self.change_x self.rect.y += self.change_y # Call this function so the Pygame library can initialize itself pygame.init() # Create an 800x600 sized screen screen = pygame.display.set_mode([800, 600]) # Set the title of the window pygame.display.set_caption('Test') # Create the player object player = Player( 50,50 ) movingsprites = pygame.sprite.Group((player)) clock = pygame.time.Clock() done = False while done == False: for event in pygame.event.get(): if event.type == pygame.QUIT: done=True # Set the speed based on the key pressed if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.changespeed(-3,0) if event.key == pygame.K_RIGHT: player.changespeed(3,0) if event.key == pygame.K_UP: player.changespeed(0,-3) if event.key == pygame.K_DOWN: player.changespeed(0,3) # Reset speed when key goes up if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.changespeed(3,0) if event.key == pygame.K_RIGHT: player.changespeed(-3,0) if event.key == pygame.K_UP: player.changespeed(0,3) if event.key == pygame.K_DOWN: player.changespeed(0,-3) # This actually moves the player block based on the current speed player.update() # -- Draw everything # Clear screen screen.fill(black) # Draw sprites movingsprites.draw(screen) # Flip screen pygame.display.flip() # Pause clock.tick(40) pygame.quit()
ee14cfc30a7d9f4c8bf99f7d90beeb688f912929
betty29/code-1
/recipes/Python/65126_Dictionary_of_MethodsFunctions/recipe-65126.py
450
3.78125
4
import string def function1(): print "called function 1" def function2(): print "called function 2" def function3(): print "called function 3" tokenDict = {"cat":function1, "dog":function2, "bear":function3} # simulate, say, lines read from a file lines = ["cat","bear","cat","dog"] for line in lines: # lookup the function to call for each line functionToCall = tokenDict[line] # and call it functionToCall()
f07b36a7bfef734419ded09925cf3b4ae23c8bb5
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/patchcarrier/Lesson04/mailroom2.py
5,801
3.796875
4
#!/usr/bin/env python3 donors = {"Conrad Anker":[550, 1200, 0.02], "Tommy Caldwell":[600.50, 80], "Margo Hayes":[200, 550.50], "Alex Honnold":[0.01], "Paige Claassen":[750, 800, 150.25]} def prompt_user(prompt, acceptable_vals): """Prompt the user for an input until the input is an element of acceptable_vals. :param prompt: Prompt to display to the user with acceptable commands :param acceptable_vale: An iterable of acceptable characters """ user_input = input(prompt) while user_input not in acceptable_vals: print("\nInput character '{}' not recognized".format(user_input)) user_input = input(prompt) return user_input def menu(prompt, disp_dict): """Execute the commands specified by the user until they specify to quit. :param prompt: Prompt to display to the user with acceptable commands :param disp_dict: A dictionary with string keys corresponding to the acceptable commands and function object values. """ # Get initial user input (only accept user inputs that are in the dispatch # dictionary keys) user_input = prompt_user(prompt, disp_dict.keys()) # Continue asking for user input until they specify to quit while user_input != 'q': disp_dict.get(user_input)() user_input = prompt_user(prompt, disp_dict.keys()) def thankyou_menu(): """Prompt the user to enter information about a donation and record the user input in the global data structure. """ thanks_prompt = """\nSpecify Donation Menu Enter: (l) to list the names of previous donors (e) to create a new donation entry and send a thank you email (q) to quit and return to the main menu >>> """ thanks_disp_dict = {'l':list_donors, 'e':enter_donor, 'q': lambda : None} menu(thanks_prompt, thanks_disp_dict) def list_donors(): "List all of the donors in the global data structure." print() for donor_i in donors: print(donor_i) def enter_donor(): """Enter the donor name and donation amount into the global data structure and send a thank you email. """ name_in = input("\nEnter the full name of the donor (or 'q' to quit)" "\n>>> ") if name_in == 'q': return amount_in = input("\nEnter the donation amount (or 'q' to quit)" "\nEnter numbers only, do not enter special characters" "\n>>> ") if amount_in == 'q': return amount_in = float(amount_in) # check if the donor already exists, if they do, add this donation to # their history, otherwise, create a new donor entry in the data structure if name_in in donors: donors[name_in].append(amount_in) else: donors[name_in] = [amount_in] send_email(dict(name=name_in, amount=amount_in)) def send_email(donation_dict): "Send a thank you email to donor for the specified amount." body = ("\n\nThank you {name} for your generous donation of ${amount:.2f} to " "Vertical Generation.\n\nWe greatly appreciate your support for our cause." "\n\n-patchcarrier") print(body.format(**donation_dict)) def write_report(): "Print a tabulated summary of all donors and donations to the screen." # Header print("\n{:<25s}|{:^13s}|{:^11s}|{:^14s}".format("Donor Name", "Total Given","Num Gifts","Average Gift")) print("-" * (25 + 13 + 11 + 14 + 3)) fstring = "{:<25s} ${:>12.2f} {:>11d} ${:>13.2f}" # Sort the global data structure by donation amount donor_names = list(donors.keys()) donor_names.sort(reverse=True, key=lambda donor_i: sum(donors[donor_i])) # Print the summary of donation data for name_i in donor_names: total_given = sum(donors[name_i]) n_gifts = len(donors[name_i]) print(fstring.format(name_i, total_given, n_gifts, total_given/n_gifts)) def send_letters(): email_text = """Dear {name}, Thank you for your continued support of Vertical Generation. Your {num_donations:d} donation{s_string1} totaling ${donation_sum:.2f} help{s_string2} us continue to share rock climbing with the underserved youth in Seattle. Sincerely, -patchcarrier """ for donor_i in donors: filename_i = donor_i + '.txt' filename_i = filename_i.replace(' ','_') with open(filename_i,'w') as outfile: #check the number of donations for the current donor, if it's only #one, donations should not be plural num_donations = len(donors.get(donor_i)) if num_donations > 1: s_string1 = 's' s_string2 = '' else: s_string1 = '' s_string2 = 's' donation_sum = sum(donors[donor_i]) outfile.write(email_text.format(name=donor_i, num_donations=num_donations, s_string1=s_string1, s_string2=s_string2, donation_sum=donation_sum)) ############### Program Block ############### if __name__ == "__main__": main_prompt = """\nMain Menu Enter: (t) to send a thank you letter (c) to create a report (s) to send letters to everyone (q) to quit >>> """ main_disp_dict = {'t':thankyou_menu, 'c':write_report, 's':send_letters, 'q': lambda : None} menu(main_prompt, main_disp_dict)
764c3d6a87619731b390b0360658e0e98bc8c704
naderalexan/sexy-python
/single_truthy_value.py
321
4.03125
4
""" Using iterators to check for one and only one truthy in a list """ def single_truthy_val(arr): my_iter = iter(arr) return any(my_iter) and not any(my_iter) if __name__ == "__main__": arr = [0, 1, 0, 0] assert single_truthy_val(arr) arr = [0, 1, 0, 0, 1] assert not single_truthy_val(arr)
a0bfb18e42b74794b86310438b45978df6f62fa5
twothicc/Algorithms
/sorting_techniques.py
24,350
3.796875
4
import random import time import math def test(ftn, xs) : start = int(time.time() * 1000) ftn(xs) end = int(time.time() * 1000) print("Time taken using {0} on list size {1} is {2}".format(ftn.__name__, len(xs), end - start)) def counting_sort_test(ftn, xs, xs_range) : start = int(time.time() * 1000) ftn(xs, xs_range) end = int(time.time() * 1000) print("Time taken using {0} on list size {1} is {2}".format(ftn.__name__, len(xs), end - start)) def generate_random_xs(size, sample_range) : lst = [] for i in range(sample_range + 1) : lst.append(i) lst = random.sample(lst, size) return lst lst = generate_random_xs(100000, 1000000) #quicksort has a runtime complexity of O(n * log n) def quick_sort(xs) : def add(xs, n, ys) : if xs == None : return n + ys elif ys == None : return xs + n else : return xs + n + ys def partition(xs, n) : #Rmbr to not include the pivot. If the pivot is included, infinite recursion will happen #Imagine you have 2 and 2, you'd move both 2s into the prev and infinite recursion occurs head = [] tail = [] xs.remove(n) for idx in range(len(xs)) : if xs[idx] <= n : head.append(xs[idx]) elif xs[idx] > n : tail.append(xs[idx]) return [[n] , head, tail] #Handles empty list cases if len(xs) == 0 : return None #If only one element left, there's nothing left to sort elif len(xs) == 1 : return xs else : partitioned = partition(xs, xs[random.randint(0, len(xs) - 1)]) #Recursive return add(quick_sort(partitioned[1]), partitioned[0], quick_sort(partitioned[2])) #Merge sort has a runtime complexity of O(n * log n) def merge(xs) : def middle(xs) : return math.floor(len(xs) / 2) def merge_sort(xs, ys) : merged = [] i = 0 j = 0 while i < len(xs) or j < len(ys) : if i >= len(xs) : merged += ys[j:] break elif j >= len(ys) : merged += xs[i:] break else : if xs[i] <= ys[j] : merged.append(xs[i]) i += 1 else : merged.append(ys[j]) j += 1 return merged if (len(xs) <= 2) : return xs else : mid = middle(xs) return merge_sort(merge(xs[:mid]), merge(xs[mid:])) #Insertion_sort has a runtime complexity of O(n^2) def insertion_sort(xs) : #For every element in list, check the preceding elements for any larger elements from the start #If larger, swap. Now we use the swapped element to check what's left of the preceding elements #O(n^2) runtime for idx in range(len(xs)) : for prev in range(idx) : if xs[idx] <= xs[prev] : xs[idx] , xs[prev] = xs[prev] , xs[idx] return xs #Selection_sort has a runtime complexity of O(n^2) def selection_sort(xs) : result = [] for i in range(len(xs)) : smallest = xs[0] for idx in range(len(xs)) : if xs[idx] <= smallest : smallest = xs[idx] result.append(smallest) xs.remove(smallest) return result #Counting_sort has a runtime complexity of O(n + k) whereby k is the range def counting_sort(xs, xs_range) : #Initialize counter vector counts = [0] * (xs_range + 1) for idx in range(len(xs)) : counts[xs[idx]] += 1 #Create copy of xs xs2 = [] #Appends count of values into xs2 for val in range(xs_range + 1) : xs2 += [val] * counts[val] return xs2 #radix_sort has a runtime complexity of O((n+b) * logb(k)) where b is the base and k is the largest possible value def radix_sort(xs) : def find_place(n, b) : return n // b % 10 def radix_place_sort(xs, base) : counts = {} #set up counts dict for i in range(10) : counts[i] = 0 for idx in range(len(xs)) : counts[find_place(xs[idx], base)] += 1 for count in range(1, 10) : counts[count] += counts[count - 1] ys = [None for x in xs] for i in range(len(xs)) : idx = len(xs) - i - 1 val = find_place(xs[idx], base) # if val == 0 : # ys[counts[0] - 1] = xs[idx] # counts[0] -= 1 # else : ys[counts[val] - 1] = xs[idx] counts[val] -= 1 return ys max_val = max(xs) num_bases = math.ceil(math.log(max_val, 10)) for bases in range(num_bases) : base = 10 ** bases xs = radix_place_sort(xs, base) return xs # print(counting_sort([1,6,5],6)) # print(radix_sort([1,23,453,24,12])) #Bubble_sort has a runtime complexity of O(n^2) #For every element in list, it checks with every following element in list. If its larger, it swaps and continues checking def bubble_sort(xs) : for idx in range(len(xs)) : for j in range(idx, len(xs)) : if xs[idx] > xs[j] : xs[idx], xs[j] = xs[j], xs[idx] return xs #Super Weenie Hub Jr #Do not do these for lists > 10000 in size. Its crazy long #test(insertion_sort, lst) #test(bubble_sort, lst) #test(selection_sort, lst) #Fast af club #counting_sort_test(counting_sort, lst, 10000000) #test(quicksort, lst) #test(merge, lst) #Sometimes fast sometimes slow club #test(radix_sort, lst) def binary_search(xs, n) : def binary_search_inner(xs, l, r, n) : mid = l + math.floor((r - l) / 2) if xs[mid] == n : return mid elif xs[mid] < n : return binary_search(xs, 0, mid - 1, n) else : return binary_search(xs, mid + 1, r, n) return binary_search_inner(xs, 0, len(xs) - 1, n) class Node(object) : def __init__(self, n) : self.entry = n self.left = None self.right = None #Inserting a value into the bst. Return True/False for Success/Failure def insert(self, n) : #If entry is None, means left, right branch are None too, change entry to value if self.entry == None : self.entry = n return True else : #If entry is equals to n, n is a duplicate value, bst cannot take duplicate values if n == self.entry : return False #If n is less then entry elif n < self.entry : #If left child node is None, means we can insert value as a new Node as a left branch if self.left == None : self.left = Node(n) return True #If left child node is a value, means we have to continue traversing down the tree else : return self.left.insert(n) #If n is more than entry else : #If right child node is None, means we can insert value as a new Node as a right branch if self.right == None : self.right = Node(n) return True #If right child node is a value, means we have to continue traversing down the tree else : return self.right.insert(n) #For finding whether a value exists in bst. returns True/False for Exist/Absent def find(self, n) : #If entry is equals to n, means value exists if self.entry == n : return True #If n is less than entry, its in left branch elif n < self.entry : #If left child node is None, n cannot exist in bst if self.left == None : return False #If left child node is a value, n can exist in left branch else : return self.left.find(n) #If n is more than entry, its in right branch else : #If right child node is None, n cannot exist in bst if self.right == None : return False #If right child node is a value, n can exist in right branch else : return self.right.find(n) #For conversion to list def show(self) : #The order in the equations determine how we traverse the bst, very impt if self.entry != None : if self.left == None and self.right == None : return [self.entry] elif self.left == None : return [self.entry] + self.right.show() elif self.right == None : return self.left.show() + [self.entry] else : return self.left.show() + [self.entry] + self.right.show() else : return [] #Visualize the tree #We use level here to represent the level from which we found a value entry def draw(self, level) : #Again the order in the equations here allow us to just pick the last element in the list later if self.entry != None : if self.left == None and self.right == None : return [[str(self.entry), level]] elif self.left == None : return [[str(self.entry), level]] + self.right.draw(level + 1) elif self.right == None : return [[str(self.entry), level]] + self.left.draw(level + 1) else : return [[str(self.entry), level]] + self.left.draw(level + 1) + self.right.draw(level + 1) else : return [] #Find maximum value def max(self) : #Keep searching till right Node is None #Don't have to worry about a None entry with 2 None leaf nodes because the None will be accounted for if self.right == None : return self.entry else : return self.right.find_max() #Remove a value from the tree. returns True/False for success/failure def remove(self, n) : #If entry is not n, no need to remove if self.entry != n : if n < self.entry : #If left node is None, means element to be removed does not exist if self.left == None : return False #If left node is a value, means element to be removed could be in left branch else : return self.left.remove(n) else : #If right node is None, means element to be removed does not exist if self.right == None : return False #If right node is a value, means element to be removed could be in right branch else : return self.right.remove(n) #If entry is n, removal needs to happen, consider 4 cases else : #If both child nodes are None if self.left == None and self.right == None : self.entry = None return True #If only left child node is None elif self.left == None : self.entry = self.right.entry self.left = self.right.left self.right = self.right.right return True #If only right child node is None elif self.right == None : self.entry = self.left.entry self.left = self.left.left self.right = self.left.right return True #If both child nodes have values. Could be containing 1 node or multiple nodes else : #Find maximum entry in left branch left_maximum = self.left.max() #Convert left branch to list left_list = self.left.show() #Remove maximum entry from list left_list.remove(left_maximum) #Set entry to be the maximum entry, effectively removing n self.entry = left_maximum #This handles the case whereby the left branch only contains 1 node first = None #This handles the case whereby left branch has multiple nodes if len(left_list) != 0: first = Node(left_list[0]) #Cannot just attach a bst object here #Must build a new bst from only Node objects. for idx in range(1, len(left_list)) : first.insert(left_list[idx]) #Attach the new tree as the left branch of the node self.left = first return True #Functions include : #insert(n), find(n), to_list(), remove(n), str() class BST(object) : def __init__(self, xs = []) : #Base case shld return an empty bst self.root = Node(None) #We're essentially building a tree here using insert functions repeatedly on the root node for idx in range(len(xs)) : if self.root.entry != None : if not self.root.insert(xs[idx]) : print('Duplicate entry {0} not added'.format(xs[idx])) else : self.root.entry = xs[idx] def insert(self, n) : if not self.root.insert(n) : print('duplicate {0} not inserted'.format(n)) def find(self, n) : return self.root.find(n) def to_list(self) : return self.root.show() def remove(self, n) : #Just for visual purposes if self.root.remove(n) : print('{0} removed'.format(n)) return True else : print('{0} is not found in BST'.format(n)) return False #Overloading str() function for bst object def __str__(self) : #Who cares about auxiliary space lst = self.root.draw(0) levels = lst[len(lst) - 1][1] + 1 level = [] for i in range(levels) : level.append([]) for i in range(len(lst)) : level[lst[i][1]].append(lst[i][0]) result = '' for lvl in level : result += ' , '.join(lvl) + '\n' return result # tree = BST([1,4,8,9,12,3]) # #Test drawing tree # print(str(tree)) # #Test find and insert # print(tree.find(2)) # tree.insert(2) # print(tree.find(2)) # print(tree.to_list()) # #Test remove on root node # print(str(tree)) # tree.remove(1) # print(tree.to_list()) # tree.insert(1) # print(str(tree)) # #Test remove on leaf node # tree.remove(12) # print(tree.to_list()) # #Test if structure of bst is still intact after removing leaf node # tree.insert(12) # print(tree.to_list()) # print(tree.remove(12)) # tree.insert(11) # print(tree.to_list()) #heap_sort has n * log n runtime complexity with 1 space complexity def heap_sort(lst) : #length here limits the index of the maxheap that max_heapify will check till. This allows us to not check #already sorted indexes def heapify(lst, index, length): idx = index largest = index #changes largest to the index of the largest value between idx, idx * 2, idx * 2 + 1 if (idx * 2 + 1) < length: if lst[idx * 2 + 1] > lst[idx * 2]: if lst[idx * 2 + 1] > lst[idx]: largest = idx * 2 + 1 else: if lst[idx * 2] > lst[idx]: largest = idx * 2 elif idx * 2 < length: if lst[idx * 2] > lst[idx]: largest = idx * 2 #if largest was not idx, heapify must be applied to new sub branch as well if largest != idx: lst[idx], lst[largest] = lst[largest], lst[idx] heapify(lst, largest, length) def max_heapify(lst, length) : #is_change checks if anything has been changed max_half = len(lst) // 2 for i in range(max_half) : idx = max_half - i - 1 heapify(lst, idx, length) #length will determine the index in maxheap to check to. Rmbr index in this maxheap goes from 1,2,3,... so dunnid to minus 1 length = len(lst) #Generate max heap max_heapify(lst, length) while length > 1 : #Swap first and last element, which are largest and smallest, then pop the last element, which is now largest lst[0], lst[length - 1] = lst[length - 1], lst[0] length -= 1 #Re heapify lst heapify(lst, 0, length) return lst def map2(f, xs) : result = [] for i in map(f, xs) : result.append(i) return result; def remove2(x, xs) : xs.remove(x) return xs #Finds combinations of values in list that would give a target value def combinations(xs, current, target) : if current == target : return [[]] elif len(xs) == 0 : return [] else : a = combinations(xs[1:], current, target) b = map2(lambda x : [xs[0]] + x, combinations(xs[1:], current + xs[0], target)) return b + a #print(combinations([1,5,5,10,20,5,10], 0, 25)) # weights = [2,4,3,8,5] # profits = [10,24,12,15,18] def fractional_knapsack(ws, ps, W) : def quick_sort_altered(xs, ys) : def partition(x, y, xs, ys) : lesser_xs = [] lesser_ys = [] greater_xs = [] greater_ys = [] xs.remove(x) ys.remove(y) for i in range(len(xs)) : if (ys[i] / xs[i]) <= (y / x) : lesser_xs.append(xs[i]) lesser_ys.append(ys[i]) else : greater_xs.append(xs[i]) greater_ys.append(ys[i]) return [lesser_xs, lesser_ys, greater_xs, greater_ys] if len(xs) == 0 : return [] else : pivot_xs = xs[0] pivot_ys = ys[0] result = partition(pivot_xs, pivot_ys, xs, ys) return quick_sort_altered(result[0], result[1]) + [[pivot_xs, pivot_ys]] + quick_sort_altered(result[2], result[3]) sorted_list = quick_sort_altered(ws, ps) current_weight = 0 current_profit = 0 for idx in range(len(sorted_list)) : if current_weight + sorted_list[idx][0] <= W : current_weight += sorted_list[idx][0] current_profit += sorted_list[idx][1] print("picked {0} of item {1} and gained {2} profit".format(sorted_list[idx][0], idx, sorted_list[idx][1])) else : missing_weight = W - current_weight ratio = missing_weight / sorted_list[idx][0] profit_gained = ratio * sorted_list[idx][1] current_profit += profit_gained print("picked {0} of item {1} and gained {2} profit".format(missing_weight, idx, profit_gained)) break return current_profit def knapsack(ws, ps, n, W) : #If there's nothing left to pick, then we have to return 0 for no value added due to nothing being picked if n < 0 or W == 0 : return 0 elif ws[n] > W : #If weight of ws is more than W, then we cannot pick it, drop the selection return knapsack(ws, ps, n - 1, W) else : #return the maximum of either combinations selecting a value at index, and combinations that don't select that value return max(ps[n] + knapsack(ws, ps, n - 1, W - ws[n]), knapsack(ws, ps, n - 1, W)) # val = [60, 100, 120, 80, 160] # wt = [10, 20, 30, 10, 20] # W = 50 # print(knapsack(wt, val, len(wt) - 1, W)) def coin_change_restrict(coins, types, T, M) : coin_idx = [[types, 0] for t in types] def smaller(xs, ys) : if len(xs) < len(ys) : if len(xs) == 0 : return ys else : return xs else : if len(ys) == 0 : return xs else : return ys def coin_change(coins, coin_idx, n, combi, curr, T, M) : if T == 0 or n < 0 : return [] elif curr == T : return combi elif curr + coins[n] > T : return coin_change(coins, coin_idx, n - 1, combi, curr, T, M) else : selection = coins[n] to_add = True new_coin_idx = [] for i in coin_idx : if i[0] == selection : if i[1] == M : to_add = False break new_coin_idx.append([i[0],i[1] + 1]) else : new_coin_idx.append(i) if to_add : return smaller(coin_change(coins, coin_idx, n - 1, combi, curr, T, M), coin_change(coins, new_coin_idx, n - 1, [selection] + combi, curr + selection, T, M)) else : return coin_change(coins, coin_idx, n - 1, combi, curr, T, M) return coin_change(coins, coin_idx, len(coins) - 1, [], 0, T, M) # coins = [10,10,20,50,5,10,20,50,5,5,10] # print(coin_change_restrict(coins, [5,10,20,50], 120, 2)) #dynamic programming approach to finding fibonacci #This function actually gives descending sequence of fibonacci values def fibonacci(n) : def fibonacci_helper(n, k, initial) : if k == n : return initial else : return fibonacci_helper(n, k + 1, [initial[1] + initial[0]] + initial) return fibonacci_helper(n, 1, [1,0]) def longest_common_subsequence(xs, ys) : def LCS(xs, ys, m, n) : #Base case would be when index < 0, cuz when index = 0, its still a value if m < 0 or n < 0 : return 0 else : if xs[m] == ys[n] : #If the values are equal, then its a subsequence or continuation of one. We must add + 1 return 1 + LCS(xs, ys, m - 1, n - 1) else : #Shld consider say # A D E # D A D # A =/= D but we must consider chance that next index has value equals to A, which in this case is true return max(LCS(xs, ys, m, n - 1), LCS(xs, ys, m - 1, n)) return LCS(xs, ys, len(xs) - 1, len(ys) - 1) # X = "AXYT" # Y = "AYZX" # print(longest_common_subsequence(X, Y)) #returns longest common order subsequence (ascending order) def longest_common_ordered_subsequence(xs, ys) : def LCOS(xs, ys, m, n) : if m < 0 or n < 0 : return 0 else : #If indexes are similar, we need to check if their preceding indexes are smaller or equals and similar if xs[m] == ys[n] : #If preceding indexes are smaller or equals and similar, then + 1 if xs[m - 1] <= xs[m] and ys[n - 1] == xs[m - 1] : return 1 + LCOS(xs, ys, m - 1, n - 1) #If preceding indexes do not meet above condition, then just return 1, cuz we haven't accounted for the duo that's similar else : return 1 else : #If indexes are not similar, maybe ordered indexes end at diff indexes, need check throughout return max(LCOS(xs, ys, m - 1, n), LCOS(xs, ys, m, n - 1)) return LCOS(xs, ys, len(xs) - 1, len(ys) - 1) # X = "AAABBT" # Y = "TAAXBB" # print(longest_common_ordered_subsequence(X, Y)) #returns longest ordered subsequence in an array. Ascending order but includes equals def ordered_subsequence(xs, f) : def LOS(xs, n, curr) : if n < 0 : return 0 else : if xs[n - 1] <= xs[n] : return LOS(xs, n - 1, curr + 1) else : return f(curr + 1, LOS(xs, n - 1, 0)) return LOS(xs, len(xs) - 1, 0) # print(ordered_subsequence("AAABAAAAAABAAABAAB", max)) def max_min(xs) : if len(xs) <= 2 : return [max(xs), min(xs)] else : mid = math.floor(len(xs) / 2) max1, min1 = max_min(xs[:mid + 1]) max2, min2 = max_min(xs[mid + 1:]) return [max(max1, max2), min(min1, min2)] # print(max_min([1,2,4,7,23,32,1,43,134])) #Needs work def knapsack_dynamic(ws, ps, W) : DP = [[] for x in range(len(ws) + 1)] for weight in range(W + 1) : curr_weight = weight for weight_ele in range(len(ws) + 1) : if weight == 0 : DP[weight_ele].append(0) else : if weight_ele == 0 : DP[weight_ele].append(0) else : if curr_weight - ws[weight_ele - 1] >= 0 : DP[weight_ele].append(max(DP[weight_ele - 1][weight], ps[weight_ele - 1] + DP[weight_ele - 1][weight])) curr_weight -= ws[weight_ele - 1] else : if weight - ws[weight_ele - 1] >= 0 : DP[weight_ele].append(max(DP[weight_ele - 1][weight], ps[weight_ele - 1])) else : DP[weight_ele].append(DP[weight_ele - 1][weight]) for i in DP : print(i) return DP[len(ws)][W] # print(knapsack_dynamic([1,2,3], [10,15,40], 6)) # test(quick_sort, lst) # test(merge, lst) # test(radix_sort, lst) # counting_sort_test(counting_sort, lst, 1000000) def base_representation(n, b) : result = [] while n >= b : result.append(n % b) n = math.floor(n / b) result.append(n) result.reverse() return result # print(base_representation(1801131029198, 16)) def base_to_decimal(xs, b) : result = 0 base = len(xs) - 1 for val in xs : result += (val * (b ** base)) base -= 1 return result #print(base_to_decimal([7,4], 16)) # Given a function f and a starting value i, # Write a function determineF(i, n, k) that returns true if a value k can # be found with n successive applications of f to i, and false otherwise. # Constraints # i < 1000000007 # k < 1000000007 # Example: def f(i): return i * 4 % 5 i = 1 k = 3 n = 5 # returns False #print(determineF(f, i, n, k)) #implementing tortoise and hare algo. k is target value, n is max iterations, i is initial value, f is function def determineF(f, i, n, k) : #Finds the start of the loop using the value at which loop is detected def find_loop_start(end) : p = end q = i start_count = 1 while q != p : q = f(q) p = f(p) start_count += 1 return start_count #Need separate values to check for loop, p would be the tortoise, q would be the hare p, q =i, i #Tracking number of function applications count = 1 #q checks 2 function applications ahead so we can stop searching at n - 2 while count <= n - 2 : p = f(p) q = f(f(q)) #print(p," : ",q) if p != k : if p == q : print('loop detected') print('loop started at : ',find_loop_start(p)) return False else : count += 1 else : print('target reached at ', count) return True else : print('no loop and k not found') return False def primality(n) : if n == 1 : return False else : for div in range(2, math.ceil(n ** 0.5)) : if (n % div == 0) : return False return True # print(primality(17)) def prime_factorization(n) : fix = n res = [] if primality(n) : return [n] else : for val in range(2, fix) : if primality(val) : while (n % val == 0) : res.append(val) n = n / val return res # print(prime_factorization(14351)); # print(217 % 24) for i in range(1000) : if (i * 48 + 6) % 4 == 0 : print(i, ":", (i * 48 + 6) / 6) print((26 * 5) % 32)
f5abaa4d8485ffa0a1d3593df6293dca6f712e8d
roveryi/LeetCode-Practice
/P39.py
1,737
3.59375
4
''' 39. Combination Sum Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. Example 1: Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7], [2,2,3] ] Example 2: Input: candidates = [2,3,5], target = 8, A solution set is: [ [2,2,2,2], [2,3,3], [3,5] ] ''' class Solution: def combinationSum(self, candidates, target): candidates.sort() ans = [] def dfs(target, idx, path): if target < 0: return if target == 0: ans.append(path) return for i in range(idx, len(candidates)): dfs(target - candidates[i], i, path + candidates[i]) dfs(target, 0, []) return ans ''' My trail ''' class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: if len(candidates) == 0 or target < min(candidates): return if len(candidates) == 1 and target%candidates[0] == 0: return [candidates[0]]*int(target/candidates[0]) ans = [] for i in range(int(target/candidates[0])+1): cur = [candidates[0]]*i if target - i*candidates[0] == 0: ans.append(cur) if self.combinationSum(candidates[1:], target - i*candidates[0]): ans.append(cur + self.combinationSum(candidates[1:], target - i*candidates[0])) return ans
be8f19a8e036c15f516b03e24dff1d1c368a8923
TitanLi/openCV
/read.py
718
3.65625
4
# -*- coding: UTF-8 -*- import numpy as np import cv2 img = cv2.imread('apple.jpg') # 圖片讀取 # 會儲存成一個 NumPy 的陣列 print type(img) # NumPy 陣列的大小 #(RGB 彩色圖片的 channel 是 3,灰階圖片則為 1) print img.shape # 此為預設值,這種格式會讀取 RGB 三個 channels 的彩色圖片,而忽略透明度的 channel imgColor = cv2.imread('apple.jpg',cv2.IMREAD_COLOR); print imgColor.shape # 以灰階的格式來讀取圖片 imgGraycale = cv2.imread('apple.jpg',cv2.IMREAD_GRAYSCALE); print imgGraycale.shape # 讀取圖片中所有的 channels,包含透明度的 channel imgUnchanged = cv2.imread('apple.jpg',cv2.IMREAD_UNCHANGED); print imgUnchanged.shape
1702d95e4f9fc22ffcc97c5fb9054811018c1406
nymul-islam-moon/Massage-Encrypt
/main.py
861
3.578125
4
#phthon Massage encryption import sys while(True): option = input("Enter Your Option : ") if "encrypt" in option or "decrypt" in option: massage = input("Enter The Massage : ") key = int(input("Enter The Key : ")) file1 = "QAZWSXEDCRFVTGBYHNUJMIKOLPabcdefghijklmnopqrstuvwxyz\ 1234567890!@#$%^&*()_+-=?/>.<,|':;~" if "encrypt" in option: encrypt = "" for i in massage: position = file1.find(i) newposition = int(position + key) % 89 encrypt += file1[newposition] print(encrypt) else: decrypt = "" for i in massage: pos = file1.find(i) newpos = int(pos - key) % 89 decrypt += file1[newpos] print(decrypt) else: sys.exit()
c4935acf1351e07fd0393de2f75cb144dd6070d6
jianengli/leetcode_practice
/jianzhi_offer/66.py
2,350
3.546875
4
# -*- coding:utf-8 -*- import collections class Solution: def movingCount(self, threshold, rows, cols): # write code here self.row, self.col = rows,cols self.dict=set() self.search(threshold,0,0) return len(self.dict) # 求满足题意要求(if not self.judge(threshold, i, j) or (i,j) in self.dict)时,字典长度就为所求 def judge(self,threshold,i,j): return sum(map(int,list(str(i))))+sum(map(int,list(str(j))))<=threshold def search(self,threshold,i,j): if not self.judge(threshold, i, j) or (i,j) in self.dict: return self.dict.add((i,j)) if i<self.row-1: self.search(threshold, i+1, j) if j<self.col-1: self.search(threshold, i, j+1) # 要注意去重:(i,j) in self.dict 如果不加这一句,时间复杂度不会满足。 # def BFS(): # if rows == 0 and cols ==0: return 0 # count=0 # openlist = collections.deque() # closedlist = set() # self.row,self.col = 0,0 # openlist.append((self.row,self.col )) # arr[self.row][self.col] = 1 # while [[0 in arr[i][j] for i in range(cols)] for j in range(rows)]: # node = openlist.popleft() # if self.row+1<=rows and self.row+1>=0 and self.col<=cols and self.col>=0 and arr[self.row+1][self.col]==0: # count+=1 # openlist.append((self.row+1,self.col )) # arr[self.row][self.col] = 1 # return count # arr = [[0 for i in range(cols)] for j in range(rows)] # for j in range(rows): # for i in range(cols): # if not self.checkValid(threshold, j, i): # arr[j][i] = -1 # print(arr) # self.BFS() # def checkValid(self,threshold, row, col): # sum = 0 # while row: # sum += row%10 # row /= 10 # while col: # sum += col%10 # col /= 10 # if sum >= threshold: # return False # return True
48db1f84c21cf83562bd874af7e13d23f4b2cdb9
jshartshorn/genome
/python/lib/genome/quality.py
759
4.0625
4
#!/usr/bin/env python def qual_str_to_codes(qual_str): """Converts a string of space-delimited quality values to an ascii string representation, where the ascii value of each character is the quality value""" return "".join([chr(int(x)) for x in qual_str.split(" ")]) def qual_codes_to_str(qual_codes): """Converts ascii quality scores to a human-readible string of space-delimited numbers""" return " ".join([str(ord(x)) for x in qual_codes]) if __name__ == "__main__": qual_str = "45 50 60" ascii_str = qual_str_to_codes(qual_str) new_qual_str = qual_codes_to_str(ascii_str) print("original qual str: " + qual_str) print("ascii quals str: " + ascii_str) print("new qual str: " + new_qual_str)
4d4218064e9cd2320068cc8af78172ca5902cb2b
ugauniyal/sort_algorithms
/bubble_sort.py
293
3.859375
4
def bubble_sort(input): size = len(input) for i in range(len(input) - 1,0,-1): for j in range(i): if input[j] > input[j+1]: input[j], input[j+1] = input[j+1], input[j] else: j = j+1 return input
08be7dd05738523d67903d32f02ff34b3dc43ae9
codingWithAndy/Thesis_Project
/Code/Project/views/svmgameboard.py
5,074
3.515625
4
import numpy as np from random import randint from sklearn import svm, datasets from PyQt5.QtWidgets import * import matplotlib import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvas, FigureCanvasQTAgg from matplotlib.figure import Figure matplotlib.use('Qt5Agg') class SVMGameboard(QWidget): model_name = "Support Vector Machine (SVM)" learning_type = "Supervised Learning!" model_overview = "SVM or Support Vector Machine is a linear model for classification and regression problems. " +\ "It can solve linear and non-linear problems and work well for many practical problems.\n\n" +\ "The idea of SVM is simple: The algorithm creates a line or a hyperplane which separates the data into classes.\n\n" +\ "At first approximation what SVMs do is to find a separating line(or hyperplane) between data of two classes. SVM is an algorithm that takes the data as an input and outputs a line that separates those classes if possible." boundaries_on = False def __init__(self, parent=None): QWidget.__init__(self, parent) self.canvas = FigureCanvas(Figure()) self.fig = self.canvas.figure self.canvas.ax = self.fig.add_subplot(111) self.ax = self.canvas.ax self.vertical_layout = QVBoxLayout() self.vertical_layout.addWidget(self.canvas) self.iris = datasets.load_iris() # we only take the first two features. We could self.X = self.iris.data[:, :2] self.y = self.iris.target self.h = .02 # step size in the mesh self.C = 1.0 # SVM regularization parameter self.svc = svm.SVC(kernel='linear', C=self.C).fit(self.X, self.y) # create a mesh to plot in self.x_min, self.x_max = self.X[:, 0].min() - 1, self.X[:, 0].max() + 1 self.y_min, self.y_max = self.X[:, 1].min() - 1, self.X[:, 1].max() + 1 self.xx, self.yy = np.meshgrid(np.arange(self.x_min, self.x_max, self.h), np.arange(self.y_min, self.y_max, self.h)) self.Z = self.svc.predict(np.c_[self.xx.ravel(), self.yy.ravel()]) self.Z = self.Z.reshape(self.xx.shape) self.ax.contourf(self.xx, self.yy, self.Z, alpha=0.8) self.ax.scatter(self.X[:, 0], self.X[:, 1], c=self.y) self.setLayout(self.vertical_layout) self.fig.canvas.draw() def plot_clusters(self, X, y=None): self.ax.scatter(X[:, 0], X[:, 1], c=y, s=1) self.fig.canvas.draw() def __call__(self, event): print('click', event) def plot_data(self, X): self.ax.plot(self.X[:, 0], self.X[:, 1], 'k.', markersize=2) def plot_centroids(self, centroids, weights=None, circle_color='w', cross_color='k'): if weights is not None: centroids = centroids[weights > weights.max() / 10] self.ax.scatter(centroids[:, 0], centroids[:, 1], marker='o', s=30, linewidths=8, color=circle_color, zorder=10, alpha=0.9) self.ax.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=50, linewidths=50, color=cross_color, zorder=11, alpha=1) def plot_decision_boundaries(self, clusterer, X, resolution=1000, show_centroids=True, show_xlabels=True, show_ylabels=True): mins = X.min(axis=0) - 0.1 maxs = X.max(axis=0) + 0.1 xx, yy = np.meshgrid(np.linspace(mins[0], maxs[0], resolution), np.linspace(mins[1], maxs[1], resolution)) Z = clusterer.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) self.ax.contourf(Z, extent=(mins[0], maxs[0], mins[1], maxs[1]), cmap="Pastel2") self.ax.contour(Z, extent=(mins[0], maxs[0], mins[1], maxs[1]), linewidths=1, colors='k') self.plot_data(self.X) if show_centroids: self.plot_centroids(clusterer.cluster_centers_) self.fig.canvas.draw() # Toggle decision boundary off def switch_boundaries_on_off(self): if self.boundaries_on != False: pass else: print("boundary = False") self.fig.canvas.draw() # Need to figure out how to clear the boundaries def clear_values(self): self.ix, iy = 0, 0 self.playerID = False self.turn = 0 self.pointOwner = [] self.points = [] self.X = [] self.y = [] self.x_point = [] self.y_point = [] self.prepopulated = False self.ax.clear() self.ax.set_xlim([-2, 3]) self.ax.set_ylim([-1, 15]) self.fig.canvas.draw()
5b40804765c6aeba313bfe30f5ea9e63f29e9ba2
jkxruby/IntroductionToAlgorithms
/src/6.3-1.py
2,312
3.515625
4
# -*- coding:utf-8 -*- __author__ = 'haoxiang' def minHeapify(A,length,i): smallest = i left = 2*i right = 2*i+1 if left<= i and A[left]<A[smallest]: smallest = left if right<=i and A[right]<A[smallest]: smallest = right if smallest!=i: temp = A[i] A[i] = A[smallest] A[smallest] = temp minHeapify(A,smallest) return (A) def maxHeapify(A,i,length): largest = -1 left = 2*i right = 2*i+1 if length > left and A[left] > A[i]: largest = left else : largest = i if length > right and A[right] > A[largest]: largest = right if largest != i: A[i],A[largest] = A[largest],A[i] maxHeapify(A,largest,length) return A def buildMinHeap(A): size = len(A) for i in range(size/2,1,-1): minHeapify(A,i) return A def buildMaxHeap(A): n = len(A) first = int(n/2-1) #最后一个非叶子节点 for start in range(first,-1,-1): maxHeapify(A,start,n) return A def heapSort(A): buildMaxHeap(A) lens = len(A) for i in range(lens-1,-1,-1): A[i],A[0] = A[0],A[i] maxHeapify(A,0,i) print A def heap_sort(ary) : n = len(ary) first = int(n/2-1) #最后一个非叶子节点 for start in range(first,-1,-1) : #构造大根堆 max_heapify(ary,start,n-1) for end in range(n-1,0,-1): #堆排,将大根堆转换成有序数组 ary[end],ary[0] = ary[0],ary[end] max_heapify(ary,0,end-1) print ary #最大堆调整:将堆的末端子节点作调整,使得子节点永远小于父节点 #start为当前需要调整最大堆的位置,end为调整边界 def max_heapify(ary,start,end): root = start while True : child = root*2 +1 #调整节点的子节点 if child > end : break if child+1 <= end and ary[child] < ary[child+1] : child = child+1 #取较大的子节点 if ary[root] < ary[child] : #较大的子节点成为父节点 ary[root],ary[child] = ary[child],ary[root] #交换 root = child else : break test = [1,3,2,4,8,5,9,36] # buildMinHeap(test) # buildMaxHeap(test) # heapSort(test) heapSort(test)
b3bb37e56b85d415c84e6c96096f4541cbc0995f
gceylan/pro-lang
/piton/stringtools.py
2,096
4.15625
4
#!/usr/bin/env python #-*- coding: utf-8 -*- def reverse(s): """ >>> reverse('happy') 'yppah' >>> reverse('Python') 'nohtyP' >>> reverse("") '' >>> reverse("P") 'P' """ return s[::-1] def mirror(s): """ >>> mirror("good") 'gooddoog' >>> mirror("yes") 'yessey' >>> mirror('Python') 'PythonnohtyP' >>> mirror("") '' >>> mirror("a") 'aa' """ return s[:] + s[::-1] def remove_letter(letter, s): """ >>> remove_letter('a', 'apple') 'pple' >>> remove_letter('a', 'banana') 'bnn' >>> remove_letter('z', 'banana') 'banana' >>> remove_letter('i', 'Mississippi') 'Msssspp' """ new_s = '' for i in s: if i != letter: new_s += i return new_s def count(sub, s): """ >>> count('is', 'Mississippi') 2 >>> count('an', 'banana') 2 >>> count('ana', 'banana') 2 >>> count('nana', 'banana') 1 >>> count('nanan', 'banana') 0 """ t = 0 m = len(sub) for i in range(0, len(s)): n = s[i:i + m] if n == sub: t += 1 return t def remove(sub, s): """ >>> remove('an', 'banana') 'bana' >>> remove('cyc', 'bicycle') 'bile' >>> remove('iss', 'Mississippi') 'Missippi' >>> remove('egg', 'bicycle') 'bicycle' """ if sub in s: m = len(sub) n = s.index(sub) return s[:n] + s[n + m:] else: return s def remove_all(sub, s): """ >>> remove_all('an', 'banana') 'ba' >>> remove_all('cyc', 'bicycle') 'bile' >>> remove_all('iss', 'Mississippi') 'Mippi' >>> remove_all('eggs', 'bicycle') 'bicycle' """ n = count(sub, s) if sub in s: while 0 < n: m = remove(sub, s) s = m n -= 1 return m else: return s if __name__ == '__main__': import doctest doctest.testmod()
180c51f638ac92c8e136a2f0c2fd59e8c958a305
yychuyu/LeetCode
/problems/0498_Diagonal_Traverse/Elon.py
1,057
3.546875
4
class Solution: def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: '''find diagonal''' if not matrix: return [] m = len(matrix) n = len(matrix[0]) signal = 1 if m > n: matrix = list(zip(*matrix)) m, n = n, m signal = 0 result = [] for summon in range(m+n-1): diagonal = [] for x in range(m): if 0<= summon-x <n: diagonal.append(matrix[x][summon-x]) result += diagonal if summon%2==signal else diagonal[::-1] return result '''learn res = [] lines = [[]for _ in range(m+n-1)] for i in range(len(matrix)): for j in range(len(matrix[0])): lines[i+j].append(matrix[i][j]) for k in range(len(matrix) + len(matrix[0]) - 1): if k % 2 == 0: res += lines[k][::-1] else: res += lines[k] return res '''
996a9039dbbef12a7fa538849527ebf70e2a2051
k0malSharma/Competitive-programming
/FLOW006.py
137
3.671875
4
for _ in range(int(input())): a=int(input()) s=0 while(a>0): s+=int(a%10) a=int(a/10) print(int(s))
686f6174afefd051a3fb13214c0c7362b3ab4080
criptik/puzcorner
/gui/turtle/tubouncer.py
17,981
3.65625
4
# import TK import sys import time import turtle from random import * import math from abc import ABC, abstractmethod global dbg dbg = False def dbgprint(*args): global dbg if dbg: print(args) def vectorEnd(x1, y1, ang, len): angrad = math.radians(ang) angcos = math.cos(angrad) angsin = math.sin(angrad) x2 = x1 + len * angcos y2 = y1 + len * angsin return (x2, y2) # the abstract class Wall class Wall(ABC): @abstractmethod def __str__(self): pass @abstractmethod def draw(self): pass @abstractmethod def getTurtleIntersections(self, x0, y0, mt): pass @abstractmethod def reflectAngle(self, oldheading, xint, yint): pass # the linear wall here is basically a line segment class LinearWall(Wall): def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 if (x2 == x1): self.mw = math.inf self.ang = 90 else: self.mw = (y2-y1)/(x2-x1) self.ang = math.degrees(math.atan(self.mw)) @classmethod def fromVector(cls, x1, y1, ang, len): (x2, y2) = vectorEnd(x1, y1, ang, len) return cls(x1, y1, x2, y2) def __str__(self): return('(%d,%d) to (%d,%d), slope=%f, ang=%f' % (self.x1, self.y1, self.x2, self.y2, self.mw, self.ang)) def x2y2(self): return(self.x2, self.y2) def containsPoint(self, x, y): e = 0.1 if self.x1 < self.x2: xpart = self.x1-e <= x <= self.x2+e elif self.x1 > self.x2: xpart = self.x2-e <= x <= self.x1+e else: xpart = True if self.y1 < self.y2: ypart = self.y1-e <= y <= self.y2+e elif self.y1 > self.y2: ypart = self.y2-e <= y <= self.y1+e else: ypart = True return xpart and ypart def draw(self, t): t.penup() t.goto(self.x1, self.y1) t.pendown() t.pencolor("red") t.goto(self.x2, self.y2) # in the LinearWall class, reflectAngle does not use # xint, yint but other types of walls might. def reflectAngle(self, oldheading, xint, yint): return (2 * self.ang - oldheading) % 360 # notes on linear wall intersections # call (y2-y1)/(x2-x1) = mw # wall equation is y=y1 + (x-x1)*mw # turt equation is y=y0 + (x-x0)*mt # so at intersection: # y1 + (x-x1)*mw = y0 + mt*(x-x0) # y1 + mw*x - x1*mw = y0 + mt*x - mt*x0 # x*(mt-mw) + mw*x1 - mt*x0 = (y1-y0) # x = (y1-y0 - mw*x1 + mt*x0)/(mt-mw) # special case: wall line x=constant (vertical), so mw = inf # then equations are x=x1 and y=(x-x0)*mt + y0 # so solve for y get: # y = (x1-x0)*mt + y0 # # special case 2: turang is 90 or 180 so turslope = inf # then tur equation is x=x0 # then eqs are x=x0 (tur) and y=(x-x1)*mw + y1 (wall) # so solve for y get: # y = (x0-x1)*mw + y1 # example: # wall(vert) = 300, 0, 300, 300, turtang=30(mt=0.5), turpos=(150, 150) # y = (300-150)*0.5 + 150 = 225 # example (turt vert): # wall = 300, 0, 0 300, (mw=-1) turtang=90, turpos=(60, 60) # y = (60-300)*(-1) + 0 = 225 # y = 240 + 0 = 240 # example: # wall = 150, 300, 300, 150 turtang=45(mt=1), turpos=(0,0) # mw = -1 # x = (y1-y0 - mw*x1 + mt*x0)/(mt-mw) # xint = (300-0 - (-1*150) + 1*0)/(1 - -1) # = 450/2 = 225 # yint = x0 + mt*x-x0 = 0 + 1*225 = 150 # special case if wall and turtle path are parallel def getTurtleIntersections(self, x0, y0, mt): xint = None yint = None if self.mw == mt: dbgprint('skipping %s, parallel to turtle' % (self)) # special case if self is vertical (equation x=x1) elif self.mw == math.inf: yint = (self.x1 - x0) * mt + y0 xint = self.x1 # special case if turtle path is vertical (equation x=x0) elif mt == math.inf: yint = (x0-self.x1) * self.mw + self.y1 xint = x0 else: xint = (self.y1 - y0 - self.mw * self.x1 + mt * x0)/(mt - self.mw) yint = y0 + (xint - x0) * mt # special cases for vertical, etc. if self.x1 == self.x2: xint = self.x1 if self.y1 == self.y2: yint = self.y1 # now only return if wall really contains that point. # Note that linear wall only returns at most one intersection if xint is not None and self.containsPoint(xint, yint): dbgprint('wall does contain (%f, %f)' % (xint, yint)) return [(xint, yint)] else: return [] # the circular wall class CircularWall(Wall): def __init__(self, xcent, ycent, radius, degstart=0, degend=360): self.xcent = xcent self.ycent = ycent self.radius = radius self.degstart = degstart self.degend = degend self.degsize = (degend-degstart) % 360 if self.degsize == 0: self.degsize = 360 def __str__(self): return('center at (%d,%d), radius %f, deg from %d-%d' % (self.xcent, self.ycent, self.radius, self.degstart, self.degend)) def containsPoint(self, x, y): # shortcut for full circle, always true if self.degsize == 360: return True # measure angle from intersection point to center degint = math.degrees(math.atan2(x - self.xcent, y - self.ycent)) % 360 # atan2 degrees go clockwise, so different from turtle degrees degint = (90 - degint) % 360 dbgprint('for (%f,%f), degint is %f' % (x, y, degint)) return self.degstart <= degint <= self.degend def draw(self, t): t.penup() t.goto(self.xcent, self.ycent) t.setheading(self.degstart) t.forward(self.radius) t.left(90) if False: (x, y) = t.pos() print('turtle at (%f,%f), heading=%f ' % (x, y, turtle.heading())) t.pendown() t.pencolor("red") t.circle(self.radius, self.degsize) def reflectAngle(self, oldheading, xint, yint): # get angle to center of circle angcos = (self.xcent - xint) / self.radius angsin = (self.ycent - yint) / self.radius if angcos == 0: angleFromCent = 90 if angsin > 0 else -90 else: angleFromCent = math.degrees(math.atan(angsin/angcos)) dbgprint('angleFromCent = %f' % (angleFromCent)) angleTangToCirc = (angleFromCent + 90) % 360 return (2 * angleTangToCirc - oldheading) % 360 # notes on circular wall intersections # xc = xcent, yc = ycent # wall equation is (x-xc)**2 + (y-yc)**2 = radius**2 # turt equation is y=y0 + (x-x0)*mt # from web page http://www.ambrsoft.com/TrigoCalc/Circles2/circlrLine_.htm # x1,2 = a + bm -dm +/- sqrt(w) # y1,2 = d + am + bm**2 +/- m*sqrt(w) # where: w = r**2(1+m**2) - (b - ma - d)**2 # if y = mx + d # and y = y0 + (x-x0)*mt # y = y0 + x*mt - x0*mt # so d = y0 - x0*mt def getTurtleIntersections(self, x0, y0, mt): xint = None yint = None a = [] if mt == math.inf: # handle this later return a # calculate w to see how many intersection points if any d = y0 - x0*mt w = self.radius**2 * (1 + mt**2) - (self.ycent - (mt * self.xcent) - d)**2 dbgprint('w=%f, mt=%f, x0/y0 at (%f, %f)' % (w, mt, x0, y0)) if w < 0: dbgprint('no intersections') return a # w is >= 0 x1 = (self.xcent + self.ycent*mt - d*mt + math.sqrt(w)) / (1 + mt**2) y1 = mt*x1 + d # y1 = y0 + (x1 - x0) * mt if self.containsPoint(x1, y1): pos1 = (x1, y1) a.append(pos1) if w == 0: dbgprint('at most one intersection (%f,%f)' % (x1, y1)) else: x2 = (self.xcent + self.ycent*mt - d*mt - math.sqrt(w)) / (1 + mt**2) y2 = mt*x2 + d dbgprint('at most possibly two intersections (%f,%f) and (%f,%f)' % (x1, y1, x2, y2)) if self.containsPoint(x2, y2): pos2 = (x2, y2) a.append(pos2) # sys.exit() return a def pointAtDegrees(self, deg): x = self.xcent + math.cos(math.radians(deg)) * self.radius y = self.ycent + math.sin(math.radians(deg)) * self.radius return (x, y) def x1y1(self): return self.pointAtDegrees(self.degstart) def x2y2(self): return self.pointAtDegrees(self.degend) # some routines for generating sets of linear walls def genPolygonWalls(x0, y0, numsides, heading, sidelen, headingChange=None): a = [] if headingChange is None: headingChange = 360/numsides a.append(LinearWall.fromVector(x0, y0, heading, sidelen)) for n in range(numsides-1): heading = heading + headingChange prevx, prevy = a[-1].x2y2() a.append(LinearWall.fromVector(prevx, prevy, heading, sidelen)) return a def genSquareWalls(x0, y0, heading, sidelen): return genPolygonWalls(x0, y0, 4, heading, sidelen) def genTriangleWalls(x0, y0, heading, sidelen): return genPolygonWalls(x0, y0, 3, heading, sidelen) class World: def __init__(self, walls): self.walls = walls self.wallHit = None def draw(self, t): t.clear() for wall in self.walls: wall.draw(t) t.penup() def isRightDirection(self, x0, y0, xint, yint, angsin, angcos): if angcos == 0: rightx = (x0 == xint) elif angcos > 0: rightx = xint > x0 else: rightx = xint < x0 if angsin == 0: righty = (y0 == yint) elif angsin > 0: righty = yint > y0 else: righty = yint < y0 return (rightx and righty) def hitsEarlier(self, xint, yint, x0, y0): if self.xret is None: return True intDist = math.sqrt((xint - x0)**2 + (yint - y0)**2) dbgprint('intDist=%f, self.intDist=%f' % (intDist, self.intDist)) return (intDist < self.intDist) def isValidIntersection(self, wall, x0, y0, xint, yint, angsin, angcos): rightDirection = self.isRightDirection(x0, y0, xint, yint, angsin, angcos) dbgprint('rightDirection = %s' % rightDirection) if not rightDirection: return False earlier = self.hitsEarlier(xint, yint, x0, y0) dbgprint('hits Earlier = %s' % earlier) if not earlier: return False # if we made it this far... return True # find the intersection with any wall # given the current position and angle def findIntersect(self, posOrig, angle, t, excludeWalls=[]): dbgprint("posOrig is ", posOrig) (x0, y0) = posOrig rads = math.radians(angle) # print("rads=", rads) mt = math.tan(rads) if (angle % 180) == 90: mt = math.inf elif (angle % 180) == 0: mt = 0 angsin = math.sin(rads) angcos = math.cos(rads) if abs(angcos) < 1e-15: angcos = 0 if abs(angsin) < 1e-15: angsin = 0 dbgprint('turtle slope=%f, sin=%f, cos=%f'% (mt, angsin, angcos)) self.xret = None self.yret = None for wall in self.walls: if wall in excludeWalls: continue dbgprint('wall is %s' % (wall)) # getTurtleIntersection returns a list of intersections of turtle path with that wall # for linear wall types that will only be one intersection. for intersectPosition in wall.getTurtleIntersections(x0, y0, mt): (xint, yint) = intersectPosition # if we computed a wall turtle intersection, see if it is in # the right turtle direction, and is earlier than any existing one if xint is not None: if False: t.goto((xint, yint)) t.stamp() # time.sleep(1) dbgprint('computed intersection at (%f,%f)' % (xint, yint)) if self.isValidIntersection(wall, x0, y0, xint, yint, angsin, angcos): self.xret = xint self.yret = yint self.intDist = math.sqrt((xint - x0)**2 + (yint - y0)**2) self.wallHit = wall # having finished all walls, xret,yret should conotain the first intersect if self.xret is not None: dbgprint('returning (%f, %f)' % (self.xret, self.yret)) posret = (self.xret, self.yret) return(posret) def getWallHit(self): return self.wallHit class TurtleRing: def __init__(self, num, scr): self.turtRing = [] self.ringIndex = 0 self.ringSize = num self.useUndo = True self.noErase = False # num == 0 is a special no-erase situation if num == 0: self.noErase = True self.ringSize = 1 for n in range(self.ringSize): self.createNewTurtle(scr) def createNewTurtle(self, scr): newt = turtle.RawTurtle(scr) newt.speed(0) newt.setundobuffer(1) if True: newt.shape('circle') newt.resizemode('user') newt.shapesize(0.25, 0.25) self.turtRing.append(newt) return newt def getNextTurtle(self): tnext = self.turtRing[self.ringIndex] self.ringIndex = (self.ringIndex + 1) % self.ringSize return tnext def clearAll(self): for t in self.turtRing: while t.undobufferentries(): t.undo() t.clear() t.penup() def undoDraw(self, tur): if self.noErase: return if self.useUndo: tur.undo() else: tur.clear() # ---------- main program ---------------- scr = turtle.Screen() tmain = turtle.RawTurtle(scr) tmain.shape('circle') tmain.resizemode('user') tmain.shapesize(0.5, 0.5) tmain.speed(0) scr.colormode(255) mywalls = [] sqsiz = 300 smsqsiz = 50 if False: mywalls.extend(genSquareWalls(0, 0, 0, sqsiz)) else: mywalls.extend(genSquareWalls(0, 0, 10, sqsiz)) mywalls.append(CircularWall(150, 235, 50, 0, 180)) lastwall = mywalls[-1] # make a linear wall between endpoints (x1, y1) = lastwall.x1y1() (x2, y2) = lastwall.x2y2() mywalls.append(LinearWall(x1, y1, x2, y2)) mywalls.append(CircularWall(150, 225, 50, 180, 360)) lastwall = mywalls[-1] # make a linear wall between endpoints (x1, y1) = lastwall.x1y1() (x2, y2) = lastwall.x2y2() mywalls.append(LinearWall(x1, y1, x2, y2)) mywalls.append(CircularWall(55, 225, 40)) # mywalls.append(CircularWall(51, 222, 90, 90, 180)) if True: if True: mywalls.extend(genTriangleWalls(100, 100, -30, smsqsiz*2)) mywalls.extend(genTriangleWalls(195, 40, 30, smsqsiz*2)) else: # linear barriers mywalls.append(LinearWall(50, 0, 50, 280)) mywalls.append(LinearWall(100, 300, 100, 20)) mywalls.append(LinearWall(150, 0, 150, 280)) mywalls.append(LinearWall(200, 300, 200, 20)) mywalls.append(LinearWall(250, 0, 250, 280)) world = World(mywalls) if False: for w in mywalls: print(w) xTestStart = 25 yTestStart = 50 tmain.setpos(xTestStart, yTestStart) tmain.pencolor("black") turtRing = TurtleRing(5, scr) if True: scr.title("Testing...") world.draw(tmain) tmain.hideturtle() dbg = False for headTest in range(0, 360, 8): tnext = turtRing.getNextTurtle() tnext.penup() tnext.setpos(xTestStart, yTestStart) tnext.setheading(headTest) dbgprint('Computing for %d' % headTest) pos = world.findIntersect(tnext.pos(), headTest, tnext) # dbgprint('for %d, pos is %s' % (headTest, pos)) if True: tnext.pendown() tnext.goto(pos) tnext.penup() if False: time.sleep(5) sys.exit() time.sleep(3) # sys.exit() turtRing.clearAll() tmain.penup() world.draw(tmain) tmain.hideturtle() tmain.pencolor("black") scr.title("Bouncing") dbg = False xBounceStart = 150 yBounceStart = 150 if True: newhead = random() * 90 else: newhead = 45 randerr = True excludes = [] tlast = None count = 0 while True: ta = turtRing.getNextTurtle() # ta = t turtRing.undoDraw(ta) ta.penup() if tlast is None: ta.goto(xBounceStart, yBounceStart) else: (lastx, lasty) = tlast.pos() ta.goto(lastx, lasty) ta.setheading(newhead) pos = world.findIntersect(ta.pos(), newhead, ta, excludes) (posx, posy) = pos dbgprint(newhead, posx, posy) if posx == None: print(ta.pos(), newhead, excludes, pos) time.sleep(10) sys.exit() continue ta.pendown() ta.goto(pos) # ta.dot(5, "blue") tlast = ta if False: newhead = random() * 360 else: wallHit = world.getWallHit() newhead = wallHit.reflectAngle(newhead, posx, posy) if randerr: newhead = newhead + (random()*5 - 2.5) # for next time, make sure we don't hit the same wall. excludes = [wallHit] if False: time.sleep(2) if False: count = count + 1 if count == 1000: break turtle.done()
dd4ee2e4035fb5a01ddd31f9e0f7f589c677df10
Sedrak-Khachatryan/BasicITCenter
/Homework/Homework_04/Xndir_647.py
71
3.578125
4
n=input("") if n==n[::-1]: t=True else: t = False print(t)
7da38bba841992c65d71c78ca7e2722dbeff4091
Avangarde2225/pyththonWithBeatifulSoup
/pythonDataAnalysis/classesAndObjects/student.py
1,214
4
4
file_name = "data.txt" # f = open(file_name) # # f_content = f.readline() #reads only the firstline of the file # # f_content = f.read() #reads all the lines # # for line in f: # print(line.strip()) # f.close() def prep_record(line): line = line.split(":") first_name, last_name = line[0].split(",") course_details = line[1].rstrip().split(",") return first_name, last_name, course_details def prep_to_write(first_name, last_name, courses): full_name = first_name+','+last_name courses = ",".join(courses) return full_name+':'+courses #to read the file using with with open(file_name) as f: for line in f: print(line.strip()) first_name, last_name, course_details = prep_record(line) print(first_name,last_name,course_details) record_to_add = "john,schome:python, java, jugo" # #to write in a file # record_to_add = "john,schome:python, java, jugo" # with open(file_name,"a+") as to_write: #"w" will write to a new file and delete the prior entires # to_write.write(record_to_add+"\n") # mashur = Student('mashur','hosain',['python','ruby','javascript']) # print(mashur.find_in_file(file_name)) # print(mashur.add_to_file(file_name))
00c5706c656062e7f9118fbb7210c49b4ed6bfca
dulcetlife/Larsen_CSCI3202_Assignment1
/Larsen_Assignment1.py
4,446
4.21875
4
#CSCI 3202 Assignment 1 #Henrik Larsen #Github username: dulcetlife #Github repo: https://github.com/dulcetlife/Larsen_CSCI3202_Assignment1 #Written in Python 3 import Queue #Queue class #Using a list to store all the integers class Queue(object): def __init__(self): self.list = [] def enqueue(self, x): self.list.insert(0,x) def dequeue(self): return self.list.pop() def checkSize(self): return len(self.list) def testQueue(): print("Testing Queue") queue=Queue() for i in range(1,16): queue.enqueue(i) while (queue.checkSize() != 0): print(queue.dequeue()) #Stack class #Using a list to store all the integers class Stack(object): def __init__(self): self.list = [] def push(self, x): self.list.append(x) def pop(self): return self.list.pop() def checkSize(self): return len(self.list) def testStack(): print("Testing Stack") stack = Stack() for i in range(1,16): stack.push(i) while (stack.checkSize() != 0): print(stack.pop()) #Node class class Node(object): def __init__(self, intkey, left = None, right = None, parent = None): self.intkey = intkey self.left = left self.right = right self.parent = parent #Binary Tree class #I looked at http://stackoverflow.com/questions/20156243/binary-search-tree-python-implementing-delete #to get some inspiration for my binary tree #Using a list to store the nodes class BinaryTree(object): def __init__(self, value): self.root = Node(value, None, None, None) self.nodesList = [] self.nodesList.append(self.root) def findNode(self, nodeValue): for node in self.nodesList: if node.intkey == nodeValue: return node def addNode(self, value, parentValue): node = None parentNode = self.findNode(parentValue) if parentNode == None: print("Parent not found") new_Node = Node(value, None, None, parentNode) if parentNode.left == None: parentNode.left = new_Node self.nodesList.append(new_Node) elif parentNode.right == None: parentNode.right = new_Node self.nodesList.append(new_Node) else: print("Parent has two children, node not added") return print "Node", value, "added with parent", parentValue def delete(self, value): node = self.findNode(value) if node == None: print "Node not found" elif node.left != None: print("Node not deleted, has children") elif node.right != None: print("Node not deleted, has children") else: self.nodesList.remove(node) new_Parent = node.parent if new_Parent.left == node: new_Parent.left = None if new_Parent.right == node: new_Parent.right = None print "Node", value, "deleted" def printTree(self): self.helper_print(self.root) def helper_print(self, node): if node != None: node_Value = node.intkey node_Left = 0 node_Right = 0 if node.left != None: node_Left = node.left.intkey if node.right != None: node_Right = node.right.intkey print " ",node_Value print node_Left," ", node_Right self.helper_print(node.left) self.helper_print(node.right) def testBinaryTree(): print("Testing BinaryTree") myTree = BinaryTree(1) myTree.addNode(2, 1) myTree.addNode(3, 1) myTree.addNode(4, 2) myTree.addNode(5, 2) myTree.addNode(6, 3) myTree.addNode(7, 3) myTree.addNode(8, 4) myTree.addNode(9, 4) myTree.addNode(10, 5) myTree.addNode(11, 5) myTree.addNode(12, 5) myTree.printTree() for i in range(8,12): myTree.delete(i) myTree.delete(3) myTree.delete(2) myTree.printTree() #Graph class #Using a dictionary to store the vertices and edges class Graph(object): def __init__(self, dict = {}): self.dict = dict def addVertex(self, value): if value in self.dict: print("Vertex already exists") else: self.dict[value] = [] def addEdge(self, value1, value2): if value1 not in self.dict or value2 not in self.dict: print ("One or more vertices not found.") else: self.dict[value1].append(value2) self.dict[value2].append(value1) def findVertex(self, value): if value in self.dict: print(self.dict[value]) else: print("Vertex not found") def testGraph(): print("Testing Graph") graph = Graph() for i in range(1,22): graph.addVertex(i) graph.addVertex(20) for i in range(1,21): graph.addEdge(i,i+1) graph.addEdge(30,1) for i in range(2,7): graph.findVertex(i) graph.findVertex(22) def main(): testQueue() testStack() testBinaryTree() testGraph() if __name__ == '__main__': main()
2b9ec29039f1d45c042900d6d9c201917f5078f9
santiagoom/leetcode
/solution/python/120_Triangle_3.py
694
3.6875
4
from typing import List from utils import * class Solution_120_Triangle_3: def minimumTotal(self, triangle: List[List[int]]) -> int: below_row = triangle[-1] n = len(triangle) for row in reversed(range(n - 1)): curr_row = [] for col in range(row + 1): smallest_below = min(below_row[col], below_row[col + 1]) curr_row.append(triangle[row][col] + smallest_below) below_row = curr_row return below_row[0] if __name__ == "__main__": nums = [2, 7, 11, 15] target = 26 s = "aa" arrays = [[1, 2, 3], [4, 5, 6]] print(arrays)
cc7d018e72ff82a8a7038d7bff5632701587df26
adamsfrancis/Python
/BaseConversion/getInput.py
501
3.796875
4
class numToConvert(): def __init__(self, numberInput, numberBase, convertNumber): self.ni = numberInput self.nb = numberBase self.cn = convertNumber def main(): numberInput = int(input('Please enter an integer: ')) numberBase = int(input('Please input the starting base(10,8,6,2): ')) convertNumber = int(input('Please input the base you want converted to(10,8,6,2): ')) newNumber = numToConvert(numberInput,numberBase,convertNumber) return newNumber
ec754747f0ac8e1b3167dd288c14c54c84f67fbe
gajo357/IntroToAlgorithms
/Week7/FeelTheLoveModule.py
3,602
3.90625
4
import unittest import copy from DijkstraHeapModule import dijkstra_shortest_path # # Take a weighted graph representing a social network where the weight # between two nodes is the "love" between them. In this "feel the # love of a path" problem, we want to find the best path from node `i` # and node `j` where the score for a path is the maximum love of an # edge on this path. If there is no path from `i` to `j` return # `None`. The returned path doesn't need to be simple, ie it can # contain cycles or repeated vertices. # # Devise and implement an algorithm for this problem. # def break_link(G, node1, node2): if node1 not in G: print("error: breaking link in a non-existent node") return if node2 not in G: print("error: breaking link in a non-existent node") return if node2 not in G[node1]: print("error: breaking non-existent link") return if node1 not in G[node2]: print("error: breaking non-existent link") return del G[node1][node2] del G[node2][node1] return G def FindAllEdges(G): all_edges = [] for nodeA, edges in G.items(): for nodeB, weight in edges.items(): if((nodeA, nodeB) not in all_edges and (nodeB, nodeA) not in all_edges): all_edges.append((nodeA, nodeB)) return all_edges def feel_the_love(G, i, j): # return a path (a list of nodes) between `i` and `j`, # with `i` as the first node and `j` as the last node, # or None if no path exists (score, path) = dijkstra_shortest_path(G, i, j) # there is no path, no need to look any further if path is None: return None # visit all possible edges, so we're sure we got the maximum # remove the destination from the graph, as we do not want to end there Gcopy = copy.deepcopy(G) dest_edges = G[j] entering_node = None max_weight = None for node, weight in dest_edges.items(): break_link(Gcopy, j, node) # find the final edge that gives us the maximum if entering_node is None or weight > max_weight: entering_node = node max_weight = weight #start from the start node temp_start = i final_path = [] # for each edge in the graph for nodeA, nodeB in FindAllEdges(Gcopy): # find any path to it's begining nodeA (score, path) = dijkstra_shortest_path(G, temp_start, nodeA) # if it can't be reached, skip it if(path is None): continue # travel to node A final_path.extend(path) # travel to node B (we are looking at the A-B edge, so there is a direct path) # set node B as our new origin temp_start = nodeB # find the shortest path from where we are to (score, path) = dijkstra_shortest_path(Gcopy, temp_start, entering_node) final_path.extend(path) final_path.append(j) return final_path ######### # # Test def score_of_path(G, path): max_love = -float('inf') for n1, n2 in zip(path[:-1], path[1:]): love = G[n1][n2] if love > max_love: max_love = love return max_love class test_feelthelove(unittest.TestCase): def test(self): G = {'a':{'c':1}, 'b':{'c':1}, 'c':{'a':1, 'b':1, 'e':1, 'd':1}, 'e':{'c':1, 'd':2}, 'd':{'e':2, 'c':1}, 'f':{}} path = feel_the_love(G, 'a', 'b') self.assertEqual(score_of_path(G, path), 2) path = feel_the_love(G, 'a', 'f') self.assertEqual(path, None)
0812e326660e46021982afc5b51da0add726de96
dig017/ubiquitous-daniel
/functions.py
4,341
4.09375
4
import string import random def creditcard(number): """This function checks a True Credit Card by verifying that the input is an integer and subsequently checks if that input's length is 16 characters. Parameters: ----------- number: list list of strings, for it to run the first string must be a integers otherwise nothing is returned. if string is a integer it returns True if it is 16 chars long, and False if not """ if number[0].isdigit() == True: if len(number[0]) == 16: return True else: return False def selector(input_list, check_list, return_list): """This function is checking for inputs from the chatbox. Initially, it is checking for the word no and then for a potential subsequent input from the input_list. If the word is not no, then the input is taken from its respective input_list. Parameters: input_list, check_list, return_list ----------- element: list for this function to run you must input no and if another word is followed by no, it checks both words and pulls it from the respective list. if the input does not contain no, the output will come from the respective list where that input is located """ output = None for index, word in enumerate(input_list): if word in check_list: #Checks input for no and subsquent input to return a particular list if word == 'no' and input_list[index +1] in check_list: output = random.choice(return_list) break elif word != 'no': output = random.choice(return_list) break return output def find_in_list(list_one, list_two): """Find and return an element from list_one that is in list_two, or None otherwise. Parameters: list_one, list_two ----------- list_one: list list of objects list_two: list A differnt list of objets Returns: -------- element: int, float, or string Item that is in both list_one and list_two, if none exist then None returned Examples: --------- >>> list1 = [1,2,3,4] >>> list2 = [5,2,6,3,8] >>> find_in_lihttp://localhost:8889/notebooks/Desktop/BurritoBot/FinalProjectFinalCopy.ipynb#nst(list1, list2) 2 """ for element in list_one: if element in list_two: return element return None def is_in_list(list_one, list_two): """The following function is checking to see if any element in list_one is in list_two Parameters: list_one, list_two """ for element in list_one: if element in list_two: return True return False def question_asked(input_string): """This function is checking the input of the chat box for ? in order to output the appropiate list. Parameters: input_string """ if '?' in input_string: output = True else: output = False return output def string_concatenator(string1, string2, separator): result = string1 + separator + string2 return result def remove_punctuation(input_string): out_string = '' for char in input_string: if char not in string.punctuation: out_string += char return out_string def prepare_text(input_string): temp_string = input_string.lower() temp_string = remove_punctuation(temp_string) out_list = temp_string.split() return out_list def defined_output(input_list, check_list, return_list, questionNumber): output = None for word in input_list: if word in check_list: output = return_list[questionNumber] break return output def list_to_string(input_list, separator): output = input_list[0] for item in input_list[1:]: output = string_concatenator(output, item, separator) return output def end_chat(input_list): if 'bye' in input_list: output = True elif 'cancel' in input_list: output = True elif 'goodbye' in input_list: output = True else: output = False return output
18270df81a3a64222cb45e3161b2dd7043ab303e
okwesi/machine-learning
/traintestsplit/KNN.py
1,144
3.515625
4
import numpy import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn import neighbors, metrics from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt #READING THE DATA data = pd.read_csv('car.data') #print(data) X = data[[ 'buying', 'maintenance', 'safety' ]].values y = data[['class']] #CONVERTING THE DATA le = LabelEncoder() for i in range(len(X[0])): X[:, i ] = le.fit_transform(X[:, i]) label_mapping = { 'unacc': 0, 'acc': 1, 'good': 2, 'vgood': 3 } y['class'] = y['class'].map(label_mapping) # Mapping y = np.array(y) knn = neighbors.KNeighborsClassifier(n_neighbors=25, weights='uniform') X_train, X_test, y_train, y_test = train_test_split(X , y, test_size=0.20) knn.fit(X_train, y_train) y_prediction = knn.predict(X_test) accuracy = metrics.accuracy_score(y_test, y_prediction) #print(f" y_prediction : {y_prediction}") print(f"Accuracy : {accuracy}") print(f"actual value {y[234]}") print(f"predicted value : {knn.predict(X)[20]}")
c4d56459e8f0bf152f2c685b93026b63586178cf
nmyeomans/Nivelacion_Python
/21082019/000858.py
957
4.25
4
# En esta ocasion vamos a cambiar de lugar los parametros de una lista # para eso vamos a generar variables seleccionando un parametro especifico de la lista # la forma siguiente es mas larga de lo normal pero es utilil para cambiar de orden en una lista goleador=["Hans", "Nicolas", "Matias"] ordenar=goleador[0] # asignamos una varible con el parametro de la lista de la posicion respectiva goleador[0]=goleador[1] #luego modificamos reemplazando el primer parametro de la lista con el segundo goleador[1]=ordenar #luego el segundo parametro de la lista guardara el primero print goleador # podemos ver que la consola nos imprime el cambio de sujeto en este caso # otra forma mas eficiente es hacerlo con comas , designando un orden a cada variable de la lista goleador[1],goleador[2]=goleador[2],goleador[1] print goleador # podemos ver que es mas eficiente esta forma de asignacion para cada parametro de la lista
3ddaa21b632d73c1b1872a89a72a66f1c35895ee
trevor-ofarrell/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py~
158
3.75
4
#!/usr/bin/python3 def multiply_by_2(a_dictionary): newd = {} newd = a_dictionary.copy() for key in newd: newd[key] *= 2; return newd
2f7a53bc82bec0b4a2556c471a3a93d6d8f004cb
beginOfAll/base_study
/leetcode/88_MergeSortedArray.py
936
3.546875
4
class Solution: def merge(self, nums1, m, nums2, n): """ :type nums1: list[int] :type m: int :type nums2: list[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ temp = {} count = 0 if m == 0: temp = {k: v for k, v in enumerate(nums2)} else: for n2 in nums2: if n2 < nums1[0]: temp[0] = n2 elif n2 >= nums1[m - 1]: temp[m] = n2 else: for k in range(m): if n2 >= nums1[k] and n2 < nums1[k + 1]: temp[k + 1] = n2 for index in temp: nums1.insert(index + count, temp[index]) count += 1 s = Solution() num1 = [1] num2 = [] s.merge(num1, 1, num2, 0) print(num1) ### # leetcode 测试集有错
0c609d60dac2a42fd979999c15db1ebdeaedfb84
YujiaY/leetCodePractice
/LeetcodePython3/q0143.py
966
4
4
#!/usr/bin/python3 from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ if head is None: return nodesList: List[ListNode] = list() p: ListNode = head while p is not None: nodesList.append(p) p = p.next lenOfList: int = len(nodesList) for i in range(lenOfList // 2): nodesList[i].next = nodesList[lenOfList - i - 1] nodesList[lenOfList - i - 1].next = nodesList[i + 1] nodesList[len(nodesList) // 2].next = None node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next = node3 solu = Solution() solu.reorderList(node1) p = node1 while p is not None: print(p.val) p = p.next
61400eb94c6b0302b2ec1644793a1e5aa8d44bf9
PaLaMuNDeR/algorithms
/Coding Interview Bootcamp/08_array_chunk.py
1,427
4.09375
4
import timeit import operator """ Given an array and chunk size, divide the array into n amount of sub-arrays Examples: chunk([1,2,3,4],2) -> ([1,2],[3,4]) chunk([1,2,3,4,5],2) -> ([1,2],[3,4],[5]) chunk([1,2,3,4,5,6,7,8],3) -> ([1,2,3],[4,5,6],[7,8]) chunk([1,2,3,4,5],4) -> ([1,2,3,4],[5]) chunk([1,2,3,4,5],10) -> ([1,2,3,4,5]) """ def chunk(arr, chunk): """ Cut and append lists Time - 47 sec. """ small_list = [] answer = [] for i in arr: if len(small_list) < chunk: small_list.append(i) else: answer.append(small_list) small_list=[] small_list.append(i) answer.append(small_list) return answer def chunk_with_slice(arr, chunk): """ Use Python's slicer Time - 16 sec """ answer = [] index = 0 while index < len(arr): answer.append(arr[index:index+chunk]) index = index+chunk return answer # print( chunk([1,2,3,4],2)) # print(chunk([1,2,3,4,5],2)) # print("This") # print(chunk([1,2,3,4,5,6,7,8,9,10],3)) # print( chunk([1,2,3,4,5],4)) # print( chunk([1,2,3,4,5],10)) arr_input = '[1,2,3,4,5,6,7,8,9,10]' * 10 chunk_input = 3 print "Method 1 - Chunk standard" print min(timeit.repeat(lambda: chunk(arr_input, chunk_input))) print "Method 2 - Chunk with slice" print min(timeit.repeat(lambda: chunk_with_slice(arr_input, chunk_input)))
142b93ee4184e6eff8a84d217ad397ae1cbf674f
Robert0306/dailyprogrammer
/expandNumbers.py
559
4.09375
4
# script to find the expanded number form. def expandedNumber(num): answer = [] divide = 10 # using 10 to divide the int. while divide < num: # modulo helps us find the number we need to work with. rest = num % divide if rest != 0: answer.insert(0, str(rest)) # Then we need to decrement num to find another number to work with num -= rest divide = divide * 10 answer.insert(0, str(num)) return "+".join(answer) # should ofc have more tests. print(expandedNumber(12))