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
|
---|---|---|---|---|---|---|
b380ff419257316e675334943842995e14c26db6 | HashiniK/StudentProgressPrediction | /W1790198_Q3.py | 3,827 | 3.890625 | 4 | passes=0
defers=0
fails=0
countProgress=0
countTrailer=0
countRetriever=0
countExclude=0
mainCount=0
progression=0
def verticalHistogram():
global countProgress,countTrailer,countRetriever,countExclude
print("You have quit the program")
print("")
print ("-----VERTICAL HISTOGRAM-----")
print(f'{"Progress":4} {"Trailing":5} {"Retriever":6} {"Exclude":7}')
while countProgress>0 or countTrailer>0 or countRetriever>0 or countExclude>0:
if countProgress>0:
print (" * ",end="")
countProgress-=1
else:
print (" ",end="")
countProgress-=1
if countTrailer>0:
print (" * ",end="")
countTrailer-=1
else:
print (" ",end="")
countTrailer-=1
if countRetriever>0:
print (" * ",end="")
countRetriever-=1
else:
print (" ",end="")
countRetriever-=1
if countExclude>0:
print (" * ",end="")
countExclude-=1
else:
print (" ",end="")
countExclude-=1
print ("")
print (mainCount,"outcomes in total")
def GettingTheInput():
global passes,defers,fails
while True:
while True:
try:
passes=int(input("Enter the number of credits for passes: "))
if(passes)>=0 and (passes)<=120 and (passes) % 20 == 0:
break
else:
print("Range Error!!")
except ValueError:
print("Please input an INTEGER!")
while True:
try:
defers=int(input("Enter the number of credits for defers: "))
if(defers)>=0 and (defers)<=120 and (defers) % 20 == 0:
break
else:
print("Range Error!!")
except ValueError:
print("Please input an INTEGER!")
while True:
try:
fails=int(input("Enter the number of credits for fails : "))
if(fails)>=0 and (fails)<=120 and (fails) % 20 == 0:
break
else:
print("Range Error!!")
except ValueError:
print("Please input an INTEGER!")
if passes+defers+fails==120:
break
else:
print("Total incorrect")
#output
def GettingTheOutput():
global mainCount,countProgress,countTrailer,countRetriever,countExclude
global progression
if passes==120: #progress
progression="Progress"
countProgress+=1
elif passes == 100 : #Module trailer
progression="Progress - Module Trailer"
countTrailer+=1
elif (passes <= 80)and (fails <=60): #module retrieve
progression="Do Not Progress - Module Retriever"
countRetriever+=1
elif fails>=80: #exclude
progression="Exclude"
countExclude+=1
print(progression)
mainCount+=1
def programQuit():
global endConfirmation
endConfirmation = input ("Press 'q' to exit and see the histogram or 'Enter' to keep running: ")
if endConfirmation == "q":
verticalHistogram()
print("Program will exit now...")
elif endConfirmation == "":
finalOutput()
else:
print ("Input Incorrect! Please try again!")
programQuit()
def finalOutput():
GettingTheInput()
GettingTheOutput()
programQuit()
finalOutput()
|
c4831a400a27fdbdc55c6d19de49cbf7721104bc | Robert-Becker/Python-Project | /Project1Part3.py | 618 | 4.03125 | 4 | print("")
print("")
print("Select Service")
print("")
choice = input("Makeover(M) or HairStyling(H) or Manicure(N) or Permanent Makeup(P): ")
if choice == "M":
cost = 125
elif choice == "H":
cost = 60
elif choice == "N":
cost = 35
elif choice == "P":
cost = 200
print("")
print("Select Discount")
print("")
choice = input("10% Discount(10) or 20% Discount(20) or No Discount(0): ")
if choice == "10":
discount = 0.9
elif choice == "20":
discount = 0.8
elif choice == "0":
discount = 1.0
print("")
TotalCost = (cost * discount)
print("Total: $" + str((TotalCost)))
|
15be8bceb7e5ff759edd95012a671ef9bad452b0 | Robert-Becker/Python-Project | /Project5-1.py | 1,834 | 3.90625 | 4 | #Original Code Written by Robert Becker
#Date Written - 6/25/2019
#Program was written to calculate end of semester scores for students by using an input file with a single space used as the delimiter between items
inputFile = open("scores.txt", "rt") #Define Input FIle Variable, opens file to read text
fileData = inputFile.readlines() #defines fileData variable, tells it to look at each line of the file
inputFile.close()#closes file we opened
for line in fileData:#specifies what to do for each line of data from fileData
items = line.split()#tells the file to create logical indexes with each space character in the file
name = str(items[0]) + " " + str(items[1])#creates name variable set to items 0 and 1 / First / Last Names
assignmentScores = int(items[2]) + int(items[3]) + int(items[4]) + int(items[5]) + int(items[6])#creates assignmentScores variable and adds all the assignments together
quizScores = int(items[7]) + int(items[8]) + int(items[9]) + int(items[10]) + int(items[11])#creates quizScores variable and adds all the quizzes together
examScores = int(items[12]) + int(items[13])#creates examScores variable and adds all the exams together
computeAverage = (assignmentScores/500*.4 + quizScores/100*.2 + examScores/200*.4)*100#creates computeAverage variable that find the students weighted final score
if 90 <= computeAverage <= 100: #Creates conditional statements that changes the total grade from a number to a letter
grade = "A"
if 80 <= computeAverage <90:
grade = "B"
if 70 <= computeAverage <80:
grade = "C"
if 60 <= computeAverage <70:
grade = "D"
if 0<= computeAverage <60:
grade = "F"
print(name + " " + str(grade))#Prints name variable, adds a space, and prints final letter grade
|
c0b5522a54c4607fd8f088b7824a32a9d44f151c | djstull/COMS127 | /class5/twofunctions.py | 386 | 3.84375 | 4 | def max(num1, num2):
if num1 > num2:
largest = num1
elif num2 > num1:
largest = num2
return largest
print(max(4, 5))
print(max(8, 9))
print(max(-4, -5))
print(max(4000, 6000))
def is_div(divend, divise):
if divend % divise == 0:
return True
else:
return False
#the if and else are redundant
print(is_div(4, 4))
print(is_div(3, 2)) |
c3317d237ba9cfb9a6bdd2f857d09e5f00ad30fc | djstull/COMS127 | /lab6/piggy.py | 721 | 4 | 4 | # converts the words to piggy latin
def convert_word(word):
from vowels import vowelfinder
vowel = vowelfinder(word)
first_letter = word[0]
if first_letter in ["a", "e", "i", "o", "u"]:
return word + "way"
else:
return word[vowel:] + word[:vowel] + "ay"
print(convert_word("google"))
print(convert_word("ggoogle"))
def convert_sentence(sentence):
list_of_words = sentence.split(' ')
new_sentence = ""
for word in list_of_words:
new_sentence = new_sentence + convert_word(word)
new_sentence = new_sentence + " "
return new_sentence
print(convert_sentence("google is a good search engine"))
print(convert_sentence("ggoogle is not a search engine"))
|
6aa7e4d251675baf3f0f3af97d70ae2f27dd55e0 | djstull/COMS127 | /ultimatecoinage.py | 1,025 | 4 | 4 | #Write a program to calculate the coinage needed for a given amount of change.
amount = int(input('Please input the total change in cents): '))
hundreds = amount // 10000
amount = amount % 10000
fifties = amount // 5000
amount = amount % 5000
twenties = amount // 2000
amount = amount % 2000
tens = amount // 1000
amount = amount % 1000
fives = amount // 500
amount = amount % 500
ones = amount // 100
amount = amount % 100
quarters = amount // 25
amount = amount % 25
dimes = amount // 10
amount = amount % 10
nickels = amount // 5
pennies = amount % 5
print(' ')
if hundreds > 0:
print(hundreds, "hundreds\n")
if fifties > 0:
print(fifties, "fifties\n")
if twenties > 0:
print(twenties, "twenties\n")
if tens > 0:
print(tens, "tens\n")
if fives > 0:
print(fives, "fives\n")
if ones > 0:
print(ones, "ones\n")
if quarters > 0:
print(quarters, "quarters\n")
if dimes > 0:
print(dimes, "dimes\n")
if nickels > 0:
print(nickels, "nickels\n")
if pennies > 0:
print(pennies, "pennies\n") |
9a0dc3a6736fe4139f6658b6dde626a9c6bc9bff | djstull/COMS127 | /lab1/coinage.py | 389 | 4.0625 | 4 | #Write a program to calculate the coinage needed for a given amount of change.
amount = int(input('Please input the amount of cents: '))
quarters = amount // 25
amount = amount % 25
dimes = amount // 10
amount = amount % 10
nickels = amount // 5
pennies = amount % 5
print(' ')
print(quarters, "quarters\n")
print(dimes, "dimes\n")
print(nickels, "nickels\n")
print(pennies, "pennies\n") |
142cb67953b8138f718d46206f2ec63b3b4f9cdb | Mychailo02/laboratorna_2_py | /PythonApplication6/PythonApplication6.py | 288 | 3.953125 | 4 | x = float(input("Введіть значення агрументу - "))
A = float(input("Введіть значення константи - "))
if x<0:
y = x
print(y)
elif A>0:
y = A
print(y)
else:
print("Немає розв'язків")
|
2f3913d011987d472f7f8ee29e838275b5109ae0 | IsaacDiaz09/Soluciones-HackerRank-repo | /30 dias de codigo HackerRank/24.) Arbol de busqueda binaria Lvl-Order/solucion.py | 1,450 | 3.859375 | 4 | # https://www.hackerrank.com/challenges/30-binary-trees/problem?isFullScreen=false
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def levelOrder(self,root):
l = []
res = []
# Se añade el nodo root
l.append(root)
# Cuando ya no hayan nodos por recorrer saldra del bucle
while len(l)>0:
res.append(l[0].data)
# Se elimina y recupera el primer nodo
node = l.pop(0)
# Se busca si tiene nodos hijos y si si, se añaden
if node.left is not None:
l.append(node.left)
if node.right is not None:
l.append(node.right)
# El proceso se repite sucesivamente y cada vez se elimina el primer elemento avanzando asi de nivel
del l
print(" ".join([str(x) for x in res]))
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
print()
myTree.levelOrder(root)
"""
6
3
5
4
7
2
1
"""
# 3 2 5 1 4 7
|
3fc0226c6bdb8eeacf35635e21e1b6772e648e63 | IsaacDiaz09/Soluciones-HackerRank-repo | /30 dias de codigo HackerRank/3.) Operadores/solucion.py | 546 | 3.734375 | 4 | # https://www.hackerrank.com/challenges/30-operators/
def mealTotalCost(base,tip,tax):
totalCost = base + (base*(tip/100)) + (base*(tax/100))
# halla el valor total calculando a cuanto equivale cada % y entrega la respuesta en un entero redondeado
return int(round(totalCost))
if __name__ == "__main__":
# precio base de la comida
mealBasePrice = float(input())
# % de propina
tipPercent = int(input())
# % de impuesto
taxPercent = int(input())
print(mealTotalCost(mealBasePrice,tipPercent,taxPercent))
|
198fd801462e9e255b22788fa2f79ed1b0220b18 | nneuro/lesson1 | /example.py | 435 | 3.859375 | 4 |
def check(triplets):
if 'ATG' in triplets and 'TAA' in triplets:
if triplets.index('ATG') < triplets.index('TAA'):
return True
else:
return False
x = 0
triplets = ['ATG', 'TAA', 'TAG', 'ATG', 'GGC', 'TAA']
while check(triplets) == True :
print(f'цикл номер {x}, check = {check(triplets)}')
x += 1
triplets = triplets[1::]
print(f'{triplets}, check = {check(triplets)}') |
d58e2b914284a47fc558b730364ccadce3a4a772 | Muhammadali-gold/python-portfolio | /python-projects/matplot.py | 447 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.array([[0, 0, 255], [255, 255, 0], [0, 255, 0]])
plt.imshow(x, interpolation='nearest')
plt.show()
def addGlider(i, j, grid):
"""adds a glider with top left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
N=3
grid = np.zeros(N*N).reshape(N, N)
addGlider(1, 1, grid) |
e0d1f159e8db74f3dc7d8a3a1a2a6c0f6d448c42 | Muhammadali-gold/python-portfolio | /python 100 days/tip-calculator/src/main.py | 363 | 4 | 4 | if __name__ == '__main__':
print('Welcome to the tip calculator ')
total_bill=float(input('What was the total bill? '))
person_count=int(input('How may people split bill? '))
percent=int(input('What percentage tip would you like to give? 10, 12, or 15? '))
print(f'Each person should pay ${round(total_bill*(100+percent)/100/person_count,2)}') |
0cb6cc118fa6988b4e6a8a38e036ef9e8736e451 | markaalvaro/advent-2020 | /day2.py | 710 | 3.9375 | 4 | def count_occurences(password, character):
count = 0
for i in range(0, len(password)):
if password[i] == character:
count += 1
return count
def find_num_valid_passwords():
numValid = 0
for line in open('day2_input.txt'):
fragments = line.split(' ')
expectedRange = fragments[0].split('-')
minExpected = int(expectedRange[0])
maxExpected = int(expectedRange[1])
letter = fragments[1][0]
password = fragments[2]
occurences = count_occurences(password, letter)
if occurences >= minExpected and occurences <= maxExpected:
numValid += 1
return numValid
print(find_num_valid_passwords()) |
8ee6857c5bf0ca2ab86d1f5f1ca6139bdefeaf2b | maleficarium/manga-downloader | /manga-downloader.py | 15,167 | 3.609375 | 4 | ## DESIGN
## This script takes in an url pointing to the main page of a comic/manga/manhwa in Batoto.net
## It then parses the chapter links, goes to each, downloads the images for each chapter and compresses
## them into zip files.
## Alternatively, we may be able to specify a name, and have the script search for it and ask for results.
## All choices should be one click; the software is deferential to the user.
## Let's build the script block by block, so we may have the choice to put in a GUI later.
## FUNCTIONS
## 1. Parsing an url to get the chapter links
## 1A.Confirm that an url points to the main page of a comic
## 2. Given a chapter link, identifying all the pages
## 2A.Retrieve the volume number, chapter number and name of the chapter; including support for fractional and negative chapter numbers
## 3. Downloading the pages and compressing them
import re
import urllib2
from lxml import html
from lxml.etree import tostring
from StringIO import StringIO
import gzip
import shutil
import os
import os.path
import glob
import sys
import zipfile
import urlparse
import argparse
import unicodedata
from string import maketrans
## Constants
__DOWNLOAD__ = True
__DEBUG__ = False
__RETRY_URL__ = 5
## Function to compress a directory
def zipdir(path, zipf):
for root, dirs, files in os.walk(path):
for f in files:
zipf.write(os.path.join(root, f), arcname = os.path.basename(f))
## Function to ask for URL
def checkURLType(url_input):
print "Checking: " + url_input
url_ok = False
for url_type in URL_TYPES:
if re.compile(URL_TYPES[url_type]['url']).match(url_input):
print "Site supported: " + url_type
url_ok = True
break
if not url_ok:
print "URL not supported or unknown"
exit(1)
return url_type
## Function to get a webpage
def readURL(url):
if url[0] == '/':
url = url_type + url
if __DEBUG__:
print "Reading url: " + url
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
for i in range(1, __RETRY_URL__):
try:
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip': # Large pages are often gzipped
buf = StringIO(response.read())
data = gzip.GzipFile(fileobj = buf)
else:
data = response
return data
except:
pass
## Function to retrieve and parse an HTML page
def readHTML(url):
data = readURL(url)
page = html.parse(data)
return page
## Function to download an image from a direct URL
def downloadImage(img_url, file_path):
data = readURL(img_url)
with open(file_path, 'wb') as f:
f.write(data.read())
## Fuction to clean the path from problematic characters.
def cleanPath(pathString):
if isinstance(pathString, unicode):
pathString = unicodedata.normalize('NFKD', pathString).encode('ascii', 'ignore')
pathString = pathString.translate(None, '\/:*?<>|')
transTable = maketrans("\"", "\'")
pathString = pathString.translate(transTable)
return pathString
## Generic class representing a manga chapter
class MangaChapter(object):
def __init__(self, manga_name, chapter_number, chapter_url, chapter_root_path, chapter_title=None, volume_number=None, group_name=None):
self.chapter_number = chapter_number
self.volume_number = volume_number
self.chapter_title = chapter_title
self.chapter_url = chapter_url
self.group_name = group_name
self.chapter_root_path = chapter_root_path
self.page_list = []
self.page_num = 0
prefix = [manga_name]
if volume_number is not None:
prefix.append("Volume " + volume_number)
prefix.append("Chapter " + chapter_number)
if chapter_title is not None:
prefix.append("- " + chapter_title)
if group_name is not None:
prefix.append("[" + group_name + "]")
self.prefix = " ".join(prefix)
def show(self):
print "Vol: ", self.volume_number, " Ch: ", self.chapter_number, " - ", self.chapter_title, ", by: ", self.group_name
def addPage(self, page_url):
self.page_list.append(page_url)
def retrieveAllPages(self):
raise NotImplementedError # To be overridden in subclasses
def downloadPage(self, page_url, page_file_path):
raise NotImplementedError # To be overridden in subclasses
def downloadChapter(self):
pathA = cleanPath(self.chapter_root_path)
pathB = cleanPath(self.prefix)
dir_path = os.path.join(pathA, pathB)
if verbose:
print ""
print dir_path
zip_path = dir_path + ".zip"
if os.path.exists(zip_path):
zipf = zipfile.ZipFile(zip_path)
if zipf.testzip() is None:
if __DEBUG__:
print "Skipping chapter " + self.chapter_number
return
else:
os.remove(zip_path)
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
os.makedirs(dir_path)
self.retrieveAllPages()
for page_url in self.page_list:
self.page_num = self.page_num + 1
page_path = os.path.join(dir_path, "p" + str(self.page_num).zfill(3))
self.downloadPage(page_url, page_path)
zipf = zipfile.ZipFile(zip_path, "w")
zipdir(dir_path, zipf)
zipf.close()
shutil.rmtree(dir_path)
## Subclass representing a manga chapter from Batoto
class MangaChapterBatoto(MangaChapter):
def __init__(self, manga_name, chapter_number, chapter_url, chapter_root_path, chapter_title=None, volume_number=None, group_name=None):
super(MangaChapterBatoto, self).__init__(manga_name, chapter_number, chapter_url, chapter_root_path, chapter_title, volume_number, group_name)
def retrieveAllPages(self):
## Look at the options of select element at //*[@id="page_select"]
## Take the value for each (page url) and save them
webpage = readHTML(self.chapter_url)
if webpage.xpath("//a[@href='?supress_webtoon=t']"): ## Long strip format for webtoons
if __DEBUG__:
print "Webtoon: reading in long strip format"
s = webpage.xpath("//div[@id='read_settings']/following-sibling::div/img")
for l in s:
self.addPage(l.get('src'))
else:
s = webpage.xpath("//*[@id='page_select']")[0]
for option in s.xpath('.//option[@value]'):
self.addPage(option.get('value'))
def downloadPage(self, page_url, page_file_path):
## Get @src attribute of element at //*[@id="comic_page"]
if urlparse.urlparse(page_url).path.split('.')[-1] in ['jpg', 'png']:
img_url = page_url
else:
webpage = readHTML(page_url)
img_url = webpage.xpath('//*[@id="comic_page"]')[0].get('src')
downloadImage(img_url, page_file_path + "." + urlparse.urlparse(img_url).path.split('.')[-1])
## Subclass representing a manga chapter from Starkana
class MangaChapterStarkana(MangaChapter):
def __init__(self, manga_name, chapter_number, chapter_url, chapter_root_path):
super(MangaChapterStarkana, self).__init__(manga_name, chapter_number, chapter_url, chapter_root_path)
def retrieveAllPages(self):
## Look at the options of select element at //*[@id="page_switch"]
## Take the value for each (page url) and save them
webpage = readHTML(self.chapter_url)
s = webpage.xpath("//*[@id='page_switch']")[0]
for option in s.xpath('.//option[@value]'):
self.addPage(option.get('value'))
def downloadPage(self, page_url, page_file_path):
## Get @src attribute of element at //*[@id="pic"/div/img]
webpage = readHTML(page_url)
img_url = webpage.xpath('//*[@id="pic"]/div/img')[0].get('src')
downloadImage(img_url, page_file_path + "." + urlparse.urlparse(img_url).path.split('.')[-1])
## Generic class representing a manga
class Manga(object):
def __init__(self, manga_url, manga_name=None):
self.name = manga_name
self.url = manga_url
self.chapter_list = []
def createFolder(self, path):
path = cleanPath(path)
if not os.path.exists(path):
os.makedirs(path)
with open(path + '/mangadl.link', 'w') as f:
f.write(self.url)
def addMangaChapter(self, manga_chapter):
self.chapter_list.insert(0, manga_chapter)
if __DEBUG__:
print "Added chapter " + manga_chapter.chapter_number
def retrieveAllChapters(self):
raise NotImplementedError # To be overridden in subclasses
## Subclass representing a manga hosted in Batoto
class MangaBatoto(Manga):
def __init__(self, manga_url, manga_name=None):
super(MangaBatoto, self).__init__(manga_url, manga_name)
## Regular expressions for parsing the chapter headings and retrieve volume number, chapter number, title etc
self.CHAPTER_TITLE_PATTERN_CHECK_VOLUME = '^Vol\..+'
self.CHAPTER_TITLE_PATTERN_WITH_VOLUME = '^Vol\.\s*([0-9]+|Extra)\s*Ch.\s*([0-9\.vA-Za-z-\(\)]+):?\s+(.+)'
self.CHAPTER_TITLE_PATTERN_NO_VOLUME = '^Ch.\s*([0-9\.vA-Za-z-\(\)]+):?\s+(.+)'
def retrieveAllChapters(self):
webpage = readHTML(self.url)
## print tostring(page) # For testing only
if self.name is None:
self.name = webpage.xpath('//h1[@class="ipsType_pagetitle"]')[0].text.strip()
print "Set name to: " + self.name
assert(self.name is not None)
ch_path = "Batoto - " + self.name
self.createFolder(ch_path)
for ch_row in webpage.xpath('//table[@class="ipb_table chapters_list"]/tbody/tr')[1:]:
if ch_row.get('class') == 'row lang_English chapter_row':
ch_a = ch_row.xpath('.//td')[0].xpath('.//a')[0]
ch_url = ch_a.get('href')
ch_name = unicode(ch_a.text_content().strip(' \t\n\r')).translate(dict.fromkeys(map(ord, '\\/'), None))
if __DEBUG__:
print ch_name
vol_no = None
ch_no = None
ch_title = None
if re.match(self.CHAPTER_TITLE_PATTERN_CHECK_VOLUME, ch_name):
m = re.match(self.CHAPTER_TITLE_PATTERN_WITH_VOLUME, ch_name)
vol_no = m.group(1)
ch_no = m.group(2)
ch_title = m.group(3)
else:
m = re.match(self.CHAPTER_TITLE_PATTERN_NO_VOLUME, ch_name)
ch_no = m.group(1)
ch_title = m.group(2)
assert(ch_no is not None) # Chapter number is mandatory
gr_a = ch_row.xpath('.//td')[2].xpath('.//a')[0]
gr_name = unicode(gr_a.text.strip(' \t\n\r')).translate(dict.fromkeys(map(ord, '\\/'), None))
self.addMangaChapter(MangaChapterBatoto(self.name, ch_no, ch_url, ch_path, ch_title, vol_no, gr_name))
## Subclass representing a manga hosted in Starkana
class MangaStarkana(Manga):
def __init__(self, manga_url, manga_name=None):
super(MangaStarkana, self).__init__(manga_url, manga_name)
def retrieveAllChapters(self):
webpage = readHTML(self.url)
## print tostring(page) # For testing only
if self.name is None:
if webpage.xpath('//meta[@property="og:title"]'):
self.name = webpage.xpath('//meta[@property="og:title"]/@content')[0].strip()
else:
self.name = self.url.split('/')[-1].replace('_', ' ')
print "Set name to: " + self.name
assert(self.name is not None)
ch_path = "Starkana - " + self.name
self.createFolder(ch_path)
for ch_row in webpage.xpath('//a[@class="download-link"]'):
ch_no = None
ch_url = ch_row.get('href')
ch_no = ch_url.split('/')[-1]
assert(ch_no is not None)
self.addMangaChapter(MangaChapterStarkana(self.name, ch_no, ch_url, ch_path))
# Data structures that help instantiating the right subclasses based on URL
URL_TYPES = {'http://www.batoto.net' : {'url' : '(http://)?(www\.)?(batoto\.net).+-r[0-9]+', 'manga' : MangaBatoto, 'mangachapter' : MangaChapterBatoto},
'http://www.bato.to' : {'url' : '(http://)?(www\.)?(bato\.to).+-r[0-9]+', 'manga' : MangaBatoto, 'mangachapter' : MangaChapterBatoto},
'http://www.starkana.com' : {'url' : '(http://)?(www\.)?starkana\.com/manga/[0A-Z]/.+', 'manga' : MangaStarkana, 'mangachapter' : MangaChapterStarkana}
}
# Parse command line arguments
parser = argparse.ArgumentParser(description = 'Download manga chapters from collection sites.')
parser.add_argument('--Debug', '-D', help = 'Run in debug mode', action = 'store_true')
parser.add_argument('--Test', '-T', help = 'Run in test mode (downloads suppressed)', action = 'store_true')
parser.add_argument('--verbose', '-v', help = 'Enable verbose mode', action = 'store_true')
group = parser.add_mutually_exclusive_group(required = False)
group.add_argument('--reload', '-r', help = 'Update all manga folders in current directory', action = 'store_true')
group.add_argument('--update', '-u', help = 'Update the manga at the url(s) provided', action = 'append')
args = vars(parser.parse_args())
url_list = []
__DEBUG__ = args['Debug']
__DOWNLOAD__ = not args['Test']
if args['verbose']:
verbose = True
else:
verbose = False
if args['reload']:
for subdir in filter(lambda f: os.path.isdir(f), glob.glob('*')):
if glob.glob(subdir + '/mangadl.link'):
with open(subdir + '/mangadl.link', 'r') as f:
url_list.append(f.read())
elif glob.glob(subdir + '/* Chapter *'):
url_input = raw_input("Enter URL for folder " + subdir + " (Press ENTER to skip) : ")
url_list.append(url_input)
elif args['update']:
url_list = args['update']
else:
url_input = raw_input("Enter URL: ")
url_list.append(url_input)
url_list = filter(None, url_list)
assert(url_list)
for url in url_list:
url_type = checkURLType(url)
manga = URL_TYPES[url_type]['manga'](url) # Instantiate manga object
manga.retrieveAllChapters() # Add all chapters to it
chapter_count = len(manga.chapter_list)
curr_download_count = 0
for chapter in manga.chapter_list:
if __DEBUG__:
chapter.show()
sys.stdout.write("\rDownloaded " + str(curr_download_count) + "/" + str(chapter_count) + " chapters.")
sys.stdout.flush()
if __DOWNLOAD__:
if __DEBUG__:
print "\nDownloading chapter..."
chapter.downloadChapter()
curr_download_count = curr_download_count + 1
sys.stdout.write("\rDownloaded " + str(curr_download_count) + "/" + str(chapter_count) + " chapters.")
sys.stdout.flush()
print "\n"
print "Finished."
exit(0)
|
917d4ff1aca38a81a6c2ec51d13f535109de534e | anaves/CursoPython3-Libertas | /etapa4/ExemploFuncao.py | 162 | 3.640625 | 4 | def soma(a,b):
return a+b
def sm(a,b):
return a+b,a*b
print('início')
r=soma(1,6)
print(r)
x,y=sm(3,6)
print('soma:{}, multiplicação:{}'.format(x,y)) |
22dcbe99009dcb889dc176bc99379c39f97c773f | tenglibai/Data-struct | /1.基本数据结构/栈-进制转换.py | 358 | 3.546875 | 4 | def baseConverter(decNumber, base):
digits = "0123456789ABCDEF"
stack = []
while decNumber > 0:
rem = decNumber % base
stack.append(rem)
decNumber = decNumber // base
newString = ""
while not stack == []:
newString = newString + digits[stack.pop()]
return newString
assert baseConverter(25, 2) == '11001'
assert baseConverter(25, 16) == '19'
|
b27d9d674f57863a994a1f6f98e9711a12d574a3 | Aries5522/daily | /2021届秋招/leetcode/递归回溯分治/添加不同的括号.py | 717 | 3.796875 | 4 | class Sulotion:
def diffWaysToCompute(self, input):
if input.isdigit():
return [int(input)]
res = []
for i, char in enumerate(input):
if char in ["+", "-", "*"]:
left = self.diffWaysToCompute(input[0:i])
right = self.diffWaysToCompute(input[i + 1:])
for l in left:
for r in right:
if char == "+":
res.append(l + r)
elif char == "-":
res.append(l - r)
else:
res.append(l * r)
return res
print(Sulotion().diffWaysToCompute("2-1-1"))
|
a0b187be9d8441ac232d0cd63c65f534f7dfd1f9 | Aries5522/daily | /2021届秋招/leetcode/paixu.py | 2,832 | 3.84375 | 4 | def bubble_sort(numbs):
for i in range (len(numbs)-1):
for j in range (len(numbs)-i-1):
if numbs[j]>numbs[j+1]:
numbs[j],numbs[j+1]=numbs[j+1],numbs[j]
return numbs
# 冒泡排序的思想:就是每次比较相邻的两个书,如果前面的比
# 后面的大,那么交换两个数,关键点在于,一次循环之后,
# 最大值必然放到最后一个去了,那么我men第二次循环的次数就
# 少了一个,如同程序所看。直到循环结束。冒泡排序是一种
# 稳定的排序
# numbs=[1,3,4,2]
numbs=[3,1,4,2,33,5,8,42,5,41,7,6,6,12,134,44,6,9,1,2,3,2,1]
print("冒泡排序结果:")
print(bubble_sort(numbs))
def selection_sort(numbs):
for i in range(len(numbs)-1):
min =numbs[i]
for j in range (i+1,len(numbs)-1):
if numbs[j]<min:
numbs[j],min=min,numbs[j]
return numbs
##选择排序的思路:取第一个值为最小值,然后遍历后面所有值
#如果碰到更小值就让min为这个更小的,一次遍历后,找到最小值
#和第一个位置元素互换位置,第二次,从第二个元素开始,一样操作,
#直到整个列表遍历。时间复杂度(O(n^2))
print("选择排序结果:")
print(selection_sort(numbs))
def insertion_sort(numbs):
for i in range(1,len(numbs)-1):
for j in range(0,i):
if numbs[i]<numbs[j]:
numbs[j],numbs[i]=numbs[i],numbs[j]
return numbs
print("插入排序结果:")
print(insertion_sort(numbs))
#插入排序的思想是:
#从第一个元素开始,该元素可以认为已经被排序;
#取出下一个元素,在已经排序的元素序列中从后向前扫描;
#如果该元素(已排序)大于新元素,将该元素移到下一位置;
#重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
#将新元素插入到该位置后;
#重复步骤2~5。
def quick_sort(numbs):
pass
def merge_sort(list1,list2):
list3=[]
i=0
j=0
# for i in range(len(list1)):
# for j in range(len(list2)):
while ((i+j)<(len(list1)+len(list2)-1)):
if list1[i]<list2[j]:
list3.append(list1[i])
i=i+1
else:
list3.append(list2[j])
j=j+1
return list3
list1=[1,3,4,5,6,10]
list2=[2,5,8,12]
print("归并排序结果:")
print(merge_sort(list1,list2))
quick_sort = lambda array: array if len(array) <= 1 else quick_sort([item for item in array[1:] if item <= array[0]]) + [array[0]] + quick_sort([item for item in array[1:] if item > array[0]])
print("快速排序结果:")
print(quick_sort(numbs))
#这一种排序是递归加二分的思想
a=map(lambda x: "pic_"+str(x)+".png",range(9))
b=[ "pic_%d.png" % (i) for i in range(20)]
print(b) |
9238816b49a3cfaf29a77679b877f95ce476d981 | Aries5522/daily | /2021届秋招/leetcode/排序/各种排序.py | 1,144 | 4.09375 | 4 | def merge_sort(list0):
import math
if len(list0)<2:
return list0
mid=math.floor(len(list0)/2)
left,right=list0[0:mid],list0[mid:]
return merge(merge_sort(left),merge_sort(right))
def merge(list1,list2):
list3=[]
while list1!=[] and list2!=[]:
if list1[0]<list2[0]:
list3.append(list1.pop(0))
else:
list3.append(list2.pop(0))
while list1!=[]:
list3.append(list1.pop(0))
while list2!=[]:
list3.append(list2.pop(0))
return list3
numbs=[3,1,4,2,33,5,8,42,5,41,7,6,6,12,134,44,6,9,1,2,3,2,1]
print("归并结果为:{}".format(merge_sort(numbs)))
quick_sort = lambda array: array if len(array) <= 1 else \
quick_sort([item for item in array[1:] if item <= array[0]]) + \
[array[0]] + quick_sort([item for item in array[1:] if item > array[0]])
def quick(array):
if len(array)<=1:
return array
else:
left=[item for item in array[1:] if item<=array[0]]
right=[item for item in array[1:] if item>array[0]]
return quick(left)+[array[0]]+quick(right)
print("快排结果为:{}".format(quick(numbs))) |
b0b07b894931ec3d9caabfd3d7cd3adc194ba972 | Aries5522/daily | /2021届秋招/leetcode/面试真题/美团/美团3.py | 1,016 | 3.5 | 4 | def union_find(nodes, edges):
father = [0] * len(nodes) # 记录父节点
for node in nodes: # 初始化为本身
father[node] = node
for edge in edges: # 标记父节点
head = edge[0]
tail = edge[1]
father[tail] = head
for node in nodes:
while True: # 循环,直到找到根节点
father_of_node = father[node]
if father_of_node != father[father_of_node]:
father[node] = father[father_of_node]
else: # 如果该节点的父节点与其爷爷节点相同,
break # 则说明找到了根节点
L = {}
for i, f in enumerate(father):
L[f] = []
for i, f in enumerate(father):
L[f].append(i)
return L
import sys
n, m = map(int, sys.stdin.readline().split())
data=[]
node=set()
for _ in range(m):
a,b=map(int, sys.stdin.readline().split())
data.append([a,b])
node.add(a)
node.add(b)
res=union_find(node,data)
print(len(res))
print(res) |
e61ae13b383db473ce0b6bd1603ad374bfdb3eb0 | Aries5522/daily | /2021届秋招/leetcode/二分查找/二分查找.py | 734 | 3.953125 | 4 | """
二分查找模板:
[l, r) 左闭右开
def binary_search(l, r):
while l < r:
m = l + (r - l) // 2
if f(m): # 判断找了没有,optional
return m
if g(m):
r = m # new range [l, m)
else:
l = m + 1 # new range [m+1, r)
return l # or not found
"""
"""
完全平方
"""
class Solution:
def mySqrt(self, x: int) -> int:
# if x==0:return 0
l,r=0,x+1 ###因为输出空间可能为x
while l<r:
mid=l+(r-l)//2
if mid**2==x:
return mid
if mid**2<x:
l=mid+1
else:
r=mid
return l-1
print(Solution().mySqrt(0)) |
f93c5949f051aa1e1a8be47e98d1796a97eeb088 | Aries5522/daily | /2021届秋招/leetcode/DFS/字符串排列.py | 1,717 | 3.6875 | 4 | """
一般来说做不出来 感觉
dfs做法
交换两者顺序
确定搜索
判断搜索终止条件
x到倒数第二位就终止
因为最后一位确定了
如果不终止的话就
跳下一位
一直到跳出为止然后开始回溯
"""
# from typing import List
#
#
# class Solution:
# def permutation(self, s: str) -> List[str]:
# res = []
# c = list(s)
#
# def dfs(x):
# if x == len(c) - 1:
# res.append("".join(c))
# else:
# dict = set()
# for i in range(x, len(c)):
# if c[i] in dict:
# continue
# else:
# dict.add(c[i])
# c[i], c[x] = c[x], c[i]
# dfs(x + 1)
# c[i], c[x] = c[x], c[i]
#
# dfs(0)
# return res
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
if not ss:
return []
ss = "".join(sorted(list(ss)))
res = []
n = len(ss)
record = [0] * n
def dfs(lenth, record, path):
if lenth == n:
res.append(path)
return
for i in range(n):
if record[i]==0:
if i != 0 and ss[i]== ss[i - 1] and record[i - 1]: ##代表当前字母和前面字母一样,并且前面的字母已经被用了,这里就剪枝
continue
record[i] = 1
dfs(lenth + 1, record, path + ss[i])
record[i] = 0
dfs(0, record, "")
return res
print(Solution().Permutation("aaAb"))
|
291516016fdb34d23458247953670fcd2def6a85 | Aries5522/daily | /2021届秋招/leetcode/栈/队列最大值.py | 1,182 | 3.6875 | 4 |
'''
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
'''
##定义一个辅助栈实现,空间换时间,这个辅助栈单调递减.进来一个教大的,那么前面那个小的就都要走.
"""
https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
"""
class MaxQueue:
def __init__(self):
self.res = []
self.temp = []
def max_value(self) -> int:
if self.res == []: return -1
return self.temp[0]
def push_back(self, value: int) -> None:
self.res.append(value)
if self.temp == []:
self.temp.append(value)
else:
while self.temp != []:
if value > self.temp[-1]:
self.temp.pop(-1)
else:
break
self.temp.append(value)
def pop_front(self) -> int:
if self.res != []:
if self.res[0] == self.temp[0]:
self.temp.pop(0)
else:
return -1
return self.res.pop(0)
|
c86cac8eb810c6d817d150b21d40f8a24d07e81b | Aries5522/daily | /2021届秋招/leetcode/DFS/回溯全排列.py | 978 | 3.828125 | 4 | """
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择
作者:labuladong
链接:https://leetcode-cn.com/problems/permutations/solution/hui-su-suan-fa-xiang-jie-by-labuladong-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
"""
class Solution:
def permute(self, nums):
n=len(nums)
if not nums:
return []
res=[]
def traceback(first=0):
if first==n:
res.append(nums[:])
for i in range(first,n):
nums[i],nums[first]=nums[first],nums[i]
traceback(first+1)
nums[i],nums[first]=nums[first],nums[i]
traceback()
return res
print(Solution().permute([1,2,3])) |
be7db40d0e8a04568fa83556e047f116127dd153 | Aries5522/daily | /CPP/cppworkspace/ieee_test3.py | 299 | 3.5 | 4 | import numpy
import scipy
A=[3,2]
S=[3,1,5]
# A = list(map(int, input().rstrip().split()))
# S = list(map(int, input().rstrip().split()))
S.sort()
for i in range(len(S)):
for j in range(len(A)):
if S[i] < A[j]:
A.insert(j,S[i])
break
for i in A:
print(i) |
7ea27b712e9f3bf4faedd2dbf71d2dd720123209 | Aries5522/daily | /2021届秋招/leetcode/拓扑排序/合并区间.py | 292 | 3.5625 | 4 | data = [[1, 'B'], [1, 'A'], [2, 'A'], [0, 'B'], [0, 'a']]
#利用参数key来规定排序的规则
result = sorted(data,key=lambda x:(x[0]))
print(data) #结果为 [(1, 'B'), (1, 'A'), (2, 'A'), (0, 'B'), (0, 'a')]
print(result) #结果为 [(0, 'a'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A')]
|
e31599e77ca4514f91bccb5f26ad32293fe6dfbb | os-utep-master/python-intro-djr2344 | /w_cc.py | 4,317 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 21:23:58 2019
@author: Derek
Sources Cited:
method for removing non-alphanumeric characters (lines 20 -> 22):
<https://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python>
"""
import sys # command line arguments
import re # regular expression tools
import os # checking if file exists
import subprocess # executing program
import string
from sys import exit
def ExtractAlphanumeric(InputString):
from string import ascii_letters, digits
return "".join([ch for ch in InputString if ch in (ascii_letters + digits + ' ')])
# set input and output files
if len(sys.argv) is not 4:
print("Correct usage: <input text file> <output file>")
for argg in sys.argv:
print(argg)
sys.exit()
for argg in sys.argv:
print(argg)
textFname = sys.argv[1]
outputFname = sys.argv[2]
inputFname = sys.argv[3]
#make sure text files exist
if not os.path.exists(textFname):
print ("text file input %s doesn't exist! Exiting" % textFname)
sys.exit()
#make sure output file exists
if not os.path.exists(outputFname):
print ("wordCount output file %s doesn't exist! Exiting" % outputFname)
sys.exit()
# attempt to open input file
with open(textFname, 'r') as inputFile:
wordlist = []
full_tx = ""
for line in inputFile:
# get rid of newline characters
line = line.strip()
newline = ""
newline = line.replace('-', ' ')
newline = newline.replace('\'', ' ')
#get rid of non-alpha chars
newline = ExtractAlphanumeric(newline)
#compile lines to single string
full_tx = full_tx + " " + newline
#split string for list of words
word_list = re.split('[ \t]', full_tx.lower())
wordfreq = []
wordfreq = [str(word_list.count(w)) for w in word_list] #get word counts
results = set( zip(word_list, wordfreq) ) #create the sets of (word, word-count)
s_results = sorted(results,key= lambda x: x[0]) #sort set for descending order
empt = 0
with open(outputFname, 'w') as outputFile:
for r in s_results:
if (empt != 0): #skip first set that references junk
ent = ""
ent = str(r[0]) + " " + str(r[1])
outputFile.write(str(ent)) #write line to output file
outputFile.write('\n')
empt = empt + 1
#stats
passed = True
faults = 0
words = 0
#master dictionary
master = {}
#dictionary to test
test = {}
# attempt to open input file
with open(inputFname, 'r') as inputFile:
for line in inputFile:
# get rid of newline characters
line = line.strip()
# split line on whitespace and punctuation
word = re.split('[ \t]', line)
if len(word) != 2:
print ("Badly formatted line, exiting. Bad line:\n %s" % line)
exit()
master[word[0]] = int(word[1])
words += 1
with open(outputFname, 'r') as outputFile:
lastWord = ""
for line in outputFile:
# get rid of newline characters
line = line.strip()
# split line on whitespace and punctuation
word = re.split('[ \t]', line)
if len(word) != 2:
print ("Badly formatted line, exiting. Bad line:\n %s" % line)
exit()
if word[0] <= lastWord:
print ("Misordered words: %s appears before %s" % (lastWord, word[0]))
passed = False
faults += 1
test[word[0]] = int(word[1])
lastWord = word[0]
# see if test is missing words from master
for key in master:
if key not in test:
print ("Missing word in test file: %s" % key)
passed = False
faults += 1
# see if test has words master doesn't have
for key in test:
if key not in master:
print ("Extra word in test file: %s" % key)
passed = False
faults += 1
# see if counts match
for key in master:
if key in test and test[key] != master[key]:
print ("Count mismatch for %s, should be %s value is %s" % (key, master[key], test[key]))
passed = False
faults += 1
if passed:
print ("Passed!")
else:
print ("Error rate {0:.3f}%".format(faults * 100.0 / words))
print ("Failed!") |
a417c87eb913067a78ed822d16ca440811619258 | PanoStiv/algorithms | /Linked list (Συνδεδεμένη λίστα)/ordered_list_example.py | 1,790 | 3.875 | 4 | from linked_list import LinkedList
from random import randrange
class OrderedList(LinkedList):
def __init__(self):
super().__init__()
def insert(self, data):
if self.empty():
self.insert_start(data)
elif data < self.head.data:
self.insert_start(data)
else:
prev = self.head
cur = self.head.next
while cur is not None:
if data < cur.data:
self.insert_after(prev,data)
return
else:
prev = cur
cur = cur.next
else:
self.insert_after(prev, data)
def delete(self, data):
if self.empty():
return None
elif self.head.data == data:
return self.delete_start()
else:
prev = self.head
cur = self.head.next
while cur is not None:
if data == cur.data:
return self.delete_after(prev)
else:
prev = cur
cur = cur.next
else:
return None
#example
l = LinkedList()
for i in range(4,-1,-1):
l.insert_start(i)
print(l)
l.insert_after(l.head.next.next, 5)
print(l)
print(l.delete_start())
print(l)
print(l.delete_after(l.head.next))
print(l)
print("-" * 20)
ol = OrderedList()
for i in range(50):
val = randrange(10)
if i%2 == 0:
ol.insert(val)
print(f"inserted {val}.")
else:
ret = ol.delete(val)
if ret is None:
print(f"Deleting... {val} not found!")
else:
print(f"Deleted {val}")
print(ol)
|
c2c47a482c392499be6f990faaf3407503edbb73 | PanoStiv/algorithms | /Linked list (Συνδεδεμένη λίστα)/linked_list.py | 1,053 | 3.96875 | 4 | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def empty(self):
return self.head is None
def insert_start(self, data):
n = Node(data)
n.next = self.head
self.head = n
def insert_after(self, prev, data):
n = Node(data)
n.next = prev.next
prev.next = n
def delete_start(self):
if self.empty():
return None
else:
c = self.head
self.head = self.head.next
return c.data
def delete_after(self, prev):
if prev.next is None:
return None
else:
c = prev.next
prev.next = c.next
return c.data
def __str__(self):
p = self.head
st = ""
while p is not None:
st += str(p.data) + "-->"
p = p.next
st += "."
return st
|
9a29246f53a94dd803b6c30cbec5e2837557f3bd | mirceadino/Blackjack | /cards/Deck.py | 2,385 | 3.703125 | 4 | from random import shuffle
from cards.Card import Card
from game.Exceptions import BlackjackException
class Deck():
'''
Class used for handling a deck of cards.
'''
def __init__(self):
'''
Constructor for a Deck.
'''
self.pack = [] # pack = all cards of the deck
self.stack = [] # stack = remaining cards of the deck, face down
self.popped = [] # popped = cards that were drawn
self.__generate()
def __generate(self):
for i, suit in [(0, "clubs"), (1, "diams"), (2, "hearts"), (3, "spades")]:
if i in [0, 3]: color="black"
else: color="red"
for number in range(2, 11):
name = str(number) + " " + suit
value = number
url = "{0}{1}.png".format(i, number)
text = "{0}<font color={1}>&{2};</font>".format(number, color, suit)
card = Card(name, value, url, text, color)
self.pack.append(card)
for number in ['J', 'Q', 'K']:
name = str(number) + " " + suit
value = 10
url = "{0}{1}.png".format(i, number)
text = "{0}<font color={1}>&{2};</font>".format(number, color, suit)
card = Card(name, value, url, text, color)
self.pack.append(card)
for number in ['A']:
name = str(number) + " " + suit
value = 11
url = "{0}{1}.png".format(i, number)
text = "{0}<font color={1}>&{2};</font>".format(number, color, suit)
card = Card(name, value, url, text, color)
self.pack.append(card)
def shuffle(self):
'''
Puts all the pack in the game and shuffles it.
'''
self.stack[:] = self.pack
self.popped[:] = []
self.reshuffle()
def reshuffle(self):
'''
Shuffles the stack.
'''
shuffle(self.stack)
def draw(self):
'''
Draws a card from the stack.
:return: Card - the card from the top of the stack is popped
:raises BlackjackException: if all cards have been popped and no cards are left in the stack
'''
if len(self.stack) == 0:
raise BlackjackException("No cards left.")
return self.stack.pop() |
5bad2f32074ac303626daaf7d4e2e0f931b31bb1 | LikhithShankarPrithvi/College_codes | /python/problem.py | 259 | 3.59375 | 4 | x=int(input("enter your number"))
a=[]
n=0
temp=x
while x!=0:
x=x//10
n=n+1
print("your number length=",n)
x=temp
while x!=0:
z=x%10
a.append(z)
x=x//10
a.reverse()
for i in range(0,n):
print(a)
a[i]=0
|
86eda09e9afb6230ab6aab95f91a1d740682e69d | LikhithShankarPrithvi/College_codes | /python/problem1.py | 252 | 3.828125 | 4 | x=int(input("enter your number"))
n=0
temp=x
while x!=0:
x=x//10
n=n+1
print("your number length=",n)
x=temp
for i in range(0,n):
for j in range(0,i):
print(end=" ")
print(x)
x=x%(10**(n-i-1))
|
f84916da1481dc054dc0219cb0943f41309e4bf6 | jayse45/alx-higher_level_programming-1 | /0x06-python-classes/1-square.py | 192 | 3.765625 | 4 | #!/usr/bin/python3
"""class square defined by size"""
class Square:
"""private attribute instance size"""
def __init__(self, size):
"""new size"""
self.__size = size
|
1c6393f8a3b3011ac59a5d3d282b6731eadf6fcf | Arsen339/Skillbox-functional-programming | /practice2.py | 1,441 | 3.75 | 4 | ops = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
"//": lambda x, y: x // y,
"%": lambda x, y: x % y
}
total = 0
def calc(line):
print(f"Read line {line}", flush=True) # flush-вывод сразу после команды print без буферизации
operand1, operation, operand2 = line.split(" ") # разбиение на пробелы
if operation in ops:
func = ops[operation]
value = func(int(operand1), int(operand2))
else:
print(f"Unknown operand {operation}")
value = None
print("value is ", value)
return value
# Упростим код используя генератор
def get_lines(file_name):
with open(file_name, 'r') as ff:
for line in ff:
line = line[:-1]
yield line
for line in get_lines(file_name="calc.txt"):
try:
total += calc(line)
except ZeroDivisionError as zde:
print(f"На ноль делить запрещено! {zde}")
except ValueError as exc:
if 'unpack' in exc.args[0]:
print(f"Не хватает операндов {exc}")
else:
print(f"Не могу преобразовать к целому {exc}")
except TypeError as tex:
print(f"Ошибка типа {tex}")
print(f"Total {total}") |
6e35b4dcb3cf64c0d7a2df0f43bbdaab476f8002 | Aakash-Dogra/Mortality-Rate-Analysis-US | /Mortality_Rate_Analysis.py | 37,269 | 3.984375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="darkgrid", color_codes=True)
def birth_death_ratio(df, df2):
"""
In this function, we have performed analysis in terms of race or ethnicity of an individual. This analysis is
further done on basis of poverty and birth to death ratio in a particular county.
This analysis is further bifurcated on county wise and state wise. The function returns a dataframe that is used
to provide a detailed graphical representation.
:param df: We are passing the demographics data-frame for the analysis.
:param df2: We are passing the birth_death_measure data-frame for the analysis.
:return: returns two data-frames consisting of analysis based on the race or ethnicity and grouped by county and
state names.
>>> df = pd.read_csv("Testfile_DEMO.csv")
>>> df2 = pd.read_csv("Testfile_MOBAD.csv")
>>> df3 , df4 = birth_death_ratio(df,df2)
>>> print((df3[["CHSI_County_Name","Poverty","birth_death_ratio"]]).head(5))
CHSI_County_Name Poverty birth_death_ratio
0 Adams 11.2 102.618057
1 Alexander 22.2 94.186047
2 Bond 10.8 89.892802
3 Boone 7.7 48.572345
4 Brown 11.6 101.206897
>>> print(df4[["CHSI_State_Name","Poverty","Total_Deaths"]])
CHSI_State_Name Poverty Total_Deaths
0 Illinois 10.74 4001.82
"""
df1 = df[
["CHSI_County_Name", "CHSI_State_Name", "White", "Black", "Native_American", "Asian", "Hispanic", "Poverty",
"Population_Size"]]
df_1 = df1[df1["Poverty"] >= 0].copy()
df_1['Others'] = df_1['Native_American'] + df_1['Asian']
df_1 = df_1.drop(["Native_American", "Asian"], axis=1)
birth_death = df2[["CHSI_County_Name", "CHSI_State_Name", "Total_Births", "Total_Deaths"]].copy()
birth_death = birth_death.loc[(birth_death["Total_Births"] >= 0) & (birth_death["Total_Deaths"] >= 0)]
birth_death["birth_death_ratio"] = birth_death['Total_Deaths'] / birth_death['Total_Births'] * 100
data = pd.merge(df_1, birth_death, on=['CHSI_County_Name', 'CHSI_State_Name'])
pd.set_option('display.max_columns', None)
# print(data.sort_values(by = 'Poverty',ascending=False)) #jadhgjsagvjhsajvksbdahfvhsjdak
dfa = df_1.groupby(["CHSI_State_Name"], as_index=False).agg(
{"White": "mean", "Black": "mean", "Others": "mean", "Hispanic": "mean", "Poverty": "mean"})
dfb = birth_death.groupby(["CHSI_State_Name"], as_index=False).agg({"Total_Births": "mean", "Total_Deaths": "mean"})
final_df = pd.merge(dfa, dfb, on="CHSI_State_Name")
final_df = final_df.round(2)
final_df = final_df.sort_values(by=["Poverty"], ascending=False)
return data, final_df
def plot_birth_death_ratio(x, y):
"""
This function is used to provide a graphical representation of the analysis done in the previous function, i.e.
birth_death_ratio().
:param x: the data-frame on used to complete the plot
:param y: data-frame used to create the bar graph plot
:return: Returns the plot for the dataframes and comparison done
"""
df_1, df_2 = birth_death_ratio(x, y)
plt.subplot(2, 1, 1)
plt.scatter(x=df_1['Poverty'], y=df_1["White"], color="DarkGreen", label="White")
plt.scatter(x=df_1['Poverty'], y=df_1["Black"], color="DarkBlue", label="Black")
plt.scatter(x=df_1['Poverty'], y=df_1["Others"], color="Red", label="Others")
plt.scatter(x=df_1['Poverty'], y=df_1["Hispanic"], color="Orange", label="Hispanic")
plt.xlabel("Poverty")
plt.ylabel("Race-wise Pop")
plt.legend(loc="upper right", fontsize="x-small")
plt.title("County & Race-wise Poverty")
plt.grid(linewidth=0.5, color="grey")
plt.subplot(2, 1, 2)
plt.scatter(x=df_2['Poverty'], y=df_2["White"], color="DarkGreen", label="White")
plt.scatter(x=df_2['Poverty'], y=df_2["Black"], color="DarkBlue", label="Black")
plt.scatter(x=df_2['Poverty'], y=df_2["Others"], color="Red", label="Others")
plt.scatter(x=df_2['Poverty'], y=df_2["Hispanic"], color="Orange", label="Hispanic")
plt.xlabel("Poverty")
plt.ylabel("Race-wise Pop")
plt.legend(loc="upper right", fontsize="x-small")
plt.grid(linewidth=0.5, color="grey")
plt.title("State & Race-wise Poverty")
plt.show()
def population_poverty(df):
"""
In this function, we have performed analysis of poverty and population for the given dataset and the data is
further divided on state names. The end result of this function gives us distribution where we can relate how population is
affected by the poverty value of a particular county. This function gives us idea of the population to poverty
ratio.
:param df: We are passing the demographics data-frame for the analysis
:return: returns the fata-frame with the analysis.
>>> df1 = pd.read_csv("Testfile_DEMO.csv")
>>> df2 = population_poverty(df1)
>>> print(df2)
CHSI_State_Name Population_Size Poverty Pop_Poverty_ratio
0 Illinois 125131.09 10.74 11646.47
"""
df1 = df[["CHSI_State_Name", "Poverty", "Population_Size"]]
df1 = df1[df1["Poverty"] >= 0]
df_2 = df1.groupby(["CHSI_State_Name"], as_index=False).agg({"Population_Size": "mean", "Poverty": "mean"})
df_2["Pop_Poverty_ratio"] = df_2["Population_Size"] / df_2["Poverty"]
df_2 = df_2.sort_values(by=["Pop_Poverty_ratio"], ascending=True)
df_2 = df_2.round(2)
return df_2
def death_factors(df1, df2):
"""
In this function, we have performed analysis to demonstrate how the deaths among the different races or
different ethnic groups in United States. The data is sorted on basis of highest death rate. The final data
is then used to create plots for demonstrating the same.
:param df1: We are passing the demographics data-frame for the analysis
:param df2: We are passing the birth_death_measure data-frame for the analysis
:return: The function returns two data-frames, the actual analysis and other data-frame used to create plots to
demonstrate the analysis.
>>> df1 = pd.read_csv("Testfile_DEMO.csv")
>>> df2 = pd.read_csv("Testfile_MOBAD.csv")
>>> df3 , df4, df5 = death_factors(df1, df2)
>>> print(df4[["CHSI_State_Name", "Total_Deaths"]])
CHSI_State_Name Total_Deaths
0 Illinois 4002.0
"""
df = df1[["CHSI_State_Name", "White", "Black", "Native_American", "Asian", "Hispanic"]]
df_2 = df2[["CHSI_State_Name", "Total_Deaths"]]
df_1 = df.copy()
df_3 = df_2.copy()
df_1["Others"] = df_1['Native_American'] + df_1['Asian']
df_1 = df_1.drop(["Native_American", "Asian"], axis=1)
population = df_1.groupby(["CHSI_State_Name"], as_index=False).agg(
{"Black": "mean", "White": "mean", "Others": "mean", "Hispanic": "mean"})
population = population.round(2)
deaths = df_2.groupby(["CHSI_State_Name"], as_index=False).agg({"Total_Deaths": "mean"})
deaths = deaths.round(0)
pop_deaths = pd.merge(population, deaths, on="CHSI_State_Name")
pop_deaths = pop_deaths.sort_values(by=["Total_Deaths"], ascending=False)
first_10 = pop_deaths.head(10)
last_10 = pop_deaths.tail(10)
# print(first_20)
return pop_deaths, first_10, last_10
def plot_death_factors(x, y):
"""
This function is used to plot and demonstrate the analysis done in the previous function, i.e. death_factors.
:param x: the first data-frame used, i.e. we are passing the demographics data-frame for the analysis
:param y: the second data-frame used, i.e. we are passing the birth_death_measure data-frame for the analysis
:return: the function plots the resultant data-frame of the death_factors function.
"""
pop_deaths, first_10, last_10 = death_factors(x, y)
p1 = plt.bar(first_10["CHSI_State_Name"], first_10["White"], width=1, color="DarkGreen", edgecolor="black",
label="White")
p2 = plt.bar(first_10["CHSI_State_Name"], first_10["Black"], width=1, bottom=first_10["White"], color="Blue",
edgecolor="black", label="Black")
p3 = plt.bar(first_10["CHSI_State_Name"], first_10["Others"], width=1,
bottom=np.array(first_10["White"]) + np.array(first_10["Black"]),
color="Red", edgecolor="black", label="Others")
p4 = plt.bar(first_10["CHSI_State_Name"], first_10["Hispanic"], width=1,
bottom=np.array(first_10["White"]) + np.array(first_10["Black"]) + np.array(first_10["Others"]),
color="Orange", edgecolor="black", label="Hispanic")
r1 = plt.bar(last_10["CHSI_State_Name"], last_10["White"], width=1, color="DarkGreen", edgecolor="black")
r2 = plt.bar(last_10["CHSI_State_Name"], last_10["Black"], width=1, bottom=last_10["White"], color="Blue",
edgecolor="black")
r3 = plt.bar(last_10["CHSI_State_Name"], last_10["Others"], width=1,
bottom=np.array(last_10["White"]) + np.array(last_10["Black"]),
color="Red", edgecolor="black")
r4 = plt.bar(last_10["CHSI_State_Name"], last_10["Hispanic"], width=1,
bottom=np.array(last_10["White"]) + np.array(last_10["Black"]) + np.array(last_10["Others"]),
color="Orange", edgecolor="black")
plt.xlabel("Top & Last 10 States")
plt.ylabel("Race-wise Pop percent")
plt.legend(loc="upper right", fontsize="x-small")
plt.xticks(rotation="vertical")
plt.grid(linewidth=0.5, color="grey")
plt.title("Top 10 & last 10 states ")
plt.show()
def merge_dataframes(dataframe1, dataframe2, dataframe3, dataframe4):
"""
In this function, we are combining the required data obtained by various data-frames and merged them into different data-frames, according to
the required conditions.
:param dataframe1: We are passing the risk_factors dataframe for the analysis
:param dataframe2: We are passing the demographics dataframe for the analysis
:param dataframe3: We are passing the birth_death_measure dataframe for the analysis
:param dataframe4: We are passing the vulnerable_pops dataframe for the analysis
:return: df_demo_risk_bd_unemp as the final dataframe to be used in the future analysis
"""
df_demo = dataframe2[["CHSI_County_Name", "CHSI_State_Name", "Poverty", "Population_Size"]]
df_riskfactor = dataframe1[
["CHSI_County_Name", "CHSI_State_Name", "No_Exercise", "Obesity", "High_Blood_Pres", "Few_Fruit_Veg", "Smoker",
"Diabetes", "Uninsured", "Elderly_Medicare", "Disabled_Medicare", "Prim_Care_Phys_Rate"]]
df_measurebd = dataframe3[
["State_FIPS_Code", "County_FIPS_Code", "CHSI_County_Name", "CHSI_State_Name", "Late_Care", "Infant_Mortality",
"Total_Deaths", "Total_Births"]]
df_unemp = dataframe4[["State_FIPS_Code", "County_FIPS_Code", "CHSI_County_Name", "CHSI_State_Name", "Unemployed"]]
df_demo_risk = pd.merge(df_demo, df_riskfactor, on=['CHSI_State_Name', 'CHSI_County_Name'])
df_demo_risk_bd = pd.merge(df_demo_risk, df_measurebd, on=['CHSI_State_Name', 'CHSI_County_Name'])
df_demo_risk_bd_unemp = pd.merge(df_demo_risk_bd, df_unemp, on=['CHSI_State_Name', 'CHSI_County_Name'])
pd.set_option('display.max_columns', None)
return df_demo_risk_bd_unemp
def analysis_1(df):
"""
In this function we are analysing the co relation between Poverty , Total_deaths and various risk factors like Poverty", "Total_Deaths", "No_Exercise", "Obesity",
"Few_Fruit_Veg", "Smoker", "Diabetes", "High_Blood_Pres" ,etc. These risk factors are either by choice or circumstantial.
Also , in addition to that we have analyzed the co-relation between Poverty , Total_deaths and various factors related to medical care provided.
:param df: We are passing the result dataframe for the analysis which is obtained from merge_dataframes function.
:return:returns the data frame with the desired analysis
"""
df_final_1 = df.replace([-1111, -1111.1, -1, -2222.2, -2222, -2], np.nan)
df_1 = df_final_1[
["CHSI_County_Name", "CHSI_State_Name", "Population_Size", "Poverty", "Total_Deaths", "No_Exercise", "Obesity",
"Few_Fruit_Veg", "Smoker", "Diabetes", "High_Blood_Pres"]]
df_1 = df_1.groupby(["CHSI_State_Name"], as_index=False)[
"Poverty", "Total_Deaths", "Population_Size", "No_Exercise", "Obesity", "Few_Fruit_Veg", "Smoker", "Diabetes", "High_Blood_Pres"].mean()
df_1 = df_1.sort_values(by=["Poverty", "Total_Deaths"], ascending=False)
df_1["Mortality_Rate"] = df_1["Total_Deaths"] / df_1["Population_Size"] * 100
df_1 = df_1.drop(["Total_Deaths", "Population_Size"], axis=1)
df_1 = df_1.round(2)
# print(df_1.head(10))
df_2 = df_final_1[
["CHSI_County_Name", "CHSI_State_Name", "Population_Size", "Poverty", "Uninsured", "Elderly_Medicare",
"Disabled_Medicare", "Late_Care", "Prim_Care_Phys_Rate", "Total_Deaths"]]
df_2 = df_2.groupby(["CHSI_State_Name"], as_index=False)[
"Population_Size", "Poverty", "Uninsured", "Elderly_Medicare", "Disabled_Medicare", "Late_Care", "Prim_Care_Phys_Rate", "Total_Deaths"].mean()
df_2 = df_2.sort_values(by=["Poverty", "Total_Deaths"], ascending=False)
df_2["Mortality_Rate"] = df_2["Total_Deaths"] / df_2["Population_Size"] * 100
df_2 = df_2.drop(["Total_Deaths", "Population_Size"], axis=1)
df_2 = df_2.round(2)
pd.set_option('display.max_columns', None)
return df_1, df_2
def plot_analysis_1(df):
"""
In this function, we are trying to plot between the Poverty on basis of various factors and population size of a
particular county.
:param df: thee dataframe used to create the plot
:return: returns the plot for the analysis
"""
df_1, df_2 = analysis_1(df)
df_2 = df_2.dropna()
sns.heatmap(df_2.corr(), xticklabels=df_2.corr().columns, yticklabels=df_2.corr().columns, cmap='RdYlGn', center=0,
annot=True)
plt.title('Correlogram of Poverty', fontsize=12)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.show()
# print(df_2.head(10))
def other_risk_factors(df1, df2):
"""
in this function, we are analysing other risk factors like "Premature", "Under_18", "Over_40", "Late_Care"
and sort the values based on Poverty and Birth Death ratio.
It shows that counties with high poverty rate generally have high "Premature", "Under_18", "Over_40", "Late_Care" ratio.
:param df1: We are passing the demographics data-frame for the analysis
:param df2: We are passing the birth_death_measure data-frame for the analysis
:return: The functions returns the analysed data in the form of a data-frame, which is used to create plots to
demonstrate the analysis.
>>> df1 = pd.read_csv("Testfile_MOBAD.csv")
>>> df2 = pd.read_csv("Testfile_DEMO.csv")
>>> df3 = other_risk_factors(df1,df2)
>>> print((df3[["CHSI_County_Name", "Poverty"]].head(10)))
CHSI_County_Name Poverty
1 Alexander 22.2
76 Pulaski 19.8
38 Jackson 19.3
54 McDonough 15.9
29 Gallatin 15.8
82 Saline 15.0
34 Hardin 14.8
27 Franklin 14.8
81 St. Clair 14.5
15 Cook 14.5
"""
df_1 = df1[["CHSI_County_Name", "CHSI_State_Name", "LBW", "VLBW", "Premature", "Under_18", "Over_40", "Late_Care",
"Total_Births", "Total_Deaths"]]
df_1 = df_1.replace([-1111.1, -2222.2], np.nan)
df_1["Birth_Death_Ratio"] = df_1["Total_Deaths"] / df_1["Total_Births"] * 100
df_1["LBW_VLBW"] = df_1["LBW"] + df_1["VLBW"]
df_1 = df_1.drop(["Total_Deaths", "Total_Births", "LBW", "VLBW"], axis=1)
df_2 = df2[["CHSI_County_Name", "CHSI_State_Name", "Poverty", "Population_Size"]]
df_2 = df_2.replace([-1111.1, -2222.2], np.nan)
df_3 = pd.merge(df_1, df_2, on=["CHSI_County_Name", "CHSI_State_Name"])
df_3 = df_3.sort_values(by=["Poverty", "Birth_Death_Ratio"], ascending=[False, False])
# print(df_3.head(20))
# print(df_3.tail(20))
return df_3
def plot_other_risk_factors(a, b):
"""
In this function, we are trying to plot the factors responsible for mortality rates on basis of county.
:param a: data frame used to create the plot
:param b: date frame used to create the plot
:return: the function returns the plot of the previous function.
"""
df = other_risk_factors(a, b)
df_4 = df.groupby(["CHSI_State_Name"], as_index=False)[
"Premature", "Under_18", "Over_40", "Late_Care", "LBW_VLBW", "Birth_Death_Ratio", "Poverty"].mean()
df_4 = df_4.sort_values(by=["Poverty", "Birth_Death_Ratio"], ascending=[False, False])
df_4 = df_4.round(2)
# print(df_4.head(10))
# print(df_4.tail(10))
df_5 = df_4.head(10)
df_6 = df_4.tail(10)
# print(df_5)
# print(df_6)
df_7 = pd.concat([df_5, df_6])
# print(df_7)
plt.subplot(2, 2, 1)
plt.bar(df_7["CHSI_State_Name"], df_7["Poverty"])
plt.ylabel("State-wise Poverty Distribution")
plt.xticks([])
plt.subplot(2, 2, 3)
plt.bar(df_7["CHSI_State_Name"], df_7["Under_18"])
plt.ylabel("Under_18_births")
plt.xticks(df_7["CHSI_State_Name"], rotation="vertical")
plt.subplot(2, 2, 2)
plt.bar(df_7["CHSI_State_Name"], df_7["Premature"])
plt.ylabel("Premature_births")
plt.xticks([])
plt.subplot(2, 2, 4)
under_18 = plt.bar(df_7["CHSI_State_Name"], df_7["Late_Care"])
plt.ylabel("Late_Care_births")
plt.xticks(df_7["CHSI_State_Name"], rotation="vertical")
plt.show()
def genetic_deaths(df1, df2):
"""
This function helps us to understand and provide information regarding the mortality rate in all the counties or
states in the United States of America based on birth defects.
The factors taken into consideration are State name and Birth defects in different ethnic groups, for every county.
This data is then calculated for each state by taking the total of all county data, for a particular state.
:param df1: Here we have provided leading causes of deaths data frame.
:param df2: Here we have provided birth_death_measure dataframe
:return: Returns the resultant data frame
>>> df1 = pd.read_csv("Testfile_LCOD.csv")
>>> df2 = pd.read_csv("Testfile_MOBAD.csv")
>>> df3 = pd.merge(df1,df2, on= ["CHSI_County_Name","CHSI_State_Name"])
>>> df3 = df3.replace(to_replace=[-9999, -2222, -2222.2, -2, -1111.1, -1111, -1], value=0)
>>> df3 = df3.groupby("CHSI_State_Name")["A_Wh_BirthDef", "A_Bl_BirthDef", "A_Ot_BirthDef", "A_Hi_BirthDef", "Total_Births"].sum()
>>> print(df3["Total_Births"])
CHSI_State_Name
Illinois 639809
Name: Total_Births, dtype: int64
"""
df = pd.merge(df1, df2, on=["CHSI_County_Name", "County_FIPS_Code", "CHSI_State_Name", "State_FIPS_Code"])
df_1 = df[['CHSI_State_Name', "A_Wh_BirthDef", "A_Bl_BirthDef", "A_Ot_BirthDef", "A_Hi_BirthDef", "Total_Births"]]
df_1 = df_1.replace(to_replace=[-9999, -2222, -2222.2, -2, -1111.1, -1111, -1], value=0)
df_1 = df_1.groupby("CHSI_State_Name")[
"A_Wh_BirthDef", "A_Bl_BirthDef", "A_Ot_BirthDef", "A_Hi_BirthDef", "Total_Births"].sum()
df_1["Total_Deaths"] = df_1["A_Wh_BirthDef"] + df_1["A_Bl_BirthDef"] + df_1["A_Ot_BirthDef"] + df_1["A_Hi_BirthDef"]
df_1["Mortality_Rate"] = (df_1["Total_Deaths"] / df_1["Total_Births"]) * 100
df_1 = df_1.drop(["Total_Deaths", "Total_Births"], axis=1)
df_1.reset_index()
df_1 = df_1.sort_values(by="Mortality_Rate", ascending=False)
pd.set_option('display.max_columns', None)
return df_1
# print(df_1.head(10))
def air_quality_death(df1, df2, df3):
"""
Here we are analysing the various factors which affect the air quality for all the states. These factors are then sorted,
and then we compare the death ratio in that particular state with respect to the values of these factors.
:param df1: We are passing the birth_death_measure dataframe for the analysis.
:param df2: We are passing the air_quality dataframe for the analysis.
:param df3: We are passing the demographics dataframe for the analysis.
:return: We are returning the final dataframe 'data_1' obtained after the analysis
>>> df1 = pd.read_csv("Testfile_MOBAD.csv")
>>> df2 = pd.read_csv("Testfile_AAQI.csv")
>>> df3 = pd.read_csv("Testfile_DEMO.csv")
>>> df4 = air_quality_death(df1,df2,df3)
>>> print((df4[["County", "Max AQI"]]).head(10))
County Max AQI
21 Tazewell 200
16 Madison 151
10 Lake 156
22 Wabash 160
0 Adams 122
1 Champaign 87
2 Clark 90
3 Cook 140
4 DuPage 110
5 Effingham 105
"""
df_3 = df3[["CHSI_County_Name", "CHSI_State_Name", "Population_Size"]]
df_1 = df1[["CHSI_County_Name", "CHSI_State_Name", "Total_Deaths"]]
df4 = pd.merge(df_1, df_3, on=["CHSI_County_Name", "CHSI_State_Name"])
df4["Mortality_Rate"] = df4["Total_Deaths"] / df4["Population_Size"] * 100
df4 = df4.drop(["Population_Size", "Total_Deaths"], axis=1)
df4 = df4.round(2)
df4.columns = ["County", "State", "Mortality_Rate"]
df4 = df4[df4["Mortality_Rate"] > 0]
(df4.sort_values(by="Mortality_Rate", ascending=True))
df_2 = df2[["County", "State", "Max AQI", "Unhealthy Days", "Very Unhealthy Days", "Hazardous Days"]]
data = pd.merge(df4, df_2, on=["County", "State"])
pd.set_option('display.max_columns', None)
data_1 = data.sort_values(by=["Hazardous Days", "Very Unhealthy Days", "Unhealthy Days"],
ascending=[False, False, False])
return data_1
def plot_air_quality_death(a, b, c):
"""
:param a: the data-frame on used to complete the plot
:param b: the data-frame on used to complete the plot
:param c: the data-frame on used to complete the plot
:return:
"""
data_1 = air_quality_death(a, b, c)
df_4 = data_1.head(15)
df_5 = data_1.tail(15)
df_6 = pd.concat([df_4, df_5])
df_6["Total_Unhealthy_days"] = df_6["Hazardous Days"] + df_6["Unhealthy Days"] + df_6["Very Unhealthy Days"]
df_6 = df_6.drop(["Hazardous Days", "Very Unhealthy Days", "Unhealthy Days"], axis=1)
sns.scatterplot(x=df_6["State"], y=df_6["Mortality_Rate"], size=df_6["Total_Unhealthy_days"], data=df_6)
plt.xticks(rotation="vertical")
plt.legend(loc="upper left", fontsize="x-small")
plt.title("")
plt.show()
def disease_pollution(df1, df2, df3, df4):
"""
We have performed the analysis on various diseases like lung cancer, breast cancer, Col_cancer_d. We check the occurences of these diseases
based on the AQI and toxic chemicals in a particular state.
:param df1: We are passing the birth_death_measure dataframe for the analysis.
:param df2: We are passing the air_quality dataframe for the analysis.
:param df3: We are passing the vulnerable_pops dataframe for the analysis.
:param df4: We are passing the demographics dataframe for the analysis.
:return: We are returning the final dataframe 'data_7' obtained after the analysis
>>> df1 = pd.read_csv("Testfile_MOBAD.csv")
>>> df2 = pd.read_csv("Testfile_AAQI.csv")
>>> df3 = pd.read_csv("Testfile_VPAEH.csv")
>>> df4 = pd.read_csv("Testfile_DEMO.csv")
>>> df5 = disease_pollution(df1,df2,df3,df4)
>>> print((df5[["County","Toxic_Chem"]].head(5)))
County Toxic_Chem
14 Peoria 31953727
3 Cook 12221689
13 Madison 11328080
12 Macon 7163343
19 Will 5328100
"""
df_1 = df1[["CHSI_County_Name", "CHSI_State_Name", "Lung_Cancer", "Brst_Cancer", "Col_Cancer"]]
df_1 = df_1[(df_1["Lung_Cancer"] > 0) & (df_1["Brst_Cancer"] > 0) & (df_1["Col_Cancer"] > 0)]
# print(df_1.sort_values(by="Brst_Cancer", ascending=True))
df_2 = df2[["County", "State", "Max AQI"]]
df_3 = df3[["CHSI_County_Name", "CHSI_State_Name", "Toxic_Chem"]]
df_3 = df_3[df_3["Toxic_Chem"] > 0]
df_4 = df4[["CHSI_County_Name", "CHSI_State_Name", "Population_Size"]]
df_5 = pd.merge(df_1, df_4, on=["CHSI_County_Name", "CHSI_State_Name"])
df_5["Lung_Cancer_d"] = (df_5["Lung_Cancer"] * df_5["Population_Size"]) / 100000
df_5["Brst_cancer_d"] = (df_5["Brst_Cancer"] * df_5["Population_Size"]) / 100000
df_5["Col_cancer_d"] = (df_5["Col_Cancer"] * df_5["Population_Size"]) / 100000
df_5 = df_5.drop(["Lung_Cancer", "Brst_Cancer", "Col_Cancer"], axis=1)
df_5 = df_5.round()
df_5["Total_cancer_deaths"] = df_5["Lung_Cancer_d"] + df_5["Brst_cancer_d"] + df_5["Col_cancer_d"]
# print(df_5.head(10))
df_6 = pd.merge(df_5, df_3, on=["CHSI_County_Name", "CHSI_State_Name"])
df_6.columns = ["County", "State", "Population_Size", "Lung_Cancer_d", "Brst_cancer_d", "Col_cancer_d",
"Total_cancer_deaths", "Toxic_Chem"]
df_7 = pd.merge(df_6, df_2, on=["County", "State"])
df_7 = df_7.sort_values(by=["Toxic_Chem", "Max AQI"], ascending=[False, False])
pd.set_option("display.max_columns", None)
return df_7
# print(df_7.head(10))
# print(df_7.tail(10))
def plot_disease_pollution(df1, df2, df3, df4):
"""
:param df1: the data-frame on used to complete the plot
:param df2: the data-frame on used to complete the plot
:param df3: the data-frame on used to complete the plot
:param df4: the data-frame on used to complete the plot
:return:
"""
df_7 = disease_pollution(df1, df2, df3, df4)
df_8 = df_7.head(7)
df_9 = df_7.tail(7)
df_10 = pd.concat([df_8, df_9])
plt.subplot(2, 2, 1)
plt.scatter(x=df_10["County"], y=df_10["Total_cancer_deaths"], color="c")
plt.plot(x=df_10["County"], y=df_10["Total_cancer_deaths"], color="c")
plt.xticks(rotation="vertical")
plt.ylabel("Cancer_deaths")
plt.title("Total cancer deaths for top & last 10 counties")
plt.subplot(2, 2, 2)
plt.scatter(x=df_10["County"], y=df_10["Max AQI"], color="m")
plt.plot(x=df_10["County"], y=df_10["Max AQI"], color="m")
plt.xticks(rotation="vertical")
plt.ylabel("Max AQI")
plt.title("Max AQI for top & last 10 counties")
plt.subplot(2, 2, 3)
plt.scatter(x=df_10["County"], y=df_10["Toxic_Chem"], color="darkgreen")
plt.plot(x=df_10["County"], y=df_10["Toxic_Chem"], color="darkgreen")
plt.xticks(rotation="vertical")
plt.ylabel("Toxic Chemicals")
plt.title("Toxic Chemicals for top & last 10 counties")
plt.show()
def death_other_factors(df1, df2, df3):
"""
We have performed the analysis on various factors like Major_Depression, Unemployment, Recent_Drug_Use,Suicide,Homicide based on the poverty for
a particular region.Further we have compared the number of deaths depending on these factors.
:param df1: We are passing the vulnerable_pops dataframe for the analysis.
:param df2: We are passing the birth_death_measure dataframe for the analysis.
:param df3: We are passing the demographics dataframe for the analysis.
:return: We are returning the final dataframe 'data_5' obtained after the analysis
>>> df1 = pd.read_csv("Testfile_VPAEH.csv")
>>> df2 = pd.read_csv("Testfile_MOBAD.csv")
>>> df3 = pd.read_csv("Testfile_DEMO.csv")
>>> df4 = death_other_factors(df1,df2,df3)
>>> print(df4[["CHSI_County_Name","Deaths_Suicide"]].head(5))
CHSI_County_Name Deaths_Suicide
0 Alexander 1.0
5 Jackson 5.0
16 St. Clair 24.0
2 Cook 398.0
18 Vermilion 8.0
"""
df_1 = df1[["CHSI_County_Name", "CHSI_State_Name", "Major_Depression", "Unemployed", "Recent_Drug_Use"]]
df_1 = df_1[df_1["Unemployed"] > 0]
df_2 = df2[["CHSI_County_Name", "CHSI_State_Name", "Suicide", "Homicide"]]
df_2 = df_2[(df_2["Suicide"] > 0) & (df_2["Homicide"] > 0)]
df_3 = df3[["CHSI_County_Name", "CHSI_State_Name", "Population_Size", "Poverty"]]
df_3 = df_3[df_3["Poverty"] > 0]
df_4 = pd.merge(df_2, df_3, on=["CHSI_County_Name", "CHSI_State_Name"])
df_4["Deaths_Suicide"] = (df_4["Suicide"] * df_4["Population_Size"]) / 100000
df_4["Deaths_Homicide"] = (df_4["Homicide"] * df_4["Population_Size"]) / 100000
df_4["Number of people Below Poverty Line"] = (df_4["Poverty"] * df_4["Population_Size"]) / 100
df_4 = df_4.drop(["Homicide", "Suicide", "Poverty"], axis=1)
df_4 = df_4.round()
df_5 = pd.merge(df_1, df_4, on=["CHSI_County_Name", "CHSI_State_Name"])
df_5["Poverty Ratio"] = (df_5["Number of people Below Poverty Line"] / df_5["Population_Size"]) * 100
df_5 = df_5.sort_values(["Poverty Ratio"], ascending=False)
df_5 = df_5.drop(["Population_Size", "Number of people Below Poverty Line"], axis=1)
pd.set_option("display.max_columns", None)
return df_5
def age_poverty(df):
"""
The state wise output shows that the percent of population for Age_85_and_Over is slightly greater in top 10 states with Low Poverty index
as compared to that of states with high poverty index.
:param df: We are passing the demographics dataframe for the analysis.
:return: We are returning the final dataframe 'data_5' obtained after the analysis
"""
df_1 = df[
["CHSI_County_Name", "CHSI_State_Name", "Age_19_Under", "Age_19_64", "Age_65_84", "Age_85_and_Over", "Poverty"]]
df_1 = df_1.replace([-1111.1, -2222.2], np.nan)
df_2 = df_1.groupby(["CHSI_County_Name", "CHSI_State_Name"], as_index=False)[
"Age_19_Under", "Age_19_64", "Age_65_84", "Age_85_and_Over", "Poverty"].mean()
df_3 = df_2.sort_values(by="Poverty", ascending=False)
df_3 = df_3.round(2)
print(df_3.head(10))
print(df_3.tail(10))
df_4 = df_1.groupby(["CHSI_State_Name"], as_index=False)[
"Age_19_Under", "Age_19_64", "Age_65_84", "Age_85_and_Over", "Poverty"].mean()
df_5 = df_4.sort_values(by="Poverty", ascending=False)
df_5 = df_5.round(2)
return df_5
# print(df_5.head(10))
# print(df_5.tail(10))
def read_dataframes():
"""
In this function, we are are reading the required csv files from the dataset into dataframes.
:return: We return the demographics, lead_death_cause, birth_death_measure, risk_factors, vulnerable_pops as dataframes after reading the csv files.
"""
demographics = pd.read_csv("DEMOGRAPHICS.csv")
lead_death_cause = pd.read_csv("LEADINGCAUSESOFDEATH.csv")
birth_death_measure = pd.read_csv("MEASURESOFBIRTHANDDEATH.csv")
risk_factors = pd.read_csv("RISKFACTORSANDACCESSTOCARE.csv")
vulnerable_pops = pd.read_csv("VUNERABLEPOPSANDENVHEALTH.csv")
air_quality = pd.read_csv("annual_aqi_by_county_2010.csv")
return demographics, lead_death_cause, birth_death_measure, risk_factors, vulnerable_pops, air_quality
if __name__ == '__main__':
demographics, lead_death_cause, birth_death_measure, risk_factors, vulnerable_pops, air_quality = read_dataframes()
a, b = birth_death_ratio(demographics, birth_death_measure)
print("The relational analysis of Poverty with respect to different races in different counties: \n")
print((a.sort_values(by='Poverty', ascending=False)).head(5))
print("\n Analysis based on how poverty in a state is biased on basis of race of an individual: \n")
print(b.head(10))
print("\n The graph for the same can be depicted as: \n")
plot_birth_death_ratio(demographics, birth_death_measure)
c, d, e = death_factors(demographics, birth_death_measure)
print("\n The total number of deaths in a particular county. The data is distributed and related on basis of race"
"of an individual \n")
print("\nStates with highest number of deaths (race-wise distribution) : \n")
print("---------------------------------------------------------------------\n\n")
print(d)
print("\nStates with lowest number of deaths (race-wise distribution) : \n")
print("---------------------------------------------------------------------\n\n")
print(e)
print("\nThe plot for the above analysis is as follows: \n\n")
plot_death_factors(demographics, birth_death_measure)
f = other_risk_factors(birth_death_measure, demographics)
pd.set_option('display.max_columns', None)
print(
"\n The mortality rate and Poverty analysis based on various risk factors like premature birth, birth to females both below age 18 and above 40, etc. for different counties in each state."
" These values show the top 5 counties for the given analysis. \n")
print("---------------------------------------------------------------------\n")
print(f.head())
print(
"\nThe mortality rate and Poverty analysis based on various risk factors like premature birth, birth to females "
"both below age 18 and above 40, etc. for different counties in each state."
" These values show the lowest 5 counties for the given analysis.")
print("---------------------------------------------------------------------\n")
print(f.tail())
print("\n The graph demontrating the above analysis: \n")
plot_other_risk_factors(birth_death_measure, demographics)
g = population_poverty(demographics)
print("\n The ratio of population to poverty for every state has been analysed. The analysis is as follows: \n")
print("---------------------------------------------------------------------\n")
print(g)
result = merge_dataframes(risk_factors, demographics, birth_death_measure, vulnerable_pops)
h, i = analysis_1(result)
print("\n Co-relation between Poverty , Total_Death , various risk factors and medical assistance provided is done. The analysis is as follows: \n")
print("---------------------------------------------------------------------\n")
print(h.head())
print(i.head())
print("\n The correlation between various risk factors, poverty")
plot_analysis_1(result)
j = genetic_deaths(lead_death_cause, birth_death_measure)
print("\n\n The mortality rate based on genetic defects has been analyzed. The analysis can be demonstrated as: \n")
print("---------------------------------------------------------------------\n")
print("\n", j.head(10))
k = air_quality_death(birth_death_measure, air_quality, demographics)
print(
"\n This analysis is based on how pollution(AQI index) adds to cause of fata diseases in different counties. The analysis can be demonstrated as: \n")
print("---------------------------------------------------------------------\n")
print(k.head())
print("The graphical representation of the data is done as follows: \n")
plot_air_quality_death(birth_death_measure, air_quality, demographics)
l = disease_pollution(birth_death_measure, air_quality, vulnerable_pops, demographics)
print(
"\n This analysis provides information about the total number of cases of fatal diseases like various types of cancer due to pollution and toxic chemicals for each county. This can be shown as : \n")
print("---------------------------------------------------------------------\n")
print(l.head(10))
print("\n The plot to demonstrate the above analysis is as follows: \n")
plot_disease_pollution(birth_death_measure, air_quality, vulnerable_pops, demographics)
m = death_other_factors(vulnerable_pops, birth_death_measure, demographics)
print(
"\n This analysis shows the mortality rate based on various other human-centric factors. The analysis is done for each county.\n")
print("---------------------------------------------------------------------\n")
print(m.head(10))
n = age_poverty(demographics)
print(
"\n The analysis shows state wise output for percent of population for Age_85_and_Over is slightly greater in top 10 states with Low Poverty index "
"as compared to that of states with high poverty index. The analysis can be demonstrated as: \n")
print("---------------------------------------------------------------------\n")
print(n.head(10))
print("---------------------------------------------------------------------\n")
print("Analysis Complete")
|
b2a5cdffa4dc2d5a67652a4307ad11facd7bb492 | jindalpankaj/python-sklearn-in-r-shiny | /nlp.py | 2,692 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 15:09:53 2020
@author: Pankaj Jindal
"""
# This is a project to begin learning NLP; influenced by a Thinkful webinar.
import pandas as pd
import numpy as np
import sklearn
import re
import matplotlib.pyplot as plt
data = pd.read_csv('https://github.com/Thinkful-Ed/data-201-resources/raw/master/hotel-reviews.csv')
# data.columns
# data.head(3).address
# data[["name","reviews.rating", "reviews.text","reviews.title"]]
# data.head()
# data.values
# type(data)
# data.index
data = data[["name","reviews.rating", "reviews.text","reviews.title"]]
data.rename(columns={'name':'hotel_name',
"reviews.rating":"review_rating",
"reviews.text":"review_comment",
"reviews.title":"review_title"}, inplace = True)
# removing blank reviews and replacing with ""
data["review_comment"] = data["review_comment"].fillna("")
data["review_title"] = data["review_title"].fillna("")
# concatinating review title and review comment as review
data["review"] = data["review_title"] + " " + data["review_comment"]
data = data[["hotel_name","review","review_rating"]]
data.rename(columns = {"review_rating":"rating"}, inplace = True)
# removing non-text and digit characters using regular expressions
data["review"] = data["review"].str.replace(r'\?|\.|\!|\'|\(|\)|,|-|\d',"")
# lowercase all characters
data["review"] = data["review"].str.lower()
# checking if there are any blank review
# sum(data["review"].isna())
# removing blank ratings
sum(~data["rating"].isna())
data = data[~data["rating"].isna()]
# data.shape
# data.head(3)
# kinds of ratings
data["rating"].value_counts()
# keeping only 0 to 5 ratings and removing others
data = data[data["rating"].isin([0,1,2,3,4,5])]
# plotting
# data["rating"].value_counts().plot(kind = "bar")
# bag of words
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(max_features = 10000)
X = vectorizer.fit_transform(data["review"])
bag_of_words = pd.DataFrame(X.toarray(), columns = vectorizer.get_feature_names())
bag_of_words.head(2)
# modeling
from sklearn.naive_bayes import MultinomialNB
model = MultinomialNB()
trained_model = model.fit(bag_of_words, data["rating"])
def funcPredictRating(inputText):
inputText = [inputText]
X_test = vectorizer.transform(inputText).toarray()
predicted_rating = trained_model.predict(X_test)
return predicted_rating
# testing. making predictions.
# test_review = ["Absolutely wonderful."]
# X_test = vectorizer.transform(test_review).toarray()
# predicted_rating = trained_model.predict(X_test)
# print("Predicted rating is: " + str(predicted_rating))
|
c0827d86fc184e95229d96da18e196a24f123aff | edhaz/exercism-projects | /python/raindrops/raindrops.py | 238 | 3.671875 | 4 | def raindrops(number):
answer = ''
factors = {3: 'Pling', 5: 'Plang', 7: 'Plong'}
for i in factors:
if number % i == 0:
answer += factors[i]
if answer == '':
return str(number)
return answer |
07685415a7a84d9daf4330543e2b56a2c6783ac6 | Reisande/ProjectEuler | /Project Euler 9.py | 2,492 | 3.75 | 4 | def triples_generator(input_size_of_terms): # argument of triples_generator is how large the sum of triples can be
def ozanam_generator(term_ozanam): # argument is just how many terms are generated
term_ozanam += 1
numerator = ((4 * term_ozanam) + 3)
denominator = ((4 * term_ozanam) + 4)
side_a = denominator
side_b = (term_ozanam * denominator) + numerator
side_c = ((side_a ** 2) + (side_b ** 2)) ** .5
triples_sublist = [side_a, side_b, side_c]
return triples_sublist
def stifel_generator(term_stifel):
term_stifel += 1
numerator = term_stifel
denominator = ((2 * term_stifel) + 1)
side_a = denominator
side_b = (term_stifel * denominator) + numerator
side_c = ((side_a ** 2) + (side_b ** 2)) ** .5
triples_sublist = [side_a, side_b, side_c]
return triples_sublist
def triple_multiplier(input_list): #finds multiples of already found pythagorean triplets, which, also, are valid triplets
for i in range(0, len(input_list)):
new_a, new_b, new_c = input_list[i][0], input_list[i][1], input_list[i][2]
while new_a + new_b + new_c <= input_size_of_terms:
new_a += input_list[i][0]
new_b += input_list[i][1]
new_c += input_list[i][2]
list_of_new_sides = [new_a, new_b, new_c]
input_list.append(list_of_new_sides)
triples_list = []
triples_sublist_ozanam = [[8, 15, 17]]
triples_sublist_stifel = [[3, 4, 5]]
term_ozanam = 1
term_stifel = 1
while sum(triples_sublist_ozanam[-1]) < input_size_of_terms:
triples_sublist_ozanam.append(ozanam_generator(term_ozanam))
term_ozanam += 1
while sum(triples_sublist_stifel[-1]) <= input_size_of_terms:
triples_sublist_stifel.append(stifel_generator(term_stifel))
term_stifel += 1
triple_multiplier(triples_sublist_ozanam)
triple_multiplier(triples_sublist_stifel)
def list_populater(input_list): # argument must be a list
for i in range(0, len(input_list)):
triples_list.append(input_list[i])
list_populater(triples_sublist_stifel)
list_populater(triples_sublist_ozanam)
for i in range(0, len(triples_list)):
if sum(triples_list[i]) == input_size_of_terms:
print(triples_list[i][0] * triples_list[i][1] * triples_list[i][2])
break
triples_generator(12)
|
10e452d8689027a882425e4c31329c3348599379 | Jithendrachowdary48/Python-Lab | /Lab_5 Linear Search User Inputs.py | 365 | 3.953125 | 4 | #Linear Search by User input
#Inputs
print("Enter an array")
l=list(map(int,input().split()))
find=int(input("Enter a digit to find "))
def linearsearch(a,search):
for i in range(len(a)):
if a[i]==find:
return i
pos=linearsearch(l,find)
if pos==None:
print("Element Not Found")
else:
print(find,"found at",pos,"index")
|
edc975992907520af4ccf3318da0470c8eb7a9b0 | Jithendrachowdary48/Python-Lab | /Lab_4 Transpose of Sparse Matrix.py | 976 | 4.03125 | 4 | # Function to represent the Sparse Matrix
def sparse_matrix(arr):
sp = []
r = len(arr)
c = len(arr[0])
for i in range(r):
for j in range(c):
if arr[i][j]!=0:
sp.append([i,j,arr[i][j]])
return sp
def trans(arr):
res = []
for i in arr:
res.append([i[1],i[0],i[2]])
res.sort()
return res
def print_martix(arr):
if arr==[]: print("Empty Matrix")
for i in arr:
print(*i)
arr = []
#Inputs
r = int(input("Enter the number of rows : "))
c = int(input("Enter the number of columns : "))
for i in range(r):
dup = list(map(int,input().split()))
arr.append(dup)
print("The Original Matrix")
print_martix(arr)
print()
#Sparse matrix
sparse = sparse_matrix(arr)
print("The Sparse Matrix")
print_martix(sparse)
#Transpose of a sparse matrix
transpose = trans(sparse)
print("The Transpose of the Sparse Matrix")
print_martix(transpose)
|
8e2d5d8ae6120354932d2a3874610dfbc88c39ed | Jithendrachowdary48/Python-Lab | /Lab_9 27-10 pop push exit display From Stack.py | 187 | 3.65625 | 4 | #program to implement pop push and exit
stack = [10,20,30]
print(stack)
#push
stack.append(40)
stack.append(50)
print(stack)
#pop
print(stack.pop( ))
print(stack)
exit
|
2d05b1b979779617ce76b15b16f6030b4691cfb9 | baltornat/programming | /python/security/SecLab1/Solutions/Solution5.py | 978 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 15:22:20 2020
@author: marco
Esercizio #5 SecLab1:
-Provide the value of 'i'
"""
import random
import hashlib as h
pool = b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' #Item pool
out = ""
while out[:5] != "00000": #Execute as long as the first 5 characters of the output isn't like 00000xxxxxxxxxxxxxxxx
s = bytearray()
for i in range(20): #Execute 20 times because 20*8(bit) = 160 bit (sha1 length)
s.append(random.choice(pool)) #Choose randomly one character from the pool and put it in the input
out = h.sha1(s).hexdigest() #Apply sha1 on the input, repeat if the first 5 characters aren't like 00000xxxxxxxxxxxxxxxx
print("Value found: ")
print(s.decode("utf-8"))
|
ba539c0e7b1291fafbcad61a647a1b9faade5cf3 | Abrown1211/Python-Practice | /Python-Practice/week-6-review-Abrown1211/random_shapes.py | 2,040 | 3.859375 | 4 | #creates a file with random shape points written to it.
from random import *
from graphics import *
def userFileInput():
fileName = input("Enter the drawing file name to create: ")
shapeCount = int(input("Enter the number of shapes to make: "))
fileName = open(fileName, "w")
return fileName, shapeCount
def randomShape():
if random() < .5:
shapeChoice = "rectangle"
else:
shapeChoice = "circle"
return shapeChoice
def shapeColorGenerator():
r = randrange(50,225)
b = randrange(25,256)
g = randrange(55,240)
color = color_rgb(r, g, b)
return color
def getRectangle( fileName, color ):
x1 = randint(5,440)
y1 = randint(5,440)
uprLftPt = x1,y1
x2 = x1 + randrange(20,440)
y2 = y1 + randrange(20,440)
lwrRghtPt = x2,y2
color = shapeColorGenerator()
rectangleWrite = print("rectangle;{0};{1};{2}".format( uprLftPt,lwrRghtPt,color), file= fileName)
return rectangleWrite
def getCircle( fileName, color ):
radius = randrange(3, 20)
x = randrange(5, 395)
y = randrange(5, 395)
centerPt = x,y
color = shapeColorGenerator()
circleWrite = print("circle;{0};{1};{2}".format( centerPt, radius,color), file=fileName)
return circleWrite
def shapeGenerator( shapeCount, fileName, color ):
for shapes in range(shapeCount):
shapeChoice = randomShape()
if shapeChoice == "rectangle":
shapes = getRectangle( fileName, color)
else:
shapes = getCircle( fileName, color )
return shapes
def main():
fileName, shapeCount = userFileInput()
color = shapeColorGenerator()
for shapes in range(shapeCount):
shapeChoice = randomShape()
if shapeChoice == "rectangle":
shapes = getRectangle( fileName, color)
else:
shapes = getCircle( fileName, color )
fileName = fileName.close()
print ("Your file has been processed successfully!")
main()
|
5fbb53b4895ee1a50a8d49f68dedc40b34d3e237 | Abrown1211/Python-Practice | /Python-Practice/week-7-review-Abrown1211/stock_seller.py | 2,120 | 3.859375 | 4 | class StockHolding:
def __init__( self, symbol, totalShares, initialPrice ):
self.symbol = symbol
self.totalShares = totalShares
self.initialPrice = initialPrice
def getSymbol(self):
return self.symbol
def getNumShares(self):
return self.totalShares
def getInitialPrice(self):
return self.initialPrice
def sellShares(self, sharesToSell ):
self.sharesToSell = sharesToSell #method to sell shares from the clients stockholdings, throws error if stockholding shares are exceeded.
if self.totalShares - sharesToSell >= 0:
self.totalShares = self.totalShares - sharesToSell
print("Your total remaining shares are: {}".format( self.totalShares ))
else:
raise ValueError("You do not have that many shares to sell.")
return self.totalShares, sharesToSell
#method to determine if a profit exists and output the result.
def estimatedProfit(self, finalPrice, sharesToSell):
estimatedProfit = (finalPrice - self.initialPrice) * sharesToSell
if estimatedProfit > 0:
print("Estimated profit for selling {0} {1} shares is {2}".format( sharesToSell, self.symbol, estimatedProfit ))
else:
print("This trade is not profitable")
return estimatedProfit
def getInputs():
symbol = input("Enter the symbol for the stock you wish to sell: ")
totalShares = int(input("How many Shares of this stock do you have?: "))
initialPrice = float(input("Initial share price (in dollars) : "))
finalPrice = float(input("What is the final share price (in dollars) : "))
sharesToSell = float(input("How many shares would you like to sell?: "))
return symbol, totalShares, initialPrice, finalPrice, sharesToSell
def main():
symbol,totalShares, initialPrice, finalPrice, sharesToSell = getInputs()
sh = StockHolding( symbol, totalShares, initialPrice )
sh.sellShares( sharesToSell )
sh.estimatedProfit( finalPrice, sharesToSell)
main()
|
18a4c56bcc6207df2464276b34c71246ac3c4d98 | joao-fontenele/NPuzzleSolver | /misc.py | 3,828 | 3.53125 | 4 | #!/usr/bin/env python
#coding: utf-8
from NPuzzle import NPuzzle
from search import a_star
from search import a_star_tree
from search import ida_star
def print_solution(expanded_nodes, steps, path):
print '{} nodes expanded.'.format(expanded_nodes)
print '{} steps to solution.'.format(steps)
for move, state in path:
if state is not None:
print move
state.show()
def read_input(f):
"""
Returns the initial state (NPuzzle object) the file f contains.
The file should contain in the first line the dimension of the puzzle,
i.e., in the case its an 8 puzzle it should be 3.
The following lines should be the state of the board, one number per line,
the blank should be the number 0.
"""
K = int(f.readline())
block = []
for k in range(K*K):
e = f.readline()
block.append(int(e))
initial = NPuzzle(K, block)
return initial
def solve(initial, search=a_star, heuristic=NPuzzle.manhattan_distance):
"""
Solve if solvable and print the results, given an initial state, search
method and heuristic.
"""
print 'Initial state'
initial.show()
solvable = initial.is_solvable()
print 'Is this puzzle solvable? {}\n'.format(solvable)
if solvable:
goal = NPuzzle(initial.K, range(initial.K**2))
expanded, steps, path = search(initial, goal, heuristic)
print_solution(expanded, steps, path)
def generate_random_states(fname, amount, K = 3):
with open(fname, 'w') as f:
d = {}
for i in range(amount):
state = NPuzzle(K)
while not state.is_solvable() and state not in d:
state = NPuzzle(K)
d[state] = 1
f.write('{}\n'.format(state))
def write_heuristics_data(start, n, res_fname, states_fname='data/states.txt', search=a_star, h_name='linear_conflict', heuristic=NPuzzle.linear_conflict):
"""
Write a file with information on states, depths, expanded nodes, and
running time for the 3 heuristics implemented on a specific search method.
"""
from ProgressBar import ProgressBar
import time
import re
with open(res_fname, 'a') as res_f, open(states_fname, 'r') as s_f:
K = 3
goal = NPuzzle(K, range(K*K))
for i in range(start):
s_f.readline()
print 'Reading states from file {:s}'.format(states_fname)
print 'Writing {} states data to file {:s}'.format(n, res_fname)
pb = ProgressBar() # a simple pogressbar
pb.start()
f_format = '{};{};{};{}\n'
if start == 0:
columns = ['state', 'steps', h_name + '_nodes', h_name + '_time']
res_f.write(f_format.format(*columns))
for i in range(n - start):
state_str = s_f.readline().strip()
state = [int (b) for b in re.findall('[0-9]+', state_str)]
initial = NPuzzle(3, state)
percent = float(i+start)/(n)
pb.update(percent)
try:
init_time1 = time.time()
n1, s1, path1 = search(initial, goal, heuristic)
end_time1 = time.time()
t1 = end_time1 - init_time1
except KeyboardInterrupt:
break
except:
t1 = 'NaN'
n1 = 'NaN'
s1 = 'NaN'
res_f.write(f_format.format(initial, s1, n1, t1))
res_f.flush()
pb.finish()
def print_analysis(fname='heuristics_data.csv'):
"""
Print statistical analysis of the file created by the write_heuristics_data
function.
"""
import pandas as pd
data = pd.read_csv(fname, sep=';')
#print data
#print data['state']
print data.describe()
if __name__ == '__main__':
pass
|
61f7f07a765f2f305f05471e4d6177a7d6707616 | samwelkinuthia/snakey | /samples/jaden.py | 264 | 3.859375 | 4 | def jaden(sentence):
return ' '.join(i.capitalize() for i in sentence.split())
# for user input scenario
# sentence = input("enter a sentence: ")
# print(jaden(sentence))
#test scenario
# print(jaden("Why does round pizza come in a square box?")) |
f83fcdb7cf66fc15b70ce5df0cf93eb25e9074b5 | samwelkinuthia/snakey | /samples/bubble_sort.py | 427 | 3.9375 | 4 | def bubble_sort(n):
swap = False
while not swap:
print('bubble sort: ' + str(n))
swap = True
for j in range(1, len(n)):
if n[j - 1] > n[j]:
swap = False
temp = n[j]
n[j] = n[j - 1]
n[j-1] = temp
test = [2, 16, 12, 8, 49, 4,498, 5487, 12, 45, 6, 3, 45, 6, 8, 9, 9, 8, 9]
print('')
print(bubble_sort(test))
print(test)
|
8b0f03d4d4e0db2bb35c8ad1db0c8e0381f56ed4 | samwelkinuthia/snakey | /samples/merge_sort.py | 548 | 3.90625 | 4 | def merge(left, right):
# empty dic to hold data.
result = []
# i and j, two indices, beginning of both right and left list
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j])
j += 1
return result
print(merge([3,11,4,6,10])) |
bb0bd9dca9195533f9031ce4aee299613ef9b81f | samwelkinuthia/snakey | /samples/largest_no.py | 149 | 3.65625 | 4 | def max(n):
largest = 0
for i in n:
if i > largest:
largest = i
return largest
print(max([11, 2, 14, 5, 0, 19, 21])) |
dd6b6c00d59cb5a26089744badf9ac3e3588e7c7 | davronismoilov/pdp-1-modul | /task 6_2.py | 489 | 4.1875 | 4 | """Standart kiruvchi ma'lumotdagi vergul bilan ajratilgan so'zlar ketma-ketligini teskari tartibda chiqaradigan dastur tuzing
Masalan: Ismlar: john, alice, bob
Natija: bob, alice, john"""
words = input("Vergul bilan ajratib so'zlar kiriting:\n Ismlar: ").split(sep=",")
#First metod slise orqali chiqarish teskarisiga
print('Natija :',*words[::-1])
words.reverse()
print('Natija :',end=" ")
for i in range (len(words)):
print(words[i],end=",")
|
41fa6d39451fe444bf8d6a9a3753bac587b4d6db | davronismoilov/pdp-1-modul | /10.3task.py | 433 | 3.53125 | 4 | '''
1- va 2- topshiriqda yozgan kodingizni try/except ichida yozib
, ekranga errorni chiqaradigan kod yozing
'''
try :
a = [1, 5, 8, 5, 6, 5, 8, 5]
print(a[9])
except IndexError as e:
print(e)
try:
ab = {'a': 12, "b": 3, 'c': 6}
print(ab[45])
except KeyError :
print('key error ishlayapti :')
try:
a = 12
b = 'salom Davron '
print(int(a) + b)
except TypeError as e:
print(e)
|
671dd620f6f34e20c4602a264404afdc5a85da1f | davronismoilov/pdp-1-modul | /9.3 task.py | 578 | 3.796875 | 4 | '''
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i if non of the above conditions are true.
Input: n = 3
Output: ["1","2","Fizz"]
'''
n=int(input('n = '))
a= []
for i in range (1,n+1):
if i%3 == 0 and i%5==0:
a.append("FizzBuzz")
elif i % 3 == 0:
a.append("Fizz")
elif i%5 == 0:
a.append("Buzz")
else :
a.append(i)
print(a) |
284fc596554833c0570f6cb982c752a97dce51e9 | Eleazar-Harold/WeatherDetection | /api_assessment.py | 1,679 | 3.546875 | 4 | import calendar
import datetime
import requests
import json
import urllib
from iso8601 import parse_date
from apixu_client import ApixuClient
from apixu_exception import ApixuException
def iso2unix(timestamp):
# use iso8601.parse_date to convert the timestamp into a datetime object.
parsed = parse_date(timestamp)
# now grab a time tuple that we can feed mktime
timetuple = parsed.timetuple()
# return a unix timestamp
return calendar.timegm(timetuple)
def main():
api_key = 'eb2a0633229b456ba6093557151106' #current api key borrowed from the C# functionality on github
client = ApixuClient(api_key) #api function instatiated to enable use of api functions
current = client.getCurrentWeather(q='nairobi') #current weather data in Nairobi
timestamp = datetime.datetime.now().isoformat('T') #converting date time now to iso 8601 format
unix = iso2unix(timestamp) #converting current 'timestamp' to unix timestamp
usum = sum(map(int, str(unix))) #sum of digits in the unix timestamp
devname = "Eleazar Yewa Harold" #name of developer doing this code
#passing data above to json format below 'postdata'
postdata = {
"name": devname,
"timestamp": str(timestamp),
"unix": str(unix),
"sum": str(usum),
"temperature_celsius": str(current['current']['temp_c']),
"humidity": str(current['current']['humidity'])
}
urlpost = "https://hooks.zapier.com/hooks/catch/1604383/mw5sh8/" #passing posting url
post = requests.post(urlpost, data=postdata) #function to post json data on the url above
print(post.content) #return message of the posting
if __name__ == '__main__': main() |
3de650934569cf2b5118fc4a8a4fbd4244114589 | rbfarr/Simple-Server | /remotecalc-server-udp.py | 758 | 3.546875 | 4 | #!/usr/bin/env python
# Richard Farr (rfarr6)
# CS 3251
# 9/21/2014
# Project 1
import socket, sys
# Bind to 127.0.0.1 at the specified port
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", int(sys.argv[1])))
# Buffer size for received data
buffer_size = 32
while True:
# Receive data and sender's address
data, addr = sock.recvfrom(buffer_size)
# Respond to client query
if (data == "kill"): break
op, num1, num2 = data.split(" ")
if (op == "multiply"):
sock.sendto(str(int(num1)*int(num2))+"\n", addr)
elif (op == "add"):
sock.sendto(str(int(num1)+int(num2))+"\n", addr)
else:
sock.sendto("invalid operation\n", addr)
# Release bound network interface
sock.close()
|
3c036ccf967bf7c94e288b5b1d371ddd1567e984 | JA4N/lern_python | /Excersise/u_08_kontrollfluss/__init__.py | 976 | 3.875 | 4 | #Aufgabe 2
"""""
liste = ["Hochschule", "der", "TEST", "Medien"]
gesuchtNach = "Medien"
zaehler = 0
gefunden = False
while zaehler < len(liste):
if liste[zaehler] == gesuchtNach:
gefunden = True
break
zaehler += 1
if gefunden == True:
print("Gefunden! Nach dem " + str(zaehler) + " durchgang")
else:
print("nicht gefunden")
"""""
#Aufgabe 3
""""
list = [1, 2, 3, 4, 5, 6]
list2 = []
zaehler = 0
kontrolle = 3, 6
while zaehler < len(list):
if list[zaehler] != kontrolle:
list2.append(list[zaehler])
else:
continue
zaehler += 1
print(list2)
"""
#Aufgabe 5
"""
listNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
geradeZahl = 0
ungeradeZahl = 0
zaehler = 0
while zaehler < len(listNumbers):
erg = listNumbers[zaehler] % 2
if erg != 0:
ungeradeZahl += 1
elif erg == 0:
geradeZahl += 1
zaehler += 1
print("Gerade Zahlen: " + str(geradeZahl))
print("Ungerade Zahlen: " + str(ungeradeZahl))
"""
|
b8ab12a52930764e694596ad1c4ec4346fb82590 | pankajmore/AI_assignments | /grid.py | 1,243 | 4.15625 | 4 | #!/usr/bin/python
class gridclass(object):
"""Grid class with a width, height"""
def __init__(self, width, height,value=0):
self.width = width
self.height = height
self.value=value
def new_grid(self):
"""Create an empty grid"""
self.grid = []
row_grid = []
for col in range(self.width):
for row in range(self.height):
row_grid.append(self.value)
self.grid.append(row_grid)
row_grid = [] # reset row
return self.grid
def print_grid(self):
for row in range(self.height):
for col in range(self.width):
print(self.grid[row][col],end=" ")
print()
def insertrow(self,pos):
cell_value = '_'
self.height+=1
self.grid.insert(pos,[cell_value]*self.width)
def insertcolumn(self,pos):
cell_value='_'
for i in range(self.height):
self.grid[i].insert(pos,cell_value)
self.width+=1
def edit(self,x,y,val):
self.grid[x][y]=val
#my_grid = grid(10, 10)
#print ("Empty grid ...")
#my_grid.new_grid()
#my_grid.print_grid()
#my_grid.insertrow(3)
#my_grid.insertcolumn(8)
#my_grid.print_grid()
|
7814dec1d1327584bfcc7f7ff8e963a27cc32d06 | tag1234567/assignments | /day1.py | 151 | 3.625 | 4 | p=int(input("Enter principal : "))
r=int(input("Enter rate : "))
t=int(input("Enter time : "))
si=(p*r*t)/100
print("Simple Interest is : ",si)
|
78847ee82c62c876401fef71b5f5f3709fc4ff4d | bertvn/floodtags | /floodtags/datascience/analysis.py | 2,255 | 3.890625 | 4 | """
analyzes the tweets to find which language the dataset is and what keyword is the most frequent
"""
from random import randrange
from collections import Counter
class AnalyzeDataSet(object):
"""
class for analyzing the twitter dataset
"""
def __init__(self):
"""
constructor for AnalyzeDataSet
:return: None
"""
self.data = []
def set_data(self, data):
"""
sets the twitter data
:param data: twitter dataset
:return: None
"""
self.data = data
def start_analysis(self):
"""
starts analysis of the dataset
:return: tuple containing the most frequent keyword and language (keyword, language)
"""
try:
keywords = [tweet.tweet["keywords"][0] for tweet in self.data]
except IndexError:
keywords = ["flood"]
languages = self.get_lang()
return (self.most_common(keywords), self.most_common(languages))
def get_lang(self):
"""
finds languages used in the dataset
:return: list of used languages
"""
dataset = self.get_random(int(len(self.data) / 100))
languages = []
for tweet in dataset:
languages.append(tweet.language)
return languages
def most_common(self, lst):
"""
gets the most frequent element in lst
:param lst: dataset that needs to be analyzed
:return: most frequent element in lst
"""
data = Counter(lst)
return data.most_common(1)[0][0]
def get_random(self, amount):
"""
selects the specified amount of random tweets
:param amount: amount of tweets
:return: list of random tweets
"""
random_selection = []
for i in range(0, amount):
while True:
rnd = randrange(0, len(self.data))
if self.data[rnd] not in random_selection:
if len(self.data[rnd].tweet["text"].split()) > 3:
random_selection.append(self.data[rnd])
break
return random_selection
|
ead67175dbdc6286f97ca1a2b68724ed1ad4ed99 | jakubclark/schnapsen | /schnapsen/api/util.py | 2,501 | 3.859375 | 4 | """
General utility functions
"""
import importlib
import math
import os
import sys
import traceback
from api import Deck
def other(
player_id # type: int
):
# type: () -> int
"""
Returns the index of the opposite player to the one given: ie. 1 if the argument is 2 and 2 if the argument is 1.
:param player:
:return:
"""
return 1 if player_id == 2 else 2 # type: int
def get_suit(card_index):
"""
Returns the suit of a card
:param card_index:
:return:
"""
return Deck.get_suit(card_index)
def get_rank(card_index):
"""
Returns the rank of a card
:param card_index:
:return:
"""
return Deck.get_rank(card_index)
def get_card_name(card_index):
# type: () -> int
"""
Returns the rank and the suit of a card. Maps card indices as stored in memory to actual cards
:param card_index:
:return:
"""
return get_rank(card_index), get_suit(card_index)
def load_player(name, classname='Bot'):
#
"""
Accepts a string representing a bot and returns an instance of that bot. If the name is 'random'
this function will load the file ./bots/random/random.py and instantiate the class "Bot"
from that file.
:param name: The name of a bot
:return: An instantiated Bot
"""
name = name.lower()
path = './bots/{}/{}.py'.format(name, name)
# Load the python file (making it a _module_)
try:
module = importlib.import_module('bots.{}.{}'.format(name, name))
except:
print('ERROR: Could not load the python file {}, for player with name {}. Are you sure your Bot has the right '
'filename in the right place? Does your python file have any syntax errors?'.format(path, name))
traceback.print_exc()
sys.exit(1)
# Get a reference to the class
try:
cls = getattr(module, classname)
player = cls() # Instantiate the class
player.__init__()
except:
print('ERROR: Could not load the class "Bot" {} from file {}.'.format(
classname, path))
traceback.print_exc()
sys.exit()
return player
def ratio_points(state, player):
if state.get_points(player) + state.get_points(other(player)) != 0:
return state.get_points(player) / float((state.get_points(player) + state.get_points(other(player))))
return 0
def difference_points(state, player):
return state.get_points(player) - state.get_points(other(player))
|
58995a5d2fc6bdab5db7267ed206936c2cec69b6 | Medha7979/FloorPlan3D_PY | /2D.py | 4,267 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 15:00:00 2019
@author: MEDHA
"""
from turtle import Turtle, Screen
import time
import itertools
a=[1,1]
b=[2,3]
i=0
for x, y in zip(a, b):
if(i<(len(a)-1)):
x=a[i]
y=b[i]
x1=a[i+1]
y1=b[i+1]
if((x1>x)and(y1==y)):
s="right"
elif((x1<x)and(y1==y)):
s="left"
elif((x1==x)and(y1>y)):
s="forward"
elif((x1==x)and(y1<y)):
s="backward"
print(s)
i+=1
NAME = "F"
BORDER = 1
BOX_WIDTH, BOX_HEIGHT = 6, 10 # letter bounding box
WIDTH, HEIGHT = BOX_WIDTH - BORDER * 2, BOX_HEIGHT - BORDER * 2 # letter size
time.sleep(12)
def letter_A(turtle):
turtle.forward(HEIGHT / 2)
for _ in range(3):
turtle.forward(HEIGHT / 2)
turtle.right(90)
turtle.forward(WIDTH)
turtle.right(90)
turtle.forward(HEIGHT)
def letter_B(turtle):
turtle.forward(HEIGHT /2)
turtle.right(90)
turtle.circle(-HEIGHT / 4, 180, 30)
turtle.right(90)
turtle.forward(HEIGHT )
turtle.right(90)
turtle.circle(-HEIGHT / 4, 180, 30)
def letter_C(turtle):
turtle.left(90)
turtle.circle(-HEIGHT/4, 180, 30)
def letter_D(turtle):
turtle.forward(HEIGHT)
turtle.right(90)
turtle.circle(-HEIGHT / 2, 180, 30)
def letter_I(turtle):
turtle.right(90)
turtle.forward(WIDTH)
turtle.backward(WIDTH / 2)
turtle.left(90)
turtle.forward(HEIGHT)
turtle.right(90)
turtle.backward(WIDTH / 2)
turtle.forward(WIDTH)
def letter_F(turtle):
turtle.right(90)
turtle.forward(WIDTH/4)
turtle.left(90)
turtle.forward(HEIGHT/4)
turtle.right(90)
turtle.forward((3*WIDTH)/4)
turtle.left(90)
turtle.forward(HEIGHT/4)
turtle.left(90)
turtle.forward(WIDTH)
turtle.right(90)
turtle.backward(HEIGHT/2)
turtle.forward(HEIGHT)
turtle.right(90)
turtle.forward(WIDTH/2)
turtle.left(90)
turtle.backward(WIDTH)
turtle.left(90)
turtle.backward(WIDTH/2)
turtle.right(90)
turtle.forward(WIDTH)
turtle.right(90)
turtle.backward(WIDTH/2)
def letter_N(turtle):
turtle.forward(HEIGHT )
turtle.goto(turtle.xcor() + WIDTH, BORDER)
turtle.forward(HEIGHT)
def letter_G(turtle):
turtle.forward(HEIGHT)
turtle.right(90)
turtle.forward(WIDTH/4)
turtle.left(90)
turtle.backward(WIDTH/2)
turtle.right(90)
turtle.forward(HEIGHT/4)
turtle.left(90)
turtle.forward(WIDTH/2)
turtle.right(90)
turtle.forward(WIDTH/4)
turtle.right(90)
turtle.forward(HEIGHT)
turtle.right(90)
turtle.circle(-HEIGHT/4 , 180, 30)
turtle.left(90)
turtle.backward(HEIGHT/2)
turtle.left(90)
turtle.forward((3*WIDTH)/4)
turtle.right(90)
turtle.forward(HEIGHT/4)
turtle.left(90)
turtle.forward(WIDTH/8)
turtle.right(90)
turtle.backward(WIDTH/2)
LETTERS = {'A': letter_A, 'B': letter_B, 'C':letter_C, 'D': letter_D, 'I': letter_I, 'N': letter_N, 'F':letter_F, 'G':letter_G}
wn = Screen()
wn.setup(800, 400) # arbitrary
wn.title("Turtle writing my name: {}".format(NAME))
wn.setworldcoordinates(0, 0, BOX_WIDTH * len(NAME), BOX_HEIGHT)
marker = Turtle()
for counter, letter in enumerate(NAME):
marker.penup()
marker.goto(counter * BOX_WIDTH + BORDER, BORDER)
marker.setheading(90)
if letter in LETTERS:
marker.pendown()
LETTERS[letter](marker)
marker.hideturtle()
wn.mainloop()
import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib.pyplot import imread
from mpl_toolkits.mplot3d import Axes3D
import scipy.ndimage as ndimage
imageFile = '2d.jpg'
mat = cv2.imread(imageFile)
mat = mat[:,:,0] # get the first channel
rows, cols = mat.shape
xv, yv = np.meshgrid(range(cols), range(rows)[::-1])
blurred = ndimage.gaussian_filter(mat, sigma=(10, 10), order=0)
fig = plt.figure(figsize=(16,16))
ax = fig.add_subplot(221)
ax.imshow(mat, cmap='gray')
ax = fig.add_subplot(222, projection='3d')
ax.elev= 250
ax.plot_surface(xv, yv, mat)
ax = fig.add_subplot(223)
ax.imshow(blurred, cmap='gray')
ax = fig.add_subplot(224, projection='3d')
ax.elev= 400
ax.plot_surface(xv, yv, blurred)
plt.show()
|
00c5e35f7f5bddc7030403d74b1b75de84bf8c9d | razzaksr/KabilanPython | /basics/LoopMore.py | 891 | 3.875 | 4 | # Another real time example
#for seats in range(1,16):
'''seats=1
while seats<=15:
amt=int(input("Tell us amount to book ticket: "))
if amt>= 190:
print("Ticket Booked @",seats)
seats+=1
else:print("Insufficient amount")'''
'''seats=1
while seats<=30:
if seats%5!=0 and seats%2!=0:
amt = int(input("Tell us amount to book ticket: "))
if amt >= 190:
print("Ticket Booked @", seats)
seats += 1
else:
print("Insufficient amount")
else:
seats += 1
continue#break'''
hire=20
while hire>0:
skill=input("Tell us skill set you knew: ")
poc=int(input("Tell us how may POC done on "+skill+": "))
if (skill=='java' or skill=='python') and poc>=4:
print("You are recruited to our company")
hire-=1
else:
print("Try to update skill/ work more POC") |
b1c8244326ea335cb4f5a78289b8cb783bdac7ae | razzaksr/KabilanPython | /basics/Member.py | 451 | 3.828125 | 4 | # member operator: in, not in
# list
models=['Redmi9','Realme7','Nokia6.1Plus','Honor9lite']
print(models[2])
#tuple
price=('avenger220','apache200',98700,12,'vikrant',1.2)
print(price[3])
#dict
skills={'java':8000,'python':9000,'dot net':15000,'CCPP':5000,'java':23000,'PHP':8000}
print(skills)
print('Realme5S' in models)
print('Redmi9' in models)
print(12 in price)
print(1.2 not in price)
print('php' in skills)
print('dotNet' not in skills)
|
18c356c2cfc979d40c09aa0a5ed32bbb62f94834 | tceyhan/python-snippets | /functions.py | 191,904 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: bm-zi
def f1():
# Chapter 1 - Python Basics
print('''Chapter 1 - Python Basics
. Entering Expressions into the Interactive Shell
. The Integer, Floating-Point, and String Data Types
. String Concatenation and Replication
. Storing Values in Variables
. Your First Program
''')
def f2():
# Math Operators
print(2+2) # 4
print(2) # 2
print(2 + 3 * 6) # 20
print((2 + 3) * 6) # 30
print(48565878 * 578453) # 28093077826734
print(2 ** 8) # 256
print(23 / 7) # 3.2857142857142856
print(23 // 7) # 3
print(23 % 7) # 2
print(2 + 2) # 4
print((5 - 1) * ((7 + 1) / (3 - 1))) # 16.0
print() # blank line in python3
def f3():
# String concatenation and replication
print('Alice' + 'Bob') # AliceBob
print('Alice' * 5) # AliceAliceAliceAliceAlice
def f4():
# First Python Program - print user input
print('Hello world!')
print('What is your name?') # ask for their name,
# name has to be entered as a str-
# ing like 'Jim' in python2
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
def f5():
# Function len() - string length
print(len('hello'))
print(len('My very energetic monster just scarfed nachos.'))
def f6():
# Function str()
print('I am ' + str(29) + ' years old.')
# you get an error if you just use 29 without function str()
def f7():
# Function str(), int(), float
# The str() , int() , and float() functions will evaluate to the string,
# integer, and floating-point forms of the value you pass, respectively.
print(str(0)) # 0
print(str(-3.14)) # -3.14
print(int('42')) # 42
print(int('-99')) # -99
print(int(1.25)) # 1
print(int(1.99)) # 1
print(float('3.14')) # 3.14
print(float(10)) # 10.0
def f8():
# input() function
# input() function always returns a string,
# to change it to an integer use int() function
spam = input()
spam = int(spam)
print(spam) # If you type a string that cannot be converted to integer,
# you will get an error shows that the variable is not defined
# These are error: int('99.99') int('twelve')
print(int(7.7)) # 7
print(int(7.7) + 1) # 8
print(42 == '42') # False
print(42 == 42.0) # True
print(42.0 == 0042.000) # True
print()
print()
print()
def f9():
print('''Chapter 2 - Flow Control:
. Boolean Values
. Comparison Operators
. Boolean Operators
. Mixing Boolean and Comparison Operators
. Elements of Flow Control (if, else, ilif, while, break, continue, for and rang)
. Flow Control Statements
. Importing Modules
. Ending a Program Early with sys.exit()
''')
def f10():
# Boolean data types
# --- CHAPTER 2 ---
# Boolean data types are having values: False and True
print(42 == 42) # True
print(42 == 99) # False
print(2 != 3) # True
print(2 != 2) # False
# The == and != operators can actually work with values of any data type.
print('hello' == 'hello') # True
print('hello' == 'Hello') # False
print('dog' != 'cat') # True
print(True == True) # True
print(True != False) # True
print(42 == 42.0) # True
print(42 == '42') # False
print(42 < 100) # True
print(42 > 100) # False
print(42 < 42) # False
eggCount = 42
print(eggCount <= 42) # True
myAge = 29
print(myAge >= 10) # True
def f11():
# Boolean Operators
# and operator
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
# or operator
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
# not operator
print(not True) # False
print(not False) # True
def f12():
# Mixing Boolean and Comparison Operators
#
print((4 < 5) and (5 < 6)) # True
print((4 < 5) and (9 < 6)) # False
print((1 == 2) or (2 == 2)) # True
print(2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2) # True
def f13():
# if,elif,else conditional
name='alice'
age=20
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')
spam = 0
if spam < 5:
print('Hello, world.')
spam = spam + 1
def f14():
# while loop
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
def f15():
# An Annoying while Loop
name = 'Al'
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
def f16():
# break Statements, breaks the loop
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
def f17():
# continue statement, keeps running the loop start from begining
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue # restarts the loop
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break # stops the loop
print('Access granted.')
# Note:
# A combination of 'if not statement' with 'continue' helps if
# the condition is not true then loops resets, otherwise it k-
# eeps going to the next statement in loop.
def f18():
# empty value is considered False
name = ''
while not name:
print('Entenning the loop start from beginingr your name:')
name = input()
print('How many guests will you have?')
numOfGuests = int(input())
if numOfGuests: # if no of guest not empty
print('Be sure to have enough room for all your guests.')
print('Done')
def f19():
# for Loops and the range() Function
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
def f20():
# while loop equivalent to for loop
print('My name is')
i = 0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i = i + 1
def f21():
# for loop example - sum of numbers from 1 to 100
total = 0
for num in range(101):
total = total + num
print(total)
def f22():
# for loop to show alphabet characters
alphabet = list()
for letter in range(97,123):
alphabet.append(chr(letter)) # chr() is inverse of ord()
print(alphabet)
def f23():
# range() function examples
for i in range(12, 16):
print(i)
print('.' * 10)
for i in range(0, 10, 2):
print(i)
print('.' * 10)
for i in range(5, -1, -1):
print(i)
def f24():
# import modules
# functions like print(), input() , and len() are builtin fuctions;
# No need to import them.
# function like randint() are from standard library modules that
# has to be imported
# if use "from random import *" ,
# then no need to to call a function with the random. prefix.
import random
for i in range(5):
print(random.randint(1, 10))
def f25():
# sys.exit()
# Ending a Program Early with sys.exit()
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')
def f26():
#
print('''Chapter 3 - Functions:
. def Statements with Parameters
. Return Values and return Statements
. The None Value
. Keyword Arguments and print()
. Local and Global Scope
. The global Statement
. Exception Handling''')
def f27():
# FUNCTIONS
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
hello()
hello()
hello()
def f28():
# Function with argument
def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')
def f29():
# return statement
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no'
elif answerNumber == 8:
return 'Outlook not so good'
elif answerNumber == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
# return exits the fuction block
def f30():
# None type
# 'None' is a value-without-value
# (like null or undefined in other languages.)
spam = print('Hello!') # print function returns no value that
# is known as 'None'
print(None == spam)
# return without value returns value 'None'
# continue in for or while loop also returns value 'None'
def f31():
# Optional keywords for functions
# functions have optional keyword like end and sep in print() function
print('Hello', end='') # The 'end' keyword cause to ignore the new line.
print('World') # By defualt print prints a newline after printing
# its argument
print('cats', 'dogs', 'mice')
print('cats', 'dogs', 'mice', sep=',') # the function print will automatically
# separates multiple string values
# with a single space.
def f32():
# Local and Global Scopes
# 1.
# Local Variables Cannot Be Used in the Global Scope
# The following snippet generates error if uncommented:
# def spam():
# eggs = 31337
# spam()
# print(eggs)
# 2.
# Local Scopes Cannot Use Variables in Other Local Scopes
# The following snippet prints '99' if is uncommented
def spam1():
eggs = 99
bacon1()
print(eggs)
def bacon1():
ham = 101
eggs = 0
spam1()
print('.' * 10)
# 3.
# Global Variables Can Be Read from a Local Scope
# '42' will be printed, for the following snippet
def spam2():
# eggs = 21
print(eggs) # because no local eggs exists, python con-
# siders it a reference to the global vari-
# able eggs(42). If a local variale eggs -
# exists, it uses that local variable inst-
# ead of the variable eggs in global scope.
eggs = 42
spam2()
print(eggs) # prints 21, if 'eggs = 21' is uncommented.
print('.' * 10)
# 4.
# Local and Global Variables with the Same Name
# Avoid using the same variable name in different scopes.
def spam3():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon3():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam3() # prints 'spam local'
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon3()
print(eggs) # prints 'global'
def f33():
# Local and Global Variables
# If you need to modify a global variable from within a funct-
# ion, use the global statement.
def spam4():
global eggs
eggs = 'spam'
print(eggs)
eggs = 'global'
spam4() # prints spam
print(eggs) # prints 'global'
print('.' * 10)
# Rules:
# 1. If a variable is being used in the global scope (that -
# is, outside of all functions), then it is always a glo-
# bal variable.
# 2. If there is a global statement for that variable in a -
# function, it is a global variable.
# 3. Otherwise, if the variable is used in an assignment st-
# atement in the function, it is a local variable.
# 4. But if the variable is not used in an assignment state-
# ment, it is a global variable.
# To get a better feel for the above rule, here is another sn-
# ippet:
def spam5():
global eggs
eggs = 'spam' # this is the global
print(eggs)
def bacon5():
eggs = 'bacon' # this is a local
print(eggs)
def ham5():
print(eggs) # this is the global
eggs = 42 # this is the global
spam5()
print(eggs)
bacon5()
ham5()
print('.' * 10)
# If try to use a local variable in a function before you ass-
# ign a value to it, Python will give you an error.
def spam6():
# print(eggs) # if uncommented you get ERROR!
eggs = 'spam local'
print(eggs)
eggs = 'global'
spam6()
def f34():
# Exception Handling
def spam(divideBy):
try: # Potential error code is in try clause
return 42 / divideBy
except ZeroDivisionError: # When error is caught in try clause, then it moves to except block,
# and then gets back to try block and continue the next statement
# after the statement with error
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
def f35():
# Out Of Function Exception Handling
# Difference between the folloing code and the previous one:
# In previous code any errors that occur in function calls in
# a try block will also be caught.
def spam(divideBy):
return 42 / divideBy
try:
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
except ZeroDivisionError:
print('Error: Invalid argument.')
def f36():
# Guessing Game
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
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
# This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
def f37():
#
print('''Chapter 4 - Lists:
. The List Data Type
. Working with Lists
. Augmented Assignment Operators
. Finding a Value in a List with the index() Method
. Adding Values to Lists with the append() and insert() Methods
. Removing Values from Lists with remove()
. Sorting the Values in a List with the sort() Method
. List-like Types: Strings and Tuples
. Mutable and Immutable Data Types
. The Tuple Data Type
. Converting Types with the list() and tuple() Functions''')
def f38():
# Lists - examples
print([1, 2, 3])
print(['cat', 'bat', 'rat', 'elephant'])
print(['hello', 3.1415, True, None, 42])
# Getting Individual Values in a List with Indexes
spam = ['cat', 'bat', 'rat', 'elephant']
print(spam)
print(spam[0])
print(spam[1])
print(spam[2])
print(spam[3])
print(['cat', 'bat', 'rat', 'elephant'][3])
print('Hello ' + spam[0])
print('The ' + spam[1] + ' ate the ' + spam[0] + '.')
print(spam[int(1.0)])
def f39():
# Lists : list of lists
spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] # List of lists
print(spam)
print(spam[0][1])
print(spam[1][4])
def f40():
# Lists : negative indexes
spam = ['cat', 'bat', 'rat', 'elephant']
print(spam[-1]) # elephant
print(spam[-3]) # bat
print(spam[0:-1]) # ['cat', 'bat', 'rat']
print('The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.')
def f41():
# Lists : getting sublists with slices
spam = ['cat', 'bat', 'rat', 'elephant']
print(spam[0:4]) # ['cat', 'bat', 'rat', 'elephant']
print(spam[1:3]) # ['bat', 'rat']
print(spam[0:-1]) # ['cat', 'bat', 'rat']
print(spam[:2]) # ['cat', 'bat']
print(spam[1:]) # ['bat', 'rat', 'elephant']
print(spam[:]) # ['cat', 'bat', 'rat', 'elephant']
def f42():
# Lists : getting a list’s length with len()
spam = ['cat', 'dog', 'moose']
print(len(spam)) # 3
def f43():
# Lists : changing values in a list with indexes
spam = ['cat', 'bat', 'rat', 'elephant']
spam[1] = 'aardvark'
print(spam)
spam[2] = spam[1]
print(spam)
spam[-1] = 12345
print(spam)
def f44():
# Lists: list concatenation and list replication
# It is like strings concatenation and replication
x = [1, 2, 3] + ['A', 'B', 'C']
print(x)
x = ['X', 'Y', 'Z'] * 3
print(x)
spam = [1, 2, 3]
spam = spam + ['A', 'B', 'C']
print(spam)
def f45():
# Lists : removing values from lists with del statements
spam = ['cat', 'bat', 'rat', 'elephant']
del spam[2]
print(spam)
del spam[2]
print(spam)
def f46():
# Lists : working with lists
# instead of using many varibales use lists for data entry
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
def f47():
# Lists : using for loops
print('simple for loop : ')
for i in range(4):
print(i)
print('using for loop with list : ')
for i in [0, 1, 2, 3]:
print(i)
print('technique of using range(len(someList)) with a for loop : ')
supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
def f48():
# Lists : in and not in operators
# determine whether a value is or isn’t in a list
print('howdy' in ['hello', 'hi', 'howdy', 'heyas'])
spam = ['hello', 'hi', 'howdy', 'heyas']
print(spam)
print('cat' in spam)
print('howdy' not in spam)
print('cat' not in spam)
print ('...')
print('Sample program to check if value is in list : ')
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print(myPets)
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
def f49():
# Lists : multiple assignment trick
cat = ['fat', 'black', 'loud']
size = cat[0]
color = cat[1]
disposition = cat[2]
print(cat)
print('... ... ... ... ')
cat = ['fat', 'black', 'loud']
size, color, disposition = cat
print(cat)
def f50():
# Augmented assignment operators
'''
statement Equivalent
spam = spam + 1 spam += 1
spam = spam - 1 spam -= 1
spam = spam * 1 spam *= 1
spam = spam / 1 spam /= 1
spam = spam % 1 spam %= 1
'''
spam = 42
spam = spam + 1
print(spam)
spam = 42
spam += 1
print(spam)
spam = 'Hello'
spam += ' world!'
print(spam)
bacon = ['Zophie']
bacon *= 3
print(bacon)
def f51():
# Lists : finding a Value in a list with the index() method
# Methods are the same as functoions, except that is called on value
# Each data type has its own set of methods.
# list data type, for example, has several useful methods for finding,
# adding, removing, and manipulating values in a list.
spam = ['hello', 'hi', 'howdy', 'heyas']
print(spam.index('hello'))
print(spam.index('heyas'))
# When there are duplicates of the value in the list,
# the index of its first appearance is returned.
spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
print(spam.index('Pooka'))
def f52():
# Methods - adding values to lists with append() and insert() methods
spam = ['cat', 'dog', 'bat']
spam.append('moose')
print(spam)
spam = ['cat', 'dog', 'bat']
spam.insert(1, 'chicken')
print(spam)
def f53():
# Lists : removing values from lists with remove()
spam = ['cat', 'bat', 'rat', 'elephant']
spam.remove('bat')
print(spam)
# If the value appears multiple times in the list,
# only the first instance of the value will be removed
spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
spam.remove('cat')
print(spam)
def f54():
# List : sorting the values in a list with the sort() method
spam = [2, 5, 3.14, 1, -7]
spam.sort()
print(spam)
spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
spam.sort()
print(spam)
# You can also pass True for the reverse keyword argument to have sort()
# sort the values in reverse order
spam.sort(reverse=True)
print(spam)
# note (1) :
# You cannot write: spam = spam.sort() ,
# sort() method sorts the list in place
# note (2) :
# cannot sort lists that have both number and string
# note (3) :
# sort() uses “ASCIIbetical order” rather than actual alphabetical
spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
spam.sort()
print(spam)
# To sort in alphabetic order:
spam = ['a', 'z', 'A', 'Z']
spam.sort(key=str.lower)
print(spam)
def f55():
# Using function randint() with a list
# much more elegant version of previous 8 ball
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again',
'My reply is no',
'Outlook not so good',
'Very doubtful']
print(messages[random.randint(0, len(messages) - 1)])
def f56():
# list-like types: strings and tuples
'''
You can consider a string to be a "list" of single text characters.
Then you can use indexing; slicing; and using them with for loops,
with len() , and with the in and not in operators.
'''
name = 'Zophie'
print(name[0])
print(name[-2])
print(name[0:4])
print('Zo' in name)
print('z' in name)
print('p' not in name)
for i in name:
print('* * * ' + i + ' * * *')
def f57():
# mutable and immutable data types
# Lists can have values added, removed, or changed. (mutable)
# Strings are not. (immutable)
name = 'Zophie a cat'
# name[7] = 'the' # this generates error
newName = name[0:7] + 'the' + name[8:12]
print(name)
print(newName)
eggs = [1, 2, 3]
eggs = [4, 5, 6] # The list value in eggs isn’t being changed here; is overwriiten.
print(eggs)
print('The actual modification is as following: ')
eggs = [1, 2, 3]
del eggs[2]
del eggs[1]
del eggs[0]
eggs.append(4)
eggs.append(5)
eggs.append(6)
print(eggs)
def f58():
# tuple data type
# tuples are like lists but use () instead aof []
# tuples are like strings, cannot have their values modified,
# appended, or removed.
eggs = ('hello', 42, 0.5)
# eggs[1] = 99 # this generates error
# If you have only one value in your tuple, you can indicate this
# by placing a trailing comma
print(type(('hello',)))
print(type(('hello')))
'''tuples advantages:
. When you don't want the values to be changed.(unlike the list)
. They are faster than lists
'''
print('Converting Types with the list() and tuple() Functions')
print(tuple(['cat', 'dog', 5]))
print(list(('cat', 'dog', 5)))
print(list('hello'))
def f59():
# references
# assignment for strings and integers value
spam = 42
cheese = spam
spam = 100
print('spam has different value than cheese: ')
print(spam)
print(cheese) # cheese didn't chage
# assignment foe lists is different, actually we are assiging a
# list reference to the variable
spam = [0, 1, 2, 3, 4, 5]
cheese = spam
cheese[1] = 'Hello!'
print('spam and cheese have the same value: ')
print(spam)
print(cheese)
'''
When you create the list, you assign a reference to it in the spam
variable. But the next line copies only the list reference in spam
to cheese , not the list value itself.
list variables don’t actually contain lists—they contain references
to lists.
'''
def f60():
# Passing References
'''
When a function is called, the values of the arguments are copied
to the parameter variables. For lists and dictionaries, this means
a copy of the reference is used for the parameter.
'''
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)
'''
Notice that when eggs() is called, a return value is not used to
assign a new value to spam. Instead, it modifies the list in place, directly.
Even though spam and someParameter contain separate references, they
both refer to the same list. This is why the append('Hello') method call
inside the function affects the list even after the function call has returned.
'''
def f61():
# The copy Module’s copy() and deepcopy() Functions
'''
copy.copy() , makes a duplicate copy of a mutable value like a list or dictionary,
not just a copy of a reference.
'''
import copy
spam = ['A', 'B', 'C', 'D']
cheese = copy.copy(spam) # creates a second list that can be
# modified independently of the first.
cheese[1] = 42
print('copy.copy')
print(spam)
print(cheese)
milk = copy.deepcopy(cheese)
milk[1] = 52
print('copy.deepcopy')
print(spam)
print(cheese)
print(milk)
def f62():
grid = [['.','.','.','.','.','.'],
['.','0','0','.','.','.'],
['0','0','0','0','.','.'],
['0','0','0','0','0','.'],
['.','0','0','0','0','0'],
['0','0','0','0','0','.'],
['0','0','0','0','.','.'],
['.','0','0','.','.','.'],
['.','.','.','.','.','.']]
print(grid)
def f63():
# Chapter 5 - Dictionaries and Structuring Data
print('''Chapter 5 - Dictionaries and Structuring Data:
. The Dictionary Data Type
. Using Data Structures to Model Real-World Things
. The keys(), values(), and items() Methods
. Checking Whether a Key or Value Exists in a Dictionary
. The get() Method
. The setdefault() Method
. Pretty Printing
. Using Data Structures to Model Real-World Things
. A Tic-Tac-Toe Board
. Nested Dictionaries and Lists
''')
def f64():
# Dictionary Data Type
myCat = {'size': 'fat', 'color': 'grey', 'disposition': "loud" }
print(myCat['size'])
print('My cat has ' + myCat['color'] + ' fur.')
# Dictionaries can use integer values as keys, like lists.
# There is no item order in dictionaries.
spam = {12345: 'Luggage Combination', 42: 'The Answer'}
print(spam)
print('Dictionaries vs. Lists')
spam = ['cats', 'dogs', 'moose']
bacon = ['dogs', 'moose', 'cats']
print(spam == bacon)
eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
print(eggs == ham)
def f65():
# program to store data
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
print(birthdays)
def f66():
# Dictionary's methods: keys, values, items
spam = {'color': 'red', 'age': 42}
print('Values:')
for v in spam.values():
print(v)
print('Keys::')
for k in spam.keys():
print(k)
print('Items:')
for i in spam.items():
print(i)
def f67():
# Build a list from dictionary's keys
spam = {'color': 'red', 'age': 42}
print('spam.keys() returns \'dict_key\' data type')
print(spam.keys())
print(list(spam.keys()))
#
# The list(spam.keys()) line takes the dict_keys value
# returned from keys() and passes it to list() , which
# then returns a list value of ['color', 'age']
def f68():
# Show dictionary's keys & values by for loop
spam = {'color': 'red', 'age': 42}
for k, v in spam.items():
print('Key: ' + k + ' Value: ' + str(v))
# spam.items() returns a dict_items data type
print(spam.items())
def f69():
# Check if key or value exists in a dictionary,
# by using in and not operators
spam = {'name': 'Zophie', 'age': 7}
print('name' in spam.keys())
print('Zophie' in spam.values())
print('color' in spam.keys())
print('color' not in spam.keys())
print('color' in spam)
print('age' in spam) # True
print('Zophie' in spam) # False
print('Zophie' in spam.values())
def f70():
# Dictionary get() method
picnicItems = {'apples': 5, 'cups': 2}
print('I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.')
print('I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.')
print('I am bringing ' + str(picnicItems.get('eggs', 'no value')) + ' eggs.')
'''
get() returns the value of the key, if the key exists.
Because there is no 'eggs' key in the picnicItems dictionary,
the default value 0 is returned by the get() method. Without
using get() , the code would have caused an KeyError error.
'''
def f71():
# Dictionary setdefault() Method
# sets a default value for key if key does not already have a value
spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'
# The nice shortcut is using setdefault() method:
spam = {'name': 'Pooka', 'age': 5}
spam.setdefault('color', 'black') # returns black
print(spam.setdefault('color', 'black'))
print(spam)
spam.setdefault('color', 'white') # returns black
print(spam.setdefault('color', 'white'))
print(spam)
def f72():
# Using setdefault() to count number of occurance of a
# character in string.
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
'''
The setdefault() method call ensures that the key is in the
count dictionary (with a default value of 0 )
So the program doesn’t throw a KeyError error,
when count[character] = count[character] + 1 is executed.
'''
def f73():
# Pretty Printing - using pprint module
# Following code counts number of the occurance of
# character in the string and then using pprint to
# display cleaner the items in a dictionary
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
# print even prettier for nested loops:
# pprint.pprint(someDictionaryValue)
# print(pprint.pformat(someDictionaryValue))
def f74():
# TIC-TOC-TOE - using dictionary to model the board
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ',
'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|'+ board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|'+ board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|'+ board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
if move == 'q':
return
theBoard[move] = turn
if turn == 'X':
turn = 'O'
elif turn == 'q' : return
else:
turn = 'X'
printBoard(theBoard)
def f75():
# Nested Dictionaries and Lists
# more complex data structure
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
print('Number of things being brought:')
print(' - apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))
'''Inside the totalBrought() function, the for loop iterates
over the key-value pairs in guests. Inside the loop, the stri-
ng of the guest’s name is assigned to k , and the dictionary -
of picnic items they’re bringing is assigned to v. If the item
parameter exists as a key in this dictionary, it’s value ( the
quantity) is added to numBrought. If it doesn't exist as key,
the get() method returns 0 to be added to numBrought .'''
def f76():
# Fantasy Game Inventory
print('project to do')
def f77():
# List to Dictionary Function for Fantasy Game Inventory
print('project to do')
def f78():
# Chapter 6 - Manipulating Strings
print('''Chapter 6 - Manipulating Strings:
. String Literals
. Indexing and Slicing Strings
. The in and not in Operators with Strings
. The upper(), lower(), isupper(), and islower() String Methods
. The isX String Methods
. The startswith() and endswith() String Methods
. The join() and split() String Methods
. Justifying Text with rjust(), ljust(), and center()
. Removing Whitespace with strip(), rstrip(), and lstrip()
. Copying and Pasting Strings with the pyperclip Module
''')
def f79():
# Working with Strings - Double Quotes
# By using double quotes, strings can have a single quote,
# inside of string, and no need to be escaped.(interpolates)
spam = "That is Alice's cat."
print(spam)
# When using single quotes, the single quote character,
# inside string has to be escaped.
spam = 'That is Alice\'s cat.'
print(spam)
def f80():
# Raw Strings and escape characters
print('Printing string with special characters:')
print("Hello there!\nHow are you?\nI\'m doing fine.")
# You can place an r before the beginning quotation mark of a string to make
# it a raw string. A raw string completely ignores all escape characters and
# prints any backslash that appears in the string.
print(r'That is Carol\'s cat.')
es = r'''Escape ccharacters
\' Single quote
\" Double quote
\t Tab
\n Newline (line break)
\\ Backslash'''
print(es)
def f81():
# Multiline Strings with Triple Quotes
# Any quotes, tabs, or newlines in between the “triple quotes”,
# are considered part of the string.
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
print()
print("""Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob""")
print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and extortion.\n\nSincerely,\nBob')
def f82():
# Multiline Comments
"""This is a test Python program.
Written by tester ...
This program was designed for Python 3, not Python 2.
"""
def spam():
"""This is a multiline comment to help
explain what the spam() function does."""
print('Hello!')
spam()
def f83():
# Indexing and Slicing Strings
spam = 'Hello world!'
print(spam[0])
print(spam[4])
print(spam[-1])
print(spam[0:5])
print(spam[:5])
print(spam[6:])
print(spam[0:5])
def f84():
# The in and not in Operators with Strings
spam = 'Hello world!'
print('Hello' in 'Hello World')
print('Hello' in 'Hello')
print('HELLO' in 'Hello World')
print('' in 'spam')
print('cats' not in 'cats and dogs')
def f85():
# String Methods: upper(), lower(), isupper(), and islower()
spam = 'Hello world!'
spam = spam.upper()
print(spam)
spam = spam.lower()
print(spam)
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')
''' Sample output
How are you?
GREat
I feel great too.
'''
def f86():
# String Methods: isupper(), and islower()
spam = 'Hello world!'
print(spam.islower())
print(spam.isupper())
print('HELLO'.isupper())
print('abc12345'.islower())
print('12345'.islower())
print('12345'.isupper())
# upper and lower returns strings
print('Hello'.upper())
print('Hello'.upper().lower())
print('Hello'.upper().lower().upper())
print('HELLO'.lower())
print('HELLO'.lower().islower())
def f87():
# The isX String Methods
print(
# returns True if the string consists only of letters
# and is not blank.
'hello'.isalpha(),
'hello123'.isalpha(),
# isalnum() returns True if the string consists only of
# letters and numbers
'hello123'.isalnum(),
'hello'.isalnum(),
# isdecimal() returns True if the string consists only of numeric
# characters and is not blank.
'123'.isdecimal(),
# isspace() returns True if the string consists only of spaces,
# tabs, and new-lines and is not blank.
' '.isspace(),
# istitle() returns True if the string consists only of words that
# begin with an uppercase letter followed by only lowercase letters.
'This Is Title Case'.istitle(),
'This Is Title Case 123'.istitle(),
'This Is not Title Case'.istitle(),
'This Is NOT Title Case Either'.istitle(),
)
def f88():
# isX methods helps to validate user input
while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Please enter a number for your age.')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers.')
''' Sample output
Enter your age:
forty two
Please enter a number for your age.
Enter your age:
42
Select a new password (letters and numbers only):
secr3t!
Passwords can only have letters and numbers.
Select a new password (letters and numbers only):
secr3t
'''
def f89():
# startswith() and endswith() String Methods
print(
'Hello world!'.startswith('Hello'),
# True
'Hello world!'.endswith('world!'),
# True
'abc123'.startswith('abcdef'),
# False
'abc123'.endswith('12'),
# False
'Hello world!'.startswith('Hello world!'),
# True
'Hello world!'.endswith('Hello world!'),
# True
)
def f90():
# join() and split() String Methods
print(', '.join(['cats', 'rats', 'bats']))
print(' '.join(['My', 'name', 'is', 'Simon']))
print('ABC'.join(['My', 'name', 'is', 'Simon']))
print('My name is Simon'.split())
print('MyABCnameABCisABCSimon'.split('ABC'))
print('My name is Simon'.split('m'))
def f91():
# split a multiline string
spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob'''
print(spam.split('\n'))
def f92():
# Justifying Text with rjust(), ljust(), and center()
print('Hello'.rjust(10))
print('Hello'.rjust(20))
print('Hello World'.rjust(20))
print('Hello'.ljust(10))
print('Hello'.rjust(20, '*'))
print('Hello'.ljust(20, '-'))
print('Hello'.center(20))
print('Hello'.center(20, '='))
def f93():
# Using Justifying Text for Tabular Data
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6)
def f94():
# Removing Whitespace with strip(), rstrip(), and lstrip()
spam = ' Hello World '
print(spam.strip())
print(spam.lstrip())
print(spam.rstrip())
spam = 'SpamSpamBaconSpamEggsSpamSpam'
print(spam.strip('ampS'))
print(spam.strip('Spma'))
# Above two are the same, order of argument character is ignored.
def f95():
# Copy and Paste Strings with the pyperclip Module
import pyperclip
pyperclip.copy('Hello world!')
print(pyperclip.paste())
def f96():
# An insecure password locker program.
import pyperclip
# Step 1: Program Design and Data Structures
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
# Step 2: Handle Command Line Arguments
import sys
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
# Step 3: Copy the Right Password
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)
def f97():
# Adding Bullets to Wiki Markup
# Step 1: Copy and Paste from the Clipboard
import pyperclip
text = pyperclip.paste()
# Step 2 - # TODO: Separate lines and add stars.
lines = text.split('\n')
# loop through all indexes in the "lines" list and add star to
# each string in "lines" list
for i in range(len(lines)):
lines[i] = '* ' + lines[i]
# Step 3: Join the Modified Lines
text = '\n'.join(lines)
pyperclip.copy(text)
# When this program is run, it replaces the text on the clipboard with
# text that has stars at the start of each line.
def f98():
# Chapter 7 - Pattern Matching With Reular Expression
print('')
def f99():
# Finding Patterns of Text Without Regular Expressions
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3): # i = [0, 1, 2]
if not text[i].isdecimal(): # Convert string to list and
# parsing the list for decimals
return False
if text[3] != '-':
return False
for i in range(4, 7): # i = [4, 5, 6]
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8, 12): # i = [8, 9, 10, 11]
if not text[i].isdecimal():
return False
return True
print('415-555-4242 is a phone number:')
print(isPhoneNumber('415-555-4242'))
print('Moshi moshi is a phone number:')
print(isPhoneNumber('Moshi moshi'))
def f100():
# Finding pattern without RE from a string
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
for i in range(len(message)):
chunk = message[i:i+12] # parsing chunks of 12 character in string
if isPhoneNumber(chunk):
print('Phone number found: ' + chunk)
print('Done')
def f101():
# Matching regex objects
# In a raw string a backslash is taken as meaning just as backslash not as
# a escape sequence. if we donot use r'', then we have to escape all the
# backslashes between the single quotes
import re
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search('My number is 415-555-4242.')
print('Phone number found: ' + mo.group())
'''
Steps in using regex:
---------------------
1. Import the regex module with import re.
2. Create a Regex object with the re.compile() function.
(Remember to use a raw string.)
3. Pass the string you want to search into the Regex object’s search() method.
This returns a Match object.
4. Call the Match object’s group() method to return a string of the actual
matched text.
'''
def f102():
# Pattern matching with grouping
import re
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My number is 415-555-4242.')
print(mo.group(1))
print(mo.group(2))
print(mo.group(0)) # returns entire match
print(mo.group()) # returns entire match, the same as group(0)
print(mo.groups()) # Retrives all groups, attention at plural form of group
areaCode, mainNumber = mo.groups() # group 1 and 2 are elements in a list
# generated by method groups()
print(areaCode)
print(mainNumber)
def f103():
# Pattern matching with grouping and escaping parantheses
import re
phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My phone number is (415) 555-4242.')
print(mo.group(1))
print(mo.group(2))
def f104():
# Matching multiple groups with the pipe
import re
heroRegex = re.compile (r'Batman|Tina Fey')
mo1 = heroRegex.search('Batman and Tina Fey.')
print(mo1.group())
mo2 = heroRegex.search('Tina Fey and Batman.')
print(mo2.group())
def f105():
# Matching groups with the pipe as part of re
import re
batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
mo = batRegex.search('Batmobile lost a wheel')
print(mo.group()) # returns all full-matched text 'Batmobile'
print(mo.group(1)) # returns the first match it founds,
# in first group
def f106():
# Optional matching with the question mark
import re
batRegex = re.compile(r'Bat(wo)?man')
mo1 = batRegex.search('The Adventures of Batman')
print(mo1.group())
mo2 = batRegex.search('The Adventures of Batwoman')
print(mo2.group())
# (wo)? means that the pattern wo is an optional group.
# the re matches zero instances or one instance of wo in it.
# same way for phone numbers that do or do not have an area code:
phoneRegex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
mo1 = phoneRegex.search('My number is 415-555-4242')
print(mo1.group())
mo2 = phoneRegex.search('My number is 555-4242')
print(mo2.group())
# (pattern)?
# Match zero or one of the group pre-ceding this question mark.
def f107():
# Matching zero or more with star
import re
batRegex = re.compile(r'Bat(wo)*man')
mo1 = batRegex.search('The Adventures of Batman')
print(mo1.group())
mo2 = batRegex.search('The Adventures of Batwoman')
print(mo2.group())
mo3 = batRegex.search('The Adventures of Batwowowowoman')
print(mo3.group())
# (pattern)* means match zero or more of the group
# that precedes the star
def f108():
# Matching one or more with the plus
# the group preceding a plus must appear at least once.
import re
batRegex = re.compile(r'Bat(wo)+man')
mo1 = batRegex.search('The Adventures of Batwoman')
print(mo1.group())
mo2 = batRegex.search('The Adventures of Batwowowowoman')
print(mo2.group())
mo3 = batRegex.search('The Adventures of Batman')
print(mo3 == None)
def f109():
# Matching specific repetitions with {}
# (pattern){a_number}
import re
haRegex = re.compile(r'(Ha){3}')
mo1 = haRegex.search('HaHaHa')
print(mo1.group())
mo2 = haRegex.search('Ha')
print(mo2 == None)
def f110():
# Greedy and nongreedy matching
# RE by default is greedy, matches the longest match.
# To have non-greedy match use {}?
import re
greedyHaRegex = re.compile(r'(Ha){3,5}') # greedy
mo1 = greedyHaRegex.search('HaHaHaHaHa')
print(mo1.group())
nongreedyHaRegex = re.compile(r'(Ha){3,5}?') # non-greedy
mo2 = nongreedyHaRegex.search('HaHaHaHaHa')
print(mo2.group())
# question mark can have two different meanings in RE:
# declaring a nongreedy match or flagging an optional group.
def f111():
# RE findall() Method
# While search() will return a Match object of the first matched text
# in the searched string, the findall() method will return the strings
# of every match in the searched string.
import re
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search('Cell: 415-555-9999 Work: 212-555-0000')
print(mo.group())
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # has no groups
print(phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000'))
# findall() will not return a Match object but a list of strings
# as long as there are no groups in the regular expression.
# When groups are in RE, then findall returns list of tuples
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)') # has groups
print(phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000'))
def f112():
# RE Character Classes
# Character classes are nice for shortening REs
# \d is equal to (0|1|2|3|4|5|6|7|8|9)
# \D Any character that is not a numeric digit from 0 to 9.
# \w Any letter, numeric digit, or the underscore character. (word character)
# \W Any character that is not a letter, numeric digit, or the underscore character.
# \s Any space, tab, or newline character.(space character)
# \S Any character that is not a space, tab, or newline.
import re
xmasRegex = re.compile(r'\d+\s\w+')
f = xmasRegex.findall('12 drummers, 11 pipers, 10 lords, 9 ladies, 8 maids, swans, 6 geese, 5 rings, 4 birds, 3 hens, 2 doves, 1 partridge')
print(f)
def f113():
# Making your own character classes
# match any vowel, both lowercase and uppercase
import re
vowelRegex = re.compile(r'[aeiouAEIOU]')
print(vowelRegex.findall('RoboCop eats baby food. BABY FOOD.'))
# [a-zA-Z0-9] will match all lowercase letters,
# uppercase letters, and numbers
# negative character class by ^
consonantRegex = re.compile(r'[^aeiouAEIOU]')
print(consonantRegex.findall('RoboCop eats baby food. BABY FOOD.'))
def f114():
# Caret and dollar sign characters
import re
beginsWithHello = re.compile(r'^Hello')
print(beginsWithHello.search('Hello world!'))
print(beginsWithHello.search('He said hello.') == None)
endsWithNumber = re.compile(r'\d$')
print(endsWithNumber.search('Your number is 42'))
print(endsWithNumber.search('Your number is forty two.') == None)
# To match strings that both begin and end with one or
# more numeric characters:
wholeStringIsNum = re.compile(r'^\d+$')
print(wholeStringIsNum.search('1234567890'))
print(wholeStringIsNum.search('12345xyz67890') == None)
print(wholeStringIsNum.search('12 34567890') == None)
def f115():
# Wild card character
# The . (or dot) character in a RE is called a wildcard
# and will match just one character except for a newline.
import re
atRegex = re.compile(r'.at')
print(atRegex.findall('The cat in the hat sat on the flat mat.'))
def f116():
# Matching everything with dot-star
import re
nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')
mo = nameRegex.search('First Name: Al Last Name: Sweigart')
print(mo.group(1))
print(mo.group(2))
# The dot-star uses greedy mode,
# to match any and all text in a nongreedy fashion, use (.*?)
nongreedyRegex = re.compile(r'<.*?>')
mo = nongreedyRegex.search('<To serve man> for dinner.>')
print(mo.group())
greedyRegex = re.compile(r'<.*>')
mo = greedyRegex.search('<To serve man> for dinner.>')
print(mo.group())
def f117():
# Matching newlines with the dot character
import re
# To match everything only up to the first newline character,
# newline character is not encluded
noNewlineRegex = re.compile('.*')
print(noNewlineRegex.search(
'Serve the public trust.\nProtect the innocent.\nUphold the law.'
).group())
# re.DOTALL matches everything,
# To include newline character:
newlineRegex = re.compile('.*', re.DOTALL)
print(newlineRegex.search(
'Serve the public trust.\nProtect the innocent.\nUphold the law.'
).group())
def f118():
# Case-insensitive matching
# Use re.I or re.IGNORECASE
import re
robocop = re.compile(r'robocop', re.I)
print(robocop.search(
'RoboCop is part man, part machine, all cop.').group())
print(robocop.search(
'ROBOCOP protects the innocent.').group())
print(robocop.search(
'Al, why does your programming book talk about robocop so much?'
).group())
def f119():
# Substituting strings with sub() method
import re
namesRegex = re.compile(r'Agent \w+')
print(namesRegex.sub(
'CENSORED', 'Agent Alice gave the secret documents to Agent Bob.'))
# using with groups: text of group 1 , 2 , 3
agentNamesRegex = re.compile(r'Agent (\w)\w*')
print(agentNamesRegex.sub(r'\1****', 'Agent Alice told Agent Carol \
that Agent Eve knew Agent Bob was a double agent.'))
def f120():
# Managing complex regexes
# You can simplify the hard-to-read REs by using verbose mode
# re.VERBOSE ignores whitespace and comments inside the RE string.
import re
# Hard to read :
phoneRegex = re.compile(r'((\d{3}|\(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4}(\s*(ext|x|ext.)\s*\d{2,5})?)')
# Expand to multiline using comments:
phoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? # area code
(\s|-|\.)? # separator
\d{3} # first 3 digits
(\s|-|\.) # separator
\d{4} # last 4 digits
(\s*(ext|x|ext.)\s*\d{2,5})? # extension
)''', re.VERBOSE)
someRegexValue = re.compile('foo', re.IGNORECASE | re.DOTALL)
someRegexValue = re.compile('foo', re.IGNORECASE | re.DOTALL | re.VERBOSE)
def f121():
# Combining re.IGNORECASE, re.DOTALL, and re.VERBOSE
import re
someRegexValue = re.compile('foo', re.IGNORECASE | re.DOTALL)
someRegexValue = re.compile('foo', re.IGNORECASE | re.DOTALL | re.VERBOSE)
def f122():
# Finds phone numbers and email addresses on the clipboard
import re, pyperclip
# Step 1: Create a Regex for Phone Numbers
phoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? # area code
(\s|-|\.)? # separator
(\d{3}) # first 3 digits
(\s|-|\.) # separator
(\d{4}) # last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? # extension
)''', re.VERBOSE)
# Step 2: Create a Regex for Email Addresses
emailRegex = re.compile(r'''(
[a-zA-Z0-9._%+-]+ # username
@ # @ symbol
[a-zA-Z0-9.-]+ # domain name
(\.[a-zA-Z]{2,4}) # dot-something
)''', re.VERBOSE)
# Step 3: Find matches in clipboard text.
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
phoneNum = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '':
phoneNum += ' x' + groups[8]
matches.append(phoneNum)
for groups in emailRegex.findall(text):
matches.append(groups[0])
# Step 4: Copy results to the clipboard.
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to clipboard:')
print('\n'.join(matches))
else:
print('No phone numbers or email addresses found.')
def f123():
# In this assignment you will read through and parse a file
# with text and numbers. You will extract all the numbers in -
# the file and compute the sum of the numbers.
import re
fileName = input('Enter file name: ')
fh = open(fileName)
# Initiate an empty list and extend it with list of
# numbers found in the file.
allNumbers = []
for line in fh:
line = line.rstrip()
# Restart the loop if line has no numbers:
if re.search('[0-9]+', line) == None : continue
# extract numbers from each line, ignoring zero/s for
# numbers starting with zero:
numbers = re.findall('0*([0-9]+)', line)
# extend the list allNumbers with list of numbers,
# extracted from each line
allNumbers.extend(numbers)
# Compute the sum of all elements of the list,
# that includes all numbers in the file:
total = 0
for n in allNumbers:
total = total + int(n)
print(total)
def f124():
# Python Regular Expression Quick Guide:
'''
^ Matches the beginning of a line
$ Matches the end of the line
. Matches any character
\s Matches whitespace
\S Matches any non-whitespace character
* Repeats a character zero or more times
*? Repeats a character zero or more times
(non-greedy)
+ Repeats a character one or more times
+? Repeats a character one or more times
(non-greedy)
[aeiou] Matches a single character in the listed set
[^XYZ] Matches a single character not in the listed set
[a-z0-9] The set of characters can include a range
( Indicates where string extraction is to start
) Indicates where string extraction is to end
'''
def f125():
# Chapter 8 - Reading and Writing Files
print('Chapter - Reading and Writing Files')
def f126():
# Create strings for file names
import os
# os.path is a module inside the os module
print(os.path.join('usr', 'bin', 'spam'))
# On Windows the ouput will be with backslash
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
print(os.path.join('/home/username/asweigart', filename))
def f127():
# The Current Working Directory
import os
print(os.getcwd())
os.chdir('/var/log') # returns None
print(os.getcwd())
# After running this function you get error in main program
# because the path to current running script has been changed.
def f128():
# Creating New Folders with os.makedirs()
import os
os.makedirs('/tmp/delicious/walnut/waffles')
os.system('ls /tmp/delicious/walnut/')
# You get error if you run this function forthe second time
# because the directory already exists.
def f129():
# Handling Absolute and Relative Paths
import os
print(os.path.abspath('.'))
print(os.path.abspath('./Scripts'))
print(os.path.isabs('.'))
print(os.path.isabs(os.path.abspath('.')))
print(os.path.relpath('/var/log', '/var/ftp'))
print(os.getcwd())
path = '/windows/logs/messages'
print(os.path.basename(path))
print(os.path.dirname(path))
calcFilePath = '/Windows/System32/calc.exe'
print(os.path.split(calcFilePath))
print((os.path.dirname(calcFilePath), os.path.basename(calcFilePath)))
print('/usr/bin'.split(os.path.sep))
def f130():
# Finding File Sizes and Folder Contents
import os
print(os.path.getsize('runme.py'))
print(os.listdir('/home'))
# Calculating total size in current folder
totalSize = 0
for filename in os.listdir('./'):
totalSize = totalSize + os.path.getsize(os.path.join('./', filename))
print(totalSize)
def f131():
# Checking Path Validity
import os
print(os.path.exists('/var/log'))
print(os.path.exists('/tmp/some_made_up_folder'))
print(os.path.isdir('/var/log'))
print(os.path.isfile('/var/log'))
print(os.path.isdir('/var/log/messages'))
print(os.path.isfile('/var/log/messages'))
# Check if dvd drive exists
print(os.path.exists('D:\\'))
def f132():
# The File Reading/Writing Process
# open() function returns a File object, and opens file in plain text mode.
# Assuming file hello.txt already created.
helloFile = open('./hello.txt')
# You also can open a file in read mode with 'r' option,
# the following is the same as above:
# helloFile = open('./hello.txt', 'r')
helloContent = helloFile.read()
print(helloContent)
# Use the readlines() method to get a list of string,
# values from the file, one string for each line of text.
relFile = open('/etc/os-release')
print(relFile.readlines())
def f133():
# Writing to Files
baconFile = open('bacon.txt', 'w') # open in writr mode
baconFile.write('Hello world!\n')
baconFile.close()
baconFile = open('bacon.txt', 'a')
baconFile.write('Bacon is not a vegetable.')
baconFile.close()
baconFile = open('bacon.txt')
content = baconFile.read()
baconFile.close()
print(content)
def f134():
# Saving Variables with the shelve Module
import shelve
# shelf value is stored in shelfFile:
shelfFile = shelve.open('mydata')
cats = ['Zophie', 'Pooka', 'Simon']
# You can make changes to the shelf value as if it were a dictionary.
shelfFile['cats'] = cats
shelfFile.close()
shelfFile = shelve.open('mydata')
print(type(shelfFile))
print(shelfFile['cats'])
shelfFile.close()
shelfFile = shelve.open('mydata')
print(list(shelfFile.keys()))
print(list(shelfFile.values()))
shelfFile.close()
# but if you want to save data from your Python programs,
# use the shelve module
def f135():
# Saving Variables with the pprint.pformat() Function
'''
Say you have a dictionary stored in a variable and you want to save this
variable and its contents for future use. Using pprint.pformat() will give
you a string that you can write to .py file. This file will be your very
own module that you can import when-ever you want to use the variable stored in it.
'''
import pprint
cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
pprint.pformat(cats)
fileObj = open('myCats.py', 'w')
fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
fileObj.close()
''' In terminal:
$ cat myCats.py
cats = [{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]
'''
'''
And since Python scripts are themselves just text files with the .py file
extension, your Python programs can even generate other Python programs.
You can then import these files into scripts.'''
import myCats
print(myCats.cats)
print(myCats.cats[0])
print(myCats.cats[0]['name'])
def f136():
# Generating Random Quiz Files
import random
# Step 1: Store the Quiz Data in a Dictionary
capitals = {
'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield',
'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka',
'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta',
'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing',
'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City',
'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City',
'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New Mexico': 'Santa Fe',
'New York': 'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck',
'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem',
'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee': 'Nashville',
'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont': 'Montpelier',
'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston',
'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
# Step 2: Create the Quiz File and Shuffle the Question Order
for quizNum in range(35):
# Create the quiz and answer key files.
quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')
answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')
# Write out the header for the quiz.
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')
# Shuffle the order of the states.
states = list(capitals.keys())
random.shuffle(states)
# Step 3: Create the Answer Options
# Loop through all 50 states, making a question for each.
for questionNum in range(50):
# Get right and wrong answers.
correctAnswer = capitals[states[questionNum]]
wrongAnswers = list(capitals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
# Step 4: Write Content to the Quiz and Answer Key Files
quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1, states[questionNum]))
for i in range(4):
quizFile.write(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
quizFile.write('\n')
# Write the answer key to a file.
answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerKeyFile.close()
def f137():
# Multiclipboard
print('')
# Step 1: Comments and Shelf Setup
def f138():
# Chapter 9 - Organizing Files
print('Chapter 9 - Organizing Files')
def f139():
# Copying Files and Folders - using shutil module
# shutil.copy(source, destination)
# copy() returns a string of the path of the copied file.
import shutil, os
print(shutil.copy('./runme.py', '/tmp'))
print(shutil.copy('./runme.py', '/tmp/runme2.py'))
os.listdir('/tmp')
# shutil.copytree(source, destination)
print('--- Cope all files and subfolders from a folder by copytree() --- ')
shutil.copytree('./', '/tmp/test')
# Above copies all files and subfolders in current directory into /tmp/test,
# the test directroy will be created if it is not already exist.
def f140():
# Moving and Renaming Files and Folders
''' Examples:
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt')
'C:\\eggs\\new_bacon.txt'
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs'
>>> shutil.move('spam.txt', 'c:\\does_not_exist\\eggs\\ham')
If move() cannot find the destination folder or file,
then will get FileNotFoundError error.
'''
print()
def f141():
# Permanently Deleting Files and Folders
'''
. Calling os.unlink(path) will delete the file at path.
. Calling os.rmdir(path) will delete the folder at path . This folder must be
empty of any files or folders.
. Calling shutil.rmtree(path) will remove the folder at path , and all files
and folders it contains will also be deleted.
'''
import os
for filename in os.listdir('/tmp'):
if filename.endswith('.py'):
#os.unlink(filename)
print(filename)
def f142():
# Safe Deletes with the send2trash Module
# install the 3rd party module send2trash, first:
# sudo pip3 install send2trash
import send2trash
baconFile = open('bacon.txt', 'a') # creates the file
print(baconFile.write('Bacon is not a vegetable.'))
baconFile.close()
send2trash.send2trash('bacon.txt')
def f143():
# Walk through the directory tree
import os
for folderName, subfolders, filenames in os.walk('/tmp'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print('')
# os.walk, doesn't return list of files/subfolders recursively, it returns
# current folder name, subfolders and file names in current directory.
def f144():
# Compressing Files with the zipfile Module
import zipfile, os
# First create a zip file, from alll files in current directory:
os.system('zip -r example.zip ./')
# 1st create a ZipFile object, similar to when creating a file object
exampleZip = zipfile.ZipFile('example.zip')
print('\nList of files and folders in example.zip :')
print(exampleZip.namelist())
fileInfo = exampleZip.getinfo('runme.py')
print(fileInfo)
print('--------')
print(fileInfo.file_size)
print(fileInfo.compress_size)
print('Compressed file is %sx smaller!' % (round(fileInfo.file_size / fileInfo.compress_size, 2)))
exampleZip.close()
os.unlink('example.zip')
def f145():
# Extracting from ZIP Files
import zipfile, shutil, os
os.makedirs('/tmp/test')
os.system('zip -r /tmp/test/example.zip ./') # Create a zip file in /tmp
# os.chdir('/tmp/test') # move to the folder with example.zip
exampleZip = zipfile.ZipFile('/tmp/test/example.zip') # Creating ZipFile object
exampleZip.extractall()
exampleZip.close()
print(os.listdir('/tmp/test'))
shutil.rmtree('/tmp/test')
def f146():
# Creating and Adding to ZIP Files
import zipfile, os
# Create an ZipFile object in write mode, similar to file object in write mode
newZip = zipfile.ZipFile('new.zip', 'w')
newZip.write('runme.py', compress_type=zipfile.ZIP_DEFLATED)
newZip.close()
os.system('ls')
os.unlink('new.zip')
def f147():
# Renaming Files with American-Style Dates to
# European-Style Dates
# shutil.move() function can be used to rename files
# Step 1: Create a Regex for American-Style Dates
import shutil, os, re
# Create a regex that matches files with the American date format.
datePattern = re.compile(r"""^(.*?) # all text before the date
((0|1)?\d)- # one or two digits for the month
((0|1|2|3)?\d)- # one or two digits for the day
((19|20)\d\d) # four digits for the year
(.*?)$ # all text after the date
""", re.VERBOSE)
# Step 2: Identify the Date Parts from the Filenames
# Loop over the files in the working directory.
for amerFilename in os.listdir('.'):
mo = datePattern.search(amerFilename)
# Skip files without a date.
if mo == None:
continue
# Get the different parts of the filename.
beforePart = mo.group(1)
monthPart = mo.group(2)
dayPart = mo.group(4)
yearPart = mo.group(6)
afterPart = mo.group(8)
# Step 3: Form the New Filename and Rename the Files
# Form the European-style filename.
euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart
# Get the full, absolute file paths.
absWorkingDir = os.path.abspath('.')
amerFilename = os.path.join(absWorkingDir, amerFilename)
euroFilename = os.path.join(absWorkingDir, euroFilename)
# Rename the files.
print('Renaming "%s" to "%s"...' % (amerFilename, euroFilename))
#shutil.move(amerFilename, euroFilename) # uncomment after testing
def f148():
# Backing Up a Folder into a ZIP File
import zipfile, os
# Step 1: Figure Out the ZIP File’s Name
def backupToZip(folder):
# Backup the entire contents of "folder" into a ZIP file.
folder = os.path.abspath(folder) # make sure folder is absolute
# Figure out the filename this code should use based on
# what files already exist.
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
# Step 2: Create the ZIP file.
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
# step 3: Walk the entire folder tree and compress the files
# in each folder.
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
# Add the current folder to the ZIP file.
backupZip.write(foldername)
# Add all the files in this folder to the ZIP file.
for filename in filenames:
newBase = os.path.basename(folder) + '_'
if filename.startswith(newBase) and filename.endswith('.zip'):
continue # don't backup the backup ZIP files
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('/home/bmzi/bin')
def f149():
# Chapter 10 - Debugging
print('Chapter 10 - Debugging')
def f150():
# Raising Exceptions
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <= 2:
raise Exception('Width must be greater than 2.')
if height <= 2:
raise Exception('Height must be greater than 2.')
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('An exception happened: ' + str(err))
# If there are no try and except statements covering the raise statement
# that raised the exception, the program simply crashes and displays the
# exception’s error message.
def f151():
# Getting the Traceback as a String
import traceback, os
try:
raise Exception('This is the error message.')
except:
errorFile = open('errorInfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to errorInfo.txt.')
print('---')
os.system('ls')
print('---')
os.system('cat errorInfo.txt')
os.unlink('errorInfo.txt')
def f152():
# Assertions - is a sanity check of the code
# an assert statement says, 'I assert that this condition holds true,
# and if not, there is a bug somewhere in the program.'
''' assert statement consists of the following:
. The assert keyword
. A condition (that is, an expression that evaluates to True or False )
. A comma
. A string to display when the condition is False'''
# After running following code in a separate file like test.py:
'''
podBayDoorStatus = 'open'
assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
podBayDoorStatus = 'I\'m sorry, Dave. I\'m afraid I cant do that.\''
assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
'''
# output error:
'''
Traceback (most recent call last):
File "./test.py", line 7, in <module>
assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
AssertionError: The pod bay doors need to be "open".
'''
print()
def f153():
# Using an Assertion in a Traffic Light Simulation
def switchLights(stoplight):
for key in stoplight.keys():
if stoplight[key] == 'green':
stoplight[key] = 'yellow'
elif stoplight[key] == 'yellow':
stoplight[key] = 'red'
elif stoplight[key] == 'red':
stoplight[key] = 'green'
market_2nd = {'ns': 'green', 'ew': 'red'}
mission_16th = {'ns': 'red', 'ew': 'green'}
switchLights(market_2nd)
# assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight)
''' If you uncomment the line above your program would crash with this error
message:
Traceback (most recent call last):
File "carSim.py", line 14, in <module>
switchLights(market_2nd)
File "carSim.py", line 13, in switchLights
assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight)
AssertionError: Neither light is red! {'ns': 'yellow', 'ew': 'green'}
'''
# Assertions can be disabled by passing the -O option when running Python.
def f154():
# Logging - Using the logging Module
import logging
logging.basicConfig(level=logging.DEBUG,
format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')
def factorial(n):
logging.debug('Start of factorial(%s%%)' % (n))
total = 1
for i in range(n + 1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
return total
print(factorial(5))
logging.debug('End of program')
''' About this code:
Here, we use the logging.debug() function when we want to print
log information. This debug() function will call basicConfig(),
and a line of information will be printed. This information will
be in the format we specified in basicConfig() and will include
the messages we passed to debug() . The print(factorial(5)) call
is part of the original program, so the result is displayed even
if logging messages are disabled.'''
def f155():
# Logging to a file
# Instead of displaying the log messages to the screen, you can
# write them to a text file.
import logging, os
logging.basicConfig(filename='myProgramLog.txt',
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
def factorial(n):
logging.debug('Start of factorial(%s%%)' % (n))
total = 1
for i in range(n + 1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
return total
print(factorial(5))
os.system('cat myProgramLog.txt')
os.unlink('myProgramLog.txt')
def f156():
# IDLE Debuger
print('Should be installed and practised!')
def f157():
# Find the program bug!
'''
import random
guess = ''
while guess not in ('heads', 'tails'):
print('Guess the coin toss! Enter heads or tails:')
guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
if toss == guess:
print('You got it!')
else:
print('Nope! Guess again!')
guesss = input()
if toss == guess:
print('You got it!')
else:
print('Nope. You are really bad at this game.')
'''
print()
def f158():
# Chapter 11 - Web Scraping
print('''Chapter 11 - Web Scraping:
157 - Open google map address from terminal or clipboard
158 - Download Web Page with requests.get() Function
159 - Checking Downloading A Web Page
160 - Saving Downloaded Files to the Hard Drive
161 - Parsing HTML with the BeautifulSoup Module
162 - Creating a BeautifulSoup Object from local HTML file
163 - Finding an Element with the select() Method
164 - Getting Data from an Element’s Attributes
165 - I’m Feeling Lucky - Google Search
166 - Downloading All XKCD Comics
167 - Starting a Selenium-Controlled Browser
168 - Finding Elements on the Page
169 - WebElement Attributes and Methods
170 - Clicking the Page
171 - Filling Out and Submitting Forms
172 - Sending Special Keys
''')
def f159():
# Launch a new browser by webbrowser module
import webbrowser
webbrowser.open('https://www.google.com')
def f160():
# Open google map address from terminal or clipboard
import webbrowser, sys, pyperclip
# We chop off the first element of the array(i.e. script name)
if len(sys.argv) > 1:
# Get address from command line.
address = ' '.join(sys.argv[1:])
# address variable will be a string of commmand line arguments,
# which are separated with space, using list join method
else:
# Get address from clipboard.
address = pyperclip.paste()
webbrowser.open('https://www.google.com/maps/place/' + address)
# The address variable is the address in clipboard, or typed in
# clipboard, in a browser, you can open the google map url and
# append your address. Websites often add extra data to URLs to
# help to track visitors or customize sites.
def f161():
# Downloading a Web Page with the requests.get() Function
# First install requests module:
# sudo pip3 install requests
import requests
res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
print(type(res)) # returns a Response object, which contains the
# response that the web server gave for your request.
if res.status_code == requests.codes.ok:
print('Request for url succeeded!')
# If the request succeeded, the downloaded web page is stored as a string
# in the Response object’s text variable.
print(len(res.text)) # shows nr of characters for downloaded text
print(res.text[:250]) # displays only the first 250 characters
def f162():
# Checking Downloading A Web Page
import requests
res = requests.get('http://inventwithpython.com/page_that_does_not_exist')
# Raise the error when the request fails and by
# using try/except, avoid crashing the program:
try:
res.raise_for_status()
except Exception as exc:
print('There was a problem: %s' % (exc))
# Always call raise_for_status() after calling requests.get() . You want to be
# sure that the download has actually worked before your program continues.
def f163():
# Saving Downloaded Files to the Hard Drive
import requests, os
# 1.
# Create a Response object from URL address
res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
res.raise_for_status()
# 2.
# open the file in write binary mode (wb), even if the page is in
# plain-text, to maintain the Unicode encod-ing of the text.
playFile = open('RomeoAndJuliet.txt', 'wb')
# 3.
# Loop over the Response object’s iter_content() method.
# This avoids reading the content at once into memory for large responses.
for chunk in res.iter_content(100000): # chunk size is 100000 bytes
# 4.
# Call write() on each iteration to write the content to the file.
playFile.write(chunk)
# 5.
# Call close() to close the file.
playFile.close()
print('----------')
os.system('ls -l RomeoAndJuliet.txt')
os.unlink('RomeoAndJuliet.txt')
def f164():
# Parsing HTML with the BeautifulSoup Module
import requests, bs4
res = requests.get('http://nostarch.com')
res.raise_for_status()
noStarchSoup = bs4.BeautifulSoup(res.text, features="html.parser")
print(type(noStarchSoup))
'''This code uses requests.get() to download the main page from the
the website and then passes the text attribute of the response to
bs4.BeautifulSoup() . The BeautifulSoup object that it returns is
stored in a variable named noStarchSoup .
Once you have a BeautifulSoup object, you can use its methods to
locate specific parts of an HTML document.'''
def f165():
# Creating a BeautifulSoup Object from a local HTM
import requests, bs4, os
htmltext = '''<!-- This is the example.html example file. -->
<html><head><title>The Website Title</title></head>
<body>
<p>Download my <strong>Python</strong> book from <a href="http://
inventwithpython.com">my website</a>.</p>
<p class="slogan">Learn Python the easy way!</p>
<p>By <span id="author">Al Sweigart</span></p>
</body></html>'''
myFile = open('example.html', 'w')
myFile.write(htmltext)
myFile.close()
exampleFile = open('example.html')
exampleSoup = bs4.BeautifulSoup(exampleFile, features="html.parser")
print(type(exampleSoup))
os.system('rm -f example.html')
def f166():
# Finding an Element with the select() Method
import bs4, os
htmltext = '''<!-- This is the example.html example file. -->
<html><head><title>The Website Title</title></head>
<body>
<p>Download my <strong>Python</strong> book from <a href="http://
inventwithpython.com">my website</a>.</p>
<p class="slogan">Learn Python the easy way!</p>
<p>By <span id="author">Al Sweigart</span></p>
</body></html>'''
myFile = open('example.html', 'w')
myFile.write(htmltext)
myFile.close()
exampleFile = open('example.html')
exampleSoup = bs4.BeautifulSoup(exampleFile.read(), features="html.parser")
# The following matches any element that has an id attribute of author,
# as long as it is also inside a <p> element.
elems = exampleSoup.select('#author') # select stors a list of Tag
# objects in the elems variable
print(type(elems))
print(len(elems)) # tells us there is one Tag object in the list
print(type(elems[0]))
print(elems[0].getText()) # returns the element’s text, or inner HTML
print(str(elems[0]))
print(elems[0].attrs)
print('-----------')
pElems = exampleSoup.select('p') # pull all the <p> elements from the
# BeautifulSoup object, it gives 3 matches
print(str(pElems[0]))
print(pElems[0].getText())
print(str(pElems[1]))
print(pElems[1].getText())
print(str(pElems[2]))
print(pElems[2].getText())
os.system('rm -f example.html')
def f167():
# Getting Data from an Element’s Attributes
# The get() method for Tag objects makes it simple to access attribute values
# from an element. The method is passed a string of an attribute name and
# returns that attribute’s value.
import bs4, os
htmltext = '''<!-- This is the example.html example file. -->
<html><head><title>The Website Title</title></head>
<body>
<p>Download my <strong>Python</strong> book from <a href="http://
inventwithpython.com">my website</a>.</p>
<p class="slogan">Learn Python the easy way!</p>
<p>By <span id="author">Al Sweigart</span></p>
</body></html>'''
myFile = open('example.html', 'w')
myFile.write(htmltext)
myFile.close()
soup = bs4.BeautifulSoup(open('example.html'), features="html.parser")
spanElem = soup.select('span')[0]
print(str(spanElem))
print(spanElem.get('id')) # Passing the attribute name 'id' to get()
# returns the attribute’s value, 'author'
print(spanElem.get('some_nonexistent_addr') == None)
print(spanElem.attrs)
os.system('rm -f example.html')
def f168():
# I’m Feeling Lucky - Google Search
import requests, sys, webbrowser, bs4
### Step 1: Get the Command Line Arguments and Request the Search Page
# (Instead we get user input as search pattern)
# if you want to have the search terms as arguments of a separate running
# script, then use the following line of code:
# res = requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:]))
pattern = input('Enter your search pattern: ')
pattern = "' {} '".format(pattern) # enclose variable with quotes
res = requests.get('http://google.com/search?q=' + pattern )
print('Googling...') # display text while downloading the Google page
res.raise_for_status()
### Step 2: Find All the Results
# Retrieve top search result links:
soup = bs4.BeautifulSoup(res.text, features="html.parser")
linkElems = soup.select('.r a') # returns a list of all css class type 'r',
# which are in link 'a'
### Step 3: Open Web Browsers for Each Result
# number of tabs you want to open is either 5 or the length of this list:
numOpen = min(5, len(linkElems))
for i in range(numOpen): # Open a browser tab for each result.
webbrowser.open('http://google.com' + linkElems[i].get('href'))
def f169():
# Downloading All XKCD Comics
import requests, os, bs4
### Step 1 - TODO: Download the web page.
url = 'http://xkcd.com' # starting url
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
while not url.endswith('#'):
print('Downloading page %s...' % url)
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, features="html.parser")
### Step 2 - TODO: Find the URL of the comic image.
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = comicElem[0].get('src').strip("http://")
comicUrl="http://"+comicUrl
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
### Step 3: Save the Image and Find the Previous Comic
# 100000 bytes of image size will be written each time to the file
# join funcion puts an slash after folder name: xkcd/file_name.png
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
### Step 4: Get the Prev button's url, and repeating the loop
prevLink = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prevLink.get('href')
# the selector 'a[rel="prev"]' identifies the <a> element with
# the rel attribute set to prev , and you can use this <a> element’s href
# attribute to get the previous comic’s URL, which gets stored in url.
# Now the same process continue for the new url, up to when url ends with #.
print('Done.')
def f170():
# Starting a Selenium-Controlled Browser
from selenium import webdriver
browser = webdriver.Firefox() # opens firefox browser, with no url loaded
print(type(browser)) # prints the class type of browser:
# <class 'selenium.webdriver.firefox.webdriver.WebDriver'>
browser.get('http://inventwithpython.com') # opens the url in the already opened
# firefox browser
def f171():
# Finding Elements on the Page
from selenium import webdriver
browser = webdriver.Firefox() # opens firefox browser, with no url loaded
browser.get('http://inventwithpython.com') # loads the url argument in browser
try:
elem = browser.find_element_by_class_name('card-img-top')
# The find_element_* methods is looking just for a single element,
# while find_elements_* methods returns a list of WebElement_* objects.
print('Found <%s> element with that class name!' % (elem.tag_name))
except:
print('Was not able to find an element with that name.')
# The output will be:
# Found <img> element with that class name!
# To see the list of methods refer to item 159 in main menu !
def f172():
# WebElement Attributes and Methods
'''
.................................................
Selenium’s WebDriver Methods for Finding Elements
.................................................
- Elements that use the CSS class name:
browser.find_element_by_class_name(name)
browser.find_elements_by_class_name(name)
- Elements that match the CSS selector
browser.find_element_by_css_selector(selector)
browser.find_elements_by_css_selector(selector)
- Elements with a matching id attribute value
browser.find_element_by_id(id)
browser.find_elements_by_id(id)
- <a> elements that completely match the text provided
browser.find_element_by_link_text(text)
browser.find_elements_by_link_text(text)
- <a> elements that contain the text provided
browser.find_element_by_partial_link_text(text)
browser.find_elements_by_partial_link_text(text)
- Elements with a matching name attribute value
browser.find_element_by_name(name)
browser.find_elements_by_name(name)
- Elements with a matching tag name
(case insensitive; an <a> element is matched by 'a' and 'A')
browser.find_element_by_tag_name(name)
browser.find_elements_by_tag_name(name)
.................................
WebElement Attributes and Methods
.................................
tag_name - The tag name, such as 'a' for an <a> element
get_attribute(name) - The value for the element’s name attribute
text - The text within the element, such as 'hello' in <span>hello</span>
clear() - For text field or text area elements, clears the text typed into it
is_displayed() - Returns True if the element is visible; otherwise returns False
is_enabled() - For input elements, returns True if the element is enabled; other-
wise returns False
is_selected() - For checkbox or radio button elements, returns True if the ele-
ment is selected; otherwise returns False
location - A dictionary with keys 'x' and 'y' for the position of the ele-
ment in the page
'''
def f173():
# Clicking the Page
from selenium import webdriver
# opens firefox browser, with no url loaded
browser = webdriver.Firefox()
# load the url argument in browser
browser.get('http://inventwithpython.com')
linkElem = browser.find_element_by_link_text('Read Online for Free')
print(type(linkElem))
# It prints:
# <class 'selenium.webdriver.remote.webelement.WebElement'>
linkElem.click() # follows the "Read It Online" link
# click() simulate mouse click on the first
# link element with text as:
# 'Read Online for Free'
def f174():
# Filling Out and Submitting Forms, automate browser login
from selenium import webdriver
# open firefox browser, with no url loaded
browser = webdriver.Firefox()
# load the url argument in browser
browser.get('http://gmail.com')
emailElem = browser.find_element_by_id('identifierId')
emailElem.send_keys('[email protected]')
passwordElem = browser.find_element_by_id('Passwd')
passwordElem.send_keys('12345')
passwordElem.submit()
'''
The previous code will fill in those text fields with the pro-
vided text.
You can always use the browser’s inspector to verify the id.
Calling the submit() method on any element will have the same
result as clicking the Submit button for the form that element
is in.
'''
def f175():
# Sending Special Keys
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox() # opens just the firefox browser,
# no url loaded is loaded
browser.get('http://nostarch.com') # loads url in browser
htmlElem = browser.find_element_by_tag_name('html')
htmlElem.send_keys(Keys.END) # scrolls to bottom
# To scroll up again uncomment the following
# htmlElem.send_keys(Keys.HOME) # scrolls to top
'''Commonly Used Variables in the selenium.webdriver.common.keys Module
Keys.DOWN , Keys.UP , Keys.LEFT , Keys.RIGHT The keyboard arrow keys
Keys.ENTER , Keys.RETURN The Enter or RETURNS keys
Keys.HOME , Keys.END , Keys.PAGE_DOWN, Keys.PAGE_UP HOME,END, ...
Keys.ESCAPE , Keys.BACK_SPACE , Keys.DELETE esc , backspace , DELETE
Keys.F1 , Keys.F2 , . . . , Keys.F12 F1 to F12
Keys.TAB The tab key
- Selenium can simulate clicks on various browser buttons by
following methods:
browser.back() Clicks the Back button.
browser.forward() Clicks the Forward button.
browser.refresh() Clicks the Refresh/Reload button.
browser.quit() Clicks the Close Window button.
Selenium reference: http://selenium-python.readthedocs.org/
'''
def f176():
#
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
def f177():
# Download an image from webserver while showing the file
# header response information and dowloaded chuncks of data,
# during the download
import socket, time
HOST = 'data.pr4e.org'
PORT = 80
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((HOST, PORT))
mysock.sendall(b'GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n')
count = 0
picture = b""
while True:
data = mysock.recv(5120)
if len(data) < 1: break
time.sleep(0.25)
count = count + len(data)
print(len(data), count)
picture = picture + data
mysock.close()
# Look for the end of the header (2 CRLF)
pos = picture.find(b"\r\n\r\n")
print('Header length', pos)
print(picture[:pos].decode())
# Skip past the header and save the picture data
picture = picture[pos+4:]
fhand = open("stuff.jpg", "wb")
fhand.write(picture)
fhand.close()
def f178():
# Retrieve a web page over a socket and display the headers
# from the web server.
import socket
HOST = input('Enter webserver URL: ')
DOC = input('Enter document to be retrived [Press Enter to default index.html]: ')
if DOC == '': DOC = 'index.html'
PORT = input('Enter port number [Press Enter to default 80]: ')
if PORT == '': PORT = 80
# Open a connection
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((HOST, PORT))
cmd = 'GET http://' + HOST + '/' + DOC + ' HTTP/1.0\r\n\r\n'
cmd = cmd.encode()
print(cmd)
mysock.send(cmd)
receivedData = b""
while True:
data = mysock.recv(512)
if len(data) < 1: break
receivedData = receivedData + data
mysock.close()
pos = receivedData.find(b"\r\n\r\n")
print('Header length', pos)
print(receivedData[:pos].decode())
def f179():
# Load a web document, browser simulation
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
def f180():
# Open a web page with urlib module
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
for line in fhand:
print(line.decode().strip())
# This program displays the html document as you see the sour-
# ce code in browser. The urlopen returns an object similar to
# file handle that can be manipulated the same way as a file.
# For example, you can iterate each line of html document, or
# any other oprations.
def f181():
# Count the number of words in a web page
import urllib.request, urllib.parse, urllib.error, pprint
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict() # Creates an empty dictionary
for line in fhand:
words = line.decode().split() # line coming from webserver
# will be decoded and split-
# ted as words.
# decode converts to string.
for word in words: # Use a dictionary to count the words
counts[word] = counts.get(word, 0) + 1
# get(dic_key, set_default) is used to get value for a
# key in dictionay, if not exists, here is set to 0.
pprint.pprint(counts)
# Here is another operation, counting number of the words in a
# html document. Here html document, has been treated like a
# regular file, with urlopen() function.
def f182():
# Search for link values within URL input - using RE
import urllib.request, urllib.parse, urllib.error
import re
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urllib.request.urlopen(url).read()
links = re.findall(b'href="(http[s]?://.*?)"', html)
for link in links:
print(link.decode())
def f183():
# Retrieve href links from html document with BeautifulSoup
# To run this, you can install BeautifulSoup
# https://pypi.python.org/pypi/beautifulsoup4
# Or download the file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# BeautifulSoup link:
# http://www.crummy.com/software/BeautifulSoup/
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
fhand = urllib.request.urlopen(url, context=ctx)
# fhand type is: <class 'http.client.HTTPResponse'>
html = fhand.read() # html has the type: <class 'bytes'>
soup = BeautifulSoup(html, 'html.parser')
# Here we get a clean and well structured object of type:
# <class 'bs4.BeautifulSoup'>
# Retrieve all of the anchor tags
tags = soup('a') # <class 'bs4.element.ResultSet'>
for tag in tags:
print(tag.get('href', None))
def f184():
# Hoping from an html link to another, with specified rule
# Assignment: Following Links in HTML Using BeautifulSoup
# In this assignment you will write a Python program that exp-
# ands on https://www.py4e.com/code3/urllinks.py . The program
# will use urllib to read the HTML from the data files below,
# extract the href=values from the anchor tags, scan for a tag
# that is in a particular position from the top and follow
# that link, repeat the process a number of times, and report
# the last name you find.
# url = 'http://py4e-data.dr-chuck.net/known_by_Fikret.html'
# url = 'http://py4e-data.dr-chuck.net/known_by_Beraka.html'
url = input('Enter URL: ')
count = int(input('Enter count: '))
position = int(input('Enter position: '))
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
def openurl(link):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
html = urllib.request.urlopen(link, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all of the anchor tags
tags = soup('a')
for pos, tag in enumerate(tags, 1):
if pos == position:
return tag.get('href', None)
for i in range(count):
print('Retrieving: ', openurl(url))
url = openurl(url)
# for pos, tag in enumerate(tags, 1): print(pos, tag.get('href', None))
def f185():
# Scraping HTML Data with without BeautifulSoup
# Write a Python program to use urllib to read the HTML from the -
# data files below, and parse the data, extracting numbers and co-
# mpute the sum of the numbers in the file
dataFile = 'http://py4e-data.dr-chuck.net/comments_229270.html'
# dataFile = 'http://www.dr-chuck.com'
# dataFile = input('Enter: ')
import urllib.request, re
fhand = urllib.request.urlopen(dataFile)
allNumbers = []
for line in fhand:
line = line.decode().rstrip()
if re.search('[0-9]+', line) == None : continue
numbers = re.findall('>0*([0-9]+)<', line)
allNumbers.extend(numbers)
total = 0
for n in allNumbers:
total = total + int(n)
print('Count: ', len(allNumbers))
print('Sum of all numbers: ', total)
def f186():
# Scraping HTML Data with BeautifulSoup
# Write a Python program to use urllib to read the HTML from the -
# data files below, and parse the data, extracting numbers and co-
# mpute the sum of the numbers in the file
url = input('Enter : ')
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
spanContent = []
tags = soup('span')
for tag in tags:
# print('Contents:', tag.contents[0].split())
spanContent.extend(tag.contents[0].split())
# print(spanContent)
print('Count: ', len(spanContent))
total = 0
for n in spanContent:
total = total + int(n)
print('Sum: ', total)
def f187():
# Retrieve links from html with specific conditions
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors for https
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
todo = list()
visited = list()
url = input('Enter - ')
todo.append(url)
count = int(input('How many to retrieve - '))
while len(todo) > 0 and count > 0 :
print("====== To Retrieve:",count, "Queue Length:", len(todo))
url = todo.pop()
count = count - 1
if (not url.startswith('http')):
print("Skipping", url)
continue
if (url.find('facebook') > 0):
continue
if (url.find('linkedin') > 0):
continue
if (url in visited):
print("Visited", url)
continue
print("===== Retrieving ", url)
try:
html = urllib.request.urlopen(url, context=ctx).read()
except:
print("*** Error in retrieval")
continue
soup = BeautifulSoup(html, 'html.parser')
visited.append(url)
# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
newurl = tag.get('href', None)
if (newurl is not None):
todo.append(newurl)
def f188():
# Chapter 12 - Working with Excel Spreadsheets
print('Chapter 12 - Working with Excel Spreadsheets')
def f189():
# Opening Excel Documents with OpenPyXL
# To work with Excel documents first install the module:
# sudo pip3 install OpenPyXL
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
# This does not open the file
print(type(wb)) # Returns workbook data type
# printing list of all the sheet names in the workbook
print(wb.get_sheet_names())
sheet = wb.get_sheet_by_name('Sheet3')
# Returns only the name of Sheet3 to variable sheet
print(sheet)
print(type(sheet)) # Returns Worksheet data type
print(sheet.title) #
# The active sheet is the sheet that’s on top when the
# workbook is opened in Excel.
# To get the workbook’s active sheet:
anotherSheet = wb.get_active_sheet()
print(anotherSheet)
def f190():
# Getting Cells from the Sheets
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
# This does not open the file, just loads the file in memory
sheet = wb.get_sheet_by_name('Sheet1')
print(sheet['A1'])
print(sheet['A1'].value) # Note: cell A1 is quoted!
c = sheet['B1'] # Note: cell B1 is quoted!
print(c.value)
print('Row ' + str(c.row) + ', Column ' + str(c.column) + ' is '
+ c.value)
print('Cell ' + c.coordinate + ' is ' + c.value)
print(sheet['C1'].value)
# 'value' is an attribute of Cell objects.
# Cell objects also have row , column , and coordinate attri-
# butes that provide location information for the cell.
def f191():
# excel sheet cell() method
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
sheet.cell(row=1, column=2) # <Cell Sheet1.B1>
sheet.cell(row=1, column=2).value # 'Apples'
for i in range(1, 8, 2):
print(i, sheet.cell(row=i, column=2).value)
def f192():
# Determine the size of the sheet
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
# Following deprecated:
# print(sheet.get_highest_row()) # 7
# print(sheet.get_highest_column()) # 3
print(sheet.max_row) # 7
print(sheet.max_column) # 3
def f193():
# Converting Between Column Letters and Numbers
import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string
get_column_letter(1) # 'A'
get_column_letter(2) # 'B'
get_column_letter(27) # 'AA'
get_column_letter(900) # 'AHP'
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
# Following deprecated:
# get_column_letter(sheet.get_highest_column()) #'C'
print(get_column_letter(sheet.max_column)) #'C'
print(column_index_from_string('A')) # 1
print(column_index_from_string('AA')) # 27
def f194():
# Getting Rows and Columns from the Sheets
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
print(tuple(sheet['A1':'C3']))
for rowOfCellObjects in sheet['A1':'C3']:
for cellObj in rowOfCellObjects:
print(cellObj.coordinate, cellObj.value)
print('--- END OF ROW ---')
# To print the values of each cell in the area, we use two for
# loops. The outer for loop goes over each row in the slice.
# Then, for each row, the nested for loop goes through each
# cell in that row.
def f195():
# Access the values of cells in a particular row or column
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_active_sheet()
print(list(sheet.columns)[1])
for cellObj in list(sheet.columns)[1]:
print(cellObj.value)
# Quick Review
# 1. Import the openpyxl module.
# 2. Call the openpyxl.load_workbook() function.
# 3. Get a Workbook object.
# 4. Call the get_active_sheet() or get_sheet_by_name()
# workbook method.
# 5. Get a Worksheet object.
# 6. Use indexing or the cell() sheet method with row and
# column keyword arguments.
# 7. Get a Cell object.
# 8. Read the Cell object’s value attribute.
def f196():
# Reading Data from a Spreadsheet
# Tabulates population and number of census tracts for
# each county.
import openpyxl, pprint
print('Opening workbook...')
wb = openpyxl.load_workbook('censuspopdata.xlsx')
sheet = wb.get_sheet_by_name('Population by Census Tract')
countyData = {}
# Fill in countyData with each county's population and tracts.
print('Reading rows...')
# iterating over the rowa
# method sheet.get_highest_row(), has been deprecated and ins-
# tead we use sheet.max_row
for row in range(2, sheet.max_row + 1):
# Each row in the spreadsheet has data for one census tract.
state = sheet['B' + str(row)].value
county = sheet['C' + str(row)].value
pop = sheet['D' + str(row)].value
# Make sure the key for this state exists.
countyData.setdefault(state, {})
# Make sure the key for this county in this state exists.
countyData[state].setdefault(county, {'tracts': 0, 'pop': 0})
# Each row represents one census tract, so increment by one.
countyData[state][county]['tracts'] += 1
# Increase the county pop by the pop in this census tract.
countyData[state][county]['pop'] += int(pop)
# Open a new text file and write the contents of countyData to it.
print('Writing results...')
resultFile = open('census2010.py', 'w')
resultFile.write('allData = ' + pprint.pformat(countyData))
resultFile.close()
print('Done.')
def f197():
# Writing Excel Documents
import openpyxl
wb = openpyxl.Workbook() #creates a new, blank Workbook object
# No document wil be saved unil usinfg save method.
wb.get_sheet_names()
sheet = wb.get_active_sheet()
print(sheet.title)
sheet.title = 'Spam Bacon Eggs Sheet'
wb.get_sheet_names()
def f198():
# Create and save a spreed sheet
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_active_sheet()
sheet.title = 'Spam Spam Spam'
wb.save('example_copy.xlsx')
def f199():
# Creating and Removing Sheets
import openpyxl
wb = openpyxl.Workbook()
print(wb.get_sheet_names())
wb.create_sheet(index=0, title='First Sheet')
print(wb.get_sheet_names())
wb.create_sheet(index=2, title='Middle Sheet')
print(wb.get_sheet_names())
wb.remove_sheet(wb.get_sheet_by_name('Middle Sheet'))
print(wb.get_sheet_names())
wb.remove_sheet(wb.get_sheet_by_name('First Sheet'))
print(wb.get_sheet_names())
# If you want the new created excel be saved, uncomment this:
# wb.save('test.xlsx')
def f200():
# Writing Values to Cells
import openpyxl
# Writing values to cells is much like writing values to keys
# in a dictionary.
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
sheet['A1'] = 'Hello world!'
print(sheet['A1'].value)
# If you want the new created excel be saved, uncomment this:
# wb.save('test.xlsx')
def f201():
# Project: Updating a Spreadsheet
# This program updates prices for specific produces in file
# 'produceSales.xlsx'
import openpyxl
wb = openpyxl.load_workbook('produceSales.xlsx')
sheet = wb.get_sheet_by_name('Sheet')
# The produce types and their updated prices
PRICE_UPDATES = {'Garlic': 3.07,
'Celery': 1.19,
'Lemon': 1.27}
# Loop through the rows and update the prices.
# skip the first row:
for rowNum in range(2, sheet.max_row):
# The cell in column 1 (that is, column A) will be stored
# in the variable produceName
produceName = sheet.cell(row=rowNum, column=1).value
# If produceName exists as a key in the PRICE_UPDATES
# dictionary, then update the cell
if produceName in PRICE_UPDATES:
sheet.cell(row=rowNum, column=2).value = PRICE_UPDATES[produceName]
wb.save('updatedProduceSales.xlsx')
def f202():
# Setting the Font Style of Cells
import openpyxl
from openpyxl.styles import NamedStyle, Font, Border, Side
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
highlight = NamedStyle(name="highlight")
highlight.font = Font(size=24, italic=True)
# Once a named style has been created, it can be registered
# with the workbook:
wb.add_named_style(highlight)
# But named styles will also be registered automatically the
# first time they are assigned to a cell:
sheet['A1'].style = highlight
sheet['A1'] = 'Hello world!'
wb.save('styled.xlsx')
def f203():
# Font object
import openpyxl
from openpyxl.styles import Font, NamedStyle
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
fontObj1 = NamedStyle(name="fontObj1")
fontObj1.font = Font(name='Times New Roman', bold=True)
sheet['A1'].style = fontObj1
sheet['A1'] = 'Bold Times New Roman'
fontObj2 = NamedStyle(name="fontObj2")
fontObj2.font = Font(size=24, italic=True)
sheet['B3'].style = fontObj2
sheet['B3'] = 'Bold Times New Roman'
wb.save('styles.xlsx')
def f204():
# Formulas
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.get_active_sheet()
sheet['A1'] = 200
sheet['A2'] = 300
sheet['A3'] = '=SUM(A1:A2)'
wb.save('writeFormula.xlsx')
def f205():
# loading a workbook with and without the data_only keyword
# argument
import openpyxl
wbFormulas = openpyxl.load_workbook('writeFormula.xlsx')
sheet = wbFormulas.get_active_sheet()
print(sheet['A3'].value)
wbDataOnly = openpyxl.load_workbook('writeFormula.xlsx',
data_only=True)
ws = wbDataOnly.get_active_sheet()
print(ws['A3'].value)
# in my case it shows None
def f206():
# Setting Row Height and Column Width
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.get_active_sheet()
sheet['A1'] = 'Tall row'
sheet['B2'] = 'Wide column'
sheet.row_dimensions[1].height = 70
sheet.column_dimensions['B'].width = 20
wb.save('dimensions.xlsx')
def f207():
# Merging and Unmerging Cells
# A rectangular area of cells can be merged into a single cell
# with the merge_cells() sheet method
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.get_active_sheet()
sheet.merge_cells('A1:D3')
sheet['A1'] = 'Twelve cells merged together.'
sheet.merge_cells('C5:D5')
sheet['C5'] = 'Two merged cells.'
wb.save('merged.xlsx')
def f208():
# Unmerge cells
# To unmerge cells, call the unmerge_cells() sheet method
import openpyxl
wb = openpyxl.load_workbook('merged.xlsx')
sheet = wb.get_active_sheet()
sheet.unmerge_cells('A1:D3')
sheet.unmerge_cells('C5:D5')
wb.save('merged.xlsx')
def f209():
# Freeze Panes - Pan is visible top rows or leftmost columns
# to a specific cell that is helpfull to be used for larg spr-
# eadsheets to display all at once.
# sheet.freeze_panes = 'A2' Row 1 is frozen
# sheet.freeze_panes = 'B1' Column A is frozen
# sheet.freeze_panes = 'C1' Columns A and B are frozen
# sheet.freeze_panes = 'C2' Row 1 and columns A and B
# sheet.freeze_panes = 'A1' No frozen panes
# sheet.freeze_panes = None No frozen panes
import openpyxl
wb = openpyxl.load_workbook('produceSales.xlsx')
sheet = wb.get_active_sheet()
sheet.freeze_panes = 'A2' # The row header si visible, even when
# scroll down
wb.save('freezeExample.xlsx')
# To unfreez all pan set the the atribute to None
def f210():
# Charts
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for i in range(10):
ws.append([i])
from openpyxl.chart import BarChart, Reference, Series
values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)
ws.add_chart(chart, "E15")
wb.save("sampleChart.xlsx")
# For complete documentation refere to:
# https://openpyxl.readthedocs.io/en/stable/charts/introduction.html
def f211():
# Chapter 13 - Working with PDF and Word Documents
print('Chapter 13 - Working with PDF and Word Documents')
def f212():
# Extracting Text from PDFs
# sudo pip3 install PyPDF2
import PyPDF2
pdfFileObj = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
print(pdfReader.numPages)
pageObj = pdfReader.getPage(0)
print(pageObj.extractText())
def f213():
# Decrypting PDFs
import PyPDF2
pdfReader = PyPDF2.PdfFileReader(open('encrypted.pdf', 'rb'))
print(pdfReader.isEncrypted)
# When you try uncomment following, you get error(encrypted)
# pdfReader.getPage(0)
pdfReader.decrypt('rosebud') # password='rosebud'
pageObj = pdfReader.getPage(0) # No more error you get
print(pageObj.extractText())
def f214():
# copy pages from one PDF document to another
# files 'meetingminutes.pdf' and 'meetingminutes2.pdf' must
# exist in current directory!
import PyPDF2, os
if not os.path.isfile('meetingminutes.pdf'):
print('meetingminutes.pdf is required in current working directory!')
return
pdf1File = open('meetingminutes.pdf', 'rb')
pdf2File = open('meetingminutes2.pdf', 'rb')
pdf1Reader = PyPDF2.PdfFileReader(pdf1File)
pdf2Reader = PyPDF2.PdfFileReader(pdf2File)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdf1Reader.numPages):
pageObj = pdf1Reader.getPage(pageNum)
pdfWriter.addPage(pageObj)
for pageNum in range(pdf2Reader.numPages):
pageObj = pdf2Reader.getPage(pageNum)
pdfWriter.addPage(pageObj)
pdfOutputFile = open('combinedminutes.pdf', 'wb')
pdfWriter.write(pdfOutputFile)
pdfOutputFile.close()
pdf1File.close()
pdf2File.close()
def f215():
# Rotating Pages
# file 'meetingminutes.pdf' must be in current directory!
import PyPDF2, os
if not os.path.isfile('meetingminutes.pdf'):
print('meetingminutes.pdf is required in current working directory!')
return
minutesFile = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(minutesFile)
page = pdfReader.getPage(0)
page.rotateClockwise(90)
pdfWriter = PyPDF2.PdfFileWriter()
pdfWriter.addPage(page)
resultPdfFile = open('rotatedPage.pdf', 'wb')
pdfWriter.write(resultPdfFile)
resultPdfFile.close()
minutesFile.close()
def f216():
# Overlaying Pages
# files 'meetingminutes.pdf' and 'watermark.pdf' must exist in
# current directory!
import os
if not os.path.isfile('meetingminutes.pdf') and os.path.isfile('watermark.pdf'):
print('meetingminutes.pdf and watermark.pdf are required!')
return
import PyPDF2
minutesFile = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(minutesFile)
minutesFirstPage = pdfReader.getPage(0)
pdfWatermarkReader = PyPDF2.PdfFileReader(open('watermark.pdf', 'rb'))
minutesFirstPage.mergePage(pdfWatermarkReader.getPage(0))
pdfWriter = PyPDF2.PdfFileWriter()
pdfWriter.addPage(minutesFirstPage)
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
resultPdfFile = open('watermarkedCover.pdf', 'wb')
pdfWriter.write(resultPdfFile)
minutesFile.close()
resultPdfFile.close()
def f217():
# Encrypting PDFs
import PyPDF2
pdfFile = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWriter.encrypt('swordfish')
resultPdf = open('encryptedminutes.pdf', 'wb')
pdfWriter.write(resultPdf)
resultPdf.close()
def f218():
# Combining Select Pages from Many PDFs
import PyPDF2, os
# Get all the PDF filenames.
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith('.pdf'):
pdfFiles.append(filename)
pdfFiles.sort(key=str.lower)
pdfWriter = PyPDF2.PdfFileWriter()
# Loop through all the PDF files.
for filename in pdfFiles:
pdfFileObj = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# TODO: Loop through all the pages (except the first) and
# add them.
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# Save the resulting PDF to a file.
pdfOutput = open('allminutes.pdf', 'wb')
pdfWriter.write(pdfOutput)
pdfOutput.close()
def f219():
# Word Documents
# sudo pip3 install python-docx (install module 'python-docx')
# file 'demo.docx' must be in working directory.
import docx
doc = docx.Document('demo.docx') # return a Document object
print(len(doc.paragraphs)) # a list of paragraph objects
# string of the text in paragraph[0]:
print(doc.paragraphs[0].text)
# string of the text in paragraph[1]
print(doc.paragraphs[1].text)
# Each paragraph object has a list of Run objects
print(len(doc.paragraphs[1].runs))
print(doc.paragraphs[1].runs[0].text)
print(doc.paragraphs[1].runs[1].text)
print(doc.paragraphs[1].runs[2].text)
print(doc.paragraphs[1].runs[3].text)
def f220():
# Getting the Full Text from a .docx File
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
# fullText.append(para.text)
fullText.append(' ' + para.text)
return '\n'.join(fullText)
print(getText('demo.docx'))
def f221():
# Styling Paragraph and Run Attributes
print('''
The string values for the default Word styles are:
Normal BodyText BodyText2 BodyText3 Caption Heading1 Heading2
Heading3 Heading4 Heading5 Heading6 Heading7 Heading8 Heading9
IntenseQuote List List2 List3 ListBullet ListBullet2 ListBullet3
ListContinue ListContinue2 ListContinue3 ListNumber ListNumber2
ListNumber3 ListParagraph MacroText NoSpacing Quote Subtitle
TOCHeading Title
''')
print('''
Run attributes are:
bold italic underline strike double_strike all_caps small_caps
shadow outline rtl imprint emboss
''')
def f222():
# Creating Word Documents with Nondefault Styles
import docx
doc = docx.Document('demo.docx')
doc.paragraphs[0].text
'Document Title'
print(doc.paragraphs[0].style) #'Title'
doc.paragraphs[0].style = 'Normal'
print(doc.paragraphs[1].text)
# returns:
# 'A plain paragraph with some bold and some italic'
(doc.paragraphs[1].runs[0].text, doc.paragraphs[1].runs[1].text, doc.
paragraphs[1].runs[2].text, doc.paragraphs[1].runs[3].text)
# output:
# ('A plain paragraph with some ', 'bold', ' and some ', 'italic')
doc.paragraphs[1].runs[0].style = 'QuoteChar'
doc.paragraphs[1].runs[1].underline = True
doc.paragraphs[1].runs[3].underline = True
doc.save('restyled.docx')
def f223():
# Writing Word Documents
import docx
doc = docx.Document()
print(doc.add_paragraph('Hello world!'))
doc.save('helloworld.docx')
def f224():
# Add paragraphs
import docx
doc = docx.Document()
doc.add_paragraph('Hello world!')
paraObj1 = doc.add_paragraph('This is a second paragraph.')
paraObj2 = doc.add_paragraph('This is a yet another paragraph.')
paraObj1.add_run(' This text is being added to the second paragraph.')
doc.save('multipleParagraphs.docx')
def f225():
# Adding Headings
import docx
doc = docx.Document()
doc.add_heading('Header 0', 0)
doc.add_heading('Header 1', 1)
doc.add_heading('Header 2', 2)
doc.add_heading('Header 3', 3)
doc.add_heading('Header 4', 4)
doc.save('headings.docx')
def f226():
# Adding Line and Page Breaks and Adding Pictures
import docx, os
if not os.path.isfile('zophie.png'):
print('zophie.png is required in current working directory!')
return
doc = docx.Document()
doc.add_paragraph('This is on the first page!')
# Following didn't work, for page break
# doc.paragraphs[0].runs[0].add_break(docx.text.WD_BREAK.PAGE)
doc.add_page_break()
doc.add_paragraph('This is on the second page!')
# doc.save('twoPage.docx')
doc.add_picture('zophie.png', width=docx.shared.Inches(1),
height=docx.shared.Cm(4))
doc.save('twoPage.docx')
def f227():
# Chapter 14 - Working with CSV Files and JSON Data
data = '''
Working with CSV Files and JSON Data
Function
no Topic
........ ......
227 - Read data from a CSV file
228 - Reading Data from Reader Objects in a for Loop
229 - Writer object
230 - The delimeter and lineterminator keyword arguments
231 - Project: Removing the Header from CSV Files
232 - JSON and API description
233 - Reading JSON with the loads() Function
234 - Writing JSON with the dumps() Function
235 - Project: Fetching Current Weather Data
236 - json1.py
237 - json2.py
238 - geojson.py
239 - twtest.py
240 - twitter1.py
241 - twitter2.py
242 - Parsing and extracting elements from xml
243 - Parsing an extracting elements from a multiple node xml
244 - Iterate and change xml tree elements to strings
245 - Extract all tags with non empty inner text from xml document
246 - Read from remote xml tags with numbers and compute the sum
'''
print(data)
def f228():
# Read data from a CSV file with csv module,
# you need to create a Reader object
# csv is built in module
import csv, os
from pprint import pprint
if not os.path.isfile('example.csv'):
print('example.csv is required in current working directory!')
return
# open a file just any other text file, with open()
exampleFile = open('example.csv')
# instead of read/readlines for files use reader method:
exampleReader = csv.reader(exampleFile) # returns a Reader obj
# To access values, convert the reader object to a list:
exampleData = list(exampleReader)
pprint(exampleData)
def f229():
# Reading Data from Reader Objects in a for Loop
import csv, os
if not os.path.isfile('example.csv'):
print('example.csv is required in current working directory!')
return
exampleFile = open('example.csv')
exampleReader = csv.reader(exampleFile)
for row in exampleReader:
# to get the row number in Reader object use
# variable line_num
print('Row #' + str(exampleReader.line_num) + \
' ' + str(row))
# The Reader object can be looped over only once
def f230():
# Writer object
# A Writer object lets you write data to csv file.
import csv
# Open a file in write mode:
outputFile = open('output.csv', 'w', newline='')
# If you forget the newline='' keyword argument in open(), the
# CSV file will be double-spaced.
# Create a Writer object:
outputWriter = csv.writer(outputFile)
outputWriter.writerow(['spam', 'eggs', 'bacon', 'ham'])
outputWriter.writerow(['Hello, world!', 'eggs', 'bacon', 'ham'])
outputWriter.writerow([1, 2, 3.141592, 4])
outputFile.close()
with open('output.csv') as myFile: print(myFile.read())
def f231():
# The 'delimiter' and 'lineterminator' keyword arguments
# We change the above arguments to change the default values.
# Arguments default values are comma and '\n'.
import csv
csvFile = open('example.tsv', 'w', newline='')
csvWriter = csv.writer(csvFile, delimiter='\t',
lineterminator='\n\n')
csvWriter.writerow(['apples', 'oranges', 'grapes'])
csvWriter.writerow(['eggs', 'bacon', 'ham'])
csvWriter.writerow(['spam', 'spam', 'spam', 'spam', 'spam',
'spam'])
csvFile.close()
def f232():
# Project: Removes the header from all CSV files in the current
# working directory.
import csv, os
os.makedirs('headerRemoved', exist_ok=True)
# Step 1: Loop Through Each CSV File
# ...................................
for csvFilename in os.listdir('.'):
if not csvFilename.endswith('.csv'):
continue
# makes the for loop move on to the next
# filename when it comes across a non-CSV file
print('Removing header from ' + csvFilename + '...')
# Step 2: Read in the CSV File (skipping first row)
# .................................................
csvRows = []
csvFileObj = open(csvFilename)
readerObj = csv.reader(csvFileObj)
for row in readerObj:
if readerObj.line_num == 1:
continue # skip first row
csvRows.append(row)
csvFileObj.close()
# Step 3: Write Out the CSV File Without the First Row
# .....................................................
csvFileObj = open(os.path.join('headerRemoved',
csvFilename), 'w', newline='')
csvWriter = csv.writer(csvFileObj)
for row in csvRows:
csvWriter.writerow(row)
csvFileObj.close()
def f233():
# What is JSON
print('''
JavaScript Object Notation is a popular way to format data as
a single human-readable string. JSON is the native way that -
JavaScript programs write their data structures and usually -
resembles what Python’s pprint function would produce. Ex:
{"name": "Zophie", "isCat": true,
"miceCaught": 0, "napsTaken": 37.5,
"felineIQ": null}
Many websites offer JSON content as a way for programs to int-
eract with the website. This is known as providing an API. Ac-
cessing an API is the same as accessing any other web page via
a URL. The difference is that the data returned by an API is -
formatted with JSON. Facebook, Twitter, Yahoo, Google, Tumblr,
Wikipedia, Flickr, Data.gov, Reddit, IMDb, Rotten Tomatoes, -
LinkedIn, and many other offer APIs for programs to use. Some
of these sites require registration, which is almost always -
free. You’ll have to find documentation for what URLs your pr-
ogram needs to request in order to get the data you want, as -
well as the general format of the JSON data structures, which
are returned.
This documentation should be provided by whatever site is off-
ering the API; if they have a “Developers” page, look for the
documentation there. What you can do with JSON:
- Scrape raw data from websites.
Accessing APIs and parsing HTML with Beautiful Soup.
- Automatically download new posts from one of your social ne-
twork accounts and post them to another account.
- Pulling data from IMDb, Rotten Tomatoes, and Wikipedia and -
putting it into a single text file.
''')
def f234():
# Reading JSON with the loads() Function
# To translate a string containing JSON data into a Python
# value, pass it to the json.loads() function.
# JSON strings always use double quotes
stringOfJsonData = '{"name": "Zophie", "isCat": true, \
"miceCaught": 0, "felineIQ": null}'
import json # built-in module
jsonDataAsPythonValue = json.loads(stringOfJsonData)
print(jsonDataAsPythonValue)
def f235():
# Writing JSON with the dumps() Function
# The json.dumps() function ("dump string") translate a Python
# value into a string of JSON-formatted data.
pythonValue = {'isCat': True, 'miceCaught': 0,
'name': 'Zophie', 'felineIQ': None}
import json
stringOfJsonData = json.dumps(pythonValue)
print(stringOfJsonData)
def f236():
# Project: Fetching Current Weather Data
import json, requests, sys
# Step 1: Get Location from the Command Line Argument
# # Compute location from command line arguments.
# if len(sys.argv) < 2:
# print('Usage: quickWeather.py location')
# sys.exit()
# location = ' '.join(sys.argv[1:])
location = 'San Francisco CA'
# Step 2: Download the JSON Data
url ='http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt=3' % (location)
response = requests.get(url)
response.raise_for_status()
# Load JSON data into a Python variable.
weatherData = json.loads(response.text)
# Print weather descriptions.
w = weatherData['list']
print('Current weather in %s:' % (location))
print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
print()
print('Tomorrow:')
print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0]['description'])
print()
print('Day after tomorrow:')
print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0]['description'])
def f237():
# json1.py
# JSON represents data as nested "lists" and "dictionaries"
import json
data = '''
{
"name" : "Chuck",
"phone" : {
"type" : "intl",
"number" : "+1 734 303 4456"
},
"email" : {
"hide" : "yes"
}
}'''
info = json.loads(data) # Returns a dictionary
print(type(info))
print('Name:', info["name"])
print('Hide:', info["email"]["hide"])
print('email:', info["email"])
print('info dictionary: ')
print(info)
def f238():
# json2.py
# JSON represents data as nested "lists" and "dictionaries"
import json
data = '''
[
{ "id" : "001",
"x" : "2",
"name" : "Chuck"
} ,
{ "id" : "009",
"x" : "7",
"name" : "Brent"
}
]'''
info = json.loads(data) # Returns a list
print(type(info))
print('User count:', len(info))
for item in info:
print('Name', item['name'])
print('Id', item['id'])
print('Attribute', item['x'])
def f239():
# geojson.py
'''
Note:
Using the google geocoding service is free and can be done
only through gooogle map page.
if we need to use the service from API (your program), we need
an API key. For example we can use the following link to get
the geometry of an address using dr-chuck api key:
http://py4e-data.dr-chuck.net/json?address=Ann+Arbor+MI&key=42
'''
import urllib.request, urllib.parse, urllib.error
import json
import ssl
api_key = False
# If you have a Google Places API key, enter it here
# api_key = 'AIzaSy___IDByT70'
# https://developers.google.com/maps/documentation/ \
# geocoding/intro
if api_key is False:
api_key = 42
serviceurl = 'http://py4e-data.dr-chuck.net/json?'
else :
serviceurl = '\
https://maps.googleapis.com/maps/api/geocode/json?'
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
address = input('Enter location: ')
if len(address) < 1: break
parms = dict()
parms['address'] = address
if api_key is not False: parms['key'] = api_key
url = serviceurl + urllib.parse.urlencode(parms)
print('Retrieving', url)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
try:
js = json.loads(data)
except:
js = None
if not js or 'status' not in js or js['status'] != 'OK':
print('==== Failure To Retrieve ====')
print(data)
continue
print(json.dumps(js, indent=4))
lat = js['results'][0]['geometry']['location']['lat']
lng = js['results'][0]['geometry']['location']['lng']
print('lat', lat, 'lng', lng)
location = js['results'][0]['formatted_address']
print(location)
def f240():
# twtest.py
import urllib.request, urllib.parse, urllib.error
from data import twurl
import ssl
import oauth # I copied oauth.py to /usr/lib64/python3.6
# https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py
# instead of hidden.py keys are copied in function mykey()
print('* Calling Twitter...')
url = twurl.augment('https://api.twitter.com/1.1/statuses/user_timeline.json',
{'screen_name': 'drchuck', 'count': '2'})
print(url)
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
connection = urllib.request.urlopen(url, context=ctx)
data = connection.read()
print(data)
print ('======================================')
headers = dict(connection.getheaders())
print(headers)
def f241():
# twitter1.py
import urllib.request, urllib.parse, urllib.error
import ssl
import oauth
from data import twurl
# https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py
print('* Calling Twitter...')
TWITTER_URL = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
print('')
acct = input('Enter Twitter Account:')
if acct == 'quit': return
if (len(acct) < 1): break
url = twurl.augment(TWITTER_URL,
{'screen_name': acct, 'count': '2'})
print('Retrieving', url)
connection = urllib.request.urlopen(url, context=ctx)
data = connection.read().decode()
print(data[:250])
headers = dict(connection.getheaders())
# print headers
print('Remaining', headers['x-rate-limit-remaining'])
def f242():
# twitter2.py
import urllib.request, urllib.parse, urllib.error
import json
import ssl
import oauth
from data import twurl
# https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py
print('* Calling Twitter...')
TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json'
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
print('')
acct = input('Enter Twitter Account:')
if (len(acct) < 1): break
url = twurl.augment(TWITTER_URL,
{'screen_name': acct, 'count': '5'})
print('Retrieving', url)
connection = urllib.request.urlopen(url, context=ctx)
data = connection.read().decode()
js = json.loads(data)
print(json.dumps(js, indent=2))
headers = dict(connection.getheaders())
print('Remaining', headers['x-rate-limit-remaining'])
for u in js['users']:
print(u['screen_name'])
if 'status' not in u:
print(' * No status found')
continue
s = u['status']['text']
print(' ', s[:50])
def f243():
# Parsing and extracting elements from xml
import xml.etree.ElementTree as ET
data = '''
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes" />
</person>'''
tree = ET.fromstring(data)
# fromstring() converts the string representation of the XML
# into a “tree” of XML elements.
print('Name:', tree.find('name').text)
print('Attr:', tree.find('email').get('hide'))
def f244():
# Parsing an extracting elements through looping nodes
# from a multiple node xml
import xml.etree.ElementTree as ET
input = '''
<stuff>
<users>
<user x="2">
<id>001</id>
<name>Chuck</name>
</user>
<user x="7">
<id>009</id>
<name>Brent</name>
</user>
</users>
</stuff>'''
stuff = ET.fromstring(input) # tree
# builds a “tree” of XML elements
lst = stuff.findall('users/user') # subtree
# The findall method retrieves a Python list of subtrees that
# represent the user structures in the XML tree
print('User count:', len(lst))
for item in lst:
print('Name', item.find('name').text)
print('Id', item.find('id').text)
print('Attribute', item.get('x'))
def f245():
# Iterate and change xml tree elements to strings
f = input('Enter your documnet name: ')
import xml.etree.ElementTree as ET
fhand = open(f)
data = fhand.read()
tree = ET.fromstring(data)
# itertext() Creates a text iterator. The iterator loops over
# this element and all subelements, in document order, and re-
# turns all inner text.
# print(''.join(tree.itertext()))
# If you uncomment above you get an output with empty lines.
# To get rid of blank lines:
import re
x = tree.itertext()
for line in x:
if not re.match(r'^\s*$', line):
print(line)
def f246():
# Extract all tags with non empty inner text from xml document
import re
import xml.etree.ElementTree as ET
xmlfile = input('Enter xml file name: ')
fh = open(xmlfile)
data = fh.read()
tree = ET.fromstring(data)
sp = '-> '
for line in tree:
if not line.text.strip(): continue
print(line.tag, sp, line.text)
def f247():
# Read an xml from reomte server and get the sum of the tags
# with numbers.
# Program to prompt for a URL, read the xml data from that URL,
# using urllib and then parse and extract the comment counts
# from the xml data, compute the sum of the numbers in the file.
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
# url = input('Enter location: ')
url = 'http://py4e-data.dr-chuck.net/comments_42.xml'
# url = 'http://py4e-data.dr-chuck.net/comments_229272.xml'
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
print('Retrieving', url)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read()
print('Retrieved', len(data), 'characters')
# print(data.decode())
tree = ET.fromstring(data)
# lst = tree.findall('./comments/comment/count')
lst = tree.findall('.//count')
print('count : ', len(lst))
count_list = list()
for elem in lst:
count_list.extend(elem.text.split())
# print(count_list)
total = 0
for n in count_list:
total = total + int(n)
print('Sum: ', total)
def f248():
# Chapter 15 - Time, Scheduling Tasks, Launching Programs
print('Chapter 15 - Time, Scheduling Tasks, Launching Programs')
def f249():
# The time.time() Function
from time import time
print(time())
# number of seconds since 12 am on January 1, 1970 (UTC)
# The return number is called epoch timestamp
def f250():
# calculate running time for a program
import time
def calcProd():
# Calculate the product of the first 100,000 numbers.
product = 1
for i in range(1, 100000):
product = product * i
return product
startTime = time.time()
prod = calcProd()
endTime = time.time()
print('The result is %s digits long.' % (len(str(prod))))
print('Took %s seconds to calculate.' % (endTime - startTime))
# cProfile.run can() be used as an alternative for time.time()
# For help go to: https://docs.python.org/3/library/profile.html.
def f251():
# sleep function to pause the program
import time
for i in range(3):
print('Tick')
time.sleep(1)
print('Tock')
time.sleep(1)
# Making 10 calls to time.sleep(1) is equivalent to
# time.slweep(10)
for i in range(10):
time.sleep(1)
def f252():
# Rounding the current time number
import time
now = time.time()
print(now)
print(round(now, 2))
print(round(now, 4))
print(round(now)) # No 2nd argument, rounds to nearest integer
def f253():
# Project: Super Stopwatch - track spent time on a task
# Step 1: Set Up the Program to Track Times
import time
# Display the program's instructions.
print('''
Press ENTER to begin. Afterwards,
press ENTER to "click" the stopwatch.Press Ctrl-C to quit.''')
input()
# press Enter to begin
print('Started.')
startTime = time.time()
# get the first lap's start time
lastTime = startTime
lapNum = 1
# Step 2: Track and Print Lap Times
try:
# To prevent crashing by Ctl-c, we wrap this part of the -
# program in a try statement.
while True: # infinit loop, to interrupt Ctl-c needed.
input()
lapTime = round(time.time() - lastTime, 2)
totalTime = round(time.time() - startTime, 2)
print('Lap #%s: Total time: %s - Lap time: %s' % (lapNum, totalTime, lapTime), end='')
lapNum += 1
lastTime = time.time() # reset the last lap time
except KeyboardInterrupt:
# Handle the Ctrl-C exception to keep its error message from displaying.
print('\nDone.')
def f254():
# The datetime Module
import datetime, time
# The following returns a datetime object for the current date
# and time:
print(type(datetime.datetime.now()))
print(datetime.datetime.now()) # Displays current date and time
# If you in IDLE:
# >>> datetime.datetime.now()
# datetime.datetime(2019, 5, 6, 17, 2, 33, 739924)
# To make datetime object, we use function datetime()
dt = datetime.datetime(2015, 10, 21, 16, 29, 0)
print(dt.year, dt.month, dt.day)
print(dt.hour, dt.minute, dt.second)
# To convert a Unix epoch timestamp to a datetime object, we -
# use function fromtimestamp().
dt = datetime.datetime.fromtimestamp(1000000)
print('\nPrinting 1,000,000 seconds after the Unix epoch in the'
+ '\nform of a datetime object: ', dt)
dt = datetime.datetime.fromtimestamp(time.time())
print('\nPrinting the current time in the form of a'
+ '\ndatetime object: ', dt)
def f255():
# Compare datetime objects with each other
import datetime
halloween2015 = datetime.datetime(2015, 10, 31, 0, 0, 0)
newyears2016 = datetime.datetime(2016, 1, 1, 0, 0, 0)
oct31_2015 = datetime.datetime(2015, 10, 31, 0, 0, 0)
print(halloween2015 == oct31_2015) # True
print(halloween2015 > newyears2016) # False
print(newyears2016 > halloween2015) # True
print(newyears2016 != oct31_2015) # True
def f256():
# Find time duration with timedelta module
import datetime
# timedelta arguments are: (has no month or year argument)
# days, hours, minutes, seconds, milliseconds and microseconds
delta = datetime.timedelta(days=11, hours=10, minutes=9, seconds=8)
print(delta.days, delta.seconds, delta.microseconds)
print(delta.total_seconds())
print(str(delta)) # nice human readable format
print('.' * 10)
def f257():
# Using arithmatic operators on datetime values
import datetime
# calculate the date 1,000 days from now, using arithmatic op-
# erators on datetime values
dt = datetime.datetime.now()
print(dt)
thousandDays = datetime.timedelta(days=1000)
print(dt + thousandDays)
# timedelta objects can be added or subtracted with datetime -
# objects or other timedelta objects using the + and - operat-
# ors. A timedelta object can be multiplied or divided by int-
# eger or float values with the * and / operators.
oct21st = datetime.datetime(2015, 10, 21, 16, 29, 0)
aboutThirtyYears = datetime.timedelta(days=365 * 30)
print(oct21st)
print(oct21st - aboutThirtyYears)
print(oct21st - (2 * aboutThirtyYears))
def f258():
# Pausing Until a Specific Date
import datetime
import time
halloween2016 = datetime.datetime(2016, 10, 31, 0, 0, 0)
while datetime.datetime.now() < halloween2016:
time.sleep(1)
# The time.sleep(1) call will pause your Python program so that
# the computer doesn’t waste CPU processing cycles simply chec-
# king the time over and over. Rather, the while loop will just
# check the condition once per second and continue with the re-
# st of the program after Halloween 2016
def f259():
# Converting datetime Objects into Strings
import datetime
# Use strftime() to get a custom string format
oct21st = datetime.datetime(2015, 10, 21, 16, 29, 0)
print(oct21st.strftime('%Y/%m/%d %H:%M:%S'))
print(oct21st.strftime('%I:%M %p'))
print(oct21st.strftime("%B of '%y"))
'''
Directives meaning:
%Y Year with century, as in '2014'
%y Year without century, '00' to '99' (1970 to 2069)
%m Month as a decimal number, '01' to '12'
%B Full month name, as in 'November'
%b Abbreviated month name, as in 'Nov'
%d Day of the month, '01' to '31'
%j Day of the year, '001' to '366'
%w Day of the week, '0' (Sunday) to '6' (Saturday)
%A Full weekday name, as in 'Monday'
%a Abbreviated weekday name, as in 'Mon'
%H Hour (24-hour clock), '00' to '23'
%I Hour (12-hour clock), '01' to '12'
%M Minute, '00' to '59'
%S Second, '00' to '59'
%p 'AM' or 'PM'
%% Literal '%' character
'''
def f260():
# Converting Strings into datetime Objects
import datetime
# Parsing strings that are convertible to datetime object can
# be done using method strptime()
print('',
datetime.datetime.strptime('October 21, 2015', '%B %d, %Y'),'\n',
datetime.datetime.strptime('2015/10/21 16:29:00', '%Y/%m/%d %H:%M:%S'),'\n',
datetime.datetime.strptime("October of '15", "%B of '%y"),'\n',
datetime.datetime.strptime("November of '63", "%B of '%y")
)
'''
Directives meaning:
%Y Year with century, as in '2014'
%y Year without century, '00' to '99' (1970 to 2069)
%m Month as a decimal number, '01' to '12'
%B Full month name, as in 'November'
%b Abbreviated month name, as in 'Nov'
%d Day of the month, '01' to '31'
%j Day of the year, '001' to '366'
%w Day of the week, '0' (Sunday) to '6' (Saturday)
%A Full weekday name, as in 'Monday'
%a Abbreviated weekday name, as in 'Mon'
%H Hour (24-hour clock), '00' to '23'
%I Hour (12-hour clock), '01' to '12'
%M Minute, '00' to '59'
%S Second, '00' to '59'
%p 'AM' or 'PM'
%% Literal '%' character
'''
def f261():
# Review of Python’s Time Functions
print('''
• A Unix epoch timestamp (used by the time module) is a fl-
oat or integer value of the number of seconds since 12 am on
January 1, 1970, UTC.
• A datetime object ( of the datetime module ) has integers
stored in the attributes year , month , day , hour , minute ,
and second.
• A timedelta object (of the datetime module) represents a
time duration, rather than a specific moment.
Here’s a review of time functions and their parameters and re-
turn values:
..............................................................
• The time.time() function returns an epoch timestamp float
value of the current moment.
• The time.sleep(seconds) function stops the program for
the amount of seconds specified by the seconds argument.
• The datetime.datetime(year, month, day, hour, minute, se-
cond) function returns a datetime object of the moment specif-
ied by the arguments. If hour , minute , or second arguments
are not provided, they default to 0.
• The datetime.datetime.now() function returns a datetime -
object of the current moment.
• The datetime.datetime.fromtimestamp(epoch) function ret-
urns a datetime object of the moment represented by the epoch
timestamp argument.
• The datetime.timedelta(weeks, days, hours, minutes, seco-
nds, milliseconds, microseconds) function returns a timedelta
object representing a duration of time. The function’s keyword
arguments are all optional and do not include month or year.
• The total_seconds() method for timedelta objects returns
the number of seconds the timedelta object represents.
• The strftime(format) method returns a string of the time
represented by the datetime object in a custom format that’s
based on the format string.
• The datetime.datetime.strptime(time_string, format) func-
tion returns a datetime object of the moment specified by
time_string , parsed using the format string argument.
'''
)
def f262():
# Multithreading
# To make a separate thread, you first need to make a Thread
# object by calling the threading.Thread() function.
# This thread demo shows running different parts of a python
# program at the same time in parallel:
import threading, time
print('Start of program.')
# The function we want to call in the new thread is takeANap()
def takeANap():
time.sleep(5)
print('Wake up!')
threadObj = threading.Thread(target=takeANap)
threadObj.start()
# Notice that the keyword argument is target=takeANap ,
# not target=takeANap() .
print('End of program.')
# output:
# Start of program.
# End of program.
# Wake up!
# The first is the original thread that began at the start of
# the program and ends after print('End of program.') .
# The 2nd thread is created when threadObj.start() is called,
# begins at the start of the takeANap() function, and ends
# after takeANap() returns.
def f263():
# Passing Arguments to the Thread’s Target Function
import threading
print('Cats', 'Dogs', 'Frogs', sep=' & ')
print('#' * 20)
threadObj = threading.Thread(target=print,
args=('Cats', 'Dogs', 'Frogs'), kwargs={'sep': ' & '})
threadObj.start()
# 'threading' module is higher-level threading interface.
# 'threading.Thread' is an object that represents a thread.
# The arguments for Thread object constructer:
# 'target' is the callable object to be invoked by the run() -
# method. Defaults to None, meaning nothing is called.
# 'args' is the argument tuple for the target invocation,
# defaults to ().
# 'kwargs' is a dictionary of keyword arguments for the target
# invocation. Defaults to {}.
# To avoid concurrency issues, never let multiple threads read
# or write the same variables.
def f264():
# Downloads XKCD comics using multiple threads
import requests, os, bs4, threading
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
def downloadXkcd(startComic, endComic):
for urlNumber in range(startComic, endComic):
# Download the page.
print('Downloading page http://xkcd.com/%s...' % (urlNumber))
res = requests.get('http://xkcd.com/%s' % (urlNumber))
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
# Find the URL of the comic image.
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
# Save the image to ./xkcd.
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
# Create and start the Thread objects.
downloadThreads = [] # a list of all the Thread objects
for i in range(0, 1400, 100): # loops 14 times,
# creates 14 threads
downloadThread = threading.Thread(target=downloadXkcd,
args=(i, i + 99))
downloadThreads.append(downloadThread)
downloadThread.start()
# Wait for all threads to end.
for downloadThread in downloadThreads:
downloadThread.join()
print('Done.')
def f265():
# Launching Other Programs from Python
import subprocess
subprocess.Popen('/usr/bin/gnome-calculator')
# Popen object has two methods: poll() and wait()
# The poll() method will return None if the process is still
# running at the time poll() is called. If the program has
# terminated, it will return the process’s integer exit code.
# The wait() method will block until the launched process has
# terminated. This is helpful if you want your program to pau-
# se until the user finishes with the other program. The retu-
# rn value of wait() is the process’s integer exit code.
'''
>>> calcProc = subprocess.Popen('/usr/bin/gnome-calculator')
>>> calcProc.poll() == None
True
>>> calcProc.wait()
0
>>> calcProc.poll() # After closing calculator program
0
'''
def f266():
import subprocess
# Passing Command Line Arguments to Popen()
subprocess.Popen(['/usr/bin/gedit', 'list'])
def f267():
# Opening Files with Default Applications
fileObj = open('hello.txt', 'w')
fileObj.write('Hello world!')
fileObj.close()
import subprocess
subprocess.Popen(['start', 'hello.txt'], shell=True)
def f268():
#
print('Chapter 16 OO programming')
def f269():
#
print('Chapter 17 DataBase programming and SQLite')
'''
CHPTER 17 includes following:
270 - Simple DB connection and input data
271 - Create an SQLite DB and Update the table with data
272 - Counting emails from Organization and store in SQLite DB
273 - Spidering Twitter Using a DataBase
274 - Create a DataBase of friends from twitter account
275 - One to one relationship database example - tracks.py
276 - One to one relationship database example - tracks_assignment.py
277 - multi-relational database table example - roster.py
278 - Multiple relational database - roster_assignment.py
'''
def f270():
# Simple db connection and input data (db1.py)
import sqlite3
conn = sqlite3.connect('music.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Tracks')
cur.execute('CREATE TABLE Tracks (title TEXT, plays INTEGER)')
conn = sqlite3.connect('music.sqlite')
cur = conn.cursor()
cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)',
('Thunderstruck', 20))
cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)',
('My Way', 15))
conn.commit()
print('Tracks:')
cur.execute('SELECT title, plays FROM Tracks')
for row in cur: print(row)
# cur.execute('DELETE FROM Tracks WHERE plays < 100')
conn.commit()
cur.close()
def f271():
# Create and Update an SQLite DB from a file or a string
# emaildb.py
import sqlite3
# Instead of following string we can have a file as input!
lst = '''From [email protected] Sat Jan 5 09:14:16 2008
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]'''
lines = lst.splitlines() # 1
conn = sqlite3.connect('emaildb.sqlite') # 2
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Counts')
cur.execute('CREATE TABLE Counts (email TEXT, count INTEGER)')
for line in lines:
if not line.startswith('From: '): continue
pieces = line.split()
email = pieces[1]
cur.execute('SELECT count FROM Counts WHERE email = ? ',
(email,))
row = cur.fetchone() # 3
if row is None:
cur.execute('''INSERT INTO Counts (email, count)
VALUES (?, 1)''', (email,))
else:
cur.execute('UPDATE Counts SET count = count + 1 \
WHERE email = ?', (email,))
conn.commit()
# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT email, count FROM Counts ORDER BY count \
DESC LIMIT 10'
for row in cur.execute(sqlstr): print(str(row[0]), row[1])
cur.close()
''' Comments:
-1 function splitlines() returns a list of the lines in the
string, breaking at line boundaries.
-2 object conn can also be used for sending sql commands to db,
instead of object cur. cursor() creates an object, that is
used for making application portable between databases.
-3 function fetchone() fetches the next row of a query result
set, returning a single sequence, or None when no more data
is available.'''
def f272():
# Counting emails from Organization and store in SQLite DB
import sqlite3
conn = sqlite3.connect('orgs.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Counts;')
cur.execute('CREATE TABLE Counts (org TEXT, count INTEGER)')
fname = input('Enter file name: ')
if len(fname) < 1: fname = './data/mbox.txt'
fhand = open(fname)
for line in fhand:
if line.startswith('From: '):
orgName = line.split()[1].split('@')[1].split('.')[0]
cur.execute('SELECT * FROM Counts WHERE org = ?',
(orgName,))
row = cur.fetchone()
if row is None:
cur.execute('''INSERT INTO Counts (org, count)
VALUES (?, 1)''',
(orgName,))
else:
cur.execute('''UPDATE Counts SET count = count + 1
WHERE org = ?''',
(orgName,))
conn.commit()
result = cur.execute('SELECT * FROM Counts').fetchall()
for row in result: print(str(row[0]), row[1])
cur.close()
def f273():
# Spidering twitter using a database (twspider.py)
import urllib.request, urllib.parse, urllib.error
from data import twurl
import json
import sqlite3
import ssl
TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json'
conn = sqlite3.connect('friends.sqlite')
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS People(
id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
retrieved INTEGER
)''')
cur.execute('''CREATE TABLE IF NOT EXISTS Follows(
from_id INTEGER,
to_id INTEGER,
UNIQUE(from_id, to_id))
''')
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
acct = input('Enter a Twitter account, or quit: ')
if (acct == 'quit'): break
if (len(acct) < 1):
cur.execute('''SELECT id, name FROM People
WHERE retrieved = 0 LIMIT 1''')
try:
(id, acct) = cur.fetchone()
except:
print('No unretrieved Twitter accounts found')
continue
else:
cur.execute('''SELECT id FROM People
WHERE name = ?
LIMIT 1
''',(acct, ))
try:
id = cur.fetchone()[0]
except:
cur.execute('''INSERT OR IGNORE INTO People
(name, retrieved)
VALUES (?, 0)''', (acct, ))
conn.commit()
if cur.rowcount != 1:
print('Error inserting account:', acct)
continue
id = cur.lastrowid
url = twurl.augment(TWITTER_URL,
{'screen_name': acct, 'count': '100'})
print('Retrieving account', acct)
try:
connection = urllib.request.urlopen(url, context=ctx)
except Exception as err:
print('Failed to Retrieve', err)
break
data = connection.read().decode()
headers = dict(connection.getheaders())
print('Remaining', headers['x-rate-limit-remaining'])
try:
js = json.loads(data)
except:
print('Unable to parse json')
print(data)
break
# Debugging
# print(json.dumps(js, indent=4))
if 'users' not in js:
print('Incorrect JSON received')
print(json.dumps(js, indent=4))
continue
cur.execute('''UPDATE People SET retrieved=1
WHERE name = ?''', (acct, ))
countnew = 0
countold = 0
for u in js['users']:
friend = u['screen_name']
print(friend)
cur.execute('''SELECT id FROM People
WHERE name = ?
LIMIT 1''', (friend, ))
try:
friend_id = cur.fetchone()[0]
countold = countold + 1
except:
cur.execute('''INSERT OR IGNORE INTO People
(name, retrieved)
VALUES (?, 0)''', (friend, ))
conn.commit()
if cur.rowcount != 1:
print('Error inserting account:', friend)
continue
friend_id = cur.lastrowid
countnew = countnew + 1
cur.execute('''INSERT OR IGNORE INTO Follows
(from_id, to_id)
VALUES (?, ?)''', (id, friend_id))
print('New accounts=', countnew, ' revisited=', countold)
print('Remaining', headers['x-rate-limit-remaining'])
conn.commit()
cur.close()
def f274():
# Retriving twitter friernds and store them in SQLite database
# twfriends.py
import sqlite3
from data import twurl
import urllib.request, urllib.parse, urllib.error
import ssl
import json
TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json'
# DB Connection
conn = sqlite3.connect('friends.sqlite')
cur = conn.cursor()
# -- Creating Tables --
# Table: People
cur.execute('''
CREATE TABLE IF NOT EXISTS People(
id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
retrieved INTEGER
)''')
# Table: Follows
cur.execute('''
CREATE TABLE IF NOT EXISTS Follows(
from_id INTEGER,
to_id INTEGER,
UNIQUE(from_id, to_id)
)''')
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Ask twitter account name:
while True:
acct = input('Enter twitter account, or quit: ')
if acct == 'quit': break
if len(acct) < 1:
cur.execute('''
SELECT id, name FROM TABLE PEOPLE
WHERE retrieved = 0
LIMIT 1
''')
try:
(id, name) = cur.fetchone()
print(id, name)
except:
print('No unretrieved twitter account found!')
continue
else:
cur.execute('''
SELECT id FROM People
WHERE name = ?
LIMIT 1
''', (acct, ))
try:
id = cur.fetchone()[0]
print('fetchone()[0]',id)
except:
cur.execute('''
INSERT OR IGNORE INTO People
(name, retrieved) VALUES(?, 0)''',
(acct,))
conn.commit()
# rowcount is sum pf the number of insert operation
# performed.
if cur.rowcount != 1:
print('Error inserting account: ', acct)
continue
# lastrowid is the id of the last modified row
id = cur.lastrowid
print('lastrowid: ', id)
url = twurl.augment(TWITTER_URL, {'screen_name': acct, 'count': '5'})
print('Retrieving account', acct)
try:
connection = urllib.request.urlopen(url, context=ctx)
except Exception as err:
print('Failed to retrive: ', err)
break
data = connection.read().decode() # <class 'str'>
headers = dict(connection.getheaders())
try:
js = json.loads(data) # <class 'dict'>
except:
print('Unable to parse json')
print(data)
break
if 'users' not in js:
print('Incorrect JSON received')
print(json.dumps(js, indent=4))
continue
cur.execute('UPDATE People SET retrieved=1 WHERE name = ?', (acct, ))
countnew = 0
countold = 0
for u in js['users']:
friend = u['screen_name']
print(friend)
cur.execute('''
SELECT id FROM People
WHERE name = ?
LIMIT 1
''', (friend,))
try:
friend_id = cur.fetchone()[0]
countold = countold + 1
except:
cur.execute('''
INSERT OR IGNORE INTO People
(name, retrieved)
VALUES (?, 0)
''', (friend, ))
conn.commit()
if cur.rowcount != 1:
print('Error inserting account:', friend)
continue
friend_id = cur.lastrowid
countnew = countnew + 1
cur.execute('''INSERT OR IGNORE INTO Follows (from_id, to_id)
VALUES (?, ?)''', (id, friend_id))
print('New accounts=', countnew, ' revisited=', countold)
print('Remaining', headers['x-rate-limit-remaining'])
conn.commit()
cur.close()
'''
Reminding:
To check syntaxes without running script:
$ python3 -m py_compile twfriends.py
What does this program do?
..........................
1. Create an SQLite DB
2. Create tables: People and Follows
3. Ask twitter account name and action on user input
as following:
- if quit as input, exit program
- if nothing as input:
get a row and check if row is unretrived, get
the id and name from row, otherwise reset the
loop
- if having an account name as input:
-- if name in People, get id of that name,
-- if not in People add name with retrived '0'
At the end of this step, we get values for id and
the account name.
4. generate url string to twitter API after successful
authentication and then make a connection to that URL.
5. print out 'Retrieving account: '
- if retrieving successful, open a connection to twitter
- if fails, exit program
6. read and decode data from twitter connection
7. from headers part of data, find twitter account
retriving limit
8. if a bad json data came from twitter, then dump it, and
print it. Break the loop.
9. if string 'users' not found in json data, continue the loop.
Update People with the last retrieved account, setting the
'retrieved' value to '1'
10. Updating table Follows:
From jason object, we search values for 'users' dictionary.
'users' dictionary is a nested dictionary, that will be parsed
in a for loop; looking for values of keyword 'screen_name'.
Each value obtained from 'screen_name' is a friend of the
entered acccount.
Check searching the name of the friend in People:
- if successful:
assign the friend_id with id of that account name,
and increment index for countold
- if failed: update People with friend and commit.
check inserting:
-- insertion failed, print out error and continue the loop
-- insertion successful: set friend_id as the id of the
last modified row in People table and increment the
variable countnew.
In continuation of for loop for friends, we insert the values
for (from_id, to_id) in table Follows
11. At the end of program, we print these messages:
One showing the number of new accounts and the other the
number of revisited accounts. Also a print out of the
number of possible twitter accounts that can be retrieved.
# Debugging
# To view the content of received data, it can be saved on disk
FH = open('data.txt', 'w')
FH.write(str(data))
FH.close()
# You can always use json.dumps(a_dictionary) to convert that
# dictionay to a string and then printing or saving on disk
FH = open('headers.txt', 'w')
FH.write(json.dumps(headers, indent=4))
FH.close()
# To view the content of JSON, dump it and save it on disk
FH = open('js.txt', 'w')
FH.write(json.dumps(js, indent=4))
FH.close()
'''
def f275():
# One to one relationship database example - tracks.py
import xml.etree.ElementTree as ET
import sqlite3
conn = sqlite3.connect('trackdb.sqlite')
cur = conn.cursor()
# Make some fresh tables using executescript()
cur.executescript('''
DROP TABLE IF EXISTS Artist;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Track;
DROP TABLE IF EXISTS Genre;
CREATE TABLE Artist (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Genre (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Album (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
artist_id INTEGER,
title TEXT UNIQUE
);
CREATE TABLE Track (
id INTEGER NOT NULL PRIMARY KEY
AUTOINCREMENT UNIQUE,
title TEXT UNIQUE,
album_id INTEGER,
genre_id INTEGER,
len INTEGER, rating INTEGER, count INTEGER
);
''')
fname = input('Enter file name: ')
if ( len(fname) < 1 ) : fname = './data/Library.xml'
# <key>Track ID</key><integer>369</integer>
# <key>Name</key><string>Another One Bites The Dust</string>
# <key>Artist</key><string>Queen</string>
def lookup(d, key):
found = False
for child in d:
if found : return child.text
if child.tag == 'key' and child.text == key :
found = True
return None
stuff = ET.parse(fname)
all = stuff.findall('dict/dict/dict')
print('Dict count:', len(all))
for entry in all:
if ( lookup(entry, 'Track ID') is None ) : continue
name = lookup(entry, 'Name')
artist = lookup(entry, 'Artist')
album = lookup(entry, 'Album')
count = lookup(entry, 'Play Count')
rating = lookup(entry, 'Rating')
length = lookup(entry, 'Total Time')
if name is None or artist is None or album is None :
continue
print(name, artist, album, count, rating, length)
cur.execute('''INSERT OR IGNORE INTO Artist (name)
VALUES ( ? )''', ( artist, ) )
cur.execute('SELECT id FROM Artist WHERE name = ? ', (artist, ))
artist_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Album (title, artist_id)
VALUES ( ?, ? )''', ( album, artist_id ) )
cur.execute('SELECT id FROM Album WHERE title = ? ', (album, ))
album_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Track
(title, album_id, len, rating, count)
VALUES ( ?, ?, ?, ?, ? )''',
( name, album_id, length, rating, count ) )
conn.commit()
def f276():
# One to one relationship database example - tracks_assignment.py
import xml.etree.ElementTree as ET
import sqlite3
conn = sqlite3.connect('trackdb.sqlite')
cur = conn.cursor()
# Make some fresh tables using executescript()
cur.executescript('''
DROP TABLE IF EXISTS Artist;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Track;
DROP TABLE IF EXISTS Genre;
CREATE TABLE Artist (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Genre (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Album (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
artist_id INTEGER,
title TEXT UNIQUE
);
CREATE TABLE Track (
id INTEGER NOT NULL PRIMARY KEY
AUTOINCREMENT UNIQUE,
title TEXT UNIQUE,
album_id INTEGER,
genre_id INTEGER,
len INTEGER, rating INTEGER, count INTEGER
);
''')
fname = input('Enter file name: ')
if ( len(fname) < 1 ) : fname = './data/Library.xml'
# <key>Track ID</key><integer>369</integer>
# <key>Name</key><string>Another One Bites The Dust</string>
# <key>Artist</key><string>Queen</string>
def lookup(d, key):
found = False
for child in d:
if found : return child.text
if child.tag == 'key' and child.text == key :
found = True
return None
stuff = ET.parse(fname)
all = stuff.findall('dict/dict/dict')
print('Dict count:', len(all))
for entry in all:
if ( lookup(entry, 'Track ID') is None ) : continue
name = lookup(entry, 'Name')
artist = lookup(entry, 'Artist')
album = lookup(entry, 'Album')
count = lookup(entry, 'Play Count')
rating = lookup(entry, 'Rating')
length = lookup(entry, 'Total Time')
genre = lookup(entry, 'Genre')
lst = [name, count, rating, length, artist, album, genre]
if None not in (name, count, rating, length, artist, album, genre):
print(lst)
cur.execute('''INSERT OR IGNORE INTO Artist (name)
VALUES ( ? )''', ( artist, ) )
cur.execute('SELECT id FROM Artist WHERE name = ? ', (artist, ))
artist_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Album (title, artist_id)
VALUES ( ?, ? )''', ( album, artist_id ) )
cur.execute('SELECT id FROM Album WHERE title = ? ', (album, ))
album_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Genre (name)
VALUES ( ? )''', ( genre, ) )
cur.execute('SELECT id FROM Genre WHERE name = ? ', (genre, ))
genre_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Track
(title, album_id, len, rating, count, genre_id)
VALUES ( ?, ?, ?, ?, ?, ?)''',
( name, album_id, length, rating, count, genre_id ) )
conn.commit()
sqlstr = '''SELECT Track.title, Artist.name, Album.title, Genre.name
FROM Track JOIN Genre JOIN Album JOIN Artist
ON Track.genre_id = Genre.id AND Track.album_id = Album.id
AND Album.artist_id = Artist.id
ORDER BY Artist.name LIMIT 3'''
print('..............................................')
for row in cur.execute(sqlstr):
lsti = [row[0], row[1], row[2], row[3]]
print(lsti)
cur.close()
def f277():
# multi-relational database table example - roster.py
import json
import sqlite3
conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()
# Do some setup
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
''')
fname = input('Enter file name: ')
if len(fname) < 1:
fname = './data/roster_data_sample.json'
# [
# [ "Charley", "si110", 1 ],
# [ "Mea", "si110", 0 ],
str_data = open(fname).read()
json_data = json.loads(str_data)
for entry in json_data:
name = entry[0];
title = entry[1];
print((name, title))
cur.execute('''INSERT OR IGNORE INTO User (name)
VALUES ( ? )''', ( name, ) )
cur.execute('SELECT id FROM User WHERE name = ? ', (name, ))
user_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Course (title)
VALUES ( ? )''', ( title, ) )
cur.execute('SELECT id FROM Course WHERE title = ? ', (title, ))
course_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Member
(user_id, course_id) VALUES ( ?, ? )''',
( user_id, course_id ) )
conn.commit()
def f278():
# Multiple relational database - assignment
import json
import sqlite3
conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()
# Do some setup
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
''')
fname = input('Enter file name: ')
if len(fname) < 1:
fname = './data/roster_data.json'
# [
# [ "Charley", "si110", 1 ],
# [ "Mea", "si110", 0 ],
str_data = open(fname).read()
json_data = json.loads(str_data)
for entry in json_data:
name = entry[0];
title = entry[1];
role = entry[2];
#print((name, title, role))
cur.execute('''INSERT OR IGNORE INTO User (name)
VALUES ( ? )''', ( name, ) )
cur.execute('SELECT id FROM User WHERE name = ? ', (name, ))
user_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Course (title)
VALUES ( ? )''', ( title, ) )
cur.execute('SELECT id FROM Course WHERE title = ? ', (title, ))
course_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Member
(user_id, course_id, role) VALUES ( ?, ?, ?)''',
( user_id, course_id, role) )
conn.commit()
cur.execute('''
SELECT hex(User.name || Course.title || Member.role ) AS X FROM
User JOIN Member JOIN Course
ON User.id = Member.user_id AND Member.course_id = Course.id
ORDER BY X
LIMIT 1''')
try:
(user) = cur.fetchone()
print(user)
except:
print('No user found!')
def f279():
#
print('')
|
fd393a3fcc2a41c01b037ba61b733490bc2bbf43 | alexrosl/python_automated_testing_udemy | /PythonRefresher/if_statements.py | 690 | 3.921875 | 4 | # should_continue = True
# if should_continue:
# print("hello")
known_people = ["John", "Anna", "Mary"]
person = input("Enter the person you know: ")
if person in known_people:
print("You know the person {}".format(person))
else:
print("you don't know the person {}".format(person))
# Exercise
def who_do_you_know():
people = input("Enter the names of people you know: ")
people_list = people.split(",")
people_without_spaces = []
for person in people_list:
people_without_spaces.append(person.strip())
return people_without_spaces
def ask_user():
person = input("Enter the person you know: ")
if person in who_do_you_know():
print("You know this person")
ask_user()
|
bcd9aedc8e906802871157763f6046fd67f08aba | obrienadam/APS106 | /midterm/word_count.py | 1,082 | 3.828125 | 4 | def word_count(filename):
with open('article.txt', 'r') as f:
text = f.read().replace('\n', ' ').replace('-', ' ')
# We may want to remove any non-alphabetic characters, eg punctuation
processed_text = ''
for ch in text:
if ch.isalpha() or ch == ' ':
processed_text += ch.lower()
word_freq = {}
for word in processed_text.split():
if word.isalpha(): # Make sure it's a word, we may have missed special cases
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
return word_freq
if __name__ == '__main__':
word_freq = word_count('article.txt')
max_freq = 0
for word, freq in word_freq.items():
if freq > max_freq and len(word) >= 4:
max_freq = freq
max_freq_word = word
print('The most common four letter word was "{}", which appeared {} times.'.format(max_freq_word, max_freq))
print('In total, there were {} words, with {} unique words.'.format(sum(word_freq.values()), len(word_freq))) |
6cd1676e716a609f138136b027cbe6655c7292a4 | obrienadam/APS106 | /week5/palindrome.py | 1,178 | 4.21875 | 4 | def is_palindrome(word):
return word[::-1] == word
if __name__ == '__main__':
word = input('Enter a word: ')
if is_palindrome(word):
print('The word "{}" is a palindrome!'.format(word))
else:
print('The word "{}" is not a palindrome.'.format(word))
phrase = input('What would you like to say?: ').lower()
if phrase == 'hello':
print('Hello to you too!')
elif phrase == 'goodbye':
print('Goodbye!')
elif phrase == 'how are you doing today?':
print('Fine, thank you!')
else:
print('I did not understand that phrase.')
from random import randint
num = randint(1, 10)
guess = int(input('Guess a number between 1 and 10: '))
if 1 <= guess <= 10:
if guess == num:
print('Good guess!')
else:
print('Terrible guess. The number was {}'.format(num))
else:
print(num, 'is not between 1 and 10...')
from random import randint
num = randint(1, 10)
guess = int(input('Guess a number between 1 and 10: '))
if not 1 <= guess <= 10:
print(num, 'is not between 1 and 10...')
else:
if guess == num:
print('Good guess!')
else:
print('Terrible guess. The number was {}'.format(num)) |
14f61f9325c15fc173f0c5d598525d01481f7098 | obrienadam/APS106 | /week3/recursion.py | 376 | 3.859375 | 4 | from random import randint
def pow(x, y):
if y == 0:
return 1
return x*pow(x, y - 1)
def factorial(x):
if x == 0:
return 1
return x*factorial(x - 1)
if __name__ == '__main__':
x = randint(1, 9)
y = randint(0, 9)
print('{}^{} = {}'.format(x, y, pow(x, y)))
x = randint(1, 20)
print('{}! = {}'.format(x, factorial(x))) |
653627c23040a590d27c862de0db36c6fe46d7b5 | obrienadam/APS106 | /midterm/temperature.py | 699 | 3.859375 | 4 | def to_celsius(temp):
return (temp - 32)*5/9
def avg_temperature(filename):
tmins = []
tmaxs = []
with open('temperature.csv', 'r') as f:
for line in f:
tmin, tmax = map(float, line.split(','))
tmins.append(to_celsius(tmin))
tmaxs.append(to_celsius(tmax))
with open('temperature_celsius.csv', 'w') as f:
for tmin, tmax in zip(tmins, tmaxs):
f.write('{:.2f},{:.2f}\n'.format(tmin, tmax))
avg_temp = (sum(tmins) + sum(tmaxs))/(len(tmins) + len(tmaxs))
return avg_temp
if __name__ == '__main__':
print('The average temperature is {:.2f} degrees celsius.'.format(avg_temperature('temperatures.csv')))
|
1ced13face080c2b0b62936a454a1f0b07e604fc | j721/Data-Structures | /binary_search_tree/binary_search_tree.py | 8,650 | 4.28125 | 4 | """
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`
on the BSTNode class.
2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods
on the BSTNode class.
"""
from collections import deque
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
# #1. check if there is no root,
# # we can check this by checking if self is None
# if self is None:
# #if there isn't, create the node and park it there
# self = BSTNode(value)
# #2. Otherwise, there is a root
# else:
#compare the value to the root's value to determine which direction
#we're gonna go in
#if the value < root's value
if value < self.value:
#go left
#how do we go left
#we have to check if there is another node on the left side
if self.left:
#then self.left is a Node
#moved the root from (self.left )and the .insert(value)- adds new value from the new root (self.left)
self.left.insert(value)
else:
#then we can park the value here
self.left = BSTNode(value)
#else te value >= root's value
else:
#go right
#how do we go right
#we have to check if there is another node on the right side
if self.right:
#then self.right is a Node
self.right.insert(value)
else:
#then we can park the value here
self.right = BSTNode(value)
# Return True if the tree contains the value
# False if it does not
# def contains(self, target):
# #If tree contains target value, return True
# if self.value == target:
# return True
# # figure out which direction we need to go
# else:
# #if target is lower than value
# if target < self.value:
# #if the target value is going to be on the left as a child node
# if not self.left:
# return False
# if self.left.value == target:
# return True
# else:
# self.left.contains(target)
# # if target is >= than the value from the tree(self.value)
# else:
# #is there any child node on the right?
# if not self.right:
# return False
# #if the right child node is our target than return True
# if self.right.value == target:
# return True
# else:
# self.right.contains(target)
def contains(self, target):
#base case?
#we find the target in the tree node
if self.value == target:
return True
#figure out which direction we need to go in
if target < self.value:
#we go left
if not self.left:
return False
else:
return self.left.contains(target)
#or, we get a spot where the node should be, but nothing is there
else:
#we go right
if not self.right:
return False
else:
return self.right.contains(target)
#how do we move towards the base case?
# Return the maximum value found in the tree
#used recursion - function that calls itself
#run time O (log n)
def get_max(self):
#check to the right side of the tree
#since left (self.left.value) side of the tree will always be smaller than the root
#if the right side of the tree is empty that just return the tree
if not self.right:
return self.value
#if right side of the tree is not empty. Then get the right child node with the max value
else:
return self.right.get_max()
# Call the function `fn` on the value of each node
#example of a tree traversal. Want to traverse through every tree node
#recursion
#doesn't actually return anything
def for_each(self, fn):
#call the function `fn` on self.value
fn(self.value)
#go to right child nodes if any exists
if self.right:
self.right.for_each(fn)
#go to the left child nodes if any exists
if self.left:
self.left.for_each(fn)
def iter_depth_first_for_each(self,fn):
#with depth-first traversal, there's a certain order to when we visit nodes
#what's that order? LIFO
#use a stack to get that order
#initialize a stack to keep track of the nodes we visited
stack = []
#add the first node (root) to our stack
stack.append(self)
#continue traversing until our stack is empty
while len(stack) > 0:
#pop off the stack
current_node = stack.pop()
#add its children to the stack
#add the right first and left child second
# to ensure that left is popped off the stack first
if current_node.right:
stack.append(current_node.right)
if current_node.left:
stack.append(current_node.left)
#call the fn function on self.value
fn(self.value)
def breadth_first_for_each(self,fn):
#breadth first traversal follows FIFO ordering of its nodes
#init a deque
q = deque()
# add first node to our q
q.append(self)
while len(q) > 0:
current_node = q.popleft()
if current_node.left:
q.append(current_node.left)
if current_node.right:
q.append(current_node.right)
fn(self.value)
from collections import deque
# Part 2 -----------------------
# Print all the values in order from low to high
# Hint: Use a recursive, depth first traversal
def in_order_print(self, node):
if node.left:
node.left.in_order_print(node.left)
print(node.value)
if node.right:
node.right.in_order_print(node.right)
# Print the value of every node, starting with the given node,
# in an iterative breadth first traversal
#uses a queue
def bft_print(self, node):
#init a queue
queue = self.deque()
#add first node to our queue
queue.append(node)
#breadth first traversal, working by layers
#if queue is not empty
while len(queue) > 0:
current_node = queue.popleft()
print(current_node.value)
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
# Print the value of every node, starting with the given node,
# in an iterative depth first traversal
def dft_print(self, node):
#dft have to create a stack
stack = []
#add a node to our empty stack
stack.append(node)
while len(stack) > 0:
current = stack.pop()
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
print(current.value)
# print (node.value)
# if node.left:
# node.left.dft_print(node.left)
# if node.right:
# node.right.dft_print(node.right)
# Stretch Goals -------------------------
# Note: Research may be required
# Print Pre-order recursive DFT
def pre_order_dft(self, node):
print(node.value)
if node.left:
node.left.pre_order_dft(node.left)
if node.right:
node.right.pre_order_dft(node.right)
# Print Post-order recursive DFT
def post_order_dft(self, node):
# print(node.value)
if node.left:
node.left.post_order_dft(node.left)
if node.right:
node.right.post_order_dft(node.right)
print(node.value) |
0aeeed9a00982db0a4991c67e1f9129ec6443ba9 | foxer9developer/test2-tools-repo | /main.py | 387 | 4.0625 | 4 | from add import add
from divide import divide
from multiply import multiply
from subtract import subtract
print("Welcome to Simple Calculator")
print("1. Addition")
print("2. Subtraction ")
print("3. Multliply")
print("4. Divide")
ch = input("Enter Operation: ")
if ch == '1':
add()
elif ch == '2':
subtract()
elif ch == '3':
multiply()
elif ch == '4':
divide()
else:
print("Error") |
40a2727f0a5fa4b6ccdd7d7026cf4ae7a4b3daa0 | KuzmichevaKsenia/itmo-optimization-labs | /4 - genetics/genetic.py | 815 | 3.546875 | 4 | import random
from .population import Population
from .specimen import Specimen
mutation_probability = 0.01
population_num = 4
generations_num = 3
population = Population(mutation_probability, population_num)
for i in range(population_num):
rand_genome = [j for j in range(1, len(Specimen.paths))]
random.shuffle(rand_genome)
rand_genome.insert(0, 0)
rand_genome.append(0)
population.specimens.append(Specimen(rand_genome))
population.specimens.sort()
print('Поколение 1:')
print(population)
for i in range(generations_num - 1):
population.next_generation()
print('Поколение {0}:'.format(i + 2))
print(population)
best_specimen = min(population.specimens)
print('Оптимальный путь:', best_specimen.genome, 'длиной', best_specimen.weight)
|
560d269361aaf0c285f0380b8c8170a009494cfe | VamsiMohanRamineedi/Python_OOPS | /inheritenceExercis.py | 956 | 3.515625 | 4 | class Character:
def __init__(self, name, hp, level):
self.name = name
if hp >= 1:
self.hp = hp
else:
raise ValueError('hp cannot be less than 1.')
if level >= 1 and level <= 15:
self._level = level
else:
raise ValueError('select levels from 1 to 15.')
def __repr__(self):
return f"My name is {self.name}"
@property
def level(self):
return self._level
@level.setter
def level(self, new_level):
if new_level >= 1 and new_level <= 15:
self._level = new_level
else:
raise ValueError('select levels from 1 to 15.')
class NPC(Character):
def __init__(self, name, hp, level):
super().__init__(name, hp, level)
def speak(self):
return "I heard there were monsters running around last night!"
villager = NPC('Bob', 10, 12)
print(villager.name)
print(villager.hp)
print(villager.level)
print(villager.speak())
# print('Level: ',villager.level)
# villager.level = 7
# print('New Level: ',villager.level)
|
b568b7729ed3c9775c6b0798aa9653e61c9e5d96 | Mailhot/sell-bigin | /app.py | 11,312 | 3.8125 | 4 | #!/usr/bin/env python3
import csv
import sys
class Mapper:
"""This instance makes a correspondance between 2 csv files
it takes the column from a first csv and map columns to a second csv"""
def __init__(self, csv_from, csv_to, mapper=None):
self.csv_from = csv_from
self.csv_to = csv_to
self.mapper = mapper
def create_mapper(self, ):
csv_from_header = read_file(self.csv_from, line_numbers=0) # get the file header
csv_to_header = read_file(self.csv_to, line_numbers=0) # get the file header
compare_columns_headers(csv_from_header, csv_to_header)
while True:
try:
print('Press "q" to exit, "p" to print headers status')
map_pair = input('Enter column map pair(from to)[1 2] >>')
if map_pair in ['q', 'Q', 'exit']:
print(self.mapper)
return self.mapper
elif map_pair in ['p', 'P', 'print']:
compare_columns_headers(csv_from_header, csv_to_header, self.mapper)
continue
result = map_pair.split(' ')
results = []
for result1 in result:
results.append(int(result1))
#TODO: add an error handling for not int values
if len(results) != 2:
print('Error, need two values separated by space')
if type(results[0]) == int and type(results[1]) == int:
if self.mapper == None:
self.mapper = {}
if results[0] in self.mapper.keys():
self.mapper[results[0]] = results[1]
else:
self.mapper[results[0]] = results[1] #TODO: useless at the moment
else:
print('Error, pair should be int type separated by space, not: %s %s' %(type(results[0]), type(results[1])))
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
print('map: ', self.mapper)
return self.mapper
def save_file(self, filename):
csv_to_header = read_file(self.csv_to, line_numbers=0)
csv_from_header = read_file(self.csv_from, line_numbers=0)
self.mapper = dict(sorted(self.mapper.items(), key=lambda item: item[1])) # sort mapper (need python 3.7 and more)
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_to_header)
first_line_passed = False
for line1 in read_file(self.csv_from, line_numbers=None):
if first_line_passed == False:
first_line_passed = True
continue
output_line = [''] * len(csv_to_header) # Create an output list of len equal to output header length
for key in self.mapper.keys(): # populate the values based on mapper
output_line[self.mapper[key]] = line1[key]
writer.writerow(output_line)
return filename
def compare_columns_headers(header1, header2, mapper={}):
"""This function compares 2 headers vertically (print them)
"""
longest_header1 = len(max(header1, key=len))
longest_header2 = len(max(header2, key=len))
headers = [header1, header2]
print('headers', headers)
table_height = len(max(headers, key=len)) # find the maximum header length
print('table_height', table_height)
display_content1 = 'Header 1'
display_content2 = 'Header 2'
print(longest_header1)
max_number_len = len(str(table_height))
# print(f'{display_content1:^{longest_header1}}')
#, " | ", f'\n{display_content2:^{longest_header2}}')
print(("{0:>"+str(longest_header1)+"}").format("header1") + " " + ("{0:>"+str(longest_header2)+"}").format("header2"))
for i in range(table_height):
#print(i)
print_str = ''
if i < (len(header1)):
if header1[i]:
#print('header1[i]', header1[i])
print_str += f'{i:^{max_number_len+1}}'
if i in mapper.keys():
print_str += "\033[4m"
print_str += f'{header1[i]:^{longest_header1}}'
print_str += "\033[0m"
else:
print_str += f'{header1[i]:^{longest_header1}}'
else:
# print_str += ("{0:>"+str(longest_header1+2)+"}").format(" None ")
print_str += f'{"":^{max_number_len+1}}' + f'{"":^{longest_header1}}'
print_str += " | "
if i < (len(header2)):
if header2[i]:
print_str += f'{i:^{max_number_len+1}}'
if i in mapper.values():
print_str += "\033[4m"
print_str += f'{header2[i]:^{longest_header2}}'
print_str += "\033[0m"
else:
print_str += f'{header2[i]:^{longest_header2}}'
else:
# print_str += ("{0:>"+str(longest_header2+2)+"}").format(" None ")
print_str += f'{"":^{max_number_len+1}}' + f'{"":^{longest_header2}}'
print(print_str)
# else:
# print((str(i+1)+"{0:>"+str(longest_header1)+"}").format(header1[i]) + " " + (str(i+1)+"{0:>"+str(longest_header2)+"}").format(header2[i]))
def convert_contact(from_file, to_file, mapper):
pass
def read_file(filename, line_numbers=None):
"""takes a filename and return a list of lines,
lines returned are either all if line_number == None
or filtered based on line_numbers (either list or int)
"""
with open(filename, 'r', encoding="latin-1") as file:
csv_reader = list(csv.reader(file, delimiter=',')) # TODO: could be more efficient for big file, not to open the complete file at once.
if line_numbers == None:
return csv_reader
elif type(line_numbers) == int:
return csv_reader[line_numbers]
elif type(line_numbers) == list:
return [csv_reader[i] for i in line_numbers]
else:
print('lines_numbers should be int or list, not %s' %type(line_numbers))
def update_field(csv_from, csv_ref, csv_from_column_name, csv_ref_in_column_name, csv_ref_out_column_name, output_filename,):
# replace a column name to an email.
# in this example we take the output of deal_map and replace the contact name by the contact email.
# Take a csv file, specify a reference csv file.
# Take a column(csv_from_column_name) in csv_from, search value in csv_ref (csv_ref_in_column_name) and replace by (csv_ref_out_column_name)
# then save to output_filename
# this is to adjust some value that requires other refs. than the original export.
lines = read_file(csv_from)
ref_lines = read_file(csv_ref)
with open(output_filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(lines[0])
first_line_passed = False
# Find column index
csv_from_column_index = lines[0].index(csv_from_column_name)
csv_ref_in_column_index = ref_lines[0].index(csv_ref_in_column_name)
csv_ref_out_column_index = ref_lines[0].index(csv_ref_out_column_name)
for line1 in lines:
if first_line_passed == False:
first_line_passed = True
continue
for line2 in ref_lines:
if line1[csv_from_column_index] == line2[csv_ref_in_column_index]:
line1[csv_from_column_index] = line2[csv_ref_out_column_index]
writer.writerow(line1)
def update_column(csv_from, csv_from_column_name, value, output_filename):
""" Replace column value conditional to being empty (len less than 2)
"""
lines = read_file(csv_from)
with open(output_filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(lines[0])
first_line_passed = False
csv_from_column_index = lines[0].index(csv_from_column_name)
for line1 in lines:
if first_line_passed == False:
first_line_passed = True
continue
if len(line1[csv_from_column_index]) < 2:
line1[csv_from_column_index] = value
writer.writerow(line1)
def update_stage(csv_from, csv_from_column_name, mapper, output_filename):
"""will update the stage based on a mapper of the stages between the input and output"""
lines = read_file(csv_from)
with open(output_filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(lines[0])
first_line_passed = False
csv_from_column_index = lines[0].index(csv_from_column_name)
for line1 in lines:
if first_line_passed == False:
first_line_passed = True
continue
if line1[csv_from_column_index] in mapper.keys():
line1[csv_from_column_index] = mapper[line1[csv_from_column_index]]
writer.writerow(line1)
if __name__ == "__main__":
# # Companies
# # In zendesk Companies is the Contact with Is_company set to True
# company_map1 = Mapper(csv_from='./data/ZendeskSell/contacts.0.csv', csv_to='./data/ZohoBigin/CompanySampleCsvFile.csv', mapper={4: 3, 5: 1, 6: 19, 10: 4, 15: 13, 16: 16, 18: 6, 19: 7, 20: 17, 23: 0, 25: 18, 29: 14, 31: 12, 34: 18, 36: 5, 37: 15})
# company_map1.create_mapper()
# company_map1.save_file('./CompanyOutput.csv')
# # Contact
# map1 = Mapper(csv_from='./data/ZendeskSell/contacts.0.csv', csv_to='./data/ZohoBigin/ContactSampleCsvFile.csv', mapper={0: 3, 1: 4, 4: 5, 6: 26, 7: 7, 8: 18, 9: 11, 10: 9, 15: 19, 16: 22, 17: 16, 20: 23, 23: 0, 25: 25, 29: 20, 31: 18, 32: 8, 34: 25, 37: 21})
# map1.create_mapper()
# map1.save_file('./contactoutput.csv')
# # Deals
# deal_map = Mapper(csv_from='./data/ZendeskSell/deals.0.csv', csv_to='./data/ZohoBigin/DealSampleCsvFile.csv', mapper={0: 0, 1: 4, 3: 20, 5: 8, 9: 17, 10: 16, 11: 7, 12: 6, 14: 13, 20: 3, 22: 5, 25: 18})
# deal_map.create_mapper()
# deal_map.save_file('./DealOutput.csv')
# #Correct the contact on deals
# update_field(csv_from='./DealOutput.csv',
# csv_ref='./data/ZendeskSell/contacts.0.csv',
# csv_from_column_name='Contact ID',
# csv_ref_in_column_name='id',
# csv_ref_out_column_name='email',
# output_filename='./DealOutputEmail.csv',
# )
# # Update close date
# update_column(csv_from='./DealOutputEmail.csv', csv_from_column_name='Closing Date', value='2021-01-01', output_filename='./DealOutputEmailCDate.csv')
#update stage
update_stage(csv_from='./DealOutputEmailCDate.csv', csv_from_column_name='Stage', mapper={'Unqualified': 'Closed Lost', 'Incomming': 'Qualification', 'Qualified': 'Needs Analysis', 'Quote': 'Proposal/Price Quote', 'Closure': 'Negotiation/Review', 'Won': 'Closed Won', 'Lost': 'Closed Lost'}, output_filename='./DealOutputEmailCDate2.csv')
|
b5308acdce732f2c83f423e502758b2e50a68197 | Ellavonn/Hello-Python | /Python Class/Example 3/student.py | 359 | 3.546875 | 4 | class Student:
def __init__(self,first_name,second_name,age):
self.first_name=first_name
self.second_name=second_name
self.age=age
def full_name(self):
name =self.first_name + self.second_name
return name
def year_of_birth(self):
return 2019- self.age
def initials(self):
name=self.first_name[0] + self.second_name[0]
return name |
818bdca7f0985e823400c463c259dc31c133294c | AnnapooraniKadhiravan/cartoonizer | /main.py | 1,308 | 3.75 | 4 | import cv2 #computer vision to read images
import numpy as np #to perform mathematical operations on arrays
from tkinter.filedialog import * #code causes several widgets like button,frame,label
photo = askopenfilename() #opens internal file to select image
img = cv2.imread(photo) #loads an image from the specified file
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #used to convert an image from one color space to another
grey = cv2.medianBlur(grey, 5) #central pixel is replace with median value,computes median value
edges = cv2.adaptiveThreshold(grey, 255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,9 ,9) #separate desirable foreground image objects from background based on the difference in pixel intensities of each region
#cartoonize
color = cv2.bilateralFilter(img,9,250,250) #edge preserving and noise-reducing smoothing filter for images
cartoon = cv2.bitwise_and(color,color,mask = edges) #calculates the conjunction of pixel in both images
cv2.imshow("Image", img) #used to display an image in a window
cv2.imshow("Cartoon",cartoon)
#save
cv2.imwrite("cartoon.jpg",cartoon) #used to save an image to any storage device
cv2.waitKey(0) #it only accepts time in milliseconds as an argument.
cv2.destroyAllWindows() #simply destroys all the windows we created
|
0e48b63dfbfe7beed362b5a51c3b3ff3c36793c7 | vishal-keshav/nn-incremental-learning-project | /dynamic_model.py | 9,800 | 3.546875 | 4 | """Define model architecture here.
The model class must be a torch.nn.Module and should have forward method.
For custome model, they are needed to be treated accordingly in train function.
"""
import torch
import torch.nn as nn
is_cuda = torch.cuda.is_available()
device = torch.device("cuda" if is_cuda else "cpu")
"""
Some terminology:
Each task is composed of a series of modules.
If there are K modules in a task, then input layer (where input is a tensor)
is indexed 0 and the the last layer that produces the output is indexed K-1.
Each of this indexes are called levels. Eg. if level=2, we are talking about
third module from the input module.
Each module is composed of a series of blocks. The information of the block
is provided in a list called block_list. Each element of a block_list is a
tuple (called block_info). This tuple looks like the following:
(
'conv',
param1,
param2,
..
)
based on the layer name (first entry), the tuple has to contain the parameters.
"""
class ModuleFactory(object):
def __init__(self, layer_list_info):
"""
Initialization of the the factory
layer_list_info is a dictionary with layer level as key
and a list describing all layer information as value.
Currently, no checks are made if the layer information is valid.
Arguments:
layer_list_info: dict
Returns:
None
"""
self.layer_list_info = layer_list_info
def _construct_block(self, block_info):
"""
Constructs a neural network layer based on information in block_info
Only three operations are application as of now!
Arguments:
block_info: tuple
Returns:
block: nn.Module
"""
layer_name = block_info[0]
if layer_name=='Conv2d':
in_channels, out_channels, kernel_size = block_info[1:]
return nn.Conv2d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size)
elif layer_name=='ReLU':
return nn.ReLU(inplace=True)
elif layer_name=='MaxPool2d':
kernel_size, stride = block_info[1:]
return nn.MaxPool2d(kernel_size=kernel_size,
stride=stride)
elif layer_name=='BatchNorm2d':
num_features = block_info[1]
return nn.BatchNorm2d(num_features=num_features)
elif layer_name=='Linear':
in_features, out_features = block_info[1:]
return nn.Linear(in_features=in_features,
out_features=out_features)
else:
raise Exception("_construct_block cannot construct block")
def generate_module(self, level):
"""
Constructs a module based on the info indexed at level idx in
layer_list_info dictionary
Arguments:
level: int
Returns:
final_module: nn.Module
nr_params_in_module: int
"""
layer_info = self.layer_list_info[level]
block_list = []
for block_info in layer_info:
block_list.append(self._construct_block(block_info))
final_module = nn.ModuleList(block_list)
nr_params_in_module = sum(p.numel() for p in final_module.parameters())
return final_module, nr_params_in_module
class DynaNet(nn.Module):
def __init__(self, layer_list_info):
"""
The initialization does not add any parameter in the module.
self.add_module() is done by add_model_for_task in the module dicts
initialized here.
Arguments:
layer_list_info: dict
Returns:
None
"""
super(DynaNet, self).__init__()
self.layer_list_info = layer_list_info
self.task_modules = nn.ModuleDict()
self.classification_layers = nn.ModuleDict()
self.module_generator = ModuleFactory(layer_list_info)
self.task_module_name_path = {}
self.nr_levels = len(layer_list_info)
self.task_idx = None
def add_model_for_task(self, task_idx):
"""
Adds the modules for a specific task.
It is assumed that this is called with task_idx = 0, 1, 2,... in this order
If the task_idx = 0, all modules are added.
else only one module is added (right now it is the last module)
Classification layer is added for each task.
Returns number of new parameters added.
Arguments:
task_idx: int
Returns:
total_params: int
"""
level_path = []
total_params = 0
nr_params = 0
if task_idx==0:
for level in range(self.nr_levels):
str_handle = "{}_{}".format(task_idx, level)
level_path.append(str_handle)
self.task_modules[str_handle], nr_params = self.module_generator.generate_module(level)
total_params += nr_params
else:
# For now, just add a module at the end
for level in range(self.nr_levels-1):
str_handle = "{}_{}".format(0, level)
level_path.append(str_handle)
str_handle = "{}_{}".format(task_idx, self.nr_levels-1)
level_path.append(str_handle)
self.task_modules[str_handle], nr_params = self.module_generator.generate_module(self.nr_levels-1)
total_params += nr_params
self.task_module_name_path[task_idx] = level_path
self.classification_layers[str(task_idx)] = nn.Linear(144, 10)
self._set_task(task_idx)
# print("{} parameters added".format(total_params))
return total_params
def _set_task(self, task_idx):
"""
User of this function is add_model_for_task.
It sets the task path that will be taken when forward is called.
For testing, it can be set from the user of this class object.
Arguments:
task_idx: int
Returns:
None
"""
self.task_idx = task_idx
# Defining the forward pass
def forward(self, x):
"""
Defines the forward pass for the selected task_idx
"""
for task_module_name in self.task_module_name_path[self.task_idx]:
for layer in self.task_modules[task_module_name]:
x = layer(x)
#x = self.task_modules[task_module_name](x)
x = x.view(x.size(0), -1)
x = self.classification_layers[str(self.task_idx)](x)
return x
def param_per_task_group_helper(task_id, model):
"""
A helper function that is going to group parameters used during training
a particular task. Optimizier will use this helper function.
The implementation is ad-hoc, meaning it is based on the module names we
know is going to be constructed by the DynaNet.
Arguments:
task_id: int
model: nn.Module
Returns:
parameters: List[nn.Parameters]
"""
# The first task is special case
param_list = []
nr_layers = model.nr_levels
if task_id==0:
for i in range(nr_layers):
module_name = '{}_{}'.format(0, i)
param_list.extend(list(model._modules['task_modules'][module_name].parameters()))
else:
module_name = '{}_{}'.format(task_id, nr_layers-1)
param_list.extend(list(model._modules['task_modules'][module_name].parameters()))
param_list.extend(list(model._modules['classification_layers'][str(task_id)].parameters()))
return param_list
#################################### Test ######################################
def test_module_factory():
layer_list_info = {
0: [('Conv2d', 3, 16, 3), ('BatchNorm2d', 16), ('ReLU',), ('MaxPool2d', 2, 2)],
1: [('Conv2d', 16, 4, 3), ('BatchNorm2d', 4), ('ReLU',), ('MaxPool2d', 2, 2)]
#2: [('Linear', 256, 10)]
}
model_factory_obj = ModuleFactory(layer_list_info)
layer1 = model_factory_obj.generate_module(0)
print(layer1)
layer2 = model_factory_obj.generate_module(1)
print(layer2)
layer3 = model_factory_obj.generate_module(2)
print(layer3)
def test_DynaNet():
layer_list_info = {
0: [('Conv2d', 3, 16, 3), ('BatchNorm2d', 16), ('ReLU',), ('MaxPool2d', 2, 2)],
1: [('Conv2d', 16, 4, 3), ('BatchNorm2d', 4), ('ReLU',), ('MaxPool2d', 2, 2)]
#2: [('Linear', 256, 10)]
}
net = DynaNet(layer_list_info)
print(net)
net.add_model_for_task(0)
print(net)
x = torch.ones(1,3,32,32)
y = net(x)
net.add_model_for_task(1)
print(net)
x = torch.ones(1,3,32,32)
y = net(x)
net.add_model_for_task(2)
print(net)
x = torch.ones(1,3,32,32)
y = net(x)
def test_param_group_helper():
layer_list_info = {
0: [('Conv2d', 3, 16, 3), ('BatchNorm2d', 16), ('ReLU',), ('MaxPool2d', 2, 2)],
1: [('Conv2d', 16, 4, 3), ('BatchNorm2d', 4), ('ReLU',), ('MaxPool2d', 2, 2)]
#2: [('Linear', 256, 10)]
}
net = DynaNet(layer_list_info)
print(net)
net.add_model_for_task(0)
net.add_model_for_task(1)
net.add_model_for_task(2)
print(net)
#for m in net.named_modules():
# print("M", m)
param_t0 = param_per_task_group_helper(0, net)
print("For task 0")
for p in param_t0:
print(type(p))
param_t1 = param_per_task_group_helper(1, net)
print("For task 1")
for p in param_t1:
print(type(p))
param_t2 = param_per_task_group_helper(2, net)
print("For task 2")
for p in param_t2:
print(type(p))
if __name__ == "__main__":
#test_module_factory()
#test_DynaNet()
test_param_group_helper() |
29e8eb7b6bba6a0ccd18b57b1f9c34c391d43044 | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios IV/Ex05.py | 1,153 | 3.796875 | 4 | # Exercicio 05
print('Exercicio 05')
import random
resultado = 0
statement = '''The Python Software Foundation and the global Python community welcome and encourage participation by everyone. Our community is based on mutual respect, tolerance, and encouragement, and we are working to help each other live up to these principles. We want our community to be more diverse: whoever you are, and whatever your background, we welcome you.'''
statement = statement.replace(',', '')
statement = statement.replace('.', '')
statement = statement.replace(':', '')
statement = statement.lower()
statement = statement.split()
def caracteresPy(palavra):
for caractere in palavra: # Para cada caractere da palavra...
if caractere in 'python': # Verifica se o caractere está em 'python'
return True # retorna verdadeiro se o caractere estiver em 'python'
return False # retorna falso se o caractere não estiver em 'python'
for x in statement:
if caracteresPy(x) and len(x) > 4: # passa x como parametro
resultado = resultado + 1
print(f'Palavras que possuem uma das letras "python" e com mais de 4 caracteres: {resultado}.') |
0dafc3ecb2533432faf42a7d7c3eca8f280e8f79 | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios IV/Ex01.py | 286 | 3.90625 | 4 | # Exercicio 01
print('Exercicio 01')
import random
num = []
min, max = 100, 0
num = random.sample(range(100), 10)
for x in num:
if x >= max:
max = x
if x <= min:
min = x
print(f'Todos os números: {num}')
print(f'Menor valor: {min}')
print(f'Maior valor: {max}') |
9059036f8be7c150514f821de7a3034cd0f3339c | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios I/Ex06.py | 304 | 3.734375 | 4 | # Exercicio 06
print('Exercicio 06: Tempo de Viagem de um Carro')
distancia = int(input('Insira a distância a ser percorrida em KM: '))
velocidade = int(input('Insira a velocidade média esperada para a viagem (KM/H): '))
tempo = distancia / velocidade
print(f'O tempo da viagem será de {tempo} horas') |
8f4cb8cbb8f0b0b47c32ae695ff90be71d0ddc32 | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios I/Ex01.py | 219 | 3.953125 | 4 | # Exercicio 01
print('Exercicio 01: Calculando a Soma de dois números!')
n1 = int(input('Insira um número: '))
n2 = int(input('Insira outro número: '))
soma = n1 + n2
print(f'A soma dos números inseridos é {soma}') |
ad5a4b4510f4fba1c1439b99a4e4a6167709997c | lbtdne/Coffee-Machine | /coffee_machine.py | 3,078 | 3.984375 | 4 | machine_steps = ["Starting to make a coffee",
"Grinding coffee beans",
"Boiling water",
"Mixing boiled water with crushed coffee beans",
"Pouring coffee into the cup",
"Pouring some milk into the cup",
"Coffee is ready!"]
recipes_ = [[250, 0, 16, 1, -4], [350, 75, 20, 1, -7], [200, 100, 12, 1, -6]]
active_recipe = [0, 0, 0, 0, 0]
machine_levels = [400, 540, 120, 9, 550]
trig_end = False
def request_action():
global trig_end
print("Write action (buy, fill, take, remaining, exit):")
action_ = str(input())
if action_ == "buy":
recipe_selector()
make_coffee()
elif action_ == "fill":
fill_machine()
elif action_ == "take":
take_money()
elif action_ == "remaining":
print_levels()
elif action_ == "exit":
trig_end = True
def print_levels():
global machine_levels
print("The coffee machine has:")
print(str(machine_levels[0])
+ " of water")
print(str(machine_levels[1])
+ " of milk")
print(str(machine_levels[2])
+ " of coffee beans")
print(str(machine_levels[3])
+ " of disposable cups")
print(str(machine_levels[4])
+ " of money")
def fill_machine():
global machine_levels
message_ = ["Write how many ml of water do you want to add:",
"Write how many ml of milk do you want to add:",
"Write how many grams of coffee beans do you want to add",
"Write how many disposable cups of coffee do you want to add"]
for i in range(len(message_)):
print(message_[i])
machine_levels[i] = machine_levels[i] + int(input())
def how_many_cups():
global machine_levels
global active_recipe
cups_ = []
parts_ = ["water", "milk", "coffee beans", "cups"]
for i in range(len(active_recipe)):
if active_recipe[i] > 0:
cups_.append(float(machine_levels[i] / active_recipe[i]))
else:
cups_.append(float(1))
if min(cups_) < 1:
return parts_[cups_.index(min(cups_))]
else:
return "True"
def recipe_selector():
global recipes_
global active_recipe
print("What do you want to buy?\n"
"1 - espresso\n"
"2 - latte\n"
"3 - cappuccino:")
chosen_ = input()
if chosen_ == "back":
request_action()
else:
active_recipe = recipes_[int(chosen_) - 1]
def make_coffee():
global active_recipe
global machine_levels
if how_many_cups() == "True":
print("I have enough resources, making you a coffee!")
machine_levels = [machine_levels[i] - active_recipe[i] for i in range(len(machine_levels))]
else:
print("Sorry, not enough "
+ str(how_many_cups())
+ "!")
def take_money():
global machine_levels
print("I gave you $"
+ str(machine_levels[4]))
machine_levels[4] = 0
while not trig_end:
request_action()
else:
exit() |
296cc9fc649aec65aa297645babfe674d91232ad | DenVankov/Numerical-Methods | /Lab1/NM_1_1.py | 4,860 | 3.671875 | 4 | from random import randint
class MatrixException(Exception):
pass
def getCofactor(A, tmp, p, q, n): # Function to get cofactor of A[p][q] in tmp[][]
i = 0
j = 0
# Copying into temporary matrix only those element which are not in given row and column
for row in range(n):
for col in range(n):
if row != p and col != q:
tmp[i][j] = A[row][col]
j += 1
if j == n - 1:
j = 0
i += 1
def determinant(A, n):
D = 0
if n == 1:
return A[0][0]
tmp = [[0] * n for _ in range(n)] # Cofactors
sign = 1 # Plus or minus
for i in range(n):
getCofactor(A, tmp, 0, i, n)
D += sign * A[0][i] * determinant(tmp, n - 1)
sign = -sign
return D
def adjoin(A, n): # Сопряженная
adj = [[0] * n for _ in range(n)]
if n == 1:
adj[0][0] = 1
return
tmp = [[0] * n for _ in range(n)] # Cofactors
sign = 1 # Plus or minusn
for i in range(n):
for j in range(n):
getCofactor(A, tmp, i, j, n) # Cofactor A[i][j]
if (i + j) % 2 == 0:
sign = 1
else:
sign = -1
adj[j][i] = (sign) * (determinant(tmp, n - 1)) # transpose of the cofactor matrix
return adj
def inverse(A, B, n):
det = determinant(A, n)
if det == 0:
print("Singular matrix, can't find its inverse")
return False
adj = adjoin(A, n)
for i in range(n):
for j in range(n):
B[i][j] = adj[i][j] / det
return True
def transpose(A, n):
B = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
B[i][j] = A[j][i]
return B
def multi(M1, M2):
sum = 0 # сумма
tmp = [] # временная матрица
ans = [] # конечная матрица
if len(M2) != len(M1[0]):
raise MatrixException('Matrix can\'t be multiplied')
else:
row1 = len(M1) # количество строк в первой матрице
col1 = len(M1[0]) # Количество столбцов в 1
row2 = col1 # и строк во 2ой матрице
col2 = len(M2[0]) # количество столбцов во 2ой матрице
for k in range(0, row1):
for j in range(0, col2):
for i in range(0, col1):
sum = round(sum + M1[k][i] * M2[i][j], 8)
tmp.append(sum)
sum = 0
ans.append(tmp)
tmp = []
return ans
def show(A, n):
for i in range(0, n):
for j in range(0, n):
print("\t", A[i][j], " ", end="")
print("\n")
def LUP_solve(L, U, pi, b, n):
x = [0 for i in range(n)]
y = [0 for i in range(n)]
for i in range(n):
summ = 0
for j in range(i):
summ += L[i][j] * y[j]
y[i] = b[pi[i]] - summ
for i in range(n - 1, -1, -1):
sec_summ = 0
for j in range(i + 1, n):
sec_summ += U[i][j] * x[j]
x[i] = (y[i] - sec_summ) / U[i][i]
x = [round(x[i], 5) for i in range(len(x))]
return x
def LUP_decompose(A, n):
pi = [i for i in range(n)]
for k in range(n):
p = 0
for i in range(k, n):
if abs(A[i][k]) > p:
p = abs(A[i][k])
tmp_k = i
if p == 0:
raise MatrixException('Matrix is degenerate')
pi[k], pi[tmp_k] = pi[tmp_k], pi[k]
for i in range(n):
A[k][i], A[tmp_k][i] = A[tmp_k][i], A[k][i]
for i in range(k + 1, n):
A[i][k] = A[i][k] / A[k][k]
for j in range(k + 1, n):
A[i][j] = A[i][j] - A[i][k] * A[k][j]
return pi
def get_LU(A):
n = len(A)
L = [[0] * n for i in range(0, n)]
U = [[0] * n for i in range(0, n)]
for i in range(n):
L[i][i] = 1
for j in range(n):
if j < i:
L[i][j] = A[i][j]
else:
U[i][j] = A[i][j]
return L, U
if __name__ == '__main__':
print("Input demention of matrix: ")
n = int(input())
A = []
for i in range(n):
A.append(list(map(float, input().split())))
print("Start:")
show(A, n)
print("The Adjoint is :\n")
inv = [[0] * n for _ in range(n)]
adj = adjoin(A, n)
show(adj, n)
print("The Inverse is :\n")
if inverse(A, inv, n):
show(inv, n)
pi = LUP_decompose(A, n)
print("A after LUP:")
show(A, n)
L, U = get_LU(A)
print("L:")
show(L, n)
print("U:")
show(U, n)
print("A:\n")
R = multi(L, U)
show(R, n)
print("Solving:")
b = [-23, 39, -7, 30]
print(LUP_solve(L, U, pi, b, n))
|
69df0ffef277af6e3466541e8e07265ed79b960e | GGGomer/AoC2020 | /02/02b.py | 1,012 | 3.609375 | 4 | import re
def main():
f = open("./02input", 'r')
line = f.readline()
lowest_indices = []
highest_indices = []
characters = []
passwords = []
# Loop through all lines
while line:
# deconstruct line into elements for lists
decimals = re.findall(r'\d+', line)
lowest_indices.append(int(decimals[0]))
highest_indices.append(int(decimals[1]))
characters.append(re.search(r'[a-z]', line).group())
passwords.append(re.sub('\n',"",re.split(": ", line)[1]))
# Next line
line = f.readline()
# Assert if arrays are of same length
assert len(passwords) == len(lowest_indices)
assert len(passwords) == len(highest_indices)
assert len(passwords) == len(characters)
# Count correct passwords
correct_passwords = 0
for i in range(len(passwords)):
if((passwords[i][lowest_indices[i]-1] == characters[i])^(passwords[i][highest_indices[i]-1] == characters[i])):
correct_passwords += 1
print(correct_passwords)
if __name__ == "__main__":
main()
|
2d120b9d6eb107bbd9404e0a20c88b354f0944cc | aaskorohodov/Learning_Python | /Обучение/Range comprehension.py | 189 | 3.515625 | 4 | list = [eo * 2 for eo in range(10,1,-1) if eo % 2 != 1]
print(list)
words = ["hello", "hey", 'goodbey', "guitar", "piano"]
words2 = [eo + "." for eo in words if len(eo) < 7]
print(words2) |
ab1df5f6495bf2de81da4b47c6f82acf8b9645ae | aaskorohodov/Learning_Python | /Обучение/Set (множество).py | 477 | 4.15625 | 4 | a = set()
print(a)
a = set([1,2,3,4,5,"Hello"])
print(a)
b = {1,2,3,4,5,6,6}
print(b)
a = set()
a.add(1)
print(a)
a.add(2)
a.add(10)
a.add("Hello")
print(a)
a.add(2)
print(a)
a.add("hello")
print(a)
for eo in a:
print(eo)
my_list = [1,2,1,1,5,'hello']
my_set = set()
for el in my_list:
my_set.add(el)
print(my_set)
my_set = set(my_list)
print(my_set)
my_list = list(my_set)
print(my_list)
a = {"hello", "hey", 1,2,3}
print(5 in a)
print(15 not in a)
|
7e39b989796a5177bff5ea327f1566012aeb5a37 | aaskorohodov/Learning_Python | /Обучение/Вывод чисел меньше х.py | 189 | 3.59375 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for elem in a:
if elem < 5:
print(elem)
print([elem for elem in a if elem < 5])
b = 0
while a[b] < 5:
print(a[b])
b += 1 |
32b882820ebdb60f96270d0e908bc0ba2cf559f6 | aaskorohodov/Learning_Python | /Обучение/What do U want to eat.py | 266 | 4 | 4 | print("Введите выше имя, затем нажмите Entr")
name = input()
print(name + ", что вы хотите поесть?")
food = input()
print("")
print(name + ", немедленно идите в магизин и купите " + food + "!") |
f1aae24aa9c84713a937dace34fdbda5d367cb50 | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Is_sorted.py | 292 | 3.640625 | 4 | a = ['a', 'v', 'a']
b = [1, 2, 3, 5, 4]
def is_sorted(lis):
i = 0
for el in lis:
try:
if lis[i] <= lis[i+1]:
i = i + 1
else:
return False
except IndexError:
pass
return True
print(is_sorted(a)) |
f407b77eda6e4ceaf757b664a2cf0d03ec59337d | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Metathesis pair.py | 4,342 | 4.03125 | 4 | '''Ищет пары-метатезисы – такие слова, где перестановка дищь 2х букв дает другое слово'''
file = open('C:\word.txt')
words = ''
for eo in file:
words += eo
'''Превращаем файл в строку, где каждое слово идет с новой строки.'''
def anagrams(all_words):
'''
Ищем анаграмы, собирая их в словарь, где ключ = последовательность букв, а значение = последовательность слов,
которые можно собрать из этих букв.
1. Создаем пустой словарь
2. Для каждого элемента (строки) исходного списка (строки), вызываем функцию, которая вернет список букв,
из которых состоит это слово. Буквы возвращаются в алфавитном порядке, но их порядок роли не играет, он нужен,
чтобы сделать следующий шаг
3. Если этого набора букв еще нет в словаре, то кладем на место ключа, а значением кладем слово в виде списка.
4. Если набор букв уже есть в словаре, то кладем к нему в значение (в список) слово, из которого получились эти буквы.
'''
an_dict = {}
for el in all_words.split('\n'):
l = letters(el)
if l not in an_dict:
an_dict[l] = [el]
else:
an_dict[l].append(el)
return an_dict
def letters(word):
'''Берет слово и превращает его в набор букв, из которогоэто слово состоит. Буквы ставит в алфавитный порядок.'''
let = list(word)
let.sort()
let = ''.join(let)
return let
def metathesis_pair(words):
'''
Среди собранного ранее словаря ищет пары-метатезисы.
1. Берет исходный словарь и начинает перебирать списки (for ang in an_dict.values():)
2. Для каждого слова в списке, пребирает все прочие слова в списке
3. Если слова отличаются (причем первое меньше второго) и если разница между словами == 2 буквы, то вот наша пара.
*сравнивать слова (<) надо, чтобы пара не попала в выдачу дважды. Это условие дает возможность сравнить 2 слова
по разнице в 2 буквы первый раз, но переверни слова, и в выдачу они уже не попадут.
**для сравнения на 2 буквы вызывается другая функция
'''
global anagrams
an_dict = anagrams(words)
for ang in an_dict.values():
for word1 in ang:
for word2 in ang:
if word1 < word2 and word_difference(word1, word2) == 2:
print(word1, word2)
def word_difference(word1, word2):
'''
Сравнивает 2 слова, считает, на сколько букв они отличаются. Каждое различие == другая буква в том же месте слова.
1. Заводит счетчик различий
2. Сравнивает длину слов, если совпадает, то идет дальше
3. Зипует слова, делая список кортежей, где в каждом (кортеже) лежат по 1 букве из кождого слова
4. Берет кортеж и сравнивает быквы, если они не одинаковы, то добавляет в счетчик 1.
'''
count = 0
if len(word1) == len(word2):
for c1, c2 in zip(word1, word2):
if c1 != c2:
count += 1
return count
metathesis_pair(words) |
ffbda9f72900acc80ed03bf871db381d5ce5fc5e | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Avoids.py | 2,388 | 3.8125 | 4 | avoid_ths = input()
'''Принимает от пользователя набор стоп-букв'''
file = open('C:\word.txt')
'''открывает файл с большим количеством слов'''
words = ''
for eo in file:
words += eo
words = words.replace('\n', ' ')
'''собирает из файла строку со словами через пробел'''
def avoids(list, avoid_ths):
'''принимает набор слов и стоп слова. превращает набор слов в список.
Каждое слово из списка передает функции, которая принимает решение "есть ли стоп-буква в этом слове" и возвращает ответ remove, если слово надо убрать.
В случае ответа remove, ничего не происходит, а если ответ не приходит, то слово заносится в новый список.
*у меня не получилось убирать слова из старого списка, потому что в этом случае список начинает прыгать через слово.
**берет первое слово в списке, его надо убрать, убирает, берет второе слово в списке, но второе слово теперь третье (одно ведь убрали), и так пропускает слова.
в конце печатает получившийся список и длину этого списка (сколько там слов)'''
list = list.split()
list2 = []
for word in list:
if avoid_checker(word, avoid_ths) == 'remove':
pass
else:
list2.append(word)
print(list2)
print(len(list2))
def avoid_checker(word, avoid_ths):
'''Принимает слово и стоп-буквы, и то и другое строкой, стоп-буквы без пробелов. Берет каждую букву слова и сравнивает со стоп-буквами.
Если совпадает хоть с одной стоп-буквой, то возвращает remove'''
for letter in word:
if letter in avoid_ths:
return 'remove'
avoids(words, avoid_ths) |
db236bab002eac619047121dde53949450c3daf6 | aaskorohodov/Learning_Python | /Обучение/Dict counter 2.py | 680 | 3.625 | 4 | text = "привет привет привет пока пока здрасьте"
my_dict2 = {}
for eo in text.split():
my_dict2[eo] = my_dict2.get(eo, 0) + 1 #часть до знака = присваивает словарю ключ, часть справа присваивает значение, при этом...
#...get возвращает значение по ключу eo, чтобы его и присвоить, а если ключа нет, то присваивается 0. Ко всему добавляется 1, чтобы если ключ есть то +1, если нет, то 0+1
print(my_dict2) |
c6bfbae89417c7307e7ff93ea916db38b789ac6c | aaskorohodov/Learning_Python | /Обучение/Классы - наследование.py | 857 | 4.03125 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("Person created")
def say_hello(self):
print(f"{self.name} say hello!")
class Student(Person):
def __init__(self, name, age, average_grade):
#Person.__init__(self, name, age)
super().__init__(name, age)
self.average_grade = average_grade
print("Student created")
def study(self):
print(f"{self.name} studies")
def say_hello(self):
super().say_hello()
print(f"Student with name: {self.name} say hello!")
class Teacher(Person):
pass
def introduce(person):
print("Now, a person will say hello")
person.say_hello()
people_qrr = [Student("Tom", 18, 3.5), Teacher("Katy", 45), Student("Bob", 26, 4.8)]\
for person in people_qrr:
introduce(person) |
9beefaee0cd2529075f223c1e2fb39871d45f24c | bjlovejoy/workoutPi | /challenge.py | 5,594 | 3.515625 | 4 | import os
import datetime
from time import time, sleep
from gpiozero import Button, RGBLED, Buzzer
from colorzero import Color
from oled import OLED
'''
Creates or appends to file in logs directory with below date format
Each line contains the time of entry, followed by a tab, the entry text and a newline
'''
def log_data(text):
today_date = str(datetime.date.today()).replace("-", "_")
hour_min = (datetime.datetime.now()).strftime("%H:%M")
log_path = "/home/pi/workoutPi/logs/error_log_" + today_date + ".txt"
append_write = "w"
if os.path.isfile(log_path):
append_write = "a"
with open(log_path, append_write) as log:
line = hour_min + "\t" + text + "\n"
log.write(line)
class Challenge:
def __init__(self, name, style, description, num_time_sec=60, lowest=True):
"""
name: name of the challenge to save to text file (str)
style: how long it takes to do activity ("stopwatch") or how many done in timeframe ("counter") (str)
num_time_sec: time for "counter" challenges (int)
description: text to output to OLED display for challenge (str)
lowest: if True, then lowest time (stopwatch) is highest score
"""
self.name = name.replace(" ", "_")
self.style = style
self.description = description
self.num_time_sec = num_time_sec
self.lowest = lowest
def save_results_counter(self, button, oled, led):
records_path = "/home/pi/workoutPi/records/" + self.name + ".txt"
edit_file = False
nums = list()
select = False
num = 0
while not select:
oled.show_num(num, "How many?")
button.wait_for_press()
held_time = time()
sleep(0.05)
while button.is_pressed:
if time() - held_time > 1.5:
led.color = Color("green")
select = True
sleep(0.05)
if not select:
num += 1
led.off()
if os.path.isfile(records_path):
with open(records_path, 'r') as rec:
nums = rec.readlines()
if num > int(nums[0].rstrip('\n')):
nums[2] = nums[1]
nums[1] = nums[0]
nums[0] = str(num) + '\n'
edit_file = True
elif num > int(nums[1].rstrip('\n')):
nums[2] = nums[1]
nums[1] = str(num) + '\n'
edit_file = True
elif num > int(nums[2].rstrip('\n')):
nums[2] = str(num) + '\n'
edit_file = True
if edit_file:
with open(records_path, "w") as rec:
rec.writelines(nums)
else:
edit_file = True
record = str(num) + '\n'
nums.append(record)
nums.append("0\n")
nums.append("0\n")
with open(records_path, "w") as rec:
rec.writelines(nums)
log_data("Challenge counter event saved: " + str(num) + "\tin list: " + str(nums))
log_data("Saved location: " + records_path)
oled.challenge_records(nums, "reps", edit_file)
def save_results_stopwatch(self, recorded_time, oled):
records_path = "/home/pi/workoutPi/records/" + self.name + ".txt"
edit_file = False
times = list()
if os.path.isfile(records_path):
with open(records_path, 'r') as rec:
times = rec.readlines()
if lowest:
if recorded_time < float(times[0].rstrip('\n')) or float(times[0].rstrip('\n')) == 0:
times[2] = times[1]
times[1] = times[0]
times[0] = str(recorded_time) + '\n'
edit_file = True
elif recorded_time < float(times[1].rstrip('\n')) or float(times[1].rstrip('\n')) == 0:
times[2] = times[1]
times[1] = str(recorded_time) + '\n'
edit_file = True
elif recorded_time < float(times[2].rstrip('\n')) or float(times[2].rstrip('\n')) == 0:
times[2] = str(recorded_time) + '\n'
edit_file = True
else:
if recorded_time > float(times[0].rstrip('\n')):
times[2] = times[1]
times[1] = times[0]
times[0] = str(recorded_time) + '\n'
edit_file = True
elif recorded_time > float(times[1].rstrip('\n')):
times[2] = times[1]
times[1] = str(recorded_time) + '\n'
edit_file = True
elif recorded_time > float(times[2].rstrip('\n')):
times[2] = str(recorded_time) + '\n'
edit_file = True
if edit_file:
with open(records_path, "w") as rec:
rec.writelines(times)
else:
edit_file = True
record = str(recorded_time) + '\n'
times.append(record)
times.append("0\n")
times.append("0\n")
with open(records_path, "w") as rec:
rec.writelines(times)
oled.challenge_records(times, "sec", edit_file)
|
aed5cd14882ef0a82e36f8b3bed9cf81748bd3ae | LeaderRushi/PythonForKids | /basic data.py | 455 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 25 11:54:29 2020
@author: giris
"""
subject_list = ['math', "science", "LASS", "PE"]
subject_list.append("music")
print (subject_list)
subject_list.remove("PE")
print (subject_list)
subject_list.sort()
print (subject_list)
teacher_list = ['Harder','Drake', 'Kirkman', 'Lidstrum']
print (teacher_list)
teacher_map = {'math':'Harder','science':'Drake'}
print(teacher_map['math'])
|
1ce5004cdc178694f616e2ea4eabe0f73c3581b2 | riterdba/magicbox | /cl9.py | 337 | 3.984375 | 4 | #!/usr/bin/python3
class Horse():
def __init__(self, name, color, rider):
self.name = name
self.color = color
self.rider = rider
class Rider():
def __init__(self, name):
self.name = name
riderr = Rider('Миша')
horsee = Horse('Гроза', 'черная', riderr)
print(horsee.rider.name)
|
9de3f927d4cd56dc1f3b0d3397cebad9b61f67a8 | riterdba/magicbox | /4.py | 426 | 3.6875 | 4 | #!/usr/bin/python3
#Определение високосного года.
x=input('Введите год:')
y=len(x)
x=int(x)
if (y==4):
if((x%4==0) and (x%100!=0)):
print('Год високосный')
elif((x%100==0) and (x%400==0)):
print('Год високосный')
else:
print('Год не високосный')
else:
print('Вы ввели неправильный год')
|
e0dd4c5a6ead7cd585d9d4cf387e6d4c8849accb | riterdba/magicbox | /cl11.py | 283 | 4.125 | 4 | #!/usr/bin/python3
class Square():
def __init__(self, a):
self.a = a
def __repr__(self):
return ('''{} на {} на {} на {}'''.format(self.a, self.a, self.a, self.a))
sq1 = Square(10)
sq2 = Square(23)
sq3 = Square(77)
print(sq1)
print(sq2)
print(sq3)
|
cf0e08f57baf9bb7b3e9a2f27acce377fdf33c1d | mayIlearnloopsbrother/Python | /chapters/chapter_7/ch7b.py | 400 | 3.890625 | 4 | #!/usr/bin/python3
#7-8 deli
sandwich_orders = ['ham', 'chicken', 'brocoli']
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
print("making you a " + sandwich.title() + " sandwich")
finished_sandwiches.append(sandwich)
print("\n")
print("following sandwiches have been made")
for finished_sandwich in finished_sandwiches:
print(finished_sandwich.title())
|
9f3e5247a1c58d8c2e625138306b8422bc430afc | mayIlearnloopsbrother/Python | /chapters/chapter_6/ch6a.py | 300 | 4.15625 | 4 | #!/usr/bin/python3
#6-5 Rivers
rivers = {
'nile': 'egypt',
'mile': 'fgypt',
'oile': 'ggypt',
}
for river, country in rivers.items():
print(river + " runs through " + country)
print("\n")
for river in rivers.keys():
print(river)
print("\n")
for country in rivers.values():
print(country)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.