blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f2b49603b7d73397bfea44963877660e6ba6b32c
gerffson/design-patterns-python
/adapter/object_adapter.py
1,003
3.515625
4
class ObjectAdapter(): """ This is the Adapter class: it implements the target interface that is expected by the clients and is composed of an Adaptee object instance. In this case, adaptation is achieved through composition. Please notice that, as Python is dinamically typed, it makes no sense to rely on type hierarchy because the clients can't be aware of the type definitions: instead, clients only rely on duck typing. This also means that class adaptation is not a valid alternative. """ _adaptee = None def __init__(self, adaptee): self._adaptee = adaptee def get_operands(self): return [ self._adaptee.get_first_operand(), self._adaptee.get_second_operand()] def sum(self): return self._adaptee.compute_sum() def multiply(self): return self._adaptee.get_first_operand() * \ self._adaptee.get_second_operand() def max(self): return self._adaptee.max()
3b0294c499e934ac3f9c8ea834484fa6f63461d7
davidmcglashan/advent-of-code-2020
/day 6.py
1,177
3.625
4
partOneTotal = 0 partTwoTotal = 0 with open('day 6 input.txt') as f: lines = f.readlines() partOneGroup = set() partTwoGroup = set() first = True for line in lines: line = line.strip() # a blank line is a new set. Add the group total to the major part One Total if ( len( line ) == 0 ): print( partTwoGroup ) partOneTotal = partOneTotal + len( partOneGroup ) partTwoTotal = partTwoTotal + len( partTwoGroup ) partOneGroup = set() partTwoGroup = set() first = True continue # Pile all the chars on this line into the partOneGroup set. for c in line: partOneGroup.add( c ) # the part two group is the intersection of this line and the current part two group if ( len( partTwoGroup ) == 0 and first ): partTwoGroup = partTwoGroup.union( partOneGroup ) else: tempGroup = set() for c in line: tempGroup.add( c ) partTwoGroup = partTwoGroup.intersection( tempGroup ) first = False print( partOneTotal ) print( partTwoTotal )
899e033fb380e35de6bc47b4328d33c15f0fde73
cenwachukwu/pythonCLIProject
/notes.py
8,386
3.75
4
#first after creating your directory and your file is to run {pipenv install peewee then pipenv install psycopg2-binary} to install peewee in your file #importing peewee from peewee import * from datetime import date #Using the PostgresqlDatabase class to create a database connection, #passing in the name of the database (in the case = notetaker), the user (postgres), the password (blank), the host (localhost), and the port. db = PostgresqlDatabase('notetaker2', user='postgres', password='', host='localhost', port=5432) #Use db.connect() to actually connect to the database db.connect() #PeeWee gives us a base Model class that we can inherit from. #Our model needs to define the fields for that SQL table as well as the database the table should be in #(because there can be more than one). class BaseModel(Model): #this class defines a BaseModel class that sets the database connection class Meta: database = db #A Meta class is a class that describes and configures another class, #so basically to explain where exactly where our Note model #should be pulling its information from #Now that we have our BaseModel, we can define our model and have it inherit from this BaseModel class: # Define what a 'Note' (our model) is class NoteTaker(BaseModel): #These are all the fields NoteTaker has, but You need to explain to peewee what the datatype in each column in the table is: user = CharField() title = CharField() date = DateField() notes = CharField() # both CharField() and DateField() are from PeeWee's datatypes. others are BooleanField(), IntegerField() etc. # CharField() basically means that both the title and note fields are strings and # the DateField() means that the date field will take a date class User(BaseModel): #the requirement asked for users to be able to view all their notes or a particular note name = CharField() #in the functions below we would use their name as a filter in our select() #db.create_tables([NoteTaker]) to add this table to the database db.create_tables([NoteTaker, User]) # creating interactive input logic for creating the data: #initially, i didnt have this as a function but it makes more sense to have it as a function. #so we can have functions that serve as menu to view or create, creates new notes, and views notes or view particular notes #we also had to add the user, so we have to have a function that creates a user with the user table and adds it to the notetaker's user column def find_user(): name = str(input("Enter your username: ")).title() #adding a title() or upper() to variables you want to query is extremly important b/c lack of it can lead to dumb bugs print(f'Hello {name}') returning = User.select().where(User.name == name) if not returning : new_user = User(name=name) new_user.save() elif returning : your_notes = NoteTaker.select().where(NoteTaker.user == name).count()#i want to count the number of books each user has if your_notes >= 1: print(f'Youve got {your_notes} notes.') #and tell them oh you've xyz amout of notes else : print("Youve got 0 notes!") return name #return name #we pass the user's username to the rest of the function to be able to access it to create a user with that user name def view_or_create(name): note = input("view note or create new note?: ") if note == 'view note': your_notes = NoteTaker.select().where(NoteTaker.user == name).count() if your_notes >= 1: view_note(name) else: print("Youve got 0 notes!") create_note(name) elif note == 'create new note': create_note(name) def view_note(name): searchEngine = str(input("Type in note title or say view all: ")).title() #ask for input to enable us to select() search in the next step if searchEngine == 'View All': all_user_notes = NoteTaker.select().where(NoteTaker.user == name) #how we get all the notes belonging to the user using select print(f'{name}s notes: ') for notes in all_user_notes: #we use a for loop to loop/map through the notes belonging to the user and print it print(f'{notes.date}\n{notes.title}\n{notes.notes}') #\n makes the entry go down to the next line view_or_create(name) else : result = NoteTaker.get(NoteTaker.title == searchEngine, NoteTaker.user == name) #{Get} search finds a single data while {select} finds multiple #above we search by note title and by the user name for a strict single result search. #our first step to achieving crud. print(result.date) print(result.title) print(result.notes) #working on update and delete: user_edit = str(input("Would you like to edit the post? y/n: ")).title() if user_edit == 'Y': print(result.title) user_edit2 = str(input("Would you like to Update or Delete this note? update / delete: ")).title() if user_edit2 == 'Delete': result.delete_instance() print(f'{result} has been deleted') elif user_edit2 == 'Update': user_update = str(input("What would you like to update? title / notes / date")).title() if user_update == 'Title': update = str(input('Update your title: ')).title() result.title = update result.save() print(f'{result} has been updated') print(result.date) print(result.title) print(result.notes) elif user_update == 'Notes': update = input('Add some content to your note: ') result.notes = update result.save() print(f'{result} has been updated') print(result.date) print(result.title) print(result.notes) view_another = input('Would you like to view another note? Y/N: ') if view_another == "y": view_note(name) else : view_or_create(name) def create_note(name): #first step to creating a new note is to collect inputs # date input below is always year, date, month in that order, also because the date a num/integer, we wrap the input in int eg. # int(input()) print(f'{name}') year = int(input('Enter the year like so (2012) ')) month = int(input('Enter the month number like so (for March type 3): ')) day = int(input('Enter the day number like so (21): ')) # we can also ask for date input like so: date = int(input(enter date like so (1990, 11, 18))) and to get date of present time(date = datetime.datetime.now()) title = str(input('Add a title for your new note: ')).title() notes = input('Add some content to your note: ') # next step to bind all the entries together to make a new note in the NoteTaker db, we also call the name agruement as the name of the user new_note = NoteTaker( title=title, notes=notes, date=date(year, month, day), user=name) #next we save the new note like so: new_note.save() #next we display our new note: print("") #for space asthetics lol print(new_note.date) print(new_note.title) # print(f"{new_note.title}") print(f"{new_note.notes}") print("") #for space asthetics #next we create a cycle, so we ask the user if they want to create a another note or view a note create_another = input('Would you like to create another note or would you like to view notes? Enter create / view: ') if create_another == 'create' : create_note(name) elif create_another == 'view' : view_note(name) else : theNotes() #since we broke our code up into functions, we have to make a function to start our application def theNotes(): print("Welcome to the theNotesCli application!") print("To begin, enter your username") name = find_user() view_or_create(name) theNotes() #we call theNotes function here
46dc3ff1eb130cdf2ab1d64abc3d291f88b67d9d
Chiva-Zhao/pproject
/201909/20190910/matplotlib_viz.py
5,635
3.5
4
import numpy as np import matplotlib.pyplot as plt if __name__ == '__main__': # sample plot x = np.linspace(-10, 10, 50) y = np.sin(x) plt.plot(x, y) plt.title('Sine Curve using matplotlib') plt.xlabel('x-axis') plt.ylabel('y-axis') plt.show() # figure plt.figure(1) plt.plot(x, y) plt.title('Fig1: Sine Curve') plt.xlabel('x-axis') plt.ylabel('y-axis') plt.show() plt.figure(2) y = np.cos(x) plt.plot(x, y) plt.title('Fig2: Cosine Curve') plt.xlabel('x-axis') plt.ylabel('y-axis') plt.show() ### subplot # fig.add_subplot y = np.sin(x) figure_obj = plt.figure() ax1 = figure_obj.add_subplot(2, 2, 1) ax1.plot(x, y) ax2 = figure_obj.add_subplot(2, 2, 2) ax3 = figure_obj.add_subplot(2, 2, 3) ax4 = figure_obj.add_subplot(2, 2, 4) ax4.plot(x + 10, y) plt.show() # plt.subplots fig, ax_list = plt.subplots(2, 1, sharex=True) y = np.sin(x) ax_list[0].plot(x, y) y = np.cos(x) ax_list[1].plot(x, y) plt.show() # plt.subplot (creates figure and axes objects automatically) plt.subplot(2, 2, 1) y = np.sin(x) plt.plot(x, y) plt.subplot(2, 2, 2) y = np.cos(x) plt.plot(x, y) plt.subplot(2, 1, 2) y = np.tan(x) plt.plot(x, y) plt.show() # Using subplot2grid y = np.abs(x) z = x ** 2 plt.subplot2grid((4, 3), (0, 0), rowspan=4, colspan=2) plt.plot(x, y, 'b', x, z, 'r') ax2 = plt.subplot2grid((4, 3), (0, 2), rowspan=2) plt.plot(x, y, 'b') plt.setp(ax2.get_xticklabels(), visible=False) plt.subplot2grid((4, 3), (2, 2), rowspan=2) plt.plot(x, z, 'r') plt.show() ### formatting # Line # Color # Line # Style # Data # Marker # Line # Width # Alpha # Level / Transparency # Shorthand # notation # color y = x ax1 = plt.subplot(611) plt.plot(x, y, color='green') ax1.set_title('Line Color') plt.setp(ax1.get_xticklabels(), visible=False) # linestyle # linestyles -> '-','--','-.', ':', 'steps' ax2 = plt.subplot(612, sharex=ax1) plt.plot(x, y, linestyle='--') ax2.set_title('Line Style') plt.setp(ax2.get_xticklabels(), visible=False) # marker # markers -> '+', 'o', '*', 's', ',', '.', etc ax3 = plt.subplot(613, sharex=ax1) plt.plot(x, y, marker='*') ax3.set_title('Point Marker') plt.setp(ax3.get_xticklabels(), visible=False) # line width ax4 = plt.subplot(614, sharex=ax1) line = plt.plot(x, y) line[0].set_linewidth(3.0) ax4.set_title('Line Width') plt.setp(ax4.get_xticklabels(), visible=False) # alpha ax5 = plt.subplot(615, sharex=ax1) alpha = plt.plot(x, y) alpha[0].set_alpha(0.3) ax5.set_title('Line Alpha') plt.setp(ax5.get_xticklabels(), visible=False) # combine linestyle ax6 = plt.subplot(616, sharex=ax1) plt.plot(x, y, 'b^') ax6.set_title('Styling Shorthand') fig = plt.gcf() fig.set_figheight(15) plt.show() # legends y = x ** 2 z = x plt.plot(x, y, 'g', label='y=x^2') plt.plot(x, z, 'b:', label='y=x') plt.legend(loc="best") plt.title('Legend Sample') plt.show() # Legend with $Latex$ formatting # legend with latex formatting plt.plot(x, y, 'g', label='$y = x^2$') plt.plot(x, z, 'b:', linewidth=3, label='$y = x$') plt.legend(loc="best", fontsize='x-large') plt.title('Legend with LaTEX formatting') plt.show() ## axis controls # secondary y-axis fig, ax1 = plt.subplots() ax1.plot(x, y, 'g') ax1.set_ylabel(r"primary y-axis", color="green") ax2 = ax1.twinx() ax2.plot(x, z, 'b:', linewidth=3) ax2.set_ylabel(r"secondary y-axis", color="blue") plt.title('Secondary Y Axis') plt.show() # ticks y = np.log(x) z = np.log2(x) w = np.log10(x) plt.plot(x, y, 'r', x, z, 'g', x, w, 'b') plt.title('Default Axis Ticks') plt.show() plt.plot(x, y, 'r', x, z, 'g', x, w, 'b') # values: tight, scaled, equal,auto plt.axis('tight') plt.title('Tight Axis') plt.show() # manual plt.plot(x, y, 'r', x, z, 'g', x, w, 'b') plt.axis([0, 2, -1, 2]) plt.title('Manual Axis Range') plt.show() # Manual ticks plt.plot(x, y) ax = plt.gca() ax.xaxis.set_ticks(np.arange(-2, 2, 1)) plt.grid(True) plt.title("Manual ticks on the x-axis") plt.show() # minor ticks plt.plot(x, z) plt.minorticks_on() ax = plt.gca() ax.yaxis.set_ticks(np.arange(0, 5)) ax.yaxis.set_ticklabels(["min", 2, 4, "max"]) plt.title("Minor ticks on the y-axis") plt.show() # scaling plt.plot(x, y) ax = plt.gca() # values: log, logit, symlog ax.set_yscale("log") plt.grid(True) plt.title("Log Scaled Axis") plt.show() # annotations y = x ** 2 min_x = 0 min_y = min_x ** 2 plt.plot(x, y, "b-", min_x, min_y, "ro") plt.axis([-10, 10, -25, 100]) plt.text(0, 60, "Parabola\n$y = x^2$", fontsize=15, ha="center") plt.text(min_x, min_y + 2, "Minima", ha="center") plt.text(min_x, min_y - 6, "(%0.1f, %0.1f)" % (min_x, min_y), ha='center', color='gray') plt.title("Annotated Plot") plt.show() # global formatting params params = {'legend.fontsize': 'large', 'figure.figsize': (10, 10), 'axes.labelsize': 'large', 'axes.titlesize':'large', 'xtick.labelsize':'large', 'ytick.labelsize':'large'} plt.rcParams.update(params)
b04e7e104e4a865919126af2c51f998f457934de
BrianBORV/Tesis
/Drive/vista.py
6,737
3.671875
4
from tkinter import * from tkinter import ttk import quickstart # La clase 'Aplicacion' ha crecido. En el ejemplo se incluyen # nuevos widgets en el método constructor __init__(): Uno de # ellos es el botón 'Info' que cuando sea presionado llamará # al método 'verinfo' para mostrar información en el otro # widget, una caja de texto: un evento ejecuta una acción: class Aplicacion(): def __init__(self): # En el ejemplo se utiliza el prefijo 'self' para # declarar algunas variables asociadas al objeto # ('mi_app') de la clase 'Aplicacion'. Su uso es # imprescindible para que se pueda acceder a sus # valores desde otros métodos: self.raiz = Tk() self.raiz.geometry('1000x760') self.raiz.configure(bg='lightBlue') self.raiz.title('Aplicación') self.raiz.style=ttk.Style() # Impide que los bordes puedan desplazarse para # ampliar o reducir el tamaño de la ventana 'self.raiz': self.raiz.resizable() self.raiz.title('Ver info') # Define el widget Text 'self.tinfo ' en el que se # pueden introducir varias líneas de texto: self.tinfo = Text(self.raiz, width=100, height=40) # Sitúa la caja de texto 'self.tinfo' en la parte # superior de la ventana 'self.raiz': self.tinfo.pack(side=TOP) # Define el widget Button 'self.binfo' que llamará # al metodo 'self.verinfo' cuando sea presionado self.binfo = ttk.Button(self.raiz, text='Info', command=self.verinfo) # Coloca el botón 'self.binfo' debajo y a la izquierda # del widget anterior #self.binfo.pack(side=LEFT) # Define el botón 'self.bsalir'. En este caso # cuando sea presionado, el método destruirá o # terminará la aplicación-ventana 'self.raíz' con # 'self.raiz.destroy' ttk.Style().configure("TButton", padding=3, relief="flat", background="#125", font=("algerian",10)) self.bsalir = ttk.Button(self.raiz, text='Salir', command=self.raiz.destroy) self.bapi = ttk.Button(self.raiz, text='Excel', command = self.apiEx) self.bword = ttk.Button(self.raiz, text='Word', command = self.apiWo) self.bpres = ttk.Button(self.raiz, text='Slides', command = self.apiPre) self.bpdf = ttk.Button(self.raiz, text='PDF', command = self.apiPDF) self.bfolder = ttk.Button(self.raiz, text='Carpetas', command = self.apifol) self.bdescarga = ttk.Button(self.raiz, text='Descargar', command = self.apidesc) self.bcrear = ttk.Button(self.raiz, text='crear', command = self.apicrea) self.bcreardoc = ttk.Button(self.raiz, text='Crear Doc', command = self.creaDoc) self.bapi.place(x=270, y=655) self.bword.place(x=270, y=688) self.bpres.place(x=270, y=721) self.bpdf.place(x=420, y=708) self.bfolder.place(x= 420, y=671) self.bsalir.place(x=800, y=685) self.bdescarga.place(x=610, y=685) self.bcrear.place(x=100, y=671) self.bcreardoc.place(x=100, y=708 ) # El foco de la aplicación se sitúa en el botón # 'self.binfo' resaltando su borde. Si se presiona # la barra espaciadora el botón que tiene el foco # será pulsado. El foco puede cambiar de un widget # a otro con la tecla tabulador [tab] #self.binfo.focus_set() self.raiz.mainloop() def apiEx(self): quickstart.api('excel') self.tinfo.delete("1.0", END) i=len(quickstart.aux)-1 while i >= 0: self.tinfo.insert('1.0', str(i+1)+str(quickstart.aux[i])+'\n') i=i-1 def apiWo(self): quickstart.api('word') self.tinfo.delete("1.0", END) i=len(quickstart.aux)-1 while i >= 0: self.tinfo.insert('1.0', str(i+1)+str(quickstart.aux[i])+'\n') i=i-1 def apiPre(self): quickstart.api('pres') self.tinfo.delete("1.0", END) i=len(quickstart.aux)-1 while i >= 0: self.tinfo.insert('1.0', str(i+1)+str(quickstart.aux[i])+'\n') i=i-1 def apiPDF(self): quickstart.api('PDF') self.tinfo.delete("1.0", END) i=len(quickstart.aux)-1 while i >= 0: self.tinfo.insert('1.0', str(i+1)+str(quickstart.aux[i])+'\n') i=i-1 def apifol(self): quickstart.api('carpeta') self.tinfo.delete("1.0", END) i=len(quickstart.aux)-1 while i >= 0: self.tinfo.insert('1.0', str(i+1)+str(quickstart.aux[i])+'\n') i=i-1 def apidesc(self): quickstart.api('descarga') def apicrea(self): quickstart.api('crear') print('creado') def creaDoc(self): quickstart.api('crearDoc') print ('creado') def verinfo(self): # Borra el contenido que tenga en un momento dado # la caja de texto self.tinfo.delete("1.0", END) # Obtiene información de la ventana 'self.raiz': info1 = self.raiz.winfo_class() info2 = self.raiz.winfo_geometry() info3 = str(self.raiz.winfo_width()) info4 = str(self.raiz.winfo_height()) info5 = str(self.raiz.winfo_rootx()) info6 = str(self.raiz.winfo_rooty()) info7 = str(self.raiz.winfo_id()) info8 = self.raiz.winfo_name() info9 = self.raiz.winfo_manager() # Construye una cadena de texto con toda la # información obtenida: texto_info = "Clase de 'raiz': " + info1 + "\n" texto_info += "Resolución y posición: " + info2 + "\n" texto_info += "Anchura ventana: " + info3 + "\n" texto_info += "Altura ventana: " + info4 + "\n" texto_info += "Pos. Ventana X: " + info5 + "\n" texto_info += "Pos. Ventana Y: " + info6 + "\n" texto_info += "Id. de 'raiz': " + info7 + "\n" texto_info += "Nombre objeto: " + info8 + "\n" texto_info += "Gestor ventanas: " + info9 + "\n" # Inserta la información en la caja de texto: self.tinfo.insert("1.0", texto_info) def main(): mi_app = Aplicacion() return 0 if __name__ == '__main__': main()
462627812b44018fae34bf356779f96dcc387dba
shaversj/100-days-of-code
/days/44/cp.py
727
3.65625
4
import shutil import argparse def copy(src, dst): """Copies a file or folder from source to destination.""" try: shutil.copyfile(src, dst) # shutil.copyfile will throw an IsADirectoryError if src is a directory instead of a file. except IsADirectoryError: shutil.copytree(src, dst) except Exception as e: print(f'The following error occured: {e}') if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "src", type=str, help="source directory and/or filename") parser.add_argument( "dst", type=str, help="destination directory and/or filename") arguments = parser.parse_args() copy(arguments.src, arguments.dst)
135f030d65a54c87aeed6c71db125e2306b6854a
giahieu01/giahieu01
/b8c5.py
460
3.953125
4
def Sequential_Search(arr, n, x): for i in range(n): if (arr[i] == x): return i return -1 arr=[] n =int(input('Co bao nhieu item: ')) for k in range(n): item=input('Nhap item: ') arr.append(item) x =input('Nhap vao item can tim: ') n= len(arr) result = Sequential_Search(arr, n, x) if (result == -1): print("Phan tu khong co trong mang") else: print("Phan tu co trong mang", 'va co vi tri:',result)
7b21cbed746633114aec027fb229031ce8d8f52f
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/beginner-bite-161-count-files-and-directories.py
1,606
4.375
4
""" Complete count_dirs_and_files traversing the passed in directory path. Return a tuple of (number_of_directories, number_of_files) Let's use the tree command to show an example: $ mkdir -p project/a/1/I project/a/1/II project/a/2 project/b/1/I tree project/ project/ ├── a │ ├── 1 │ │ ├── I │ │ └── II │ └── 2 └── b └── 1 └── I 8 directories, 0 files Your solution should match these counts: $ python >>> from tree import count_dirs_and_files >>> count_dirs_and_files('project') (8, 0) Let's add two files: $ touch project/a/1/I/bob $ touch project/a/2/julian $ python >>> from tree import count_dirs_and_files >>> count_dirs_and_files('project') (8, 2) Good luck and have fun! """ import os # Solution 1 def count_dirs_and_files(directory='.'): """Count the amount of of directories and files in passed in "directory" arg. Return a tuple of (number_of_directories, number_of_files) """ # os.walk() returns a generator that creates a tuple of values (current_path, directories in current_path, # files in current_path) # Every time the generator is called it will follow each directory recursively until no further # subdirectories are available from the initial directory that walk was called upon count_dirs = 0 count_files = 0 for dir, number_of_dirs, number_of_files in os.walk(directory): count_dirs += len(number_of_dirs) count_files += len(number_of_files) result = (count_dirs, count_files) return result print(count_dirs_and_files())
754bc94b52ff09719cdd0f474a38df6236d11247
talkycape/PythonChallenge
/challenge0/challenge0.py
523
3.75
4
import webbrowser print("hello world") solution = 2**38 target_url = 'http://www.pythonchallenge.com/pc/def/%s.html' % solution print("The value of 2**38 is: " + str(solution)) print("The target URL is therefore: %s" % target_url) # If new is 0, the url is opened in the same browser window if possible. # If new is 1, a new browser window is opened if possible. # If new is 2, a new browser page ("tab") is opened if possible. # finish by opening up webpage of next step of challenge webbrowser.open(target_url, new=2)
6a7f403551b1283d7234ed8f92834c7194753b1a
smile921/hak_blog
/code/dato-code-userguide/how-to/word_frequency.py
1,503
3.59375
4
import graphlab as gl def get_word_frequency(docs): """ Returns the frequency of occurrence of words in an SArray of documents Args: docs: An SArray (of dtype str) of documents Returns: An SFrame with the following columns: 'word' : Word used 'count' : Number of times the word occured in all documents. 'frequency' : Relative frequency of the word in the set of input documents. """ # Use the count_words function to count the number of words. docs_sf = gl.SFrame() docs_sf['words'] = gl.text_analytics.count_words(docs) # Stack the dictionary into individual word-count pairs. docs_sf = docs_sf.stack('words', new_column_name=['word', 'count']) # Count the number of unique words (remove None values) docs_sf = docs_sf.groupby('word', {'count': gl.aggregate.SUM('count')}) docs_sf['frequency'] = docs_sf['count'] / docs_sf["count"].sum() return docs_sf # Sample SArray docs = gl.SArray(['The quick', 'brown fox', 'jumps over the', 'lazy dog']) docs_count = get_word_frequency(docs) print docs_count # +-------+-------+-----------+ # | word | count | frequency | # +-------+-------+-----------+ # | brown | 1 | 0.25 | # | lazy | 1 | 0.25 | # | dog | 1 | 0.25 | # | quick | 1 | 0.25 | # | jumps | 1 | 0.25 | # | the | 2 | 0.5 | # | fox | 1 | 0.25 | # | over | 1 | 0.25 | # +-------+-------+-----------+
8df47a922a83fcedcc6083e9323aa93dc3887503
FluffyKod/gameOfLife
/game_of_life_starter.py
4,282
4.09375
4
#!/usr/bin/env python3 import time import os import random import sys ################################### # HELPER FUNCTIONS ################################### def clear_console(): """ Clears the console using a system command based on the user's operating system. """ if sys.platform.startswith('win'): os.system("cls") elif sys.platform.startswith('linux'): os.system("clear") elif sys.platform.startswith('darwin'): os.system("clear") def get_integer_value(prompt, low, high): """ Asks the user for integer input and between given bounds low and high. """ while True: try: value = int(input(prompt)) except ValueError: print("Input was not a valid integer value.") continue if value < low or value > high: print("Input was not inside the bounds (value <= {0} or value >= {1}).".format( low, high)) else: break return value def get_live_neighbors(row, col, rows, cols, grid): """ Counts the number of live cells surrounding a center cell at grid[row][cell] """ life_sum = 0 for i in range(-1, 2): for j in range(-1, 2): # Make sure to count the center cell located at grid[row][col] if not (i == 0 and j == 0): # Using the modulo operator (%) the grid wraps around life_sum += grid[((row + i) % rows)][((col + j) % cols)] return life_sum def print_grid(rows, cols, grid, generation): """ Prints to console the Game of Life grid """ clear_console() # A single output string is used to help reduce the flickering caused by printing multiple lines output_str = "" # Compile the output string together and then print it to console output_str += "Generation {0} - To exit the program early press <Ctrl-C>\n\r".format( generation) for row in range(rows): for col in range(cols): if grid[row][col] == 0: output_str += ". " else: output_str += "@ " output_str += "\n\r" print(output_str, end=" ") ################################### # FUNCTIONS TO IMPLEMENT ################################### def create_initial_grid(rows, cols): """ Creates a random list of lists that contains 1s and 0s to represent the cells in Conway's Game of Life. """ raise NotImplementedError def create_next_grid(rows, cols, grid, next_grid): """ Analyzes the current generation of the Game of Life grid and determines what cells live and die in the next generation of the Game of Life grid. """ raise NotImplementedError def grid_changing(rows, cols, grid, next_grid): """ Checks to see if the current generation Game of Life grid differs from the next generation Game of Life grid. """ raise NotImplementedError def run_game(): """ Asks the user for input to setup the Game of Life to run for a given number of generations. """ clear_console() # Get the number of rows and columns for the Game of Life grid rows = get_integer_value("Enter the number of rows (10-60): ", 10, 60) cols = get_integer_value("Enter the number of cols (10-118): ", 10, 118) # Get the number of generations that the Game of Life should run for generations = get_integer_value( "Enter the number of generations (1-100000): ", 1, 100000) # Create the initial random Game of Life grids current_generation = create_initial_grid(rows, cols) next_generation = create_initial_grid(rows, cols) # Run Game of Life sequence gen = 1 for gen in range(1, generations + 1): if not grid_changing(rows, cols, current_generation, next_generation): break print_grid(rows, cols, current_generation, gen) create_next_grid(rows, cols, current_generation, next_generation) # Run automatically time.sleep(1 / 5.0) # Run manually # input() current_generation, next_generation = next_generation, current_generation print_grid(rows, cols, current_generation, gen) input("Press <Enter> to exit.") # Start the Game of Life run_game()
f9c7aa8e19d538c4cd2d40bf7d883b8282b31b15
AxelThevenot/Logistic_Regression
/algorithm/logistic_regression.py
7,976
3.65625
4
import csv # to deal with .csv file import numpy as np # to deal with array and matrix calculation easily import matplotlib.pyplot as plt # to plot import matplotlib.animation as animation # to animate the plot from mpl_toolkits.mplot3d import Axes3D # for 3D plot import matplotlib.patches as mpatches # to add legends easily import matplotlib.font_manager as font_manager # to change the font size # region variables X = None # features matrix Y = None # label array # weights and bias for logistic regression weights, bias = None, None # logistic regression with gradient descent LEARNING_RATE = 0.05 MAX_EPOCH = 20000 # stop the run at MAX_EPOCH DISPLAY_EPOCH = 500 # update the plot each DisPLAY_EPOCH epoch epoch = 0 # epoch counter cost = 0 # actual cost of the logistic regression # to display the graph of points fig = plt.figure(1, figsize=(8, 4.5)) # to plot ax = fig.add_subplot(111, projection='3d') # the axes ani = None # to animate started = False # variable to indicate if the run is started or not legends = {1: 'pass the two exams', 0: 'does not pass the two exams'} # legends color = {1: '#2F9599', 0: '#999999'} # category's color for points # endregion # region load dataset def load_dataset(filename): """ load a dataset from a filename :param filename: filename of the dataset :return: X features matrix, Y label array (as np.array) """ # read the file with open(filename, 'r') as file: reader = csv.reader(file, delimiter=',') # get header from first row headers = next(reader) # if headers are needed # get all the rows as a list dataset = list(zip(*reader)) # transpose the dataset matrix # change the label as 0 or 1 values dataset = [dataset[3], dataset[2], [1 if label == '2' else 0 for i, label in enumerate(dataset[4])]] # transform data into numpy array dataset = np.array(dataset).astype(float) X = dataset[:-1].transpose() # features matrix Y = dataset[-1].transpose() # label array return X, Y # endregion # region logistic regression def sigmoid(z): """ Sigmoid function :param z: input of the sigmoid function :return: sigmoid calculation """ return 1 / (1 + np.exp(-z)) def step_logistic_gradient(X, Y, learning_rate): """ One step of the gradient descent in logistic regression case :param X: features matrix :param Y: label array :param learning_rate: learning rate of interest :return: weights, bias, cost of the actual state """ global weights, bias # pick up the weights and the bias N = X.shape[0] # number of training samples # calculation of the z value as z = weigths * x + b z = np.dot(X, np.hstack((weights, bias))) # calculation of the sigmoid value of z h = sigmoid(z) # calculation of the cost cost = sum(- Y * np.log(h) - (1 - Y) * np.log(1 - h)) # Update gradients # gradient weights uptdate rule dJ/dweigth_i = 1/n * sum((h(x_i) - y_i) * x_i) # gradient bias uptdate rule dJ/dbias = 1/n * sum((h(x_i) - y_i)) error = h - Y gradient = np.divide(np.dot(error, X), N) # Update weights # weights update rule weigth_i := weigth_i - learning_rate * (dJ/dweigth_i) # bias update rule bias := bias - learning_rate * (dJ/dbias) weights -= learning_rate * gradient[:-1] bias -= learning_rate * gradient[-1] return weights, bias, cost def logistic_gradient(frame_number): """ Run the logistic regression """ if started: # waiting for start global weights, bias, cost, epoch # pick up global variables # Initialize the weigths and the bias with a 0 value (can be randomized too) weights = np.zeros(X.shape[1]) bias = np.zeros(np.shape(1)) # add a 1 variable to add the bias on the equation X_with_bias = np.hstack((X, (np.ones((X.shape[0], 1))))) while epoch < MAX_EPOCH: # run the logistic regression # update continuously the weigths and the bias weights, bias, cost = step_logistic_gradient(X_with_bias, Y, LEARNING_RATE) if epoch % DISPLAY_EPOCH == 0: # update the plot display() epoch += 1 # update the counter # endregion # region display def display(): """ plot the points of the training set """ global X, Y # pick the the features and the labels ax.clear() # clear the plot before the update # set the title, the axes and the legends ax.set_title('Passing final exams according to subject\'s average') ax.set_xlabel('Maths') ax.set_ylabel('French') ax.set_ylim(4, 19) # only for a better view plt_legends = [mpatches.Patch(color=color[key], label=legends[key]) for key, _ in enumerate(legends)] # plot the points of the training set for i, sample in enumerate(X): ax.scatter(sample[0], sample[1], Y[i], c=color[Y[i]]) if started: # waiting for start # The logistic regression is an area (infinity number of point) # So we will represent it line by line # It is a huge time-consuming process so put n as lower as possible n = 20 # number of line to plot # Create n different lines to render the logistic regression function[...] # [...] with a constant x value [...] lines = np.linspace(min(X.transpose()[0]), max(X.transpose()[0]), num=n) # [...] from the min to the max value of the second feature[...] min_y, max_y = min(X.transpose()[1]), max(X.transpose()[1]) y_array = np.linspace(min_y, max_y, num=n) # from min to max eah time # [...] with the sigmoid value height according to the features. # for each line to represent for _, x in enumerate(lines): x_array = np.full(n, x) # create x constant array z_array = np.array([]) # to append with the sigmoid values for _, y in enumerate(y_array): # append with the sigmoid value z_array = np.hstack((z_array, np.array(sigmoid(weights[0] * x + weights[1] * y + bias)))) # plot the line ax.plot(x_array, y_array, z_array, c='#8800FF', alpha=0.2) # add a big legend to describe the state of the logistic regression label = 'Logistic Regression :\n' label += 'Equation : {0} * math + {1} * french + {2}\n'. \ format(round(weights[0], 2), round(weights[1], 2), int(bias)) label += 'Epoch : {0}\n'.format(epoch) label += 'Learning Rate : {0}\n'.format(LEARNING_RATE) label += 'Squared Error : {0}'.format(round(cost, 2)) # add the created legend plt_legends.append(mpatches.Patch(color='#8800FF', label=label)) # to have smaller font size font_prop = font_manager.FontProperties(fname='C:\Windows\Fonts\Arial.ttf', size=6) # Put a legend above current axis plt.legend(handles=plt_legends, loc='upper center', bbox_to_anchor=(0.5, 0.1), prop=font_prop, ncol=3) # then plot everything fig.canvas.draw() def key_pressed(event): """ To start to run the programme by enter key :param event: key_press_event """ if event.key == 'enter': global started started = not started # endregion if __name__ == '__main__': X, Y = load_dataset('student.csv') # load dataset display() # first display to show the samples # connect to the key press event to start the program fig.canvas.mpl_connect('key_press_event', key_pressed) # to animate the plot and launch the gradient descent update ani = animation.FuncAnimation(fig, logistic_gradient) plt.show() # show the plot
cdfddeb686c6d61fb879230095bd612cd457c774
poojakancherla/Problem-Solving
/Leetcode Problem Solving/DataStructures/Strings/438-find-all-anagrams-in-a-string.py
1,599
3.625
4
# https://leetcode.com/problems/find-all-anagrams-in-a-string/ from collections import deque from collections import Counter def findAllNeedles(hayStack, needle): def delFromCounter(i): dq[hayStack[i]] -= 1 if dq[hayStack[i]] == 0: del dq[hayStack[i]] def addToCounter(i): dq[hayStack[i]] += 1 dq = Counter(hayStack[: len(needle)]) needle = Counter(needle); res = [] for i in range(len(hayStack) - (len(needle) - 1)): if dq == needle: res.append(i) if i + len(needle) < len(hayStack): delFromCounter(i) addToCounter(i + len(needle)) return res print(findAllNeedles("adsksjdfjsadaisfasd", "asd")) def findAllNeedles(hayStack, needle): dq = deque(hayStack[: len(needle)]) needle = deque(needle); res = [] for i in range(len(hayStack) - (len(needle) - 1)): if dq == needle: res.append(i) if i + len(needle) < len(hayStack): dq.popleft() dq.append(hayStack[i + len(needle)]) return res print(findAllNeedles("asdksjdfjasdaisfasd", "asd")) # from collections import Counter def findAnagrams(s, p): pCounter = Counter(p); sCounter = Counter(s[:len(p)-1]) result = [] for i in range(len(p)-1, len(s)): sCounter[s[i]] += 1 if sCounter == pCounter: result.append(i-len(p)+1) sCounter[s[i-len(p)+1]] -= 1 # decrease the count of oldest char in the window if sCounter[s[i-len(p)+1]] == 0: del sCounter[s[i-len(p)+1]] return result print(findAnagrams("adsksjdfjsadaisfasd", "asd"))
dec21d8b21dc06a286841442752191bd7bdf53fe
AlejandroQR23/pong
/main.py
1,276
3.6875
4
from turtle import Screen from paddle import Paddle from scoreboard import Scoreboard from ball import Ball import time # * Screen screen = Screen() screen.setup( width=800, height=600 ) screen.title( "Pong" ) screen.bgcolor( "black" ) screen.tracer( 0 ) # * Scoreboard scoreboard = Scoreboard() # * Ball ball = Ball() # * Paddles r_paddle = Paddle( xcor=350, ycor=0 ) l_paddle = Paddle( xcor=-350, ycor=0 ) # * Paddles controls screen.listen() screen.onkeypress( r_paddle.up, "Up" ) screen.onkeypress( r_paddle.down, "Down" ) screen.onkeypress( l_paddle.up, "w" ) screen.onkeypress( l_paddle.down, "s" ) # * Game flow game_is_on = True while game_is_on: time.sleep( ball.move_speed ) screen.update() ball.move() # Detect wall collision if ball.ycor() > 280 or ball.ycor() < -280: ball.bounce('y') # Detect collision with the paddles elif ball.xcor() > 320 and ball.distance(r_paddle) < 50 or ball.xcor() < -320 and ball.distance(l_paddle) < 50: ball.bounce('x') # Detects if the ball bounds at the edge elif ball.xcor() > 380: scoreboard.increase_score( 'left' ) ball.restart() elif ball.xcor() < -380: scoreboard.increase_score( 'right' ) ball.restart() screen.exitonclick()
87d72cf503e730caf97c173a6987658fd03c0074
iramshiv/ase_scraper
/src/main/python/duration_check.py
339
3.84375
4
def duration_check(duration_value): number_duration = int(duration_value) while number_duration > 2 or number_duration < 1: print("Enter Job posted duration: (0-Default, 1- newer than 24 hours, 2- newer than 7 days)") duration_value = input() number_duration = int(duration_value) return duration_value
4e80d38220902473aba2fb523c039d4cf15f36f0
Nutlope/algorithms
/Problems/Strings/reverse_vowels.py
803
3.890625
4
''' Leetcode problem 557: Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. ''' def reverseVowels(s: str) -> str: # O(N) time, O(N) space # Use a set for because checking if an element is in a set is O(1) on average vowels = set(list('aeiouAEIOU')) l = 0 r = len(s) - 1 s = list(s) # 2 pointer approach while l < r: if s[l] not in vowels: l += 1 elif s[r] not in vowels: r -= 1 else: s[l], s[r] = s[r], s[l] l += 1 r -= 1 return "".join(s) # Test Cases assert reverseVowels("hello") == "holle" assert reverseVowels("leetcode") == "leotcede" assert reverseVowels("Ello") == "ollE"
94ffc44d49bfd56e5080fa35385762a833d2a736
nguyntony/class
/small_exercises/small_sequences/5.py
108
3.734375
4
num_list = [-5, -4, -3, -2, -1, 0, 1, 10] for number in num_list: if number > 0: print(number)
d4ad9cd64e06a95e4b9fbd1f561138de81e82f5f
msckat11/python-challenge
/PyBank/main.py
4,028
3.953125
4
# Import libraries import os import csv #Tell it where to get the csv file file_path = os.path.join("Resources", "budget_data.csv") #Create variables to count months and net profit loss later total_months = 0 net_profit_loss = 0 #Create empty lists and dictionaries to fill later months = [] raw_pl_list = [] pl_list1 = [] pl_list2 = [] date_change_dict = {} date_change_dict = dict() #Print out heading print("Financial Analysis") print("---------------------------") #Open the csv file and read it with open(file_path, "r") as bankfile: csv_reader = csv.reader(bankfile, delimiter=",") csv_header = next(bankfile) for row in csv_reader: #Find Total Months and store in variable total_months = total_months + 1 #Find net profit/loss by adding each month's profit/loss to the last net_profit_loss = net_profit_loss + float(row[1]) #Pull all profit/loss values from each month and put them in the raw_pl_list raw_pl_list.append(row[1]) #Pull each month's date and put them in the months list months.append(row[0]) #Check creation of raw list # print(raw_pl_list) #Check creation of months list # print(months) #Creating the first zip list from the raw data list pl_list1 = raw_pl_list.copy() pl_list1.pop() #Check creation of pl_list1 # print(pl_list1) #Creating the second zip list from the raw data list pl_list2 = raw_pl_list.copy() pl_list2.pop(0) #Check creation of pl_list2 # print(pl_list2) #Create empty list to hold profit/loss changes as they are calculated pl_difference = [] pl_zip = zip(pl_list1, pl_list2) for pl_list1, pl_list2 in pl_zip: pl_difference.append(float(pl_list2)-float(pl_list1)) #Check creation of list holding profit/loss changes # print(pl_difference) #Calculate the average profit/loss change pl_avg_change = round(sum(pl_difference) / len(pl_difference), 2) # print(pl_avg_change) #Find the max value in pl_difference list pl_change_max = max(pl_difference) #Find the min value in pl_difference list pl_change_min = min(pl_difference) #Copy months list and remove first month dates = months.copy() dates.pop(0) # Check new dates list # print(dates) #Create dictionary with dates corresponding to profit/loss changes for i in range(len(pl_difference)): date_change_dict[pl_difference[i]] = dates[i] #Check dictionary creation # print(date_change_dict) #Call the key pair for pl_change_max pl_change_max_date = date_change_dict[pl_change_max] #Check the new variable for the date matching the max # print(pl_change_max_date) #Call the key pair for pl_change_min pl_change_min_date = date_change_dict[pl_change_min] #Check the new variable for the date matching the min # print(pl_change_min_date) print("Total Months: " + str(total_months)) print("Total Profit/Loss: $" + str(round(net_profit_loss))) print("Average Change: $ " + str(pl_avg_change)) print("Greatest Increase in Profits: " + str(pl_change_max_date) + " ($" + str(round(pl_change_max)) + ")") print("Greatest Decrease in Profits: " + str(pl_change_min_date) + " ($" + str(round(pl_change_min)) + ")") new_file_path = os.path.join("Analysis", "Financial_Analysis.txt") with open(new_file_path, "w+") as analysisfile: print("Financial Analysis", file=analysisfile) print("---------------------------", file=analysisfile) print("Total Months: " + str(total_months), file=analysisfile) print("Total Profit/Loss: $" + str(round(net_profit_loss)), file=analysisfile) print("Average Change: $ " + str(pl_avg_change), file=analysisfile) print("Greatest Increase in Profits: " + str(pl_change_max_date) + " ($" + str(round(pl_change_max)) + ")", file=analysisfile) print("Greatest Decrease in Profits: " + str(pl_change_min_date) + " ($" + str(round(pl_change_min)) + ")", file=analysisfile)
ea3a0799aab160429524881f76eeb7819d2d4c1d
Orodef/Python
/Reverse.py
367
4.3125
4
text = '' def reverse(text): total = [] for i in range(len(text)-1,-1,-1): # '-1' meanings in order: len-1, until -1 and step -1 total.append(text[i]) return "".join(total) print("Welcome to the reverse program") text = input("Enter the word you want to reverse: ") reverse(text) print("The reversed word is ", reverse(text))
3fdd830f6307a7c5a357b5fa517a0eebeb0cbde3
Iansdfg/9chap
/5Two pointers/521. Remove Duplicate Numbers in Array.py
515
3.65625
4
class Solution: """ @param nums: an array of integers @return: the number of unique integers """ def deduplication(self, nums): # write your code here left, right = 0, len(nums) - 1 visited = set() while left <= right: if nums[left] not in visited: visited.add(nums[left]) left += 1 else: nums[left], nums[right] = nums[right], nums[left] right -= 1 return left
308bfd8f6793e70b7939d043a172fd02b75b5bd8
dikspr/homeworks
/homework5/mod2.py
647
3.984375
4
# 2: Создайте модуль. # В нем создайте функцию, которая принимает список и возвращает из него случайный элемент. # Если список пустой функция должна вернуть None. # Проверьте работу функций в этом же модуле. # Примечание: Список для проверки введите вручную. Или возьмите этот: [1, 2, 3, 4] import random def rand_el(list): if len(list) == 0: func = None else: func = random.choice(list) return func
445ff3303ba592ecd82bbfe416b417e28929284c
dbzahariev/Python-Fundamentals
/lec_01_python_intro_functions_debugging/01_functions_and_debugging/08_multiply_evens_by_odds.py
314
4.1875
4
numbers = input() def printing(): sum_odd = 0 sum_even = 0 for later in numbers: if later != '-': number = int(later) if number % 2 == 1: sum_odd += number else: sum_even += number print(sum_odd * sum_even) printing()
c438e1b2aa27a8383d25645c1ca167ff0a19784b
mayankp158/Machine-Learning-and-Artificial-Intelligence
/MLAIPractical12.py
922
3.625
4
import numpy as np arr = np.array( [11, 22, 33, 0. ,44, 55] )#one float value will covert other in float in output print( "arr.sum() = ", arr.sum() ) print( "arr.std() = ", arr.std() ) print( "arr.mean() = ", arr.mean() ) print( "arr.max() = ", arr.max() ) print( "arr.min() = ", arr.min() ) print( "arr.size : = ", arr.size ) #index of non zero value print( "arr.nonzero() = ", arr.nonzero() ) print( "arr.dtype= " , arr.dtype ) #are all elements greater than zero print(np.all([1,2,3,4] ) ) print(np.all([1,2,0,3,4] ) ) #Is any elements non zero print( np.any( [1,2,3,4])) print( np.any( [1,2,0,3,4])) print( np.any( [0,0,0,0.,0])) print( np.any( [0,0,0,0.,0,1])) n1 = np.array([4,5,6]) n2 = np.array([1,2,3]) print( "\n\n" ) print( "n1 = " , n1 ) print( "n2 = " , n2 ) print( "n1 + n2 = " , n1 + n2 ) print( "n1 - n2 = " , n1 - n2 ) n3 = np.array([4,5,6,7]) #print( n1 + n3 ) #error
8298cc9ae110c032ce884c2c764c9cbdaa3a2872
sjd-2020-gy/sjd-5003-2-gy
/neighbourhood.py
12,813
3.65625
4
''' Neighbourhood Data Object Purpose: - Creates a 3 x 3 cell instance from the terrain Filename: - neighbourhood.py Input: - Terrain surface Raster data (excluding headers) - Terrain resolution / cell size - Terrain processing cell row number - Terrain processing cell column number Output: - Instance of Neighbourhood class Classes: - Neighbourhood - a 3 x 3 block of cells with the processing cell located in the centre (1,1) Methods: - slope_aspect - sink_fill - get<var name> (multiple) - Set<var name> (multiple). ''' import math #---------------------------------------------------------- # Neighbourhood Class #---------------------------------------------------------- class Neighbourhood(): ''' Processing an instance of a 3 x 3 Neighbourhood. ''' def __init__(self, terrain, resolution, y, x): ''' Initialisation of the Neighbourhood instance with variables relating to: - 3 x 3 neighbourhood grid - Slope (percentage & degrees) - Aspect Triggered by: - tothemaxmain.py Input: - Terrain Raster data (excluding headers) - Terrain resolution / cell size - Terrain processing cell row number - Terrain processing cell column number Output: - 3 x 3 cell instance from the terrain data ''' #--------------------------------------------------------- # Initialise variables. #--------------------------------------------------------- self.resolution = resolution self.y_boundary = len(terrain) - 1 self.x_boundary = len(terrain[0]) - 1 self.edge = None self.slope = -math.inf self.slope_perc = -math.inf self.slope_deg = -math.inf self.aspect = math.nan self.d8 = [] #--------------------------------------------------------- # Construct 3 x 3 Neighbourhood grid. # Identify, if applicable, direction of adjacent edge. #--------------------------------------------------------- if y == 0 and x == 0: self.neighbourhood = [ [terrain[y][x]] * 3, [terrain[y][x], terrain[y][x], terrain[y][x+1]], [terrain[y][x], terrain[y+1][x], terrain[y+1][x+1]]] self.edge = 'NW' elif y == 0 and x < self.x_boundary: self.neighbourhood = [ [terrain[y][x]] * 3, [terrain[y][x-1], terrain[y][x], terrain[y][x+1]], [terrain[y+1][x-1], terrain[y+1][x], terrain[y+1][x+1]]] self.edge = 'N' elif y == 0: self.neighbourhood = [ [terrain[y][x]] * 3, [terrain[y][x-1], terrain[y][x], terrain[y][x]], [terrain[y+1][x-1], terrain[y+1][x], terrain[y][x]]] self.edge = 'NE' elif y < self.y_boundary and x == 0: self.neighbourhood = [ [terrain[y][x], terrain[y-1][x], terrain[y-1][x+1]], [terrain[y][x], terrain[y][x], terrain[y][x+1]], [terrain[y][x], terrain[y+1][x], terrain[y+1][x+1]]] self.edge = 'W' elif y < self.y_boundary and x < self.x_boundary: self.neighbourhood = [ [terrain[y-1][x-1], terrain[y-1][x], terrain[y-1][x+1]], [terrain[y][x-1], terrain[y][x], terrain[y][x+1]], [terrain[y+1][x-1], terrain[y+1][x], terrain[y+1][x+1]]] self.edge = 'No Edge' elif y < self.y_boundary: self.neighbourhood = [ [terrain[y-1][x-1], terrain[y-1][x], terrain[y][x]], [terrain[y][x-1], terrain[y][x], terrain[y][x]], [terrain[y+1][x-1], terrain[y+1][x], terrain[y][x]]] self.edge = 'E' elif x == 0: self.neighbourhood = [ [terrain[y][x], terrain[y-1][x], terrain[y-1][x+1]], [terrain[y][x], terrain[y][x], terrain[y][x+1]], [terrain[y][x]] * 3] self.edge = 'SW' elif x < self.x_boundary: self.neighbourhood = [ [terrain[y-1][x-1], terrain[y-1][x], terrain[y-1][x+1]], [terrain[y][x-1], terrain[y][x], terrain[y][x+1]], [terrain[y][x]] * 3] self.edge = 'S' else: self.neighbourhood = [ [terrain[y-1][x-1], terrain[y-1][x], terrain[y][x]], [terrain[y][x-1], terrain[y][x], terrain[y][x]], [terrain[y][x]] * 3] self.edge = 'SE' #--------------------------------------------------------- # Seperate the centre Neighbourhood cell from the # neighbours and order the neighbours for D8 slope # calculation purposes, starting with the East # neighbour and working clockwise. #--------------------------------------------------------- self.centre = self.neighbourhood[1][1] # Processing cell self.neighbours = [ self.neighbourhood[1][2], # East neighbour self.neighbourhood[2][2], # South-East neighbour self.neighbourhood[2][1], # South neighbour self.neighbourhood[2][0], # South_West neighbour self.neighbourhood[1][0], # West neighbour self.neighbourhood[0][0], # Noth_West neighbour self.neighbourhood[0][1], # North neighbour self.neighbourhood[0][2]] # North-East neighbour def slope_aspect(self, d8_dict, nodata_value): ''' Use this method to identify the maximum downhill gradient of a Neigbourhood, and the applicable aspect using D8 notation. Start with the East neighbour and work clockwise. Triggered by: - tothemaxmain.py Input: - D8 dictionary - Geo-referenced NoData value Output: - Slope calculation as a percentage - Slope calculation in degrees - Aspect of max. gradient (first cell if more than 1 with the same) - List of D8 directions containing the same maximum slope ''' # --Straight edge-- ---------Corner edge-------- DICT_EDGE = {0:('NE', 'E', 'SE'), 1:('NE', 'E', 'SE', 'S', 'SW'), 2:('SW', 'S', 'SE'), 3:('NW', 'W', 'SW', 'S', 'SE'), 4:('NW', 'W', 'SW'), 5:('SW', 'W', 'NW', 'N', 'NE'), 6:('NW', 'N', 'NE'), 7:('NW', 'N', 'NE', 'E', 'SE')} dist_adjacent = self.resolution dist_diagonal = math.sqrt((self.resolution**2) * 2) #--------------------------------------------------------- # Starting from the East neighbour and working clockwise. #--------------------------------------------------------- for n, neighbour in enumerate(self.neighbours): # Do not use if upward gradient if self.centre == nodata_value: break # Do not use if neighbour contains NoData if self.neighbours[n] == nodata_value: continue # Do not use if neighbour is outside of the boundaries if self.edge in DICT_EDGE[n]: continue # Do not use if upward gradient if self.centre - self.neighbours[n] < 0: continue # Is cells comparison orthogonl or diagonal to each other? # Note: diagonal is when n = 1, 3, 5 or 7) if n % 2 == 0: if (self.centre - self.neighbours[n]) / dist_adjacent \ > self.slope: self.slope = (self.centre - self.neighbours[n]) \ / dist_adjacent self.d8 = [n] self.aspect = d8_dict[2**n] elif (self.centre - self.neighbours[n]) / dist_adjacent \ == self.slope: self.d8.append(n) else: if (self.centre - self.neighbours[n]) / dist_diagonal \ > self.slope: self.slope = (self.centre - self.neighbours[n]) \ / dist_diagonal self.d8 = [n] self.aspect = d8_dict[2**n] elif (self.centre - self.neighbours[n]) / dist_diagonal \ == self.slope: self.d8.append(n) #--------------------------------------------------------- # No downhill slope found #--------------------------------------------------------- if math.isinf(self.slope): self.slope_perc = math.nan self.slope_deg = math.nan else: self.slope_perc = self.slope * 100 self.slope_deg = math.atan(self.slope) * 180 / math.pi def sink_fill(self, d8_dict): ''' Use this method to fill the processing cell when it does not have any neighbours that lead downhill from it. Triggered by: - tothemaxmain.py Input: - D8 dictionary Output: - Slope calculation as a percentage - Slope calculation in degrees - Aspect calculation - D8 direction calculation ''' #--------------------------------------------------------- # If the processing cell is not an an edge cell, modify # height value equal to the lowest height of the 8 # neighbours. Then assign slope and aspect. #--------------------------------------------------------- if self.edge == 'No Edge' and self.neighbours.count(-math.inf) != 8: self.slope = 0.0 self.d8 = [self.neighbours.index( min(n for n in self.neighbours if n != -math.inf))] self.aspect = d8_dict[2**self.d8[0]] #--------------------------------------------------------- # If the cell is now filled, do more slope calculations. #--------------------------------------------------------- if math.isinf(self.slope) is False: self.slope_perc = self.slope * 100 self.slope_deg = math.atan(self.slope) * 180 / math.pi #------------------------------------- # Get & Set methods #------------------------------------- @property def edge(self): '''Get the cell edge indicator''' return self._edge @edge.setter def edge(self,val): '''Set the cell edge indicator''' self._edge = val @property def y_boundary(self): '''Get the y axis boundary''' return self._y_boundary @y_boundary.setter def y_boundary(self,val): '''Set the y axis boundary''' self._y_boundary = val @property def x_boundary(self): '''Get the x axis boundary''' return self._x_boundary @x_boundary.setter def x_boundary(self,val): '''Set the x axis boundary''' self._x_boundary = val @property def slope(self): '''Get the cell to cell rise over run value''' return self._slope @slope.setter def slope(self,val): '''Set the cell to cell rise over run value''' self._slope = val @property def slope_perc(self): '''Get the cell to cell slope as a percentage value''' return self._slope_perc @slope_perc.setter def slope_perc(self,val): '''Set the cell to cell slope as a percentage value''' self._slope_perc = val @property def slope_deg(self): '''Get the cell to cell slope in degrees value''' return self._slope_deg @slope_deg.setter def slope_deg(self,val): '''Set the cell to cell slope in degrees value''' self._slope_deg = val @property def aspect(self): '''Get the cell aspect value''' return self._aspect @aspect.setter def aspect(self,val): '''Set the cell aspect value''' self._aspect = val
9290087a2c36ac9563a01857245c9be22e41912f
oscarjibo/project-ux-identificador-analisis-qra
/algoritmo.py
3,516
3.78125
4
# arrancamo import listas.py import fun # numero de instalacion numero_instalaciones=int(input()) instalacion=[] tipo_instalaciones=[] numero_sustancias=[] tipo_sustancia=[] tipo_sus_t_i_e=[] cantidad_sustancia=[] condiciones=[] o1=[] o2=[] o3=[] g=[] d=[] A_sus=[] num_dis=[] distancias_s=[] for i in range(1,numero_instalaciones+1): print("tipo de instalacion (Almacenamiento) (Proceso)", i,":") tipo_in = (input()) print("ingrese condiciones de instalacion 'Aire libre' 'Cerrada' 'condicion A' 'condicion B': ") # - instalación al aire libre: 1.0 condicion=(input()) print("ingrese cuantas sustancias hay en instacion :",i) sustancias = [] cantidades = [] distancias = [] numero_sustancia=int(input()) for h in range(1,numero_sustancia+1): print("ingrese sustancia :",h, " de instalacion :",i) sus=input() sustancias.append(sus) print("ingrese cantidad de sustancia :", h, " de instalacion :", i) cant=input() cantidades.append(cant) tipo_sustancia.append(sustancias) cantidad_sustancia.append(cantidades) instalacion.append(i) tipo_instalaciones.append(tipo_in) condiciones.append(condicion) numero_sustancias.append(numero_sustancia) distancias_s.append(distancias) for i in range(len(instalacion)): print("===================================") print("INSTALACION ",i+1) print("===================================") g_sus = [] o3_sus = [] d_sus = [] tipo_sus=[] a_sus=[] # iniciamos los factores A A_tox=0 A_inf=0 A_exp=0 # para las distancias # inicio cilos print( "| instalacion :", instalacion[i] , " | tipo :" , tipo_instalaciones [i], "| sustancia: ", tipo_sustancia[i],"| cantidad : ", cantidad_sustancia[i],"| condicion :", condiciones[i]) o_1=fun.buscar_o1(tipo_instalaciones[i]) o1.append(o_1) print("| o1","instalacion:",instalacion[i]," = ",o_1) o_2=fun.buscar_o2(condiciones[i]) o2.append(o_2) print("| o2","instalacion:",instalacion[i]," = ",o_2) for t in range(numero_sustancias[i]): g1,o31,d1,Tipo1= fun.buscar_G_y_o3_y_d(tipo_sustancia[i][t],cantidad_sustancia[i][t]) A=fun.Calcular_A(o_1,o_2,o31,g1,d1) g_sus.append(g1) o3_sus.append(o31) d_sus.append(d1) tipo_sus.append(Tipo1) a_sus.append(A) print("para instalacion:",i+1,"sustancia:",Tipo1," el factor A es:",A) if Tipo1=="Toxica": A_tox +=A else: pass if Tipo1=="Inflamable": A_inf +=A else: pass if Tipo1=="Explosiva": A_exp +=A else: pass print("num_ind tox = ", A_tox) print("num_ind inf = ", A_inf) print("num_ind exp = ", A_exp) o3.append(o3_sus) g.append(g_sus) d.append(d_sus) A_sus.append(a_sus) tipo_sus_t_i_e.append(tipo_sus) print("==============================") # agregamos las distancias print("ingrese cuantas distancias desea conocer") num_di = int(input()) num_dis.append(num_di) for p in range(1, num_di + 1): print("ingrese distancia :", p, " para instalacion:",i+1) dis_n = float(input()) fun.buscar_s(dis_n,A_tox,"Toxica") fun.buscar_s(dis_n,A_inf,"Inflamable") fun.buscar_s(dis_n,A_exp,"Explosiva")
b7305367b256472f6418731aefbda47e41eda612
IvanWoo/coding-interview-questions
/puzzles/unique_morse_code_words.py
2,038
4
4
# https://leetcode.com/problems/unique-morse-code-words/ """ International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: 'a' maps to ".-", 'b' maps to "-...", 'c' maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word. Return the number of different transformations among all words we have. Example 1: Input: words = ["gin","zen","gig","msg"] Output: 2 Explanation: The transformation of each word is: "gin" -> "--...-." "zen" -> "--...-." "gig" -> "--...--." "msg" -> "--...--." There are 2 different transformations: "--...-." and "--...--.". Example 2: Input: words = ["a"] Output: 1 Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 12 words[i] consists of lowercase English letters. """ def unique_morse_representations(words: list[str]) -> int: def translate(word: str) -> str: morse_rule = [ ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ] return "".join([morse_rule[ord(char) - ord("a")] for char in word]) return len({translate(w) for w in words})
ad8bf6d2f51d2c0fa038bd16f1354668fd60d6e5
steamedbunss/LEARN-PYTHON-THE-HARD-WAY
/05.py
1,266
4.34375
4
my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = "Blue" my_teeth = "White" my_hair = "Brown" print("Let's talk about %s." % my_name) print("He's %d inches tall." % my_height) print("He's %d pounds heavy." % my_weight) print("Actually that's not too heavy.") print("He's got %s eyes and %s hair." % (my_eyes, my_hair)) print("His teeth are usually %s depending on the coffee." % my_teeth) #The % operand is used to form a set of variables enclosed in a tuple #using argument specifiers, special symbols like %s and %d #They tell python to take the variable on the right and put it in to replace #the %s with its value # %s - String(or any object with a string representation, like numbers) # %d - Integers # %f - Floating point numbers # %.<number of digits>f - Floating point numbers with a fixed amount of # digits to the right of the dot print("If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)) #SHOULD SEE Let's talk about Zed A. Shaw. He's 74 inches tall. He's 180 pounds heavy. Actually that's not too heavy. He's got Blue eyes and Brown hair. His teeth are usually White depending on the coffee. If I add 35, 74, and 180 I get 289.
5be54578c502bfe9d4ebbe593f09c2ef9f4f6691
gil-log/GilPyBrain
/baekjoon/stepseven/string_repeat.py
309
3.53125
4
# https://www.acmicpc.net/problem/2675 test_case_number = int(input()) for i in range(test_case_number): R, S = input().split() R = int(R) P = '' length = len(S) for index in range(length): letter = S[index] for repeat in range(R): P = P + letter print(P)
c01522cc690254a0695aaa184f7db3a5802fd7e8
kanuos/python-programs
/Basic Program/CompoundInterest.py
531
3.921875
4
# Python Program for compound interest def calculate_compound_interest(p,t,r,n): r = r/100 amount = p * (1+r/n)**(n*t) return amount print('-'*50) principal = float(input('Enter the principal : ')) time = int(input('Enter the time period : ')) rate = float(input('Enter the rate of interest : ')) compounding_frequency = int(input('Enter compounding frequency in momths : ')) print('-'*50) result = calculate_compound_interest(principal, time, rate, compounding_frequency) print(f'Final amount {round(result,2)}')
b9bb04f867fb279f24714ba655967765453638e7
Cuits-spec/testRepo
/Browser_driver/3-coad/test_09_pytest-参数化.py
947
3.625
4
# 如何编写一个pytest的测试类? import pytest # 定义被测试的函数 from parameterized import parameterized def divide(x, y): a = x / y return a # 1.定义pytest的测试类 class TestDivide: # 2.定义测试方法 # 测试个数位的除法 def test_pp_001(self): a = divide(2, 2) assert a == 1 # 测试多位数的除法 def test_pp_002(self): a = divide(20, 10) assert a == 2 @pytest.mark.parametrize(("x","y","z"),[(2,2,1),(20,10,2)]) def canshuhua001(self,x,y,z): a = divide(x,y) assert a == z # def test_canshuhua(self): # for x,y,z in [(2,2,1),(20,10,2)]: # print("x=%d y=%d z=%d" % (x,y,z)) # # a = divide(x,y) # assert a == z # # # @parameterized.expand([(2,2,1),(20,10,2)]) # def canshuhua2(self,x,y,z): # a = divide(x,y) # assert a == z
e545f33782c9dcc2b27792524c9875948552ee1a
dlm95/Highlight-Portfolio
/Academic Highlight/CSC 3340 Programming Languages/lab5.py
494
3.578125
4
import math import socket while True: p = float(input('Enter Original Investment \n')) if p > 0: break print (p) while True: r = float(input('Enter Annual Interest Rate \n')) / 100 if r >= 0: break print (r) while True: n = int(input('Enter years \n')) if n > 0 or n< 70: break print (n) def calculate(p,r,n): a = p( 1 + r ) ** n print('Amount you will have in your account is ' , a) calculate(p,r,n)
a9f15805e833ac78e2f082eebb3745d66c69f5f5
SowmicaML/Cryptography
/Caesar cipher/caesar.py
1,077
4.375
4
#python program to implement caesar cipher import sys #encrypt func def encrypt(str,shift): res="" for char in str: if(char == ' '): continue if(char.isupper()): res += chr(((ord(char)+shift-65)%26)+65) else: res += chr(((ord(char)+shift-97)%26)+97) return res #decrypt func def decrypt(str,shift): res="" for char in str: if(char == ' '): continue if(char.isupper()): res += chr(((ord(char)-shift-65)%26)+65) else: res += chr(((ord(char)-shift-97)%26)+97) return res print("CAESAR CIPHER") while(1): choice=int(input("\n1.encrypt text\n2.decrypt text\n")) if choice==1: string=input("enter plain text: ") shift=int(input("shift ?")) print("cipher text: ",encrypt(string,shift)) elif choice==2: string=input("enter cipher text: ") shift=int(input("shift ?")) print("plain text: ",decrypt(string,shift)) else: exit()
6e9b9f1c6d8a5ea8e3894b22c73c8c5acda2e717
ljrky/functional_program
/src/immutable.py
213
3.734375
4
a = 0 b = 0 def increment_mutable(): global a a += 1 return a def increment_immutable(b): return b + 1 print a print increment_mutable() print a print b print increment_immutable(b) print b
fbdb74171f5d1a1309d037b7f4bdb9c7784011a1
yq-12/ml
/Logistic/Logistic.py
2,800
3.640625
4
# logistic # 数据集来自《机器学习实战》 from matplotlib import pyplot as plt import numpy as np #读取数据 def readData(): filename = "testSet.txt" ifile = open(filename) lines = ifile.readlines() trainDataSet = [] trainLabel = [] for line in lines: line = line.split('\n')[0] lineList = line.split('\t') lineList = [float(x) for x in lineList] trainDataSet.append(lineList[:-1]) trainDataSet[-1].append(1) trainLabel.append(lineList[-1]) ifile.close() return trainDataSet, trainLabel # 绘制数据的散点图 def plotScatter(trainDataSet, trainLabel): labelList = [0, 1] m = len(trainLabel) for label in labelList: x1 = [] x2 = [] for i in range(m): if(trainLabel[i] == label): x1.append(trainDataSet[i][0]) x2.append(trainDataSet[i][1]) x1 = np.array(x1) x2 = np.array(x2) if(label == labelList[0]): plt.plot(x1, x2, 'o') else: plt.plot(x1, x2, '*') plt.xlim(-4, 4) plt.ylim(-5, 20) plt.xlabel('X1') plt.ylabel('X2') plt.show() #绘制回归直线 def plotBestFitLine(trainDataSet, trainLabel, w): labelList = [0, 1] m = len(trainLabel) for label in labelList: x1 = [] x2 = [] for i in range(m): if(trainLabel[i] == label): x1.append(trainDataSet[i][0]) x2.append(trainDataSet[i][1]) x1 = np.array(x1) x2 = np.array(x2) if(label == labelList[0]): plt.plot(x1, x2, 'o') else: plt.plot(x1, x2, '*') #画直线 x = np.arange(-3.0, 3.0, 0.1) w = np.array(w) y = -(w[0][0] * x + w[0][2]) / w[0][1] plt.plot(x, y, '-') plt.xlim(-4, 4) plt.ylim(-5, 20) plt.xlabel('X1') plt.ylabel('X2') plt.show() #sigmoid函数 def sigmoid(z): return 1 / (1 + np.exp(-z)) #运用梯度上升法 - 训练数据 def train(trainDataSet, trainLabel): trainDataSet = np.mat(trainDataSet) trainLabel = np.mat(trainLabel) learnRate = 0.01 w = np.mat(np.random.rand(1, np.shape(trainDataSet)[1])) #权重初始化 iteration = 100 #100次迭代 for i in range(iteration): print(w) hxi = sigmoid(w * trainDataSet.transpose()) dw = (trainLabel - hxi) * trainDataSet w = w + learnRate * dw return w def main(): #读取数据 trainDataSet, trainLabel = readData() #绘制数据散点图 #plotScatter(trainDataSet, trainLabel) #训练数据 w = train(trainDataSet, trainLabel) #w = (w1, w2, ...wn, b) #绘制直线 plotBestFitLine(trainDataSet, trainLabel, w) if __name__ == "__main__": main()
a38e30bad8ca940f381cf5bed9c2627c4c2b3d75
ItzMystic/school-projects
/Turtle game.
1,211
3.984375
4
#!/bin/python3 import time from turtle import * from random import randint speed(0) penup() goto(-140, 140) for step in range (15): write(step, align='center') right(90) forward(10) pendown() forward(150) penup() backward(160) left(90) forward(20) ada = Turtle() ada.color('red') ada.shape('turtle') ada.penup() ada.goto(-160, 100) ada.pendown() ada.right(360) hannah = Turtle() hannah.color('blue') hannah.shape('turtle') hannah.penup() hannah.goto(-160, 78) hannah.pendown() hannah.right(360) theodor = Turtle() theodor.color('green') theodor.shape('turtle') theodor.penup() theodor.goto(-160, 56) theodor.pendown() theodor.right(360) fantorangen = Turtle() fantorangen.color('pink') fantorangen.shape('turtle') fantorangen.penup() fantorangen.goto(-160, 34) fantorangen.pendown() fantorangen.right(360) import time num_seconds = 3 print('Place your bets!') for countdown in reversed(range(num_seconds + 1)): if countdown > 0: print(countdown, end='...') time.sleep(1) else: print('Go!') for turn in range(100): ada.forward(randint(1,5)) theodor.forward(randint(1,5)) hannah.forward(randint(1,5)) fantorangen.forward(randint(1,5))
cb33a7b8fbcdd9e8cc0a54ef7ef233e5235c2988
dyb-py/pk
/com/baizhi/杜亚博作业/计时器.py
948
3.78125
4
import time class TimeJ(): start='' end='' def start(self): print('开始计时') self.start=time.localtime() def end(self): if self.start: print('结束计时') self.end=time.localtime() else: print('未开始计时') def jiShi(self): if self.start and self.end: self.h=self.end[3]-self.start[3] self.m=self.end[4]-self.start[4] self.s=self.end[5]-self.start[5] print('经过了'+str(self.h)+'小时 '+str(self.m)+'分 '+str(self.s)+'秒') else:print('没有start或end') def __add__(self, other): h = self.h+other.h m = self.m + other.m s = self.s + other.s return ('一共经过了' + str(h) + '小时 ' + str(m) + '分 ' + str(s) + '秒') a=TimeJ() a.start() time.sleep(2) a.end() a.jiShi() b=TimeJ() b.start() time.sleep(2) b.end() b.jiShi() print(a+b)
73fe83f4681119f752e71f19ea8e30ea2de2ab68
junyanyao/LC_solutions
/_3_LongestSubstringWithoutRepeatingChar.py
2,298
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 27 17:01:15 2021 @author: YaoJunyan """ # 3 longest substring without repeating characters #解法1:单指针: window是滑窗内字符的集合,初始化为空。从前向后移动滑窗,同时更新当前子串长度cur_len和最长子串长度max_len。当滑窗右端移动到字符ch: #如果ch已存在window中,那么从滑窗的左端起删除字符,直到删除ch。每删除一个字符cur_len减1。 #将ch添加到window中,cur_len加1。 #更新最长子串长度max_len。 #返回max_len。 def lengthOfLongestSubstring(s): if s =='': return 0 window = set() left = 0 cur_len= 0 max_len = 0 for ch in s: while ch in window: window.remove(s[left]) cur_len -=1 left += 1 window.add(ch) cur_len +=1 max_len= max(max_len, cur_len) return max_len # 解法2: #双指针滑动窗口的经典写法。右指针不断往右移,移动到不能往右移动为止(具体条件根据题目而定)。当右指针到最右边以后,开始挪动左指针,释放窗口左边界 #滑动窗口的右边界不断的右移,只要没有重复的字符,就持续向右扩大窗口边界。一旦出现了重复字符,就需要缩小左边界,直到重复的字符移出了左边界,然后继续移动滑动窗口的右边界。以此类推,每次移动需要计算当前长度,并判断是否需要更新最大长度,最终最大的值就是题目中的所求。 def lengthOfLongestSubstring(s): start = 0 end = 0 store = {} max_len =0 while end < len(s) and start <= end: if s[end] in store: store.pop(s[start]) start +=1 else: store[s[end]]==True end +=1 max_len = max(len(store), max_len) return max_len #single pointer class Solution: def lengthOfLongestSubstring(self, s: str) -> int: char = [] cur= 0 max_=0 for i in range(len(s)): char.append(s[i]) cur +=1 if len(set(char)) != len(char): char.pop(0) cur -=1 max_= max(max_, cur) return max_
5c1d1d931d456b0622ec9fc9db3dc9a1601d667f
KATO-Hiro/AtCoder
/ABC/abc001-abc050/abc043/b.py
359
3.5
4
'''input 0BB1 1 01B0 00 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem B if __name__ == '__main__': s = input() result = '' for si in s: if si == '0' or si == '1': result += si elif si == 'B': if len(result) != 0: result = result[:len(result) - 1] print(result)
b3b6681536fad51b9a3c0c1629d16b95e5ad0a72
1fabrism/Daily-Programmer
/[Easy] UPC check digits/checkdigits.py
878
3.953125
4
#!usr/bin/env #TODO: # sanitize user input def check12(): #step 1 str_number = raw_input("Enter an 11 digit number: ") while (len(str_number) < 11): #If input is less than 11 digits, pad with leading zeroes str_number = "0"+str_number even_digits = [int(str_number[i]) for i in range(0, len(str_number)) if i%2==0] evensum = sum(even_digits) #step 2 evensum *= 3 #step 3 odd_digits = [int(str_number[i]) for i in range(0, len(str_number)) if i%2!=0] oddsum = sum(odd_digits) totalsum = oddsum + evensum #step 4 M = totalsum % 10 #step 5 if M == 0 : check = 0 else: check = 10-M return [check, str_number+str(check)] if __name__ == "__main__": [check, upc] = check12() print("Correct check digit is: {}. Complete UPC is: {}.".format(check,upc))
6c63b740793d2a4b27d5a546149a19a17f23f5cd
olivcmoi/euler
/euler028.py
781
3.890625
4
# -*- coding: utf-8 -*- #Number spiral diagonals #Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: #21 22 23 24 25 #20 7 8 9 10 #19 6 1 2 11 #18 5 4 3 12 #17 16 15 14 13 #It can be verified that the sum of the numbers on the diagonals is 101. #What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? limit = 1001; upright = 0; upleft = 0; downleft = 0; downright = 0; def calcul(limit): if limit == 1: return 1; else: upright = limit * limit; upleft = upright - limit + 1; downleft = upleft - limit + 1; downright = downleft - limit + 1; return calcul(limit-2) + upright + upleft + downleft + downright; print calcul(limit);
0d51d8e62b41361e89a1cc3edacbceedf65a743f
hartikainen/euler
/380_amazing_mazes.py
295
3.8125
4
def amazing_mazes(m, n): data = [[[0,0,0,0] for x in xrange(n)] for y in xrange(m)] for x in xrange(0, n): pass print(amazing_mazes(2, 3)) def jiiri(x_0, y_0, column): x, y = x_0, y_0 for i in xrange(2, column+1): x, y = 2*x + 2*y, x + y return x, y print jiiri(2, 3, 3)
1c323c88e96d9ff92826c62ed01aca867bb799ec
Vik81/algorithm
/lesson_5/Task_2.py
2,407
3.53125
4
# Написать программу сложения и умножения двух шестнадцатеричных чисел. При этом каждое число представляется # как массив, элементы которого это цифры числа. Например, пользователь ввёл A2 и C4F. # Сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно. # Сумма чисел из примера: [‘C’, ‘F’, ‘1’], произведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’]. from collections import deque print('Шестнадцатеричные цыфры вводятся в нижнем регистре') a = deque(input('Введите первое шестнадцатеричное число: ')) b = deque(input('Введите второе шестнадцатеричное число: ')) def sum_hex(a, b): hex_ = deque('0123456789abcdef') summ = deque() if len(a) < len(b): n = len(b) for i in range(len(a), n): a.extendleft('0') else: n = len(a) for i in range(len(b), n): b.extendleft('0') a.reverse() b.reverse() spam = 0 for i in range(n): elem = hex_.index(a[i]) + hex_.index(b[i]) + spam if elem <= 15: summ.extendleft(hex_[elem]) spam = 0 else: summ.extendleft(hex_[elem % 16]) spam = elem // 16 if spam > 0: summ.extendleft(hex_[spam]) a.reverse() b.reverse() return summ print(sum_hex(a, b)) # умножение hex_ = deque('0123456789abcdef') mult = deque() spam_mult = deque() spam = 0 if len(a) < len(b): n = len(b) for i in range(len(a), n): a.extendleft('0') else: n = len(a) for i in range(len(b), n): b.extendleft('0') a.reverse() b.reverse() for i in range(n): for j in range(n): elem = hex_.index(a[j]) * hex_.index(b[i]) + spam if elem <= 15: spam_mult.extendleft(hex_[elem]) spam = 0 else: spam_mult.extendleft(hex_[elem % 16]) spam = elem // 16 if spam > 0: spam_mult.extendleft(hex_[spam]) mult = sum_hex(mult, spam_mult) spam_mult.clear() spam_mult.extendleft(['0'] * (i + 1)) spam = 0 print(mult)
c0dc9b079c3b10ea103a92244cb2e6b65b88dc18
student-103653193/ICTPRG-Python
/Week 3/2strings.py
128
3.953125
4
string1= "Rela238#" password =str(input("Enter the password ")) if password == string1: print ('yes') else: print ('no')
973e89bbfdb77eac8cd1072d8de6adfed2cd0c81
hiagoleite93/exercicios
/aula6.py
676
3.921875
4
""" Iniciar com letra, pode conter numeros, separar _, letras minúsculas """ import math nome = 'Luiz Otávio' idade = 32 altura = 1.80 peso = 75 e_maior = idade > 18 imc = peso/(math.pow(altura, 2)) imc_1 = (f'{imc:.2f}') print('Nome: ', nome) print('Idade: ', idade) print('Altura: ', altura) print('É maior de idade? ', e_maior) print(imc_1) print(nome, 'tem', idade, 'anos de idade e tem', imc_1, 'de IMC.') ''' #formatar nome = 'Otavio' sobrenome = 'Miranda' nome_formatado = '{0:#^50} {1:@^50}' .format(nome, sobrenome) print(nome_formatado) print(nome.lower()) - tudo minusculo print(nome.upper()) - tudo maiusculo print(nome.title()) - Primeiras letas maiusculas '''
89e3058b2ac71809b033ec11c78877d3a2bb9e0f
hanrick2000/LaoJi
/Leetcode/0721.py
1,589
3.75
4
# 721. Accounts Merge ''' Basic idea: Union Find 1. Save unique email to username dictionary 2. union all emails under same username 3. get all emails under same root Time O(n) (Amortized) where n is the number of total emails ''' class UnionFind: def __init__(self, email_username): self.p = {email:email for email in email_username} def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): rootx = self.find(x) rooty = self.find(y) if rootx != rooty: self.p[rootx] = rooty class Solution: def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: # save all unique email to username pairs email_username = {} for username, *emails in accounts: for email in emails: email_username[email] = username # union all emails under one username uf = UnionFind(email_username) for username, *emails in accounts: for i in range(len(emails)-1): uf.union(emails[i], emails[i+1]) # get unioned each block emails root_children = collections.defaultdict(list) for email in email_username: root_children[uf.find(email)].append(email) # result format res = [] for root in root_children: res.append([email_username[root]]+sorted(root_children[root])) return res
27fe2d41e9a027f815bce85d1701e466141e81d0
AngryBird3/gotta_code
/leetcode_oj/surrounded_region3.py
1,622
3.859375
4
''' Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X X X X O O X X X O X X O X X After running your function, the board should be: X X X X X X X X X X X X X O X X ''' import collections class Solution: # @param {character[][]} board # @return {void} Do not return anything, modify board in-place instead. def solve(self, board): if not board: return row, col = len(board), len(board[0]) q = collections.deque() for i in xrange(row): if board[i][0] == "O": q.append((i, 0)) if board[i][col - 1] == "O": q.append((i, col -1)) for j in xrange(col): if board[0][j] == "O": q.append((0, j)) if board[row-1][j] == "O": q.append((row-1, j)) while q: r, c = q.popleft() l = list(board[r]) l[c] = 'B' board[r] = "".join(l) if r > 0 and board[r-1][c] == "O": q.append((r-1,c)) if r < row - 1 and board[r+1][c] == "O": q.append((r+1, c)) if c > 0 and board[r][c-1] == "O": q.append((r,c-1)) if c < col - 1 and board[r][c+1] == "O": q.append((r,c+1)) #Recover for i in xrange(row): for j in xrange(col): if board[i][j] == "X": continue l = list(board[i]) l[j] = "O" if l[j] == "B" else "X" board[i] = ''.join(l) s = Solution() #board = ["OOOO", "OOOO", "OOOO"] #board = ["XXXX", "XOOX", "XXOX", "XOXX"] board = ["OXXOX", "XOOXO", "XOXOX", "OXOOO", "XXOXO"] s.solve(board) for i in range(len(board)): print "" for j in range(len(board[i])): print board[i][j], " ",
14b0b5eb568a3d64d9856468c8d68a707e68ef33
kmtheobald/project_euler
/80-89/80.py
584
3.640625
4
# For the first one hundred natural numbers, find the total of the digital sums # of the first one hundred decimal digits for all the irrational square roots. import decimal from math import sqrt decimal.getcontext().prec = 105 # safely above 100 to avoid rounding errors digital_sum = 0 for i in range(1, 101): root = decimal.Decimal(i).sqrt() string = list(str(root)) if (len(string) > 2): del string[1] num_list = [int(c) for c in string] digital_sum += sum(num_list[:100]) else: continue print(digital_sum) # answer equals 40886
5d849d42860e51071232284dbd1f9d9516410655
wojtez/ThePythonWorkbook
/004.AreaOfField.py
457
4.34375
4
# Create a program that reads the length and width of a farmer’s field # from the user in feet. Display the area of the field in acres. # Hint: There are 43,560 square feet in an acre. width = float(input('What is the width of the field in feet: ')) length = float(input('What is the length of the field in feet: ')) area = width * length acr = round((area / 43560), 2) print('Area of the field is:', area, 'square feet, which gives:', acr, 'acres')
6d80a49e40b9566ef1a15df8ce3b339d0b7415c6
FacundoAcevedo/tp3
/modulos/tad.py
3,655
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # tad.py #version 0.1 """Modulo. Contiene los tipos abstractos de datos a usar en el programa""" class Pila(object): """Clase pila""" def __init__(self): """Constructor""" self.items = [] self.largo = 0 def __str__(self): """string""" return str(self.items) def __len__(self): """len""" return str(self.largo) def agregar(self,item): """Agrega un objeto a la pila""" self.items.append(item) self.largo += 1 def liberar(self): """Quita elemento de la pila""" try: self.largo -= 1 return self.items.pop() except: return None def estaVacia(self): """True si esta vacia, de lo contrario False""" return (self.items == []) class Cola(object): """Clase cola""" def __init__(self): """Constructor""" self.items = [] self.largo = 0 def __str__(self): """string""" return str(self.items) def __len__(self): """len""" return str(self.largo) def agregar(self,item): """Agrega un objeto al principio de la cola""" self.items.insert(0, item) self.largo += 1 def liberar(self): """Quita el primer elemento de la cola""" try: self.largo -= 1 return self.items.pop() except: return None def estaVacia(self): """True si esta vacia, de lo contrario False""" return (self.items == []) class ListaSimplementeEnlazada(object): " Modela una lista enlazada, compuesta de Nodos. " def __init__(self): """ Crea una lista enlazada vacía. """ # prim: apuntará al primer nodo - None con la lista vacía self.prim = None # len: longitud de la lista - 0 con la lista vacía self.len = 0 def agregar(self,dato): nodo=Nodo(dato,self.prim) #crea un nuevo nodo con el dato como parámetro self.prim=nodo #cambia la referencia self.prim y hace que apunte al nodo creado self.len+=1 def pop(self, i = None): """ Elimina el nodo de la posición i, y devuelve el dato contenido. Si i está fuera de rango, se levanta la excepción IndexError. Si no se recibe la posición, devuelve el último elemento. """ # Verificación de los límites if (i < 0) or (i >= self.len): raise IndexError("Índice fuera de rango") # Si no se recibió i, se devuelve el último. if i == None: i = self.len - 1 # Caso particular, si es el primero, # hay que saltear la cabecera de la lista if i == 0: dato = self.prim.dato self.prim = self.prim.prox # Para todos los demás elementos, busca la posición else: n_ant = self.prim n_act = n_ant.prox for pos in xrange(1, i): n_ant = n_act n_act = n_ant.prox # Guarda el dato y elimina el nodo a borrar dato = n_act.dato n_ant.prox = n_act.prox # hay que restar 1 de len self.len -= 1 # y devolver el valor borrado return dato def __str__(self): nodo = self.prim #comienza la lista s= '[' while nodo != None: s= s+ str(nodo)+ "," nodo = nodo.prox #pasa al proximo nodo s=s+ "]" # cierra la lista return s class Nodo(object): def __init__(self, dato=None, prox = None): self.dato = dato self.prox = prox def __str__(self): return str(self.dato) def verLista(nodo): """ Recorre todos los nodos a través de sus enlaces, mostrando sus contenidos. """ # cicla mientras nodo no es None while nodo: #muestra el dato print nodo # ahora nodo apunta a nodo.prox nodo = nodo.prox
1f0c00866cc0eca8087a7bb89e8c093bebd1113e
BhagyashreeKarale/request
/5ThodisiProgramming.py
1,328
3.65625
4
# Thodi si Programming! # What we have done so far # requests use kar ke courses download kar liye # aur user ko aapne ek list of courses bhi dikha di # Aage kya karna hai? # user koi bhi ek course select karega iske liye user, # uss course ke saamne likha hua number input karega # agar aap dhyaan se dekhenge toh, yeh number # course ki jo list aapko json se milegi # uss list ke `index` ki tarah hoga, jaise aapne # KBC game mei shayad kiya hoga # ussi json ko use kar kar, ab aap, uss course ke # corresponding jo `id` stored hai, `json` mei, # woh aap dhoondh sakte hai # yeh `id` print karo. yehi `id` hum agle part mei use karenge. import requests import json with open("/home/bhagyashri/Desktop/request/courses.json","r") as jsonfile: pobj=json.loads(jsonfile.read()) index=97 sr_1=1 for i in pobj: print(chr(index).upper(),".",i,":") sr_no=1 for values in pobj[i]: print(sr_no,".",values["name"]) sr_no+=1 print() index+=1 selection=int(input("Enter seriel number of the course you want to explore:\n")) for i in pobj: sr_no=1 for values in pobj[i]: if sr_no==selection: print("name of the selected course is:",values["name"]) print("ID of the selected course is:",values["id"]) sr_no+=1
0332c2f5563fb2ab2578841273eaf9a7b143411b
irfanahamed69/python
/Day1/exercise1.py
140
3.765625
4
names = ["john", "jake", "jack", "george", "jenny", "jason"] for name in names: if len(name) < 5 and 'e' not in name: print(name)
b0db2f98bc4e77b552cee0342b382de8d7171ece
GintasBu/python-code
/openbookproject_thinkcs_python/ch21_tree.py
1,892
3.546875
4
class Tree(): def __init__(self, cargo, left=None, right=None): self.cargo=cargo self.right=right self.left=left def __str__(self): return str(self.cargo) def total(tree): if (tree)==None: return 0 return total(tree.left)+total(tree.right)+tree.cargo def print_tree(tree): if tree == None: return print tree.cargo, print_tree(tree.left) print_tree(tree.right) def print_tree_postorder(tree): if tree == None: return print_tree_postorder(tree.left) print_tree_postorder(tree.right) print tree.cargo, def print_tree_inorder(tree): if tree == None: return print_tree_inorder(tree.left) print tree.cargo, print_tree_inorder(tree.right) def get_number(token_list): if get_token(token_list, '('): x = get_sum(token_list) # get the subexpression get_token(token_list, ')') # remove the closing parenthesis return x else: x = token_list[0] if type(x) != type(0): return None token_list[0:1] = [] return Tree (x, None, None) def get_token(token_list, expected): if token_list[0] == expected: del token_list[0] return True else: return False def get_product(token_list): a = get_number(token_list) if get_token(token_list, '*'): b = get_product(token_list) # this line changed return Tree ('*', a, b) else: return a def get_sum(token_list): a = get_product(token_list) if get_token(token_list, '+'): b = get_sum(token_list) return Tree ('+', a, b) else: return a def make_token_list(expr): import string expr=raw_input('Enter expression: ') ll=[] for e in expr: ll.append(e) ll.append('end') return ll
5a28477169c4a081dd1a78ab6a2afe8d87376295
Qiong/ycyc
/pchallengecom/chain.py
1,227
3.578125
4
#follow the link #http://www.pythonchallenge.com/pc/def/linkedlist.php # http://www.pythonchallenge.com/pc/def/peak.html #http://wiki.pythonchallenge.com/index.php?title=Level4:Main_Page """ <!-- urllib may help. DON'T TRY ALL NOTHINGS, since it will never end. 400 times is more than enough. --> <center> <a href="linkedlist.php?nothing=12345"><img src="chainsaw.jpg" border="0"/></a> A possibly clearer way uses a list comprehension instead of map(): >>> for linelist in banner: ... line = [ch * count for ch, count in linelist] ... print "".join(line) """ import urllib2 import re import time def main(): url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345" p1 = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=" number =12345 response = "" n=1 while (n<=400): response = urllib2.urlopen(url) txt = response.read() #print txt #time.sleep(1) match = re.search(r'(and the next nothing is )(.*)',txt) #print match.group() if match: number = match.group(2) print number url = p1 + number n +=1 else: print 'last number is ', number url = p1 + str(int(number)/2) n +=1 print 'the final url is ' , url if __name__ == '__main__': main()
37aa65bd55ab8c2309a869a61f1c0766a4690c53
whiteavian/hkrnk
/median.py
1,753
3.734375
4
from heapq import heappush, heappop class MedianList: def __init__(self): self.min_heap = [] self.max_heap = [] self.median = None def __repr__(self): return "Min {}, max {}".format(self.min_heap, self.max_heap) def add(self, element): element = float(element) if self.median: if element <= self.median: heappush(self.min_heap, -1 * element) else: heappush(self.max_heap, element) self.update_median() else: self.median = element heappush(self.min_heap, -1 * element) return self.median def update_median(self): self.balance() if len(self.min_heap) > len(self.max_heap): self.median = -1 * heappop(self.min_heap) heappush(self.min_heap, self.median * -1) elif len(self.max_heap) > len(self.min_heap): self.median = heappop(self.max_heap) heappush(self.max_heap, self.median) else: a = -1 * heappop(self.min_heap) b = heappop(self.max_heap) self.median = (a + b) / 2 heappush(self.min_heap, -1 * a) heappush(self.max_heap, b) return self.median def balance(self): if len(self.min_heap) -1 > len(self.max_heap): move = -1 * heappop(self.min_heap) heappush(self.max_heap, move) elif len(self.min_heap) < len(self.max_heap) - 1: move = heappop(self.max_heap) heappush(self.min_heap, -1 * move) ml = MedianList() a = ml.add(1) b = ml.add(2) c = ml.add(3) d = ml.add(4) e = ml.add(5) f = ml.add(6) g = ml.add(7) h = ml.add(8) i = ml.add(9) j = ml.add(10)
3b0b8161abc02dcd9a68dcafbe0405fc3e364ddc
SanGlebovskii/lesson_5
/homework_5_4.py
164
3.8125
4
n = int(input()) def sum_of_n(number) -> int: summary = 0 for i in range(1, number + 1): summary += 1 / i return summary print(sum_of_n(n))
5f4980e7b213461779bebe0f7feafd57d9c9a87e
rafaelperazzo/programacao-web
/moodledata/vpl_data/38/usersdata/87/12928/submittedfiles/decimal2bin.py
135
3.703125
4
# -*- coding: utf-8 -*- from __future__ import division n=bin(input("digite valor do numero binario:")) inteiro=int(n) print(inteiro)
5327cf91a96bf1b8de03987e42adc7d1c4e21b4f
anildhaker/DailyCodingChallenge
/LeetCode/stockProfitDP.py
608
3.71875
4
# Say you have an array for which the ith element is the price # of a given stock on day i. # If you were only permitted to complete at most one transaction (i.e., # buy one and sell one share of the stock), design an algorithm to find # the maximum profit. # MAx profit using dym=namic programming def maxProfit(self, prices: List[int]) -> int: if len(prices) <= 0: return 0 l = len(prices) dp = [0]*l for i in range(1,l): dp[i] = max(dp[i - 1] + prices[i] - prices[i - 1], 0) return max(dp)
32bd12a885092bf1d6c9c8f4f34d7e7bd4239ea2
jamesl33/210CT-Course-Work
/task4/part 2/main.py
1,448
4.3125
4
#!/usr/bin/python3 """main.py: Code to use quick sort to get an input from the user and return that indexes value from the sorted list """ import random from sorting import quick_sort def ordinal(num): """ordinal: Generate an ordinal number representation of 'num' :param num: Integer which you want the ordinal representation of """ if num >= 10 and num <= 20: suffix = 'th' else: suffix = {1: 'st', 2: 'nd', 3: 'rd'}.get(num % 10, 'th') return str(num) + suffix def main(): """ generate an array of length '10' sort it and as the user which element they would like """ sorted_array = quick_sort([random.randint(1, 1000) for i in range(10)]) while True: try: element = int(input('Which element do you want to find? ')) break except ValueError: print("Please enter a integer between 1 and {0}".format(len(sorted_array))) print("{0}".format(sorted_array)) try: if element > len(sorted_array) // 2: print('The {0} largest element is {1}'.format(ordinal(element), sorted_array[element - 1])) else: print('The {0} smallest element is {1}'.format(ordinal(element), sorted_array[element - 1])) except IndexError: raise IndexError('Index is not in list') main()
5340bd5f0dcd8a3789672a5c1074c967e02e144b
vb64/bulls_cows
/source/default/bull_cows.py
2,299
3.859375
4
"""Bull&Cows game.""" import sys import random PUZZLE_LENGTH = 4 def make_puzzle(): """Return random string from 4 different digits.""" puzzle = [] while len(puzzle) < PUZZLE_LENGTH: digit = str(random.choice(range(10))) if digit not in puzzle: # pragma: no cover puzzle.append(digit) return ''.join(puzzle) def is_unique_chars(text): """Return True, if text consist from unique chars.""" for i in range(len(text) - 1): if text[i] in text[i + 1:]: return False return True def is_valid(text): """Return True, if user input follow formal criteria.""" if len(text) != PUZZLE_LENGTH: return False try: int(text) except ValueError: return False if not is_unique_chars(text): return False return True class BullCows: """Bull&Cows quest.""" def __init__(self, puzzle=None): """Can use predefined puzzle.""" self.try_count = 0 self.puzzle = puzzle if self.puzzle is None: self.puzzle = make_puzzle() def check(self, answer): """Check answer string for cows and bulls.""" if not is_valid(answer): return (None, None) self.try_count += 1 position, cows, bulls = 0, 0, 0 for digit in answer: if digit in self.puzzle: if position == self.puzzle.index(digit): bulls += 1 else: cows += 1 position += 1 return (cows, bulls) def get_input(prompt): # pragma: no cover """Return user input.""" return input(prompt) def main(argv, puzzle=None): """Standalone app.""" quest = BullCows(puzzle=puzzle) cows, bulls = None, None if (len(argv) > 1) and (argv[1] == 'imcheater'): print("my puzzle:", quest.puzzle) while bulls != PUZZLE_LENGTH: cows, bulls = quest.check(get_input('enter 4 digits:')) if cows is None: print('need {} different digits!'.format(PUZZLE_LENGTH)) else: print('cows:', cows, 'bulls:', bulls) print('Done!') print('Quest solved with {} tries'.format(quest.try_count)) if __name__ == "__main__": # pragma: no cover main(sys.argv)
f7ab51ddc54c8a0b3d4a6bdbfda65f3da03a5b0f
katameszaros/homework
/1.hello/hello.py
265
3.9375
4
import sys def has_name_argument(): return len(sys.argv)>=2 def get_name_argument(): return sys.argv[1] def print_hello(name="World"): print("Hello " + name + "!") if has_name_argument(): print_hello(get_name_argument()) else: print_hello()
0797bae7b23070403ae5a39e71f343c38b17364d
wherculano/wikiPython
/04_Exercicios_Listas/06-MediaDe4Notas.py
613
3.875
4
""" Faça um Programa que peça as quatro notas de 10 alunos, calcule e armazene num vetor a média de cada aluno, imprima o número de alunos com média maior ou igual a 7.0. """ medias = [] for a in range(10): soma = 0 for n in range(4): nota = float(input(f'{n + 1}ª Nota do {a + 1}º aluno: ')) soma += nota print('-=' * 12) medias.append(soma / 4) # filtra a lista de médias e cria uma nova lista com medias maiores ou iguais a 7 cont = list(filter((lambda x: x >= 7), medias)) print(f'A quantidade de alunos com média maior ou igual a 7 é de: {len(cont)} aluno(s).')
0c6ee9533d11bd5c04e321f6a786490aa589525a
ftorresi/PythonLearning
/Unit8/ej8.34.py
1,432
3.546875
4
import numpy # not as np since np is an important variable here import time, sys try: x0 = int(sys.argv[1]) # Initial money F = int(sys.argv[2]) # Target Fortune p=float(sys.argv[3]) #Winning probability except IndexError: x0= 10 F = 100 p=0.7 #Using p<0.5 takes TOO LONG def number_of_games(x0,F,p): ns= 10000000 #batch size position = x0 #Only 1 particle starting at x0 count=0 # Draw from 1, 2 moves = numpy.random.random_integers(1, 2, size=ns) # Transform 1 to -1 and 2 to 1 moves = 2*moves - 3 while (position!=F): count+=1 # Draw from [0,1) moves = numpy.random.rand(ns) # Transform 1 to -1 according to p moves=numpy.where(moves<p,1,-1) for step in range(ns): position += moves[step] if position==F: realstep=(count-1)*ns+step+1 #print("A fortune of %i euro was reached in %i steps" %(F, realstep)) return realstep N=int(input("Number of experiments? ")) t0=time.clock() M=number_of_games(x0,F,p) t1=time.clock() texp=t1-t0 print("Time for 1st experiment: %g s"%texp) for i in range(1,N): M+=number_of_games(x0,F,p) M/=N print("It took an average of %i games to go from %i to %i euro playing a game with winning probability %g"%(M,x0,F,p)) r=numpy.log(M)/numpy.log(F-x0) print("The exponent r results %g"%r)
b8159f969ed72a6aa73d67fb449f6a807c2bc04e
pele98/Object_Oriented_Programming
/OOP/Exercise4/Exercise4_5/cellphone_main.py
995
4.03125
4
# File name: Cellphone_main # Author: Pekka Lehtola # Description: Cellphone class main function from cellphone_class import Cellphone #List of all cellphone objects cellphone_object_list = [] def create_cellphones(): global cellphone_object_list ID = 0 #Ask user how many objects are created #ID is given automaticly for phone. #Lastly add object to list for i in range(int(input("How many cellphones you want to create: "))): users_cellphone = input("Enter objects name: ") users_cellphone = Cellphone() users_cellphone.set_manufact() users_cellphone.set_model() users_cellphone.set_retail_price() ID += 1 users_cellphone.set_id(ID) cellphone_object_list.append(users_cellphone) print() #Prints every cellphone using __str__ method def main(): create_cellphones() print("Here is the cellphones you created: ") for object in cellphone_object_list: print(object) main()
964e60e3d535766bc01df74e592d4ebbc744f757
srisrinu1/Coursera
/Python files and dictionaries/week3/assignment-1.3.py
293
4.1875
4
''' Write a function called change that takes any string, adds “Nice to meet you!” to the end of the argument given, and returns that new string. ''' def change(string): return("{}Nice to meet you!".format(string)) if __name__=="__main__": string=input() print(change(string))
7a95dce1ce60dcc80a9cce866adba18d078036a8
eldadmwangi/sifu
/design/lru_cache.py
515
3.578125
4
from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.lru = OrderedDict() self.capacity = capacity def get(self, key): if key not in self.lru: return -1 v = self.lru.pop(key) self.lru[key] = v return v def put(self, key, value): if key in self.lru: self.lru.pop(key) elif len(self.lru) >= self.capacity: self.lru.popitem(last=False) self.lru[key] = value
4f28e04a784677848d23c7ab0b7b367e3d8a656b
xururuca82/PythonForEveryone
/12B-fact.py
464
3.578125
4
## 1부터 n까지 곱을 구하는 함수 def factorial(n): fact = 1 # 곱을 구하기 위한 변수 fact(시작 값을 1로 지정). for x in range(1,n+1): # range(1,n+1)로 1,2,...n까지 반복합니다(n+1은 제외). fact = fact*x # 지금까지 계사된 값에 x를 곱해 fact에 다시 저장합니다. return fact # 계산된 fact 값을 돌려줍니다. print(factorial(5)) print(factorial(10))
39a79a8daa28c7b852448e68bf31dbb4799003fc
skriptkoder/dns-resolver
/dns-resolver.py
6,842
3.703125
4
"""" A program that search and store store domain name dns Domain Name, A Records, MX Records, MX, CNAME, TXT """ import tkinter as tk from tkinter import * from tkinter.ttk import * from tkinter import scrolledtext import dns.resolver import whois import socket from tkinter import filedialog def add_spacer(): displayResult.insert(END, '----------------------------------------\n') def is_registered(domain_name): """ A function that returns a boolean indicating whether a `domain_name` is registered """ try: w = whois.whois(domain_name) except Exception: return False else: return bool(w.domain_name) def get_whois(p_domain_name): print('Retrieve WHOIS') whois_info = whois.whois(p_domain_name) displayResult.insert(END, 'Registrar: ') displayResult.insert(END, whois_info.registrar) displayResult.insert(END, '\n') displayResult.insert(END, 'Expiration Date: ') displayResult.insert(END, whois_info.expiration_date) displayResult.insert(END, '\n') add_spacer() def get_hostname(p_domain_name): try: a_record = dns.resolver.resolve(p_domain_name, 'A') except dns.resolver.NoAnswer: print('No A record') if not a_record == '': # retrieve hostname by ip for a_data in a_record: str_a_record = str(a_data) hostname = socket.gethostbyaddr(str_a_record) displayResult.insert(END, 'Hostname: ') displayResult.insert(END, hostname[0]) displayResult.insert(END, '\n') else: displayResult.insert(END, 'No A record for the Hostname: ') displayResult.insert(END, '\n') add_spacer() def loop_record(p_domain_name, p_record_type): _record = '' try: _record = dns.resolver.resolve(p_domain_name, p_record_type) except dns.resolver.NoAnswer: print('No', p_record_type, 'record') if _record: for data_record in _record: displayResult.insert(END, p_record_type) displayResult.insert(END, ': ') displayResult.insert(END, data_record) displayResult.insert(END, '\n') else: displayResult.insert(END, 'No', p_record_type, 'record') displayResult.insert(END, '\n') add_spacer() def search_command(): # clear results field displayResult.delete(1.0, END) domain_name = domainName_text.get() if not domain_name: displayResult.insert(END, 'Please enter a domain name') # displayResult.insert(END, '\n') elif not is_registered(domain_name): displayResult.insert(END, 'This domain is not registered') else: print('Domain Name: ', domain_name) # print('WHOIS: ', rdo_selected.get()) if rdo_selected.get() == 1: get_whois(domain_name) else: print('Do not Query WHOIS') if rdo_selected_host.get() == 1: get_hostname(domain_name) else: print('Do not Query hostname') # print('Query Type', cb_queryType.get()) record_type = cb_queryType.get() if not record_type == 'Any': print('Query Specific type', record_type) loop_record(domain_name, record_type) else: print('Query all record type') # displayResult.insert(END, 'Any') all_record_type = ['NS', 'A', 'CNAME', 'MX', 'TXT'] for record_type in all_record_type: loop_record(domain_name, record_type) def reset_command(): displayResult.delete(1.0, END) domainName_entry.delete(0, 'end') cb_queryType.current(0) rdo_yes.select() def close_command(): window.destroy() def print_command(): f = filedialog.asksaveasfile(mode='w', initialfile='DNS-' + domainName_text.get() + '.txt', filetypes=(("text files", "*.txt"), ("all files", "*.*")), defaultextension=".txt") if f is None: # asksaveasfile return `None` if dialog closed with "cancel". return text2save = str(displayResult.get(1.0, END)) # starts from `1.0`, not `0.0` f.write(text2save) f.close() # `()` was missing. window = tk.Tk() window.wm_title("DNS Resolver Tool") frame_domain_name = tk.Frame() frame_domain_name.pack(pady=(15, 5)) frame_ctrl_top = tk.Frame(pady=5) frame_ctrl_top.pack() frame_display = tk.Frame() frame_display.pack(pady=5) frame_ctrl_bottom = tk.Frame() frame_ctrl_bottom.pack(pady=10) # window.geometry("880x500") window.wm_title("DNS Resolver Tool") # Labels lbl_domain_name = tk.Label(master=frame_domain_name, text="Domain Name ", width=13) lbl_domain_name.pack(side=tk.LEFT) # Domain name entry field domainName_text = StringVar() domainName_entry = tk.Entry(master=frame_domain_name, width=76, textvariable=domainName_text) domainName_entry.pack(side=tk.LEFT) domainName_entry.focus() lbl_whois = tk.Label(master=frame_ctrl_top, text="WHOIS: ") lbl_whois.pack(side=tk.LEFT) rdo_selected = IntVar() rdo_yes = tk.Radiobutton(master=frame_ctrl_top, text='yes', value=1, variable=rdo_selected) rdo_yes.select() rdo_yes.pack(side=tk.LEFT) rdo_no = tk.Radiobutton(master=frame_ctrl_top, text='no', value=2, variable=rdo_selected) rdo_no.pack(side=tk.LEFT) lbl_hostname = tk.Label(master=frame_ctrl_top, text="Hostname: ") lbl_hostname.pack(side=tk.LEFT) rdo_selected_host = IntVar() rdo_host_yes = tk.Radiobutton(master=frame_ctrl_top, text='yes', value=1, variable=rdo_selected_host) rdo_host_yes.select() rdo_host_yes.pack(side=tk.LEFT) rdo_host_no = tk.Radiobutton(master=frame_ctrl_top, text='no', value=2, variable=rdo_selected_host) rdo_host_no.pack(side=tk.LEFT) lbl_query = tk.Label(master=frame_ctrl_top, text="Query Type:", width=13) lbl_query.pack(side=tk.LEFT) # combobox for Record Type cb_queryType = Combobox(master=frame_ctrl_top, text='Query Type', width=10) cb_queryType['values'] = ('Any', 'A', 'CNAME', 'MX', 'NS', 'TXT') cb_queryType.current(0) cb_queryType.pack(side=tk.LEFT, padx=(0, 2)) # Buttons btn_search = Button(master=frame_ctrl_top, text="Search", width=6, command=search_command) btn_search.pack(side=tk.LEFT, padx=2) btn_reset = Button(master=frame_ctrl_top, text="Reset", width=6, command=reset_command) btn_reset.pack(side=tk.LEFT, padx=2) btn_close = Button(master=frame_ctrl_top, text="Close", width=6, command=close_command) btn_close.pack(side=tk.LEFT, padx=2) # Labels lbl_result = tk.Label(master=frame_display, text="Result ", width=13) lbl_result.pack(side=tk.LEFT) displayResult = tk.scrolledtext.ScrolledText(master=frame_display, height=15, width=60) displayResult.pack(side=tk.LEFT) btn_print_to_file = Button(master=frame_ctrl_bottom, text="Print Result to File", width=15, command=print_command) btn_print_to_file.pack(side=tk.RIGHT) # Run program window.mainloop()
d39bef736958bf77d7367d746e1ad29abaca0395
A-Shot/Flask
/flask_7/csvorder.py
1,247
3.609375
4
import csv def csv_read(file_): with open(file_, 'rb') as csv_file: reader = csv.reader(csv_file) mydict = dict(reader) return mydict def csv_write(): with open('dict.csv', 'wb') as csv_file: writer = csv.writer(csv_file) for key, value in mydict.items(): writer.writerow([key, value]) def csv_write_R(file,value): with open(file, 'a') as csv_file: writer = csv.writer(csv_file) writer.writerow([value]) line_ = dict() info = list() total = list() def csv_read_(file_): mydict = dict() with open(file_, 'rb') as csv_file: reader = csv.reader(csv_file) try: print "fuck im traing" mydict = dict(reader) print "oho" except: print "ok" return mydict c = dict() c = csv_read_("test1.csv") print c index = 0 with open("test1.csv", 'rb') as csv_file: reader = csv.reader(csv_file) for i in reader: try: k = i[0]+","+i[2]+","+i[4][3:] csv_write_R("test2.csv",k) print "oops" index+=1 except: csv_write_R("test2.csv",i) print "done" print info """ buf=list() index = 0 with open("test1.csv", 'rb') as csv_file: while True: buf = csv_file.readline() print index info.append(buf) print buf index+=1 if not buf: break print index print info """
da2dc4c6eeeaddeacb6efc5bae48ea7a7557b382
micy-snoozle/GB_Python
/les6_task3.py
2,317
3.9375
4
# 3. Реализовать базовый класс Worker (работник), в котором определить атрибуты: # name, surname, position (должность), income (доход). # Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: # оклад и премия, например, {"wage": wage, "bonus": bonus}. # Создать класс Position (должность) на базе класса Worker. # В классе Position реализовать методы получения полного имени сотрудника # (get_full_name) и дохода с учетом премии (get_total_income). # Проверить работу примера на реальных данных (создать экземпляры класса Position, # передать данные, проверить значения атрибутов, вызвать методы экземпляров). class Worker: def __init__(self, name, surname, position, wage, bonus): self.name = name self.surname = surname self.position = position self._income = {"wage": wage, "bonus": bonus} class Position(Worker): def __init__(self, name, surname, position, wage, bonus): super().__init__(name, surname, position, wage, bonus) def get_full_name(self): return self.name + ' ' + self.surname def get_total_income(self): return self._income.get('wage') + self._income.get('bonus') a = Position('Tuomas', 'Ottosson', 'Therapist', 56100, 15250) print('Name: ', a.get_full_name(), '\n', 'Position: ', a.position, '\n', 'Salary: ', a.get_total_income(), '\n') b = Position('Kira', 'Saari', 'Nurse', 43200, 5450) print('Name: ', b.get_full_name(), '\n', 'Position: ', b.position, '\n', 'Salary: ', b.get_total_income(), '\n') c = Position('Taru', 'Eklund', 'Surgeon', 81400, 12600) print('Name: ', c.get_full_name(), '\n', 'Position: ', c.position, '\n', 'Salary: ', c.get_total_income(), '\n') d = Position('Helena', 'Engberg', 'Dentist', 61300, 28500) print('Name: ', d.get_full_name(), '\n', 'Position: ', d.position, '\n', 'Salary: ', d.get_total_income(), '\n')
51051711dbc5ad004ed1bc521204b4f0a7a3170f
tharlysdias/estudos-python
/aula_3.py
320
4.28125
4
# if elif else a = 3 b = 2 if a >= b: print("a é maior ou igual") else: print("a é menor") if a < b: print("Faça isso") # else if === elif elif a > b: print("Faça aquilo") # exemplos if a > b: print("A") elif a > c: print("C") elif b > c: print("B") elif c > b: print("C") else: print("Nada encontrado")
129536deecde1c2c6a46388062278d0aeafcd52e
MacBruce/lc101
/chapter10/counting.py
1,360
3.984375
4
#inp_str = input("Count the amount of time charecters appear in a string! Input string!") def count_char(str): #alphabet map alphabet = { 'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0, 'e' : 0, 'f' : 0, 'g' : 0, 'h' : 0, 'i' : 0, 'j' : 0, 'k' : 0, 'l' : 0, 'm' : 0, 'n' : 0, 'o' : 0, 'n' : 0, 'q' : 0, 'r' : 0, 's' : 0, 't' : 0, 'u' : 0, 'v' : 0, 'w' : 0, 'x' : 0, 'y' : 0, 'z' : 0 } #set string input to lower case new_str = str.lower() #loop over each item -- if i is a key in map add 1 to value at i and return for i in new_str: if alphabet.has_key(i): alphabet[i] += 1 return alphabet def main(): #test strings test = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc accumsan sem ut ligula scelerisque sollicitudin. Ut at sagittis augue. Praesent quis rhoncus justo. Aliquam erat volutpat. Donec sit amet suscipit metus, non lobortis massa. Vestibulum augue ex, dapibus ac suscipit vel, volutpat eget massa. Donec nec velit non ligula efficitur luctus. """ test2 = "My name is mac bruce" print(count_char(test2)) if _name_ = '_main_': main()
30f1b2cfac7c7d15b7e76177eef833828cd64c1c
Shivampanwar/algo-ds
/Dynamic Programming/Alpha code.py
3,460
3.984375
4
''' Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages: Alice: “Let’s just use a very simple code: We’ll assign ‘A’ the code word 1, ‘B’ will be 2, and so on down to ‘Z’ being assigned 26.” Bob: “That’s a stupid code, Alice. Suppose I send you the word ‘BEAN’ encoded as 25114. You could decode that in many different ways!” Alice: “Sure you could, but what words would you get? Other than ‘BEAN’, you’d get ‘BEAAD’, ‘YAAD’, ‘YAN’, ‘YKD’ and ‘BEKD’. I think you would be able to figure out the correct decoding. And why would you send me the word ‘BEAN’ anyway?” Bob: “OK, maybe that’s a bad example, but I bet you that if you got a string of length 5000 there would be tons of different decodings and with that many you would find at least two different ones that would make sense.” Alice: “How many different decodings?” Bob: “Jillions!” For some reason, Alice is still unconvinced by Bob’s argument, so she requires a program that will determine how many decodings there can be for a given string using her code. Input Input will consist of multiple input sets. Each set will consist of a single line of at most 5000 digits representing a valid encryption (for example, no line will begin with a 0). There will be no spaces between the digits. An input line of ‘0’ will terminate the input and should not be processed. Output For each input set, output the number of possible decodings for the input string. Print your answer taking modulo "10^9+7" ''' ''' Sample Input: 25114 1111111111 3333333333 0 Sample Output: 6 89 1 ''' def all_codes(array, size_array): if len(array) == 0: return 1 if len(array) == 1: return 1 else: length = len(array) if size_array[length] is not 0: return size_array[length] else: small_output = all_codes(array[1:], size_array) if 10 * array[0] + array[1] < 27: small_output += all_codes(array[2:], size_array) size_array[length] = small_output return small_output def all_codes_proper_dp(array): if len(array) == 1: return 1 if len(array) == 0: return 1 else: temp_array = [] temp_array.append(1) temp_array.append(1) for i in range(2, len(array) + 1): temp = temp_array[i - 1] numbers = array[-i:] k = numbers[0] * 10 + numbers[1] if k < 27: temp += temp_array[i - 2] temp_array.append(temp) return temp_array[-1] # a = str(input()) # while int(a) is not 0: # arr = [int(x) for x in a] # size_array = [] # size_array.append(0) # for i in range(len(arr) + 1): # size_array.append(0) # result = all_codes(arr, size_array) # print (result) # a = str(input()) a = str(input()) while int(a) is not 0: arr = [int(x) for x in a] result = all_codes_proper_dp(arr) print (result) a = str(input()) # inp=str(input()) # list_word=inp.split(" ") # for i in list_word: # if int(i)==0: # break # else: # arr = [int(x) for x in i] # size_array = [] # size_array.append(0) # for i in range(len(arr) + 1): # size_array.append(0) # result = all_codes(arr, size_array) # print (result)
381aafc92d22a8bf9a42fc31bdab369c3ceaa062
Pratyush1014/Python
/ControlstrucControlstat/numbers/strong.py
192
3.921875
4
n = input("Enter any number :") b = n sum = 0 while n>0 : d=1 a = n%10 while a>0 : d = d*a a-=1 sum = sum + d n = n/10 if sum == b : print "its a strong number" else : print "not"
c9e259d3d1d31fecb15b55420ffa02987f2603a2
adamtupper/alphablooms
/blooms/BloomsLogic.py
15,846
3.921875
4
"""A board class for the game of Blooms. """ import copy from itertools import permutations import matplotlib.pyplot as plt import numpy as np from bidict import bidict from matplotlib.patches import Patch, RegularPolygon class Board: """A board class for the game of Blooms. """ def __init__(self, size=4, score_target=15): """Initialise a new game board. The state of the board is represented by a 3D Numpy array, where the first dimension has four elements (one for each color stone) and the second an third dimensions represent a position on the board (in axial coordinates). :param size: the size of the board (either base 4, 5, or 6). :param score_target: the number of 'captures' to win the game. It is recommended that the number of captures are 15 for a base 4 board, 20 for a base 5 board, and 25 or 30 for a base 6 board. """ self.size = size self.score_target = score_target self.captures = [0, 0] self.board_2d = np.zeros((2 * self.size - 1, 2 * self.size - 1)) self.colours = [(1, 2), (3, 4)] self.move_map_player_0 = self.build_move_map(player=0) self.move_map_player_1 = self.build_move_map(player=1) def copy(self): """Create and return a copy of the current board state. :return: a copy of the board state. """ duplicate = copy.copy(self) duplicate.board_2d = np.copy(self.board_2d) duplicate.captures = copy.deepcopy(self.captures) return duplicate def build_move_map(self, player): """Build a dictionary that specifies the index of each possible move in a binary move vector. :param player: 0 or 1 to denote the player in question. :return: a dictionary which maps all possible moves that can be many by the player to a unique index that can be used to build a binary vector of valid moves. """ all_moves = self.get_legal_moves(player) move_map = bidict({m: i for i, m in enumerate(all_moves)}) return move_map def get_board_3d(self): """Converts the board representation into a 3D representation, where each channel stores the pieces of a different colour. This representation is used as input to a CNN. :return: A 3D representation of the board state, which is a 3D Numpy array with shape (4, 2n - 1, 2n - 1). """ board_3d = np.repeat(self.board_2d[np.newaxis, :, :], 4, axis=0) for c in range(0, board_3d.shape[0]): board_3d[c] = np.where(board_3d[c] == c + 1, 1, 0) return board_3d def get_empty_spaces(self): """Returns a list of all the empty spaces on the board. :return: the list of empty spaces on the board. Each element is the coordinate of the space, i.e. (q, r). """ empty_spaces = [] for r in range(self.board_2d.shape[0]): for q in range(self.board_2d.shape[1]): if self.is_valid_space((q, r)) and self.is_empty_space((q, r)): # (q, r) is a valid space and is empty empty_spaces.append((q, r)) return empty_spaces def is_valid_space(self, position): """Check to see if the given position is a valid space on the board. Because of the hexagonal shape of the board, some elements of the 2D board representation are not spaces on the board. :param position: A tuple representing the (q, r) coord to place the stone. :return: True if the given position is a valid space, False otherwise. """ q, r = position q_in_range = 0 <= q < 2 * self.size - 1 r_in_range = 0 <= r < 2 * self.size - 1 not_in_top_left = q + r >= self.size - 1 not_in_bottom_right = 4 * self.size - 4 - q - r >= self.size - 1 return q_in_range and r_in_range and not_in_top_left and not_in_bottom_right def is_empty_space(self, position): """Check to see if a space is empty. :param position: A tuple representing the (q, r) coord to place the stone. :return: True if the given position is empty, False otherwise. """ q, r = position return self.board_2d[r, q] == 0 def place_stone(self, position, colour): """Place a stone on the board. :param position: A tuple representing the (q, r) coord to place the stone. :param colour: The colour of the stone to be placed (1, 2, 3, or 4). """ q, r = position # Check the position is valid and empty assert self.is_valid_space(position) assert self.board_2d[r, q] == 0 self.board_2d[r, q] = colour def remove_stone(self, position): """Remove a stone from the board. :param position: A tuple representing the (q, r) coord to place the stone. """ q, r = position # Check that there is a stone at the given position assert not self.is_empty_space(position) self.board_2d[r, q] = 0 def get_legal_moves(self, player): """Returns all the legal moves for the given player. Each turn, the player can place up to two stones on any empty spaces on the board. However, if the player places two stones they must be different colors. :param player: 0 or 1 to denote the player in question. :return: the list of all legal moves for the given player. """ colour1, colour2 = self.colours[player] empty_spaces = self.get_empty_spaces() moves = [] # Add all possible one stone moves of the player's 1st colour moves += [((q, r, colour1), ()) for (q, r) in empty_spaces] # Add all possible one stone moves of the player's 2nd colour moves += [((q, r, colour2), ()) for (q, r) in empty_spaces] # Generate all possible two stone moves moves += [((m1[0], m1[1], colour1), (m2[0], m2[1], colour2)) for (m1, m2) in permutations(empty_spaces, r=2)] return moves def has_legal_moves(self): """Return True or False depending on whether there are any legal moves remaining. There are legal moves remaining if there are empty spaces on the board. :return: True if there are legal moves, False otherwise. """ # Check each index (q, r) to see if it is empty. for r in range(self.board_2d.shape[0]): for q in range(self.board_2d.shape[1]): if self.is_valid_space((q, r)) and self.board_2d[r][q] == 0: # (q, r) is a valid space and is empty return True def is_legal_move(self, move): """Check to see if the given move is legal. :param move: the move to be performed. A tuple of the form ((q coord, r coord, colour), (q coord, r coord, colour)) or ((q coord, r coord, colour), ()). """ if move[1]: # The move consists of two placements diff_colour = move[0][2] != move[1][2] # The space for the first stone is empty position1 = (move[0][0], move[0][1]) space1_empty = self.is_empty_space(position1) # The space for the second stone is empty position2 = (move[1][0], move[1][1]) space2_empty = self.is_empty_space(position2) return diff_colour and space1_empty and space2_empty else: position = (move[0][0], move[0][1]) return self.is_empty_space(position) def is_win(self, player): """A player wins if they reach the target number of captures. :param player: 0 or 1 to denote the player in question. :return: True if the given player has won the game, False otherwise. """ return self.captures[player] >= self.score_target def execute_move(self, move, player): """Perform the given move on the board. :param move: the move to be performed. A tuple of the form ((q coord, r coord, colour), (q coord, r coord, colour)) or ((q coord, r coord, colour), ()). :param player: the player performing the move (0 or 1). player is actually unused, but is required for interfacing with the Alpha Zero General library. """ # Place the stones for placement in move: if placement: # Must check this because some moves place only one stone q, r, colour = placement self.board_2d[r, q] = colour # Identify blooms blooms = [] for r in range(self.board_2d.shape[1]): for q in range(self.board_2d.shape[0]): if self.is_valid_space((q, r)) and self.board_2d[r, q] > 0: # (q, r) is a valid, non-empty space if not any(((q, r) in bloom for bloom in blooms)): # If the stone is not a member of a currently known bloom colour = self.board_2d[r, q] bloom = self.find_bloom_members({(q, r)}, colour, (q, r)) blooms.append(bloom) # Remove any fenced blooms (and increment the # of captured stones) fenced_blooms = [] for bloom in blooms: if self.is_fenced(bloom): bloom = list(bloom) fenced_blooms.append(bloom) # Update captures bloom_colour = self.board_2d[bloom[0][1], bloom[0][0]] if bloom_colour in self.colours[0]: # Bloom belongs to Player 1, so increment Player 2's captures self.captures[1] += len(bloom) else: # Bloom belongs to Player 2, so increment Player 1's captures self.captures[0] += len(bloom) # Remove stones from the board for bloom in fenced_blooms: for position in bloom: self.remove_stone(position) def is_fenced(self, bloom): """Check to see if the given bloom is fenced. :param bloom: A list of the positions that make up the bloom. :return: True if the bloom is fenced, False otherwise. """ for position in bloom: for q, r in self.get_neighbours(position): if self.board_2d[r, q] == 0: # A neighbouring position is empty return False return True def get_neighbours(self, position): """Return a list of the neighbouring positions to the given position. :param position: A tuple representing the (q, r) coord to place the stone. :return: A list of the neighbouring positions. """ q, r = position axial_directions = [(1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1)] neighbours = [] for dq, dr in axial_directions: neighbour = (q + dq, r + dr) if self.is_valid_space(neighbour): neighbours.append(neighbour) return neighbours def find_bloom_members(self, bloom, colour, position): """A recursive function for finding all stones that belong to the same bloom as te stone at the given position. :param bloom: A set of all stones in the bloom (on the first call this is empty). :param colour: The colour of the bloom. :param position: The position to start the search for other bloom members from. :return: The set of all positions with a stone in the bloom. """ neighbours = self.get_neighbours(position) neighbours = {n for n in neighbours if self.board_2d[n[1], n[0]] == colour and n not in bloom} if not neighbours: return bloom else: bloom |= neighbours for neighbour in neighbours: bloom |= self.find_bloom_members(bloom, colour, neighbour) return bloom @staticmethod def axial_to_pixel(q, r): """Convert axial coordinates to pixel (i.e. cartesian coordinates). :param q: the q coordinate. :param r: the r coordinate :return: a tuple containing the corresponding (x, y) pixel coordinates. """ x = np.sqrt(3) * q + np.sqrt(3) / 2 * r y = 3 / 2 * r return x, y @staticmethod def axial_to_cube(q, r): """Convert axial coordinates to cube coordinates. :param q: the q coordinate. :param r: the r coordinate :return: a tuple containing the corresponding (x, y, z) cube coordinates. """ x = q z = r y = -x - z return x, y, z @staticmethod def cube_to_axial(x, y, z): """Convert cube coordinates to axial coordinates. :param x: the x component of the cube coordinate. :param y: the y component of the cube coordinate. :param z: the z component of the cube coordinate. :return: a tuple containing the corresponding (q, r) axial coordinates. """ q = x r = z return q, r def visualise(self, show_coords=False, title="", filename=""): """Visualise the state of the board using matplotlib. :param show_coords: whether or not to annotate each space with its axial coordinates. :param title: the title of the plot. :param filename: the filename to save the visualisation to. """ fig, ax = plt.subplots(1, figsize=(5, 5)) ax.set_aspect('equal') for q in range(0, self.board_2d.shape[-1]): for r in range(0, self.board_2d.shape[-1]): if self.is_valid_space((q, r)): x, y = self.axial_to_pixel(q, r) colour = self.board_2d[r, q] face_colour = f'C{int(colour)}' if colour else 'w' hexagon = RegularPolygon((x, y), numVertices=6, radius=1.75 * np.sqrt(1 / 3), alpha=0.2, edgecolor='k', facecolor=face_colour, label='Player 1' if 0 < colour <= 2 else 'Player 2') ax.add_patch(hexagon) if show_coords: ax.annotate(text=f'({q}, {r})', xy=(x, y), ha='center', va='center') legend_elements = [Patch(facecolor='C1', edgecolor='w', alpha=0.2, label='Player 1'), Patch(facecolor='C2', edgecolor='w', alpha=0.2, label='Player 1'), Patch(facecolor='C3', edgecolor='w', alpha=0.2, label='Player 2'), Patch(facecolor='C4', edgecolor='w', alpha=0.2, label='Player 2')] plt.xticks([]) plt.yticks([]) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(False) plt.title(title) plt.legend(handles=legend_elements, handlelength=1, handleheight=1, ncol=4, loc='lower center', borderaxespad=-0.75, frameon=False) plt.gca().invert_yaxis() plt.autoscale(enable=True) if filename: plt.savefig(filename) plt.show()
9c605be132b004aa7a411df28303f2094b3b0004
hyunjun/practice
/Problems/hacker_rank/Algorithm/Strings/20150313_Palindrome_Index/solution2.py
424
3.921875
4
def is_palindrome(s): l, r = 0, len(s) - 1 while l < r: if s[l] != s[r]: return False l += 1 r -= 1 return True def palindrome_index(s): if is_palindrome(s): return -1 str_len = len(s) for i in range(str_len): if is_palindrome(s[:i] + s[i + 1:]): return i return 0 if __name__ == '__main__': n = int(raw_input()) for i in range(n): print palindrome_index(raw_input())
c22bfdfc4f43b84b922cbd1f4e930578c4d9fbf5
yoshimo8/100knock_project
/0-10project/project4.py
471
3.875
4
def word_sort(words): word_legend = {} numbers = [1, 5, 6, 7, 8, 9, 15, 16, 19] word_list = words.split() for word,i in zip(word_list,range(len(word_list))): if i in numbers: word_legend[word[1]] = i else: word_legend[word[0:2]] = i return(word_legend) words = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." print(word_sort(words))
66ba94e2d190f8560945cfd177e40d15aef886b2
jxy147258/qianfeng_python
/qianfeng_400/多任务/线程/8,凑够一定数量才能一起执行.py
575
3.671875
4
''' bar = threading.Barrier(2) 凑够2个数量之后才能运行bar.wait()之后的语句,凑不够就一直等 ''' import threading,time bar = threading.Barrier(2) def run(): print("%s---开始"%(threading.current_thread().name)) time.sleep(1) bar.wait() # 根据开头的说明,一共5个线程,凑够两个才能运行以下语句,所以一定会有一个线程因为凑不够而阻塞 print("%s---结束"%(threading.current_thread().name)) if __name__ == '__main__': for i in range(5): threading.Thread(target=run).start()
94bc21cf75c755167018b8a07258941b7c96e1e3
DouglasKosvoski/DFA-Generator
/main.py
1,305
3.859375
4
from sys import argv, exit from Automata import * from Csv import * """ Author: Douglas Kosvoski Email: douglas.contactpro@gmail.com Construction of an application to construct, determinate and minify (eliminate dead and unreachable grammar rules) of finite automata. This program executes the token load (reserved words, operators, special symbols, etc...) and Regular Grammars (RG) from a given text file. Input: file with the token and/or grammar relations from a hypothetical language. Output: deterministic finite automaton (DFA), free from dead and unreacheable states into a CSV file table representation. """ def verify_args(): """ Check number of arguments passed """ if (len(argv) != 2): print("""Unexpected number of arguments: One file as input to the program is required Try: `python3 main.py <input.in>`""") exit() def main(): """ Main program function, responsible for calling all other methods and constructors """ verify_args() # name of the file with the GR and tokens filename = str(argv[1]) automata = Automata(filename, debug=True) csv_filename = "output.csv" csv = Csv(csv_filename, automata.table) if __name__ == "__main__": """ blocks other script from calling this main.py file only this file can call itself """ main()
3584ac548af8a35eaf432af7024a3c3172047374
SafonovMikhail/python_000577
/001132StepikITclassPy/Stepik001132ITclassPyсh05p03st01THEORY01_20210216.py
840
4.09375
4
string = "1501" print(string.isdigit()) #True string = "school" print(string.isdigit()) #False string = "sch1501" print(string.isdigit()) #False string = "15.01" print(string.isdigit()) #False string = "-1501" print(string.isdigit()) #False # использование функции def is_digit(string): if string.isdigit(): return True elif string[0] == '-' and string[1:].isdigit(): # проверка на "отрицательность" return True else: try: float(string) return True except ValueError: return False print(is_digit('school')) #False print(is_digit('-1501')) #True print(is_digit('-15.01')) #True print(is_digit('306')) #True print(is_digit('0.05')) #True print(is_digit('15.01abc')) #False print(is_digit('a.05')) #False
134901fe69a7e3ed09fdac7f60116235706fd3d7
sharifh530/Learn-Python
/Beginner/Data types/5.escape_sequence.py
284
4.25
4
# whatever comes after "\" it will be a string weather = "Its a \"kind of sunny\" weather " print(weather) # whatever comes after "\t" it create a tab space and "\n" creates a new line weather1 = "\t Its a \"kind of sunny\" weather \n hope you have a good day" print(weather1)
0ceaeaf9d5d7edcdb51804a15d0b1e629c5ef7e7
luxcem/advent-2019
/src/utils.py
1,228
3.5
4
from math import sqrt def fid(x): return x def Input(filename, split=str.split, mapt=int): with open(filename) as fo: if split: source = split(fo.read()) else: source = fo.read() if mapt: return list(map(mapt, source)) else: return source def split(char): return lambda x: x.split(char) class Point: def __init__(self, x, y): self.x = x self.y = y self.t = (x, y) self.m = abs(x) + abs(y) def __add__(self, c): return Point(self.x + c.x, self.y + c.y) def __mul__(self, c): return self.x * c.x + self.y * c.y def length_sq(self): return self.x * self.x + self.y * self.y def norm(self): # normalize vector norm = sqrt(self.x * self.x + self.y * self.y) return Point(self.x / norm, self.y / norm) def __sub__(self, c): return Point(self.x - c.x, self.y - c.y) def __eq__(self, c): return self.x == c.x and self.y == c.y def __iter__(self): return self.t.__iter__() def __repr__(self): return "Point" + self.t.__repr__() def __hash__(self): return hash(self.t)
7a19110181b28d387cfc3737e6bbf1d6906686c9
prashant133/Labwork
/question4.py
534
4.3125
4
''' 4. Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock? The program should print two numbers: the number of hours (between 0 and 23) and the number of minutes (between 0 and 59). For example, if N = 150, then 150 minutes have passed since midnight - i.e. now is 2:30 am. So, the program should print 2 30. ''' N=int(input('enter the time ')) hours=N//60 minutes=N%60 print(f'The time passed since the midnight is {hours} : {minutes} ')
d3341fba3d94aac16e23ecb3abba35773a33f963
lowellbander/girlswhocode
/python/mad_libs.py
1,255
3.734375
4
''' Mad Libs adapted from the Shel Silverstein poem "Magic" from "Where the Sidewalk Ends" Original Poem Sandra’s seen a leprechaun, Eddie touched a troll, Laurie danced with witches once, Charlie found some goblins’ gold. Donald heard a mermaid sing, Susy spied an elf, But all the magic I have known I’ve had to make myself. ''' name_1 = input("Give me a person's name: ") magic_creature1 = input("Give the name of a magic creature: ") line_1 = name_1 + " seen a " + magic_creature1 name_2 = input("Give me a another person's name: ") magic_creature2 = input("Give the name of another magic creature: ") line_2 = name_2 + " touched a " + magic_creature2 physical_activity = input("Give me a physical activity: ") line_3 = "Laurie " + physical_activity + " with witches once" precious_item = input("Give me precious item: ") line_4 = "Charlie found some globin's " + precious_item verb = input("Give me a verb: ") line_5 = "Donald heard a mermaid " + verb quiet_activity = input("Give me a quiet activity: ") line_6 = "Susy " + quiet_activity + " an elf" last_lines = '''But all the magic I've known I've had to make myself ''' print(line_1) print(line_2) print(line_3) print(line_4) print(line_5) print(line_6) print(last_lines)
80d00909fda338ba2df63033f504c29563b95a2a
Nhalzainal/Tugas5
/Praktikum3latihan1.py
200
3.609375
4
print("Tampilkan n bilangan acak yang lebih kecil dari 0.5") jumblah = int(input("Masukan jumblah n: ")) import random for i in range(jumblah): print("Data ke",i+1 ,"-",(random.uniform(0.1,0.5)))
daf5115bcd51b72a54a3996e4aa40d521aafa524
GMwang550146647/network
/0.leetcode/99.有趣问题/acm/fence repair using heap.py
1,310
3.515625
4
#-*- coding:utf-8 -*- import numpy as np import pandas as pd import sklearn from pandas import DataFrame, Series import matplotlib.pyplot as plt class heap(object): def __init__(self): self.arr=np.zeros(20) self.size=0 def push(self,value): position=self.size self.size+=1 while(position>0): parent=(position-1)/2 if self.arr[parent]<=value: break self.arr[position]=self.arr[parent] position=parent self.arr[position]=value def pop(self): min=self.arr[0] x=self.arr[self.size-1] self.size-=1 p=0 while(p*2+1<self.size): left=p*2+1 right=p*2+2 if self.arr[left]>self.arr[right] and right<=self.size: left,right=right,left if self.arr[left]>=x: break self.arr[p]=self.arr[left] p=left self.arr[p]=x return min def main(): heap1=heap() total=0 arr=[3,4,5,1,2] for i in arr: heap1.push(i) while(heap1.size>1): min1=heap1.pop() min2=heap1.pop() tempt=min1+min2 total+=tempt heap1.push(tempt) print total
ba8ac2ed813820055e71719ae071205def7a94a7
pranav-kirsur/megathon2019
/discourse_connector.py
595
3.609375
4
def discourse_connector(sentence): connectors = ['because of', 'despite the fact that', 'in spite of', 'however', 'nevertheless', 'despite', 'in addition to', 'although', 'since', 'therefore', 'due to', 'as a result of', 'and', 'but', 'consequently', 'in addition', 'additionally', 'furthermore', 'moreover', 'along with', 'as well as', 'because'] count = 0 for connector in connectors: if connector in sentence: count+=1 sentence = sentence.replace(connector + " ", "") # print(sentence) return count/len(sentence.split())
dfacb834de3cdbdcc1082248a4dae2096841985b
StevenLdh/PythonActualPractice
/Excption.py
2,273
4
4
#!/usr/bin/env python # -*- coding:utf8 -*- ''' # 捕获异常处理 num1 = input("please input a num1:") num2 = input("please input a num1:") try: print(float(num1)/float(num2)) except ZeroDivisionError: print("error") finally: print("over") assert (float(num2) != 0),'Error!' print(float(num1)/float(num2)) ''' import requests from urllib.parse import urlencode import json def get_page(): params = { '___method': 'cc.erp.bll.report.reportmanager.getdatalist', 'pagetype': 'erp', 'from': 'allinoneclient', 'platform': 'pc', 's': '63c8be8fa3f3b42e', 'tok': '346f6f14de5543ce8826af3a4d4691a0' } param = { "reportparam": { "orders": "", "parid": 0, "pagetype": "erp", "displaytype": "tree", "pagerow": 19, "pagenumber": 0 }, "conditionparam": { "sid": "", "sfullname": "", "gfullname": "", "dfullname1": "", "did1": "", "showtree": "false", "showqtytype": "-1", "isexchange": "-1", "showstop": "-1", "shownotused": "false", "brandid": "", "keywords": "", "showstopstatus": "0", "deal1name": "", "deal2name": "", "brandname": "", "showcansaleqtytype": "-1", "showrealqtyqtytype": "-1", "pagetype": "erp", "pageid": "stock_allstatus", "usedeal1": 0, "usedeal2": 0, "usedeal3": 0, "dealsfullname": "", "deal1id": "", "deal2id": "" } } data = { '__postdata': json.dumps(param) } headers = {'Content-Type': 'application/json'} url = 'http://192.168.4.108:93/api.cc?' + urlencode(params) try: response = requests.post(url, data=data) if response.status_code == 200: return response.json() except requests.ConnectionError: return None if __name__ == '__main__': data = get_page() for item in data['data']['datasource']: print(item)
4d2fea298fe6157fe96ff5e0621071c7345bc736
zois-tasoulas/algoExpert
/medium/numberOfWaysToMakeChange.py
503
3.9375
4
def number_of_ways_to_make_change(n, denominations): ways_per_number = dict() ways_per_number[0] = 1 for ii in range(1, n + 1): ways_per_number[ii] = 0 for element in denominations: for ii in range(element, n + 1): ways_per_number[ii] += ways_per_number[ii - element] return ways_per_number[n] def main(): n = 11 denominations = [1, 25, 5, 10] print(number_of_ways_to_make_change(n, denominations)) if __name__ == "__main__": main()
e1baf2d2b8aacdfe71cf25c979d15b284ac9a0b1
myth002/CP1404_Practical
/Prac5_2.py
672
4.1875
4
#Pgm to output color codes based on keys using dictionaries COLOR_NAME={"aliceblue": "#f0f8ff","antiquewhite": "#faebd7","beige": "#f5f5dc","black": "#000000","coral": "#ff7f50","darkgreen": "#006400","darkviolet": "#9400d3","greenyellow": "#adff2f","lavender": "#e6e6fa","magenta": "#ff00ff"} user_choice = str(input("Enter color name: ")).lower() while user_choice != "": if user_choice in COLOR_NAME: print(user_choice, "is", COLOR_NAME[user_choice]) else: print("Invalid color name") user_choice = input("Enter color name: ").lower() for user_choice in COLOR_NAME: print("{:4} is {:20}".format(user_choice, COLOR_NAME[user_choice]))
026333579c68799c18c795b8bd1996b1fa890ff4
rebecabramos/Course_Exercises
/Week 4/integer_division.py
477
4.3125
4
# Program that prompts the user to enter two integers. # Then, display the result of dividing the first number by the second number, # using integer division so that the answer is an integer quotient, and a remainder value1 = int(input('Enter an integer >')) value2 = int(input('Enter an integer >')) division = int(value1/value2) restOfDivision = value1%value2 print(str(value1) + ' divided by ' + str(value2) + ' is ' + str(division) + ' remainder ' + str(restOfDivision))
81092b495c775235a8d97230c2a28f65e58d3138
TimothySjiang/leetcodepy
/Solution_429.py
562
3.59375
4
""" # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] queue = [root] ans = [] while queue: res = [] for i in range(len(queue)): p = queue.pop(0) res.append(p.val) for child in p.children: queue.append(child) ans.append(res) return ans
998f29d674561ff168519a8fe67afe5e6cb82015
ptamayo4/DojoAssignments
/Python/pythonFun/stars.py
301
3.71875
4
def draw_stars(arr): for i in range(len(arr)): if type(arr[i]) is int: print "*" * arr[i] elif type(arr[i]) is str: temp = arr[i] print temp[0] * len(temp) x = [4,6,1,3,5,7,25] y = ["Patrick",2,10,"Richard", "Hello"] draw_stars(x) draw_stars(y)
0606c869a817c216bb97f500b9ce2314895124c2
angiegonzalez596/Proyecto1
/entrada de datos2.py
306
3.859375
4
nombre = input("Ingrese su Nombre") print("Hola " + nombre + ", Vamos a realizar una suma," ) num_uno = int(input("Por favor ingrese el primer valor: ")) num_dos = int(input("Por favor ingrese el segunto valor: ")) resultado = num_uno + num_dos print(nombre + " El resultado de la suma es: ", resultado)
59c886e2b0a8350f3e63eedf351cc3c4e7d824b1
felit/python-expirement
/decorator.py
556
3.859375
4
#-*- coding:utf8 -*- def foo(): print("foo") foo print foo() foo = lambda x: x + 1 print foo(2) def w1(func=None,hello="world"): print("添加装饰器:%s%s"%(func,hello)) def inner(*args,**kwargs): print "from w1" return func(*args,**kwargs) return inner @w1 def f1(): print("f1") """ f1 = def inner(*args,**kwargs): print "from w1" return _f1(*args,**kwargs) """ # @w1(hello="hello") def f2(): print("f2") def f3(): print("f3") def f4(): print("f4") print f1 f1() f2() f3() f4()
423114e77ee15c36fbd36a206fb431c07a6eeea5
pierrce/euler
/one.py
237
3.75
4
#!/usr/bin/python print('Calculating...') myList=[] x=0 for i in range(1, 1000): if(i%3)==0 or (i%5)==0: print('Appended...') myList.append(i) myList = map(int, myList) x = sum(myList) print(x)
11f8f6af5140f5b8c7042ccef577b3f43987045f
dudulacerdadl/Curso-Python
/Mundo2/Exercícios/ex062.py
499
3.9375
4
start = int(input('Digite o primeiro número de uma PA: ')) reason = int(input('Digite a razão de uma PA: ')) decimal = start + (10 - 1) * reason counter = 0 counter2 = 0 terms = 10 print('') while terms != 0: while counter < terms: print(start, end=' -> ') start += reason counter += 1 counter2 += 1 counter = 0 terms = int(input('Deseja escrever mais quantos termos: ')) print('A progressão foi finalizada com {} termos mostrados.'.format(counter2))
7fd73df6ab94d6443e78636bad0c7e1af2ef124a
RrennM/python_bc_mileage_converter
/mileage_converter.py
317
4.0625
4
print("How many kilometers did you cycle today?") kms = input() mile = float(kms) * 0.621371 # kms = str(kms) # mile = str(mile) # print("Okay, you said " + kms + " kilometers. That's about " + mile + " miles!") round_mile = round(mile, 2) print(f"Okay, you said {kms} kilometers. That's about {round_mile} miles!")
61e1054c9b4aff6e3c955e7b40963351f5a98cdd
AlterFritz88/pybits
/bite177.py
2,054
3.796875
4
import pandas as pd import numpy as np movie_excel_file = "https://bit.ly/2BVUyrO" def explode(df, lst_cols, fill_value='', preserve_index=False): """Helper found on SO to split pipe (|) separted genres into multiple rows so it becomes easier to group the data - https://stackoverflow.com/a/40449726 """ if(lst_cols is not None and len(lst_cols) > 0 and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))): lst_cols = [lst_cols] idx_cols = df.columns.difference(lst_cols) lens = df[lst_cols[0]].str.len() idx = np.repeat(df.index.values, lens) res = (pd.DataFrame({ col:np.repeat(df[col].values, lens) for col in idx_cols}, index=idx) .assign(**{col:np.concatenate(df.loc[lens>0, col].values) for col in lst_cols})) if (lens == 0).any(): res = (res.append(df.loc[lens==0, idx_cols], sort=False) .fillna(fill_value)) res = res.sort_index() if not preserve_index: res = res.reset_index(drop=True) return res def group_by_genre(data=movie_excel_file): """Takes movies data excel file (https://bit.ly/2BXra4w) and loads it into a DataFrame (df). Explode genre1|genre2|genre3 into separte rows using the provided "explode" function we found here: https://bit.ly/2Udfkdt Filters out '(no genres listed)' and groups the df by genre counting the movies in each genre. Return the new df of shape (rows, cols) = (19, 1) sorted by movie count descending (example output: https://bit.ly/2ILODva) """ data = pd.read_excel(data,skiprows=7) data = data[['genres', 'movie']] data.genres = data.genres.str.split('|') data = explode(data, ['genres']) data = data[data['genres'] != '(no genres listed)'] data = data.groupby(['genres']).agg(['count']) return data['movie'].sort_values(['count'], ascending=False).rename(columns={'count': 'movie'}) print(group_by_genre())
1a9e0d0476c1d56ecdae3241ecf901e87d447aec
S-PaveI/tutorial
/MyCoin.py
658
3.96875
4
# Программа для имитации подбрасывания монеты import random class Coin: def __init__(self): self.__sideup = 'Орел' def toss(self): if random.randint(0, 1) == '0': self.__sideup = 'Орел' else: self.__sideup = 'Решка' def get_sideup(self): return self.__sideup def main(): my_coin = Coin() print('Показать сторону монеты', my_coin.get_sideup()) print('Подбрасываю монету...') my_coin.toss() print('Показать сторону монеты', my_coin.get_sideup()) main()
b86f1080f3455d89b905d2ce81c402d0b776b8bb
NEO2756/HackerEarth
/python/max_heap.py
1,467
3.953125
4
from sys import stdin, stdout tree = [0, 10, 40, 15, 50, 100, 30, 10] heap = [] def insert(new): heap.append(new) idx = len(heap) - 1 while heap[idx//2] != -1: if heap[idx//2] < heap[idx]: heap[idx//2], heap[idx] = heap[idx], heap[idx//2] idx = idx//2 continue else: break def heapify(idx): left = 2 * idx right = 2 * idx + 1 heapSize = len(heap) - 1 if left <= heapSize and heap[left] > heap[idx]: heap[left], heap[idx] = heap[idx], heap[left] return heapify(left) if right <= heapSize and heap[right] > heap[idx]: heap[right], heap[idx] = heap[idx], heap[right] return heapify(right) def delete(targetnodeIdx): if targetnodeIdx == len(heap) - 1: heap.pop() return heap[targetnodeIdx] = heap.pop() heapify(targetnodeIdx) def ExtractMax(): e = heap[1] heap[1] = heap[len(heap) - 1] heapify(1) return e if __name__ == "__main__": heap.append(-1) # parent of root is -1 for v in range(1, len(tree)): insert(tree[v]) print('Heap Formed') print(heap) print('Delete node at index 3 in heap') delete(3) print('After deletion') print(heap) print('Extract Max') print(ExtractMax()) print('This is the result') print(heap) print('Extract Max Again') print(ExtractMax()) print('This is the result again') print(heap)