text
stringlengths 37
1.41M
|
---|
from PIL import Image, ImageFilter
class Canvas(object):
""" The primary class which holds all of the different elements that are going into building
the diagram """
def __init__(self, width=400, height=400, backgroundcolor=(0,0,0,0)):
""" Initializes a blank canvas, with a specified width and height (defaults to 400x400), and
a background color (default transparent)"""
self.__canvas = Image.new("RGBA", (width, height), backgroundcolor)
self.__bg = backgroundcolor
self.__elements = [] # Stores Icon objects
self.__position = [] # Stores tuples : (leftOffset, topOffset)
self.__connections = [] # Stores connections between elements : ( 1, 3)
def addElement(self, element, leftOffset, topOffset):
""" Function for adding Icons/Text/Canvases to the canvas for future rendering """
self.__elements.append(element)
self.__position.append((leftOffset, topOffset))
def createConnection(self, elInd1, elInd2):
def Render(self, outputname="out.png"):
""" Renders the Canvas object as an image for use """
for i, el in enumerate(self.__elements):
self.__canvas.paste(el.image, self.__position[i])
# Checks to make sure there is no transparency:
if self.__bg == (0,0,0,0):
self.__canvas = self.__canvas.filter(ImageFilter.SMOOTH)
self.__canvas.save(outputname)
return
i = self.__canvas.convert("RGBA")
data = i.getdata()
newData = []
for val in data:
if val[3] == 0:
newData.append(self.__bg)
else:
newData.append(val)
i.putdata(newData)
i = i.filter(ImageFilter.SMOOTH_MORE)
i = i.filter(ImageFilter.EDGE_ENHANCE)
i.save(outputname)
|
#Global Variable Definitions
prec = 10**-12
def cmplxConj(num):
return complex(num.real,-1*num.imag)
def printRoot(root):
print("Roots are as follows")
for i in range (len(root)):
print("x - [" + str(root[i]) + "]")
print("Done")
def roundComplex (val):
if abs(round(val.imag) - val.imag) < 10**-8: #Round Imaginary
val = complex(val.real, round(val.imag))
if abs(round(val.real) - val.real) < 10**-8: #Round Real
val = complex(round(val.real), val.imag)
if val.imag == 0:
val = val.real
#val = complex(round(val.real,5),round(val.imag,5))
return val
def printFunc(function):
#Initial Setup
order = len(function)-1
func = ""
if function[0] < 0:
func += "-"
#Building term by term
try:
for cnt in range (0,order):
func += str(abs(function[cnt]))+"x^"+str(order-cnt)
if function[cnt+1] >= 0: #Figure out how to use ternary operator?
func += " + "
else:
func += " - "
except TypeError: #For accounting for Integral + C addition
print("Printing an Integral")
func += " + C"
print(func)
return
#Ending & Printing
func += str(abs(function[order]))#Adding entry with no x
print(func)
def computeFunc (function, value):
#Setup
ans = 0
order = len(function)-1
#Computing Values
for cnt in range (0, order+1):
if function[cnt] != None:
val = function[cnt] * (value ** (order-cnt))
ans += val
return ans
def makeFunc ():
correct = True
while correct:
#Initial Setup
function = []
order = -5
#Getting Size
while order < 0:
order = int(input("Please enter the highest order\n"))
#Creating list to model function
for cnt in range (order,-1,-1):
a = float(input("Please enter coefficient for power " + str(cnt)+ "\n"))
function.append(a)
#Printing Values
printFunc(function)
#Check
ans = input("Is this accurate? Y?N\n")
if ans == "Y" or ans == "y":
correct = False
return function #Shouldn't function not exist anymore???
def computeDerivative (function):
#Initial Setup
order = len(function)-1
derivative = []
#Base Cases
if order == 0:
derivative.append(0)
elif order == 1:
derivative.append(function[0])
#Build Derivative List
else:
for cnt in range (0, order+1):
entry = function[cnt] * (order - cnt)
derivative.append(entry)
derivative.pop(order)#Clear last entry b/c x^0 term becomes 0
#Print Values
return derivative
def computeIntegral (function):
#Initial Setup
order = len(function)-1
integral = []
#Base Cases
if order == 0 and function[0] != 0:
integral.append(function[0])
#Build Integral List
else:
for cnt in range (0, order+1):
entry = function[cnt] / (order - cnt + 1)
integral.append(entry)
integral.append('c')
printFunc(integral)
integral[integral.index('c')] = 0
return integral
def factorLinear (function, root):
#only 1 case
val = -1 * function[1]/function[0]
if abs(val) == 0:#Addressing case of y = x where root = -0.0
val = 0.0
root.append(val)
return root
def factorQuad (function, root):
#Initial Calculations
discr = (function[1]**2) - (4 * function[0] * function[2])
twoA = 2.0*function[0]
#Evaluations
if discr >= 0:
root.append(((-1*function[1])+ (discr**0.5))/twoA)
root.append(((-1*function[1])- (discr**0.5))/twoA)
#Will be the same root if discriminant == 0
else: #If discriminant < 0, complex roots
real = (-1*function[1])/twoA
imaginary = abs(((abs(discr))**0.5)/twoA)
root.append(roundComplex(complex(real,imaginary)))
root.append(roundComplex(complex(real, -1*imaginary)))
return root
def newtMethod (function,derivative,start):
#Base Case
if derivative == 0: #If function is a horizontal line
return "no_root" #Shouldnt ever get here though
if computeFunc(function, 0) == 0: #Initial guess of 0
return 0
#Setup
x = start
derivVal = computeFunc(derivative, x)
while derivVal == 0: #Ensuring initial guess is valid
x, y = [float(x) for x in input("Enter 2 numbers seperated by white space\n").split()]
derivVal = computeFunc(derivative,complex(x,y))
#Setting & Printing Initial Values
delta = 1
cnt = 0
maxCnt = 1000
#Computing Final Root
while (delta > prec) and (cnt <= maxCnt):
funcVal = computeFunc(function,x)
derivVal = computeFunc(derivative,x)
val = x - (funcVal/derivVal)
cnt += 1
delta = abs(x - val)
x = val
if (delta > prec) and (cnt > maxCnt):
if start == complex(10,10):
print("FAILED")
return "FAILED"
return newtMethod(function,derivative,complex(10,10))
#Adjusting Complex Numbers, or switching to real where appropriate
x = roundComplex(x)
return x
def synthDivide(function, root):
#Initial Setup
newFunction = [function[0]]
order = len(function)-1
#Creating simplified function
for cnt in range (1, order):
val = roundComplex((root * newFunction[cnt-1]) + function[cnt])
newFunction.append(val)
return newFunction
def solveFunc (): #Function to quickly enter and test a function
printRoot (factor (makeFunc(), []))
def factor (function, root):
#Initial Setup
order = len(function)-1
index = next((i for i, x in enumerate(function) if x != 0), None)#look for first nonzero int
if index == None:
print("Function is all zeroes")
return None
#Base Cases
if order - index == 0:#Index to account for extra 0'd terms @ front
#print("Function is now scalar")
return root
elif order - index == 1:
#print("Function is now linear")
return factorLinear(function[order-1:], root)
elif order - index == 2:
#print("Function is now quadratic")
return factorQuad(function[order-2:], root)
#General Cases
derivative = computeDerivative(function)
root1 = newtMethod(function,derivative,complex(10,-10))
if root1 == "FAILED":
root.append(root1)
return root
if root1.imag == 0: #Single real root
root.append(root1)
function = synthDivide (function, root[-1])
else: #2 complex roots
root2 = cmplxConj(root1)
root.append(root1)
root.append(root2)
function = synthDivide(function, root1)
function = synthDivide(function, root2)
return factor(function, root)
|
"""
Solution to
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""
def fib(limit):
res = []
a, b, c = 1, 0, 1
while True:
a, b = b, c
c = a + b
if c > limit:
break
res.append(c)
return res
sol = sum([f for f in fib(4_000_000) if f % 2 == 0])
print(sol)
|
"""
Solution to
Champernowne's constant
Problem 40
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
"""
def champernowne_constant(limit):
res = ""
for i in range(1_000_000):
res += str(i)
if len(res) >= limit:
return res
def prod(arr):
res = 1
for item in arr:
res *= item
return res
const = champernowne_constant(1_000_001)
sol = prod([int(const[10 ** x]) for x in range(7)])
print(sol)
|
"""
Solution to
Sum square difference
Problem 6
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
sol = (sum(range(1, 101)) ** 2) - sum([x * x for x in range(1, 101)])
print(sol)
|
"""
Solution to
Circular primes
Problem 35
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
"""
def sieve(limit):
primes = [True for x in range(limit)]
primes[0] = primes[1] = False
res = []
for i in range(2, limit):
if primes[i]:
res.append(i)
for j in range(i * i, limit, i):
primes[j] = False
return res
prime_list = sieve(1_000_001)
def is_prime(n):
return n in prime_list
def rotate_left(arr, n):
n = n % len(arr)
return arr[n:] + arr[:n]
def to_digits(n):
return [int(x) for x in str(n)]
def from_digits(n):
return int("".join([str(x) for x in n]))
def is_circular_prime(n):
n_digits = to_digits(n)
if n > 10 and len(set([0, 2, 4, 5, 6, 8]).intersection(n_digits)) > 0:
return False
for i in range(len(str(n))):
if not is_prime(from_digits(rotate_left(n_digits, i))):
return False
return True
sol = len([x for x in range(2, 1_000_001) if is_circular_prime(x)])
print(sol)
|
"""
Solution to
10001st prime
Problem 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
def sieve(limit):
primes = [True for x in range(limit)]
primes[0] = primes[1] = False
res = []
for i in range(2, limit):
if primes[i]:
res.append(i)
for j in range(i * i, limit, i):
primes[j] = False
return res
sol = sieve(200_000)[10_001 - 1]
print(sol)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 4 15:29:26 2019
@author: paul
"""
class Tree:
def __init__(self, tree_list):
node_list = []
for i in range(len(tree_list)):
if tree_list[i]:
node = TreeNode(tree_list[i])
node_list.append(node)
if i==0:
continue
if (i-1) % 2 ==0:
node_list[int((i-1)/2)].left = node
else:
node_list[int((i-2)/2)].right = node
if node_list:
self.root = node_list[0]
else:
self.root = None
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxthrough(self,node):
if not node:
return 0
left_sum = max(self.maxthrough(node.left),0)
right_sum = max(self.maxthrough(node.right),0)
self.res = max(node.val+left_sum+right_sum, self.res)
return max(left_sum, right_sum)+node.val
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = float('-inf')
self.maxthrough(root)
return self.res
if __name__ == "__main__":
num_list = [-10,9,20,None,None,15,7]
tree = Tree(num_list)
sol = Solution()
print(sol.maxPathSum(tree.root)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 14:46:19 2019
@author: paul
"""
class Solution:
def searchMatrix(self, matrix, target):
if not matrix:
return False
if not matrix[0]:
return False
low = 0
high = len(matrix)-1
while low+1<high:
mid = int((low+high)/2)
if matrix[mid][0]<target:
low = mid
elif matrix[mid][0]>target:
high = mid-1
else:
return True
if matrix[high][-1]<target:
return False
elif matrix[high][0]<=target:
row = high
elif matrix[low][0]<=target:
row = low
else:
return False
low = 0
high = len(matrix[0])-1
while low<high:
mid = int((low+high)/2)
if matrix[row][mid]<target:
low = mid+1
elif matrix[row][mid]>target:
high = mid-1
else:
return True
if matrix[row][low]==target:
return True
return False
if __name__ == "__main__":
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]
target = 3
sol = Solution()
print(sol.searchMatrix(matrix,target)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 15:14:15 2019
@author: paul
"""
class Solution:
def findMin(self, nums):
if len(nums)==1:
return nums[0]
low = 0
high = len(nums)-1
while True:
mid = int((low+high)/2)
if nums[mid]<nums[mid-1]:
return nums[mid]
if low==len(nums)-1:
return nums[0]
if nums[mid]<nums[0]:
high = mid-1
else:
low = mid+1
if __name__ == "__main__":
nums = [3,4,5,1,2]
sol = Solution()
print(sol.findMin(nums))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 13:34:28 2019
@author: paul
"""
class Solution:
def findMinHeightTrees(self, n, edges):
###Try BFS from the leaves
adj = {}
for i in range(n):
adj[i] = {}
for i,j in edges:
adj[i][j] = 1
adj[j][i] = 1
sign = {}
leaves = [i for i in range(n) if len(adj[i])==1]
while True:
for i in leaves:
sign[i] = 1
if len(sign)==n:
return leaves
for i in leaves:
tmp_list = list(adj[i].keys())
for j in tmp_list:
del adj[i][j]
del adj[j][i]
if len(sign)==n-1:
return [i for i in range(n) if sign.get(i,0)==0]
leaves = [i for i in range(n) if len(adj[i])==1]
if __name__ == "__main__":
n = 7
edges = [[0,1],[1,2],[1,3],[2,4],[3,5],[4,6]]
sol = Solution()
print(sol.findMinHeightTrees(n, edges)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 18:53:30 2019
@author: paul
"""
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
self.count = 0
self.dfs(s, p)
return self.count>0
def dfs(self, s, p):
if len(s)==0 and len(p)==0:
self.count+=1
return True
if len(s)!=0 and len(p)==0:
return
if len(s)==0 and p[-1]!='*':
return
if p[-1]=='*':
for i in range(len(s)):
if s[-i-1]==p[-2] or p[-2]=='.':
if self.dfs(s[:-i-1], p[:-2]):
return True
else:
break
if self.dfs(s, p[:-2]):
return True
elif p[-1]=='.' or p[-1]==s[-1]:
if self.dfs(s[:-1], p[:-1]):
return True
if __name__ == "__main__":
sol = Solution()
s = "aaaaaaaaaaaaab"
p = "a*a*a*a*a*a*a*a*a*a*a*a*b"
print(sol.isMatch(s, p)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 16:55:32 2019
@author: paul
"""
import heapq
class Heap:
def __init__(self, k):
self.k = k
self.list = []
def add(self, t):
if len(self.list)<self.k:
heapq.heappush(self.list, t)
elif self.list[0]<t:
heapq.heappop(self.list)
heapq.heappush(self.list, t)
def peek(self):
return self.list[0]
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
heap = Heap(k)
for num in nums:
heap.add(num)
return heap.peek()
if __name__ == "__main__":
nums = [3,2,1,5,6,4]
k = 2
sol = Solution()
print(sol.findKthLargest(nums, k)) |
def frab(n):
if n<1:
return None
lastNum=2
secondLastNum=1
for x in range(n-2):
tmpResult=lastNum+secondLastNum
secondLastNum=lastNum
lastNum=tmpResult
return lastNum
print(frab(1))
[] sum
|
"""
********************************Space Platfrom Game***********************************
Main game program
=================
Done
=====
screen created = Salvador 2/27/2021
Game loop created = Salvador 2/27/2021
Game exit event = Salvador 2/27/2021
still needs work
================
1
"""
import pygame
from Animate import Animate
#import world data
import World_1
#import player class
import Player
#import enemy class
#import Enemy
pygame.init()
#inter game clock and frame per sec setup
clock = pygame.time.Clock()
fps = 60
#set screen sizes and create screen
screen_width = 1000
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
#Set tile size for game. Will be used to setup floor, item, and enemy positions
tile_size = 50
#create player object and image. Also rezises player image, and position it inside the screen
Player1R = Animate('playerImgs', 'R', 4, 'png', False, tile_size)
Player1L = Animate('playerImgs', 'R', 4, 'png', True, tile_size)
Player1RNew = Animate('playerImgs2', 'G', 4, 'png', False, tile_size)
Player1LNew = Animate('playerImgs2', 'G', 4, 'png', True, tile_size)
Player1 = Player.Player(screen, Player1R, Player1L, 0, 450)
#load player image files for animation
"""
#function draws grid on screen
#NOT PART OF THE GAME. HELP TO LAYOUT THE PLATFORM
def draw_grid():
for line in range(0, 20):
pygame.draw.line(screen, (255, 255, 255), (0, line * tile_size), (screen_width, line * tile_size))
pygame.draw.line(screen, (255, 255, 255), (line * tile_size, 0), (line * tile_size, screen_height))
"""
#WORLD AND LEVEL CREATION
#*******************************************
#CREATE LEVEL ONE
#CREATE LEVEL ONE
Level_1 = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
#call world to create levels
world = World_1.World_1(Level_1, tile_size, screen)
#*******************************************
#GAME LOOP CONTROL AND JUMPING CONDITIONAL
KeepGoing = True
jumped = False
PlayerRect = Player1.rect
#GAME LOOP
#*******************************************************@
while KeepGoing:
#set frame per sec inside game loop
clock.tick(fps)
#DRAW SECTION
#==============================================
#Draw tile on screen
world.draw()
#Draws the grid---NOT PART OF THE GAME
#draw_grid()
#=============================================
for event in pygame.event.get():
#closes window/game
if event.type == pygame.QUIT:
KeepGoing = False
#GAME CONTROLS
#=============================================
key = pygame.key.get_pressed()
if key[pygame.K_SPACE] and jumped == False:
Player1.Player_Jump()
jumped = True
if key[pygame.K_SPACE] == False:
jumped = False
Player1.Player_Gravity()
if key[pygame.K_LEFT]:
Player1.Player_Left()
if key[pygame.K_RIGHT]:
Player1.Player_Right()
#=============================================
#Check for collision between player and game blocks
#need to get tile list from world_1 class to do collision checks
for tile in world.tile_list:
#check for collision in the Y direction
if tile[1].colliderect(Player1.rect):
#print("collision")
#check if below the ground
if Player1.rect.bottom > tile[1].top:
#print("tile top: "+str(tile[1].top))
#print("Player rect Y: "+str(Player1.rect.y))
Player1.rect.y = tile[1].top - 50
#print("Bottom player collision")
elif Player1.rect.top <= tile[1].bottom:
#print("TOP player collision")
Player1.jump = 0
Player1.rect.top += 50
#print("tile bottom: "+str(tile[1].bottom))
#print("Player rect Y: "+str(Player1.rect.y))
#check if above the ground
#if Player1.jump >= 0:
# Player1.rect.y = tile[1].top - Player1.rect.bottom
# print("Top player collision")
#Draw player on screen and updates player coordinates
Player1.draw()
pygame.display.update()
pygame.quit()
#*******************************************************@
|
import math
import random
from objective import *
from utils import *
def simulated_annealing(photos, SA_temp, SA_min_temp, SA_cool_rate, SA_it_per_temp):
import time
start_time = time.process_time()
s = generate_slides(photos) #generate slides, sorted by horizontal and then vertical
solution = organize_slides(s)
score = ObjectiveFunction(solution)
temp = SA_temp
initial_temp = temp
temp_min = SA_min_temp
cooling_rate = SA_cool_rate
itPerTemp = SA_it_per_temp
while temp > temp_min:
it = 0
while it < itPerTemp:
new_solution = addOperator(solution)
new_score = ObjectiveFunction(new_solution) #para dar positivo
if new_score >= score: #so > diminui mt o nr de pontos,
solution = new_solution
score = new_score
else:
accProbability = acceptanceProbability(score, new_score, temp)
if accProbability > random.random():
solution = new_solution
score = new_score
print(score)
it = it + 1
temp = temp-cooling_rate
print("--------------------")
print("Simulated Annealing")
print(" ")
print("Score: ", score)
print("With ", initial_temp, " of temperature and ", cooling_rate, " of cooling rate")
time = time.process_time() - start_time
print("In %.3f seconds of processor time" % time)
return new_solution
def acceptanceProbability(score, new_score, temp):
loss = abs(new_score-score)
return math.exp(-(loss/temp))
def addRandomOperator(slides):
#For example, in the travelling salesman problem each state is typically defined as a
# permutation of the cities to be visited, and its neighbours are the set of permutations
# produced by reversing the order of any two successive cities.
# A new solution is generated by inverting the "place" of two successive images
length = len(slides)-1-1 #[0,length-1] -> nao seleciona o ultimo
idx = random.randrange(0, length)
swapPositions(slides, idx, idx+1)
return slides
def addOperator(slides):
copy = slides.copy()
length = len(copy)-1-1 #para nao apanhar o ultimo >>> por causa do swap
idx = random.randrange(0, length)
s = copy[idx]
score = 0
i = len(copy)-1
for s1 in reversed(copy):
new_score = s.interest(s1)
if new_score > score:
new_i = i
score = new_score
i = i-1
swapPositions(copy, new_i, idx+1)
return copy
def swapPositions(slides, pos1, pos2):
slides[pos1], slides[pos2] = slides[pos2], slides[pos1]
return slides
def organize_slides(slides):
sol = sorted(slides, key=lambda x: x.getNrTags(), reverse=True) #ordenar por ordem crescente de nr de tags
return sol |
# 垃圾回收机制
class ClassA():
def __init__(self):
print('object born,id:%s'%str(hex(id(self))))
def __del__(self):
print('object del,id:%s'%str(hex(id(self))))
#
#
# def f2():
# while True:
# c1=ClassA()
# c2=ClassA()
# c1.t=c2
# c2.t=c1
# del c1
# del c2
#
#
# if __name__ == '__main__':
# f2()
import gc
import time
def f3():
# print gc.collect()
c1=ClassA()
c2=ClassA()
c1.t=c2
c2.t=c1
del c1
del c2
print('garbage>>',gc.garbage)
print('collect>>',gc.collect()) #显式执行垃圾回收
print('garbage>>',gc.garbage)
time.sleep(10)
if __name__ == '__main__':
gc.set_debug(gc.DEBUG_LEAK) #设置gc模块的日志
f3() |
#-----------Clase Premio------------
class Premio:
#Se define el tipo de premio y el valor acumulado
def __init__(self, tipo):
self.tipo = tipo
self.acumulado = 0
def acumular(self, valor):
self.acumulado += valor |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: lifangcheng <[email protected]>
list1 = [1, 3, 2, 6, 7, 3, 4]
list2 = [9, 4, 5, 7, 3, 6, 1]
list1 = set(list1)
list2 = set(list2)
print(list1, list2)
print(list1 & list2) # 并集
print(list1 | list2) # 交集
print(list1 - list2) # 差集(项在 list1中,但不在 list2中)
print(list1 ^ lists2) # 对称差集(项在 list1 或 list2中, 但不会同时出现在二者中)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: lifangcheng
# 错误尝试达到3次后,询问是否继续,只要输入的不是 N 或者 n 就可以继续。
age_of_lfc = 26
count = 0
while count < 3:
guess_age = int(input("guess a age:"))
if guess_age == age_of_lfc:
print("right.")
break
elif guess_age > age_of_lfc:
print("old.")
else:
print("young.")
count = count +1
if count == 3:
go_on = input("do you want go on ?")
if go_on != 'n' and go_on != 'N':
count = 0
|
class Point(object):
def __init__(self,x,y):
self.x = x
self.y = y
def distance(self, other_point):
dis = (self.x – other.x)**2 + (self.y – other.y) ** 2
return genhao(dis)
a = Point(3,4)
b = Point(4,5)
dis = a.distance(b)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: lifangcheng <[email protected]>
'''
str 字符串的常用操作
'''
name = "my name is lifangcheng"
print(name.capitalize()) # 首字母大写
print(name.count('n')) # 统计一个字符串内有多少个字母或者其他信息
print(name.center(50, '-')) # 打印50个'-', 把变量 name 的信息放在横杠的中间
print(name.endswith('eng')) # 判断一个字符串是不是以某些字符结尾
print(name.find('name')) # 取出切片的值
'''
字符串格式化
name1 = 'my name is {name} and i am {year} old'
print(name.format(name='lifangcheng', year=26))
print(name.format_map( {'name':'alex', 'year':12}) # str.format_map 字典的方式 format
'''
print('abc123'.isalnum()) # 检查字符串内是否包括特殊字符, 如果不包括返回 True
print('abc123!#$%'.isalnum())
print(name.isdigit()) # 判断字符串内容是否是一个整数
print(name.isidentifier()) # 判断是不是一个合法的标识符(合法的变量名)
print(' '.isspace()) # 判断字符串内容是否是空格
print(''.join(['1', '2', '3', 'abc', 'bbc'])) # 把列表转成字符串
print('+'.join(['1', '2', '3', 'abc', 'bbc'])) # 每个字符串中间加一个区分的自定义符号
print(name.ljust(50, '*')) # 字符串长度50,如果长度不够,在结尾用*号补齐, 长度和补齐的符号可以自定义
print(name.rjust(50, '-')) # 与 ljust 相反,这个补齐在开头, 长度和补齐的符号可以自定义
print('Reckful'.lower()) # 字符串里的所有字母变小写
print('Reckful'.upper()) # 字符串里的所有字母变大写
print('\nReckful'.lstrip()) # 去掉最左边的空格或者回车
print('\nReckful'.rstrip()) # 去掉最右边的空格或者回车
print('\nReckful\n'.strip()) # 去掉两边的空格或者回车
print('Reckful'.replace('f', 'F', 1)) # 把字符串内的字符替换成指定字符, 如果只想替换一个, 后面写上具体数字
print('my name is lfc'.split(' ')) # 把字符串按照指定字符分割成一个列表,可以用空格为分隔符
print('1+2+3+4+5'.split('+')) # 以加号为分隔符, 做为分隔符的字符会被删掉,所以这样可以直接把数字提取出来
print('1+2\n+3+4'.splitlines()) # 按照换行符去分割,转化为列表
print('LiFangCheng'.swapcase()) # 大写变小写, 小写变大写
print('li fang cheng'.title()) # 把每一个字符的首字母变成大写
|
from graphics import *
'''
# create a window with width = 700 and height = 500
win = GraphWin('Program Name', 700, 500)
tri = Polygon(Point(0,500),Point(350,0), Point(700,500))
tri.setFill('yellow')
tri.draw(win)
win.mainloop() '''
def Sierpinski(level,point_b,point_a,point_c):
colors=['yellow','green','blue','red','orange','purple','white','black','pink']
tri = Polygon(point_b,point_a,point_c)
l=level
#for i in range(len(colors)):
tri.setFill(colors[level%len(colors)])
tri.draw(win)
b_x=(point_c.x+point_b.x)/2.0
b_y=point_b.y
a_x=(point_a.x+point_b.x)/2.0
a_y=(point_b.y+point_a.y)/2.0
c_x=(point_c.x-point_a.x)/2.0+point_a.x
c_y=(point_c.y+point_a.y)/2.0
'''
b1_x=( b_x-point_b.x)/2.0
b1_y=(point_b.y)
a1_x=(b_x-point_b.x)/2.0
a1_y=(point_b.y-b_y)/2.0
c1_x=(b_x-a_x)/2
c1_y=(b_y-a_y)/2
tri = Polygon(Point(b_x,b_y),Point(a_x,a_y),Point(c_x,c_y))
print Point(b_x,b_y),Point(a_x,a_y),Point(c_x,c_y)
tri.setFill('black')
tri.draw(win)
tri = Polygon(Point(b1_x,b1_y),Point(a1_x,a1_y),Point(c1_x,c1_y))
print Point(b1_x,b1_y),Point(a1_x,a1_y),Point(c1_x,c1_y)
tri.setFill('black')
tri.draw(win)'''
for i in range(1,level):
Sierpinski(i,point_b,Point(a_x,a_y),Point(b_x,b_y))
Sierpinski(i,Point(a_x,a_y),point_a,Point(c_x,c_y))
Sierpinski(i,Point(b_x,b_y),Point(c_x,c_y),point_c)
#def half(point):
win = GraphWin('Program Name', 700, 500)
Sierpinski(50,Point(0,500),Point(350,0), Point(700,500))
win.mainloop()
|
# Multiplication and Exponent Table
#welcome message
print("Welcome to the Multiplication/Exponent Table App")
#Get the name and the number
name = input("\nHello, What is your name:\t\t")
number = float(input("What number would you like to work with:\t"))
#Multiplication
print("\nMultiplication Table For "+str(number))
b = number
print("\n\t"+str(1.0)+" * "+str(b)+" = "+str(1.0*b))
print("\t"+str(2.0)+" * "+str(b)+" = "+str(2.0*b))
print("\t"+str(3.0)+" * "+str(b)+" = "+str(3.0*b))
print("\t"+str(4.0)+" * "+str(b)+" = "+str(4.0*b))
print("\t"+str(5.0)+" * "+str(b)+" = "+str(5.0*b))
print("\t"+str(6.0)+" * "+str(b)+" = "+str(6.0*b))
print("\t"+str(7.0)+" * "+str(b)+" = "+str(7.0*b))
print("\t"+str(8.0)+" * "+str(b)+" = "+str(8.0*b))
print("\t"+str(9.0)+" * "+str(b)+" = "+str(9.0*b))
print("\t"+str(10.)+" * "+str(b)+" = "+str(10.0*b))
#Exponent Table
print("\nExponent Table For "+ str(number))
print("\n\t"+str(b)+" ** "+str(1.0)+" = "+str(round((b**1.0),4)))
print("\t"+str(b)+" ** "+str(2.0)+" = "+str(round((b**2.0),4)))
print("\t"+str(b)+" ** "+str(3.0)+" = "+str(round((b**3.0),4)))
print("\t"+str(b)+" ** "+str(4.0)+" = "+str(round((b**4.0),4)))
print("\t"+str(b)+" ** "+str(5.0)+" = "+str(round((b**5.0),4)))
print("\t"+str(b)+" ** "+str(6.0)+" = "+str(round((b**6.0),4)))
print("\t"+str(b)+" ** "+str(7.0)+" = "+str(round((b**7.0),4)))
print("\t"+str(b)+" ** "+str(8.0)+" = "+str(round((b**8.0),4)))
print("\t"+str(b)+" ** "+str(9.0)+" = "+str(round((b**9.0),4)))
print("\t"+str(b)+" ** "+str(10.0)+" = "+str(round((b**10.0),4)))
#print fun statement
statement = name + " Math is cool!"
print("\n"+statement)
print("\t"+statement.lower())
print("\t\t"+statement.title())
print("\t\t\t"+statement.upper())
|
#Temprature Conversion App
#Welcome message
print("Welcome to the Temprature Conversion Program")
#gather the input
temp = float(input("\nWhat is the given temprature in degrees Fahrenheit: "))
#Convert the fagreneheit to celsius and kelvin
fahreneheit = temp
Celsius = round(((fahreneheit - 32)*(5/9)),4)
kelvin = round(Celsius + 273.15,4)
#Print the results
print("\nDegree Fahreneheit:\t "+str(fahreneheit)+"\n"+"Degree Celsius:\t\t "+str(Celsius)+"\n"+"Degree Kelvin:\t\t "+str(kelvin))
|
#String format
name = "Dhaval"
age = 30
money = 50.3
#print using string concatenation
print(name + " is "+ str(age) + " and has $"+str(money)+" dollars.")
#Print using .format() method
print("{0} is {1} and has ${2} dollars.".format(name,age,money))
#print using f-string
print(f"{name} is {age} and has ${money} dollars.")
|
#Elif chains
age = int(input("what your age: "))
if age<18:
print("\nyou are only "+str(age)+"!!")
print("you can't gamble")
elif age<21:
print("okay you are at "+str(age)+"!")
print("YOu can play blackjack but can't have a drink")
else:
print("\nOkay you can play blackjack and can have a drink") |
#包含一个学生类
#一个say hello函数
#一个打印语句
class Student():
def __init__(self,name="haha",age=18):
self.name = name
self.age = age
def say(self):
print("My name is {0}".format(self.name))
def sayhello():
print("欢迎来到图灵学院")
if __name__ == "__main__":
print("我是木块p01")
|
import time,datetime
t1 = time.clock()
for i in range(10):
print(i)
time.sleep(1)
t2 = time.clock()
print(t2-t1)
t3 = time.localtime()
t4 = time.strftime("%Y{Y}%m{m}%d{d} %H{o}%M",t3).format(Y="年",m="月",d="日",o=":")
print(t4)
d5 = datetime.date(2018,3,3)
print(d5)
print(d5.year)
print(d5.month)
print(d5.day)
|
l = [x*x for x in range(5)]#放在中括号中就是列表生成器
g = (x*x for x in range(5))#放在小括号中就是生成器
print(type(l))
print(type(g))#type函数就是返回的是括号内的变量类型
def odd():
print("Step 1")
yield 1#在函数odd中,yield负责返回,不用return是因为
print("Step 2")
yield 2
print("Step 3")
yield 3
def fib(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b = b,a+b
n += 1
if __name__ == "__main__":
m= odd()
one=next(m)#odd()是调用生成器
print(one)
two = next(m)
print(two)
three = next(m)
print(three)
m2 = fib(10)
# print(m2)
for i in range(6):
rst = next(m2)
print(rst)
|
import random
from graphics import *
win = GraphWin("Barnsley Fern", 500, 500)
win.setBackground("black")
class BarnsleyFern(object):
def __init__(self):
self.x, self.y = 0, 0
def transform(self, x, y):
rand = random.uniform(0, 100)
if rand < 1:
return 0, 0.16 * y
elif 1 <= rand < 86:
return 0.85 * x + 0.04 * y, -0.04 * x + 0.85 * y + 1.6
elif 86 <= rand < 93:
return 0.2 * x - 0.26 * y, 0.23 * x + 0.22 * y + 1.6
else:
return -0.15 * x + 0.28 * y, 0.26 * x + 0.24 * y + 0.44
def iterate(self, iterations):
print("Iterating")
for _ in range(iterations):
win.plot(win.width/2 + self.x*50, (win.height - self.y*50), "green")
self.x, self.y = self.transform(self.x, self.y)
print("Done")
fern = BarnsleyFern()
fern.iterate(1000000)
|
#!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You should explore features_dict as part of the mini-project,
but here's an example to get you started:
enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000
"""
import pickle
enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "rb"))
print("Number of persons in dataset : ", len(enron_data))
print("Persons in dataset : ", enron_data.keys())
print("Number of features per person : ", len(enron_data["METTS MARK"]))
number_poi = 0
number_poi_with_unknown_total_payments = 0
number_people_with_salary = 0
number_known_emails = 0
number_people_without_defined_total_payments = 0
for person in enron_data:
if enron_data[person]['poi'] == True:
number_poi = number_poi + 1
if enron_data[person]['total_payments'] == 'NaN':
number_poi_with_unknown_total_payments = number_poi_with_unknown_total_payments + 1
if enron_data[person]['salary'] != 'NaN':
number_people_with_salary = number_people_with_salary + 1
if enron_data[person]['email_address'] != 'NaN':
number_known_emails = number_known_emails + 1
if enron_data[person]['total_payments'] == 'NaN':
number_people_without_defined_total_payments = number_people_without_defined_total_payments + 1
print("Number of persons of interest : ", number_poi)
print("Stock for James Prentice : ", enron_data["PRENTICE JAMES"]["total_stock_value"])
print("Emails from Wesley Colwell to POI : ", enron_data["COLWELL WESLEY"]["from_this_person_to_poi"])
print("Stock options for Jeffrey K Skilling : ", enron_data["SKILLING JEFFREY K"]["exercised_stock_options"])
print("People with defined salary : ", number_people_with_salary)
print("Known emails : ", number_known_emails)
print("People without defined total payments : ", number_people_without_defined_total_payments, " which is percentage : ", (number_people_without_defined_total_payments * 100) / len(enron_data))
print("POI without defined total payments : ", number_poi_with_unknown_total_payments, " which is percentage : ", (number_poi_with_unknown_total_payments * 100) / len(enron_data)) |
'''Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.
Return the minimum number of steps to make t an anagram of s.
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.'''
class Solution:
def minSteps(self, s: str, t: str) -> int:
dict_n = {}
for ch in s:
if ch in dict_n:
dict_n[ch] += 1
else:
dict_n[ch] = 1
count = 0
for ch in t:
if ch not in dict_n or dict_n[ch] == 0:
count += 1
else:
dict_n[ch] -= 1
return count |
#Xiang Fan
#Gefei Tian
import copy
import math
from graphics import*
class Player():
def __init__(self,color):
self.color = color
def move(self, game):
flag = 0
while flag == 0:
try:
pos = input('Enter a number: ')
if pos in game.remaining:
flag = 1
else:
print "Invalid input. \n"
except:
print "Invalid input. \n"
game.remaining.remove(pos)
self.replace(game, game.position_dict[pos])
y = (pos - 1) // 15
x = (pos - 1) % 15
game.black[x + 1][y + 1]=1
game.q[x][y]=Circle(game.p[x][y],10)
game.q[x][y].draw(game.window)
game.q[x][y].setFill(self.color)
def replace(self, game, position):
game.board[position[0]][position[1]] = self.color
class AI(Player):
def __init__(self,color):
Player.__init__(self,color)
self.VALUE = {'FOUR' : 9999999, 'THREE' : 99999, 'ATTACK' : 0, 'DEFEND' : 0, 'NEUTRAL' : 0, 'MINE' : 0, 'OTHER' : 0}
self.learn = 1
if self.color == 'black':
self.opponent = 'white'
else:
self.opponent = 'black'
def move(self, game):
self.position_type = {}
self.position_points = {}
self.points_list = {}
for i in range(1,15**2+1):
self.position_type[i] = [0,0]
self.position_points[i] = [0,0,0]
self.points_list[i] = 0
self.count_points(game)
for position in range(1,15**2+1):
self.points_list[position] += self.position_points[position][0]*((self.position_type[position][0]**2))\
+ self.position_points[position][1]*((self.position_type[position][1]**2))
highest = {'points' : 0, 'position' : 0}
for position in self.points_list:
if self.points_list[position] > highest['points']:
highest['points'] = self.points_list[position]
highest['position'] = position
if highest['position'] == 0:
highest['position'] = game.remaining[0]
pos_y = (highest['position'] - 1) // 15
pos_x = (highest['position'] - 1) % 15
game.q[pos_x][pos_y]=Circle(game.p[pos_x][pos_y],10)
if self.learn == 1:
game.q[pos_x][pos_y].draw(game.window)
game.q[pos_x][pos_y].setFill(self.color)
self.replace(game, game.position_dict[highest['position']])
game.remaining.remove(highest['position'])
def count_points(self, game):
if self.color == 'O':
index = 1
else:
index = 0
checklist = []
for i in range(1, 16):
checklist.append(game.row_position(i))
checklist.append(game.col_position(i))
checklist.append(game.diagonal_position(0))
checklist.append(game.diagonal_position(1))
for major_row in checklist:
for row in major_row:
row_list = game.number_in_row(row)
for position in row:
if position in game.remaining:
if row_list[self.color] == 4 and row_list[self.opponent] == 0 and game.learning == 0:
self.points_list[position] += self.VALUE['FOUR']
elif row_list[self.color] == 3 and row_list[self.opponent] == 0 and game.learning == 0:
self.points_list[position] += self.VALUE['THREE']
elif row_list[self.opponent] == 4 and row_list[self.color] == 0 and game.learning == 0:
self.points_list[position] += self.VALUE['FOUR']
elif row_list[self.opponent] == 3 and row_list[self.color] == 0 and game.learning == 0:
self.points_list[position] += self.VALUE['THREE']
elif row_list[self.color] + row_list[self.opponent] == 0:
self.points_list[position] += self.VALUE['NEUTRAL']
elif row_list[self.opponent] == 0:
self.position_type[position][int(math.fabs(index-1))] += 1
self.position_points[position][int(math.fabs(index-1))] += self.VALUE['ATTACK'] + row_list[self.color]*self.VALUE['MINE']
elif row_list[self.color] == 0:
self.position_type[position][index] += 1
self.position_points[position][index] += self.VALUE['DEFEND'] + row_list[self.opponent]*self.VALUE['OTHER']
def switch(self, other):
self.VALUE['FOUR'] = copy.copy(other.VALUE['FOUR'])
self.VALUE['THREE'] = copy.copy(other.VALUE['THREE'])
self.VALUE['NEUTRAL'] = copy.copy(other.VALUE['NEUTRAL'])
self.VALUE['ATTACK'] = copy.copy(other.VALUE['ATTACK'])
self.VALUE['DEFEND'] = copy.copy(other.VALUE['DEFEND'])
self.VALUE['MINE'] = copy.copy(other.VALUE['MINE'])
self.VALUE['OTHER'] = copy.copy(other.VALUE['OTHER'])
class Game(object):
def __init__(self):
self.player1, self.player2 = self.setup()
self.active = 0
self.speed = 0
self.learning = 0
self.depth = 10
self.p=[[0 for a in range(16)] for b in range(16)]
self.q=[[0 for a in range(15)] for b in range(15)]
def setup(self):
player1, player2 = Player('black'), AI('white')
return player1, player2
def WinBoard(self):
self.p=[[0 for a in range(16)] for b in range(16)]
self.q=[[0 for a in range(15)] for b in range(15)]
self.window = GraphWin('Gomoku',480,600)
for i in range(15):
for j in range(15):
self.p[i][j] = Point(i*30+30,j*30+30)
self.p[i][j].draw(self.window)
Text(self.p[i][j], str(j * 15 + i + 1)).draw(self.window)
def play_game(self, player1, player2):
self.board = [[x*15+(y+1) for y in range(15)] for x in range(15)]
self.remaining = [i for i in range(1,15**2+1)]
self.position_dict = {}
self.WinBoard()
for i in range(1,15**2+1):
self.position_dict[i] = ((i-1)/15,(i-1)%15)
for i in range(15**2):
if self.active%2 == 0:
player1.move(self)
else:
player2.move(self)
self.active += 1
win_color = self.check_winners()
if win_color != None:
if win_color == 'black':
winner = 'player1' + '(black)'
else:
winner = 'player2' + '(white)'
if winner == 'player2' + '(white)':
print('you loss')
break
else:
print('you win')
break
if win_color == None:
print('tie')
def check_winners(self):
checklist = []
for i in range(1, 16):
for element in self.row_position(i):
checklist.append(self.number_in_row(element))
for element in self.col_position(i):
checklist.append(self.number_in_row(element))
for element in self.diagonal_position(0):
checklist.append(self.number_in_row(element))
for element in self.diagonal_position(1):
checklist.append(self.number_in_row(element))
for check in checklist:
if check['white'] == 5:
return 'white'
if check['black'] == 5:
return 'black'
def number_in_row(self, row):
row_list = {'white': 0, 'black': 0, 0: 0}
for position in row:
num = self.board[self.position_dict[position][0]][self.position_dict[position][1]]
if type(num) == int:
num = 0
row_list[num] += 1
return row_list
def row_position(self, row_number):
result = []
for i in range(11):
result.append(range((row_number-1)*15+1+i,(row_number-1)*15+1+i+5))
return result
def col_position(self, col):
result = []
for i in range(11):
result.append(range(col+i*(15), 15*(5+i)+1, 15))
return result
def diagonal_position(self, dia):
x_pos = set([])
y_pos = set([])
result = []
if dia == 0:
for row_number in range(1, 12):
x_pos = x_pos.union(set(range((row_number-1)
*15+1,(row_number-1)
*15+15+1)))
y_pos = y_pos.union(set(range(row_number, 15**2+1, 15)))
for start_pos in x_pos.intersection(y_pos):
result.append(range(start_pos,start_pos+(4)
*(16)+1,16))
if dia == 1:
for row_number in range(1, 15-5+2):
x_pos = x_pos.union(set(range((row_number-1)
*15+1,(row_number-1)*15+15+1)))
for row_number in range(15, 5-1, -1):
y_pos = y_pos.union(set(range(row_number, 15**2+1, 15)))
for start_pos in x_pos.intersection(y_pos):
result.append(range(start_pos, start_pos +
(5-1)*(14) + 1,14))
return result
def adjust(self, old, new, value, i):
old_v = 0
new_v = 0
new.VALUE[value] += i
self.self_play(old, new)
if self.self_play(old, new): old_v = old_v + 1
else: new_v += 1
if new.VALUE[value] - i > 0:
new.VALUE[value] -= i
self.self_play(old, new)
if self.self_play(old, new): old_v = old_v + 1
else: new_v += 1
def start_learning(self, player, speed):
old = AI('black')
new = AI('white')
self.speed = speed
self.learning = 1
for i in range(self.depth,0,-1):
self.adjust(old, new, 'NEUTRAL', i)
self.adjust(old, new, 'ATTACK', i)
self.adjust(old, new, 'DEFEND', i)
self.adjust(old, new, 'MINE', i)
self.adjust(old, new, 'OTHER', i)
player.switch(old)
self.learning = 0
def self_play(self, old, new):
if self.self_game_play(old, new, 1) == 'white':
old.switch(new)
new.switch(old)
print(old.VALUE['ATTACK'])
print(old.VALUE['DEFEND'])
print(old.VALUE['MINE'])
print(old.VALUE['OTHER'])
return (self.self_game_play(old, new, 1) == 'white')
def self_game_play(self, player1, player2, active):
self.WinBoard()
self.board = [[x*15+(y+1) for y in range(15)] for x in range(15)]
self.remaining = [i for i in range(1,15**2+1)]
self.position_dict = {}
for i in range(1,15**2+1):
self.position_dict[i] = ((i-1)/15,(i-1)%15)
for i in range(15**2):
if active%2 == 0:
player1.move(self)
else:
player2.move(self)
active += 1
win_color = self.check_winners()
if win_color != None:
if win_color == 'black':
winner = 'player1' + '(black)'
else:
winner = 'player2' + '(white)'
return win_color
def main():
game = Game()
player1 = game.player1
player2 = game.player2
game.depth = 5
speed = 1
if speed == 2 :
game.start_learning(player2,speed)
else: print("skip learning")
print("The game is ready")
while True:
game.play_game(player1, player2)
player2.learn = 0
break
while True:
main()
break
|
from tkinter import *
def covert():
m = float(miles.get())
killometer = m*1.609
result.config(text = f"{killometer}")
window = Tk()
window.title("MILES TO KM CONVERTER")
window.config(padx = 20,pady=20)
miles = Entry(width = 5)
miles.grid(column =1, row=0)
label = Label(text = "miles")
label.grid(column = 2,row =0)
equal = Label(text = "is equal to")
equal.grid(column = 0 ,row =1)
result = Label(text = "0")
result.grid(column =1,row =1)
km = Label(text = "km")
km.grid(column = 2,row =1)
calculate = Button(text = "calculate",command=covert)
calculate.grid(column = 1,row =2)
window.mainloop() |
# Knapsack problem
weight = [3, 1, 3, 4, 2] # weight of the items
value = [2, 2, 4, 5, 3] # Value of the items
def knapsack(C, W, V):
"""
This function calculates the highest value possible for the items in respect to their weights and maximum capacity.
:param C: (int) Maximum capacity of the knapsack.
:param W: (list) list of all item weights.
:param V: (list) list of all item values (Same index).
:return: (list) containing list of tuples with all picked items and maximum value.
"""
# Creating table where each row is value and each column is a specific capacity 0 -> C
table = [[0]*(C+1) for y in range(len(W)+1)]
numberOfItems = len(W)
answer = [[]]
# loop to solve the knapsack problem and fill the table
for i in range(1, numberOfItems+1):
_weight = W[i-1] # Weight of current element
_value = V[i-1] # Value of current element
for size in range(1, C+1):
table[i][size] = table[i - 1][size] # Same value as the row above it, as if it was not picked
# Consider picking the item if there is enough weight for it
# and it's value + the value of the item one row above and W behind it in capacity
# is currently higher than the value of the item above it in the table
if size >= _weight:
if table[i - 1][size - _weight] + _value > table[i][size]:
table[i][size] = table[i - 1][size - _weight] + _value
# will always be the best possible value
answer.append(table[-1][-1])
for i in range(numberOfItems, 1, -1):
if table[i][C] != table[i - 1][C]:
answer[0].append((W[i-1], V[i-1]))
C -= W[i-1]
return answer
print(knapsack(7, weight, value))
|
"""
Program that reads a PDB file and extracts each atom coordinates
"""
import pandas as pd
def coord(file):
"""
The function that reads the PDB file and extracts the atoms coordinates
it returns as a result a list of lists containing the atom name and its
coordinates.
Arguments :
file : the PDB file
Return :
atoms_df : Data frame of atoms coordinates
"""
with open(file, "r") as f_pdb:
coor_lst = []
for ligne in f_pdb:
if ligne[0:4] == "ATOM":
# Creating the empty dictionary.
dico = {}
# Atom extraction.
dico["atom"] = str(ligne[77:79].strip())
# Extraction of the name of the residue.
dico["residu "] = str(ligne[17:21].strip())
# Extraction of the residue number.
dico["N° resid"] = int(ligne[22:26].strip())
# Extraction of the x coordinate.
dico["x"] = float(ligne[30:38].strip())
# Extraction of the y coordinate.
dico["y"] = float(ligne[38:46].strip())
# Extraction of the z coordinate.
dico["z"] = float(ligne[46:54].strip())
coor_lst.append(dico)
atoms_df = pd.DataFrame(coor_lst)
return atoms_df
if __name__ == "__main__":
import coor_atom
print(help(coor_atom))
|
import csv
import os
from .AbstractLoader import AbstractLoader
class CsvLoader(AbstractLoader):
""" A helper to load a folder of CSV files and to represent it by:
- a numpy array for the positions, [n_tracks, n_pos_per_track, 3 (x/y/z)]
- a numpy array for attributes, [n_tracks, n_pos_per_track, n_attributes]
- a list of attribute names, derived from the header or automatically [att0, att1,...]
"""
def __init__(self, folderWithCSVs, resampleTo=50, minTrackLength=2, firstLineIsHeader=True, csvSeparator=",", dim=3):
super(CsvLoader, self).__init__(resampleTo, minTrackLength)
self.csvSeparator = csvSeparator
self.firstLineIsHeader = firstLineIsHeader
self.loadCsvs(folderWithCSVs)
self.convertTrackListToMatrix()
def loadCsvs(self, folder):
""" Calls the loading-function for each csv file """
counter = 0
for filename in sorted(os.listdir(folder)):
if filename.endswith(".csv"):
if counter == 0:
self.analyzeHeader(folder + "/" + filename)
self.handleCsv(folder + "/" + filename, counter)
counter += 1
print()
def analyzeHeader(self, filename):
try:
with open(filename) as f:
objectReader = csv.reader(f, delimiter=self.csvSeparator, skipinitialspace=True)
row = next(objectReader)
for i in range(self.dim, len(row)):
if self.firstLineIsHeader:
self.attributeNames.append(row[i])
else:
self.attributeNames.append("Attrib" + str(i - self.dim))
except IOError:
self.stopBecauseMissingFile(filename, "csv file")
def handleCsv(self, filename, counter):
try:
with open(filename) as f:
self.trackList[counter] = []
self.simpleStatusPrint(counter, 50)
objectReader = csv.reader(f, delimiter=self.csvSeparator, skipinitialspace=True)
# skip first line if it's a header
if self.firstLineIsHeader:
row = next(objectReader)
for row in objectReader:
self.trackList[counter].append([float(x) for x in row])
except IOError:
self.stopBecauseMissingFile(filename, "csv file") |
import pygame
import random
# ---------------Türkis--------Gelb-----------Lila-----------Grün---------Rot----------Blau---------Orange
block_colors = [(0, 255, 255), (255, 255, 0), (128, 0, 128), (0, 255, 0), (255, 0, 0), (0, 0, 255), (255, 127, 0)]
block_size = 20
board_width = block_size * 16
board_height = block_size * 20
block_speed = 5
block_x = random.randint(0, 380)
block_y = 50
random_color = random.randint(0, 6)
pygame.init()
pygame.display.set_mode((board_width, board_height))
pygame.display.set_caption("Tetris")
win = pygame.display.get_surface()
bRun = True
while bRun:
pygame.time.delay(100)
win.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
bRun = False
pygame.draw.rect(win, block_colors[random_color], (block_x, block_y + block_speed, block_size, block_size))
block_speed += 5
if block_speed >= block_size * 20 - 70:
block_speed = 0
random_color = random.randint(0, 6)
block_x = random.randint(0, 380)
pygame.display.update()
|
import json
name = input("Please enter your name: ")
print("Thank you for completing your name, " + name + "...")
print("\nBy the way, Hello World!")
|
from random import randint
class Calcular:
def __init__(self: object, dificuldade: int, /) -> None: # somente posicional
self.dificuldade: int = dificuldade
self.valor1: int = self._gerar_valor
self.valor2: int = self._gerar_valor
self.operacao: int = randint(1, 3) # 1: +, 2: -, 3: x
self.resultado: int = self._gerar_resultado
def __str__(self: object) -> str:
op: str = ''
if self.operacao == 1:
op = 'Somar'
elif self.operacao == 2:
op = 'Subtrair'
elif self.operacao == 3:
op = 'Multiplicar'
else:
op = 'Operação desconhecida'
return f'Valor 1: {self.valor1} \n'\
f'Valor2: {self.valor2} \n'\
f'Dificuldade: {self.dificuldade} \n'\
f'Operação: {op}'
def __conv_op(a: int, b: int, op: int) -> int:
"""Recebe dois parâmetros e o índice da operação
a ser executada e retorna o resultado.
Args:
a (int): 1o valor de entrada
b (int): 2o valor de entrada
op (int): índice da operação (1: +, 2: -, 3: *)
Returns:
int: a {op} b
"""
if op == 1:
return a + b
elif op == 2:
return a - b
return a * b
def __dif_random(dif: int) -> int:
"""Recebe um inteiro de 1 até 4 e retorna um
número aleatório pertencente a um dado inter-
valo.
Args:
dif (int): inteiro (1, 2, 3, 4)
Returns:
int: 1: n.aleat (0, 10)
2: n.aleat (0, 100)
3: n.aleat (0, 1000)
4: n.aleat (0, 10000)
"""
dif_dict: dict = {1: randint(0, 10),
2: randint(0, 100),
3: randint(0, 1000),
4: randint(0, 10_000)}
return dif_dict.get(dif)
@property
def _gerar_valor(self: object) -> int:
"""Retorna um número aleatório baseado na
dificuldade de entrada.
Args:
self (object): objeto
Returns:
int: número aleatório
"""
if self.dificuldade in range(1, 4):
return Calcular.__dif_random(self.dificuldade)
return randint(0, 100_000)
@property
def _gerar_resultado(self: object) -> int:
"""Retorna o resultado da operação de acordo com
os atributos instanciados do objeto.
Args:
self (object): objeto
Returns:
int: valor1 {op} valor2
"""
return Calcular.__conv_op(self.valor1,
self.valor2,
self.operacao)
@property
def _op_simbolo(self: object) -> str:
"""Retorna o símbolo que representa a ope-
ração matemática associada ao atributo ope-
ração.
Args:
self (object): objeto
Returns:
str: +, - ou *
"""
if self.operacao == 1:
return '+'
elif self.operacao == 2:
return '-'
return '*'
def check_resposta(self: object, resposta: int) -> bool:
"""Confere se a resposta de entrada, fornecida pelo
usuário é igual ao resultado da operação.
Args:
self (object): objeto
resposta (int): resposta do usuário
Returns:
bool: True se a resposta for correta,
False caso contrário.
"""
check: bool = False
if self.resultado == resposta:
print('Resposta correta.')
check = True
else:
print('Resposta errada.')
print(f'{self.valor1} {self._op_simbolo} {self.valor2} = '\
f'{self.resultado}')
return check
def show_op(self: object) -> None:
"""Imprime na tela a expressão matemática a ser
resolvida pelo usuário, de acordo com os atribu-
tos do objeto.
Args:
self (object): objeto
"""
print(f'{self.valor1} {self._op_simbolo} {self.valor2} = ?')
|
x = int(input("Ente the value for x: "))
y = int(input("Ente the value for y: "))
z = int(input("Ente the value for z: "))
n = int(input("Ente the value for N: "))
a = [[a, b, c] for a in range(x + 1) for b in range(y + 1) for c in range(z + 1) if a+ b + c != n]
print(a)
|
def main():
try:
num1 =float(input("Please enter first number: "))
num2 =float(input("Please enter second number: "))
print("INSTRACTIONS".center(50, "="))
print(""" Please=>
Enter 'a' for addition
Enter 's' for substraction
Enter 'm' for multiplication
Enter 'd' for division
Enter 'o' to stop the loop""")
ch=input ("Please Enter char: ")
while ch != 'o':
if ch.lower() == 'a':
addition(num1, num2)
elif ch.lower() == 's':
substraction(num1, num2)
elif ch.lower() == 'm':
multipilication(num1, num2)
elif ch.lower() == 'd':
division(num1, num2)
elif ch.lower()=='o':
break
else:
print ("please enter only the char mentioned")
ch=input ("Please Enter char if u want to do another calculations: ")
ch=ch.lower()
if ch == 'a' or ch == 's' or ch =='m' or ch=='d':
num1 =float(input("Please enter first number: "))
num2 =float(input("Please enter second number: "))
elif ch=='o':
break
else:
print ("please enter only the char mentioned")
except Exception as e:
print ("Unknown Error",e)
def addition(x, y):
result=x+y
print (f"The sum of the numbers is: {result}")
def substraction(x,y):
result=x-y
print (f"The substraction of the numbers is: {result}")
def multipilication(x,y):
result= x*y
print (f"The Result of the numbers is: {result}")
def division(x,y):
result= x/y
print (f"The Result of the numbers is: {result}")
main() |
from random import choice
def main():
print("Rule of the game".center(60, "="))
print("""
Rock smashes scissors.
Paper covers rock.
Scissors cut paper.
""")
computer_sco=0
player_sco=0
tie=0
while True:
poss_ac=["rock", "paper", "scissors"]
user_guess=input("please enter one of these'rock' or 'paper' or 'scissors': ")
user_guess=user_guess.lower()
comp_guess=choice(poss_ac)
print(f"your choice is {user_guess} computer choice is {comp_guess}")
if user_guess==comp_guess:
print(f"It is tie, Both select {user_guess}")
tie +=1
elif user_guess=='rock':
if comp_guess=='paper':
print("Oops, You lose Computer won!")
computer_sco +=1
#print(f"computer Won:{computer_sco}")
else:
print("Congradulations, You won!")
player_sco +=1
#print(f"You Won: {player_sco}")
elif user_guess=='scissors':
if comp_guess=='rock':
print("Oops, You lose Computer won")
computer_sco +=1
#print(f"computer Won:{computer_sco}")
else:
print("Congrats, You won!")
player_sco +=1
#print(f"You Won: {player_sco}")
elif user_guess=='paper':
if comp_guess=='scissors':
print("Oops, You lose Computer won")
computer_sco +=1
#print(f"computer Won:{computer_sco}")
else:
print("Congrats, You won!")
player_sco +=1
#print(f"You Won: {player_sco}")
else:
print("please enter correct value:")
play_again=input("Do you want to play again y/n: ")
play_again=play_again.upper()
if play_again != 'Y':
break
game_stat(computer_sco, player_sco, tie)
def game_stat(computer_sco, player_sco, tie):
total_count= tie + computer_sco + player_sco
print("Game Statstics".center(100,'+'))
print (f"Total prompt: {total_count}")
print(f"Tie: {tie}")
print (f"Computer won: {computer_sco}")
print(f"You Won: {player_sco}")
main() |
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist)/2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i += 1
else:
alist[k] = righthalf[j]
j += 1
k += 1
while i < len(lefthalf):
alist[k] = lefthalf[i]
i += 1
k += 1
while j < len(righthalf):
alist[k] = righthalf[j]
j += 1
k += 1
alist = [54,26,93,17]
mergeSort(alist)
print(alist)
def another_mergesort(alist):
if len(alist) == 1:
return alist
mid = len(alist)/2
lefthalf = alist[:mid]
righthalf = alist[mid:]
lefthalf = another_mergesort(lefthalf)
righthalf = another_mergesort(righthalf)
sortedl = []
while lefthalf and righthalf:
if lefthalf[0] > righthalf[0]:
sortedl.append(righthalf.pop(0))
else:
sortedl.append(lefthalf.pop(0))
sortedl += lefthalf
sortedl += righthalf
return sortedl
print (another_mergesort([54,26,93,17, 1, 3, 55])) |
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
self.tail = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
if not self.tail:
self.tail = temp
self.head = temp
def add_2(self, item):
new = Node(item)
if self.tail:
self.tail.setNext(new)
if not self.head:
self.head = new
self.tail = new
def append(self, item):
new_node = Node(item)
current = self.head
last_node = None
while current is not None:
last_node = current
current = current.getNext()
if last_node:
last_node.setNext(new_node)
else:
self.head = new_node
def size(self):
current = self.head
count = 0
while current is not None:
print (current)
count = count + 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def index(self, item):
index = 0
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
break
else:
found = False
index = index + 1
current = current.getNext()
if found is False:
return -1
return index
def insert(self, index, char):
current = self.head
new_node = Node(char)
previous = None
i = 0
while current is not None:
data = current.getData()
if i == index:
new_node.setNext(current)
break
else:
previous = current
current = current.getNext()
i = i + 1
if previous:
previous.setNext(new_node)
else:
self.head = new_node
return
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if current == self.tail:
self.tail = previous
if previous is None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
def pop(self, index=None):
current = self.head
previous = None
found = False
count = 0
if index is None:
index = self.size() - 1
while not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if current == self.tail:
self.tail = previous
if previous is None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
print (current.getData())
def print_list(self):
current = self.head
data = []
while current:
data.append(current.getData())
current = current.getNext()
print (data)
mylist = UnorderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print (mylist.search(17))
print (mylist.size())
mylist.print_list()
# mylist = UnorderedList()
#
# mylist.append(31)
# mylist.append(77)
# mylist.append(17)
# mylist.append(93)
# mylist.append(26)
# mylist.append(54)
print (mylist.search(17))
print (mylist.size())
mylist.print_list()
print (mylist.index(93))
mylist.insert(0, 13)
mylist.insert(66, 13)
mylist.print_list()
mylist.remove(54)
mylist.print_list()
mylist.remove(13)
mylist.print_list()
mylist.remove(13)
mylist.print_list()
mylist.append(13)
mylist.print_list()
mylist.add_2(999)
mylist.add_2(88)
mylist.add_2(34)
mylist.print_list()
mylist.pop(0)
mylist.print_list()
mylist.pop(1)
mylist.print_list()
mylist.pop(2)
mylist.print_list()
mylist.pop(4)
mylist.print_list()
mylist.pop()
mylist.print_list()
|
import os
def rename():
path = input("请输入路径:")
name = input("请输入开头名:")
start_number = input("请输入开始数:")
file_type = input("请输入后缀名(如 .jpg、.txt等等):")
print("正在生成以" + name + start_number + file_type + "迭代的文件名")
count = 0
file_list = os.listdir(path)
for files in file_list:
old_dir = os.path.join(path, files)
new_dir = os.path.join(path, name + str(count + int(start_number)) + file_type)
os.rename(old_dir, new_dir)
count += 1
print("一共修改了" + str(count) + "个文件")
rename()
|
print("******* PROGRAMA QUE MATRICULA E IMPRIME LA CONSTANCIA DE MATRICULA *******")
import os
import sys
from modulog import *
def menu():
print("Estas en el menu principal")
print("1) MATRICULA")
print("2) MODIFICAR MATRICULA")
print("3) CONSTANCIA DE MATRICULA")
print("4) SALIR")
try:
opc=int(input("Seleccione la opccion a realizar:_"))
except:
print("No ingreso un numero,porfavor introduzca un numero")
print("")
menu()
os.system('cls')
if opc==1:
matricula()
menu()
elif opc==2:
modificar()
menu()
elif opc==3:
constancia()
menu()
elif opc==4:
salir()
else:
print("Por favor digite un numero de los mencionados en la opcion")
menu()
menu()
|
"""
LA1
Comp 445 - Fall 2018
HTTP Client Library
"""
import socket
from urllib.parse import urlparse
import ipaddress
from packet import Packet
class Response:
"""Represents an HTTP response message.
Attributes:
http_version (str): HTTP version.
code (int): Status code.
status (str): Description of status code.
headers (dict): Collection of key value pairs representing the response
headers.
body (str): The response body.
"""
def __init__(self, response: str):
"""Parse the response string."""
# The first consecutive CRLF sequence demarcates the start of the
# entity-body.
preamble, self.body = response.split("\r\n\r\n", maxsplit=1)
status_line, *headers = preamble.split("\r\n")
self.http_version, code, *status = status_line.split()
self.code = int(code)
self.status = " ".join(status)
map(_remove_whitespace, headers)
self.headers = dict(kv.split(":", maxsplit=1) for kv in headers)
def __str__(self):
"""Return a string representation of the response."""
status_line = "{} {} {}".format(self.http_version, self.code,
self.status)
headers = "\n".join(
"{}: {}".format(k, v) for k, v in self.headers.items())
return "\n".join((status_line, headers, self.body))
def _remove_whitespace(s: str):
"""Return a string with all whitespace removed from the input."""
return "".join(s.split())
def handle_recv(sock: socket.socket):
"""
Handles the receiving of a response from a server
"""
BUFFER_SIZE = 1024
response = b""
while True:
data = sock.recv(BUFFER_SIZE)
response = response + data
if not data:
break
return response
def send_req_tcp(url: str, port: int, req: str, verbose: bool):
"""
Sends a request to the specified url:port
and returns the response as a string
:param url:
:param port:
:param req:
:param verbose: enables verbose mode
:return:
"""
res = ""
conn = socket.create_connection((url, port), 5)
try:
if verbose:
print("Sending: \n" + req) # print request
data = req.encode("UTF-8")
conn.sendall(data)
res_data = handle_recv(conn)
res_str = res_data.decode("UTF-8")
res = Response(res_str)
if verbose:
print(res.headers)
print(res.body)
except socket.timeout:
print("Connection to " + url + ": " + str(port) + " timed out")
finally:
conn.close()
return res
def send_req_udp(router_addr: str, router_port: int, server_addr: str, server_port: int, packet_type: int, seq_num: int,
req: str, verbose=False):
peer_ip = ipaddress.ip_address(socket.gethostbyname(server_addr))
conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
timeout = 5
print("sending SYN")
syn = Packet(packet_type=1,
seq_num=seq_num,
peer_ip_addr=peer_ip,
peer_port=server_port,
payload='')
conn.sendto(syn.to_bytes(), (router_addr, router_port))
print("waiting for SYN-ACK")
conn.settimeout(timeout)
syn.packet_type = -1
while syn.packet_type != 2:
resp, send = conn.recvfrom(1024)
recv_packet = Packet.from_bytes(resp)
syn.packet_type = recv_packet.packet_type
print("Received SYN-ACK")
print("Sending ACK")
ack = Packet(packet_type=3,
seq_num=seq_num,
peer_ip_addr=peer_ip,
peer_port=server_port,
payload='')
conn.sendto(ack.to_bytes(), (router_addr, router_port))
res = ""
try:
msg = req
p = Packet(packet_type=packet_type,
seq_num=seq_num,
peer_ip_addr=peer_ip,
peer_port=server_port,
payload=msg.encode("UTF-8"))
conn.sendto(p.to_bytes(), (router_addr, router_port))
print('Send: \n"{}"\nto router'.format(msg))
# Try to receive a response within timeout
conn.settimeout(timeout)
response, sender = conn.recvfrom(1024)
print('Waiting for a response')
p = Packet.from_bytes(response)
print('Router: ', sender)
print('Packet: ', p)
res = Response(p.payload.decode("UTF-8"))
print('Payload: ' + p.payload.decode("UTF-8"))
except socket.timeout:
print('No response after {}s'.format(timeout))
finally:
conn.close()
return res
def get(url: str, headers=None, verbose=False, udp=False):
"""
Makes a GET request and returns the response
:param url:
:param verbose: enables verbose mode
:param headers:
:param udp:
:return: response from server
"""
# Parse URL components
url_parsed = urlparse(url)
# if scheme is absent from URL, urlparse makes problems
# this next part checks if the url was parsed correctly
if url_parsed.hostname is None:
url = "http://"+url
url_parsed = urlparse(url, "http") # if not parsed properly, parse the url again
host = url_parsed.hostname
port = url_parsed.port or 80
path = url_parsed.path or "/"
query = url_parsed.query or ""
uri = path
if query != "":
uri = uri + "?" + query
# Prepare request line
req = "GET " + uri + " HTTP/1.0\r\n"
# Headers
if headers is None:
headers = {}
headers.setdefault("Host", " "+host+":"+str(port))
headers.setdefault("User-Agent", " "+"HttpClient-Concordia")
# Add headers to request
for k, v in headers.items():
req = req + k + ": " + v + "\r\n"
# The request needs to finish with two empty lines. took me 4 hours to figure this out on my own
req = req + "\r\n"
res = ""
if not udp:
# Send request TCP
res = send_req_tcp(host, port, req, verbose)
# print("Reply: \n" + res) # print response
if res.code >= 300 and res.code < 400:
print("Redirecting to: " + res.headers['Location'])
url = res.headers['Location'].strip()
return get(url, headers, verbose, False)
return res
# Send request UDP
elif udp:
router_host = "localhost"
router_port = 3000
res = mimick_tcp_handshake(router_host, router_port, host, port, req, verbose)
return res
return res
def post(url: str, data="", headers=None, verbose=False, udp=False):
"""
Sends a POST request
:param url:
:param data: the body of the request
:param verbose: enables verbose mode
:param headers:
:param udp:
:return:
"""
# Parse URL components
url_parsed = urlparse(url)
# if scheme is absent from URL, urlparse makes problems
# this next part checks if the url was parsed correctly
if url_parsed.hostname is None:
url = "http://"+url
url_parsed = urlparse(url, "http") # if not parsed properly, parse the url again
host = url_parsed.hostname
port = url_parsed.port or 80
path = url_parsed.path or "/"
query = url_parsed.query or ""
uri = path
if query != "":
uri = uri + "?" + query
# Prepare request line
req = "POST " + uri + " HTTP/1.0\r\n"
# Headers
if headers is None:
headers = {}
headers.setdefault("Host", "" + host + ":" + str(port))
headers.setdefault("User-Agent", "" + "HttpClient-Concordia")
headers.setdefault("Content-Length", "" + str(len(data)))
headers.setdefault("Content-Type", "" + "application/text")
# Add headers to request
for k, v in headers.items():
req = req + k + ": " + v + "\r\n"
req = req + "\r\n"
req = req + data + "\r\n"
# The request needs to finish with two empty lines. took me 4 hours to figure this out on my own
req = req + "\r\n"
# Send request
if udp:
router_host = "localhost"
router_port = 3000
res = mimick_tcp_handshake(router_host, router_port, host, port, req, verbose)
else:
res = send_req_tcp(host, port, req, verbose)
return res
def mimick_tcp_handshake(router_host: str, router_port: int, server_host:str, server_port: int, msg: str, verbose=False):
res = send_req_udp(router_host, router_port, server_host, server_port, 0, 1, msg, verbose)
return res
"""
For Demo purposes
"""
"""
#get("localhost:8007", True)
get("http://httpbin.org/get", True)
get("http://httpbin.org/status/418", True)
post("http://httpbin.org/post", "Nice teapot you got there.", True)
"""
# get("http://httpbin.org/status/418", None, True)
# post("http://httpbin.org/post", "Nice teapot you got there.", None, True)
# get("https://httpbin.org/redirect-to?url=http://httpbin.org/get&status_code=302", None, False)
|
def solution(number):
count = 0
sum = 0
while count < number:
if count%3 == 0 or count%5 == 0:
sum = sum + count
count += 1
return(sum)
|
"""
Generating randomness
"""
import random
# current = len(final_data)
# remain = 100 - len(final_data)
print("Please give AI some data to learn...")
def datastring():
final_data = ''
while len(final_data) < 10:
print(
f'Current data length is {len(final_data)}, {10 - len(final_data)} symbols left')
input_data = input('Print a random string containing 0 or 1: ')
final_data += ''.join(x for x in input_data if x in '01')
return final_data
final_data = datastring()
print(f'Final data string:\n{final_data}\n')
#########################################################################
# Creates a list of four character slices for each character
split_data = [final_data[i: i + 4]
for i in range(0, len(final_data) - 3)] # - 3 removes lagging slices
# Creates a list of triads for use in the next two dictionaries.
triads = ['000', '001', '010', '011', '100', '101', '110', '111']
# Count slices that end with 0 or 1 for each triad.
triad_counts = {key: [split_data.count(
key + '0'), split_data.count(key + '1')] for key in triads}
# Creates a dictionary mapping the probability of 0 for each triad.
# Add 0.0001 to each value to avoid DivisionByZero.
triad_prob = {key: (value[0] + 0.0001) / (value[0] + value[1] + 0.0001)
for key, value in triad_counts.items()}
# This is another solution to DivisionByZero using if/else statement.
# triad_prob = {key: value[0] / (value[0] + value[1]) if value[0] +
# value[1] != 0 else 0.5 for key, value in triad_counts.items()}
#########################################################################
print('You have $1000. Every time the system successfully predicts your next press, you lose $1.')
print('Otherwise, you earn $1. Print "enough" to leave the game. Let\'s go!')
final_test = ''
while True:
game_over = False
input_test = input('Please enter a test string containing 0 or 1: ')
final_test = final_test.join(x for x in input_test if x in '01')
if input_test.lower() == 'enough':
game_over = True
print('Game over!')
break
elif len(final_test) < 3: # Must be at least three characters long or prediction doesn't work
print('Must enter at least three valid characters (0 or 1).')
else:
print(final_test)
break
while not game_over:
# Chooses first three characters in prediction string with random module
prediction = ''
for i in range(3):
prediction += random.choice('01')
if len(final_test) > 3:
# Adds 0 or 1 to prediction based on the mapping of user input and probability dictionary
# - 3 ensures length of prediction matches user string
for i in range(len(final_test) - 3):
if triad_prob[final_test[i: i + 3]] > 0.5:
prediction += '0'
elif triad_prob[final_test[i: i + 3]] < 0.5:
prediction += '1'
else: # if 50/50, uses random to select
prediction += random.choice('01')
else:
print(f'Prediction:\n{prediction}')
break
|
def sayHello(name):
print(f"hello {name}, how are you ?")
# sayHello("Mohit")
def sum(x, y):
z = x+y
return z
# print(sum(12,32))
def getSum(num1, num2): return num1 + 2*num2
print(getSum(1, 3))
str1 = "2751" # 7215
str2 = "3219" # 2391
arr = []
arr[:] = str1
print(arr)
res = " "
x = res.join(arr)
print(x) |
import matplotlib
import glob
from pylab import median, mean, std
from random import shuffle
from seq import *
def pn(name):
"""Returns the prefix of a name, with the prefix
separated by '_' for the remainder of the name.
name - string
"""
return name[:name.find('_')]
def ps(sequence):
"""Returns the prefix of a sequence name, with the prefix
separated by '_' for the remainder of the name.
sequence - sequence the name is extracted from.
"""
return pn(sequence.name())
def colordict(sequences):
""" returns a dictionary that maps prefixes of sequence names to
label colors for the dot plot"""
prefixes = enumerate(set([ps(s) for s in sequences]))
return dict([(prefix,"bgrkcmy"[i%7]) for i,prefix in prefixes])
def mod_alpha(sequence):
"""Modifies the alphabet and replaces the letters of a sequence
by letters drawn from a different alphabet"""
code = { 'H':'0','R':'0','K':'0',
'D':'1','E':'1','N':'1','Q':'1',
'S':'2','T':'2','P':'2','A':'2','G':'2',
'M':'3','I':'3','L':'3','V':'3',
'F':'4','Y':'4','W':'4',
'C':'5',
'X':'6' }
sequence._letters = "".join(code[aa] for aa in sequence._letters)
def similarities(seqs1, seqs2):
"""Calculates the similarities between two lists of sequences.
seqs1 -- first list of sequences
seqs2 -- second list of sequences
"""
sims = []
ns = len(seqs1)
for i in range(ns):
for j in range(i+1, ns):
s1 = seqs1[i]
s2 = seqs2[j]
sims.append(s1.similarity(s2))
return sims
def select_starts(prefix, sequences):
"""Selects sequences from the given list of sequences which info attribute
start with the given prefix."""
print("select sequences: "+prefix)
return [s for s in sequences if s.info().startswith(prefix)]
def select_contains(substr, sequences):
"""Selects sequences from the given list of sequences which name
contain the given substring."""
print("get sequences: "+substr)
return [s for s in sequences if substr in s.name()]
def take(name, sequences):
"""Takes a sequence with the given name from the list of sequences"""
for s in sequences:
if s.name() == name: return s
return None
def randomize(sequences):
"""Glues all sequences together, randomly shuffles the letters
and the splits the shuffled letter sequence in sub-sequences
of the same lengths as the original sequences."""
print "randomizing sequences"
aas = []
for s in sequences:
aas += [aa for aa in s.letters()]
shuffle(aas)
rnd_sequences = []
i = 0
for s in sequences:
n = len(s)
letters = "".join(aas[i:i+n])
i += n
rnd_sequences.append(Seq('R'+s.name(), letters))
return rnd_sequences
def threshold(sequences, n):
"""Calculates a cutoff threshold for the similarity between
sequences"""
sequences = ngramize(randomize(sequences),n)
return(max(similarities(sequences, sequences)))
def AUC(output, target, classID1=0, classID2=1):
"""Area Under the ROC curve. 0.5 means no correlation.
1.0 means perfect correlation.
output - classifier output. Real value that represents confidence.
target - target output.
classID1 - ID of the first class
classID2 - ID of the second class.
"""
idx = sort_index(output) # sorting index according to output
np = target.count(classID1) # number positives
nn = target.count(classID2) # number negatives
tp, fp = 0.0, 0.0 # true and false positives
ox, oy = 0.0, 0.0 # old pos of ROC curve
old_i = None # old index
auc = 0.0 # AUC
for i in idx:
if target[i] == classID1: tp += 1.0
elif target[i] == classID2: fp += 1.0
else : continue
if old_i and not output[old_i] == output[i]:
x,y = fp/nn, tp/np
auc += (x-ox)*(y+oy)/2.0
ox, oy = x,y
old_i = i
auc += (1-ox)*(1+oy)/2.0
return auc if auc > 0.5 else 1.0-auc
def sort_index(v):
"""Returns a sorting index for the elements in v.
The smallest element in v has index zero
"""
return [i for i,e in sorted(enumerate(v), key=lambda t: t[1])]
if __name__ == "__main__":
"""Just a usage example"""
for filename in glob.glob('data/MR_GR.ffa'):
print "loading ... "+filename
sequences = load_sequences(filename, 0)
sequences = select(sequences, 'MR_')
sequences = randomize(sequences)
for s in sequences:
print s
|
failure = object()
class Result:
"""
Wraps a callable and calls it with the given arguments
if an exception is raised in the callable, it is wrapped.
"""
def __init__(self, _callable, *args, suppress=Exception, **kwargs):
"""
>>> w = Result(lambda x: x, 1)
>>> w.unwrap()
1
>>> w = Result(lambda x: x, 1, suppress=TypeError)
>>> w.unwrap()
1
>>> w = Result(lambda x, y: x, 1)
>>> w.unwrap()
Traceback (most recent call last):
...
TypeError: missing required positional argument: 'y'
>>> w = Result(lambda x, y: x, 1)
>>> w.unwrap_or("default")
'default'
>>> w.unwrap_or_else(lambda: "default")
'default'
>>> w.is_ok()
False
>>> w.is_error()
True
>>> w = Result(lambda: 2)
>>> w.and_then(lambda value, x: x * value, 5)
10
"""
self.exc = None
self.value = failure
try:
self.value = _callable(*args, **kwargs)
except suppress as e:
self.exc = e
def unwrap(self):
"""
If an exception was raised in the wrapped callable,
raise it otherwise return the result value.
"""
if self.exc is not None:
raise self.exc
return self.value
def unwrap_or(self, default):
"""
If an exception was raised in the wrapped callable,
return the default value otherwise return the result value.
"""
return self.value if self.value is not failure else default
def unwrap_or_else(self, _callable, *args, **kwargs):
"""
If an exception was raised in the wrapped callable,
return the result of passed calleble otherwise return the result value.
"""
return self.unwrap_or(_callable(*args, **kwargs))
def is_ok(self):
"""
Tells if the wrapped callable returned without error.
"""
return self.value is not failure
def is_error(self):
"""
Tells if the wrapped callable raised an exception.
"""
return self.value is failure
def ok(self):
"""
Same as unwrap().
"""
return self.unwrap()
def and_then(self, _callable, *args, **kwargs):
"""
If no exception was raised in the wrapped callable,
pass the result value to the given callable.
as a wrapped callable.
"""
return Result(_callable, self.unwrap(), *args, **kwargs)
|
""" Some computations that are necessary for the polygon intersection algorithm."""
from __future__ import division
from fractions import *
def point_in_polygon(point, polygon):
"""
Return true if the point point is contained in the polygon polygon.
Input:
point: a 2D point as [x,y]
polygon: a list of n points in CCW order: [[x1, y1], ..., [xn, yn]]
"""
polygon_translated = [[vertex[0] - point[0], vertex[1] - point[1]] for vertex in polygon]
polygon_shift = polygon_translated[1:]
polygon_shift.append(polygon_translated[0])
area = [
1
for (a, b)
in zip(polygon_translated, polygon_shift)
if (b[0] * a[1] - a[0] * b[1]) < 0
]
return sum(area) in [0, len(polygon)]
def vertex_in_half_plane(vertex, half_plane):
"""
Return true if the vertex vertex lies in the half plane half_plane.
Input:
vertex: a 2D vertex as [x,y]
half-plane: a vector as its begin point (bx, by) and its endpoint
(ex, ey) in a list: [[bx, by], [ex, ey]].
"""
[p_min, p] = half_plane
return (
(p[1] * p_min[0] - p[0] * p_min[1] - p[1] * vertex[0] +
p_min[1] * vertex[0] + p[0] * vertex[1] - p_min[0] * vertex[1]) >= 0
)
class LineSegment(object):
"""This class stores a line as a vector and a point on the line."""
def __init__(self, points):
"""
Construct a LineSegment object.
Input:
points: list of two points of the form [[x1, y1], [x2, y2]].
"""
super(LineSegment, self).__init__()
[p1, p2] = points
self.vector = [-p1[0] + p2[0], -p1[1] + p2[1]]
self.point = p1
def intersect_line_segment(self, other):
"""Find the intersection of this LineSegment with other."""
p = self.point
r = self.vector
q = other.point
s = other.vector
r_cross_s = -(r[1]*s[0]) + r[0]*s[1]
if(r_cross_s):
u_numerator = p[1]*r[0] - q[1]*r[0] - p[0]*r[1] + q[0]*r[1]
u = u_numerator / r_cross_s
if (u >= 0 and u <= 1):
t_numerator = p[1]*s[0] - q[1]*s[0] - p[0]*s[1] + q[0]*s[1]
t = t_numerator / r_cross_s
if (t >= 0 and t <= 1):
x = p[0] + r[0] * t
y = p[1] + r[1] * t
return [x, y]
return None
|
"""The class face."""
class Face(object):
"""
Class to represent a face.
Properties:
- outer_component: half edge on its outer boundary when traversed
counter clockwise.
- inner_components: list of half edges, on of each of the holes in the face.
None if the face does not have any hole.s
- circumcentre: The circumcentre of the face, [+inf, +inf] if the face is unbounded.
"""
def __init__(
self, outer_component=None,
inner_components=None,
circumcentre=[float('inf'), float('inf')]
):
"""Construct a Face object."""
super(Face, self).__init__()
self.outer_component = outer_component
self.inner_components = inner_components or []
self.circumcentre = circumcentre
def __eq__(self, other):
"""Check if two objects are equal."""
if type(other) is type(self):
return self.circumcentre == other.circumcentre
return False
def number_of_vertices(self):
"""Return the number of vertices that define the face."""
def number_of_vertices_helper(current_edge):
if(self.outer_component == current_edge):
return 1
else:
return 1 + number_of_vertices_helper(current_edge.nxt)
return number_of_vertices_helper(self.outer_component.nxt)
def get_edges_inner_component(self, inner_component_idx=0):
"""Return all edges of this face in CCW order."""
def get_edges_helper(current_edge, edges):
if(self.inner_components[inner_component_idx] == current_edge):
return edges
else:
edges.append(current_edge)
return get_edges_helper(current_edge.nxt, edges)
return get_edges_helper(
self.inner_components[inner_component_idx].nxt,
[self.inner_components[inner_component_idx]]
)
def __neq__(self, other):
"""Check if two objects are not equal."""
return not self.__eq__(other)
def is_bounded(self):
"""Return if the face is bounded, i.e. if its circumcentre == [inf, inf]."""
return not(self.circumcentre[0] == float('inf') and self.circumcentre[1] == float('inf'))
def __repr__(self):
"""Print-friendly representation of the Face object."""
outer = None
if(self.outer_component):
outer = self.outer_component.as_points()
return (
'<Face ('
'outer_component = {outer},\t '
'inner_components = {inners},\t '
'circumcentre = {obj.circumcentre}>\n'
.format(
obj=self,
outer=outer,
inners=[c.as_points() for c in self.inner_components]
)
)
|
"""Module with unit tests for the triangle module."""
import unittest
from triangle import *
class Test_triangle_point_in_triangle(unittest.TestCase):
"""Unit tests for the method point_in_triangle in the module triangle."""
def setUp(self):
"""."""
pass
def test_point_in_triangle(self):
"""The point lies inside the triangle."""
triangle = [[2, 1], [7, 2], [4, 6]]
point = [4, 3]
self.assertTrue(point_in_triangle(triangle, point))
def test_point_is_triangle_vertex(self):
"""The point is a vertex of the triangle."""
triangle = [[2, 1], [7, 2], [4, 6]]
point = triangle[0]
self.assertFalse(point_in_triangle(triangle, point))
def test_point_on_triangle_edge(self):
"""The lies on the edge of the triangle."""
triangle = [[2, 1], [7, 1], [4, 6]]
point = [3, 1]
self.assertFalse(point_in_triangle(triangle, point))
def test_point_outside_of_triangle(self):
"""The point lies outside the triangle."""
triangle = [[2, 1], [7, 2], [4, 6]]
point = [10, 9]
self.assertFalse(point_in_triangle(triangle, point))
if __name__ == '__main__':
unittest.main()
|
str = input()
if str.islower():
print('a')
else:
print('A')
|
# Dan Wu
# 1/26/2021
# 4a - Modify the binary search function from the exploration so that, instead of returning -1 when the target value is not in the list,
# raises a TargetNotFound exception (you'll need to define this exception class).
class TargetNotFound(Exception) :
"""define exception when target value is not in the list."""
pass
def bin_except(a_list, target):
"""
Searches a_list for an occurrence of target
If found, returns the index of its position in the list
If not found, returns -1, indicating the target value isn't in the list
"""
first = 0
last = len(a_list) - 1
while first <= last:
middle = (first + last) // 2
if a_list[middle] == target:
return middle
if a_list[middle] > target:
last = middle - 1
else:
first = middle + 1
raise TargetNotFound
|
import datetime as dt
now = dt.datetime.now()
year = now.year
day_of_week = now.weekday()
print(f"Year={year}")
print(f"Day Of week:{day_of_week}")
dob = dt.datetime(year=1980, month=12, day=31, hour=4, minute=45, second=58, microsecond=2568)
print(dob)
|
import pandas
data = pandas.read_csv("weather_data.csv")
# data_dict = data.to_dict()
# print(data_dict)
temp_list = data["temp"].to_list()
# avg_temp = sum(temp_list)/len(temp_list)
# print(avg_temp)
avg_temp = data["temp"].mean()
print(f"Average Temp: f{avg_temp}")
max_temp = data["temp"].max()
print(f"Max Temp: {max_temp}")
# Prints Monday row from Data Frame
print(data[data["day"] == "Monday"])
# Prints Row with Max Temp
print(data[data["temp"] == data["temp"].max()])
data[data.temp == data.temp.max()]
# Get Monday's Condition
monday = data[data.day == "Monday"]
print(monday.condition)
# Monday's Temp in F
monday_temp_F = (int(monday.temp) * (9/5) + 32)
print(f"Monday Temp in F: {monday_temp_F}")
student_data = {
"Name": ["Vibin", "Febin", "Nathan", "Nolan"],
"scores": [80, 81, 82, 84]
}
df = pandas.DataFrame(student_data)
print(df)
df.to_csv("student_data.csv")
|
row1=[' ',' ',' ']
row2=[' ',' ',' ']
row3=[' ',' ',' ']
map=[row1,row2,row3]
print(f"{row1}\n{row2}\n{row3}")
position=input("Where do you want to place the treasure?")
print("Position is "+position[0:1]+","+position[1:1])
map [int(position[0:1])-1] [int(position[1:2])-1]="X"
print(f"{row1}\n{row2}\n{row3}") |
import random
tie=0
my_choice=3
while my_choice not in (0,1,2):
my_choice=int(input("enter your choice - 0 for Rock ; 1 for Paper ; 2 for Sciccors:"))
comp_input=random.randint(0,2)
print(f"You chose:{my_choice}")
print(f"Computer chose:{comp_input}")
if (my_choice==comp_input):
print("You're tied! Pls play again!")
exit()
if (my_choice==0):
if(comp_input==1):
you_win=0
else:
you_win=1
elif(my_choice==1):
if(comp_input==2):
you_win=0
else:
you_win=1
else:
if(comp_input==0):
you_win=0
else:
you_win=1
if you_win==0:
print("You Lose!")
else:
print("Yay!! You win!!")
|
# def summ_n_diff(a, b):
# return a+b, a-b
#
# def sum(a):
# return a[0]+a[1]
#
# print(sum(summ_n_diff(10,3)))
import datetime as dt
print(dt.datetime.utcnow())
|
from tkinter import *
window = Tk()
window.title("Mils to Kms Converter")
window.minsize(width=400, height=200)
window.config(padx=40, pady=40)
def convert_miles_to_km():
miles = input_miles.get()
kms = (int(miles)*1.609)
show_result(kms)
def show_result(kms):
kms_val_label.config(text=kms)
input_miles = Entry(width=10)
input_miles.insert(END, string="0")
miles_label = Label(text="Miles", font=("Arial", 16))
is_eq_label = Label(text="is equal to", font=("Arial", 16))
kms_val_label = Label(text="0", font=("Arial", 16, "bold"))
kms_label = Label(text="Km(s)", font=("Arial", 16))
calc_button = Button(text="Calculate", command=convert_miles_to_km)
input_miles.grid(row=0, column=1)
miles_label.grid(row=0, column=2)
miles_label.config(padx=10, pady=10)
is_eq_label.grid(row=1, column=0)
kms_val_label.grid(row=1, column=1)
kms_val_label.config(padx=10, pady=10)
kms_label.grid(row=1, column=2)
calc_button.grid(row=2,column=1)
calc_button.config(padx=10, pady=10)
window.mainloop() |
import jsonpickle
class Parser:
"""Contains methods for storing and loading objects to and from JSON files"""
file_path = ""
def dump_to_file(self, object, file_name):
"""Save an object to a JSON file of the provided name
NOTE: The file path should be set before calling this method.
NOTE 2: As of the current implementation (3/24/17) existing
files are overwritten without warning.
:param Object object: the object to be saved
:param str file_name: the desired file name
"""
jp_object = jsonpickle.encode(object) # Encode using json_pickle to prepare for file writing
f = open(self.file_path+"\\"+file_name, "w+") # Open new file or existing file for writing
f.write(jp_object) # Write to the file
f.close() # Close file
def read_file(self,file_name):
"""Construct and return an object from a JSON file of the provided name
NOTE: The file path should be set before calling this method.
:param str file_name: JSON file from which the object is to be constructed
:return: the object constructed from the JSON file of the provided name
"""
f = open(self.file_path+"\\"+file_name) # Load File specified by user
jp_object = f.read() # Read encoded object from file
f.close() # Close file
object = jsonpickle.decode(jp_object) # Decode file back to its original object
return object
|
# Don't forget to change this file's name before submission.
import sys
import os
import enum
import struct
import socket
class TftpProcessor(object):
"""
Implements logic for a TFTP client.
The input to this object is a received UDP packet,
the output is the packets to be written to the socket.
This class MUST NOT know anything about the existing sockets
its input and outputs are byte arrays ONLY.
Store the output packets in a buffer (some list) in this class
the function get_next_output_packet returns the first item in
the packets to be sent.
This class is also responsible for reading/writing files to the
hard disk.
Failing to comply with those requirements will invalidate
your submission.
Feel free to add more functions to this class as long as
those functions don't interact with sockets nor inputs from
user/sockets. For example, you can add functions that you
think they are "private" only. Private functions in Python
start with an "_", check the example below
"""
class TftpPacketType(enum.Enum):
"""
Represents a TFTP packet type add the missing types here and
modify the existing values as necessary.
"""
RRQ = 1
WRQ = 2
DATA = 3
ACK = 4
ERROR = 5
def __init__(self):
"""
Add and initialize the *internal* fields you need.
Do NOT change the arguments passed to this function.
Here's an example of what you can do inside this function.
"""
self.packet_buffer = []
self.server_address = ("127.0.0.1", 69)
self.mode = "octet"
self.terminate = False
pass
#unkown
def process_udp_packet(self, packet_data, packet_source, databytes = None):
"""
Parse the input packet, execute your logic according to that packet.
packet data is a bytearray, packet source contains the address
information of the sender.
"""
# Add your logic here, after your logic is done,
# add the packet to be sent to self.packet_buffer
# feel free to remove this line
print(f"Received a packet from {packet_source}")
#in_packet = self._parse_udp_packet(packet_data)
#out_packet = self._do_some_logic(in_packet)
out_packet = self._parse_udp_packet(packet_data, databytes)
# This shouldn't change.
self.packet_buffer.append(out_packet)
pass
#common
def _parse_udp_packet(self, packet_bytes,data_bytes): ##parsing file to 512 packets
"""
You'll use the struct module here to determine
the type of the packet and extract other available
information.
"""
out_packet = bytearray()
if(packet_bytes[1] == 3):
print('data')
block_no_1 = packet_bytes[2]
block_no_2 = packet_bytes[3]
print(f'block_no: {block_no_2}, {block_no_1}')
if(len(packet_bytes) < 516):
self.terminate = True
#ack op code
out_packet.append(0)
out_packet.append(4)
#adding block-number
out_packet.append(block_no_1)
out_packet.append(block_no_2)
#print(f"output_packet: {out_packet}")
elif(packet_bytes[1] == 4):
print('Ack')
block_no_1 = packet_bytes[2]
block_no_2 = packet_bytes[3]
block_no_2 += 1
print(f'block_no Upload: {block_no_2} , {block_no_1} ')
#data op code
out_packet.append(0)
out_packet.append(3)
#adding block-number
if(block_no_2 == 256):
block_no_1 += 1
block_no_2 = 0
out_packet.append(block_no_1)
out_packet.append(block_no_2)
#adding data
out_packet += data_bytes
#print(f"output_packet: {out_packet}")
elif(packet_bytes[1] == 5):
self._handle_error(packet_bytes[3])
return out_packet
def _do_some_logic(self, input_packet):
"""
Example of a private function that does some logic.
"""
pass
#upload
def get_next_output_packet(self):
"""
Returns the next packet that needs to be sent.
This function returns a byetarray representing
the next packet to be sent.
For example;
s_socket.send(tftp_processor.get_next_output_packet())
Leave this function as is.
"""
return self.packet_buffer.pop(0)
#upload
def has_pending_packets_to_be_sent(self):
"""
Returns if any packets to be sent are available.
Leave this function as is.
"""
return len(self.packet_buffer) != 0
#download
def request_file(self, file_path_on_server):
"""
This method is only valid if you're implementing
a TFTP client, since the client requests or uploads
a file to/from a server, one of the inputs the client
accept is the file name. Remove this function if you're
implementing a server.
"""
##creating the tftp RRQ format
request = bytearray()
#opcode for RRQ is 01
request.append(0)
request.append(1)
#converting file name to bytes
request += bytearray(file_path_on_server.encode("ASCII"))
#delimiting it by 0
request.append(0)
#adding mode
request += bytearray(self.mode.encode("ASCII"))
print(f"Request {request}")
request.append(0)
return request
#upload
def upload_file(self, file_path_on_server):
"""
This method is only valid if you're implementing
a TFTP client, since the client requests or uploads
a file to/from a server, one of the inputs the client
accept is the file name. Remove this function if you're
implementing a server.
"""
##making tftp format##
request = bytearray()
#opcode for write 02
request.append(0)
request.append(2)
#file name
#print(bytearray(file_path_on_server.encode("ASCII")))
request += bytearray(file_path_on_server.encode("ASCII"))
# request.append(bytes(file_path_on_server,"ASCII"))
#then 0
request.append(0)
#then modes
request += bytearray(self.mode.encode("ASCII"))
#request.append(bytes(self.mode, "ASCII"))
print(f"Request {request}")
request.append(0)
return request
#common
def _handle_error(self, error_num):
#print(error_num)
switcher = {
0 : "Not defined, see error message (if any).",
1 : "File not found.",
2 : "Access violation.",
3 : "Disk full or allocation exceeded.",
4 : "Illegal TFTP operation.",
5 : "Unknown transfer ID.",
6 : "File already exists.",
7 : "No such user.",
}
print(switcher.get(error_num, "Invalid error number"))
exit(-1) #to terminate the program after printing the error
#testing
def check_file_name():
script_name = os.path.basename(__file__)
import re
matches = re.findall(r"(\d{4}_)+lab1\.(py|rar|zip)", script_name)
if not matches:
print(f"[WARN] File name is invalid [{script_name}]")
pass
#common
def setup_sockets(address):
"""
Socket logic MUST NOT be written in the TftpProcessor
class. It knows nothing about the sockets.
Feel free to delete this function.
"""
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #Create udp socket
return client_socket
#common
def do_socket_logic_download(client_socket,request,tf,file):
"""
Gets the Server packet along with the packet source
and sends it for further processing to know which operation to be done depending on op-code
"""
client_socket.sendto(request, tf.server_address)
serverpacket, address = client_socket.recvfrom(4096)
print(serverpacket)
do_file_operation_download(file,serverpacket)
tf.process_udp_packet(serverpacket,address)
while tf.has_pending_packets_to_be_sent():
#print(f"Request to be sent: {request}")
client_socket.sendto(tf.get_next_output_packet(),address)
if not tf.terminate:
serverpacket, address = client_socket.recvfrom(4096)
tf.process_udp_packet(serverpacket,address)
do_file_operation_download(file,serverpacket)
#print(serverpacket)
file.close()
pass
def do_socket_logic_upload(client_socket,request,tf,file):
"""
Gets the Server packet along with the packet source
and sends it for further processing to know which operation to be done depending on op-code
"""
client_socket.sendto(request, tf.server_address)
serverpacket, address = client_socket.recvfrom(4096)
#print(serverpacket)
file_bytes = _read_f_arraybytes(file)
databytes, file_bytes = do_file_operation_upload(file_bytes)
tf.process_udp_packet(serverpacket, address, databytes)
while True:
#print(f"Request to be sent: {request}")
client_socket.sendto(tf.get_next_output_packet(),address)
serverpacket, address = client_socket.recvfrom(4096)
#print(f"Server packets in while {serverpacket}")
databytes, file_bytes = do_file_operation_upload(file_bytes) #to get 512 bytes
if(len(databytes) == 0):
print("File uploaded completed successfully")
break
tf.process_udp_packet(serverpacket, address, databytes)
if not tf.has_pending_packets_to_be_sent():
print("SADASDASDASDASDAASDSA")
file.close()
pass
def _read_f_arraybytes(filename):
"""read file in array of bytes"""
return filename.read()
def do_file_operation_download(file,serverpacket):
if(serverpacket[1] == 3):
file.write(serverpacket[4:])
pass
def do_file_operation_upload(file_bytes):
returnbytes = file_bytes[0 : 512]
file_bytes = file_bytes[512 : len(file_bytes)]
return returnbytes, file_bytes
pass
#common
def parse_user_input(address, operation, file_name=None):
# Your socket logic can go here,
# you can surely add new functions
# to contain the socket code.
# But don't add socket code in the TftpProcessor class.
# Feel free to delete this code as long as the
# functionality is preserved.
client_socket = setup_sockets(address)
tf = TftpProcessor()
if operation == "push":
print(f"Attempting to upload [{file_name}]...")
request = tf.upload_file(file_name)
file = open(file_name,"rb")
do_socket_logic_upload(client_socket,request,tf,file)
print("Upload Complete!")
elif operation == "pull":
print(f"Attempting to download [{file_name}]...")
request = tf.request_file(file_name)
file = open(file_name,"wb")
do_socket_logic_download(client_socket,request,tf,file)
print("File downloaded successfully!")
pass
#common
def get_arg(param_index, default=None):
"""
Gets a command line argument by index (note: index starts from 1)
If the argument is not supplies, it tries to use a default value.
If a default value isn't supplied, an error message is printed
and terminates the program.
"""
try:
return sys.argv[param_index]
except IndexError as e:
if default:
return default
else:
print(e)
print(
f"[FATAL] The comamnd-line argument #[{param_index}] is missing")
exit(-1) # Program execution failed.
def main():
"""
Write your code above this function.
if you need the command line arguments
"""
print("*" * 50)
print("[LOG] Printing command line arguments\n", ",".join(sys.argv))
check_file_name()
print("*" * 50)
# This argument is required.
# For a server, this means the IP that the server socket
# will use.
# The IP of the server, some default values
# are provided. Feel free to modify them.
ip_address = get_arg(1, "127.0.0.1")
operation = get_arg(2, "push")
file_name = get_arg(3, "test.txt")
# Modify this as needed.
parse_user_input(ip_address, operation, file_name)
if __name__ == "__main__":
main() |
a = 1
b = 2
print (a,b)
w ="Do I love Anan?"
print("I said:%r" % w)
|
# https://colab.research.google.com/notebooks/mlcc/tensorflow_programming_concepts.ipynb#scrollTo=SDbi6heigEGA
from __future__ import print_function
import tensorflow as tf
import matplotlib.pyplot as plt # Dataset visualization.
import numpy as np # Low-level numerical Python library.
import pandas as pd # Higher-level numerical Python library.
from tensorflow_core.python.framework.ops import Tensor, Graph
print(tf.__version__)
# Create a graph.
g = tf.Graph()
# Establish the graph as the "default" graph.
with g.as_default():
# Assemble a graph consisting of the following three operations:
# * Two tf.constant operations to create the operands.
# * One tf.add operation to add the two operands.
x = tf.constant(8, name="x_const")
y = tf.constant(5, name="y_const")
my_sum = tf.add(x, y, name="x_y_sum")
# Now create a session.
# The session will run the default graph.
with tf.Session as sess:
print(my_sum.eval())
z = tf.constant(4, name="z_const")
new_sum = tf.add(my_sum, z, name="x_y_z_sum")
with tf.Session as sess:
print(new_sum.eval())
|
# https://stackabuse.com/creating-a-neural-network-from-scratch-in-python/
"""
Neural Network Theory
A neural network is a supervised learning algorithm which means that we provide it the input data containing the independent
variables and the output data that contains the dependent variable.
In the beginning, the neural network makes some random predictions, these predictions are matched with the correct output and
the error or the difference between the predicted values and the actual values is calculated. The function that finds the
difference between the actual value and the propagated values is called the cost function. The cost here refers to the error.
Our objective is to minimize the cost function. Training a neural network basically refers to minimizing the cost function.
Back Propagation
Step 1: Calculating the cost
The first step in the back propagation section is to find the "cost" of the predictions. The cost of the prediction can simply
be calculated by finding the difference between the predicted output and the actual output. The higher the difference, the
higher the cost will be.
Step 2: Minimizing the cost
Our ultimate purpose is to fine-tune the knobs of our neural network in such a way that the cost is minimized. If your look
at our neural network, you'll notice that we can only control the weights and the bias. Everything else is beyond our control.
We cannot control the inputs, we cannot control the dot products, and we cannot manipulate the sigmoid function.
In order to minimize the cost, we need to find the weight and bias values for which the cost function returns the smallest
value possible. The smaller the cost, the more correct our predictions are.
This is an optimization problem where we have to find the function minima.
To find the minima of a function, we can use the gradient decent algorithm.
"""
import numpy as np
feature_set = np.array([[0,1,0],[0,0,1],[1,0,0],[1,1,0],[1,1,1]])
labels = np.array([[1,0,0,1,1]])
labels = labels.reshape(5,1)
np.random.seed(42)
weights = np.random.rand(3,1)
bias = np.random.rand(1)
lr = 0.05
def sigmoid(x):
return 1/(1+np.exp(-x))
#And the method that calculates the derivative of the sigmoid function is defined as follows:
def sigmoid_der(x):
return sigmoid(x)*(1-sigmoid(x))
for epoch in range(20000):
inputs = feature_set
# feedforward step1
XW = np.dot(feature_set, weights) + bias
#feedforward step2
z = sigmoid(XW)
# backpropagation step 1
error = z - labels
print(error.sum())
# backpropagation step 2
dcost_dpred = error
dpred_dz = sigmoid_der(z)
z_delta = dcost_dpred * dpred_dz
inputs = feature_set.T
weights -= lr * np.dot(inputs, z_delta)
for num in z_delta:
bias -= lr * num
XW = np.dot(feature_set, weights) + bias
z = sigmoid(XW)
error = z - labels
dcost_dpred = error # ........ (2)
dpred_dz = sigmoid_der(z) # ......... (3)
#slope = input x dcost_dpred x dpred_dz
#Take a look at the following three lines:
z_delta = dcost_dpred * dpred_dz
inputs = feature_set.T
weights -= lr * np.dot(inputs, z_delta)
"""
You can now try and predict the value of a single instance. Let's suppose we have a record of a patient that comes in who smokes,
is not obese, and doesn't exercise. Let's find if he is likely to be diabetic or not. The input feature will look like this: [1,0,0].
"""
single_point = np.array([1,0,0])
result = sigmoid(np.dot(single_point, weights) + bias)
print("")
print(result)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 10:56:56 2019
PURPOSE: Return a numpy array that contains binary labels for "male" and "female"
REQUIRES:
import numpy as np
from sklearn.preprocessing import LabelEncoder
INPUT:
df: pandas dataframe
col: str
name of column that contains male and female assignments
male_female: list
list of the two terms that are used to describe male and female in the source file
OUTPUT:
binary_labels: numpy array that contains binarized male/female labels
le:
@author: duchezbr
"""
def binarize_male_female(df, col, male_female):
le = LabelEncoder()
le.fit(male_female)
binary_labels = le.transform(df[col].values)
return binary_labels, le
|
tupla = ("Python","Java","Android",12,[1,2,3],(1,2))
tupla[0] #A saída disso será 'Python'
print(tupla)
dir(tupla)
tupla.append(15) #Retorna uma exception porque tupla é imutável
tupla.count("Python") #Quantas vezes python aparece na tupla
tupla[4].append(4) #Isso funciona porque está manipulado uma lista dentro de uma tupla |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def __len__(self):
count = 0
head = self.head
while head:
count += 1
head = head.next
return count
def add_node_end(self, value):
temp = Node(value=value)
if not self.head:
self.head = temp
return
node = self.head
while node.next:
node = node.next
node.next = temp
def add_node_beginning(self, value):
temp = Node(value=value)
temp.next = self.head
self.head = temp
def in_between(self, existing_node, value):
node = Node(value=value)
if not existing_node:
return
node.next = existing_node.next
existing_node.next = node
def remove(self, key):
head = self.head
if head and head.value == key:
self.head = head.next
head = None
return
while head:
if head.value == key:
break
prev = head
head = prev.next
if not head:
return
prev.next = head.next
head = None
def traverse(self):
result = []
node = self.head
while node:
result.append(node.value)
node = node.next
return result
def remove_last(self):
head = self.head
if not head:
return
if not head.next:
head = None
return
while head.next.next:
head = head.next
head.next = None
if __name__ == '__main__':
sll = SinglyLinkedList()
items = [12, 13, 14, 15, 16, 17, 18, 19, 20]
for item in items:
sll.add_node_end(item)
print(sll.traverse())
sll.remove(15)
sll.remove(20)
sll.in_between(sll.head.next.next, 15)
print(sll.traverse())
print(len(sll))
sll.remove_last()
print(sll.traverse())
|
from typing import Callable, Any, List
# Problem: https://challenges.wolframcloud.com/challenge/flutter
def flutter(f: Callable, x: Any, items: List[Any]) -> List[Callable]:
"""
params:
X = 2
L = [a, b, c, d]
returns:
{f[2, a], f[2, b], f[2, c], f[2, d]}
"""
results = []
for item in items:
results.append(f(x, item))
return results
def check_equals(x, y):
return x == y
def subtract(x, y):
results = []
for i in x:
k = i - y
results.append(k)
return results
if __name__ == '__main__':
res = flutter(subtract, [1, 2], [5, 19, 2])
print(res)
|
def dijkstra_algorithm():
heap = []
heappush(heap, (0, start)) # Initialize start with zero cost
came_from = {}
# For node n, g_score[n] is the cost of the cheapest path from start to n currently known.
g_score = defaultdict(int)
g_score[start] = 0
result = None
while heap:
cost, current = heappop(heap)
if current == goal:
total_path = [current]
while current in came_from:
current = came_from[current]
total_path = [*[current], *total_path]
result = total_path
break
neighbours = neighbouring_vectors(current, h, w)
for nr in neighbours:
child = (nr.x, nr.y)
if child not in g_score:
g_score[child] = math.inf
# d(current, child) is the weight of the edge from current to child
t_score = g_score[current] + dist(current, child)
if t_score < g_score[current]:
came_from[child] = current
g_score[child] = t_score
if not contains(heap, child):
heappush(heap, (t_g_score, child))
|
"""
Imports
"""
def straight_insertion_sort(_a: list):
"""
The simplest insertion sort is the most obvious one
"""
_n = len(_a)
for j in range(1, _n):
i = j - 1
k = _a[j]
_r = _a[j]
while i >= 0 and k < _a[i]:
_a[i + 1] = _a[i]
i = i - 1
_a[i + 1] = _r
return _a
def isort(array):
n = len(array)
i = 0
j = 1
is_sorted = True
while 1:
x = array[i]
y = array[j]
if x > y:
array[i] = y
array[j] = x
is_sorted = False
i += 1
j += 1
if j >= n:
i = 0
j = 1
if is_sorted:
break
return array
if __name__ == "__main__":
A = [
23, 128, 41, 1, 32, 3, 0, 93, 23, 42, 54, 12, 31, 14, 5, 87, 41, 10,
11, 9, 7, 2
]
RESULT = isort(A)
print(RESULT)
|
import re
def polish_function(expression):
expression = re.sub(r'\s+', '', expression)
maps = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y
}
stack = []
error = ''
for item in expression:
try:
if item == ')':
prev = stack.pop()
res = None
op = ''
while prev != '(':
if prev in maps and res is not None:
op = prev
elif res is None:
parsed = prev
while parsed:
# we handle cases where we a 5 * 234. Without this 5 * 2 will be evaluated
prev = stack.pop()
if prev not in maps and prev not in '()':
parsed = prev + parsed
else:
stack.append(prev)
break
res = int(parsed)
else:
res = maps[op](int(prev), res)
prev = stack.pop()
stack.append(res)
else:
stack.append(item)
except ZeroDivisionError:
error = 'Cannot divide by zero value.'
except Exception as e:
stack.append(item)
if error:
return error
return stack[0]
if __name__ == '__main__':
expression = '((((5 + 15) * 6 * 7) * 2) / (9 - 2))'
result = polish_function(expression)
print(result)
|
def fib(d):
a = 0
b = 1
n = 1
while 1:
x = a + b
a = b
b = x
n += 1
if count_digits(x) == d:
break
return n
def count_digits(n):
t = 0
while n >= 10:
n //= 10
t += 1
return t + 1
result = fib(1000)
print(result)
|
import math
from time import sleep
from collections import Counter
from read_file import read_data
def part_one(timers, days=80):
n_timers = timers
number_of_fish = len(n_timers)
counter = Counter(n_timers) # Keep a count of each timer
ncount = 0
def _process(timer):
k = timer - 1
if k < 0: # reset elapsed time
k = 6 # 6 because lanternfish are assumed to spawn after 7 days and 0 is considered
return k
def _counter(list_tuple):
"""This function creates new Counter and assigns to counter.
This handles a case where the a doublicates for example n_t variable on line 34
if n_t = [(2, 3), (2,4), (1,3), (1,5)] then counter will be {2: 7, 1: 8}
"""
seen = {}
for item in list_tuple:
key, value = item
try:
seen[key] += value
except Exception as e:
seen[key] = value
return seen
for day in range(days):
k, count = math.inf, 0
n_t = [] # keep updated time and the count of that time i.e [(3, 14)] means 3 days appear 4 times
if ncount:
n_t.append((8, ncount))
number_of_fish += ncount # old population plus new
for key, value in counter.items():
ncount = 0
k = _process(key)
n_t.append((k, value))
if not k: # time has time has elapsed, so lanternfish can spawn new ones
count += value
ncount = count # ncount is the number of new lanternfish based of elapsed time
counter = _counter(n_t)
print(f'After {day + 1} day = {number_of_fish}')
return number_of_fish
def part_two(timers):
return part_one(timers, 1000)
if __name__ == '__main__':
data = read_data('data/2021/day6_input.txt', parser=int, sep=',')
result_p1 = part_one(data)
result_p2 = part_two(data)
print(result_p1, result_p2)
|
import base64
from encoding import split_in_twos
def read_file(filename):
return open(filename)
def create_file(encoded_file: str):
# Create and manually unzip or you can do it with python using zipfile lib
with open('data/output.zip', 'wb') as f:
base64.decode(encoded_file, f)
def decode():
flag = split_in_twos(read_file('data/flag.txt').read(), 2)
xor_key = split_in_twos(read_file('data/xor_key.txt').read())
text = ''
for x, y in zip(flag, xor_key):
k = int(x, 16)
char = chr(k ^ ord(y))
text += char
return text
if __name__ == '__main__':
encoded = read_file('data/base64.txt')
create_file(encoded)
d = decode()
print(d)
|
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
from keras.layers.normalization import BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
def get_small_cnn_model(input_shape=(28, 28, 1),num_classes=10):
# Three steps to create a CNN
# 1. Convolution
# 2. Activation
# 3. Pooling
# Repeat Steps 1,2,3 for adding more hidden layers
# 4. After that make a fully connected network
# This fully connected network gives ability to the CNN
# to classify the samples
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Flatten())
# Fully connected layer
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer=Adam(), metrics=['accuracy'])
model.count_params()
return model
|
#Everett Williams
#14JUL17 as of 150755JUL17
#HW3 Problem 4
#Make Change program
def buildCoinsArr(coinsUsed, coinSet):
start = len(coinsUsed)-1
numCoinsUsed = []
#initialize numCoinsUsed to 0. This array will be used to track
#the number of each coin that was used.
for i in range(0, len(coinSet)):
numCoinsUsed.append(0)
#accumulate the coins
while start != 0:
numCoinsUsed[coinsUsed[start]] = numCoinsUsed[coinsUsed[start]]+1
start = start - coinSet[coinsUsed[start]]
return numCoinsUsed
#read data from amount.txt and store the coin denominations as integers into the
#list dataArray return unsorted array
def readWriteArray():
with open('amount.txt') as data:
lineCount = 0
val = -1
for line in data:
if lineCount%2 == 0:
dataArray = []
line = line.split() # to deal with blank
if line: # lines (ie skip them)
for value in line:
num = int(value)
dataArray.append(num)
elif lineCount%2 == 1:
val = line.rstrip("\n")
coinNum, coinsUsed = makeChange(dataArray, int(val))
outPutToFile(dataArray, val, coinsUsed, coinNum)
lineCount+=1
#write change results to change.txt
def outPutToFile(coinDenom, val, coinsUsed, coinNum):
with open('change.txt', 'a') as outPutFile:
for i in coinDenom:
num = str(i)
outPutFile.write(num + " ")
outPutFile.write("\n")
outPutFile.write(val)
outPutFile.write("\n")
for i in coinsUsed:
num = str(i)
outPutFile.write(num + " ")
outPutFile.write("\n")
outPutFile.write(str(coinNum))
outPutFile.write("\n")
def makeChange(coinSet, value):
numCoins=[]
coinsUsed=[]
#initialize the counting array (numCoins) with values infinity, since we know
#no number is greater than infinity. This ensures that a count is made upon
#a initial visit
for i in range(0, value + 1):
if i == 0:
numCoins.append(0)
else:
numCoins.append(float('inf'))
#initialize the tracking array (coinsUsed) to track the coin with the greatest
#value that was used to make the particular value represented with the array
#indice. The array was initialized with inf since that value will never be
#a valid denomination.
for i in range(0, value + 1):
coinsUsed.append(float('inf'))
for j in range(len(coinSet)):
for i in range(1, value + 1):
if i >= coinSet[j]: #avoids index errors
if numCoins[i] > (1 + numCoins[i - coinSet[j]]):
numCoins[i] = (1 + numCoins[i - coinSet[j]])
coinsUsed[i] = j
coins=buildCoinsArr(coinsUsed,coinSet)
return numCoins[-1], coins
def main():
readWriteArray()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def fun1(x,n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
def fun2(*numbers):
s = 0
for n in numbers:
s = s + n * n
return s
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
def person(name, age, **kw):
if 'city' in kw:
# 有city参数
pass
if 'job' in kw:
# 有job参数
pass
print('name:', name, 'age:', age, 'other:', kw)
# 命名关键字参数 特殊分隔符*,*后面的参数被视为命名关键字参数 本例为city job
# 有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了 name, age, *args, city, job
def person(name, age, *, city, job):
print(name, age, city, job)
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
|
class Tree:
def __init__(self, me, left, right):
self.me = me
self.left = left
self.right = right
self.visit = 0
def make(tree):
if tree.visit == 0:
tree.left = Tree(tree.me + 1, 0, 0)
make(tree.left)
tree.visit = 1
tree.right = Tree(tree.left.me + 1)
make(tree.right)
t = int(input())
for tc in range(1, t + 1):
N = int(input())
children = [0] * (N + 1)
visit = [0] * (N + 1)
t = Tree(1, 0, 0)
print(t.me, t.left, t.right)
# getlist = make(t)
# root, half = find(getlist, N)
# print("#{} {} {}".format(tc, root, half))
|
def check(line):
temp = []
i = 0
for cnt in range(len(line)):
if line[i] == '{':
temp.append('{')
if line[i] == '(':
temp.append('(')
if line[i] == '}':
if not temp:
return 0
if temp[-1] == '(':
return 0
else:
temp.pop()
if line[i] == ')':
if not temp:
return 0
if temp[-1] == '{':
return 0
else:
temp.pop()
i += 1
if temp:
return 0
return 1
test_case = int(input())
for case in range(1, test_case + 1):
get = input()
print("#{} {}".format(case, check(get))) |
def find(N):
global board
t = int(input())
for tc in range(1, t+1):
N = int(input())
board = [[0]*N for i in range(N)]
res = find(N)
print("#{} {}".format(tc, res)) |
for i1 in range(1, 4):
for i2 in range(1, 4):
if i2 != i1:
for i3 in range(1, 4):
if i3 != i1 and i3 != i2:
print(i1, i2, i3)
def perm(n, k, m): # m 개의 숫자들에서 k자리의 순열 n은 현재 위치
global arr
if k == n:
print(arr)
else:
for i in range(n, m):
arr[n], arr[i] = arr[i], arr[n]
perm(n + 1, k, m)
arr[n], arr[i] = arr[i], arr[n]
arr = [1, 2, 3, 4, 5, 6]
perm(0, 6, 6) |
def change(i, j, S, ok):
global board
global setting
global N
di, dj = setting[S] # 증가값
ni, nj = i + di, j + dj # 변화값
before = board[i][j]
after = board[ni][nj]
if S == 'up':
print(board)
if i == 0 and after == 0:
if i < N - 2:
change(i + 1, j, S, False)
if before == after and ok and before != 0:
board[i][j] = before + after
board[ni][nj] = 0
if i < N - 2:
change(i + 1, j, S, ok)
elif before == 0:
board[i][j] = after
board[ni][nj] = 0
if i < N - 2:
change(i + 1, j, S, False)
change(i, j, S, ok)
else:
if i < N - 2:
change(i + 1, j, S, ok)
def doit(N, S):
global board
board = list(map(list, zip(*board)))
for i in range(N):
for j in range(N):
if board[i][j] == 0:
del board[i][j]
board[i].append(0)
board = list(map(list, zip(*board)))
t = int(input())
for tc in range(1, t + 1):
N, S = input().split()
N = int(N)
board = [list(map(int, input().split())) for i in range(N)]
setting = {'up': [1, 0], 'down': [1, 0], 'left': [0, -1], 'right': [0, 1]}
for j in range(N):
doit(N, S)
change(0, j, S, True)
print("#{}".format(tc))
for line in board:
print(*line)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sort_utils import swap
def sort(array):
"""
Selection sort
Complexity
Memory
O(n) - since all swaps "in place"
and no addition data strictures requires
Time
Always O(n^2) - because no matter how array element is placed,
second pointer go till the end
"""
for i in range(len(array)):
j = i
while j > 0 and array[j - 1] > array[j]:
swap(array, j, j - 1)
j -= 1
|
import random
import nltk
from sequences import *
"""
Best sequence
eg. for she were today (if there is not any appearence of 'she were today')
she <is> today
she <was> <yesterday>
Generate
random [w1,w2,w3][w2,w3,w4][w3,w4,w5]...
r.prob [w1,w2,w3]hp[w2,w3,w4].... the higher probability trigram that has w2 and w3 and not w1
"""
#
# @ngram
# a ngram
#
#
# @words MIN=1 MAX=4
# words to be used as seed
# eg. word ['it','is','good'] *see example bellow
#
#
# @rank
# the top most frequentes
#
#
# @randomize
# if that option is True then the return list will be only one value radomically choose from
# the original list
#
# example. [the,a,not,it]
# randomically choose 'not' the return will be [she,is,[not]]
#
#
#
# return
# words[]
# example. words = [she,is]
# [she,is,[the,a,not,it]]
#
#
###############
#
#
# nextMostProbablyWord(trigram,['a','b'],3)
# P(w|a,b) given w as any word in the corpus, return the three words (w1,w2,w3)
# that has the highest odd
#
# 3 in max(P(w|a,b))
#
#
###############
def nextMostProbablyWord(ngram,words,rank=1,randomize=False):
"""
examples
corpus = "a b c d a b c a d d d a b c d a d b".split()
Input: nextWord(getBigram(corpus),['b'])
Output : ['b', ['c']] it's means that the most probable next word is c
Input: nextWord(getBigram(corpus),['b'],2)
Output : ['b', ['#','c']] it's means that the most probable next word is c and #
Input: nextWord(getBigram(corpus),['b'],2,True)
Output : ['b', ['#'] or ['c']] it's means that among the most two frequent words randomically
will random '#' or 'c'
Input: nextWord(getTrigram(corpus),['b','c'],2)
Output : ['b','c' ['a','d']] it's means that the most probable next two words following
after 'b c' are 'a' and 'd'
"""
type_ngram = detectNgram(ngram)
if type_ngram < 2:
raise NameError("Type of Ngram cannot be lower than 2, for unigrans use generateTextByNgram")
if len(words) >= type_ngram:
raise NameError("too much words to process <nextWord:function> %d" % len(words))
if len(words)+1 < type_ngram:
raise NameError("insufficiente words to process <nextWord:function> %d " % len(words))
if type_ngram == 2:
if words[-1] in ngram:
ngram_sorted = sortNgram(ngram[words[-1]])
limite_rank = min(rank,len(ngram_sorted))
most_frequent_words = [n[1]for n in ngram_sorted[-limite_rank:]]
words.append(most_frequent_words)
else:
ngram_sorted = sortNgram(ngram)
words.pop() #delete the last word since it was not found in the bigrams
#eg. she is <the word is was not found in the bigrams[she][is]
limite_rank = min(rank,len(ngram_sorted))
words.append([w[1].split("_")[-1] for w in ngram_sorted[-limite_rank:]])
#since the simbol '_' is used to separete unigrams
#eg. she_is
elif type_ngram == 3:
if words[-2] in ngram: #ex [she] is | 'she' in ngram
if words[-1] in ngram[words[-2]]: #ex 'is' in ngram[she]
unigrams = ngram[words[-2]][words[-1]] #ex. ngram[she][is] = [cute,pretty,tall,smart...]
ngram_sorted = sortNgram(unigrams) #ex. sort by most frequents
limite_rank = min(rank,len(ngram_sorted))
words.append([w[1] for w in ngram_sorted[-limite_rank:]])
else:
bigrams = ngram[words[-2]]
ngram_sorted = sortNgram(bigrams)
words.pop() #delete the last word since it was not found in the bigrams
#eg. she is <the word is was not found in the bigrams[she][is]
limite_rank = min(rank,len(ngram_sorted))
words.append([w[1].split("_")[-1] for w in ngram_sorted[-limite_rank:]])
#since the simbol '_' is used to separete unigrams
#eg. she_is
else:
ngram_sorted = sortNgram(ngram)
words.pop() #delete the last word since it was not found in the trigrams
#eg. she is pretty <the word is was not found in the trigram[she][is][pretty]
limite_rank = min(rank,len(ngram_sorted))
words.append([w[1].split("_")[-1] for w in ngram_sorted[-limite_rank:]])
#since the simbol '_' is used to separete unigrams
#eg. she_is_pretty
if randomize:
#print words
words[-1] = [words[-1][random.randint(0,len(words[-1])-1)]]
return words
#
# @ngram
# ngram data
#
# @length
# length of the text generated
#
#
# w1,w2,w3 w2,w3,w4 w3,w4,w5
#
def generateTextByNgram(ngram,length):
type_ngram = detectNgram(ngram)
text_generate = ""
if type_ngram == 1:
tokens = ngram.keys()
for t in xrange(length):
text_generate += " "+ tokens[random.randint(0,len(tokens)-1)]
elif type_ngram >= 2:
ngram_sorted = sortNgram(ngram)
for t in xrange(length-1):
bigram = ngram_sorted[random.randint(0,len(ngram_sorted)-1)][1]
text_generate += " "+" ".join(bigram.split("_"))
return text_generate[1:]
#
# @ngram
# ngram data
#
# @seed
# a list of words to start the generation
#
#
# @length
# length of the text generated
#
#
# @rank
# the top most frequentes
#
#
#TODO is better choose automatically the seed?
def generateTextByNextWord(ngram,seed,length,rank):
text_generate = " ".join(seed)+ " "
type_ngram = detectNgram(ngram)
for i in xrange(length):
seed = nextMostProbablyWord(ngram,seed,rank,True)
#print seed,
if type_ngram == 2:
seed = seed[-1]
elif type_ngram == 3:
seed = [seed[-2],seed[-1][0]]
else:
seed = [seed[-3],seed[-2],seed[-1][0]]
#print seed
text_generate += seed[-1]+" "
return text_generate
def tests():
corpus = "a b c d a b c a d d d a b c d a d b".split()
unigram = getUnigram(corpus)
bigram = getBigram(corpus)
trigram = getTrigram(corpus)
if not nextWord(trigram,['a','b'],3,1) == ['a','b',['c']]:
raise NameError("Excepted ['a','b',['c']],but was %s" % str(nextWord(trigram,['a','b'],3,1)))
else:
print "TEST 1 - OK"
####################################################################################
file_corpus = open("/Users/diegopedro/Documents/corpora/data/citations/authors_30_2010.txt").read()
corpus = nltk.word_tokenize(file_corpus.lower().decode("utf-8"))
#unigram = getUnigram(corpus)
bigram = getBigram(corpus)
trigram = getTrigram(corpus)
#fourgram = getFourgram(corpus)
print generateTextByNextWord(bigram,['she'],100,8)
print "#"*70
print generateTextByNextWord(trigram,['she','has'],100,8)
#print "#"*70
#print generateTextByNextWord(fourgram,['she','has','been'],5,5)
|
"""
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,
their colleagues and Jeremy Roy.
"""
########################################################################
# Done: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# Done: 2.
#
# You should have RUN the PREVIOUS module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOUR WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT your work by using VCS ~ Commit and Push.
########################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
jeff = rg.SimpleTurtle("turtle")
jeff.pen = rg.Pen('green', 5)
jeff.speed = 10
size = 420
for k in range(13):
jeff.draw_circle(size)
jeff.pen_up()
jeff.forward(15)
jeff.right(29)
jeff.pen_down()
size = size - 69
greg = rg.SimpleTurtle()
greg.pen = rg.Pen('red', 10)
greg.speed = 6
size = 341
for k in range(17):
greg.draw_square(size)
greg.pen_up()
greg.forward(19)
greg.right(23)
greg.pen_down()
size = size - 65
|
def fib_dict(i, d):
"""
Get Fibonacci Sequence using dictionary
which is more efficient than using recursion
i - get n of Fibonacci Sequence
d - dictionary that store Fibonacci Sequence
"""
if (i == 0 or i == 1) and i not in d:
d[i] = 1
return d[i]
if i in d:
return d[i]
else:
fib = fib_dict(i-1, d) + fib_dict(i-2, d)
d[i] = fib
return fib
dictionary = {}
fib_dict(9, dictionary)
print('Fibonacci Sequence: ')
print(dictionary.values()) |
from getpass import getpass
d = {
"spy": "spy",
"p": "private",
"serg": "sergeant",
"2l": "2nd lieutenant",
"1l": "1st lieutenant",
"capt": "captain",
"m": "major",
"lc": "lieutenant colonel",
"col": "colonel",
"1g": "1 star general",
"2g": "2 star general",
"3g": "3 star general",
"4g": "4 star general",
"5g": "5 star general"
}
while True:
while True:
p1 = getpass("Attacking: ")
if p1 == "q":
break
if p1 not in d.keys():
print("Invalid game piece")
else:
break
if p1 == "q":
break
while True:
p2 = getpass("Defending: ")
if p2 == "q":
break
if p2 not in d.keys():
print("Invalid game piece")
else:
break
if p2 == "q":
break
print(f"Attacking: {d[p1]}")
print(f"Defending: {d[p2]}")
|
from random import shuffle
def print_board(queen_pos):
"""
Prints board on screen
:param queen_pos: list of queens' positions
"""
board_size = len(queen_pos)
for x in range(board_size):
for y in range(board_size):
if queen_pos[y] == x:
print(' Q ', end='')
else:
print(' . ', end='')
print()
def random_board(board_size):
"""
Generates a random board of size 'board_size'. Returns the list of queens' positions
"""
queen_pos = list(range(board_size))
shuffle(queen_pos)
return queen_pos
|
done = False
while not done:
number = int(input("What numbers times table would you like? > "))
upto = int(input('what number would you like it to go up to? > '))
upto += 1
for i in range(1,upto):
answer = i*number
print(i,"x",number,"=",answer)
again = input('would you like to enter another number? (Y/N) > ')
if again == 'N' or again == 'n':
done = True
|
1 = "januarry"
2 = "Febuary"
3 = "March"
4 = "April"
5 = "May"
6 = "June"
7 = "July"
8 = "August"
9 = "September"
10 = "October"
11 = "November"
12 = "December"
month = int(input("Enter a month (number) > "))
if number > 12 and number < 1:
print("Between 1 and 12!")
elif number == 1:
print(1)
elif number == 2:
print(2)
elif number == 3:
print(3)
elif number == 4:
print(4)
elif number == 5:
print(5)
elif number == 6:
print(6)
elif number == 7:
print(7)
elif number == 8:
print(8)
elif number == 9:
print(9)
elif number == 10:
print(10)
elif number == 11:
print(11)
elif number == 12:
print(12)
|
#running total
total = 0
for i in range(5):
new_number = int(input("Enter a number: " ))
total += new_number
print("The total is: ", total)
|
import random
print('Welcome to Camel!')
print('You have stolen a camel to make your way across the great Mobi desert.')
print('The natives want their camel back and are chasing you down! Survive your')
print('desert trek and out run the natives.')
done = False
traveled = 0
thirst = 0
tiredness = 0
Ndistance = 30
drinks = 3
while not done:
print('A. Drink from your canteen.\nB. Ahead moderate speed.\nC. Ahead full speed.\nD. Stop for the night.\nE. Status check.\nQ. Quit.')
choice = input('Your choice? > ')
oasis = random.randrange(1,21)
if choice == 'Q' or choice == 'q':
done = True
elif choice == 'E' or choice == 'e':
print('Miles traveled:', traveled)
print('Drinks in canteen:', drinks)
print('The natives are', Ndistance,'miles behind you')
elif choice == 'd' or choice == 'D':
tiredness = 0
print('The camel is happy!')
Ndistance -= random.randrange(3,11)
elif choice == 'C' or choice == 'c':
traveled += random.randrange(10,21)
print('You have traveled',traveled,'miles')
thirst += 1
tiredness += random.randrange(1,4)
Ndistance -= random.randrange(3,11)
elif choice == 'B' or choice == 'b':
traveled += random.randrange(5,13)
print('You have traveled',traveled,'miles')
thirst += 1
tiredness += 1
Ndistance -= random.randrange(3,11)
elif choice == 'A' or choice == 'a':
if drinks > 0:
drinks -= 1
thirst = 0
else:
print('You are out of drinks!')
if thirst > 4 and thirst < 7:
print('You are thirsty')
elif thirst > 6:
print('You died of thirst!')
done = True
if tiredness > 5 and tiredness < 9:
print('Your camel is getting tired')
elif tiredness > 8:
print('Your camel is dead!')
done = True
if Ndistance < 1:
print('The natives caught up!')
done = True
elif Ndistance > 0 and Ndistance < 15:
print('The natives are getting close!')
if traveled > 199:
print('You crossed the dessert. You win!')
done = True
elif oasis == 1:
print('You found an oasis!\nYou fill up your bottle and have a drink!')
drink = 3
thirst = 0
|
temp = int(input("What is the temperature of the water?(degrees) > "))
if temp > 100:
print("The water is boiling")
elif temp < 0:
print("The water is frozen)
else:
Print("The water is liquid")
|
number = 1
while number < 10:
print("This is turn ",number)
number += 1
print("The loop is now finnished")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.