inital commit. about to start file IO.

This commit is contained in:
gabe venberg 2021-02-08 11:29:13 -06:00
commit 054879c11d
19 changed files with 564 additions and 0 deletions

139
.gitignore vendored Normal file
View file

@ -0,0 +1,139 @@
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
pytestdebug.log
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
doc/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
pythonenv*
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# profiling data
.prof

16
collatz/collatz.py Executable file
View file

@ -0,0 +1,16 @@
def nextInSequence(number):
if isinstance(number, int):
if number % 2 == 0:
return number // 2
else:
return 3*number+1
else:
raise TypeError('input must be int!')
def seqenceLength(number):
length = 0
while number != 1:
number = nextInSequence(number)
length += 1
return length

24
collatz/collatzSearch.py Executable file
View file

@ -0,0 +1,24 @@
#! /usr/bin/env python3
import sys
import collatz
usage='usage: collatzSearch [digits] outputs the lenght of the collatz sequence for every number less than 10^digits'
if len(sys.argv)<2:
print(usage)
sys.exit()
digits = sys.argv[1]
try:
digits = int(digits)
except:
print(usage)
sys.exit()
nextNumber = 1
maxNumber = 10**digits
while nextNumber<maxNumber:
print('collatz length of '+str(nextNumber)+' is: \n'+str(collatz.seqenceLength(nextNumber)))
nextNumber += 1

21
collatz/collatzSequence.py Executable file
View file

@ -0,0 +1,21 @@
#! /usr/bin/env python3
import sys
import collatz
usage='usage: collatzSequence [number] prints the collatz sequence for the given number'
if len(sys.argv)<2:
Print(usage)
sys.exit()
number = sys.argv[1]
try:
number = int(number)
except:
print(usage)
sys.exit()
while number != 1:
number = collatz.nextInSequence(number)
print(number)

70
conway.py Executable file
View file

@ -0,0 +1,70 @@
#! /usr/bin/env python3
#conways game of life
import time, random, copy
width = 100
hight = 50
nextCells = []
currentCells = []
def createInitalBoard(): #create inital board
for x in range(width):
column = [] #add a column
for y in range(hight):
if random.randint(0, 1) == 0:
column.append('#') #add a living cell
else:
column.append(' ') #add a dead cell
nextCells.append(column) #append the newly created random column
def printBoard():
for y in range(hight):
for x in range(width):
print(nextCells[x][y], end='')
print()#print a newline at the end of the row.
print('\n\n\n\n\n') #seperate each step with newlines
def updateBoard():
currentCells = copy.deepcopy(nextCells) #create a buffer of the grid to work on.
for x in range(width):
for y in range(hight):
#get neighboring cordinates
#% width makes the board wrap.
leftCoord = (x-1)%width
rightCoord = (x+1)%width
aboveCoord = (y-1)%hight
belowCoord = (y+1)%hight
numNeighbors = 0
#count the number of living neighbors
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors +=1 #top left
if currentCells[x][aboveCoord] == '#':
numNeighbors +=1 #top
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors +=1 #top right
if currentCells[leftCoord][y] == '#':
numNeighbors +=1 #left
if currentCells[rightCoord][y] == '#':
numNeighbors +=1 #right
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors +=1 #bottom left
if currentCells[x][belowCoord] == '#':
numNeighbors +=1 #bottom
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors +=1 #bottom right
#set cell state based on conways rules
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
nextCells[x][y] = '#'
else:
nextCells[x][y] = ' '
createInitalBoard()
while True: #main loop
printBoard()
updateBoard()
time.sleep(.1)

7
function.py Executable file
View file

@ -0,0 +1,7 @@
#! /usr/bin/env python3
def hello(name):
print('hello, '+name)
hello('alice')
hello('bob')

7
import.py Executable file
View file

@ -0,0 +1,7 @@
#! /usr/bin/env python3
import random,sys
for i in range(100):
print(random.randint(1,10))
sys.exit()

22
inventory.py Executable file
View file

@ -0,0 +1,22 @@
#! /usr/bin/env python3
def displayInventory(inventory):
print("Inventory:")
output = ""
item_total = 0
for k,v in inventory.items():
output += str(v)+" "+k+"\n"
item_total+= v
output += "Total number of items: "+str(item_total)
return output
def addToInventory(inventory, addedItems): #modifies in place!
for i in addedItems:
inventory.setdefault(i, 0)
inventory[i] += 1
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
print(displayInventory(inventory))
addToInventory(inventory, dragonLoot)
print(displayInventory(inventory))

18
magic_8.py Executable file
View file

@ -0,0 +1,18 @@
#! /usr/bin/env python3
import random
def getAwnser():
r = random.randint(0, 8)
messages = ['It is certain',
'It is decidedly so',
'Yes',
'Reply hazy, try again',
'Ask again later',
'My reply is no',
'Outlook not so good',
'Very doubtful' ]
return messages[r]
for i in range(0,10):
print(getAwnser())

17
magic_8_v2.py Executable file
View file

@ -0,0 +1,17 @@
#! /usr/bin/env python3
import random
def getAwnser():
messages = ('It is certain',
'It is decidedly so',
'Yes',
'Reply hazy, try again',
'Ask again later',
'My reply is no',
'Outlook not so good',
'Very doubtful' )
return messages[random.randint(0, len(messages)-1)]
for i in range(0,10):
print(getAwnser())

22
number_guess.py Executable file
View file

@ -0,0 +1,22 @@
#! /usr/bin/env python3
#guess the number game
import random
secretNumber = random.randint(1,100)
print('I am thinking of a number between 1 and 100.')
#ask the player to guess 10 times.
for guessesTaken in range(1,10):
print('take a guess')
guess = int(input())
if guess < secretNumber:
print('your guess is too low.')
elif guess > secretNumber:
print('your guess is too high.')
else:
break
if guess == secretNumber:
print('you guessed correctly! it only took you '+str(guessesTaken)+' guesses!')
else:
print('you were not able to guess in 10 guesses. the number I was thinking of was '+str(secretNumber))

9
password.py Executable file
View file

@ -0,0 +1,9 @@
#! /usr/bin/env python3
name = 'mary'
password = 'swordfish'
if name == 'mary':
print('hello mary')
if password == 'swordfish':
print('acess granted')
else:
print('Wrong Password')

61
pigLatin.py Executable file
View file

@ -0,0 +1,61 @@
#! /usr/bin/env python3
import sys
if len(sys.argv)<2:
print('usage: piglatin [text] -translate text to piglatin')
sys.exit()
message = sys.argv[1]
def translateToPigLatin(message):
vowels=('a', 'e', 'i', 'o', 'u', 'y')
piglatin=[] #list of the words
for word in message.split():
#seperate the non-letters at the start of the word
prefixNonLetters = ''
while len(word) > 0 and not word[0].isalpha():
prefixNonLetters += word[0]
word = word[1:]
if len (word) == 0:
piglatin.append(prefixNonLetters)
continue
suffixNonLetters = ''
while len(word)>0 and not word[-1].isalpha():
suffixNonLetters = word[-1]+suffixNonLetters
word = word[:-1]
#remember if word was in uppercase or title case.
wasUpper = word.isupper()
wasTitle = word.istitle()
#make word lowercase for translation.
word = word.lower()
#seperate the consanants at the end of the word.
prefixConsonants = ''
while len(word) > 0 and not word[0] in vowels:
prefixConsonants += word[0]
word = word[1:]
#add pig latin ending
if prefixConsonants == '':
word += 'yay'
else:
word += prefixConsonants+'ay'
#set the word back to upercase or titlecase.
if wasUpper:
word=word.upper()
if wasTitle:
word = word.title()
#add non letters back.
piglatin.append(prefixNonLetters + word + suffixNonLetters)
#join all the words back into a string.
return' '.join(piglatin)
print(translateToPigLatin(message)

68
rock_paper_scissors.py Executable file
View file

@ -0,0 +1,68 @@
#! /usr/bin/env python3
import random, sys
print('ROCK, PAPER, SCISSORS')
#variables to keep track of wins, losses, ties.
wins =0
losses = 0
ties = 0
while True: #main game loop.
print('%s Wins, %s Losses, %s Ties' %(wins, losses, ties))
while True: #input loop
print('Enter your move: (r)ock, (p)aper, (s)cissors, or (q)uit')
playerMove = input()
if playerMove == 'q':
sys.exit() #exit program
elif playerMove == 'r' or playerMove == 'p' or playerMove == 's':
break #get out of input loop.
else:
print('type of of r, p, s, or q.')
#display player choice.
if playerMove == 'r':
print('ROCK vs ...')
elif playerMove == 'p':
print('PAPER vs ...')
elif playerMove == 's':
print('SCISSORS vs ...')
#determine computer move and display it.
randomNumber = random.randint(1,3)
if randomNumber == 1:
computerMove = 'r'
print('ROCK')
if randomNumber == 2:
computerMove = 'p'
print('PAPER')
if randomNumber == 3:
computerMove = 's'
print('SCISSORS')
#determine and display results.
if playerMove == computerMove:
print('Its a Tie!')
ties += 1
elif playerMove == 'r':
if computerMove == 's':
print('You Win!')
wins += 1
else:
print('You Loose!')
losses += 1
elif playerMove == 'p':
if computerMove == 'r':
print('You Win!')
wins +=1
else:
print('You Loose!')
losses += 1
elif playerMove == 's':
if computerMove == 'p':
print('You Win!')
wins +=1
else:
print('You Loose!')
losses +=1

5
spam.py Executable file
View file

@ -0,0 +1,5 @@
#! /usr/bin/env python3
spam = 0
while spam <5:
print('spam'+str(spam))
spam = spam+1

29
strongPassword.py Executable file
View file

@ -0,0 +1,29 @@
#! /usr/bin/env python3
import re, sys
if len(sys.argv)<2:
print('usage: strongPassword [password] tests whether the password is at least 8 characters, contains both upper and lowercase, and has at least one digit/symbol, OR consists of at least 3 words of 4 letters each, containing both upper and lower case.')
sys.exit()
def checkShortPassword(password):
if len(password)<8:
return false
hasLower = re.search('[a-z]', password)
hasCaps = re.search('[A-Z]', password)
hasDigitOrSymbol = re.search('[\d]|[\W_\s]', password)
#
return hasLower and hasCaps and hasDigitOrSymbol
def checkLongPassword(password):
has3Words = re.match('\s*\S+(?:\s+\S+){3,}', password)
hasLower = re.search('[a-z]', password)
hasCaps = re.search('[A-Z]', password)
return has3Words and hasLower and hasCaps
password = sys.argv[1]
if checkLongPassword(password) or checkShortPassword(password):
print('password is strong')
else:
print('password is weak!')

3
tmp.py Executable file
View file

@ -0,0 +1,3 @@
#! /usr/bin/env python3

6
your_name.py Executable file
View file

@ -0,0 +1,6 @@
#! /usr/bin/env python3
name =''
while name != 'your name':
print('please type your name')
name = input()
print('thank you!')

20
zigzag.py Executable file
View file

@ -0,0 +1,20 @@
#! /usr/bin/env python3
import time, sys
maxIndent = 100 #how many spaces the zigzag should move
linewidth = 5 #width of line
linechar = '*'
indent = 0
indentIncreasing = 1
try:
while True:
print((' '*indent)+(linechar*linewidth)) #form the string for the current line
indent += indentIncreasing
if indent > maxIndent or indent <= 0:
indentIncreasing *= -1 # change direction
time.sleep(0.01)
except KeyboardInterrupt:
sys.exit()