blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
5c33bc4253bbc6b29bbd097e7a98c0c1c33863ce
kimmothy/PuzzleSolver
/puzzle_solver/BlockPuzzle.py
2,375
3.59375
4
from puzzle_solver.Puzzle import Puzzle class BlockPuzzle(Puzzle): def isValidate(self, newPosition, movedBlockIndex): rowNum = len(self.field) colNum = len(self.field[0]) block = newPosition[movedBlockIndex] if ["position", newPosition] in self.visited: return False for cell in block: if cell[0] < 0 or cell[0] >= rowNum: return False elif cell[1] < 0 or cell[1] >= colNum: return False elif self.field[cell[0]][cell[1]] == 0: return False for otherIndex, otherBlock in enumerate(newPosition): if otherIndex == movedBlockIndex: continue elif cell in otherBlock: return False return True def getWays(self): ways = [] up = lambda x: [x[0]-1, x[1]] down = lambda x: [x[0]+1, x[1]] left = lambda x: [x[0], x[1]-1] right = lambda x: [x[0], x[1]+1] directions = {"up":up, "down": down, "left":left, "right":right} for index, block in enumerate(self.position): for d in directions.keys(): newPosition = self.position.copy() movedBlock = list(map(directions[d], block)) newPosition[index] = movedBlock if self.isValidate(newPosition, index): recordMove = str(index) + d ways.append((recordMove, newPosition)) return ways if __name__ == "__main__": field = [[0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], ] firstPosition = [[[0, 2], [0, 3], [1, 2], [1, 3]], [[3, 1], [3, 2], [4, 2]], [[3, 3], [3, 4], [4, 3]], [[4, 1], [5, 1], [5, 2]], [[4, 4], [5, 3], [5, 4]], [[6, 2], [6, 3]] ] goal = lambda position: position[0][0] == (6,2) # container = "Stack" container = "Queue" myPuzzle = BlockPuzzle(firstPosition, goal, container, field) moving, moveNum = myPuzzle.solve() print("이동횟수",moveNum) print("이동경로", moving)
13e89dfbc2ba6c54ce9a6309cf128fddf843a7a2
AakSin/CS-Practical-FIle
/Reference/Lab Reference/PC 2/List Worksheet/q9.py
260
3.703125
4
a=["hello","mello","trello"] b=["chellp","nello","mello"] def common(a,b): s=[] for i in a: s.append(i) for i in b: s.append(i) for i in s: if s.count(i)>1: return True break print(common(a,b))
1a46aeae63884ccacbc343f53e0da6d9f7068b9c
pagesofpages/python-pdf
/PdfText.py
24,720
3.515625
4
# PdfText.py """ Classes for managing the production of formatted text, i.e. a chapter. PdfChapter() PdfParagraph() PdfString() """ from PdfDoc import PdfDocument from PdfFontMetrics import PdfFontMetrics import math # global metrics = PdfFontMetrics() FNfontkey = 'F3' FNfontsize = 5 FONTMarker = '^' # function copied from stackoverflow # https://stackoverflow.com/questions/28777219/basic-program-to-convert-integer-to-roman-numerals from collections import OrderedDict def write_roman(num): roman = OrderedDict() roman[1000] = "M" roman[900] = "CM" roman[500] = "D" roman[400] = "CD" roman[100] = "C" roman[90] = "XC" roman[50] = "L" roman[40] = "XL" roman[10] = "X" roman[9] = "IX" roman[5] = "V" roman[4] = "IV" roman[1] = "I" def roman_num(num): for r in roman.keys(): x, y = divmod(num, r) yield roman[r] * x num -= (r * x) if num <= 0: break return "".join([a for a in roman_num(num)]).lower() class TextFont( object ): """ Simple data structure to hold font name and size Fonts are the standard pdf fonts F1, F2, F3, with I and B varians, Times Roman F3 Italic F3I Bold F3B F1: Courier] [F2: Helvetica] [F3: Times-Roman] """ def __init__(self, pname, psize): """ Example: f = TextFont('F3',10) """ self.name = pname self.size = psize def __str__( self): return 'TextFont("' + self.name+'",'+str(self.size)+')' def asItalic( self): """ Return a new TextFont, which is a italic version of self """ return TextFont( self.name[0:2]+'I', self.size) def asBold(self): """ Return a copy of self as a bold font """ return TextFont( self.name[0:2]+'I', self.size) def asNormal(self): """ Return a copy of self as a plain font, not italic or bold """ return TextFont( self.name[0:2], self.size) class PdfChapter( object ): """ PdfChapter is the container for stand-alone amount of formatted text, such as a chapter of text. It may have headings, multiple paragraphs, and changes of font within a section of text such as a paragraph. It begins with a new page and terminates with an end page. PdfParagraphs are added to self.paragraphs list PdfPages are later constructed from the list of PdfParagraphs A chapter may have a standard header, stored as a paragraph in self.header A chapter may have a footer, set via a very limited method, and later converted into a paragraph. instance variables: """ def __init__( self, doc ): """ Initializer for PdfChapter The PDFDoc instance passed as <doc> should be already initialized. chapter printing starts at a new page """ self.pdf = doc self.paragraphs = [] self.pages = [] self.initialPageNumber = 0 # modify this to start with something other than 1 self.runningPageNumber = 0 # this increments as pages are produced # printed page number is initialPageNumber + runningPageNumber self.header = None # a header is a PdfParagraph() self.headerSkip = None # flag to skip the first page when printing a header self.footerStyle = None self.footerFont = None self.footer = None self.footnotes = [] # self.footnoteFont = TextFont('F3',7) self.superscriptFont = TextFont('F3',5) # dimensional info extracted from PdfDocument, may be overridden self.lineHeightFactor = doc.lineHeightFactor self.leftMargin = doc.getLeftMargin('p') self.rightMargin = doc.getRightMargin('p') self.lineWidth = doc.getLineWidth('p') self.topRow = doc.getTopMargin('p') self.bottomRow = self.getBottomMargin('p') def nxtFootnoteNbr( self ): """ Return the next available footnote number. """ return len(self.footnotes) + 1 def addFootnote(self, fnote): """ Add a PdfFoontnote() to the chapter list """ assert fnote is PdfFootnote self.footnotes.append( fnote ) def getFootnote(self, nbr): """ Get the <nbr>th footnote. Footnote 2 is expected to be in self.footnotes[1] """ assert len(self.footnotes) >= nbr - 1 assert self.footnotes[ ngr - 1].fnNum == nbr return self.footnotes[nbr - 1] def footnoteParagraph(self, fnNbr): """ Construct a paragraph from the chapter's <fnNbr>th footnote. generate an exception if it does not exist """ fn = self.getFootnote( nbr) para = PdfParagraph( self ) para.indent = 0 para.lead = 0 para.tail = 0 def footerParagraph(self, pageNumber): """ Construct a paragraph that will print the footer Return None is there is no footer. Since page number may be printed, it must be called for each page. """ ret = None if self.footerStyle is not None: para = PdfParagraph() para.tail = 0 para.indent = 0 if self.footerType == 'RomanRight': para.alignment = 'r' para.addString( self.footerFont, write_roman( page_number)) para.buildLines(self) return para def setFooterStyle(self, pStyle, font): """ define the chapter footer, such as setFooterStyle( 'RomanRight', TextFont('F3',9)) """ assert pStyle in [ 'RomanRight','None'], "Unknown footer style: "+pStyle assert font is TextFont self.footerStyle = pStyle self.footerFont = font def footerDepth( self ): """ Return the depth, in points, of the footer. """ ret = 0 if self.footerStyle is not None: ret = 2 * self.footerFont.size * self.lineHeightFactor return ret def addParagraph( self, para): """ Add <para> to the list of paragraphs """ assert para is PdfParagraph self.paragraphs.append( para ) def setHeader( self, pheader, pskipFirst ): """ add the header - it is a paragraph repeated on each page, except maybe the first """ assert header is PdfParagrah self.header = pheader self.headerSkip = pskipFirst def headerDepth(self): """ return the number of points required for the optional header. A header is just a paragraph so is """ if self.header is None: return 0 else: self.header.depth() def lineWidth(self): """ return the width of a line (without paragraph-specific modifications) for a chapter """ ret = self.pdf.getLineWidth('p') def buildPages(): """ construct a list of PdfPage() """ self.pages = [] self.runningPageNumber = 0 done = False paraCtr = -1 page = None r = self.topRow # end row should be constant other than for footnotes er = self.bottomRow - self.footerDepth() for para in self.paragraphs: if page is None: # we need a new page self.runningPageNumber++ fnDepth = 0 page = PdfPage( self, self.runningPageNumber + self.initialPageNumber) # add the header for ln in while not done: self.runningPageNumber++ page = PdfPage( self, self.runningPageNumber + self.initialPageNumber) fnDepth = 0 # track footnote depth as footnotes are added to the page # the page hdrLines and ftrLines are populated # the first addressable body line is the bottom hdrline + header.tail # now start to consume paragraphs r = self.topRow + self.headerDepth() # end row is the start of the footer, adjusted for optional footnotes # (when implemented) er = chapter.bottomRow - self.footerDepth() def print(self): """ A paragraphs have been added. header and footer defined. Perform the sequence of steps to print. for each paragraph execute para.buildLines(), i.e. self.buildLines execute self.buildPages() for each page execute page.print() """ for para in self.paragrahs: para.buildLines(self) self.header.buildLines() self.buildLines() self.buildPages() self.printPages() # ****** def prepare( self ): # calculate the total length, in points, of all strings in all paragraphs. linewidth = self.pdf.getLineWidth('p') # print(' Building lines of length '+ str( linewidth )) for para in self.paragraphs: # length of each string. Probably redundant. for s in para.strings: s.length = metrics.strLength( s.fontkey, s.fontsize, s.string ) # now within each paragragh, build lines - which may be multiple strings or # more often may be subsections of strings. para.buildLines( linewidth ) def newPage(self ): """ uses Chapter().pdf to invoke a new page in the pdf document. Increments pagenumber sets chapter prow and pcol to 0 """ self.pdf.newPage() # is there a header string? self.pageNumber += 1 self.prow = 0 self.pcol = 0 def endPage(self, footNotesCtr = 0, fnOrd = 1): if footNotesCtr > 0: print('printing footnotes') self.footnotes.printFootNotes( footNotesCtr, fnOrd, self.prow ) # ef printFootNotes( self, qty, firstNum, pRow): if self.footerStyle is None: pass elif self.footerStyle == 'RomanRight': s = write_roman(self.pageNumber) br = self.pdf.getBottomRow('p') rc = self.pdf.getLineWidth('p') self.pdf.write( rc,br, s,'r','p') self.pdf.endPage() def process(self ): """ PdfChapter.process( PdfDoc ) Print the chapter. Start a new page at the beginning. End whatever page is current at the end """ # self.newPage( ) self.pdf.setTextState() # go paragraph by paragraph, lines by lines. initial = True self.lineIncrement = self.pdf.lineHeight * self.pdf.lineHeightFactor for para in self.paragraphs: para.printParagraph( self ) self.endPage( ) def stretch(self, lns, amt): """ insert spaces until the length of the set to strings has been increased by <amt> points. """ ret = [] amtToAdd = amt while amtToAdd > 2: for l in lns: ol = l.length l.stretch( amtToAdd ) # retuce amtToAdd by the increase in length of the string amtToAdd = amtToAdd - ( l.length - ol ) if amtToAdd <= 2 : break; return lns class PdfParagraph( object ): """ PdfParagraph represents a body of text. It may be one-line, such as a chapter (or section) header, it may be a long paragraph. It contains of a list of PdfString objects- it may contain one string, it may contain many. For all of its components, they are produced sequentially and share the same justification: left, center, right, full l c r f A chapter heading would often be one short line of text, in a larger or more distinct font, and centered. Properties: alignment [ 'l','c','r','j'] indent points tail points lead points strings = [] lines = None or [] """ def __init__( self, chapter, lineHeightFactor = 1.2, alignment = 'l', indent = 0, tail = 10 ): """ all elements in a PdfParagraph share the same justification. <indent> is used for the first line of text. It is in points. <tail> moves the chapter row counter down tail points """ assert alignment in [ 'l','c','r','j'] assert chapter is PdfChapter self.chapter = chapter self.lineHeightFactor = lineHeightFactor self.alignment = alignment self.indent = indent self.tail = tail self.lead = 0 self.strings = [] self.lines = None def setIndent(self, pIndent): self.indent = pIndent def setAlignment(self, pAlignment): self.alignment = pAlignment def setJustification( self, pJustification): self.justification = pJustification def setLineHeightFactor( self, pLineHeightFactor ): self.lineHeightFactor = pLineHeightFactor def setTail(self, pTail): self.tail = pTail def setLead(self, pLead): self.lead = plead def depth( self): if self.lines is None: self.buildLines() ret = 0 for ln in self.lines: ret += ln.depth() * self.lineHeightFactor ret += (self.tail + self.lead) return ret def addString(self, pfont, pstring, pfootnotes = None): """ Construct a PdfString from the parameters and add to the strings list <pfootnotes> may be None (the dault) or a list of strings. Uses chapter.nxtFootnoteNbr() """ assert pfont is TextFont if pfootnotes is None: self.strings.append( PdfString( pfont, pstring ) else: # split the string on the ^ charactert txt = pstring.split('^') # the string should be in a list with 1 more element than there are footnotes assert len(txt) = len(pfootnotes) + 1 i = None for i in range(0,len(pstring)) # the first string is split self.strings.append( PdfString(pfont, txt[i])) num = self.chapter.nxtFootnoteNbr() # add the superscript self.strings.append( PdfStringFN( chapter.superscriptFont, str(num))) fn = PdfFootnote( num, pstring[i] # add the ending string is it exists if len(txt[-1]) > 0: self.strings.append( PdfString( pfont, txt[-1])) def buildLines( self, chapter ): """ This method takes all of the strings and breaks them up fit within individual lines. The end result is an array of PdfLine() lines that each fit on a single line regardless of font changes (within reason). It does this by splitting PdfStrings that overflow a line into multiple shorter PdfStrings. And combing short strings. Each PdfLine contains one or more PdfStrings, so be printed on the same line. The lines[] attribute contains a list of PdfLines. These will have the col value set, the row will be None while owned by a PdfParagraph. Within a paragraph the first line may have an indent, and therefore e shorter If the next string is a PdfStringFN then it is added no matter what. """ workingLine = PdfLine(None, chapter.leftMargin - self.indent) self.lines = [] linewidth = chapter.lineWidth workingLen = 0 # spaceLen = metrics.strLength(self.fontkey, self.fontsize, ' ') ctr = 0 ps = None # the first line of a paragraph may have an indent. targetlen = linewidth - self.indent worklingLine.col = lm for s in self.strings: ps = s.split2( targetlen ) workingLine.addString(ps) targetlen = targetlen - ps.length # print('added '+ps.string+' new targetlen is '+str(targetlen)) # we are at the end if a line when s.length > 0 # is s.length == 0 then the current line may not be full while s.length > 0: self.lines.append( workingLine ) lm = chapter.leftMargin workingLine = PdfLine( None, chapter.lm) targetlen = chapter.lineWidth ps = s.split2( targetlen ) targetlen = targetlen - ps.length workingLine.addString( ps ) # at this point s is consumed. targetlen is reduced as necessary, The # next string - perhaps in a different font - may fit, in full or in part # on the same line if targetlen < 10: self.lines.append( pdfLine ) workingLine = PdfLine( None, chapter.leftMargin) targetlen = chapter.lineWidth if len(workingLine.strings) > 0: self.lines.append( workingLine ) # now fully populated para.lines with PdfLine() instances def documentLines(self): """ print out the complete lines with total length for each """ for ln in self.lines: s = '' x = 0 for l in ln.strings: s += l.string x += l.length print( "{:4.0f}".format(x)+": "+s) def printParagraph(self, chapter): """ <chapter> is a PdfChapter. It is needed because it has access to endPage() and newPage() methods. And it tracks the chapter page number. chapter().pdf is a pdfDoc which is used for the printing. This method prints the paragraphs, beginning at the current row and at column 0. If there is insufficient room for one or more rows then the chapter.endPage() and chapter.newPage() methods are invoked. """ # self.documentLines() if self.lines is None: self.buildLines(doc.getLineWidth('p')) self.pcol = self.indent firstLine = True lineCount = len( self.lines ) lineCtr = 0 fnCtr = 0 # footnote counter for ln in self.lines: lineCtr += 1 if chapter.prow >= chapter.pdf.getBottomRow('p') - (chapter.footerLines() * (chapter.lineIncrement)) - chapter.footnotes.height(fnCtr): chapter.endPage( fnCtr ) fnCtr = 0 chapter.newPage( ) if firstLine: chapter.pcol = self.indent firstLine = False else: chapter.prow += chapter.lineIncrement if firstLine: chapter.pcol = self.indent firstLine = False else: chapter.pcol = 0 # how many point in this line lnlen = 0 # calculate the length of the line, after removing any trailing spaces # from the end of the ln ln[-1].setString( ln[-1].string.rstrip()) for l in ln: lnlen += l.length gap = chapter.pdf.getLineWidth('p') - lnlen if lineCtr == 1: gap = gap - self.indent if self.alignment == 'c': # bump pcol by half the difference between string length and line length chapter.pcol = gap / 2 elif self.alignment == 'r': chapter.pcol = gap elif self.alignment == 'j': # need to allocate gap among Strings # unless it is the last line if lineCtr < lineCount: ln = chapter.stretch( ln, gap) for l in ln: # each line [ ln ] in self.lines is a list of 1 or more print statements, all to # be on the same line. If there are multiple print statements they probably # use different fonts # set position to next Line f = l.string.count('^') if f > 0: print('footnote found in '+l.string) chapter.pdf.setFont( l.fontkey, l.fontsize ) chapter.pdf.write(chapter.pcol, chapter.prow , l.string, 'l','p') chapter.pcol += l.length if self.tail > 0: chapter.prow += self.tail * chapter.lineIncrement class PdfString( object ): """ PDFString is a continuous bit of text in a common font. It may end with a footnote. """ def __init__( self, pfont, pstring): """ Initialize a new string, invoke setLength() """ assert pfont is TextFont self.fontkey = pfont.name self.fontsize = pfont.size self.string = string self.setLength() def setLength(self): """ set the length property based on metrics.strLenth """ self.length = metrics.strLength( self.fontkey, self.fontsize, self.string) def depth(self): """ the depth of a string - not very useful - is simply the fontize """ return self.fontsize def setString(self, t): """ reset the string property with <t> and invoke self.setLength() """ self.string = t self.setLength() def split2(self, strLen): """ Splits a string. Returns a new PdfString that has a string <= strLen Modifes self, removing that portion of the string. 1. if the length of the string is 0 then it returns None 2. If the length is < <strLen> then it returns a clone of itself, and sets itself to an empty string of length 0 3. If there is no space in self.string then the same as #2 above 4. If the very first word in self.string is longer than strLen then it returns a PdfString with that first word. So if self.string is not empty then it returns a string of some length that may be greater than strLen """ ret = None if len(self.string) == 0: return None elif self.length <= strLen: ret = PdfString( TextFont(self.fontkey, self.fontsize), self.string) self.setString('') elif self.string.find(' ') < 0: ret = PdfString( TextFont(self.fontkey, self.fontsize), self.string) self.setString('') else: # build a new string. wrkStr = self.string newStr = '' newLen = 0 # if there is some content and at least 1 space return the characters # up to and including the first space no matter now long newStr = wrkStr[ 0: wrkStr.find(' ')+ 1] wrkStr = wrkStr[ wrkStr.find(' ')+ 1 :] newLen = metrics.strLength( self.fontkey, self.fontsize, newStr) while newLen < strLen and len(wrkStr) > 0: nxtStr = wrkStr[ 0: wrkStr.find(' ')+1] nxtLen = metrics.strLength(self.fontkey,self.fontsize, nxtStr) if newLen + nxtLen <= strLen: newStr += nxtStr newLen += nxtLen wrkStr = wrkStr[ wrkStr.find(' ')+1 :] else: # print('Could not fit in' + str(nxtLen)) break ret = PdfString( TextFont( self.fontkey, self.fontsize ) , newStr) ret.setLength() self.setString( wrkStr) self.setLength() return ret class PdfStringFN( PdfString ): """ Inherits from PdfString. Font is set """ def __init__( self, pfont, pstring): """ passes through to super class """ PfdString.__init__(self, pfont,pstring) class PdfLine( object): """ # a PdfLine is a collection of strings that are to be output on the same row. Methods: footnoteCount() getFootNote(<nPos>) setPos(r,c) addString( pdfString ) height() print() Properties row col strings [] length """ def __init__(self, prow = None, pcol = none): """ properties self.row self.col self.strings = [] self.length = 0 """ self.row = pRow self.col = pCol self.strings = [] self.length = 0 def footnoteCount(self): """ Return the count of footnotes present in the line. Footnotes are identified by being a PdfStringFN type """ ret = 0 for s in self.strings: if s is PdfStringFN: ret++ return ret def getFootnote( nPos ): """ Returns an int, or None Return the footnote number of the footnote in the <nPos> position. The first footnote by position in a string might be footnote number 7, if it is the 7th footnote registered in the chapter. The value is returned as an int. """ ret = None ctr = 0 for s in self.strings: if s is PdfStringFN: ctr++ if ctr == nPos: ret = int(s.string) break return ret def setPos( self, r, c): """ Set self.row and self.col """ self.row = r self.col = c def addString(self, pdfString): """ add a PdfString to self.strings, and reset self.length """ assert pdfString is PdfString self.strings.append( pdfString) self.length += pdfString.length def height(self): """ height is the maximum height found in strings """ ret = 0 for s in self.strings: ret = max(ret, s.fontsize) return ret def print(self, doc): """ print the line of text using the <doc> PdfDocument methods """ r = self.row c - self.col for s in self.strings doc.write( c, r, s.string,'l','p') c += s.length # ##### def findChars(self, c ): """ return a list of the indexes of all occurrences of <c> in self.string. May be useful for full justification """ ret = [] for i in range(0, len(self.string)): if self.string[i] == c: ret.append(i) return ret def stretch(self, amt): """ loop though self.string once, adding spaces to existing spaces, until the string has been traversed or each space has been padded once. So will not necessarily stretch the string to the full amount. The <amt> to be added may be spread among multiple strings. """ spaceLen = metrics.strLength( self.fontkey, self.fontsize, ' ') added = 0 newStr = '' if amt < 2: return self elif self.length < 10: return self for c in self.string: if c == ' ' and added < amt : newStr += c + ' ' added += spaceLen else: newStr += c self.setString( newStr ) class PdfPage(object): """ a single printable page """ def __init__(self, chapter, pageNumber): """ Initializes a new pasge. writes out hdrlines to self.hdrLines, starting at chapter.topRow writes out foot lines at chapter.bottomRow bdyLines is an empty list. <pageNUmber> is the number to print. """ self.footnoteCount = 0 self.pageNumber = pageNumber self.bdyLines = [] self.hdrLines = [] self.ftrLines = [] # add the header lines. Starting point is chapter.topRow lctr = 0 for ln in self.header.lines: lctr++ ln.row = chapter.topRow + lctr - 1 self.hdrLines.append( ln ) # create a footer paragraph if self.footerStyle is not None: para = chapter.footerParagraph( self.pageNumber ) for ln in para.lines: ln.row = chapter.bottomRow self.ftrLines.append( ln) class PdfFootNote( PdfParagraph): """ Inherits from PdfParagraph(), but hard-codes most spacing properties """ def __init__(self, chapter, fnNum): """ fnNum is the footnote number That is created in chapter.superscriptFont as the first string in the paragraph. """ self.chapter = chapter self.fnNum = fnNum self.lead = 0 self.tail = 0 self.indent = 0 self.alignment = 'l' self.strings = [] self.lines = [] self.strings.append ( PdfString( self.chapter.superscriptFont, str(fnNum)) ) def addString(self, pString): """ Add a string to a footnote """ self.strings.append( PdfString(self.chapter.footnoteFont, pString)) def addItalic( self, pString): """ Add an italic string to a footnote """ self.strings.append( PdfString(self.chapter.footnoteFont.asItalic(), pString)) def addBold( self, pString): """ Add a bold font string to a footnote """ self.strings.append( PdfString(self.chapter.footnoteFont.asBold(), pString))
d361b0228f4c84bb2b244eb616db13ebe8c20a85
cessor/httpcache
/httpcache.py
1,700
3.765625
4
'''Downloads websites and caches them in a sqlite3 database. If the page was downloaded before, it retrieves it from the cache. I used this to retrieve websites that lock you out if you request the same page too often. Free software. Use and change. Improve and distribute. Give credit. Be excellent to each other. Author, Johannes Feb 2017, http://cessor.de Todo: I need a better name for this. ''' from httpcache.cache import Cache from httpcache.store import Store from httpcache.download import Download from httpcache.folder import Folder import fire import requests @fire.Fire class HttpCache(object): '''Downloads and caches websites.''' def __init__(self): self.cache = Cache( store=Store(), session=Download(requests.Session()), folder=Folder() ) def clear(self): '''Clear cache (removes all data)''' with self.cache as cache: prompt = 'Clear cache? This deletes all cached urls.\nYes / No> ' answer = input(prompt) answer = answer.strip().lower() if answer and answer in ['y', 'yes']: cache.clear() print('Cache cleared.') return def get(self, *urls): with self.cache as cache: for url in urls: record = cache.get(url) print(record.content) def list(self): '''Lists urls in cache as <url>, <status_code>, <Content-Type>, <timestamp>''' with self.cache as cache: cache.list() def remove(self, *urls): '''Removes urls''' with self.cache as cache: for url in urls: cache.remove(url)
6dfa6d5f334ab128930a8f3f0c3728a6bce16953
alex-dsouza777/Python-Basics
/Project 2 - The Perfect Guess/main.py
1,179
4.46875
4
'''We are going to write a program that generates a random number and asks the user to guess it. If the player’s guess is higher than the actual number, the program displays “Lower number please”. Similarly, if the user’s guess is too low, the program prints “higher number please”. When the user guesses the correct number, the program displays the number of guesses the player used to arrive at the number. Hint: Use the random module''' import random randNumber = random.randint(1, 10) # print(randNumber) userGuess = None guesses = 0 while(userGuess != randNumber): userGuess = int(input("Enter Your Hint: ")) guesses += 1 if(userGuess == randNumber): print("You guessed it right") else: if(userGuess>randNumber): print("You guessed it wrong. Enter a smaller number") else: print("You guessed it wrong. Enter a larger number") print(f"You guessed the number in {guesses} guesses") with open("highscore.txt", "r") as f: highscore = int(f.read()) if(guesses<highscore): print("You broke the highscore") with open("highscore.txt", "w") as f: f.write(str(guesses))
875fe898427f0ce88c1ef75674acc3ff5f225b15
ietuday/python-pratice-1-cont
/test/binary_search.py
496
3.9375
4
#!/usr/bin/env python3 def binary_search(arr, item): beg = 0 end = len(arr) - 1 while beg <= end: mid = beg + end // 2 if arr[mid] == item: return (mid + 1) elif arr[mid] < item: beg = mid + 1 else: end = mid - 1 return -1 def main(): arr = [int(ele) for ele in input().split()] ele = int(input()) print(ele, 'found at', binary_search(arr, ele), 'position') if __name__ == '__main__': main()
31cf0599ac31c623f18133f01af35716e7200685
thuurzz/Python
/faculd_impacta/tec_prg_1sem/exercicios_py/aula_01/exerc_02.py
258
3.875
4
print('ola, digite uma quantidade em metros e ela sera convertida para miliímetros!') metros = float(input('valor em metros: ')) milimetros = (metros)*1000 print('você digitou:', metros, 'metros, este valor em milímetros é:', milimetros, 'milímetros.')
a5382b37d2bcd1d99600a932ecaf3e7158d6d0be
Holit/XlsxToCsv
/ExcelProtocolHandler.py
3,331
3.578125
4
import xlrd import csv import sys import os if __name__ == '__main__': if len(sys.argv) == 1: print("illegal argument, try again.") elif len(sys.argv[1]) == 0: print("illegal argument, try again.") elif sys.argv[1] == "--help" or sys.argv[1] == "-h": print(""" Excel file handler A simple program which helps transformed into csv or other file, which is much more simple to analysis.Sheets will be saved as name '... - SheetN.csv' this will create some files to storage all data Due to some problems in Microsoft Excel (R), csv file is encoded as UTF-8 BOM, which program cannot write with, you may need to trans file from utf-8 to utf-8 BOM. For any issues or bugs, please go to github and report. This is an executable version (winPE-32/.exe) which disabled the exit() code. For open-source version, please check https://github.com/Holit/XlsxToCsv -----------------------Copyright (c) 2020 Jerry------------------------------- usage: eph [-h|-c|-p|--help|--csv|--print] {filename} -h --help Print this screen -c --csv trans to .csv (Comma-Separated Values) YOU MAY NEED TO TRANS FILE FROM UTF-8 TO UTF-8 BOM. THIS IS A BUG OF EXCEL WHEN PROCESSING CSV {filename} file name """) elif sys.argv[1] == "--csv" or sys.argv[1] == "-c": if len(sys.argv) != 3: print("illegal input file : null file") elif not(os.path.exists(sys.argv[2])): print("illegal input file : there's no such file named " + sys.argv[2]) elif not(os.access(sys.argv[2],os.R_OK)): print("illegal input file : access failed at " + sys.argv[2]) elif not(os.path.splitext(sys.argv[2])[-1][1:] == "xlsx" or os.path.splitext(sys.argv[2])[-1][1:] == "xls"): print("illegal input file : is not a excel-based file") else: try: workbook = xlrd.open_workbook(sys.argv[2]) i = 1 for table in workbook.sheets(): csv_file_name = os.path.splitext(sys.argv[2])[0] csv_file_name = csv_file_name + " - " + table.name csv_file_name += ".csv" if(os.path.exists(csv_file_name)): os.remove(csv_file_name) nrows = table.nrows ncols = table.ncols for rows_read in range(1,nrows): row_value = [] for cols_read in range(ncols): ctype = table.cell(rows_read, cols_read).ctype nu_str = table.cell(rows_read, cols_read).value if ctype == 2: nu_str = int(nu_str) row_value.append(nu_str) with open(csv_file_name, 'a', encoding='utf-8',newline='') as f: write = csv.writer(f) write.writerow(row_value) i = i +1 print('Succeed, proceed ' + str(i) + ' sheets \n You may need to use excel to trans encoding from utf-8 to utf-8 BOM') except Exception as e: print("Unexcepted error occured: " + str(e))
4299f97b11357f07cf7cca438e5164579b28f749
Ranjanpaul66/python_practie
/practice_1.py
1,225
4.21875
4
# 1) Write the following function’s body. A nested dictionary is passed as parameter. You need to print all keys with their depth. # Sample Input: a = { 'key1': 1, 'key2': { 'key3': 1, 'key4': { 'key5': 4, 'key6':{ 'key7':8, 'key8':0 }, 'key10':7, 'key11':{ 'key22':9 } } } } # Sample Output: # key1 1 # key2 1 # key3 2 # key4 2 # so on def print_depth(data): new_list = [(data, list(data.keys()))] # print(new_list) while len(new_list): dic, keys_list = new_list.pop() # print('dic_values',dic) # print('key_list_values',keys_list) while len(keys_list): key, keys_list = keys_list[0], keys_list[1:] # print(len(new_list)) print(key, len(new_list) + 1) value = dic[key] # print(value) if isinstance(value, dict): new_list.append((dic, keys_list)) new_list.append((value, list(value.keys()))) break print_depth(a)
64122eb49f6ab72e11f6bd7042de7088c8a117d1
Swathi-Swaminathan/Swathi-Swaminathan
/5.6.21(pattern and iteration)/Display string.py
190
4.375
4
#Python program to display string in right angle triangle str=input("Enter the name:") b=len(str) for i in range(b): for j in range(i+1): print(str[j],end="") print()
d5c73e410bddf2da22905c5a183d92e737db8f89
ZunLayNwe12/GitSample
/Tuple.py
559
4.1875
4
#Tuple Tuple - () t = 12345, 54321, 'hello' t[0] t #tuples may be nested: u = t , (1, 2, 3, 4, 5) u #Tuples are immutable: cannot be replaced t[0] = 88888 # but they contain mutable objects: v = ([1, 2, 3], [3, 2, 1]) v fruits = ("apples", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(fruits[2:5]) #change Tuples value x = ("apples", "banana", "cherry", "orange") y = list(x) y[1] = "mango" x = tuple(y) x fruits = ("apples", "banana", "cherry", "orange", "kiwi", "melon", "mango") x[4] = "pineapple" fruits >>>Set
7598155aa8cc4867847b1c0fcc4802d319d78d65
hirobel/todoapp
/4_src/3_other/1_surasura-python/q2-5/q2-5.py
65
3.625
4
number = 10 print('number(10) + 5 = {}'.format(str(number)+'5'))
cc9133502e0695e4c83800f322f9921aad4ae259
IvanWoo/coding-interview-questions
/puzzles/reverse_vowels_of_a_string.py
1,109
4.125
4
# https://leetcode.com/problems/reverse-vowels-of-a-string/ """ Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Input: "hello" Output: "holle" Example 2: Input: "leetcode" Output: "leotcede" Note: The vowels does not include the letter "y". """ def reverse_vowels(s: str) -> str: VOWELS = set("aeiou") s_l = list(s) lo, hi = 0, len(s_l) - 1 while lo < hi: if s_l[lo].lower() in VOWELS and s_l[hi].lower() in VOWELS: s_l[lo], s_l[hi] = s_l[hi], s_l[lo] lo += 1 hi -= 1 while s_l[lo].lower() not in VOWELS and lo < hi: lo += 1 while s_l[hi].lower() not in VOWELS and lo < hi: hi -= 1 return "".join(s_l) def reverse_vowels(s: str) -> str: ans = list(s) vowel_idxs = [i for i, char in enumerate(s) if char.lower() in "aeiou"] left, right = 0, len(vowel_idxs) - 1 while left < right: i, j = vowel_idxs[left], vowel_idxs[right] ans[i], ans[j] = ans[j], ans[i] left += 1 right -= 1 return "".join(ans)
5eca0fbb7c53205a9e7313a1e78386d96d9f59e3
ahwang1995/Cracking-the-Code
/Chapter 1/oneAway.py
617
3.875
4
#check two strings are one or zero edits away def oneAway(str1,str2): #make sure the lengths of the strings don't differ bby more than one diff = abs(len(str1) - len(str2)) if diff > 1: return False list1 = list(str1) list2 = list(str2) diff2 = 0 #remove matching characters from each list one at a time while(len(list1) > 0 & len(list2) > 0): for c in list1: if c in list2: list1.remove(c) list2.remove(c) #if the two list's differ by a length greater than one then return false if abs(len(list1)-len(list2)) > 1: return False return abs(len(list1)-len(list2)) < 2 print oneAway("a","ab")
75ae3a5c451438b8c288d46ceb39f154a9b19f14
karlicoss/kython
/kython/__init__.py
1,155
4.0625
4
from functools import wraps from .misc import * # https://stackoverflow.com/a/12377059/706389 def listify(fn=None, wrapper=list): """ A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the function should return an list. Example:: >>> @listify ... def get_lengths(iterable): ... for i in iterable: ... yield len(i) >>> get_lengths(["spam", "eggs"]) [4, 4] >>> >>> @listify(wrapper=tuple) ... def get_lengths_tuple(iterable): ... for i in iterable: ... yield len(i) >>> get_lengths_tuple(["foo", "bar"]) (3, 3) """ def listify_return(fn): @wraps(fn) def listify_helper(*args, **kw): return wrapper(fn(*args, **kw)) return listify_helper if fn is None: return listify_return return listify_return(fn) def dictify(fn=None, key=None, value=None): def md(it): return make_dict(it, key=key, value=value) return listify(fn=fn, wrapper=md)
040f37ad9bd59cd2770d0a5d0c1c6cc395370b56
L4sse/smart_uebung
/Test.pu.py
221
4.09375
4
x = 3 y = 4 operation = raw_input("Bitte geben Sie wie folg ein, + - / ") if operation == "+": print x + y elif operation == "-": print x - y elif operation == "/": print x / y else == "*": print x * y
028e73aab6a25145064048c00eb5d9f35d8037c1
PriyaRcodes/Threading-Arduino-Tasks
/multi-threading-locks.py
995
4.375
4
''' Multi Threading using Locks This involves 3 threads excluding the main thread. ''' import threading import time lock = threading.Lock() def Fact(n): lock.acquire() print('Thread 1 started ') f = 1 for i in range(n,0,-1): f = f*i print('Factorial of',n,'=',f) lock.release() def Square(n): lock.acquire() print('Thread 2 started ') sq = n*n print('Square of',n,'=',sq) lock.release() def Task(): print('Thread 3 started ') time.sleep(1) #represents any task that takes 1 sec print('Task done') print('This is the main thread') n = int(input('Enter a number: ')) start_time = time.time() T1 = threading.Thread(target=Fact,args=(n,)) T2 = threading.Thread(target=Square,args=(n,)) T3 = threading.Thread(target=Task) T1.start() T2.start() T3.start() T1.join() T2.join() T3.join() print('All threads have been closed') print('Processing time taken: ',time.time()-start_time,'seconds')
9ec3b2b3b7478f7632e13dc506cda74b1e386b28
anushatsatish/File-Processing-The-Payroll-Program
/Lab5_AnushaSatish_Main.py
1,443
3.78125
4
import Lab5_AnushaSatish_Function function_file = Lab5_AnushaSatish_Function def main(): print('**' * 50) print(' ' * 25, "Employee Operations") print('**' * 50) choice = function_file.menu() print(choice) while choice != 6: if choice == 1: function_file.print_all() choice = function_file.menu() elif choice == 2: find_fname = input('Enter in a FName to search employee') find_lname = input('Enter in a LName to search employee') find_emp = find_fname + " " + find_lname function_file.print_emp(find_emp) choice = function_file.menu() elif choice == 3: function_file.add_emp() choice = function_file.menu() elif choice == 4: del_fame = input('Enter in a FName to delete employee') del_lname = input('Enter in a LName to delete employee') del_emp = del_fame + " " + del_lname function_file.delete_emp(del_emp) choice = function_file.menu() elif choice == 5: mod_fname = input('Enter in a FName to modify employee') mod_lname = input('Enter in a LName to modify employee') mod_emp = mod_fname + " " + mod_lname function_file.modify_emp(mod_emp) choice = function_file.menu() function_file.exit_app() if __name__ == "__main__": main()
4cadd9bb2ec39561ad3ce2d2b4cc3028b3548860
minghao2016/AutoBlast
/util/util.py
975
3.765625
4
import os def show_header(title): print "\n" multiply_asterisk = 95 print '#'*multiply_asterisk number_of_remaining_sharp = multiply_asterisk - len(title) put_this_number_of_sharp = int(int(number_of_remaining_sharp)/2) print '#'*(put_this_number_of_sharp-1) + " " + title + " " + '#'*(put_this_number_of_sharp-1) print '#'*multiply_asterisk ########### end of show_header function def show_time(process, time_start, time_end): time_took = str(process) + " finished in " if (round((time_end-time_start)/60, 1) < 1): time_took = time_took + str(round((time_end-time_start), 1)) + " seconds " elif (round((time_end-time_start)/60/60, 1) < 1): time_took = time_took + str(round((time_end-time_start)/60, 1)) + " minutes " else: time_took = time_took + str(round((time_end-time_start)/60/60, 1)) + " hours " time_took = time_took + "(wallclock)." return time_took ############### end of show_time function
717c5d99e6895b2be2b22faa9e7554a066b17e77
mgavrin/games
/Battleship AI/battleship-5.py
21,103
3.515625
4
import pygame from pygame.locals import * import random from random import * import math from math import * pygame.init() class Grid: def __init__(self,location,name,dim,game): #Unpack location into x and y co-ordinates of upper left corner self.base_x=location[0] self.base_y=location[1] self.dim=dim self.name=name self.game=game self.game.boards.append(self) self.lines=self.game.lines self.shiplist=[] self.shipcount=0 self.time_to_sink=[] self.turn_counter=0 self.count_status=False #and now to creat the board state memory #The goal of this code is to create a boad of dimensions dim by dim # The end result below would result with dim=3 # [ [0,0,0] # [0,0,0] # [0,0,0] ]temp=0 self.board=[] temp=0 while temp<dim: tmp=0 row=[] while tmp<dim: row.append(0) tmp+=1 self.board.append(row) temp+=1 #Create a temporary state matrix that can be modified without changing permanent matrix self.tempBoard=[] temp=0 while temp<dim: tmp=0 row=[] while tmp<dim: row.append(0) tmp+=1 self.tempBoard.append(row) temp+=1 #Construct lines self.box=30.0 #box side length in pixels #Vertical lines temp=0 while temp<=self.dim: x=self.base_x+temp*self.box self.lines.append([(x, self.base_y), (x, self.base_y+self.box*dim), (0,0,0)]) temp+=1 #Horizontal lines temp=0 while temp<=self.dim: y=self.base_y+temp*self.box self.lines.append([(self.base_x, y), (self.base_x+self.box*dim,y), (0,0,0)]) temp+=1 def genTemp(self, board=False): #If fed another Grid instance "board," updates board as guess board #If board is unspecified, defaults to False and updates temp state from perm state for ship in self.shiplist: sunk=True for square in ship: squareVal=self.board[square[0]][square[1]] if squareVal!=2: sunk=False elif squareVal==2: if self.count_status==False: self.count_status=True if sunk==True: self.turn_counter+=1 self.time_to_sink.append(self.turn_counter) self.turn_counter=0 self.count_status=False for square in ship: self.board[square[0]][square[1]]=3 self.shipcount-=1 if board!=False: for row in range(0,self.dim): for col in range(0,self.dim): boardVal=board.board[row][col] if boardVal==1 or boardVal==2 or boardVal==3: self.tempBoard[row][col]=boardVal else: self.tempBoard[row][col]=self.board[row][col] else: for row in range(0,self.dim): for col in range(0,self.dim): self.tempBoard[row][col]=self.board[row][col] def Update(self): #Updates the host rects list with data on each square on the board. #Data is taken from temp state matrix, not permanent one (changed 8/5/2012) #Stores this as a list item with the folowing format: # [ Pygame Rect of square , value of square ] #Updates top to bottom, left to right col=0 while col<self.dim: row=0 while row<self.dim: x=self.base_x+self.box*col y=self.base_y+self.box*row value=self.tempBoard[row][col] rect=Rect(x,y,self.box,self.box) #x, y of corner, width, height self.game.rects.append([rect, value]) row+=1 col+=1 def addShip(self, points): shipZone=[] (start,end)=points #Pass a set of points [(row,col), (row,col)] #Unpack start and end points (start_row,start_col)=start (end_row,end_col)=end #Check if start and end share a row, then construct a rectangle rowxcol based off that if end_row==start_row: if end_col>start_col: cols=range(start_col, end_col+1) else: cols=range(end_col, start_col+1) #The plus one anti-fenceposting, because range(0,2) only returns [0,1] not [0,1,2] #Two ranges, one for if the person clicks on a 2nd square to the left of the 1st click rows=[end_row] elif end_col==start_col: if end_row>start_row: rows=range(start_row, end_row+1) else: rows=range(end_row, start_row+1) #See above note, this time adjusting in case they click an end above the start cols=[end_col] for row in rows: for col in cols: self.board[row][col]=4 shipZone.append((row,col)) #Set that square to contain an unshot ship self.shiplist.append(shipZone) self.shipcount+=1 def check(self, position): if position[0]<=self.base_x or position[1]<=self.base_y: return False elif position[0]>=self.base_x+self.box*self.dim: return False elif position[1]>=self.base_y+self.box*self.dim: return False else: x_box=int(floor((position[0]-self.base_x)/self.box)) y_box=int(floor((position[1]-self.base_y)/self.box)) return(y_box,x_box) def empty(self): if self.shipcount==0: return True else: return False def saveGame(self): self.savedBoard=[] for row in self.board: self.savedBoard.append(list(row)) self.savedCount=self.shipcount self.savedList=list(self.shiplist) def loadSave(self): self.board=[] for row in self.savedBoard: self.board.append(list(row)) self.shipcount=self.savedCount self.shiplist=list(self.savedList) self.count_status=False self.turn_counter=0 class Game: def __init__(self): self.size=(900,750) self.screen= pygame.display.set_mode(self.size, 0, 32) pygame.display.set_caption("Battleship: AI Edition--Is less more? Or is more more?") self.fps=70 self.shot_time=self.fps/50 #1=1 shot per second, 25=25 shots/sec self.dim=10 self.clock=pygame.time.Clock() #state codes self.running=True self.shipSet=True self.playing=False self.shipLoc=[(-1,-1),(-1,-1)] self.curBoard="none" self.P1_wins=0 self.P2_wins=0 self.draws=0 self.games=0 self.max_games=100 self.games=1 self.drawcount=0 self.playcount=0 self.rects=[] self.lines=[] self.boards=[] self.Board1=Grid((50,50),"P1 guess",self.dim,self) self.Board2=Grid((550,50),"P2 guess",self.dim,self) self.Board3=Grid((50,400),"P1 ships",self.dim,self) self.Board4=Grid((550,400),"P2 ships",self.dim,self) while self.running==True: events=pygame.event.get() for event in events: if event.type==QUIT: self.running=False pygame.display.quit() self.inputCheck(events) self.Update() if self.checkEndGame(): self.Update() if self.playing==True and self.drawcount%(self.shot_time)==0: self.takeShot(self.Board4,self.Board1,"checker") self.takeShot(self.Board3,self.Board2,"random") if self.Board3.count_status==True: self.Board3.turn_counter+=1 if self.Board4.count_status==True: self.Board4.turn_counter+=1 if self.running==True: self.Refresh() self.clock.tick(self.fps) self.drawcount+=1 if self.playing==True: self.playcount+=1 def isValid(self,board,square): #Checks if a square on board is valid target for shot (i.e. has square state==0) s_row,s_col=square if s_row>=0 and s_row <self.dim and s_col>=0 and s_col<self.dim: if board.board[s_row][s_col]==0 or board.board[s_row][s_col]==4: return True else: return False def outputGameMessage(self,winner): total_time=round(float(self.playcount)/self.fps) av_time=round(total_time/self.games,2) perc_cmplt=round(float(self.games)/(self.max_games+1)*100,2) rem_time=int(av_time*(self.max_games-self.games+1)) rem_min=rem_time/60 rem_sec=rem_time%60 if winner=="draw": output= "Game " + str(self.games) + " ended in a draw. " elif winner=="P1": output= "Game " + str(self.games) + " ended in P1 win. " elif winner=="P2": output= "Game " + str(self.games) + " ended in P2 win. " output+= str(total_time) + " seconds elapsed, " output+=str(av_time)+ " games/sec \n" output+="Sim run is " + str(perc_cmplt) output+="% complete, estimate " + str(rem_min) + "m " + str(rem_sec) output+=" seconds left in run." return(output) def checkEndGame(self): endgame=True if self.playing==True and self.Board3.empty() and self.Board4.empty(): print self.outputGameMessage("draw") if self.games<=self.max_games: self.draws+=1 self.games+=1 for board in self.boards: board.loadSave() else: self.playing=False #And then reset from backups elif self.playing==True and self.Board3.empty(): print self.outputGameMessage("P2") if self.games<=self.max_games: self.P2_wins+=1 self.games+=1 for board in self.boards: board.loadSave() else: self.playing=False elif self.playing==True and self.Board4.empty(): print self.outputGameMessage("P1") if self.games<=self.max_games: self.P1_wins+=1 self.games+=1 for board in self.boards: board.loadSave() else: self.playing=False else: endgame=False if self.playing==False and self.games==self.max_games+1: #Do post-game stats stuff print "Simulation completed, " + str(self.games) + " played." output="Player 1 won " + str(self.P1_wins) + " games (" output+=str(100*float(self.P1_wins)/self.games) + "%)" print output output="Player 2 won " + str(self.P2_wins) + " games (" output+=str(100*float(self.P2_wins)/self.games) + "%)" print output output="The game was a draw in " + str(self.draws) + " games (" output+=str(100*float(self.draws)/self.games) + "%)" print output self.running=False return(endgame) def mouseCheck(self,pos): failboards=0 #Counter for number of boards square is not on for board in self.boards: #Run board check to see if it's on that board square=board.check(pos) if square: #It is, return that board's info and the square it's on return board,square else: #It's not, increment the count of boards it isn't on failboards+=1 if failboards==4: #Square clicked is outside all active boards return False def inputCheck(self,events): for event in events: if event.type==MOUSEBUTTONDOWN: clicked=self.mouseCheck(event.pos) if self.shipSet==True: if clicked and clicked[0]: board=clicked[0] square=clicked[1] if self.shipLoc==[(-1,-1),(-1,-1)]: self.shipLoc[0]=square self.curBoard=board self.curBoard.board[square[0]][square[1]]=4 elif self.shipLoc[1]==(-1,-1) and board==self.curBoard: start=self.shipLoc[0] if square[0]==start[0] or square[1]==start[1]: self.shipLoc[1]=square self.curBoard.addShip(self.shipLoc) self.shipLoc=[(-1,-1),(-1,-1)] self.curBoard="none" elif clicked: grid=clicked[0] board=grid.board square=clicked[1] row=square[0] col=square[1] board[row][col]=(board[row][col]+1)%6 if event.type==KEYDOWN: if event.key==K_RETURN: if self.shipSet==True: self.shipSet=False if self.shipLoc[0]!=(-1,-1): self.curBoard.board[self.shipLoc[0][0]][self.shipLoc[0][1]]=0 self.curBoard="none" self.shipLoc=[(-1,-1),(-1,-1)] elif self.shipSet==False and self.playing==False: self.shipSet=True if event.key==K_p: if self.playing==False: self.playing=True for board in self.boards: board.saveGame() #Create backups of Board 3 and Board 4 boards and shipcounts elif self.playing==True: self.playing=False def Update(self): self.Board3.genTemp() self.Board4.genTemp() self.Board1.genTemp(self.Board4) #Give P1 guess p2 actual board and update guess board self.Board2.genTemp(self.Board3) #Give P2 guess P1 actual board and update guess board #Over-ride temp board values for necesary squares if self.playing==False: try: pos=pygame.mouse.get_pos() hover=self.mouseCheck(pos) if hover and self.shipSet: board=hover[0] square=hover[1] if self.shipLoc==[(-1,-1),(-1,-1)]: board.tempBoard[square[0]][square[1]]=5 elif self.shipLoc[1]==(-1,-1): if board==self.curBoard: board.tempBoard[square[0]][square[1]]=4 except: print "game ended, this is just avoiding a crash" else: pass def pickShot(self,guess,real,mode): guessboard=guess.tempBoard realboard=real.tempBoard targets=[] if self.playing==True: hitlist=[] potlist=[] checkerlist=[] for row in range(0,self.dim): for col in range(0,self.dim): cell=guessboard[row][col] if cell==2: hitlist.append((row,col)) if cell==0: potlist.append((row,col)) if (row+col)%2==0: checkerlist.append((row,col)) shuffle(hitlist) shuffle(potlist) shuffle(checkerlist) shot=False for first in hitlist: if len(targets)==0: for second in hitlist: if len(targets)==0: #finds horizontal pairs of hits if first[0]==second[0] and (first[1]==second[1]-1 or first[1]==second[1]+1): if first[1]>second[1]: first,second=second,first right=(second[0],second[1]+1) if self.isValid(real,right): targets.append(right) left=(first[0],first[1]-1) if self.isValid(real,left): targets.append(left) #finds vertical pairs of hits elif first[1]==second[1] and (first[0]==second[0]-1 or first[0]==second[0]+1): if first[0]>second[0]: first,second=second,first above=(first[0]-1,first[1]) if self.isValid(real,above): targets.append(above) below=(second[0]+1,second[1]) if self.isValid(real,below): targets.append(below) for first in hitlist: if len(targets)==0: left=(first[0],first[1]-1) if self.isValid(real,left): targets.append(left) right=(first[0],first[1]+1) if self.isValid(real,right): targets.append(right) above=(first[0]-1,first[1]) if self.isValid(real,above): targets.append(above) below=(first[0]+1,first[1]) if self.isValid(real,below): targets.append(below) shuffle(targets) for point in targets: if point in potlist and shot==False: shot=point if len(targets)==0: if mode=="checker": shot=checkerlist[0] else: shot=potlist[0] if shot==False: print "Arg, this fucking bug!!! #@$% &*@#!!" return(shot) def takeShot(self,real,guess,mode): try: square=self.pickShot(guess,real,mode) (s_row,s_col)=square except: self.running=False else: if real.board[s_row][s_col]==0: real.board[s_row][s_col]=1 elif real.board[s_row][s_col]==4: real.board[s_row][s_col]=2 def Refresh(self): #Fill screen with background color (white atm) self.screen.fill( (255,255,255)) del self.rects[:] #Empty the list of old rectangles #Tell all Grids to update their rectangle data for board in self.boards: board.Update() #Draw rectangles to screen by filling rects of squares for rect in self.rects: box=rect[0] value=rect[1] if value==0: color=(127,255,212) elif value==1: color=(255,255,255) elif value==2: color=(255,0,0) elif value==3: color=(178,34,34) elif value==4: color=(139,139,139) elif value==5: color=(255,255,0) self.screen.fill(color, box) #Draw lines to the screen for line in self.lines: start_pos=line[0] end_pos=line[1] color=line[2] pygame.draw.line(self.screen, color, start_pos, end_pos, 2) #Flip the screen to update changes pygame.display.flip() def std_dev(list,mean): length=len(list) total=0 for item in list: total+=(float(item)-mean)**2 return(sqrt(total)/length) def mean(list): length=len(list) total=0 for item in list: total+=item return(float(total)/length) theGame=Game()
b1886665d9be0afdea379ebef37c88a656135f75
GLMF/GLMF198
/Reperes/Tensorflow/Tensorflow/display_image.py
577
3.5625
4
from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib import random import numpy mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) index = random.randint(0, len(mnist.train.images)) img = mnist.train.images[index] img = img.reshape((28,28)) label = mnist.train.labels[index] num = numpy.where(label == 1)[0][0] fig = plt.figure() fig.suptitle('Écriture manuscrite d\'un {}'.format(num), fontsize=14, fontweight='bold', color='blue') plt.imshow(img, cmap = cm.Greys) plt.show()
f6de9fb72f4405a34352338d7828842e82cd3c15
smartinsert/CodingProblem
/algorithmic_patterns/modified_binary_search/ceiling_of_a_number.py
470
3.953125
4
""" Find the smallest number index in the array greater than or equal to the key """ # Time: O(logN) def smallest_number_greater_than(arr, key): n = len(arr) if n == 0 or key > arr[n-1]: return -1 start, end = 0, n - 1 while start <= end: mid = start + (end - start) // 2 if arr[mid] > key: end = mid - 1 elif arr[mid] < key: start = mid + 1 else: return mid return start
62f8412617ea39957161d13305278f5ff8cee045
Beltran89/Curso-Python-Django-Flask
/09-listas/predefinidas.py
711
4.125
4
cantantes = ["kase o", "Morodo", "Rapsuskley", "haze"] numeros = [1, 2, 32, 14, 8, 8, 8] #Ordenar print(numeros) numeros.sort() print(numeros) #Añadir elementos cantantes.append("Lirico") cantantes.insert(1,"CPV") #Posicion print(cantantes) #Eliminar elementos cantantes.pop(1) #eliminar por posicion cantantes.remove("Lirico") #Eliminamos por nombre print(cantantes) #Dar la vuelta numeros.reverse() print(numeros) #Buscar dentro de una lista print("kase o" in cantantes) #Contar elementos print(len(cantantes)) #Cuantas veces aparece un elemento en la lista print(numeros.count(8)) #conseguir el indice print(cantantes.index("haze")) #unir dos listas cantantes.extend(numeros) print(cantantes)
6f21caa165132ab8f1983659194f53c568b9e8fe
josemrp/test-python
/Basic/loops.py
218
3.921875
4
def ss(): print(' ') for i in range(5): print(i) ss() names = ['jose', 'carlos', 'maria'] for name in names: print(name) ss() for j in range(len(names)): print(j, names[j]) ss() for n in names[:]: print(n)
1d2f84381f488e7fa211661f21ce97f264a00bab
scls19fr/openphysic
/python/oreilly/cours_python/solutions/exercice_10_07.py
462
3.546875
4
#! /usr/bin/env python # -*- coding: Latin-1 -*- def compteMots(ch): "comptage du nombre de mots dans la chane ch" if len(ch) ==0: return 0 nm = 1 # la chane comporte au moins un mot for c in ch: if c == " ": # il suffit de compter les espaces nm = nm + 1 return nm # Test : if __name__ == '__main__': print compteMots("Les petits ruisseaux font les grandes rivires")
97c3fcbababb9409058ee3fa656c9d6f160d7e71
Iainmon/Chess-Player-with-Python
/ChessPlayer/chess_manager.py
2,051
3.546875
4
import chess import time from players import player_human, player_minimax, player_random COLOR_TO_STRING = {chess.WHITE : "White", chess.BLACK : "Black"} class ChessManager: def __init__(self, white_player, black_player): self.board = chess.Board() self.white_player = white_player self.black_player = black_player self.color_to_player = {chess.WHITE: self.white_player, chess.BLACK: self.black_player} white_player.assign(chess.WHITE, self.board) black_player.assign(chess.BLACK, self.board) def play(self, is_displayed=False, delay=0): """ Starts a turn by turn game with the two players. Parameters: is_displayed (bool): Whether or not the board is printed each turn delay (float): Time in seconds to sleep inbetween turns """ # Set initial turn turn = chess.WHITE # Game loop turn_count = 0 while(True): current_player = self.color_to_player[turn] if is_displayed: print("\n\nTurn: " + str(turn_count)) print(COLOR_TO_STRING[turn] + "'s move") print("Player type: " + str(type(current_player)) + "\n") print(self.board) move = None if turn == chess.WHITE: move = current_player.get_move() elif turn == chess.BLACK: move = current_player.get_move() assert self.board.is_legal(move) self.board.push(move) if self.board.is_game_over(): print("\nGame finished with final score: " + self.board.result()) break turn = not turn turn_count += 1 time.sleep(delay) if __name__ == "__main__": #w = player_human.PlayerHuman() #b = player_human.PlayerHuman() b = player_minimax.PlayerMinimax(2, print_move_info=True) w = player_random.PlayerRandom() cm = ChessManager(w, b) cm.play(is_displayed=True, delay=0)
c93925308a05feb89e235979de406e6bb0e9b3e8
arvidpm/dvg007.programmeringsteknik
/Uppgift_3/Uppgift3_temp.py
3,174
3.625
4
import random, sys # Programmeringsteknik webbkurs KTH inlämningsuppgift 3. # Robin Chowdhury # 2014-08-06 # Ett nöjesfält där man får välja mellan 3 åkturer # Det finns en chans att åkturen man åker med havererar # Attraktion för nökesfältet. # Har funktioner för att starta, stoppa, skriva reklam. # Denna klass använder man för att skapa åkturer till nöjesfältet class Attraction: """Attaktion för nöjesfältet""" def __init__(self, name, lengthreq, passengers, excitementlevel ): self.name = name self.lengthReq = lengthreq self.passengers = passengers self.excitementLevel = excitementlevel self.wreckedList = ["exploderade!", "blev till aska!", "blev upäten av en drake!"] self.introText = "" self.stopSound = "" self.excitementSound = "" # Används för att starta åkturen # Finns en chans att åkturen havererar då den startas. def start(self): print() if random.randrange(0,3) == 0: self.wrecked() self.stop() else: print(self.excitementSound) self.stop() # Då åkturen stannar kallas denna def stop(self): print(self.stopSound, self.name, "har stannat.") # Om åkturen går sönder så kallas denna def wrecked(self): print("Oh, nej! Något fel hände!") print(self.name, self.wreckedList[random.randrange(0,3)]) # Denna används för att för att beskriva åkturen lite def printcommercial(self): print() print("Så du vill åka", self.name) print(self.introText) print("Du måste vara längre än", self.lengthReq, "cm för att åka den här") if self.excitementLevel > 9000: excite = "Livsfarlig" elif self.excitementLevel > 20: excite = "Spännande" else: excite = "Rolig" print (self.name, "klassas som", excite) print("Är du säker på att du vill åka denna?") def __str__(self): return self.name # Huvudprogrammet # Här initieras alla objekt som ska användas. # De ges även egna ljud (textformat) samt introtexter rides = [Attraction("Extrema åket", 140, 30, 9421), Attraction("Släppet", 150, 16, 32), Attraction("Lilla åket", 90, 20, 4)] rides[0].introText ="Detta åk är den farligaste, snabbaste och mest dödliga attraktionen på nöjesfältet" rides[0].excitementSound = "AAAhhhhhhhhhh!" rides[0].stopSound ="Screeeeech!" rides[1].introText ="Ett 200 m fritt fall. Hoppas att du inte är höjdrädd!" rides[1].excitementSound = "Whooooooo!" rides[1].stopSound ="Klonk!" rides[2].introText ="Perfekt för dem små knattarna. Eller ganska tråkig för dem också" rides[2].excitementSound = "Weeeeeee!" rides[2].stopSound ="Gnissel!" # Här sker det som användaren kommer att få se. # Alla valalternativ samt flödet av programmet. print() print("Välkommen till Spännande åk! Världens bästa nöjespark!") while True: print() print("Vilken attraktion vill du åka?") for i in range(len(rides)): print(rides[i], "[" + str(i) + "]", end = " ") print("Avsluta [q]") ride = input() if ride == "q": sys.exit(9) ride = int(ride) if ride < len(rides): rides[ride].printcommercial() choice = input("[y/n]") if choice[0] == "y": rides[ride].start() else: print("Den åkturen finns inte, var god välj en annan")
9601a5cc11d24d95c89eeeed41be17778a58665b
ruturaj9345/MSAM
/LeastCostMethod.py
1,659
3.59375
4
def getMin(cost_matrix, warehouse_demand, no_of_fac, no_of_wah): min = 1000 i_val = 0 j_val = 0 for i in range(0, no_of_fac): for j in range(0, no_of_wah): if(cost_matrix[i][j] < min): min = cost_matrix[i][j] i_val = i j_val = j elif(cost_matrix[i][j] == min): if(warehouse_demand[j] > warehouse_demand[j_val]): i_val = i j_val = j return i_val, j_val def run(): print("Enter no. of factories") no_of_fac = int(input()) print("Enter no. of warehouses") no_of_wah = int(input()) factory_production = [0 for x in range(0,no_of_fac+1)] warehouse_demand = [0 for x in range(0,no_of_wah+1)] for loopCounter in range(0,no_of_fac): print("Enter",loopCounter+1," factory's production") factory_production[loopCounter] = int(input()) for loopCounter in range(0,no_of_wah): print("Enter",loopCounter+1," warehouse demand") warehouse_demand[loopCounter] = int(input()) if sum(factory_production) != sum(warehouse_demand): print("It is an unbalanced Problem") exit() arr = [[0 for i in range(0,no_of_fac)]for j in range(0,no_of_wah)] cost_matrix = [[0 for i in range(0,no_of_fac)]for j in range(0,no_of_wah)] for i in range(0, no_of_fac): for j in range(0, no_of_wah): print("enter ",i,j,"cost matrix") cost_matrix[i][j] = int(input()) i , j = getMin(cost_matrix, warehouse_demand, no_of_fac, no_of_wah) print(i) print(j) if __name__ == '__main__': run()
82074ffb50970810e5091e0260b596f6fab2b141
Sandbox4KidsTM/Python_Basics
/Supplemental_Material/PythonProjects/GAMES/game.py
1,580
4.375
4
# https://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python # 1 - Import library import pygame from pygame.locals import * # 2 - Initialize the game pygame.init() width, height = 640, 480 screen=pygame.display.set_mode((width, height)) keys = [False, False, False, False] #track state of 4 keys: W, A, S, D, whether pressed or not playerpos=[100,100] #track position of player 'bunny' # 3 - Load images player = pygame.image.load("resources/images/dude.png") grass = pygame.image.load("resources/images/grass.png") castle = pygame.image.load("resources/images/castle.png") # 4 - keep looping through while 1: # 5 - clear the screen before drawing it again screen.fill(0) # 6 - draw the screen elements #grass image is not large enough to fill the screen, hence you tile it. for x in range(int(width/grass.get_width())+1): for y in range(int(height/grass.get_height())+1): screen.blit(grass,(x*100,y*100)) screen.blit(castle,(0,30)) #post 4 castles at diff positions on screen screen.blit(castle,(0,135)) screen.blit(castle,(0,240)) screen.blit(castle,(0,345 )) screen.blit(player, playerpos) #player 'bunny' position on the screen # 7 - update the screen pygame.display.flip() # 8 - loop through the events for event in pygame.event.get(): # check if the event is the X button if event.type==pygame.QUIT: # if it is quit the game pygame.quit() exit(0)
4c3351152540a3cd39545a6fc33eb53843b4a722
KonSprin/RecruitmentTask
/mac.py
803
3.640625
4
import requests import json import argparse parser = argparse.ArgumentParser() # Taking MAC as an input parser.add_argument("MAC", type=str, help="MAC address") arguments = parser.parse_args() # 44:38:39:ff:ef:57 # Trying to get the response from server try: response = requests.get("https://api.macaddress.io/v1?apiKey=at_pPk0FKIlnX9WXqqsTDZ7i9yQyusQe&output=json&search={}".format(arguments.MAC)) except: print("get request error") exit() # Checking if the response was correct if response.status_code != 200: print("Response error: " + str(response.status_code)) exit() # convering response from json response_json = json.loads(response.text) # printing the vendor name try: print(response_json['vendorDetails']['companyName']) except: print("Couldn't find company name or vendor details in response")
36163bede6481af5b3c5d08fe7d50c64b09e667a
poojhamuralidharan/ineuronassignment
/printing star pattern.py
205
3.96875
4
for i in range (0,6,1): for j in range(0,i,1): print("*",end=" ") print("\n") for i in range (4,0,-1): for j in range(0,i,1): print("*",end=" ") print("\n")
2d1532bad8bb68a516ac0371998d5277481707ef
jefflike/python_advance
/packet/016.不要轻易继承python的基本数据结构.py
926
4.1875
4
''' __title__ = '016.不要轻易继承python的基本数据结构.py' __author__ = 'Jeffd' __time__ = '4/17/18 5:27 PM' ''' ''' tips: 这里尤其是不建议继承list,dict等底层是c语言实现的一些函数。 ''' class my_dict(dict): def __setitem__(self, key, value): super().__setitem__(key, value*2) d = my_dict(a=1) print(d) # {'a': 1} # def __setitem__(self, *args, **kwargs): # real signature unknown # """ Set self[key] to value. """ # pass # dict底层并没有return什么值,所以上面这种方式的继承是不生效的,v并不是我们想要的值 d['a'] = 1 print(d) # {'a': 2} # 因为底层是c写的,某些情况下并不会出发继承关系 # 如果一定要继承,就继承 from collections import UserDict class my_dict(UserDict): def __setitem__(self, key, value): super().__setitem__(key, value*2) e = my_dict(a=1) print(e) # {'a': 2}
26f104f18065ce8cb466d1c4060e2d142e7097d3
randyarbolaez/codesignal
/daily-challenges/MaxCupCakes.py
336
3.53125
4
# Your task it to find the quality of the Kth cupcake after the cupcakes from the list P are removed from the box. def MaxCupCakes(N, P, K): cupcakeQuality = [] for i in range(1,N+1): cupcakeQuality.append(i) for i in P: cupcakeQuality.remove(i) if len(cupcakeQuality) < K-1: return -1 return cupcakeQuality[K-1]
8af43256102f51fff162c903294e8dcacc3bc99a
DojoFatecSP/Dojos
/2019/20190920 - media1 - python/uritest.py
137
3.78125
4
n1 = float(input()) * 2 n2 = float(input()) * 3 n3 = float(input()) * 5 media = (n1 + n2 + n3)/10 print("MEDIA = {:.1f}".format(media))
b4d13c8aaf5089896903fb573f4eda7a27e6438e
ViajeDeReina/Lets_Practice
/Python Etc/run_turtle_run_2.py
2,883
4.1875
4
#this is upgrade version of Run Turtle Run #basically everything is same except some details import turtle as t import random t.title("Run Turtle Run") t.setup(500,500) t.bgcolor("black") #tframe for just making frame around the window. turtle will only move within this area tframe=t.Turtle() tframe.shape("classic") tframe.goto(-230,-230) tframe.color("white") for x in range(4): tframe.forward(460) tframe.left(90) tframe.ht() #our dear turtle t.shape("turtle") t.speed(0) t.color("white") t.up() #adding score variables score=0 #variable, default playing=False #variable, default; True when space is pressed #now we're setting each character tvill=t.Turtle() #as a villian tvill.shape("turtle") tvill.color("red") tvill.speed(10) tvill.up() tvill.goto(0,200) #default position tfood=t.Turtle() #as food to eat tfood.shape("circle") tfood.color("yellow") tfood.speed(0) tfood.up() tfood.goto(0,-200) #default position #now we define each function for key control def turn_right(): t.setheading(0) t.forward(10) def turn_left(): t.setheading(180) t.forward(10) def turn_up(): t.setheading(90) t.forward(10) def turn_down(): t.setheading(270) t.forward(10) def start(): global playing #this means that variable "playing" can be used in other place if playing == False: playing = True t.up() t.clear() #delete all previous trace of the turtle play() def play(): global score global playing if random.randint(1,5)==3: ang=tvill.towards(t.pos()) #villian will head towards the turtle with 20% possibility tvill.setheading(ang) speed=score+5 if speed>15: speed=15 #speed will not exceed 15 tvill.forward(speed) if t.distance(tvill)<12: #when the villian touches our dear turtle text="Score : "+str(score) message("Game Over",text) playing = False score=0 if t.distance(tfood)<12: #when the food is close enough score=score+1 #gain 1 point t.write(score) starx=random.randint(-230,230) stary=random.randint(-230,230) #when turtle eats the food, new food will be reallocated tfood.goto(starx,stary) if playing: t.ontimer(play,100) #after 0.1sec, the function play will work (it means keep going) def message(m1,m2): #this is for score message t.clear() t.goto(0,100) t.write(m1,False,"center",("Courier",20)) t.goto(0,-100) t.write(m2,False,"center",("Courier",20)) t.goto(0,-150) t.write("Press space to play again",False,"center",("Courier",20)) t.home() #to the original position #setting key press t.onkeypress(turn_right,"Right") t.onkeypress(turn_left,"Left") t.onkeypress(turn_up,"Up") t.onkeypress(turn_down,"Down") t.onkeypress(start,"space") t.listen() message("Run Turtle Run","[Space]")
17fbbcd01be831931e534b5a30122f96ea3d78dc
slaveveve/NLP100
/ch01/03.py
633
4.125
4
# 03. 円周率 # "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics." # という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ. import re def count_word_len(sentence: str) : dropped_sentence = re.sub(r'[.,]', '', sentence) splitted_sentence = dropped_sentence.split() count_word_len = ''.join(str(len(word)) for word in splitted_sentence) return count_word_len count_word_len('Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.')
c114ea87c289705830fc9e2fcbcf5ef29bad489f
cdtibaquicha19/curso-python
/fundamentos/tienda-libros.py
711
3.734375
4
print("Proporcione los siguientes datos del libro ") nombre = input("Proporciona el nombre ") i = int(input("proporciona el id del libro ")) precio = float(input("Proporcione precio del libro ")) enviogratuito = input("Indica si el envio es gratuito (True/False) ") if enviogratuito == "True" : enviogratuito = True elif enviogratuito =="False": enviogratuito = False else: enviogratuito ="Valor incorrecto debe ser True/False" print("Nombre de libro :" , nombre) print("ID :" , i) print("Precio :" , precio) print("envio gratuito :" , enviogratuito) <<<<<<< HEAD # se muestra el vtipo de dato que esta generando la variable print (type(nombre)) ======= >>>>>>> master
808a0b6ac2984ef6ad8228c785e2d2fd3a5482e4
gmftbyGMFTBY/Study
/Python/StudyPython/python_test_workspace/code2_2.py
130
3.890625
4
import re url = input("Please input your URL:") pattern = "http://www.(.+)\.com" an = re.findall(pattern,url) print(an.group(1))
ec1e4a2c85e0b2ba5eecbc6c9ecadd4ec7619083
timols/spellwalrus
/calling/utils.py
303
3.78125
4
import string def chars_to_digits(word): "Given a string of characters, return the corresponding keypad digits" keypad_mapping = dict(zip(string.ascii_lowercase, "22233344455566677778889999")) return ''.join(str(keypad_mapping[l]) for l in word.lower())
0d80029c5b5598108f5d4eabf9ef355775d359e6
Taiwanese-Corpus/klokah_data_extract
/klokah/補充教材句型篇動詞時態比較.py
1,694
3.5
4
from klokah.補充教材句型篇解析 import 補充教材句型篇解析 from collections import OrderedDict from csv import DictWriter class 補充教材句型篇動詞時態比較: _補充教材句型篇解析 = 補充教材句型篇解析() 祈使對應表 = {'看': '看(如看電視、看東西)', '坐下': '坐著', '起立': '站著'} 否定對應表 = {'看': '看(如看電視、看東西)'} 欄位名 = ['華語', '肯定', '祈使', '否定'] def 輸出檔案(self, 方言編號, 檔名): with open(檔名, 'w') as 檔案: 輸出 = DictWriter(檔案, fieldnames=self.欄位名) 輸出.writeheader() for 資料 in self.資料物件(方言編號).values(): 輸出.writerow(資料) def 資料物件(self, 方言編號): 結果 = OrderedDict() for 族語, 華語 in self._取資料(方言編號, 14): # 肯定資料 結果[華語] = {'華語': 華語, '肯定': 族語} for 族語, 華語 in self._取資料(方言編號, 15): # 祈使資料 if 華語 in self.祈使對應表: 華語 = self.祈使對應表[華語] 結果[華語]['祈使'] = 族語 for 族語, 華語 in self._取資料(方言編號, 211): # 否定資料 if 華語 in self.否定對應表: 華語 = self.否定對應表[華語] 結果[華語]['否定'] = 族語 return 結果 def _取資料(self, 方言編號, 項目編號): for 一筆 in self._補充教材句型篇解析.解析一個句型篇檔案('senior', 方言編號, 項目編號): yield 一筆['資料'][0]
26105e5db1d2494c94be6b254a4153edd167aae1
pythonfoo/pythonfoo
/beginnerscorner/decorators.py
4,789
3.546875
4
#Dekoratoren #----------- # Dekoratoren sind Funktionen, die Funktionen verändern. # Zuerst brauchen wir eine Funktion, die irgend etwas macht: # Signatur: `f`: int -> int def f(n): """Addiert etwas zum gegebenen Argument.""" return n + 4 # garantiert zufällig gewählt f(13) # Nehmen wir an, wir wollen wissen, wann die Funktion aufgerufen wird, z.B. zum Debuggen. # Wir könnten eine andere Funktion machen, die die Aufrufe protokolliert: # Signatur: `fDebug`: int -> int def fDebug(n): """Addiert etwas zum gegebenen Argument und protokolliert das.""" print(" aufgerufen mit %d" % n) res = n + 4 print(" Ergebnis ist: %d" % res) return res fDebug(13) # Das ist nicht so toll, weil wir dann jeden Aufruf der Funktion durch unsere Debug-Funktion # austauschen müssen -- und wenn wir wieder fertig sind, dann müssen wir die Funktion wieder # zurücktauschen. fPrime = f # Eine andere Variante wäre, die Funktion selbst zu modifizieren oder auszutauschen: # Signatur: `f`: int -> int def f(n): # debug-variante """Addiert etwas zum gegebenen Argument und protokolliert das.""" print(" aufgerufen mit %d" % n) res = n + 4 print(" Ergebnis ist: %d" % res) return res f(13) # und wieder zurück für später: f = fPrime # Auch hier ist das Problem, dass wir unsere Funktion austauschen und hinterher wieder # zurücktauschen müssen. Und diese Lösung ist auch nicht wiederbenutzbar. # Besser wäre es also, wenn wir die Funktion (die das macht, was wir wollen), mit dem # Verhalten, das wir zusätzlich/temporär haben wollen, zu modifizieren. # Signatur: `fDebugProtocol`: int -> int def fDebugProtocol(n): print(" aufgerufen mit %d" % n) res = f(n) print(" Ergebnis ist: %d" % res) return res fDebugProtocol(13) # Auch hier: die Funktion ist speziell für `f` gemacht, also nicht wiederverwendbar. # Immerhin haben wir schon das Verhalten aus-faktoriert. # Die Wiederverwendbarkeit erreichen wir jetzt, indem wir der `debugProtocol` die # Funktion übergeben, die wir protokollieren wollen: # Signatur: `debugProtocolForFunction`: (`f`: int -> int, int) -> int def debugProtocolForFunction(someF, n): print(" aufgerufen mit %d" % n) res = someF(n) print(" Ergebnis ist: %d" % res) return res debugProtocolForFunction(f, 13) # Besser, aber immer noch nicht toll: Wir müssen jeden Aufruf von `f` durch # das `debugProtocol` ersetzen. # Besser wäre es doch, die Funktion direkt zu modifizieren. Das erreichen wir, indem # wir eine Funktion machen, die `f` als Argument nimmt und wieder eine Funktion zurückgibt. # Das heißt, die Signatur ist # debugF: (int -> int) -> (int -> int) def debugF(someF): # wir müssen wieder eine Funktion zurückgeben, also müssen wir eine machen: def aux(n): print(" aufgerufen mit %d" % n) res = someF(n) # warum können wir hier f benutzen? Weil hier eine "Closure" vorhanden ist. print(" Ergebnis ist: %d" % res) return res return aux # direkter Aufruf: debugF(f)(13) # und für später: f2 = debugF(f) # beliebieger Code f2(13) # Weil das sehr praktisch ist, gibt es dafür in Python eine spezielle Syntax: die @-Syntax. # Dadurch wird `debugF` zum Dekorator. @debugF def f3(n): """Gleiche Funktion wie vorhin!""" return n + 4 def f7(n): return n ** 2 f7 = debugF(f7) # Jede Funktion, die eine Funktion nimmt und eine Funktion zurückgibt, kann als Dekorator benutzt werden. # (Auch, wenn sich die Signaturen verändern (was auch sehr nützlich sein kann).) def needsPassword(f): def aux(password, n): if password != 'vErYsEcReT': raise ValueError('password unknown') return f(n) return aux @needsPassword def g(n): return n + 7 g(7) # Falsche Signatur! g('meinPasswort', 7) # ValueError weil falsches Passwort g('vErYsEcReT', 7) # yay! # Komplizierter wird es, wenn der Dekorator auch noch ein Argument haben soll. def addTo(N): def addNTo(f): def aux(n): return f(n) + N return aux return addNTo # addTo: int -> ((int -> int) -> (int -> int)) @addTo(7) # (int -> int) -> (int -> int) def f(n): return n * 2 # Dekorator, der zu jeder Ausgabe auch die Uhrzeit ausgibt. # >>> output("hallo") # output: * -> None # 19:30 hallo def timeOut(f): def aux(*ausgabe): print("the time is now!",) f(*ausgabe) # return None return aux @timeOut def output(*ausgabe): print(*ausgabe) lambda x : (x + 1) def no_name(x): return x + 1
4fa10dd2aa7b79dcc30a8df61f0b22627114030c
iZainAsif/Tkinter-Auction-App
/Listitem.py
2,148
3.671875
4
from tkinter import* from tkinter import messagebox def listitem(hp): name=StringVar() typ=StringVar() startingprice=IntVar() buynow=IntVar() global li li = Toplevel(hp) li.title("List Item") li.geometry("500x520") li.configure(bg="wheat4") Label(li,text="Zain's Auction App",bg="PeachPuff3",fg="dim gray",font=("Courier New",25,"bold") ,width="300",height="1",relief="raised",borderwidth=2).pack() Label(li,text="",bg="wheat4",height="2").pack() Label(li,text="Enter Name of Item",bg="misty rose",fg="VioletRed4",font=("Courier",15,"bold"),relief="raised",borderwidth=2,width="24").pack() ename=Entry(li,textvariable=name,width="28").pack() Label(li,text="",bg="wheat4",height="2").pack() Label(li,text="What is the type of Item",bg="misty rose",fg="VioletRed4",font=("Courier",15,"bold"),relief="raised",borderwidth=2,width="24").pack() etyp=Entry(li,textvariable=typ,width="28").pack() Label(li,text="",bg="wheat4",height="2").pack() Label(li,text="Enter Starting Price",bg="misty rose",fg="VioletRed4",font=("Courier",15,"bold"),relief="raised",borderwidth=2,width="24").pack() esprice=Entry(li,textvariable=startingprice,width="28").pack() Label(li,text="",bg="wheat4",height="2").pack() Label(li,text="Enter Buy Now price",bg="misty rose",fg="VioletRed4",font=("Courier",15,"bold"),relief="raised",borderwidth=2,width="24").pack() ebnow=Entry(li,textvariable=buynow,width="28").pack() Label(li,text="",bg="wheat4",height="2").pack() Button(li,text="Submit",bg="misty rose",fg="VioletRed4",font=("Courier",20,"bold"),relief="raised",borderwidth=2,width="15",command=lambda: Listit(name,typ,startingprice,buynow)).pack() class Listit(): def __init__(self,name,typ,spr,bnp): self.__name=name.get() self.__typ=typ.get() self.__spr=spr.get() self.bnp=bnp.get() with open("items.txt","a") as f: f.write("{},{},{}\n".format(self.__name,self.__spr,self.bnp)) f.close() messagebox.showinfo('Success', 'Your Item has been listed').pack()
a0f54b2540729052b3702081b28ae708e1616f5f
saby95/Leetcode-Submissions
/Climbing Stairs.py
815
3.703125
4
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n<3: return n a,b =1,1 for i in range(2, n+1): a,b = b,a+b return b def stringToInt(input): return int(input) def intToString(input): if input is None: input = 0 return str(input) def main(): import sys def readlines(): for line in sys.stdin: yield line.strip('\n') lines = readlines() while True: try: line = lines.next() n = stringToInt(line) ret = Solution().climbStairs(n) out = intToString(ret) print out except StopIteration: break if __name__ == '__main__': main()
20cf1ad3f98da6082b65272981eb58dd2d8b446e
nami-h/Python
/itertools combination and [print("".join(i)) for i in itertools.combinations(sorted(word), i)] .py
147
3.515625
4
import itertools word, n = input().split() for i in range(1, int(n)+1): [print("".join(i)) for i in itertools.combinations(sorted(word), i)]
f6e06e1e3a897d505de94d23aa83c6c587e7b466
karar-vir/python
/return_duble.py
143
3.75
4
def double(num): return num*num print(double(3)) def double_lambda(n): return lambda x:x*n y=double_lambda(3) print(y(5))
954f6bf858924fd06a5e92784bfa282b5e31451b
Goodusernamenotfound/c4t-nhatnam
/session3/asterisk1.py
176
3.578125
4
rows = int(input("Nhập số hàng: ")) if rows<=0: print("Invalid!") else: for i in range (0, rows): for j in range(0, i + 1): print("*", end=' ')
70960e95dafdcf9188c6ab5df6d889ef4d2cfb00
marcossilvaxx/PraticandoPython
/ExercicioPOO/Questao3.py
1,219
3.890625
4
class Retangulo: def __init__(self): self.comprimento = eval(input("Informe o comprimento do retângulo:\n")) self.largura = eval(input("Informe a largura do retângulo:\n")) print("Construtor finalizado.") def mudarLados(self): self.comprimento = eval(input("Informe o novo comprimento do retângulo:\n")) self.largura = eval(input("Informe a nova largura do retângulo:\n")) print("Valor dos lados alterados.") def retornarLados(self): return self.comprimento, self.largura def calcularArea(self): return self.comprimento * self.largura def calcularPerimetro(self): return self.comprimento + self.largura retangulo = Retangulo() pergunta = str(input("Deseja mudar o valor dos lados? (S/N)\n")) if pergunta == "S": retangulo.mudarLados() pergunta = str(input("Deseja ver o valor dos lados? (S/N)\n")) if pergunta == "S": print(retangulo.retornarLados()) pergunta = str(input("Deseja ver a área do retângulo? (S/N)\n")) if pergunta == "S": print(retangulo.calcularArea()) pergunta = str(input("Deseja ver o perímetro do retângulo? (S/N)\n")) if pergunta == "S": print(retangulo.calcularPerimetro())
f54d34b7e73d7608a25925058303eadd2b619b43
bobsiunn/One-Day-One-BOJ-Pyhton
/Graph/1697.py
2,282
3.546875
4
#앞뒤 출구가 있어 stack,queue를 유연하게 사용할 수 있는 deaue import from collections import deque #bfs 탐색을 위한 함수 정의 def bfs(): #탐색해야할 위치를 저장하는 큐 선언 q = deque() #해당 큐에 탐색 시작 위치인 N을 저장 q.append(N) #더이상 탐색해야할 위치가 없을 때까지 반복 #if조건에 의해 조기 종료되지 않고, q = empty로 종료시, 탐색 대상이 존재x while q: #popleft로 가장 앞에 저장된(가장 먼저 저장된) 위치를 불러옴 v = q.popleft() #불러온 위치가 탐색 대상일때 if v == K: #visited의 해당 인덱스에 저장된 것은 해당 노드에 도달하기 위해 필요한 최단 이동 횟수 print(visited[v]) #함수 종료 return #다음 노드 후보군에 대해(각각 뒤로 걷기, 앞으로 걷기, 순간이동을 의미) for next_node in (v-1, v+1, v*2): #다음 노드가 유효값의 범위 안에 있고 #다음 노드가 이전에 탐색된 적이 없을 때 if(0 <= next_node < MAX and visited[next_node] == 0): #다음 노드의 방문기록에 이전 노드의 방문기록 +1 (이전노드 -> 다음노드로 이동을 의미) visited[next_node] = visited[v] + 1 #큐에 다음 노드의 새끼 노드들을 등록 q.append(next_node) #유효값의 최대범위를 저장하는 MAX 변수 MAX = 100001 #수빈과 동생의 위치를 입력받기 N, K = map(int, input().split()) #각 노드들에 도달하기 위한 최단 이동 횟수를 저장하는 list(방문기록) visited = [0]*MAX #해당 함수 호출 bfs() #인사이트 #BFS는 탐색과정에서 한번에 목표로 직진하는 것이 아니라 #노드의 레벨을 다운그레이드 하면서 목표 노드에 도달할 때까지 모든 노드를 탐색하고 #이 과정에서 해당 노드에 도달하기 위한 경로, 혹은 필수 이동횟수를 기록 #최종적으로 목표 노드에 도달했을 때, 목표 노드의 인덱스에 저장된 방문기록을 호출
72ad73420fd703b505543edc2056e72d22ab3ec0
joinalahmed/University_of_Michigan_Python_for_Informatics_Certificate
/2_Python_Data_Structures/Week1_Ch6_Strings/extractcode.py
319
4.09375
4
# 6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below. # Convert the extracted value to a floating point number and print it out. text = "X-DSPAM-Confidence: 0.8475" x = text.find('0') y = text[x-1:] val = float(y) print val #Expected output: 0.8475
4c2c90e7022c7be58e90ca1d8c3172bed5f2384c
mdelia17/bigdata-labs
/wordcount/reducer.py
870
3.828125
4
#!/usr/bin/env python3 """reducer.py""" import sys # this dictionary maps each word to the sum of the values # that the mapper has computed for that word word_2_sum = {} # input comes from STDIN (output from the mapper) for line in sys.stdin: # remove leading and trailing spaces line = line.strip() # parse the input elements current_word, current_count = line.split("\t") # convert count (currently a string) to int try: current_count = int(current_count) except ValueError: # count was not a number, so # silently ignore/discard this line continue # initialize words that were not seen before with 0 if current_word not in word_2_sum: word_2_sum[current_word] = 0 word_2_sum[current_word] += current_count for word in word_2_sum: print("%s\t%i" % (word, word_2_sum[word]))
2258d02169741cf22061ea0374e50dc58a60beb3
JasperMi/python_learning
/chapter_07/rent_seat.py
179
4.125
4
rent_seat = input("How much seat do you want? ") rent_seat = int(rent_seat) if rent_seat > 8: print("There are not enough seats.") else: print("There are enough seats.")
65c77cfe0853aa9773bef4ea304ab777693b6794
daniel-reich/ubiquitous-fiesta
/LByfZDbfkYTyZs8cD_12.py
111
3.703125
4
def areaofhexagon(x): if x <= 0: return None else: return round(3 * pow(3,1/2) * pow(x,2) / 2,1)
63e8e25a11d5e18a93fa472cfdf18dda393359c7
sethuiyer/visualize-GOT
/visualise_char_deaths.py
1,878
3.671875
4
'''Question is how allegiances, nobility and the appearence in the book affect the gender of charecter deaths. ''' #Step 1: Import dependencies import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt from sklearn.manifold import TSNE from sklearn.preprocessing import LabelEncoder from sklearn.cross_validation import train_test_split #Step 2: Load the dataset chardeaths = pd.read_csv("dataset/character-deaths.csv") y=chardeaths["Gender"] chardeaths=chardeaths.drop(chardeaths.columns[[0]],1) counter_nan = chardeaths.isnull().sum() counter_without_nan=counter_nan[counter_nan == 0] chardeaths = chardeaths[counter_without_nan.keys()] chardeaths=chardeaths.drop("Gender",axis=1) le = LabelEncoder() le.fit(np.unique(y)) y_encoded=le.transform(y) le.fit(np.unique(chardeaths["Allegiances"])) chardeaths["Allegiances_encoded"]=le.transform(chardeaths["Allegiances"]) chardeaths=chardeaths.drop("Allegiances",axis=1) #chardeaths=chardeaths.drop(chardeaths.columns[[1,2,3,4,5]],axis=1) # t-distributed Stochastic Neighbor Embedding (t-SNE) visualization print chardeaths.columns.values #Standardize the feature vectors X = chardeaths.ix[:].values standard_scalar = StandardScaler() x_std = standard_scalar.fit_transform(X) test_percentage = 0.1 x_train, x_test, y_train, y_test = train_test_split(x_std, y_encoded, test_size = test_percentage, random_state = 0) tsne = TSNE(n_components=2, random_state=0) x_std_2d = tsne.fit_transform(x_test) markers=('o', 'o') color_map = {0:'red', 1:'blue'} plt.figure() for idx, cl in enumerate(np.unique(y)): plt.scatter(x=x_std_2d[y_test==cl,0], y=x_std_2d[y_test==cl,1], c=color_map[idx], marker=markers[idx], label=cl) plt.xlabel('X in t-SNE') plt.ylabel('Y in t-SNE') plt.legend(loc='upper left') plt.title('t-SNE visualization of test data') plt.show()
b7b5854abd25923d37dfcde75292dcc5733b70e4
GTRgoSky/TestLOL
/Python/PAT/pat.py
4,854
3.828125
4
# 进程和线程 ### 多进程 ##### fork 多进程模块。 """ Python的os模块封装了常见的系统调用, 其中就包括fork,可以在Python程序中轻松创建子进程 os.getpid() : 获取当前进程号 os.getppid() : 获取父级进程号 """ import os """ print('Process (%s) start...' % os.getpid()) # Only works on Unix/Linux/Mac: pid = os.fork() if pid == 0: print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())) else: print('I (%s) just created a child process (%s).' % (os.getpid(), pid)) """ """ 结果: Process (876) start... I (876) just created a child process (877). I am child process (877) and my parent is 876. Linux和Unix 或者 Mac 可执行, Window 不能执行 """ ##### multiprocessing 提供了跨平台 的 多进程模块。 """ from multiprocessing import Process # 子进程要执行的代码 def run_proc(name): print('Run child process %s (%s)...' % (name, os.getpid())) if __name__=='__main__': print('Parent process %s.' % os.getpid()) p = Process(target=run_proc, args=('test',)) print('Child process will start.') p.start() p.join() print('Child process end.') """ """ 执行结果如下: Parent process 928. Process will start. Run child process test (929)... Process end. ----------------------------------- 执行过程: 创建子进程时,只需要传入一个执行函数和函数的参数, 创建一个Process实例,用start()方法启动 join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步 """ ##### Pool 进程池 """ 如果要启动大量的子进程,可以用进程池的方式批量创建子进程 """ """ from multiprocessing import Pool import time, random def long_time_task(name): print('Run task %s (%s)...' % (name, os.getpid())) start = time.time() time.sleep(random.random() * 3)#进程休息(阻塞执行) end = time.time() print('Task %s runs %0.2f seconds.' % (name, (end - start)))# %0.2f保留两位小数 if __name__=='__main__': print('Parent process %s.' % os.getpid())#当前进程号 p = Pool(4)#开启4个进程,最多执行4个进程,所以第五个进程会等待其中一个结束后在执行 for i in range(5):#循环5次 p.apply_async(long_time_task, args=(i,))#(传入进程执行函数,传入函数所需参数(trip类型)) print('Waiting for all subprocesses done...') p.close()#调用后不能添加新的进程 Process p.join()#必须在close之后,等待所有子进程执行完毕 print('All subprocesses done.') """ """ 输出情况(不一定是这个顺序): Parent process 669. Waiting for all subprocesses done... Run task 0 (671)... Run task 1 (672)... Run task 2 (673)... Run task 3 (674)... Task 2 runs 0.14 seconds.#task2 执行结束,杀死进程号 Run task 4 (673)...#使用进程号673 Task 1 runs 0.27 seconds. Task 3 runs 0.86 seconds. Task 0 runs 1.41 seconds. Task 4 runs 1.91 seconds. All subprocesses done. """ ##### 子进程 (上述情况子进程是自身,下面的子进程并不是自身) ####### subprocess 模块可以让我们非常方便地启动一个子进程,然后控制其输入和输出 import subprocess """ print('$ nslookup www.python.org') r = subprocess.call(['nslookup', 'www.python.org']) print('Exit code:', r) """ """ print('$ nslookup') p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = p.communicate(b'set q=mx\npython.org\nexit\n')# 相当于手动输入 set q=mx python.org exit print(output.decode('oem'))# win下要用oem ,Linux用utf-8 print('Exit code:', p.returncode) """ ##### 进程间通信 Queue、Pipes等多种方式 ####### Queue ######### 在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据 from multiprocessing import Process, Queue import time, random #写数据进程执行的代码: def write(q): print('Process to write: %s' % os.getpid())#输出当前进程号 for value in ['A', 'B', 'C']: print('Put %s to queue...' % value) q.put(value)# time.sleep(random.random())#进程休眠(阻塞 # 读数据进程执行的代码: def read(q): print('Process to read: %s' % os.getpid()) while True: value = q.get(True) print('Get %s from queue.' % value) if __name__=='__main__': # 父进程创建Queue,并传给各个子进程: q = Queue() pw = Process(target=write, args=(q,))#赋值子进程 写 pr = Process(target=read, args=(q,))#赋值子进程 读 # 启动子进程pw,写入: pw.start() # 启动子进程pr,读取: pr.start() # 等待pw结束: pw.join() # pr进程里是死循环,无法等待其结束,只能强行终止: pr.terminate()
cd85ce0762726e8c98c7300d9d3d3d01ab8e41b8
bunnybryna/Learn_Python_The_Hard_Way
/ex13s.py
508
3.671875
4
from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third print "What did you have for breakfast?", breakfast = raw_input() print "What did you have for lunch?", lunch = raw_input() print "What did you have for dinner?", dinner = raw_input() print "So, you had %r for breakfast, %r for lunch and %r for dinner. " % ( breakfast, lunch, dinner)
a746afa94ba5e4c76342eff0eb0e29d8fba758b8
vjbytes101/Bigdata-project
/New York/Data Analysis/parks/unsafe_parks_queens.py
699
3.546875
4
import sys import csv from pyspark.sql import SparkSession from pyspark.sql.functions import * spark = SparkSession.builder.appName("Python Spark SQL basic example").config("spark.some.config.option", "some-value").getOrCreate() df_parking = spark.read.format("csv").option("header", "true").load("/user/edureka_123073/result.csv") df_parking.createOrReplaceTempView("crime") result = spark.sql("Select PARKS_NM as park_nm, count(PARKS_NM) as crime_count from crime where BORO_NM = 'QUEENS' group by PARKS_NM ORDER BY count(PARKS_NM) DESC limit 5") result.select(format_string('%s\t%d', result.park_nm,result.crime_count)).write.save("/Output/Analysis/unsafe_park_queens.csv",format="csv")
5f02783ba9aadddf46f029f218478112b3cbf95b
a-angeliev/Python-Fundamentals-SoftUni
/05. Password Guess.py
94
3.515625
4
a = str(input()) if a == 's3cr3t!P@ssw0rd': print('Welcome') else: print('Wrong password!')
c4ff080721938ae3003cd3df9e435f7d8e430905
comedxd/Artificial_Intelligence
/6_BreadthFirstSearch.py
4,969
3.90625
4
class LinkedListNode: def __init__(self,value=0,parent=None,leftnode=None,rightnode=None): self.value=value self.parent=parent self.left=leftnode self.right=rightnode self.visited=False def PreorderWalk(self, node): if (node is not None): print(node.value) self.PreorderWalk(node.left) self.PreorderWalk(node.right) def InorderWalk(self,node): if(node is not None): self.InorderWalk(node.left) print(node.value) self.InorderWalk(node.right) def PostorderWalk(self,node): if(node is not None): self.PostorderWalk(node.left) self.PostorderWalk(node.right) print(node.value) def TreeSearch(self,node,val): if(node is None or val==node.value): return node else: if(val<node.value): self.TreeSearch(node.left) else: self.TreeSearch(node.right) def TreeMinimum(self,node): tmp=node while(tmp.left is not None): tmp=tmp.left return tmp def TreeMaximum(self,node): tmp=node while(tmp.left is not None): tmp=tmp.right return tmp def TreeSuccessor(self,node): if(node.right is not None): return self.TreeMinimum(node.right) y=node.parent while(y is not None and node==y.right): node=y y=y.parent return y def TreePredecessor(self,node): pass def Tree_Insert(self,value): tmp=self while(tmp is not None): tmp_parent=tmp if(value<tmp.value): tmp=tmp.left elif(value>tmp.value): tmp=tmp.right newnode=LinkedListNode(value) tmp=tmp_parent newnode.parent=tmp if(tmp.left is None and value<tmp.value): tmp.left=newnode if (tmp.right is None and value > tmp.value): tmp.right = newnode def Breadth_First_Traversal(self, Graph, root): """ create a queue Q mark v as visited and put v into Q while Q is non-empty remove the head u of Q mark and enqueue all (unvisited) neighbors of u """ visited = [] # List to keep track of visited nodes. queue = [] # Initialize a queue visited.append(root) queue.append(root) while queue: s = queue.pop(0) print(s, end=" ") for neighbour in graph[s]: if neighbour not in visited: visited.append(neighbour) queue.append(neighbour) def Breadth_First_Traversal_Tree(self, root): #visited = [] # List to keep track of visited nodes. queue = [] # Initialize a queue #visited.append(root) queue.append(root) while queue: s = queue.pop(0) print(s.value, end=" ") for child in (s.left,s.right): if (child is not None ) and (child.visited==False): child.visited=True queue.append(child) def Breadth_First_Traversal_Tree_Search(self, root,value): queue = [] values=[] queue.append(root) values.append(root.value) while queue: s = queue.pop(0) #print(s.value, end=" ") if(s.value==value): print("Value found") return print(values) values.clear() for child in (s.left,s.right): if (child is not None ) and (child.visited==False): child.visited=True queue.append(child) values.append(child.value) if __name__=="__main__": # Assignment-1: implement the BFT using tree data structure # Assignment-2: convert the bft search method to Breadth First Search where user passes a value and # using breadth first search, find the value graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } tree=LinkedListNode() tree.Breadth_First_Traversal(graph,'A') #=========== using tree data structure root = LinkedListNode(20) root.Tree_Insert(21) root.Tree_Insert(30) root.Tree_Insert(10) root.Tree_Insert(9) root.Tree_Insert(15) root.Tree_Insert(14) root.Tree_Insert(18) root.Tree_Insert(25) root.Tree_Insert(24) root.Tree_Insert(28) #root.Breadth_First_Traversal_Tree(root) print("===============================") root.Breadth_First_Traversal_Tree_Search(root, 24)
7657df7ce1a2ac63e694cc972b36da9d457286a6
702criticcal/1Day1Commit
/Baekjoon/9095.py
187
3.65625
4
for _ in range(int(input())): n = int(input()) nums = [0, 1, 2, 4] for i in range(4, n + 1): nums.append(nums[i - 3] + nums[i - 2] + nums[i - 1]) print(nums[n])
66afab404dc3f595fe1bedc36673e8a3af47f0c4
DT2004/intro-to-python-arithmetic-
/simple_arithmetic.py
198
3.78125
4
print(1+2) # this function is for addition print(30%2)# this is for finding out the remainder print(1984928347/10823) #using vaariables a = 10 b = 2 print(a/b) #prints out to 5.0 not 5 print(a/b)
aad6d219277e41030628948cf8ad916298f6eb26
nischalshk/IWPython
/Functions/2.py
225
4.0625
4
# Write a Python function to sum all the numbers in a list. # Sample List : (8, 2, 3, 0, 7) # Expected Output : 20 def sumAll(l): sum = 0 for i in l: sum += i return sum print(sumAll([0, 1, 2, 3, 4]))
f616747588095625b937947541a403c41f8d31d8
chuanfanyoudong/algorithm
/leetcode/DividedTwoIntegers.py
963
3.734375
4
""" @author: zkjiang @contact: jiang_zhenkang@163.com @software: PyCharm @file: DividedTwoIntegers.py @time: 2019/2/20 22:49 """ import math class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ positive = (dividend < 0) is (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) res = 0 while dividend >= divisor: temp, i = divisor, 1 while dividend >= temp: dividend -= temp res += i i <<= 1 # i 记录的就是当前temp是几个divisor,是几个就加上几,这样就不是一个一个diviso的加了,是根据2的平方数加,所以会快。 temp <<= 1 if not positive: res = -res return min(max(-2147483648, res), 2147483647) if __name__ == '__main__': a = Solution() print(a.divide(15,3))
55ff6c1d07e6d079e8a6b0589aaf4495ae1c6337
MikhailRyskin/Lessons
/Module29/03_format_logging/main.py
738
3.515625
4
from log_module import log_methods @log_methods("b d Y - H:M:S") class A: def test_sum_1(self) -> int: print('test sum 1') number = 100 result = 0 for _ in range(number + 1): result += sum([i_num ** 2 for i_num in range(10000)]) return result @log_methods("b d Y - H:M:S") class B(A): def test_sum_1(self): super().test_sum_1() print("Наследник test sum 1") def test_sum_2(self): print("test sum 2") number = 200 result = 0 for _ in range(number + 1): result += sum([i_num ** 2 for i_num in range(10000)]) return result my_obj = B() my_obj.test_sum_1() my_obj.test_sum_2() # зачёт!
c377de2b7e19833a7745caec7dfda790014bf8dd
trigodeepak/Programming
/Palindrome_partioning.py
1,531
4.15625
4
#Program for palindrome partitioning def minPalPartition(string): length = len(string) dp_cuts = [[0 for i in range(length)]for x in range(length)] #This matrix is to determine that the given substring is palindrome or not p = [[False for i in range(length)]for x in range(length)] #This loop is to access the matrix diagonally from left to right for k in range(length): i = 0 j = k while(i<length-k): #First 3 conditions are to check if substring is palindrome if i == j: p[i][j] = True dp_cuts[i][j] = 0 elif k+1 == 2: p[i][j] = (string[i] == string[j]) else: p[i][j] = (string[i] == string[j]) and p[i+1][j-1] #Following conditions are to find the minimum cut if (p[i][j]==True): dp_cuts[i][j] = 0 else: dp_cuts[i][j] = float('inf') #Make a cut at every possible location and get the minimum cost for x in range(i,j): dp_cuts[i][j] = min(dp_cuts[i][j],dp_cuts[i][x]+dp_cuts[x+1][j]+1) i+=1 j+=1 #Uncomment below lines to print the matrix obtained ## for row in dp_cuts: ## print row #returning the minimum cut value return dp_cuts[0][length-1] #Driver program string = "ababbbabbababa"#raw_input().strip() #to take user input print "Minimum cuts to form a palindrome is :",minPalPartition(string)
3468cc033a160811c97cfbf0f6ba37ae1eeac953
alphatrl/IS111
/Lab Tests/2018.1 Lab Test/Original/q3.py
440
3.515625
4
def mask_out(sentence, banned, substitutes): # write your answer between #start and #end #start return '' #end print('Test 1') print('Expected:abcd#') print('Actual :' + mask_out('abcde', 'e', '#')) print() print('Test 2') print('Expected:#$solute') print('Actual :' + mask_out('absolute', 'ab', '#$')) print() print('Test 3') print('Expected:121hon') print('Actual :' + mask_out('python', 'pyt', '12')) print()
5664be4f80364bd712b04324ab79f3f1f3811bd0
iftakher-m/Library-database-app
/backend.py
1,686
3.625
4
import sqlite3 class Database: def __init__(self, db): # if "self" isn't written, "database" object from 'frontend' will be passsed there. self.conn = sqlite3.connect(db) self.cur = self.conn.cursor() # 'self' to make 'cur' an attribute of 'database' object and later use in other functions. self.cur.execute("CREATE TABLE IF NOT EXISTS library (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer) ") self.conn.commit() def insert(self,title,author,year,isbn): self.cur.execute("INSERT INTO library VALUES (NULL,?,?,?,?) ", (title,author,year,isbn)) self.conn.commit() def view(self): self.cur.execute("SELECT * FROM library") rows= self.cur.fetchall() return rows def search(self,title="", author="", year="", isbn=""): self.cur.execute("SELECT * FROM library WHERE title=? or author=? or year=? or isbn=?" ,(title,author,year,isbn)) rows= self.cur.fetchall() return rows def delete(self,id): self.cur.execute("DELETE FROM library WHERE id=?", (id,)) self.conn.commit() def update(self,id,title,author,year,isbn): self.cur.execute("UPDATE library SET title=?, author=?, year=?, isbn=? WHERE id=?", (title,author,year,isbn,id)) self.conn.commit() def __del__(self): # Delete the object when the script is discarded, similar to 'destructor', not mandatory to use. self.conn.close() # connect() # insert('The sun','John mun',4665,235545) # update(4,"Good life","Stanley clark",3677,3432090) # print(view()) # delete(2) # print(search(isbn=455))
0fe163504a3ff957a7ef925799f778471a0296b5
dwightmulcahy/healthchecker.server
/uptime.py
1,014
3.6875
4
from datetime import datetime class UpTime: def __init__(self): self.startDatetime = datetime.now() def __repr__(self): return self.__str__() def current(self): return (datetime.now() - self.startDatetime).total_seconds() def __str__(self): return self.timetostring(self.current()) def timetostring(self, time): seconds = int(time) periods = [ ('year', 60 * 60 * 24 * 365), ('month', 60 * 60 * 24 * 30), ('day', 60 * 60 * 24), ('hour', 60 * 60), ('minute', 60), ('second', 1) ] strings = [] for period_name, period_seconds in periods: if seconds >= period_seconds: period_value, seconds = divmod(seconds, period_seconds) has_s = 's' if period_value > 1 else '' strings.append("%s %s%s" % (period_value, period_name, has_s)) return ", ".join(strings) if __name__ == '__main__': uptime = UpTime() print(str(uptime))
b7d6028761718e621b3740fef73d27d03be44d76
wassimmarrakchi/crimtechcomp
/assignments/Wassim Marrakchi/000-code/assignment.py
1,264
4.03125
4
# Color: Crimson def say_hello(): print("Hello, world!") # Prints message back out to console def echo_me(msg): print(msg) def string_or_not(d): exec(d) def append_msg(msg): print("Your message should have been: {}!".format(msg)) # TODO: understanding classes (an introduction) class QuickMaths(): def add(self, x, y): return x+y def subtract(self, x, y): return x-y def multiply(self, x, y): return x*y def divide(self, x, y): return x/y # TODO: implement - can you do this more efficiently? def increment_by_one(lst): for x in range(len(lst)): lst[x] = lst[x] + 1 return lst # TODO: understand - do we need a return statement here? why? def update_name(person, new_name): person["name"] = new_name # TODO: implement - these are still required, but are combinations of learned skills + some def challenge1(lst): lst.reverse() new_lst = [] for x in lst: string = "" for y in range(len(x)): string = x[y] + string new_lst.append(string) return new_lst # TODO: implement def challenge2(n): divisors = [] for x in range(1,n/2): if n % x == 0: divisors.append((x,n/x)) return divisors
d5d4d87ebbe418f35fd7ad97a5aff966305ff0ed
liamdebellada/python-utilities-collection
/class-practice.py
1,426
3.5625
4
class setup(): def __init__(self, name, status): self.name = name self.status = status def getName(self): return self.name def getStatus(self): return self.status bools = { "true" : True, "false" : False } for item in bools: print(item) for key, value in bools.items(): print(f'String representation: {key}, Boolean representation: {value}') data = {} def getValues(x): for key, value in x.items(): return value arrofdict = [{"test": 1}, {"test2": 2}] print(arrofdict) print([getValues(x) for x in arrofdict]) testlist = [1,2,4,3] for count, i in enumerate(testlist): print(f'Counter value: {count}, Item at counter value index: {i}') query = input("Enter search query for testlist: ") try: print(list(filter(lambda x: x==int(query), testlist))) except: print("invalid") checking = True while checking: name = input("Enter name: ") status = input("Enter status (true/false): ") try: data[name] = setup(name, bools[status]) except: print("One or more fields are invalid") if len(data) == 3: checking = False for x in data: print("Objects:", x) getData = True while getData: selection = input("Enter one of the objects name: ") try: res = data[selection] print(f'{res.name} -> {res.getStatus()}') except: print("Object name not found")
1a997b9760eeeaedfa96f2fcaafa8773fb34664b
1998sachin/CP_reference-material
/Algorithm/DP/factoiral_recursion.py
169
4.125
4
#this is simplest recursive factorial function, it performs very bad def fact(n): if n==1 or n==0: return 1 else: return n*fact(n-1) n=int(input()) print(fact(n))
a959ec08ece97215c5649ed82685c9759b2292a1
kristjanlink/python-wrangling
/process_icons.py
718
3.65625
4
#!/usr/bin/env python3 import os from PIL import Image def process_icons(): """Rotates images 90 degrees clockwise, resizes them to 128 x 128 and saves them in *.jpeg format.""" for image in os.listdir("images"): if not image.startswith('.'): # To skip system files such as ".DS_Store" with Image.open("images/" + image) as im: im = im.rotate(90) im = im.resize((128, 128)) im = im.convert("RGB") # To be able to convert from *.tiff # Split path to file into path with filename and extension, then take path only # (which is just the filename in the current case) im.save("/opt/icons/" + os.path.splitext(image)[0], "JPEG") def main(): process_icons() main()
ca600902fbb0e8724b6719bc087c64e135d4dbc0
mrstevenlu/Tuple-and-List
/01.py
740
3.671875
4
# -*- coding: UTF-8 -*- # Filename : 01-string.py23 # author by : Steven Lu # 目的: # 列表和元组 print("开始") import random List1 = ['张飞','赵云','马超','吕布'] Tup1 = ('刘备','曹操','孙权') pos = 0 value = List1[pos] print("取出列表的第%d个值,它是%s"%(pos,value)) print ("输出列表中所有元素") pos = 0 for v in List1: print ("取出列表的第%d个值,它是%s"%(pos,v)) pos = pos + 1 print("开始") newvalue = '关羽' List1[0] = newvalue print("取出列表的第%d 个值, 它是%s"%(pos,v)) pos = 0 for v in List1: print ("取出列表的第%d个值,它是%s"%(pos,v)) pos = pos + 1 print("开始") for i in range(1,5): s= random.choice(List1) print(s)
f89760eff8f701d69c71b82dc06122a7f84501d7
DickyHendraP/Phyton-Projects-Protek
/Pratikum 10/Nomor 3.py
510
3.734375
4
#Program Memofifikasi dari nomor 2 #Program akan diperoleh variable bertipe data ditionari #Membuka file file = open("file.txt" , "r") #Membaca file secara per baris data = file.readlines() #Membuat dictionari kosong dataMHS = {} for i in range(len(data)) : Mhs = data[i] #Memisah data a,b,c = Mhs.split('|') a,b,c= a,b,c.replace('\n', '') #Membuat Dictionari dataMahasiswa = {'nim' : a, 'nama' : b, 'alamat' : c} dataMHS[a] = dataMahasiswa print(dataMHS) #Menutup file file.close
d4543122f9435b9d0680ba2e06cf5df710507fa3
yingxingtianxia/python
/PycharmProjects/my_python_v03/base1/ent.py
572
3.640625
4
#!/usr/bin/env python3 #--*--coding: utf8--*-- import keyword import string first_chs = string.ascii_letters + '_' all_chs = first_chs + string.digits def check_id(idt): if idt[0] not in first_chs: return '1st char invalid.' for ind, cha in enumerate(idt[1:]): if cha not in all_chs: return '第%s个字符%s非法' % (ind+2, cha) if idt in keyword.kwlist: return '%s为关键字' % idt return '合法字符' if __name__ == '__main__': idt = input('请输入带检测的标示符:') print(check_id(idt))
a413379d2e7aa18ef97ff8b6835bb45fd4c6b734
elMimu/python-bootcamp
/fatorial.py
102
3.609375
4
def fatorial(x): if x == 0: return 1 return x*fatorial(x -1) N = int(input()) print(fatorial(N))
3f1f692d9c46f727cf263bdd5dfd2395975bd717
manticorevault/100ProjectsIn100Days
/Day 1 - Random Phrases Game.py
3,008
3.5
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 7 15:03:50 2016 @author: Artur """ import random import time def regrasDoJogo(): print("\nNão se sabe muito bem como esse jogo surgiu, mas ele") print("foi trazido para o ocidente pelo bardo e mercador Tenório.") print("Esse jogo fez muito sucesso no 1º Ano do Ensino Médio") print("de um colégio em Aracaju, capital de Sergipe, pois servia") print("como atrativo para os alunos sobreviverem às longas") print("e tediosas aulas. Agora ele foi transformado em um jogo") print("de computador para ser imortalizado em forma digital.") print("\nAs regras do jogo são bem simples. Você só precisa escrever") print("o que o jogo pede e ele criará frases aleatórias baseadas no") print("que você escreveu. E sim, nós nos divertíamos muito com isso.") print("\nPara a primeira experiência, é recomendado jogar com 5 itens.") def jogoDaFuleragem(num, tema): while True: listTema = [] count = 1 print("\nDigite", num, tema +": \n") while count <= num: item = input("- ") print(count, "-", item) listTema.append(item) count += 1 print("\nSua lista é:\n", listTema) confirm = input("Deseja confirmar essa lista? S/N ") if confirm.lower() == "s": print("Lista confirmada!\n") break else: print("Vamos refazer a lista, então!") return listTema def montadorDeFrases(lista1, lista2, lista3, lista4, lista5): frases = 0 while frases < num: item1 = random.choice(lista1) lista1.remove(item1) item2 = random.choice(lista2) lista2.remove(item2) item3 = random.choice(lista3) lista3.remove(item3) item4 = random.choice(lista4) lista4.remove(item4) item5 = random.choice(lista5) lista5.remove(item5) print("\n", item1, item2, item3, "no/na", item4, "de", item5) frases += 1 while True: regrasDoJogo() num = int(input("\nCom quantos items você pretende jogar? \n")) lista1 = jogoDaFuleragem(num, "pessoas que você gosta") lista2 = jogoDaFuleragem(num, "verbos de movimento na 3ª pessoa") lista3 = jogoDaFuleragem(num, "objetos") lista4 = jogoDaFuleragem(num, "partes do corpo humano") lista5 = jogoDaFuleragem(num, "pessoas que você não gosta") montadorDeFrases(lista1, lista2, lista3, lista4, lista5) print("\nEspero que você tenha se divertido!") replay = input("Você quer jogar de novo? S/N ") if replay.lower() == "s": print("Okay, então vamos lá! :D/n/n") else: print("Tudo bem, nos vemos na próxima! Obrigado por ter jogado! :D") time.sleep(4) break
7649c75bb9c05639ea9ab367dfc1067cee62b7d0
kotaro0522/python
/procon20180512/exponential.py
564
3.640625
4
x = int(input()) maximum = 1 for i in range(2,32): if i*i <= x and i*i > maximum: maximum = i*i for i in range(2, 11): if pow(i,3) <= x and pow(i,3) > maximum: maximum = pow(i,3) for i in range(2, 6): if pow(i,4) <= x and pow(i,4) > maximum: maximum = pow(i,4) for i in range(2, 4): if pow(i,5) <= x and pow(i,5) > maximum: maximum = pow(i,5) for i in range(2, 4): if pow(i,6) <= x and pow(i,6) > maximum: maximum = pow(i,6) for i in range(7,10): if pow(2,i) <= x and pow(2,i) > maximum: maximum = pow(2,i) print(maximum)
7ed478ff7b098fca0dce8fe05a1514b5c74a4ce4
yemao616/summer18
/Google/2. medium/356. Line Reflection.py
1,190
3.71875
4
# Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points. # Example 1: # Given points = [[1,1],[-1,1]], return true. # Example 2: # Given points = [[1,1],[-1,-1]], return false. # Follow up: # Could you do better than O(n2)? class Solution(object): def isReflected(self, points): """ :type points: List[List[int]] :rtype: bool """ n = len(points) if n <= 1: return True min_x = max_x = points[0][0] s = set() for p in points: min_x = min(min_x, p[0]) max_x = max(max_x, p[0]) s.add((p[0], p[1])) total = min_x + max_x for x, y in points: if (total - x, y) not in s: return False return True class Solution(object): def isReflected(self, points): """ :type points: List[List[int]] :rtype: bool """ if not points: return True X = min(points)[0] + max(points)[0] return {(x, y) for x, y in points} == {(X - x, y) for x, y in points}
459d145e8f8cd0b95a2a366c0bad86b326c6232f
zhaxylykova/LAB2-TSIS4
/n.py
732
3.828125
4
def addition(a, b): if a == b: return a + b if a > b: if b == 0: return a else: if b > 0: recurs = addition(a, b-1) + 1 return recurs else: recurs = addition(a, b+1) - 1 return recurs if a < b: if a == 0: return b else: if a > 0: recurs = addition(a - 1, b) + 1 return recurs else: recurs = addition(a + 1, b) - 1 return recurs number1, number2 = input().split() number1 = int(number1) number2 = int(number2) answer = addition(number1, number2) print(answer)
5d663c38ce8bb0ba38d9e62aa8ef6217f75f3ce5
dawidsielski/Python-learning
/sites with exercises/w3resource.com/Python Basics/ex34.py
125
3.625
4
def sum(a,b): result = a + b if result >= 15 and result <= 20: return 20 return result print(sum(10,11))
c3b79bac781e64a42b86c03ee81756d923f87dce
guhwanbae/GuLA
/orthogonality/qr_factorization.py
826
3.96875
4
# Author : Gu-hwan Bae # Summary : Find the QR factorization and solving a linear equation. import numpy as np import gula.qr as gQR # Case I : QR decomposition. Find the QR factorization, QR = A. print('Find the QR factorization.') # Col A is linear independent. A = np.array([[1, 1, 0], [1, 1, 1], [0, 1, 1]]) Q, R = gQR.decomposition(A) print('A =\n', A) print('Q =\n', Q) print('R =\n', R) print('QR =\n', np.dot(Q, R)) print('-' * 20) # Case II : Solving a linear equation with a coefficient matrix A which has # linearly independent column vectors. print('Solving a linear equation.') A = np.array([[1, 1, 0], [1, 1, 1], [0, 1, 1]]) b = np.array([2, 3, 5]) x = gQR.solve(A, b) print('A =\n', A) print('b =', b) print('x =', x) print('A*x =', np.dot(A, x))
ae38f4b38413c9e7785cae84334bb1f73de17dba
snowcity1231/python_learning
/list/list.py
582
4.125
4
# -*- coding: UTF-8 -*- # 列表的数据项不需要具有相同的类型 list1 = ['physics', 'chemistry', 1997, 2000] #列表截取 print "list1[0]: ", list1[0] print "list1[2:5]: ", list1[1:3] print "list1[-2]:", list1[-2] # 扩展列表 list = [] list.append('Google') print "list: ", list # 删除元素 print 'list1:', list1 del list1[2] print "after deleting list1:", list1 # 列表操作符 print "长度:", len(list1) print "组合: ", list1 + list1 print "重复: ", list1 * 3 print "是否存在: ", 1998 in list1 print "迭代:", for x in list1 : print x,",", print
204277b17a086cbdf263c3fd30576f32f703cdbb
mustafa7777/LPTHW
/ex21_2.py
879
4.09375
4
def add(a, b): print "ADDING %d to %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d from %d" % (b, a) return a - b def multiply(a, b): print "MULTIPLYING %d with %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d by %d" % (a, b) return a / b print "lets do some math:\n" first_calculation = add(3, 5) second_calculation = subtract(6, 4) third_calculation = multiply(10, 5) fourth_calculation = divide(100, 25) print "Our calculations are as follows:\n%d\n%d\n%d\n%d\n" % (first_calculation, second_calculation, third_calculation, fourth_calculation) print "Now we're going to play around with numbers calculated above:\n" final_calculation = add(first_calculation, subtract(second_calculation, multiply(third_calculation, divide(fourth_calculation, 1)))) print "The final result is ", final_calculation
92da57cf9d9b87376f945b14ced331d9674fd04a
pnguyen90/HogDiceGame
/strategies.py
7,637
4.1875
4
from dice import * from hog import * ####################### # Phase 2: Strategies # ####################### # This file is the testing ground for strategies. first make your strategy or strategies. # To run your strategy against another one, modify the run_experiments function. # # Experiments """Below are some functions used to play strategies against each other and find out statistical advantages of one strategy over another""" '''Below is our first super basic strategy.''' def always_roll(n): """Return a strategy that always rolls N dice. A strategy is a function that takes two total scores as arguments (the current player's score, and the opponent's score), and returns a number of dice that the current player will roll this turn. >>> strategy = always_roll(5) >>> strategy(0, 0) 5 >>> strategy(99, 99) 5 """ def strategy(score, opponent_score): return n return strategy def make_averaged(fn, num_samples=1000): """Return a function that returns the average_value of FN when called. To implement this function, you will have to use *args syntax, a new Python feature introduced in this project. See the project description. >>> dice = make_test_dice(3, 1, 5, 6) >>> averaged_dice = make_averaged(dice, 1000) >>> averaged_dice() 3.75 >>> make_averaged(roll_dice, 1000)(2, dice) 5.5 In this last example, two different turn scenarios are averaged. - In the first, the player rolls a 3 then a 1, receiving a score of 0. - In the other, the player rolls a 5 and 6, scoring 11. Thus, the average value is 5.5. Note that the last example uses roll_dice so the hogtimus prime rule does not apply. """ # BEGIN Question 6 def helper(*args): sum = 0 count = 0 while (count < num_samples): sum += fn(*args) count += 1 return sum/num_samples return helper # END Question 6 def max_scoring_num_rolls(dice=six_sided, num_samples=1000): """Return the number of dice (1 to 10) that gives the highest average turn score by calling roll_dice with the provided DICE over NUM_SAMPLES times. Assume that dice always return positive outcomes. >>> dice = make_test_dice(3) >>> max_scoring_num_rolls(dice) 10 """ # BEGIN Question 7 def roll_n(n): return roll_dice(n, dice) n = 1 top_score = 0 top_dice_num = 1 current_score = 0 while (n < 11): current_score = make_averaged(roll_n, num_samples)(n) if (current_score > top_score): top_score = current_score top_dice_num = n n += 1 return top_dice_num # END Question 7 def winner(strategy0, strategy1): """Return 0 if strategy0 wins against strategy1, and 1 otherwise.""" score0, score1 = play(strategy0, strategy1) if score0 > score1: return 0 else: return 1 def average_win_rate(strategy, baseline=always_roll(5)): """Return the average win rate of STRATEGY against BASELINE. Averages the winrate when starting the game as player 0 and as player 1. """ win_rate_as_player_0 = 1 - make_averaged(winner,10000)(strategy, baseline) win_rate_as_player_1 = make_averaged(winner,10000)(baseline, strategy) return (win_rate_as_player_0 + win_rate_as_player_1) / 2 def run_experiments(): """Run a series of strategy experiments and report results.""" if False: # Change to False when done finding max_scoring_num_rolls six_sided_max = max_scoring_num_rolls(six_sided) print('Max scoring num rolls for six-sided dice:', six_sided_max) four_sided_max = max_scoring_num_rolls(four_sided) print('Max scoring num rolls for four-sided dice:', four_sided_max) if False: # Change to True to test always_roll(8) print('always_roll(2) win rate:', average_win_rate(always_roll(3))) if False: # Change to True to test bacon_strategy print('bacon_strategy win rate:', average_win_rate(bacon_strategy)) if False: # Change to True to test swap_strategy print('swap_strategy win rate:', average_win_rate(swap_strategy)) if True: # Change to True to test final_strategy print ('final_strategy win rate:', average_win_rate(final_strategy,always_roll(5))) # Strategies """Below are various hog strategy functions""" def always_roll(n): """Return a strategy that always rolls N dice. A strategy is a function that takes two total scores as arguments (the current player's score, and the opponent's score), and returns a number of dice that the current player will roll this turn. >>> strategy = always_roll(5) >>> strategy(0, 0) 5 >>> strategy(99, 99) 5 """ def strategy(score, opponent_score): return n return strategy def bacon_strategy(score, opponent_score, margin=8, num_rolls=5): """This strategy rolls 0 dice if that gives at least MARGIN points, and rolls NUM_ROLLS otherwise. """ # BEGIN Question 8 "*** REPLACE THIS LINE ***" if margin <= take_turn(0,opponent_score, select_dice(score,opponent_score)): return 0 else: return num_rolls # Replace this statement # END Question 8 def swap_strategy(score, opponent_score, num_rolls=5): """This strategy rolls 0 dice when it results in a beneficial swap and rolls NUM_ROLLS otherwise. """ # BEGIN Question 9 score += take_turn(0,opponent_score,select_dice(score,opponent_score)) if is_swap(score, opponent_score) and (opponent_score > score): return 0 else: return num_rolls # Replace this statement # END Question 9 ## winning candidate def final_strategy(score, opponent_score): bacon = take_turn(0, score, opponent_score) the_dice = select_dice(score , opponent_score) if the_dice == six_sided: margin = 7 else: margin = 3 def opt_num(dice, my_score, opponent_score): if dice == six_sided: if my_score >= 89: if bacon > margin: return 0 else: return 2 else: if bacon > margin: return 0 else: return 4 else: if my_score >= 93: if bacon > margin: return 0 else: return 1 else: if bacon > margin: return 0 else: return 4 def piggy_swap(score,opponent_score): if is_swap((opponent_score + 10), score) : return 10 if is_swap((opponent_score + 9), score) : return 9 if is_swap((opponent_score + 8), score) : return 8 if is_swap((opponent_score + 7), score) : return 7 if is_swap((opponent_score + 6), score) : return 6 if is_swap((opponent_score + 5), score) : return 5 if is_swap((opponent_score + 4), score) : return 4 if is_swap((opponent_score + 3), score) and the_dice == four_sided: return 3 else: return False if opponent_score <= 80 and score <= 70: if piggy_swap(score, opponent_score) != False: return piggy_swap(score, opponent_score) else: return 7 elif opponent_score >= 81 and score <= 70: return -1 else: return opt_num(the_dice, score, opponent_score)
d3f502b87fe2a7b857ef922e6d2e20aba2eebd02
nahomtefera/udacity_datastructures_algorithms
/P2/Problem_5/Autocomplete_with_Tries.py
2,219
4.125
4
## Represents a single node in the Trie class TrieNode: def __init__(self): ## Initialize this node in the Trie self.is_word = False self.children = {} def insert(self, char): ## Add a child node in this Trie if char in self.children: return self.children[char] = TrieNode() def suffixes(self, suffix='', list=[]): ## Recursive function that collects the suffix for ## all complete words below this point for char in self.children: if self.children[char].is_word: list.append(suffix + char) self.children[char].suffixes(suffix + char, list) return list ## The Trie itself containing the root node and insert/find functions class Trie: def __init__(self): ## Initialize this Trie (add a root node) self.root = TrieNode() def insert(self, word): ## Add a word to the Trie node = self.root for char in word: if not char in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_word = True def find(self, prefix): ## Find the Trie node that represents this prefix if prefix == '' or prefix is None: return 'Enter non-empty prefix' node = self.root for char in prefix: if not char in node.children: return 'Not Found' node = node.children[char] return node # Testing it all out # Run the following code to add some words to your trie and then use the interactive search box to see what your code returns. MyTrie = Trie() wordList = [ "ant", "anthology", "antagonist", "antonym", "fun", "function", "factory", "trie", "trigger", "trigonometry", "tripod" ] for word in wordList: MyTrie.insert(word) # Aditional Test cases # Null value find_word = MyTrie.find(None) print(find_word) # Returns 'Enter non-empty prefix' # Empty string find_word = MyTrie.find('') print(find_word) # Returns 'Enter non-empty prefix' # Testing suffix method suffix = MyTrie.find('a') print(suffix.suffixes()) #['nt', 'ntagonist', 'nthology', 'ntonym']
a409961ac62b913219e2ff641656a97ed659b366
MysteriousSonOfGod/adventure_engine
/mechanics.py
3,248
3.75
4
#!/usr/bin/env python27 # -*- coding: utf-8 -*- import sys import yaml import colorama from colorama import Fore, Back, Style class BaseAdventure: """This is a base class for all of our adventure objects.""" def __init__(self, name, description): self.name = name self.description = description def look(self): return self.description def __str__(self): return self.name def __repr__(self): return self.name class Character(BaseAdventure): def __init__(self, name, startarea): self.name = name self.location = startarea self.inventory = [] def move(self, direction): area = self.location.exits.get(direction, None) if area: self.location = self.location.exits[direction] self.look() else: print "You don't see any way to go {}".format(direction) def drop(self, item): try: self.location.inventory.push(self.location.remove(item)) except: print "Couldn't drop {}".format(item) def take(self, item): try: self.inventory.push(self.location.inventory.remove(item)) except: print "Couldn't take {}".format(item) def look(self): look_str = "You find yourself in {}\n {}\n Objects: {}\n Exits: {}" return look_str.format( self.location, self.location.description, self.location.inventory, self.location.exits) class Area(BaseAdventure): def __init__(self, name, description): self.name = name self.description = description self.exits = dict() self.inventory = [] def addPath(self, direction, area): self.exits[direction] = area class Item(BaseAdventure): def __init__(self, name, description, hidden=False): self.name = name self.description = description self.hidden = hidden def __str__(self): return ''.join([Fore.BLUE, self.name]) class Game: def __init__(self): first = Area("first", "this is first area") second = Area("second", "this is the second area") first.addPath("south", second) self.maincharacter = Character("ranman", first) def parse_command(self, commandstr): command = commandstr.split() if "go" == command[0]: self.maincharacter.move(command[1]) if "look" == command[0]: print self.maincharacter.look() if "take" == command[0]: self.maincharacter.take(command[1]) if "drop" == command[0]: self.maincharacter.drop(command[1]) def run(self): colorama.init(autoreset=True) # automatically reset colors prompt_str = ''.join(['\n', Fore.RED, '> ']) try: print self.maincharacter.look() while True: commandstr = raw_input(prompt_str).lower().strip() if not commandstr: continue self.parse_command(commandstr) except (KeyboardInterrupt, EOFError): print "\n Good Game!" sys.exit() if __name__ == '__main__': game = Game() game.run()
885a4763dc59947a1d6382a9af13bf5a753ab4df
sandjes1046/Grade-Visualization-System
/Client/LoginGUI1.py
3,756
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 9 22:59:02 2021 @author: DanielSanchez """ import tkinter as tk from tkinter import ttk import tkinter.messagebox as msb from tkinter import * class loginGUI: def redirectToSignUp(self): self.command = "sign up" self.win.destroy() def get_info(self): if(self.command == "sign up"): info = [f"{self.command}"] if(self.command == "exit GVS"): info = [f"{self.command}"] if(self.command == "log in"): if(self.v0.get() == 1): role = "teacher" if(self.v0.get() == 0): role = "student" info = [self.command,role, str(self.realemail),str(self.realpassword)] return(info) def close(self): self.win.destroy() def on_closing(self): if msb.askokcancel("Exit", "Do you really want to exit?"): self.command = "exit GVS" self.win.destroy() def password_validate(self): password=self.password.get() self.realpassword = password.strip() self.submit_form() def submit_form(self): email=self.email.get() self.realemail = email.strip() self.command = "log in" print(f" Thanks for logging in {email}") self.win.destroy() def __init__(self): self.win = tk.Tk() self.email = tk.StringVar() self.password = tk.StringVar() self.win.title("UTRGV Gradebook Visualization System(GVS)") w, h = self.win.winfo_screenwidth(), self.win.winfo_screenheight() self.win.geometry('400x400+525+250') self.win.configure(background = "orange"); self.win.protocol("WM_DELETE_WINDOW", self.on_closing) self.loginInfo = ttk.LabelFrame(self.win, text=' Login: ') self.loginInfo.grid(column=0, row=0,rowspan=10,columnspan=1, padx=10, pady=5,sticky='EWNS') self.win.grid_rowconfigure(0, weight=0) self.win.grid_columnconfigure(0, weight=1) self.win.resizable(0,0) email_label = ttk.Label(self.loginInfo ,text = "Enter Email") self.email_entry = ttk.Entry(self.loginInfo, width=20, textvariable=self.email) email_label.grid(column=0, row=0, rowspan=1,columnspan=1,sticky='W') self.email_entry.grid(column=1, row=0, rowspan=1,columnspan=1,sticky='W') password_label = ttk.Label(self.loginInfo ,text = "Enter Password") self.password_entry = ttk.Entry(self.loginInfo, width=20, textvariable=self.password,show='*') password_label.grid(column=0, row=2, rowspan=1,columnspan=1,sticky='W') self.password_entry.grid(column=1, row=2, rowspan=1,columnspan=1,sticky='W') submit_button = ttk.Button(self.loginInfo, text = "Submit", command=self.password_validate) submit_button.grid(column=0, row=4,sticky='W') signUp_button = ttk.Button(self.loginInfo, text = "Sign up!", command=self.redirectToSignUp) signUp_button.grid(column=1, row=4,sticky='W') self.v0=IntVar() self.v0.set(0) r1=Radiobutton(self.loginInfo, text="Faculty", value=1, variable = self.v0) r1.grid(column = 2, row = 4) r2=Radiobutton(self.loginInfo, text="Student", value=0, variable = self.v0) r2.grid(column = 3, row = 4) self.win.mainloop() if __name__ == "__main__": loginGUI() else: print("Code is being imported into another module")
16b83a6a51a47fa2ffe6ee25ba5225f0a91d9c73
jfernand196/Ejercicios-Python
/primer_ultimo_lista.py
312
3.8125
4
#Obtener el primer y ultimo elemento de una lista lista = ['juan', 'mateo', 'yamile', 'vero'] primer_elemento = lista[0] #OPCION 1 #ultimo_elemento = lista[len(lista) -1] #OPCION 2 CON SLICE ultimo_elemento = lista[-1] print(' primer elemento: {} y ultimo elemento: {}'.format(primer_elemento, ultimo_elemento))
4a873c4721c07c080be39db750042292b6fc9691
SyedSaifi/PythonExample
/com/example/pythonex/InheritanceEx.py
575
3.796875
4
''' Created on Feb 19, 2017 @author: ssaifi ''' class Parent: value1="Value One" def __init__(self,name, age): self.name=name self.age=age def changeAge(self,age): self.age = age def __str__(self): return self.name+" -- "+str(self.age) class Child(Parent): def __init__(self,name, age, grade): Parent.__init__(self,name,age) self.grade=grade def __str__(self): return Parent.__str__(self)+"--"+str(self.grade) c1=Child("syed",30,9) print(c1.value1) print(c1) c1.changeAge(29) print(c1)
fe1b9833294d39692842ecc536b2781fc62be6da
CxpKing/script_study
/python/基础/data_type.py
3,611
4.125
4
''' 关于python的数据类型,元组、列表、字典以及集合四大 数据类型的定义、使用及其各自的特性 ''' #元组 tup1 = ('A','B','C') print('tup1->',tup1) #列表 list1 = ['A','B','C'] print('list1->',list1) #字典 dict1 = {'key1':'value1','key2':'value2'} print('dict1->',dict1) #集合 #方式1 使用符号 {} set1 = {'A','B','C'} print('set1->',set1) #方式2 使用 set() 其参数为一个元组, set2 = set(('A','B','C')) print('set2->',set2) '''特性''' ##--------------------start-------------------列表 print('------------------start-------------------list') #计算元组长度 print('length of list1->',len(list1)) #判断元素是否在元组中 bl = 'A' in list1 print('A in list1->',bl) #获取元素,下标和切片 print('get list1[2]->',list1[2]) print('list1 chip->',list1[0:2]) #增 list1.append('D') print('list1 add->',list1) #删 remove pop list1.remove('D') print('list1 delete->',list1) #改 list1[0] = 'F' print('change list1[0]->',list1) #加法 list2 = [1,2] l = list1+list2 print('list1+list2->',l) #乘法 l1 = list1*3 print('list1*3->',l1) print('-------------------end--------------------list') ##---------------------end--------------------列表 ##--------------------start-------------------元组 print('------------------start-------------------tuple') #计算元组长度 print('length of tup1->',len(tup1)) #判断元素是否在元组中 b = 'A' in tup1 print('A in tup1->',b) #获取元素,下标法以及切片使用 print('get tup1[0]->',tup1[0]) print('chip tup1[0:2]->',tup1[0:2]) #没有增加元素的方法 #改 print('tup1[0] = \'F\' is not allowed') #元组运算符 #元组的加法 tup2 = (1,2) t = tup1+tup2 print('tup1+tup2->',t) #乘法 只能乘数字 t1 = tup1*2 print('tup1*2->',t1) #删除 del tup1 #特殊性质 tup2 = (10) print('type of tup2=(10) ->',type(tup2)) tup3 = (10,) print('type of tup3=(10,) ->',type(tup3)) print('-------------------end--------------------tuple') ##---------------------end--------------------元组 ##--------------------start-------------------字典 print('------------------start-------------------dict') #获取字典的长度 print('length of dict1->',len(dict1)) #判断字典元素是否存在,只能判断键 bd = 'key1' in dict1 print('key1 in dict1->',bd) #获取字典的值,通过键去获取对应的值 print('dict1[\'key1\']->',dict1['key1']) print('-------------------end--------------------dict') ##---------------------end--------------------字典 ##--------------------start-------------------集合 print('------------------start-------------------set') set2 = {'B','C','D'} print('set1->',set1) print('set2->',set2) #获取集合长度 print('length of set1->',len(set1)) #集合的常规运算 交集,并集,差集以及 并集-交集 ##交集 s1 = set1 & set2 print('交集 set1 & set2 ->',s1) ##并集 s2 = set1 | set2 print('并集 set1 | set2 ->',s2) ##差集set1对set2 s3 = set1 - set2 print('差集 set1 - set2 ->',s3) ##不同时属于两集合的元素 print('不同时属于两集合的元素 ->') s4 = s2-s1 print(' 方式1:并集-交集 ->',s4) s5 = s1 ^ s2 print(' 方式2:set1^set2 ->',s5) #增加 set1.add('F') print('set1.add(\'F\') ->',set1) set1.update({'M','N'}) print('set1.update({\'M\',\'N\'}) ->',set1) #移除 set1.remove('A') print('set1.remove(\'A\') ->',set1) #随机删除一个元素 set1.pop() print('返回被删除的元素 set1.pop() ->',set1.pop(),',pop 随机删除一个元素后 set1.pop() ->',set1) print('-------------------end--------------------set') ##---------------------end--------------------集合
c943411e726e0ba0d904a2e635418163e2711721
toggame/Python_learn
/第二章/test2.py
950
3.609375
4
a = int(input('请输入整数a:')) b = int(input('请输入整数b:')) print(a // b) print(a / b) print(a + b) print(a - b) print(a * b) st1 = input('请输入字符串:') st2 = input('请输入子串:') ct = 0 print(st1.count(st2)) # count计数不会重复 for i in range(len(st1)): # range默认0 start,不包含end项 if st1[i: i + len(st2)] == st2: ct += 1 print(ct) print('二进制:%s' % bin(a)) print('十六进制:%s' % hex(a)) # 会带出0x print('十六进制:%x' % a) # 不会带出0x,可自行在文本中添加 st = input('请输入字符串:') num = input('请输入需替换的索引号:') cha = input('请输入替换字符:') if int(num) < len(st): st_c = st.replace(st[int(num)], cha) # 会将所有相同字符替换,不可行 print(st_c) st_c = st[:int(num)] + cha + st[int(num) + 1:] # 注意end项不会包含 print(st_c) else: print('索引号超出范围')
ea292af4cae942964d9dee084bb87f6106bca56a
VicenteDH/tarea-2-EstebanVega1
/assignments/05Ordena/src/exercise.py
703
4.03125
4
numero1=int(input("Ponga un numero :")) numero2=int(input("Ponga otro numero:")) numero3=int(input("Ponga el ulitmo numero:")) if ((numero1<=numero2) and (numero1<=numero3)): menor=numero1 if(numero2<=numero3): medio=numero2 mayor=numero3 else: medio=numero3 mayor=numero2 elif((numero2<=numero1)and(numero2<numero3)): menor=numero2 if (numero1<=numero3): medio=numero1 mayor=numero3 else: medio=numero3 mayor=numero1 else: menor=numero3 if(numero1<=numero2): medio=numero1 mayor=numero2 else: medio=numero2 mayor=numero1 print(str(menor),str(medio),str(mayor))
cef551d7cc3bcd9cda660a189e8683bd786dc476
OutlawAK/OutlawAK
/Python/dict.py
712
4.09375
4
student = {'name': 'John', 'age': 23, 'type': ['math', 'physics']} print(student['name']) print(student.get('age')) print(student.get('phone', 'not found')) # if found sends the value, if not ,then second value is printed. student.update({'name': 'jane', 'age': 26, 'phone': '555-5555-555'}) print(student) # for updating del student['age'] # for deleting any key print(len(student)) print(' ') print(student.keys()) # keys print(' ') print(student.values()) # values print(' ') print(student.items()) # pairwise print(' ') for keys, values in student.items(): print(keys, values) # printing thru for loop
c7f4e85ba75d6db18c45e463e2613b6e82832884
mohammedterry/fuzzy
/fuzzy_bot.py
3,951
3.578125
4
class FuzzyBot: # this bot is robust to: # spelling (using chargrams) # phrasing (using question vector classification method) # and it can learn to speak from example conversations answers = {} answer_ids = {} word_vectors = {} chargram_vectors = {} def clean(self,txt): cleaned = '' for letter in txt.lower(): if ord('a') <= ord(letter) <= ord('z') or letter.isspace(): cleaned += letter return cleaned def chargrams(self,sentence,n=5): PAD = ' '*(n-1) chars = PAD + self.clean(sentence).lower() + PAD return {a+b+c+d+e for a,b,c,d,e in zip(chars,chars[1:],chars[2:],chars[3:],chars[4:])} def words(self,sentence): return set(self.clean(sentence).split()) def learn(self, question, answer): # unsupervised learning of chargram vectors a = answer.lower() # get answer id if a in self.answers: ans_id = self.answers[a] else: ans_id = len(self.answers) self.answer_ids[ans_id] = a self.answers[a] = ans_id # chargrams are used alongside words as they can be more robust to variations in spelling # update vectors for word in self.words(question): if word not in self.word_vectors: self.word_vectors[word] = {ans_id} else: self.word_vectors[word] |= {ans_id} for chargram in self.chargrams(question): if chargram not in self.chargram_vectors: self.chargram_vectors[chargram] = {ans_id} else: self.chargram_vectors[chargram] |= {ans_id} def classify(self,utterance,weights = [1,1]): #use learnt word vectors to classify question # each class corresponds to an answer # weights allow you to increase/decrease the relative contribution of words:chargrams word_weight,cg_weight = weights merged_vector = [0 for _ in range(len(self.answers))] for word in self.words(utterance): if word in self.word_vectors: vector = self.word_vectors[word] commonness = len(vector) #to weight rarer words more heavily for v in vector: merged_vector[v] += word_weight/commonness for chargram in self.chargrams(utterance): if chargram in self.chargram_vectors: vector = self.chargram_vectors[chargram] commonness = len(vector) for v in vector: merged_vector[v] += cg_weight/commonness highest_value = max(merged_vector) if highest_value > 0: ans_ids = [i for i,count in enumerate(merged_vector) if count == highest_value] return [self.answer_ids[ans_id] for ans_id in ans_ids] def batch_learn(self,questions_answers): # learn from a log of training examples # input: list of tuples: [...(utterance,reply)...] for qa in questions_answers: self.learn(qa[0],qa[1]) def chat(self,utterance): replies = self.classify(utterance) if replies is not None: if len(replies) > 1: return '\n'.join(replies) return replies[0] return "???" def learn_live(self): # learn while talking to the user bot_reply = '???' while True: human_reply = input("\nuser: ") self.learn(bot_reply,human_reply) bot_reply = self.chat(human_reply) print('bot: {}'.format(bot_reply)) training_data = [] with open('training_examples.txt') as f: for line in f.readlines(): q,a = line.split('§') training_data.append((q.strip(),a.strip())) b = FuzzyBot() b.batch_learn(training_data) print(b.classify("hi, how are you?")) b.learn_live()
e54bca9000e3e2b6d62fd9666d9630f52beb0641
nicwigs/231
/Projects/proj10(Alaska)/proj10__2.py
11,287
3.859375
4
import cards # This line is required #-------------------------------------------------------------------------- RULES = ''' Alaska Card Game: Foundation: Columns are numbered 1, 2, 3, 4 Built up by rank and by suit from Ace to King. The top card may be moved. Tableau: Columns are numbered 1,2,3,4,5,6,7 Built up or down by rank and by suit. The top card may be moved. Complete or partial face-up piles may be moved. An empty spot may be filled with a King or a pile starting with a King. To win, all cards must be in the Foundation.''' MENU = ''' Input options: F x y : Move card from Tableau column x to Foundation y. T x y c: Move pile of length c >= 1 from Tableau column x to Tableau column y. R: Restart the game (after shuffling) H: Display the menu of choices Q: Quit the game ''' #--------------------------------------------------------------------------- def valid_move(c1,c2): '''return True if suits are the same and ranks differ by 1; c1 & c2 are cards.''' move = False #boolean, True if valid move move = c1.suit() == c2.suit() and abs(c1.rank()-c2.rank()) == 1 if not move: if c1.suit() != c2.suit(): print("Error: Invalid move: Wrong suits") else: print("Error: Invalid move: Rank {} & {} not 1 away"\ .format(c1.rank(),c2.rank())) return move #-------------------------------------------------------------------------- def check_flip(tableau,x): """ Given the tableau and the column the card was removed from, it checks to make sure the last card in the column is face up """ if len(tableau[x-1]): if not tableau[x-1][-1].is_face_up(): tableau[x-1][-1].flip_card() #--------------------------------------------------------------------------- def valid_tableau(tableau,x,y,c): check = False #initalize bool index = len(tableau[x-1])-c #before setting the card in col adding to make sure not empty if len(tableau[y-1]) == 0: c1 = [] else: c1 = tableau[y-1][-1] #in error checking, already made sure there is a card to take c2 = tableau[x-1][index] if not c1: if c2.rank() == 13: check = True else: check = valid_move(c1,c2) return check #------------------------------------------------------------------------ def valid_foundation(tableau,foundation,x,y): check = False c1 = foundation[y-1][-1] c2 = tableau[x-1][-1] if c1 == "": if c2.rank() == 1: check = True else: print("Error: Invalid move: empty foundation only accepts aces") else: check = valid_move(c1,c2) return check #------------------------------------------------------------------------- def tableau_move(tableau,x,y,c): '''Move pile of length c >= 1 from Tableau column x to Tableau column y.''' if valid_tableau(tableau,x,y,c): tableau[y-1].extend(tableau[x-1][len(tableau[x-1])-c:]) for i in range(c): tableau[x-1].pop() check_flip(tableau,x) #-------------------------------------------------------------------------- def foundation_move(tableau,foundation,x,y): '''Move card from Tableau x to Foundation y. Return True if successful''' if valid_foundation(tableau,foundation,x,y): foundation[y-1].append(tableau[x-1].pop()) check_flip(tableau,x) #----------------------------------------------------------------------------- def win(tableau,foundation): '''Return True if the game is won. Detects by making sure each foundation pile has a king''' if foundation[0][-1] == "" or foundation[1][-1] == "" or \ foundation[2][-1] == "" or foundation[3][-1] == "": return False else: return foundation[0][-1].rank() == foundation[1][-1].rank() == \ foundation[2][-1].rank() == foundation[3][-1].rank() == 13 #----------------------------------------------------------------------------- def init_game(): '''Initialize and return the tableau, and foundation. - foundation is a list of 4 empty lists - tableau is a list of 7 lists - deck is shuffled and then all cards dealt to the tableau''' foundation = [[""],[""],[""],[""]] tableau = [[],[],[],[],[],[],[]] deck = cards.Deck() deck.shuffle() tableau[0] = [deck.deal()] #column 0 for c in range(1,7): #column 1-6 for r in range(c+5): #column 1 = 6 cards,2 = 7 tableau[c].append(deck.deal()) #add to right column for col in range(1,7): #hides cards, flips back over for i in range(len(tableau[col])-5): tableau[col][i].flip_card() return tableau, foundation #---------------------------------------------------------------------------- def display_game(tableau,foundation): '''Display foundation with tableau below. Format as described in specifications.''' print("="*40) print("{:>5s}{:>5s}{:>5s}{:>5s}".format(str(foundation[0][-1]),\ str(foundation[1][-1]), str(foundation[2][-1]),str(foundation[3][-1]))) print("-"*40) maxx = 0 #find the largest column for col in tableau: if len(col) > maxx: maxx = len(col) for c in range(maxx): print_lst = [] for i in range(7): try: #try appending works if col len >= c print_lst.append(str(tableau[i][c])) except IndexError: #if column not longest, add blank space print_lst.append(" ") print("{:>5s}{:>5s}{:>5s}{:>5s}{:>5s}{:>5s}{:>5s}".format\ (print_lst[0],print_lst[1],print_lst[2],print_lst[3],print_lst[4]\ ,print_lst[5],print_lst[6])) #--------------------------------------------------------------------- def start(): print(RULES) tableau,foundation = init_game() display_game(tableau, foundation) print(MENU) return tableau,foundation #----------------------------------------------------------------------- def e1(choice,NUM): if len(choice) != NUM: print("Incorrect number of arguments") return False return True #--------------------------------------------------------------------------- def e2(choice,TUP): for i in range(1,len(choice)): #are all ints? try: choice[i] = int(choice[i]) except ValueError: print("Incorrect type of arguments, {} must be type int"\ .format(TUP[i])) return False return True #--------------------------------------------------------------------------- def e3(num,TUP): if not 0 < num < 8: #check if possible tableau column print("Value out of range: {} must be between 1 -> 7 inclusive"\ .format(TUP[1])) return False return True #----------------------------------------------------------------------- def e4(choice,TUP): if not 0 < choice[2] < 5: #check if possible foundation column print("Value out of range: {} must be between 1 -> 4 inclusive"\ .format(TUP[2])) return False return True #--------------------------------------------------------------------------- def e5(choice,TUP,tableau): if choice[3] < 1: #check if possible card number print("Value out of range: {} must be positive"\ .format(TUP[3])) return False count = 0 for card in tableau[choice[1]-1]: if card.is_face_up(): count +=1 if choice[3] > count: print("Value out of range:{} selected was {}..."\ .format(TUP[3],choice[3])) print(" {} is only {}".format(TUP[3],count)) return False return True #--------------------------------------------------------------------------- def e6(choice,TUP,tableau): if not tableau[choice[1]-1]: print("Value out of range:{} {} was selected for a card but its empty"\ .format(TUP[1],choice[1])) return False return True #--------------------------------------------------------------------------- def error_check(choice,tableau): if choice[0].upper() == "F": TUP = (3,"Tableau column 'x'","Foundation column 'y'") else: TUP = (4,"Tableau column 'x'","Tableau column 'y'","Number of cards 'c'") """ For readability error functions were not given descriptive names: e1: Checks number of arguments e2: Checks type of arguments e3: Checks that the tableau column number is within range 1-7 e4: Checks that the foundation column number is within range 1-4 e5: Checks that the number of cards wished to move is at least 1 and less than or eqaul to the amount of flipped up cards in the take column e6:Checks that the take column for the foundation has at least one card to remove. c1-6 corespond to the errors,False if error occurs """ c1 = c2= c3 = c4 = c5 = c6 = True c1= e1(choice,TUP[0]) #argument count if c1: c2 = e2(choice,TUP) #agrument type if c2: c3 = e3(choice[1],TUP) #tab. take column in range if c3: if TUP[0] == 3: #foundation only c4 = e4(choice,TUP) #foundation column in range c6 = e6(choice,TUP,tableau) #check take column if TUP[0] == 4: #Tableau only c3 = e3(choice[2],TUP) #tab. place column in range c5 = e5(choice,TUP,tableau) #check card number return c1 and c2 and c3 and c4 and c6 and c5 #-------------------------------------------------------------------------- def main(): tableau,foundation = start() choice = input("Enter a choice: ").split() while choice[0].lower() != 'q': #fix when push enter if choice[0].upper() == "F": if error_check(choice,tableau): foundation_move(tableau,foundation,choice[1],choice[2]) elif choice[0].upper() == "T": if error_check(choice,tableau): tableau_move(tableau,choice[1],choice[2],choice[3]) elif choice[0].upper() == "R": tableau,foundation = start() elif choice[0].upper() == "H": print(MENU) else: print("Incorrect Command") if win(tableau,foundation): print("You won!") break else: display_game(tableau, foundation) choice = input("Enter a choice: ").split() #------------------------------------------------------------------------ main()
1b55b3537f2848dfbc7cc83a1b3fab98c885fb02
dsbrown1331/Python1
/IterationLogic/compound_interest.py
346
3.96875
4
#Write a program that computes the balance of a bank account with #interest compounded monthly balance = 100 #starting balance rate = 0.05 #interest rate years = 3 num_compounds = years while(num_compounds > 0): num_compounds -= 1 balance *= rate + 1 print(balance) print("After {} years you will have ${}".format(years, balance))
1444e0dd67c8a1238efcf452b6480e0d6bb66b6a
edoardovivo/algo_designII
/Assignment1/schedule_greedy.py
3,054
4.09375
4
''' Problem 1: In this programming problem and the next you'll code up the greedy algorithms from lecture for minimizing the weighted sum of completion times.. Download the text file below. jobs.txt This file describes a set of jobs with positive and integral weights and lengths. It has the format [number_of_jobs] [job_1_weight] [job_1_length] [job_2_weight] [job_2_length] ... For example, the third line of the file is "74 59", indicating that the second job has weight 74 and length 59. You should NOT assume that edge weights or lengths are distinct. Your task in this problem is to run the greedy algorithm that schedules jobs in decreasing order of the difference (weight - length). Recall from lecture that this algorithm is not always optimal. IMPORTANT: if two jobs have equal difference (weight - length), you should schedule the job with higher weight first. Beware: if you break ties in a different way, you are likely to get the wrong answer. You should report the sum of weighted completion times of the resulting schedule --- a positive integer --- in the box below. ADVICE: If you get the wrong answer, try out some small test cases to debug your algorithm (and post your test cases to the discussion forum). Problem 2: For this problem, use the same data set as in the previous problem. Your task now is to run the greedy algorithm that schedules jobs (optimally) in decreasing order of the ratio (weight/length). In this algorithm, it does not matter how you break ties. You should report the sum of weighted completion times of the resulting schedule --- a positive integer --- in the box below. SOLUTIONS: Diff: 69119377652 Ratio: 67311454237 ''' import csv import numpy as np def read_jobs(fname): jobs = {} with open(fname) as f: reader = csv.reader(f, delimiter=' ') next(reader, None) # skip the headers for row in reader: w = float(row[0]) l = float(row[1]) jobs[int(reader.line_num - 1)] = {'weight': w, 'length': l} return jobs def compute_sum_completion_times(jobs, jobs_scores): # Computes the lengths in order lengths = [jobs[v[0]]['length'] for v in jobs_scores] weights = [jobs[v[0]]['weight'] for v in jobs_scores] C = np.cumsum(lengths) return (C * weights).sum() def schedule_diff(jobs): jobs_scores = [(k, v['weight'] - v['length'], v['weight']) for k, v in jobs.iteritems()] jobs_scores.sort(key=lambda x: (x[1], x[2]), reverse=True) return jobs_scores def schedule_ratio(jobs): jobs_scores = [(k, v['weight'] / v['length']) for k, v in jobs.iteritems()] jobs_scores.sort(key=lambda x: x[1], reverse=True) return jobs_scores def main(): fname = "jobs.txt" jobs = read_jobs(fname) scores_diff = schedule_diff(jobs) scores_ratio = schedule_ratio(jobs) print "Diff: ", compute_sum_completion_times(jobs, scores_diff) print "Ratio: ", compute_sum_completion_times(jobs, scores_ratio) if __name__ == "__main__": main()
e7dd6416c564eece232cc1890b9043e77e4a97bd
drmtv10/samples
/match_paren.py
950
4.09375
4
#!/bin/python # match parenthesis in given string def match_paren(in_str): paren = list() for x in in_str: if x == '(' or x == '[': paren.append(x) elif x == ')': y = paren.pop() if y != '(': return False elif x == ']': y = paren.pop() if y != '[': return False if len(paren) == 0: return True else: return False def do_match_print(input_string): if match_paren(input_string): print input_string, 'ok' else: print input_string, 'failed matching paren' if __name__ == '__main__': input_strings = ['( This is [ invalid', 'Another ()[] valid (string)', '([1 2 3]]==', '(value)' ] for pstring in input_strings: do_match_print(pstring)
04515093f91cbb41e4c6e9641716fbc5bda39fc1
Sheetal777/ds-algo
/Codechef/Practice Problems/7_small_fact.py
128
3.546875
4
t=int(input()) for j in range(0,t): k=int(input()) fact=1 for i in range(2,k+1): fact=fact*i print(fact)
3265720c866e029eecf5a7b2f2d3dba6e3b87512
Astony/Homeworks
/homework6/task02/hard_classes_task.py
4,888
3.703125
4
from datetime import datetime, timedelta from typing import ClassVar, Type class InvalidError(Exception): """This is my personal error for check_homework_type method""" def check_homework_type(some_obj: ClassVar, homework_class: Type) -> "Homework": if isinstance(some_obj, homework_class): return some_obj else: raise InvalidError("Argument should has Homeworks class type") class DeadlineError(Exception): """This is my personal error for do_homework method""" class Homework: """ Class Homework that contains information about task, day of finish it, data of creating and information about deadline. :param task: Text of task that should be done in the homework. :type task: str :param days: This argument represents how much time available to do this homework. :type days: int """ def __init__(self, task: str, days: int) -> None: self.task = task self.created = datetime.now() self.deadline = self.created + timedelta(days=days) - datetime.now() def is_active(self) -> bool: """Returns True of False depending on time of deadline of this :return: Status of the homework :rtype: bool """ return self.deadline > timedelta(days=0) class Person: """Base class for students and teachers :param first_name: The first name of person. :type first_name: str :param last_name: The second name of person. :type last_name: str """ def __init__(self, first_name: str, last_name: str) -> None: self.first_name = first_name self.last_name = last_name class Student(Person): """ Class Student contains information about student and also have method to check if managed student do homework or not. Class has as same attributes as :class: `Person` has. """ def do_homework(self, homework_obj: Homework, solution: str) -> "HomeworkResult": """This method allows for instance of :class:`Student` to do a created homework :param homework: Some :class:`Homework` instance :return: :class:`HomeworkResult` instance or raise :class:`DeadlineError` """ if check_homework_type(homework_obj, Homework) and homework_obj.is_active(): return HomeworkResult(self, homework_obj, solution) else: raise DeadlineError("You are late") class HomeworkResult: """Class that contains information about author(student) homework and solution :param student: an instance of :class:`Student` class. :type student: :class:`Student. :param homework_obj: an instance of :class:`Homework` class. :type homework_obj: :class:`Homework. :param solution: solution of given task. :type solution: str """ def __init__(self, student: Student, homework_obj: Homework, solution: str) -> None: self.homework = check_homework_type(homework_obj, Homework) self.student = student self.solution = solution self.created = datetime.now() class Teacher(Person): """ Class Teacher contains info about teacher and have method to create homework and also here is the dictionary with all homeworks that have done and with their solutions. Class has as same attributes as :class: `Person` has. """ homework_done = {} @staticmethod def create_homework(task: str, days: int) -> Homework: """This method creates a :class:`Homework` instance :param task: Text of task that should be done in the homework. :type task: str :param days: This argument represents how much time available to do this homework. :type days: int :return: :class:`Homework` instance """ return Homework(task, days) @staticmethod def check_homework(homework_result_obj: HomeworkResult) -> bool: """This method check a :class:`HomeworkResult` instance. :param homework_result_obj: an instance of :class:`HomeworkResult` class. :type homework_result_obj: :class:`HomeworkResult` :return: True if len of solution > 5 and False instead. :rtype: bool """ if len(homework_result_obj.solution) > 5: Teacher.homework_done[homework_result_obj] = homework_result_obj.solution return True return False @staticmethod def reset_results(homework_result: HomeworkResult = None) -> None: """This method reset dictionary with completed homeworks if it using without arguments or deletes element that gives as attribute. :param homework_result_obj: an instance of :class:`HomeworkResult` class. :type homework_result_obj: :class:`HomeworkResult` """ if homework_result: del Teacher.homework_done[homework_result] else: Teacher.homework_done.clear()