text
stringlengths 37
1.41M
|
---|
#!python2
"""
(C) Michael Kane 2017
Student No: C14402048
Course: DT211C
Date: 26/10/2017
Title: Edge and gradient detection.
Introduction:
Step-by-step:
Give an overview:
Comment on experiments:
References:
"""
# import the necessary packages:
import numpy as np
import cv2
from matplotlib import pyplot as plt
from matplotlib import image as image
import easygui
class edge():
def getImage(self):
try:
#Opening an image from a file:
print("Please Select an image:")
file = easygui.fileopenbox()
image = cv2.imread(file)
gradients = self.getGradients(image)
canny = self.getCanny(image)
except:
print("User failed to select an image.")
while True:
# Showing an image on the screen (OpenCV):
cv2.imshow("Image", canny)
key = cv2.waitKey(0)
# if the 'q' key is pressed, quit:
if key == ord("q"):
break
def getGradients(self, image):
G = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gradients = cv2.Sobel(G,ddepth=cv2.CV_64F,dx=1,dy=0)
return gradients
def getCanny(self, image):
canny = cv2.Canny(image,threshold1=100,threshold2=200)
return canny
if __name__ == "__main__":
detect_edge = edge()
detect_edge.getImage()
|
"""
Name of Activity: Module 3 Live Session Assignment: Class Inheritance
Name: Nathan England
Computing ID: nle4bz
Partner: John Carpenter
Partner Computing ID: jmc7dt
"""
class Student:
# fields: name, id, grades(a list)
#Local variable
#grades = [] # initially empty
def __init__(self, name, id): # constructor
self.name = name
self.id = id
self.grades = [] #creates a new empty list for each student
def addGrade(self, grade): # add the grade to the list of grades
self.grades.append(grade)
def showGrades(self): # displaying the grades
grds = '' # empty string
for grade in self.grades: # Loop through grades list
grds += str(grade) + ' ' # assign each grade to the string grds
return grds
def average(self): # takes average of grades
num = sum(self.grades)
denom = len(self.grades)
return str(num/denom)
#1. Add two methods to class Student
def welcome(self, graduationyear): # first new method
print("Welcome " + self.name + " to the class of " + str(graduationyear))
def graduated(self, currentyear, graduationyear): # second new method
if currentyear > graduationyear:
return True
else:
return False
def __str__(self):
return self.name + ', ' + self.id + '\n' + 'Grades: ' + self.showGrades() + '\n' + 'Average: ' + self.average()
#2. Class that inherits one or two of these methods
class Freshman(Student): #child class of student
def __init__(self, name, id, graduationyear): # Note all the attributes
Student.__init__(self, name, id) # Call the base class constructor
self.graduationyear = graduationyear
def __str__(self):
retStr = Student.__str__(self) # Call to-string of base class (Student)
retStr += '\n Graduation Year: ' + str(self.graduationyear)
return retStr
#Testing inheritance
freshman1 = Freshman('Nathan', '456', 2018)
print(freshman1.welcome(freshman1.graduationyear))
print(freshman1.graduated(2019, freshman1.graduationyear))
#==================================================
student1 = Student('Jones', '123')
print(str(student1.name) + ', ' + str(student1.id)) # Output: Jones, 123
student1.addGrade(88)
student1.addGrade(72)
student1.addGrade(100)
print("Grades: " + student1.showGrades()) # showing grades for student1
# print(student1) # Will NOT work, since we do not have a "to-string" (__str__) method
# Output of the above line will be a memory address like:
# <__main__.Student object at 0x00000220B8611BE0>
#==================================================
# ** TO THINK ABOUT: **
# This is fine, however, what happens if you create a second Student object??
# Local ("global") variable grades (a list - which is a mutable object) will
# accumulate grades from ALL students... this behavior is not what we want.
# Uncomment lines 46-51 below and see what happens. How would you fix this??
# For now, the above file is fine for the above scenario.
# =============================================================================
s2 = Student('Clayton', '115')
print(str(s2.name) + ', ' + str(s2.id))
s2.addGrade(85)
s2.addGrade(95)
s2.addGrade(99)
print("Grades: " + s2.showGrades()) # !!!
# =============================================================================
#3: Creating Student 1 and adding grades appears to have desired outcome by printing student name and ID and allowing you to add grades to the grades list.
#When creating s2 the code prints the individual student's name and ID, but s2's grades output includes those of Student 1 which is not the desired outcome.
#4: Defined grades within the constructor so that a new empty grades list is created for each student (see changed code above).
#5: See above __str__(self) function (lines 35-36)
#6: See above average(self) function (lines 30-33)
#7:
studentA = Student('John', '123')
print(str(studentA.name) + ', ' + str(studentA.id)) # Output: John, 123
studentA.addGrade(90)
studentA.addGrade(95)
studentA.addGrade(100)
print("Grades: " + studentA.showGrades()) # showing grades for studentA
print("Average: " + studentA.average())
print(studentA) # Will work, since we do have a "to-string" (__str__) method
studentB = Student('Nathan', '456')
print(str(studentB.name) + ', ' + str(studentB.id)) # Output: Nathan, 456
studentB.addGrade(91)
studentB.addGrade(96)
studentB.addGrade(101) # Test had bonus questions
print("Grades: " + studentB.showGrades()) # showing grades for studentB
print("Average: " + studentB.average())
print(studentB) # Will work, since we do have a "to-string" (__str__) method
|
import functools as ft
import numpy as np
fib = [0,1]
array = np.array([])
def fib(integer):
if integer < 0:
print("Not a valid input")
elif integer <= len(fib):
return fib[integer - 1]
else:
temp_fibonacci =
|
class BinarySearch(list):
def __init__(self, first, a, b):
"""Variables a,b are respectivery the length and step of
the list we're creating, when subclassing list"""
super(BinarySearch, self).__init__(self)
"""i.e., Inherit to
BinarySearch the arguments of the parent class, list"""
array_ = [num for num in range(first,a*b+1, b)]
"""creates and array with the bracketed characteristics
start at 0, step = (a*b) + 1, end at b"""
self.a = len(array_)
self.extend(array_)
length = self.a #initializing instance variable called length
def search(self, querry):
"""method iterates thro' array and returns dict with
count of number of iterations, and index of querry"""
count = 0
index = 0
first_element = 0
last_element = len(self) - 1
found = False
while first_element <= last_element and not found:
midpoint = (first_element + last_element) // 2
count += 1
if self[midpoint] == querry:
found = True
index = self.index(querry)
else:
if querry < self[midpoint]:
last_element = midpoint - 1
else:
first_element = midpoint + 1
return {"count": count, "index":self.index(querry)}
paul = BinarySearch(10,100,10)
print
print len(paul)
print
print paul
print
print paul.search(500)
print
|
"""
Homework 2
>Problem 4
Author: Derrick Unger
Date: 1/24/20
CSC232 Winter 2020
"""
# Initialize Variables
i = 0 # Array Counter
inputSum = 0
print("\n=======================================")
print(" Compound Interest Calculator\n")
print("Input instructions:")
print(" -Input interest rate in percent form i.e. input 10.5 for 10.5%")
print(" -When prompted, input one of these desired factors in this form: ")
print(" -F/P, P/F, P/A, A/P, A/F, F/A, A/G, or P/G\n")
while True:
try:
i = eval(input("Enter a desired interest rate: "))
factorIn = input("Choose desired factor title: ")
print("\n n ", factorIn)
print(" === ==========")
i = i/100
# Equations
for n in range(1, 11):
FP = (1+i)**n
PF = 1/FP
PA = (((1+i)**n)-1)/(i*(1+i)**n)
AP = 1/PA
AF = i/((1+i)**n-1)
FA = 1/AF
AG = abs((1/i)-(n/(((1+i)**n)-1)))
PG = abs((((1+i)**n)-(i*n)-1)/((i**2)*((1+i)**n)))
if factorIn == "F/P":
factor = str.format('{0:.4f}', FP)
elif factorIn == "P/F":
factor = str.format('{0:.4f}', PF)
elif factorIn == "P/A":
factor = str.format('{0:.4f}', PA)
elif factorIn == "A/P":
factor = str.format('{0:.4f}', AP)
elif factorIn == "A/F":
factor = str.format('{0:.4f}', AF)
elif factorIn == "F/A":
factor = str.format('{0:.4f}', FA)
elif factorIn == "A/G":
factor = str.format('{0:.4f}', AG)
elif factorIn == "P/G":
factor = str.format('{0:.4f}', PG)
else:
print("Invalid factor, try again")
if n < 10:
print(" ", n, " ", factor)
else:
print("", n, " ", factor)
break
except:
print("Error: Invalid value, try again\n")
print("=======================================\n")
|
"""
Homework 5
>Problem 8
Author: Derrick Unger
Date: 2/14/20
CSC232 Winter 2020
"""
while True:
try:
print("\nInstructions: ")
print("Inputs must be a string of digits, separated by a space.")
print("Ex: 12345 67890\n")
s1, s2 = input("\nInput two numeric strings of digits: ").split(" ")
# Create list of ints from string input
l1 = list(map(int, list(s1)))
l2 = list(map(int, list(s2)))
if len(l1) != len(l2):
print("String of digits must be the same length! Try again")
else:
for i in range(0, len(l1)):
if l1[i] < l2[i]:
l1Temp = l1[i] # Save original l1 value for swapping
l1[i] = l2[i] # Swap l2 to l1
l2[i] = l1Temp # Assign l2 to old l1 value
l1[i] = str(l1[i]) # Convert all values back to strings
l2[i] = str(l2[i])
# Rejoin list of strings
s3 = ""
s4 = ""
s3 = s3.join(l1)
s4 = s4.join(l2)
print("\nOriginal input: ")
print(s1)
print(s2)
print("\nSorted Form: ")
print(s3)
print(s4)
break
except:
print("Invalid input, try again")
|
"""
Homework 7
>Problem 4
Author: Derrick Unger
Date: 2/29/20
CSC232 Winter 2020
"""
# User Input
code = 0
while code == 0:
try:
puzzle = input("\nEnter puzzle: ").upper()
whiteList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-& "
print("\nPuzzle: " + puzzle)
# Check input validation
for char in list(puzzle):
if char not in list(whiteList):
print("\nInvalid character input, please retry.\n")
code = 0
break
else:
code = 1
except:
print("Error, try again...")
# Hide Characters
hidden = []
for char in list(puzzle):
if char.isalpha():
hidden.append("*")
else:
hidden.append(char)
print("Puzzle: ", "".join(hidden))
# Ask for User for Guess
code = 0
whiteList2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while code == 0:
try:
print("Unused guesses: ", whiteList2)
guess = input("\nEnter guess: ").upper()
if guess not in list(puzzle): # Incorrect Guesses
print("\nIncorrect guess!\n")
elif guess not in list(whiteList2):
print("You already guessed that, or thats not a good guess.")
else: # Correct Guesses
whiteList2 = whiteList2.replace(guess, "") # Remove guess
correctGuesses = []
correctGuesses.append(guess)
print("Correct guess!")
# Remove asterisks from correct guesses
hidden = []
for char in list(puzzle):
if char in whiteList2: # If in remaining guesses, "*"
hidden.append("*")
else:
hidden.append(char)
hidden = "".join(hidden)
print("Puzzle: ", hidden)
# If not more asterisks, quit
if hidden.find("*") == -1:
code = 1
except ZeroDivisionError:
print("Error, try again...")
print("\nPuzzle solved, good job!!\n")
|
"""
Homework 3
>Problem 2
Author: Derrick Unger
Date: 1/31/20
CSC232 Winter 2020
"""
code, i = 0, 0
mylist = [] # Define your list
print("\n=============================================")
while code == 0:
try:
userInput = input("Enter a number or type 'EXIT' or 'exit' to stop: ")
if userInput.upper() == "EXIT":
print("No longer accepting inputs...")
code = 1
else:
eval(userInput)
mylist.append(str(userInput))
except:
print("Error: wrong value entered")
for n in range(0, len(mylist)):
print(mylist[n])
print("=============================================\n")
|
"""
Homework 5
>Problem 3
Author: Derrick Unger
Date: 2/14/20
CSC232 Winter 2020
"""
import numpy as np
np.set_printoptions(formatter={'float_kind': lambda value: format(value, '8.3f'),
'int_kind': lambda value: format(value, '10d')})
print("\nINSTRUCTIONS")
print("-"*len("INSTRUCTIONS"))
print("Input arrays by value and by row i.e for ([1,2],[3,4]),"
" input 1,2,3,4 all separated by commas and on one line.\n")
while True:
try:
# 3x2 Array
print("3x2 Array Builder (only first 6 inputs accpeted)...")
a = list(map(eval, input("\nEnter values : ").split(",")))[:6]
array1 = np.reshape(np.array(a), (3, 2))
# 2x1 Array
print("2x1 Array Builder (only first 2 inputs accepted)...")
b = list(map(eval, input("\nEnter values : ").split(",")))[:2]
array2 = np.reshape(np.array(b), (2, 1))
break
except:
print("\nError: Invalid input, retry\n")
# Dot Product
print("Array 1: \n", array1)
print("Array 2: \n", array2)
print("Dot Product: \n", np.dot(array1, array2))
|
"""
Test 6
>Problem 1
Author: Derrick Unger
Date: 3/20/20
CSC232 Winter 2020
"""
print("\n" + "="*40)
print("PROBLEM 1")
print("Input format: last,first 123-45-6789 23.51")
print("Notice, no space between first and last as shown in problem statement")
print("To exit, enter 'exit ' without quotes and with two spaces at end")
names = []
socs = []
miles = []
while True:
try:
name, soc, mile = input("\nInput values: ").split(" ")
# Exit Checks
if (name.upper() == "EXIT" or soc.upper() == "EXIT" or
mile.upper() == "EXIT"):
print("Exit detected... quitting\n")
break
names.append(name)
socs.append(soc)
miles.append(mile)
print(names, socs, miles)
except:
print("\nError: Invalid input, retry\n")
# ALIGNMENT
a, b, c = 0, 0, 0
for y in names:
commaPlace = str(y).find(",")
if commaPlace > b:
b = commaPlace
# Max Len after Comma
if (len(y) - commaPlace) > c:
c = len(y) - commaPlace
for x in miles:
decimalPlace = str(x).find(".")
if decimalPlace > a:
a = decimalPlace
if decimalPlace == -1:
if len(x) > a:
a = len(x)
for x in range(len(names)):
# Sort Commas
commaPlace = str(names[x]).find(",")
if commaPlace == -1:
spaces = b - len(name[x])
else:
spaces = b - commaPlace
# Sort Decimals
decimalPlace = str(miles[x]).find(".")
if decimalPlace == -1:
spaces2 = a - len(miles[x])
else:
spaces2 = a - decimalPlace
# Gap
firstLen = len(names[x]) - commaPlace
gap = c - firstLen + 1
# Print with Spacing
print(spaces*" " + names[x] + gap*" " + socs[x] + " " + spaces2*" " + miles[x])
print("\n" + "="*40)
|
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets,linear_model
from sklearn.metrics import mean_squared_error
# load the data of diabetes from datasets
diabetes = datasets.load_diabetes()
# load the data of index 2 of diabetes to diabetes_X
diabetes_X = diabetes.data[:,np.newaxis,2]
# print(diabetes)
# print(diabetes.keys())
# print(diabetes_X)
# collect the last 30 data as training data from diabetes_X
diabetes_X_train = diabetes_X[:-30]
# collect the first 30 data as testing data from diabetes_X
diabetes_X_test = diabetes_X[-30:]
# datasets of required or actual output
diabetes_Y_train = diabetes.target[:-30]
diabetes_Y_test = diabetes.target[-30:]
# create the model for linear regression
model = linear_model.LinearRegression()
# put the values in model by fit() method
model.fit(diabetes_X_train, diabetes_Y_train)
# check the predicted values that come from the regression by using the values of diabetes_X_test
diabetes_Y_predicted = model.predict(diabetes_X_test)
# printing mean squared error
print("Mean squared error is", mean_squared_error(diabetes_Y_test, diabetes_Y_predicted))
# printing weights and intercept
print("weights are:", model.coef_)
print("intercept:", model.intercept_)
# Scatter plots are used to plot data points on horizontal and vertical axis in the attempt
# to show how much one variable is affected by another.
plt.scatter(diabetes_X_test, diabetes_Y_test)
plt.plot(diabetes_X_test, diabetes_Y_predicted)
plt.show()
|
import turtle
def draw_triangle():
window=turtle.Screen();
window.bgcolor("red");
brad =turtle.Turtle();
for i in range(1,3):
brad.forward(100);
brad.right(60)
brad.right(90)
brad.forward(170)
sid=turtle.Turtle();
sid.shape("turtle");
sid.color('yellow');
sid.circle(100);
window.exitonclick();
draw_triangle();
|
import math
li = {}
def factorial(n):
if(n==0):
return 1
else:
fact = n*factorial(n-1)
li=fact
return fact
print(factorial(900))
print(li[3])
|
class Point:
"""
表示一个点
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if self.x == other.x and self.y == other.y:
return True
return False
def __str__(self):
return "x:" + str(self.x) + ",y:" + str(self.y)
class AStar:
"""
AStar算法的Python3.x实现
"""
class Node: # 描述AStar算法中的节点数据
def __init__(self, point, endPoint, g=0):
self.point = point # 自己的坐标
self.father = None # 父节点
self.g = g # g值,g值在用到的时候会重新算
self.h = (abs(endPoint.x - point.x) + abs(endPoint.y - point.y)) * 10 # 计算h值
def __init__(self, map2d, startPoint, endPoint, passTag=0):
"""
构造AStar算法的启动条件
:param map2d: Array2D类型的寻路数组
:param startPoint: Point或二元组类型的寻路起点
:param endPoint: Point或二元组类型的寻路终点
:param passTag: int类型的可行走标记(若地图数据!=passTag即为障碍)
"""
# 开启表
self.openList = []
# 关闭表
self.closeList = []
# 寻路地图
self.map2d = map2d
# 起点终点
if isinstance(startPoint, Point) and isinstance(endPoint, Point):
self.startPoint = startPoint
self.endPoint = endPoint
else:
self.startPoint = Point(*startPoint)
self.endPoint = Point(*endPoint)
# 可行走标记
self.passTag = passTag
def getMinNode(self):
"""
获得openlist中F值最小的节点
:return: Node
"""
currentNode = self.openList[0]
for node in self.openList:
if node.g + node.h < currentNode.g + currentNode.h:
currentNode = node
return currentNode
def pointInCloseList(self, point):
for node in self.closeList:
if node.point == point:
return True
return False
def pointInOpenList(self, point):
for node in self.openList:
if node.point == point:
return node
return None
def endPointInCloseList(self):
for node in self.openList:
if node.point == self.endPoint:
return node
return None
def searchNear(self, minF, offsetX, offsetY):
"""
搜索节点周围的点
:param minF:F值最小的节点
:param offsetX:坐标偏移量
:param offsetY:
:return:
"""
# 越界检测
if minF.point.x + offsetX < 0 or minF.point.x + offsetX > self.map2d.w - 1 or minF.point.y + offsetY < 0 or minF.point.y + offsetY > self.map2d.h - 1:
return
# 如果是障碍,就忽略
if self.map2d[minF.point.x + offsetX][minF.point.y + offsetY] != self.passTag:
return
# 如果在关闭表中,就忽略
currentPoint = Point(minF.point.x + offsetX, minF.point.y + offsetY)
if self.pointInCloseList(currentPoint):
return
# 设置单位花费
if offsetX == 0 or offsetY == 0:
step = 10
else:
step = 14
# 如果不再openList中,就把它加入openlist
currentNode = self.pointInOpenList(currentPoint)
if not currentNode:
currentNode = AStar.Node(currentPoint, self.endPoint, g=minF.g + step)
currentNode.father = minF
self.openList.append(currentNode)
return
# 如果在openList中,判断minF到当前点的G是否更小
if minF.g + step < currentNode.g: # 如果更小,就重新计算g值,并且改变father
currentNode.g = minF.g + step
currentNode.father = minF
def start(self):
"""
开始寻路
:return: None或Point列表(路径)
"""
# 判断寻路终点是否是障碍
if self.map2d[self.endPoint.x][self.endPoint.y] != self.passTag:
return None
# 1.将起点放入开启列表
startNode = AStar.Node(self.startPoint, self.endPoint)
self.openList.append(startNode)
# 2.主循环逻辑
while True:
# 找到F值最小的点
minF = self.getMinNode()
# 把这个点加入closeList中,并且在openList中删除它
self.closeList.append(minF)
self.openList.remove(minF)
# 判断这个节点的上下左右节点
self.searchNear(minF, 0, -1)
self.searchNear(minF, 0, 1)
self.searchNear(minF, -1, 0)
self.searchNear(minF, 1, 0)
# 判断是否终止
point = self.endPointInCloseList()
if point: # 如果终点在关闭表中,就返回结果
# print("关闭表中")
cPoint = point
pathList = []
while True:
if cPoint.father:
pathList.append(cPoint.point)
cPoint = cPoint.father
else:
# print(pathList)
# print(list(reversed(pathList)))
# print(pathList.reverse())
return list(reversed(pathList))
if len(self.openList) == 0:
return None
|
# Author: Andrew Davidson
# Date: 04/10/2019
#
# This application tracks baseball players batting average using parallel lists.
# The user can enter 12 player names, which are then populated into a list.
# The user can switch between name entry, stat entry, and summary display during runtime. name entry allows
# the user to enter 12 player names. Stat entry allows the user to enter player number, at bats, and hits.
# Display summary will display the player names, at bats, hits, and average.
import os
clear = lambda : os.system('cls')
listNames = list()
listBats = list()
listHits = list()
def main():
init()
menu()
def init():
#initializes 12 default slots in the parallel lists
for x in range(12):
listNames.append("")
listBats.append(0)
listHits.append(0)
def menu():
#Calls function based on option selected
optionSelect = 0
clear()
print("Please select an option")
optionSelect = optionInputAndValidation()
if optionSelect == 1:
optionEnterNames()
elif optionSelect == 2:
optionEnterStats()
elif optionSelect == 3:
optionDisplaySummary()
else:
clear()
print("Program ending...")
def optionInputAndValidation():
#Prompts user to enter 1-4. Loops until valid option is entered.
option = 0
errSw = True
while errSw:
print("1 - Enter Player Names")
print("2 - Enter Player Stats")
print("3 - Display Summary")
print("4 - Exit Program")
try:
option = int(input())
if option < 1 or option > 4:
print("\nInvalid option. Please select 1-4")
else:
errSw = False
except:
print("\nInvalid option. Please select 1-4")
return option
def optionEnterNames():
#Prompts user to enter in 12 player names. Validates to make sure name is not empty. Places names into listNames
#returns to main menu once completed
clear()
for x in range(12):
print("Enter a name for player #", x + 1)
playerName = str(input())
while not playerName:
print("\nInvalid player name. Player name cannot be empty.")
print("Enter a name for player #", x + 1)
playerName = str(input())
listNames[x] = playerName
print("\n\nPlayer names entered sucessfully.")
print("Press enter to return to main menu...")
input()
menu()
def optionEnterStats():
#Calls functions to prompt for data entry. Validates that hits do not exceed bats.
#Loops while user wants to enter more data.
errSw = True
playerNum = 0
bats = 0
hits = 0
again = "y"
while again == "y" or again == "Y":
clear()
errSw = True
while errSw:
playerNum = playerNumInputAndValidation()
bats = batsInputAndValidation()
hits = hitsInputAndValidation()
if hits > bats:
print("\nError! Hits can't be greater than At Bats. Please re-enter data.")
else:
errSw = False
#Places data entered into appropriate places on lists based on player number
listHits[playerNum - 1] += hits
listBats[playerNum - 1] += bats
#Asks user if they want to enter more data
print("Data submitted! Would you like to enter more data? (Y/N)");
again = input()
menu()
def playerNumInputAndValidation():
p = 0
errSw = True
#Prompts user to enter player number (1-12). Loops until valid.
while errSw:
try:
p = int(input("Enter Player Number (1-12):\n"))
if p < 1 or p > 12:
print("\nInvalid Player Number. Please enter 1-12.")
else:
errSw = False
except:
print("\nInvalid Player Number. Please enter 1-12.")
return p
def batsInputAndValidation():
b = 0
errSw = True
#Prompts the user to enter "at bats" for their entered player. Loops until valid.
while errSw:
try:
b = int(input("Enter number of At Bats:\n"))
if b < 0:
print("\nInvalid At Bats. Please enter a whole number.")
else:
errSw = False
except:
print("\nInvalid At Bats. Please enter a whole number.")
return b
def hitsInputAndValidation():
h = 0
errSw = True
#Prompts the user to enter hits for their entered player. Loops until valid.
while errSw:
try:
h = int(input("Enter number of Hits:\n"))
if h < 0:
print("\nInvalid Hits. Please enter a whole number.")
else:
errSw = False
except:
print("\nInvalid Hits. Please enter a whole number.")
return h
def optionDisplaySummary():
avg = 0.0
clear()
#Header
print("-------------------------------------------")
print("{0:16s} | {1:7s} | {2:4s} | {3:7s}".format("Player Name", "At Bats", "Hits", "Average"))
print("-------------------------------------------")
#Calls method to calculate average (passing x), and then formats / prints summary report.
for x in range(12):
avg = calcAvg(x)
print("{0:16s} | {1:7d} | {2:4d} | {3:7.3f}".format(listNames[x], listBats[x], listHits[x], avg))
print("\nPress Enter to return to main menu...");
input()
menu();
def calcAvg(x):
#Calculates batting average for player. If hits are 0, then returns 0 to avoid division by 0.
if listHits[x] == 0:
return 0
else:
return 1.0 * listHits[x] / listBats[x]
main()
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def bi_dist(x, n, p):
b = (math.factorial(n)/(math.factorial(x)*math.factorial(n-x)))*(p**x)*((1-p)**(n-x))
return(b)
b1,b2, p, n = 0, 0, 12/100, 10
for i in range(3):
b1 += bi_dist(i, n, p)
for i in range(2,n+1):
b2 += bi_dist(i, n, p)
print("{:.3f}".format(b1))
print("{:.3f}".format(b2))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
mean_of_A = 0.88
mean_of_B = 1.55
result_of_A = 160 + 40 * (mean_of_A + mean_of_A**2)
result_of_B = 128 + 40 * (mean_of_B + mean_of_B**2)
print("{:.3f}".format(result_of_A))
print("{:.3f}".format(result_of_B))
|
print("Calculadora de fuerza de atraccion")
print('Inserta el valor sin el 10 de la primera masa')
MassOne = float(input())
print('Inserta el valor sin el 10 de la segunda masa')
MassTwo = float(input())
print('Inserta el exponente de la primera masa')
MassOne_Exponent = int(input())
print('Inserta el exponente de la segunda masa')
MassTwo_Exponent = int(input())
print('Inserta la distancia')
Distance = float(input())
print("Inserta el exponente de la distancia")
Distance_Exponent = int(input())
print("Calculando..")
AttractionForce = MassOne * MassTwo / (Distance * Distance) * 6.7
Distance_Exponent1 = Distance_Exponent * 2
AttractionForce_Exponent = MassOne_Exponent + MassTwo_Exponent - Distance_Exponent1 -11
print('Calculation job done')
print('Tu cantidad es:')
print(AttractionForce)
print("x10 a la")
print(AttractionForce_Exponent)
|
#!usr/bin/env python3
import re
from re import match, split
class genbank_parser:
''' Use this class to parse the genbank file.
Parsing the genbank file follows the order of:
1) Accession - 6-8 character string containing the
accession code
2) Features - strings which represent the gene,
amino acid sequence, chromosome location and protein
name.
3) Origin - string of letters which refer to the DNA
sequence.
'''
def __init__(self, filename):
''' Creates a new file parser
Parameters:
filename (str):
name of the file pointing to the file to be parsed
Returns:
file object
'''
self.openfile = open(filename, 'r')
def find_keyword(self, keyword):
''' Places file pointer towards the header of interest
given the order of headers is the same throughout the file.
Parameters:
keyword - string that a line should start with
to be considered a header.
Returns:
line - return the read sting stripped of trailing
whitespace.
'''
line = ''
while not line.startswith(keyword):
line = self.openfile.readline().strip()
line = line[len(keyword):].strip()
return line
def check_eof(self):
''' Identifies when the end of file has been reached
Return:
boolean: true if the next line read after '//' is 'eof,
false if next line read does not start with 'eof'.
'''
line = self.openfile.readline().strip()
if line.startswith ('//'):
line = self.openfile.readline().strip()
if line.startswith('eof'):
return True
else:
return False
def parse_accession(self):
''' Parses the accession code presented by the header "ACCESSION"
Returns
accession (string): returns the first accession code in the string
'''
accession = ''
line = self.find_keyword('ACCESSION')
if len(line) > 8:
line = split('\\s+', line)
accession = line[0]
else:
accession = line
return accession
def parse_features(self):
''' Parses features described in the docstring of this class presented by the headers
"FEATURES" and "CDS".
Return:
features (list): list containing the gene ID, protein product,
protein sequence, coding sequence, and chromosome
location.
'''
line = self.find_keyword('FEATURES')
while not line.startswith('/'):
line = self.openfile.readline().strip()
chrom = self.parse_attributes(line)
line = self.find_keyword('CDS')
location = line.strip()
line = self.openfile.readline().strip()
while not line.startswith('/'):
location += line
line = self.openfile.readline().strip()
location = self.parse_location(location)
features = self.parse_attributes(line)
features.append(location)
features.extend(chrom)
return features
def parse_attributes(self, line):
''' Parses values of features described in the docstring
of this class.
Return:
dictlist (list): list of strings containing the gene ID,
protein product, protein sequence, coding sequence, and
chromosome location.
'''
attributes = {}
dictlist = []
while line.startswith('/'):
if match('^/gene|^/prod|^/trans|^/map', line):
key = ''
for char in line:
if char == '=':
break
key += char
value = line[len(key) + 1:]
if value[0:1] == '"':
remaining = value[1:]
while remaining[-1] != '"':
remaining += self.openfile.readline().strip()
value = remaining[:-1]
attributes[key] = value
line = self.openfile.readline().strip()
else:
line = self.openfile.readline().strip()
for key, value in dict.items(attributes):
dictlist.append(value.strip('"'))
return dictlist
def parse_origin(self):
''' Parses ORIGIN described in the docstring of this class.
Return:
sequence (string): string containing DNA sequence.
'''
sequence = ''
line = self.find_keyword('ORIGIN')
line = self.openfile.readline().strip()
while match('^\d+.*', line):
seq = split('\s+', line)
del seq[0]
sequence += ''.join(seq).upper()
last_position = self.openfile.tell()
line = self.openfile.readline().strip()
self.openfile.seek(last_position)
return sequence
def parse_location(self, location_string):
''' Formats location strings in the format:
'x..y'
Return:
location_string (string): string representing the location of
the coding sequence for a gene within the DNA sequence.
'''
terms = match('\w*', location_string)
terms = terms.group(0)
location_string = location_string.strip(terms)
for char in location_string:
if char == '(':
location_string = location_string.strip(char)
elif char == ')':
location_string = location_string.strip(char)
elif char == '<':
location_string = location_string.strip(char)
elif char == '>':
location_string = location_string.strip(char)
return location_string
def close(self):
''' Closes the file object '''
self.openfile.close()
|
#
# @lc app=leetcode id=199 lang=python3
#
# [199] Binary Tree Right Side View
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
# edge cases
if root is None:
return []
def helper(root, arr):
if root is None:
return []
# create recursive calls
right = helper(root.right, arr) # [x, x, ...]
left = helper(root.left, arr) # [x, x ...]
# process data
# do array replacement
if len(left) == 0:
arr = right
elif len(right) == 0:
arr = left
elif len(left) > len(right):
# replace all left elements not deeper than right
print(left, right)
for i in range(len(right)):
left[i] = right[i]
arr = left
else: # just return len(left) < len(left)
arr = right
# add new data
arr = [root.val] + arr
# return arr for root
return arr
result = helper(root, [])
return result
# @lc code=end
|
#
# @lc app=leetcode id=146 lang=python3
#
# [146] LRU Cache
#
from collections import OrderedDict
# https://leetcode.com/problems/lru-cache/discuss/45926/Python-Dict-+-Double-LinkedList/45368
# @lc code=start
class LRUCache:
def __init__(self, capacity: int):
self.vals = {} # { key: (val, Node) }
self.lru = None # Node
self.mru = None # Node
def get(self, key: int) -> int:
# go to vals[key][1]:
# 1) reassign prev and next to each other
# 2) assign mru.next = vals[key][0]
# return vals[key][0]
def put(self, key: int, value: int) -> None:
# get lru node: 1) pop from vals, 2) remove from array + reassign
# add new node: 1) add to vals, 2) add as mru node + reassign pointers
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
# @lc code=end
|
#
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
# @lc code=start
class Solution:
def longestPalindrome(self, s: str) -> str:
def findPalindromeFromPivot(left, right, s):
if (s == None):
return 0
if left > right:
return 0
while(left >= 0 and right < len(s) and s[left] == s[right]):
left -= 1
right += 1
return right-left-1 # length of string
curr_max = 0
pivot1 = 0
pivot2 = 0
case1, case2 = 0, 0
for i in range(0, len(s)):
# if midpoint % 1 == 0: #even case
case1 = findPalindromeFromPivot(i, i, s)
# else: # odd case
case2 = findPalindromeFromPivot(i, i+1, s)
# pick new case if its better
if case1 > curr_max:
curr_max = case1
pivot1 = i
pivot2 = i
if case2 > curr_max:
curr_max = case2
pivot1 = i
pivot2 = i+1
lnmax = findPalindromeFromPivot(pivot1, pivot2, s)
print(lnmax, pivot1, pivot2)
if pivot1 != pivot2: # even case
lnmax = lnmax - 2 # remove the two indexes core
expansion = lnmax // 2 # guarenteed whole number
for i in range(expansion):
pivot1 -= 1
pivot2 += 1
print(pivot1, pivot2)
elif pivot1 == pivot2: # odd case
lnmax = lnmax - 1 # remove the one index core
expansion = lnmax // 2 # guarenteed whole number
for i in range(expansion):
pivot1 -= 1
pivot2 += 1
print(pivot1, pivot2)
return s[pivot1:pivot2+1]
# @lc code=end
|
#
# @lc app=leetcode id=19 lang=python3
#
# [19] Remove Nth Node From End of List
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if head == None:
return []
end = []
tmp = head
while (tmp != None):
# print(tmp.val)
end.append(tmp)
if len(end) > (n + 1):
end.pop(0) # pop the oldest element
tmp = tmp.next
# print(end)
# print('...')
# edge: if total # less than n
if len(end) < n:
return head
# print("len: ", len(end))
if len(end) >= 3: # n = 3
prev = end.pop(0)
pivot = end.pop(0)
# print(n, len(end))
if n == len(end) + 2: # after removing prev and pivot
head = pivot
return head
# print("prev: ", prev.val)
# print("pivot: ", pivot.val)
prev.next = pivot.next
pivot.next.prev = prev
elif len(end) == 2: # n = 1
prev = end.pop(0)
if n == 1:
prev.next = None
if n == 2:
head = prev.next
elif len(end) == 1:
return None
return head
# @lc code=end
|
#
# @lc app=leetcode id=141 lang=python3
#
# [141] Linked List Cycle
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
# situations: 1) duplicate values, 1) has cycle, 2) doesn't have cycle, 3) one element or zero elements
nodes = set()
# for each node, add to hashmap, until == .next = null meaning found an end
while (head is not None):
print(head)
if head in nodes:
return True
else:
nodes.add(head)
head = head.next
return False
# @lc code=end
|
#
# @lc app=leetcode id=101 lang=python3
#
# [101] Symmetric Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def isMirror(t1: TreeNode, t2: TreeNode):
# no nodes
if (t1 == None) and (t2 == None):
return True # both are None
if (t1 == None) or (t2 == None):
return False # one is not None, one is None
# if there are two not None values
if (t1.val == t2.val):
return isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left)
return False
return isMirror(root, root)
# @lc code=end
|
#
# @lc app=leetcode id=142 lang=python3
#
# [142] Linked List Cycle II
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
'''
Accepted
16/16 cases passed (52 ms)
Your runtime beats 50.93 % of python3 submissions
Your memory usage beats 7.78 % of python3 submissions (17.8 MB)
'''
nodes = set()
while head is not None:
if head in nodes:
return head
nodes.add(head)
head = head.next
return None
# @lc code=end
|
#
# @lc app=leetcode id=34 lang=python3
#
# [34] Find First and Last Position of Element in Sorted Array
#
# @lc code=start
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
# brute force o(n)
'''
start = -1
end = -1
ind = 0
for elem in nums:
if elem == target:
if start == -1:
start = ind
else:
end = ind
ind += 1
if start != -1 and end == -1:
end = start # only one occurance
return (start, end)
'''
def binarySearchHelper(elem, arr, start, end):
if start > end:
return -1
mid = (start + end)//2
if arr[mid] == elem:
return mid
elif arr[mid] > elem:
# recurse to the left of mid
return binarySearchHelper(elem, arr, start, mid - 1)
else:
# recurse to the right of mid
return binarySearchHelper(elem, arr, mid + 1, end)
mdpt = len(nums) // 2
print("search ", nums, mdpt)
ind = binarySearchHelper(target, nums, 0, len(nums) - 1)
print(ind)
right = ind
if ind is not None:
while ind > 0 and nums[ind - 1] == target:
print(nums[ind])
ind -= 1
while right < len(nums) - 1 and nums[right + 1] == target:
print(nums[ind])
right += 1
return (ind, right)
# if ind is not found
return (-1, -1)
# @lc code=end
|
#
# @lc app=leetcode id=112 lang=python3
#
# [112] Path Sum
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
# edge case
if root is None:
return False
def f(root):
if root.left is None and root.right is None: # leaf
return [root.val]
# create joint left and right array
left, right = [], []
if root.left:
left = f(root.left)
if root.right:
right = f(root.right)
net = left + right
# add root.val to all values
net = [elem + root.val for elem in net]
return net
result = f(root)
if targetSum in result:
return True
return False
# @lc code=end
|
# Name:
# Date:
"""
proj04
Asks the user for a string and prints out whether or not the string is a palindrome.
"""
# raw_input ("lets play a game of hangman, press RETURN to start")
#
# raw_input ("guess a letter for the word")
raw_input ("press RETURN to see if the word is a palindrome")
str = "racecar"
lst = []
for letter in str:
lst.append(letter)
print lst
str = "racecar"
lst2 = []
for letter in str:
lst.reverse()
print lst
|
listamulheres = []
#Definido uma classe mãe
class mae:
def __init__(self,nome,idade,estadocivil,quantfilhos):
self.nome = nome
self.idade=idade
self.estadocivil = estadocivil
self.quantfilhos = quantfilhos
def cuidarfilhos(self):
return '{} Cuidando do filho'.format(self.nome)
def filhopracreche(self):
return '{} Mandou o filho pra creche'.format(self.nome)
def fazercomida(self):
return '{} Fazendo comida'.format(self.nome)
class Mulheres(mae):
def __init__(self, nome, idade, estadocivil, quantfilhos):
super().__init__(nome, idade, estadocivil, quantfilhos)
def emcadastro():
NovoCadastro='Sim'
ConfirNovoCadastro = input('Fazer Novo Cadastro ? ')
if ConfirNovoCadastro == NovoCadastro:
mulher01=Mulheres
mulher01=[input('nome'),input('Idade'),input("estado"),input('Filhos')]
print('Nome: ',mulher01.nome)
print('Idade: ',mulher01.idade)
print('Estad0 Civil: ',mulher01.estadocivil)
print('Quantidade Filhos ' ,mulher01.quantfilhos)
print(mulher01.filhopracreche())
print(mulher01.fazercomida())
print(mulher01.cuidarfilhos())
else:
op2 = input('Cancelar Cadastro')
if op2=='sim':
final()
else:
emcadastro()
def final():
pass
def main ():
emcadastro()
final()
if __name__ == "__main__":
main()
|
# Linguagem de Programação II
# Atividade Contínua 02 - Classes e Herança
#
# e-mail: [email protected]
"""
Implementar aqui as cinco classes filhas de Mamifero ou Reptil,
de acordo com o caso, conforme dado no diagrama apresentado no padrão UML.
Os atributos específicos de cada classe filha devem ser recebidos
como parâmetros no momento da criação, a única exceção é o número de vidas
do gato, que sempre começa em 7.
Os métodos de cada classe filha devem sempre RETORNAR uma string
no seguinte formato '<nome do animal> <método em questão no gerúndio>'
Sem nenhuma pontuação, conforme os exemplos a seguir.
Exemplo:
método trocar_pele() retorna '<nome> trocando de pele'
método dormir() retorna '<nome> dormindo'
método miar() retorna '<nome> miando'
Onde <nome> é o nome dado para cada animal (o valor atributo nome de
cada instância, não o nome da classe)
"""
class Reptil:
"""
Classe mãe - não deve ser editada
"""
def __init__(self, nome, cor, idade):
self.nome = nome
self.cor = cor
self.idade = idade
def tomar_sol(self):
return '{} tomando sol'.format(self.nome)
def botar_ovo(self):
if self.idade > 2:
return '{} botou um ovo'.format(self.nome)
else:
return '{} ainda não atingiu maturidade sexual'.format(self.nome)
class Mamifero:
"""
Classe mãe - não deve ser editada
"""
def __init__(self, nome, cor_pelo, idade, tipo_pata):
self.nome = nome
self.cor_pelo = cor_pelo
self.idade = idade
self.tipo_pata = tipo_pata
def correr(self):
return '{} correndo'.format(self.nome)
def mamar(self):
if self.idade <= 1:
return '{} mamando'.format(self.nome)
else:
return '{} já desmamou'.format(self.nome)
class Camaleao(Reptil):
"""
Exemplo de solução do exercício:
Além dos atributos da classe mãe, possui o atributo:
inseto_favorito, do tipo string.
Implementa os métodos específicos:
mudar_de_cor() e comer_inseto()
"""
def __init__(self, nome, cor, idade, inseto_favorito):
super().__init__(nome, cor, idade)
self.inseto_favorito = inseto_favorito
def mudar_de_cor(self):
return '{} mudando de cor'.format(self.nome)
def comer_inseto(self):
return '{} comendo inseto'.format(self.nome)
class Cavalo(Mamifero):
"""
Além dos atributos da classe mãe, possui o atributo:
cor_crina, do tipo string.
"""
"""
Implementa os métodos específicos:
galopar() e relinchar()
"""
def __init__(self, nome, cor_pelo, idade, tipo_pata,cor_crina):
super().__init__(nome, cor_pelo, idade, tipo_pata)
self.cor_crina = cor_crina
def galopar(self):
return '{} Galopar'.format(self.nome)
def relinchar(self):
return '{} relinchar'.format(self.nome)
class Cobra(Reptil):
"""
Além dos atributos da classe mãe, possui o atributo:
veneno, do tipo booleano.
Implementa os métodos específicos:
rastejar() e trocar_pele()
"""
def __init__(self, nome, cor, idade,veneno):
super().__init__(nome, cor, idade)
self.veneno = veneno
def rastejar(self):
return '{} Rastejando'.format(self.nome)
def trocar_pele (self):
return '{} trocar de pele'.format(self.nome)
class Cachorro(Mamifero):
"""
Além dos atributos da classe mãe, possui o atributo:
raca, do tipo string. (raça, porém sem o ç)
Implementa os métodos específicos:
latir() e rosnar()
"""
def __init__(self, nome, cor_pelo, idade, tipo_pata,raca):
super().__init__(nome, cor_pelo, idade, tipo_pata)
self.raca = raca
def latir(self):
return '{} Latindo'.format(self.nome)
def rosnar (self):
return '{} Rosnando'.format(self.nome)
class Jacare(Reptil):
"""
Além dos atributos da classe mãe, possui o atributo:
num_dentes, do tipo inteiro.
Implementa os métodos específicos:
atacar() e dormir()
"""
def __init__(self, nome, cor, idade, num_dentes):
super().__init__(nome, cor, idade)
self.num_dentes = num_dentes
def atacar(self):
return '{} Atacando'.format(self.nome)
def dormir (self):
return '{} Dormindo'.format(self.nome)
class Gato(Mamifero):
"""
Além dos atributos da classe mãe, possui o atributo:
vidas, do tipo inteiro.
Implementa os métodos específicos:
miar() e morrer()
No método morrer, você deve verificar quantas vidas o gato ainda
tem sobrando, se for igual a zero, retornar:
'<nome> morreu'
se ainda houver vidas sobrando, retirar uma vida (que começa em 7),
e retornar:
'<nome> tem <vidas> vidas sobrando'
Onde <vidas> é o número de vidas restantes do gato em questão.
"""
def __init__(self, nome, cor_pelo, idade, tipo_pata):
super().__init__(nome, cor_pelo, idade, tipo_pata)
self.vidas = 7
def miar(self):
return '{} miando'.format(self.nome)
def morrer(self):
if self.vidas <= 0:
return '{} morreu'.format(self.nome)
else:
self.vidas = self.vidas -1
return '{} tem {} vidas'.format(self.nome, self.vidas)
def main ():
cachorro = Cachorro("toto", "Preto", 2, "Quadrupede", "SRD")
print(cachorro.nome)
print(cachorro.cor_pelo)
print(cachorro.idade)
print(cachorro.tipo_pata)
print(cachorro.raca)
print(cachorro.latir())
print(cachorro.rosnar())
print(cachorro.correr())
print(cachorro.mamar())
print("______________________________________")
cavalo = Cavalo("Pangaré", "Branco", 10, "Quadrupede", "Bicolor")
print(cavalo.nome)
print(cavalo.cor_pelo)
print(cavalo.idade)
print(cavalo.tipo_pata)
print(cavalo.cor_crina)
print(cavalo.galopar())
print(cavalo.relinchar())
print(cavalo.correr())
print(cavalo.mamar())
print("______________________________________")
gato = Gato("kiko", "cinza", 3, "Quadrupede")
print(gato.nome)
print(gato.cor_pelo)
print(gato.idade)
print(gato.tipo_pata)
print(gato.miar())
print(gato.morrer())
print(gato.correr())
print(gato.mamar())
print("______________________________________")
camaleao = Camaleao("jorge", "verde", 2, "cupim")
print(camaleao.nome)
print(camaleao.cor)
print(camaleao.idade)
print(camaleao.inseto_favorito)
print(camaleao.tomar_sol())
print(camaleao.botar_ovo())
print(camaleao.comer_inseto())
print(camaleao.mudar_de_cor())
print("______________________________________")
cobra = Cobra("Gibóia", "Verde e Preta", 5, True)
print(cobra.nome)
print(cobra.cor)
print(cobra.idade)
print(cobra.veneno)
print(cobra.tomar_sol())
print(cobra.trocar_pele())
print(cobra.rastejar())
print(cobra.botar_ovo())
print("______________________________________")
jacare = Jacare("olga", "Verde", 10, 50)
print(jacare.nome)
print(jacare.cor)
print(jacare.idade)
print(jacare.num_dentes)
print(jacare.tomar_sol())
print(jacare.botar_ovo())
print(jacare.atacar())
print(jacare.dormir())
if __name__ == "__main__":
main()
|
def recursive_dfs(a):
if a not in visited:
visited.append(a)
for i in graph[a]:
if i not in visited:
recursive_dfs(i)
return visited
visited = []
graph = {'A': set(['B', 'C', 'E']),
'B': set(['A', 'D', 'F']),
'C': set(['A', 'G']),
'D': set(['B']),
'E': set(['A', 'F']),
'F': set(['B']),
'G': set(['G'])}
root = 'B'
print(recursive_dfs(root))
|
#### - 미로1
>일종의 그래프이므로 탐색을 위해 ***DFS 이용***. 0 or 1이므로 결정 문제
```python
'''
16 x 16
'''
def maze(y, x):
global flag
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
# data[y][x] = 9 #방문표시 ## 사실 한 번만 지나가면 되므로 data 자체에 표시해도 된다.
visit[y][x] = 1
for i in range(4):
ny = y + dy[i]
nx = x + dx[i]
if ny < 0 or ny == N: continue
if nx < 0 or nx == N: continue
# if data[ny][nx] == 9 : continue
if visit[ny][nx] == 1: continue
if data[ny][nx] == 1 : continue
if data[ny][nx] == 3:
flag = 1
return
## return 하면 바로 이전 dfs(ny, nx)로 돌아간다. return 하지 않아도 사실 상관없음
## ★ 여기서 끝나는 게 아니라는 것★에 주의하자.
## 즉, 첫 시작까지 돌아가고 끝난다.
maze(ny, nx)
def findStart(data):
for y in range(N):
for x in range(N):
if data[y][x] == 2:
return y, x
## return 값은 1개 뿐이므로 실제로는 튜플 형식으로 리턴 된다는 것을 기억하자.
import sys
sys.stdin = open("(1226)미로1_input.txt", 'r')
T = 10
N = 16
for tc in range(T):
flag = 0
no = int(input())
data = [list(map(int, input())) for _ in range(N)] # 미로를 중첩리스트로 저장
# data = [0 for _ in range(N)]
# for i in range(N):
# data[i] = list(map(int, input()))
visit = [[0 for _ in range(N)]for _ in range(N)]
sy, sx = findStart(data)
maze(sy, sx)
print("#{} {}".format(tc+1, flag))
|
array = [1, 5, 2, 6, 3, 7, 4]
commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
def solution(array, commands):
answer = []
for command in commands:
i, j, k = command
answer.append(sorted(array[i-1:j]))
return answer
print(solution(array, commands))
# def solution(array, commands):
# ans = []
# for i in range(len(commands)):
# criteria = []
# for j in range(len(commands[i])):
# criteria.append(commands[i][j])
# arr = array[criteria[0]-1:criteria[1]]
# sorted_arr = sorted(arr)
# ans.append(sorted_arr[criteria[2]-1])
# return ans
|
#!/usr/bin/env python
# coding=utf-8
"""
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
Note:
The order of output does not matter.
The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
"""
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
if not num:
return ["0:00"]
res = []
self.bc(res, list(), 0, num)
print res
return self.transform(res)
def bc(self, res, tmp, start, num):
if len(tmp) == num:
import copy
res.append(copy.copy(tmp))
return
if start == 10:
return
for i in range(start, 10):
tmp.append(i)
self.bc(res, tmp, i + 1, num)
tmp.pop(-1)
def transform(self, res):
if not res:
return []
ret = []
for l in res:
h = 0
m = 0
for t in l:
if 0 <= t <= 3:
h += pow(2, t)
else:
m += pow(2, t - 4)
if h > 11 or m > 59:
continue
else:
h_s = str(h)
m_s = str(m)
m_s = m_s if len(m_s) == 2 else "0" + m_s
ret.append(h_s + ":" + m_s)
return ret
|
#!/usr/bin/env python3
# Create a timer
import time
run = input("Start? >")
seconds = 0
if run == "yes":
while seconds !=6:
print(">",seconds)
time.sleep(1) # tempo de espera
seconds+=1
print('Finish')
|
# coding=UTF-8
def computeResult(x, y, op):
result = ""
if op == "+":
result = x + y
elif op == "-":
result = x - y
elif op == "*":
result = x * y
elif op == "/":
result = x / y
elif op == "%":
result = x % y
elif op == "**":
result = x ** y
elif op == "//":
result = x // y
elif op == "==":
result = x == y
elif op == "!=":
result = x != y
elif op == "<>":
result = x <> y
elif op == ">":
result = x > y
elif op == "<":
result = x < y
elif op == ">=":
result = x >= y
elif op == "<=":
result = x <= y
elif op == "and":
result = x and y
elif op == "or":
result = x or y
elif op == "not":
result = not x
elif op == "in":
result = x in y
elif op == "not in":
result = x not in y
else:
result = ""
print x, op, y, ": ", result
return
print "--------------------------算术运算符"
# 1.算术运算符
a, b = 22, 7
computeResult(a, b, "+")
computeResult(a, b, "-")
computeResult(a, b, "*")
computeResult(a, b, "/")
computeResult(a, b, "%")
computeResult(a, b, "**") # a的b次方
computeResult(a, b, "//") # 取整除 - 返回商的整数部分(向下取整)
print "--------------------------比较运算符"
# 2.比较运算符
computeResult(a, b, "==")
computeResult(a, b, "!=")
computeResult(a, b, "<>")
computeResult(a, b, ">")
computeResult(a, b, "<")
computeResult(a, b, ">=")
computeResult(a, b, "<=")
# 3.赋值运算符
# =, +=, -+, *=, /=, %=, **=, //=
print "--------------------------逻辑运算符"
# 4.逻辑运算符, 类似js, and or短路后会返回一个值 : a = a||0;
# and, or, not
computeResult(a, b, "and")
computeResult(a, b, "or")
computeResult(a, b, "not")
print "--------------------------成员运算符"
# 5.成员运算符
# in, not in 注意在字典中查找的是key并不是value
list = [1,22,7,"sss"]
tuple = (1,22,7,'sss')
dict = {"a": "AAA",'b': 22,}
dict2 = {"a": "AAA",22: "BBB",}
dict3 = {"a": "AAA","22": "BBB",}
computeResult(a, list, "in")
computeResult(a, list, "not in")
computeResult(a, tuple, "in")
computeResult(a, dict, "in")
computeResult(a, dict2, "in")
computeResult(a, dict3, "in")
# 6.身份运算符
# is, is not
# x is y 等价于:id(x) == id(y) 注:id()函数用于获取对象内存地址
# x is not y 等价于:id(x) != id(y)
|
import time
def fibonacci (previous, current):
if current == 0:
return 1
return previous + current
previous = 0
current = 0
for i in range(10):
previous, current = current, fibonacci(previous, current)
print (current)
time.sleep(0.5)
|
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
print("Hello! Let\'s explore some US cities bikeshare data!\n")
while True:
city = input("Would you like to visualize data for Chicago, New York City or Washington?\n").lower()
if city.lower() not in ('chicago', 'new york city', 'washington'):
#if city not in CITY_DATA.keys():
print("Sorry, {} is not a valid city. Please type again by entering either 'Chicago', 'New York City' OR 'Washington' again".format(city))
else:
break
# TO DO: get user input for month (all, january, february, ... , june)
while True:
month = input("which month would you like to analyze? | (e.g. for january, please input [1])\n")
if month.lower() not in ('1','2','3','4','5','6'):
print ("please enter the correct input. | (e.g. for january, please input [1])\n")
else:
break
#while True:
#month = input("Which month? January, February, March, April, June or all?\n").lower()
#months = ['january', 'february', 'march', 'april', 'may', 'june','all']
#if month not in months:
#print("Sorry, {} is not a valid month. Please type again by entering again".format(month))
#continue
#else:
#break
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day = input("which day of week shall we analyze?\n")
if day.lower() not in ('monday','tuesday','wednesday','thursday','friday','saturday','sunday'):
print ("please enter the correct input.\n")
else:
break
"""while True:
day = input("Which day? Please type a day M, T, W, Th, F, Sa, Su, A for All.\n")
days = {'M':'Monday','T':'Tuesday','W':'Wednesday','Th':'Thursday','F':'Friday','Sa':'Saturday','Su':'Sunday','A':'All'}
if day not in days.keys():
print("Sorry, {} is not a valid day. Please type a day using one of the following values: M, T, W, Th, F, Sa, Su, A for All.".format(day))
continue
else:
break
"""
print('-'*50)
return city, month, day
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
def load_data(city, month, day):
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month and day of week from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
# filter by month if applicable
if month !='all':
months = ['1', '2', '3', '4', '5', '6']
month = months.index(month) + 1
df = df[df['month'] == month]
# filter by day of week if applicable
if day !='all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
#TO DO: display the most common month
common_month = df['month'].mode()[0]
print("The most common month is", common_month)
# TO DO: display the most common day of week
common_day_of_week = df['day_of_week'].mode()[0]
print("{} is the most common day".format(common_day_of_week))
# TO DO: display the most common start hour
df["hour"] = df["Start Time"].dt.hour
common_start_hour = df["hour"].mode()[0]
print("{} is the most common hour".format(common_start_hour))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*50)
def station_stats(df):
#"""Displays statistics on the most popular stations and trip."""
print('Calculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
common_start = df['Start Station'].mode()[0]
print("{} is the most commonly used start station".format(common_start))
# TO DO: display most commonly used end station
common_end = df['End Station'].mode()[0]
print("{} is the most commonly used end station".format(common_end))
# TO DO: display most frequent combination of start station and end station trip
#most_common_start_end_station = df[['Start Station', 'End Station']].mode().loc[0]
#print("The most commonly used start station and end station : {}, {}".format(most_common_start_end_station[0],most_common_start_end_station[1]))
df['Trip'] = df['Start Station'] + "-" + df['End Station']
common_trip = df['Trip'].mode()
print("{} is most frequent combination of start station and end station trip".format(common_trip))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*50)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
total_duration = df['Trip Duration'].sum()
print("Total travel time:",total_duration)
# TO DO: display mean travel time
average_duration = df['Trip Duration'].mean()
print("Average travel time:",average_duration)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*50)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
user_types = df['User Type'].value_counts()
print("Counts of user types:",user_types)
# TO DO: Display counts of gender
if 'Gender' in df.columns:
gender_types = df['Gender'].value_counts()
print("Counts of gender:",gender_types)
else:
print('No gender data is found')
# TO DO: Display earliest, most recent, and most common year of birth
if 'Birth Year' in df.columns:
birth_year_earliest = df['Birth Year'].min()
birth_year_recent = df['Birth Year'].max()
birth_year_common = df['Birth Year'].mode()[0]
else:
print('No age data is found')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*50)
def display_data(df):
user_input = input('\nWould you like to see individual raw data?\nPlease enter yes or no\n').lower()
if user_input in ('yes', 'y'):
i = 0
while True:
print(df.iloc[i:i+5])
i += 5
more_data = input('Would you like to see more data? Please enter yes or no: ').lower()
if more_data not in ('yes', 'y'):
break
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
display_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
def selamla(isim ="isimsiz"):
print("merhaba", isim)
def topla(*vals):
topla = 0
for val in vals:
topla = topla + val
return topla
ciftMi = lambda say : ((say % 2) == 0)
|
class nuqta:
def __init__(self, x:int, y:int) -> None:
self.x = x
self.y = y
#bu metod nuqtadan (x, y) nuqtagacha bo'lgan masofani hisoblaydi
def gacha_masofa(self, x, y):
a=((self.x - x)**2+(self.y - y)**2)**(1/2)
return a
class planeta:
def __init__(self, x, y, r) -> None:
self.markaz = nuqta(x, y)
self.r = r
#bu metod nuqta planeta ichida yoki ichida emasligini qaytaradi
def ni_ichidami(self, nuqtacha:nuqta):
return self.markaz.gacha_masofa(nuqtacha.x, nuqtacha.y)<self.r
class shahzoda:
def __init__(self, x1, y1, x2, y2) -> None:
self.start = nuqta(x1, y1)
self.end = nuqta(x2, y2)
#bu metod shahzoda kesi o'tish o'tmasligini qaytaradi
def kesib_otadimi(self, nuqtacha:planeta):
if nuqtacha.ni_ichidami(self.start)==True and nuqtacha.ni_ichidami(self.end)==False:
a=True
elif nuqtacha.ni_ichidami(self.start)==False and nuqtacha.ni_ichidami(self.end)==True:
a=True
else:
a=False
return a
|
#library 추가
import time
import RPi.GPIO as GPIO
s2 = 23 # Raspberry Pi Pin 23
s3 = 24 # Raspberry Pi Pin 24
out = 25 # Raspberry Pi Pin 25
NUM_CYCLES = 10
def read_value(a2, a3):
GPIO.output(s2, a2)
GPIO.output(s3, a3)
# 센서를 조정할 시간을 준다
time.sleep(0.3)
# 전체주기 웨이팅
#GPIO.wait_for_edge(out, GPIO.FALLING)
#GPIO.wait_for_edge(out, GPIO.RISING)
start = time.time() # 현재 시각
for impulse_count in range(NUM_CYCLES):
GPIO.wait_for_edge(out, GPIO.FALLING)
end = (time.time() - start)
return NUM_CYCLES / end # 색상 결과 리턴
## GPIO 세팅
def setup():
#pass ## 함수 내용이 정해지지않은 경우
GPIO.setmode(GPIO.BCM)
GPIO.setup(s2, GPIO.OUT)
GPIO.setup(s3, GPIO.OUT)
GPIO.setup(out, GPIO.IN, pull_up_down=GPIO.PUD_UP) # 센서결과 받기
## 반복하면서 일처리
def loop():
result = ''
while True:
red = read_value(GPIO.LOW, GPIO.LOW) # s2 low, s3 low
time.sleep(0.1) # 0.1초 딜레이
green = read_value(GPIO.HIGH, GPIO.HIGH)# s2 high, s3 high
time.sleep(0.1)
blue = read_value(GPIO.LOW, GPIO.HIGH)
print('red = {0}, green = {1}, blue = {2}'.format(red, green, blue))
time.sleep(1)
## int main()
if __name__=='__main__':
setup()
try:
loop()
except KeyboardInterrupt:
GPIO.cleanup()
|
import argparse
import os
import pickle
import sys
from tictactoe.agent import Qlearner, SARSAlearner
from tictactoe.teacher import Teacher
from tictactoe.game import Game
class GameLearning(object):
"""
A class that holds the state of the learning process. Learning
agents are created/loaded here, and a count is kept of the
games that have been played.
"""
def __init__(self, args, alpha=0.5, gamma=0.9, epsilon=0.1):
if args.load:
# load an existing agent and continue training
if not os.path.isfile(args.path):
raise ValueError("Cannot load agent: file does not exist.")
with open(args.path, 'rb') as f:
agent = pickle.load(f)
else:
# check if agent state file already exists, and ask
# user whether to overwrite if so
if os.path.isfile(args.path):
print('An agent is already saved at {}.'.format(args.path))
while True:
response = input("Are you sure you want to overwrite? [y/n]: ")
if response.lower() in ['y', 'yes']:
break
elif response.lower() in ['n', 'no']:
print("OK. Quitting.")
sys.exit(0)
else:
print("Invalid input. Please choose 'y' or 'n'.")
if args.agent_type == "q":
agent = Qlearner(alpha,gamma,epsilon)
else:
agent = SARSAlearner(alpha,gamma,epsilon)
self.games_played = 0
self.path = args.path
self.agent = agent
def beginPlaying(self):
""" Loop through game iterations with a human player. """
print("Welcome to Tic-Tac-Toe. You are 'X' and the computer is 'O'.")
def play_again():
print("Games played: %i" % self.games_played)
while True:
play = input("Do you want to play again? [y/n]: ")
if play == 'y' or play == 'yes':
return True
elif play == 'n' or play == 'no':
return False
else:
print("Invalid input. Please choose 'y' or 'n'.")
while True:
game = Game(self.agent)
game.start()
self.games_played += 1
self.agent.save(self.path)
if not play_again():
print("OK. Quitting.")
break
def beginTeaching(self, episodes):
""" Loop through game iterations with a teaching agent. """
teacher = Teacher()
# Train for alotted number of episodes
while self.games_played < episodes:
game = Game(self.agent, teacher=teacher)
game.start()
self.games_played += 1
# Monitor progress
if self.games_played % 1000 == 0:
print("Games played: %i" % self.games_played)
# save final agent
self.agent.save(self.path)
if __name__ == "__main__":
# Parse command line arguments
parser = argparse.ArgumentParser(description="Play Tic-Tac-Toe.")
parser.add_argument('-a', "--agent_type", type=str, default="q",
choices=['q', 's'],
help="Specify the computer agent learning algorithm. "
"AGENT_TYPE='q' for Q-learning and AGENT_TYPE='s' "
"for Sarsa-learning.")
parser.add_argument("-p", "--path", type=str, required=False,
help="Specify the path for the agent pickle file. "
"Defaults to q_agent.pkl for AGENT_TYPE='q' and "
"sarsa_agent.pkl for AGENT_TYPE='s'.")
parser.add_argument("-l", "--load", action="store_true",
help="whether to load trained agent")
parser.add_argument("-t", "--teacher_episodes", default=None, type=int,
help="employ teacher agent who knows the optimal "
"strategy and will play for TEACHER_EPISODES games")
args = parser.parse_args()
# set default path
if args.path is None:
args.path = 'q_agent.pkl' if args.agent_type == 'q' else 'sarsa_agent.pkl'
# initialize game instance
gl = GameLearning(args)
# play or teach
if args.teacher_episodes is not None:
gl.beginTeaching(args.teacher_episodes)
else:
gl.beginPlaying()
|
from urllib.request import urlopen, hashlib
sha1hash = input("> Please insert the SHA-1 hash here.\n>")
common_passwords_list_url = input("> Please, also, provide the URL of the word list that you would like me to check.\n>")
common_passwords_list = urlopen(common_passwords_list_url).read()
common_passwords_list = str(common_passwords_list, 'utf-8')
#common_passwords_list = str(urlopen('https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-10000.txt').read(), 'utf-8')
for word in common_passwords_list.split('\n'):
hashed_word = hashlib.sha1(bytes(word, 'utf-8')).hexdigest()
if hashed_word == sha1hash:
print(">We found the word. The password is ", str(word))
quit()
elif hashed_word != sha1hash:
print("> The word ",str(word),"does not match this sha-1 hash, trying the next one...")
print("The word for the SHA-1 hash that you have inserted does not correspond toany word on the current database.")
|
import pandas as pd
import numpy as np
d = {"a": [1, 2, 3], "c": [4, 5, 6]}
a = pd.DataFrame(data=d)
b = pd.DataFrame(data={"a": [1, 2, 3], "c": [4, 2, 3]})
c = pd.DataFrame(data={"a": [1, 2, 3], "c": [5, 1, 3]})
d = pd.DataFrame(data={"a": [1, 2, 3], "c": [5, 1, 3]})
rs = a.merge(b, on="a", suffixes=("_a", "_b")).merge(c, on='a').merge(d, on='a')
# .merge(c,on="a")
print a
print a.apply(lambda x:x['a']**2,axis=1)
ls = [a, b, c, d]
def mult_merge(l, key):
x1 = l[0]
for x in l[1:]:
x1 = x1.merge(x, on=key)
return x1
print mult_merge(ls,"a")
|
from urllib.request import urlopen
import json
import datetime
import csv
import time
import pandas as pd
# input group name
# input access_token
# group_name is the name of the group as it appears in the url
# access_token can be attained from Graph API Explorer
def getGroupID(group_name, access_token):
base = "https://graph.facebook.com/v2.12"
group_query = "/search?q=%s&type=group" % group_name
token = "&access_token=%s" % access_token
url = base + group_query + token
response = urlopen(url)
# data = json.loads(resp)
# return type(response.read())
data = json.loads(response.read())
return data["data"][0]["id"]
def getPostIDs(group_id):
base = "https://graph.facebook.com/v2.12/" + group_id
group_query = "/feed?fields=name"
token = "&access_token=%s" % access_token
url = base + group_query + token
response = urlopen(url)
data = json.loads(response.read())
list_of_dicts = data["data"]
list_of_group_post_ids = [each["id"] for each in list_of_dicts]
post_order_dict = {}
iter_range = len(list_of_group_post_ids)
for i in range(iter_range):
back = list_of_group_post_ids.pop()
post_order_dict[i+1] = back
return post_order_dict
# return data["data"]
# string_identifier is a sample string from the post you're looking for.
# use only words (avoid emojis or other ill-formed units of meaning)
string_identifier = """
Looking forwards to the upcoming practice! We have a lotta announcements for y'all, and have summarized them here (we will also email a more in-depth version of announcements for your convenience). Respond to the fun prompt at the end of the post! We highly value team engagement :)
"""
def findCorrectPost(group_id, string_identifier):
base = "https://graph.facebook.com/v2.12/" + group_id
group_query = "/feed?fields=name,message,comments"
token = "&access_token=%s" % access_token
url = base + group_query + token
# print(url)
response = urlopen(url)
data = json.loads(response.read())
correct_post = None
for post in data["data"]:
# print(type(list(post.keys())))
if "message" not in list(post.keys()):
continue
check = post["message"]
identical = False
for word in string_identifier.split():
if word not in check:
break
identical = True
if identical:
print(post["id"])
correct_post = post
break
# print(word)
return correct_post
def getListOfComments(correct_post):
# TRY BLOCK 1
comments = []
data = []
# Method 1A: getting comments on current page
try:
# print("try1")
data = correct_post["comments"]["data"]
for comment in data:
comments.append(comment)
# print("hsdf", next_page_responders)
except:
pass
# Method 2A: getting comments on current page
try:
data = correct_post["data"]
for comment in data:
comments.append(comment)
except:
pass
# TRY BLOCK 2
url = None
# Method 1B: accessing the next page of responses
try:
url = correct_post["comments"]["paging"]["next"]
except:
pass
try:
# Method 2B: accessing the next page of responses
url = correct_post["paging"]["next"]
except:
pass
# Open the url (found by Method 1B/2B) if it exists.
next_page_responders = []
if url:
response = urlopen(url)
next_page = json.loads(response.read())
next_page_responders = getListOfComments(next_page)
comments.extend(next_page_responders)
return comments
def getNamesFromListOfComments(list_of_comments):
responders = []
for comment in list_of_comments:
responders.append(comment["from"]["name"])
return responders
def getListOfResponders(correct_post):
responders = []
for comment in correct_post["comments"]["data"]:
responders.append(comment["from"]["name"])
return responders
def main():
group_name = "afxlowkey"
access_token = "EAALJfWzkKZAgBACDGJ7SWpGS6nbJB8XnpK2M2otvKw27OjMwhaEvVJeh1JjHCEbkqDbzEOIrCDIFhE7BOvxYBQGYdDDXHEN9Anu8gTKw7lYKMy9HsMga7OqzScZBPYreqLTmVPJTHDiWnvfxlCmC17HZCBZBUdIMzIMrtwmRoQZDZD"
group_id = getGroupID(group_name, access_token)
print(group_id)
if __name__ == "__main__":
main()
# group_id = getGroupID(group_name, access_token)
# group_id
# correct_post = findCorrectPost(group_id, string_identifier)
# correct_post
# list_of_comments = getListOfComments(correct_post)
# list_of_comments
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''get the size of a file'''
import os
def get_file_size(file_path):
size = os.path.getsize(file_path)
print('Size of this file is {} byte'.format(size))
if __name__ == '__main__':
file_path = 'C:/Users/Bairong/Desktop/graph.txt'
get_file_size(file_path)
file_path2 = 'C:/Users/Bairong/Desktop/11.txt'
get_file_size(file_path2)
png_path = 'C:/Users/Bairong/Desktop/error.png'
get_file_size(png_path)
|
print("Welcome to the login!")
name = input("Enter user name:")
password = input("Enter user password:")
def login(user_name,user_pass):
un = user_name.lower()
up = user_pass.lower()
account = (un, up)
login_msg = ("You are now logged in as %s!" % name)
if un.lower() in account:
print(login_msg)
if len(up) < 8:
print("Password must be more than 8 characters long.")
del account
if str(un) in ("1,2,3,4,5,6,7,8,9,0"):
print("Why have any numbers \n This is literally the first account. ._.")
login(name, password)
|
def finger(landmark):
x = 0
y = 1
thumbFinger = False
firstFinger = False
secondFinger = False
thirdFinger = False
fourthFinger = False
if landmark[9][y] < landmark[0][y]:
Hand_direction_y = 'up'
else:
Hand_direction_y = 'down'
landmark_point = landmark[2][x]
if landmark[5][x] < landmark[17][x]:
if landmark[3][x] < landmark_point and landmark[4][x] < landmark_point:
thumbFinger = True
Hand_direction_x = 'right'
else:
if landmark[3][x] > landmark_point and landmark[4][x] > landmark_point:
thumbFinger = True
Hand_direction_x = 'left'
landmark_point = landmark[6][y]
if landmark[7][y] < landmark_point and landmark[8][y] < landmark_point:
firstFinger = True
landmark_point = landmark[10][y]
if landmark[11][y] < landmark_point and landmark[12][y] < landmark_point:
secondFinger = True
landmark_point = landmark[14][y]
if landmark[15][y] < landmark_point and landmark[16][y] < landmark_point:
thirdFinger = True
landmark_point = landmark[18][y]
if landmark[19][y] < landmark_point and landmark[20][y] < landmark_point:
fourthFinger = True
if thumbFinger and firstFinger and secondFinger and thirdFinger and fourthFinger:
hand = 'five'
elif not thumbFinger and firstFinger and secondFinger and thirdFinger and fourthFinger:
hand = 'four'
elif not thumbFinger and firstFinger and secondFinger and thirdFinger and not fourthFinger:
hand = 'tree'
elif not thumbFinger and firstFinger and secondFinger and not thirdFinger and not fourthFinger:
hand = 'two'
elif not thumbFinger and firstFinger and not secondFinger and not thirdFinger and not fourthFinger:
hand = 'one'
elif not thumbFinger and not firstFinger and not secondFinger and not thirdFinger and not fourthFinger:
hand = 'zero'
elif thumbFinger and not firstFinger and not secondFinger and not thirdFinger and fourthFinger:
hand = 'aloha'
elif not thumbFinger and firstFinger and not secondFinger and not thirdFinger and fourthFinger:
hand = 'fox'
elif thumbFinger and firstFinger and not secondFinger and not thirdFinger and not fourthFinger:
hand = 'up'
elif thumbFinger and firstFinger and not secondFinger and not thirdFinger and fourthFinger:
hand = 'RankaLee'
else:
hand = None
return hand, Hand_direction_x, Hand_direction_y
|
"""Estimate the future state of pedestrian motion useing a Kalman Filter.
This file contains the class, KalmanFilter, used to store the state of the
modeled system to estimate the state in a future timestep. The Kalman Filter
is applied as part of the project to the modelling of human motion, relating
the predicted positions back to detected centroids, allowing for people to be
tracked between frames.
"""
import numpy as np
class KalmanFilter:
"""Estimate the future state of a system.
This class is used to store the state of the modeled system to estimate the
state in a future timestep. The Kalman Filter is applied as part of the
project to the modelling of human motion, relating the predicted positions
back to detected centroids, allowing for people to be tracked between
frames. In this application, each instance of the Kalman filter has to
be allocated to only one pedestrian as that pedestrians 'state' differs
from those around it as the differnces in velocities will produce erronious
results.
Attributes:
dt (float): Delta time, used to create state transition model.
self.A (list): The observation model.
self.x (array): Vector of previous system state (position).
self.b (array): Vector of the current observed state.
self.P (array): Vector of previous system error.
self.F (array): State transition model.
self.Q (array): Covariance of the process noise.
Self.R (array): Covariance of the observation noise.
Self.lastResult (array): Last predicted position.
"""
def __init__(self):
"""Create a new instance of the Kalman Filter.
This constuctor initalises the inital state of the filter as well as
many of the variables within it such as the state transtion model. The
variables initalised here are used in the subsiquent prediction and
updating steps.
Args:
None
"""
self.dt = 0.005
self.A = np.array([[1, 0], [0, 1]])
self.x = np.zeros((2, 1))
self.b = np.array([[0], [255]])
self.P = np.diag((3.0, 3.0))
self.F = np.array([[1.0, self.dt], [0.0, 1.0]])
self.Q = np.eye(self.x.shape[0])
self.R = np.eye(self.b.shape[0])
self.lastResult = np.array([[0], [255]])
def predict(self):
"""Predict the state vector and variance of uncertainty.
This function uses the Time Update prediction equation from the two
part Kalman Filter equations to predict the position of the pedestrian
in the next frame. It first predicts the state of the system in the
next time step and then predicts the expected covariance of system
error.
Args:
None
Returns:
The predicted state vector.
"""
# Predicted state estimate
self.x = np.round(np.dot(self.F, self.x))
# Predicted estimate covariance
self.P = np.dot(self.F, np.dot(self.P, self.F.T)) + self.Q
self.lastResult = self.x
return self.x
def correct(self, b, allocated):
"""Update the state vector and uncertainty using an observation.
This function uses the Measurement Update correction equation from the
two part Kalman filter equations to correct the state of the system
and the position of the pedestrian in the next frame. If no observation
is made due to either noise in the system or the detection not being
made in the case of the pedestrian centroid then the last predicted
position will be used to correct the state and covariance instead.
Args:
b (array): Vector of observations.
allocated (bool): True if b contains a valid observation, false
if not.
Returns:
The updated state vector.
"""
if not allocated:
# Use the prediction instead
self.b = self.lastResult
else:
self.b = b
C = np.dot(self.A, np.dot(self.P, self.A.T)) + self.R
K = np.dot(self.P, np.dot(self.A.T, np.linalg.inv(C)))
self.x = np.round(self.x + np.dot(K, (self.b - np.dot(self.A,
self.x))))
self.P = self.P - np.dot(K, np.dot(C, K.T))
self.lastResult = self.x
return self.x
|
import os
import csv
# identify location of source data
sourcedirectory = 'input_data'
file1 = 'election_data_1.csv'
file2 = 'election_data_2.csv'
# wrap files in list for iteration
filelist = [file1, file2]
# for exploration, shown(n) prints n number of rows in each file
def shown(n):
# iterate over files
for afile in filelist:
# initialize row counter
counter = 0
# construct filepath using appropriate directory seperators
path = os.path.join(sourcedirectory, afile)
# open file to read, use with statement so file closes afterward
with open(path, 'r', newline='') as f:
# create reader object (iterable with .csv rows as elements)
reader = csv.reader(f)
# iterate over rows in .csv
for row in reader:
# increment row counter
counter = counter + 1
# print current row
print(row)
# stop printing rows when row counter == supplied argument
if counter >= n:
break
# countvotes() returns total number of votes, skipping headers
def countvotes():
# initialize vote counter
totcount = 0
# iterate over .csv files
for afile in filelist:
# initialize counter for all files
counter = 0
# construct filepath using appropriate directory seperators
path = os.path.join(sourcedirectory, afile)
# open file to read, use with statement so file closes afterward
with open(path, 'r', newline='') as f:
# create reader object (iterable with .csv rows as elements)
reader = csv.reader(f)
# iterate over rows in .csv
for row in reader:
# pass row if it is a header, typified by 'Voter ID'
if row[0] == 'Voter ID':
pass
# if not a header row, increment single file row counter
else:
counter = counter + 1
# when finished counting rows in file, add to counter for all files
totcount = totcount + counter
return totcount
# listcand() returns a list of unique candidates
def listcand():
# create list to hold unique candidates
candidates = []
# iterate over .csv files
for afile in filelist:
# construct filepath using appropriate directory seperators
path = os.path.join(sourcedirectory, afile)
# open file to read, use with statement so file closes afterward
with open(path, 'r', newline='') as f:
# create reader object (iterable with .csv rows as elements)
reader = csv.reader(f)
# iterate over rows in .csv
for row in reader:
# skip header row
if row[0] == 'Voter ID':
pass
else:
# check to see if current candidate is in list
if row[2] not in candidates:
# if new candidate, add to candidate list
candidates.append(row[2])
else:
pass
return candidates
# tallyvotes() returns a dictionary: {"Candidate":[percentage, votes]}
def tallyvotes():
# initialize dictionary
candidatedict = {}
# iterate over list of unique candidates
for candidate in candidates:
# initialize list of 2 integers for each candidate key
candidatedict[candidate] = [0,0]
# iterate over poll files
for afile in filelist:
# create filepath with appropriate directory seperators
path = os.path.join(sourcedirectory, afile)
# open file to read
with open(path, 'r', newline='') as f:
# create reader object to iterate over rows in .csv
reader = csv.reader(f)
# iterate over rows
for row in reader:
# skip headers
if row[0] == 'Voter ID':
pass
else:
# iterate over initialized candidate dictionary
for key, value in candidatedict.items():
# when candidate dictionary key matches voter candidate
if key == row[2]:
# increment vote value (2nd element in dict value list)
value[1] = value[1] + 1
# update percent votes for candidate in dict
value[0] = round(((value[1] / totcount) * 100), 1)
else:
pass
return candidatedict
# findwinner() returns key (candidate name string) of highest vote count value
def findwinner():
# initialize comparison value
topdog = 0
# iterate over each unique candidate in dict
for key, value in candidatedict.items():
# if largest vote count so far, store as top vote count
if value[1] > topdog:
topdog = value[1]
# store corresponding candidate name
winner = key
else:
pass
return winner
# run above functions in sequence
totcount = countvotes()
candidates = listcand()
candidatedict = tallyvotes()
winner = findwinner()
# function for easy line seperator in .txt output
def printsep():
print('\n', ('-' * 30))
# printresults() formats .txt file output
def printresults():
print('Election Results')
printsep()
print('\n', 'Total Votes:', totcount)
printsep()
# print contents of candidate dictionary with % formatting
for key, value in candidatedict.items():
print('\n' + key + ':', str(value[0]) + '% (' + str(value[1]) + ')')
printsep()
print('\n' + 'Winner: ', winner)
printsep()
# printtofile() opens output file to write and writes results of analysis
def printtofile():
path = os.path.join('output_data', 'election_results.txt')
with open(path, 'w', newline='') as f:
f.write('Election Results')
f.write('\n' + ('-' * 30))
f.write('\n' + 'Total Votes: ' + str(totcount))
f.write('\n' + ('-' * 30))
for key, value in candidatedict.items():
f.write('\n' + key + ': ' + str(value[0]) + '% (' + str(value[1]) + ')')
f.write('\n' + ('-' * 30))
f.write('\n' + 'Winner: ' + winner)
f.write('\n' + ('-' * 30))
# execute above functions to record election result
printresults()
printtofile()
|
#GUI that allows user to toggle Windows Key functionality
import keyboard
from tkinter import *
window = Tk()
window.title("NoWinKey")
winBlocked = False
def disable():
global winBlocked
winBlocked = True
keyboard.block_key('win')
enable.configure(state=ACTIVE)
disable.configure(state=DISABLED)
dLabel.configure(text='Current Status: DISABLED')
def enable():
global winBlocked
if winBlocked == True:
winBlocked = False
keyboard.unblock_key('win')
disable.configure(state=ACTIVE)
enable.configure(state=DISABLED)
dLabel.configure(text='Current Status: ENABLED')
else:
disable.configure(state=ACTIVE)
enable.configure(state=DISABLED)
myLabel = Label(window, text='Toggle your \'Windows Key\' functionality',padx=10, pady=10)
disable = Button(window, text='DISABLE', padx=30, pady=10, command=disable)
enable = Button(window, text='ENABLE', padx=30, pady=10, command=enable)
emptyBottom = Label(text="")
dLabel = Label(window, text='Current Status: ENABLED')
myLabel.grid(row=2, columnspan=4)
disable.grid(row=4, column=1)
enable.grid(row=4, column=2)
emptyBottom.grid(row=5, columnspan=4)
dLabel.grid(row=6, columnspan=4)
window.mainloop()
|
class Node:
"""
A node in singly linked list
"""
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __repr__(self):
return repr(self.data)
class SinglyLinkedList:
def __init__(self):
"""
Creates a new singly linked list
Takes O(1) time
"""
self.head = None
def __repr__(self):
"""
Return a string representation of the list
Takes O(n) time
"""
nodes = []
curr = self.head
while curr:
nodes.append(repr(curr))
curr = curr.next
return '[ ' + ', '.join(nodes) + ' ]'
def prepend(self, data):
"""
Insert a new element at the beginning of the list
Takes O(1) time
"""
self.head = Node(data, self.head)
def topFront(self):
"""
Return the first element of list
Takes O(1) time
"""
return self.head
def popFront(self):
"""
Remove the first element of list
Takes O(1) time
"""
self.head = self.head.next
def append(self, data):
"""
Insert a new element at the end of the list
Takes O(n) time
"""
if not self.head:
self.head = Node(data)
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = Node(data)
def find(self, key):
"""
Search for the first element with data matching
key. Return the element or None if not found.
Take O(n) time
"""
curr = self.head
while curr and curr.data != key:
curr = curr.next
return curr
def remove(self, key):
"""
Removes the first occurrence of the key in the list
Takes O(n) time
"""
curr = self.head
prev = None
while curr and curr.data != key:
prev = curr
curr = curr.next
if prev is None:
self.head = curr.next
elif curr:
prev.next = curr.next
curr.next = None
def topBack(self):
"""
Returns the last element of list
Takes O(n) time
"""
curr = self.head
while curr.next:
curr = curr.next
return curr.data
def popBack(self):
"""
Removes the last element of list
Takes O(n) time
"""
curr = self.head
while curr.next.next:
curr = curr.next
curr.next = None
def isEmpty(self):
"""
Return true if list is empty otherwise returns false
Takes O(1) time
"""
return True if self.head is None else False
def addBefore(self, key, data):
"""
Add an element before given key
Takes O(n) time
"""
curr = self.head
if key == curr.data:
self.prepend(data)
return
while curr:
if curr.next is None:
break
if curr.next.data == key:
node = Node(data, curr.next)
curr.next = node
break
else:
curr = curr.next
return
def addAfter(self, key, data):
"""
Add an element after given key
Takes O(n) time
"""
curr = self.head
while curr:
if curr.data == key:
node = Node(data, curr.next)
curr.next = node
break
else:
curr = curr.next
return
def reverse(self):
"""
Reverse the list in-place
Takes O(n) time
"""
curr = self.head
prev_node = None
next_node = None
while curr:
next_node = curr.next
curr.next = prev_node
prev_node = curr
curr = next_node
self.head = prev_node
if __name__=='__main__':
llist = SinglyLinkedList()
llist.prepend(10)
llist.prepend(20)
llist.prepend(30)
print(llist)
llist.append(40)
llist.append(50)
llist.append(60)
print(llist)
llist.reverse()
print(llist)
llist.remove(30)
print(llist)
print(llist.find('X'))
print(llist.topFront())
llist.popFront()
print(llist)
print(llist.topBack())
llist.popBack()
print(llist)
llist.addBefore(40, 20)
print(llist)
llist.addAfter(10, 55)
print(llist)
|
#!/usr/bin/python
# GOOGLE VOICE NUMBER ----------- 734-506-8603 -----------
from googlevoice import Voice
from googlevoice.util import input
import sys
def login(voice):
username, password = "[email protected]", "umichvois"
print("Logging in...")
client = voice.login(username, password)
return client
def call(voice):
outgoing = sys.argv[1]
if len(sys.argv[1]) != 10 or not sys.argv[1].isdigit():
print("Error: outgoing number is not a proper ten digit number")
return
print("Calling: ", outgoing)
voice.call('+1'+outgoing, '+17347806855')
voice = Voice() #Create new voice object
login(voice) #Login to our google account
call(voice) #Call number
|
str=input("enter any string of choice").split()
str.sort()
print(str)
str2=[]
for i in str:
if i not in str2:
str2.append(i)
for i in range(0,len(str2)):
print(f'{str2[i]} : {str.count(str2[i])}')
|
username=input("enter your username to register-->")
u,l,n,s=0,0,0,0
while True:
password=input("enter your password to register-->")
if(len(password)>=8 and len(password)<16):
for char in password:
if (char.islower()):
l+=1
elif (char.isupper()):
u+=1
elif (char.isdigit()):
n+=1
elif(char=='$' or char=='#' or char=="@"):
s+=1
if(1>=1 and u>=1 and n>=1 and s>=1):
if(l+u+n+s==len(password)):
print("it is a valid password!")
break
else:
print("it is an invalid password! Try again!")
|
from tabulate import tabulate
class Teacher:
quizapp = []
score = []
def __init__(self,teacher_name,question,options,correct_answer):
self.teacher_name=teacher_name
self.question=question
self.options=options
self.correct_answer=correct_answer
def question_answer(obj,i):
"""displays the questions along with its options from quizapp list"""
print(obj.question[i])
print(f"a.{obj.options[i][0]} \nb.{obj.options[i][1]} \nc.{obj.options[i][2]} \nd.{obj.options[i][3]}")
def correct_ans(ans,i,obj):
"""checks if the student's answer(ans) is the same as the correct answer as entered by teacher"""
if ans == obj.correct_answer[i]:
print("That was the correct answer!!")
return 1
else:
print(f"That's the wrong answer.The correct answer is: {obj.correct_answer[i]}")
return 0
class Student:
quizer = []
table=[]
def __init__(self,name,total_score):
self.total_score= total_score
self.name=name
def tot_marks():
"""displays the marks of all the students that have taken the quiz"""
if not Student.quizer:
print("No results added yet. Please check in later.")
else:
for obj in Student.quizer:
print(f"{obj.name}:{obj.total_score}")
|
''' check for map list '''
import time
from functools import wraps
def time_fun(method):
'''
@brief decorator to compute execution time of a function.
'''
@wraps(method)
def wrap_timed(*args, **kw):
'''
@brief compute time elapsed while executing
@param *args arguments for called method
@param **kw arguments for called method
'''
start_time = time.time()
result = method(*args, **kw)
elapsed_time = time.time() - start_time
print(elapsed_time*1000, end='')
# print(method.__name__ + " " + str(elapsed_time*1000))
return result
return wrap_timed
@time_fun
def create_list_for(num):
the_list = []
for i in range(num):
the_list.append(i)
return the_list
@time_fun
def create_list_comp(num):
the_list = [x for x in range(num)]
return the_list
@time_fun
def create_list_map(num):
the_list = list(map(lambda f: f, range(num)))
return the_list
def process(val):
return val / 2
@time_fun
def process_entries_for(num):
tot = 0
for idx in range(num):
tot = tot + process(idx)
return tot
@time_fun
def process_entries_comp(num):
return sum([process(x) for x in range(num)])
@time_fun
def process_entries_map(num):
return sum(map(lambda f: f/2, range(num)))
if __name__ == '__main__':
test_data = [1000, 10000, 100000, 1000000, 10000000, 100000000]
for item in test_data:
print(" "+str(len(create_list_for(item))))
for item in test_data:
print(" "+str(len(create_list_comp(item))))
for item in test_data:
print(" "+str(len(create_list_map(item))))
for item in test_data:
print(" "+str(process_entries_for(item))+" "+str(item))
for item in test_data:
print(" "+str(process_entries_comp(item))+" "+str(item))
for item in test_data:
print(" "+str(process_entries_map(item))+" "+str(item))
|
''' Worker threads sample code '''
import threading
import time
def worker(worker_name, timing):
'''
@brief a function that does something
'''
for _ in range(10):
print(worker_name)
time.sleep(timing)
if __name__ == '__main__':
TH1 = threading.Thread(target=worker, args=('TH1', 0.1,))
TH2 = threading.Thread(target=worker, args=('TH2', 0.4,))
TH1.start()
TH2.start()
TH1.join()
TH2.join()
|
import numpy as np
import math
import matplotlib.pyplot as plt
train_dat = np.genfromtxt('Wage_dataset.csv', delimiter=',')
train_data = np.array(train_dat)
year =train_data[0:2250,0]
age = train_data[0:2250,1]
edu = train_data[0:2250,4]
wage= train_data[0:2250,10]
yeart =train_data[2250:3000,0]
aget = train_data[2250:3000,1]
edut = train_data[2250:3000,4]
waget= train_data[2250:3000,10]
error=0
degree=3 #input the degree here
Y=[]
i=0
x=np.linspace(0,6,400)
x=np.array(x)
X=np.ones(np.size(edu))
X=np.transpose(X)
for i in range(degree):
X=np.c_[X,edu**(i+1)]
W=np.matmul(np.linalg.inv(np.matmul(np.transpose(X),X)),np.matmul(np.transpose(X),wage))
Y=W[0]*np.ones(400)
for i in range(1,degree+1):
Y=Y+W[i]*(x**i)
for i in range(0,750):
a=0
for j in range(0,degree+1):
a=a+W[j]*(edut[i]**j)
error=error+(a-waget[i])**2
print(error)
plt.xlabel("Wage")
plt.ylabel("Education")
plt.title("Polynomial regression for Education Vs Wage") # error
plt.plot(edu,wage,'r.') #points
plt.plot(x,Y) #Plot of the curve
plt.show()
|
#coding=utf-8
#自定
def testfunction(x):
return -x
a=testfunction(2919)
print(a)
#自定义函数2
def function2(numbers):
a=0
for n in numbers:
a=a+n*n
return a
b=function2([1,2,3,4])
print(b)
#关键字参数,**代表可以省略的参数
def guanjianzifunction(name,age,**height):
print("name",name,"age",age,"other",height)
guanjianzifunction("wuhao",20)
guanjianzifunction("micheal",14)
guanjianzifunction("wuhao",14,city="hefei")
#可以利用**来获取更多参数(以字典的方式)
extra={"city":"beijing","weight":"20"}
guanjianzifunction("wuhao",14,**extra)
#可以利用*来取得Tuple参数
def completefunction(name,age,*height,**other):
print("name:",name,"age:",age,"height:",height,"other",other)
extranew={"jionghao":123,"buzhidao":421}
completefunction("wuhao",12,144,123,124,**extranew)
|
#coding=utf-8
#遍历数组进行打印
newArray=["wuhao","ligang","micheal"];
for name in newArray:
print(name);
#简单的进行计算
a=0;
for x in [1,2,3,4,5,6,7,8,9,10]:
a+=x;
print(a);
#简单的求和运算
b=0;
#range(101)代表的意思是[0,1,2,3.......100];
#range()函数可以生成整数数列
for x in range(101):
b+=x;
print(b);
newsum=0;
n=0;
while n<100:
newsum+=n;
n+=2;
print(newsum);
# while 1:
# print("你是一个好人");
def hello(x):
return -x
a=hello(10)
print(a)
|
# coding: utf-8
from collections import OrderedDict
def first_not_not_repeating_number(s):
hash_map = OrderedDict()
for ch in s:
cnt_num = hash_map.get(ch, 0)
hash_map[ch] = cnt_num + 1
for k, v in hash_map.iteritems():
if v == 1:
return k
return None
if __name__ == '__main__':
print first_not_not_repeating_number("abaccdeff")
|
# coding: utf-8
def sort_array_for_min_number(arr):
"""
:param arr: 数组
:return: int
"""
length = len(arr)
if length == 1:
return arr[0]
arr = map(str, arr)
arr.sort(compare)
return ''.join(arr)
def compare(a, b):
len_a, len_b = len(a), len(b)
if len_a < len_b:
while len(a) < len_b:
a += a[-1]
elif len_a > len_b:
while len(b) < len_a:
b += b[-1]
return -1 if a < b else 1
if __name__ == '__main__':
arr = [3, 3, 32, 321, 432, 434, 43, 4, 5, 66, 67]
print sort_array_for_min_number(arr)
|
# coding: utf-8
def decode_string(s):
res = ''
idx = 0
length = len(s)
while idx < length:
ch = s[idx]
if ch.isdigit():
i = idx + 1
while s[i].isdigit():
i += 1
num = int(s[idx:i])
if s[-1] == ']':
inner_s = decode_string(s[i+1:-1])
res += (num * inner_s)
break
else:
j = length - 1
while s[j] != ']':
j -= 1
inner_s = decode_string(s[i+1:j])
res += (num * inner_s)
idx = j
elif ch.isalpha():
res += ch
idx += 1
return res
if __name__ == '__main__':
print decode_string('e3[2[abc]gh]')
print decode_string('e9[xyz]')
|
# coding: utf-8
def greatest_sum_of_subarray(arr):
res, tmp = float('-inf'), float('-inf')
for n in arr:
if tmp < 0:
tmp = n
else:
tmp += n
if tmp > res:
res = tmp
return res
if __name__ == "__main__":
arr = [1, -2, 3, 10, -4, 7, 2, -5]
print greatest_sum_of_subarray(arr)
|
# coding: utf-8
def duplicate(nums):
length = len(nums)
for i in xrange(length):
while nums[i] != i:
if nums[nums[i]] == nums[i]:
return nums[i]
a, b = i, nums[i]
nums[a], nums[b] = nums[b], nums[a]
return -1
if __name__ == '__main__':
print duplicate([2, 3, 1, 0, 2, 5, 3])
|
from keras.datasets import mnist # standard dataset of hand drawn numbers - digit recognition
import matplotlib.pyplot as plt
import keras
from keras.layers import Input, Dense, Convolution2D, MaxPooling2D, Flatten
import numpy as np
(x_train, y_train), (x_test,y_test) = mnist.load_data()
x_train = x_train[:10000, :]
y_train = y_train[:10000]
x_test = x_test[:1000, :]
y_test = y_test[:1000]
# x = input (images), y = output (numbers)
print(x_train.shape)
print(y_train.shape)
# Plot some images to see how they look. In grey. With a title.
for i in range(0):
plt.imshow(x_train[i,:,:], cmap="gray")
plt.title(y_train[i])
plt.show()
# have now looked at the data and it looks smashin'
# last 4th dimentions is channels, but we're doing greyscale so dont need that
x_train = np.expand_dims(x_train,axis=-1)
x_test = np.expand_dims(x_test,axis=-1)
print(x_train.shape)
# must now convert images to floats
print(x_train.dtype)
x_train = x_train.astype(np.float32)/255
x_test = x_test.astype(np.float32)/255
print(x_train.dtype)
# must now convert the output data. It is values, but we want it to match data
# we want onehotencoding
y_train = keras.utils.to_categorical(y_train,10)
y_test = keras.utils.to_categorical(y_test,10)
print(y_train.shape)
print(y_test.shape)
print(y_train[0,:])
# MAKING LAYER MAKING NETWORK DUDUDU ITS OURS THIS TIME
first_layer = Input(shape=x_train.shape[1:])
# nr of filters, size of filter, activationfilter, and x is the prev layer
x = Convolution2D(32, 3, activation="relu",padding="same")(first_layer)
x = Convolution2D(64, 3, activation="relu",padding="same")(x)
# half the width and height
x = MaxPooling2D((2,2))(x)
x = Flatten()(x)
# nr of neurons in this layer
x = Dense(128)(x)
x = Dense(128)(x)
x = Dense(10,activation="softmax")(x)
model = keras.Model(inputs=first_layer,outputs=x)
print(model.summary())
model.compile(loss="categorical_crossentropy",optimizer="adadelta")
model.fit(x_train,y_train,batch_size=24,epochs=3,validation_data=(x_test,y_test))
|
import requests
class Api:
"""
This is a python class to extract data from different API's in JSON format and store it in files.
The different functions are used for extracting data using Non-GMO HTTP library
for python known as Requests.
Mainly consists the following variables:
payload - a dictionary which is used to pass the parameters to a particular URL query string.
r - a response object which is used to GET data from the URL query string.
data - a json decoder for the stream of data from r.
extract - It is used to get particular lists(details of certain key attributes) from the dictionary
returned from the response object.
outfile - text file to store values of specific keys present in the response object dictionary.
For further Details:http://info.rightrelevance.com/docs/api-docs/
"""
def __init__(self):
"""
Generating the access_token whenever an API is invoked
"""
self.access_token = '68a98c9fe9ebfc409d7d46bd9d496561045e9d52372c8896c8f25d1d6e64e1d8'
def articles(self,query,start,rows):
"""
This API returns relevant articles for a given topic in near real-time.
Signature:http://api.rightrelevance.com/v2/articles/search?query=<rr_topic>&start=X&rows=Y&access_token=<access_token>
:param query: a particular query topic user searches.
:param start: start=X: Starting index for articles. Default-0
:param rows: rows=Y: Number of articles to return. Default-10
:return: JSON String of the topic.
"""
payload = {'query':query,'start':start,'rows':rows,'access_token': self.access_token}
r = requests.get("http://api.rightrelevance.com/v2/articles/search",params=payload,stream=True)
#with open('art_file.txt','w') as outfile:
# for chunk in r.iter_content(chunk_size=1):
# outfile.write(chunk)
""" returning the JSON Response """
for chunk in r.iter_content(chunk_size=1000000):
return chunk
def influencers(self,query,start,rows):
"""
This API provides access to the influencers graph for a structured RightRelevance topic.
It is 2-level (global and per-topic) rank page provides unparalleled relevance.
Signature: http://api.rightrelevance.com/v2/experts/search?query=<rr_topic>&start=X&rows=Y&access_token=<access_token>
:param query: a particular query topic user searches.
:param start: start=X: Starting index for articles. Default-0
:param rows: rows=Y: Number of articles to return. Default-10
:return: JSON String of the topic.
"""
payload = {'query':query,'start':start,'rows':rows,'access_token':self.access_token}
r = requests.get("http://api.rightrelevance.com/v2/experts/search",params=payload,stream=True)
#with open('influencers_file.txt','w') as outfile:
# for chunk in r.iter_content(chunk_size=1):
# outfile.write(chunk)
""" returning the JSON Response """
for chunk in r.iter_content(chunk_size=1000000):
return chunk
def conversations(self,query,page,rows,order):
"""
This API aggregates and provide topical influencer conversations in a tree topology.
Signature: http://api.rightrelevance.com/v2/conversations/search?query=<rr_topic>&page=X&rows=Y&order_by=_order_by_&access_token=<access_token>
:param query: a particular query topic user searches.
:param page: page=X: Starting index for articles. Default-0
:param rows: rows=Y: Number of articles to return. Default-10
:param order: orderby=[time|relevance]: Order in which the conversations are received. Default-relevance
:return: JSON String of the topic.
"""
payload = {'query':query,'page':page,'rows':rows,'order_by':order,'access_token':self.access_token}
r = requests.get("http://api.rightrelevance.com/v2/conversations/search",params=payload,stream=True)
#with open('conversations_file.txt','w') as outfile:
# for chunk in r.iter_content(chunk_size=1):
# outfile.write(chunk)
""" returning the JSON Response """
for chunk in r.iter_content(chunk_size=1000000):
return chunk
def autocomplete(self, q):
"""
This API supports auto-complete functionality for a search box experience in your application.
Signature: http://api.rightrelevance.com/v2/topics/autocomplete?q=<string>&access_token=<access_token>
:param q: q=string: Any string for which suggested topics are needed.
:return: JSON String of the topic.
"""
payload = {'query':q,'access_token':self.access_token}
r = requests.get("http://api.rightrelevance.com/v2/topics/autocomplete",params=payload,stream=True)
#with open('autocomplete_file.txt','w') as outfile:
# for chunk in r.iter_content(chunk_size=1):
# outfile.write(chunk)
""" returning the JSON Response """
for chunk in r.iter_content(chunk_size=1000000):
return chunk
api_obj = Api() # object of class Api.
api_obj.articles('data', 0, 1) # Data Extraction from articles API which is stored in a file called 'art_file.txt'
|
#
# Challenge Description:
#
# Credits: This challenge appeared in the Facebook Hacker Cup 2011.
#
# A double-square number is an integer X which can be expressed
# as the sum of two perfect squares. For example, 10 is a double-square because 10 = 3^2 + 1^2.
# Your task in this problem is, given X, determine the number of ways in which it can be written
# as the sum of two squares. For example, 10 can only be written as 3^2 + 1^2 (we don't count 1^2 + 3^2 as being different).
# On the other hand, 25 can be written as 5^2 + 0^2 or as 4^2 + 3^2.
# NOTE: Do NOT attempt a brute force approach. It will not work. The following constraints hold:
# 0 <= X <= 2147483647
# 1 <= N <= 100
#
# Input sample:
#
# You should first read an integer N, the number of test cases.
# The next N lines will contain N values of X.
#
# 5
# 10
# 25
# 3
# 0
# 1
# Output sample:
#
# e.g.
#
# 1
# 2
# 0
# 1
# 1
#
import sys
from math import sqrt
def doubleSquare(s):
N = int(s)
half = int(sqrt(N))
i, j = 0, half
pairs = 0
while i <= j:
sum_of_pair = i**2 + j**2
if sum_of_pair == N:
pairs += 1
i += 1
elif sum_of_pair > N:
j -= 1
else:
i += 1
return pairs
def main():
test_cases = open(sys.argv[1], 'r')
i = 0
for test in test_cases:
test = test.strip()
if i == 0: i = 1
elif test:
print doubleSquare(test)
test_cases.close()
if __name__ == "__main__":
main()
|
#
# Challenge Description:
#
# You are given a sorted array of positive integers and a number 'X'.
# Print out all pairs of numbers whose sum is equal to X.
# Print out only unique pairs and the pairs should be in ascending order
#
# Input sample:
# Your program should accept as its first argument a filename.
# This file will contain a comma separated list of sorted numbers and then the sum 'X', separated by semicolon.
# Ignore all empty lines. If no pair exists, print the string NULL eg.
#
# 1,2,3,4,6;5
# 2,4,5,6,9,11,15;20
# 1,2,3,4;50
#
# Output sample:
# Print out the pairs of numbers that equal to the sum X.
# The pairs should themselves be printed in sorted order
# i.e the first number of each pair should be in ascending order .e.g.
#
# 1,4;2,3
# 5,15;9,11
# NULL
#
import sys
def numberPairs(s):
numbers, X = process(s)
i = 0
j = len(numbers)-1
pairs = []
while i < j:
A = numbers[i]
B = numbers[j]
if A + B == X:
pairs.append("%s,%s" % (A , B))
i += 1
elif A + B < X:
i += 1
else:
j -= 1
return ";".join(pairs) if len(pairs) > 0 else "NULL"
def process(s):
s_list = s.strip().split(';')
part1 = s_list[0].strip().split(',')
A = [ int(v.strip()) for v in part1 ]
B = int(s_list[1].strip())
return A, B
def main():
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
print numberPairs(test)
#process(test)
test_cases.close()
if __name__ == "__main__":
main()
|
"""
Module for graph-based classes
"""
from __future__ import annotations
from typing import Callable
import torch
import heat as ht
from heat.core.dndarray import DNDarray
class Laplacian:
"""
Graph Laplacian from a dataset
Parameters
----------
similarity : Callable
Metric function that defines similarity between vertices. Should accept a data matrix :math:`n \\times f` as input and
return an :math:`n\\times n` similarity matrix. Additional required parameters can be passed via a lambda function.
definition : str
Type of Laplacian \n
- ``'simple'``: Laplacian matrix for simple graphs :math:`L = D - A` \n
- ``'norm_sym'``: Symmetric normalized Laplacian :math:`L^{sym} = I - D^{-1/2} A D^{-1/2}` \n
- ``'norm_rw'``: Random walk normalized Laplacian :math:`L^{rw} = D^{-1} L = I - D^{-1}` \n
mode : str
How to calculate adjacency from the similarity matrix \n
- ``'fully_connected'`` is fully-connected, so :math:`A = S` \n
- ``'eNeighbour'`` is the epsilon neighbourhood, with :math:`A_{ji} = 0` if :math:`S_{ij} > upper` or
:math:`S_{ij} < lower`; for eNeighbour an upper or lower boundary needs to be set \n
threshold_key : str
``'upper'`` or ``'lower'``, defining the type of threshold for the epsilon-neighborhood
threshold_value : float
Boundary value for the epsilon-neighborhood
neighbours : int
Number of nearest neighbors to be considered for adjacency definition. Currently not implemented
"""
def __init__(
self,
similarity: Callable,
weighted: bool = True,
definition: str = "norm_sym",
mode: str = "fully_connected",
threshold_key: str = "upper",
threshold_value: float = 1.0,
neighbours: int = 10,
) -> DNDarray:
self.similarity_metric = similarity
self.weighted = weighted
if definition not in ["simple", "norm_sym"]:
raise NotImplementedError(
"Currently only simple and normalized symmetric graph laplacians are supported"
)
else:
self.definition = definition
if mode not in ["eNeighbour", "fully_connected"]:
raise NotImplementedError(
"Only eNeighborhood and fully-connected graphs supported at the moment."
)
else:
self.mode = mode
if threshold_key not in ["upper", "lower"]:
raise ValueError(
"Only 'upper' and 'lower' threshold types supported for eNeighbouhood graph construction"
)
else:
self.epsilon = (threshold_key, threshold_value)
self.neighbours = neighbours
def _normalized_symmetric_L(self, A: DNDarray) -> DNDarray:
"""
Helper function to calculate the normalized symmetric Laplacian
.. math:: L^{sym} = D^{-1/2} L D^{-1/2} = I - D^{-1/2} A D^{-1/2}
Parameters
----------
A : DNDarray
The adjacency matrix of the graph
"""
degree = ht.sum(A, axis=1)
degree.resplit_(axis=None)
# Find stand-alone vertices with no connections
temp = torch.ones(
degree.shape, dtype=degree.larray.dtype, device=degree.device.torch_device
)
degree.larray = torch.where(degree.larray == 0, temp, degree.larray)
L = A / ht.sqrt(ht.expand_dims(degree, axis=1))
L = L / ht.sqrt(ht.expand_dims(degree, axis=0))
L = L * (-1.0)
L.fill_diagonal(1.0)
return L
def _simple_L(self, A: DNDarray):
"""
Helper function to calculate the simple graph Laplacian
.. math:: L = D - A
Parameters
----------
A : DNDarray
The Adjacency Matrix of the graph
"""
degree = ht.sum(A, axis=1)
L = ht.diag(degree) - A
return L
def construct(self, X: DNDarray) -> DNDarray:
"""
Callable to get the Laplacian matrix from the dataset ``X`` according to the specified Laplacian
Parameters
----------
X : DNDarray
The data matrix, Shape = (n_samples, n_features)
"""
S = self.similarity_metric(X)
S.fill_diagonal(0.0)
if self.mode == "eNeighbour":
if self.epsilon[0] == "upper":
if self.weighted:
S = ht.where(S < self.epsilon[1], S, 0)
else:
S = ht.int(S < self.epsilon[1])
else:
if self.weighted:
S = ht.where(S > self.epsilon[1], S, 0)
else:
S = ht.int(S > self.epsilon[1])
if self.definition == "simple":
L = self._simple_L(S)
elif self.definition == "norm_sym":
L = self._normalized_symmetric_L(S)
return L
|
import sys
symbols = ['', ' ', ',', '!', '?', '.', '-', ':']
sentence = sys.argv[1]
# print(sentence)
sentence = sentence.split(' ')
sentence = list(set(sentence))
# print(sentence)
sentence.sort()
# print(sentence)
for i in symbols:
try:
i
sentence.remove(i)
# print(i)
except:
continue
# print(sentence)
print(len(sentence))
|
def genPrimes():
number = 2
prime_list = [2]
yield number
while True:
continue_while = False
number += 1
for divisor in prime_list:
if number % divisor == 0:
continue_while = True
break
if continue_while:
continue
prime_list.append(number)
yield number
|
"""
1. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
"""
"""
解題思路
找出兩數和有兩種方法,一個為使用哈希表,另一個方法為使用排序+相向雙指針
時空複雜度:
1.哈希表
時:O(n)
空:O(n)
2.排序+雙指針
時:O(nlogn)
空:O(1)
"""
nums = [2,7,11,15], target = 9
"""
哈希表
"""
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
#異常檢測
if not nums:
return [-1, -1]
#哈希表
hashtable = {}
for i in range(len(nums)):
if target - nums[i] in hashtable:
return hashtable[target - nums[i]], i
hashtable[nums[i]] = i
return [-1, -1]
"""
排序+雙指針
"""
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
#異常檢測
if not nums:
return [-1, -1]
#枚舉法
numbers = [ (number,index) for index, number in enumerate(nums)]
#排序,帶著他的index一起排序
numbers.sort()
#相向雙指針
left, right = 0, len(nums) - 1
while left < right:
if numbers[left][0] + numbers[right][0] > target:
right -= 1
elif numbers[left][0] + numbers[right][0] < target:
left += 1
else:
return sorted([numbers[left][1], numbers[right][1]])
return [-1, -1]
|
"""
1304. Find N Unique Integers Sum up to Zero
Given an integer n, return any array containing n unique integers such that they add up to 0.
Example 1:
Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
Example 2:
Input: n = 3
Output: [-1,0,1]
Example 3:
Input: n = 1
Output: [0]
"""
class Solution:
def sumZero(self, n: int) -> List[int]:
ans = range(1,n)
return (ans) + [-sum(ans)]
|
"""
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
TLE:to much recursion called
"""
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not list:
return
if len(lists) ==1:
return list[0]
mid = len(lists)//2
head1 = self.mergeKLists(lists[:mid])
head2 = self.mergeKLists(lists[mid:])
return self.sortedmerge(head1,head2)
def sortedmerge(self,head1,head2):
tmp = None
if not head1:
return head2
if not head2:
return head1
if head1.val <= head2.val:
tmp = head1
tmp.next = self.sortedmerge(head1.next,head2)
else:
tmp = head2
tmp.next = self.sortedmerge(head1,head2.next)
"""
TC:O(nlogn)
SC:O(N)
"""
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return
if len(lists) ==1:
return lists[0]
mid = len(lists)//2
head1 = self.mergeKLists(lists[:mid])
head2 = self.mergeKLists(lists[mid:])
return self.sortedmerge(head1,head2)
def sortedmerge(self,head1,head2):
tmp = cur = ListNode(-1)
while head1 and head2:
if head1.val<head2.val:
cur.next = head1
head1 = head1.next
else:
cur.next = head2
head2 = head2.next
cur = cur.next
cur.next = head1 or head2
return tmp.next
|
"""
18. 4Sum
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target?
Find all unique quadruplets in the array which gives the sum of target.
Notice that the solution set must not contain duplicate quadruplets.
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [], target = 0
Output: []
"""
"""
解題思路:
此題求四數之和為target a + b + c + d = target
首先先排序,外圍兩層for循環 一個a 一個 b
內層再使用相向雙指針一個頭 一個偉
虽然题目是四数之和,但是我们可以将他转换为三数之和,再进一步就是二数之和,先进行稳定排序,然后我们准备用四个指针
先用将问题看待为三数之和,即一个指针和三个指针
再将这三个指针看成二数之和,即一个指针和两个指针
那么问题就被化简了,先框定两个指针,再在这个基础上,用双指针解决问题,
当头指针和尾指针的元素之和大于new_target,尾指针-1(因为头指针+1的结果肯定大于new_target),
同理当头指针和尾指针的元素之和小于new_target,头指针+1。
時空複雜度:
時:O(n^3)
空:O(n^2)
"""
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
#異常檢測
if not nums or len(nums) < 4:return []
#排序
nums.sort()
#initialize
ans = []
for i in range (len(nums) - 3):
#如果i前面有數而且相鄰兩數兩等,直接往下繼續
if i > 0 and nums[i - 1] == nums[i]:
continue
#remove duplicate
for j in range (i + 1, len(nums) - 2):
#如果j前面有數而且相鄰兩數兩等,直接往下繼續
if j > i + 1 and nums[j - 1] == nums[j]:
continue
#雙指針
left, right = j + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
ans.append([nums[i], nums[j], nums[left], nums[right]])
left += 1
right -= 1
#remove duplicate
while left < right and nums[left] == nums[left - 1]:
continue
#remove duplicate
while left < right and nums[right] == nums[right + 1]:
continue
elif total < target:
left += 1
else:
right -= 1
return ans
|
import random
# represents a square in the board.
class Square:
def __init__(self, is_black, piece, board, x, y):
self.isBlack = is_black
self.piece = piece # 1 is p1, 2 is p2, 3 is p1king, 4 is p2king, 0 is empty
self.board = board
self.x = x
self.y = y
self.jump_simulated = False # to prevent infinite recursion in chained jumps with kings
def __repr__(self):
return "(" + chr(self.x + 96).capitalize() + "," + str(self.y) + ")"
def symbol(self):
if self.piece != 0:
return str(self.piece)
else:
if self.isBlack:
return " "
else:
return " "
def get_diagonals(self, player):
squares = []
relative_coordinates = []
if player == 1 or player > 2:
relative_coordinates.extend([(-1, -1), (1, -1)])
if player >= 2:
relative_coordinates.extend([(1, 1), (-1, 1)])
for coordinate in relative_coordinates:
x = self.x + coordinate[0]
y = self.y + coordinate[1]
diagonal = self.board.get(x, y)
if diagonal is not None:
squares.append(diagonal)
return squares
def get_next_one_over(self, over_square):
return self.board.get(over_square.x + (over_square.x - self.x), over_square.y + (over_square.y - self.y))
class Board:
def __init__(self):
self.squares = [] # 8x8 list of Square objects
self.move_history = [] # a list containing lists of moves that have been executed.
self.moves_without_jump = 0
self.winner = 0
# add all squares into the board and initialize them to be like they should in the beginninf of the game
for i in range(8):
row = []
for j in range(8):
append_square = Square(True, 0, self, j+1, i+1)
if i % 2 == 0:
if j % 2 == 0:
append_square.isBlack = False
else:
if j % 2 != 0:
append_square.isBlack = False
if append_square.isBlack:
if i < 3:
append_square.piece = 2
elif i > 4:
append_square.piece = 1
row.append(append_square)
self.squares.append(row)
def get(self, x, y):
if 1 <= x <= 8 and 1 <= y <= 8:
return self.squares[y-1][x-1]
else:
return None
# returns a string representing the board
def board_str(self):
append_str = ""
for row in self.squares:
append_str += str(row[0].y) + " "
for square in row:
append_str += square.symbol() + " "
append_str += "\n"
append_str += " A B C D E F G H\n"
return append_str
# (used for robot) compares binary 8x8 list of integers to current internal board state
def is_up_to_date(self, board_data):
for x in range(1, 9):
for y in range(1, 9):
square = self.get(x, y)
if square.isBlack:
bit = board_data[y-1][x-1]
if (square.piece != 0 and bit == 0) or (square.piece == 0 and bit == 1):
return False
return True
# (used for robot) returns false, until a legal move is detected from input
def process_input(self, board_data, player):
if not self.is_up_to_date(board_data):
return self.execute_difference_move(self.find_differences(board_data, player), player)
else:
return False
# (used for robot)
def find_differences(self, board_data, player):
differences = []
for x in range(1, 9):
for y in range(1, 9):
square = self.get(x, y)
if square.isBlack:
piece = square.piece
bit = board_data[y - 1][x - 1]
if bit == 1 and piece == 0:
differences.append({'x': x, 'y': y, 'type': 3}) # player end square
elif bit == 0 and self.is_same_team(piece, player):
differences.append({'x': x, 'y': y, 'type': 1}) # player move start square
elif bit == 0 and piece != 0:
differences.append({'x': x, 'y': y, 'type': 2}) # eaten piece square
return differences
# (used for robot)
def execute_difference_move(self, differences, player):
starts = list(filter(lambda diff: diff['type'] == 1, differences))
if len(starts) != 1:
return False
start = starts[0]
player_piece = self.get(start['x'], start['y']).piece
if not self.is_same_team(player_piece, player):
return False
possible_moves = self.possible_moves(start['x'], start['y'])
for moves in possible_moves:
found_legal_move = True
self.execute_moves(moves)
for difference in differences:
square = self.get(difference['x'], difference['y'])
if (difference['type'] == 2 and square.piece != 0) or \
(difference['type'] == 3 and not self.is_same_team(square.piece, player)):
found_legal_move = False
break
if found_legal_move:
return True
else:
self.undo_moves()
return False
@staticmethod
def is_same_team(piece1, piece2):
if piece1 == 0 or piece2 == 0:
return False
elif piece1 % 2 == piece2 % 2:
return True
else:
return False
# returns all possible moves for a piece in certain coordinates
def possible_moves(self, x, y, is_chain=False, chain_piece=0):
moves_list = []
square = self.get(x, y)
if is_chain:
p = chain_piece
else:
p = square.piece
if p != 0:
for target_square in square.get_diagonals(p):
if target_square.piece == 0 and not is_chain:
moves_list.append([Move(square, target_square, p)])
elif target_square.piece != 0 and target_square.piece % 2 != p % 2:
# the target square has an enemy piece
jump_square = square.get_next_one_over(target_square)
if jump_square is not None and jump_square.piece == 0 and not jump_square.jump_simulated:
jump_square.jump_simulated = True
for move in self.possible_moves(jump_square.x, jump_square.y, True, p):
moves_list.append([Move(square, jump_square, p, True, target_square)] + move)
jump_square.jump_simulated = False
if any(moves[0].jumps for moves in moves_list):
moves_list = list(filter(lambda move: move[0].jumps, moves_list))
if is_chain and not moves_list:
moves_list.append([])
return moves_list
def get_all_squares(self):
all_squares = []
for row in self.squares:
all_squares.extend(row)
return all_squares
# return all squares where a certain player is
def get_player_squares(self, player):
all_squares = self.get_all_squares()
return list(filter(lambda square: square.piece % 2 == player % 2 and square.piece != 0, all_squares))
# return all possible moves that a player currently has
def all_possible_moves(self, player):
player_squares = self.get_player_squares(player)
moves = []
for piece_square in player_squares:
moves.extend(self.possible_moves(piece_square.x, piece_square.y))
if any(move[0].jumps for move in moves):
moves = list(filter(lambda move: move[0].jumps, moves))
return moves
# executes moves and saves them in move_history
def execute_moves(self, moves):
for move in moves:
move.end.piece = move.start.piece
move.start.piece = 0
if move.jumps:
move.between_square.piece = 0
if move.kinged:
move.end.piece += 2 # kings a piece if it reaches the end.
self.move_history.append(moves)
return moves
# will change instance variable 'winner' once called if a certain win condition is met
def check_game_over(self):
if not self.all_possible_moves(1):
self.winner = 2
if not self.all_possible_moves(2):
self.winner = 1
if self.moves_without_jump > 20:
self.winner = 99 # tie
# undoes most recent set of moves in the internal gameboard
def undo_moves(self):
moves = reversed(self.move_history.pop())
for move in moves:
if move.kinged:
move.start.piece -= 2.
if move.jumps:
move.between_square.piece = move.captured
move.start.piece = move.moved_piece
move.end.piece = 0
return moves
# used to evaluate current situation for a player (greater than 0 is leagin and less is losing)
def evaluate(self, player):
score = 0
all_squares = self.get_all_squares()
for square in all_squares:
p = square.piece
if p != 0:
if p % 2 == player % 2:
score += 100
if p == player + 2:
score += 50
else:
score -= 100
if p > 2:
score -= 50
return score
# returns best move according to the minimax algorithm
def evaluate_best_move(self, player, depth):
possible_moves = self.all_possible_moves(player)
random.shuffle(possible_moves)
return max(possible_moves, key=(lambda move: Simulation().minimax(depth, self, player)))
# Represents a move in the game. Contains necessary information for AI and controlling the robot.
class Move:
def __init__(self, square_1, square_2, moved_piece, jumps=False, between_square=None):
self.start = square_1
self.end = square_2
self.jumps = jumps
self.between_square = between_square
self.moved_piece = moved_piece
if between_square is not None:
self.captured = between_square.piece
else:
self.captured = None
self.kinged = (self.moved_piece == 1 and self.end.y == 1) or (self.moved_piece == 2 and self.end.y == 8)
def __repr__(self):
return str(self.start) + "to" + str(self.end)
class Simulation:
def __init__(self):
pass
def minimax(self, depth, board, player, is_maxing_player=True):
if depth == 0:
return board.evaluate(player)
possible_moves = board.all_possible_moves(player)
if player == 1:
nextplayer = 2
else:
nextplayer = 1
if is_maxing_player:
best_move = -9999
for move in possible_moves:
board.execute_moves(move)
best_move = max(best_move,
self.minimax(depth-1, board, nextplayer, not is_maxing_player))
board.undo_moves()
return best_move
else:
best_move = 9999
for move in possible_moves:
board.execute_moves(move)
best_move = min(best_move,
self.minimax(depth-1, board, nextplayer, not is_maxing_player))
board.undo_moves()
return best_move
# AI vs. AI on console
def ai_vs_ai_game():
pnum = 1
turn = 1
while test_board.winner == 0:
print("\n" + str(turn) + "# Round, Player:" + str(pnum))
print(test_board.print_board())
best_moves = test_board.evaluate_best_move(pnum, 4)
if best_moves[0].jumps:
test_board.moves_without_jump = 0
else:
test_board.moves_without_jump += 1
print(test_board.execute_moves(best_moves))
print("evaluation for player " + str(pnum) + ": " + str(test_board.evaluate(pnum)))
test_board.check_game_over()
turn += 1
if pnum == 1:
pnum = 2
else:
pnum = 1
print("\n" + str(turn) + "# Round, Player:" + str(pnum))
print(test_board.print_board())
print("The winner is " + str(test_board.winner) + "\n")
|
# TODO
from sys import argv, exit
import csv
from cs50 import SQL
db = SQL("sqlite:///students.db")
if len(argv) != 2 :
print("CSV file not provided")
exit(1)
variableArg = argv[1]
myResult = db.execute("SELECT * FROM students WHERE house = (?) ORDER BY last ASC, first ASC", variableArg)
for result in myResult:
if result["middle"] == None:
print(result['first'] + ' ' + result['last'] + ', ' + 'born ' + str(result['birth']))
else:
print(result['first'] + ' ' + result['middle'] + ' ' + result['last'] + ', ' + 'born ' + str(result['birth']))
|
# <2021>, by ISB Institute of Data Science
# Contributors: Dr. Shruti Mantri, Gokul S Kumar and Vishal Sriram
# Faculty Mentors: Dr. Manish Gangwar and Dr. Madhu Vishwanathan
# Affiliation: Indian School of Business
# Script for removing the duplicate entries from the downloaded addresses.
import pandas as pd
import glob
import os
if __name__ == '__main__':
joint = pd.DataFrame()
length = 0
filenames = glob.glob('./data/address_by_city/*.csv')
for file in filenames:
df = pd.read_csv(file)
# Creating a new column to identify the name of the city, this makes it easier to segregate the addresses
# by cities
df['city'] = os.path.basename(file).split('.')[0]
joint = pd.concat([joint, df])
# Removing the duplicate entries based on place_id.
joint = joint.drop_duplicates(subset = 'place_id').drop(columns = ['Unnamed: 0'], axis = 1)
for city in joint['city'].unique():
df_save = joint[joint['city'] == city]
df_save.to_csv('./data/addresses/{}.csv'.format(city))
|
#!/usr/bin/python3
"""
Module Docstring
"""
__author__ = "Dinesh Tumu"
__version__ = "0.1.0"
__license__ = "MIT"
# imports
# init variables
# define basic function
def function_1():
print("Printed from function_1()\n")
def function_2():
print("Printed from function_2()\n")
def function_3():
print("Printed from function_3()\n")
# function that takes arguments
def function_4(arg1, arg2):
print (arg1, " ", arg2)
# function that returns a value
def cube(x):
return x*x*x
# function with default value for an argument
# functions with default arguments should be at the end
def power(num, x=1):
result = 1;
for i in range(x):
result = result * num
return result
# function with variable number of arguments.
# *args should always be at the end
def multi_add(*args):
result = 0;
for x in args:
result = result + x
return result
def multi_func(*args):
for item in args:
item()
def fn_kw_args(**kwargs):
if len(kwargs):
for k in kwargs:
print('{} : {}'.format(k, kwargs[k]))
else: print('Meow.')
def main():
""" Main entry point of the app """
# Executes the function
function_1()
# Executes the function and also prints 'None' as the function doesn't have any return type
print(function_1())
print()
# Prints the string representation of the function
# Functions themselves are objects that can be passed around other pieces of python code
print(function_1)
print()
# Executes the function. If there is a return type, saves it in the variable
var_0 = function_1()
print()
# The string representation of the function is stored in the variable
var_1 = function_1
var_2 = function_2
var_3 = function_3
functions_list = [function_1,function_2, function_3]
for item in functions_list:
# show the function reference
print(item)
# call the function
item()
function_4(10,20)
print (function_4(10,20))
print (cube(3))
print (power(2))
print (power(2,3))
print (power(x=3, num=2))
# args
print (multi_add(4,5,10,4))
print (multi_func(function_1, function_2, function_3))
# kwargs - KeyWordARGumentS
# ** unpacks dictionaries.
# This
# func(a=1, b=2, c=3)
# is the same as
# args = {'a': 1, 'b': 2, 'c':3}
# func(**args)
fn_kw_args(name = 'xyz', college = 'abc', course = 'qwe')
if __name__ == "__main__":
""" This is executed when run from the command line """
main()
|
#!/usr/bin/python3
import unittest
def Descending_Order(num):
num_list = []
str_num = str(num)
# To convert string into list of chars
for i in range(len(str_num)):
num_list.append(str_num[i])
# sort the list and convert it back to string
sorted_str = ''.join(sorted(num_list, reverse=True))
return int(sorted_str)
class Test(unittest.TestCase):
def test_cases(self):
self.assertEqual(Descending_Order(15),51)
self.assertEqual(Descending_Order(21445),54421)
self.assertEqual(Descending_Order(145263),654321)
self.assertEqual(Descending_Order(1254859723),9875543221)
if __name__ == "__main__":
unittest.main()
|
def choose_level():
choise = int(input("""Выберите уровень:
1 - 1-й уровень
2 - 2-й уровень
0 - Выйти"""))
if choise not in (1, 2, 0):
return None
else:
return choise
|
from tkinter import *
# Create an empty Tkinter window
window=Tk()
# def km_to_miles():
# miles=int(e1_value.get())*1.6
# t1.insert(END, (f'{miles} miles'))
def kg_converter():
# Get user value from input box
kg = int(e1_value.get())
# converts user value to various units
grams = kg*1000
pounds = kg*2.20462
ounces= kg*35.274
# Empty the Text boxes if they had text from the previous use and fill them again
t1.delete("1.0", END)
t1.insert(END, (f'{grams} grams'))
t2.delete("1.0", END)
t2.insert(END, (f'{pounds} pounds'))
t3.delete("1.0", END)
t3.insert(END, (f'{ounces} ounces'))
# Create a button widget
# The kg_converter() function is called when the button is push
b1=Button(window, text='Convert', command=kg_converter)
b1.grid(row=0, column=2)
e1_value= StringVar() # Create a special StringVar object
e1 = Entry(window, textvariable=e1_value) # Create an Entry box for user
e1.grid(row=0, column=1)
# Create a Label widget with "Input Kg" as label
l1 = Label(window, text='Input Kg')
l1.grid(row=0, column=0)
# Create three empty text boxes, t1, t2, and t3
t1=Text(window, height=1, width = 20)
t1.grid(row=1, column=0)
t2=Text(window, height=1, width = 20)
t2.grid(row=1, column=1)
t3=Text(window, height=1, width = 20)
t3.grid(row=1, column=2)
# This makes sure to keep the main window open
window.mainloop()
|
## Multiples
# Part I
for odd in range(1, 1001,2):
print odd
# Part II
for multiples in range(5, 1000001, 5):
print multiples
## Sum List
a = [1, 2, 5, 10, 255, 3]
print sum(a)
## Average List
b = [1, 2, 5, 10, 255, 3]
x= sum(b)/len(b)
print x
|
import sqlite3
con = sqlite3.connect('MFM.db')
print("Database connected....")
cur=con.cursor()
cur.execute("INSERT INTO My_Favourite_Movies(movie_name,dor,actor_name,actress_name,director_name) VALUES('3idiots',2009,'Amirkhan','Kareena Kapoor','Rajkumar Hirani')")
cur.execute("INSERT INTO My_Favourite_Movies(movie_name,dor,actor_name,actress_name,director_name) VALUES('Munna bhai MBBS',2003,'Sanja Dutt','Gracy Singh','Rajkumar Hirani')")
cur.execute("INSERT INTO My_Favourite_Movies(movie_name,dor,actor_name,actress_name,director_name) VALUES('pk',2014,'Amirkhan','Anushka Sharma','Rajkumar Hirani')")
cur.execute("INSERT INTO My_Favourite_Movies(movie_name,dor,actor_name,actress_name,director_name) VALUES('Shershaah',2021,'Sidharth Malhotra','Kiara Advani','Vishnuvardhan')")
cur.execute("INSERT INTO My_Favourite_Movies(movie_name,dor,actor_name,actress_name,director_name) VALUES('Commando 3',2019,'Vidyut Jammwal','Adah Sharma','Aditya datt')")
print("data inserted....")
print("movie_name\t ,dor\t ,actor_name\t ,actress_name\t ,director_name\n")
cursor=cur.execute("SELECT * FROM My_Favourite_Movies");
for row in cursor:
print(row[0], "\t",row[1], "\t",row[2], "\t",row[3],"\t",row[4], "\n")
con.close()
|
#!/usr/local/bin/python3
import datetime
from enum import Enum
import locale
locale.setlocale(locale.LC_ALL, '')
class Loan:
class PaymentFrequency(Enum):
monthly = 1
biweekly = 2
weekly = 3
def __init__(self, name, starting_balance, interest_rate, date_disbursed):
self.name = name
self.starting_balance = starting_balance
self.interest_rate = interest_rate
self.date_disbursed = date_disbursed
def first_due_date(today, payment_day):
if today.day <= payment_day:
due_date = datetime.date(today.year, today.month, payment_day)
elif today.day > payment_day:
if today.month == 12:
due_date = datetime.date(today.year + 1, 1, payment_day)
else:
due_date = datetime.date(today.year, today.month + 1, payment_day)
return due_date
def pay(self, payment_amount, payment_day, payment_frequency):
current_balance = self.starting_balance
current_date = self.date_disbursed
payment_due_date = Loan.first_due_date(current_date, payment_day)
total_paid = 0.0
total_interest = 0.0
total_payment_count = 0
header = self.name.upper() + ': ' + payment_frequency.name + ' payments of ' + locale.currency(payment_amount, grouping = True)
print(len(header) * '=')
print(header)
print(len(header) * '=')
print(' Balance:', locale.currency(self.starting_balance, grouping = True))
print('First payment:', payment_due_date.isoformat())
#print('Original balance:', locale.currency(self.starting_balance, grouping = True))
#print('Funding date: ', self.date_disbursed)
#print('Payment day: ', payment_day)
while current_balance > 0:
# Accumulate interest.
interest_today = current_balance * (self.interest_rate / 365)
current_balance += interest_today
total_interest += interest_today
# Make a payment if one is due today.
if current_date == payment_due_date:
if current_balance < payment_amount:
total_paid += current_balance
current_balance = 0.0
else:
current_balance -= payment_amount
total_paid += payment_amount
total_payment_count += 1
# Forward the due date.
if payment_frequency == Loan.PaymentFrequency.monthly:
if current_date.month == 12:
payment_due_date = datetime.date(current_date.year + 1, 1, payment_day)
else:
payment_due_date = datetime.date(current_date.year, current_date.month + 1, payment_day)
elif payment_frequency == Loan.PaymentFrequency.biweekly:
payment_due_date += datetime.timedelta(weeks = 2)
elif payment_frequency == Loan.PaymentFrequency.weekly:
payment_due_date += datetime.timedelta(weeks = 1)
# Print what happened.
#print(current_date.isoformat(), '==', locale.currency(current_balance, grouping = True))
# Forward the current date.
#print(current_date.isoformat(), '==', locale.currency(current_balance, grouping = True))
if current_balance > 0:
current_date += datetime.timedelta(days = 1)
print(' Last payment:', current_date.isoformat(), '(' + str(total_payment_count) + ' payments)')
print(' Duration:', "%.1f" % ((current_date - self.date_disbursed).days / 365), 'years')
print(' Total paid:', locale.currency(total_paid, grouping = True))
print('Interest paid:', locale.currency(total_interest, grouping = True), '(' + "%.2f" % ((total_interest / total_paid) * 100) + '%)')
car = Loan('New Car', 20000.0, 0.0415, datetime.date(2016, 1, 1))
car.pay(500.0, 20, Loan.PaymentFrequency.monthly)
|
def finiteMult(a, b):
aString = '{0:08b}'.format(a)
bString = '{0:08b}'.format(b)
p = 0
for x in range(0, 8):
if(bString[-1] == '1'):
p = p ^ a
b = b >> 1
carry = (aString[0] == '1')
a = (a << 1)%256
if(carry):
a = a ^ 27
aString = '{0:08b}'.format(a)
bString = '{0:08b}'.format(b)
return p
print(finiteMult(87,131))
|
num = [1, 2, 3]
print(num + [4, 5, 6])
print(num * 3)
|
i = 0
while 1==1:
print(i)
i = i + 1
if i >= 5:
print("break statement")
break
print("end")
|
#encoding: utf-8
print "\n"
print "+ FUNCIÓN REDUCE \n"
print "++ Reducir una lista a un solo elemento."
print "++ Recorre y junta elementos de par en par."
print "\n"
s = ("H", "o", "l", "a", "_", "m", "u", "n", "d", "o")
l = [1,2,3,4,5]
def concatenar(a,b):
return a+b
def suma(a,b):
return a+b
sr = reduce(concatenar,s)
sr2 = reduce(suma, l)
print type(sr)
print sr
print type(sr2)
print sr2
|
#encoding: utf-8
print "\n"
print "+ ARCHIVOS\n"
print "++ Sin pasar parámetor, por defecto, modo lectura (r)."
print "++ Escritura. Si no existe, lo crea, si no lo pisa. (w)."
print "++ Añadir, solo se puede escribir en él. Se agrega al final y debe existir. (a)."
print "++ Leer y escribir. Debe existir. (r+)."
print "\n"
try:
f = open("32_ejemplo.txt", "r+")
except:
print "Error al abrir el archivo"
else:
print f
f.close()
print f
|
#encoding: utf-8
print "\n"
print "+ FUNCIÓN FILTER \n"
print "++ Recibe una función y una lista e itera sobre cada uno de los elementos."
print "++ PYTHON 3 SE LLAMA COMPRESIÓN DE LISTAS."
print "\n"
def filtro(elem):
return (elem > 0)
def filtro2(elem):
return (elem == "o")
lista = [1,-3,2,-7,-8,10]
s = "hola mundo"
lr = filter(filtro,lista)
fs = filter(filtro2, s)
print lista
print lr
print "\n"
print s
print fs
print type(fs)
####################################
# http://www.juanjoconti.com.ar/2008/10/24/listas-por-comprension-en-python/
print "\n ##########################"
print "Más info: http://www.juanjoconti.com.ar/2008/10/24/listas-por-comprension-en-python/"
print "\n"
palabras = ['uno', 'dos', 'Santa Fe', 'Python', '...', 'Soleado']
def incluye_n(s):
return 'N' in s.upper()
print incluye_n('Python')
print incluye_n('Soleado')
sin_compresion = filter(incluye_n, palabras)
print "Sin compresión: ", sin_compresion
compresion = [p for p in palabras if incluye_n(p)]
print "Compresión: ", compresion
|
#encoding: utf-8
print "\n"
print "+ CLASES DECORADORES\n"
print "++ "
print "\n"
class Decorador(object):
"""Mi clase decoradora"""
def __init__(self, funcion):
self.funcion = funcion
def __call__(self,*args,**kwargs):
print "Functión ejecutada ", self.funcion.__name__
self.funcion(*args,**kwargs)
@Decorador
def resta(n,m):
print n-m
resta(3,5)
|
from math import sqrt
def problem10():
# based on the Sieve of Eratosthenes
numberList = [True] * 2000000
primesSum = 0
numberList[0] = numberList[1] = False
for (i, prime) in enumerate(numberList):
if prime:
primesSum += i
if i <= sqrt(2000000):
j = i * i
while j < 2000000:
numberList[j] = False
j += i
print(primesSum)
problem10()
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, cohen_kappa_score
from keras.models import Sequential
from keras.layers.core import Dense
#read in the data
white = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv", sep=';')
red = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv", sep=';')
### Pre process the data and begin creating the information for the neural network. This is where we are labeling the data (ie. hot encoding ) and joining the data. This model is based on the relu fuction. The rectified linear unit function: a linear function that will only output if positive. It is the defaul for many neural networks because the model is easier to train and often achieves beter performance.
### Tanh function is another alternative to the ReLu function and stands for the "Hyperbolic Tangent". This function outputs values between -1.0 and 1.0. Tanh is preferred over sigmmoid ###
# add a type column for red with value 1
red['type'] = 1
# add a type column for white with a value of 0
white['type'] = 0
# Append 'white' to 'red'
wine = red.append(white, ignore_index=True)
print(wine.head())
# Use the created data to come up with a machine learning model specfically using sklearn
# Specify the data
X = wine.iloc[:,0:11]
# Specify the target labels and flatten the array
y = np.ravel(wine.type)
# Split the data in train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
#Standardize the data (Some of the data shows a giant range)
#We must define the scaler with the training set
scaler = StandardScaler().fit(X_train)
#Scale the training and test set to better fit the data
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# Layer the model (more data, more layers. In this instance one layer is sufficient)
model = Sequential()
# Add input layer
model.add(Dense(12, activation='relu', input_shape=(11,)))
# Add one hidden layer
model.add(Dense(8, activation='relu'))
# Add an output layer
model.add(Dense(1, activation='sigmoid'))
### Time to summarize the model and see how the model was output ###
#Shape the model
model.output_shape
#Model summary
model.summary()
#Model Config
model.get_config()
# List all weight tensors
model.get_weights()
# Compile and fit the data
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=20, batch_size=1, verbose=1)
## Putting the model to use ##
y_pred = model.predict(X_test)
### Finally score the model and evaluate your results ###
score = model.evaluate(X_test, y_test, verbose=1)
print(score)
## This score is 0.99 or 99%... realistically this is much much higher than you would get from a typical model and in fact may be overfit to the data ##
# Confusion Matrix
## A matrix which shows the correct predictions as well as the incorrect predictions made . in a ideal situation numbers will only be displayed in the diagonal (left to right ) ##
confusion_matrix(y_test, y_pred)
# Precision score
## Precision score is the numeric representative for exactness in the model. Higher is better.
precision_score(y_test, y_pred)
# Recall
## Recall is a measure of the classifiers completeness. Higher means more cases the classifier covers.
recall_score(y_test, y_pred)
# F1 Score
## The weighted average of precision and recall
f1_score(y_test, y_pred)
# Cohen's kappa
## Classification accuracy normalized by the class imbalances in the data
cohen_kappa_score(y_test, y_pred)
|
# This is a collection of work snippets from the chapter
from typing import NoReturn, Text
from textblob import TextBlob
"""Textblob"""
text = 'Today is a beautiful day. Tomorrow looks like bad weather.'
blob = TextBlob(text)
print(blob.__dict__)
"""Tokenizing"""
# sentences feature breaks apart sentences via the period
print(blob.sentences)
# Words breaks down each word by spaces
print(blob.words)
"""Parts of Speech tagging"""
# tag each word with their word attributes like verb, noun etc...
print(blob.tags)
# Here is the index for each word (note this is just a sample, there are 63 total):
# NN is singular or mass noun`
# VBZ is third person singular verb
# DT is determiner
# JJ is adjective
# NNP is proper singular noun
# IN is a subordinating conjuction or preposition
# Full list at www.clips.uantwerpen.be/pages/MBSP-tags
# Noun phrases ; nouns vs the following/previous word
print(blob.noun_phrases)
"""Sentiment Analysis"""
# Polarity is -1 to 1 with 0 being neutral
# Subjectivities is 0 (objective) to 1 (subjective)
print(blob.sentiment)
# Can also have sentence sentiment
for sentence in blob.sentences:
print(sentence.sentiment)
# expanding on this further we can use NaiveBayes models
"""Sentiment analysis with NaiveBayesAnalyzer"""
from textblob.sentiments import NaiveBayesAnalyzer
blob = TextBlob(text, analyzer=NaiveBayesAnalyzer())
print(blob.sentiment)
# the naive bayes analyzer adds a classfication (positive, negative etc..)
# also applies to sentences
for sentence in blob.sentences:
print(sentence.sentiment)
"""Language Detection"""
print(blob.detect_language)
spanish = blob.translate(to='es')
print(spanish)
chinese = blob.translate(to='zh')
print(chinese)
print(chinese.detect_language())
"""Inflection: Pluralization and Singularization"""
from textblob import Word
# take a singular word and make it plural
index = Word('index')
print(index.pluralize())
# take a plural word and singularize it
cacti = Word('cacti')
print(cacti.singularize())
# Spellcheck also exists
word = Word('tel')
print(word.spellcheck()) #spell check matches based on % value what it could be
print(word.correct()) # correct picks the highest value in spell check
"""Normalization: Stemming and Lemmatization"""
# stemming removes prefix or suffix
word = Word('varieties')
print(word.stem())
# lemmatizing removes the prefix or suffix but ensures a word is made
print(word.lemmatize())
""" Word Frequency """
# count the frequency of words in a blob of teext
# see page 492 in Intry to python book.add()
"""Getting definitions, synonyms, antonyms"""
# Princeton has a database of words with definitions
hidden = Word('Sequestered')
print(hidden.definitions)
# Synonyms
print(hidden.synsets)
# Antonyms
lemmas = hidden.synsets[0].lemmas()
print(lemmas)
antonym= lemmas[0].antonyms()
print(antonym)
""" Using Stop words """
# we can download stopwords
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
stops= stopwords.words('english')
print([word for word in blob.words if word not in stops])
"""" n-grams """
# ngrams arfe a sequence of n text items
# the default is 3 but you can specify how many you would like
print(blob.ngrams())
print(blob.ngrams(5))
|
from __future__ import print_function
from operator import add
from pyspark.sql import SparkSession
if __name__ == "__main__":
# create a SparkSession
spark = SparkSession\
.builder\
.appName("PythonWordCount")\
.getOrCreate()
# read the input file directly in the same Swift container than the one that hosts the current script
# create a rdd that contains lines of the input file
lines = spark.read.text("wordcount.txt").rdd.map(lambda r: r[0])
# split lines, extract words and count the number of occurrences for each of them
counts = lines.flatMap(lambda x: x.split(' ')) \
.map(lambda x: (x, 1)) \
.reduceByKey(add)
# print the result
output = counts.collect()
for (word, count) in output:
print("%s: %i" % (word, count))
# very important: stop the current session
spark.stop()
|
import sqlite3
import random
### First, initialize a connection
db_name = "localEats.db"
connection = sqlite3.connect(db_name)
cur = connection.cursor()
def validTable(name):
# This function checks to make sure a user input table name is actually there
if(name=="alert" or name=="driver" or name=="menu" or name=="orders" or name=="restaurant" or name=="users"):
valid = True
else:
valid = False
return(valid)
def driver():
#This function is string formating for SQL Statements in the "driver" table
print()
query = "(" + str(random.randrange(201,999)) + ", '"
name = input("Please enter a name: ")
query = query + name + "', '"
make = input("Enter a car make: ")
query = query + make + "', '"
model = input("Enter a car model: ")
query = query + model + "', '"
license = input("Enter a license plate number (405ZX2): ")
query = query + license + "')"
return query
def alert():
#This function is string formating for SQL Statements in the "alert" table
print()
query = "(" + str(random.randrange(100301, 100900))
query = query +", '"
deliveredBy = input("Enter who delivered this order (driverID): ")
query = query + deliveredBy + "', '"
alertTime = input("Enter an alert time (13:55): ")
query = query + alertTime+ "', '"
pickupTime = input("Enter a pickup time (14:27): ")
query = query + pickupTime + "')"
return query
def menu():
# This function is string formating for SQL Statements in the "menu" table
print()
query = "(" + str(random.randrange(201,999)) + ", '"
typE = input("Enter a menu type (All Day, Breakfast, Lunch, or Dinner): ")
query = query + typE + "', "
price = input("Enter a price (7.34): ")
query = query + price + ", "
query = query + str(random.randrange(1000,9999)) + ", "
restID = input("Enter restaurantID: ")
query = query + restID +")"
print(query)
return query
def orders():
# This function is string formating for SQL Statements in the "orders" table
print()
query = "(" + str(random.randrange(100301,109999)) + ", "
ordred = input("Enter the ID of the customer who ordered this: ")
query = query + ordred + ", '"
delTime = input("Enter a delivery time (12:47): ")
query = query + delTime + "', '"
orderTime = input("Enter order time (12:34): ")
query = query + orderTime + "', "
itemID = input("Enter itemID of the item ordered(2087): ")
query = query + itemID + ", "
price = input("Enter the price of the above item: ")
query = query + price +", "
quant = input("Enter the quantity: ")
query = query + quant + ", "
extendedPrice = str(int(quant)*float(price))
query = query + extendedPrice + ", "
ful = input("Enter your restaurantID: ")
query = query + ful + ")"
return query
def restaurant():
# This function is string formating for SQL Statements in the "restaurant" table
print()
query = str(random.randrange(101,999)) + ", '"
addr = input("Enter address: ")
query = query + addr + "', '"
cat = input("Enter restaurant category: ")
query = query + cat + "', '"
name = input("Enter name: ")
query = query + name +"')"
return query
def users():
# This function is string formating for SQL Statements in the "users" table
query = "(" + str(random.randrange(201,999)) + ", '"
addr = input("Enter address: ")
query = query + addr + "', '"
name = input("Enter user name: ")
query = query + name + "')"
return query
def printTable():
# This function prints out an entire table
global connection
global cur
print("\n")
print("+-----------------------------------------+")
print("Which table would you like to see?")
print("Please enter the name of the table you wish to look at.")
choice = input("Your input: ")
valid = validTable(choice)
print()
if (valid == True):
query = "SELECT * FROM "
query = query + choice
cur.execute(query)
names = cur.description
for name in names:
print("{: <30}".format(name[0]), end="")
print()
for row in cur.fetchall():
for item in row:
if item != None:
print("{: <30}".format(item), end="")
else:
print("{: ,30}".format("None"), end="")
print()
print()
else:
print()
print("Invalid table name. Exiting to main menu...")
print()
def insert():
# This function allows the user to insert into any valid table
global connection
global cur
print()
table = input("Enter the table you want to insert into: ")
valid = validTable(table)
if (valid == True):
query = "INSERT INTO " + table
if (table == "alert"):
q2 = alert()
query = query + "('orderID', 'deliveredBy', 'alertTime', 'pickupTime') VALUES " +q2 + "; "
elif (table == "driver"):
q2 = driver()
query = query + "('ID', 'name', 'carMake', 'carModel', 'license') VALUES " +q2 + "; "
elif (table == "menu"):
q2 = menu()
query = query + "('menuID', 'type', 'price', 'itemID', 'restaurantID') VALUES " +q2 + "; "
elif (table == "orders"):
q2 = orders()
query = query + "('orderID', 'orderedBy', 'delieveryTime', 'orderTime', 'itemID', 'price', 'quantity', 'extendedPrice', 'fulfilledBy') VALUES " + q2 + "; "
elif (table == "restaurant"):
q2 = restaurant()
query = query + "('ID', 'address', 'category', 'name') VALUES (" + q2 + "; "
elif (table == "users"):
q2 = users()
query = query + "('ID', 'address', 'name') VALUES " + q2 + "; "
try:
cur.execute(query)
except sqlite3.OperationalError as e:
print(e)
else:
print()
print("Invalid table name. Exiting to main menu...")
print()
connection.commit()
print()
print("Insertion committed")
print()
def deletion():
# this function allows the user to delete from any valid table
global connection
global cur
print()
table = input("Enter the table you want to delete from: ")
valid = validTable(table)
if (valid == True):
query = "DELETE FROM " + table + " WHERE "
where = input("Enter a WHERE clause argument(s): ")
query = query + where
cur.execute(query)
else:
print()
print("Invalid table name. Exiting to main menu...")
print()
connection.commit()
print()
print("Deletion committed")
print()
def update():
# This function allows the user to update any valid database
global connection
global cur
print()
table = input("Enter a table you want to update: ")
valid = validTable(table)
if (valid == True):
query = "UPDATE " + table
setClause = input("Enter a SET clause argument(s): ")
query = query + " SET " + setClause + " WHERE "
where = input("Enter a WHERE clause argument(s): ")
query = query + where
cur.execute(query)
else:
print()
print("Bad input, kicking you back to main menu...")
print()
connection.commit()
print()
print("Update committed")
print()
def customSQL():
# This function allows for more personalization of a report for a user
global connection
global cur
print()
print("Please enter an SQL Command")
query = input("Enter command here: ")
try:
cur.execute(query)
except sqlite3.OperationalError as e:
print(e)
results = cur.fetchall()
print()
names = cur.description
for name in names:
print("{: <30}".format(name[0]), end="")
print()
for row in results:
for item in row:
print("{: <30}".format(item), end="")
print()
print()
def topTen():
# This function has a hard coded SQL query that gets the top 10 most popular restaurants
global connection
global cur
print()
print("Here are the top 10 most popular restaurants")
print()
query = "SELECT COUNT(orders.fulfilledBy) AS orderCount, restaurant.name AS restaurantName FROM orders, restaurant WHERE orders.fulfilledBy = restaurant.ID GROUP BY orders.fulfilledBy ORDER BY orderCount DESC LIMIT 10 "
cur.execute(query)
results = cur.fetchall()
print()
# Print out results
names = cur.description
for name in names:
print("{: <30}".format(name[0]), end="")
print()
for row in results:
for item in row:
print("{: <30}".format(item), end="")
print()
print()
def joinSQL():
# This function has a set SQL statement for a statistics option in the menu. It reports all users who have an account but have not ordered anything.
# Please note: This is used as our "join feature" however, SQL Lite does not have ANTI JOIN needed to complete this query so a work around has been found.
global connection
global cur
print()
print("Here are all the users who have an account, but have not ordered anything")
print()
# ANTI JOIN is not supported by SQL Lite, so NOT IN has been used to do the same thing.
query = "SELECT users.ID AS customerID, users.name AS customerName FROM users WHERE users.ID NOT IN (SELECT orders.orderedBy FROM orders) "
cur.execute(query)
results = cur.fetchall()
print()
names = cur.description
# Print out results
for name in names:
print("{: <30}".format(name[0]), end="")
print()
for row in results:
for item in row:
print("{: <30}".format(item), end="")
print()
print()
def mostPop():
#This function has a set SQL statement to generate a report of the top 10 most popular restaurnt categories in the database.
global connection
global cur
print()
print("Here are the top 10 most popular restaurant categories")
print()
query = "SELECT COUNT(orders.fulfilledBy) as orderCount, restaurant.category FROM orders, restaurant WHERE orders.fulfilledBy = restaurant.ID GROUP BY restaurant.category ORDER BY orderCount DESC LIMIT 10 "
cur.execute(query)
results = cur.fetchall()
print()
names = cur.description
#Print out the results
for name in names:
print("{: <30}".format(name[0]), end="")
print()
for row in results:
for item in row:
print("{: <30}".format(item), end="")
print()
print()
def statsMenu():
# This functions as the statistics menu
print()
print("+-----------------------------------------+")
print("This is the statistics menu!")
print("Enter 1 for the top 10 restaurants that fulfilled the most orders")
print("Enter 2 to look at all the users that have an account, but have not ordered anything")
print("Enter 3 to look at the top 10 most popular restaurant categories")
print("Enter 4 to enter a custom SQL query")
print("+-----------------------------------------+")
choice = int(input("Your Choice: "))
#Go through user choice
if (choice ==1):
topTen()
elif(choice ==2):
joinSQL()
elif(choice ==3):
mostPop()
elif(choice ==4):
customSQL()
print()
def main():
# --------------- Main ---------------
# This functions as the main menu for interaction
global connection
global cur
print()
print("+-----------------------------------------+")
print("Welcome to the LocalEats Database!")
print("What would you like to do today?")
print("+-----------------------------------------+")
print()
choice = 1
while choice > 0:
print("+-----------------------------------------+")
print("Main Menu: ")
print("Enter 0 to exit")
print("Enter 1 to print out a table")
print("Enter 2 to insert/delete/update into a table")
print("Enter 3 to enter a custom SQL command")
print("Enter 4 to go to the statistics menu")
print("+-----------------------------------------+")
choice = int(input("Your input: "))
#Go through user choice
if (choice == 1):
printTable()
elif (choice == 2):
valid = True
while (valid == True):
print()
num = int(input("Enter 1 for insert, 2 for delete, and 3 for update: "))
if (num ==1):
insert()
valid = False
elif (num ==2):
deletion()
valid = False
elif (num == 3):
update()
valid = False
elif (choice == 3):
customSQL()
elif (choice ==4):
statsMenu()
print()
print("Exiting...")
main()
# Save our changes and then close
# connection.rollback() # this will undo any changes since the last commit
connection.commit()
connection.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.