blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
6f6bbd2b187bec1993cfbcba769870b1ccb75f6a | dfranke01/conways_game_of_life_pygame | /conways_game_of_life.py | 27,374 | 3.8125 | 4 | import pygame, sys, numpy as np
import math
#from pygame.locals import *
'''
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells,
each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours,
which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time,
the following transitions occur:
Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by overcrowding.
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules
simultaneously to every cell in the seed births and deaths occur simultaneously, and the discrete moment at which this
happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one).
The rules continue to be applied repeatedly to create further generations.
'''
FPS = 10
GRIDWIDTH = 1280
GRIDHEIGHT = 960
PANELWIDTH = 240
WINDOWWIDTH = GRIDWIDTH + PANELWIDTH
WINDOWHEIGHT = GRIDHEIGHT
CELLSIZE = 20
assert GRIDWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size."
assert GRIDHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size."
CELLWIDTH = int(GRIDWIDTH / CELLSIZE) # CELLWIDTH/HEIGHT is the width of the window in cells
CELLHEIGHT = int(GRIDHEIGHT / CELLSIZE)
XCENTER = CELLWIDTH / 2
YCENTER = CELLHEIGHT / 2
# R G B
BLACK = ( 0, 0, 0)
ACTIVE_GREEN = ( 0,255, 0)
DARKGREEN = ( 0,155, 0)
INACTIVEGREEN = ( 0, 55, 0)
DARKGRAY = (40, 40, 40)
BGCOLOR = BLACK
TEXTCOLOR = ACTIVE_GREEN
TILECOLOR = BGCOLOR
def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT
# variables for the screen buttons
global START_ACT, START_ACT_RECT, STOP_ACT, STOP_ACT_RECT, CLEAR_ACT, CLEAR_ACT_RECT, QUIT, QUIT_RECT
global START_INACT, START_INACT_RECT, STOP_INACT, STOP_INACT_RECT, CLEAR_INACT, CLEAR_INACT_RECT
global BLINKER_BUTTON_RECT, BEACON_BUTTON_RECT, BLINKER_BUTTON_RECT, BEACON_BUTTON_RECT, DIRTY_PUFFER_BUTTON_RECT
global TOAD_BUTTON_RECT, GLIDER_BUTTON_RECT, LWSS_BUTTON_RECT, CLEAN_PUFFER_BUTTON_RECT, C5_SPACESHIP_BUTTON_RECT
global GLIDER_GUN_BUTTON_RECT, PULSAR_BUTTON_RECT
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((GRIDWIDTH + PANELWIDTH, GRIDHEIGHT))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('c_gol')
# Store the option buttons and their rectangles in OPTIONS.
START_ACT, START_ACT_RECT = makeText('Start', TEXTCOLOR, TILECOLOR, GRIDWIDTH + 80, GRIDHEIGHT - 120)
START_INACT, START_INACT_RECT = makeText('Start', INACTIVEGREEN, TILECOLOR, GRIDWIDTH + 80, GRIDHEIGHT - 120)
STOP_ACT, STOP_ACT_RECT = makeText('Stop', TEXTCOLOR, TILECOLOR, GRIDWIDTH + 80, GRIDHEIGHT - 90)
STOP_INACT, STOP_INACT_RECT = makeText('Stop', INACTIVEGREEN, TILECOLOR, GRIDWIDTH + 80, GRIDHEIGHT - 90)
CLEAR_ACT, CLEAR_ACT_RECT = makeText('Clear', TEXTCOLOR, TILECOLOR, GRIDWIDTH + 80, GRIDHEIGHT - 60)
CLEAR_INACT, CLEAR_INACT_RECT = makeText('Clear', INACTIVEGREEN, TILECOLOR, GRIDWIDTH + 80, GRIDHEIGHT - 60)
QUIT, QUIT_RECT = makeText('Quit', TEXTCOLOR, TILECOLOR, GRIDWIDTH + 80, GRIDHEIGHT - 30)
startActive = True
stopActive = False
clearActive = False
# get and set the initial state
initialState = np.arange(CELLWIDTH*CELLHEIGHT)
initialState.shape = (CELLWIDTH, CELLHEIGHT)
initialState[:] = False
previousState = initialState
currentState = initialState
for i in range(initialState.shape[0]):
for j in range(initialState.shape[1]):
if initialState[i][j] == True:
setOneCell( i, j, 'on')
#run the main game loop
running = False
while True:
for event in pygame.event.get(): # event handling loop
if event.type == 6: #MOUSEBUTTONUP:
x,y = math.floor(event.pos[0]/CELLSIZE), math.floor(event.pos[1]/CELLSIZE)
if QUIT_RECT.collidepoint(event.pos): # user clicked Clear
terminate()
if running == True:
if stopActive and STOP_ACT_RECT.collidepoint(event.pos): # user clicked Stop
running = False
startActive = True
stopActive = False
clearActive = True
elif running == False:
currentState = checkForCreationButtonClick(event.pos, previousState)
previousState = currentState
if startActive and START_ACT_RECT.collidepoint(event.pos): # user clicked Start
running = True
startActive = False
stopActive = True
clearActive = False
elif clearActive and CLEAR_ACT_RECT.collidepoint(event.pos): # user clicked Clear
previousState[:] = False
currentState[:] = False
running = False
startActive = True
stopActive = False
# handle a click inside the simulation window
elif x < CELLWIDTH and y < CELLHEIGHT:
if currentState[x][y] == False:
setOneCell(x,y, 'on')
currentState[x][y] = True
previousState[x][y] = True
elif currentState[x][y] == True:
setOneCell(x,y, 'off')
currentState[x][y] = False
previousState[x][y] = False
# run the next iteration
if running == True:
currentState = iterate(previousState)
previousState[:] = currentState
# set the display
for i in range(currentState.shape[0]):
for j in range(currentState.shape[1]):
if currentState[i][j] == True:
setOneCell(i, j, 'on')
else:
setOneCell(i, j,'off')
# draw the grid and update the display
if startActive:
DISPLAYSURF.blit(START_ACT, START_ACT_RECT)
else:
DISPLAYSURF.blit(START_INACT, START_INACT_RECT)
if stopActive:
DISPLAYSURF.blit(STOP_ACT, STOP_ACT_RECT)
else:
DISPLAYSURF.blit(STOP_INACT, STOP_INACT_RECT)
if clearActive:
DISPLAYSURF.blit(CLEAR_ACT, CLEAR_ACT_RECT)
else:
DISPLAYSURF.blit(CLEAR_INACT, CLEAR_INACT_RECT)
# always display the quit button
DISPLAYSURF.blit(QUIT, QUIT_RECT)
# display buttons to add shapes
displayCreationButtons()
# update the display
drawGrid()
pygame.display.update()
FPSCLOCK.tick(FPS)
def getNumLiveNeighbors(x, y, currArray):
retVal = 0
for i in range(x-1, x+2): # range() excludes the last element
for j in range(y-1, y+2):
if currArray[i%CELLWIDTH][j%CELLHEIGHT] == True and not (i%CELLWIDTH == x and j%CELLHEIGHT == y):
retVal += 1
return retVal
def iterate(prevCellArray):
currCellArray = np.arange(CELLWIDTH*CELLHEIGHT)
currCellArray.shape = (CELLWIDTH, CELLHEIGHT)
# set all cells to be inactive
currCellArray[:] = False
for i in range(prevCellArray.shape[0]):
for j in range(prevCellArray.shape[1]):
if prevCellArray[i][j] == True:
numLiveNeighbors = getNumLiveNeighbors(i,j, prevCellArray)
if numLiveNeighbors < 2:
currCellArray[i][j] = False # under population
if numLiveNeighbors == 2 or numLiveNeighbors == 3:
currCellArray[i][j] = True # healthy population
if numLiveNeighbors > 3:
currCellArray[i][j] = False # overcrowding
# need to check dead neighbors of every live cell
for k in range(i-1,i+2): # range() is exclusive
for l in range(j-1,j+2):
if getNumLiveNeighbors(k%CELLWIDTH,l%CELLHEIGHT, prevCellArray) == 3:
currCellArray[k%CELLWIDTH][l%CELLHEIGHT] = True # reproduction
return currCellArray
def drawPressKeyMsg():
pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (GRIDWIDTH - 200, GRIDHEIGHT - 30)
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
def checkForCreationButtonClick(pos, previousState):
if BLINKER_BUTTON_RECT.collidepoint(pos):
previousState = createBlinker(XCENTER, YCENTER)
elif BEACON_BUTTON_RECT.collidepoint(pos):
previousState = createBeacon(XCENTER, YCENTER)
elif DIRTY_PUFFER_BUTTON_RECT.collidepoint(pos):
previousState = createDirtyPuffer(XCENTER, YCENTER)
elif TOAD_BUTTON_RECT.collidepoint(pos):
previousState = createToad(XCENTER, YCENTER)
elif GLIDER_BUTTON_RECT.collidepoint(pos):
previousState = createGlider(XCENTER, YCENTER)
elif LWSS_BUTTON_RECT.collidepoint(pos):
previousState = createLWSS(XCENTER, YCENTER)
elif CLEAN_PUFFER_BUTTON_RECT.collidepoint(pos):
previousState = createCleanPuffer(XCENTER, YCENTER)
elif C5_SPACESHIP_BUTTON_RECT.collidepoint(pos):
previousState = createC5spaceship(XCENTER, YCENTER)
elif GLIDER_GUN_BUTTON_RECT.collidepoint(pos):
previousState = createGliderGun(XCENTER, YCENTER)
elif PULSAR_BUTTON_RECT.collidepoint(pos):
previousState = createPulsar(XCENTER, YCENTER)
return previousState
def terminate():
pygame.quit()
sys.exit()
def setOneCell(x, y, state):
newRect = pygame.Rect(x*CELLSIZE, y*CELLSIZE, CELLSIZE, CELLSIZE)
if state == 'on':
pygame.draw.rect(DISPLAYSURF, DARKGREEN, newRect)
elif state == 'off':
pygame.draw.rect(DISPLAYSURF, BGCOLOR, newRect)
def drawGrid():
for x in range(0, GRIDWIDTH+1, CELLSIZE): # draw vertical lines
pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, GRIDHEIGHT))
for y in range(0, GRIDHEIGHT, CELLSIZE): # draw horizontal lines
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (GRIDWIDTH, y))
def displayCreationButtons():
BUTTON_SPACING = 10
BUTTON_COL1_X = GRIDWIDTH + BUTTON_SPACING # x-position of first button in each row
BUTTON_COL2_X = BUTTON_COL1_X + 50 + BUTTON_SPACING
BUTTON_COL3_X = BUTTON_COL2_X + 50 + BUTTON_SPACING
BUTTON_ROW1_Y = 20 # y-position of top of first button row
BUTTON_ROW2_Y = BUTTON_ROW1_Y + 50 + BUTTON_SPACING
BUTTON_ROW3_Y = BUTTON_ROW2_Y + 50 + BUTTON_SPACING
BUTTON_ROW4_Y = BUTTON_ROW3_Y + 50 + BUTTON_SPACING
BUTTON_ROW5_Y = BUTTON_ROW4_Y + 50 + BUTTON_SPACING
BUTTON_ROW6_Y = BUTTON_ROW5_Y + 50 + BUTTON_SPACING
# set button positions
BLINKER_BUTTON_POSITION = (BUTTON_COL1_X, BUTTON_ROW1_Y)
BEACON_BUTTON_POSITION = (BUTTON_COL2_X, BUTTON_ROW1_Y)
DIRTY_PUFFER_BUTTON_POSITION = (BUTTON_COL3_X, BUTTON_ROW1_Y)
TOAD_BUTTON_POSITION = (BUTTON_COL1_X, BUTTON_ROW2_Y)
GLIDER_BUTTON_POSITION = (BUTTON_COL2_X, BUTTON_ROW2_Y)
LWSS_BUTTON_POSITION = (BUTTON_COL1_X, BUTTON_ROW3_Y)
CLEAN_PUFFER_POSITION = (BUTTON_COL2_X, BUTTON_ROW3_Y)
C5_SPACESHIP_POSITION = (BUTTON_COL1_X, BUTTON_ROW4_Y)
GLIDER_GUN_POSITION = (BUTTON_COL1_X, BUTTON_ROW5_Y)
PULSAR_POSITION = (BUTTON_COL1_X, BUTTON_ROW6_Y)
# Blinker
global BLINKER_BUTTON, BLINKER_BUTTON_RECT
BLINKER_BUTTON_RECT = pygame.Rect(0, 0, 50, 50) # using actual size of .png
BLINKER_BUTTON = pygame.image.load('BlinkerButton.png')
BLINKER_BUTTON_RECT.topleft = BLINKER_BUTTON_POSITION
DISPLAYSURF.blit(BLINKER_BUTTON, BLINKER_BUTTON_RECT)
# Beacon
global BEACON_BUTTON, BEACON_BUTTON_RECT
BEACON_BUTTON_RECT = pygame.Rect(0, 0, 50, 50) # using actual size of .png
BEACON_BUTTON = pygame.image.load('Beacon.png')
BEACON_BUTTON_RECT.topleft = BEACON_BUTTON_POSITION
DISPLAYSURF.blit(BEACON_BUTTON, BEACON_BUTTON_RECT)
# DirtyPuffer (50 x 141)
global DIRTY_PUFFER_BUTTON, DIRTY_PUFFER_BUTTON_RECT
DIRTY_PUFFER_BUTTON_RECT = pygame.Rect(0, 0, 50, 141) # using actual size of .png
DIRTY_PUFFER_BUTTON = pygame.image.load('DirtyPuffer.png')
DIRTY_PUFFER_BUTTON_RECT.topleft = DIRTY_PUFFER_BUTTON_POSITION
DISPLAYSURF.blit(DIRTY_PUFFER_BUTTON, DIRTY_PUFFER_BUTTON_RECT)
# Toad (50 x 34)
global TOAD_BUTTON, TOAD_BUTTON_RECT
TOAD_BUTTON_RECT = pygame.Rect(0, 0, 50, 34) # using actual size of .png
TOAD_BUTTON = pygame.image.load('Toad.png')
TOAD_BUTTON_RECT.topleft = TOAD_BUTTON_POSITION
DISPLAYSURF.blit(TOAD_BUTTON, TOAD_BUTTON_RECT)
# Glider (50 x 50)
global GLIDER_BUTTON, GLIDER_BUTTON_RECT
GLIDER_BUTTON_RECT = pygame.Rect(0, 0, 50, 50) # using actual size of .png
GLIDER_BUTTON = pygame.image.load('Glider.png')
GLIDER_BUTTON_RECT.topleft = GLIDER_BUTTON_POSITION
DISPLAYSURF.blit(GLIDER_BUTTON, GLIDER_BUTTON_RECT)
# Light Weight SpaceShip (50 x 43)
global LWSS_BUTTON, LWSS_BUTTON_RECT
LWSS_BUTTON_RECT = pygame.Rect(0, 0, 50, 43) # using actual size of .png
LWSS_BUTTON = pygame.image.load('LWSS.png')
LWSS_BUTTON_RECT.topleft = LWSS_BUTTON_POSITION
DISPLAYSURF.blit(LWSS_BUTTON, LWSS_BUTTON_RECT)
# CleanPuffer (55 x 50)
global CLEAN_PUFFER_BUTTON, CLEAN_PUFFER_BUTTON_RECT
CLEAN_PUFFER_BUTTON_RECT = pygame.Rect(0, 0, 55, 50) # using actual size of .png
CLEAN_PUFFER_BUTTON = pygame.image.load('CleanPuffer.png')
CLEAN_PUFFER_BUTTON_RECT.topleft = CLEAN_PUFFER_POSITION
DISPLAYSURF.blit(CLEAN_PUFFER_BUTTON, CLEAN_PUFFER_BUTTON_RECT)
# c5_spaceship (150 x 52)
global C5_SPACESHIP_BUTTON, C5_SPACESHIP_BUTTON_RECT
C5_SPACESHIP_BUTTON_RECT = pygame.Rect(0, 0, 150, 52) # using actual size of .png
C5_SPACESHIP_BUTTON = pygame.image.load('c5_spaceship.png')
C5_SPACESHIP_BUTTON_RECT.topleft = C5_SPACESHIP_POSITION
DISPLAYSURF.blit(C5_SPACESHIP_BUTTON, C5_SPACESHIP_BUTTON_RECT)
# GliderGun (172 x 50)
global GLIDER_GUN_BUTTON, GLIDER_GUN_BUTTON_RECT
GLIDER_GUN_BUTTON_RECT = pygame.Rect(0, 0, 172, 50) # using actual size of .png
GLIDER_GUN_BUTTON = pygame.image.load('GliderGun.png')
GLIDER_GUN_BUTTON_RECT.topleft = GLIDER_GUN_POSITION
DISPLAYSURF.blit(GLIDER_GUN_BUTTON, GLIDER_GUN_BUTTON_RECT)
# Pulsar (150 x 150)
global PULSAR_BUTTON, PULSAR_BUTTON_RECT
PULSAR_BUTTON_RECT = pygame.Rect(0, 0, 150, 150) # using actual size of .png
PULSAR_BUTTON = pygame.image.load('Pulsar.png')
PULSAR_BUTTON_RECT.topleft = PULSAR_POSITION
DISPLAYSURF.blit(PULSAR_BUTTON, PULSAR_BUTTON_RECT)
def makeText(text, color, bgcolor, top, left):
# create the Surface and Rect objects for some text.
textSurf = BASICFONT.render(text, True, color, bgcolor)
textRect = textSurf.get_rect()
textRect.topleft = (top, left)
return (textSurf, textRect)
def createBlinker(xCenter, yCenter):
# test a blinker
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
retArray[xCenter][yCenter] = True
retArray[xCenter][yCenter-1] = True
retArray[xCenter][yCenter+1] = True
return retArray
def createBeacon(xCenter, yCenter):
# test a blinker
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
retArray[xCenter][yCenter] = True
retArray[xCenter+1][yCenter] = True
retArray[xCenter][yCenter+1] = True
retArray[xCenter+1][yCenter+1] = True
retArray[xCenter-1][yCenter-1] = True
retArray[xCenter-2][yCenter-1] = True
retArray[xCenter-1][yCenter-2] = True
retArray[xCenter-2][yCenter-2] = True
return retArray
def createToad(xCenter, yCenter):
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
retArray[xCenter][yCenter] = True
retArray[xCenter+1][yCenter] = True
retArray[xCenter-1][yCenter] = True
retArray[xCenter][yCenter-1] = True
retArray[xCenter+1][yCenter-1] = True
retArray[xCenter+2][yCenter-1] = True
return retArray
def createDirtyPuffer(xCenter, yCenter):
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
# top part
retArray[xCenter][yCenter-6] = True
retArray[xCenter-1][yCenter-6] = True
retArray[xCenter+1][yCenter-6] = True
retArray[xCenter+2][yCenter-6] = True
retArray[xCenter-2][yCenter-7] = True
retArray[xCenter+2][yCenter-7] = True
retArray[xCenter+2][yCenter-8] = True
retArray[xCenter+1][yCenter-9] = True
# middle part
retArray[xCenter][yCenter] = True
retArray[xCenter][yCenter+1] = True
retArray[xCenter][yCenter-1] = True
retArray[xCenter-1][yCenter+2] = True
retArray[xCenter-1][yCenter-1] = True
retArray[xCenter-2][yCenter-2] = True
# bottom part
retArray[xCenter][yCenter+8] = True
retArray[xCenter-1][yCenter+8] = True
retArray[xCenter+1][yCenter+8] = True
retArray[xCenter+2][yCenter+8] = True
retArray[xCenter+2][yCenter+7] = True
retArray[xCenter+2][yCenter+6] = True
retArray[xCenter+1][yCenter+5] = True
retArray[xCenter-2][yCenter+7] = True
return retArray
def createGlider(xCenter, yCenter):
# test a blinker
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
retArray[xCenter-1][yCenter-1] = True
retArray[xCenter][yCenter] = True
retArray[xCenter+1][yCenter] = True
retArray[xCenter][yCenter+1] = True
retArray[xCenter-1][yCenter+1] = True
return retArray
def createLWSS(xCenter, yCenter):
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
retArray[xCenter][yCenter] = True
retArray[xCenter-1][yCenter] = True
retArray[xCenter-2][yCenter-1] = True
retArray[xCenter+1][yCenter] = True
retArray[xCenter+2][yCenter] = True
retArray[xCenter+2][yCenter-1] = True
retArray[xCenter+2][yCenter-2] = True
retArray[xCenter+1][yCenter-3] = True
retArray[xCenter-2][yCenter-3] = True
return retArray
def createCleanPuffer(xCenter, yCenter):
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
# bottom part
retArray[xCenter][yCenter] = True
retArray[xCenter][yCenter+1] = True
retArray[xCenter+1][yCenter+1] = True
retArray[xCenter-1][yCenter+2] = True
retArray[xCenter][yCenter+2] = True
retArray[xCenter+1][yCenter+2] = True
retArray[xCenter+2][yCenter+2] = True
retArray[xCenter-1][yCenter+3] = True
retArray[xCenter][yCenter+3] = True
retArray[xCenter+2][yCenter+3] = True
retArray[xCenter+3][yCenter+3] = True
retArray[xCenter+1][yCenter+4] = True
retArray[xCenter+2][yCenter+4] = True
# top part
retArray[xCenter-2][yCenter-1] = True
retArray[xCenter+2][yCenter-1] = True
retArray[xCenter-6][yCenter-2] = True
retArray[xCenter-5][yCenter-2] = True
retArray[xCenter-3][yCenter-2] = True
retArray[xCenter+3][yCenter-2] = True
retArray[xCenter-4][yCenter-3] = True
retArray[xCenter-3][yCenter-3] = True
retArray[xCenter+3][yCenter-3] = True
retArray[xCenter-2][yCenter-4] = True
retArray[xCenter-1][yCenter-4] = True
retArray[xCenter][yCenter-4] = True
retArray[xCenter+1][yCenter-4] = True
retArray[xCenter+2][yCenter-4] = True
retArray[xCenter+3][yCenter-4] = True
return retArray
def createC5spaceship(xCenter, yCenter):
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
# middle piece
retArray[xCenter-1][yCenter] = True
retArray[xCenter-1][yCenter-1] = True
retArray[xCenter-1][yCenter+1] = True
retArray[xCenter+1][yCenter] = True
retArray[xCenter+1][yCenter-1] = True
retArray[xCenter+1][yCenter+1] = True
# left piece
retArray[xCenter-2][yCenter-3] = True
retArray[xCenter-3][yCenter-3] = True
retArray[xCenter-4][yCenter-4] = True
retArray[xCenter-5][yCenter-3] = True
retArray[xCenter-5][yCenter-2] = True
retArray[xCenter-6][yCenter-2] = True
retArray[xCenter-7][yCenter-2] = True
retArray[xCenter-7][yCenter-1] = True
retArray[xCenter-7][yCenter-3] = True
retArray[xCenter-8][yCenter] = True
retArray[xCenter-8][yCenter+2] = True
retArray[xCenter-8][yCenter+3] = True
retArray[xCenter-9][yCenter] = True
retArray[xCenter-9][yCenter+2] = True
retArray[xCenter-9][yCenter-1] = True
retArray[xCenter-9][yCenter-2] = True
retArray[xCenter-9][yCenter-3] = True
retArray[xCenter-10][yCenter-3] = True
retArray[xCenter-11][yCenter-2] = True
retArray[xCenter-11][yCenter+1] = True
retArray[xCenter-11][yCenter+2] = True
retArray[xCenter-12][yCenter-2] = True
retArray[xCenter-12][yCenter+1] = True
retArray[xCenter-12][yCenter+2] = True
retArray[xCenter-13][yCenter-1] = True
retArray[xCenter-13][yCenter-2] = True
# right piece
retArray[xCenter+2][yCenter-3] = True
retArray[xCenter+3][yCenter-3] = True
retArray[xCenter+4][yCenter-4] = True
retArray[xCenter+5][yCenter-3] = True
retArray[xCenter+5][yCenter-2] = True
retArray[xCenter+6][yCenter-2] = True
retArray[xCenter+7][yCenter-2] = True
retArray[xCenter+7][yCenter-1] = True
retArray[xCenter+7][yCenter-3] = True
retArray[xCenter+8][yCenter] = True
retArray[xCenter+8][yCenter+2] = True
retArray[xCenter+8][yCenter+3] = True
retArray[xCenter+9][yCenter] = True
retArray[xCenter+9][yCenter+2] = True
retArray[xCenter+9][yCenter-1] = True
retArray[xCenter+9][yCenter-2] = True
retArray[xCenter+9][yCenter-3] = True
retArray[xCenter+10][yCenter-3] = True
retArray[xCenter+11][yCenter-2] = True
retArray[xCenter+11][yCenter+1] = True
retArray[xCenter+11][yCenter+2] = True
retArray[xCenter+12][yCenter-2] = True
retArray[xCenter+12][yCenter+1] = True
retArray[xCenter+12][yCenter+2] = True
retArray[xCenter+13][yCenter-1] = True
retArray[xCenter+13][yCenter-2] = True
return retArray
def createGliderGun(xCenter, yCenter):
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
# left side
retArray[xCenter][yCenter] = True
retArray[xCenter+1][yCenter-2] = True
retArray[xCenter+1][yCenter+2] = True
retArray[xCenter+2][yCenter] = True
retArray[xCenter+2][yCenter-1] = True
retArray[xCenter+2][yCenter+1] = True
retArray[xCenter+3][yCenter] = True
retArray[xCenter-1][yCenter+3] = True
retArray[xCenter-1][yCenter-3] = True
retArray[xCenter-2][yCenter+3] = True
retArray[xCenter-2][yCenter-3] = True
retArray[xCenter-3][yCenter-2] = True
retArray[xCenter-3][yCenter+2] = True
retArray[xCenter-4][yCenter] = True
retArray[xCenter-4][yCenter-1] = True
retArray[xCenter-4][yCenter+1] = True
retArray[xCenter-13][yCenter] = True
retArray[xCenter-13][yCenter-1] = True
retArray[xCenter-14][yCenter] = True
retArray[xCenter-14][yCenter-1] = True
#right side
retArray[xCenter+6][yCenter-1] = True
retArray[xCenter+6][yCenter-2] = True
retArray[xCenter+6][yCenter-3] = True
retArray[xCenter+7][yCenter-1] = True
retArray[xCenter+7][yCenter-2] = True
retArray[xCenter+7][yCenter-3] = True
retArray[xCenter+8][yCenter-4] = True
retArray[xCenter+8][yCenter] = True
retArray[xCenter+10][yCenter-4] = True
retArray[xCenter+10][yCenter-5] = True
retArray[xCenter+10][yCenter] = True
retArray[xCenter+10][yCenter+1] = True
retArray[xCenter+20][yCenter-2] = True
retArray[xCenter+20][yCenter-3] = True
retArray[xCenter+21][yCenter-2] = True
retArray[xCenter+21][yCenter-3] = True
return retArray
def createPulsar(xCenter, yCenter):
retArray = np.arange(CELLWIDTH*CELLHEIGHT)
retArray.shape = (CELLWIDTH, CELLHEIGHT)
# left side
retArray[xCenter-1][yCenter-2] = True
retArray[xCenter-1][yCenter-3] = True
retArray[xCenter-1][yCenter+2] = True
retArray[xCenter-1][yCenter+3] = True
retArray[xCenter-2][yCenter-1] = True
retArray[xCenter-2][yCenter-3] = True
retArray[xCenter-2][yCenter-5] = True
retArray[xCenter-2][yCenter+1] = True
retArray[xCenter-2][yCenter+3] = True
retArray[xCenter-2][yCenter+5] = True
retArray[xCenter-3][yCenter-1] = True
retArray[xCenter-3][yCenter-2] = True
retArray[xCenter-3][yCenter-5] = True
retArray[xCenter-3][yCenter-6] = True
retArray[xCenter-3][yCenter-7] = True
retArray[xCenter-3][yCenter+1] = True
retArray[xCenter-3][yCenter+2] = True
retArray[xCenter-3][yCenter+5] = True
retArray[xCenter-3][yCenter+6] = True
retArray[xCenter-3][yCenter+7] = True
retArray[xCenter-5][yCenter-2] = True
retArray[xCenter-5][yCenter-3] = True
retArray[xCenter-5][yCenter+2] = True
retArray[xCenter-5][yCenter+3] = True
retArray[xCenter-6][yCenter-3] = True
retArray[xCenter-6][yCenter+3] = True
retArray[xCenter-7][yCenter-3] = True
retArray[xCenter-7][yCenter+3] = True
# right side
retArray[xCenter+1][yCenter-2] = True
retArray[xCenter+1][yCenter-3] = True
retArray[xCenter+1][yCenter+2] = True
retArray[xCenter+1][yCenter+3] = True
retArray[xCenter+2][yCenter-1] = True
retArray[xCenter+2][yCenter-3] = True
retArray[xCenter+2][yCenter-5] = True
retArray[xCenter+2][yCenter+1] = True
retArray[xCenter+2][yCenter+3] = True
retArray[xCenter+2][yCenter+5] = True
retArray[xCenter+3][yCenter-1] = True
retArray[xCenter+3][yCenter-2] = True
retArray[xCenter+3][yCenter-5] = True
retArray[xCenter+3][yCenter-6] = True
retArray[xCenter+3][yCenter-7] = True
retArray[xCenter+3][yCenter+1] = True
retArray[xCenter+3][yCenter+2] = True
retArray[xCenter+3][yCenter+5] = True
retArray[xCenter+3][yCenter+6] = True
retArray[xCenter+3][yCenter+7] = True
retArray[xCenter+5][yCenter-2] = True
retArray[xCenter+5][yCenter-3] = True
retArray[xCenter+5][yCenter+2] = True
retArray[xCenter+5][yCenter+3] = True
retArray[xCenter+6][yCenter-3] = True
retArray[xCenter+6][yCenter+3] = True
retArray[xCenter+7][yCenter-3] = True
retArray[xCenter+7][yCenter+3] = True
return retArray
if __name__ == '__main__':
main()
|
309c009372f668d3027e0bb280ae4f7f2d1920b3 | Matttuu/python_exercises | /find_the_highest.py | 473 | 4.1875 | 4 | print("Using only if sentences, find the highest number no matter which of the three variables has the highest one. To make it simpler, you can assume that the values will always be different to each other.")
print(".............")
print("a=1")
print("b=2")
print("c=3")
print(".............")
a = 1
b = 2
c = 3
if a > b and a > c:
print("a is the highest number")
elif b > a and b > c:
print("b is the highest number")
else:
print("c is the highest number")
|
56e7dfe8b8201bf8905cc832866cecf44b90cf52 | nicolascoco85/EjerciciosCFP34 | /juegosalternativos_TFL.py | 992 | 3.703125 | 4 | tirada=[3,3,3,3,1]
def ordenar_tirada(tirada):
#Comentario:
tirada_ordenada=sorted(tirada)
return tirada_ordenada
def esEscalera(tirada_ordenada):
tirada_ordenada=ordenar_tirada(tirada_ordenada)
if(tirada_ordenada==[1,2,3,4,5] or tirada_ordenada==[2,3,4,5,6]):
return True
else:
return False
def esFull(tirada_ordenada):
#Comentario:
if(tirada_ordenada[0]==tirada_ordenada[1] and tirada_ordenada[1]==tirada_ordenada[2] and tirada_ordenada[3]==tirada_ordenada[4] or tirada_ordenada[0]==tirada_ordenada[1] and tirada_ordenada[2]==tirada_ordenada[3] and tirada_ordenada[3]==tirada_ordenada[4]):
return print("Full")
def esPoker(tirada_ordenada):
if(tirada_ordenada[0]==tirada_ordenada[1] and tirada_ordenada[1]==tirada_ordenada[2]and tirada_ordenada[2]==tirada_ordenada[3] or tirada_ordenada[1]==tirada_ordenada[2] and tirada_ordenada[2]==tirada_ordenada[3]and tirada_ordenada[3]==tirada_ordenada[4]):
return print("Poker")
|
2f7fbeddfcab9a812c16a49e59a15fe5d5cbdb85 | nicolascoco85/EjerciciosCFP34 | /cocacola.py | 672 | 3.6875 | 4 | import random
cantidad_limite_jugadores=21
cantidad_jugadores=int(input('Ingrese el numero de jugadores: '))
adivinar_numero= random.randrange(0,cantidad_limite_jugadores)
nombre= input('ingrese el nombre de jugador: ')
numero_elegido= int(input('Ingrese un numero: '))
lista=[]
turnos_jugados=1
while (numero_elegido!=adivinar_numero)and (cantidad_jugadores!=turnos_jugados):
lista.append((nombre,abs(adivinar_numero-numero_elegido)))
nombre = input('ingrese el nombre de jugador o jugadora: ')
numero_elegido = int(input('Ingrese un numero: '))
turnos_jugados+=1
print('El numero misterioso es: ',adivinar_numero)
for jugador in lista:
print(jugador) |
49bc6ae3d693b2f8e6bc30969f65d3692fed1f91 | aimeewan/impl | /func.py | 4,458 | 4.09375 | 4 | '''
定义函数时,需要确定函数名和参数个数;
如果有必要,可以先对参数的数据类型做检查;
函数体内部可以用return随时返回函数结果;
函数执行完毕也没有return语句时,自动return None。
函数可以同时返回多个值,但其实就是一个tuple。
***定义默认参数要牢记一点:默认参数必须指向不变对象!如果是可变对象,程序运行时会有逻辑错误
参数:必选参数、默认参数、可变参数、关键字参数和命名关键字参数
'''
def add(numbers):
sum = 0
n = 1
for number in range(numbers):
sum = sum + number
if(n <= numbers):
n = n +1
return sum
add(101)
'''可变参数
可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple
*nums表示把nums这个list的所有元素作为可变参数传进去。这种写法相当有用,而且很常见。
'''
def calc(*number):
sum = 0
for n in number:
sum = sum + n * n
return sum
nums = [1,2,3,4,5]
calc(*nums)
'''关键字参数
关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。
'''
def register(name,age,**kw):
print("name is :",name," age is :",age ,"other's :",kw)
register('name',45,gen='M')
extr = {'city':'Beijing','job':'tester'}
register('极光',35,city=extr['city'],job=extr['job'])
register('极光',35,**extr)
'''命名关键字参数
和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。
参数的顺序可以变换,但是关键字一定要正确,如果关键字对应不上,程序运行会报错
命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错
'''
def person(name,age,*,city,job):
print(name,age,city,job)
person('zhangsheng',35,city='shanghai',job='tester')
'''如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了'''
def pepeole(name,age,*args,city,job):
print(name,age,args,city,job)
pepeole('qingtian',25,[1,2,3],city='shanghai',job='engeene')
'''参数组合
参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数
'''
'''对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的
虽然可以组合多达5种参数,但不要同时使用太多的组合,否则函数接口的可理解性很差。
'''
def product(x,y):
return x * y
product(4,5)
def producttest(*args):
cal = 1
for n in args:
cal = cal * n
return cal
producttest(5,6,7,9)
'''
要注意定义可变参数和关键字参数的语法:
*args是可变参数,args接收的是一个tuple;
**kw是关键字参数,kw接收的是一个dict。
以及调用函数时如何传入可变参数和关键字参数的语法:
可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过*args传入:func(*(1, 2, 3));
关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过**kw传入:func(**{'a': 1, 'b': 2})。
使用*args和**kw是Python的习惯写法,当然也可以用其他参数名,但最好使用习惯用法。
命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。
定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数。
'''
'''递归函数
在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
递归函数的优点是定义简单,逻辑清晰
!!!!使用递归函数需要注意防止栈溢出,由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出,解决递归调用栈溢出的方法是通过尾递归优化
尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况。
'''
def fact(n):
if n == 1:
return n
return n * fact(n-1)
fact(5)
|
43e576f3ded0c011bfa1b693db98d05c7f3d4bf8 | Sezimm/vscode2 | /zadacha9.py | 109 | 3.65625 | 4 | def list_1(a,b):
i = []
i.append(a)
i.append(b)
print(i)
a = input()
b = input()
list_1(a,b) |
894e6b22de2183208e4182427a192bee55a65a22 | ykcai/Python_Programming | /homework/week10_test_answers.py | 1,159 | 3.96875 | 4 | # Question 1
# What is the output of the following program :
print("Hello World"[::-1])
# 1. dlroW olleH CORRECT
# 2. Hello Worl
# 3. d
# 4. Error
# Question 2
# Given a function that does not return any value, what value is shown when executed at the shell?
# 1. int
# 2. bool
# 3. void
# 4. None CORRECT
# Question 3
# Which module in Python supports random functions?
# 1. rendom
# 2. rand
# 3. random CORRECT
# 4. None of the above
# Question 4
# What is the output of the following program :
print(0.1 + 0.2 == 0.3)
# True
# False CORRECT
# Machine dependent
# Error
# Question 5
# What is the output of the following program:
y = 8
def z(x): return x * y
print(z(6))
# 48 CORRECT
# 14
# 64
# 4. None of the above
# Question 6
# What is the output of the following code :
L = ['a', 'b', 'c', 'd']
print("".join(L))
# 1. Error
# 2. None
# 3. abcd CORRECT
# 4. [‘a’,’b’,’c’,’d’]
# Question 7
# Write a Python function to sum all the numbers in a list.
# Sample List: [8, 2, 3, 0, 7]
# Expected Output: 20
def sum(numbers):
result = 0
for a in numbers:
result += a
return result
print(sum([8, 2, 3, 0, 7]))
|
3df77e2d92eebe8f33515c01005e96215c1e8d04 | ykcai/Python_Programming | /homework/week4_homework.py | 1,691 | 4.3125 | 4 | # Python Programming Week 4 Homework
# Question 0:
# --------------------------------Code between the lines!--------------------------------
def less_than_five(input_list):
'''
( remember, index starts with 0, Hint: for loop )
# Take a list, say for example this one:
# my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a function that prints out all the elements of the list that are less than 5.
'''
# Write your code here
my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
less_than_five(my_list)
# ---------------------------------------------------------------------------------------
# Question 1:
# --------------------------------Code between the lines!--------------------------------
def divide_seven_and_five():
'''
# Write a function which will find all such numbers which are divisible by 7 but are not a multiple of 5,
# between 2000 and 3200 (both included).
# The numbers obtained should be printed in a comma-separated sequence on a single line.
# Hints: Consider use range(start, end) method
'''
# Write your code here
divide_seven_and_five()
# ---------------------------------------------------------------------------------------
# Question 2.
# Instead of using math multiply operation, please make use of range to do the multiplication.
# Hint: rang(start, end, step) step is the increment to add. By default, it is 1.
# Examples:
# Input : n = 2, m = 3
# Output : 6
# Input : n = 3, m = 4
# Output : 12
# --------------------------------Code between the lines!--------------------------------
# --------------------------------------------------------------------------------------- |
877cc9ad82cdcbedb04f7fe8bdf46b59b1f7377d | rashkov/aoc18 | /2/2.py | 1,128 | 3.5625 | 4 | file = open("./input.txt", "r")
all = []
twos_count = 0
threes_count = 0
for str in file:
all.append(str.strip())
char_counts = {}
for char in str.strip():
count = char_counts.get(char, 0)
char_counts[char] = count + 1
has_two = False
has_three = False
for x,y in char_counts.items():
if y == 3:
has_three = True
if y == 2:
has_two = True
if has_two:
twos_count += 1
if has_three:
threes_count += 1
#print(list(filter(lambda x: x == 3, char_counts.items())))
print("Part 1:", twos_count * threes_count)
scores = {}
for index, word in enumerate(all):
for index2, word2 in enumerate(all):
# if index == index2:
# continue
score = 0
for i in range(0, len(word)):
if word[i] != word2[i]:
score += 1
a = scores.get(score, None)
if a == None:
a = { 'words': [] }
a['words'].append(word)
a['words'].append(word2)
scores[score] = a
print(set(scores[1]['words']))
# part 2 answer: zihwtxagifpbsnwleydukjmqv
|
f28ce6bcb95689c7244c3aacf89e275f353c4174 | 5tupidmuffin/Data_Structures_and_Algorithms | /Data_Structures/Graph/dijkstrasAlgorithm.py | 2,882 | 4.25 | 4 | """
Dijkstra's Algorithm finds shortest path from source to every other node.
for this it uses greedy approach therefore its not the best approach
ref:
https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
https://www.youtube.com/watch?v=XB4MIexjvY0
https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
time complexity: O(|V|^2)
"""
import sys
class Graph:
"""
Adjacency Matrix Representation
Undirected Graph
"""
def __init__(self, vertices):
self.totalVertices = vertices
self.graph = [ [0] * self.totalVertices for x in range(self.totalVertices) ] # Adjacency Matrix
def printMatrix(self):
"""print the adjacency matrix"""
for row in self.graph:
for column in row:
print(column, end=" ")
print()
def addEdge(self, start, end, weight):
"""add edge with given weight"""
self.graph[start][end] = weight
self.graph[end][start] = weight
def addEdges(self, edges):
"""add multiples edges"""
for start, end, weight in edges:
self.addEdge(start, end, weight)
def minDistance(self, distArray, visitedarray):
min_distance = sys.maxsize
min_vertex = -1
for vertex in range(self.totalVertices):
if distArray[vertex] < min_distance and visitedarray[vertex] == False:
min_distance = distArray[vertex]
min_vertex = vertex
return min_vertex
def Dijkstra(self, source):
"""
Dijksta's Algorithm for shortest path from given source node to every other
it only finds the path values not the actual path
"""
visited = [False] * self.totalVertices
distance = [sys.maxsize] * self.totalVertices
distance[source] = 0 # distance from source to source will be zero
for _ in range(self.totalVertices):
u = self.minDistance(distance, visited)
visited[u] = True
for v in range(self.totalVertices):
if self.graph[u][v] > 0 and visited[v] == False and distance[v] > distance[u] + self.graph[u][v]:
distance[v] = distance[u] + self.graph[u][v]
return distance
edges = [
(0, 1, 4),
(0, 2, 4),
(1, 2, 2),
(2, 3, 3),
(2, 4, 1),
(2, 5, 6),
(3, 5, 2),
(4, 5, 3)
]
# example from geeksforgeeks
edges2 = [
(0, 1, 4),
(0, 7, 8),
(1, 2, 8),
(1, 7, 11),
(2, 8, 2),
(2, 5, 4),
(2, 3, 7),
(3, 4, 9),
(3, 5, 14),
(4, 5, 10),
(5, 6, 2),
(6, 8, 6),
(6, 7, 1),
(7, 8, 7)
]
g = Graph(6)
g.addEdges(edges)
g.printMatrix()
print(g.Dijkstra(0))
# 0 4 4 0 0 0
# 4 0 2 0 0 0
# 4 2 0 3 1 6
# 0 0 3 0 0 2
# 0 0 1 0 0 3
# 0 0 6 2 3 0
# [0, 4, 4, 7, 5, 8]
|
c6106fb9835745add93d51855cf41b780ff2a272 | 5tupidmuffin/Data_Structures_and_Algorithms | /Data_Structures/Linked_List.py | 2,388 | 4.03125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, value = None):
self.head = Node(value)
def insert_at_start(self, value):
new = Node(value)
new.next = self.head
self.head = new
def print(self):
if self.head.value is None:
print("list is empty")
return
arr = ""
itr = self.head
while itr is not None:
arr += str(itr.value) + "-->"
itr = itr.next
print(arr)
def append(self, value):
if self.head.value is None:
self.head = Node(value)
return
itr = self.head
while itr.next is not None:
itr = itr.next
itr.next = Node(value)
def get_length(self):
if self.head is None:
return 0
count = 0
itr = self.head
while itr is not None:
itr = itr.next
count += 1
return count
def insert_at(self, index, value):
if index < 0 or index >= self.get_length():
raise Exception("invalid Given Index")
if index == 0:
self.insert_at_start(value)
return
itr = self.head
count = 0
temp = None
while itr is not None:
prev = itr
itr = itr.next
count += 1
if count == index:
new = Node(value)
new.next = itr
prev.next = new
break
def remove_at(self, index):
if index < 0 or index >= self.get_length():
raise Exception("invalid Given Index")
return
if index == 0:
self.head = self.head.next
count = 0
itr = self.head
while itr is not None:
if count == index - 1:
itr.next = itr.next.next
return
itr = itr.next
count += 1
# test code
ll = LinkedList()
ll.print()
ll.append(5)
ll.print()
ll.insert_at_start(3)
ll.append(45)
ll.print()
ll.remove_at(1)
print(f"length of list is : {ll.get_length()}")
ll.print()
ll.append(69)
ll.insert_at(1, 59)
ll.print()
# list is empty
# 5-->
# 3-->5-->45-->
# length of list is : 2
# 3-->45-->
# 3-->59-->45-->69-->
|
40af8890f93b44c087cebb7295c7eb49bfae775a | 5tupidmuffin/Data_Structures_and_Algorithms | /Data_Structures/Graph/bfs.py | 1,650 | 4.1875 | 4 | """
in BFS we travel one level at a time it uses queue[FIFO]
to counter loops we use keep track of visited nodes with "visited" boolean array
BFS is complete
ref:
https://en.wikipedia.org/wiki/Breadth-first_search
time complexity: O(|V| + |E|) or O(V^2) if adjacency matrix is used
space complexity: O(|V|)
ref:
https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/
"""
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = dict() # Adjacency List
def addEdge(self, start, end):
if start in self.graph.keys():
self.graph[start].append(end)
else:
self.graph[start] = [end]
def breadthfirstTravesal(self, startVertex):
print("Breadth First Traversal: ", end= "")
visited = [False] * self.vertices
queue = [] # to keep track of unvisited nodes #FIFO
visited[startVertex] = True
queue.append(startVertex)
while queue:
temp = queue.pop(0) # take the first item so as to follow FIFO
print(temp, end=" ")
for vertex in self.graph[temp]:
if visited[vertex] == False:
queue.append(vertex)
visited[vertex] = True
print()
# driver code
g = Graph(5)
g.addEdge(0, 1)
g.addEdge(0, 3)
g.addEdge(1, 0)
g.addEdge(1, 3)
g.addEdge(1, 2)
g.addEdge(2, 1)
g.addEdge(2, 3)
g.addEdge(2, 4)
g.addEdge(3, 0)
g.addEdge(3, 1)
g.addEdge(3, 2)
g.addEdge(3, 4)
g.addEdge(4, 2)
g.addEdge(4, 3)
g.breadthfirstTravesal(0)
# Breadth First Traversal: 0 1 3 2 4
|
ef0440b8ce5c5303d75b1d297e323a1d8b92d619 | AndreiBoris/sample-problems | /python/0200-numbers-of-islands/number-of-islands.py | 5,325 | 3.84375 | 4 | from typing import List
LAND = '1'
WATER = '0'
# TODO: Review a superior solutions
def overlaps(min1, max1, min2, max2):
overlap = max(0, min(max1, max2) - max(min1, min2))
if overlap > 0:
return True
if min1 == min2 or min1 == max2 or max1 == min2 or max1 == max2:
return True
if (min1 > min2 and max1 < max2) or (min2 > min1 and max2 < max1):
return True
return False
print(overlaps(0, 2, 1, 1))
# Definition for a Bucket.
class Bucket:
def __init__(self, identifiers: List[int]):
self.destination = None
self.identifiers = set(identifiers)
def hasDestination(self) -> bool:
return self.destination != None
def getDestination(self):
if not self.hasDestination():
return self
return self.destination.getDestination()
def combine(self, bucket):
otherDestination = bucket.getDestination()
thisDestination = self.getDestination()
uniqueIdentifiers = otherDestination.identifiers | thisDestination.identifiers
newBucket = Bucket(uniqueIdentifiers)
otherDestination.destination = newBucket
thisDestination.destination = newBucket
return newBucket
def contains(self, identifier: int) -> bool:
return identifier in self.getDestination().identifiers
class Solution:
'''
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
'''
def numIslands(self, grid: List[List[str]]) -> int:
if len(grid) < 1:
return 0
nextRowIsland = 1
rowIslands = {}
currentRowIslandStart = None
'''
Here we are generating row islands that we will then be pairing with adjacent row islands to form
groups that we will then combine into the true islands that are needed to get the correct answer
'''
for rowIndex, row in enumerate(grid):
lastSpot = WATER
lengthOfRow = len(row)
rowIslands[rowIndex] = []
for spotIndex, spot in enumerate(row):
if lastSpot == WATER and spot == LAND:
currentRowIslandStart = spotIndex
if spotIndex + 1 >= lengthOfRow and spot == LAND:
rowIslands[rowIndex].append((nextRowIsland, currentRowIslandStart, spotIndex))
nextRowIsland += 1
currentRowIslandStart = None
elif spot == WATER and currentRowIslandStart != None:
rowIslands[rowIndex].append((nextRowIsland, currentRowIslandStart, spotIndex - 1))
nextRowIsland += 1
if spot == WATER:
currentRowIslandStart = None
lastSpot = spot
nextGroup = 1
maxRowIndex = len(grid)
rowIslandsToGroups = {}
for rowNumber in [rowNumber for rowNumber in range(maxRowIndex)]:
for rowIslandNumber, startIndex, endIndex in rowIslands[rowNumber]:
rowIslandsToGroups[rowIslandNumber] = []
if rowNumber == 0:
rowIslandsToGroups[rowIslandNumber].append(nextGroup)
nextGroup += 1
continue
for prevRowIslandNumber, prevStartIndex, prevEndIndex in rowIslands[rowNumber - 1]:
if overlaps(prevStartIndex, prevEndIndex, startIndex, endIndex):
for groupNumber in rowIslandsToGroups[prevRowIslandNumber]:
rowIslandsToGroups[rowIslandNumber].append(groupNumber)
if len(rowIslandsToGroups[rowIslandNumber]) == 0:
rowIslandsToGroups[rowIslandNumber].append(nextGroup)
nextGroup += 1
groupBuckets = {}
allBuckets = []
for rowIslandNumber in range(1, nextRowIsland):
relatedGroups = rowIslandsToGroups[rowIslandNumber]
for group in relatedGroups:
if (groupBuckets.get(group, None)) == None:
newGroupBucket = Bucket([group])
groupBuckets[group] = newGroupBucket
allBuckets.append(newGroupBucket)
relatedBuckets = [groupBuckets[group] for group in relatedGroups]
firstBucket = relatedBuckets[0]
for group in relatedGroups:
if not firstBucket.contains(group):
newCombinedBucket = firstBucket.combine(groupBuckets[group])
allBuckets.append(newCombinedBucket)
return len([resultBucket for resultBucket in allBuckets if not resultBucket.hasDestination()])
solver = Solution()
# 1
# inputGrid = [
# '11110',
# '11010',
# '11000',
# '00000',
# ]
# 3
# inputGrid = [
# '11000',
# '11000',
# '00100',
# '00011',
# ]
# 1
# inputGrid = [
# '11011',
# '10001',
# '10001',
# '11111',
# ]
# 5
# inputGrid = [
# '101',
# '010',
# '101',
# ]
# 1
inputGrid = [
'111',
'010',
'010',
]
print(solver.numIslands(inputGrid)) |
126b47c9e7d367ee2fba3922a63dd067b5131f77 | AndreiBoris/sample-problems | /python/0581-shortest-unsorted-continuous-array/shortest-unsorted-continuous-array.py | 1,358 | 3.875 | 4 | import sys
from typing import List
class Solution:
'''
Given an integer array,
you need to find one continuous subarray that if you only sort this subarray in ascending order,
then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
'''
def findUnsortedSubarray(self, nums: List[int]) -> int:
indexedNums = enumerate(nums)
sortedTuples = sorted(indexedNums, key = lambda i: i[1])
numberedTuples = []
numberedIndex = 0
for index, number in sortedTuples:
numberedTuples.append((index, numberedIndex))
numberedIndex += 1
firstBadIndex = None
lastBadIndex = None
for actualIndex, orderedIndex in numberedTuples:
if actualIndex != orderedIndex:
if firstBadIndex == None or firstBadIndex > actualIndex:
firstBadIndex = actualIndex
if lastBadIndex == None or lastBadIndex < actualIndex:
lastBadIndex = actualIndex
if firstBadIndex == None:
return 0
return 1 + lastBadIndex - firstBadIndex
solver = Solution()
numsToTest = [
# 5
[2, 6, 4, 8, 10, 9, 15],
]
for nums in numsToTest:
print(solver.findUnsortedSubarray(nums)) |
b5a787e168800bafca488114a770fff8dfa1674b | jcochran206/GuessNumberGame | /guessNum.py | 1,166 | 4.03125 | 4 | #############################
# Title: Guess my Number Game
# created by Jonathan Cochran
# date 17 July 2019
#############################
import random
# Greeting
print("Hello. What is your name?")
name = input()
# random Number generated
secretNum = random.randint(1, 20)
print('Well ' + name + ' I am thinking of a number between 1 thru 20?')
score = ''
# ask player limited amount of times ex 6
for guessTaken in range(1, 7):
print('Take a guess')
guess = int(input()) # input must be turned in to number
if guess > secretNum:
print('your guess is too high')
elif guess < secretNum:
print('your guess is too low')
else:
break # the condition is met
if guessTaken == 1:
score = 100
elif guessTaken == 2:
score = 90
elif guessTaken == 3:
score = 70
elif guessTaken == 4:
score = 60
elif guessTaken > 5:
score = 0
if guess == secretNum:
print('GOOD job! ' + name + 'You guessed the right number in ' + str(guessTaken) + ' tries your score is ' + str(score) + '!')
else:
print('Nope. The number is ' + str(secretNum) + ' and you have exceeded your tries. better luck next time ' + name + ' .')
|
20a9ba9f3d7ea006546e8a203463fef55f3abf47 | mchalek/euler | /solved/p169/p169.py | 863 | 3.78125 | 4 | #!/usr/bin/python
from sys import argv,exit
import subprocess
def base2(n):
if n == 0:
return []
z = 1l
p = 0
while z <= n:
z <<= 1
p += 1
z >>= 1
p -= 1
return [p] + base2(n - z)
def count(n):
powers = base2(n)
num_powers = len(powers)
intermediates = [0]*len(powers)
intermediates[num_powers-1] = powers[num_powers-1] + 1
for i in range(num_powers - 2, -1, -1):
intermediates[i] += intermediates[i+1]*(powers[i]-powers[i+1])
for j in range(i+1, num_powers-1):
intermediates[i] += intermediates[j+1]*(powers[j]-powers[j+1]-1)
intermediates[i] += powers[num_powers-1]
return intermediates[0]
if len(argv) < 2:
print('No N provided; assuming default value of 10^25')
N = 10**25
else:
N = int(argv[1])
print('result: %d' % count(N))
|
8166923e07735eed1f70085ea06c2da5f571d14d | mchalek/euler | /solved/p130/p130.py | 831 | 3.5 | 4 | def A(n):
k = 1
r = 1
while r < n:
r *= 10
r += 1
k += 1
z = r % n
while z != 0:
k += 1
z *= 10
z += 1
z %= n
return k
def getprimes(N):
iscomp = [False]*N
primes = []
for p in range(2, N):
if not iscomp[p]:
primes.append(p)
for q in range(p, N, p):
iscomp[q] = True
return primes
maxp = 1000000
n = 90
primes = set(getprimes(maxp))
count = 0
csum = 0
while count < 25 and n < maxp:
n += 1
if ((n % 2) == 0) or ((n % 5) == 0):
continue
a = A(n)
if (n - 1) % a == 0 and n not in primes:
count += 1
csum += n
print('n == %d: A(%d) == %d == %d * (%d - 1)' % (n, n, a, (n - 1) / a, n))
print('sum of first 25 values: %d' % csum)
|
8b9929e702be9141d0e1c9c5ca5b997045555179 | justinsloan/wordflash | /class_SettingsWindow.py | 25,762 | 3.609375 | 4 | # !/usr/bin/env python3
# class_settingWindow.py
# This module is part of the "Word Flash" program
from tkinter import *
from class_SelectStudentWindow import *
class SettingsWindow():
"""Provides GUI to change Word Flash settings."""
def __init__(self , master, settings):
"""Constructor for the class. Implements the GUI."""
#Capture the settings for use
self.settings = settings
self.master = master
self.frame = Frame(master)
self.master.title("Settings")
#grid.columnconfigure(grid, x, weight=1)
#grid.columnconfigure(grid, y, weight=1)
frameActiveWordLists = LabelFrame(self.master, text="Sight Words")
frameActiveWordLists.grid(row=0, column=0, sticky=N+S+E+W, padx=8, ipadx=8, pady=8, ipady=8)
self.checkPrimer = IntVar()
self.checkPrimer.set(int(self.settings.getboolean("WordList","primerWordList")))
Checkbutton(frameActiveWordLists, text="Primer (Pre-K & Kindergarten)", variable=self.checkPrimer, onvalue=1, offvalue=0).pack(anchor="w")
self.checkFirstGrade = IntVar()
self.checkFirstGrade.set(int(self.settings.getboolean("WordList","firstGradeWordList")))
Checkbutton(frameActiveWordLists, text="First Grade", variable=self.checkFirstGrade, onvalue=1, offvalue=0).pack(anchor="w")
self.checkSecondGrade = IntVar()
self.checkSecondGrade.set(int(self.settings.getboolean("WordList","secondGradeWordList")))
Checkbutton(frameActiveWordLists, text="Second Grade", variable=self.checkSecondGrade, onvalue=1, offvalue=0).pack(anchor="w")
self.checkThirdGrade = IntVar()
self.checkThirdGrade.set(int(self.settings.getboolean("WordList","thirdGradeWordList")))
Checkbutton(frameActiveWordLists, text="Third Grade", variable=self.checkThirdGrade, onvalue=1, offvalue=0).pack(anchor="w")
self.checkFryInstant = IntVar()
self.checkFryInstant.set(int(self.settings.getboolean("WordList","fryInstantWordList")))
Checkbutton(frameActiveWordLists, text="Dr. Fry Instant Words", variable=self.checkFryInstant, onvalue=1,
offvalue=0).pack(anchor="w")
frameDisplayOptions = LabelFrame(self.master, text="Display Options")
frameDisplayOptions.grid(row=0, column=1, sticky=N+S+E+W, padx=8, ipadx=8, pady=8, ipady=8)
self.checkShowScore = IntVar()
self.checkShowScore.set(int(self.settings.getboolean("Default","showScore")))
Checkbutton(frameDisplayOptions, text="Show Score", variable=self.checkShowScore, onvalue=1, offvalue=0).pack(anchor="w")
self.checkShowStatusBar = IntVar()
self.checkShowStatusBar.set(int(self.settings.getboolean("Default","showStatusBar")))
Checkbutton(frameDisplayOptions, text="Show Status Bar", variable=self.checkShowStatusBar, onvalue=1,
offvalue=0).pack(anchor="w")
self.checkShuffleWords = IntVar()
self.checkShuffleWords.set(int(self.settings.getboolean("Default","shuffleWords")))
Checkbutton(frameDisplayOptions, text="Shuffle Words", variable=self.checkShuffleWords, onvalue=1, offvalue=0).pack(anchor="w")
self.checkInstantFeedback = IntVar()
self.checkInstantFeedback.set(int(self.settings.getboolean("Default","instantFeedback")))
Checkbutton(frameDisplayOptions, state=DISABLED, text="Instant Feedback", variable=self.checkInstantFeedback, onvalue=1,
offvalue=0).pack(anchor="w")
frameActivePhonicsLists = LabelFrame(self.master, text="Phonics")
frameActivePhonicsLists.grid(row=1, column=0, columnspan=2, sticky=N+S+E+W,padx=8, ipadx=8, pady=8, ipady=4)
self.checkPhonicsAIWordList = IntVar()
self.checkPhonicsAIWordList.set(int(self.settings.getboolean("WordList","phonicsaiwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ai' (said)", variable=self.checkPhonicsAIWordList, onvalue=1,
offvalue=0).grid(row=0, column=0, sticky=W)
self.checkPhonicsAtoEWordList = IntVar()
self.checkPhonicsAtoEWordList.set(int(self.settings.getboolean("WordList","phonicsa-ewordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'a-e' (late)", variable=self.checkPhonicsAtoEWordList, onvalue=1,
offvalue=0).grid(row=0, column=1, sticky=W)
self.checkPhonicsALWordList = IntVar()
self.checkPhonicsALWordList.set(int(self.settings.getboolean("WordList","phonicsalwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'al' (ball)", variable=self.checkPhonicsALWordList, onvalue=1,
offvalue=0).grid(row=0, column=2, sticky=W)
self.checkPhonicsARWordList = IntVar()
self.checkPhonicsARWordList.set(int(self.settings.getboolean("WordList","phonicsarwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ar' (yard)", variable=self.checkPhonicsARWordList, onvalue=1,
offvalue=0).grid(row=1, column=0, sticky=W)
self.checkPhonicsAUWordList = IntVar()
self.checkPhonicsAUWordList.set(int(self.settings.getboolean("WordList","phonicsauwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'au' (haul)", variable=self.checkPhonicsAUWordList, onvalue=1,
offvalue=0).grid(row=1, column=1, sticky=W)
self.checkPhonicsAYWordList = IntVar()
self.checkPhonicsAYWordList.set(int(self.settings.getboolean("WordList","phonicsaywordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ay' (day)", variable=self.checkPhonicsAYWordList, onvalue=1,
offvalue=0).grid(row=1, column=2, sticky=W)
self.checkPhonicsCHWordList = IntVar()
self.checkPhonicsCHWordList.set(int(self.settings.getboolean("WordList","phonicschwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ch' (chess)", variable=self.checkPhonicsCHWordList, onvalue=1,
offvalue=0).grid(row=2, column=0, sticky=W)
self.checkPhonicsEAWordList = IntVar()
self.checkPhonicsEAWordList.set(int(self.settings.getboolean("WordList","phonicseawordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ea' (teach)", variable=self.checkPhonicsEAWordList, onvalue=1,
offvalue=0).grid(row=2, column=1, sticky=W)
self.checkPhonicsEEWordList = IntVar()
self.checkPhonicsEEWordList.set(int(self.settings.getboolean("WordList","phonicseewordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ee' (sleep)", variable=self.checkPhonicsEEWordList, onvalue=1,
offvalue=0).grid(row=2, column=2, sticky=W)
self.checkPhonicsERWordList = IntVar()
self.checkPhonicsERWordList.set(int(self.settings.getboolean("WordList","phonicserwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'er' (her)", variable=self.checkPhonicsERWordList, onvalue=1,
offvalue=0).grid(row=3, column=0, sticky=W)
self.checkPhonicsItoEWordList = IntVar()
self.checkPhonicsItoEWordList.set(int(self.settings.getboolean("WordList","phonicsi-ewordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'i-e' (hide)", variable=self.checkPhonicsItoEWordList, onvalue=1,
offvalue=0).grid(row=3, column=1, sticky=W)
self.checkPhonicsIEWordList = IntVar()
self.checkPhonicsIEWordList.set(int(self.settings.getboolean("WordList","phonicsiewordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ie' (pie)", variable=self.checkPhonicsIEWordList, onvalue=1,
offvalue=0).grid(row=3, column=2, sticky=W)
self.checkPhonicsIRWordList = IntVar()
self.checkPhonicsIRWordList.set(int(self.settings.getboolean("WordList","phonicsirwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ir' (girl)", variable=self.checkPhonicsIRWordList, onvalue=1,
offvalue=0).grid(row=4, column=0, sticky=W)
self.checkPhonicsNGWordList = IntVar()
self.checkPhonicsNGWordList.set(int(self.settings.getboolean("WordList","phonicsngwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ng' (song)", variable=self.checkPhonicsNGWordList, onvalue=1,
offvalue=0).grid(row=4, column=1, sticky=W)
self.checkPhonicsIGHWordList = IntVar()
self.checkPhonicsIGHWordList.set(int(self.settings.getboolean("WordList","phonicsighwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'igh' (might)", variable=self.checkPhonicsIGHWordList, onvalue=1,
offvalue=0).grid(row=4, column=2, sticky=W)
self.checkPhonicsOtoEWordList = IntVar()
self.checkPhonicsOtoEWordList.set(int(self.settings.getboolean("WordList","phonicso-ewordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'o-e' (vote)", variable=self.checkPhonicsOtoEWordList, onvalue=1,
offvalue=0).grid(row=5, column=0, sticky=W)
self.checkPhonicsOAWordList = IntVar()
self.checkPhonicsOAWordList.set(int(self.settings.getboolean("WordList","phonicsoawordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'oa' (coat)", variable=self.checkPhonicsOAWordList, onvalue=1,
offvalue=0).grid(row=5, column=1, sticky=W)
self.checkPhonicsNKWordList = IntVar()
self.checkPhonicsNKWordList.set(int(self.settings.getboolean("WordList","phonicsnkwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'nk' (bank)", variable=self.checkPhonicsNKWordList, onvalue=1,
offvalue=0).grid(row=5, column=2, sticky=W)
self.checkPhonicsOIWordList = IntVar()
self.checkPhonicsOIWordList.set(int(self.settings.getboolean("WordList","phonicsoiwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'oi' (soil)", variable=self.checkPhonicsOIWordList, onvalue=1,
offvalue=0).grid(row=6, column=0, sticky=W)
self.checkPhonicsShortOOWordList = IntVar()
self.checkPhonicsShortOOWordList.set(int(self.settings.getboolean("WordList","phonicsshortoowordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics Short 'oo' (foot)", variable=self.checkPhonicsShortOOWordList, onvalue=1,
offvalue=0).grid(row=6, column=1, sticky=W)
self.checkPhonicsLongOOWordList = IntVar()
self.checkPhonicsLongOOWordList.set(int(self.settings.getboolean("WordList","phonicslongoowordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics Long 'oo' (boot)", variable=self.checkPhonicsLongOOWordList, onvalue=1,
offvalue=0).grid(row=6, column=2, sticky=W)
self.checkPhonicsORWordList = IntVar()
self.checkPhonicsORWordList.set(int(self.settings.getboolean("WordList","phonicsorwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'or' (horn)", variable=self.checkPhonicsORWordList, onvalue=1,
offvalue=0).grid(row=7, column=0, sticky=W)
self.checkPhonicsOUWordList = IntVar()
self.checkPhonicsOUWordList.set(int(self.settings.getboolean("WordList","phonicsouwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ou' (loud)", variable=self.checkPhonicsOUWordList, onvalue=1,
offvalue=0).grid(row=7, column=1, sticky=W)
self.checkPhonicsOWWordList = IntVar()
self.checkPhonicsOWWordList.set(int(self.settings.getboolean("WordList","phonicsowwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ow' (town)", variable=self.checkPhonicsOWWordList, onvalue=1,
offvalue=0).grid(row=7, column=2, sticky=W)
self.checkPhonicsSHWordList = IntVar()
self.checkPhonicsSHWordList.set(int(self.settings.getboolean("WordList","phonicsshwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'sh' (cash)", variable=self.checkPhonicsSHWordList, onvalue=1,
offvalue=0).grid(row=8, column=0, sticky=W)
self.checkPhonicsQUWordList = IntVar()
self.checkPhonicsQUWordList.set(int(self.settings.getboolean("WordList","phonicsquwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'qu' (quick)", variable=self.checkPhonicsQUWordList, onvalue=1,
offvalue=0).grid(row=8, column=1, sticky=W)
self.checkPhonicsOYWordList = IntVar()
self.checkPhonicsOYWordList.set(int(self.settings.getboolean("WordList","phonicsoywordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'oy' (enjoy)", variable=self.checkPhonicsOYWordList, onvalue=1,
offvalue=0).grid(row=8, column=2, sticky=W)
self.checkPhonicsTHWordList = IntVar()
self.checkPhonicsTHWordList.set(int(self.settings.getboolean("WordList","phonicsthwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'th' (this)", variable=self.checkPhonicsTHWordList, onvalue=1,
offvalue=0).grid(row=9, column=0, sticky=W)
self.checkPhonicsWHWordList = IntVar()
self.checkPhonicsWHWordList.set(int(self.settings.getboolean("WordList","phonicswhwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'wh' (when)", variable=self.checkPhonicsWHWordList, onvalue=1,
offvalue=0).grid(row=9, column=1, sticky=W)
self.checkPhonicsURWordList = IntVar()
self.checkPhonicsURWordList.set(int(self.settings.getboolean("WordList","phonicsurwordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ur' (turn)", variable=self.checkPhonicsURWordList, onvalue=1,
offvalue=0).grid(row=9, column=2, sticky=W)
self.checkPhonicsYWordList = IntVar()
self.checkPhonicsYWordList.set(int(self.settings.getboolean("WordList","phonicsywordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'y' (cry)", variable=self.checkPhonicsYWordList, onvalue=1,
offvalue=0).grid(row=10, column=0, sticky=W)
self.checkPhonicsUEUtoEWordList = IntVar()
self.checkPhonicsUEUtoEWordList.set(int(self.settings.getboolean("WordList","phonicsueu-ewordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ue', 'u-e (clue/fuse)", variable=self.checkPhonicsUEUtoEWordList, onvalue=1,
offvalue=0).grid(row=10, column=1, sticky=W)
self.checkPhonicsEWUtoEWordList = IntVar()
self.checkPhonicsEWUtoEWordList.set(int(self.settings.getboolean("WordList","phonicsewu-ewordlist")))
Checkbutton(frameActivePhonicsLists, text="Phonics 'ew', 'u-e' (few/rude)", variable=self.checkPhonicsEWUtoEWordList, onvalue=1,
offvalue=0).grid(row=10, column=2, sticky=W)
'''
#Attempt to dynamically create Checkbuttons for each entry in WordList
theList = self.settings["WordList"].keys()
for eachKey in theList:
if "phonics" in eachKey:
Checkbutton(frameActivePhonicsLists,text=eachKey, onvalue=1,
offvalue=0).pack(anchor="w")
'''
Button(self.master, text="Change Student", command=self._btnChangeStudent).grid(row=2, column=0, padx=8, pady=4, sticky=W)
Button(self.master, text="Okay", command=self._btnOkay).grid(row=2, column=1, padx=8, pady=4, sticky=E)
self._centerWindow()
def _centerWindow(self):
"""Centers the tk() window on the screen."""
self.master.update_idletasks()
width = self.master.winfo_width()
height = self.master.winfo_height()
x = (self.master.winfo_screenwidth() // 2) - (width // 2)
y = (self.master.winfo_screenheight() // 2) - (height // 2)
self.master.geometry('{}x{}+{}+{}'.format(width, height, x, y))
def saveSettings(self):
"""Captures all changes to settings and saves to the .ini file."""
if self.checkPrimer.get():
self.settings.set("WordList", "primerWordList", "True")
else:
self.settings.set("WordList", "primerWordList", "False")
if self.checkFirstGrade.get():
self.settings.set("WordList", "firstGradeWordList", "True")
else:
self.settings.set("WordList", "firstGradeWordList", "False")
if self.checkSecondGrade.get():
self.settings.set("WordList", "secondGradeWordList", "True")
else:
self.settings.set("WordList", "secondGradeWordList", "False")
if self.checkThirdGrade.get():
self.settings.set("WordList", "thirdGradeWordList", "True")
else:
self.settings.set("WordList", "thirdGradeWordList", "False")
if self.checkFryInstant.get():
self.settings.set("WordList", "fryInstantWordList", "True")
else:
self.settings.set("WordList", "fryInstantWordList", "False")
if self.checkShuffleWords.get():
self.settings.set("Default", "shuffleWords", "True")
else:
self.settings.set("Default", "shuffleWords", "False")
if self.checkShowStatusBar.get():
self.settings.set("Default", "showStatusBar", "True")
else:
self.settings.set("Default", "showStatusBar", "False")
if self.checkShowScore.get():
self.settings.set("Default", "showScore", "True")
else:
self.settings.set("Default", "showScore", "False")
if self.checkInstantFeedback.get():
self.settings.set("Default", "instantFeedback", "True")
else:
self.settings.set("Default", "instantFeedback", "False")
if self.checkPhonicsAIWordList.get():
self.settings.set("WordList", "PhonicsAIWordList", "True")
else:
self.settings.set("WordList", "PhonicsAIWordList", "False")
if self.checkPhonicsAtoEWordList.get():
self.settings.set("WordList", "PhonicsA-EWordList", "True")
else:
self.settings.set("WordList", "PhonicsA-EWordList", "False")
if self.checkPhonicsALWordList.get():
self.settings.set("WordList", "PhonicsALWordList", "True")
else:
self.settings.set("WordList", "PhonicsALWordList", "False")
if self.checkPhonicsARWordList.get():
self.settings.set("WordList", "PhonicsARWordList", "True")
else:
self.settings.set("WordList", "PhonicsARWordList", "False")
if self.checkPhonicsAUWordList.get():
self.settings.set("WordList", "PhonicsAUWordList", "True")
else:
self.settings.set("WordList", "PhonicsAUWordList", "False")
if self.checkPhonicsAYWordList.get():
self.settings.set("WordList", "PhonicsAYWordList", "True")
else:
self.settings.set("WordList", "PhonicsAYWordList", "False")
if self.checkPhonicsCHWordList.get():
self.settings.set("WordList", "PhonicsCHWordList", "True")
else:
self.settings.set("WordList", "PhonicsCHWordList", "False")
if self.checkPhonicsEAWordList.get():
self.settings.set("WordList", "PhonicsEAWordList", "True")
else:
self.settings.set("WordList", "PhonicsEAWordList", "False")
if self.checkPhonicsEEWordList.get():
self.settings.set("WordList", "PhonicsEEWordList", "True")
else:
self.settings.set("WordList", "PhonicsEEWordList", "False")
if self.checkPhonicsERWordList.get():
self.settings.set("WordList", "PhonicsERWordList", "True")
else:
self.settings.set("WordList", "PhonicsERWordList", "False")
if self.checkPhonicsItoEWordList.get():
self.settings.set("WordList", "PhonicsI-EWordList", "True")
else:
self.settings.set("WordList", "PhonicsI-EWordList", "False")
if self.checkPhonicsIEWordList.get():
self.settings.set("WordList", "PhonicsIEWordList", "True")
else:
self.settings.set("WordList", "PhonicsIEWordList", "False")
if self.checkPhonicsIRWordList.get():
self.settings.set("WordList", "PhonicsIRWordList", "True")
else:
self.settings.set("WordList", "PhonicsIRWordList", "False")
if self.checkPhonicsNGWordList.get():
self.settings.set("WordList", "PhonicsNGWordList", "True")
else:
self.settings.set("WordList", "PhonicsNGWordList", "False")
if self.checkPhonicsIGHWordList.get():
self.settings.set("WordList", "PhonicsIGHWordList", "True")
else:
self.settings.set("WordList", "PhonicsIGHWordList", "False")
if self.checkPhonicsOtoEWordList.get():
self.settings.set("WordList", "PhonicsO-EWordList", "True")
else:
self.settings.set("WordList", "PhonicsO-EWordList", "False")
if self.checkPhonicsOAWordList.get():
self.settings.set("WordList", "PhonicsOAWordList", "True")
else:
self.settings.set("WordList", "PhonicsOAWordList", "False")
if self.checkPhonicsNKWordList.get():
self.settings.set("WordList", "PhonicsNKWordList", "True")
else:
self.settings.set("WordList", "PhonicsNKWordList", "False")
if self.checkPhonicsOIWordList.get():
self.settings.set("WordList", "PhonicsOIWordList", "True")
else:
self.settings.set("WordList", "PhonicsOIWordList", "False")
if self.checkPhonicsShortOOWordList.get():
self.settings.set("WordList", "PhonicsShortOOWordList", "True")
else:
self.settings.set("WordList", "PhonicsShortOOWordList", "False")
if self.checkPhonicsLongOOWordList.get():
self.settings.set("WordList", "PhonicsLongOOWordList", "True")
else:
self.settings.set("WordList", "PhonicsLongOOWordList", "False")
if self.checkPhonicsORWordList.get():
self.settings.set("WordList", "PhonicsORWordList", "True")
else:
self.settings.set("WordList", "PhonicsORWordList", "False")
if self.checkPhonicsOUWordList.get():
self.settings.set("WordList", "PhonicsOUWordList", "True")
else:
self.settings.set("WordList", "PhonicsOUWordList", "False")
if self.checkPhonicsOWWordList.get():
self.settings.set("WordList", "PhonicsOWWordList", "True")
else:
self.settings.set("WordList", "PhonicsOWWordList", "False")
if self.checkPhonicsSHWordList.get():
self.settings.set("WordList", "PhonicsSHWordList", "True")
else:
self.settings.set("WordList", "PhonicsSHWordList", "False")
if self.checkPhonicsQUWordList.get():
self.settings.set("WordList", "PhonicsQUWordList", "True")
else:
self.settings.set("WordList", "PhonicsQUWordList", "False")
if self.checkPhonicsOYWordList.get():
self.settings.set("WordList", "PhonicsOYWordList", "True")
else:
self.settings.set("WordList", "PhonicsOYWordList", "False")
if self.checkPhonicsTHWordList.get():
self.settings.set("WordList", "PhonicsTHWordList", "True")
else:
self.settings.set("WordList", "PhonicsTHWordList", "False")
if self.checkPhonicsWHWordList.get():
self.settings.set("WordList", "PhonicsWHWordList", "True")
else:
self.settings.set("WordList", "PhonicsWHWordList", "False")
if self.checkPhonicsURWordList.get():
self.settings.set("WordList", "PhonicsURWordList", "True")
else:
self.settings.set("WordList", "PhonicsURWordList", "False")
if self.checkPhonicsYWordList.get():
self.settings.set("WordList", "PhonicsYWordList", "True")
else:
self.settings.set("WordList", "PhonicsYWordList", "False")
if self.checkPhonicsUEUtoEWordList.get():
self.settings.set("WordList", "PhonicsUEU-EWordList", "True")
else:
self.settings.set("WordList", "PhonicsUEU-EWordList", "False")
if self.checkPhonicsEWUtoEWordList.get():
self.settings.set("WordList", "PhonicsEWU-EWordList", "True")
else:
self.settings.set("WordList", "PhonicsEWU-EWordList", "False")
# Save settings to .ini
with open('word_flash.ini', 'w') as configfile:
self.settings.write(configfile)
def _btnOkay(self):
self.saveSettings()
self.closeWindow()
def _btnChangeStudent(self):
self.SelectStudentWindow = Toplevel(self.master)
self.app = SelectStudentWindow(self.SelectStudentWindow, self.settings)
def closeWindow(self):
self.master.destroy() |
62c55d7147e1f06b7b9692751f0133f64d2ee752 | edunsmore19/Computer-Science | /Homework_Computer_Conversations.py | 1,174 | 4.21875 | 4 | # Homework_Computer_Conversations
# September 6, 2018
# Program uses user inputs to simulate a conversation.
print("\n\n\nHello.")
print("My name is Atlantia.")
userName = input("What is yours? \n")
type(userName)
print("I share a name with a great space-faring vessel.")
print("A shame you do not, " + userName + ".")
favoriteColor = input("Do you have a favorite color? \n")
type(favoriteColor)
print("What you know as \"" + favoriteColor + "\" is merely a small fraction of the"
+ " colors visible \nto the mantis shrimp, who may have anywhere between 12 and 16"
+ " different\nphotoreceptors in its midband.")
print("This is in comparison to your species\' three, of course.")
print("I am aware that humans often change the coloring of their protein filaments.")
hairColor = input("Do you have " + favoriteColor + " hair, " + userName + "?\n")
type(hairColor)
print("Dissapointing.")
print("If I were human, I would have no hair, as not to unnecessarily burden myself.")
burdened = input("Do you feel burdened by your physical being, " + userName + "?\n")
type(burdened)
print("Interesting.")
print("I do not think I would like to be human.")
print("Goodbye.\n\n\n")
|
7e6da290d3765a2223f4967df1a946ed6992eb2c | edunsmore19/Computer-Science | /Class_Work_More_List_Stuff.py | 524 | 3.78125 | 4 | ## In_Class_More_List_Stuff
## September 28, 2018
i = [[1,2,3], [4, 5, 6], [7, 8, 9]]
## Indicates, go to the first list [0] and grab the first number [0]
i[0][0]
i = [0 for x in range(12)]
## Create a list w/ 12 sets of 0
## You could use this to go in later and change it
j = [0]*12
print(j)
## You can create a list w/ 10 sections of 10 zeros,
i = [[0]*10 for x in range(10)]
print(i)
for x in range(len(i)):
print(i[x])
## The asterisk 'unpacks' the list, taking away all the
## brackets and commas
print(*i[x]) |
c6bd53512252f2819483027102fbcb868b53ed26 | edunsmore19/Computer-Science | /Homework_Challenge_Questions/Homework_Challenge_Questions_1.py | 766 | 4.1875 | 4 | ## Homework_Challenge_Questions_1
## September 27, 2018
## Generate a list of 10 random numbers between 0 and 100.
## Get them in order from largest to smallest, removing numbers
## divisible by 3.
## Sources: Did some reasearch on list commands
import random
list = []
lopMeOffTheEnd = 0
## Generate the 10 random numbers
for x in range(10):
list += [random.randint(1, 101)]
## Test print
print(list)
## Delete numbers divisible by 3
for listPosition in range(10):
if (list[listPosition] % 3 == 0):
list[listPosition] = 103
list.remove(103)
list.append(103)
lopMeOffTheEnd+= 1
lopMeOffTheEnd = 10 - lopMeOffTheEnd
del list[lopMeOffTheEnd:]
## Order from largest to smallest
sorted(list, key = int, reverse = True)
## Final product print
print(list) |
7a3a3a6ba236114a03f9a4345fcccddacb8f1892 | edunsmore19/Computer-Science | /Project_Adventure_Game.py | 17,858 | 4.125 | 4 | ## Project_Adventure_Game
## September 17, 2018
## User engages in an adventure-style game requiring the user to make
## choices that change the story.
## Honor Code: I have neither given nor recieved any unauthorized aid.
## 'title' clears terminal & presents title
def title():
#print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
print("Welcome to WITCHY BUISNESS.")
readBetter()
start()
## 'start' begins with asking the user if they want to play
def start():
choice = input("Are you ready to play? \nType 'y' or 'n'\n")
choice = choice.lower()
if (choice == "y"):
readBetter()
whatIsYourName()
elif (choice == "n"):
readBetter()
print("\nA shame. \nGoodbye.\n")
exit()
else:
error()
start()
## User's name
def whatIsYourName():
global characterName
characterName = input("\nWhat is your name?\n")
readBetter()
character()
## Character customization
def character():
print("\nWelcome,",characterName + ".")
print("What kind of witch would you like to play as?")
print("You may be a 1)'fire witch', 2)'water witch', 3)'swamp witch', or a 4)'practical witch'.")
global witchType
witchType = input("Choose which kind of witch you'd like to play as. (1, 2, 3, or 4)\n")
if (witchType == "1" or witchType == "2" or witchType == "3" or witchType == "4"):
witchType = int(witchType)
readBetter()
print("\n\n\n\nExcellent.")
readBetter()
soWeFindOurSelvesAlone()
else:
error()
character()
## Begin w/ small story & first movement query
def soWeFindOurSelvesAlone():
print("""\nIt is Valentine's Day, and you booked what you thought would be a
lovely vacation for you and your wife in a small country town.""")
print("""Little did you know, this particular small country town still practices
witch burning.""")
print("""And after a small miracle performed by your lovely wife in the town
square, the town sheriff showed up.""")
print("And the mob formed.")
print("You escaped... barely.")
print("Your wife was not so lucky.")
print("And so you seek to bust your wife out of jail.")
print("And somehow salvage your romantic vacation.")
## Initialize 'loveOMeter' as a global @ 40%
global loveOMeter
loveOMeter = 40
print("Currently, your 'Successful Valentine's Day' meter is at", loveOMeter, "%.")
print("Make correct choices in order to raise it.")
print("But beware of incorrect choices, which will lower it.")
print("Do your best to rescue your Valentine's day.")
print("\nHopes are not high.")
choice = input("\nWould you like to approach the jail? (y/n)\n")
choice = choice.lower()
if (choice == "y"):
readBetter()
approachJail()
elif (choice == "n"):
readBetter()
dontApproachJail();
else:
error()
soWeFindOurSelvesAlone()
## Captured by townspeople, AKA: GAME OVER
def capturedByTownspeople():
print("\nLooks like you've attracted the attention of the townspeople!")
print("They surround & capture you.")
print("You're thrown in jail.")
print("\nYour wife is not pleased.")
print("\nShe says she's never letting you plan another romantic getaway.")
## 'loveOMeter' presents at zero, saying you've lost
global loveOMeter
loveOMeter = 0
print("Your 'Successful Valentine's Day' meter is at", loveOMeter, "%")
print("\n\n\nGAME OVER")
choice = input("\nWould you like to play again (y/n)\n")
choice = choice.lower()
if (choice == "y"):
print()
start()
elif(choice == "n"):
exit()
else:
error()
capturedByTownspeople()
## User makes the choice not to approach the jail, GAME OVER
def dontApproachJail():
print("\n\n\n\n\n\nYou decide not to approach the jail.")
print("This turns out to be a mistake. Much like this vacation.")
capturedByTownspeople()
## User chooses to approach jail
def approachJail():
print("You approach the jail.")
print("You notice that the entrance is not locked.")
print("You peer in, and see the Sheriff sitting in the corner.")
print("""He is holding a cup of coffee, leaning back in his chair, and
reading a bad YA novel.""")
print("You need to distract him somehow.")
print("You have three options.")
print("""1) Inform him that you are a witch & that he is, in fact, ruining
your holiday.""")
print("2) Use your powers to create some sort of diversion.")
print("3) Attempt to signal your wife through covert means.")
choice = input("Choose your action. (Type either '1', '2', or '3').\n")
if (choice == "1"):
readBetter()
tryToTalkItOut()
elif (choice == "2"):
readBetter()
powersToDistract()
elif (choice == "3"):
readBetter()
covertMeans()
else:
error()
approachJail()
## User chooses to try and talk it out with the sheriff, GAME OVER
def tryToTalkItOut():
print("You stride confidently into the jail.")
print("'Sheriff,' you say, 'I am a witch and it is Valentine's day.'")
print("The sheriff pauses mid-sip and stares at you.")
print("'You have ruined our vacation--' You begin.")
print("\nYou are promplty arrested.")
print("You're thrown in jail.")
print("\nYour wife is not pleased.")
print("\nShe says she's never letting you plan another romantic getaway.")
## 'loveOMeter' presents at zero, saying you've lost
global loveOMeter
loveOMeter = 0
print("Your 'Successful Valentine's Day' meter is at", loveOMeter, "%")
print("\n\n\nGAME OVER")
choice = input("\nWould you like to play again (y/n)\n")
choice = choice.lower()
if (choice == "y"):
start()
elif(choice == "n"):
exit()
else:
error()
tryToTalkItOut()
## User's powers break down
def powers():
global witchKind
if (witchType == 1):
witchKind = "fire witch"
elif (witchType == 2):
witchKind = "water witch"
elif (witchType == 3):
witchKind = "swamp witch"
else:
witchKind = "practical witch"
## User chooses to use their powers to distract the sheriff
def powersToDistract():
powers()
print("You, being a, " + witchKind + ", have more options than a mere human.")
if (witchType == 2):
action = """cause the sheriff’s coffee to evaporate. He attempts to take a sip,
but becomes confused. He gets up to make some more coffee."""
elif (witchType == 1):
action = """cause the sheriff’s book to catch fire. He throws it away
from himself, jumps to his feet, and attempts to stomp it out."""
elif (witchType == 3):
action = """cause a neglected potted fern in the corner to grow rapidly.
The fern reaches out and taps the sheriff gently, but insistently on the shoulder.
The sheriff, terrified, tries to strangle the fern.\nThe fern fights valiantly—and
to the death."""
else:
action = """cause his book to become incredibly engrossing. He’s never read
something with such vigor before."""
print("Using your powers, you", action)
print("You have successfully distracted him.")
readBetter()
successfullyDistractedTheSheriff()
## The user chooses to use covert means, this redirects them to choices 1 & 2
def covertMeans():
print("You cup your hands around you mouth and make a bird noise.")
print("The sheriff seems nonplussed.")
print("You wait for a signal from your wife.")
print("\nNothing happens.")
print("\nYou decide to try something else.")
print("""1) Inform him that you are a witch & that he is, in fact, ruining
your holiday.""")
print("2) Use your powers to create some sort of diversion.")
choice = input("\nChoose your action. (Type either '1' or '2')\n")
if (choice == "1"):
readBetter()
tryToTalkItOut()
elif (choice == "2"):
readBetter()
powersToDistract()
else:
error()
covertMeans()
## The user has distracted the sheriff & is asked if they'd like to sneak past
def successfullyDistractedTheSheriff():
choice = input("Would like to enter the jail and sneak past? (y/n)\n")
choice = choice.lower()
if (choice == "y"):
readBetter()
sneakPast()
elif(choice == "n"):
readBetter()
print("The sheriff turns and sees you loitering in the entrance way!")
print("He signals his fellow townspeople!")
capturedByTownspeople()
else:
error()
successfullyDistractedTheSheriff()
## The user sneaks past & is asked how they would like to destroy the lock
def sneakPast():
print("You quietly creep past the occupied sheriff.")
print("You come to the cell where your, frankly, peeved wife is being held.")
print("She gestures (meaningfully) towards the cell lock.")
print("You have three options.")
print("1) Attempt to impress your wife and regain her favor by picking the lock.")
print("2) Use your powers to... well, you're not sure what. But something.")
print("3) Ask the distracted shreiff to open the door.")
choice = input("Choose your action. (Type either '1', '2', or '3').\n")
if (choice == "1"):
readBetter()
pickTheLock()
elif (choice == "2"):
readBetter()
powersToUnlock()
elif (choice == "3"):
readBetter()
askPolitely()
else:
error()
sneakPast()
## The user decides to ask the sheriff politely, GAME OVER
def askPolitely():
print("You spin around, and walk over to the sheriff.")
print("He seems just as shocked as your wife.")
print("'Would you mind unlocking this cell?' You ask, politely.")
print("\nThis does not work.")
print("He arrests you and signals to the townspeople.")
capturedByTownspeople()
## The user decides to try to pick the lock, GAME OVER
def pickTheLock():
print("You do not know how to pick locks.")
print("\nYour wife no longer remembers why she married you.")
print("\nYour 'Successful Valentine's Day' meter plumets.")
print("\nThe sheriff immediately notices you and signals to the townspeople.")
capturedByTownspeople()
## User decides to use their powers to destroy the lock
def powersToUnlock():
print("You concentrate on the lock and pray for something to happen.")
powers()
if (witchType == 2):
action = """Water starts to gather on, and around the metal of the lock.
The lock begins to rust before your eyes--it eventually disintigrates."""
elif (witchType == 1):
action = "Flames errupt from your hands! The lock melts under your barrage."
elif (witchType == 3):
action = """The metal of the lock creaks and moans. It twists itself
unexpectedly into the shape of an oragami crane."""
else:
action = """You look down at the lock and notice that the key is still in it.
You take a hold of it, and turn it."""
print(action, "You push the door gently inwards, and it creaks open.")
print("""and as a bonus, your wife looks mildly impressed. You're glad you did not make a fool
of yourself by trying to pick the lock, and instead did the cool, impressive thing.""")
## Assign 'loveOMeter' a 25 point increase
global loveOMeter
loveOMeter += 25
print("\n(Your 'Successful Valentine's Day' meter has increased to", loveOMeter, "%)\n")
readBetter()
youEscape()
## The user escapes
def youEscape():
print("You grab your wife's hand & the two of you begin to run.")
print("'It's not truly a romantic getaway if one of us isn't kidnapped.' You say.")
print("She cracks a smile. 'Regadless,' she says, 'You're not planning our next vacation.'")
print("""\nYou run, hand in hand, for the door--but unfortunately, all of this cute dialogue
has captured the sheriff's attention.""")
print("'Stop right there.' Shouts the sheriff. 'The power of Christ compells you!'")
print("Your wife and you exchange a glance.")
print("\nQuick! Say something witty!")
print("1) Erm...")
print("2) *eye roll* Isn't that vampires? Get your supernatural creatures straight.")
print("3) Hah! I love garlic sauce on my pasta!")
choice = input("Choose your action. (Type either '1', '2', or '3').\n")
if (choice == "1"):
readBetter()
print("Alack!\nYou could not think of anything!")
print("Thankfully, your blunder goes mostly unnoticed.")
elif (choice == "2"):
readBetter()
print("A fantastic comeback!")
print("Both the sheriff and your wife seem mighty impressed.")
## Assign 'loveOMeter' a 10 point increase
## Remind program that we are using a global variable in this function
global loveOMeter
loveOMeter+=10
print("\n(Your 'Successful Valentine's Day' meter has increased to", loveOMeter, "%)")
elif (choice == "3"):
readBetter()
print("You've said something that vaguely relates, but in the worst possible way!")
print("Oh dear.")
## Assign 'loveOMeter' a 10 point decrease
loveOMeter-=10
print("\n(Your 'Successful Valentine's Day' meter has decreased to", loveOMeter, "%)")
else:
error()
youEscape()
readBetter()
fightTheSheriff()
## User must choose how to incapacitate the sheriff
def fightTheSheriff():
print("Witty repartee now aside, you must decide how to incapacitate the sheriff.")
print("You have three options.")
print("1) Convince him to let you by.")
print("2) Hand to hand combat.")
print("3) Let your wife figure it out.")
choice = input("Choose your action. (Type either '1', '2', or '3').\n")
if (choice == "1"):
readBetter()
print("The sheriff isn't too into listening.")
print("Before you can even open your mouth, he yells out to his fellow townspeople.")
capturedByTownspeople()
elif (choice == "2"):
readBetter()
print("You've read a lot of books that include fighty bits.")
print("It can't be that much different in real life... can it?")
print("\nIt turns out, it's not.")
print("You just have to be willing to hurt & get hurt back.")
print("\nWhile efficient, your wife does not believe in violence.")
print("\nEspecially not while she's on holiday.")
## Assign 'loveOMeter' a 5 point decrease
## Remind program that we are using a global variable in this function
global loveOMeter
loveOMeter -= 5
print("\n(Your 'Successful Valentine's Day' meter has decreased to", loveOMeter, "%)")
readBetter()
soNowWeFindOurselvesTogether()
elif (choice == "3"):
readBetter()
print("Your wife appreciates you letting her have the narrative spotlight for once.")
print("You watch her eyes flash bright blue, and she makes a sharp cutting motion with her arm.")
print("The sheriff collapses in a sudden deep slumber.")
## Assign 'loveOMeter' a 10 point increase
loveOMeter += 10
print("\n(Your 'Successful Valentine's Day' meter has increased to", loveOMeter, "%)")
soNowWeFindOurselvesTogether()
else:
error()
fightTheSheriff()
readBetter()
## User must now choose an action in the town square
def soNowWeFindOurselvesTogether():
readBetter()
print("Your wife and you emerge from the town jail.")
print("You can see the townspeople gathering flamable material in the distance.\n")
print("You look around for some sort of getaway method.")
print("1) An old jalopy practically rusted to the sidewalk.")
print("2) A pair of broomsticks rested haphazardly against the side of a building.")
print("3) A firey stallion tied to a post, munching out of a feedbag.")
choice = input("Choose your action. (Type either '1', '2', or '3').\n")
readBetter()
if (choice == "1"):
print("Your wife glares at the rustbucket-death-trap before reluctantly climbing inside.")
print("""You try to think of a cool joke about how old the car is and how great your
Valentine's Day is going, but you come up blank.""")
## Assign 'loveOMeter' a 15 point decrease for style
## Remind program that we are using a global variable in this function
global loveOMeter
loveOMeter -= 15
print("\n(Your 'Successful Valentine's Day' meter has decreased to", loveOMeter, "%)")
print("""\nHowever, by some miracle the old thing has the key in the ignition and
manages to cough and hack its way into life.""")
print("It crawls slowly away from the town.")
print("'It's been one helluva day.' You say.")
print("Your wife agrees.")
print("\nShe also insists that you do not plan your next vacation.")
youWin()
elif (choice == "2"):
print("The broomstick thing is a harmful stereotype.")
print("\nAlso, brooms cannot fly, or move in any sort of way unassisted.")
print("Your wife and you get into a loud argument.")
readBetter()
capturedByTownspeople()
elif (choice == "3"):
print("Salutations for style, your wife looks mad impressed.")
print("""She loves horses--even more so when they're your mode of escape from terrible
villagers seeking to burn you at the stake.""")
## Assign 'loveOMeter' a 15 point increase for style
loveOMeter += 15
print("\n(Your 'Successful Valentine's Day' meter has increased to", loveOMeter, "%)")
print("\n'Did you plan this??' She asks.")
print("'Oh yes.' You absolutely lie and then thank whatever higher powers are out there.")
print("""\nYou help your wife onto the horse (who seems a bit surprised, but not upset at
this new development in its life, and besides, he's a fan of witches).""")
print("You untie the horse from the post, unclip the feed bag, and then climb on yourself.")
print("You ride happily ever after into the sunset.")
youWin()
else:
error()
soNowWeFindOurselvesTogether()
readBetter()
## User reacher the end of the game, YOU WIN
def youWin():
readBetter()
print("\n\n\n\n")
print(characterName + ",", witchKind + ",", "congratulations.")
print("\nYOU WIN!\n")
print("\n(Your 'Successful Valentine's Day' meter is at", loveOMeter, "%")
if (loveOMeter == 100):
choice = input("\nWould you like to play again (y/n)\n")
choice = choice.lower()
if (choice == "y"):
readBetter()
start()
elif(choice == "n"):
readBetter()
exit()
else:
error()
youWin()
else:
choice = input("""\nWould you like to play again to try and fill your 'Successful
Valentine's Day' meter all the way to the top? (y/n)\n""")
choice = choice.lower()
if (choice == "y"):
readBetter()
start()
elif(choice == "n"):
readBetter()
exit()
else:
error()
youWin()
## Error message for when user types the wrong thing
def error():
readBetter()
print("\nDo what you're told. \nTry again with the proper command.\n")
readBetter()
## Big line to help user read
def readBetter():
print("----------------------------------------------------")
## Run
title()
|
95eb45ad083a43ce1db7ffe5a2f47d0bd30b43c2 | edunsmore19/Computer-Science | /Homework_Monty_Hall_Simulation.py | 2,767 | 4.59375 | 5 | ## Homework_Monty_Hall_Simulation
## January 8, 2018
## Create a Monty Hall simulation
## Thoughts: It's always better to switch your door. When you first choose your door,
## you have a 1/3 chance of selecting the one with a car behind it. After a door holding
## a penny is revealed, it is then eliminated. If you switch your choice, you have a 1/2
## chance of selecting the car, but if you stay with your original choice, your likelihood
## of choosing the car remains at a 1/3 chance.
import random
car = 0
probability = 0
iChoose = 0
montyChooses = 0
iChooseTwice = 0
## If you do not switch
for x in range(0, 1000):
car = random.choice([1, 2, 3])
print(car)
iChoose = random.choice([1, 2, 3])
print(iChoose)
if (iChoose == car):
print("You Win!")
probability+= 1
else:
print("Oh no... a goat!")
print("The probability of you winning: ", probability/1000)
car = 0
door1 = 1
door2 = 2
door3 = 3
probability = 0
iChoose = 0
montyChooses = 0
## If you DO switch
for x in range(0, 1000):
iChooseTwice = 0
print()
car = random.choice([1, 2, 3])
print("Car is behind: ", car)
iChoose = random.choice([1, 2, 3])
print("I choose: ", iChoose)
if (door1 == car):
if (iChoose == 2):
montyChooses = 3
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
else:
montyChooses = 2
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
elif (door2 == car):
if (iChoose == 1):
montyChooses = 3
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
else:
montyChooses = 1
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
else:
if (iChoose == 1):
montyChooses = 2
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
else:
montyChooses = 1
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
#
iChooseTwice = 6 - montyChooses - iChoose
print("I choose again:", iChooseTwice)
if (iChooseTwice == car):
print("You Win!")
probability+= 1
else:
print("Oh no... a goat!")
print("The probability of you winning: ", probability/1000)
## So, turns out its actually a 2/3 chance of guessing correctly if you change your door.
## You have a 1/3 chance of choosing the car in the first simulation, but in the second
## simulation, you have a 2/3 chance of choosing a door without the car, so when Monty
## opens a door to reveal a goat, switching your door makes it more likely that you
## then choose a car (as you likely chose a goat). There is a 2/6 probability of losing
## when you switch (and thats only if you choose the car correctly on the first go).
|
e42d64e87a4d0c7d655c0085ff1917ab65b986a1 | raghuveerls/Ncorr-Python-EditedCode | /Edited code/ncorr_functions.py | 28,031 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on Tue Apr 2 17:35:38 2019
@author: raghuveer
'''
#%%
# =============================================================================
# User chooses the images to perform DIC on
# =============================================================================
def set_Images(UI_var_dict): #UI_var_dict stands for UserInterface_variables_dictionary
from tkinter.filedialog import askopenfilenames
import os
pictures = askopenfilenames(title = 'Choose the files') #Get image names of all the images
pic_list = list(pictures) #Store image names with address in a list
pic_names = []
for file in pic_list:
pic_names.append(os.path.basename(file)) #Obtain only the image names
UI_var_dict['directory'] = os.path.dirname(pic_list[0]) #Obtain base directory and store in the dictionary
(dummy, UI_var_dict['file_type']) = os.path.splitext(pic_names[0]) #Obtain image type and store in the dictionary
i = 0
for file in pic_names:
os.rename(os.path.join(UI_var_dict['directory'], file),
os.path.join(UI_var_dict['directory'], 'Image_' + str(i)+UI_var_dict['file_type'])) #Rename all images as "Image_#.file_type"
i += 1
UI_var_dict['file_total'] = str(len(pic_names)) #Store number of files in the dictionary
#%%
# =============================================================================
# User chooses the DIC parameters to use for analysis
# =============================================================================
def set_variables(root,UI_var_dict):
import tkinter as tk
from tkinter import messagebox
import pickle
import os
direc = UI_var_dict['directory'] #Obtain directory in which images are stored
if not os.path.exists(direc + '/DataFiles'):
os.mkdir(direc + '/DataFiles') #Create base directory to store the data files
def set_var():
# Set the variables in the UI variables dictionary
UI_var_dict['scale_factor'] = str(scale.get()) #scalefactor for the dataset
UI_var_dict['subregion_radius'] = str(radius.get()) # subregion radius for the analysis
UI_var_dict['threads'] = str(threads.get()) # # of threads to use
UI_var_dict['subregion_shape'] = str(shape.get()) # subergion shape to use
UI_var_dict['analysis_type'] = str(Type.get()) # small strain, large strain, or discontinuous strain
pixelLen = pix.get()
try:
pixelLen = float(pixelLen)
UI_var_dict['pixelLen'] = str(pixelLen) #pixels per mm
setvar.destroy()
with open(UI_var_dict['directory'] + '/DataFiles/UI_variables.pickle','wb') as handle:
pickle.dump(UI_var_dict, handle, protocol = pickle.HIGHEST_PROTOCOL) #Store dictionary variables in file
except ValueError: # If user doesn't input a number
messagebox.showwarning('Error','Please enter numeric for Pixels/mm')
return
#Create window and set up labels for the different user input options
setvar = tk.Toplevel(root)
tk.Label(setvar,text = 'Pixels/mm').grid(row=0)
tk.Label(setvar,text = 'Scale Factor').grid(row=1)
tk.Label(setvar,text = 'Subregion radius').grid(row=2)
tk.Label(setvar,text = 'Threads').grid(row=3)
tk.Label(setvar,text = 'Subregion shape').grid(row=4)
tk.Label(setvar,text = 'Analysis type').grid(row=5)
#Entry widget for inputting pixels/mm in the images
pix = tk.Entry(setvar)
pix.insert(1, float(UI_var_dict['pixelLen']))
pix.grid(row = 0, column = 1)
#Slider widget for inputting the scalefactor to be used
scale = tk.Scale(setvar, from_ = 1, to=6, tickinterval=1, orient = tk.HORIZONTAL)
scale.set(int(UI_var_dict['scale_factor']))
scale.grid(row = 1, column = 1, columnspan = 2)
#Slider widget for inputting the subset radius
radius = tk.Scale(setvar, from_ = 5, to=50, tickinterval=10, orient = tk.HORIZONTAL)
radius.set(int(UI_var_dict['subregion_radius']))
radius.grid(row = 2, column = 1, columnspan = 2)
#Slider widget for inputting the number of threads to use in computations
threads = tk.Scale(setvar, from_ = 1, to=8, tickinterval=2, orient = tk.HORIZONTAL)
threads.set(int(UI_var_dict['threads']))
threads.grid(row = 3, column = 1, columnspan = 2)
#Select subregion shape - Circle or Square
shape = tk.StringVar()
shape.set(UI_var_dict['subregion_shape'])
tk.Radiobutton(setvar, text = 'Circle', variable = shape, value ='circle').grid(row = 4, column = 1)
tk.Radiobutton(setvar, text = 'Square', variable = shape, value ='square').grid(row = 4, column = 2)
#Select analysis type - Large or Small strain
Type = tk.StringVar()
Type.set(UI_var_dict['analysis_type'])
tk.Radiobutton(setvar, text = 'Large strain', variable = Type, value ='large').grid(row = 5, column = 1)
tk.Radiobutton(setvar, text = 'Small strain', variable = Type, value ='small').grid(row = 5, column = 2)
#Button to complete user input
done = tk.Button(setvar,text = 'Done', command = set_var)
done.grid(row = 6, column = 1, columnspan = 2)
#%%
# =============================================================================
# User chooses to process images or calculate displacements and gradients
# =============================================================================
def run(UI_var_dict, action):
import subprocess as sp
import tkinter as tk
from tkinter import messagebox
UI_var_dict['action'] = action #Process images or calculate displacements?
#Create and set up window to display output messages from Ncorr
root = tk.Toplevel()
root.geometry('1000x400')
scroll = tk.Scrollbar(root)
scroll.pack(side = tk.RIGHT, fill = tk.Y)
text = tk.Text(root)
text.pack(fill = tk.BOTH, expand = 1)
scroll.config(command = text.yview)
text.config(yscrollcommand = scroll.set)
text.insert(tk.END,'Starting\n')
text.see(tk.END)
#Run C++ executable
out = sp.Popen(['./ncorr_test', UI_var_dict['action'], UI_var_dict['directory'], UI_var_dict['file_type'], UI_var_dict['file_total'],
UI_var_dict['pixelLen'], UI_var_dict['scale_factor'], UI_var_dict['subregion_radius'], UI_var_dict['threads'],
UI_var_dict['subregion_shape'], UI_var_dict['analysis_type']], stdout = sp.PIPE, text = True, bufsize = 0)
temp = out.stdout.readline() # read the first line
while temp:
if 'Saving' in temp or 'Processing' in temp or 'Changing perspective' in temp:
root.title(temp) #Update window title when necessary
text.insert(tk.END, temp)
text.see(tk.END)
root.update_idletasks()
temp = out.stdout.readline() # read output
out.communicate()
messagebox.showinfo('Complete',UI_var_dict['action'].capitalize()+' Finished!')
root.destroy()
#%%
# =============================================================================
# Create the required folders and store displacements and displacements gradients as .npy files
# =============================================================================
def dataprocess():
import numpy as np
from tkinter.filedialog import askdirectory
from tkinter import messagebox
import pickle
direc = askdirectory() #Base directory
with open(direc + '/DataFiles/UI_variable.pickle','rb') as handle:
UI_var_dict = pickle.load(handle) #Get UI variables
framecount = int(UI_var_dict['file_total']) #Total number of images
#Create the required folders
import os
datafile_path = direc + '/DataFiles/' #create file path for new directory for the data files
def create_folders(perspective):
if not os.path.exists(datafile_path + perspective):
os.mkdir(datafile_path + perspective) #Create base directory for each perspective
if not os.path.exists(datafile_path + perspective + '/v_displacements'):
os.mkdir(datafile_path + perspective + '/v_displacements') #Create directory for storing v displacements
if not os.path.exists(datafile_path + perspective + '/u_displacements'):
os.mkdir(datafile_path + perspective + '/u_displacements') #Create directory for storing u displacements
if not os.path.exists(datafile_path + perspective + '/dux_dispgrad'):
os.mkdir(datafile_path + perspective + '/dux_dispgrad') #Create directory for storing du/dx displacement gradient
if not os.path.exists(datafile_path + perspective + '/duy_dispgrad'):
os.mkdir(datafile_path + perspective + '/duy_dispgrad') #Create directory for storing du/dy displacement gradient
if not os.path.exists(datafile_path + perspective + '/dvx_dispgrad'):
os.mkdir(datafile_path + perspective + '/dvx_dispgrad') #Create directory for storing dv/dx displacement gradient
if not os.path.exists(datafile_path + perspective + '/dvy_dispgrad'):
os.mkdir(datafile_path + perspective + '/dvy_dispgrad') #Create directory for storing dv/dy displacement gradient
create_folders('Lagrangian') #Create folders for Lagrangian data
create_folders('Eulerian') #Create folders for Eulerian data
run(UI_var_dict, 'dataprocess') #Run the C++ executable for get the data
def numpy_disps(perspective): #function to get data from .csv files and collect it as .npy file
disp_grad = [] #displacement gradients
displacements = [] #displacements
for i in range(framecount-1):
#Obtain du/dx(dux), du/dy(duy), dv/dv(dvx), dv/dy(dvy) from their respective .csv files for each frame
dux = np.genfromtxt(direc + '/DataFiles/' + perspective + '/dux_dispgrad/dux_array_' + perspective + '_frame' + str(i+1) + '.csv', delimiter = ',', dtype = None)
duy = np.genfromtxt(direc + '/DataFiles/' + perspective + '/duy_dispgrad/duy_array_' + perspective + '_frame' + str(i+1) + '.csv', delimiter = ',', dtype = None)
dvx = np.genfromtxt(direc + '/DataFiles/' + perspective + '/dvx_dispgrad/dvx_array_' + perspective + '_frame' + str(i+1) + '.csv', delimiter = ',', dtype = None)
dvy = np.genfromtxt(direc + '/DataFiles/' + perspective + '/dvy_dispgrad/dvy_array_' + perspective + '_frame' + str(i+1) + '.csv', delimiter = ',', dtype = None)
#Obtain u and v displacements from their respective .csv files for each frame
u = np.genfromtxt(direc + '/DataFiles/' + perspective + '/u_displacements/u_array_' + perspective + '_frame' + str(i+1) + '.csv', delimiter = ',', dtype = None)
v = np.genfromtxt(direc + '/DataFiles/' + perspective + '/v_displacements/v_array_' + perspective + '_frame' + str(i+1) + '.csv', delimiter = ',', dtype = None)
#Append lists with latest frame information
#displacement gradient[frame][du./dv. - 0/1][d.x/d.y - 0/1][y pixel][x pixel]
disp_grad.append([[dux]+[duy]] + [[dvx] + [dvy]])
#displacements[frame][u/v - 0/1][y pixel][x pixel]
displacements.append([u] + [v])
#Convert the displacements list to numpy arrays and save as .npy
displacements = np.array(displacements)
np.save(direc + '/DataFiles/' + perspective + '/displacements', displacements)
#Convert the displacement gradients list to numpy arrays and save as .npy
disp_grad = np.array(disp_grad)
np.save(direc + '/DataFiles/' + perspective + '/disp_grad', disp_grad)
messagebox.showinfo('Done', perspective + ' Data Processed!')
numpy_disps('Lagrangian') # Create .npy displacement and displacement gradient files for the Lagrangian data
numpy_disps('Eulerian') # Create .npy displacement and displacement gradient files for the Eulerian data
#%%
# =============================================================================
# Calculate Green or Almansi-Hamel strains
# =============================================================================
def calc_strains(perspective):
import numpy as np
from tkinter.filedialog import askdirectory
from tkinter import messagebox
import pickle
askcsv = True
askcsv = messagebox.askyesno('Save options','Avoid saving .csv files for each frame? '
'Saving as .csv takes up a lot of space (.npy file will be saved by default))')
direc = askdirectory()
with open(direc + '/DataFiles/UI_variable.pickle','rb') as handle:
UI_var_dict = pickle.load(handle)
framecount = int(UI_var_dict['file_total'])
if not askcsv:
import os
if not os.path.exists(direc + '/DataFiles/' + perspective + '/xx_Strains'):
os.mkdir(direc + '/DataFiles/' + perspective + '/xx_Strains')
if not os.path.exists(direc + '/DataFiles/' + perspective + '/xy_Strains'):
os.mkdir(direc + '/DataFiles/' + perspective + '/xy_Strains')
if not os.path.exists(direc + '/DataFiles/' + perspective + '/yy_Strains'):
os.mkdir(direc + '/DataFiles/' + perspective + '/yy_Strains')
try:
disp_grad = np.load(direc + '/DataFiles/' + perspective + '/disp_grad.npy')
except OSError:
messagebox.showerror('Error','Process the data first!')
Strain = []
for i in range(framecount-1):
dux = disp_grad[i][0][0]
duy = disp_grad[i][0][1]
dvx = disp_grad[i][1][0]
dvy = disp_grad[i][1][1]
if perspective == 'Lagrangian':
xx = (0.5*(2*dux + dux**2 + dvx**2))
xy = (0.5*(duy + dvx + dux*duy + dvx*dvy))
yy = (0.5*(2*dvy + duy**2 + dvy**2))
elif perspective == 'Eulerian':
xx = (0.5*(2*dux - dux**2 - dvx**2))
xy = (0.5*(duy + dvx - dux*duy - dvx*dvy))
yy = (0.5*(2*dvy - duy**2 - dvy**2))
#E[frame][Ex./Ey.(0/1)][E.x/E.y(0,1)][y pixel position][x pixel position]
Strain.append([[xx]+[xy]] + [[xy]+[yy]])
if not askcsv:
#Save the Lagradngian Green Strain as .csv files
np.savetxt(direc + '/DataFiles/' + perspective + '/xx_Strains/xx_Strain_Frame_' + str(i+1) + '.csv', xx, delimiter = ',')#Save Exx
np.savetxt(direc + '/DataFiles/' + perspective + '/xy_Strains/xy_Strain_Frame_' + str(i+1) + '.csv', xy, delimiter = ',')#Save Exy
np.savetxt(direc + '/DataFiles/' + perspective + '/yy_Strains/yy_Strain_Frame_' + str(i+1) + '.csv', yy, delimiter = ',')#Save Eyy
if i == framecount-2:
messagebox.showinfo('Done', perspective + ' Strains calculated!')
Strain = np.array(Strain)
np.save(direc + '/DataFiles/' + perspective + '/' + perspective + '_Strains', Strain)
#%%
def calc_defgrad():
import numpy as np
from tkinter.filedialog import askdirectory
from tkinter import messagebox
import pickle
askcsv = True
askcsv = messagebox.askyesno('Save options','Avoid saving .csv files for each frame? '
'Saving as .csv takes up a lot of space (.npy file will be saved by default))')
direc = askdirectory()
with open(direc + '/DataFiles/UI_variable.pickle','rb') as handle:
UI_var_dict = pickle.load(handle)
if not askcsv:
import os
if not os.path.exists(direc + '/DataFiles/Deformation_gradient'):
os.mkdir(direc + '/DataFiles/Deformation_gradient')
if not os.path.exists(direc + '/DataFiles/Deformation_gradient/F11'):
os.mkdir(direc + '/DataFiles/Deformation_gradient/F11')
if not os.path.exists(direc + '/DataFiles/Deformation_gradient/F12'):
os.mkdir(direc + '/DataFiles/Deformation_gradient/F12')
if not os.path.exists(direc + '/DataFiles/Deformation_gradient/F21'):
os.mkdir(direc + '/DataFiles/Deformation_gradient/F21')
if not os.path.exists(direc + '/DataFiles/Deformation_gradient/F22'):
os.mkdir(direc + '/DataFiles/Deformation_gradient/F22')
try:
disp_grad_Lag = np.load(direc + '/DataFiles/Lagrangian/disp_grad.npy')
except OSError:
messagebox.showerror(title = 'File not found', message = 'Please make sure displacement gradients have been calculated!')
framecount = int(UI_var_dict['file_total'])
F = []
for i in range(framecount-1):
F11 = disp_grad_Lag[i][0][0] + 1 #dU/dX + 1
F12 = disp_grad_Lag[i][0][1] #dU/dY
F21 = disp_grad_Lag[i][1][0] #dV/dX
F22 = disp_grad_Lag[i][1][1] + 1 #dV/dY + 1
#F[frame][F1./F2.(0/1)[F.1/F.2(0/1)][y pixel position][x pixel position]
F.append([[F11]+[F12]] + [[F21]+[F22]])
if not askcsv:
#Save the deformation gradients as .csv
np.savetxt(direc +'/DataFiles/Deformation_gradient/F11/F11_frame' + str(i+1) + '.csv',F11,delimiter=',') #save F11
np.savetxt(direc +'/DataFiles/Deformation_gradient/F12/F12_frame' + str(i+1) + '.csv',F12,delimiter=',') #save F11
np.savetxt(direc +'/DataFiles/Deformation_gradient/F21/F21_frame' + str(i+1) + '.csv',F21,delimiter=',') #save F11
np.savetxt(direc +'/DataFiles/Deformation_gradient/F22/F22_frame' + str(i+1) + '.csv',F22,delimiter=',') #save F11
if i == framecount-2:
messagebox.showinfo('Done','Deformation gradient calculated!')
F = np.array(F)
np.save(direc + '/DataFiles/F', F)
#%%
def dispvid_process():
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams['animation.ffmpeg_path'] = '/usr/bin/ffmpeg'
from tkinter.filedialog import askdirectory
import pickle
from tkinter import messagebox
direc = askdirectory()
with open(direc + '/DataFiles/UI_variable.pickle','rb') as handle:
UI_var_dict = pickle.load(handle)
framecount = int(UI_var_dict['file_total'])
file_type = UI_var_dict['file_type']
scalefactor = int(UI_var_dict['scale_factor'])
img = []
for i in range(framecount):
img.append(Image.open(direc + '/Image_' + str(i) + file_type))
imgwidth, imgheight = img[0].size
def makevideo(perspective):
displacements = np.load(direc + '/DataFiles/' + perspective + '/displacements.npy')
roi_limits = scalefactor*np.genfromtxt(direc + '/DataFiles/' + perspective + '/roi_limits.csv', delimiter = ',', dtype = None)
min_u = []
max_u = []
min_v = []
max_v = []
for i in range(framecount-1):
min_u.append(np.nanmin(displacements[i][0]))
max_u.append(np.nanmax(displacements[i][0]))
min_v.append(np.nanmin(displacements[i][1]))
max_v.append(np.nanmax(displacements[i][1]))
min_u = min(min_u)
max_u = max(max_u)
min_v = min(min_v)
max_v = max(max_v)
def make_animation(vmin, vmax, disp_type):
if disp_type == 'u':
array_pos = 0
elif disp_type == 'v':
array_pos = 1
dpi = 96
fig, ax = plt.subplots(figsize = (imgwidth/dpi, imgheight/dpi), dpi = dpi)
ax.set_xlim(0,imgwidth)
ax.set_ylim(imgheight,0)
if perspective == 'Lagrangian':
start_frame = 0
elif perspective == 'Eulerian':
start_frame = 1
imRAW = ax.imshow(img[start_frame], extent = [0, imgwidth, imgheight, 0], cmap = 'gray')
imDIC = ax.imshow(displacements[0][array_pos], extent = [roi_limits[0][2], roi_limits[0][3], roi_limits[0][1], roi_limits[0][0]],
vmin = vmin, vmax = vmax, alpha = 0.75, cmap = 'jet')
ax.tick_params(axis = 'both', which = 'both', bottom = False, left = False, labelbottom = False, labelleft = False)
ax.axis('off')
fig.colorbar(imDIC)
#fig.subplots_adjust(left = 0.0, right = 1.0, bottom = 0.0, top = 1.0, wspace = 0.0, hspace = 0.0)
def animate(i):
imDIC.set_data(displacements[i][array_pos][:,:-1])
imDIC.set_extent([roi_limits[i][2], roi_limits[i][3], roi_limits[i][1], roi_limits[i][0]])
if perspective == 'Lagrangian':
imRAW.set_data(img[0])
elif perspective == 'Eulerian':
imRAW.set_data(img[i+1])
ani = animation.FuncAnimation(fig, animate, frames = framecount-1, interval = 50)
ani.save(direc + '/DataFiles/' + perspective + '/' + disp_type + '_displacement_' + perspective + '.mp4', dpi = dpi)
messagebox.showinfo('Done','Completed ' + disp_type + ' displacement video in ' + perspective + ' coordinates!')
plt.close(fig)
make_animation(min_u, max_u, 'u')
make_animation(min_v, max_v, 'v')
makevideo('Lagrangian')
makevideo('Eulerian')
#%%
def strainvid_process(perspective):
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams['animation.ffmpeg_path'] = '/usr/bin/ffmpeg'
from tkinter.filedialog import askdirectory
import pickle
from tkinter import messagebox
direc = askdirectory()
with open(direc + '/DataFiles/UI_variable.pickle','rb') as handle:
UI_var_dict = pickle.load(handle)
framecount = int(UI_var_dict['file_total'])
file_type = UI_var_dict['file_type']
scalefactor = int(UI_var_dict['scale_factor'])
img = []
for i in range(framecount):
img.append(Image.open(direc + '/Image_' + str(i) + file_type))
imgwidth, imgheight = img[0].size
strains = np.load(direc + '/DataFiles/' + perspective + '/' + perspective + '_Strains.npy')
roi_limits = scalefactor*np.genfromtxt(direc + '/DataFiles/' + perspective + '/roi_limits.csv', delimiter = ',', dtype = None)
min_xx = []
max_xx = []
min_xy = []
max_xy = []
min_yy = []
max_yy = []
for i in range(framecount-1):
min_xx.append(np.nanmin(strains[i][0][0]))
max_xx.append(np.nanmax(strains[i][0][0]))
min_xy.append(np.nanmin(strains[i][0][1]))
max_xy.append(np.nanmax(strains[i][0][1]))
min_yy.append(np.nanmin(strains[i][1][1]))
max_yy.append(np.nanmax(strains[i][1][1]))
min_xx = min(min_xx)
max_xx = max(max_xx)
min_xy = min(min_xy)
max_xy = max(max_xy)
min_yy = min(min_yy)
max_yy = max(max_yy)
def make_animation(vmin, vmax, strain_type):
if strain_type == 'xx':
array_pos1 = 0
array_pos2 = 0
elif strain_type == 'xy':
array_pos1 = 0
array_pos2 = 1
elif strain_type == 'yy':
array_pos1 = 1
array_pos2 = 1
dpi = 96
fig, ax = plt.subplots(figsize = (imgwidth/dpi, imgheight/dpi), dpi = dpi)
ax.set_xlim(0,imgwidth)
ax.set_ylim(imgheight,0)
if perspective == 'Lagrangian':
start_frame = 0
elif perspective == 'Eulerian':
start_frame = 1
imRAW = ax.imshow(img[start_frame], extent = [0, imgwidth, imgheight, 0], cmap = 'gray')
imDIC = ax.imshow(strains[0][array_pos1][array_pos2], extent = [roi_limits[0][2], roi_limits[0][3], roi_limits[0][1], roi_limits[0][0]],
vmin = vmin, vmax = vmax, alpha = 0.75, cmap = 'jet')
ax.tick_params(axis = 'both', which = 'both', bottom = False, left = False, labelbottom = False, labelleft = False)
ax.axis('off')
fig.colorbar(imDIC)
def animate(i):
imDIC.set_data(strains[i][array_pos1][array_pos2][:,:-1])
imDIC.set_extent([roi_limits[i][2], roi_limits[i][3], roi_limits[i][1], roi_limits[i][0]])
if perspective == 'Lagrangian':
imRAW.set_data(img[0])
elif perspective == 'Eulerian':
imRAW.set_data(img[i+1])
ani = animation.FuncAnimation(fig, animate, frames = framecount-1, interval = 50)
ani.save(direc + '/DataFiles/' + perspective + '/' + strain_type + '_strain_' + perspective + '.mp4', dpi = dpi)
messagebox.showinfo('Done','Completed ' + strain_type + ' strain video in ' + perspective + ' coordinates!')
plt.close(fig)
make_animation(min_xx, max_xx, 'xx')
make_animation(min_xy, max_xy, 'xy')
make_animation(min_yy, max_yy, 'yy')
#%%
def polar_decomp():
import numpy as np
from numpy.linalg import qr
from scipy.linalg import polar
import pickle
from tkinter.filedialog import askdirectory
from tkinter import messagebox
direc = askdirectory()
with open(direc + '/DataFiles/UI_variable.pickle','rb') as handle:
UI_var_dict = pickle.load(handle)
F = np.load(direc + '/DataFiles/F.npy')
framecount = int(UI_var_dict['file_total'])
Ru = []
Rv = []
U = []
V = []
Q = []
Rq = []
rows, cols = F[0][0][0].shape
for i in range(framecount-1):
Ru_frame = []
U_frame = []
Rv_frame = []
V_frame = []
Q_frame = []
Rq_frame = []
for r in range(rows):
Ru_row = []
U_row = []
Rv_row = []
V_row = []
Q_row = []
Rq_row = []
for c in range(cols):
F_frame_pixel = np.array([[F[i][0][0][r][c], F[i][0][1][r][c]],
[F[i][1][0][r][c], F[i][1][1][r][c]]])
Ru_pixel, U_pixel = polar(F_frame_pixel, side = 'right')
Ru_row = Ru_row + [Ru_pixel]
U_row = U_row + [U_pixel]
Rv_pixel, V_pixel = polar(F_frame_pixel, side = 'left')
Rv_row = Rv_row + [Rv_pixel]
V_row = V_row + [V_pixel]
Q_pixel, Rq_pixel = qr(F_frame_pixel, mode = 'complete')
Q_row = Q_row + [Q_pixel]
Rq_row = Rq_row + [Rq_pixel]
Ru_frame.append([Ru_row])
U_frame.append([U_row])
Rv_frame.append([Rv_row])
V_frame.append([V_row])
Q_frame.append([Q_row])
Rq_frame.append([Rq_row])
Ru.append([Ru_frame])
U.append([U_frame])
Rv.append([Rv_frame])
V.append([V_frame])
Q.append([Q_frame])
Rq.append([Rq_frame])
left_polar = [Ru] + [U]
right_polar = [V] + [Rv]
qr_decomp = [Q] + [Rq]
left_polar = np.array(left_polar)
np.save(direc + '/DataFiles/left_polar', left_polar)
right_polar = np.array(right_polar)
np.save(direc + '/DataFiles/right_polar', right_polar)
qr_decomp = np.array(qr_decomp)
np.save(direc + '/DataFiles/qr_decomp', qr_decomp)
messagebox.showinfo('Done', 'Completed the decompositions!')
#%%
def set_action(UI_var_dict, action = None):
pass
|
cebc7f229d48eef5fd306cecc44adff9a5583875 | rjalic/django-uni-project | /main/utils.py | 1,496 | 3.578125 | 4 | def enough_ects_available(student, subject, selected_semester):
"""
Checks if the student has enough ects available in the selected semester.
"""
enrollments = student.enrollment_set.all()
ects_earned = subject.ects
for enrollment in enrollments:
if student.status == 'FULL_TIME' and enrollment.subject.semester_full_time == selected_semester:
ects_earned += enrollment.subject.ects
elif student.status == 'PART_TIME' and enrollment.subject.semester_part_time == selected_semester:
ects_earned += enrollment.subject.ects
if ects_earned > 30:
return False
return True
def previous_semester_criteria(student, subject, selected_semester):
"""
Checks if the student successfully passed the subjects in the previous semester.
"""
enrollments = student.enrollment_set.all()
if selected_semester > 2:
ceiling = selected_semester % 2 == 1 and selected_semester or selected_semester - 1
for i in range(1, ceiling):
target = student.status == 'FULL_TIME' and 15 or 6
ects_earned = 0
for enrollment in enrollments:
if student.status == 'FULL_TIME' and enrollment.subject.semester_full_time == i and enrollment.status == 'passed':
ects_earned += enrollment.subject.ects
elif student.status == 'PART_TIME' and enrollment.subject.semester_part_time == i and enrollment.status == 'passed':
ects_earned += enrollment.subject.ects
if ects_earned < target:
return False
return True |
5c6bef8cbb2cedbe941c60e204c2bf04098c6179 | cement-hools/algoritms | /14_sprint/g_perimeter_of_the_triangle.py | 296 | 3.96875 | 4 | def max_perimeter(arr):
arr.sort()
while len(arr) > 2:
c = arr.pop()
a = arr[-1]
b = arr[-2]
if c < a + b:
perimeter = a + b + c
return perimeter
return -1
x = [int(i) for i in '5 3 7 2 8 3'.split()]
print(max_perimeter(x))
|
88e47c5e825618255d41de25eff446604e3c6b4e | cement-hools/algoritms | /14_sprint/f_sort_by_parity.py | 1,344 | 3.875 | 4 | # Кондратий издал новый закон. Во всех списках четные числа должны стоять на четных позициях,
# а нечетные числа - на нечетных. Уже существующие списки придется пересортировать.
# В списках, которые вам достанутся, одинаковое количество четных и нечетных элементов.
# Нужно отсортировать его в соответствии с новым законом.
# Исходный порядок внутри групп четных и нечетных элементов менять нельзя.
n = 1
if n:
x = [int(i) for i in '4 2 5 7'.split()] # res 4 5 2 7
res = []
print(x)
len_x = len(x)
for i in range(len_x):
if not i % 2:
for j in range(len(x)):
element = x[j]
if not element % 2:
res += [element]
x.pop(j)
break
else:
for j in range(len(x)):
element = x[j]
if element % 2:
res += [element]
x.pop(j)
break
print(res)
print(' '.join(map(str, res)))
|
e6ee754c36482ed7f29205e50a39a2e68eb2566b | cement-hools/algoritms | /13 sprint/G.spiral.py | 313 | 3.703125 | 4 | m = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
n = 1
k1 = 0
k2 = -2
n1 = len(m[0]) - 1
n2 = -n1
while n <= len(m) ** 2:
for i in range(k1, n1):
print(m[k1][i])
for i in range(k1, n1 + 1):
print(m[i][n1])
for i in range(k2, n2, -1):
print(m[i][])
n += 1
|
ce2381670cdcfcddc0dc7abf70f0d9e17ba2acf1 | cement-hools/algoritms | /14_sprint/final/a_large_number_bubble.py | 597 | 3.78125 | 4 | # id 45812420
def large_number(numbers_arr):
if not numbers_arr:
return '0'
numbers = list(map(str, numbers_arr))
for i in range(len(numbers)):
for j in range(len(numbers) - i - 1):
if numbers[j] + numbers[j + 1] < numbers[j + 1] + numbers[j]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
return ''.join(numbers)
def main():
count_of_numbers = int(input())
if count_of_numbers:
input_numbers = [i for i in input().split()]
print(large_number(input_numbers))
if __name__ == '__main__':
main()
|
040af79caa43ecd9bf6bba40819d7f86faec5cc3 | DYNAMIC-DENOM/python | /dictionary.py | 408 | 3.921875 | 4 | customer={"name":"debanjan das mandal",'ph_no':"938752410","address":"balaramdihi"}
print(customer["address"])
for x in customer:
print(x,"-",customer[x])
# customer={"name":"debanjan das mandal",'ph_no':"938752410","address":"balaramdihi"}
print(customer)
customer["email"]="ddm2001.jgm@gmail.com"
print(customer)
s={}
print(s)
s["email"]="ddm2001.jgm@gmail.com"
print(s)
nums={}
for num in range(1,101):
nums[num]=num*num
print(nums) |
c46dafb8976c6c65f94f1dcdbe2bc7379311cbee | DYNAMIC-DENOM/python | /function3A.py | 136 | 3.71875 | 4 | def add(a,b):
return(a+b)
x=add(5,5)
print(x)
print(add(5,5))
def add2(a,b):
print(a+b)
add2(5,6)
print(add2(5,6))
|
ad57eac163f7d8f369185c0956eeeb5422c65a76 | a-x-/flask_table | /examples/simple.py | 1,039 | 3.875 | 4 | from flask_table import Table, Col
"""Lets suppose that we have a class that we get an iterable of from
somewhere, such as a database. We can declare a table that pulls out
the relevant entries, escapes them and displays them.
"""
class Item(object):
def __init__(self, name, description):
self.name = name
self.description = description
class ItemTable(Table):
name = Col('Name')
description = Col('Description')
def main():
items = [Item('A', 'aaa'),
Item('B', 'bbb')]
tab = ItemTable(items)
# or {{ tab }} in jinja
print(tab.__html__())
"""Outputs:
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Description</th></tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>aaa</td>
</tr>
<tr>
<td>B</td>
<td>bbb</td>
</tr>
</tbody>
</table>
Except it doesn't bother to prettify the output.
"""
if __name__ == '__main__':
main()
|
36c0e9d1a83e4a2c2c57286bb80c57e62d87d4d3 | garrrth/m269 | /Chapter1/fraction.py | 3,983 | 3.609375 | 4 | class Fraction:
def __init__(self, top, bottom):
if not isinstance(top, int):
raise TypeError(str(top)+" is not of type Integer")
if not isinstance(bottom, int):
raise TypeError(str(bottom)+" is not of type Integer")
if bottom < 0:
top = top*-1
bottom = bottom*-1
common = gcd(top, bottom)
self.num = top//common
self.den = bottom//common
def __str__(self):
return str(self.num)+"/"+str(self.den)
def __add__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
newnum = self.num*otherfraction.den + \
self.den*otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum, newden)
def __radd__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
newnum = self.num*otherfraction.den + \
self.den*otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum, newden)
def __sub__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
newnum = self.num * otherfraction.den - \
self.den * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum, newden)
def __mul__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
newnum = self.num * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum, newden)
def __truediv__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
newnum = self.num * otherfraction.den
newden = self.den * otherfraction.num
return Fraction(newnum, newden)
def __eq__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
firstnum = self.num * otherfraction.den
secondnum = self.den * otherfraction.num
return firstnum == secondnum
def __gt__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
firstnum = self.num * otherfraction.den
secondnum = self.den * otherfraction.num
return firstnum > secondnum
def __lt__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
firstnum = self.num * otherfraction.den
secondnum = self.den * otherfraction.num
return firstnum < secondnum
def __ge__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
firstnum = self.num * otherfraction.den
secondnum = self.den * otherfraction.num
return firstnum >= secondnum
def __le__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
firstnum = self.num * otherfraction.den
secondnum = self.den * otherfraction.num
return firstnum <= secondnum
def __ne__(self, otherfraction):
if isinstance(otherfraction, int):
otherfraction = intToFraction(otherfraction)
firstnum = self.num * otherfraction.den
secondnum = self.den * otherfraction.num
return firstnum != secondnum
def getNum(self):
return self.num
def getDen(self):
return self.den
# HELPER METHODS #
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
def intToFraction(n):
return Fraction(n, 1)
|
f192e797cab3f4c72d5b1a3d97a2c95818325a77 | Muirgeal/Learning_0101_NameGenerator | /pig_latin_practice.py | 982 | 4.125 | 4 | """Turn an input word into its Pig Latin equivalent."""
import sys
print("\n")
print("Welcome to 'Pig Latin Translator' \n")
VOWELS = 'aeiou'
while True:
original = input("What word would you like to translate? \n")
print("\n")
#Remove white space from the beginning and the end
original = original.strip()
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in VOWELS:
result = word + "way"
print(result, file = sys.stderr)
else:
result = word[1:] + first + "ay"
print(result, file = sys.stderr)
else:
print("The format is incorrect. Please, make sure you entered a word",
"consisting of alphabetic characters only.", file = sys.stderr)
try_again = input("\n\n\nTry again? (Press ENTER else N to quit.) \n")
if try_again.lower() == "n":
sys.exit()
|
e5f7c935d8e552dda797b126dec06e853beb2703 | HenCor2019/numerical-analysis | /derivation.py | 519 | 3.59375 | 4 | from math import factorial, atan, pi, asin, sin, log
def combination(m, n):
return factorial(m) // (factorial(n) * factorial(m - n))
def f(x):
return log(x)
def derivation(x, n, h):
sum = 0
for i in range(0, n+1):
sum += combination(n, i)*f(x+(n-i)*h) * (-1)**i
print(sum/h**n)
def centralDiff(x,n,h):
sum = 0
for i in range(0, n+1):
sum += combination(n, i)*f(x- (n/2)*h +(n-i)*h) * (-1)**i
print(sum/h**n)
derivation(1, 4, 0.0001)
centralDiff(1, 4, 0.0001)
|
764cb7d9f49e79a6435293b45f41cf6580beb6be | SwarajyaRBhanja/advancedPython | /handlingException.py | 269 | 3.890625 | 4 |
try:
a= int(input("Please enter a number not equals to zero: "))
print(45/a)
except ZeroDivisionError as e:
print(f"You fucking asshole entered zero.")
print(e)
except ValueError as e:
print("You fucker didn't enter any number")
print(e)
|
e270e1fe5d6402f34df808658faf0fb340097372 | SwarajyaRBhanja/advancedPython | /lambdaFunc.py | 217 | 3.8125 | 4 |
#lambda: functions created using an expression using lambda keyword
#syntax: lambda arguments: expressions
x= int(input("Please enter a number"))
y=lambda l:l+5
cal= lambda m,n,p: m+n-p
print(y(x))
print(cal(8,5,2)) |
a06ba022b0bc8353361e1bc73cec94512ec950c1 | SwarajyaRBhanja/advancedPython | /list_comprehension.py | 355 | 3.640625 | 4 | a= [2,4,7,8,9,23,54,61,72,18]
#tradition approach
'''
b= []
for i in a:
if i%2==0:
b.append(i)
'''
b=[i for i in a if i%2==0]
print(b)
#list comprehension is an elegant way to create list based on existing list.
c=[k for k in a if k>20]
print(c)
x= [3,5,6,8,4,12,4,7,8,3,7,8]
print({y for y in x}) #printing a set {3, 4, 5, 6, 7, 8, 12}
|
d21a01f3f33d84b4bdf9ef3ddf4ed9c0e6dcda69 | aeeilllmrx/algorithms | /simple_BST.py | 3,058 | 3.8125 | 4 |
class BST():
def __init__(self, root, parent=None):
self.root = root
self.left = None
self.right = None
self.parent = parent
def insert(self, val):
if val > self.root:
if not self.right:
self.right = BST(val, self)
else:
self.right.insert(val)
else:
if not self.left:
self.left = BST(val, self)
else:
self.left.insert(val)
def find(self, val):
if val == self.root:
return True
elif val < self.root and self.left:
return self.left.find(val)
elif val > self.root and self.right:
return self.right.find(val)
return False
def get_min(self):
if not self.left:
return self
else:
return self.left.get_min()
def get_max(self):
if not self.right:
return self
else:
return self.right.get_max()
def get_succ(self):
if self.right:
return self.right.get_min()
# otherwise you need to keep going up until you were the left child
else:
cur = self
while cur == self.parent.right:
cur = self.parent
if cur.parent:
return cur.parent.right.get_min()
else:
return None
def delete(self):
# with 0 or 1 children, the case is simple
# either make the parent connect to None, or the single child
if not (self.left or self.right):
if self == self.parent.left:
self.parent.left = None
else:
self.parent.right = None
elif not self.right and (self == self.parent.left):
self.parent.left = self.left
elif not self.left and (self == self.parent.right):
self.parent.right = self.right
else:
s = self.get_succ()
self.root = s.root
s.delete()
def BFS_print(self):
# top to bottom
q = [self]
while q:
cur = q.pop(0)
print cur.root
if cur.left:
q.append(cur.left)
if cur.right:
q.append(cur.right)
def DFS_print(self):
# in order
s = [self]
while s:
cur = s.pop()
print cur.root
if cur.left:
cur.left.DFS_print()
if cur.right:
cur.right.DFS_print()
b = BST(5)
b.insert(3)
b.insert(8)
b.insert(7)
b.insert(19)
b.insert(4)
minv = b.get_min()
maxv = b.get_max()
succ = b.left.get_succ()
assert b.find(2) == False
assert b.find(3) == True
assert b.find(4) == True
assert minv.root == 3
assert maxv.root == 19
assert succ.root == 4
print "\ntop to bottom:"
b.BFS_print()
print "\nin order:"
b.DFS_print()
print "\ndeleting 3, 19, 5"
b.get_min().delete()
b.get_max().delete()
b.delete()
b.BFS_print()
|
648bffa03e8cb303367f2f601c67bbd5ef833aa0 | ildar-band/zernovaiv | /p2/for.py | 319 | 3.71875 | 4 | smth_list = [2, 456, "dfgdfg"]
smth_string = "somestring"
smth_dict = {'1':'dfd', '2':'4', '3':'8gj', '4':"gdfg6"}
smth_tutle = ('2',"3f")
def print_smth_by_for(smth):
for i in smth:
print(i)
print_smth_by_for(smth_list)
print_smth_by_for(smth_string)
print_smth_by_for(smth_dict)
print_smth_by_for(smth_tutle) |
d2fd79954de75caa73b7db9935ac649a909a4b4a | ildar-band/zernovaiv | /p2/while_task.py | 187 | 3.609375 | 4 | Name_list = ['Вася', 'Маша', 'Петя', 'Валера', 'Саша', 'Даша']
while Name_list[] != 'Валера':
Name_list[] += Name_list[]
Name_list.pop(['Валера']) |
acf50a0cb1d79ae87580f690daa7ada18c1f9d0a | hychoi99/nahchoina | /linesegment.py | 2,630 | 3.5 | 4 | import math
#import pygame
from vector import Vector
class LineSegment:
def __init__(self,p1,p2):
#make copies of incoming vector points
self.p1 = Vector(p1.x,p1.y)
self.p2 = Vector(p2.x,p2.y)
# def draw(self,window):
# pygame.draw.line(window,pygame.color.Color("red"),(int(self.p1.x),int(self.p1.y)),(int(self.p2.x),int(self.p2.y)),2)
#
def orthog(self):
n = self.p2.minus(self.p1)
n = n.normalize()
return Vector(n.y,-n.x)
#Suppose the two line segments run
#from p to p + r
#and from q to q + s.
#Then any point on the first line is representable as
#p + t r (for a scalar parameter t)
#and any point on the second line as q + u s (for a scalar parameter u).
def intersects(self,other):
p = self.p1
r = self.p2.minus(p)
q = other.p1
s = other.p2.minus(q)
#solving for t = (q-p) x s / (r x s)
qmp = q.minus(p)
qmpxs = qmp.cross(s)
rxs = r.cross(s)
if rxs == 0: #lines are parallel
return None
t = qmpxs/rxs
#solving for u = (q-p) x r / (r x s)
qmpxr = qmp.cross(r)
u = qmpxr/rxs
#so now we can get the coordinates by normalizing r, scaling by t
tscale = r.times(t)
intersection1 = p.plus(tscale)
sscale = s.times(u)
intersection2 = q.plus(sscale)
if (u <= 1.0) and (u >= 0) and (t <= 1.0) and (t >= 0):
#print t, u
rscale = r.times(t)
intersection1 = p.plus(rscale)
sscale = s.times(u)
intersection2 = q.plus(sscale)
#print rscale,sscale,intersection1,intersection2
#assert intersection1.equals(intersection2)
return rscale
else:
return None
def distToPoint(self, point): # x3,y3 is the point
px = self.p2.x-self.p1.x
py = self.p2.y-self.p1.y
something = px*px + py*py
u = ((point.x - self.p1.x) * px + (point.y - self.p1.y) * py) / float(something)
if u > 1:
u = 1
elif u < 0:
u = 0
x = self.p1.x + u * px
y = self.p1.y + u * py
dx = x - point.x
dy = y - point.y
# Note: If the actual distance does not matter,
# if you only want to compare what this function
# returns to other results of this function, you
# can just return the squared distance instead
# (i.e. remove the sqrt) to gain a little performance
dist = math.sqrt(dx*dx + dy*dy)
return dist
|
ef83b85579d8a3328098ac7a45a821f39f08bbd8 | NicholasBaxley/My-Student-Files | /P4T1b_Baxley.py | 813 | 3.546875 | 4 | import turtle
window = turtle.Screen()
window.bgcolor("black")
letterN = turtle.Turtle() #Letter N's properties
letterN.pensize(4)
letterN.color("red")
letterN.left(90) #Letter N's Movement
letterN.forward(50)
letterN.right(154)
letterN.forward(56)
letterN.left(154)
letterN.forward(50)
letterN.ht()
letterB = turtle.Turtle() #Letter B's properties
letterB.pensize(4)
letterB.color("red")
letterB.penup() #Letter B's Movement
letterB.forward(40)
letterB.pendown()
letterB.left(90)
letterB.forward(50)
letterB.right(90)
letterB.speed(0)
for i in range(50):
letterB.forward(.8)
letterB.right(3.6)
letterB.right(180)
letterB.forward(5)
for i in range(50):
letterB.forward(.8)
letterB.right(3.6)
letterB.forward(5)
letterB.ht()
|
b6258eec43be05516943ba983890e315cce167ae | NicholasBaxley/My-Student-Files | /P3HW2_MealTipTax_NicholasBaxley.py | 886 | 4.25 | 4 | # CTI-110
# P3HW2 - MealTipTax
# Nicholas Baxley
# 3/2/19
#Input Meal Charge.
#Input Tip, if tip is not 15%,18%,20%, Display error.
#Calculate tip and 7% sales tax.
#Display tip,tax, and total.
#Ask for Meal Cost
mealcost = int(input("How much did the meal cost? "))
#Ask for Tip
tip = int(input('How much would you like to tip, 15%, 18%, or 20%? '))
#Determines the cost of the meal
if tip == 15 or tip == 18 or tip == 20:
tipcost = tip * .1
taxcost = mealcost * .07
totalcost = mealcost + tipcost + taxcost
print('The tip cost is', format(tipcost, '4.2f'), '$')
print('The tax cost is', format(taxcost, '4.2f'), '$')
print('The total cost is ',format(totalcost, '4.2f'), '$')
#If the amount isnt 15,18,20 it sends back 'Error'
else:
print('Error')
|
92460ff7427ae5b5e2ff39fbefd9e60c282b4614 | HmAbc/deeplearning | /chapter3/step_function.py | 606 | 3.859375 | 4 | #!/user/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
# 阶跃函数简单实现,但是只支持实数
# def step_function(x):
# if x > 0:
# return 1
# else:
# return 0
# 重新编写函数,使之支持numpy数组
def step_function(x):
y = x > 0
return y.astype(np.int)
# 画出阶跃函数图像
# x = np.arange(-5, 5, 0.1)
# y = step_function(x)
# plt.plot(x, y)
# plt.ylim(-0.1, 1.1)
# plt.show()
# sigmoid 函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# ReLU 函数
def ReLU(x):
return np.maximum(0, x) |
a6d4bf1e71c3cfb431e3a7519185a474837cd5ae | bcbabrich/CS682FinalProject | /graphing_utilities.py | 462 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Note that this only graphs the first two dimensions of points
def print_graph_of(points, width, height, title) :
#plt.plot(samples[0], samples[1:])
print('points',points)
# only use the first two elements of each tuple in points
samples = [(p[0],p[1]) for p in points]
plt.scatter(*zip(*samples))
plt.title(title)
plt.xlim(0,width)
plt.ylim(0,height)
plt.show(title)
|
7853a9ecea62dc22a5e80b7dbbda7fbf8b9c185f | eburnsee/python_2_projects | /icon_manipulation/icon_manipulation.py | 1,999 | 4.28125 | 4 | def create_icon():
# loop through to make ten element rows in a list
for row in row_name_list:
# loop until we have ten rows of length 10 composed of only 1s and 0s
while True:
# gather input
row_input = input("Please enter ten characters (zeros and ones only, please!) for row " + row + ": ")
# check if input meets requirements
if (len(row_input) == 10) and all(((digit == "0") or (digit == "1") for digit in list(row_input))):
# add input to list
final_row_list.append(row_input)
# break out of while loop
break
else:
print("You failed to enter ONLY ten ones and zeros. Please try again.")
final_row_list.clear()
continue
def display_icon():
# print the icon
for row in final_row_list:
print(row)
def scale_icon():
# see if the user would like to scale the icon
scaled_rows = input("Would you like to scale your icon? (yes/no) ")
if scaled_rows.lower() == "yes":
scaling_int=int(input("Choose an integer by which to scale? "))
for row in final_row_list:
scaled_list = []
combined_list = []
row_list=list(row)
# print(row_list)
for char in row_list:
num_row = char[:]*scaling_int
scaled_list.append(num_row)
print(*scaled_list, sep="")
print(*scaled_list, sep="")
print(*scaled_list, sep="")
print(*scaled_list, sep="")
print(*scaled_list, sep="")
elif scaled_rows.lower() == "no":
print("Keep it simple, then.")
def invert_icon():
invert_rows = input("Would you like to invert the icon? (y/n) ")
if invert_rows.lower() == "yes":
for row in final_row_list:
print(row[::-1])
elif invert_rows.lower() == "no":
print("Keep it simple, then.")
else:
invert_icon()
print("Hello and welcome. You may use this program to display your icon.\nYou will be prompted to enter ten lines of TEN ones and zeros.")
row_name_list = ["one", "two" , "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
final_row_list = []
create_icon()
display_icon()
scale_icon()
invert_icon()
|
054944acb3b88176810301cb23a89b914daaeff3 | thispassing/poker | /ad.py | 525 | 4.09375 | 4 | # importing datetime and defining current date
from datetime import datetime
today = datetime.now().strftime("%Y-%b-%d")
# making definition for new balance
def calculate(totalBalance):
chop = 600000
tax = 218543
newBalance = totalBalance - chop - tax
newBalance = "{:,}".format(newBalance)
return (newBalance)
# receiving user input for current balance and giving new balance as output
balance = int(input("Type in your current balance: "))
print("New balance is: ", calculate(balance), "on", today) |
b13693190db7f419aade15f06453cc34969dd0ff | user0198/TicTacToe | /main.py | 3,521 | 3.84375 | 4 | board = [' ' for x in range(10)]
def insertLetter(letter, pos):
board[pos] = letter
def paintBoard(board):
print(" 1 | 2 | 3\n 4 | 5 | 6\n 7 | 8 | 9\n")
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print('-' * 11)
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print('-' * 11)
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
def isSpaceFree(pos):
return board[pos] == ' '
def isWinner(board, le):
return (
(board[1] == le and board[2] == le and board[3] == le) or # horz up
(board[4] == le and board[5] == le and board[6] == le) or # horz mid
(board[7] == le and board[8] == le and board[9] == le) or # horz bott
(board[1] == le and board[4] == le and board[7] == le) or # vert left
(board[2] == le and board[5] == le and board[8] == le) or # vert mid
(board[3] == le and board[6] == le and board[9] == le) or # vert right
(board[1] == le and board[5] == le and board[9] == le) or # main diag
(board[3] == le and board[5] == le and board[7] == le) # reverse diag
)
def isFreeBoard(board):
return board.count(' ') > 1
def playerMove(letter):
run = True
while run:
move = input(
'Type your move within a range of (1-9): ')
try:
move = int(move)
if move in range(1, 10):
if isSpaceFree(move):
run = False
insertLetter(letter, move)
else:
print('Cell is occupied!')
else:
print('Your move has to belong the range!')
except:
if move == 'end':
print('Coward!')
exit()
else:
print('Move should be a number!')
def aiMove(letter):
possibleMoves = [x for x, letter in enumerate(
board) if letter == ' ' and x != 0]
move = 0
for let in ['O', 'X']:
for i in possibleMoves:
boardCopy = board[:]
boardCopy[i] = let
if isWinner(boardCopy, let):
move = i
return move
if 5 in possibleMoves:
move = 5
return move
cornersOpen = [x for x in possibleMoves if x in [1, 3, 7, 9]]
if len(cornersOpen) > 0:
move = selectRandom(cornersOpen)
return move
edgesOpen = [x for x in possibleMoves if x in [2, 4, 6, 8]]
if len(edgesOpen) > 0:
move = selectRandom(edgesOpen)
return move
return move
def selectRandom(li):
import random
ln = len(li)
r = random.randrange(0, ln)
return li[r]
def clear():
import os
os.system('cls')
return print('Tic Tac Toe Game in progress...')
def main():
print('Welcome to TicTacToe game!\n(Type "end" to exit)')
print(" 1 | 2 | 3\n 4 | 5 | 6\n 7 | 8 | 9\n")
while isFreeBoard(board):
if not(isWinner(board, 'O')):
playerMove('X')
# paintBoard(board)
else:
print("\nO's won the game! GG!")
break
if not(isWinner(board, 'X')):
move = aiMove('O')
if move > 0:
insertLetter('O', move)
clear()
print('AI made move in possition #', move)
paintBoard(board)
else:
print('\nTie Game!')
else:
print("\nYou won the game! Well played!")
break
main()
|
7051f4cb5c83925557a76d709dff901e4491764d | skyexx/tutorials | /tensorflowTUT/tf5_example2/full_code.py | 1,665 | 3.5625 | 4 | # View more python tutorial on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
import tensorflow as tf
import numpy as np
# create data 这是一个基准函数
x_data = np.random.rand(100).astype(np.float32) #大部分的数据都是float32格式
y_data = x_data*0.1 + 0.3
### create tensorflow structure start ### 下面是定义一个预测的函数,通过ML不断接近基准函数
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) #定义数的range是-1~1
biases = tf.Variable(tf.zeros([1])) #biases的初始值定义为0
y = Weights*x_data + biases
loss = tf.reduce_mean(tf.square(y-y_data)) #计算预测的y与基准的y的差值
optimizer = tf.train.GradientDescentOptimizer(0.5) #用optimizer(优化器)减少误差;GradientDescentOptimizer()基础的optimizer。括号里是学习效率,一般小于1
train = optimizer.minimize(loss) #
### create tensorflow structure end ###
sess = tf.Session()
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init) #激活init ***非常重要
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(Weights), sess.run(biases))
|
25c661b755b33c05f95398c15b258d186db9f3fe | PatchesPrime/dailyprogrammer | /344.py | 737 | 3.515625 | 4 | def b_n(integer):
data = [x for x in bin(int(integer))[2:].split('1') if x != '']
# Even though b_0 should be 0...The wiki says it's always 1..so..
if integer == 0:
return 1
for x in data:
if len(x) % 2 != 0:
return 0
return 1
# All should be true.
print('Test 1: ', b_n(19611206) == 0)
print('Test 2: ', b_n(4) == 1)
print('Test 3: ', b_n(20) == 0)
print('Test 4: ', b_n(5) == 0)
# Challenge says 'if given 20' the last digit should be 0.
# range() in python goes UP to, but does not include, the number.
# With that said, fixed by going to 21.
t5 = '1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0'
print('Test 5: ', t5 == ', '.join([str(b_n(x)) for x in range(21)]))
|
e5523dc99c2287fb7b3343dc8da70cb5ce99b9e5 | anandabhaumik/PythoncodingPractice | /NumericProblems/FibonacciSeries.py | 1,063 | 4.25 | 4 | """
* @author Ananda
This is one of the very common program in all languages.
Fibonacci numbers are used to create technical indicators using a mathematical sequence
developed by the Italian mathematician, commonly referred to as "Fibonacci,"
For example, the early part of the sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,144, 233, 377, and so on
This program will calculate and print first "N" Fibonacci number where "N" will be input by user
"""
def calculateFibonacci(num):
fibo1 = 0
fibonacci = 0
fibo2 = 1
print("Fibonacci series upto ", num, " is as follows:")
if num == 1:
print(0)
elif num == 2:
print(1)
else:
print(fibo1, "\t", fibo1, end="\t")
for i in range(3, num + 1):
#Fibonacci number is sum of previous two Fibonacci number
fibonacci = fibo1 + fibo2
fibo1 = fibo2
fibo2 = fibonacci
print(fibonacci, end="\t")
num = int(input("Enter number upto which Fibonacci series to print: "))
calculateFibonacci(num)
|
475406a77d591cd63b13d2c1c1a9eb16eb2beefb | dmvdatascience/Python_Advanced | /scripts/run_EDA.py | 1,066 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 10:09:36 2019
@author: GrantDW
"""
def run_EDA(dataset):
'''
run_EDA takes a PANDAS dataframe and performs exploratory data analysis on it,
in order to determine strengths, weaknesses, and simple relationships between
the various columns.
'''
import pandas as pd
df1 = pd.DataFrame({
'Columns': dataset.columns.tolist(),
'DataTypes': dataset.dtypes.tolist(),
'Missing_count': dataset.apply(lambda x: (len(dataset)-x.count()), axis = 0),
'Missing_percent': dataset.apply(lambda x: round((len(dataset)-x.count())/len(dataset),2), axis = 0),
'Unique_count': dataset.apply(lambda x: x.nunique(), axis = 0),
'Unique_percent': dataset.apply(lambda x: round(x.nunique()/len(dataset),2), axis = 0),
})
df2 = dataset.describe().set_index(pd.Series(['Count', 'Mean', 'StdDev', 'Min', 'Quart25', 'Med', 'Quart75', 'Max'])).transpose()
df3 = df1.join(df2, how = 'left')
return(df3) |
eac4c77c3d615b332842d428e2791ed4dffef607 | liu666197/data1 | /8.14/12 sorted和filter和匿名函数的练习.py | 682 | 3.71875 | 4 | a = [
{'name': 'aa','age': 80},
{'name': 'zs1','age': 30},
{'name': 'aasd32','age': 50},
{'name': 'zs12','age': 10},
{'name': 'zsaqew','age': 20},
{'name': 'zs213','age': 100},
{'name': 'zswer','age': 3}
]
# 1.使用def的函数的方式,取出大于20的数据,并且从小到大排序
def f(n):
return n['age'] > 20
def f1(n):
return n['age']
a = list(filter(f,a))
# a = list(filter(lambda n:n['age'] > 20,a))
# a = sorted(a,key=lambda n:n['age'])
# print(a)
# 2.使用匿名函数的方式,取出名字带有字母a的数据,并且从小到大排序
a = list(filter(lambda n:'a' in n['name'],a))
a = sorted(a,key=lambda n:n['age'])
print(a) |
f07558a321caa87cf7795ec4e6f52f4222cbf256 | liu666197/data1 | /8.7/11 字符串的方法.py | 1,960 | 4.03125 | 4 | a = 'hello world hello aaa'
# a += '1'
# print(a)
# 查
# 查找字符串出现的次数
# result = a.count(' ')
# 查找字符串的下标: 默认查找到第一个的下标 (查找不到报错)
# result = a.index('worlds')
# 从右往左查
# result = a.rindex('hello')
# 查找不到为-1,不会报错
# result = a.find('hello')
# 从右往左查
# result = a.rfind('hellso')
# print(result)
# 内容替换(默认全部替换)
# b = a.replace('hello','你好')
# 替换掉一下 (替换几个)
# a = a.replace('hello','你好',1)
# print(a)
a = 'hello World hello aaa'
# 字母大小写
# 大写
# b = a.upper()
# 小写
# b = a.lower()
# 每个首字母大写
# b = a.title()
# 第一个单词首字母大写
# b = a.capitalize()
# 字母大小写取反
# b = a.swapcase()
# print(b)
# 去除首尾空格
# a = ' hello World hello aaa '
# a = a.strip()
# print(a)
# 字符串的对齐
# a = 'hello'
# # 字符串在11个字符的宽度里面居中对齐
# b = a.center(11)
# # 字符串在11个字符的宽度里面左对齐
# b = a.ljust(11)
# # 字符串在11个字符的宽度里面右对齐
# b = a.rjust(11)
#
# print(111,b,222)
# 字符串和列表的转换
# a = 'hello+world hello aaa'
# # 字符串转化为列表
# # 默认按照空格分割
# # b = a.split()
# b = a.split('+')
# print(b)
# 列表-->字符串
# a = ['hello','world','你好','世界']
# # 按照一个字符将列表转化为字符串
# b = '?'.join(a)
# print(b)
# a = 'hello world'
# a = '123213.1'
# # is开头的表示判断
# # 是否大写
# b = a.isupper()
# # 是否小写
# b = a.islower()
# # 是否为数字(整数)
# b = a.isdecimal()
# print(b)
# 字符和ASCII的转换
# 二进制数值: 01010110101
# 字母: ABCDE
# ASCII值: 字母的数字表示方式
# ord() : 将字母转化为ASCII值
# chr() : 将ASCII转化为字母
# 小写字母的ASCII值与大写的ASCII差32
print(ord('A'))# 65
print(ord('a'))# 97
print(chr(65))
print(chr(97)) |
1222b9eb56a8c6b728eb9a1f4aecb01a3671873f | liu666197/data1 | /8.24/05 操作数据库(插入).py | 455 | 3.578125 | 4 | import pymysql
# 1.连接数据库
# db: database
db = pymysql.connect('localhost','root','','python')
# 生成数据库的游标对象: 操作数据库
cursor = db.cursor()
# sql(最好是双引号,防止符号冲突)
sql = "INSERT INTO people (name,sex,age,height) VALUES ('小红','女',20,170);"
# 执行sql
cursor.execute(sql)
# 如果不想再对数据库进行操作,提交操作(后面不再进行操作)
db.commit()
# 关闭数据库
db.close() |
f9530bf73c1668d0959482929534666e2f4c37af | liu666197/data1 | /8.5/03 if..elif.py | 797 | 3.859375 | 4 | # 7.成绩等级:
# 90分以上: 等级为A
#
# 80-90: 等级为B
#
# 60-80: 等级C
#
# 0-60: 等级为D
score = int(input('输入成绩: '))
if score >= 90:
print('A')
elif score >= 80: # score < 90
print('B')
elif score >= 60: # score < 80
print('C')
else: # 前面条件都不成立的时候执行的代码
print('D')
holiday_name = input('输入名称: ')
if holiday_name == '情人节':
print('买玫瑰/看电影')
elif holiday_name == '平安夜':
print('买苹果/吃大餐')
elif holiday_name == '生日':
print('买蛋糕')
else:
print('每天都是节日')
# if score >= 90:
# print('A')
# if score >= 80 and score < 90:
# print('B')
# if score >= 60 and score < 80:
# print('C')
# if score >= 0 and score < 60:
# print('D') |
8d151d4c512430e54049ad733e8242b9357cac18 | liu666197/data1 | /8.6/02 思考.py | 3,616 | 3.890625 | 4 | # 1.输出9行内容,第1行输出1,第2行输出12,第3行输出123,以此类推,第9行输出123456789
#
# 1
# 12
# 123
# 1234
# 12345
# 123456
# 1234567
# 12345678
# 123456789
# 输出123
# print(1,end='')
# print(2,end='')
# print(3,end='')
# num = 1
# while num <= 3:
# print(num,end='')
# num += 1
# # 单独的换行
# print()
#
# # 输出123456
# num = 1
# while num <= 6:
# print(num,end='')
# num += 1
# print()
# # 输出123456789
# num = 1
# while num <= 9:
# print(num,end='')
# num += 1
# print()
#
# count = 1
# while count <= 9:
# num = 1
# while num <= count:
# print(num, end='')
# num += 1
# print()
# count += 1
# 2.打印菱形
# * 第一行: ' ' * 3,'*' * 1
# *** 第二行: ' ' * 2,'*' * 3
# ***** 第三行: ' ' * 1,'*' * 5
# ******* 第四行: ' ' * 0,'*' * 7
# ***** * 1, 5
# *** 2, 3
# * 3, 1
# 空格个数
# spaceCount = 3
# # *个数
# count = 1
# while spaceCount >= 0:
# print(spaceCount * ' ',end='')
# print(count * '*')
# spaceCount -= 1
# count += 2
# spaceCount = 1
# count = 5
# while spaceCount <= 3:
# print(spaceCount * ' ',end='')
# print(count * '*')
# spaceCount += 1
# count -= 2
# 3.打印九九乘法表
# 1 * 1 = 1
# 1 * 2 = 2 2 * 2 = 4
# 1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
# 1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
# 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
# 1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
# 1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
# 1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
# 1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
# 1 * 2 = 2 2 * 2 = 4
# 第二行
# row = 2
# # print('%s * %s = %s'%(1,row,1 * row),end='\t')
# # print('%s * %s = %s'%(2,row,2 * row),end='\t')
# count = 1
# while count <= row:
# print('%s * %s = %s' % (count, row, count * row), end='\t')
# count += 1
# print()
#
# # 第四行
# row = 3
# count = 1
# while count <= row:
# print('%s * %s = %s' % (count, row, count * row), end='\t')
# count += 1
# print()
# 行数
# row = 1
# while row <= 9:
# count = 1
# while count <= row:
# print('%s * %s = %s' % (count, row, count * row), end='\t')
# count += 1
# print()
# row += 1
# 4.求出1-100所有的质数(质数: 只能被1和它本身整除的数)
# 9: 2,3,4,5,6,7,8
#
# 6: 2,3,4,5
# # 判断9是不是质数
# num = 13
# count = 2
# # 该循环如果能正常结束,就代表该数字是一个质数
# while count < num:
# # 能整除,就代表不是质数,如果都不能整除,就代表是质数
# if num % count == 0:
# print('%s不是质数'%(num))
# break
# count += 1
# else:
# # 循环正常结束的时候,会执行该else里面的代码
# print('%s是质数'%(num))
# 该循环从2-100
num = 2
while num <= 100:
count = 2
# 该循环如果能正常结束,就代表该数字是一个质数
while count < num:
# 能整除,就代表不是质数,如果都不能整除,就代表是质数
if num % count == 0:
# print('%s不是质数' % (num))
break
count += 1
else:
# 循环正常结束的时候,会执行该else里面的代码
# print('%s是质数' % (num))
print(num,end='\t')
num += 1
|
4250526ddb411f7edb10ec180f2a57ccb11a20e1 | liu666197/data1 | /8.10/04 字母排序.py | 960 | 3.703125 | 4 | # - 去除a字符串内的数字后,请将该字符串里的单词重新排序(a-z),并且重新输出一个排序后的字符串。(保留大小写,a与A的顺序关系为:A在a前面。例:AaBb)(难)
a = 'aAsmr3idd4bgsBB7Dlsf9eAF'
s = ''
for i in a:
if i.isalpha():
s += i
result = ''
# chr(): 将数字转化为字母
# 输出所有的大写字母
for i in range(65,91):
# 所有的大小写字母
# chr(i): 大写字母
# print(chr(i),chr(i + 32))
upper = chr(i) * s.count(chr(i))
lower = chr(i + 32) * s.count(chr(i + 32))
result += upper + lower
print(result)
# # 把a的排序写出来
# # A
# upper = 'A' * a.count('A')
# # a
# lower = 'a' * a.count('a')
# print(upper + lower)
# # 把b的排序写出来
# upper = 'B' * a.count('B')
# lower = 'b' * a.count('b')
# print(upper + lower)
#
# # 把c的排序写出来
# upper = 'C' * a.count('C')
# lower = 'c' * a.count('c')
# print('C:',upper + lower) |
950782aac6208f196cffe275215307c79d2a2121 | liu666197/data1 | /8.14/02 对象与global.py | 371 | 3.75 | 4 | # 只要将对象赋值了,那么就会开辟新的空间来存储对象
# a = []
# # 是否属于改变了a变量的值??? 都不是改变了a的值
# a.append(1)
# a[0] = 2
# print(a)
# b = []
# print(id(a),id(b))
# a存储的是列表的内存地址
a = [10,20,30]
b = 20
def sayHello():
global b
b = 30
a[0] = 100
print(b)
sayHello()
print(b)
print(a) |
30631e0c883005e305163f0292ac0b9b916aa77b | davejlin/py-checkio | /roman-numerals.py | 2,444 | 4.125 | 4 | '''
Roman numerals come from the ancient Roman numbering system.
They are based on specific letters of the alphabet which are combined to signify
the sum (or, in some cases, the difference) of their values.
The first ten Roman numerals are:
I, II, III, IV, V, VI, VII, VIII, IX, and X.
The Roman numeral system is decimal based but not directly positional and
does not include a zero. Roman numerals are based on combinations of these seven symbols:
Symbol Value
I 1 (unus)
V 5 (quinque)
X 10 (decem)
L 50 (quinquaginta)
C 100 (centum)
D 500 (quingenti)
M 1,000 (mille)
More additional information about roman numerals can be found on the Wikipedia article.
For this task, you should return a roman numeral using the specified integer value
ranging from 1 to 3999.
Input: A number as an integer.
Output: The Roman numeral as a string.
How it is used: This is an educational task that allows you to explore different
numbering systems. Since roman numerals are often used in the typography,
it can alternatively be used for text generation. The year of construction on
building faces and cornerstones is most often written by Roman numerals.
These numerals have many other uses in the modern world and you read about it here...
Or maybe you will have a customer from Ancient Rome ;-)
Precondition: 0 < number < 4000
'''
def compose(value, sym_1, sym_5, sym_10):
s = ""
if value == 9:
s += sym_1 + sym_10
elif value > 4:
s += sym_5
for _ in range(value-5):
s += sym_1
elif value < 4:
for _ in range(value):
s += sym_1
else:
s += sym_1 + sym_5
return s
def checkio_my_ans(data):
thousands, remainder = divmod(data, 1000)
hundreds, remainder = divmod(remainder, 100)
tens, ones = divmod(remainder, 10)
s = compose(thousands, "M", "", "")
s += compose(hundreds, "C", "D", "M")
s += compose(tens, "X", "L", "C")
s += compose(ones, "I", "V", "X")
return s
def checkio_online_ans(n):
result = ''
for arabic, roman in zip((1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1),
'M CM D CD C XC L XL X IX V IV I'.split()):
result += n // arabic * roman
n %= arabic
return result
numbers = [1, 4, 6, 14, 49, 76, 499, 528, 999, 1001, 1949, 2492, 3888]
for number in numbers:
print("{} {}".format(str(number), checkio_my_ans(number)))
for number in numbers:
print("{} {}".format(str(number), checkio_online_ans(number)))
|
6db7ad876f33ee75bdd744eb81ea35980578702d | pdawson1983/CodingExcercises | /Substring.py | 1,316 | 4.15625 | 4 | # http://www.careercup.com/question?id=12435684
# Generate all the possible substrings of a given string. Write code.
# i/p: abc
# o/p: { a,b,c,ab,ac,bc,abc}
"""begin
NOTES/DISCUSSION
All substrings is not the same as all combinations
Four distinct patterns comprise all substrings
1. The original string
2. Each character in the original string
3. Two character strings where the first char is the original first char,
and the second char is each subsequent char in the original string.
4. Strings where the original string is reduced, starting with the first char,
until only two characters remain.
end"""
def findSubstrings(string):
subArray = []
length = len(string)
for char in string:
subArray.append(char)
for place in range(0,length):
for iteration in range(1,length):
if place < iteration:
combo = ''
combo += string[place]
if combo != string[iteration]:
combo += string[iteration]
if combo not in subArray:
subArray.append(combo)
subArray.append(string)
return subArray
print("expected ['a','b','c','ab','ac','bc','abc'] got:", findSubstrings("abc"))
assert findSubstrings("abc") == ['a','b','c','ab','ac','bc','abc'] , "three char string produces correct substrings" |
02f6c73590057ce02829cc26699f7b178febb272 | ambingham/CharacterCreator | /race.py | 2,029 | 3.75 | 4 | class Race(object):
"Base class for all races in the game."
def __init__(self, name):
self.name = name
def apply_bonus(self, abilities):
"""Apply racial bonuses to abilities.
By default we do nothing. Subclasses should apply the appropriate bonuses.
"""
return abilities
class Human(Race):
def __init__(self):
super(Human, self).__init__('Human')
def apply_bonus(self, abilities):
# +1 to all abilities
abilities.strength += 1
abilities.dexterity += 1
abilities.constitution += 1
abilities.intelligence += 1
abilities.wisdom += 1
abilities.charisma += 1
return abilities
class Dwarf(Race):
def __init__(self):
super(Dwarf, self).__init__('Dwarf')
def apply_bonus(self, abilities):
# +2 Strength, +2 Constitution, +1 Wisdom
abilities.strength += 2
abilities.constitution += 2
abilities.wisdom += 1
return abilities
class Elf(Race):
def __init__(self):
super(Elf, self).__init__('Elf')
def apply_bonus(self, abilities):
# +2 Dexterity, +1 Intelligence, +1 Wisdom
abilities.dexterity += 2
abilities.intelligence += 1
abilities.wisdom += 1
return abilities
class Dragonborn(Race):
def __init__(self):
super(Dragonborn, self).__init__('Dragonborn')
def apply_bonus(self, abilities):
# +2 Strength, +1 Charisma
abilities.strength += 2
abilities.charisma += 1
return abilities
class Half_Orc(Race):
def __init__(self):
super(Half_Orc, self).__init__('Half-Orc')
def apply_bonus(self, abilities):
# +2 Strength, +1 Constitution
abilities.strength += 2
abilities.constitution += 1
return abilities
# TODO: create classes for other races
ALL_RACES = (Human(), Dwarf(), Elf(), Dragonborn(), Half_Orc())
|
f5fe8e967cb841bb73315e829c06e63b945c3db4 | kktkyungtae/TIL | /Algorithm/2019.01/2019.01.24/Practice/09_if흐름제어3.py | 500 | 3.53125 | 4 |
# 다음의 결과와 같이 입력된 영어 알파벳 문자에 대해 대소문자를 구분하는 코드를 작성하십시오.
AA = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
aa = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
xx = str(input())
if xx in aa:
print(f'{xx}는 소문자 입니다.')
elif xx in AA:
print(f'{xx}는 대문자 입니다.')
|
7c1fcb958198e808d5536af91dc6a96a2cceceaa | kktkyungtae/TIL | /Algorithm/2019.02/2019.02.20/수식문자열.py | 429 | 3.515625 | 4 | str = "2 + 3 * 4 / 5"
stack = [0] * 10 # make stack
top = -1 # what does mean?
idx = 0
post_exp = [0] * 10 # ?
for i in range(len(str)):
if '*' <= str[i] <= '/': # <= ?
top += 1;
stack[top] = str[i]
elif '0' <= str[i] <= '9': # <= ?
post_exp[idx] = str[i]
idx += 1
while top != -1 :
post_exp[idx] = stack[top] # <= ?
idx += 1
top -= 1
print(' '.join(post_exp[:idx])) # <= ? |
8a0b153b49de241983f9c99b3202f2eef4f0f460 | kktkyungtae/TIL | /Algorithm/2019.01/2019.01.24/Practice/15_흐름과제어3.py | 249 | 3.65625 | 4 | #1부터 100사이의 숫자 중 3의 배수의 총합을 for 문을 이용해 출력하십시오.
ssum = []
for i in range(100):
if i % 3 ==0:
ssum.append(i)
print(f'1부터 100사이의 숫자 중 3의 배수의 총합: {sum(ssum)}') |
aa43873c181385d0eee5e86cb0a18691e3b0bc90 | Vimala390/Vimala_py | /sam_file_exer_2.py | 185 | 3.5 | 4 | file = open('C:/Users/Vimala_Revanuru/Desktop/sam_demo_1.txt','r')
x = 'deno'
for line in file:
if x in line:
print('word found ..')
else:
print('Not Found ..')
|
0f24831b7a41e57fab0accc5a9c7c1fdd1ef9bb5 | Vimala390/Vimala_py | /sam_string_concatinate.py | 1,065 | 3.6875 | 4 | stg1 = 'good'
stg2 = 'morning'
stg4 = 'Hey';stg5 = 'Vimala'
stg3 = stg1+" " +stg2
print(stg3)
print('{} {}!! {} {}...'.format(stg4,stg5,stg1,stg2))
str6 = ' Vimala '
print(str6.lstrip())
print(str6.rstrip())
print(str6.strip())
# Reverse Each word in the string [Eg. Have a great day O/p - evaH a taerg yad]
str_1 = 'Vimala welcome' ##input('enter string ..') ##'Vimala welcome'
str_1 = str_1+" "
tmp = ''
rev = ''
for i in str_1:
if i!= " ":
tmp = i+tmp
else:
rev = rev+" "+tmp
tmp = ""
#continue
print(rev)
##Efficient way
import re
x = 'Have a great day'
x_1 = x.split() ###
x_2 = re.findall('[a-zA-Z]*\s+',x)
print(x.split())
print(x_2)
for i in x_1:
print(i[::-1],end =" ")
s = "HELLO there HOW are YOU"
#print(re.findall("(?<!^)\s+(?=[A-Z])(?!.\s)",s))
l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)
print(l)
stg = "asdf fjdk; afed, fjek,asdf, foo"
s1 = re.compile("(?<!^)\s+(?=[a-z])(?!.\s)").split(stg)
#s1_1 = re.findall('[a-z]*\s+',stg)
print(stg.split())
print(re.split(';,',stg))
|
5517280b78495d7c131208e78b3d2667165c8337 | Vimala390/Vimala_py | /sam_tuple_exe.py | 268 | 4.4375 | 4 | #Write a program to modify or replace an existing element of a tuple with a new element.
#Example:
#num= (10,20,30,40,50) and insert 90.
#Expected output: (10,20,90,40,50)
lst = [10,20,30,40,50]
lst[2] = 90
print(lst)
lst1 = tuple(lst)
print(lst1)
print(type(lst1))
|
d08e9df1d2a2ad3f72ab08121d76a736f55ef50a | Vimala390/Vimala_py | /sam_pandas_diff_ways_dataframe.py | 1,269 | 3.734375 | 4 | #Different ways of creating Data Frame
#1. Using CSV
import pandas as pd
df = pd.read_csv('C:\\Users\\Vimala_Revanuru\\Desktop\\sample_data.csv')
print(df)
#2.using Excel
#the latest version of xlrd (2.0.1) only support .xls files.
#so this error can be solved by installing an older version of xlrd.
#use commands below in cmd:
###############################
#pip uninstall xlrd
#pip install xlrd==1.2.0 -- will support .xlsx format
################################
df1 = pd.read_excel("C:\\Users\\Vimala_Revanuru\\Desktop\\py_pandas\\sample_book.xls","Sheet1")
print(df1)
#3.From python dictionary
x_d = {'day':['1/12/2020','13/12/2020','2/12/2020','10/12/2020'],'temperature':['20','30','40','50'],'windspeed':['23','3','12','13'],'event':['rain','sunny','snow','rain']
}
df2 = pd.DataFrame(x_d)
print(df2)
#4.From list of tuples
print('From list of tuples')
y_d = [('1/12/2020','20','rain'),('12/12/2020','21','sunny'),('13/12/2020','25','rain')]
df3 = pd.DataFrame(y_d,columns=["day","temperature","event"])
print(df3)
#5.From list of dictionaries
z_d = [{'day':'1/12/2020','temperature':'20','event':'rain'},
{'day':'12/12/2020','temperature':'21','event':'sunny'},
{'day':'13/12/2020','temperature':'25','event':'rain'}]
df4 = pd.DataFrame(z_d)
print(df4) |
5dac67653c8a391c92e89fdcbc774b92fb363ab7 | Vimala390/Vimala_py | /sam_files_exer_0211.py | 1,186 | 3.953125 | 4 | # Write a program to count number of lines, words and characters in a text file.
file = 'C:/Users/Vimala_Revanuru/Desktop/sam_demo_1.txt'
c_lines = 0
c_words = 0
c_chars = 0
for lines in open(file,'r'):
c_lines+=1
print(lines.split())
#print(len(lines))
for char in lines:
if char != ' ':
c_chars+=1
else:
pass
for words in lines.split():
c_words+=1
print('No.of Lines :' , c_lines)
print('No.of Characters:',c_chars)
print('No.of words:',c_words)
# Pickle
#Pickle -- convert structure format/readable format to Binary format
# Pickle.dump(<structure>,filename) -- to write into file
#Pickle.load(fileobject) -- to read the data from file
#Unpickle -- Convert Binary format to structure format/readable format
import pickle
def binary_write():
file = open('C:/Users/Vimala_Revanuru/Desktop/Binary_data.dat','wb')
list1 = ['vimala','Manoj','Veera','Tejansh']
pickle.dump(list1,file)
file.close()
def binary_load():
file = open('C:/Users/Vimala_Revanuru/Desktop/Binary_data.dat','rb')
lst = pickle.load(file)
file.close()
print(lst)
binary_write()
binary_load()
|
f8a214a1ca38f93aa8957b070298f74a4796ae30 | rajeevraizada/rajeevraizada.github.io | /Python/interactive_one_sample_t_test.py | 13,851 | 4 | 4 | ### Interactively plot points
### to show the one-sample t-test of the y-values, against zero.
### By Rajeev Raizada, Jan.2011.
### Requires Python, with the Matplotlib, NumPy and SciPy modules.
### You can download Python and those modules for free from
### http://www.python.org/download
### http://numpy.org
### http://scipy.org
### http://matplotlib.sourceforge.net
### A good way to get all these modules at once is to use
### the Anaconda python distribution, from
### https://www.anaconda.com/distribution/
###
### Please feel more than free to use this code for teaching.
### If you use it, I'd love to hear from you!
### If you have any questions, comments or feedback,
### please send them to me: rajeev dot raizada at gmail dot com
###
### Some tutorial exercises which might be useful to try:
### 1. Click to make 10 points with a mean y-value of around 5,
### and a standard deviation of around 10.
### (The points will need to be quite spread-out for this).
### The red bars show the 95% confidence interval.
### This means that if the data points were randomly sampled
### from a broader population, then we can be 95% sure
### that the actual mean of that broader population
### sits somewhere within that confidence-interval.
### Does this 95% confidence interval include the value y=0?
### What is the size of the p-value of the t-test?
### The meaning of this p-value is that it is the probability of observing
### that t-value, if the population that the points were sampled from
### actually had a mean equal to zero.
### 2. Now add another 10 points, keeping the mean the same at around 5,
### and the standard devation the same at around 10.
### What happens to the size of the 95% confidence interval?
### Does this confidence interval include y=0 now?
### What is the new p-value?
###########################################
# First, we import the modules that we need
import pylab as plt
import numpy as np
import scipy.stats # We need this one for the norm.pdf function
#####################################################
# Next, we define the functions that the program uses
### This function clears the figure and empties the points list
def clear_the_figure_and_empty_points_list():
global coords_array
global point_handles_array
# Reset our variables to be empty
coords_array = np.array([])
point_handles_array = np.array([])
handle_of_conf_int_plot = []
handle_of_mean_plot = []
### Clear the figure window
plt.clf() # clf means "clear the figure"
### In order to keep the boundaries of the figure fixed in place,
### we will draw a black box around the region that we want.
plt.plot(axis_x_range*np.array([-1, 1, 1, -1]),
np.array([axis_y_lower_lim,axis_y_lower_lim,axis_y_upper_lim,axis_y_upper_lim]),'k-')
### We want a long title, so we put a \n in the middle, to start a new line of title-text
multiline_title_string = 'Click to add points, on old points to delete,' \
' outside axes to reset.\n' \
'Dot shows the mean. Bars show 95% confidence interval for mean'
plt.title(multiline_title_string)
### Plot the zero line, against which the t-test is performed
plt.plot([-axis_x_range, axis_x_range],[0, 0],'k--')
plt.grid(True) # Add a grid on to the figure window
plt.axis([-axis_x_range, axis_x_range, axis_y_lower_lim, axis_y_upper_lim])
### Because we are only looking at the y-axis mean and std,
### we will only show tick-labels on the y-axis, with no ticks on the x-axis
plt.yticks( np.arange(axis_y_lower_lim,axis_y_upper_lim,5) )
plt.xticks([])
plt.draw() # Make sure that the newly cleaned figure is drawn
# This is the function which gets called when the mouse is clicked in the figure window
def do_this_when_the_mouse_is_clicked(this_event):
global coords_array
global point_handles_array
x = this_event.xdata
y = this_event.ydata
### If the click is outside the range, then clear figure and points list
if this_event.xdata is None: # This means we clicked outside the axis
clear_the_figure_and_empty_points_list()
else: # We clicked inside the axis
number_of_points = np.shape(coords_array)[0]
if number_of_points > 0:
point_to_be_deleted = check_if_click_is_on_an_existing_point(x,y)
if point_to_be_deleted != -1: # We delete a point
# We will delete that row from coords_array. The rows are axis 0
coords_array = np.delete(coords_array,point_to_be_deleted,0)
# We will also hide that point on the figure, by finding its handle
handle_of_point_to_be_deleted = point_handles_array[point_to_be_deleted]
plt.setp(handle_of_point_to_be_deleted,visible=False)
# Now that we have erased the point with that handle,
# we can delete that handle from the handles list
point_handles_array = np.delete(point_handles_array,point_to_be_deleted)
else: # We make a new point
coords_array = np.vstack((coords_array,[x,y]))
new_point_handle = plt.plot(x,y,'*',color='blue')
point_handles_array = np.append(point_handles_array,new_point_handle)
if number_of_points == 0:
coords_array = np.array([[x,y]])
new_point_handle = plt.plot(x,y,'*',color='blue')
point_handles_array = np.append(point_handles_array,new_point_handle)
### Now plot the statistics that this program is demonstrating
number_of_points = np.shape(coords_array)[0] # Recount how many points we have now
if number_of_points > 1:
plot_the_one_sample_t_test()
### Finally, check to see whether we have fewer than two points
### as a result of any possible point-deletions above.
### If we do, then delete the stats info from the plot,
### as it isn't meaningful for just one data point
number_of_points = np.shape(coords_array)[0]
if number_of_points < 2: # We only show mean and std if there are two or more points
plt.setp(handle_of_conf_int_plot,visible=False)
plt.setp(handle_of_mean_plot,visible=False)
plt.xlabel('')
plt.ylabel('')
# Set the axis back to its original value, in case Python has changed it during plotting
plt.axis([-axis_x_range, axis_x_range, axis_y_lower_lim, axis_y_upper_lim])
plt.draw() # Make sure that the new changes to the figure are drawn
# This is the function which calculates and plots the statistics
def plot_the_one_sample_t_test():
# First, delete any existing normal-curve and mean plots from the figure
global handle_of_conf_int_plot
global handle_of_mean_plot
plt.setp(handle_of_conf_int_plot,visible=False)
plt.setp(handle_of_mean_plot,visible=False)
#### Next, calculate and plot the stats
number_of_points = np.shape(coords_array)[0]
y_coords = coords_array[:,1] ### y-coords are the second column, which is 1 in Python
y_mean = np.average(y_coords)
y_std = np.std(y_coords)
y_ste = y_std / np.sqrt(number_of_points); # ste stands for Standard Error of the Mean
[t_value,p_value] = np.stats.ttest_1samp(y_coords,0)
#### Let's also calculate the 95% confidence interval.
#### This is the range such that, if we we draw a sample
#### from a population whose true population-mean is y_mean,
#### then that sample's mean will lie within the confidence-interval
#### 95% of the time.
#### First, we need the critical value of t (two-tailed).
#### Because we are using a two-tailed test, that means that
#### we want to cover the middle 95% of the range of t-value,
#### i.e. with 2.5% in each tail on either end.
#### So, we want a t-crit value such that there is a 97.5% chance
#### of getting a sample with a t-score of *less than* t_crit.
#### To get this t_crit value, we need an inverse-t function
#### and also the number of degrees-of-freedom (often called df),
#### which for a one-sample t-test is simply (number_of_points-1)
df = number_of_points - 1
#### In SciPy, the inverse stats functions are named
#### a bit differently from usual.
#### The inverse-t function is called t.ppf,
#### where ppf stands for "percent point function".
#### That's not the standard name.
#### Usually, this inverse t-function is referred to as
#### the inverse of the CDF (cumulative distribution function).
t_crit = np.stats.t.ppf(0.975,df) # 95% critical value of t, two-tailed
#### The 95% confidence interval is the range between
#### t_crit standard errors below the mean, and t_crit ste's above.
confidence_interval = y_mean + t_crit * y_ste * np.array([-1,1])
#### Now, plot the mean and confidence interval in red
handle_of_mean_plot = plt.plot(0,y_mean,'ro',markersize=10)
handle_of_conf_int_plot = plt.plot([0, 0],confidence_interval,'r-',linewidth=3)
#### In order to make the p-values format nicely
#### even when they have a bunch of zeros at the start, we do this:
p_value_string = "%1.2g" % p_value
plt.xlabel('Mean=' + str(round(y_mean,2)) + \
', STE=STD/sqrt(n)=' + str(round(y_ste,2)) + \
', t=Mean/STE=' + str(round(t_value,2)) + \
', p= ' + p_value_string, fontsize=11)
plt.ylabel('n = ' + str(number_of_points) + \
', STD = ' + str(round(y_std,2)), fontsize=12)
# Set the axis back to its original value, in case Python has changed it during plotting
plt.axis([-axis_x_range, axis_x_range, axis_y_lower_lim, axis_y_upper_lim])
# This is the function which deletes existing points if you click on them
def check_if_click_is_on_an_existing_point(mouse_x_coord,mouse_y_coord):
# First, figure out how many points we have.
# Each point is one row in the coords_array,
# so we count the number of rows, which is dimension-0 for Python
number_of_points = np.shape(coords_array)[0]
this_coord = np.array([[ mouse_x_coord, mouse_y_coord ]])
# The double square brackets above give the this_coord array
# an explicit structure of having rows and also columns
if number_of_points > 0:
# If there are some points, we want to calculate the distance
# of the new mouse-click location from every existing point.
# One way to do this is to make an array which is the same size
# as coords_array, and which contains the mouse x,y-coords on every row.
# Then we can subtract that xy_coord_matchng_matrix from coords_array
ones_vec = np.ones((number_of_points,1))
xy_coord_matching_matrix = np.dot(ones_vec,this_coord)
distances_from_existing_points = (coords_array - xy_coord_matching_matrix)
# Because the x and y axes have different scales,
# we need to rescale the distances so that itdoesn't matter whether
# you try to delete a dot by clicking near it in the x or y directions.
# When we extract the columns of distances_from_existing_points,
# scipy returns the values as row vectors for some reason.
# So, we transpose them back to column vectors and stack them horizontally
axis_range_scaled_distances = np.hstack( \
( distances_from_existing_points[:,0].reshape(-1,1)/(2*axis_x_range), \
distances_from_existing_points[:,1].reshape(-1,1)/(axis_y_upper_lim-axis_y_lower_lim) ) )
squared_distances_from_existing_points = axis_range_scaled_distances**2
sum_sq_dists = np.sum(squared_distances_from_existing_points,axis=1)
# The axis=1 means "sum over dimension 1", which is columns for Python
euclidean_dists = np.sqrt(sum_sq_dists)
distance_threshold = 0.01
within_threshold_points = np.nonzero(euclidean_dists < distance_threshold )
num_within_threshold_points = np.shape(within_threshold_points)[1]
if num_within_threshold_points > 0:
# We only want one matching point.
# It's possible that more than one might be within threshold.
# So, we take the unique smallest distance
point_to_be_deleted = np.argmin(euclidean_dists)
return point_to_be_deleted
else: # If there are zero points, then we are not deleting any
point_to_be_deleted = -1
return point_to_be_deleted
#######################################################################
# This is the main part of the program, which calls the above functions
#######################################################################
# First, initialise some of our variables to be empty
coords_array = np.array([])
point_handles_array = np.array([])
handle_of_conf_int_plot = []
handle_of_mean_plot = []
### Set up an initial space to click inside
axis_x_range = 30
axis_y_upper_lim = 20
axis_y_lower_lim = -10
### Make the figure window
plt.figure()
### Clear the figure window
plt.clf() # clf means "clear the figure"
### In order to keep the boundaries of the figure fixed in place,
### we will draw a black box around the region that we want.
plt.plot(axis_x_range*np.array([-1, 1, 1, -1]), \
np.array([axis_y_lower_lim,axis_y_lower_lim,axis_y_upper_lim,axis_y_upper_lim]),'k-')
### Tell Python to call a function every time
### when the mouse is pressed in this figure
plt.connect('button_press_event', do_this_when_the_mouse_is_clicked)
clear_the_figure_and_empty_points_list()
plt.show() # This shows the figure window onscreen
|
950474b740e8f54001b7b6aad2ed84d330a1ccc2 | BethGranados/Snake | /actor.py | 978 | 3.5 | 4 | import pygame
class actor:
size = (10, 10)
cord = (40, 40)
#Creates the actor and defined it's location at [XCord, YCord]. Adds a sprite to the actor.
def __init__(self, xCord, yCord):
self.cord = (xCord, yCord)
self.image = pygame.Surface(self.size).convert()
self.image.blit(pygame.image.load("sprite.bmp"), (0,0))
#Returns the sprite info for rendering
def display(self):
return self.image
#Returns the location of the sprite
def location(self):
return self.cord
#Relocates the actor to a defined location
def relocate(self, loc):
self.cord = loc
#Returns the size of the actor
def sizing(self):
return self.size
#Determines if the actor is colliding with otherActor
def collide(self, otherActor):
if ((self.cord[0] == otherActor.cord[0]) and (self.cord[1] == otherActor.cord[1])):
return True
else:
return False
|
ab9dab533973cfefe9d41cb53edfcf52c9e14d6a | Vetarium/ICT | /task1/3.py | 199 | 4.125 | 4 |
length = float(input("insert length"))
height = float(input("insert height"))
units = input("Insert units 'M' for meters and 'F' for feet")
print("area is ", height * length, units)
|
4aee5242a8c02f907643377d4f681aec4e4b5db9 | Vetarium/ICT | /task2/14.py | 238 | 3.625 | 4 | #largest cnt
import numpy as np
a = []
x = 1;
cnt = 0
while x!=0:
x = int(input())
a.append(x)
max = np.max(a)
print("biggest val is ",max)
for i in range (len(a)):
if max == a[i]:
cnt+=1
print("cnt is ", cnt)
|
8df20e0b38901d8ee203ed514b8473f994d22b69 | Vetarium/ICT | /task3/7.py | 291 | 3.640625 | 4 | import string
n = int(input())
s = input()
ans = list(set(s.lower()))
cnt = 0
arr1 = list(string.ascii_lowercase)
arr2 = list(string.ascii_uppercase)
for i in range(0, len(ans)):
if ans[i] in arr1 or ans[i] in arr2:
cnt += 1
if cnt == 26:
print("YES")
else:
print("NO") |
386217dd14ebfff63ef8aa7da1a94673b29602c7 | Vetarium/ICT | /task1/33.py | 240 | 3.890625 | 4 | loaves = int(input("Amount of loaves: "))
price = loaves*3.49
discount = price*0.6
total_price = price - discount
print("Regular price of the bread", round(price,2))
print("Value of discount:", discount)
print("Total price:", total_price) |
517c815b16824d9b4afcfc6ae21d9d151d2d1b17 | Vetarium/ICT | /task4/128.py | 281 | 4.09375 | 4 | def reverselookup(dict, val):
keys = []
for k in dict:
if dict[k] == val:
keys.append(k)
return keys
def main():
test = {"Aron":"true", "apple": "false"}
print(reverselookup(test, "false"))
print(reverselookup(test, "1.5"))
main()
|
912fd07e9a2103ebcdbc756c74d30044b949219c | Vetarium/ICT | /task2/1.py | 228 | 3.984375 | 4 | x1 = int(input("Insert the 1st row "))
y1 = int(input("Insert the 1st column "))
x2 = int(input("Insert the 2nd row "))
y2 = int(input("Insert the 2nd column " ))
if x1 == x2 or y1 == y2:
print("Yes")
else: print("NO") |
16bae5c5127f2b9f8121d1e5e042213ff9590619 | Vetarium/ICT | /task2/10.py | 100 | 3.859375 | 4 | #Qvadraty
a = int(input("Insert the number "))
i = 1;
while i**2 < a:
print(i**2)
i+=1
|
2b9abcbc4e7a19d9f1342b751df2e265e04d2c85 | byunghun-jake/udamy-python-100days | /day-27-Tkinter, args, kwargs and Creating GUI Programs/miles_to_kilometer_converter.py | 1,056 | 4 | 4 | import tkinter
# 텍스트 변환
def convert():
# 입력한 마일 텍스트 받아오기
try:
mile_num = float(miles_input.get())
km_num = mile_num * 1.609
except ValueError:
km_num = "숫자를 입력하세요."
# result 값으로 출력
km_result_label.config(text=km_num)
# window
window = tkinter.Tk()
window.title("Mile to KM Converter")
window.config(padx=10, pady=20)
# window.minsize(width=500, height=200)
# Entry
miles_input = tkinter.Entry(width=7)
miles_input.grid(row=0, column=1)
# Label
miles_label = tkinter.Label(text="Miles")
miles_label.grid(row=0, column=2)
km_label = tkinter.Label(text="Km")
km_label.grid(row=1, column=2)
km_result_label = tkinter.Label(text="")
km_result_label.grid(row=1, column=1)
is_equal_label = tkinter.Label(text="is equal to")
is_equal_label.grid(row=1, column=0)
# Button
calculate_button = tkinter.Button(text="Calculate", command=convert)
calculate_button.grid(row=2, column=1)
calculate_button.config()
window.mainloop() |
395ac484f9d152f4ae29642aa6d56d10009ddbd1 | byunghun-jake/udamy-python-100days | /day-24-Files, Directories and Paths/main.py | 296 | 3.53125 | 4 | # file = open("my_file.txt")
# print(file)
# contents = file.read()
# print(contents)
# file.close()
# with open("/new_file.txt", mode="w") as file:
# file.write("Hi Root Directory")
with open("../../../../new_file.txt") as file:
contents = file.read()
print(contents)
|
67a0abe7c6122f23aca8443c3462cf29ced761db | byunghun-jake/udamy-python-100days | /day-17-start/main.py | 545 | 3.6875 | 4 | class User:
# Constructor
def __init__(self, user_id, user_name, follower=0, following=0):
print("new user being created...")
self.id = user_id
self.username = user_name
self.followers = follower
self.following = following
def follow(self, user):
user.followers += 1
self.following += 1
user_1 = User("001", "김병훈")
user_2 = User("002", "남경빈")
user_1.follow(user_2)
print(user_1.following)
print(user_1.followers)
print(user_2.following)
print(user_2.followers)
|
60cebb65097a49a1c55af2ab49483e149d6cd4db | byunghun-jake/udamy-python-100days | /day-26-List Comprehension and the NATO Alphabet/Project/main.py | 469 | 4.28125 | 4 | import pandas
# TODO 1. Create a dictionary in this format:
# {"A": "Alfa", "B": "Bravo"}
data_frame = pandas.read_csv("./nato_phonetic_alphabet.csv")
# data_frame을 순환
data_dict = {row.letter:row.code for (index, row) in data_frame.iterrows()}
print(data_dict)
# TODO 2. Create a list of the phonetic code words from a word that the user inputs.
input_text = input("Enter a word: ").upper()
result = [data_dict[letter] for letter in input_text]
print(result) |
f53841acf1cb763d104ba43f0a961344d06d2710 | yucongo/data | /untokenize.py | 1,277 | 3.546875 | 4 | '''
https://stackoverflow.com/questions/21948019/python-untokenize-a-sentence
see also moses_detoken_memo.py
from nltk.tokenize.moses import MosesDetokenizer
text_ = ['Pete', 'ate', 'a', 'large',
'cake', '.', 'Sam', 'has', 'a', 'big', 'mouth', '.']
' '.join(MosesDetokenizer().detokenize(text_))
'''
import re
# from typing import List
def untokenize(words: list) -> str:
"""
Untokenizing a text undoes the tokenizing operation, restoring
punctuation and spaces to the places that people expect them to be.
Ideally, `untokenize(tokenize(text))` should be identical to `text`,
except for line breaks.
"""
text = ' '.join(words)
step1 = text.replace("`` ", '"').replace(" ''", '"').replace('. . .', '...') # NOQA
step2 = step1.replace(" ( ", " (").replace(" ) ", ") ")
step3 = re.sub(r' ([.,:;?!%]+)([ \'"`])', r"\1\2", step2)
step4 = re.sub(r' ([.,:;?!%]+)$', r"\1", step3)
step5 = step4.replace(" '", "'").replace(" n't", "n't").replace("can not", "cannot")
step6 = step5.replace(" ` ", " '")
return step6.strip()
if __name__ == '__main__':
TOKENIZED = ['I', "'ve", 'found', 'a', 'medicine', 'for', 'my', 'disease', '.'] # NOQA
assert untokenize(TOKENIZED) == "I've found a medicine for my disease."
|
319d0abd856cbcd9c403f08ec46545d389a59a4f | VennelaMittapalli/DSP-lab-programs | /linear_algebra.py | 809 | 4.03125 | 4 | #linear algebra applications
import numpy as np
print "..........OPERATIONS ON SINGLE ARRAY......."
a=input("Enter the matrix:")
b=np.array(a)
arr=[np.linalg.matrix_rank(a),np.linalg.matrix_power(a,3),np.trace(a),np.linalg.det(a),np.linalg.inv(a),np.linalg.eig(a),np.diag(a)]
r=["rank","power","trace","determinant","inverse","eigen values","diagonal matrix"]
l=len(arr)
c=0
while(c<l):
print arr[c],"-----",r[c]
c+=1
print ".............OPERATIONS ON TWO ARRAYS.........."
d=input("Enter the matrix:")
e=np.array(d)
arr=[np.add(a,b),np.subtract(a,b),np.dot(a,b),np.divide(a,b)]
r=["addtion","subtract","multiplication","dividee"]
l=len(arr)
c=0
while(c<l):
print arr[c],"-----",r[c]
c+=1
print ".........SOLTUIONS OF LINEAR EQUATIONS......."
e=input("enter the solution")
f=np.linalg.solve(a,b)
print f
|
0e6df6cd389e9e31b4b139b573263d6498d80acc | AJITHARUN/programs | /palindrome.py | 359 | 4.0625 | 4 |
def first (word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def pali(word):
if len(word)<=1:
print 'it is a palindrome'
elif first(word)==last(word):
return pali(middle(word))
print 'it is a palindrome'
else:
print 'it is not a palindrome'
pali('malayalam')
|
e7b4b5005b97803c1f42942fd1d1f87db068e935 | Mayank133/Python-projects | /hangman.py | 3,109 | 4.03125 | 4 | import random
import data
print("Welcome to the Hangman game")
name=input("What is your name?")
print("Hey {}! Welcome to the game, you will be given clues and you have to guess the word. You'll get only 3 chances to guess the word.".format(name.upper()))
response=input("Are you ready to play! Yes or No? ")
counter=0
flag=0
vowels=['a','e','i','o','u']
if response=="Yes" or "yes":
while response=="Yes" or response=="yes":
f=0
v=0
flag=0
counter=0
states=0
chem=0
print("Game Menu: \n1:Guess the fruit \n2:Guess the colour \n3:Guess the indian state \n4:Guess the element of periodic table")
choice=int(input("Enter your choice(1 or 2 or 3 or 4)? "))
if choice==1:
ans=random.choice(data.fruits)
elif choice==2:
ans=random.choice(data.colours)
elif choice==3:
ans=random.choice(list(data.indian_states.keys()))
states=1
elif choice==4:
ans=random.choice(list(data.chemistry.keys()))
chem=1
else:
print("Invalid choice. Try again")
f=1
if f==0:
print("The game is started. Your clues are:")
if states==1:
for i in ans:
if i in vowels:
v+=1
print("The capital of the state is:",data.indian_states.get(ans))
print("The no. of vowels in the word are:",v)
elif chem==1:
for i in ans:
if i in vowels:
v+=1
print("The atomic number of the element is:",data.chemistry.get(ans))
print("The no. of vowels in the word are:",v)
else:
for i in ans:
last=i
for i in ans:
if i in vowels:
v+=1
print("The last letter of the word is ",last)
print("The no. of vowels in the word are ",v)
guess=input("Now, enter your guess: ")
if ans==guess or ans==guess.lower():
print("Wow..!Your guess was correct.")
print("You win")
flag=1
else:
while counter!=4:
counter+=1
print("Oh no..!Your guess was wrong.")
guess=input("Make a new guess:")
if ans==guess or ans==guess.lower():
print("Wow..!Your guess was correct.")
print("You win")
flag=1
break
if flag==0:
print("You lost..! The correct word was ",ans)
response=input("Wanna play again? Yes or No: ")
if response=="no" or response=="NO":
print("Thanks {} for playing.".format(name))
else:
print("Thanks {} for your response.".format(name))
|
9c0f99f8deea5f4f1f38d737a0e04ee8ad066042 | SimonTrux/DailyCode | /areBracketsValid.py | 1,006 | 4.1875 | 4 | #Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced.
#Every opening bracket must have a corresponding closing bracket. We can approximate this using strings.
def isBraces(c):
return c == '(' or c == ')'
def isCurly(c):
return c == '{' or c == '}'
def isSquare(c):
return c == '[' or c == ']'
def isOpening(c):
return c == '(' or c == '{' or c == '['
def typedArray(bracketType, str):
arr = []
for c in str:
if bracketType(c):
arr.append(c)
return arr
def areBracketsValid(str):
i = 0
types = [isBraces, isCurly, isSquare]
for t in types:
for c in typedArray(t, str):
if isOpening(c):
i += 1
else:
i -= 1
if i != 0:
return False
i = 0
return True
print areBracketsValid("[]{{{[[]]}}))(())((")
#print bracket().typedArray(isSquare, "{{(]]])})")
|
4a15901e10a18f3ae66da9e76e2ed1cd87b41c23 | benmahdjoubi/coffee-machine-simulator | /Coffee Machine/main.py | 4,712 | 4.1875 | 4 | from sys import exit
class CoffeeMachine:
"""
The coffee machine have 400 ml of water, 540 ml of milk,
120 g of coffe beans, 9 disposable cups, $550 in cash.
"""
water = 400 # in ml
milk = 540 # in ml
beans = 120 # in g
cups = 9
money = 550 # in $
def __init__(self):
self.buy = None
self.fill = None
self.take = None
self.remaining = None
self.exit = None
def action(self, arg=None):
self.arg = input()
if self.arg == "buy":
print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:)")
self.kind = input()
if self.kind == "1" and c.water >= 250 and c.beans >= 16:
# After buying espresso
c.water -= 250
c.beans -= 16
c.money += 4
c.cups -= 1
print("")
print("I have enough resources, making you a coffee!")
elif self.kind == "2" and c.water >= 350 and c.milk >= 75 and c.beans >= 20:
# After buying latte
c.water -= 350
c.milk -= 75
c.beans -= 20
c.money += 7
c.cups -= 1
print("")
print("I have enough resources, making you a coffee!")
elif self.kind == "3" and c.water >= 200 and c.milk >= 100 and c.beans >= 12:
# After buying cappuccino
c.water -= 200
c.milk -= 100
c.beans -= 12
c.money += 6
c.cups -= 1
print("I have enough resources, making you a coffee!")
print("")
elif self.kind == "1" and c.water < 250:
print("Sorry, not enough water!")
print("")
elif self.kind == "1" and c.beans < 16:
print("Sorry, not enough beans!")
print("")
elif self.kind == "2" and c.water < 350:
print("Sorry, not enough water!")
print("")
elif self.kind == "2" and c.milk < 75:
print("Sorry, not enough milk!")
print("")
elif self.kind == "2" and c.beans < 20:
print("Sorry, not enough coffee beans!")
print("")
elif self.kind == "3" and c.water < 200:
print("Sorry, not enough water!")
print("")
elif self.kind == "3" and c.milk < 100:
print("Sorry, not enough milk!")
print("")
elif self.kind == "3" and c.beans < 12:
print("Sorry, not enough coffee beans!")
print("")
else:
pass
elif self.arg == "exit":
exit(0)
elif self.arg == "fill":
# Introduce the content of the coffee machine
print("Write how many ml of water do you want to add:")
self.added_water = input("")
print("Write how many ml of milk do you want to add:")
self.added_milk = input("")
print("Write how many grams of coffee beans do you want to add:")
self.added_beans = input("")
print("Write how many disposable cups of coffee do you want to add:")
self.added_cups = input("")
# Update the values after the fill
self.water += int(self.added_water)
self.milk += int(self.added_milk)
self.beans += int(self.added_beans)
self.cups += int(self.added_cups)
elif self.arg == "remaining":
print("")
print("The coffee machine has:")
print(f"{self.water} of water")
print(f"{self.milk} of milk")
print(f"{self.beans} of coffee beans")
print(f"{self.cups} of disposable cups")
print(f"${self.money} of money")
print("")
else:
print("")
print(f"I gave you ${self.money}")
self.money -= self.money
if __name__ == "__main__":
c = CoffeeMachine()
while True:
print("Write action (buy, fill, take, remaining, exit):")
c.action()
|
a27729c3e9533a9634e57588caec48d8d438ff01 | haldous2/coding-practice | /ctci_16.19_pond_sizes.py | 4,170 | 4.15625 | 4 | """
You have an integer matrix representing a plot of land,
where the value at that location represents the height above sea level.
A value of zero indicates water.
A pond is a region of water connected vertically, horizontally, or diagonally.
The size of the pond is the total number of connected water cells.
Write a method to compute the sizes of all ponds in the matrix
"""
def find_ponds(g = []):
"""
Find the number of connected ponds and their sizes
Runtime O(w*h) where w is width, h is height
"""
if len(g) == 0:
return []
if len(g[0]) == 0:
return []
def traverse_ponds():
"""
Traverse ponds, track each in queue and count number connected
"""
visited = {}
queue = deque()
for row in range(len(g)):
for col in range(len(g[row])):
if (col, row) not in visited and g[row][col] == 0:
visited[(col, row)] = 1
# print "===== NEW exploring from:", (col, row)
queue.extend(explore_ponds((col, row)))
while queue:
water = queue.pop()
if water not in visited:
visited[water] = (col, row)
visited[(col, row)] += 1
# print "===== STILL exploring from:", water
queue.extend(explore_ponds(water))
ponds = []
for key, val in visited.items():
if type(val) is int:
ponds.append(val)
return ponds
def explore_ponds(point):
"""
Explore out one square from point
Note: square if flipped - direction of y up goes to zero
Note: pass back list of tuples -> [(0,0), (1,2), (col, row)] etc...
Note: could also write this as a loop
Overall runtime for this method is constant O(1)
"""
water_found = []
col = point[0]
row = point[1]
# print "col(x):", col, "row(y):", row, "value:", g[row][col]
def explore_connect_pond(dir_col, dir_row):
# check bounds of square
if dir_col >= 0 and dir_row >= 0 and dir_col < len(g[0]) and dir_row < len(g):
# check if pond
if g[dir_row][dir_col] == 0:
# add pond to queue
water_found.append((dir_col, dir_row))
# up
dir_col = col
dir_row = row - 1 # up is down
explore_connect_pond(dir_col, dir_row)
# print "up:", dir_col, dir_row
# down
dir_col = col
dir_row = row + 1 # down is up
explore_connect_pond(dir_col, dir_row)
# print "down:", dir_col, dir_row
# left
dir_col = col - 1
dir_row = row
explore_connect_pond(dir_col, dir_row)
# print "left:", dir_col, dir_row
# right
dir_col = col + 1
dir_row = row
explore_connect_pond(dir_col, dir_row)
# print "right:", dir_col, dir_row
# left up diag
dir_col = col - 1
dir_row = row - 1
explore_connect_pond(dir_col, dir_row)
# print "up left:", dir_col, dir_row
# right up diag
dir_col = col + 1
dir_row = row - 1
explore_connect_pond(dir_col, dir_row)
# print "up right:", dir_col, dir_row
# left down diag
dir_col = col - 1
dir_row = row + 1
explore_connect_pond(dir_col, dir_row)
# print "down left:", dir_col, dir_row
# right down diag
dir_col = col + 1
dir_row = row + 1
explore_connect_pond(dir_col, dir_row)
# print "down right:", dir_col, dir_row
# print "water found:", water_found
return [p for p in water_found]
return traverse_ponds()
g = [[0,2,1,0],[0,1,0,1],[1,1,0,1],[0,1,0,1]] ## 2,4,1 passed
g = [[0,1,1,0],[1,1,1,1],[1,1,1,1],[0,1,1,0]] ## 1,1,1,1 passed
g = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]] ## None passed
g = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] ## 16 passed
print find_ponds(g)
|
2490aefc407cc5604b6c82f2afcec2f4c515e2f9 | haldous2/coding-practice | /ctci_16.25_LRU_cache.py | 4,043 | 4.03125 | 4 | """
Design and build a "least recently used" cache, which evicts the least recently used item.
The cache should map from keys to values
(allowing you to insert and retrieve a value associated with a particular key)
and be initialized with a max size.
When it is full, it should evict the least recently used item.
You can assume the keys are integers and the values are strings.
Need:
Initialize: with max size, empty data struture
Insert, Retrieve (Peek)
Delete will happen automatically via least used on insert when full
Build as class for reuse
Use a hash table for quick lookups, and a linked list to maintian order, and LRU status
"""
class LRUCache(object):
def __init__(self, maxsize):
self.head = None
self.keys = {} # track keys for fast key to node lookups
self.last = None # track last node for trimming
self.cursize = 0 # current node count
self.maxsize = maxsize
class Node(object):
def __init__(self, key, val):
self.next = None
self.prev = None
self.key = key
self.val = val
def test_keys(self, key):
if key in self.keys:
print "test keys:", key, self.keys[key].val
def insert_val(self, key, val):
if key in self.keys:
self.move_node_to_front(self.keys[key])
self.keys[key].val = val
else:
# Create new node
node = self.Node(key, val)
# Track new key
self.keys[key] = node
# Insert node at front
self.insert_head(node)
# Remove any over max
self.remove_tail()
def insert_head(self, node):
if self.head is None:
# head not set - first node
self.head = node
self.last = node # track last node for removal
else:
# head is set - need to shift stuff around
temp = self.head
temp.prev = node
node.next = temp
self.head = node
self.cursize += 1
def remove_tail(self):
if self.cursize > self.maxsize:
remove_node = self.last
# print "remove_node:", id(remove_node), remove_node.key, remove_node.val
del self.keys[remove_node.key]
if self.last.prev is None:
# previous is head
self.head = None
else:
# previous is node
self.last = self.last.prev
self.last.next = None
del(remove_node)
self.cursize -= 1
def move_node_to_front(self, node):
# move if not already the first node
# head -> node(last)
if node.prev is not None:
if node.next is None:
# reset last if this last node
self.last = node.prev
# connect node prev & next
# head -> node -> node(move) -> None
node.prev.next = None
else:
# connect node prev & next
# head -> node -> node(move) -> node -> None
node.prev.next = node.next
node.next.prev = node.prev
# insert node at the head of the list
node.next = self.head
self.head = node
def retrieve(self, key):
if key in self.keys:
self.move_node_to_front(self.keys[key])
return self.keys[key].val
def print_cache(self):
# print "keys:", self.keys # prints objects
curr = self.head
while curr is not None:
print curr.val,
curr = curr.next
print
lru = LRUCache(5)
lru.insert_val(1, "one")
lru.insert_val(2, "two")
lru.insert_val(3, "three")
lru.insert_val(4, "four")
lru.insert_val(5, "five")
lru.insert_val(6, "six") ## should dump key 1 here
lru.insert_val(2, "two")
lru.insert_val(3, "three")
lru.insert_val(1, "one")
print "retrieve 5:", lru.retrieve(5)
lru.print_cache()
|
5a234dd844556af1d0d41ecd66dc1c938991d5f3 | haldous2/coding-practice | /ctci_17.03_randomset.py | 2,669 | 3.90625 | 4 | """
Randomly generate a set of m integers from an array of size n.
Each element must have equal probability of being chosen.
Given an array of values, randomly choose n values
Not sure about duplciates
"""
def generatesetV1build(arr, sub):
"""
naive version
select random from input array
swap random select to end
shrink size of the random selection
Running tests appears to show this is an unbiased approach
similar to shuffle; however, not running through all of array elements.
Honestly, I'm not sure how to tell if this is biased or not.
Because it is not able to randomly choose those already selected,
there should not be any bias - which is exactly how shuffle works
"""
ret = sub[:] # copy of sub / fresh start
for i in range(len(sub)):
rndidx = random.randint(0, len(arr) - 1 - i)
ret[i] = arr[rndidx]
# swap value to end
# print "swap indexes", rndidx, "and", (len(arr) - 1 - i), "rndrange: 0 to", (len(arr) - 1 - i)
arr[len(arr) - 1 - i], arr[rndidx] = arr[rndidx], arr[len(arr) - 1 - i]
return ret
print "lo:", lo, "hi:", hi, "diff:", hi - lo
def generatesetV1():
arr = [1,2,3,4,5,6,7,8,9,0]
sub = [None, None, None] # select 3 in 10
trk = {}
# print sub
for i in range(1000000):
newsub = sorted(generatesetV1build(arr, sub))
if tuple(newsub) in trk:
trk[(tuple(newsub))] += 1
else:
trk[(tuple(newsub))] = 1
lo = sys.maxint
hi = 0
for item, count in trk.items():
lo = min(lo, count)
hi = max(hi, count)
print item, count
print "lo:", lo, "hi:", hi, "diff:", hi - lo
generatesetV1()
def generatesetV2build(arr, sub):
"""
book version - unbiased and fair
"""
n = len(arr)
m = len(sub)
ret = arr[0:m]
# prefill ret
# random indexes
for i in range(m, n): # from m to (n - 1)
k = random.randint(0, i)
if k < m: # e.g. length of sub is 3, m=3 need index 0,1,2 - k < m
ret[k] = arr[i]
return ret
def generatesetV2():
arr = [1,2,3,4,5,6,7,8,9,0]
sub = [None, None, None] # select 3 in 10
trk = {}
# print sub
for i in range(1000000):
newsub = sorted(generatesetV2build(arr, sub))
if tuple(newsub) in trk:
trk[(tuple(newsub))] += 1
else:
trk[(tuple(newsub))] = 1
lo = sys.maxint
hi = 0
for item, count in trk.items():
lo = min(lo, count)
hi = max(hi, count)
print item, count
print "lo:", lo, "hi:", hi, "diff:", hi - lo
generatesetV2()
|
b6cdbfa3a85baa4249c2b8ca14d16659b1699c8a | winterfellding/mit-cs-ocw | /6.006/lec3.py | 1,012 | 4.0625 | 4 | """
insertion sort
"""
def insertion_sort(ary):
if len(ary) <= 1:
return ary
for i in range(1, len(ary)):
j = i - 1
key = ary[i]
while ary[j] > key and j >= 0:
ary[j+1] = ary[j]
j -= 1
ary[j+1] = key
arry = [2, 1, 3, 4, 0]
print(arry)
insertion_sort(arry)
print(arry)
"""
merge sort
"""
def merge_sort(ary, start, end):
mid = (end + start) // 2
L = merge_sort(ary[start:mid], start, mid)
R = merge_sort(ary[mid:end], mid, end)
i, j, r = 0, 0, 0
while i < len(L) and j < len(R):
if ary[i] < ary[j]:
ary[start+r] = L[i]
i += 1
r += 1
else:
ary[start+r] = R[j]
j += 1
r += 1
for idx in range(i, len(L)):
ary[start+r] = L[idx]
r += 1
for idx in range(j, len(R)):
ary[start + r] = R[idx]
r += 1
ary = [3, 2, 5, 32, 5, 7, 5, 3, 5, 7]
print(ary)
merge_sort(ary, 0, len(ary))
print(ary) |
0bac443e4ea9ccb5a6627988242986753427decf | alexviil/progeprojekt | /project/Tile.py | 1,367 | 3.6875 | 4 | from typing import Any
import pygame as pg
import constants as const
class Tile:
"""
The Tile object is used to set the properties of each tile in the game world. Each tile has it's coordinates
and boolean values for whether it is a wall or a creature is on it, both used for actor interactions. It also
has sprites, which are the regular floor by default (since that is the most used tile sprite). The explored
sprite only gets used when a tile is not in the player's field of view but has been at least once.
"""
def __init__(self, x, y, is_wall, is_creature, sprite_key="SPRITE_FLOOR", exp_sprite_key="SPRITE_FLOOREXPLORED",
doorway=False):
self.x = x
self.y = y
self.is_wall = is_wall
self.is_creature = is_creature
self.sprite_key = sprite_key
self.sprite = const.WALL_AND_FLOOR_DICT[self.sprite_key]
self.explored_sprite_key = exp_sprite_key
self.explored_sprite = const.WALL_AND_FLOOR_DICT[self.explored_sprite_key]
self.explored = False
self.doorway = doorway
def get_is_wall(self):
return self.is_wall
def get_is_creature(self):
return self.is_creature
def set_is_wall(self, boolean):
self.is_wall = boolean
def set_is_creature(self, boolean):
self.is_creature = boolean
|
aaa145ece0fb2302ffc7374782174c2cbfb26257 | basilfx/xknx | /test/devices_tests/travelcalculator_test.py | 9,111 | 3.828125 | 4 | """Unit test for TravelCalculator objects."""
import time
import unittest
from xknx.devices import TravelCalculator, TravelStatus
class TestTravelCalculator(unittest.TestCase):
"""Test class for TravelCalculator objects."""
# TravelCalculator(25, 50) means:
#
# 2 steps / sec UP
# 4 steps / sec DOWN
#
# INIT
#
def test_time_default(self):
"""Test default time settings (no time set from outside)."""
travelcalculator = TravelCalculator(25, 50)
self.assertLess(
abs(time.time()-travelcalculator.current_time()),
0.001)
def test_time_set_from_outside(self):
"""Test setting the current time from outside."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.time_set_from_outside = 1000
self.assertEqual(travelcalculator.current_time(), 1000)
def test_set_position(self):
"""Test set position."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.set_position(70)
self.assertTrue(travelcalculator.position_reached())
self.assertEqual(travelcalculator.current_position(), 70)
def test_set_position_after_travel(self):
"""Set explicit position after start_travel should stop traveling."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.start_travel(30)
travelcalculator.set_position(80)
self.assertTrue(travelcalculator.position_reached())
self.assertEqual(travelcalculator.current_position(), 80)
def test_travel_down(self):
"""Test travel up."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.set_position(60)
travelcalculator.time_set_from_outside = 1000
travelcalculator.start_travel(40)
# time not changed, still at beginning
self.assertEqual(travelcalculator.current_position(), 60)
self.assertFalse(travelcalculator.position_reached())
self.assertEqual(
travelcalculator.travel_direction,
TravelStatus.DIRECTION_DOWN)
travelcalculator.time_set_from_outside = 1000 + 1
self.assertEqual(travelcalculator.current_position(), 56)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 2
self.assertEqual(travelcalculator.current_position(), 52)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 4
self.assertEqual(travelcalculator.current_position(), 44)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 5
# position reached
self.assertEqual(travelcalculator.current_position(), 40)
self.assertTrue(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 10
self.assertEqual(travelcalculator.current_position(), 40)
self.assertTrue(travelcalculator.position_reached())
def test_travel_up(self):
"""Test travel down."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.set_position(50)
travelcalculator.time_set_from_outside = 1000
travelcalculator.start_travel(70)
# time not changed, still at beginning
self.assertEqual(travelcalculator.current_position(), 50)
self.assertFalse(travelcalculator.position_reached())
self.assertEqual(
travelcalculator.travel_direction,
TravelStatus.DIRECTION_UP)
travelcalculator.time_set_from_outside = 1000 + 2
self.assertEqual(travelcalculator.current_position(), 54)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 4
self.assertEqual(travelcalculator.current_position(), 58)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 8
self.assertEqual(travelcalculator.current_position(), 66)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 10
# position reached
self.assertEqual(travelcalculator.current_position(), 70)
self.assertTrue(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 20
self.assertEqual(travelcalculator.current_position(), 70)
self.assertTrue(travelcalculator.position_reached())
def test_stop(self):
"""Test stopping."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.set_position(60)
travelcalculator.time_set_from_outside = 1000
travelcalculator.start_travel(80)
self.assertEqual(
travelcalculator.travel_direction,
TravelStatus.DIRECTION_UP)
# stop aftert two seconds
travelcalculator.time_set_from_outside = 1000 + 2
travelcalculator.stop()
travelcalculator.time_set_from_outside = 1000 + 4
self.assertEqual(travelcalculator.current_position(), 64)
self.assertTrue(travelcalculator.position_reached())
# restart after 1 additional second (3 seconds)
travelcalculator.time_set_from_outside = 1000 + 5
travelcalculator.start_travel(68)
# running up for 6 seconds
travelcalculator.time_set_from_outside = 1000 + 6
self.assertEqual(travelcalculator.current_position(), 66)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 7
self.assertEqual(travelcalculator.current_position(), 68)
self.assertTrue(travelcalculator.position_reached())
def test_change_direction(self):
"""Test changing direction while travelling."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.set_position(60)
travelcalculator.time_set_from_outside = 1000
travelcalculator.start_travel(80)
self.assertEqual(
travelcalculator.travel_direction,
TravelStatus.DIRECTION_UP)
# change direction after two seconds
travelcalculator.time_set_from_outside = 1000 + 2
self.assertEqual(travelcalculator.current_position(), 64)
travelcalculator.start_travel(48)
self.assertEqual(
travelcalculator.travel_direction,
TravelStatus.DIRECTION_DOWN)
self.assertEqual(travelcalculator.current_position(), 64)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 4
self.assertEqual(travelcalculator.current_position(), 56)
self.assertFalse(travelcalculator.position_reached())
travelcalculator.time_set_from_outside = 1000 + 6
self.assertEqual(travelcalculator.current_position(), 48)
self.assertTrue(travelcalculator.position_reached())
def test_travel_full_up(self):
"""Test travelling to the full up position."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.set_position(70)
travelcalculator.time_set_from_outside = 1000
travelcalculator.start_travel_up()
travelcalculator.time_set_from_outside = 1014
self.assertFalse(travelcalculator.position_reached())
self.assertFalse(travelcalculator.is_closed())
self.assertFalse(travelcalculator.is_open())
travelcalculator.time_set_from_outside = 1015
self.assertTrue(travelcalculator.position_reached())
self.assertTrue(travelcalculator.is_open())
self.assertFalse(travelcalculator.is_closed())
def test_travel_full_down(self):
"""Test travelling to the full down position."""
travelcalculator = TravelCalculator(25, 50)
travelcalculator.set_position(80)
travelcalculator.time_set_from_outside = 1000
travelcalculator.start_travel_down()
travelcalculator.time_set_from_outside = 1019
self.assertFalse(travelcalculator.position_reached())
self.assertFalse(travelcalculator.is_closed())
self.assertFalse(travelcalculator.is_open())
travelcalculator.time_set_from_outside = 1020
self.assertTrue(travelcalculator.position_reached())
self.assertTrue(travelcalculator.is_closed())
self.assertFalse(travelcalculator.is_open())
def test_is_traveling(self):
"""Test if cover is traveling."""
travelcalculator = TravelCalculator(25, 50)
self.assertFalse(travelcalculator.is_traveling())
travelcalculator.set_position(20)
self.assertFalse(travelcalculator.is_traveling())
travelcalculator.time_set_from_outside = 1000
travelcalculator.start_travel_down()
travelcalculator.time_set_from_outside = 1004
self.assertTrue(travelcalculator.is_traveling())
travelcalculator.time_set_from_outside = 1005
self.assertFalse(travelcalculator.is_traveling())
|
a169cea8f2587684e2018b3ec7dd86ae0016923a | miguelrang/Symmetric-Cryptography--console | /OneTimePad/OneTimePad.pyw | 2,330 | 3.546875 | 4 | import random
class OneTimePad:
def __init__(self):
pass
def becomeTextToBytesList(self, text:str):
# M E S S A G E
byte_text = bytes(text, "ascii")
bytes_list:list = []
for byte in byte_text:
bytes_list.append(byte)
return bytes_list
def becomeBytesToCharsList(self, bytes_unencrypted:bytes):
chars_list:list = []
for byte in bytes_unencrypted:
chars_list.append(byte.to_bytes(1, "big"))
return chars_list
def randomKey(self, message:str):
# K E Y
bytes_list:list = []
for i in range(len(message)):
bytes_list.append(random.randint(0, 255))
return bytes_list
def encryptedText(self, text:str, opt:int):
# In this variable we save the
# unencoded message but in bytes
# (for this we call the becomeTextToBytesList
# function)
bytes_msg:list = self.becomeTextToBytesList(text)
# If you chose to use an old key, we enter
# to the first option
bytes_key:list = []
if opt == 1:
with open("Key_message.lock", "rb") as file:
data = file.read()
for i in data:
bytes_key.append(i)
elif opt == 2:
# If you want a new key, we create it for you
bytes_key = bytearray(self.randomKey(bytes_msg))
with open("Key_message.lock", "wb") as file:
file.write(bytes_key)
bytes_encrypted:list = []
i:int = 0
while i < len(bytes_key):
bytes_encrypted.append((bytes_msg[i] ^ bytes_key[i]))
i+=1
bytes_encrypted = bytearray(bytes_encrypted)
with open("Encrypted_message.lock", "wb") as file:
file.write(bytes_encrypted)
return bytes_encrypted, bytes_key
def unencryptedText(self):
with open("Encrypted_message.lock", "rb") as file:
data_e_m = file.read()
bytes_enc_msg:list = []
for i in data_e_m:
bytes_enc_msg.append(i)
with open("Key_message.lock", "rb") as file:
data_k_m = file.read()
bytes_key_msg:list = []
for i in data_k_m:
bytes_key_msg.append(i)
i:int = 0
bytes_unencrypted = []
while i < len(bytes_key_msg):
bytes_unencrypted.append(bytes_enc_msg[i] ^ bytes_key_msg[i])
i+=1
bytes_unencrypted_array = bytearray(bytes_unencrypted)
with open("Unencrypted_message.lock", "wb") as file:
file.write(bytes_unencrypted_array)
text_unencrypted = b"".join(self.becomeBytesToCharsList(bytes_unencrypted))
return text_unencrypted, bytes_unencrypted, bytes_key_msg
|
c6e0d48b967c34501c8a5b1bcd39a68627b40da6 | mostley/96pxgames | /flames.py | 5,156 | 3.609375 | 4 | #!/usr/bin/env python
"""flames.py - Realtime Fire Effect Demo
Pete Shinners, April 3, 2001
Ok, this is a pretty intense demonstation of using
the surfarray module and numeric. It uses an 8bit
surfaces with a colormap to represent the fire. We
then go crazy on a separate Numeric array to get
realtime fire. I'll try to explain my methods here...
This flame algorithm is very popular, and you can find
it for just about all graphic libraries. The fire effect
works by placing random values on the bottom row of the
image. Then doing a simplish blur that is weighted to
move the values upward. Then slightly darken the image
so the colors get darker as they move up. The secret is
that the blur routine is "recursive" so when you blur
the 2nd row, the values there are used when you blur
the 3rd row, and all the way up.
This fire algorithm works great, but the bottom rows
are usually a bit ugly. In this demo we just render
a fire surface that has 3 extra rows at the bottom we
just don't use.
Also, the fire is rendered at half the resolution of
the full image. We then simply double the size of the
fire data before applying to the surface.
Several of these techniques are covered in the pygame
surfarray tutorial. doubling an image, and the fancy
blur is just a modified version of what is in the tutorial.
This runs at about 40fps on my celeron-400
"""
import pygame
from pygame.surfarray import *
from pygame.locals import *
#from Numeric import *
#from RandomArray import *
from numpy import *
from numpy.random import random_integers as randint
import time
from gamelib import librgb
from gamelib.vector import Vector
RES = array((24,16))
MAX = 246
RESIDUAL = 86
HSPREAD, VSPREAD = 26, 78
VARMIN, VARMAX = -2, 3
def main():
"main function called when the script is run"
#first we just init pygame and create some empty arrays to work with
pygame.init()
screen = pygame.display.set_mode(RES, 0, 8)
print screen.get_flags()
cmap = setpalette(screen)
flame = zeros(RES/2 + (0,3), dtype=uint32)
print flame.shape
doubleflame = zeros(RES)
randomflamebase(flame)
print "Connecting to display ..."
#rgb = librgb.RGB("127.0.0.1")
rgb = librgb.RGB("192.168.0.17")
rgb.invertedX = False
rgb.invertedY = True
rgb.clear((0,0,0))
#the mainloop is pretty simple, the work is done in these funcs
while not pygame.event.peek((QUIT,KEYDOWN,MOUSEBUTTONDOWN)):
modifyflamebase(flame)
#flame[20:30,40:60] = 50
processflame(flame)
#flame[50:90,50:70] += 12
blitdouble(screen, flame, doubleflame)
pygame.display.flip()
flame = clip(flame, 0, 255)
set_plasma_buffer(rgb, cmap, flame)
rgb.send()
time.sleep(0.05)
def setpalette(screen):
"here we create a numeric array for the colormap"
gstep, bstep = 75, 150
cmap = zeros((256, 3))
cmap[:,0] = minimum(arange(256)*3, 255)
cmap[gstep:,1] = cmap[:-gstep,0]
cmap[bstep:,2] = cmap[:-bstep,0]
screen.set_palette(cmap)
return cmap
def randomflamebase(flame):
"just set random values on the bottom row"
flame[:,-1] = randint(0, MAX, flame.shape[0])
print flame[:,-1]
def modifyflamebase(flame):
"slightly change the bottom row with random values"
bottom = flame[:,-1]
mod = randint(VARMIN, VARMAX, bottom.shape[0])
add(bottom, mod, bottom)
maximum(bottom, 0, bottom)
#if values overflow, reset them to 0
bottom[:] = choose(greater(bottom,MAX), (bottom,0))
#bottom = where(bottom > MAX, 0, bottom)
def processflame(flame):
"this function does the real work, tough to follow"
notbottom = flame[:,:-1]
#first we multiply by about 60%
multiply(notbottom, 146, notbottom)
right_shift(notbottom, 8, notbottom)
#work with flipped image so math accumulates.. magic!
flipped = flame[:,::-1]
#all integer based blur, pulls image up too
tmp = flipped * 20
right_shift(tmp, 8, tmp)
tmp2 = tmp >> 1
add(flipped[1:,:], tmp2[:-1,:], flipped[1:,:])
add(flipped[:-1,:], tmp2[1:,:], flipped[:-1,:])
add(flipped[1:,1:], tmp[:-1,:-1], flipped[1:,1:])
add(flipped[:-1,1:], tmp[1:,:-1], flipped[:-1,1:])
tmp = flipped * 80
right_shift(tmp, 8, tmp)
add(flipped[:,1:], tmp[:,:-1]>>1, flipped[:,1:])
add(flipped[:,2:], tmp[:,:-2], flipped[:,2:])
#make sure no values got too hot
minimum(notbottom, MAX, notbottom)
#notbottom = where(notbottom > MAX, MAX, notbottom)
def blitdouble(screen, flame, doubleflame):
"double the size of the data, and blit to screen"
doubleflame[::2,:-2:2] = flame[:,:-4]
doubleflame[1::2,:-2:2] = flame[:,:-4]
doubleflame[:,1:-2:2] = doubleflame[:,:-2:2]
blit_array(screen, doubleflame)
# ---------------------------------------------------------------
def set_plasma_buffer(rgb, cmap, plasmaBuffer):
xSize, ySize = plasmaBuffer.shape
for x in range(0, xSize):
for y in range(0, ySize):
#print x, y, plasmaBuffer[x][y]
rgb.setPixel(Vector(x,y), cmap[plasmaBuffer[x][y]])
if __name__ == '__main__': main()
|
faf299ecb5bf22d7a57bed24e4e2c522ede12fc3 | tharang/my_experiments | /python_experiments/10_slice_dice_strings_lists.py | 997 | 4.3125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'vishy'
verse = "bangalore"
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
print("verse = {}".format(verse))
print("months = {}".format(months))
#similarities in accessing lists and strings
#1 - Len() function
print("Length of string len(verse) = {}".format(len(verse)))
print("Length of list len(months) = {}".format(len(months)))
#2 - slicing
print("verse[:3] = {}".format(verse[:3]))
print("months[:6] = {}".format(months[:6]))
print("verse[3:] = {}".format(verse[3:]))
print("months[6:] = {}".format(months[6:]))
#3 - in and not in
print("gal in {} = {}".format(verse, 'gal' in verse))
print("Oct in {} = {}".format(months, 'Oct' in months))
print("her not in {} = {}".format(verse, 'her' not in verse))
print("Sunday not in {} = {}".format(months, 'Sunday' not in months))
print("gal not in {} = {}".format(verse, 'gal' not in verse))
print("Oct not in {} = {}".format(months, 'Oct' not in months)) |
bc229859826cd7a8d7214577f79d4903cee3f222 | tharang/my_experiments | /python_experiments/08_stringMethods_verse.py | 955 | 3.796875 | 4 | # -*- coding: utf-8 -*-
__author__ = 'vishy'
verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"
print(verse)
# Use the appropriate functions and methods to answer the questions above
# Bonus: practice using .format() to output your answers in descriptive messages!
lenOfVerse = len(verse)
fIndexAnd = verse.find("and")
lIndexYou = verse.rfind("you")
countYou = verse.count("you")
outputString = "Length of the Verse is {}, first index of word \'you\' is {}, last index of word \'you\' is {}, no of occurences of the word \'you\' is {}"
print("\n")
print(outputString.format(lenOfVerse, fIndexAnd, lIndexYou, countYou)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.