text
stringlengths 37
1.41M
|
---|
from typing import List
# Name: Number Of Rectangles That Can Form The Largest Square
# Link: https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/
# Difficulty: Easy
# Method: Find max and count
# Time: O(n)
# Space: O(1)
class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
max_len = 0
for w, l in rectangles:
max_len = max(max_len, min(w, l))
max_occ = 0
for w, l in rectangles:
square_len = min(w, l)
if square_len == max_len:
max_occ += 1
return max_occ
if __name__ == "__main__":
exs = (
[],
[[5, 8], [3, 9], [5, 12], [16, 5]],
[[2, 3], [3, 7], [4, 3], [3, 7]],
)
sol = Solution()
for rect in exs:
print(
f"For input {rect}, found occurence of max len {sol.countGoodRectangles(rect)}"
)
|
from typing import List
class Solution:
def reconstructMatrix(
self, upper: int, lower: int, colsum: List[int]
) -> List[List[int]]:
n = len(colsum)
up = [0 for _ in range(n)]
down = [0 for _ in range(n)]
for i in range(n):
x = colsum[i]
print(f"{i} {x} up= {up}\tdown={down}, limits up: {upper} down: {lower}")
if x == 0:
continue
elif x == 2:
up[i] = 1
down[i] = 1
upper -= 1
lower -= 1
for i in range(n):
x = colsum[i]
print(f"{i} {x} up= {up}\tdown={down}, limits up: {upper} down: {lower}")
if x != 1:
continue
if upper > 0:
up[i] = 1
upper -= 1
elif lower > 0:
down[i] = 1
lower -= 1
else: # Wait, that's illegal
return []
if upper != 0 or lower != 0:
return []
return [up, down]
if __name__ == "__main__":
upper = 5
lower = 5
colsum = [2, 1, 2, 0, 1, 0, 1, 2, 0, 1]
sol = Solution()
print(f"Ans: {sol.reconstructMatrix(upper,lower,colsum)}")
|
from collections import defaultdict
from typing import List
# Name: Number of Connected Components in an Undirected Graph
# Link: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
# Method: DFS from every node to n
# Time: O(n)
# Space: O(n + e)
# Difficulty: Medium
# Note: n = nr of nodes, e = nr of edges
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
graph = defaultdict(set)
for a, b in edges:
graph[a].add(b)
graph[b].add(a)
comps = 0
seen = set()
for node in range(n):
if node in seen:
continue
comps += 1
to_visit = [node]
seen.add(node)
while to_visit:
node_now = to_visit.pop()
for vecin in graph[node_now]:
if vecin not in seen:
to_visit.append(vecin)
seen.add(vecin)
return comps
|
from typing import List
# Name: Minimum Size Subarray Sum
# Link: https://leetcode.com/problems/minimum-size-subarray-sum/
# Method: Sliding window, once target sum is passed, reduce from left side as much as possible
# Time: O(n)
# Space: O(1)
# Difficulty: Medium
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
if sum(nums) < target:
return 0
elif sum(nums) == target:
return len(nums)
start = 0
end = 0
sum_now = 0
min_size_now = len(nums) + 1
while end < len(nums):
sum_now += nums[end]
while sum_now - nums[start] >= target and start <= end:
sum_now -= nums[start]
start += 1
if sum_now >= target:
min_size_now = min(min_size_now, end - start + 1)
end += 1
return min_size_now
if __name__ == "__main__":
folder = [2, 3, 1, 2, 4, 3]
sol = Solution()
print(f"Ans: {sol.minSubArrayLen(7, folder)}")
|
#!/bin/python3
import math
import os
import random
import re
import sys
def equal(orignal_arr):
results = []
for i in range(5):
minim = min(orignal_arr)-i
results.append(actualEqual(orignal_arr, minim))
print(results)
return min(results)
def actualEqual(original_arr,min):
moves =0
for x in original_arr:
x = x-min
if x > 0:
# How many substract 5, substract 2 and finnaly ones
moves += int(x / 5) + int(x % 5 / 2) + int(x % 5 % 2)
print(f"{original_arr} gets moves {moves}")
return moves
if __name__ == '__main__':
t = int(input())
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
for t_itr in range(t):
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = equal(arr)
try:
fptr = open(os.environ['OUTPUT_PATH'], 'w')
fptr.write(str(result) + '\n')
except KeyError:
print(str(result))
fptr.close()
|
from typing import List
# Name: Unique Email Addresses
# Link: https://leetcode.com/problems/unique-email-addresses/
# Method: Process email, store in set
# Time: O(n)
# Space: O(n)
# Difficulty: Easy
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
return len(set(map(self.simplify_email, emails)))
def simplify_email(self, email: str):
local, domain = email.split("@")
if "+" in local:
local = local.split("+")[0]
local = local.replace(".", "")
return f"{local}@{domain}"
|
from typing import List
# Name: House Robber
# Link: https://leetcode.com/problems/house-robber/
# Method: Dynamic programming, max of prev 2 days
# Time: O(n)
# Space: O(1)
# Difficulty: Medium
class Solution:
def rob(self, nums: List[int]) -> int:
rob_prev = 0
rob_max = 0
for x in nums:
temp = rob_max
rob_max = max(rob_prev + x, rob_max)
rob_prev = temp
return rob_max
def rob_alternate(self, nums: List[int]) -> int:
prev_houses = [0, 0, 0]
for i in range(len(nums)):
stolen_now = max(prev_houses[1], prev_houses[0]) + nums[i]
prev_houses[0] = prev_houses[1]
prev_houses[1] = prev_houses[2]
prev_houses[2] = stolen_now
print(prev_houses)
return max(prev_houses)
|
from functools import lru_cache
class Solution:
zero_ways = 0
def numWays(self, steps: int, arrLen: int) -> int:
@lru_cache(None)
def step(poz: int, steps: int):
if poz < 0 or steps < 0 or poz >= arrLen or steps < poz:
return 0
elif poz == steps:
return 1
else:
return (
step(poz + 1, steps - 1)
+ step(poz - 1, steps - 1)
+ step(poz, steps - 1)
)
return step(0, steps) % (10 ** 9 + 7)
if __name__ == "__main__":
sol = Solution()
print(sol.numWays(15, 15))
|
import pygame
class Text_input:
#Initilisation
def __init__(self, origin, width, height, font, box_colour, text_colour, function, border = 0.05, password = False):
# Copy Args to name space
self.font = font
self.origin = origin
self.width = width
self.height = height
self.box_colour = box_colour
self.text_colour = text_colour
self.border = border
self.password = password
self.function = function
self.focus = False
self.position_ln = 0
self.position_px = 0
self.text = ""
# Used for reading single bits from a number, used in keyboard mods
def get_bit(self,byteval,idx):
return ((byteval&(1<<idx))!=0)
def rendered_text(self):
if self.password:
return len(self.text)*"*"
else:
return self.text
def run_function(self):
self.function(self.text)
def add_char(self, char, key, mod):
text_before = self.font.render(self.rendered_text(), False, self.text_colour).get_width()
text_before_pos = self.font.render(self.rendered_text()[:self.position_ln], False, self.text_colour).get_width()
text_box_width = int(self.width - self.width*(self.border*2))
#BackSpace
if char == "\x08":
# Remove character before line position
if self.position_ln > 0:
self.text = self.text[:self.position_ln-1]+ self.text[self.position_ln:]
self.position_ln -= 1
text_after = self.font.render(self.rendered_text(), False, self.text_colour).get_width()
self.position_px += text_after-text_before
if self.position_px < 0:
self.position_px = 0
#enter/return:
elif char == "\r":
#Run linked function
self.run_function()
#LEFT
elif key == pygame.K_LEFT:
self.position_ln -= 1
if self.position_ln < 0:
self.position_ln = 0
text_after_pos = self.font.render(self.rendered_text()[:self.position_ln], False, self.text_colour).get_width()
self.position_px += text_after_pos-text_before_pos
if self.position_px < 0:
self.position_px = 0
#RIGHT
elif key == pygame.K_RIGHT:
self.position_ln += 1
if self.position_ln > len(self.text):
self.position_ln = len(self.text)
text_after_pos = self.font.render(self.rendered_text()[:self.position_ln], False, self.text_colour).get_width()
self.position_px += text_after_pos-text_before_pos
if self.position_px > text_box_width:
self.position_px = text_box_width
#Home
elif key == pygame.K_HOME:
self.position_ln = 0
self.position_px = 0
#END
elif key == pygame.K_END:
self.position_ln = len(self.text)
if text_before >= text_box_width:
self.position_px = text_box_width
else:
self.position_px = text_before
#CTRL+U (Clear input)
elif key == pygame.K_u and (self.get_bit(mod,6) or self.get_bit(mod,7)):
self.position_ln = 0
self.position_px = 0
self.text = ""
elif char != "":
self.text = self.text[:self.position_ln] + char + self.text[self.position_ln:]
self.position_ln += 1
text_after = self.font.render(self.rendered_text(), False, self.text_colour).get_width()
self.position_px += text_after-text_before
# Check if over box position
if self.position_px > text_box_width:
self.position_px = text_box_width
print(self.text)
print(len(self.text))
def pressed(self,mouse):
if (
# Check X
(mouse[0] >= self.origin[0]) and
(mouse[0] <= (self.origin[0] + self.width)) and
# Check Y
(mouse[1] >= self.origin[1]) and
(mouse[1]) <= (self.origin[1] + self.height)
):
return True
else:
return False
# When item is clicked
def click(self, pos):
self.focus = True
# Text area
current_width = self.font.render(self.rendered_text()[:self.position_ln], False, (0,0,0)).get_width()
# Goal position across screen.
mouse_x = current_width - self.position_px - self.width*self.border - self.origin[0] + pos[0]
# Find closes position to where was clicked
short = [0,float("inf")] # index, distance
for i in range(len(self.text)+1):
distance = abs(mouse_x - self.font.render(self.rendered_text()[:i], False, (0,0,0)).get_width())
if distance < short[1]:
short[1] = distance
short[0] = i
# Short now contains the closest point to where was clicked
width = self.font.render(self.rendered_text()[:short[0]], False, (0,0,0)).get_width()
anchor = current_width - self.position_px
# Within allready existing box create new cursor position.
self.position_ln = short[0]
self.position_px = width - anchor
def draw(self, surface, antialias = True):
# Add button shape
pygame.draw.rect(
surface,
self.box_colour,
(self.origin[0], self.origin[1], self.width, self.height)
)
# Make text object
textsurface = self.font.render(self.rendered_text(), antialias, self.text_colour)
text_before = self.font.render(self.rendered_text()[:self.position_ln], False, self.text_colour)
# Check if text will fit.
# |border TEXT border|
# Border provides padding so text does not clash with box
text_box_width = int(self.width - self.width*(self.border*2))
# Text box fits
if textsurface.get_width() <= text_box_width:
surface.blit(
textsurface,
(
int(self.origin[0] + self.width*self.border), #X
int(self.origin[1] + self.height*self.border) #Y
)
)
# Text does not fit and needs scrolling
else:
left_side = text_before.get_width() - self.position_px
right_side = textsurface.get_width() - left_side - text_box_width
# Blit cropped text section to screen
surface.blit(
textsurface,
(
int(self.origin[0] + self.width*self.border), #X
int(self.origin[1] + self.height*self.border) #Y
),
(
left_side, 0, # X,Y
text_box_width, textsurface.get_height(), # W,H
)
)
# Draw cursor
if self.focus:
x = int(self.origin[0] + self.width*self.border + self.position_px)
y = int(self.origin[1] + self.height*(self.border))
pygame.draw.rect(
surface,
self.text_colour,
(
x,
y,
2,
self.height*(1-self.border))
)
|
import sys
from random import randint
n=int(sys.argv[1])
ganador=randint(0,36)
if n==ganador:
print("El numero ganado es",ganador)
print("Premio")
else:
print("El numero ganado es",ganador)
|
def same_digits(a, b):
"""
Implement same_digits, which takes two positive integers. It returns whether they both become
the same number after replacing each sequence of a digit repeated consecutively with only one of that
digit. For example, in 12222321, the sequence 2222 would be replaced by only 2, leaving 12321.
Restriction: You may only write combinations of the following in the blanks:
a, b, end, 10, %, if, while, and, or, ==, !=, True, False, and return. (No division allowed!)
>>> same_digits(2002200, 2202000) # Ignoring repeats, both are 2020
True
>>> same_digits(21, 12) # Digits must appear in the same order
False
>>> same_digits(12, 2212) # 12 and 212 are not the same
False
>>> same_digits(2020, 20) # 2020 and 20 are not the same
False
"""
assert a > 0 and b > 0
while a and b:
if a != b:
end = a % 10
while end == a % 10:
a = a // 10
while end == b % 10:
b = b // 10
else:
return True
return a == b
# ORIGINAL SKELETON FOLLOWS
# def same_digits(a, b):
# assert a > 0 and b > 0
# while a and b:
# if ______:
# end = a % 10
# while ______:
# a = a // 10
# while ______:
# b = b // 10
# else:
# ______
# ______
def no_repeats(a):
"""Remove repeated adjacent digits from a.
>>> no_repeats(22000200)
2020
"""
return search(lambda x: same_digits(x, a), 1)
def search(f, x):
while not f(x):
x += 1
return x
def unique_largest(n):
"""Return whether the largest digit in n appears only once.
>>> unique_largest(132123) # 3 is largest and appears twice
False
>>> unique_largest(1321523) # 5 is largest and appears only once
True
>>> unique_largest(5)
True
"""
assert n > 0
top = 0
while n:
n, d = n // 10, n % 10
if d > top:
top, unique = d, True
elif d == top:
unique = False
return unique
# Skeleton
#
# assert n > 0
# top = 0
# while n:
# n, d = n // 10, n % 10
# if _________:
# _________ = __________
# elif d == top:
# unique = _________
# return unique
def transitive(p):
"""Return whether p is transitive over non-negative single digit integers.
>>> transitive(lambda x, y: x < y) # if a < b and b < c, then a < c
True
>>> transitive(lambda x, y: abs(x-y) == 1) # E.g., p(3, 4) and p(4, 5), but not p(3, 5)
False
"""
abc = 0
while abc < 1000:
a, b, c = abc // 100, (abc % 100) // 10, abc % 10
if p(a, b) and p(b, c) and not p(a, c):
return False
abc = abc + 1
return True
# Skeleton
#
# abc = 0
# while abc < 1000:
# a, b, c = abc // 100, __________, abc % 10
# if p(a, b) __________:
# return False
# abc = abc + 1
# return True
def compose(n):
"""Return a function that, when called n times repeatedly on unary
functions f1, f2, ..., fn, returns a function g(x) equivalent to
f1(f2( ... fn(x) ... )).
>>> add1 = lambda y: y + 1
>>> compose(3)(abs)(add1)(add1)(-4) # abs(add1(add1(-4)))
2
>>> compose(3)(add1)(add1)(abs)(-4) # add1(add1(abs(-4)))
6
>>> compose(1)(abs)(-4) # abs(-4)
4
"""
assert n > 0
if n == 1:
return lambda f: f
def call(f):
def on(g):
return compose(n-1)(lambda x: f(g(x)))
return on
return call
# Skeleton
# assert n > 0
# if n == 1:
# return _________
#
# def call(f):
# def on(g):
# return ______(________)
# return on
# return call
from operator import add
"""Complete the final expression below with only integers and names so it evaluates to 2020"""
c = lambda f: lambda x: lambda y: f(x, y)
twice = lambda z: 2 * z
compose(3)(twice)(c(add)(10))(c(pow)(10))(3) # 2 * (10 + (10^3)) = 2020
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 23 14:22:58 2018
@author: jcarraascootarola
"""
import numpy as np
import random
class SigmoidNeuron:
def __init__(self, initLearningRate,numberOfInputs):
self.lastOutput=0
self.bias = random.uniform(-2.0, 2.0)
self.learningRate=initLearningRate
self.weights=np.random.uniform(-2.0,2.0,numberOfInputs)
def activate(self, inputData):
self.lastOutput = 1.0/(1+np.exp(-(sum(self.weights * np.array(inputData)) + self.bias)))
return self.lastOutput
def train(self,trainingSet,expectedValues):
for trainingInput,exVal in trainingSet,expectedValues:
result=self.activate(trainingInput)
if result != exVal:
self.learn(result,exVal,trainingInput)
def learn(self,realOutput, expectedOutput,inputN):
diff= realOutput-expectedOutput
for i in range(len(self.weights)):
self.weights[i]= self.weights[i] + (self.learningRate*inputN*diff)
self.bias=self.bias +(self.learningRate*diff) |
import sys
import csv
import math
import operator
#it first reads the text file input2
with open("input2.txt") as f:
content = f.readlines()
i=0
numcase=float(content[i])
#check number of votes
#input of votes and candidate orders returning the vote % the highest
def check(votes,cand_order):
total={}
for y in range (0,len(votes)):
for t in range (0,len(cand_order)):
if votes[y][:1]==' ':
votes[y][:1]=votes[y][2:3]
if int(votes[y][:1])==cand_order[t]:
if cand_order[t] not in total.keys():
total[cand_order[t]]=0
total[cand_order[t]]=total[cand_order[t]]+1 # add 1 if vote is to the candidate
total_per={}
for q in total.keys(): # deletes lowest candidates & check keys
q=q-1 #candidate order starts from 1
total_per[cand_order[q]]=float(total[cand_order[q]])/float(sum(total.values()))
return (max(total_per.values()),min(total_per.iteritems(), key=operator.itemgetter(1))[0],max(total_per.iteritems(), key=operator.itemgetter(1))[0])
for k in range(0,int(numcase)):
i=i+2
noofcand=float(content[i])
cand_names=[] # names on the list
cand_order=[] # order of candidates in the list
counter=0
for u in range(0,int(noofcand)): #will write the txt with the lists
i=i+1
counter=counter+1
cand_names.append(content[i])
cand_order.append(counter)
i=i+1
votes=[]
t=0
# read votes and add to the list
while (i<len(content)):
votes.append(content[i])
i=i+1
a=(0,0,0)
a=check(votes,cand_order)
while a[0]<0.51: # no loop if votes >50%
for c in range(0,len(votes)):
for p in range(0,len(list(votes[c]))):
if votes[c][p:p+1]==str(a[1]):
votes[c]=votes[c].replace(str(a[1]),votes[c][p+2:])
a=check(votes,cand_order)
print cand_names[a[2]-1] # name of the winner
k=k+1
|
#This is a comment from RAD416
students = ['aas731',
'acw438',
'agb344',
'ajm777',
'ak4706',
'ak4728',
'am5801',
'cbj238',
'cnl272',
'efm279',
'gz475',
'hj745',
'hm1273',
'hw1067',
'jj1006',
'jl2684',
'jwr300',
'ke638',
'kll392',
'ks2890',
'kx273',
'lcv232',
'lz1023',
'mam1220',
'rad416',
'rh1328',
'rs4606',
'seltzn01',
'spp319',
'yz1897']
numberOfStudents = len(students)
print numberOfStudents
#Now I'm going to select a random student
import random
index = random.randint(0,numberOfStudents-1)
print 'the lucky person is ' + students[index]
|
# < algorithm >
#1. voter ranks all candidates
#2. gather the #1 candidates and elect candidates who get over half of ballots
#3. if there is no elected candidate, drop the candidates, who get the lowest ballots
# (one or more candidates can be dropped)
#4. Among ballots that elected candidates who are already droppped as the top priority, if there are candidates who are elected by the ballots, then give ballots to those who are elected by the voters
#5. Aggregate again, and if there are candidates who get more than half of ballots, then elect the candidates
# But, if not, repeat the #3
LIMIT_NUM_OF_VOTE = 1000 # maximum number of voters
LIMIT_NUM_OF_CANDIDATE = 20 # maximum number of candidates
f = open('input2.txt', 'r') #open the input file
input = f.readlines() # read the whole file as a list of lines
def who_is_number_one(the_votes): #to find the candidate who get the most of ballots
total_of_candidate = {} # this is for listing the gathered ballots
for i, vote in ipairs( the_votes ): # to check the entire ballots
if 0 != the_vote: # if there is any candidate who has not been dropped on the ballots
if nil == total_of_candidate[vote[1]]: # then elect the first one
total_of_candidate[vote[1]] = 1
else:
total_of_candidate[vote[1]] = total_of_candidate[vote[1]] + 1
max_total_num_of_vote = 0
index_of_best_candidate = 0
for k, v in pairs( total_of_candidate ): # to find the candidates who get the most of ballots
if v >= max_total_num_of_vote:
max_total_num_of_vote = v
index_of_best_candidate = k
if max_total_num_of_vote > (the_votes/2): # if the candidates get more than half of ballots,
return index_of_best_candidate # then, return
else:
min_total_num_of_vote = max_total_num_of_vote # if not, find the candidates who get the least of ballots
index_of_worst_candidate = 0
for k, v in pairs( total_of_candidate ):
if v <= min_total_num_of_vote:
max_total_num_of_vote = v
index_of_worst_candidate = k
if max_total_num_of_vote == min_total_num_of_vote: # if the least ballots and the most ballots are the same
return 0 # then return to repeat the voting
for i, vote in ipairs( the_votes ): #find the candidates who get the least of ballots among the entire ballots
for i, index_of_candidate in ipairs( vote ):
if index_of_worst_candidate == index_of_candidate:
table.remove( vote, i ) # then, remove the cadidates from the list
break
return who_is_number_one( the_votes ) # then, return
def main():
f = open('input2.txt', 'r')
vote_case_num = f.readlines()
vote_case_num = tonumber( vote_case_num )
if nil == vote_case_num:
return
for i = 1, vote_case_num, 1: # to make the loop for processing ballots
f = open('A3_P2_Input.txt', 'r')
candidate_num = f.readlines() # get the number of candidate
candidate_num = tonumber( candidate_num )
if nil == candidate_num or LIMIT_NUM_OF_CANDIDATE < candidate_num: #if the number is not integer or exceed the limit
return
candidate_name_pack = {} # it is to get the name of candidates
for i = 1, candidate_num, 1: # get the names of entire cadidates
candidate_name_pack[candidate_name_pack + 1] = candidate_num
the_votes = {} #it is for getting ballots
for i = 1, LIMIT_NUM_OF_CANDIDATE, 1: # it is for ordering every cadidate in the ballots
vote_t = {}
vote_str = the_votes # get the ballots as string
if "" == vote_str: # if the ballot is empty, set the ballots as already received
break
for candidate_index in string.gmatch( vote_str, "%d+" ): #get the ballots according to the numbering on the ballots
vote_t[ vote_t + 1] = tonumber( candidate_index )
the_votes[the_votes +1] = vote_t # insert the ballots to the voting list
number_one = who_is_number_one( the_votes ) # start counting
print( candidate_name_pack[number_one] )
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
#Haozhe Wang
#Assignment 5
#Problem 1 A
import pandas as pd
import csv
import pylab
import numpy as np
stockfile = pd.read_csv('stocks.dat')#read the file with pandas call function
#print stockfile
apple_stock = stockfile[['month','apple']]
index = apple_stock.set_index('month')
#print index
right_timeseq = index.sort()
prefig = right_timeseq.plot(legend = True, style = "c*--")
#configure the plot
prefig.set_title('Is Apple still a buy?')
prefig.xaxis.grid(True, which="minor")
prefig.xaxis.grid(True, which="major")
prefig.set_ylabel('Price')
prefig.set_xlabel('Month')
prefig.annotate('Used Pandas and matplotlib to sort\n "month" as index, and configured\n other factors a little bit.', xy=(16,75))
plt.tight_layout()
prefig.figure.savefig('Apple Stock Pricetest.jpg',dpi = 300)
"""
tried my best to space the plot properly. Everything is labeled with legend in the right place.
Didn't change the default font size since it seems okay on the plot.
"""
|
#Aliya Merali
#Assignment 2
#Problem 3
import csv
from collections import defaultdict
incident_log = open('Incidents_grouped_by_Address_and_Zip.csv','r')
borough_log = open('boroughs.csv','r')
zip_log = open('zipCodes.csv','r')
outputFile = open('output_problem3.txt','w')
#Creating a Dict with Zipcodes:No. Incidents in that Zipcode
#First, create a list of just zip codes
incidents = []
tempList = []
for line in incident_log.readlines():
tempList = line.split(',')
incidents.append(tempList[1][:5])
#next, create a dict with the zip key and no. of appearances as value
incidentByZip = defaultdict(int)
for x in range(len(incidents)):
incidentByZip[incidents[x]] += 1
#incidentByZip is the dict with {zip:#incidents}, assuming that each line in the input file represents only one incident
#Creating a Dictionary with Zipcodes:Borough Name
boroughDict = csv.DictReader(borough_log, ['ZipVal','BorName'])
boroughByZip = {}
for row in boroughDict:
zipcode = row['ZipVal']
boroughName = row['BorName']
boroughByZip[zipcode] = boroughName
#boroughByZip is the dict with {zip:BoroughName}
#Creating a Dictionary with ZipCodes:Population
zipDict = csv.DictReader(zip_log)
popByZip = {} #Creating an empty dictionary for the zip:Pop dict
for row in zipDict: #filtering through the data dictionary
if row['Total Population per ZIP Code'] != '': #if val for pop:
zipcode = row['name']
pop = row['Total Population per ZIP Code']
popByZip[zipcode] = pop
#popByZip is the dict with {zip:totalPop}
#Creating the final dictionary
finalDict = {}
for zipKey in boroughByZip:
tempPop = 0
tempInc = 0
if zipKey in popByZip:
tempPop = popByZip[zipKey]
if zipKey in incidentByZip:
tempInc = incidentByZip[zipKey]
if boroughByZip[zipKey] not in finalDict:
finalDict[boroughByZip[zipKey]] = [0,0]
finalDict[boroughByZip[zipKey]][1]+= int(tempPop)
finalDict[boroughByZip[zipKey]][0]+= int(tempInc)
#Calculate and write the ratio of incidents to population
for keyVal in sorted(finalDict):
ratio = float((finalDict[keyVal][0]))/float((finalDict[keyVal][1]))
outputFile.write( str(keyVal) + ' ' + str(ratio)+ "\n")
|
######################################################################
#
# tutorial 2 - zipcode class
# September 21th, 2013
#
# Michael Musick
#
######################################################################
class Zipcode(object):
number = None
def __init__(self, zipcode):
self.zipcode = zipcode |
import sys
inputFile = open("input3.txt", "r")
"""
A scenario is a list containing a pair of integers P N denoting the number of
papers P and the number of authors N in each scenario, followed by P + N lines.
Parse the input for integer pairs and splice input into a new list of scenarios
(a list of lists). Define a function that takes a scenario as input and outputs
the authors and their Erdos numbers.
"""
numScenarios = int(inputFile.readline())
for n in range (0, numScenarios):
PN = inputFile.readline().split()
P = int(PN[0]
N = int(PN[1]
papers = []
for i in range(0, P):
papers.append(inputFile.readline())
"""
Create dictionary of all authors.
"""
authorDict = {}
authorList = []
for line in papers:
newline = line.split('.:')
for entry in newline:
lines = entry.split('., ')
if (lines[0][0] != ' '):
authorList.append(lines)
for i in range(0, len(lines)):
newAuthor = lines[i]
authorDict[newAuthor] = 1000000 # set 1000000 as temporary Erdos number placeholder
"""
Create list of authors for whom we want to find Erdos numbers.
"""
authors = []
for i in range(0, N):
name = inputFile.readline().strip('\n')
authors.append(name)
for line in authorList:
if 'Erdos, P' in line: # if Erdos is one of the authors
for i in range(0, len(line)):
authorName = line[i]
authorDict[authorName] = 1 # set Erdos number to 1 for other paper authors
for j in range(0, P):
for line in authorList:
minErdos = authorDict[line[0]]
for i in range(0, len(line)):
if (authorDict[line[i]] < minErdos):
minErdos = authorDict[line[i]]
for i in range(0, len(line)):
if (authorDict[line[i]] > minErdos):
authorDict[line[i]] = minErdos + 1 # add 1 to Erdos number of authors on paper
"""
For authors with no Erdos number, ie. with no "paper trail" that leads to
Erdos, loop.
"""
for entry in authorDict:
if (authorDict[entry] == 1000000):
authorDict[entry] = 'infinity'
print 'Scenario ', n + 1
for name in authors:
for entry in authorDict:
if (str(entry) == str(name)):
print entry, ". ", authorDict[entry]
inputFile.close()
|
def main():
f = open('input1.txt', 'r') #open the input file
input = f.readlines() # read the whole file as a list of lines
line_index = 0
line_index2 = int(input[line_index].replace('\n', '')) # this line is to set the number of student in each trip (the number of student is formatted as integer)
while line_index2 != 0:
sum = 0.00 # set the initial value of the computed money
line = []
for i in range(line_index2): # this loop is for setting the amount spent by a student in dollars and cents
sum += float(input[line_index + i + 1].replace('\n', '')) #the amount spent by a student in dollars and cents is formatted as float
line.append(float(input[line_index + i + 1].replace('\n', ''))) # add line
total = sum/line_index2
line_index += line_index2 + 1
minimum = 0
for j in line: # this loop is for finding the minimum amount
if float(j - round(total,2)) > 0:
minimum += j-total
print "$ %0.2f" % minimum #show the minimum number to two decimal places
line_index2 = int(input[line_index].replace('\n', ''))# to find the next chunk in the input file,such as the number of student and amount spent by a student in dollars and cents
if __name__ == '__main__':
main()
|
#!usr/bin/python
######################################################################
#
# Assignment 2 - Problem 4
# September 25th, 2013
#
# Michael Musick
#
# Description: returns the avergae population of the user specified
# borough
#
# Sample Input: python problem4.py "staten island"
#
######################################################################
# import zipcode
from borough import Borough
import sys
from string import lower
# get the user borough
userBorough = sys.argv[1] # get the borough name
userBorough = lower(userBorough) # convert it to lower case letters
if userBorough == "staten island": # if its staten island convert
userBorough = "staten"
# check that a valid borough was supplied
acceptableBoroughs = ['manhattan', 'brooklyn', 'queens', 'bronx', 'staten']
if userBorough not in acceptableBoroughs:
print "ERROR: please enter a known borough"
print acceptableBoroughs
sys.exit()
# open the db file containing zipcodes for each borough
dbFile = open('boroughs.csv','r')
# create a Borough object
borough = Borough(userBorough)
# look through db file for zipcodes in that borough
for line in dbFile:
tempArray = line.strip().split(',')
zipnum = tempArray[0]
# if its in the borough add it to the object
if lower(tempArray[1]) == userBorough:
borough.addZipcode( zipnum )
dbFile.close()
# open the next file and pull relevant pop and area information into borough object
dbFile = open('zipCodes.csv', 'r')
for line in dbFile:
tempArray = line.strip().split(',')
zipnum = tempArray[1]
# check that this is a zipcode in the user supplied borough
if zipnum in borough.zipcodes:
# check that all values exist for that zip
# check that area is valid
if len(tempArray[7]) > 0:
area = float( tempArray[7] )
else:
area = 0
# check that the zip has a defined pop
if len(tempArray[10]) > 0:
pop = float( tempArray[10] )
else: # assign it to 0
pop = 0
# add the information to the object
borough.modify_Pop_Area(zipnum, pop, area)
# print "" + str(zipnum) + " " + str(area) + " " + str(pop) + " "
dbFile.close()
# print the average population
print borough.avgPopStr() |
import sys
inputFile = open('input1.txt', 'r') # open .txt file
inputLines = [] # save lines in a list
for line in inputFile:
inputLines.append(line)
inputFile.close()
"""
Define a function that will take costs (as floats) as input and will print as output the
minimum amount of money (again as floats) that needs to be exchanged to equalize the costs.
The function will first compute the average cost avg, which will give the net cost for each
person, then compute the distance between the average cost and the individual costs. The
minimum amount minAMT of money that needs to change hands to equalize costs is then the sum
over the differences.
"""
def minCostEqualize(costList):
avg = sum(costList)/len(costList) # compute average cost
minAmt = 0.00
for elt in costList:
if elt <= avg: # if an element is less than or equal to the average
minAmt += round((avg - elt), 2) # round to the nearest cent when computing the difference
return minAmt
"""
Parse through inputLines. Find positive integer that denotes number of students on the trip,
and convert subsequent integers to floats and feed to printMinAmt, and print the result.
Append a 0 to the result of printMinAmt if the result has only one decimal place.
"""
for i in range(0,len(inputLines)):
if inputLines[i].find(".") == -1: # find integer that denotes the number of students on the trip
expenses = [] # save subsequent integers in a list of expenses
for j in range(i+1, i+int(inputLines[i])+1):
expenses.append(float(inputLines[j])) # convert integers to floats
if len(expenses) > 0:
if len(str(printMinAmt(expenses) - int(printMinAmt(expenses)))) > 3:
print printMinAmt(expenses)
else:
print str(printMinAmt(expenses)) + "0" # append a 0 on the end of a float that has only 1 decimal place
|
import sys
def isJolly(x):
targets = (len(x)-1)*[False]
for i in range(1,len(x)):
diff = abs(int(x[i-1])-int(x[i]))
if diff<len(x) and diff>0 and not targets[diff-1]: #will not crash because first clause will evaluate first
targets[diff-1]=True
else:
print "Not jolly"
return
print "Jolly"
return
x = sys.argv[2:len(sys.argv)]
isJolly(x)
|
class Borough:
name = None
zipcodes = None
populations = 0
populationcount = 0
average = 0
def __init__(self, name):
self.name = name
self.zipcodes = []
def addZipcode(self, zipcode):
self.zipcodes.append(zipcode)
def addPopulation(self, population):
#addPopulation keeps a running total of the borough's population,
#as well as keeps track of how many times population has been added
#in order to have a value over which to compute the average.
self.populations += population
self.populationcount += 1
def findAverage(self):
self.average = (self.populations)/(self.populationcount)
|
#Kara Leary
#Urban Informatics
#Assignment 2 - Problem 2
import sys
import csv
#initialize variables for zip, population, area, density:
currentZip = 0
currentPop = 0
currentArea = 0
populationDensity = 0
#set up a temporary list to hold unsorted values
temparray = []
with open('zipCodes.csv') as f:
rows = csv.reader(f, delimiter=',')
rows.next() #skip the header row
for row in rows:
if (row[10] != ''): #I used this to eliminate rows with no population entry
currentZip = row[1].strip()
currentPop = float(row[10].strip())
currentArea = float(row[7].strip())
populationDensity = currentPop/currentArea
#create a string with the desired output values:
thisstring = currentZip, populationDensity
#add the current string to the unsorted list:
temparray.append(thisstring)
#sort the temporary list in lexicographical order
newarray = sorted(temparray)
outputFile = open('output_density_problem2.txt', 'w')
for entry in newarray:
outputFile.write(str(entry))
outputFile.write('\n')
outputFile.close()
|
myFile=open('input4.txt','r')#read the input file and put all data into an array
readdata=[]
for line in myFile:
line_lower=line.lower()#change the letters of the data to lowercase
readdata.append(line_lower[:-1])
myFile.close
readdata.append('')#add a space into the end of array to indicate the last case ends
blankposition=[]#find the space position in the readdata and put them into another array
for a in range(1,len(readdata)):
if readdata[a]=='':
blankposition.append(a)
casenumber=int(readdata[0])#get the number of how many cases there are
#Here I wanna define a function to calculate the position where each word appears
#in the grid. I will get the first letter of the first word to find the position
#where has the same letter. Then I will check whether the left lenths in 8 directions
#are longer than the word's lenth. If longer, check whether the next (lengh-1) letters
#are the same as the word's left (lenth-1) letters. If they are matched, I can get the
#position and then loop this calculating process for all words.
#I have tried my best but writing the code of this process is too complicated for me.
griddata=[]
worddata=[]
def eachcase():
allcasedata=[]#find all case data and put them into a new array
for b in range(0,len(blankposition)-1):
x=blankposition[b]+1#the case content starts from the next line of the first space
y=blankposition[b+1]#the case content ends in the line before the space
allcasedata.append(readdata[x:y])
for i in range(len(allcasedata)):#get the data of each case
eachcasedata=[]
eachcasedata=allcasedata[i]
m=int(eachcasedata[0].split()[0])#number of lines in the grid
n=int(eachcasedata[0].split()[1])#number of columes in the grid
griddata.append(eachcasedata[1:m+1])#put the data of grid into an array
w=int(eachcasedata[m+1])#number of words that could be found in the grid
worddata.append(eachcasedata[m+2:m+2+w])#put the words into an array
eachcase()
#This part hasn't been finished.
def directions(eachgriddata,eachworddata,x,y,j):
for i in range(1,len(eachworddata[i])):#check whether the left length
#in each direction is not smaller than the word's length
wordlen=int(eachworddata[i])
if len(eachgriddata[0])-y>=wordlen:#right
for i in range (1,len(eachworddata[j])):
while eachgriddata[x][y+1] == eachworddata[j][i]:
y=y+1
if y-len(eachworddata[j])>
if y+1>=wordlen:#left
if len(eachgriddata)-x>=wordlen:#down
if x+1>=wordlen:#up
if
#This part hasn't been finished.
def get_position(eachgriddata,firstletter,j):
for x in range(0,len(eachgriddata)):#find the position of first letter in the grid
for y in range(0,len(eachgriddata[0])):
if eachgriddata[x][y]==firstletter:
directions(eachgriddata,eachworddata,x,y,j)
#This part hasn't been finished.
for i in range(0,casenumber):#get everycase's grid and word data, and the first letter of each word
eachworddata=worddata[i]
eachgriddata=griddata[i]
for j in range(0,len(eachworddata)):
firstletter=eachworddata[j][0]
get_position(eachgriddata,firstletter,j)
|
#Aliya Merali
#Assignment 2
#Problem 1
import sys
import datetime
from dateutil import parser
logfile = open('log_assignment1.txt','r')
#Set the time limit to compare to from input value as an object in datetime
dateInput = sys.argv[1].split('/')
timeInput = sys.argv[2].split(':')
dateTimeLimit = datetime.datetime(int(dateInput[2]),int(dateInput[0]),int(dateInput[1]),int(timeInput[0]),int(timeInput[1]),int(timeInput[2]))
#I did this before I learned about the parser in dateutil
#Create a list with all the commit dates in it from the log file, then test for relationship to input time
for line in logfile:
indexOfDate = line.find("Date:")
if (indexOfDate != -1):
dateLine = parser.parse(line[6:32]) #Putting the Date line into an object in datetime (removing the beginning text 'Date' and end time zone
if dateLine < dateTimeLimit: #comparing the two datetime objects
pass
else:
print line
|
import sys
inputFile = open('input1.txt', 'r')
inputFile.seek(0)
thisLine = inputFile.readline()
tripList = []
averageList = []
finalList = []
while thisLine != '0\n':
thisTrip = []
numStudents = int(thisLine[:-1])
thisLine = inputFile.readline()
for student in range(0, numStudents):
thisTrip.append(round(float(thisLine[:-1]),2))
thisLine = inputFile.readline()
tripList.append(thisTrip)
averageList.append(round(round(sum(thisTrip)/len(thisTrip),3),2))
#print tripList
#print averageList
tripAverages = zip(tripList, averageList)
for trip in tripAverages:
thisPayment = 0
tripPayments = trip[0]
tripAverage = trip[1]
for payment in tripPayments:
if payment > tripAverage:
thisPayment += payment - tripAverage
finalList.append(thisPayment)
thisPayment = 0
for finalPayment in finalList:
print '$'+("%.2f"%finalPayment)
|
# !usr/bin/python
######################################################################
#
# Assignment 5 - Problem 1a
# November 24th, 2013
#
# Michael Musick
#
# Description: Plot Apple Stock Prices
#
# Plotting Principles Used:
# Improving Vision, Principle 1 - Reduce Clutter:
# This was managed by making both plot and image
# background color white. I also drew data using
# black in order to maximize contrast.
# Improving Vision, Principle 3 - Proper Scale Lines:
# The scale is set appropriately. With a suitable,
# but not superfluous number of ticks on either
# scale. Additionally, the data is set just off the
# scale lines in order to preserve Principle 1 and
# keep the data easy to read.
# Improving Understanding, Principle 1 - Provide Explanations
# The captions/labels clearly identify what is being
# plotted.
#
#
#
######################################################################
# IMPORT NECCESSARY LIBRARIES
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta
# create global variables for value arrays
dateArr = []
appleData = []
mcrstData = []
# MAIN FUNCTION
def main():
# IMPORT THAT DATA
data_fromFile = open('stocks.dat', 'r')
tempDateArr = []
for line in data_fromFile:
lineArray = line.strip().split(',')
if isfloat(lineArray[1]) and isfloat(lineArray[2]):
tempDateArr.append(lineArray[0])
appleData.append(float(lineArray[1]))
mcrstData.append(float(lineArray[2]))
# convert date strings to datetime objects
for date in tempDateArr:
dateArr.append(datetime.strptime( date, "%Y-%m"))
problem_1a();
def problem_1a():
# get the min and max values
appleMin = min(appleData)
appleMax = max(appleData)
dateMin = dateArr[len(dateArr)-1]
dateMax = dateArr[1]
fig, ax = plt.subplots(1, figsize=[10,10])
ax.plot(dateArr, appleData, 'ko-')
ax.axis( [monthdelta(dateMin, -1).toordinal(), monthdelta(dateMax, 2).toordinal(), appleMin-5, appleMax+5 ])
fig.autofmt_xdate()
ax.fmt_xdata = mdates.DateFormatter('%Y-%m')
plt.xlabel('Date')
plt.ylabel('Stock Price Value')
fig.suptitle('Apple Inc. (APPL) Stock Prices', fontsize='18')
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.95, top=None, wspace=0.01, hspace=None)
fig.patch.set_facecolor('white')
fig.savefig('Problem1a.png')
plt.show()
# determine if a string is a float
def isfloat(str):
try:
float(str)
return True
except ValueError:
return False
# get altered datetimes
def monthdelta(date, delta):
yearDelta = 0
tempMonth = ((date.month-1)+delta)
if tempMonth > 11:
yearDelta = tempMonth/12
elif tempMonth < 0:
yearDelta = (tempMonth/12)
month = (tempMonth%12)+1
year = date.year + yearDelta
dateString = str(year)+"-"+str(month)
date = datetime.strptime(dateString, "%Y-%m")
return date
# EXECUTE THE PROGRAM
if __name__ == "__main__":
main() |
"""
Note that this program accepts input on the command line *without* quotation marks.
For example, one would type
$ python problem1.py 10 20
and receive an output of
10 20 21
"""
import sys
input = (sys.argv)
input.pop(0)
first_parameter = int(input[0])
second_parameter = int(input[1])
"""
The following function takes an integer and gives the length of its cycle, as defined
in the problem statement. The variable k is a counter for the cycle length.
"""
def cycle_length(n):
k = 0
while n != 1:
if n%2 == 0:
n = n/2
k += 1
elif n%2 != 0:
n = 3*n + 1
k += 1
return k+1
list_of_lengths = []
"""
Now we put all the cycle lengths into a list, and print the max of these lengths
as a string.
"""
for i in range(min(first_parameter, second_parameter), max(first_parameter, second_parameter)+1):
list_of_lengths.append(cycle_length(i))
print str(first_parameter) + " " + str(second_parameter) + " " + str(max(list_of_lengths))
|
import sys
max = 0
def test(n):
if (n % 2 == 0):
n = n/2
else:
n = 3*n + 1
return n
def cycle(n):
global max
count = 1
while n!= 1:
n = test(n)
count += 1
if (count > max):
max = count
i = int(sys.argv[1])
j = int(sys.argv[2])
for n in range(i, j+1):
#print "Calculating Cycle of "+str(n)
cycle(n)
print str(i)+' '+str(j)+' '+str(max) |
# A script to take in a file of zipcodes with populations, calculate the density
# and output those to a file, ignoring any zipcodes without a population figure
# output is likely population per decimal degree, though it's not clear from the
# source file what the units are.
from _collections import defaultdict
zipcodeInFile = open('zipCodes.csv', 'r')
next(zipcodeInFile) #skip header in file
zipAreaPopList = [] #list to hold processed file contents
for line in zipcodeInFile: #iterate to populate list from file contents
split_line = line.split(",") #split line into list
if split_line[10] != '\n': #test for a blank in population
zipAreaPopList.append([ split_line[0], [ split_line[7], split_line[10].rstrip()] ] )
#end loop with list of form [zipcode, [zipcodeArea, zipcodePopulation]]
zipcodeInFile.close()
#convert list to dict and aggregate area and population
zipAreaPopDict = defaultdict(list)
for k,v in zipAreaPopList:
zipAreaPopDict[k].append(v)
#test for multiple population and area entries in dict and aggregate
for k in zipAreaPopDict:
if (len(zipAreaPopDict[k])>1): #aggregate figures for multiples
zipAreaPopDict[k] = [[str( float(zipAreaPopDict[k][0][0]) + float(zipAreaPopDict[k][1][0]) ),str( float(zipAreaPopDict[k][0][1]) + float(zipAreaPopDict[k][1][1]) )]]
#output result
outFile = open('output_density_problem2.txt', 'w') #open output file
for k in sorted(zipAreaPopDict):
popPerArea = str(float(zipAreaPopDict[k][0][1]) / float(zipAreaPopDict[k][0][0])) #variable to hold ration
outFile.write(k)
outFile.write(" ")
outFile.write(popPerArea)
outFile.write('\n')
outFile.close() |
#!usr/bin/python
# Assignment 1 - Problem 2
# September 18th, 2013
####################################
#
# sample input:
# python problem2.py 6 1 -3 -6 -4 -3
#
###################################
import sys # lib to get terminal input
# print len(sys.argv) # test print
# put the user supplied arguments into a list
w = 1
intList = []
while w < len(sys.argv):
intList.append( int( sys.argv[w] ) )
w += 1
# find the first difference
# initialize jolly var
jolly = True
# find the first val
curDiff = abs( intList[0] - intList[1] )
# print curDiff # test print
# make sure the difference value is n-1
if curDiff != len(intList)-1:
jolly = False
# if the first difference is correct, check the remaining
num = 1
while num < len(intList)-1 and jolly == True:
nextDiff = abs( intList[num] - intList[num+1] )
# print nextDiff # test print
# if they are not sequential then its not a jolly jumper
if nextDiff != curDiff-1:
jolly = False
# reassign and increment to next location
else:
curDiff = nextDiff
num += 1
# if the last difference does not equal 1 then the list was too short
if curDiff != 1:
jolly = False
# print statements
if jolly == True:
print "Jolly"
else:
print "not jolly"
|
#Katherine Elliott
#ke638
#Assignment 3 Problem 3
inputFile = open("input3.txt", "r")
num_scenarios = int(inputFile.readline())
for n in range (0, num_scenarios):
PN = inputFile.readline().split()
P = int(PN[0])
N = int(PN[1])
papers = []
for i in range (0, P):
papers.append(inputFile.readline())
#create dictionary of all authors
author_dict = {}
author_list = [] #authors with an Erdos number
for line in papers:
newline = line.split('.:')
for entry in newline:
lines = entry.split('., ')
if (lines[0][0] != ' '):
author_list.append(lines)
for i in range(0, len(lines)):
newauthor = lines[i]
author_dict[newauthor] = 1000
authors = []# authors to find Erdos number
for i in range (0, N):
name = inputFile.readline().strip('.\n')
authors.append(name)
#set authors with Erdos number 1 as 1
for line in author_list:
if 'Erdos, P' in line:
for x in range(0, len(line)):
author_name = line[x]
author_dict[author_name] = 1
#Determines lowest Erdos number of paper and adds 1 to other authors on that paper
for y in range (0, P):
for line in author_list:
minErdos = author_dict[line[0]]
for x in range(0, len(line)):
if (author_dict[line[x]] < minErdos):
minErdos = author_dict[line[x]]
for x in range(0, len(line)):
if (author_dict[line[x]] > minErdos):
author_dict[line[x]] = minErdos + 1
for entry in author_dict:#loop if no erdos number
if (author_dict[entry] == 1000):
author_dict[entry] = 'infinity'
print 'Scenario ', n + 1
for name in authors:
for entry in author_dict:
if (str(entry) == str(name)):
print entry, ". ", author_dict[entry]
inputFile.close() |
import sys
import numpy
import matplotlib.pyplot as plt
from sklearn import cross_validation, linear_model, datasets
from random import shuffle
"""
First we open the text file and save the lines to the list input_lines
"""
inputfile = open('labeled_data.csv', 'r')
input_lines = []
for line in inputfile:
input_lines.append(line)
inputfile.close()
#this is our predictor variable
pop_list = []
for i in range(1,len(input_lines)):
pop_list.append(float(input_lines[i].split(',')[1]))
#this is our target variable
inc_list = []
for i in range(1, len(input_lines)):
inc_list.append(float(input_lines[i].split(',')[2]))
"""
Now we set up our models and cross-validation and figure out RMSE and R^2 scores for
OLS. We also compute the Standard Deviation for RMSE (across the 10 folds), for use in
problem c.
"""
cv = cross_validation.KFold(len(inc_list), n_folds=10, shuffle=True)
pop_array = numpy.array(pop_list)
inc_array = numpy.array(inc_list)
RMSE_scores = []
R2_scores = []
RMSE_Std_scores = []
for i in range(1, 6):
#these two lists will contain the 10 RMSE and R^2 values for each fold in model i
RMSE_list = []
R2_list = []
for train, test in cv:
#this fits a polynomial of order i to the training data
train_poly = numpy.polyfit(pop_array[train], inc_array[train], i)
#this calculates the predicted values of the above poly on the test data
test_y_vals = numpy.polyval(train_poly, pop_array[test])
#compute rmse for this fold and this model
rmse = (((test_y_vals - inc_array[test]) ** 2).mean(axis=None))**.5
RMSE_list.append(rmse)
#compute R^2 for this fold and this model
y_avg = sum(inc_array[test])/len(inc_array[test])
y_avg_list = []
for j in range(0, len(inc_array[test])):
y_avg_list.append(y_avg)
SS_res = sum((test_y_vals - inc_array[test])**2)
SS_tot = sum((inc_array[test] - y_avg_list)**2)
R2_list.append(1-(SS_res/SS_tot))
#now we average the values of RMSE_list and R2_list to get the final values for model i
RMSE_scores.append(sum(RMSE_list)/len(RMSE_list))
R2_scores.append(sum(R2_list)/len(R2_list))
#here we compute the standard deviation of the values in RMSE_list.
stdev = numpy.std(RMSE_list)
RMSE_Std_scores.append(stdev)
"""
We find that [13372.764077424241, 13161.000496501243, 12978.143321384781, 13031.820885445572, 13365.200489293336]
is (a) list of RMSE_scores, and
[0.56809724987946708, 0.58382961283776169, 0.59625876247195664, 0.59331017996281132, 0.5729441493561932]
is the corresponding list of R2_scores. We can see that the degree 3 polynomial model has lowest RMSE, and also
lowest R2 score. Hence we choose this as our model. Note that although these results are pretty
consistent over multiple runs of the program, occasionally we get different results for which
model has highest R2 scores...
"""
"""
Now, also in preparation for problem c, we compute the RMSE values on *all* training data
for each model.
"""
RMSE_all_data = []
for i in range(1, 6):
train_poly = numpy.polyfit(pop_array, inc_array, i)
test_y_vals = numpy.polyval(train_poly, pop_array)
rmse = (((test_y_vals - inc_array) ** 2).mean(axis=None))**.5
RMSE_all_data.append(rmse)
"""
Finally, we print everything we need for problem c
"""
print RMSE_scores
print R2_scores
print RMSE_Std_scores
print RMSE_all_data
"""
The values that we get from the above command are:
[13519.178949317729, 13247.82770615588, 13164.52846434755, 13405.996537917486, 14109.84815164765]
[0.56200736370308402, 0.5765497421094764, 0.57975713468038703, 0.56402979331596381, 0.51125609417622575]
[1515.2051976713724, 1536.1593441442926, 1662.8911854362129, 1925.7478724867913, 3262.5729874720264]
[13492.142190458173, 13118.850073678655, 12949.022276993384, 12934.207758865856, 12918.056857850648]
and we'll just manually import this data (except the R^2 scores) into the python code for
problem c and graph this.
"""
|
import numpy
import matplotlib.pyplot as plt
"""
The lists of values that we'll graph are:
[13519.178949317729, 13247.82770615588, 13164.52846434755, 13405.996537917486, 14109.84815164765]
[1515.2051976713724, 1536.1593441442926, 1662.8911854362129, 1925.7478724867913, 3262.5729874720264]
[13492.142190458173, 13118.850073678655, 12949.022276993384, 12934.207758865856, 12918.056857850648]
The first is the RMSE scores for 10-fold cross validation for a polynomial model of degree 1,2,3,4,5.
The second is the Standard deviation for the computation in the first list, where the deviation is computed over the 10 RMSEs for each fold (see problem_b code).
The third is the RMSE scores for a polynomial model of degree 1,2,3,4,5 trained on *all* the data (without 10-fold cross validation).
"""
RMSE_list_with_cv = numpy.array([13519.178949317729, 13247.82770615588, 13164.52846434755, 13405.996537917486, 14109.84815164765])
RMSE_list_without_cv = numpy.array([13492.142190458173, 13118.850073678655, 12949.022276993384, 12934.207758865856, 12918.056857850648])
RMSE_list_with_cv_stdev = numpy.array([1515.2051976713724, 1536.1593441442926, 1662.8911854362129, 1925.7478724867913, 3262.5729874720264])
#since we're going to display the y values from 11,000 in the graph, we need to scale the stdev error bars
temp_list = ([11000, 11000, 11000, 11000, 11000])
RMSE_scaled_stdevs = RMSE_list_with_cv_stdev*((RMSE_list_with_cv - temp_list)/RMSE_list_with_cv)
#compute Standard Deviation of RMSE_list
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ind = numpy.arange(5) # the x locations for the groups
width = 0.35
p1 = plt.bar(ind, RMSE_list_with_cv, width, color='b', yerr=RMSE_scaled_stdevs, ecolor='r')
p2 = plt.bar(ind, RMSE_list_without_cv, width, color='y')
plt.ylabel('RMSE values')
plt.title('10-fold Cross-Validated RMSE for 311 Labeled Data by Polynomial Model Degree')
plt.xticks(ind+width/2., ('Deg 1', 'Deg 2', 'Deg 3', 'Deg 4', 'Deg 5') )
plt.yticks(numpy.arange(11000,18000,1000))
ax.set_ylim([11000, 18000])
plt.legend( (p1[0], p2[0]), ('with cv', 'without cv'), loc='best' )
plt.show()
|
#!usr/bin/python
######################################################################
#
# Assignment 2 - Problem 2
# September 21th, 2013
#
# Michael Musick
#
# Description:
#
######################################################################
dbFile = open('zipCodes.csv', 'r')
# create a dictionary
zipDict = {}
# instantiate a lineCount Var
numOfLine = 0
# go through that freaking document
for line in dbFile:
# print line
numOfLine += 1
# print numOfLine
tempArray = line.strip().split(',')
completeEntry = True
# if the zip is valid
if( tempArray[1].isdigit()):
# print tempArray[1]
# print tempArray
# check that each field has data
if( len(tempArray[7]) > 0 ):
area = float(tempArray[7])
else:
completeEntry = False
if( len(tempArray[10]) > 0 ):
pop = int(tempArray[10])
else:
completeEntry = False
# if both fields were populated then enter that guy into the dict
if( completeEntry ):
tempZipDict = {'area': area, 'population': pop }
# print tempZipDict
zipDict[int(tempArray[1])] = tempZipDict
# sort that sucker
sorted(zipDict)
# print that stuff out
outputFile = open('output_density_problem2.txt','w')
outputFile.write( "Zip Code\tPopulation Density\n")
for key in zipDict:
tmpStr = str(key) + "\t\t" + str(zipDict[key]['population'] / zipDict[key]['area']) + "\n"
outputFile.write(tmpStr)
# close the file
outputFile.close()
|
import sys
import borough as boroughClass
boroughInput =sys.argv[0]
boroughInput =boroughInput.title()
boroughName= open ('boroughs.csv','r')
zippop= open('zipCodes.csv','r')
#setting the input as part of the boroughClass
boroughObj= borough(boroughInput)
#add the list of the zip codes to the boroughClass
boroughDict=csv.DictReader(boroughName,'zipvalues','name')
for row in boroughDict:
if row['name']==boroughInput:
boroughObj.addZipcode(row['zippop)'])
#get the total population
popboInput=csv.DictReader(zippop)
totalpop = 0
count = 0
for row in popboInput:
if row ['total pop per zip'] != '':
population = row ['total pop per zip']
zipCode = row ['name']
if zipCode in boroughObj.zipCodes:
count =count +1
totalpop = totalpop + int(pop)
#average =
boroughObj.calcAvgPop(totalpop,count)
print boroughObj.avg
main()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 15:18:57 2013
@author: yz1897
"""
import sys
# this solution should be faster in c, but in after i test
#in python, the it get a little slower...
def Longest_Cycle(i,j):
longest=0
deleted=[-1 for k in range(j-i+1)]
for n in range(j,i-1,-1):
if deleted[n-i]==1:
continue
deleted[n-i]=1
count=1
while True:
if n==1:
break
#mark appeared number
if n>=i and n<j and deleted[n-i]==-1:
deleted[n-i]=1
count+=1
if n%2==0:
n=n/2
else:
n=n*3+1
if longest<count:
longest=count
print i,j,longest
if __name__ == "__main__":
Longest_Cycle(int(sys.argv[1]),int(sys.argv[2]))
|
import sys
import math
input = open('input2.txt','r')
value1 = input.readlines()
value1 = value1[2:]
break_arr = []
break_arr.append(0)
z = 0
for call in value1:
if call == "\n":
break_arr.append(z+1)
z = z + 1
break_arr.append(len(value1))
def candidates(x, win1): # Getting the list of candidates.
end_res = []
for winner in win1:
end_res.append(x[int(winner)].strip())
return end_res
def votes_received(x):
a = int(x[0]) # Number of Candidates in the election being listed in the array.
put_vote = x[(a+1):]
votes_array = []
for num_votes in put_vote:
val1 = num_votes.strip()
if val1 != "":
votes_array.append(val1.split(" "))
return votes_array # Returning the captured votes in the array.
def other_votes(abc):
pref_1 = {}
for num_votes in abc:
if len(num_votes) == 0:
continue
if num_votes[0] in pref_1:
pref_1[num_votes[0]] = pref_1[num_votes[0]] + 1
else:
pref_1[num_votes[0]] = 1
return pref_1
def check(cast_ballots, put_vote):
while True:
win_mark = len(cast_ballots)/2 + 1
nextvotes = other_votes(cast_ballots)
win1 = win2(nextvotes)
lost_1 = lost(nextvotes)
count_vote_num = nextvotes[win1[0]]
win1.sort()
lost_1.sort()
if count_vote_num >= win_mark:
return candidates(put_vote, win1)
elif win1 == lost_1: # Conditioning for the probability of a tie.
return candidates(put_vote, win1)
else:
del_min(cast_ballots, lost_1)
def lost(votes_cand): #Defining Losers.
if votes_cand == {}:
return []
l_votes = min(votes_cand.values()) # using min() function to find the lowest number of votes given to the candidates.
list_lost = []
for k in votes_cand: # Having the candidates with the lowest number of votes.
if votes_cand[k] == l_votes:
list_lost.append(k)
return list_lost
def win2(votes_cand): # Defining Winners.
if votes_cand == {}:
return []
h_votes = max(votes_cand.values()) # Seeking the highest number of votes to the candidates.
list_win = []
for k in votes_cand:
if votes_cand[k] == h_votes:
list_win.append(k)
return list_win
def del_min(cast_ballots, lost_1): # Eliminating Losers in round of voting.
for num_votes in cast_ballots:
for bal_lost in lost_1:
if bal_lost in num_votes:
num_votes.remove(bal_lost)
cnt1 = 0 # Checking all cases of the functions mentioned in the program above.
while cnt1 < (len(break_arr) - 1):
put_vote = []
index = break_arr[cnt1]
while ((break_arr[cnt1]) <= index < (break_arr[cnt1+1])):
put_vote.append(value1[index])
index = index + 1
print (check(votes_received(put_vote), put_vote))
cnt1 = cnt1 + 1
|
import sys
import csv
class Borough:
name = None
zipcodes = None
numOfZip=None
population=None
def __init__(self, name):
self.name = name
self.zipcodes = []
self.numOfZip=0
self.population=0
def addZipcode(self, zip):
self.zipcodes.append(zip)
self.numOfZip+=1
self.population+=zip.population
class Zipcode:
number = None
population =None
def __init__(self, number, population):
self.number = number
self.population = population
boroFileRaw = open('boroughs.csv','r') # open borough file
boroFile=csv.reader(boroFileRaw, delimiter=',')
zipList=[] #define a list of concerned zip areas
for line in boroFile: # input the borough info to zipDict
if line[1]==sys.argv[1]:
zipList.append(line[0])
boroFileRaw.close()
zipFileRaw = open('zipCodes.csv','r') #open the zip file
zipFile=csv.DictReader(zipFileRaw, delimiter=',')
borough=Borough(sys.argv[1])#instantiate borough
for line in zipFile:# instantiate the zip areas concerned
if (line['Total Population per ZIP Code']!=''):
pop=int(line['Total Population per ZIP Code'])
num=str(line['zip code tabulation area'])
if num in zipList:
zipcode=Zipcode(num,pop)
borough.addZipcode(zipcode)
zipFileRaw.close()
if borough.numOfZip==0:
print('Borough not found!Please try again!')
else:
avgpop=int(borough.population/borough.numOfZip)
print("The average ZIP population of "+sys.argv[1]+"is:"+str(avgpop)+".")
|
#!/usr/local/bin/python
#Warren Reed
#Principles of Urban Informatics
#Assignment 2, Problem 3
"""
Creating ZipCodes Population Dictionary with key as zipcode and value
as the population of that zipcode
"""
Pop_File = open('zipCodes_tr.csv','r')
population_lines = []
for line in Pop_File:
population_lines.append(line)
Pop_File.close()
zipCodes_header = population_lines[0].split(',') #adding column names to header
#strip the header of \n
zipCodes_header_length = len(zipCodes_header)
for i in range(0,zipCodes_header_length):
zipCodes_header[i] = zipCodes_header[i].strip()
zipCodes_zip_index = zipCodes_header.index('zip code tabulation area')
zipCodes_population_index = zipCodes_header.index('Total Population per ZIP Code')
zipCodes_population = {}
Pop_File_length = len(population_lines)
for i in range(1,Pop_File_length):
if population_lines[i].split(',')[10] != "\n":
zipCodes_population[population_lines[i].split(',')[zipCodes_zip_index]] = (float(population_lines[i].split(',')[zipCodes_population_index].strip()))
"""
Creating zipcode Borough dictionary with key as zipcode and value as
borough names
"""
Borough_File = open('boroughs_tr.csv','r')
borough_lines = []
for line in Borough_File:
borough_lines.append(line)
Borough_File.close()
boroughs_zip_index = 0
boroughs_index = 1
boroughs_zipcode = {}
Borough_File_length = len(borough_lines)
for i in range(1, Borough_File_length):
if borough_lines[i].split(',')[boroughs_index] != "\n":
boroughs_zipcode[borough_lines[i].split(',')[boroughs_zip_index]] = (borough_lines[i].split(',')[boroughs_index].strip())
"""
Run through every key-value pair in zipCodes_population and add it to
borough_zip_pop with key as borough and value as the borough population
"""
borough_zip_pop = {"Manhattan" : 0.0,"Brooklyn" : 0.0, "Queens": 0.0, "Bronx" : 0.0, "Staten" : 0.0}
for key in zipCodes_population:
if boroughs_zipcode.has_key(key):
borough_zip_pop[boroughs_zipcode[key].strip()] = borough_zip_pop[boroughs_zipcode[key].strip()] + zipCodes_population[key]
"""
Creating zipcode incidents dictionary with key as zipcode and value as
incident count
"""
incidents_file = open('Incidents_grouped_by_Address_and_Zip.csv','r')
incidents_lines = []
for line in incidents_file:
incidents_lines.append(line)
incidents_header = incidents_lines[0].split(',')
#strip the header of \n
incidents_header_length = len(incidents_header)
for i in range(0,incidents_header_length):
incidents_header[i] = incidents_header[i].strip()
incidents_count_index = incidents_header.index('Unique Key')
incidents_zip_index = incidents_header.index('Incident Zip')
#Create a zip_incident dictionary (including dirty data)
incidents_length = len(incidents_lines)
incidents_zipcode = {} #create dictionary
for i in range(1,incidents_length):
if (incidents_lines[i].split(',')[incidents_zip_index] != ''):
if (incidents_zipcode.has_key(incidents_lines[i].split(',')[incidents_zip_index][0:5]) == False and boroughs_zipcode.has_key(incidents_lines[i].split(',')[incidents_zip_index][0:5])):
incidents_zipcode[incidents_lines[i].split(',')[incidents_zip_index][0:5]] = int(incidents_lines[i].split(',')[incidents_count_index].strip())
else:
if (boroughs_zipcode.has_key(incidents_lines[i].split(',')[incidents_zip_index][0:5])):
if (incidents_lines[i].split(',')[incidents_count_index] != ''):
incidents_zipcode[incidents_lines[i].split(',')[incidents_zip_index][0:5]] = incidents_zipcode[incidents_lines[i].split(',')[incidents_zip_index][0:5]] + int(incidents_lines[i].split(',')[incidents_count_index].strip())
"""
Create borough_incidents dictionary with key as borough name and value
as incident count
"""
borough_incidents = {"Manhattan" : 0.0,"Brooklyn" : 0.0, "Queens": 0.0, "Bronx" : 0.0, "Staten" : 0.0}
for key in incidents_zipcode:
if boroughs_zipcode.has_key(key):
borough_incidents[boroughs_zipcode[key].strip()] = borough_incidents[boroughs_zipcode[key].strip()] + incidents_zipcode[key]
"""
Create borough_incidents dictionary with key as borough name and value
as incident count density
"""
borough_incident_density = {"Manhattan" : 0.0,"Brooklyn" : 0.0, "Queens": 0.0, "Bronx" : 0.0, "Staten" : 0.0}
for key in borough_incident_density:
borough_incident_density[key] = (borough_incidents[key] / borough_zip_pop[key])
#Update for full name of Staten Island
borough_incident_density["Staten Island"] = borough_incident_density["Staten"]
del borough_incident_density["Staten"]
#Output results of borough incident density dictionary to output txt file
outputFile = open('output_problem3.txt','w')
for key in sorted(borough_incident_density.iterkeys()):
outputFile.write("%s %s \n" % (key, borough_incident_density[key]))
outputFile.close() |
#!/usr/local/bin/python
#Warren Reed
#Principles of Urban Informatics
#Assignment 4, Problem 1
#Connects to MySQL and creates three tables to store the boroughs.csv, zipCodes, and incidents table.
import MySQLdb
import csv
def incidentsToSql(cur,db):
incidents_csv = csv.reader(open('Incidents_grouped_by_Address_and_Zip.csv'))
rows = list(incidents_csv)
rows = rows[1:]
table = 'incidents'
#make sure to set as root global max_allowed_packet=30000000;
query1 = "DROP TABLE IF EXISTS `{0}`;".format(table)
query2 = "CREATE TABLE `{0}` (incident_address varchar(255) DEFAULT NULL, incident_zip varchar(255) DEFAULT NULL, unique_key INT DEFAULT NULL);".format(table)
query3 = '''INSERT INTO `incidents` VALUES(%s, %s, %s)'''
cur.execute(query1)
db.commit()
cur.execute(query2)
db.commit()
cur.executemany('''INSERT INTO `incidents` VALUES(%s, %s, %s)''', rows)
db.commit()
def boroughToSql(cur,db):
boroughs_csv = csv.reader(open('boroughs_tr.csv'))
boroughs_rows = list(boroughs_csv)
table2 = 'boroughs'
query4 = "DROP TABLE IF EXISTS `{0}`;".format(table2)
query5 = "CREATE TABLE `{0}` (zipcode varchar(255) DEFAULT NULL, borough varchar(255) DEFAULT NULL);".format(table2)
cur.execute(query4)
db.commit()
cur.execute(query5)
db.commit()
cur.executemany('''INSERT INTO boroughs VALUES(%s, %s)''', boroughs_rows)
db.commit()
def zipcodeToSql(cur,db):
zipcodes_csv = csv.reader(open('zipcodes_tr.csv'))
zipcode_rows = list(zipcodes_csv)
zipcode_rows = zipcode_rows[1:]
table3 = 'zipcodes'
query6 = "DROP TABLE IF EXISTS `{0}`;".format(table3)
query7 = "CREATE TABLE `{0}` (name varchar(255) DEFAULT NULL, zip_code_tabulation_area varchar(255) DEFAULT NULL, zt36_d00 varchar(255) DEFAULT NULL, perimeter varchar(255) DEFAULT NULL, lsad_trans varchar(255) DEFAULT NULL, zt36_d00i varchar(255) DEFAULT NULL, lsad varchar(255) DEFAULT NULL, area varchar(255) DEFAULT NULL, latitude varchar(255) DEFAULT NULL, longitude varchar(255) DEFAULT NULL, Total_Population_per_ZIP_Code varchar(255) DEFAULT NULL);".format(table3)
cur.execute(query6)
db.commit()
cur.execute(query7)
db.commit()
cur.executemany('''INSERT INTO zipcodes VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''', zipcode_rows)
db.commit()
def main():
#connect to database
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="jwr300", # your username
passwd="jwr300", # your password
db="coursedb") # name of the data base
cur = db.cursor()
incidentsToSql(cur,db)
boroughToSql(cur,db)
zipcodeToSql(cur,db)
db.close()
print "Import complete"
if __name__ == "__main__":
main()
|
#Nathan Seltzer
#Homework 5
#Problem1c.py
#import the neccessary modules and rename them
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
#the following import form pylab will allow me to use the subplot function
from pylab import *
#same as previous annotations
f = open('stocks.dat', 'r') #opens file with intention of reading, but hasn't read yet
f.readline()
apple = []
microsoft = []
date = []
months = range(1, 34)
for line in f:
header = line.split(',')
date.append(str(header[0]))
apple.append(float(header[1]))
microsoft.append(float(header[2]))
"""
For some reason, the arrays that I had created by parsing the stock values from the
file were in reverse order. The following code reverses the order so that the
charts accurately reflect the data.
"""
arr = np.array(apple)
ap = arr[::-1]
# print ap
arr2 = np.array(microsoft)
mic = arr2[::-1]
# print mic
plt.title("Price of AAPL and MSFT Stock from January 2006 to September 2008 ")
plt.xlabel("Month and Year")
plt.ylabel("Price of Stock")
sdate = sort(date)
#In order to juxtapose both, i'm going to use the subplot command from pyplot
#I think it makes most sense to juxtopose vertically rather than horizontally
#(2,1,1) refers to the number of rows, number of columns, and number of this first plot
subplot(2,1,1)
plt.plot( months , ap)
plt.title("Apple (AAPL)", weight = 'bold', )
plt.ylabel("Price of Stock in Dollars")
plt.xticks(range(0,34,6),sdate[0:34:6])
grid(True, c = 'g')
#(2,1,1) refers to the number of rows, number of columns, and number of this second plot
subplot(2,1,1)
subplot(2,1,2)
plt.plot( months, mic)
plt.title("Microsoft (MSFT)", weight = 'bold')
plt.xlabel("Month and Year")
plt.ylabel("Price of Stock in Dollars")
plt.xticks(range(0,34,6),sdate[0:34:6])
grid(True, c = 'g')
plt.show()
"""
Superposition vs. Juxtoposition?
There really isn't one clear-cut answer. If one wants to look at larger
market trends, it makes sense to juxtapose both of the stock plots. Having
both on the same scale gives one a better understanding of the magnitude of
changes for both, and we can also see how both stocks reacted to temporal
events. However, if the goal is to look at both stocks value on the same
scale, the superpositioning is a better idea because one can see the
true difference in value.
"""
#still need to create labels |
# Awais Malik
# Assignment 2
# Problem 4
import sys
import csv
zipFile = open('zipCodes.csv','r')
zipcodeList = csv.reader(zipFile)
boroughFile = open('boroughs.csv','r')
boroughList = csv.reader(boroughFile)
boroughName = sys.argv[1].lower()
zip = {}
for line in boroughList:
zip[line[0]] = [line[1]]
for line in zipcodeList:
if(line[0] in zip):
zip[line[0]].append(line[10])
countManhattan = 0
countBrooklyn = 0
countBronx = 0
countQueens = 0
countStaten = 0
for line in zip:
if(zip[line][0] == 'Manhattan'):
countManhattan += 1
elif(zip[line][0] == 'Brooklyn'):
countBrooklyn += 1
elif(zip[line][0] == 'Bronx'):
countBronx += 1
elif(zip[line][0] == 'Queens'):
countQueens += 1
elif(zip[line][0] == 'Staten'):
countStaten += 1
else:
print "No Associated State!"
borough = {}
for line in zip:
if(zip[line][0] not in borough):
borough[zip[line][0]] = [0]
try:
borough[zip[line][0]][0] += int(zip[line][1])
except:
pass
if(boroughName == 'manhattan'):
print float(borough['Manhattan'][0])/countManhattan
elif(boroughName == 'brooklyn'):
print float(borough['Brooklyn'][0])/countBrooklyn
elif(boroughName == 'bronx'):
print float(borough['Bronx'][0])/countBronx
elif(boroughName == 'queens'):
print float(borough['Queens'][0])/countQueens
elif(boroughName == 'staten'):
print float(borough['Staten'][0])/countStaten
else:
print "Incorrect Entry!" |
#!/usr/local/bin/python
#Warren Reed
#Principles of Urban Informatics
#Assignment 4, Problem 2
#Connects to MySQL and computes the population density for a given zipcode
import MySQLdb
import sys
def main():
inputZipcode = sys.argv[1]
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="jwr300", # your username
passwd="jwr300", # your password
db="coursedb") # name of the data base
cur = db.cursor()
cur.execute('''SELECT Total_Population_per_ZIP_Code FROM coursedb.zipcodes WHERE name = %s''', inputZipcode)
population = cur.fetchall()
population = population[0][0]
cur.execute('''SELECT area FROM coursedb.zipcodes WHERE name = %s''', inputZipcode)
area = cur.fetchall()
area = area[0][0]
pop_density = float(population)/float(area)
print pop_density
db.commit()
db.close()
if __name__ == "__main__":
main()
|
def find_location(string,matrix): # find the location of keyword
location=[float("inf"),float("inf")]
lineNum=len(matrix)
colNum=len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j].lower()==string[0].lower():
lStr=string[0].lower()
rStr=string[0].lower()
uStr=string[0].lower()
dStr=string[0].lower()
ulStr=string[0].lower()
urStr=string[0].lower()
dlStr=string[0].lower()
drStr=string[0].lower()
for n in range (1,len(string)): #get the string in eight horizontal, vertical and diagonal directions through the matrix
if i in range(lineNum) and j-n in range(colNum):
lStr+=matrix[i][j-n]
if i in range(lineNum) and j+n in range(colNum):
rStr+=matrix[i][j+n]
if i-n in range(lineNum) and j in range(colNum):
uStr+=matrix[i-n][j]
if i+n in range(lineNum) and j in range(colNum):
dStr+=matrix[i+n][j]
if i-n in range(lineNum) and j-n in range(colNum):
ulStr+=matrix[i-n][j-n]
if i-n in range(lineNum) and j+n in range(colNum):
urStr+=matrix[i-n][j+n]
if i+n in range(lineNum) and j-n in range(colNum):
dlStr+=matrix[i+n][j-n]
if i+n in range(lineNum) and j+n in range(colNum):
drStr+=matrix[i+n][j+n]
if lStr.lower()==string.lower() or rStr.lower()==string.lower() or uStr.lower()==string.lower() or dStr.lower()==string.lower() or ulStr.lower()==string.lower() or urStr.lower()==string.lower() or dlStr.lower()==string.lower() or drStr.lower()==string.lower():
location[0]=i+1
location[1]=j+1
return location
return location
myFile=open("input4.txt","r") #open the input file
myInput=[]
index=0
for line in myFile: # read the file
myInput.append(line.strip())
myFile.close()
while index<len(myInput):
scenarioNum=int(myInput[index])
lineNum=int(myInput[index+2].split(" ")[0])
columnNum=int(myInput[index+2].split(" ")[1])
checkNum=int(myInput[index+lineNum+3])
matrix=[]
for i in range(index+3,index+3+lineNum):
matrix.append(myInput[i])
for i in range(index+4+lineNum, index+4+lineNum+checkNum):
location=find_location(myInput[i],matrix) #get the locations
print(str(location[0])+" "+str(location[1]))
print ('')
index=index+lineNum+checkNum+5 #move to the next scenario
|
# TIM LEAVEY
# SUPERHERO APP
# This program does NOT used prepared statements, meaning it's vulnerable to SQL injections.
# This was intentional as a lesson in what NOT to do. ;)
import sys
import sqlite3
# Initial welcome display for user
print('Welcome to the superheroes archive!')
print('1. Superheroes')
print('2. Villains')
print('3. Teams')
print('4. Powers')
print('5. Colors')
user_choice = input('Your command: ')
# Connect to the database
connection = sqlite3.connect('homework07.sqlite3.db')
c = connection.cursor()
# SUPERHEROES
if user_choice == 1:
# DISPLAY SUPERHERO LIST
c.execute('SELECT superheroes.name, teams.name, villains.name FROM superheroes, teams, villains WHERE team_id=teams.id AND villains.id=villain_id;')
superheroes_data = c.fetchall()
for superhero in superheroes_data:
print superhero[0]
print 'Team: ',superhero[1]
print 'Nemesis: ',superhero[2]
c2 = connection.cursor()
# DISPLAYING ALL THE POWERS
c2.execute("SELECT powers.name FROM powers JOIN powers_superheroes ON power_id=powers.id JOIN superheroes ON superhero_id=superheroes.id WHERE superheroes.name= '%s'" % superhero[0])
powers_data = c2.fetchall()
sys.stdout.write('Powers: ')
for power in powers_data:
if len(powers_data) > 1:
if power != powers_data[-1]:
sys.stdout.write(power[0]+', ')
else:
sys.stdout.write(power[0])
print
else:
sys.stdout.write(power[0])
print
# DISPLAYING ALL THE COLORS
c3 = connection.cursor()
c3.execute("SELECT colors.name FROM colors JOIN colors_superheroes ON color_id=colors.id JOIN superheroes ON superhero_id=superheroes.id WHERE superheroes.name= '%s'" % superhero[0])
colors_data = c3.fetchall()
sys.stdout.write('Costume Colors: ')
for color in colors_data:
if len(colors_data) > 1:
if color != colors_data[-1]:
sys.stdout.write(color[0]+', ')
else:
sys.stdout.write(color[0])
print
else:
sys.stdout.write(color[0])
print
print
user_adds_or_quits = raw_input('(A)dd a new superhero, or (Q)uit?')
add_superhero = 'a'
quit = 'q'
# ADDING A SUPERHERO
if user_adds_or_quits.lower() == add_superhero:
print 'Adding a New Superhero'
new_superhero = raw_input('Superhero Name: ')
# VILLAIN INFO
print 'Arch enemy:'
c.execute('SELECT * FROM villains;')
villains_data = c.fetchall()
for one_villain in villains_data:
villain_identifier = str(one_villain[0])
print villain_identifier + ". " + one_villain[1]
villain_id = input('')
# TEAM INFO
print 'Team:'
c.execute('SELECT * FROM teams;')
teams_data = c.fetchall()
for one_team in teams_data:
team_identifier = str(one_team[0])
print team_identifier + ". " + one_team[1]
team_id = input('')
c.execute("INSERT INTO superheroes(name, villain_id, team_id) VALUES ('%s', '%s', '%s')" % (new_superhero, villain_id, team_id))
connection.commit()
# COLOR INFO
print 'Colors:'
c.execute('SELECT * FROM colors;')
colors_data = c.fetchall()
for one_color in colors_data:
color_identifier = str(one_color[0])
print color_identifier + ". " + one_color[1]
color_id = input('')
c2 = connection.cursor()
c2.execute('SELECT id FROM superheroes;')
superhero_ids = c2.fetchall()
new_superhero_id = superhero_ids[-1][0]
c.execute("INSERT INTO colors_superheroes(color_id, superhero_id) VALUES ('%s', '%s')" % (color_id, new_superhero_id))
yes = 'y'
user_choice = yes
# ADD MULTIPLE COLORS
while user_choice.lower() == 'y':
user_choice = raw_input('Add another color? (Y)es or (N)o: ')
if user_choice.lower() == 'y':
print 'Colors:'
for one_color in colors_data:
color_identifier = str(one_color[0])
print color_identifier + ". " + one_color[1]
color_id = input('')
c.execute("INSERT INTO colors_superheroes(color_id, superhero_id) VALUES ('%s', '%s')" % (color_id, new_superhero_id))
connection.commit()
# POWERS INFO
print 'Powers:'
c.execute('SELECT * FROM powers;')
powers_data = c.fetchall()
for one_power in powers_data:
power_identifier = str(one_power[0])
print power_identifier + ". " + one_power[1]
power_id = input('')
c2 = connection.cursor()
c2.execute('SELECT id FROM superheroes;')
superhero_ids = c2.fetchall()
new_superhero_id = superhero_ids[-1][0]
c.execute("INSERT INTO powers_superheroes(superhero_id, power_id) VALUES ('%s', '%s')" % (new_superhero_id, power_id))
yes = 'y'
user_choice = yes
# ADD MULTIPLE POWERS
while user_choice.lower() == 'y':
user_choice = raw_input('Add another power? (Y)es or (N)o: ')
if user_choice.lower() == 'y':
print 'Powers:'
for one_power in powers_data:
power_identifier = str(one_power[0])
print power_identifier + ". " + one_power[1]
power_id = input('')
c.execute("INSERT INTO powers_superheroes(superhero_id, power_id) VALUES ('%s', '%s')" % (new_superhero_id, power_id))
connection.commit()
connection.close()
# USER QUITS
elif user_adds_or_quits.lower() == quit:
print 'Quitting'
connection.close()
else:
print 'BAD INPUT... QUITTING'
connection.close()
# VILLAINS
elif user_choice == 2:
# DISPLAY VILLAIN LIST
print 'Villains: '
c.execute('SELECT name FROM villains;')
villains_names = c.fetchall()
for name in villains_names:
print name[0]
user_adds_or_quits = raw_input('(A)dd a new villain, or (Q)uit?')
add_villain = 'a'
quit = 'q'
# ADD NEW VILLAIN TO DB
if user_adds_or_quits.lower() == add_villain:
print 'Adding a New Villain'
new_villain = raw_input('Villain Name: ')
c.execute("INSERT INTO villains(name) VALUES ('%s')" % new_villain)
connection.commit()
connection.close()
# QUIT
elif user_adds_or_quits.lower() == quit:
print 'Quitting'
connection.close()
else:
print 'BAD INPUT... QUITTING'
connection.close()
# TEAMS
elif user_choice == 3:
# DISPLAY TEAM LIST
print 'Teams: '
c.execute('SELECT name FROM teams;')
team_names = c.fetchall()
for name in team_names:
print name[0]
user_adds_or_quits = raw_input('(A)dd a new team, or (Q)uit?')
add_team = 'a'
quit = 'q'
# ADD NEW TEAM
if user_adds_or_quits.lower() == add_team:
print 'Adding a New Team'
new_team = raw_input('Team Name: ')
c.execute("INSERT INTO teams(name) VALUES ('%s')" % new_team)
connection.commit()
connection.close()
# QUIT
elif user_adds_or_quits.lower() == quit:
print 'Quitting'
connection.close()
else:
print 'BAD INPUT... QUITTING'
connection.close()
# POWERS
elif user_choice == 4:
# DISPLAY POWERS LIST
print 'Powers: '
c.execute('SELECT name FROM powers;')
power_names = c.fetchall()
for name in power_names:
print name[0]
user_adds_or_quits = raw_input('(A)dd a new power, or (Q)uit?')
add_power = 'a'
quit = 'q'
# ADD NEW POWER TO DB
if user_adds_or_quits.lower() == add_power:
print 'Adding a New Power'
new_power = raw_input('Power Name: ')
c.execute("INSERT INTO powers(name) VALUES ('%s')" % new_power)
connection.commit()
connection.close()
# QUIT
elif user_adds_or_quits.lower() == quit:
print 'Quitting'
connection.close()
else:
print 'BAD INPUT... QUITTING'
connection.close()
# COLORS
elif user_choice == 5:
# DISPLAY COLOR LIST
print 'Costume Colors: '
c.execute('SELECT name FROM colors;')
color_names = c.fetchall()
for name in color_names:
print name[0]
user_adds_or_quits = raw_input('(A)dd a new team, or (Q)uit?')
add_color = 'a'
quit = 'q'
# ADD NEW COLOR TO DB
if user_adds_or_quits.lower() == add_color:
print 'Adding a New Color'
new_color = raw_input('Color Name: ')
c.execute("INSERT INTO colors(name) VALUES ('%s')" % new_color)
connection.commit()
connection.close()
# QUIT
elif user_adds_or_quits.lower() == quit:
print 'Quitting'
connection.close()
else:
print 'BAD INPUT... QUITTING'
connection.close()
else:
print('Bad input. Numbers 1 - 5 only.')
connection.close()
|
from datetime import date
from lib.colors import red, green
iteration_start = date(2021, 6, 16)
iteration_end = date(2021, 9, 22)
iteration_diff = iteration_end - iteration_start
number_of_sprints = int(iteration_diff.days / 14)
days_into_iteration = int((date.today() - iteration_start).days)
current_sprint = int((days_into_iteration / 14) + 1)
days_into_sprint = int((days_into_iteration % 14) + 1)
def main():
print(green('+' * current_sprint) + red('-' * (number_of_sprints - current_sprint)))
print(f'Sprint {current_sprint}')
print(green('+' * days_into_sprint) + red('-' * (14 - days_into_sprint)))
print(f'Day {days_into_sprint}\n')
print(f'{days_into_iteration / iteration_diff.days:.0%}')
if __name__ == '__main__':
main()
|
num=int(input("Enter 3 digit number "))
n1=num%10
n2=num//10%10
n3=num//100
print(f"{n1}{n2}{n3}")
|
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from scipy.stats import pearsonr
if __name__ == "__main__":
boston = datasets.load_boston()
boston = pd.DataFrame(data=boston.data, columns=boston.feature_names)
print(boston)
correlation, _ = pearsonr(boston["TAX"], boston["B"])
print(f"Correlation between TAX and B: {correlation}")
# scatter plot
boston.plot.scatter(x="TAX", y="B") # x and y are columns names from boston data frame
plt.show()
|
from tkinter import *
from PIL import Image, ImageTk
from datastorage import Insert_user
import sqlite3
conn = sqlite3.connect("users.db")
c = conn.cursor()
def credentials():
global font
log = Tk()
log.geometry("500x600")
log.title("Fundit")
log.configure(background="white")
log.resizable(width=False, height=False)
#Displaying the main logo on the sign in page
logo = Image.open("media/logo.png")
render = ImageTk.PhotoImage(logo)
lbl_logo = Label(log, image=render, bg="white")
lbl_logo.image = render
lbl_logo.pack(fill=X)
#Creating the frame for the entrys
frame_entry1= Frame(log,width=500, height=300, bg="white")
frame_entry1.place(x=60,y=230)
#Font specifications
font = ("Helvetica", 20,"bold")
font_color = "#9acc56"
#Username entry and password
#Username label
enter_username = Label(frame_entry1,text="Username:",bg="white",fg="black",font=font)
enter_username.pack(anchor=W)
#Username entry
entry_username = Entry(frame_entry1,bg="white",width=20,font=("Helvetica", 15),fg="black")
entry_username.pack()
frame_entry2= Frame(log,width=500, height=100, bg="white")
frame_entry2.place(x=60,y=330)
#Password label
enter_password = Label(frame_entry2,text="Password:",bg="white",fg="black",font=font)
enter_password.pack(anchor=W)
#Password entry
entry_password = Entry(frame_entry2,bg="white",width=20,font=("Helvetica", 15),fg="black")
entry_password.pack()
frame_avail_name= Frame(log,width=500, height=500, bg="white")
frame_avail_name.place(x=60,y=300)
avail_response_name = Label(frame_avail_name,text="",bg="white",fg="black",font=("Helvetica", 15))
avail_response_name.pack()
frame_avail_pass= Frame(log,width=500, height=500, bg="white")
frame_avail_pass.place(x=60,y=400)
avail_response_pass = Label(frame_avail_pass,text="",bg="white",fg="black",font=("Helvetica", 15))
avail_response_pass.pack()
def adduser():
username = str(entry_username.get())
password = str(entry_password.get())
if password == "":
avail_response_pass.configure(text="Please enter a password",fg="Red")
else:
try:
avail_response_pass.configure(text="",fg="Red")
c.execute(f"SELECT * FROM users WHERE name='{username}'")
username_avail = c.fetchone()[0]
print("This username has already been taken")
avail_response_name.configure(text="This username has already been taken",fg="Red")
except TypeError:
avail_response_pass.configure(text="",fg="Red")
print("This username is available")
avail_response_name.configure(text="This username is available",fg="Green")
frame_button_entry= Frame(log,width=500, height=50, bg="white")
frame_button_entry.place(x=165,y=450)
entry_button_register = Button(frame_button_entry,bg="#9acc56",text="Register",font=("Helvetica", 15),command=adduser)
entry_button_register.pack(side=LEFT)
entry_button_login = Button(frame_button_entry,bg="#9acc56",text=" Login ",font=("Helvetica", 15))
entry_button_login.pack(side=LEFT,padx=15)
#Keeping the window active
log.mainloop()
credentials()
conn.commit()
conn.close() |
from pieces import Piece
import board
class Rook(Piece):
def __init__(self, color, type):
Piece.__init__(self, color, type)
def __str__(self):
if(self.color == "W"):
return "R"
else:
return "r"
def scan(self):
availMoves = []
optionCounter = 1
pieceFound = False
running = True
rowCount = self.row
colCount = self.col
# scan above
while rowCount - 1 > -1 and running:
rowCount -= 1
if (board.Grid(rowCount, self.col).piece.color != self.color):
board.Grid(rowCount, self.col).des = True
board.Grid(rowCount, self.col).option = optionCounter
optionCounter += 1
availMoves.append(board.Grid(rowCount, self.col))
if board.Grid(rowCount, self.col).pieceStatus:
pieceFound = True
else:
rowCount = 0
running = False
if pieceFound:
rowCount = 0
running = False
# scan below
rowCount = self.row
running = True
pieceFound = False
while rowCount + 1 < 8 and running:
rowCount += 1
if (board.Grid(rowCount, self.col).piece.color != self.color):
board.Grid(rowCount, self.col).des = True
board.Grid(rowCount, self.col).option = optionCounter
optionCounter += 1
availMoves.append(board.Grid(rowCount, self.col))
if board.Grid(rowCount, self.col).pieceStatus:
pieceFound = True
else:
rowCount = 7
running = False
if pieceFound:
rowCount = 7
running = False
# scan right
running = True
pieceFound = False
while colCount + 1 < 8 and running:
colCount += 1
if (board.Grid(self.row, colCount).piece.color != self.color):
board.Grid(self.row, colCount).des = True
board.Grid(self.row, colCount).option = optionCounter
optionCounter += 1
availMoves.append(board.Grid(self.row, colCount))
if board.Grid(self.row, colCount).pieceStatus:
pieceFound = True
else:
colCount = 7
running = False
if pieceFound:
colCount = 7
running = False
# scan left
colCount = self.col
running = True
pieceFound = False
while colCount - 1 > -1 and running:
colCount -= 1
if (board.Grid(self.row, colCount).piece.color != self.color):
board.Grid(self.row, colCount).des = True
board.Grid(self.row, colCount).option = optionCounter
optionCounter += 1
availMoves.append(board.Grid(self.row, colCount))
if board.Grid(self.row, colCount).pieceStatus:
pieceFound = True
else:
colCount = 0
running = False
if pieceFound:
colCount = 0
running = False
return availMoves
|
import pygame
from pygame.locals import *
from random import choice
from copy import deepcopy
NAME_OF_THE_GAME = "Tetris"
BLOCK_SIZE = 30
def coord_in_px(coord):
return (coord[0] * BLOCK_SIZE,
coord[1] * BLOCK_SIZE)
DRAW_SPOTLIGHT = True # the spotlight is a guide the width of the player that extends to where it would fall.
STAGE_WIDTH = 9 # stage is where the game takes place.
STAGE_HEIGHT = 17
STAGE_MARGIN = (1,1)
BOARD_WIDTH= 5 # the board shows the next piece, the score and lines
BOARD_MARGIN = (STAGE_WIDTH+3, STAGE_MARGIN[1])
BOARD_CENTER_X = BOARD_MARGIN[0] + BOARD_WIDTH/2
PIECE_STAGE_STARTING_POSITION = (4,0)
NEXT_PIECE_POSITION = (BOARD_CENTER_X - 2, 13)
SCREEN_SIZE = (BOARD_MARGIN[0] + BOARD_WIDTH + 1 , STAGE_HEIGHT + 3)
STAGE_TOP_LEFT = STAGE_MARGIN
STAGE_BOTTOM_RIGHT = (STAGE_MARGIN[0] + STAGE_WIDTH, STAGE_MARGIN[1] + STAGE_HEIGHT)
BORDER_COLOR = (160,160,160)
BORDER_WIDTH = 1 #the borders surrounding areas
SPOTLIGHT_COLOR = (15,15,15)
TITLE_COLOR = (0, 64, 128)
TEXT_COLOR = (255,255,255)
GAME_OVER_TEXT_COLOR = (255,0,0)
PAUSE_TEXT_COLOR = (255,255,255)
FPS = 60
LOWER_PIECE_EVENT_ID = USEREVENT+1
class Piece:
"""It's a piece of the game.
contains a representation of it's shape and rotation.
contains coordinates of it's components in the stage.
contains capacity to move and rotate."""
pieces = {
"L":{"color" : (128, 94, 0),
"offset": -1, # used to center the piece when it appears on screen
"shape" : [[0,1,0],
[0,1,0],
[0,1,1]]},
"J":{"color": (0, 0, 128),
"shape": [[0,1,0],
[0,1,0],
[1,1,0]]},
"I":{"color" : (0, 128, 128),
"offset": -1,
"shape" : [[0,0,1,0,0],
[0,0,1,0,0],
[0,0,1,0,0],
[0,0,1,0,0]]},
"S":{"color": (0, 128, 0),
"shape": [[1,0,0],
[1,1,0],
[0,1,0]]},
"Z":{"color": (128, 0, 0),
"shape": [[0,1,0],
[1,1,0],
[1,0,0]]},
"T": {"color": (128, 0, 128),
"shape": [[0,0,0],
[1,1,1],
[0,1,0]]},
"B": {"color": (128, 128, 0),
"shape": [[1,1],
[1,1]]}}
def __init__(self, piece_name = None, position = None):
self.position = position or list(NEXT_PIECE_POSITION)
self.name = piece_name or choice( list(self.pieces.keys()) )
self.shape = deepcopy(self.pieces[self.name]["shape"])
self.color = self.pieces[self.name]["color"]
self.blocks = None
self.update_blocks()
self.offset_piece()
def set_position(self, position):
self.position = position
self.update_blocks()
self.offset_piece()
def offset_piece(self):
if "offset" in self.pieces[self.name].keys():
self.move([self.pieces[self.name]["offset"], 0])
def update_blocks(self):
r = []
for row_i, row in enumerate(self.shape):
for col_i, block in enumerate(row):
if block:
x = col_i + self.position[0] + STAGE_MARGIN[0]
y = row_i + self.position[1] + STAGE_MARGIN[1]
r.append([x, y])
self.blocks = r
if DRAW_SPOTLIGHT:
self.blocks.sort()
def rotate_ccw(self, update_blocks = True):
r = []
while self.shape:
if self.shape[0]:
r.append([])
for row_i in range(len(self.shape)):
r[-1].append(self.shape[row_i][-1])
del self.shape[row_i][-1]
else: self.shape = []
self.shape = r
if update_blocks:
self.update_blocks()
def rotate_cw(self):
self.rotate_ccw(False)
self.rotate_ccw(False)
self.rotate_ccw()
def move(self, coord):
self.position[0] += coord[0]
self.position[1] += coord[1]
for block in self.blocks:
block[0] += coord[0]
block[1] += coord[1]
def __iter__(self):
for block in self.blocks:
yield block
def __getitem__(self, key):
return self.blocks[key]
def __delitem__(self, item):
del self.blocks[item]
def __len__(self):
return len(self.blocks)
class GameCore:
"""Manages the interaction between the player and movement, margins, lower pieces, states, score, next piece and level."""
def __init__(self, piece_name = None):
self.playing = True
self.paused = False
self.game_over = False
self.player = Piece(piece_name, list(PIECE_STAGE_STARTING_POSITION))
self.player.offset_piece()
self.next_piece = Piece()
self.score = Score()
self.bottom_pieces = BottomPieces(self)
def set_paused(self, pause = None):
self.paused = pause if pause != None else not self.paused
self.playing = not self.paused and not self.game_over
def player_oversteps_bottom_pieces(self):
for coord in self.player.blocks:
if coord in self.bottom_pieces:
return True
return False
def player_oversteps_border(self):
for coord in self.player.blocks:
if not (STAGE_MARGIN[0] <= coord[0] <= STAGE_WIDTH+STAGE_MARGIN[0]) or \
not (coord[1] <= STAGE_HEIGHT+STAGE_MARGIN[1]):
return True
return False
def player_oversteps(self):
return self.player_oversteps_border() or self.player_oversteps_bottom_pieces()
def move_player(self, coord):
self.player.move(coord)
if self.player_oversteps():
self.player.move([coord[0]*-1, coord[1]*-1])
if coord[1]:
self.change_player()
def rotate_player(self):
self.player.rotate_cw()
if self.player_oversteps():
self.player.rotate_ccw()
def change_player(self):
self.bottom_pieces.append(self.player)
self.player = self.next_piece
self.player.set_position(list(PIECE_STAGE_STARTING_POSITION))
self.next_piece = Piece()
self.bottom_pieces.check_rows()
if self.player_oversteps_bottom_pieces():
self.playing = False
self.game_over = True
def bottom_pieces_call(self, number):
"""BottomPieces uses this method when it clears lines"""
self.score.add_lines(number)
def move_piece_to_limit(self, coord):
"""It lowers the piece to the bottom in one movement,
or it moves it to the right or left until a limit is met"""
def has_advanced(previous_pos, current_pos):
if coord[0] > 0:
return previous_pos[0] < current_pos[0]
elif coord[0] < 0:
return previous_pos[0] > current_pos[0]
elif coord[1] > 0:
return previous_pos[1] < current_pos[1]
elif coord[1] < 0:
return previous_pos[1] > current_pos[1]
elif previous_pos == current_pos:
return False
keep_moving = True
while keep_moving:
old_position = self.player.position[:]
self.move_player(coord)
if not has_advanced(old_position, self.player.position):
keep_moving = False
class BottomPieces(list):
def __init__(self, game_core):
super(BottomPieces, self).__init__()
self.game_core = game_core
def __contains__(self, element):
if super(BottomPieces, self).__contains__(element):
return True
else:
for piece in self:
if element in piece:
return True
return False
def check_rows(self):
blocks_deleated = 0
acc = {}
for piece in self:
for block in piece:
if block[1] not in acc.keys():
acc[block[1]] = []
acc[block[1]].append(block[0])
for key, value in sorted(acc.items()):
if len(value) == STAGE_WIDTH+1:
blocks_deleated += self.delete_row(key)
lines_cleared = blocks_deleated // (STAGE_WIDTH + 1)
if lines_cleared:
self.game_core.bottom_pieces_call(lines_cleared)
def delete_row(self, row):
blocks_deleated = 0
for piece_index in range(len(self)-1, -1, -1):
for box_index in range(len(self[piece_index])-1,-1, -1):
if self[piece_index][box_index][1] == row:
del self[piece_index][box_index]
blocks_deleated += 1
if not len(self[piece_index]):
del self[piece_index]
elif self[piece_index][box_index][1] < row:
self[piece_index][box_index][1] += 1
return blocks_deleated
class Score:
def __init__(self):
self.lines = 0
self.level = 0
self.score = 0
def add_lines(self, lines):
self.lines += lines
self.level = self.lines//10
if lines == 1: self.score += 40 * (self.level + 1)
elif lines == 2: self.score += 100 * (self.level + 1)
elif lines == 3: self.score += 300 * (self.level + 1)
elif lines == 4: self.score += 1200 * (self.level + 1)
class Clock:
def __init__(self, score):
self.score = score
self.clock = pygame.time.Clock()
self.fps = FPS
self.lower_piece_data = {n:int(48 - 2.4 * n) for n in range(21)}
self.time_accumulated_to_lower_piece = 0
lower_piece_every = property(lambda self: self.lower_piece_data[self.score.level] or 2)
def tick(self):
elapsed_time = self.clock.tick(self.fps)
self.process_lower_piece(elapsed_time)
def process_lower_piece(self, elapsed_time):
self.time_accumulated_to_lower_piece += elapsed_time
if self.time_accumulated_to_lower_piece >= self.lower_piece_every * 1000//FPS:
self.time_accumulated_to_lower_piece = 0
event_lower_piece = pygame.event.Event(LOWER_PIECE_EVENT_ID)
pygame.event.post(event_lower_piece)
class Game:
"Draws stuff and handles events"
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode(coord_in_px(SCREEN_SIZE))
pygame.display.set_caption(NAME_OF_THE_GAME)
pygame.key.set_repeat(1,160)
self.core = GameCore()
self.running = True # is the application running
self.clock = Clock(self.core.score)
self.font = pygame.font.SysFont("Arial", 22)
def run(self):
while self.running:
self.clock.tick()
self.handle_events()
self.draw_game()
def tick(self):
self.core.move_player( (0,1) )
def draw_game(self):
self.screen.fill((0, 0, 0))
if self.core.game_over:
self.draw_game_over()
if self.core.paused:
self.draw_pause()
if DRAW_SPOTLIGHT:
self.draw_spotlight()
self.draw_pieces()
self.draw_number_of_lines()
self.draw_score()
self.draw_level_number()
self.draw_next_piece()
self.draw_borders()
pygame.display.flip()
def render_text(self, text, position, color):
txt_pos = list(coord_in_px(position))
text = self.font.render(text, True, color)
txt_pos[0] -= text.get_width()//2
self.screen.blit(text, txt_pos)
def draw_number_of_lines(self):
self.render_text("LINES", (BOARD_CENTER_X, 1.5), TITLE_COLOR)
self.render_text(str(self.core.score.lines), (BOARD_CENTER_X, 2.5), TEXT_COLOR)
def draw_level_number(self):
self.render_text("LEVEL", (BOARD_CENTER_X, 4.5), TITLE_COLOR)
self.render_text(str(self.core.score.level), (BOARD_CENTER_X, 5.5), TEXT_COLOR)
def draw_score(self):
self.render_text("SCORE", (BOARD_CENTER_X, 7.5), TITLE_COLOR)
self.render_text(str(self.core.score.score), (BOARD_CENTER_X, 8.5), TEXT_COLOR)
def draw_game_over(self):
self.render_text("GAME OVER", (BOARD_CENTER_X, 10.5), GAME_OVER_TEXT_COLOR)
def draw_pause(self):
self.render_text("PAUSE", (BOARD_CENTER_X, 10.5), PAUSE_TEXT_COLOR)
def draw_next_piece(self):
self.render_text("NEXT PIECE", (BOARD_CENTER_X, 12.5), TITLE_COLOR)
self.draw_piece(self.core.next_piece)
def draw_piece(self, piece):
size_rect = (BLOCK_SIZE, BLOCK_SIZE)
for block_pos in piece:
pixel_pos = coord_in_px(block_pos)
pygame.draw.rect(self.screen, piece.color, Rect(pixel_pos, size_rect))
def draw_spotlight(self):
top_left_x = coord_in_px(self.core.player.blocks[0])[0]
top_left_y = coord_in_px(STAGE_TOP_LEFT)[1]
top_left = (top_left_x, top_left_y)
x_for_bottom_x = self.core.player.blocks[-1][0] - self.core.player.blocks[0][0]
bottom_right_x = coord_in_px((x_for_bottom_x + STAGE_MARGIN[0], 1))[0]
bottom_right_y = coord_in_px(STAGE_BOTTOM_RIGHT)[1]
bottom_right = (bottom_right_x, bottom_right_y)
pygame.draw.rect(self.screen, SPOTLIGHT_COLOR, Rect(top_left, bottom_right))
def draw_pieces(self):
self.draw_piece(self.core.player)
for piece in self.core.bottom_pieces:
self.draw_piece(piece)
def draw_borders(self):
stage_rect = Rect(coord_in_px(STAGE_TOP_LEFT), coord_in_px(STAGE_BOTTOM_RIGHT))
pygame.draw.rect(self.screen, BORDER_COLOR, stage_rect, BORDER_WIDTH)
right_area_top_left = BOARD_MARGIN
right_area_bottom_right = (BOARD_WIDTH, STAGE_HEIGHT+1)
right_area_rect = Rect(coord_in_px(right_area_top_left), coord_in_px(right_area_bottom_right))
pygame.draw.rect(self.screen, BORDER_COLOR, right_area_rect, BORDER_WIDTH)
def handle_events(self):
keys_pressed = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
if event.type == KEYDOWN:
if event.key in (K_PAUSE, K_RETURN, K_p):
if not self.core.game_over:
self.core.set_paused()
else:
self.__init__()
if self.core.playing:
if event.type == KEYDOWN:
if event.key == K_UP:
self.core.rotate_player()
elif event.key == K_DOWN:
self.core.move_player( (0,1) )
elif event.key == K_RIGHT:
self.core.move_player( (1,0) )
elif event.key == K_LEFT:
self.core.move_player( (-1,0) )
elif event.key == K_SPACE:
if keys_pressed[K_RIGHT]:
self.core.move_piece_to_limit((1,0))
elif keys_pressed[K_LEFT]:
self.core.move_piece_to_limit((-1,0))
else:
self.core.move_piece_to_limit((0,1))
elif event.type == LOWER_PIECE_EVENT_ID:
self.core.move_player( (0,1) )
if __name__ == '__main__':
Game().run()
|
# initialize
my_dict = {}
# add item
my_dict['name'] = 'brian'
my_dict['state'] = 'florida'
my_dict['age'] = 37
# access item
print my_dict['name']
# change item
my_dict['name'] = 'engineer man'
# remove item by index
del my_dict['state']
# iterate
for k, v in my_dict.iteritems():
print k, '=>', v
|
import numpy as np
import matplotlib.pyplot as plt
# https://towardsdatascience.com/understanding-the-3-most-common-loss-functions-for-machine-learning-regression-23e0ef3e14d3
# MSE loss function
def mse_loss(y_pred, y_true):
squared_error = (y_pred - y_true) ** 2
sum_squared_error = np.sum(squared_error)
loss = sum_squared_error / y_true.size
return loss
# MAE loss function
def mae_loss(y_pred, y_true):
abs_error = np.abs(y_pred - y_true)
sum_abs_error = np.sum(abs_error)
loss = sum_abs_error / y_true.size
return loss
# Huber loss function
def huber_loss(y_pred, y, delta=1.0):
huber_mse = 0.5*(y-y_pred)**2
huber_mae = delta * (np.abs(y - y_pred) - 0.5 * delta)
return np.where(np.abs(y - y_pred) <= delta, huber_mse, huber_mae)
|
def exam_model():
# introduction
print ('Welcome to the grade caluclator for you English, Science and Maths exams')
print ('type you scores in and find out your grades')
name=raw_input ('What is you name: ')
english_score= input ('What was your exam score for English: ')
maths_score=input ('What was your exam score for Maths: ')
Science_score=input ('What was your exam score for Science: ')
for i in [english_score, maths_score, Science_score]
if >= 90
=grade_a
elif >= 80 and < 90
=grade_b
# c_grade
# d_grade
# e_grade
# f_grade
# u_grade
exam_model () |
import random
stuff = ['water', 'food', 'sword']
party = ['you']
pos_x = 2
pos_y = 2
you_hp = 15.0
map_dungeon = '''
----------------
| |__
| main room |__ outside
== | |
--------------- == ------| |-----
| |== | |
| downstairs | ---- ----
| | | armory |
-- ----------- -------------
| |
--| |-------______---------------
| cellar |______| locked room |
------------- ---------------
'''
def d_intro():
print("\nYou have travelled countless miles and faced many dangers to finally reach this dungeon. Inside, a "
"terrifying beast has kidnapped the prince/princess but, you will save them!")
def check_items(item):
x = 0
have = False
for i in range(len(stuff)):
x += 1
if stuff[x - 1] == item:
have = True
else:
pass
return have
def check_pos():
global pos_x
global pos_y
if pos_x < 0:
print("Hey, you stepped out of the world. I'll put you back")
pos_x = 0
if pos_y < 0:
print("Hey, you stepped out of the world. I'll put you back")
pos_y = 0
if pos_x > 2:
print("Wow! You're just going to leave, what a crappy hero...")
quit()
if pos_y > 3:
print("Hey, you stepped out of the world. I'll put you back")
pos_y = 3
def search():
num_items = len(stuff)
if num_items < 7:
i = random.randint(0, 15)
if i == 0 or 3:
print("you found some water")
stuff.append('water')
elif i == 1 or 5:
print("you found some floor food, YUMMY!")
stuff.append('food')
elif i == 2:
w = random.randint(0, 2)
if w == 0:
print("you found a whip")
stuff.append('whip')
elif w == 1:
print("you found a club")
stuff.append('club')
elif w == 2:
print("you found a holy sword")
stuff.append('hsword')
else:
print("you found nothing special")
else:
print("you can't carry anything else. Try dropping something or cheating the carry weight stats...")
def drop():
print(stuff)
drop_item = input("\nEnter the index of the item you wish to drop using the number keys "
"(hint: the first item is index 0)")
stuff.pop(int(drop_item))
def fight():
global you_hp
you_attack = 5.0
you_defense = 7.0
zombie_attack_one = 5.0
zombie_defense_one = 4.0
zombie_hp_one = 7.0
zombie_defense_two = 6.0
zombie_hp_two = 7.0
have = check_items('whip')
if have == True:
you_attack += 1.5
you_defense += 0.5
have = check_items('stick')
if have == True:
you_attack += 2.0
you_defense -= 0.5
have = check_items('hsword')
if have == True:
you_attack += 4.0
you_defense += 1.0
else:
pass
num_zombies = random.randint(1, 2)
turn = 0
fight = True
print("watch out, there are " + str(num_zombies) + " zombies!")
while fight == True:
turn += 1
go = turn % 2
if num_zombies == 1:
zombie_hp_two = 0
else:
pass
if zombie_hp_one <= 0 and zombie_hp_two <= 0:
print("you defeated them!")
break
if you_hp <= 0:
print("You FAILED, the prince/princess is dragon food")
quit()
if go == 1:
super_att = random.randint(1, 7)
if super_att == 1:
you_attack = 15.0
elif super_att == 2:
you_attack = 10.0
elif super_att == 3:
you_attack = 30.0
elif super_att == 4:
you_attack = 1.0
else:
you_attack = 5.0
opt = input("do you wish to attack\n")
if opt == 'yes':
dev = input("which zombie would you like to attack\n")
if dev == "1":
hit = you_attack / zombie_defense_one
zombie_hp_one -= hit
print("zombie one has " + str(int(zombie_hp_one)) + " hp left")
elif dev == "2":
hit = you_attack / zombie_defense_two
zombie_hp_two -= hit
print("zombie two has " + str(int(zombie_hp_two)) + " hp left")
else:
print("invalid input -> lose a turn")
elif opt == 'run':
r = random.randint(0, 5)
if r == 0:
print("you got away safely!")
break
else:
print("sadly you were not agile enough to escape the zombies")
pass
else:
print("Invalid input. lose a turn")
elif go == 0:
att = random.randint(1, 5)
super_att = random.randint(1, 3)
if super_att == 1:
zombie_attack_one = 20.0
elif super_att == 2:
zombie_attack_one = 2.0
else:
zombie_attack_one = 6.0
if att == 1 or 2 or 3:
hit = zombie_attack_one / you_defense
you_hp -= hit
print("\n a zombie attacked and you have " + str(int(you_hp)) + " hp left")
else:
print("\nThe Zombie misses you")
def main():
global pos_x
global pos_y
global you_hp
d_intro()
game = True
while game == True:
z = random.randint(0,3)
if z == 3:
fight()
check_pos()
dev = input("\nWhat are you going to do?\n").lower()
if dev == "quit":
game = False
elif dev == "left":
pos_x -= 1
elif dev == "right":
pos_x += 1
elif dev == "up":
pos_y += 1
elif dev == "down":
pos_y -= 1
elif dev == "pos x":
print(pos_x)
elif dev == "pos y":
print(pos_y)
elif dev == "map":
if pos_x <= 2 and pos_y <= 3:
print(map_dungeon)
if pos_x == 0 and pos_y == 0:
print("you are in the cellar")
elif pos_x == 1 and pos_y == 0:
print("you are in the *locked* room")
elif pos_x == 0 and pos_y == 1:
print("you are downstairs")
elif pos_x == 0 and pos_y == 2:
print("you are downstairs")
elif pos_x == 1 and pos_y == 2:
print("you are in the main room")
elif pos_x == 1 and pos_y == 1:
print("you are in the armory")
elif pos_x == 1 and pos_y == 3:
print("you are in the main room")
elif pos_x == 2:
print("you are outside the dungeon")
else:
print("no map... \nTry moving up or down!\n")
elif dev == "check items":
print(stuff)
elif dev == "health":
print(you_hp)
elif dev == "drink":
have = check_items('water')
if have == True:
hp_up = random.randint(2, 6)
you_hp += hp_up
stuff.remove('water')
print("your hp increased by " + str(hp_up))
elif have == False:
print("you don't have any water...sucks for you. *narrator takes sip of water*")
else:
print("something went horribly wrong")
elif dev == "eat":
have = check_items("food")
if have == True:
hp_up = random.randint(4, 8)
you_hp += hp_up
stuff.remove('food')
print("your hp has increased by " + str(hp_up))
elif have == False:
print("you don't have any food... :(")
else:
print("something went horribly wrong")
elif dev == "search":
search()
elif dev == "drop":
drop()
else:
print("what is this \"" + dev + "\" nonsense?")
print("\n\n\n\n Hello and welcome to the adventure hero! If this is your first time playing, you should type in 'how "
"to 'play' so that you can learn to play the game. If you have played the game before, know the game's code, or "
"are just really lucky, type in 'start' to begin or 'quit' to exit.")
opt = input()
if opt == 'start':
main()
elif opt == 'how to play':
print("\n\n\n\nHOW TO PLAY: \n\n MAIN CONTROLS: There are multiple things you can do in this game. To move around "
"you simply enter which way you want to go. For example, if you want to go left, type in \"left\". "
"It is importanr to note that your movement is tracked in a grid system, you can find your position at any "
"time by typing \"pos x\" or \"pos y\".\n To print the map so you can see where your are, input \"map\". To "
"see what you are holding, input \"check items\" and to drop an item, input \"drop\". You can also look for "
"items by inputting \"search\".\n If you want to know how many health points you have, type \"health\". \n\n "
"FIGHTING: You can also fight in this game. First you will be told how many enemies you are facing and then "
"you can choose to fight by typing \"yes\" or try to run by typing \"run\". To choose which enemy to attack, "
"type the number of the enemy, for example, \"1\" for enemy one or \"2\" for enemy 2. \n If your hp is low "
"after fighting, you can eat or drink to restore hp by typing \"eat\" or \"drink\", but you need the items "
"to do so. \n That's it, HAVE FUN!")
if input() == 'start':
main()
elif input() == 'quit':
exit
else:
print("Sorry, seems a black hole has opened in the game's source code. Shutting Down...")
|
#python3 programe for bubble sort
def bubbleSort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if swapped == False:
break
#driver code
if __name__ == "__main__":
arr = [9, 1, 8, 2, 7, 3, 6, 4, 5]
print(arr)
bubbleSort(arr)
print(arr)
|
#Python3 programe for deleting node from binary tree
#Class for binary tree Node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
#Print inorder of binary tree
def inorder(node):
if not node:
return
inorder(node.left)
print(node.data, end=" ")
inorder(node.right)
#function for deleting deepest node in binary tree
def deepestDelete(root, d_node):
queue = []
queue.append(root)
while (len(queue)):
node = queue.pop(0)
if node is d_node:
node = None
return
if node.right:
if node.right is d_node:
node.right = None
return
else:
queue.append(node.right)
if node.left:
if node.left is d_node:
node.left = None
return
else:
queue.append(node.left)
#Delete function for deleting node from binary tree
def delete(root, key):
if root.left == None and root.right == None:
if root.data == key:
root.data = None
return
key_node = None
queue = []
queue.append(root)
while (len(queue)):
temp = queue.pop(0)
if temp.data == key:
key_node = temp
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
if key_node:
key_node.data = temp.data
deepestDelete(root, temp)
# temp = None
# deleteDeepest(root, key_node)
#Driver code
if __name__ == "__main__":
root = Node(10)
root.left = Node(11)
root.left.left = Node(7)
root.left.right = Node(12)
root.right = Node(9)
root.right.left = Node(15)
root.right.right = Node(8)
print('Tree before deleting node.....')
inorder(root)
#delete key 12
delete(root, 10)
print('Tree after deleting 12 .....')
inorder(root) |
n = int(input("Introduzca un número positivo mayor o igual a 0: ")) #SOLICITA VALOR
for i in range (1,n+1,1): #REPETIR N VECES
print ("*",end="") #IMPRIMIR * SIN SALTO DE LINEA |
#! python3
# zipBackup.py - Copies an entire folder and its contents into a ZIP file where the file name increments each time
import zipfile, os
def backupToZip(folder):
#Back up entire folder to ZIP
folder = os.path.abspath(folder)
#Calculate version number
number = 1
while True:
zipFileName = os.path.basename(folder + '_' + str(number) + '.zip')
if not os.path.exists(zipFileName):
break
number += 1
#Create the zip file
print(f'Creating {zipFileName}...')
backupZip = zipfile.ZipFile(zipFileName, 'w')
print('Done.')
#Walk the directory tree and compress the files in each folder
for folderName, subFolders, fileNames in os.walk(folder):
print(f'Adding files in {folderName}...')
# Add the current folder to ZIP file
backupZip.write(folderName)
#Add all files in this folder to the ZIP file
for fileName in fileNames:
newBase = os.path.basename(folder) + '_'
if fileName.startswith(newBase) and fileName.endswith('.zip'):
#Dont back up ZIP files
continue
backupZip.write(os.path.join(folderName, fileName))
backupZip.close()
print('Done.')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# cw-miesiące.py
#
def main(args):
nazwy = ['styczen', 'luty', 'marzec', 'kwiecen', 'maj', 'czerwiec', 'lipiec', 'sierpien', 'wrzesien', 'pazdziernik', 'listopad', 'grudzien']
while 1 > 0:
numer = int(input("Podaj numer miesiąca: "))
if 1 > numer > 12:
print("Wprowadzone dane są błędne !")
else:
print(nazwy[numer - 1])
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
#Python 3.6.8
#author Karan Joshi
from bs4 import BeautifulSoup
import pandas
from selenium import webdriver # Use https://github.com/mozilla/geckodriver/releases to install geckodriver on your python console
import time
driver=webdriver.Firefox() # Instantiating browser object
page=driver.get("https://yourstory.com/companies/search?page=1&sortBy=EmployeeCountASC&hitsPerPage=1000")
time.sleep(10) # Waiting for automated browser to get the page downloaded
all_table=driver.find_element_by_tag_name("table") # searching the table tag in the html code
soup=BeautifulSoup(all_table.get_attribute("innerHTML"),"html.parser") # get the inner html code of tables as a Beautiful soup object
x=soup.find_all("div")# get all divs from the table html code
df=pandas.DataFrame()# start a pandas dataframe
table_text=[i.text for i in x] # for each element in the list x transfer its text to each element of table_text list
df["name"]=table_text[::5] # transfer to each row corresponding to the attributes into the dataframe
df["sectors"]=table_text[1::5]
df["headquaters"]=table_text[2::5]
df["funding"]=table_text[3::5]
df["employee count"]=table_text[4::5]
df.to_csv("your_story_full_page_type1.csv")# transfer dataframe to csv
|
def palindrome(input):
if input == "".join(reversed(input)):
return True
return False
if __name__ == "__main__":
user_in = input("Enter a string: ")
print(palindrome(user_in)) |
'''
Given an unsorted array of nonnegative integers, find a continous subarray which adds to a given number.
'''
def getShortestSubArray(input_arr, k):
shortest_length = -1
left_side = 0
right_side = 0
cur_sum = input_arr[0]
while right_side < len(input_arr):
if left_side > right_side:
right_side += 1
if right_side == len(input_arr):
break
cur_sum += input_arr[right_side]
elif cur_sum > k:
cur_sum -= input_arr[left_side]
left_side += 1
elif cur_sum < k:
right_side += 1
if right_side == len(input_arr):
break
cur_sum += input_arr[right_side]
else:
cur_length = right_side - left_side + 1
if shortest_length == -1:
shortest_length = cur_length
elif shortest_length > cur_length:
shortest_length = cur_length
cur_sum -= input_arr[left_side]
left_side += 1
return shortest_length
if __name__ == '__main__':
test_arr = [2,1,2]
print getShortestSubArray(test_arr, 33)
test_arr = [1, 4, 20, 3, 10, 5]
print getShortestSubArray(test_arr, 33)
test_arr = [1, 4, 0, 0, 3, 10, 5]
print getShortestSubArray(test_arr, 7)
|
'''
Longest Substring Which contains K Unique Characters
'''
def getLongestSubString(input_str):
# Use a hashmap to store the index of each character, if finding duplicate the left side of window will start from there
left_side = 0
right_side = 0
max_length = 1
max_left = 0
max_right = 0
char_cache = {}
char_cache[input_str[0]] = 0
while right_side + 1 <= len(input_str) - 1:
right_side += 1
if input_str[right_side] in char_cache:
# clear all the other cache
last_appear_index = char_cache[input_str[right_side]] + 1
for i in input_str[left_side:last_appear_index]:
del char_cache[i]
char_cache[input_str[right_side]] = right_side
left_side = last_appear_index
else:
char_cache[input_str[right_side]] = right_side
cur_length = right_side - left_side
if cur_length > max_length:
max_length = cur_length
max_left = left_side
max_right = right_side - 1
return max_length, max_left, max_right
def getLongestSubStringWithKUnique(input_str, k):
# stores the last appear index
char_cache = {}
left_side = 0
right_side = 0
max_length = 0
max_left = 0
max_right = 0
char_cache[input_str[0]] = 0
while right_side + 1 <= len(input_str) - 1:
right_side += 1
cur_char = input_str[right_side]
if cur_char in char_cache:
char_cache[cur_char] = right_side
else:
if len(char_cache) == k:
# find the smallest last appear index
smallest_c = None
smallest_index = right_side
for c in char_cache:
if char_cache[c] < smallest_index:
smallest_index = char_cache[c]
smallest_c = c
del char_cache[smallest_c]
left_side = smallest_index + 1
char_cache[cur_char] = right_side
print left_side, right_side
if len(char_cache) == k:
cur_length = right_side - left_side + 1
if max_length < cur_length:
max_length = cur_length
max_left = left_side
max_right = right_side
return max_length, input_str[max_left:max_right+1]
if __name__ == '__main__':
test_input = "abbbbcacdefaghi"
test_input = "abcadcacacaca"
#print getLongestSubString(test_input)
print getLongestSubStringWithKUnique(test_input, 3)
|
def integer_to_english_words(num):
ret = ""
billion = 1000000000
million = 1000000
thousand = 1000
n_to_english = {
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine',
10: 'Ten',
11: 'Eleven',
12: 'Twelve',
13: 'Thirteen',
14: 'Fourteen',
15: 'Fifteen',
16: 'Sixteen',
17: 'Sevnteen',
18: 'Eighteen',
19: 'Ninteen',
20: 'Twenty',
30: 'Thirty',
40: 'Fourty',
50: 'Fifty',
60: 'Sixty',
70: 'Seventy',
80: 'Eighty',
90: 'Ninty'
}
if num >= billion:
ret += integer_to_english_words(num / billion) + " Billion "
num = num % billon
if num >= million:
ret += integer_to_english_words(num / million) + " Million "
num = num % million
if num >= thousand:
ret += integer_to_english_words(num / thousand) + " Thousand "
num = num % thousand
if num >= 100:
ret += n_to_english[num / 100] + " Hundred "
num = num % 100
if num == 10:
return ret + " Ten"
if num > 10:
ret += n_to_english[num/10*10] + " "
num = num % 10
if num > 0:
ret += n_to_english[num]
return ret.strip()
print integer_to_english_words(9999999)
print integer_to_english_words(1234567)
|
'''
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
'''
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
water = 0
left = 0
right = len(height) - 1
water = 0
while left < right:
if height[left] < height[right]:
min_bar = height[left]
left += 1
while left < right and height[left] <= min_bar:
water += min_bar - height[left]
left += 1
else:
min_bar = height[right]
right -= 1
while left < right and height[right] <= min_bar:
water += min_bar - height[right]
right -= 1
return water
sol = Solution()
print sol.trap([0,1,0,2,1,0,1,3,2,1,2,1])
|
#Advent of Code 2019 Day 1 Part 2: The Tyranny of the Rocket Equation
fuelReq = []
def fuelCalc(mass):
mass = int(mass)
return mass//3-2
filepath = 'Day1.txt'
with open (filepath) as masses:
for mass in masses:
fuel = fuelCalc(mass)
fuelTotal = fuel
while fuel > 0:
fuel = fuelCalc(fuel)
if fuel > 0:
fuelTotal += fuel
fuelReq.append(fuelTotal)
print(sum(fuelReq)) |
from .exceptions import *
import random
# Complete with your own, just for fun :)
LIST_OF_WORDS = []
def _get_random_word(list_of_words):
if list_of_words == []:
raise InvalidListOfWordsException
else:
return random.choice(list_of_words)
def _mask_word(word):
if len(word) == 0:
raise InvalidWordException('Those words cannot.')
word_length = len(word)
masked_word = word.replace(word, "*"*word_length)
return(masked_word)
def _uncover_word(answer_word, masked_word, character):
if len(answer_word) == 0 or len(masked_word) == 0:
raise InvalidWordException('Those words are invalid.')
if len(character) > 1:
raise InvalidGuessedLetterException('Those guess letters are invalid.')
if len(answer_word) != len(masked_word):
raise InvalidWordException('Those words are invalid.')
result = ''
index = 0
for i in answer_word:
if (i.lower()) == (character.lower()):
result += (character.lower())
else:
result += masked_word[index]
index += 1
final_result = ''.join(result)
return(final_result)
def guess_letter(game, letter):
if game['masked_word'] == game['answer_word'] or game['remaining_misses'] == 0:
raise GameFinishedException('The game has finished.')
from game import _uncover_word
if (letter.lower()) in ((game['answer_word']).lower()):
new_masked_word = _uncover_word(game['answer_word'], game['masked_word'], letter)
game.update(masked_word = new_masked_word)
else:
game['remaining_misses'] -= 1
game['previous_guesses'].append(letter.lower())
if game['masked_word'].lower() == game['answer_word'].lower():
raise GameWonException
if game['remaining_misses'] == 0 and game['masked_word'] != game['answer_word']:
raise GameLostException
return game
def start_new_game(list_of_words=None, number_of_guesses=5):
if list_of_words is None:
list_of_words = LIST_OF_WORDS
word_to_guess = _get_random_word(list_of_words)
masked_word = _mask_word(word_to_guess)
game = {
'answer_word': word_to_guess,
'masked_word': masked_word,
'previous_guesses': [],
'remaining_misses': number_of_guesses,
}
return game
|
#! /usr/bin/env python3
def fuel(amt):
return (amt//3) - 2
def all_fuel(amt):
num = fuel(amt)
sub = 0
while num > 0:
sub += num
num = fuel(num)
return sub
total = 0
with open("input") as f:
for line in f:
total += all_fuel(int(line))
print(total)
|
# Multiples
# Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
number = range(0,100)
for i in number:
if i%2!=0:
print i
# Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000.
number = range(5,1000000)
for i in number:
if i%5==0:
print i
# Sum List Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3]
a = [1, 2, 5, 10, 255, 3]
print sum(a)
# Average List Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3]
a = [1, 2, 5, 10, 255, 3]
print sum(a)/ float(len(a))
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import random
def play():
a = random.randint(0,20) #a adalah bilangan random yg akan ditebak
#print("contoh angka random: ",a)
score = 100
b=11 #b adalah angka yg akan ditebak, b=11 inisiasi awal aja
tebakan_bnr = False
print("*" * 40)
print("PERMAINAN TEBAK ANGKA")
print("*" * 40)
print("Silahkan menebak angka dari 1-20")
print("Setiap kali kamu menebak salah, score akan dikurangi 10 poin")
print("Kalau kamu memasukkan selain angka, kamu akan dipenalti 20 poin ;)")
while score>0 and b!=a:
print("Score mu saat ini ", score, "\n")
try:
b = int(input("Berapa tebakanmu? "))
if b==a:
tebakan_bnr = True
elif b>a:
score -= 10
print("\nKegedean!")
else:
score -= 10
print("\nKekecilan!")
except ValueError:
score -= 20
print("itu bukan angka :(")
if tebakan_bnr:
print("yey kamu hebat! scoremu adalah ",score)
return score
else:
print("GAME OVER!! Score : ",score)
return score |
#!/usr/local/bin/python3
# Python class to implement a Kalman Filter
import numpy as np
import matplotlib.pyplot as plt
from random import random
from math import *
class kalman():
# Init assuming 2d problem with no control input or process noise
def __init__(self, t0, dx):
self.t = t0
# Measurement function
self.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]])
# Measurement uncertainty
self.R = np.array([[dx, 0], [0, dx]])
# Initialize state
self.x = np.zeros([4,1])
# Initialize variance
self.P = 1000 * np.identity(4)
def step(self, t, z):
dt = t - self.t
self.t = t
# State function with new dt
self.F = np.identity(4)
self.F[0,2] = dt
self.F[1,3] = dt
# Update
y = z - np.dot(self.H, self.x)
S = np.dot(self.H, np.dot(self.P, self.H.transpose())) + self.R
K = np.dot(np.dot(self.P, self.H.transpose()), np.linalg.inv(S))
self.x = self.x + np.dot(K, y)
self.P = np.dot((np.identity(4) - np.dot(K, self.H)), self.P)
# Predict
self.x = np.dot(self.F, self.x)
self.P = np.dot(self.F, np.dot(self.P, self.F.transpose()))
x = self.x
P = self.P
return(x, P)
def line(n, dx):
x0 = 0
y0 = 0
theta = pi/4
v = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9.5, 9, 8.5, 8, 7, 6, 5, 4, 2, 1, 0.5]
dt = 0.1
t = np.linspace(0, 10, 101)
pos = np.empty([n, 2])
for i in range(n):
x_new = np.random.normal(x0 + t[i] * v[i] * cos(theta), dx)
y_new = np.random.normal(y0 + t[i] * v[i] * sin(theta), dx)
pos[i,:] = [x_new, y_new]
return(t, pos)
def main():
# Initialize the kalman filter
dx = 0.2 # measurement uncertainty
k = kalman(0, dx)
n = 21
t, truth = line(n, dx)
filt_pos = np.empty([n, 4])
filt_spd = np.empty(n)
spd_var = np.empty(n)
for i in range(n):
# Prepare the measurement input
z = np.array(truth[i,:], ndmin=2).transpose()
# Run the Kalman Filter
x, P = k.step(t[i], z)
# Record the output
filt_pos[i,:] = np.transpose(x)
filt_spd[i] = np.linalg.norm([x[2][0], x[3][0]])
spd_var[i] = np.linalg.norm([P[2][2], P[3][3]])
# Plot the results
plt.subplot(2,1,1)
plt.plot(truth[:,0],truth[:,1],'+')
plt.plot(filt_pos[:,0],filt_pos[:,1],'--')
plt.axis('equal')
plt.subplot(2,1,2)
plt.plot([10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9.5, 9, 8.5, 8, 7, 6, 5, 4, 2, 1, 0.5])
plt.plot(filt_spd)
plt.plot(spd_var)
plt.axis([0, 50, 0, 15])
plt.show()
main() |
l = [1,2,3]
l.append(4)
l.count(2)
x = [1,2,3]
x.append([4,5])
# appends the entire element to the list, list in a list
# if you want to add to the list, use extend
x.extend([4,5])
l.index(2)
# two arguments: index, object
l.insert(2,'inserted')
ele = l.pop()
# pop always last element, but can add index
l.remove('inserted')
# removes only the first occurance of a value
l.reverse()
l.sort()
|
class Animal():
def __init__(self):
print('Animal created')
def who_am_i(self):
print('I am an animal')
def eat(self):
print('I am eating')
#myanimal = Animal()
#print(myanimal.eat())
class Dog(Animal):
#Derived class
def __init__(self):
Animal.__init__(self)
print('Dog created')
def who_am_i(self):
print('I am a dog')
def bark(self):
print('Woof!')
mydog = Dog()
mydog.eat()
mydog.who_am_i()
mydog.bark()
|
def myfunc():
print('Hello World')
def myfunc(Name):
print('Hello {}'.format(Name))
def myfunc(s):
if s == True:
return 'Hello'
if s == False:
return 'Goodbye'
def myfunc(x, y, z):
if z == True:
return x
if z == False:
return y
def myfunc(a, b):
return a+b
def is_even(a):
if a % 2 == 0:
return True
else:
return False
def is_greater(a, b):
if a > b:
return True
else:
return False
"""
def myfunc(*args):
return sum(args) > no limit to input, arbitrary number of arguments
doesn't have to be 'args', it's about the asterix but convention is args
**kwargs = keyword arguments. kwargs returns a dictionary
def myfunc(**kwargs):
if 'fruit' in kwargs:
print('My fruit of choice is {}'.format(kwargs[fruit]))
else:
print('No fruit.')
myfunc(fruit='apple', veggie='lettuce')
def myfunc(*args, **kwargs):
print('I would like {} {}'.format(args[0], kwargs['food']))
myfunc(10,20,30,fruit='orange', food='eggs', animal='dog')
"""
def myfunc(*args):
return sum(args)
def myfunc(*args):
my_list = []
for n in args:
if n % 2 == 0:
my_list.append(n)
return my_list
def myfunc(string):
new_string = ''
index = 0
for letter in string:
if index % 2 == 0:
new_string += letter.upper()
else:
new_string += letter.lower()
index += 1
return new_string
|
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposit of {amount} accepted.")
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
print(f"Withdrawal of {amount} accepted.")
else:
print("Funds unavailable!")
def __str__(self):
return f"Account owner: {self.owner}\nAccount balance: {self.balance}"
acct1 = Account('Jose',100)
print(acct1)
print(acct1.owner)
print(acct1.balance)
acct1.deposit(50)
print(acct1.balance)
acct1.withdraw(75)
print(acct1.balance)
acct1.withdraw(500)
print(acct1.balance)
|
"""
Write a Python program that matches
a string that has an a followed by three 'b'.
"""
import re
def is_match(text):
pattern = ("ab{3}")
if re.search(pattern, text):
return "Match found!"
else:
return "Match not found"
print(is_match("a")) |
"""
you get a sorted list and need to find the first and last appearence of a certain number in the list and return the indices
example if input is 1, 3, 3, 5, 7, 8, 9, 9, 15
if asked for 9 the indicie range is 6-9
lets do it in sub-linear time
"""
#this is binary search to solve it
class Range:
def GetRange(self, nums, target):
start = self.binarySearch(nums, 0, len(nums) - 1, target, True)
finish = self.binarySearch(nums, 0, len(nums) - 1, target, False)
start2 = self.binaryiterativeSearch(nums, 0, len(nums) - 1, target, True)
finish2 = self.binaryiterativeSearch(nums, 0, len(nums) - 1, target, False)
print("recursive version solution: ", start, finish)
print("iterative version solution: ", start2, finish2)
#recursive solution
def binarySearch(self, nums, low, high, target, findFirst):
if high < low:
return -1
mid = low + (high - low) // 2
if findFirst:
if (mid == 0 or target > nums[mid-1]) and nums[mid] == target:
return mid
if target > nums[mid]:
return self.binarySearch(nums, mid + 1, high, target, findFirst)
else:
return self.binarySearch(nums, low, mid - 1, target, findFirst)
else:
if (mid == len(nums) - 1 or target < nums[mid + 1]) and nums[mid] == target:
return mid
elif target < nums[mid]:
return self.binarySearch(nums, low, mid - 1, target, findFirst)
else:
return self.binarySearch(nums, mid + 1, high, target, findFirst)
#iterative version
def binaryiterativeSearch(self, nums, low, high, target, findFirst):
while True:
if high < low:
return -1
mid = low + (high - low) // 2
if findFirst:
if (mid == 0 or target > nums[mid-1]) and nums[mid] == target:
return mid
if target > nums[mid]:
low = mid + 1
else:
high = mid -1
else:
if (mid == len(nums) - 1 or target < nums[mid + 1]) and nums[mid] == target:
return mid
elif target < nums[mid]:
high = mid - 1
else:
low = mid + 1
nums = [1, 3, 3, 5, 7, 8, 9, 9, 15]
x = 9
sol = Range();
sol.GetRange(nums, x) |
#this is for adding a functionality for the stack which will return the maximum number
class Max(object):
def __init__(self):
self.stack = []
self.maxs = []
def push(self, val):
self.stack.append(val);
if self.maxs and self.maxs[-1] > val:
self.maxs.append(self.maxs[-1])
else:
self.maxs.append(val)
def pop(self):
if self.maxs:
self.maxs.pop()
return self.stack.pop()
def max(self):
return self.maxs[-1]
runner = Max()
runner.push(2)
print("pushing 2")
print("current MAX: ", runner.max(), "\n")
runner.push(1)
print("pushing 1")
print("current MAX: ", runner.max(), "\n")
runner.push(5)
print("pushing 5")
print("current MAX: ", runner.max(), "\n")
runner.push(3)
print("pushing 3", )
print("current MAX: ", runner.max(), "\n")
runner.push(7)
print("pushing 7")
print("current MAX: ", runner.max(), "\n")
runner.push(10)
print("pushing 10")
print("current MAX: ", runner.max(), "\n") |
'''Creating the functionality for the application
In this file, we are going to create the functionality for our application. There are multiple functionality.
Functionalities:
1. signup
2. login
3. add_events
4. show_events
5. remove_events
6. add_participants
7. show_participants
8. remove_participants
'''
from models import User, EventList, ParticipantList
'''1. signup
Creating a signup page where the user provides details like fullname, username, password and email address
'''
def signup():
fullname = input("Enter Full Name: ")
username = input("Enter username: ")
password = input("Enter password: ")
email_id = input("Enter email id: ")
print("Created New Sign Up")
# Creating the user
user = User.create(fullname=fullname, username=username, password=password, email_id=email_id)
'''2. login
Helping a user to login into the database
'''
def login():
username = input("Enter username: ")
password = input("Enter password: ")
for person in User.select():
# Checking the username entered is present in the database
if username not in person.username:
print("Invalid Username. Please check the username that you have entered.")
# Checking if the entered password is right or wrong
for person in User.select().where(User.username == username):
if password in person.password:
# If the entered password is 1, return 1, else print the message
return 1
else:
print("Invalid Password. Please check the password that you have entered.")
'''3. add_events
Creating an add_events page where a user can add multiple events to the database.
'''
def add_events():
count = int(input("Enter how many events to add: "))
for i in range(count):
event_name=input("Enter event: ")
event_description = input("Enter the description of the event: ")
fees = int(input("Enter the entry fee for the event: "))
coordinator_name = input("Enter the coordinator name: ")
coordinator_no = int(input("Enter the coordinator's number: "))
event_timings = input("Enter the timings of the event: ")
# Saving the entered details for the event
event = EventList.create(event_name=event_name, description=event_description, fees=fees, coordinator_name=coordinator_name,
coordinator_no=coordinator_no, event_timings=event_timings )
'''4. show_events
Showing all the events which are present.
'''
def show_events():
for event in EventList.select():
print(event.id, event.event_name, sep=" - ")
'''5. remove_events
Removing events which are not needed for the fest.
'''
def remove_events():
print("Here are the list of the events that are present: ")
for event in EventList.select():
print(f"'{event.event_name}'")
event_name = input("Enter event name to remove: ")
delete_event = EventList.get(event_name=event_name)
EventList.delete_instance(delete_event)
'''6. add_participants
Creating an add_participants page where a user can add multiple participants to the database.
'''
def add_participants():
participant_name = input("Enter the participant name: \n")
# Getting data of all the events
for event in EventList.select():
print(event.id , event.event_name)
event = int(input("Enter the choice event name from the events list above:\n"))
# Getting the event name and the entry fees for that particular event
selected_event = EventList.get(id=event)
event_name = selected_event.event_name
amount = selected_event.fees
ph_no = int(input("Enter participant's phone number: "))
# Saving the participant details to the database
participant = ParticipantList.create(name=participant_name, event_name=event_name, price=amount, ph_no=ph_no)
'''7. show_participants
Showing all the participants who are part of the event.
'''
def view_participants():
for event in ParticipantList.select():
print(event.name, event.event_name, event.price, sep=" - ")
'''8. remove_participants
Removing participants who are not part of the event.
'''
def remove_participants():
participant_name = input("Enter participant's full name whom you want to remember: ")
name = ParticipantList.get(name=participant_name)
ParticipantList.delete_instance(name)
'''
Working of the application
'''
while True:
ch = input("Select what you want to do?\n\
1. Log In\n\
2. Sign Up \n\
3. Exit \n\
Enter your choice: ")
if ch == "1":
state = login()
# Checking the user has entered the proper details
if state == 1:
while True:
ch = input("1. Add Participants \n\
2. View Participants \n\
3. Remove Participants \n\
4. Add events \n\
5. Show events \n\
6. Remove events \n\
7. Log Out \n\
Enter your choice: ")
if ch == "1":
add_participants()
elif ch == '2':
view_participants()
elif ch == '3':
remove_participants()
elif ch == "4":
add_events()
elif ch == '5':
show_events()
elif ch == '6':
remove_events()
else:
break
elif ch == "2":
signup()
else:
break |
# 18. Read in some text from a corpus, tokenize it, and print the list of all wh-word types that occur. (wh-words in English are used in questions, relative clauses and exclamations: who, which, what, and so on.) Print them in order. Are any words duplicated in this list, because of the presence of case distinctions or punctuation?
import re
from nltk.corpus import brown
REGEX = re.compile('^wh', re.IGNORECASE)
wh_words = set([])
for genre in brown.categories():
for word in brown.words(categories=genre):
if REGEX.match(word):
wh_words.add(word.lower())
print('==========')
print('Ex18 words : {}\n'.format(len(wh_words)))
print(wh_words)
# 25. Pig Latin is a simple transformation of English text. Each word of the text is converted as follows: move any consonant (or consonant cluster) that appears at the start of the word to the end, then append ay, e.g. string → ingstray, idle → idleay. http://en.wikipedia.org/wiki/Pig_Latin
# + Write a function to convert a word to Pig Latin.
# + Write code that converts text, instead of individual words.
# + Extend it further to preserve capitalization, to keep qu together (i.e. so that quiet becomes ietquay), and to detect when y is used as a consonant (e.g. yellow) vs a vowel (e.g. style).
def pig_latinize_word(word):
word = list(word)
result = []
back = []
while len(word):
c = word[0]
if c in 'aeiou':
result.extend(word)
result.extend(back)
break
else:
back.append(word.pop(0))
return ''.join(result) + 'ay'
def pig_latinize_text(text):
text = text.split(' ')
text = map(pig_latinize_word, text)
return ' '.join(text)
text = 'You can find an excellent introduction to regular experssoins at this site'
result = pig_latinize_text(text)
print('\n==========')
print("Ex28 test: {}".format(result))
|
list = [2, 4, 6, 8 ,10]
for item in list[0:3]:
print(item)
list2 = ["Gustavo", "Costa"]
for name in list2:
if not name == "Gustavo":
print(name) |
#!/usr/bin/env python3
import numpy as np
import cv2
import matplotlib.pyplot as plt
from VO import MonoVo as VO
import os
classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable',
'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep',
'sofa', 'train', 'tvmonitor']
colors = np.random.uniform(0, 255, size=(len(classes), 3))
def recognize(image, confidence_thresh: float):
'''
recognize takes an image and draws boxes on it in place then passes
it back to the calling function
Parameters
----------
image - The opencv read matrix image
confidence_thresh (float) - The confidence under which we filter detections
'''
network = cv2.dnn.readNetFromCaffe(
'./caffe_model.prototxt.txt', './model.caffemodel')
h, w = image.shape[:2]
blob = cv2.dnn.blobFromImage(
cv2.resize(image, (800, 800)), 0.007843, (800, 800), 127.5)
print('[INFO] Detecting...')
network.setInput(blob)
detections = network.forward()
# Get all the detections
for i in np.arange(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
# Filter out weak detections
if confidence > confidence_thresh:
# Get the class label, then place the box
idx = int(detections[0, 0, i, 1])
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
start_x, start_y, end_x, end_y = box.astype('int')
# show prediction
label = '{}: {:.2f}%'.format(classes[idx], confidence * 100)
cv2.rectangle(
image, (start_x, start_y), (end_x, end_y), colors[idx], 2)
y = start_y - 15 if start_y - 15 > 15 else start_y + 15
cv2.putText(image,
label,
(start_x, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, colors[idx], 2)
return image
def run(image_path, pose_path, focal, pp, R_total, t_total):
lk_params = dict(winSize=(21, 21),
criteria=(
cv2.TERM_CRITERIA_EPS |
cv2.TERM_CRITERIA_COUNT, 30, 0.01))
vo = VO(image_path, pose_path, focal, pp, lk_params)
traj = np.zeros(shape=(600, 800, 3))
while(vo.has_next_frame):
frame = recognize(vo.current_frame, 0.7)
cv2.imshow('frame', frame)
k = cv2.waitKey(1)
if k == 27:
break
if k == 121:
mask = np.zeros_like(vo.old_frame)
mask = np.zeros_like(vo.current_frame)
vo.process_frame()
print(vo.get_mono_coordinates())
mono_coord = vo.get_mono_coordinates()
true_coord = vo.get_true_coordinates()
print('MSE Error: ', np.linalg.norm(mono_coord - true_coord))
print("x: {}, y: {}, z: {}".format(*[str(pt) for pt in mono_coord]))
print("true_x: {}, true_y: {}, true_z: {}".format(
*[str(pt) for pt in true_coord]))
draw_x, draw_y, draw_z = [int(round(x)) for x in mono_coord]
true_x, true_y, true_z = [int(round(x)) for x in true_coord]
traj = cv2.circle(
traj, (true_x + 400, true_z + 100), 1, list((0, 0, 255)), 4)
traj = cv2.circle(
traj, (draw_x + 400, draw_z + 100), 1, list((0, 255, 0)), 4)
cv2.putText(
traj,
'Actual Position:',
(140, 90),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(255, 255, 255), 1)
cv2.putText(
traj,
'Red',
(270, 90),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 0, 255), 1)
cv2.putText(
traj,
'Estimated Odometry Position:',
(30, 120),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(255, 255, 255), 1)
cv2.putText(
traj,
'Green',
(270, 120),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 255, 0), 1)
cv2.imshow('trajectory', traj)
cv2.imwrite("./images/trajectory.png", traj)
cv2.destoryAllWindows()
if __name__ == '__main__':
pose_path = '../poses/dataset/poses/00.txt'
image_path = '../gray/dataset/sequences/00/image_0/'
focal = 718.8560
pp = (607.1928, 185.2157)
R_total = np.zeros((3, 3))
t_total = np.empty(shape=(3, 1))
run(image_path, pose_path, focal, pp, R_total, t_total)
|
x = input("enter list 1:")
y = input("enter list 2: ")
comb = len(x) + len(y)
if comb % 3 == 0 and comb % 5 == 0:
print("fizzbuzz")
elif comb % 3 == 0:
print("Fizz")
elif comb % 5 == 0:
print("Buzz")
else:
print(comb)
|
class dog:
species = "mamal"
def __init__(self, sound_made):
self.sound_made = sound_made
def sound(self):
print(self.sound_made)
def bite(self):
self.sound_made()
print("bite")
def identify_yourself():
print("i am a" + self.species)
my_dog = dog("wooof")
my_second_dog = dog("wooooooooooof")
# my_dog.sound()
# my_second_dog.sound()
class bulldog(dog):
def run(self):
speed = "100km/hr"
print("i run 100km/hr")
bulldog = dog("reeeeeee")
bulldog.sound
|
txt = str(input("Enter any word: "))
text = txt[1::]
print(txt)
text = text + txt[0]
cyrus = ("ay")
print(text + "ay") |
# tuples
# tuples are immutable
# tuples are ordered collection of data
# tuples can store any data type
# you cannot change(add or delete) values from tuple once it created
# but can add, delete data from list which is present inside tuples
mixed = (1,2,3,4,5,'six')
# no append, no pop, no insert, no remove
# only count and index
# functions
# min(), max(), len(), sum()
mixed2 = (1,2,3,4,5,[6,7,8])
mixed2[5].pop()
print(mixed2) |
# check empty or not
# important
name = input("enter name = ")
if name: # true is string is not empty
print(f"your name is {name}")
else:
print("you did'nt type anything") |
# fromkeys() - used to create dictionaries :-
# d = {'name' : 'unknown', 'age' : 'unknown'}
# d = dict.fromkeys(['name', 'age', 'dob'], 'unknown')
# print(d)
# get() method (useful):- to handls errors we use get() method
d = {'name' : 'harshit', 'age' : 24}
# print(d['dob']) # gives error because 'dob' key is not present in dictionary
# print(d.get('dob', 'dob not found')) # better to access keys in dictionaries
# if 'name' in d:
# print('present')
# else:
# print('not present')
# if d.get('name'):
# print('present')
# else:
# print('not present')
# if None ----> False, else ----> Trues
# clear() method :- clear dictionary
# d.clear()
# print(d)
# copy() method :- copy dictionary
# d1 = d.copy() #--- different dictionary
# d1 = d #--- same dictionary
# print(d1.popitem())
# print(d)
# print(d1 == d) |
# sum : 1 to 10 (or any number)
total = 0
i = 1 # i = 2
while i <= 10:
total = total + i
i = i + 1
print(total)
# total = 0 + 1 |
# will discuss three problems in existing
# then we will solve them using getter , setter decorator
class Phone:
def __init__(self, brand, model_name, price):
self.brand = brand
self.model_name = model_name
self._price = max(price,0)
@property
def complete_specific(self):
return f"{self.brand} {self.model_name} and price {self._price}"
# getter(), setter()
@property
def price(self):
return self._price
@price.setter
def price(self, new_price):
self._price = max(new_price, 0)
def make_a_call(self, phone_number):
return f"calling... {self.phone_number}"
def full_name(self):
return f"{self.brand} {self.model_name}"
phone1 = Phone('Nokia', '1100', -1000)
phone1.price = -500
print(phone1.price)
print(phone1.complete_specific) |
. center(lenght of string, '*')
. replace(" " , "_") # replace ' ' by '_'
. replace("is" , "was" , 1) # replace 1 'is' if 2 then replaces two 'is
. find("is")) # finds the position of is o/p = 4'
. find("is",skip the first 'is')
. str()
. split(",")
. len() function
. lower()
. upper()
. title()
. count('')
. strip methods:-
name = " Har shit "
dots = "..............."
# to remove white spaces we use strip methods
print(name+dots)
print(name.lstrip() + dots) # remove spaces from left side
print(name.rstrip() + dots) # remove spaces from right side
print(name.strip() + dots) # remove spaces from both left and right side
print(name.replace(" ","") + dots) # remove all spaces
|
# common elements finder function
# define a function which takes two lists as input and return a list
# which conatins common elemetns of both lists
# example
# input ---> [1,2,5,8], [1,2,7,6]
# output ---> [1,2]
def common_elements(list1, list2):
common_list = []
for i in list1:
if i in list2:
common_list.append(i)
return common_list
list1 = [1,2,5,8,9,16]
list2 = [1,2,7,6,4,11,9]
print(common_elements(list1, list2)) |
# compare list
# == , is
fruits1 = ['orange', 'apple', 'pear']
fruits3 = ['orange', 'apple', 'pear']
fruits2 = ['banana', 'kiwi', 'apple', 'banana']
print(fruits1 == fruits3) # values are same
print(fruits1 is fruits3) # false |
# some more mehods to add data in out list
# insert method
# how to join(concatenate) two list
# extend method
# difference between append and extend methods
fruits1 = ['mango', 'orange']
# fruits1.insert(1, "grapes")
# print(fruits1)
fruits2 = ["grapes", "apple"]
# fruits = fruits1 + fruits2
# print(fruits)
fruits1.append(fruits2)
# fruits1.extend(fruits2)
print(fruits1)
print(fruits2) |
# lambda expressions (anonymous function)
def add(a,b):
return a+b
add2 = lambda a,b : a+b
print(add2(2,3))
# built in, map , reduce
multiply = lambda a,b : a*b
print(multiply(2,3)) |
# class methods
# difference between class methods and instance methods
class Person:
count_instance = 0 # class variable / class attribute
def __init__(self, first_name):
Person.count_instance = Person.count_instance + 1
self.first_name = first_name
@classmethod
def count_instances(cls): # according to convention we use cls as class
return f"you have created {cls.count_instance} instances of {cls.__name__} class"
p1 = Person('wajid')
p2 = Person('harshit')
p3 = Person('mohit')
print(Person.count_instance) # we use class method like this
# o/p = 3 because three object is created |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.