text
stringlengths
37
1.41M
#This program used to remove redundant words in a sentence. s = input("Please input you text: ") w = s.split(" ") print (" ".join(sorted(list(set(w)))))
import BinaryTree root = BinaryTree.BinaryTree('root') a = root.insertLeftChild('A') b = root.insertRightChild('B') c = a.insertLeftChild('3') d = c.insertRightChild('D') e = b.insertRightChild('E') f = e.insertLeftChild('F') root.inOrder() a.preOrder() print('\n') root.preOrder()
""" title: data_structures author: Zyden Walcher date: 7/19/18 data_structures """ import random def name_generator(first_list, last_list ): """generates random name :param first_list: the list of strings of first names :param last_list: the list of strings of last names if __name__ == '__main__': first_list = ["Joe", "Moe", "Bo", "LoLo", "Zo"] last_list = ["Smith", "Rodriguez", "Hernandez", "Doe", "Phillips"] print(name_generator(first_list, last_list)
import numpy as np class Conv3x3: # A Convolution layer using 3x3 filters. def __init__(self, num_filters): self.num_filters = num_filters # filters is a 3d array with dimensions (num_filters, 3, 3) # We divide by 9 to reduce the variance of our initial values self.filters = np.random.randn(num_filters, 3, 3)/9 def iterate_regions(self, image): ''' Generates all possible 3x3 image regions using valid padding. - image is a 2d numpy array ''' h, w = image.shape for i in range(h - 2): for j in range(w - 2): im_region = image[i: (i+3), j:(j+3)] yield im_region, i, j def forward(self, input): ''' Performs a forward pass of the conv layer using the given input. Returns a 3d numpy array with dimensions (h, w, num_filters). - input is a 2d numpy array ''' h, w = input.shape output = np.zeros((h - 2, w - 2, self.num_filters)) for im_region, i, j in self.iterate_regions(input): output[i, j] = np.sum(im_region * self.filters, axis=(1, 2)) return output
#!/usr/bin/env python """ parse_species_data.py - script to display number of unique genera for (a) given habitat(s) Usage: parse_species_data.py [-m] [-v] <data_file> One can run parse_species_data.py -h for a list of command-line options. Supplied data should be in the format of: [habitat_number]: [species,...] e.g.: 12345: Homo sapiens sapiens, Homo habilis, Homo heidelbergensis 67891: Homo neanderthalensis, Mosasaurus hofmanni Limited coverage tests in the bottom of the file. Tested using Nose, python v2.7.6. """ import sys, re, os, argparse HEADER_COLOR = "\033[32m" ERROR_COLOR = "\033[31m" WARNING_COLOR = "\033[93m" END_COLOR = "\033[0m" RECORD_REGEX = re.compile( r"""^ (?P<habitat>[0-9]{5,}) (?:\s?\:+\s?) (?P<species>(?:(\w+\s\w+)(?:\s?\,?\s?))+) $""", re.VERBOSE ) SPECIES_REGEX = re.compile( r""" (?P<species> (?P<genus>\w+) (\s\w+)+) """, re.VERBOSE ) """ Render a non-fatal warning """ def warn(message): fatal(message, fatal=False) def fatal(message, fatal=True): """ Raises a fatal exception (default) or throws a warning. """ if fatal: raise RuntimeError("%sError parsing data: %s%s" % (ERROR_COLOR, message, END_COLOR)) sys.stderr.write("%s*** Warning: %s ***%s\n" % (WARNING_COLOR, message, END_COLOR)) def _sanitise_record(record): CONSECUTIVE_SPACES = re.compile(r"\s{2,}") record = record.strip() if not record: return None ### normalise possible multiple spaces record = re.sub(CONSECUTIVE_SPACES, " ", record) return record def extract_data_from_record(record): """ Attempt to extract data from a given record using two regular expressions. The first regex checks for a valid data record and extracts the habitat and species list. The second regex extracts the full name and genus for each species. Any non-parseable record throws a warning. Returns: { "habitat" : [int], # 12345 "species" : [set], # Homo habilis, Mosasaurus hofmanni "genera" : [set], # Homo, Mosasaurus } """ record = _sanitise_record(record) if record is None: return record match = RECORD_REGEX.match(record) if match is None: warn("Invalid data record: '%s' " \ "could not parse, skipping." % record) return match data_dict = match.groupdict() habitat = int(data_dict["habitat"]) species = data_dict["species"] genus_set = set() species_set = set() matches = re.finditer(SPECIES_REGEX, species) for match in matches: data_dict = match.groupdict() genus_set.add(data_dict["genus"]) species_set.add(data_dict["species"]) return { "habitat" : habitat, "species" : species_set, "genera" : genus_set, } def parse_file(file_name, merge): """ Initialise a generator that yields a processed record for each line of data in the file. Depending on whether we attempt to merge duplicate habitats, either the generator itself is returned, or a final processed dictionary of habitats, of the format: { [habitat] : { # 12345 "habitat" : [int] # 12345 - denormalised for rendering later "genera" : [set], # Homo, Mosasaurus "species" : [set], # Homo habilis, Mosasaurus hofmanni } ... } """ ### use a generator to save memory in case of huge data files ### this only works when we are not merging duplicate habitats ### since that requires processing the entire file def record_generator(file_name): try: with open(file_name) as file_handler: for line in file_handler: extracted = extract_data_from_record(line) if not extracted: continue yield extracted except IOError as file_error: fatal(file_error.strerror) records = record_generator(file_name) if not merge: return records habitats = {} ### merge distinct genera and species by habitat for record in records: if record["habitat"] in habitats: habitat_data = habitats[ record["habitat"] ] for key in ["genera", "species"]: habitat_data[key].update(record[key]) else: habitats[ record["habitat"] ] = { "habitat" : record["habitat"], "genera" : record["genera"], "species" : record["species"], } return habitats def render_parsing_results(habitat_data, verbose, merge): """ Pretty-print the relevant parsing results. """ def render_header(): print "%s%-8s %s%s" % (HEADER_COLOR, "HABITAT", "GENERA", END_COLOR) def render_record(r): if not verbose: print "%-8d %d" % (r["habitat"], len(r["genera"])) return print "%-8d %-6d (%s) - (%s)" % \ (r["habitat"], len(r["genera"]), ', '.join(sorted(r["genera"])), ', '.join(sorted(r["species"]))) ### no merging, so this is a generator we can process if not merge: render_header() for record in habitat_data: render_record(record) ### process the pre-merged habitat dict ### this also allows us to sort by habitat and ### warn the user about possible flawed data beforehand else: if not habitat_data: fatal("No valid data found in file.") render_header() for habitat in sorted(habitat_data): render_record(habitat_data[habitat]) def main(): """ Parse command-line arguments, parse and render the results. """ parser = argparse.ArgumentParser( description = 'Display number of unique genera " \ for a list of habitats and species.') parser.add_argument('file_name', metavar = 'FILE', type = str, help = 'a file containing data to process' ) parser.add_argument('-v', dest = 'verbose', action = 'store_true', help = "append the list of genera and species for each habitat" ) parser.add_argument('-m', dest = 'merge', action = 'store_true', help = "merge multiple habitat occurrences " \ "(possibly memory intensive)" ) class ArgumentHolder(object): pass a = ArgumentHolder() parser.parse_args(namespace = a) render_parsing_results( parse_file(a.file_name, a.merge), a.verbose, a.merge ) if __name__ == "__main__": main() """ __TESTS__ """ import unittest, tempfile class MockNull(object): """ Mock std* replacement for output capturing. """ def __init__(self): self._capture = '' def write(self, data): self._capture += data class WarningCapturer(object): """ Simple context manager to suppress and capture stderr output. """ def __enter__(self): self.old_stderr = sys.stderr self.mocknull = MockNull() sys.stderr = self.mocknull def __exit__(self, type, value, traceback): sys.stderr = self.old_stderr class TestParser(unittest.TestCase): def setUp(self): try: self.temp_file = tempfile.NamedTemporaryFile() except Exception as e: raise Exception("Unable to create temp file: %s" % e) self.capture_warnings = WarningCapturer() def tearDown(self): # self.temp_file is closed automatically on GC pass def test_single_record(self): record = "12345: Homo sapiens, Homo habilis" actual = extract_data_from_record(record) expected = { "habitat" : 12345, "genera" : set(["Homo"]), "species" : set(["Homo sapiens", "Homo habilis"]), } self.assertEqual(actual, expected, "Single record extracts") def test_invalid_data_file(self): with self.assertRaises(RuntimeError) as context: self.temp_file.write("foo\nbar\naz\n") self.temp_file.flush() merge = True no_verbose = False with self.capture_warnings: result = parse_file(self.temp_file.name, merge) render_parsing_results(result, no_verbose, merge) self.assertEqual(result, {}, "Invalid file begets empty dict") self.assertRegexpMatches(context.exception.__str__(), r"No valid data found in file.") def test_merge_multi_record_file(self): test_records = \ """12345: Homo habilis, Homo sapiens, Homo erectus 45678: Baryonyx walkeri, Mosasaurus hofmanni 12345: Baryonyx walkeri, Homo sapiens""" self.temp_file.write(test_records) self.temp_file.flush() merge = True actual = parse_file(self.temp_file.name, merge) expected = { 12345 : { "habitat" : 12345, "genera" : set(["Homo", "Baryonyx"]), "species" : set(["Homo habilis", "Homo sapiens", "Homo erectus", "Baryonyx walkeri"]), }, 45678 : { "habitat" : 45678, "genera" : set(["Baryonyx", "Mosasaurus"]), "species" : set(["Baryonyx walkeri", "Mosasaurus hofmanni"]), } } self.assertEqual(actual, expected) def test_liberal_parser(self): data = [ { "record" : "12345678: Homo sapiens sapiens, Homo " \ "sapiens sapiens, Baryonyx walkeri", "expected" : { "habitat" : 12345678, "genera" : set(["Homo", "Baryonyx"]), "species" : set(["Homo sapiens sapiens", "Baryonyx walkeri"]) } }, { "record" : "12345 :::: Homo sapiens sapiens, Baryonyx " \ "walkeri", "expected" : { "habitat" : 12345, "genera" : set(["Homo", "Baryonyx"]), "species" : set(["Homo sapiens sapiens", "Baryonyx walkeri"]) } }, { "record" : "12345 : Homo sapiens sapiens , Baryonyx walkeri ", "expected" : { "habitat" : 12345, "genera" : set(["Homo", "Baryonyx"]), "species" : set(["Homo sapiens sapiens", "Baryonyx walkeri"]) } } ] for case in data: actual = extract_data_from_record(case["record"]) self.assertEqual(actual, case["expected"]) def test_broken_record(self): record = "abcde: Homo sapiens, Homo habilis" with self.capture_warnings: actual = extract_data_from_record(record) captured_warning = self.capture_warnings.mocknull._capture expected = None self.assertRegexpMatches(captured_warning, r"could not parse, skipping", "Broken record parsing throws warning") self.assertEqual(actual, expected, "Broken record results in None")
#!/usr/local/bin/python # Written by Duncan Forgan, 18th July 2012 # This code produces a Photon Wavelength/Frequency Calculator GUI # We use the standard Tkinter toolkit which comes with pretty much all Python distributions # We start by defining the GUI as a class (derived from the base class Frame), with methods # to create the elements inside the window, and methods to handle events from Tkinter import Frame, Button, Entry, Listbox,Text, END,SINGLE,W class photGUI(Frame): """The base class for the phot_calc GUI""" # This is the constructor for the GUI def __init__(self,master=None): # We begin by calling the base class's constructor first Frame.__init__(self,master) # We now have an empty window! # This command sets up a grid structure in the window self.grid() # This loop generates rows and columns in the grid for i in range(13): self.rowconfigure(i,minsize=10) for i in range(3): self.columnconfigure(i,minsize=30) # These are methods which appear below the constructor self.defineUnits() # this sets up the units I'll be using in the converter self.createWidgets() # this places the elements (or widgets) in the grid # This command "binds" the user's click to a method (varChoice) # This method will determine which variable the user wants (Distance, Mass, Time) self.inputlist.bind("<Button-1>",self.__varChoice) # This is a similar command for the selection of unit self.unitlist.bind("<Button-1>",self.__unitChoice) # Finally, this bind reads in whatever value is in the text box when the user hits return # and carries out the unit conversion self.inputfield.bind("<Return>",self.__calcConversion) # This function creates and defines the units def defineUnits(self): '''Method defines tuples that carry the various units stored by the converter''' self.speed = 2.997924580000019e10 self.h = 6.6260755e-27 # Wavelengths self.wavunits = ('nm','um', 'cm','m') self.wavvalues = (1.0e-7, 1.0e-4,1.0,1.0e2) self.frequnits = ('Hz','MHz','GHz','THz') self.freqvalues = (1.0, 1.0e6, 1.0e9, 1.0e12) self.energunits = ('eV','keV','MeV','GeV','erg') self.energvalues = (1.0,1.0e3,1.0e6,1.0e9,1.6e-12) # Keep the unit values in dictionaries, and use the above strings as keys self.wavdict = {} self.createUnitDict(self.wavdict,self.wavunits,self.wavvalues) # this method is shown below self.freqdict = {} self.createUnitDict(self.freqdict,self.frequnits,self.freqvalues) self.energdict = {} self.createUnitDict(self.energdict, self.energunits, self.energvalues) self.myunits = self.wavunits self.myvalues = self.wavvalues self.mydict = self.wavdict def createUnitDict(self,mydict,mykeys,myvalues): '''This method takes a set of units and values, and creates a dictionary to store them in''' for i in range(len(myvalues)): mydict[mykeys[i]] = myvalues[i] def createWidgets(self): '''This method creates all widgets and adds them to the GUI''' # Create Widgets in order of appearance # This is not necessary, but makes code easier to read # Start with text telling user what to do self.varlabel = Text(self,height=1, width=20) self.varlabel.insert(END,"Which Variable?") # Place widget on the Frame according to a grid self.varlabel.grid(row=0,column=0,sticky=W) # Second text label asking user which units are being used self.unitlabel = Text(self,height=1,width=20) self.unitlabel.insert(END,"Which Units?") self.unitlabel.grid(row=0,column=1,sticky=W) # Third text label asking user for numerical value self.numlabel = Text(self,height=1, width=20) self.numlabel.insert(END,"Enter Variable Values") self.numlabel.grid(row=0,column=2,sticky=W) # This creates a list of options for the user to select self.inputlist = Listbox(self, height=4, selectmode=SINGLE) # Tuple of choices we're going to put in this list self.paramlist = ('Frequency', 'Wavelength', 'Energy') # Add each item separately for item in self.paramlist: self.inputlist.insert(END,item) # Add it to the grid self.inputlist.grid(row=1, column=0,rowspan=4,sticky=W) # Add a unit list (several combinations of units allowed) self.unitlist = Listbox(self, height=4,selectmode=SINGLE) self.unitlist.grid(row=1,column=1,rowspan=4, sticky=W) # Number Entry Boxes (and Text Labels) self.inputlabel = Text(self,height=1,width=20) self.inputlabel.insert(END,"Waiting Selection") self.inputlabel.grid(row=1,column=2,sticky=W) self.inputfield = Entry(self) self.inputfield.grid(row=2,column=2,sticky=W) # Text Output Boxes self.wavoutput = Text(self, height=5, width=20) self.wavoutput.grid(row=7,column=0,rowspan=5,sticky=W) self.wavoutput.insert(END, "Wavelength: \n") self.freqoutput = Text(self, height=5, width=20) self.freqoutput.grid(row=7,column=1,rowspan=5,sticky=W) self.freqoutput.insert(END, "Frequency: \n") self.energoutput = Text(self, height=5, width=20) self.energoutput.grid(row=7,column=2,rowspan=5,sticky=W) self.energoutput.insert(END, "Energy: \n") # Create the Quit Button self.quitButton=Button(self,text='Quit',command=self.quit) self.quitButton.grid(row =13, column=0, sticky=W) # Event handler functions begin here # This handler defines the choice of units available to the user, # depending on selected variable def __varChoice(self, event): '''Handles the selection of variable: updates the list of units''' # Firstly, delete anything already in the units column self.unitlist.delete(first=0,last=len(self.myvalues)) num = 0 # Identify which option was clicked on try: num = self.inputlist.curselection()[0] self.varchoice = int(num) except: self.varchoice = 0 return # Get the string associated with this choice selection= self.inputlist.get(self.varchoice) print selection, " chosen" # Highlight current choice in red self.inputlist.itemconfig(self.varchoice, selectbackground='red') # If statement defines units being used if selection =='Wavelength': self.myunits = self.wavunits self.myvalues = self.wavvalues self.mydict = self.wavdict elif selection == 'Frequency': self.myunits = self.frequnits self.myvalues = self.freqvalues self.mydict = self.freqdict elif selection == 'Energy': self.myunits = self.energunits self.myvalues = self.energvalues self.mydict = self.energdict self.inputlabel.delete("1.0",index2=END) self.inputlabel.insert(END,selection) for i in range(len(self.myunits)): self.unitlist.insert(END,self.myunits[i]) def __unitChoice(self,event): '''Handles the selection of units''' num = 0 # Find which number is selected try: num = self.unitlist.curselection()[0] self.unitchoice = int(num) except: self.unitchoice = 0 return # Get the string (i.e. which unit is selected) selection= self.unitlist.get(self.unitchoice) print selection, " chosen" # Highlight current choice in red self.unitlist.itemconfig(self.unitchoice, selectbackground='red') # Handler takes current state of GUI, and calculates results def __calcConversion(self,event): '''This method takes the current state of all GUI variables, calculates one of four equations''' # Which variable has been selected for calculation? # This decides what equation to use a = self.inputfield.get() var = self.unitlist.get(self.unitchoice) a=float(a) freq = 0.0 wav = 0.0 energy = 0.0 if self.varchoice==0: freq = a freq = freq*self.mydict[var] wav = self.speed/freq energy = self.h*freq/self.energdict['erg'] elif self.varchoice==1: wav = a wav = wav*self.mydict[var] freq = self.speed/wav energy = self.speed*self.h/wav elif self.varchoice==2: energy = a energy=energy*self.energdict["erg"] freq = energy/self.h wav = self.speed*self.h/energy energy = energy*self.mydict[var]/self.energdict["erg"] # Remove all text in the output boxes self.wavoutput.delete("1.0",index2=END) self.freqoutput.delete("1.0",index2=END) self.energoutput.delete("1.0",index2=END) self.wavoutput.insert(END, "Wavelength: \n") self.freqoutput.insert(END, "Frequency: \n") self.energoutput.insert(END, "Energy: \n") # Calculate each conversion and output it to the GUI for i in range(len(self.wavvalues)): # As all units stored in cgs values, conversion is simple output = wav/self.wavvalues[i] # Express output in # Add to the output list self.wavoutput.insert(END,self.wavunits[i] + ": %.4e" % output+"\n") for i in range(len(self.freqvalues)): # As all units stored in cgs values, conversion is simple output = freq/self.freqvalues[i] # Add to the output list self.freqoutput.insert(END,self.frequnits[i] + ": %.4e" % output+"\n") for i in range(len(self.energvalues)): # As all units stored in cgs values, conversion is simple output = energy/self.energvalues[i] # Add to the output list self.energoutput.insert(END,self.energunits[i] + ": %.4e" % output+"\n") # End of methods and class definition # Main program begins here app = photGUI() # Call the exo class app.master.title("Photon Property Calculator") # Give it a title app.mainloop() # This command allows the GUI to run until a terminate command is issued (e.g. the user clicks "Quit")
import os import math def timedelta_to_seconds(delta): '''Convert a timedelta to seconds with the microseconds as fraction >>> from datetime import timedelta >>> '%d' % timedelta_to_seconds(timedelta(days=1)) '86400' >>> '%d' % timedelta_to_seconds(timedelta(seconds=1)) '1' >>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1)) '1.000001' >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1)) '0.000001' ''' # Only convert to float if needed if delta.microseconds: total = delta.microseconds * 1e-6 else: total = 0 total += delta.seconds total += delta.days * 60 * 60 * 24 return total def scale_1024(x, n_prefixes): '''Scale a number down to a suitable size, based on powers of 1024. Returns the scaled number and the power of 1024 used. Use to format numbers of bytes to KiB, MiB, etc. >>> scale_1024(310, 3) (310.0, 0) >>> scale_1024(2048, 3) (2.0, 1) ''' power = min(int(math.log(x, 2) / 10), n_prefixes - 1) scaled = float(x) / (2 ** (10 * power)) return scaled, power def get_terminal_size(): # pragma: no cover '''Get the current size of your terminal Multiple returns are not always a good idea, but in this case it greatly simplifies the code so I believe it's justified. It's not the prettiest function but that's never really possible with cross-platform code. Returns: width, height: Two integers containing width and height ''' try: # This works for Python 3, but not Pypy3. Probably the best method if # it's supported so let's always try import shutil w, h = shutil.get_terminal_size() if w and h: # The off by one is needed due to progressbars in some cases, for # safety we'll always substract it. return w - 1, h except: # pragma: no cover pass try: w = int(os.environ.get('COLUMNS')) h = int(os.environ.get('LINES')) if w and h: return w, h except: # pragma: no cover pass try: import blessings terminal = blessings.Terminal() w = terminal.width h = terminal.height if w and h: return w, h except: # pragma: no cover pass try: w, h = _get_terminal_size_linux() if w and h: return w, h except: # pragma: no cover pass try: # Windows detection doesn't always work, let's try anyhow w, h = _get_terminal_size_windows() if w and h: return w, h except: # pragma: no cover pass try: # needed for window's python in cygwin's xterm! w, h = _get_terminal_size_tput() if w and h: return w, h except: # pragma: no cover pass return 79, 24 def _get_terminal_size_windows(): # pragma: no cover res = None try: from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) except: return None if res: import struct (_, _, _, _, _, left, top, right, bottom, _, _) = \ struct.unpack("hhhhHhhhhhh", csbi.raw) w = right - left h = bottom - top return w, h else: return None def _get_terminal_size_tput(): # pragma: no cover # get terminal width src: http://stackoverflow.com/questions/263890/ try: import subprocess proc = subprocess.Popen( ['tput', 'cols'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate(input=None) w = int(output[0]) proc = subprocess.Popen( ['tput', 'lines'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate(input=None) h = int(output[0]) return w, h except: return None def _get_terminal_size_linux(): # pragma: no cover def ioctl_GWINSZ(fd): try: import fcntl import termios import struct size = struct.unpack( 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except: return None return size size = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not size: try: fd = os.open(os.ctermid(), os.O_RDONLY) size = ioctl_GWINSZ(fd) os.close(fd) except: pass if not size: try: size = os.environ['LINES'], os.environ['COLUMNS'] except: return None return int(size[1]), int(size[0])
""" Name: 12_flatten Author: Lio Hong Date: 20180726 Goal: Write a function to flatten a list. The list contains other lists, strings, or ints. For example, [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5] I.E. transfers all entries from nested lists to main list. Comments: Might have to use recursion for this. What's the base case then? A single list? Or an entry that is a list itself? Anyway, to insert the sublist entries we have list.insert(i,x) Might have to do some reverse-traversing to manage it though. Knowing this, the base case will be a list containing at least one sublist entry. """ aList = [88,[1,'a',['cat'],2],[[[3]],'dog'],4,5] ##OUTPUT = [88,1,'a','cat',2,3,'dog',4,5] def flatten(aList): ''' aList: a list Returns a copy of aList, which is a flattened version of aList ''' bList = aList for i in bList: print(i) if type(i) == int or type(i) == str: continue elif type(i) == list: for b in range(0,len(i)): bList.insert(bList.index(i),i[b]) #Assumes there are no duplicate sublists #Even if there were, only the leftmost would be removed. bList.remove(i) print(bList) return bList ## for j in aList: ## print(j) ## while type(j) == list: ## flatten(aList)
""" Name: letter_freq_counter Date: 20181008 Author: Lio Hong Purpose: Counts letter frequencies. Comments: I actually found code examples online but couldn't make sense of it. I can check my results against online databases at least, but I still have to code this to use on encrypted texts. There's a lot of patterns: - Single letter - 26 - Two-letter - 26^2 - Three-letter - 26^3 - Start of word - 26. > at start. Find symbol and take next char. - End of word - 26. < at end. Find symbol and take prev char - Followed by apostrophe - Potentially 26 but more like 6 (stdrlv) Find symbol and take next char. - Doubles - 26. Subset of two-letter techincally. The hints are actually not that suitable because of how short they are, so running a statistical analysis on them would be difficult because of the high likelihood of random error. Personally, it might be possible for me to find these letter frequencies myself. Once I have the function setup, it's just a matter of finding data to crunch. I could also search online for the figures, and make sure I get it from a reliable source. Regardless, I'll still have to crunch the numbers so as to handle encrypted texts. In the end though, I know there are other, more complex ciphers. The pendulum one, the reverse, the space-less. Very fitting entry into data analytics. """ import string import operator def get_passage(): """ Returns: A passage in plain text """ files = ['laudato-si1-6.txt','laudato-si.txt','1m.txt','1m2.txt','1m3.txt',\ 'bible2.txt'] print('Files available: ', files) num = int(input('Which file do you want to open? ')) f = open(files[num], "r") story = removeNonAscii(str(f.read())) f.close() return story def removeNonAscii(s): return "".join(i for i in s if ord(i)<128) def word_Lister(text): # Returns a list of words textSplit = text.split() textWords = [] numList = ['0','1','2','3','4','5','6','7','8,','9'] for word in textSplit: word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") word = word.strip('""') if word in numList: pass else: textWords.append(word) return textWords def wordFreq(text): # Returns a dict for word:freq textWords = word_Lister(text) textDict = {} for word in textWords: if word not in textDict: textDict[word] = 1 else: textDict[word] += 1 return textDict def letterFreq(text): # Counts frequency textWords = word_Lister(text) letterDict = {} for char in string.ascii_lowercase: letterDict[char] = 0 for word in textWords: for letter in word: if letter in letterDict: letterDict[letter] += 1 else: pass return letterDict def rankLF(text): # Really janky stuff. But I managed to make it functional. letterDict = letterFreq(text) letterTot = 0 ## letterDictRanked = sorted(letterDict.items(), key=operator.itemgetter(0),reverse=True) letterDictRanked = sorted(letterDict.items() , reverse=True, key=lambda x: x[1]) for pair in letterDictRanked: letterTot += pair[1] print(pair) ## print(pair[0],end='') letterDict2 = letterDict.copy() ## letterDictPerc = sorted(letterDict2.items() , reverse=True, key=lambda x: x[1]) for key in letterDict: letterDict2[key] = round(letterDict2[key]/letterTot*100,3) letterDictPerc = sorted(letterDict2.items() , reverse=True, key=lambda x: x[1]) for pair in letterDictPerc: print(pair,end='%\n') for pair in letterDictRanked: print(pair[0],end='')
L = [3,9,5,3,5,3,9,5,9,13] def largest_odd_times(L): """ Date: 20180725 Goal: Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ ''' Today we learn that dictionary keys can also be int ''' if type(L) != list: print('Lists only!') dict_L = {} for num in L: if num in dict_L: dict_L[num] += 1 else: dict_L[num] = 1 largest = max(dict_L) if dict_L[largest] %2 == 1: return largest else: return None
""" Name: genPrimes Date: 20181005 Author: Lio Hong Purpose: A generator that returns primes numbers on successive calls to its method Comments: Store a list of primes that is used to find whether subsequent numbers are primes. //Generators are used for printing out unbounded sequences, or finding a specific value in a sequence. Standard functions are more suitable for bounded sequences (though generators can handle these as well). Also use standard functions when more than two values have to be stored in memory. """ def genPrimes(): listPrimes = [2] count = 3 prime = 2 #First prime number while True: listModulo = [] for num in listPrimes: listModulo.append(count % num) if (0 in listModulo) == False: yield prime prime = count listPrimes.append(prime) count += 1 ''' A far more elegant example from online. Supposedly is more Pythonic as well. Perhaps because of how wordy my code is. Apparently Java is also pretty wordy. ''' def genPrimesANS(): x = 2 while True: flag = True for i in range(2, x): if not x % i: flag = False break if flag: yield x x += 1 #Is a generator still a generator if its yield statement is never reached? #Yes. def generator1(): if True: yield 1 def generator2(): if False: yield 1 g1 = generator1() g2 = generator2() print(type(g1)) print(type(g2)) print(g1.__next__()) print(g2.__next__())
""" Name: Mastermind00 Date: 20181003 Author: Lio Hong Purpose: Recreate the game 'Mastermind' with Python. Inspired by EthosLab who is doing this in Minecraft Rules: 1. Player 2 generates a combination of coloured beads -> CPU randomly generates a sequence 2. Player 1 makes a guess 3. [P2] Check for beads with same colour and same position -> BLACK peg 4. Check for other beads with same colour only --> WHITE peg #WHITE = #sameValue - #BLACK Comments: COMPLETE All you need to know are the rules to create a game. You don't have to know how to beat it. I'm sure this is something profound for game design. I found a pretty reliable approach to beat this game for 4 terms + 6 colours First start with all same colours. This identifies those terms that match. Keep changing the colour for non-B terms, and position for non-W terms. Usually the answer will be found within 6 tries. """ def comboGen(): import random ## numHoles = random.randint(4,9) numHoles = 4 ansCombo = [random.randint(1,6) for i in range(numHoles)] print('Length of target sequence is ' + str(numHoles)) return ansCombo def guesser(): ans = comboGen() numHoles = len(ans) guess = [] pegs = [0,0] countg = 0 countMax = 8 print("I have a sequence of " + str(numHoles) + " terms, each from 1 to 6.") while guess != ans and countg < countMax: ## print('Please make a guess of ' + str(numHoles) + ' terms: ') ## guess = [int(x) for x in input().split()] guess = [] g = input('Please make a guess: ') #Cheat code to show answer and break if g == 'answer': print(ans) break #Converts string input into list g1 = g.split() for term in g1: guess.append(int(term)) if type(guess) != list: print('Input must be of type list!') elif len(guess) != numHoles: print('Input must have ' + str(numHoles) + ' terms.') else: pegs = pegChecker(guess,ans) print('Guess #' + str(countg + 1) + ': ' + str(guess) + ' || ' + \ str(pegs[0]) + 'B ' + str(pegs[1]) + 'W') countg += 1 print('Game Over. Answer is ' + str(ans)) def pegChecker(guess,ans): guessCopy = guess[:] ansCopy = ans[:] numHoles = len(guess) pegBlack = 0 pegWhite = 0 listBlack = [] #Find which terms are identical for i in range(numHoles): if guess[i] == ans[i]: pegBlack += 1 listBlack.append(i) #Remove identical terms in reverse order listBlack.reverse() for index in listBlack: guessCopy.pop(index) ansCopy.pop(index) #Find terms with identical values for bead in guessCopy: if bead in ansCopy: pegWhite += 1 ansCopy.remove(bead) return pegBlack, pegWhite def pegChecker1(): ## guess and ans should be the parameter guess = comboGen() guessCopy = guess[:] ans = comboGen() ansCopy = ans[:] numHoles = len(guess) pegBlack = 0 pegWhite = 0 listBlack = [] for i in range(numHoles): if guess[i] == ans[i]: pegBlack += 1 listBlack.append(i) #Etho exploits item stacking to automatically execute this removal. #How to remove the term properly? listBlack.reverse() for index in listBlack: guessCopy.pop(index) ansCopy.pop(index) print(guess) print(ans) print('Indexes: ' + str(listBlack)) print(guessCopy) print(ansCopy) for bead in guessCopy: if bead in ansCopy: pegWhite += 1 ansCopy.remove(bead) print('=====') print(guessCopy) print(ansCopy) return pegBlack, pegWhite ## guessCDict = {} ## ansCDict = {} ## for bead in guessCopy: ## if bead in guessCDict: ## guessCDict[bead] += 1 ## else: ## guessCDict[bead] = 1 ## ## for bead in ansCopy: ## if bead in ansCDict: ## ansCDict[bead] += 1 ## else: ## ansCDict[bead] = 1 ## print(guessCDict) ## print(ansCDict) ## for bead in guessCDict: ## if bead in ans
ch = input("enter a character") if(ch=='A' or ch=='a'): print(ch,"is a vowel") else: print(ch,"is aconstant")
# GUI 모듈(tkinter) import import tkinter # 가장 상위 레벨의 윈도우 창 생성 window = tkinter.Tk() window.title("LEE A REUM") # 윈도우 창의 제목 설정 window.geometry("640x400+100+100") # ("너비x높이+x좌표+y좌표") 윈도우 창의 너비와 높이, 초기 화면의 위치 설정 window.resizable(False, False) # (상하, 좌우) 윈도우 창의 창 크기 조절 가능 여부 설정 label = tkinter.Label(window, text="안녕하세요.") # 윈도우 창에 Label 위젯 설정 # 위젯 배치 label.pack() # 윈도우 이름의 윈도우 창을 윈도우가 종료될 때까지 실행 window.mainloop()
# Resolve the problem!! import string import random SYMBOLS = list('!"#$%&\'()*+,-./:;?@[]^_`{|}~') LETTERS = list('abcdefghijklmnopqrstuvwxyz') CAPITAL_LETTERS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') NUMBERS = list('0123456789') def generate_password(): # Start coding here characters = SYMBOLS + LETTERS + CAPITAL_LETTERS + NUMBERS password = [] one_SYMBOL = random.choice(SYMBOLS) one_LETTER = random.choice(LETTERS) one_CAPITAL_LETTER = random.choice(CAPITAL_LETTERS) one_NUMBER = random.choice(NUMBERS) password.extend([one_SYMBOL, one_LETTER , one_CAPITAL_LETTER, one_NUMBER]) random_password_length = random.randint(4, 12) for i in range(random_password_length): random_character = random.choice(characters) password.append(random_character) random.shuffle(password) password = ''.join(password) return password def validate(password): if len(password) >= 8 and len(password) <= 16: has_lowercase_letters = False has_numbers = False has_uppercase_letters = False has_symbols = False for char in password: if char in string.ascii_lowercase: has_lowercase_letters = True break for char in password: if char in string.ascii_uppercase: has_uppercase_letters = True break for char in password: if char in string.digits: has_numbers = True break for char in password: if char in SYMBOLS: has_symbols = True break if has_symbols and has_numbers and has_lowercase_letters and has_uppercase_letters: return True return False def run(): password = generate_password() if validate(password): print('Secure Password') else: print('Insecure Password') if __name__ == '__main__': run()
def ears_cout(n): if n == 0: return 0 elif n % 2 == 0: #To count even bunnies return ears_cout(n - 1) + 3 else: #To count odd bunnies return ears_cout(n - 1) + 2 print("How many bunnies in a line?") n = int ( input() ) m = ears_cout(n) print("There are total",m,"ears") #--------------------------simple output1 #/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/QW/Documents/classtest/classtest.py #How many bunnies in a line? #0 #There are total 0 ears #Process finished with exit code 0 #--------------------------simple output2 #/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/QW/Documents/classtest/classtest.py #How many bunnies in a line? #5 #There are total 12 ears #Process finished with exit code 0
class Employee: def __init__(self,first,last): self.first = first self.last = last def get_data(self): print(self.first + '' +self.last) def Email(self): email = self.first + '.' + self.last + '@company.com' return email # emp1 = Employee() # First instance of class is created # emp2 = Employee() # Second Instance of class is created # emp1.name = 'Rajat' # This is instance varibale # emp2.name = 'Manav' # This is instance varibale # print(emp1.name) # print(emp2.name) emp1 = Employee('Rajat','Prakash') emp2 = Employee('Manav','Saxena') # emp1.get_data() # emp2.get_data() print(emp1.Email()) print(emp2.Email())
import os def divide(a, b): assert b > 0 nmr=a//b rem=a%b visited={rem:0} digit=[] while(True): rem *= 10 digit.append(rem//b) rem = rem % b if rem in visited: location=visited[rem] print "location is:" print location return (nmr, digit[:location], digit[location:]) else: visited[rem] = len(digit) print "visited is:" print visited print "digit is:" print digit for a, b in [(5,4), (1,6), (7,17), (2,4), (1,3)]: (n,f,r)=divide(a,b) print "%d/%d = %d.%s(%s)" % (a,b,n, ''.join(map(str,f)), ''.join(map(str,r)))
#you only have access to one node. the sol is to copy the data from next node # and then delete the next node. import os global nodea global nodeb global nodec global noded class LinkedListNode: def __init__(self, initData): self.data = initData self.next = None self.previous = None def getData(self): return self.data def setData(self, newData): self.data=newData def getNext(self): return self.next def setNext(self, newNext): self.next=newNext def getPrevious(self): return self.previous def setPrevious(self, newPrevious): self.previous = newPrevious nodea = LinkedListNode("first") nodeb = LinkedListNode("second") nodec = LinkedListNode("NodeC") noded = LinkedListNode("third") nodea.previous=None nodea.next=nodeb nodeb.next=nodec nodec.next=noded nodeb.previous=nodea nodec.previous=nodeb noded.previous=nodec noded.next=None def printList(): node=nodea; while(node!=None): print node.data node=node.next def deleteMiddleNode(middlenode): if(middlenode == None or middlenode.next==None): print "Invalid Node - can't be removed" return None nextNode=middlenode.next middlenode.data=nextNode.data middlenode.next=nextNode.next print "-----deleting nodec------" deleteMiddleNode(noded) print "--- AND NEW LIST IS ---" printList()
lista = [2,4,3,1,7,6,9,8,5] print('Lista :', (lista)) print("Minha lista em ordem numérica : ", sorted(lista))
print('Привет') print('Напишите несколько чисел. Ваше первое число?') a = int(input()) print('Напишите второе число') b = int(input()) print('Напишите третье число') c = int(input()) if (a*b = c): print('Условие о равенстве произведении первых чисел третьему верно') else: print('Условие о равенстве произведения первых чисел третьему не верно') if (b*c) = a): print('Условие о равенстве частного первых чисел третьему верно') else: print('Условие о равенстве частного первых чисел третьему не верно') input()
# store previous values of function f in a cache # function takes a function as input # function currying style def memoize(f): # create empty cache to store previously computed values of f(x) cache = {} # def g(x): print cache if x not in cache: print x,"not in cache" # print "adding", f(x),"to cache for",x cache[x] = f(x) return cache[x] return g def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n-2)+fib(n-1) # pass in the function fib to memoize # fib(n) now passes n into function g # memoize creates and returns a new function fib = memoize(fib) print fib(7)
def summ(x): if x == 1: return 1 else: return x + summ(x-1) def sumSeries(n): if n <= 0: return 0 else: return n + sumSeries(n-2) def main(): print "returning sum of all integers from 1,2,3...10" print summ(10) print "returning sum of all integers from 24,22,20,18,16...0" print sumSeries(24) main()
""" https://leetcode.com/problems/find-all-duplicates-in-an-array/ Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? """ class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ results = {} ans = [] for i in xrange(len(nums)): results[nums[i]] = 0 for i in xrange(len(nums)): results[nums[i]]+=1 for x in results: if results[x] == 2: ans.append(x) return ans def findDuplicates_2(self, nums): ans = [] for i in nums: if nums[i] > 0: nums[i] = -nums[i] else: ans.append(abs(nums[i])) return ans
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): row=[] def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root is None: return [] result=[] h = self.getHeight(root)+1 for i in range(1, h+1): self.row=[] print "iteration:",i self.makeLevelOrder(root,i) result.append(self.row) return result def makeLevelOrder(self, root, height): if root is None: return if height == 1: self.row.append(root.val) return elif height > 1: leftEle = self.makeLevelOrder(root.left, height-1) rightEle = self.makeLevelOrder(root.right, height-1) def getHeight(self, root): if root is None: return 0 if root.left is None and root.right is None: return 0 height = 0 hleft = self.getHeight(root.left) hright = self.getHeight(root.right) height = 1 + max(hleft,hright) return height
import keyboard import time time.sleep(2) # to give some time for interpreter to execute for i in range(10): # here we are using loop for how many time we need to run our script keyboard.write("hy \n") # write() function take the text as input keyboard.press_and_release("enter") # here press_and_release() function used to enter hotkeys(like enter , shift+@, etc)
from turtle import * import tkinter import sys class Node: def __init__(self,item): self.item = item self.next = None class Queue: def __init__(self): self.head = None self.tail = None def is_empty(self): return self.head == None def enqueue(self, item): if self.is_empty(): self.head = self.tail = Node(item) else: self.tail.next = self.tail = Node(item) def dequeue(self): if self.is_empty(): raise IndexError else: temp = self.head self.head = self.head.next return temp.item def peek(self): return self.head.item def size(self): return size_helper(self.head) def size_helper(node): if node == None: return 0 return 1 + size_helper(node.next) class TreeNode: def __init__(self, item, left=None, right=None): self.item = item self.left = left self.right = right self.x = None self.y = None class BinarySearchTree: def __init__(self, contents=[]): self.root = None for e in contents: self.insert(e) def __contains__(self, item): if contains_helper(self.root, item) == False: return False return True def is_empty(self): return self.root == None def insert(self, item): insert_helper(self, self.root, item) def find_min(self): return min_helper(self.root) def find_max(self): return max_helper(self.root) def numItems(self): return numItems_helper(self.root) def tree_height(self): if self.is_empty(): return None else: leaves = height_helper(self.root, []) heights = [] for item in leaves: node = self.root height = 0 while node.item != item: if item < node.item: node = node.left elif item > node.item: node = node.right height += 1 heights.append(height) return max(heights) def inorder(self): if self.is_empty(): return [] return inorder_helper(self.root, []) def preorder(self): if self.is_empty(): return [] return preorder_helper(self.root, []) def postorder(self): if self.is_empty(): return [] return postorder_helper(self.root, []) def levelorder(self): lst = [] if self.is_empty(): return lst q = Queue() q.enqueue(self.root) while not q.is_empty(): node = q.dequeue() lst.append(node.item) if node.left != None: q.enqueue(node.left) if node.right != None: q.enqueue(node.right) return lst def delete(self, item): if not item in self: return False elif self.root.item == item: if self.root.left == None and self.root.right == None: self.root = None elif self.root.right == None: self.root = self.root.left elif self.root.left == None: self.root = self.root.right else: min_item = max_helper(self.root.left) self.delete(min_item) self.root = TreeNode(min_item, self.root.left, self.root.right) return True node = delete_helper(self.root, item) if node.left != None and node.left.item == item: if node.left.left == None and node.left.right == None: node.left = None elif node.left.right == None: node.left = node.left.left elif node.left.left == None: node.left = node.left.right else: min_item = max_helper(node.left.left) self.delete(min_item) node.left = TreeNode(min_item, node.left.left, node.left.right) elif node.right != None and node.right.item == item: if node.right.left == None and node.right.right == None: node.right = None elif node.right.right == None: node.right = node.right.left elif node.right.left == None: node.right = node.right.right else: min_item = max_helper(node.right.left) self.delete(min_item) node.right = TreeNode(min_item, node.right.left, node.right.right) return True def delete_helper(node, item): if (node.right != None and node.right.item == item) or (node.left != None and node.left.item == item): return node elif item < node.item: return delete_helper(node.left, item) else: return delete_helper(node.right, item) def numItems_helper(node): if node == None: return 0 return 1 + numItems_helper(node.left) + numItems_helper(node.right) def max_helper(node): if node.right == None: return node.item return max_helper(node.right) def min_helper(node): if node.left == None: return node.item return min_helper(node.left) def postorder_helper(node, postorderlst): if node.left != None: postorderlst = postorder_helper(node.left, postorderlst) if node.right != None: postorderlst = postorder_helper(node.right, postorderlst) postorderlst.append(node.item) return postorderlst def preorder_helper(node, preorderlst): preorderlst.append(node.item) if node.left != None: preorderlst = preorder_helper(node.left, preorderlst) if node.right != None: preorderlst = preorder_helper(node.right, preorderlst) return preorderlst def inorder_helper(node, inorderlst): if node.left != None: inorderlst = inorder_helper(node.left, inorderlst) inorderlst.append(node.item) if node.right != None: inorderlst = inorder_helper(node.right, inorderlst) return inorderlst def height_helper(node, leaves_list): if node == None: return [] elif node.left == None and node.right == None: return [node.item] else: return leaves_list + height_helper(node.left, leaves_list) + height_helper(node.right, leaves_list) def insert_helper(tree, node, item): if tree.is_empty(): tree.root = TreeNode(item) elif item > node.item: if node.right == None: node.right = TreeNode(item) else: return insert_helper(tree, node.right, item) elif item < node.item: if node.left == None: node.left = TreeNode(item) else: return insert_helper(tree, node.left, item) def contains_helper(node,item): if node == None: return False elif node.item == item: return node elif item > node.item: return contains_helper(node.right, item) elif item < node.item: return contains_helper(node.left, item) class Grid: def __init__(self, rows, cols, screen=None, canvas=None): self.screen = screen self.canvas = canvas self.rows = rows self.cols = cols self.items = [] for i in range(rows): self.items.append([None] * cols) def __getitem__(self, index): return self.items[index] def drawNodes(self): self.screen.tracer(0) x_spacing = 500 // self.cols y_spacing = 500 // self.rows for row in range(self.rows): for col in range(self.cols): if self[row][col] != None: bstnode = RawTurtle(self.canvas) bstnode.ht() bstnode.shape("circle") bstnode.shapesize(.25, .25) bstnode.penup() bstnode.speed(5) bstnode.goto(100+col*x_spacing,500-row*y_spacing) bstnode.st() bstnode.write(str(float(self[row][col].item)), False, align="center") if self[row][col].left != None: parent = self[row][col] left_child = self[row][col].left LineTurtle = RawTurtle(self.canvas) LineTurtle.ht() LineTurtle.penup() LineTurtle.goto(100+col*x_spacing,500-row*y_spacing) LineTurtle.pendown() LineTurtle.goto(100+left_child.x*x_spacing,500-left_child.y*y_spacing) if self[row][col].right != None: parent = self[row][col] right_child = self[row][col].right LineTurtle = RawTurtle(self.canvas) LineTurtle.ht() LineTurtle.penup() LineTurtle.goto(100+col*x_spacing,500-row*y_spacing) LineTurtle.pendown() LineTurtle.goto(100+right_child.x*x_spacing,500-right_child.y*y_spacing) self.screen.update() class BinaryTreeApplication(tkinter.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.buildWindow() def buildWindow(self): cv = ScrolledCanvas(self,600,600,600,600) cv.pack(side = tkinter.LEFT) t = RawTurtle(cv) screen = t.getscreen() screen.setworldcoordinates(0,0,600,600) screen.bgcolor("white") t.ht() frame = tkinter.Frame(self) frame.pack(side = tkinter.RIGHT,fill=tkinter.BOTH) def quitHandler(): self.master.quit() quitButton = tkinter.Button(frame, text = "Quit", command=quitHandler) quitButton.pack() label = tkinter.Label(frame,text="Node Value:") label.pack() nodevalue = tkinter.StringVar() entry = tkinter.Entry(frame, width=25, textvariable=nodevalue) entry.pack() tree = BinarySearchTree() def insertHandler(): try: item = float(nodevalue.get()) except: return if item in tree: pass else: tree.insert(item) knuth_layout(tree.root, 0) global i i = 0 grid = Grid(tree.tree_height() + 1, tree.numItems(), screen, cv) screen.clear() for n in tree.inorder(): node = contains_helper(tree.root, n) grid[node.y][node.x] = TreeNode(node.item, node.left, node.right) grid.drawNodes() def removeHandler(): try: item = int(nodevalue.get()) except: return if item in tree: tree.delete(item) if tree.is_empty(): screen.clear() return knuth_layout(tree.root, 0) global i i = 0 grid = Grid(tree.tree_height() + 1, tree.numItems(), screen, cv) screen.clear() for n in tree.inorder(): node = contains_helper(tree.root, n) grid[node.y][node.x] = TreeNode(node.item,node.left,node.right) grid.drawNodes() else: pass def containsHandler(): try: item = int(nodevalue.get()) except: return if item in tree: tkinter.messagebox.showwarning("Search Result","Item is in tree!") else: tkinter.messagebox.showwarning("Search Result","Item is NOT in tree!") insertButton = tkinter.Button(frame, text = "Insert", command=insertHandler) #add command=insertHander parameter insertButton.pack() removeButton = tkinter.Button(frame, text = "Remove", command=removeHandler) #add command=removeHandler parameter removeButton.pack() containsButton = tkinter.Button(frame, text = "Contains?", command=containsHandler) #add command=containsHandler parameter containsButton.pack() i = 0 def knuth_layout(root, depth): if root.left != None: knuth_layout(root.left, depth + 1) global i root.x = i root.y = depth; i += 1 if root.right != None: knuth_layout(root.right, depth + 1) def main(): root = tkinter.Tk() root.title("Binary Tree Visualization") application = BinaryTreeApplication(root) application.mainloop() if __name__ == "__main__": main()
# 增加单个元素 # list1=[1,2,3] # list1.append(4) # print(list1) # 指定位置添加 # list1=[1,2,3] # list1.insert(3,4) # print(list1) # 列表一次性添加多个元素 # list1 = [1,2,3,4] # list1.extend([5,6,7,8,9,10]) # print(list1) #取值 # list1 = [1,2,3,4,5,6,7,8,9,10] # print(list1[0:4]) # 修改 # list1 = [1,2,3,4,5,6,7,8,9,10] # list1[-1]=11 # print(list1) # 默认删除最后一个元素 # list1 = [1,2,3,4,5,6,7,8,9,10] # list1.pop() # print(list1) # 删除整个列表,清空 # list1 = [1,2,3,4,5,6,7,8,9,10] # del list1 # 创建空列表 # list2=[] # print(list2,type(list2)) # 字典 # dict1 = {"name":"lemon"} # print(dict1,type(dict1)) # 取值 # dict1 = {"name":"lemon"} # # print(dict1['name']) # print(dict1.get('name')) # 更新修改字典 # dict1 = {"name":"lemon","age":18} # dict1["age"]=19 # print(dict1) # 字典增加多个元素:update({字典}) # dict1 = {"name":"lemon","age":18} # dict1.update({"工作年限:":2,"sex":"男"}) # print(dict1) # 字典增加一个元素 # dict1 = {"name":"lemon","age":18} # dict1["adress"]="江苏" # dict1["工作年限"]=2 # print(dict1) # 创建只有一个元素的元祖 # tup3=(4,) # print(tup3) # 元祖中的元素不能修改 # tup1=(1,2,3,4,5) # tup1[0]=0 # print("修改后的元组:",tup1) # 元祖和列表转换,然后修改元素 # tup1=(1,2,3,4,5) # list1=list(tup1) # # print(list1,type(list1)) # list1[0]=0 # # print(list1) # tup2=tuple(list1) # print(tup2) # 元祖转换为列表取值 # tup1=(1,2,3,4,5) # list1=list(tup1) # print(list1[0]) # 集合去重复 # set1=set({1,2,3,4,5,1,2,3}) # print (set1) # 两种方式定义集合 # 方法一:{} # set1={1,2,3,4,5} # print (set1) # 方法二:set() 函数 # set1=set({1,2,3,4,5}) # print (set1) # if判断语句 # 根据你输入的工资,去判断你当前的岗位级别,初级:小于15k;中级:15-25k;高级:25-50k # xinzi=int(input('请输入月薪:')) # if xinzi < 15: # print('初级') # elif xinzi >= 15 and xinzi < 25: # print('中级') # else: # print('高级') # for循环语句 # sum=0 # for nuber in [1,2,3,4,5,6,7,8,9,10]: # print(nuber) # sum=sum+nuber # print('1+2+3+4+5+6+7+8+9+10=',sum) # 求1+2+3+4+....+100=?range() 函数 # sum=0 # for nuber in range(1,101): # sum+=nuber # print('1+2+3+4+....+100=',sum) # 求2+4+6+...+100=?---->求偶数值 # 方法一 # sum=0 # for nuber in range(2,101,2): # sum += nuber # print('2+4+6+...+100=',sum) # 方法二:内嵌 if 语句 # sum=0 # for nuber in range(1,101): # if nuber%2==0: # print(nuber) # sum+=nuber # else: # continue # print('2+4+6+...+100=',sum) # 方法三:while 语句 # sum=0 # nuber=2 # while nuber<=100: # sum+=nuber # nuber+=2 # print('2+4+6+...+100=',sum) # 定义无参数函数 # def sum(): # sum = 0 # for nuber in range(1, 11): # print(nuber) # sum = sum + nuber # print('1+2+3+...+10=', sum) # sum() # 求1+2+...+n=? # def sum(n): # sum = 0 # for nuber in range(1, n + 1): # print(nuber) # sum = sum + nuber # print(f'1+2+...+{n}=', sum) # sum(10) # 必备参数 # def user_info(name,age,adress): # # name = "张三" # # age = 18 # # adress = "江苏" # print(f"hello{name},age{age},来自:{adress}") # user_info("张三",18,"江苏") # 关键字参数 # def user_info(name, age, adress, nianxian, sex): # print(f"hello{name},age{age},来自:{adress},工作年限:{nianxian},性别:{sex}") # # user_info(name="张三", age=18, adress="江苏", nianxian=2, sex="男") # user_info(age=18,adress="江苏",nianxian=2,name="张三",sex="男") # 默认参数 # def user_info(name, age, adress, nianxian, sex='男'): # print(f"hello{name},age{age},来自:{adress},工作年限:{nianxian},性别:{sex}") # # user_info(name="张三", age=18, adress="江苏", nianxian=2) # user_info(name="李四", age=18, adress="江苏", nianxian=2,sex='女') # 题目:a=[1,2,'6','summer'] 请用成员运算符判断 i是否在这个列表里面 # 方法一 # a=[1,2,'6','summer'] # print('i'in a) # 方法二 # a=[1,2,'6','summer'] # print('i'not in a) # 题目:dict_1={"class_id":45,'num':20} 请判断班级上课人数是否大于5 注:num表示课堂人数。如果大于5,输出人数 # dict_1={"class_id":45,'num':20} # if dict_1['num'] > 5: # print(dict_1['num']) # list3 = ['飞羽', '路飞', '凉公子', '社会杨', '小书生', '凉夏'] 列表当中的每一个值包含:姓名、性别、年龄、城市。以字典的形 # 式表达。并且把字典都存在新的 list中,最后打印最终的列表 # 方法1: 手动扩充--字典--存放在列表里面;{} --简单 # list3=['飞羽','路飞', '凉公子', '社会杨', '小书生', '凉夏'] # dict1={"姓名":"飞羽","性别":'男',"年龄":"20","城市":"上海"} # dict2={"姓名":"路飞","性别":'男',"年龄":"21","城市":"江苏"} # dict3={"姓名":"凉公子","性别":'男',"年龄":"22","城市":"重庆"} # dict4={"姓名":"社会杨","性别":'男',"年龄":"23","城市":"陕西"} # dict5={"姓名":"小书生","性别":'男',"年龄":"24","城市":"浙江"} # dict6={"姓名":"凉夏","性别":'男',"年龄":"25","城市":"上海"} # list1=[dict1,dict2,dict3,dict4,dict5,dict6] # # for list2 in list1: -----> 这句不用写,写了打印出来的只是每个字典,而不是一个列表,题目时打印出列表 # print(list1) # 方法1.1: # list3=['飞羽','路飞', '凉公子', '社会杨', '小书生', '凉夏'] # list1=[] # dict1={"姓名":'飞羽',"性别":'男',"年龄":"20","城市":"上海"} # dict2={"姓名":"路飞","性别":'男',"年龄":"21","城市":"江苏"} # dict3={"姓名":"凉公子","性别":'男',"年龄":"22","城市":"重庆"} # dict4={"姓名":"社会杨","性别":'男',"年龄":"23","城市":"陕西"} # dict5={"姓名":"小书生","性别":'男',"年龄":"24","城市":"浙江"} # dict6={"姓名":"凉夏","性别":'男',"年龄":"25","城市":"上海"} # list1.append(dict1) # list1.append(dict2) # list1.append(dict3) # list1.append(dict4) # list1.append(dict5) # list1.append(dict6) # # for list2 in list1: # print(list2) # 方法2:自动--dict()--不强制 list.append() # list3=['飞羽','路飞', '凉公子', '社会杨', '小书生', '凉夏'] # list1=[] # for x in list3: # dict1 = { "性别": '男', "年龄": "20", "城市": "上海"} # print(x) # dict1['姓名']=x # list1.append(dict1) # print(list1) # 遍历列表 # list1 = ['name', 'age', 'sex'] # for list2 in list1: # print(list2) # 遍历字典,items()返回一个键 — 值对列表, for 循环依次将每个键 — 值对存储到指定的两个变量(key,value)中 # dict1 = {'name':"张三", 'age':"20", 'sex':"男"} # for key,value in dict1.items(): # print(key+":"+value) # 遍历集合 # set1={1,2,3,4,5} # for set2 in set1: # print(set2) # 遍历元祖 # tup1=(1,2,3,4,5) # for tup2 in tup1: # print(tup2) # 题目:把字符串转成列表 # title=('hello','lemon',2) # list1=list(title) # print(list1,type(list1)) # 题目:任意整数序列相加 # def sum(n): # sum=0 # for x in range(1,n+1): # print(x) # sum+=x # print(f'1+2+...+{n}=',sum) # # sum(10) # 题目:定义函数,判断一个对象(列表、字典、字符串)的长度是否大于5 # def a(x): # if len(x) > 5: # print(len(x) > 5) # else: # print(len(x) <= 5) # # a({'namezhangsan'}) # 不定长参数 # def sum2(**b): # print(b) # sum=0 # for x in b: # sum += b[x] # print(sum) # return sum # # print(sum2(one=1,two=2,three=3),type(sum2(one=1,two=2,three=3))) # print(all,type(all)) # 计算字符串中 a 的数量 # x="python hello aaa 123123aabb" # print('a的次数:',x.count('a'))
def get_fibonacci_n(n): return fibonacci_n_helper(n) def fibonacci_n_helper(n, i=1, a=0, b=1): return a if n <= i else fibonacci_n_helper(n, i + 1, b, a + b) # if n <= i: # print(a) # return a # print(a, end=" ") # return fibonacci_n_helper(n, i + 1, b, a + b) n1 = int(input("Enter a number: ")) print("element number", n1, "in fibonacci series:", get_fibonacci_n(n1))
""" * ** *** **** ***** """ a1 = int(input("Enter a number: ")) for i in range(a1): print(" " * (a1 - i - 1), end="") print("*" * (i + 1))
l1 = [] for i in range(10): l1.append(int(input(f"Enter {i+1} value: "))) max_value = max(l1) for i in range(max_value, 0, -1): for value in l1: if value >= i: print("*\t", end="") else: print("\t", end="") print()
from day13_inheritance.item_inheritance.book import Book from day13_inheritance.item_inheritance.dvd import Dvd print("Enter 5 items you want to issue") items = [] for i in range(5): item_type = input("book or dvd (b/d): ") item = Book() if 'b' == item_type else Dvd() item.read() items.append(item) print("\nlist of issued items") for item in items: item.show()
a1 = input("Enter a word:\n") for i in range(1, len(a1) + 1): print(a1[i:], a1[:i], sep="")
a1 = input("Enter a word:\n") l = len(a1) for i in range(l): for i2 in range(l): print(a1[(i + i2 + 1) % l], end="") print()
def power(x, y): if(y == 0): return 1 temp = power(x, int(y/2)) if (y%2==0): return temp*temp else: if(y>0): return x * temp * temp else: return (temp * temp)/x x = 2; y = 10 print('%.6f' %(power(x, y)))
from utils.base_estimator import BaseEstimator import numpy as np from sklearn.tree import DecisionTreeClassifier class AdaBoost(BaseEstimator): """ An AdaBoost classifier is a meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset but where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases. Parameters ---------- n_estimators : integer, optional (default=50) The maximum number of estimators at which boosting is terminated. """ def __init__(self, n_estimators=50): self.n_estimators = n_estimators self.estimators_ = [] self.estimator_weights_ = np.zeros(self.n_estimators) def fit(self, X, y=None): """Build a boosted classifier from the training set (X, y).""" self._setup_input(X, y) # Initialize weights to 1 / n_samples sample_weight = np.zeros(self.n_samples) sample_weight[:] = 1.0 / self.n_samples for i in range(self.n_estimators): # Boosting step sample_weight, estimator_weight = self._boost(sample_weight) self.estimator_weights_[i] = estimator_weight def _boost(self, sample_weight): """Implement a single boost. sample_weight : array-like of shape = [n_samples] The current sample weights. Returns ------- sample_weight : array-like of shape = [n_samples] or None The reweighted sample weights. estimator_weight : float The weight for the current boost. """ X, y = self.X, self.y estimator = DecisionTreeClassifier(max_depth=1) # TODO: replace with custom decision tree estimator.fit(X, y, sample_weight=sample_weight) self.estimators_.append(estimator) y_predict = estimator.predict(X) # Instances incorrectly and correctly classified incorrect = y != y_predict correct = y == y_predict # Error fraction estimator_error = np.average(incorrect, weights=sample_weight) scaling_factor = np.sqrt((1 - estimator_error) / estimator_error) # Boosting by weighting up incorrect samples and weighting down correct ones sample_weight[incorrect] *= scaling_factor sample_weight[correct] /= scaling_factor # Normalize sample_weight sample_weight /= sample_weight.sum() estimator_weight = np.log(scaling_factor) return sample_weight, estimator_weight def _predict(self, X): score = self.decision_function(X) # expect y to be 1 or 0 return np.where(score >= 0.5, 1.0, 0.0) def decision_function(self, X): """Compute the decision function of ``X``.""" pred = np.sum([estimator.predict(X) * w for estimator, w in zip(self.estimators_, self.estimator_weights_)], axis=0) pred /= self.estimator_weights_.sum() return pred
from utils.base_estimator import BaseEstimator import numpy as np import matplotlib.pyplot as plt import seaborn as sns np.random.seed(2046) def euclidean_distance(x, y): return np.sqrt(np.sum((x - y) ** 2)) class KMeans(BaseEstimator): """Partition a dataset into K clusters. Finds clusters by repeatedly assigning each data point to the cluster with the nearest centroid and iterating until the assignments converge (meaning they don't change during an iteration) or the maximum number of iterations is reached. Init centroids by randomly select k values from the dataset For better method to improve convergence rates and avoid degenerate cases. See: Arthur, D. and Vassilvitskii, S. "k-means++: the advantages of careful seeding". ACM-SIAM symposium on Discrete algorithms. 2007 Parameters ---------- K : int, default 8 The number of clusters into which the dataset is partitioned. max_iters: int, default 300 The maximum iterations of assigning points to the nearest cluster. Short-circuited by the assignments converging on their own. """ def __init__(self, K=8, max_iters=300): self.K = K self.max_iters = max_iters # an array of cluster that each data point belongs to self.labels = [] # an array of center value of cluster self.centroids = [] def _init_cetroids(self): """Set the initial centroids.""" indices = np.random.choice(self.n_samples, self.K, replace=False) self.centroids = self.X[indices] def _dist_from_centers(self): return np.array([min([euclidean_distance(x, c) for c in self.centroids]) for x in self.X]) def fit(self, X=None): """Perform the clustering on the given dataset.""" self._setup_input(X, y_required=False) self._init_cetroids() for i in range(self.max_iters): new_centroids = [] # update clusters base on new centroids new_labels = np.apply_along_axis(self._closest_cluster, 1, self.X) # update centroids base on new clusters for k in range(self.K): centroid = np.mean(self.X[new_labels == k], axis=0) new_centroids.append(centroid) if self._is_converged(self.centroids, new_centroids): print('Converged on iteration %s' % (i + 1)) break # not converged yet, update centroids / labels to new centroids / labels self.labels = new_labels self.centroids = new_centroids def _predict(self, X=None): return np.apply_along_axis(self._closest_cluster, 1, X) def _closest_cluster(self, data_point): """ Return the closest cluster index and distance given data point""" closest_index = 0 closest_distance = float("inf") for cluster_i, centroid in enumerate(self.centroids): distance = euclidean_distance(data_point, centroid) if distance < closest_distance: closest_distance = distance closest_index = cluster_i return closest_index def _is_converged(self, centroids, new_centroids): return True if sum([euclidean_distance(centroids[i], new_centroids[i]) for i in range(self.K)]) == 0 else False def plot(self, data=None): if data is None: data = self.X for k in range(self.K): points = data[self.labels == k].T plt.scatter(*points, c=sns.color_palette("hls", self.K + 1)[k]) for point in self.centroids: plt.scatter(*point, marker='x', linewidths=10)
""" For a categorization task the user has to select a category from a set of options. Tasks and responses are stored in a SQLite database. """ from typing import NamedTuple from typing import List, Optional import json class CategorizationTask(NamedTuple): task_id: int description: str metadata: str options: List[str] category: Optional[str] class CategorizationTaskStore: def __init__(self, cursor): self.cursor = cursor def create_task(self, description, options, metadata=None): metadata = metadata or {} self.cursor.execute( """ insert into categorization_task (description, options, metadata) values (:description, :options, :metadata) """, { "description": description, "options": json.dumps(options), "metadata": json.dumps(metadata), }, ) return CategorizationTask( task_id=self.cursor.lastrowid, description=description, options=options, metadata=metadata, category=None, ) def fetch_tasks_by_category(self, category): self.cursor.execute( """ select ROWID, description, options, category, metadata from categorization_task where category = :category """, {"category": category}, ) return self._fetch_results() def load_tasks(self, include_completed=False): if include_completed: self.cursor.execute( """ select ROWID, description, options, category, metadata from categorization_task """ ) else: self.cursor.execute( """ select ROWID, description, options, category, metadata from categorization_task where category is null """ ) return self._fetch_results() def _fetch_results(self): result = [] for row in self.cursor.fetchall(): metadata = json.loads(row["metadata"]) if row["metadata"] else {} result.append( CategorizationTask( task_id=row["ROWID"], description=row["description"], options=json.loads(row["options"]), metadata=metadata, category=row["category"], ) ) return result def save_result(self, task_id, result): self.cursor.execute( """ update categorization_task set category=:result where ROWID=:task_id """, {"task_id": task_id, "result": result}, ) def update_metadata(self, task_id, metadata): self.cursor.execute( """ update categorization_task set metadata=:metadata where ROWID=:task_id """, {"task_id": task_id, "metadata": json.dumps(metadata)}, ) def create_schema(self): self.cursor.execute( """ create table if not exists categorization_task ( description text not null, options text not null, category text, metadata text ); """ ) if __name__ == "__main__": import sqlite3 conn = sqlite3.connect(":memory:") conn.row_factory = sqlite3.Row store = CategorizationTaskStore(conn.cursor()) store.create_schema() print(store.create_task(description="desc", options=["a", "b", "c"])) print(store.create_task(description="desc2", options=["a2", "b2", "c2"])) store.save_result(1, "c") print(store.load_tasks(include_completed=True))
#STACK with Python List class Stack_with_Plist: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.appent(item) def pop(self): if self.is_empty(): return None else: return self.items.pop() def peek(self): if self.is_empty(): return None else: self.items[len(self.items)-1] def size(self): return len(self.items) #Stack with simply linked list #단순 연결 리스트로 구현한 스택 class Node: def __init__(self, item): self.item = item self.next = None def get_next(self): return self.next def get_item(self): return self.item def set_item(self, new_item): self.item = new_item def set_next(self, new_next): self.next = new_next class Stack: def __init__(self): self.head = None def is_empty(self): return self.head == None def push(self,item): new_node = Node(item) new_node.set_next(self.head) self.head = new_node def pop(self): if self.is_empty(): return None else: pop_item = self.head.item self.head = self.head.get_next() return pop_item def peek(self): if self.is_empty(): return None else: return self.head.get_item() def size(self): current = self.head count =0 while current != None: count +=1 current = current.get_next() return count
# Author: coneypo # Blog: http://www.cnblogs.com/AdaminXie/ # Github: https://github.com/coneypo/Generate_handwritten_number # 生成手写体数字 / Generate handwritten numbers from 1~9 import random import os from PIL import Image, ImageDraw, ImageFont random.seed(3) path_img = "data_pngs/" # 在目录下生成用来存放数字 1-9 的 9 个文件夹,分别用 number_1-9 命名 / mkdir folders with name 'number_1' to 'number_9' def mkdir_for_images(): if not os.path.isdir(path_img): os.mkdir(path_img) for i in range(1, 10): if os.path.isdir(path_img + "number_" + str(i)): pass else: print(path_img + "number_" + str(i)) os.mkdir(path_img + "number_" + str(i)) mkdir_for_images() # 删除路径下的图片 / Clear images in 'data/pngs/number_x/' def clear_images(): for i in range(1, 10): dir_nums = os.listdir(path_img+ "number_" + str(i)) for tmp_img in dir_nums: if tmp_img in dir_nums: # print("delete: ", tmp_img) os.remove(path_img + "number_" + str(i) + "/" + tmp_img) print("Delete finish", "\n") clear_images() # 生成单张扭曲的数字图像 / Generate a single distorted digital image def generate_single(): # 先绘制一个 50*50 的空图像 / Draw a blank image with size 50*50 im_50_blank = Image.new('RGB', (50, 50), (255, 255, 255)) # 创建画笔 / Create drawer draw = ImageDraw.Draw(im_50_blank) # 生成随机数 1-9 / Generate random number from 1-9 num = str(random.randint(1, 9)) # 设置字体,这里选取字体大小 25 / Set font font = ImageFont.truetype('simsun.ttc', 20) # xy 是左上角开始的位置坐标 / xy is the position starts draw.text(xy=(18, 11), font=font, text=num, fill=(0, 0, 0)) # 随机旋转-10-10角度 / Rotate with an angle of -10 to 10 randomly random_angle = random.randint(-10, 10) im_50_rotated = im_50_blank.rotate(random_angle) # 图形扭曲参数 / Distortion parameters params = [1 - float(random.randint(1, 2)) / 100, 0, 0, 0, 1 - float(random.randint(1, 10)) / 100, float(random.randint(1, 2)) / 500, 0.001, float(random.randint(1, 2)) / 500] # 创建扭曲 / Do distortion im_50_transformed = im_50_rotated.transform((50, 50), Image.PERSPECTIVE, params) # 生成新的 30*30 空白图像 / Generate blank image with size 30*30 im_30 = im_50_transformed.crop([10, 10, 40, 40]) return im_30, num # 生成手写体数字 1-9 存入指定文件夹 1-9 / Generate 1-9 def generate_number_1_to_9(n): cnt_num = [] for i in range(10): cnt_num.append(0) for m in range(1, n + 1): img, generate_num = generate_single() img_gray = img.convert('1') for j in range(1, 10): if generate_num == str(j): cnt_num[j] = cnt_num[j] + 1 print("Generate:", path_img + "number_" + str(j) + "/" + str(j) + "_" + str(cnt_num[j]) + ".png") img_gray.save(path_img + "number_" + str(j) + "/" + str(j) + "_" + str(cnt_num[j]) + ".png") print("\n") print("生成的数字 1-9 的分布 / Distribution of generated numbers 1-9:") for k in range(9): print("number", k + 1, ":", cnt_num[k + 1], "in all") def main(): # 运行 1000 次 / Run 100 times generate_number_1_to_9(100) if __name__ == '__main__': main()
import numpy as np import time from time import time time0 = time() '''numero de ecuaciones''' n = int(input("Número de ecuaciones: ")) print("\n") '''llenado de matriz''' def LlenarM(M): m = np.zeros((n,n+1)) for i in range(n): for j in range(n+1): m[i][j]=float(input(f"Valor elemento [{i}][{j}]: ")) return m '''eliminacion de gauss jordan''' def GaussJordan(m,n): piv = 0 for x in range(n-1): r = 1 while m[x][x] == 0: if renglon == n: return math.nan IntercambiarRenglones(m, x,re) r += 1 for i in range(x+1, n): piv = m[i][x]/m[x][x] m[i][x] = 0 for j in range(x+1, n+1): m[i][j] -= piv*m[x][j] x = n -1 while x > 0: for i in range(x): piv = m[i][x]/m[x][x] m[i][x] = 0 m[i][-1] -= piv*m[x][-1] x -= 1 for i in range(n): m[i][-1] /= m[i][i] m[i][i]= 1 '''intercambio de renglones''' def IntercambiarRenglones(m,x,r): y = len(m) z = m[x] m[x]= m[x+r] m[x+r] = z '''solucion''' def ImprimirSolucion(s): print("Solucion:") y = len(s) for i in range(y): sf = float(s[i][-1]) print(f"x{i} = {sf}") Matriz = LlenarM(n) GaussJordan(Matriz,n) ImprimirSolucion(Matriz) print(f"Tiempo: {time() - time0}")
#!/usr/bin/env python from hwtools import * print "Section 4: For Loops" print "-----------------------------" nums = input_nums() # 1. What is the sum of all the numbers in nums? print "1.", sum(nums) # 2. Print every even number in nums print "2." for i in nums: if not i%2: print i #CODE GOES HERE # 3. Does nums only contain even numbers? only_even = False for num in nums: if num%2: only_even = False break else: only_even = True print "3.", if only_even: print "only even" else: print "some odd" # 4. Generate a list every odd number less than 100. Hint: use range() print "4.", y = range(1,100) q = [] for g in y: if g%2: q.append(g) print q
#!/usr/bin/env python """ tron.py The simple game of tron with two players. Press the space bar to start the game. Player 1 (red) is controlled with WSAD and player 2 (blue) is controlled with the arrow keys. Once the game is over, press space to reset and then again to restart. Escape quits the program. """ import pygame from pygame.locals import * ## Defining player one. ## class tron_p1: def __init__(self, surface, x, y, length): self.surface = surface self.x = x self.y = y self.length = length self.dir_x = 0 self.dir_y = -1 self.body = [] self.crashed = False # Defining player one's keyboard controls (w,a,s,d) and which direction they move the character towards. def key_event_p1(self, event): if event.key == pygame.K_w and self.dir_y != 1: # This prevents the player from crashing into themselves while pressing the key that would go in the opposite direction of their current movement. self.dir_x = 0 self.dir_y = -1 elif event.key == pygame.K_d and self.dir_x != -1: self.dir_x = 1 self.dir_y = 0 elif event.key == pygame.K_s and self.dir_y != -1: self.dir_x = 0 self.dir_y = 1 elif event.key == pygame.K_a and self.dir_x != 1: self.dir_x = -1 self.dir_y = 0 # Defining player one's movement. def move(self): self.x += self.dir_x self.y += self.dir_y # Tells the character to crash if it runs into itself. if (self.x, self.y) in self.body: self.crashed = True self.body.insert(0, (self.x, self.y)) # Defining player one's color (red) def draw(self): for x, y in self.body: self.surface.set_at((x, y), (255, 0, 0)) ## Defining player two (almost the same as Player One's stuff). ## class tron_p2: def __init__(self, surface, x, y, length): self.surface = surface self.x = x self.y = y self.length = length self.dir_x = 0 self.dir_y = -1 self.body = [] self.crashed = False # Defining player two's keyboard controls (the arrow keys). def key_event_p2(self, event): if event.key == pygame.K_UP and self.dir_y != 1: self.dir_x = 0 self.dir_y = -1 elif event.key == pygame.K_RIGHT and self.dir_x != -1: self.dir_x = 1 self.dir_y = 0 elif event.key == pygame.K_DOWN and self.dir_y != -1: self.dir_x = 0 self.dir_y = 1 elif event.key == pygame.K_LEFT and self.dir_x != 1: self.dir_x = -1 self.dir_y = 0 # Defining player two's movement. def move(self): self.x += self.dir_x self.y += self.dir_y if (self.x, self.y) in self.body: self.crashed = True self.body.insert(0, (self.x, self.y)) # Defining player two's color (blue). def draw(self): for x, y in self.body: self.surface.set_at((x, y), (0, 0, 255)) # The dimensions of the screen. width = 700 height = 600 screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() running = True end_game = False p1 = tron_p1(screen, width/3, height/2, 500) # Player one's starting position. p2 = tron_p2(screen, width/2, height/2, 500) # Player two's starting position. # Printed instructions on how to play the game. print "Controls: " print "Player one is Red and uses w,a,s,d to move." print "Player two is blue and uses the arrow keys to move." print "Avoid the edges of the screen, the other player and your own trail." # While the game hasn't ended, play the game. (This is how the player can exit the game using the escape key but this extra while loop was originally how I was going to have the space bar start and repeat work). It also adds a pause at the end of the game after one eprson crashes (but before the player exits) so I decided to keep it in. while end_game == False: # While the game is running... # while running == True: screen.fill((0, 0, 0)) #Making the screen black. # Player one during the game. p1.move() p1.draw() # If player one crashes into itself or into the boundries of the screen, end the game. if p1.crashed or (p1.x <= 0) or (p1.x >= width-1) or (p1.y <= 0) or (p1.y >= height-1): print "Player one crashes!" running = False # If player one crashes into player two, end the game. if (p1.x, p1.y) in p2.body: p1.crashed = True print "Player one crashes!" running = False # Key commands for both players. for event in pygame.event.get(): # Exiting the game using the escape key during the game. if event.type == KEYDOWN and event.key == pygame.K_ESCAPE: running = False end_game = True print "Thanks for playing!" # Player one and two controls. elif event.type == pygame.KEYDOWN: p1.key_event_p1(event) p2.key_event_p2(event) # Player two during the game. p2.move() p2.draw() # If player two crashes into itself or into the boundries of the screen, end the game. if p2.crashed or (p2.x <= 0) or (p2.x >= width-1) or (p2.y <= 0) or (p2.y >= height-1): print "Player two crashes!" running = False # If player two crashes into player one, end the game. if (p2.x, p2.y) in p1.body: p2.crashed = True print "Player two crashes!" running = False pygame.display.flip() clock.tick(250) # Exiting the game using the escape key after the game is over. for event in pygame.event.get(): if event.type == KEYDOWN and event.key == pygame.K_ESCAPE: end_game = True print "Thanks for playing!" """ I couldn't find a way to make the game restart when the player hits the spacebar. All of the ways I tried made it so the game would only run if the spacebar was constantly being pressed and this was annoying. So for the sake of my sanity, the game will just have to be restarted in the terminal. One of the most promising ways I tried to make this thing restart: - Turning the enitre game (everything inside the "while running == True" loop) into a function (named "play_tron") and then making this: for event in pygame.event.get(): if event.type == KEYDOWN and event.key == pygame.K_SPACE: play_tron() elif event.type == KEYDOWN and event.key == pygame.K_ESCAPE: end_game = True But this didn't work. And this was about as close as the internet got to gettingthe "spacebar restart" problem to work. Soooo... this made me sad. :( """
#!/usr/bin/env python """ users.py User Database (Advanced) ========================================================= The nice thing about dictionaries (and objects) is you can have a list or a dictionary of items that all have the same properties. The result is something like a lookup table or a database For the following examples, assume that users is a list that looks something like this: users = { "Ben S": { "age": 23, "follows": [ "Sally F", "Gerald Q" ] }, "Sally F": { "age": 10, "follows": [ "Gerald Q", "Frank L" ] }, "Jeff B": { "age": 12, "follows": [ "Steve M", "Sally F", "Gerald Q" ] }, "Gerald Q": { "age": 20, "follows": [ ] }, "Steve M": { "age": 18, "follows": [ ] }, ... } You can see the actual data as a table in users_data.txt """ # 1. followers # Find everyone who is following the given names. Using the # above example: # >>> followers(users, "Gerald Q", "Sally F") # [ "Ben S", "Sally F", "Jeff B", "Steve M" ] # # Hint, lookup "set" in python def followers(users, *names): "find followers for given names" # 2. underage_follows # Find everyone that underage users (age <= 12) follow. Make # sure there are no duplicates. Do not include the underage # users themselves # >>> underage_follows(users) # [ "Steve M", "Gerald Q", "Frank L" ] def underage_follows(users): "find who underage users follow" # 3. foaf # Foaf (friend of a freind) returns a list of everyone whom # a user's followers follow not including the user themself. # >>> foaf(users, "Gerald Q") # [ "Sally F", "Frank L", "Steve M" ] def foaf(users, name): "find everyone whom a user's followers follow (not including user)" # 4. age_demographics # For "statistics", return a dictionary with the average age # of the followers for a given user age. So, for example, # find the average age of EVERYONE who follows someone who is # 19. # # Sample output: # { 19: 20.33333333, # 20: 24.125, # 21: 17 # ... # } def age_demographics(users): "calculate age demographics" # UNCOMMENT THE FOLLOWING TO WRITE YOUR OWN CODE USING USERS # if __name__ == "__main__": # from tests.test_users import USERS # print USERS
import pygame from pygame import Rect, Surface from layer import Layer class ShadowLayer(Layer): color = 0,0,0,150 ratio = 3.0 / 4.0 def draw_sprite(self, sprite, ratio=None): if ratio is None: ratio = self.ratio # calculate the size of the shadow w = sprite.rect.width * ratio + 1 h = w/2 rect = Rect(0,0,w,h) # shrink the shadow according to height if hasattr(sprite, "height"): height0 = sprite.__class__.height ratio = (height0 - sprite.height) / float(height0) rect.width = max(8, rect.width * ratio) rect.height = max(4, rect.height * ratio) # move the the midbottom of the sprite rect.center = sprite.rect.midbottom rect.x -= 1 rect.y -= 3 # if the sprite has a height property, use it to move the shadow if hasattr(sprite, "height"): rect.y += sprite.height # draw to the layer pygame.draw.ellipse(self._layer, self.color, rect) # self._layer.fill(self.color, rect)
import sqlite3 class ToDoItem: dbpath = "" tablename = "todoitems" def __init__(self,**kwargs): #use kwargs if your table name is constantly changing, kwargs lets you take in any column value pairs self.pk = kwargs.get("pk") self.title = kwargs.get("title") self.description = kwargs.get("description") self.complete = kwargs.get("complete") def save(self): if self.pk is None: #if pk doesnt exist, insert or update data self.insert() else: self.update() def insert(self): with sqlite3.connect(self.dbpath) as conn: curs = conn.cursor() SQL = """INSERT INTO {} (title,description,complete) VALUES(?,?,?);""".format(self.tablename) values = (self.title, self.description, self.complete) curs.execute(SQL,values) pk = curs.lastrowid #this just put the id of the last row it interacted with self.pk = pk #or could say self.pk = curs.lastrowid def update(self): with sqlite3.connect(self.dbpath) as conn: curs = conn.cursor() SQL = """UPDATE {} SET title=?,description=?,complete=? WHERE pk=?;""".format(self.tablename) values = (self.title, self.description, self.complete,self.pk) curs.execute(SQL,values) def delete(self): if not self.pk: raise KeyError(self.__repr__() + " is not a row in " + self.tablename) with sqlite3.connect(self.dbpath) as conn: curs = conn.cursor() SQL = """DELETE FROM {} WHERE pk=?;""".format(self.tablename) curs.execute(SQL, (self.pk,)) @classmethod def all(cls,complete=None): #select all, if used True it would select all where complete = True only if complete is None: #if none are complete SQL = """ SELECT * FROM {};""".format(cls.tablename) elif bool(complete) is True: SQL = """SELECT * FROM {} WHERE complete=1;""".format(cls.tablename) elif bool(complete) is False: SQL = """SELECT * FROM {} WHERE complete=1;""".format(cls.tablename) with sqlite3.connect(cls.dbpath) as conn: conn.row_factory = sqlite3.Row curs = conn.cursor() curs.execute(SQL) rows = curs.fetchall() return [cls(***row) for row in rows] # lets you manipualte rows like a dictionary #this returns a list of objects that are of type ToDoItem that can be fed into the init method @classmethod def one_from_pk(cls,pk): SQL = """SELECT * FROM {} WHERE pk=?;""".format(cls.tablename) with sqlite3.connect(cls.dbpath) as conn: conn.row_factory = sqlite3.Row curs = conn.cursor() curs.execute(SQL,(pk,)) #class method so there is no self, no instance attributes yet rows = curs.fetchone() return cls(***row) #creating one instance def __repr__(self): pattern = "<ToDoItem: title={} pk={}>" return pattern.format(self.title,self.pk)
# a=50 # if a>50: # print('yes') # elif a<50: # print("hemine") # else: # print('nadarimo') r = int(input('num')) if r%2==0: print('{} is even' .format(r)) else: print('{} is fard',r)
string = input().split() a = float(string[0]) b = float(string[1]) c = float(string[2]) lista = [a, b, c] lista.sort(reverse=True) a = lista[0] b = lista[1] c = lista[2] if a >= (b + c): print('NAO FORMA TRIANGULO') if (a ** 2) == (b ** 2) + (c ** 2): print('TRIANGULO RETANGULO') if ((a ** 2) > (b ** 2) + (c ** 2)) and ((a + b) > c ) and ((b + c) > a) and ((a + c) > b): print('TRIANGULO OBTUSANGULO') if (a ** 2) < (b ** 2) + (c ** 2): print('TRIANGULO ACUTANGULO') if a == b == c: print('TRIANGULO EQUILATERO') if ((a == b) and (b != c)) or ((b == c) and (a != b)) or ((a == c) and (c != b)): print('TRIANGULO ISOSCELES')
x = int(input()) z = 0 while True: z = int(input()) if z > x: break soma = x c = 1 while z > soma: soma = soma + x c += 1 x += 1 print(c)
while True: try: c1 = c = 0 flag = True s = input() if s == '': flag = True elif s[0] == ')' or s[-1] == '(': flag = False c = s.count('(') c1 = s.count(')') if c == 0 and c1 == 0 and s == '': print('correct') elif c == 0 or c1 == 0 and s != 0: print('incorrect') elif c == 1 and c1 == 1: if flag is True: print('correct') else: print('incorrect') elif c == c1: if flag is True: print('correct') else: print('incorrect') else: print('incorrect') except EOFError: break
# criar uma lista com range l = list(range(1, 11)) # step 2 l1 = list(range(2, 11, 2)) # criar um lista vazia lista = list() lista1 = [] # copiar um lista lnew = l.copy() print(lnew)
''' from collections import deque >>> d=deque([1,2,3,4,5]) >>> d deque([1, 2, 3, 4, 5]) >>> d.rotate(2) >>> d deque([4, 5, 1, 2, 3]) >>> d.rotate(-2) >>> d deque([1, 2, 3, 4, 5]) Or with list slices: >>> li=[1,2,3,4,5] >>> li[2:]+li[:2] [3, 4, 5, 1, 2] >>> li[-2:]+li[:-2] [4, 5, 1, 2, 3] Note that the sign convention is opposite with deque.rotate vs slices. If you want a function that has the same sign convention: def rotate(l, y=1): if len(l) == 0: return l y = -y % len(l) # flip rotation direction return l[y:] + l[:y] >>> rotate([1,2,3,4,5],2) [4, 5, 1, 2, 3] >>> rotate([1,2,3,4,5],-22) [3, 4, 5, 1, 2] >>> rotate('abcdefg',3) 'efgabcd' For numpy, just use np.roll >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.roll(a, 1) array([9, 0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> np.roll(a, -1) array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) '''
print() dados = {'nome':'Pedro', 'idade': 25} # Criando um elemento dados['sexo'] = 'M' # Removendo um elemento e o valor dele #del dados['idade'] # imprimindo somente as chaves print(dados.keys(), 'imprimindo somente as chaves\n') # imprimindo somente os valores print(dados.values(),'imprimindo somente os valores\n') # imprimindo todos os itens print(dados.items(),'imprimindo todos os itens\n') print(dados)
i = 0 j = 1 for x in range(3): print("I=%d J=%d" % (i, j)) j = j + 1 for x in range(9): j = j - 3 j = j + 0.2 i = i + 0.2 for x in range(3): if (i == 1): print("I=%d J=%d" % (i, j)) else: print("I=%.1f J=%.1f" % (i, j)) j = j + 1 i = 2 j = 3 for x in range(3): print("I=%d J=%d" % (i, j)) j = j + 1
n = int(input()) res2 = '' if n == 0: print('0') n = -1 else: t1 = 0 t2 = 1 res2 = '0 1 ' i = 2 while i < n: t3 = t1 + t2 res2 += str(t3) + ' ' t1 = t2 t2 = t3 i += 1 print(res2[:-1])
c = 0 soma = 0 for x in range(1,7,1): a = float(input()) if a > 0: c = c + 1 soma = soma + a print('%d valores positivos' % c) print('%.1f' % (soma/c))
n = int(input()) if n <= 800: print('1') if 800 < n <= 1400: print('2') if 1400 < n <= 2000: print('3')
x = float(input()) if (x > 0.00) and (x < 2000.00): print('Isento') elif(x >= 2000.01) and (x <= 3000.00): resto = x - 2000 res = resto * 0.08 print("R$ %.2f" % res) elif (x >= 3000.01) and (x <= 4500.00): resto = x - 3000 res = (resto * 0.18) + (1000 * 0.08) print("R$ %.2f" % res) else: resto = x - 4500 res = (resto * 0.28) + (1500 * 0.18) + (1000 * 0.08) print("R$ %.2f" % res)
# coding=utf-8 import random import time print("2 tane 1-6 arasında rakam gir ve kaçıncı denemede geldiğini öğren") birinci_rakam = int(input("Birinci Rakamı Giriniz: ")) ikinci_rakam = int(input("İkinci rakamı giriniz: ")) if birinci_rakam >=1 and birinci_rakam <=6 and ikinci_rakam >= 1 and ikinci_rakam<=6: i = 1 while True: zar_1 = random.randint(1, 6) zar_2 = random.randint(1, 6) if zar_1 == birinci_rakam and zar_2 == ikinci_rakam: print("""Deneme {}:\t({},{}) *** """.format(i, zar_1, zar_2)) time.sleep(2) break print("""Deneme {}:\t({},{}) """.format(i, zar_1, zar_2)) i += 1 time.sleep(0.5) print("""\n*** {}. denemede ({},{}) geldi ***""".format(i, birinci_rakam,ikinci_rakam)) else: print("1 ile 6 arasında sayı seçmelisiniz")
#文字列を反転し、後ろから探索してみる def execute(S): while "dreameraser" in S: S = S.replace("dreameraser", "") while "dreamerase" in S: S = S.replace("dreamerase", "") while "eraser" in S: S = S.replace("dreamerase", "") while "dreamerase" in S: S = S.replace("dreamerase", "") while "dreamerase" in S: S = S.replace("dreamerase", "") S = S.replace("dreamer", "")\ .replace("eraser", "")\ .replace("dream", "")\ .replace("erase", "") #print(S) res = '' if S == '': res = 'YES' else: res = 'NO' print(res) return res if __name__ == '__main__': S = input() execute(S)
def create_list(max,incr): i = 0 numbers = [] for i in range(0,max,incr): print "At the top i is %d" %i print "Numbers is now: ", numbers numbers.append(i) print "At the bottom i is %d." %i for num in numbers: print num create_list(8,2)
## Towers of Hanoi game. Plan is later use this with ## Reinforcement Learning model to find optimal strategy ## Create Initial Game State def game_setup(): state = [[1,2,3,4],[],[]] return state ## Check to see if rod is empty def is_empty(rod,state): if len(state[rod]) == 0: is_empty = True else: is_empty = False return is_empty ## Check to see if move is legal. Returns 1 if valid def check_valid_move(from_rod,to_rod,state): if is_empty(from_rod,state): valid_move = 0 elif is_empty(to_rod,state): valid_move = 1 elif state[from_rod][0] < state[to_rod][0]: valid_move = 1 elif state[from_rod][0] > state[to_rod][0]: valid_move = 0 else: valid_move = 2 print "something weird is happening here" return valid_move ## Make a move def move(from_rod,to_rod,state): if check_valid_move(from_rod,to_rod,state)== 1: disk_to_move = state[from_rod].pop(0) state[to_rod].insert(0,disk_to_move) print "Valid move! New board is: %r" %state elif check_valid_move(from_rod,to_rod,state)== 0: print "Try again" print "Current board is %r" %state else: print "It looks like the move didn't make sense. valid move = 2"
from flask import Flask app = Flask(__name__) a=2 b=3 @app.route("/") def index(): return str(a+b) @app.route("/sub") def sub(): return str(a-b) @app.route("/mul") def mul(): return str(a*b) @app.route("/power") def power(): return str(a**b) @app.route("/exp") def exp(): return str(a*b+a**b) #"Hello, world!" if __name__ == "__main__": app.run() #from flask import Flask #app = Flask(__name__) #@app.route("/") #def index(): # return "Hello, world!" #if __name__ == "__main__": # app.run()
class Pixel: @classmethod def is_in_tap(cls, b: int, g: int, r: int) -> bool: """ :return: 色がTapの中身のものであればTrueを返す. :rtype: bool """ if b in range(128, 213) and g in range(128, 238) and r in range(128, 238): return True else: return False @classmethod def is_green(cls, b: int, g: int, r: int) -> bool: """ :return: 色がStart,TapEndの枠またはmiddleの中身のものであればTrueを返す. :rtype: bool """ if b == 50 and g == 205 and r == 50: return True else: return False @classmethod def is_connecting_green(cls, b: int, g: int, r: int) -> bool: """ (startを識別するためのもの。) :return: 色が長押しの途中のものであればTrueを返す. :rtype: bool """ if b == 13 and g == 51 and r == 13: return True elif b == 106 and g == 144 and r == 92: return True elif b == 37 and g == 51 and r == 13: return True # elif b == 25 and g == 103 and r == 25: # TapStartの中身 or つながり緑の枠。終点と認識されるのでだめ。 # return True elif b == 31 and g == 128 and r == 31: return True elif b == 31 and g == 128 and r == 43: return True elif b == 37 and g == 75 and r == 13: # サビ return True elif b == 140 and g == 178 and r == 140: # 小節境界線と繋がり緑中身 return True elif b == 109 and g == 187 and r == 109: # 小節境界線と繋がり緑枠 return True else: return False @classmethod def is_middle_frame(cls, b: int, g: int, r: int) -> bool: """ :return: 色がmiddleの枠のものであればTrueを返す. :rtype: bool """ if b == 211 and g == 211 and r == 211: return True else: return False @classmethod def is_tap_frame(cls, b: int, g: int, r: int) -> bool: """ :return: 色がTapの枠のものであればTrueを返す. :rtype: bool """ if b == 255 and g == 255 and r == 255: return True else: return False @classmethod def is_flick_frame(cls, b: int, g: int, r: int) -> bool: """ :return: 色がFlickの枠のものであればTrueを返す. :rtype: bool """ if b == 255 and g == 0 and r == 255: return True else: return False @classmethod def is_yellow_frame(cls, b: int, g: int, r: int) -> bool: """ :return: 色が黄色円枠のものであればTrueを返す. :rtype: bool """ if b == 0 and g == 165 and r == 255: # 黄色 return True else: return False @classmethod def is_following_color(cls, b: int, g: int, r: int) -> bool: """ :return: 色が追跡すべきものであればTrueを返す. :rtype: bool """ bgr = [b, g, r] if max(bgr) == g and max(bgr) != b and max(bgr) != r: return True elif cls.is_middle_frame(r, g, b): return True else: return False # if cls.is_connecting_green(b, g, r) or cls.is_flick_frame(b, g, r): # return True # elif cls.is_green(b, g, r) or cls.is_middle_frame(b, g, r): # return True # elif b == 42 and g == 221 and r == 138: # TapEnd中身+同時押し黄色 # return True # elif b == 47 and g == 221 and r == 142: # TapEnd中身+同時押し黄色+サビ # return True # elif b == 95 and g == 192 and r == 95: # TapEnd中身+小節境界線 # return True # elif b == 115 and g == 193 and r == 109: # TapEnd中身+小節境界線+サビ # return True # else: # return False
import math def binary_search(list, item): low = 0 high = len(list) - 1 while low <= high: mid = (low + high) // 2 guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid + 1 return None my_list = [1, 3, 5, 7, 9] print(binary_search(my_list, 3)) #1 print(binary_search(my_list, 8)) #None print(math.log2(128)) #7 print(math.log2(256)) #8 print(math.log2(1000000000)) #30 #always remember that bigO notation is about WORST case scenarios, NOT best case
x=(1,2,3) y=(4,5,6) # length of tuple print len(x) #index based print x[2] #list of tuples listOfTuples = [x,y] print listOfTuples #use in data analysis (age,income) = "20,120000".split(',') print age print income
import numpy as np np.random.seed(0) totals = {20:0,30:0,40:0,50:0,60:0,70:0} #total number of people in each age grp purchases = {20:0,30:0,40:0,50:0,60:0,70:0} # total purchase done by each age group totalpurchases = 0 for _ in range(100000): ageDecade = np.random.choice([20,30,40,50,60,70]) totals[ageDecade]+=1 purchaseProbability = float(ageDecade)/100.0 # to assign lesser probability for young people if (np.random.random() < purchaseProbability): totalpurchases+=1 purchases[ageDecade]+=1 print totals print purchases print totalpurchases # Probability of buying something given that you are in your 30's, P(E|F) # Equivalent to the percentage of how many 30 year old bought something PEF = float(purchases[30])/float(totals[30]) print "P(Purchases | 30)" , PEF # Probablity of being 30 in the data set , p(F) PF = float(totals[30])/100000.0 print "P(30)" , PF #Overall probability of buying something , P(E) PE = float(totalpurchases) / 100000.0 print "P(Purchase)" , PE #Since P(E) and P(E|F) are different , that means purchase and age are dependent print "P(30)*P(Purchase)",PE*PF #Probability of both being in 30's and purchasing , P(E,F) = P(E)*P(F). #Here it might defer due to random nature of data print "P(purchase,30)" , float(purchases[30])/100000.0 #P(E,F)/P(F) = P(E|F) print (float(purchases[30])/100000.0)/PF # Equal to P(E|F)
import sys class minHeap(): def __init__(self, arr, n): self.harr = arr self.heapSize = n i = (self.heapSize // 2) - 1 while i >= 0: self.heapify(i) i -= 1 def left(self, i): return (i * 2) + 1 def right(self, i): return (i * 2) + 2 def parent(self, i): return (i - 1) // 2 def heapify(self, i): l = self.left(i) r = self.right(i) smallest = i if l < self.heapSize and self.harr[l] < self.harr[smallest]: smallest = l if r < self.heapSize and self.harr[r] < self.harr[smallest]: smallest = r if smallest != i: self.harr[smallest], self.harr[i] = self.harr[i], self.harr[smallest] self.heapify(smallest) def extractMin(self): if self.heapSize == 0: return sys.maxsize min = self.harr[0] if self.heapSize > 1: self.harr[0] = self.harr[self.heapSize - 1] self.heapify(0) self.heapSize -= 1 return min def getMin(self): return self.harr[0] def heapSort(self): n = self.heapSize while n > 0: res = self.extractMin() self.harr[n - 1] = res n -= 1 if __name__ == '__main__': a = [12, 11, 13, 5, 6, 7, 1, 10, 100, 8] print('Initial array: ', a) minheap = minHeap(a, len(a)) print('After heapify, array: ', a) print('Minimum element: ', minheap.getMin()) minheap.heapSort() print('After heap sort, array: ', a)
# chess dictionary validator # Fantasy game Inventory stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12, 'map fragments': 3} def display_inventory(inventory): #Print contents and total number of items in inventory. print('Inventory:') item_total = 0 for k, v in inventory.items(): # FILL THIS PART IN print(str(v) + ' ' + k) item_total += v print('Total number of items : ' + str(item_total)) # List to Dictionary Function for Fantasy Game Inventory def add_to_inventory(inventory, added_items): for item in added_items: inventory.setdefault(item, 0) inventory[item] += 1 return(inventory) inv = {'gold coin': 42, 'rope': 1} dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = add_to_inventory(inv, dragon_loot) display_inventory(inv)
numpeople = input("How many people are taking the journey? ") nummiles = input("How many miles is your trip? ") price = 3 if int(numpeople) < 5: price = price if int(nummiles) == 1: price = price elif int(nummiles) > 1: price = ((price * 2) - 1) elif int(numpeople) >= 5: price = (price * 2) print (("Your price is £") + str(price))
# Create table updated import MySQLdb #======================== Connect to database ================================== # Create an Object = connection to database db = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="vertrigo", # your password db="mybooks") # name of the data base # prepare a cursor object using cursor() method cursor = db.cursor() #========================== Use sql from Py ==================================== # Show the SQL response def SQL(sql): s = "" try: cursor.execute(sql) # execute for x in cursor.fetchall(): print x s = s + str(x) + "\n" except: print " !!!!!!!! Error happened !!!!!!!!!! " return s #====================== Create table as per requirement ======================== SQL("DROP TABLE IF EXISTS updated;") # Carefull !!! Drops the Table!!. sql = """CREATE TABLE updated ( ID INT(15) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, Title VARCHAR(1000) NOT NULL DEFAULT '', Author VARCHAR(300) NOT NULL DEFAULT '', VolumeInfo VARCHAR(100) NOT NULL DEFAULT '', Year INT(4) UNSIGNED DEFAULT NULL, Edition VARCHAR(50) NOT NULL DEFAULT '', Publisher VARCHAR(100) NOT NULL DEFAULT '', Pages INT(10) UNSIGNED DEFAULT NULL, Identifier VARCHAR(100) NOT NULL DEFAULT '', Language VARCHAR(50) NOT NULL DEFAULT '', Extension VARCHAR(50) NOT NULL DEFAULT '', Filesize BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', Library VARCHAR(50) NOT NULL DEFAULT '', MD5 CHAR(32) NOT NULL UNIQUE KEY, Topic VARCHAR(500) DEFAULT '', Commentary VARCHAR(10000) DEFAULT '', Path VARCHAR(733) DEFAULT '' ) ENGINE=MyISAM DEFAULT CHARSET=utf8""" SQL(sql) #======================== disconnect from server =============================== cursor.close () db.close() # disconnect from server
import math # the above code imports everything from python math # you can print number by just putting them in a print statement print(2) print(3.1415) print(-6) # all types of numbers work and you have the basic math operators too! print(3*4) print(4/2) # % is the remainder operator will give you the remainder or division print(10 % 3) # you can also use "()" to change order of operations print(3*(4+5)) my_num = 64 print(str(my_num) + " my favorite number!") # you can use functions on nubmers too! my_num = -64 # gives you the absolute value of a number print(abs(my_num)) # you can use pow(num1,num2) will let you do exponents print(pow(5, 2)) # functions such as min(num1, num2) or max(num1, num2) will give you the # minimum or maximum value # when you import everything you have more functions like floor(num) and # ceil(num) which truncates the decimal or rounds up regardless the number # respectively print(math.pi)
from PIL import Image, ImageDraw, ImageFont from datetime import date import pandas as pd import numpy as np import yagmail import os #Function to verify if the certificate exists in the search_path def find_files(filename, search_path): result = [] for root, dir, files in os.walk(search_path): if filename in files: result.append(filename) return result #Function to attach the certificate file and send using #gmail account ([email protected]) to all participants def mail_send(recv_mail, filename,name): receiver = recv_mail body = "Hi "+name+"! Here's your Certificate of Participation for Hack-n-Slash Webinar by HackersVilla :)" location = "certs/"+filename.strip() yag = yagmail.SMTP("[email protected]") yag.send( to=receiver, subject="Knock Knock! Its HackersVilla..", contents=body, attachments=location, ) #Fetch today's date for printing on certificate today = date.today() date = today.strftime("%B %d, %Y") #Storing entire csv file into a dataframe df = pd.read_csv('list.csv') #Length of dataframe (for iterating in the loop) entries = len(df) #Storing the names and emails of participants as a numpy array arr = np.array(df[['name','email','date']]) date = arr[0][2] print("Found",entries,"participants") print("Creating Certificates now.. Please Wait") #Segment to create certificate font1 = ImageFont.truetype('Herland.ttf',170) font2 = ImageFont.truetype('Poppins-SemiBold.otf',34) for index,j in df.iterrows(): img = Image.open('certificate.jpg') draw = ImageDraw.Draw(img) W = 3650 msg = '{}'.format(j['name']) w, h = draw.textsize(msg, font=font1) draw.text(((W-w)/2,900), msg, fill="white", font=font1) #draw.text(xy=(1700,900),text='{}'.format(j['name']),fill="white",font=font1) draw.text(xy=(2400,1385),text=date,fill="#00f0ff",font=font2) img.save('certs/{}.jpg'.format(j['name'])) print("Certificates have been created and are ready to mail") print("Stariting now \n\n") #Segment to iterate over every row in the array, verify the cert file and send on the corresponding email of participant for x in range(entries): name = arr[x][0] img = "" img = img + name + ".jpg" print("Name of Participant:", name) print("Searching for cert", img) if find_files(img,"./certs"): print("Certificate Found for", name) email = arr[x][1] print("Sending email on",email) mail_send(email,img,name) print("Certificate Sent\n\n") else: print("Certificate file not found for",name) print("Continuing further..\n\n") print("Huff! I am done boss")
# Credit: http://www.python-course.eu/turing_machine.php class Tape(object): blank_symbol = " " def __init__(self, input=""): self.__tape = {} for i,sym in enumerate(input): self.__tape[i] = sym def __str__(self): # BUG s = "" minUsedIndex = min(self.__tape.keys()) maxUsedIndex = max(self.__tape.keys()) for i in range(minUsedIndex, maxUsedIndex): s += self.__tape[i] return s def __getItem__(self,index): if index in self.__tape: return self.__tape[index] else: return blank_symbol def __setItem__(self, pos, char): self.__tape[pos] = char class TuringMachine(object): def __init__(self, tape = "", blank_symbol = " ", tape_alphabet = ["0", "1"], initial_state = "", accepting_states = [], final_states = [], transition_function = {}): self.__tape = Tape(tape) self.__head_position = 0 self.__blank_symbol = blank_symbol self.__current_state = initial_state self.__transition_function = transition_function self.__tape_alphabet = tape_alphabet self.__final_states = final_states def showTape(self): print(self.__tape) return True def step(self): char_under_head = self.__tape[self.__head_position] x = (self.__current_state, char_under_head) if x in self.__transition_function: y = self.__transition_function[x] self.__tape[self.__head_position] = y[1] if y[2] == "R": self.__head_position += 1 elif y[2] == "L": self.__head_position -= 1 self.__current_state = y[0] def inFinal(self): if self.__current_state in self.__final_states: return True else: return False if __name__ == "__main__": # Test the class def quickTest( func, input, expected): if func(input) == expected: print(input, ": passed!") else: print(input, ": failed!")
########################### # a lambda in Python is just an anonymous function that has one or more arguments, but only one expression. ########################### # Syntax: # lambda arguments : expression # Example add_ten = lambda a : a + 10 print(type(add_ten)) # Prints <class 'function'> print(add_ten(5)) # Prints 15 my_list = [1, 8, 5, 2] sort_list = lambda x : sorted(x) result = sort_list(my_list) my_list.sort() print(my_list) # [1, 2, 5, 8] print(result) # [1, 2, 5, 8] def daily_activity(order, day, activity): return {'order': order, 'day': day, 'activity': activity} mon_activity = daily_activity(0, 'Mon', 'Baseball') tue_activity = daily_activity(1, 'Tue', 'Swim') wed_activity = daily_activity(2, 'Wed', 'Soccer') thu_activity0 = daily_activity(3, 'Thu', 'Basketball') thu_activity1 = daily_activity(4, 'Thu', 'Dance') thu_activity2 = daily_activity(5, 'Thu', 'Football') activities = [mon_activity, tue_activity, wed_activity, thu_activity0, thu_activity1, thu_activity2] # print(activities) # prints in one wrapable row def print_nice(val): for item in val: print(item) # to sort by a key value sorted_activities = sorted(activities, key= lambda x : x['order'], reverse = True) print(f' sort by activities') print_nice(sorted_activities) print(f' original') print_nice(activities) # to sort by more than one Key sorted_activities2 = sorted(activities, key = lambda x : (x['order'], x['activity']), reverse = True ) print(f" sort by \'order\' and then by \'activity\' ") print_nice(sorted_activities2) # the itemgetter function cna be used to represent the sequence of keys from operator import itemgetter sorted_activities3 = sorted(activities, key = itemgetter('day', 'activity'), reverse = True) print(f" sort by \'day\' and then by \'activity\' ") print_nice(sorted_activities3) # we can use a function to define the key as well def sort_keys(day): return (day['day']) sorted_activities4 = sorted(activities, key = sort_keys) print(f"sorted by \'day\'") print_nice(sorted_activities4)
"""Задача 0 Написать программу, запрашивающую у пользователя строку с текстом и разделитель. Необходимо вывести список слов с их длиной в начале слова, например, 5hello. Для каждой из пользовательских функций написать функцию-тест. """ def inp(): usstr = input("String here: ") r = input("Razdel: ") usstr = usstr.split(r) return usstr def count(ustr): #ustr = inp() print(ustr) for i in range(len(ustr)): # берет строку с длиной каждого слова(которые лежат в списке) ustr[i] = str(len(ustr[i])) + ustr[i] # и складывает с самим словом, которое тоже строка return ustr def tests(): if count(['saddsa', 'dsdsadsa', 'dsadsadsa']) == ['6saddsa', '8dsdsadsa', '9dsadsadsa']: print(count(['saddsa', 'dsdsadsa', 'dsadsadsa'])) print("tests are okay") else: print("errors") tests()
"""Задача 1 Дана целая матрица А(N,N). Составить программу подсчета среднего арифметического значения элементов матрицы. """ # input: [1, 2, 3], [1, 4, 5], [3, 8, 0] # output: ((1+2+3)/3 + (1+4+5)/3 + (3+8+0)/3)3 def make_matrix(): from random import randrange # Задаем матрицу через генератор n = int(input("Enter n: ")) # количество строк матрицы m = int(input("Enter m: ")) # кол-во эл-тов строки матрицы matrix = [[randrange(0, 10) for i in range(m)] for j in range(n)] return matrix def n_mid(): x = 0 matrix = make_matrix() for i in matrix: x += sum(i)/len(i) # считаю среднее арифметическое для каждой строки, сразу добавляя в общую сумму return x/len(matrix) def test_func(): try: print(n_mid()) print("Tests are okay") except ValueError: print("An error occured") test_func()
"""Задача 4* Дана квадратная матрица А(N,N). Составить программу подсчета количества отрицательных элементов, расположенных выше главной диагонали. """ def make_matrix(n=3): from random import randrange # n = int(input("Enter n: ")) matrix = [[randrange(-100, 100) for i in range(n)] for j in range(n)] d = [] # Главная диагональ -- проведена из левого верхнего,т.e 1 эл-ту 1-го столбца к for i in range(len(matrix)): # правому нижнему, т.e последнему эл-ту последнего стольца d.append(matrix[i][i]) print("Matrix is:", matrix) print("Diagonal is:", d) return matrix # Для 0-й строки проверяю каждый эл-т от [0+1] до [len()] # Для 1-й эл-ты [1+1] до [len()] # Для n-ной эл-ты [n+1] до [len()] def elements(): c = 0 i_num = 0 # т.к. диагональ не считается. Если бы считалась, то начал бы с -1 matrix = make_matrix() for i in range(len(matrix)): i_num += 1 for j in range(i_num, len(matrix[i])): # для каждой итерации j будет начинаться на 1 правее if matrix[i][j] < 0: c += 1 return c def test_fuct(): try: print("\nThe ammount of negative elements above the diagonal is/are:", elements()) print("\nTests are okay") except ValueError as err: print(err) print("\nAn error occured!") test_fuct()
# Задача 5. На вход поступают две строки. Необходимо выяснить, является ли вторая строка подстрокой первой. str1 = 'aaaaaaasdadasdsadsadasgsdfgfggsg' str2 = 'aaa' # 1 if str2 in str1: print(1) else: print(0)
""" Дана строка ‘Hello!Anthony!Have!A!Good!Day!’. Создать список, состоящий из отдельных слов[‘HELLO’, ‘ANTHONY’, ‘HAVE’, ‘A’, ‘GOOD’, ‘DAY’]. """ mystr = "Hello!How!Are!you?!" s = mystr.upper().split("!") s.remove("") print(s)
from urllib.request import Request from urllib.request import urlopen from urllib.error import HTTPError from urllib.error import URLError from bs4 import BeautifulSoup def converToSoup(url): ''' This function will parse the url to BeautifulSoup(BS) ''' try: urlRequest = Request(url,headers={'User-Agent':'Mozilla/6.0'}) urlOpen = urlopen(urlRequest) urlRead = urlOpen.read() urlClose = urlOpen.close() urlBSoup = BeautifulSoup(urlRead,"html.parser") return urlBSoup except HTTPError: print ("The server returned an HTTP error") except URLError: print ("The server could not be found") def getNewsInfo(urlBSoup): ''' This function will get title,author,date information ''' Title = urlBSoup.find("h1",{"class":"entry-title"}).text checkAuthorisNull = urlBSoup.find("div",{"id":"art_author"}) if checkAuthorisNull == None: Author = "" else: Author = checkAuthorisNull.text.replace("\n","") Date = urlBSoup.find("div",{"id":"art_plat"}).text NewsInfo = [Title,Author,Date] return NewsInfo def getWholeArticle(urlBSoup): ''' This function will get article's body. It also removes unwanted text after the <p> tag making use of the decompose method ''' soupBody = urlBSoup.findAll("div",{"id":"article_content"}) articleBody = soupBody[0].div for unwantedText in articleBody.findAll("div"): unwantedText.decompose() wholeArticle = articleBody.get_text() return wholeArticle def saveData(newsInfo,url,wholeArticle): ''' This function will save the scraped data to a text file ''' filename = newsInfo[0].replace(" ","_") + ".txt" f = open(filename,"w") f.write(newsInfo[0] + "\n") f.write(newsInfo[1] + "\n") f.write(newsInfo[2] + "\n") f.write(url + "\n") f.write(wholeArticle) f.close() return True def main(): # The url of the website we will scrape url="https://opinion.inquirer.net/117659/a-hard-hitting-biography-of-duterte" # This function (converToSoup) will convert the url to BeautifulSoup urlBSoup = converToSoup(url) # This function will get the title,author,date of the article newsInfo = getNewsInfo(urlBSoup) print (newsInfo) # This function will retrieve the content of the entire article wholeArticle = getWholeArticle(urlBSoup) print (wholeArticle) # This function will save the scraped data to a text file saveData(newsInfo,url,wholeArticle) main()
from datetime import date import Book # Receipt class # # Class to generate the receipt class Receipt: books = [] def add_book(self, book: Book, due_date=date.today()): self.books.append([book, due_date]) def remove_book(self, book: Book): self.books.remove(book) def generate_receipt(self): print("Receipt") for book, due_date in self.books: print(book) print("Due date: ", due_date)
from itertools import combinations """ Python ====== Your code will run inside a Python 2.7.13 sandbox. All tests will be run by calling the solution() function. Standard libraries are supported except for bz2, crypt, fcntl, mmap, pwd, pyexpat, select, signal, termios, thread, time, unicodedata, zipimport, zlib. Input/output operations are not allowed. Your solution must be under 32000 characters in length including new lines and and other non-printing characters. Please Pass the Coded Messages ============================== You need to pass a message to the bunny prisoners, but to avoid detection, the code you agreed to use is... obscure, to say the least. The bunnies are given food on standard-issue prison plates that are stamped with the numbers 0-9 for easier sorting, and you need to combine sets of plates to create the numbers in the code. The signal that a number is part of the code is that it is divisible by 3. You can do smaller numbers like 15 and 45 easily, but bigger numbers like 144 and 414 are a little trickier. Write a program to help yourself quickly create large numbers for use in the code, given a limited number of plates to work with. You have L, a list containing some digits (0 to 9). Write a function solution(L) which finds the largest number that can be made from some or all of these digits and is divisible by 3. If it is not possible to make such a number, return 0 as the solution. L will contain anywhere from 1 to 9 digits. The same digit may appear multiple times in the list, but each element in the list may only be used once. -- Python cases -- Input: solution.solution([3, 1, 4, 1]) Output: 4311 Input: solution.solution([3, 1, 4, 1, 5, 9]) Output: 94311 """ """ -L, a list of 0 to 9 - function is solution(L) - number must be divisible by 3 """ def solution(L): L.sort(reverse=True) for i in reversed(range(1, len(L) + 1)): for n in list(combinations(L, i)): if sum(n) % 3 == 0: return int(''.join(map(str, n))) return 0 print(solution([3, 1, 4, 1])) print(solution([3, 1, 4, 1, 5, 9]))
#2. """ #4. Convert degree celsius to fahrenheit #take input in degree celsius input1 = int(input("Enter temperatue in ˚C:")) print("temperature in fahrenheit is: "+str(input1*(9/5)+32)) """ """ #5. to check the palindrome def isPalindrome(string): str = string[::-1] #check whether str and string are the same if str == string: print(True) else: print(False) isPalindrome("malayalam") """ """ #6. to count the number of vowels in a string a = ['a','e','i','o','u','A','E','I','O','U'] b = input("Enter a string:") count = 0 not_a_vowel = 0 for i in b: if i in a: count = count+1 else: not_a_vowel = not_a_vowel+1 print("number of vowels is:"+str(count)) """ """ #7. to check the presence of substring in a string b = input("Enter something:") c = input("Enter substring:") if c in b: print(True) else: print(False) """ """ #8. slice and convert to float str = "X-DSPAM-Confidence:0.8475" i = str.find(":") res = str[i+1:] print(float(res)) """
#!/usr/bin/env python3 # An insecure password locker program. import sys import pyperclip PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6', 'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt', 'luggage': '12345'} if len(sys.argv) < 2: print('Copy account password to system clipboard') print('Usage: python3 password_locker.py [account]') sys.exit() account = sys.argv[1] if account in PASSWORDS: pyperclip.copy(PASSWORDS[account]) print(f'Password for {account} copied to clipboard.') else: print(f'There is no account named {account}.')
import numpy as np from scipy.optimize import fmin_cg class NeuralNetwork_Classifier(object): forwardProp = None def __init__(self,hidden_layers = [2]): self.hidden_layers_size = hidden_layers print(self.hidden_layers_size) def sigmoid(self,X): """ It returns the sigmoid function applied to the matrix X. X may have any shape. """ sig = 1/(1+np.exp(-X)) return sig def sigmoidGradient(self,X): """ It returns the derivative of the sigmoid function calculated at X. X is a matrix and may have any shape. """ sig_g = self.sigmoid(X)*(1-self.sigmoid(X)) return sig_g def Rand_param_Theta(self,In_value, Out_value): """ It returns a (Out_value x In_value+1) random matrix with small entries. """ epsilon_init = 0.12 Rand_param = np.random.rand(Out_value, In_value+1) * 2 * epsilon_init - epsilon_init return Rand_param def predict(self,nn_params, layers_data, X, min_class_pred = 0): """ The function returns a vector with the classification prediction for the set X. min_class_pred identify the smaller integer in the classification and must be adjusted accordingly to your classification labels. For instance if your labels are 1-10 you need to set min_class_pred =1. This is because the predictions are obtained from the indeces of a matrix and python as base index 0. By default it is setted on zero. """ Theta_vec = self.reshape_thetas(nn_params, layers_data) m = np.shape(X)[0] h_pred = [0 for i in range(len(Theta_vec)+1)] h_pred[0] = np.hstack((np.ones(m)[np.newaxis].T, X)) for i in range(len(h_pred)-1): h = self.sigmoid(h_pred[i]@Theta_vec[i].T) if i == len(h_pred)-2: h_pred[i+1] = h # h_pred[-1] is a (num_exp x num_label) matrix. The entry (i,j) contains the probabilities # that the i-th experiment is classified with label j else: h_pred[i+1] = np.hstack((np.ones(m)[np.newaxis].T, h)) return np.argmax(h_pred[-1],axis = 1)+min_class_pred def score(self,nn_params, X, Y): """ It return the accuracy of the Neural Network given the parameter vector nn_params, the expereiments matrix X and the label vector Y. """ X = np.array(X) Y = np.array(Y) input_layer_size = np.shape(X)[1] #recovering the input units from the experimental matrix num_labels = len(np.unique(Y)) #recovering the number of labels from the data stored in the label vector Y layers_data = [input_layer_size] + self.hidden_layers_size + [num_labels] # a vector that contains the info about the units of all the layers min_class_pred = np.unique(Y)[0] pred = self.predict(nn_params, layers_data, X, min_class_pred) if np.ndim(Y) ==1: Y = Y[np.newaxis] if np.shape(Y)[1] == 1: Y = Y.T # Reshape Y in a row vector in order to perform boolean operation return(pred == Y).mean() def reshape_thetas(self,nn_params,layers_data): """ Given a vector v and a list of integers L of lenght n it will returns a list of n-1 matrices exatrapolated by the vector v. The shape of a returned matrix is (j x (i+1)) where [...,i,j,..] are two consecutive entries of the list L. If it will not be possible automatically rise an Error. The order to reshape the matrices is F = Fortran. """ T_list = [] start_ind = 0 for m,n in zip(layers_data,layers_data[1:]): dum = np.reshape(nn_params[start_ind:start_ind+n*(m+1)], (n, m+1), order = 'F') T_list.append(dum) start_ind = start_ind + n*(m+1) return T_list def ForwardProp(self,nn_params, layers_data, X, Y, class_range = [0,1]): """ It compute the Forward Propagation of the Neural Network. It returns -a_vec : a vector containing the computed value of the units for each layer. Therefore a_vec[0] are the input units + bias, while a_vec[-1] are the outputs units without the bias to use in the activation function. - z_vec : contains the values of the activation function at each unit of the layer excluded the output ones. - Y : is a label Matrix of zeroes and ones. Column j has value 1 in i-th position if i is the value of the j-th entries of Y. If it is not a "row" vector it will be reshape into one - Theta_vec : is the list of the weights matrices. """ ### UTILITIES ### if self.forwardProp is None: Theta_vec = self.reshape_thetas(nn_params, layers_data) # recover the weights matrices from the weights vector m = np.shape(X)[0] # number of experiments min_class = class_range[0] # smallest value occurring in the classification max_class = class_range[-1] # larger alue occurring in the classification ### CLASSIFICATION MATRIX ### I = np.repeat([np.arange(min_class, max_class +1)],m,0).T # Classification Matrix if np.ndim(Y) == 1: Y = Y[np.newaxis] if np.shape(Y)[1] == 1: Y = Y.T # Reshape Y in a row vector in order to perform boolean operation Y = np.array(I == Y).astype(int) # Matrix of zeroes and ones of the labels. Column j has value 1 in i-th position if i is the value of the j-th entries of Y. ### FORWARD ROPAGATION ### J = 0 # Initialise the cost Function J a1 = np.hstack((np.ones(m)[np.newaxis].T, X)) # Add the bias Column at the Input Layer a_vec = [0 for i in range(len(layers_data))] # Initialise the units vector z_vec = [0 for i in range(len(layers_data)-1)] # Initialise the activation function vector a_vec[0] = a1.T for i in range(len(layers_data)-1): zi = Theta_vec[i]@a_vec[i] # comupte z(i) z_vec[i] = zi ai = self.sigmoid(zi) # Values of the unit at layer (i) mi = np.shape(ai)[1] if i != len(layers_data)-2: a_i_bias = np.vstack((np.ones(mi), ai)) # Add the Bias Column at the units a_vec[i+1] = a_i_bias else: a_vec[i+1] = ai forwardProp = a_vec, z_vec, Y,Theta_vec return forwardProp def cost_func_NN(self,nn_params, layers_data, X, Y, class_range = [0,1], Lambda =0): """ The function has input: - nn params : a vector of weights parameters - layers_data: a list containing the number of units at each layer (input and output included) - X : the training set matrix X - Y : the label vector Y -class_range (optional): is a list that contains the minimum and the maximum value of the classifier. The maximum value determines also how many values the Neural Network need to classify. By default it is setted as a binary 0,1 classifier. - J : the regularisation parameter, by default is zero The algorithm is vectorised and will return the value of the cost function J on the output layer. """ m = np.shape(X)[0] a,_,Y,Theta_vec = self.ForwardProp(nn_params, layers_data, X, Y, class_range) #computing the units values, the label matrix Y and the weights matrices a_out = a[-1] # the output units of the Neural Network reg = (Lambda/(2*m))*(sum([(Theta[:,1:]*Theta[:,1:]).sum() for Theta in Theta_vec])) #regolarisation factor J = (1/m) * (((-Y * np.log(a_out))-((1-Y) * np.log(1-a_out))).sum()) + reg #formula for the regularised cost function return(J) def grad_NN(self,nn_params,layers_data, X, Y, class_range = [0,1], Lambda =0): """ It compute the Backward Propagation and gradient of the Neural Network. The function as input - nn params : a vector of weights parameters - layers_data: a list containing the number of units at each layer (input and output included) - X : the training set matrix X - Y : the label vector Y -class_range (optional): is a list that contains the minimum and the maximum value of the classifier. The maximum value determines also how many values the Neural Network need to classify. By default it is setted as a binary 0,1 classifier. - Lambda : the regularisation parameter, by default is zero The output is a single vector containing all the unrolled gradients. This is because the fmin_cg accept only vectors and not matrices. """ m = np.shape(X)[0] a_vet,z,Y,Theta_vec = self.ForwardProp(nn_params, layers_data, X, Y, class_range) #computing the units values, the activated values z, the label matrix Y and the weights matrices self.forwardProp = None delta = [0 for i in range(len(layers_data)-1)] # initialise the little delta list for i in reversed(range(1,len(layers_data))): if i == len(layers_data)-1: delta[i-1] = a_vet[-1]-Y # this is the value of the delta_out else: delta[i-1]= (Theta_vec[i][:,1:].T@delta[i])*self.sigmoidGradient(z[i-1]) #formula for computing the inner delta. Delta = [0 for i in range(len(layers_data)-1)] # Initialise the big delta list. for i in reversed(range(0, len(layers_data)-1)): Delta[i] = delta[i]@a_vet[i].T # The entry i is a matrix with same shape of the weights matrix i reg_grad = [(Lambda/m)*(np.hstack((np.zeros(np.shape(Theta)[0])[np.newaxis].T, Theta[:,1:]))) for Theta in Theta_vec] #regularisation factors Theta_grad =[(1/m)*Del+reg for Del,reg in zip(Delta,reg_grad)] # list of gradient matrices grad_vec = np.concatenate([Theta_g.reshape(Theta_g.size,order = 'F') for Theta_g in Theta_grad]) #gradients vector ForwardProp = None return grad_vec def mini_batches(self,X,Y, num_batches = 1, strict_num_batches = True): """ The function will divides the trainining and labels sets into mini batches. The output is a list containing the mini batches and their respictevely labels. It takes input -X : is a training matrix. Each row is an experiment and each column is a feature. -Y : is a vector containing the labels of the experiments. -num_batches (optional): it is the number of mini batch you want create. By defaul it is 1, so tat it returns the entire training and label set -strict_num_batches(optional): if the required number of mini_batches does not split the training when True it will return num_batches mini batches with the last one bigger since contains the remaining value of X. If False it return num_batches+1 mini batches with the first num_batches dimensionally equals. """ if num_batches == 1: return [(X,Y)] else: ### INITIALISATION ### m = np.shape(X)[0] # Number of training examples if np.ndim(Y) ==1: Y = Y[np.newaxis] # we need to see a vector as a mx1 or 1xm matrix to perform the transpose if np.shape(Y)[1] != 1: # Y must be a column vector Y = Y.T full_data = np.hstack((X,Y)) np.random.shuffle(full_data) batch_size = m // num_batches # it returns the floor of m/num_batches batches = [0 for i in range(num_batches)] if m % num_batches ==0: creation_iter = num_batches flag = False else: creation_iter = num_batches +1 flag = True ### BATCHES CREATION ### for i in range(creation_iter): batch_i = full_data[i*batch_size:(i+1)*batch_size,:] X_i = batch_i[:,:-1] Y_i = batch_i[:,-1] if flag: if strict_num_batches and i+1 == num_batches: # if the number of batches does not split perfectly the training set batch_i = full_data[i*batch_size:,:] # then the last batch it will contains all the remaining values and X_i = batch_i[:,:-1] # the function it will return a list with num_batches entries Y_i = batch_i[:,-1] batches[i] = X_i,Y_i break elif i == num_batches: # if the number of batches does not split perfectly the training set batches.append((X_i,Y_i)) # then the function it will return a list with num_batches+1 entries break # with the first num_batches will be dimensional equal. batches[i] = X_i,Y_i return batches def grad_descent(self,nn_params, layers_data, X, Y, n_iters = 100, class_range = [0,1], learning_rate = 0.001, momentum = 0, Lambda = 0, num_batches = 1, strict_num_batches = True, verbose = True, SGD_history = False): """ Perform the Gradient descent Algorithm(s). It returns the vector of parameters obtained by the last iteration. The function receive input: - nn params : a vector of weights parameters - layers_data: a list containing the number of units at each layer (input and output included) - X : the training set matrix X - Y : the label vector Y - n_iter(optional): the number of iteration for the algorithm. By default is 100 -class_range (optional): is a list that contains the minimum and the maximum value of the classifier. The maximum value determines also how many values the Neural Network need to classify. By default it is setted as a binary 0,1 classifier. - learning_rate (optional): is the size of the step for the gradient descent algorithm. Usually referred as 'alpha'. By default is 0.01. - momentum (optional): is the rate to multiply the velocity vector. It is a float between 0 and 1. By default is zero so that the function perform a plain gradient descent. - Lambda (optional) : the regularisation parameter for the cost function and the gradient function. By default is zero - num_batches : it is the number of mini batches we want to extrapolate from the the training set. When setted as 1 it will perform the 'Batch Gradient Descent'. When it is equal to the number of training example the function will do the 'Stochastic Gradient Descent'. For intermediate value it will perform the 'Mini Batch Gradient Descent'. By default is setted to perform the Gradient Descent. - strict_num_batches : is a value to pass to the batch creation function. It will adjust the batches in the case the training set is not perfectly divisible by the choosen number of batches. """ if SGD_history: Theta_history = [0 for i in range(n_iters*num_batches)] Cost_history = [0 for i in range(n_iters*num_batches)] idx = 0 else: Theta_history = [0 for i in range(n_iters)] Cost_history = [0 for i in range(n_iters)] v = np.zeros_like(nn_params) for i in range(n_iters): m_batches = self.mini_batches(X,Y, num_batches, strict_num_batches) for batch in m_batches: X_i,Y_i = batch grad = self.grad_NN(nn_params,layers_data, X_i, Y_i, class_range, Lambda) # Derivative of the Cost Function v = momentum*v+ learning_rate*grad # computing the velocity vector nn_params = nn_params - v # updating the parameters if SGD_history: Cost_history[idx] = self.cost_func_NN(nn_params, layers_data, X_i, Y_i, class_range, Lambda) # storing the new value of the cost function Theta_history[idx] = nn_params idx+=1 else: Cost_history[i] = self.cost_func_NN(nn_params, layers_data, X_i, Y_i, class_range, Lambda) Theta_history[i] = nn_params if verbose: print('The value of the cost function is: {}'.format(Cost_history[i])) return nn_params, Cost_history, Theta_history def fit(self,X, Y, class_range =[0,1], Lambda = 0, max_iter = 50, optim_fun = 'fmin_cg', learning_rate = 0.01, momentum = 0, num_batches = 1, strict_num_batches = True, verbose = True, SGD_history = False): """ The function will train a Neural Network Classifier on your set X with labels in the vector Y. It returns a single vector that containing all the optimal weights for the classifier after max_iter iterations of the optimisation function fmin_cg. To use it for the prediction you need to reshape all the Weights matrix. The function reshape_thetas will do it for you. The function has input: -X : is a training matrix. Each row is an experiment and each column is a feature. -Y : is a vector containing the labels of the experiments. You have also the following options: -hidden_layers_sizes (optional): is a list that contains the numbers of units in each internal layer of the Neural Network. By default the Neural Network has a single internal layer with two units. More entries in the vector means more layers. -class_range (optional): is a list that contains the minimum and the maximum value of the classifier. The maximum value determines also how many values the Neural Network need to clssify. By default it is setted as a binary 0,1 classifier. -max_iter(optional): it determines the maximum number of iterations that the optimisation function -Lambda (optional): is the regularisation parameter. By default is zero. Increase the parameter if you are experiencing high variance or reduce it if you have high bias. -optim_fun (optional): You can choose the optimisation function to find the best weights parameters. At the moment you can give the value 'fmin_cg' (default value) and will use the fmin_cg function from the library scipy.optimize. Alternatively you can write 'GradDesc' and we will use our implementation of the Gradient Descent Algorithm. -learning_rate (optional): is the learning rate parameter 'alpha' for the Gradient Descent algorithm. By default is 0.01. - num_batches(optional): it is the number of mini batches we want to extrapolate from the the training set. When setted as 1 it will perform the 'Batch Gradient Descent'. When it is equal to the number of training example the function will do the 'Stochastic Gradient Descent'. For intermediate value it will perform the 'Mini Batch Gradient Descent'. By default is setted to perform the Gradient Descent. - strict_num_batches(optional) : is a value to pass to the batch creation function. It will adjust the batches in the case the training set is not perfectly divisible by the choosen number of batches. """ X = np.array(X) Y = np.array(Y) #### UTILITIES #### input_layer_size = np.shape(X)[1] #recovering the input units from the experimental matrix num_labels = len(np.unique(Y)) #recovering the number of labels from the data stored in the label vector Y layers_data = [input_layer_size] + self.hidden_layers_size + [num_labels] # a list that contains the info about the units of all the layers #### INITIALISATION OF THE PARAMETERS #### Thetas = [self.Rand_param_Theta(i,j) for i,j in zip(layers_data,layers_data[1:])] #random initialisation of the layers matrices Weights nn_params_init = np.concatenate([Theta_p.reshape(Theta_p.size,order = 'F') for Theta_p in Thetas]) #it creates a vector with all the entries of the Weights #### FITTING OF THE NEURAL NETWORK #### if optim_fun == 'fmin_cg': args = (layers_data, X, Y, class_range, Lambda) #arguments to pass to the functions xopt = fmin_cg(self.cost_func_NN, x0 = nn_params_init, fprime = self.grad_NN, args = args, maxiter = max_iter) #computes the optimal Weights vector return xopt elif optim_fun == 'GradDesc': if num_batches > np.shape(X)[0]: print('Error: Number of batches bigger than number of training examples') return None xopt, Cost_history, Theta_history = self.grad_descent(nn_params_init, layers_data, X, Y, max_iter, class_range, learning_rate, momentum, Lambda, num_batches, strict_num_batches, verbose, SGD_history) return xopt, Cost_history, Theta_history
# https://www.reddit.com/r/dailyprogrammer/comments/8bh8dh/20180411_challenge_356_intermediate_goldbachs/ def goldbach_weak_conjecture(*args): for n in args: if n % 2 == 0 or n < 6: print("Illegal argument") return -1 def find_primes(n): l = [] for i in range(2, n): is_prime = True for j in range(2, i): if i%j == 0: is_prime = False if is_prime: l.append(i) return l for n in args: list_of_primes = find_primes(n) for i in range(len(list_of_primes)): for j in range(i, len(list_of_primes)): for k in range(j, len(list_of_primes)): if list_of_primes[i] + list_of_primes[j] + list_of_primes[k] == n: print("{} = {} + {} + {}".format(n, list_of_primes[j], list_of_primes[i], list_of_primes[k]))
import unittest import numpy as np from LogisticRegression import LogisticRegressionClassifier class Test(unittest.TestCase): def test_sigmoid(self): # Creating object of classifier for unit testing lrs = LogisticRegressionClassifier() print("test_sigmoid") # Checking if values for sigmoid are between 0 and 1 # testing with positive and negative numbers which are varied. self.assertEqual(lrs.sigmoid(100), 1) self.assertEqual(lrs.sigmoid(1), 0.7310585786300049) self.assertEqual(lrs.sigmoid(2), 0.8807970779778823) self.assertEqual(lrs.sigmoid(3), 0.9525741268224334) self.assertEqual(lrs.sigmoid(0.1), 0.52497918747894) self.assertEqual(lrs.sigmoid(-1), 0.2689414213699951) def test_loss(self): lrs = LogisticRegressionClassifier() print("test_loss") # Testing for correct log loss output from cost function. self.assertAlmostEqual(lrs.loss(0,0), -0.0000099999) self.assertAlmostEqual(lrs.loss(1,1), -0.0000099999) self.assertAlmostEqual(lrs.loss(0.5,1), 0.69312718) self.assertAlmostEqual(lrs.loss(0.5,0), 0.69312718) def test_prediction(self): lrs = LogisticRegressionClassifier() # Testing prediction when classifier is not trained print("test_prediction when not trained") self.assertEqual(lrs.predict(0.222), None) lrs.weight = np.zeros(1) print("test_prediction when trained") # Testing prediction when classifier has some weight self.assertEqual(lrs.predict(0.222), 0) # simulating trained weights. lrs.weight += 0.3 self.assertEqual(lrs.predict(0.222), 1) def test_gradientD(self): lrs = LogisticRegressionClassifier() print("test_gradient") # Test case for when max iterations are 0. lrs.iterations = 0 self.assertEqual(lrs.fit(np.array([0]),1), None) lrs.iterations = 10 # Checking correct update of weights for network. lrs.fit(np.array([[0.4, 0.5],[0.2,0.3]]),np.array([1,0])) self.assertAlmostEqual(lrs.weight[0],0.04872931) self.assertAlmostEqual(lrs.weight[1],0.04834258) if __name__ == '__main__': unittest.main()
# 第二章 CSV文件 # comma-separated value 逗号分隔值 #=======读写CSV文件========================================================= # #---------------------------------------------------------------- # input_file = 'supplier_data.csv' # output_file = 'output_1.csv' # with open(input_file,'r',newline='') as filereader: # with open(output_file,'w',newline='') as filewriter: # header = filereader.readline() # header = header.strip() # header_list = header.split(',') # print(header_list) # filewriter.write(','.join(map(str,header_list))+'\n') # # map() 将str()应用于 header_list中每个元素 确保每个元素都是字符串 # # join() 在header_list中每个值之间插一个逗号 将列表转换为一个字符串 # for row in filereader: # row = row.strip() # row_list = row.split(',') # print(row_list) # filewriter.write(','.join(map(str,row_list))+'\n') #---------------------------------------------------------------- #======pandas 处理CSV========================================================== # pd.read_csv() data_frame.to_csv() #---------------------------------------------------------------- # import pandas as pd # input_file = 'supplier_data.csv' # output_file = 'output_pandas.csv' # data_frame = pd.read_csv(input_file) # 数据框 # print(data_frame) # data_frame.to_csv(output_file, index=False) #---------------------------------------------------------------- #======读写CSV文件(二)========================================================== # Python内置csv模块 csv.reader() csv.writer() .writerow() #---------------------------------------------------------------- # import csv # input_file = 'supplier_data.csv' # output_file = 'output_2.csv' # with open(input_file,'r',newline='') as csv_in_file: # with open(output_file,'w',newline='') as csv_out_file: # filereader = csv.reader(csv_in_file,delimiter=',',quotechar='"') # filewriter = csv.writer(csv_out_file,delimiter=',') # delimiter 分隔符 # for row_list in filereader: # print(row_list) # filewriter.writerow(row_list) # #---------------------------------------------------------------- #======筛选行========================================================== # for row in filereader: # if value in row meets some business rule or set of rules: # do something # else: # do something #---------------------------------------------------------------- #---------------------------------------------------------------- #======筛选行中的值满足某个条件========================================================== # python csv #---------------------------------------------------------------- # import csv # input_file = 'supplier_data.csv' # output_file = 'output_3.csv' # with open(input_file,'r',newline='') as csv_in_file: # 如果不指定newline='',则每写入一行将有一空行被写入。 # with open(output_file,'w',newline='') as csv_out_file: # filereader = csv.reader(csv_in_file) # filewriter = csv.writer(csv_out_file) # header = next(filereader) # next() 读取文件的第一行 # filewriter.writerow(header) # for row_list in filereader: # suppiler = str(row_list[0]).strip() # cost = str(row_list[3].strip('$').replace(',','')) # if suppiler == 'Suppiler Z' or float(cost) > 600.0: # filewriter.writerow(row_list) #---------------------------------------------------------------- #=======筛选行中的值满足某个条件========================================================= # pandas .loc() 设置筛选条件 #---------------------------------------------------------------- # import pandas as pd # input_file = 'supplier_data.csv' # output_file = 'output_pandas_3.csv' # data_frame = pd.read_csv(input_file) # # data_frame['Cost'] = data_frame['Cost'].str.strip('$').str.replace(',','').astype(float) # 直接改变['Cost']的内容 # cost = data_frame['Cost'].str.strip('$').str.replace(',','').astype(float) # 保留原始格式 # data_frame_value_meets_condition = data_frame.loc[(data_frame['Supplier Name'].str.contains('Z'))|(cost >600.0),:] # print(data_frame_value_meets_condition) # data_frame_value_meets_condition.to_csv(output_file,index=False) #---------------------------------------------------------------- #=======筛选行中的值属于某个集合========================================================= # python csv #---------------------------------------------------------------- # import csv # input_file = 'supplier_data.csv' # output_file = 'output_4.csv' # important_dates = ['1/20/14', '1/30/14'] # with open(input_file,'r',newline='') as csv_in_file: # 如果不指定newline='',则每写入一行将有一空行被写入。 # with open(output_file,'w',newline='') as csv_out_file: # filereader = csv.reader(csv_in_file) # filewriter = csv.writer(csv_out_file) # header = next(filereader) # next() 读取文件的第一行 # filewriter.writerow(header) # for row_list in filereader: # a_data = row_list[4] # if a_data in important_dates: # filewriter.writerow(row_list) #---------------------------------------------------------------- #========筛选行中的值属于某个集合======================================================== # pandas isin() #---------------------------------------------------------------- # import pandas as pd # input_file = 'supplier_data.csv' # output_file = 'output_pandas_4.csv' # data_frame = pd.read_csv(input_file) # important_dates = ['1/20/14', '1/30/14'] # data_frame_value_in_set = data_frame.loc[data_frame['Purchase Date'].isin(important_dates),:] # print(data_frame_value_in_set) # data_frame_value_in_set.to_csv(output_file,index=False) #---------------------------------------------------------------- #=======行中的值匹配于某个模式\正则表达式========================================================= # python csv #---------------------------------------------------------------- # import csv # import re # input_file = 'supplier_data.csv' # output_file = 'output_5.csv' # # ?P<my_pattern_group> 捕获了名为<my_p_g>的组中匹配了的子字符串 不知道这句目前有什么用 # # ^001-.* ^:只在字符串开头搜索模式 .:匹配任何字符,除了换行符 *:重复前面的字符0次或更多次 # # 即 .* 组合 表示除换行符意外的任何字符出现 # # 参数 re.I 正则表达式进行大小写敏感匹配 # pattern = re.compile(r'(?P<my_pattern_group>^001-.*)',re.I) # with open(input_file,'r',newline='') as csv_in_file: # with open(output_file,'w',newline='') as csv_out_file: # filereader = csv.reader(csv_in_file) # filewriter = csv.writer(csv_out_file) # header = next(filereader) # filewriter.writerow(header) # for row_list in filereader: # invoice_number = row_list[1] # if pattern.search(invoice_number): # filewriter.writerow(row_list) # print(row_list) #---------------------------------------------------------------- #========行中的值匹配于某个模式\正则表达式======================================================== # pandas startswith() 进行搜索数据 #---------------------------------------------------------------- # import pandas as pd # input_file = 'supplier_data.csv' # output_file = 'output_pandas_5.csv' # data_frame = pd.read_csv(input_file) # data_frame_value_matches_pattern = data_frame.loc[data_frame['Invoice Number'].str.startswith("001-"),:] # data_frame_value_matches_pattern.to_csv(output_file,index=False) # print(data_frame_value_matches_pattern) #---------------------------------------------------------------- #======选取特定的列========================================================== # 1.使用列索引值 # 2.使用列标题 #---------------------------------------------------------------- #---------------------------------------------------------------- #======列索引值========================================================== # python #---------------------------------------------------------------- # import csv # input_file = 'supplier_data.csv' # output_file = 'output_6.csv' # my_columns = [0,3] # with open(input_file,'r',newline='') as csv_in_file: # with open(output_file,'w',newline='') as csv_out_file: # filereader = csv.reader(csv_in_file) # filewriter = csv.writer(csv_out_file) # for row_list in filereader: # row_list_ouput = [] # for index_value in my_columns: # row_list_ouput.append(row_list[index_value]) # filewriter.writerow(row_list_ouput) # print(row_list_ouput) #---------------------------------------------------------------- #========列索引值======================================================== # pandas iloc[] 根据索引位置选取列 #---------------------------------------------------------------- # import pandas as pd # input_file = 'supplier_data.csv' # output_file = 'output_pandas_6.csv' # data_frame = pd.read_csv(input_file) # data_frame_column_by_index = data_frame.iloc[:,[0,3]] # data_frame_column_by_index.to_csv(output_file,index=False) # print(data_frame_column_by_index) #---------------------------------------------------------------- #========列标题======================================================== # python 思想:通过标题行的关键词 得到索引值 #---------------------------------------------------------------- # import csv # input_file = 'supplier_data.csv' # output_file = 'output_7.csv' # my_columns = ['Invoice Number','Purchase Date'] # my_columns_index = [] # with open(input_file,'r',newline='') as csv_in_file: # with open(output_file,'w',newline='') as csv_out_file: # filereader = csv.reader(csv_in_file) # filewriter = csv.writer(csv_out_file) # header = next(filereader,None) # for index_value in range(len(header)): # if header[index_value] in my_columns: # my_columns_index.append(index_value) # 得到索引值 # filewriter.writerow(my_columns) # print(my_columns) # for row_list in filereader: # row_list_ouput = [] # for index_value in my_columns_index: # row_list_ouput.append(row_list[index_value]) # filewriter.writerow(row_list_ouput) # print(row_list_ouput) #---------------------------------------------------------------- #========列标题======================================================== # pandas lic[] 选取列 #---------------------------------------------------------------- # import pandas as pd # input_file = 'supplier_data.csv' # output_file = 'output_pandas_7.csv' # data_frame = pd.read_csv(input_file) # data_frame_column_by_name = data_frame.loc[:,['Invoice Number','Purchase Date']] # data_frame_column_by_name.to_csv(output_file,index=False) # print(data_frame_column_by_name) #---------------------------------------------------------------- #=======选取连续的行========================================================= # python row_counter 来跟踪行编号 #---------------------------------------------------------------- # import csv # input_file = 'supplier_data_unnecessary_header_footer.csv' # output_file = 'output_8.csv' # row_counter = 0 # with open(input_file,'r',newline='') as csv_in_file: # with open(output_file,'w',newline='') as csv_out_file: # filereader = csv.reader(csv_in_file) # filewriter = csv.writer(csv_out_file) # for row in filereader: # if row_counter >=3 and row_counter <=15: # filewriter.writerow([value.strip() for value in row]) # print(row_counter,[value.strip() for value in row]) # row_counter += 1 #---------------------------------------------------------------- #=======选取连续的行========================================================= # pandas drop() 根据索引的行、列标题来丢弃行或列 # iloc[] 根据行索引选取一个单独的行作为列索引 # reindex() 为数据框重新生成索引 #---------------------------------------------------------------- # import pandas as pd # input_file = 'supplier_data_unnecessary_header_footer.csv' # output_file = 'output_pandas_8.csv' # data_frame = pd.read_csv(input_file, header=None) # 不读取header # data_frame = data_frame.drop([0,1,2,16,17,18]) # data_frame.columns = data_frame.iloc[0] # # data_frame = data_frame.reindex(data_frame.index.drop(3)) # data_frame.to_csv(output_file,index=False) # print(data_frame) #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #---------------------------------------------------------------- #================================================================ # #---------------------------------------------------------------- #----------------------------------------------------------------
class Punkt: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"POINT ({self.x} {self.y})" def __int__(self): return f"POINT ({self.x} {self.y})" # ------------------------------------- a = Punkt(2,3) print(a) # <__main__.Punkt object at 0x000002851A29D190> #b = Punkt(4,5) #print(b) ##print(str(b)) #c = int(a) #print(c)
from copy import deepcopy class Board: """Represents a chess board which keeps track of positions where a queen can be placed.""" def __init__(self, n, allowed=None): """Initialize board dimension and allowed positions.""" assert isinstance(n, int), "Size must be an integer" assert n > 0, "Size must be positive" self.dim = n if allowed is None: self.allowed = [[True for _ in range(n)] for _ in range(n)] else: self.allowed = allowed def place(self, position): """Try to place a queen on the given position and return a new board. If the queen cannot be placed, return False. Otherwise, return a new board which has the board state of the queen being in that position plus the previous state. """ x, y = position if not self.allowed[x][y]: return False updated = deepcopy(self.allowed) # Update horizontally and vertically for i in range(self.dim): updated[x][i] = False updated[i][y] = False # Update diagonally directions = [(1, 1), (1, -1), (-1, 1), (-1, 1)] for xdir, ydir in directions: row, col = x, y while row < self.dim and col < self.dim and row >= 0 and col >= 0: updated[row][col] = False row += xdir col += ydir return Board(self.dim, allowed=updated) def valid_positions(self, row): """Return a list of valid positions for a given row.""" return [(row, col) for col in range(self.dim) if self.allowed[row][col]] def nqueen(board, positions=[], row=0): """Solve the n-queen puzzle recursively for a given board.""" valids = board.valid_positions(row) if not valids: return False, None for valid in valids: # Try to find a solution with queen in this position new_board = board.place(valid) positions.append(valid) if row == board.dim - 1: return True, positions found, final_positions = nqueen(new_board, positions=positions, row=row + 1) if found: return True, final_positions # There was no solution, keep trying positions.pop() # No solution found with the given board return False, None def main(): """Prompt the user for a board size and solve the n-queen puzzle for that board.""" size = input("Grid size: ") size = int(size) board = Board(size) found, positions = nqueen(board) if not found: print("No solution found") else: print("Queen positions:", positions) if __name__ == "__main__": main()
import numpy as np import pandas as pd #n = input("Enter an integer:") #for i in range(n): # print(n) my_matrix = np.identity(5) second_matrix = np.random.random(size(5,4)) print(my_matrix, second_matrix)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 4 18:16:54 2020 @author: luismanuelalvarez """ class Estudiante: def __init__(self,nombre,edad=16): self.nombre = nombre self.edad = edad def devuelve_datos(self): if(self.edad > 18): return "El estudiante"+ self.nombre + " con edad "+ str(self.edad) +" es mayor de edad" return "El estudiante " + self.nombre + " Es menor de edad" if __name__ == '__main__': a1 = Estudiante('Manuel', 30) print(a1.devuelve_datos())
import random """ Chapter 1.10 """ print() print() print("self_check_1:") # the answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i'] wordlist = ['cat', 'dog', 'rabbit'] letterlist = [] for aword in wordlist: for aletter in aword: if aletter not in letterlist: letterlist.append(aletter) print(letterlist) print() print("self_check_2:") # the answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't'] awordlist = ['cat', 'dog', 'rabbit'] aletterlist = [letter for word in awordlist for letter in word] print(aletterlist) print("extra challege:") aletter_set = set(aletterlist) new_letterlist = [letter for letter in aletter_set] print(new_letterlist) print() print("self_check_3:") quote = "methinks it is like a weasel" # goal string qlen = 28 # length of quote def monkey(qlen): alphabet = "abcdefghijklmnopqrstuvwxyz " res = "" for i in range(qlen): res = res + alphabet[random.randrange(27)] return res print(monkey(qlen)) print("self_check_3 Challenge:") def luck(quote, guess): num_same = 0 for i in range(qlen): if quote == guess[i]: num_same += 1 return num_same / qlen def lucky_monkey(): new_guess = monkey(qlen) best = 0 count = 0 mluck = luck(quote, new_guess) while mluck < 1 or count < 10: if mluck > best: print(mluck, new_guess) best = mluck count += 1 new_guess = monkey(qlen) mluck = luck(quote, new_guess) print(new_guess) # lucky_monkey() print("not working but I realized I didn't need to do this one anyway...")
import re import string def count_me(): freq = {} file_obj = open('count.txt', 'r') word_content = file_obj.read().lower() reg_exp = re.findall(r'\b[a-z]{3,15}\b', word_content) for word in reg_exp: count = freq.get(word, 0) freq[word] = count + 1 freq_list = freq.keys() for word in freq_list: print word, freq[word] if __name__ == '__main__': count_me()
import numpy as np #Do not import any other libraries """ Write a function that takes a two dimensional array, and returns another two dimensional array where the columns of the array are the Z scores of the columns in the original array. You should do question 2 before doing this question. For example, suppose arr = array([[4.,2.,-3.], [3.,7.,11.], [13.,6.,2.], [2.,-9.,8.]]) Then f(arr) should return array([[-0.34188173, 0.07881104, -1.38675049], [-0.56980288, 0.86692145, 1.20185043], [ 1.70940865, 0.70929937, -0.46225016], [-0.79772404, -1.65503185, 0.64715023]]) If you are going to test this function, make sure to use an array of floats rather than an array of integers. Otherwise you may run into rounding issues. """ def f(arr): ##########YOUR CODE HERE########## pass ###########END CODE############### if __name__=='__main__': ######CREATE TEST CASES HERE###### pass ##################################
import numpy as np import pandas as pd #Do not import any other libraries """ Write a function that takes a pandas dataframe, df as input. df is assumed to have the columns col_1 and col_2. df will have missing values (NaNs) in both columns. The function should return the dataframe but with the missing values in col_1 replaced with the mean value within col_1 and have the rows with missing values in col_2 dropped. Note that the order that these operations are done matters. Dropping the rows with missing values first will remove some entries and thus change the mean value in col_1. Make sure that the NaNs in col_1 are replaced with the mean value first and then drop the rows with NaNs in col_2. This function should not actually mutate df but instead return a different version of it. You can create a copy of df within the function by using the built in copy() method if you wish. There is a file in this repo called testdf7.csv. Loading this dataframe into memory and running f(df) should return col_1 col_2 0 1.0 2.0 2 6.6 6.0 3 7.0 8.0 5 6.6 12.0 6 13.0 14.0 """ def f(df): ##########YOUR CODE HERE########## pass ###########END CODE############### if __name__=='__main__': ######CREATE TEST CASES HERE###### pass ##################################
#!/usr/bin/env python3 # Wankyu Choi (c) 2014 # For Creative Works of Knowledge Python Training # for loop and iterators: custom iterator def my_year_range(start, end, step=1): """ iterator should yield resulting value """ result = start while result < end: yield result result += step def my_year_range_with_bug(start, end, step=1): """ return breaks the code """ result = start while result < end: return result # the following line will never run result += step def main(): """program entry point """ start = 1800 end = 2014 step = 1 per_line = 10 year = start count = 1 for year in my_year_range(start, end+1): end_char = "\n" if count % per_line == 0 else "\t" print(year, end=end_char) year += step count += 1 if __name__ == '__main__': main()
#program to find the sum of contiguous subarray of numbers that has the largest sum def maxSubArraySum(arr): size = len(arr) if size == 0: return 0 max_so_far = float('-inf') max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + arr[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far if __name__ == '__main__': arr = [-4, 2, 2, -5, 8, 4, 3] print(maxSubArraySum(arr))
"""All messages.""" class Messages: """Class message.""" def __init__(self): """Init.""" self.message = "" def set_message(self, message): """Add.""" self.message = message def get_message(self): """Get and clear the messages.""" msg = self.message self.message = "" return msg def exists(self): """Return true if there is a message.""" return bool(self.message) messages = Messages()