text stringlengths 37 1.41M |
|---|
#Peter Tran
#1104985
#lab1-problem4
amt = float(input("Enter projected amount of total sales: $"));
print("Expected annual profit is ${:,.2f}".format(.24*amt));
##Enter projected amount of total sales: $10000
##Expected annual profit is $2,400.00
|
"""This problem was asked by Google.
A unival tree (which stands for "universal value") is a tree where all nodes
under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/\ / \
1 0 1 0
/ \
1 1
"""
# FRIST WE NEED TO EMPLEMENT A TREE
class BSTNode:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def add_child(self, data):
if self.data > data:
if self.right is None:
self.right = BSTNode(data)
return
else:
self.right.add_child(data)
else:
if self.left is None:
self.left = BSTNode(data)
return
else:
self.left.add_child(data)
def in_order(self):
elements = []
if self.left:
elements += self.left.in_order()
elements.append(self.data)
if self.right:
elements += self.right.in_order()
return elements
def count_sub_trees(self):
right_node = self.right is None
left_node = self.left is None
if not right_node and not left_node:
return 1 +self.left.count_sub_trees() + self.right.count_sub_trees()
if not right_node :
return 1 + self.right.count_sub_trees()
if not left_node:
return 1+ self.left.count_sub_trees()
return 0
def emplement_tree():
tree = BSTNode(0)
tree.add_child(0)
tree.add_child(1)
tree.add_child(0)
tree.add_child(1)
tree.add_child(1)
tree.add_child(1)
print(tree.count_sub_trees())
if __name__ == "__main__":
emplement_tree() |
"""This problem was asked by Google.
The edit distance between two strings refers to the minimum
number of character insertions, deletions, and substitutions
required to change one string to the other. For example,
the edit distance between “kitten” and “sitting” is three:
substitute the “k” for “s”, substitute the “e” for “i”, and append a “g”.
Given two strings, compute the edit distance between them."""
def compare(first,second):
if len(first) > len(second):
return first
return second
def compute_edit_distance(first,second):
substitute = 0
bigger = compare(first, second)
for i in range(len(bigger)):
try:
if first[i] != second[i]:
substitute += 1
except :
substitute += 1
return substitute
substitute = compute_edit_distance("kitten","sitting")
print("sub =",substitute) |
"""This problem was asked by Google.
Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its descendants or ancestors are not locked.
Design a binary tree node class with the following methods:
• is_locked, which returns whether the node is locked
• lock, which attempts to lock the node. If it cannot be locked, then it should return false. Otherwise, it should lock it and return true.
• unlock, which unlocks the node. If it cannot be unlocked, then it should return false. Otherwise, it should unlock it and return true.
You may augment the node to add parent pointers or any other property you would like. You may assume the class is used in a single-threaded program, so there is no need for actual locks or mutexes. Each method should run in O(h), where h is the height of the tree.
"""
class BinaryTree:
def __init__(self, data, left, right, is_locked):
self.data = data
self.left = left
self.right = right
self.parent = None
self.is_locked = is_locked
self.locked_counter = 0
def is_locked(self):
return self.is_locked
def add_node(self, data: int, is_locked: bool):
if self.data > data:
if self.right is None:
if is_locked:
self.locked_counter += 1
self.right = BinaryTree(data, None, None, is_locked)
self.right.parent = self
return
else:
self.right.add_node(data, is_locked)
else:
if self.left is None:
if is_locked:
self.locked_counter += 1
self.left = BinaryTree(data, None, None, is_locked)
self.left.parent = self
return
else:
self.left.add_child(data, is_locked)
def check(self):
if self.is_locked:
return False
if self.parent:
are_not_locked = self.parent.check()
if are_not_locked:
return False
return True
def lock(self):
if self.check():
self.is_locked = True
curr = self.parent
while curr:
self.locked_counter += 1
curr = curr.parent
return True
return False
def unlocked(self):
are_locked = self.check()
if are_locked:
self.is_locked = True
while curr:
self.locked_counter -= 1
curr = curr.parent
return True
return False
|
print("1" ,"2" , sep="--")
print("1","2", end="|")
print("Model S" , "Model 3" , end="|")
print("100" , "200" , end="|")
print("USA" , "France")
# данный код
print("Добро пожаловать!")
# требуемый вывод:
# Добро пожаловать!
# данный код
my_text="print()"
print(my_text)
# требуемый вывод:
# Функция print()
# данный код
name = "Иван"
surname = "Петров"
salary = "90 000"
# требуемый вывод:
# Иван Петров зарабатывает 90 000 рублей
print(name, surname, salary, "рублей")
name = "Alex"
print("name")
print("Hello World", end="!")
|
"""
Course: CS101
File: <name of your file>
Project: <project number>
Author: <Your name>
Description:
<What does your project/program do?>
"""
"""
Instructions:
1) Create a function to display the welcome message at the start
of the program.
2) You need to create a function that prompts the user for the current month.
3) You need to create a function that prompts the user for the items' name.
4) You need to create a function that prompts the user for the items' monthly amount.
5) You need a function to prompt the users' first name.
6) You need a function to prompt the users' surname name.
7) Display the monthly budget in main after calling the
functions above.
You will end up with 6 functions in this project. Name these functions
correctly (ie., use full words that describe what they do)
Example Output:
Welcome to the monthly budget program
-------------------------------------
Enter Month: March
Enter first name: John
Enter surname: Brown
Enter Item name: Food
Enter Item monthly amount: 50.55
Enter Item name: Coding
Enter Item monthly amount: 5.02
Enter Item name: Toothpaste
Enter Item monthly amount: 0.02
Enter Item name: Rent
Enter Item monthly amount: 350
Enter Item name: Yoga lessons
Enter Item monthly amount: 9.95
March Monthly Budget for John Brown
=================================================
Item Month Year
=================================================
Food $ 50.55 $ 606.60
Coding $ 5.02 $ 60.24
Toothpaste $ 0.02 $ 0.24
Rent $ 350.00 $ 4200.00
Yoga lessons $ 9.95 $ 119.40
=================================================
Totals $ 415.54 $ 4986.48
"""
# Add your functions here
# Add your main here
# You will be calling your functions from here.
|
"""
Course: CS101
File: team.py
Author: Brother Comeau
Description:
This is the code for the weekly team activity.
Please work together in groups of 2 to 3.
You will not be sumbitting your code for this activity.
You are free to continue working on this activity after class if you need more time.
Sample Output:
Display Change
=================================================================
100 cents is Pennies = 0, Nickels = 0, Dimes = 0, Quarters = 4
91 cents is Pennies = 1, Nickels = 1, Dimes = 1, Quarters = 3
49 cents is Pennies = 4, Nickels = 0, Dimes = 2, Quarters = 1
41 cents is Pennies = 1, Nickels = 1, Dimes = 1, Quarters = 1
Display Change in a list
=================================================================
Wallet with 100 cents: [25, 25, 25, 25]
Wallet with 91 cents: [1, 5, 10, 25, 25, 25]
Wallet with 49 cents: [1, 1, 1, 1, 10, 10, 25]
Wallet with 41 cents: [1, 5, 10, 25]
"""
def displayChange(money):
""" Display change of the given money variable """
# Add your code here
print('{:>3} cents is Pennies = {}, Nickels = {}, Dimes = {}, Quarters = {}'.format(originalMoney, pennies, nickels, dimes, quarters))
def fillWallet(money):
""" Creates and fills in a Python list with change based on the money variable """
wallet = []
# Add your code here
return wallet
# ===========================================================================
# Main Code - Don't change
print('Display Change')
print('=' * 65)
displayChange(100)
displayChange(91)
displayChange(49)
displayChange(41)
print('\nDisplay Change in a list')
print('=' * 65)
print('Wallet with 100 cents:', fillWallet(100))
print('Wallet with 91 cents:', fillWallet(91))
print('Wallet with 49 cents:', fillWallet(49))
print('Wallet with 41 cents:', fillWallet(41))
|
"""
Course: CS101
File: team02.py
Author: Brother Comeau
Description:
This is the code for the weekly team activity.
Please work together in groups of 2 to 3.
You will not be sumbitting your code for this activity.
You are free to continue working on this activity after class if you need more time.
Sample Output:
Age 10 can't vote
Age 20 can't vote
Age 21 can vote
Age 30 can vote
Yes you are happy and knowit
You are a sad person
You are a sad person
You are a sad person
The three sorted values are:
339, 175, 11
happy
"""
import random
# ====================================================================
# Complete these functions
def canVote(age):
# TODO -> add print statements if the person can vote based on age (above 20)
pass
canVote(10)
canVote(20)
canVote(21)
canVote(30)
print()
def DisplayIfHappyAndKnowit(happy, knowit):
# TODO -> add your print statements here
pass
DisplayIfHappyAndKnowit(True, True)
DisplayIfHappyAndKnowit(True, False)
DisplayIfHappyAndKnowit(False, True)
DisplayIfHappyAndKnowit(False, False)
print()
def displayThreeSortedValues(a, b, c):
print('The three sorted values are:')
# TODO -> Add your if statements here
# hint: use this format -> print('{}, {}, {}'.format(a, b, c))
pass
displayThreeSortedValues(random.randint(1, 1000), random.randint(1, 1000), random.randint(1, 1000))
print()
# ====================================================================
# Using assert() to test functions
def add(a, b):
pass
assert(add(1, 2) == 3)
assert(add(-10, 20) == 10)
def multiply(a, b):
pass
assert(multiply(1, 2) == 2)
assert(multiply(-1, 1000) == -1000)
assert(multiply(10, 20) == 200)
def power(a, b):
pass
assert(power(2, 0) == 1)
assert(power(2, 1) == 2)
assert(power(2, 2) == 4)
assert(power(2, 3) == 8)
assert(power(2, 4) == power(2, 3) * 2)
def subtract(a, b):
return (a - b)
# TODO -> create at least 3 assert() tests for the function subtract() above.
def isFactor(number, factor):
pass
assert(isFactor(10, 2) == True)
assert(isFactor(20, 3) == False)
assert(isFactor(21, 3) == True)
# ======================================================================
# Advanced features
happy = True
# TODO -> convert the following If statement to be one line
# (There are at least are two solutions)
if (happy):
print('happy')
else:
print('sad')
|
#!/usr/bin/python
import math
""" The file contains help methods to logic functions.
These are object independent; they only need the data given as parameters
to return a result.
"""
point_proximity_radius = 5
def direction_to_point(current, target):
a = math.radians(current.latitude)
b = math.radians(target.latitude)
d = math.radians(target.longitude - current.longitude)
y = math.sin(d) * math.cos(b)
x = math.cos(a) * math.sin(b) - math.sin(a) * math.cos(b) * math.cos(d)
return (math.degrees(math.atan2(y, x)) + 360) % 360
def point_proximity(current, target):
a = math.sin(math.radians(current.latitude))
b = math.sin(math.radians(target.latitude))
c = math.cos(math.radians(current.latitude))
d = math.cos(math.radians(target.latitude))
e = a * b + c * d * math.cos((math.radians(target.longitude - current.longitude)))
f = math.acos(e)
distance = f * 6371 * 1000
return (distance <= point_proximity_radius)
|
import sys
import tkinter as View
from tkinter import messagebox as MessageBox
from tkinter import font
# Tkinter クラスのインスタンス化
MainWindow = View.Tk()
# ウィンドウのタイトル
MainWindow.title("ほげほげ")
# ウィンドウサイズの指定
MainWindow.geometry("700x400")
# ウィンドウの最小サイズの指定
MainWindow.minsize(100,100)
# ウィンドウの最大サイズの指定
MainWindow.maxsize(1000,1000)
# ウィンドウのサイズを固定するか(0 固定, 1 可変)
MainWindow.resizable(1,1)
# ラベルの作成
Label1 = View.Label(MainWindow, text="好きな文字を入力してくださいな")
# ラベル内のフォント指定
font1 = font.Font(family="Helvetica", size=20, weight="bold")
# ラベルの座標指定
#Label1.place(x=50, y=10)
Label1.pack()
# 進捗度を表示するステータスバー
Statusbar = View.Label(MainWindow, text="ステータスが表示されます", borderwidth=2, relief="groove")
# バーの表示する位置、fill で X軸いっぱいに広げて表示
Statusbar.pack(side=View.BOTTOM, fill=View.X)
# ボタンを使う
def On_Click():
# ボタンのクリックイベントハンドラ
text = Textbox1.get()
MessageBox.showinfo("ボタンクリック", text)
Statusbar.update
# ボタンの引数に command を指定してトリガを設定する
Button1 = View.Button(MainWindow, text="クリック", command=On_Click)
Button1.place(x=400, y=100)
# テキストボックス
Textbox1 = View.Entry(width=30)
Textbox1.place(x=200, y=100)
# ウィンドウ GUI を動かすための処理
MainWindow.mainloop() |
#Quiz: List Indexing
#Use list indexing to determine how many days are in a particular month based on the integer variable month, and store that value in the integer variable num_days. For example, if month is 8, num_days should be set to 31, since the eighth month, August, has 31 days.
#Remember to account for zero-based indexing!
month = 8
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
num_days = days_in_month[month - 1]
print(num_days)
# use list indexing to determine the number of days in month
|
#Nearest Square
#Write a while loop that finds the largest square number less than an integerlimit and stores it in a variable nearest_square. A square number is the product of an integer multiplied by itself, for example 36 is a square number because it equals 6*6.
#For example, if limit is 40, your code should set the nearest_square to 36.
limit = 40
# write your while loop here
# while limit == 40:
# import math
square_list = []
for num in range(40):
if (num ** (.5) == int(num ** (.5))):
square_list.append(int(num))
while max(square_list) < limit :
limit = max(square_list)
nearest_square = limit
print(nearest_square) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# author: wq
# description: ""
class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
if l <= 1:
return 0
start = 0
reach = 0
step = 0
while reach < l - 1:
farest = 0
for i in range(start, reach+1):
farest = max(farest, nums[i]+i)
start = reach+1
reach = farest
step += 1
return step
def main():
s = Solution()
print(s.jump([2, 3, 1, 1, 4]))
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
# 返回这三个数的和。
# 假定每组输入只存在恰好一个解。
# 示例 1:
# 输入:nums = [-1,2,1,-4], target = 1
# 输出:2
# 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
# 示例 2:
# 输入:nums = [0,0,0], target = 1
# 输出:0
# 提示:
# 3 <= nums.length <= 1000
# -1000 <= nums[i] <= 1000
# -104 <= target <= 104
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
res = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
left, right = i + 1, len(nums) - 1
while left < right:
sum = nums[i] + nums[left] + nums[right]
res = sum if abs(sum - target) < abs(res - target) else res
if sum == target:
return sum
elif sum < target:
left += 1
else:
right -= 1
return res
def main():
print(Solution().threeSumClosest([2, 3, 8, 9, 10], 16))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# author: wq
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if len(preorder) == 0:
return None
ans = TreeNode()
ans.val = preorder[0]
preorder_left = [x for x in preorder if x < ans.val]
preorder_right = [x for x in preorder if x > ans.val]
ans.left = self.bstFromPreorder(preorder_left)
ans.right = self.bstFromPreorder(preorder_right)
return ans
def main():
pass
if __name__ == "__main__":
main()
|
# Daniel Rono.
# Astrophysics II.
# CNO Coding.
import math
print ("Welcome to the CNO cycle!")
c = 3*(10**8) # the speed of light in vacuo, in metres per second.
L_sol = 3.839*10**26 # solar luminosity in Watts
M_sol = 1.9891*10**30 # solar mass in kg
He4 = 4.00260325413 # mass of Helium-4 in AMU
H = 1.00782503223 # mass of Hydrogen-1 in AMU
C12 = 12 # the following twelve lines are isotope masses in AMU and lifetimes in seconds.
t_C12 = 1 # this is a stable isotope
N13 = 13.005738609
t_N13 = (5.98*10**2)/math.log1p(2) # mean lifetime in seconds, calculated as the halflife divided by ln(2)
C13 = 13.00335483507
t_C13 = 1
N14 = 14.00307400443
t_N14 = 1
O15 = 15.003065618
t_O15 = (1.22*10**2)/math.log1p(2)
N15 = 15.00010889888
t_N15 = 1
def cno():
E = 0 # setting initial energy generated at zero.
X = float (input("Please enter the mass fraction of hydrogen in the sun as a number between 0 and 1 : ")) # Allows the user to enter the mass fraction of hydrogen in the sun.
dC12 = (N15/t_N15) + H - (N13/t_N13) # the following six lines calculate the rate at which various isotopes in the CNO cycle are generated.
dN13 = (C12/t_C12) + H - (C13/t_C13)
dC13 = (N13/t_N13) - (N14/t_N14)
dN14 = (C13/t_C13) + H - (O15/t_O15)
dO15 = (N14/t_N14) + H - (N15/t_N15)
dN15 = (O15/t_O15) - (C12/t_C12) - He4
E = (X*(((4*H)-He4)*(1.6605*(10**-27)))*M_sol)*(c**2) # calculates the energy generated in the CNO cycle.
print ("The total energy in Joules generated by the CNO cycle in the sun is ",E)
print ("The rate of generation of Carbon-12 in the CNO cycle is ",dC12)
print ("The rate of generation of Nitrogen-13 in the CNO cycle is ",dN13)
print ("The rate of generation of Carbon-13 in the CNO cycle is ",dC13)
print ("The rate of generation of Nitrogen-14 in the CNO cycle is ",dN14)
print ("The rate of generation of Oxygen-15 in the CNO cycle is ",dO15)
print ("The rate of generation of Nitrogen-15 in the CNO cycle is ",dN15)
cno()
#References:
# https://www-nds.iaea.org/
|
# -*- coding: utf-8 -*-
def fizzbuzz(x):
if x % 15 == 0:
return 'fizzbuzz'
if x % 3 == 0:
return 'fizz'
if x % 5 == 0:
return 'buzz'
return x |
import pygame, math
Black = (0,0,0)
White = (255,255,255)
Blue = (0,0,255)
clock = pygame.time.Clock()
size = (900,600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Double Pendulum")
origin = [int(size[0]/2),100]
r1 = 100
r2 = 100
m1 = 10
m2 = 10
g = 1
a1 = math.pi/2
a2 = math.pi/8
a1_v = 0
a2_v = 0
a1_a = 0
a2_a = 0
# creates tracer sprites to draw on the screen to follow the path
class Tracer(pygame.sprite.Sprite):
def __init__(self,x,y,Color,size=2):
super().__init__()
self.image = pygame.Surface([size,size])
self.image.fill(Color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
all_tracers = pygame.sprite.Group()
CarryOn = True
while CarryOn:
x1 = (math.sin(a1)*r1) + origin[0]
y1 = (math.cos(a1)*r1) + origin[1]
x2 = x1 + (math.sin(a2)*r2)
y2 = y1 + (math.cos(a2)*r2)
tracer = Tracer(x2,y2,Black)
tracer2 = Tracer(x1,y1,Blue)
all_tracers.add(tracer,tracer2)
a1_v += a1_a
a2_v += a2_a
a1 += a1_v
a2 += a2_v
num1 = ((-1*g)*((2*m1)+m2)*math.sin(a1))
num2 = (m2*g*math.sin(a1-(2*a2)))
num3 = (((2*math.sin(a1-a2))*m2)*((((a2_v)**2)*r2) + (((a1_v)**2)*r1*math.cos(a1-a2))))
den1 = (r1*((2*m1) + m2 - (m2*math.cos((2*a1) - (2*a2)))))
a1_a = (num1 - num2 -num3) / (den1)
num1 = (2*math.sin(a1-a2))
num2 = (a1_v*a1_v*r1*(m1+m2))
num3 = (g*(m1+m2)*math.cos(a1))
num4 = (a2_v*a2_v*r2*m2*math.cos(a1-a2))
den1 = (r2*(2*m1 + m2 - (m2*math.cos(2*a1 - 2*a2))))
a2_a = (num1 * (num2 + num3 + num4)) / (den1)
# # dampening
# a1_v *= .999
# a2_v *= .999
for event in pygame.event.get():
if event.type == pygame.QUIT:
CarryOn = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
CarryOn = False
screen.fill(White)
pygame.draw.circle(screen, Black, [origin[0], origin[1]], 10) # circle @ origin
pygame.draw.line(screen, Black, [origin[0], origin[1]], [int(x1), int(y1)], 2) # line from origin to first mass
pygame.draw.circle(screen, Black, [int(x1),int(y1)],m1) # first mass
pygame.draw.line(screen, Black, [int(x1),int(y1)], [int(x2), int(y2)], 2)
pygame.draw.circle(screen,Black,[int(x2),int(y2)],m2) # second mass
all_tracers.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
|
def grader(name, score) :
if score < 60 :
grade = 'F'
elif score >= 60 and score <= 64 :
grade = 'D'
elif score >= 65 and score <= 69 :
grade = 'D+'
elif score >= 70 and score <= 74 :
grade = 'C'
elif score >= 75 and score <= 79 :
grade = 'C+'
elif score >= 80 and score <= 84 :
grade = 'B'
elif score >= 85 and score <= 89 :
grade = 'B+'
elif score >= 90 and score <= 94 :
grade = 'A'
else :
grade = 'A+'
print("학생 이름 : {} \n점수 : {} \n학점 : {}".format(name, score, grade))
student_name = input()
student_grade = int(input())
grader(student_name, student_grade)
|
###
#Jhamni Young-Shinnick
#10.25.17
#RisingSun.py
#Interactive Animation w/rising Sun
###
import time
import Tkinter as tk #names TKinter to be used as tk
from Tkinter import *
root = tk.Tk() #Creates root window
canvas = tk.Canvas(root, width=1000, height=1000, borderwidth=0, highlightthickness=0, bg="white")
canvas.grid() #Fills background white and creates a larger Canvas
#format (x0, y0, x1, y1), all are poits for the circle's box
#canvas.create_oval(100,200,0,300, width=2, fill='red')
class Ball: # Class is object
def __init__(self,color,size,x,y):
self.color = color
self.size = size
self.x = x
self.y = y
self.xVel = 0
self.yVel = 0
self.xAccel = 0
self.yAccel = 0
global canvas
self.sprite = canvas.create_oval(self.x,self.y,self.x + self.size,self.y + self.size, width=2, fill=self.color)
def move(self):# moves ball
self.xVel = self.xVel + self.xAccel
self.yVel = self.yVel + self.yAccel
canvas.move(self.sprite,self.xVel,self.yVel)
self.x = self.x + self.xVel
self.y = self.y + self.yVel
if(self.y > 801): # if above 800 sets to 800 then flips velocity and lowers
self.setPos(self.x,800)
self.setVel(self.xVel,self.yVel * -0.9)
if(self.x > 1001): # if above 1000 set to 100 and flip velocity and lower
self.setPos(1000,self.y)
self.setVel(self.xVel * -0.9,self.yVel)
if(self.x < -1):
self.setPos(0,self.y)
self.setVel(self.xVel * -0.9,self.yVel)
def setAccel(self, x ,y):
self.xAccel = x
self.yAccel = y
def setVel(self, x ,y):
self.xVel = x
self.yVel = y
def setColor(self,color):
global canvas
canvas.itemconfig(self.sprite, fill=color)
def setPos(self,x,y):
canvas.move(self.sprite,x - self.x,y - self.y)
self.x = x
self.y = y
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple','pink','black']
balls = []
for point in range(0,50):
balls.append(Ball(colors[point%8],50,(point*15),800 - (point * 15)))#gives color
balls[point].setVel(4,-30)
balls[point].setAccel(0,1)
balls[point].setColor(colors[point%8])
def tick():#event loop
global ball
for ball in balls:
ball.move()
time.sleep(0.015)
canvas.after(1,tick)
tick()
root.mainloop()# Event loop |
import os
import random
import sys
class Piece:
def __init__(self, x, y, c):
self.x, self.y, self.color = x, y, c
def flip(self):
if self.color == 'b':
self.color = 'w'
else:
self.color = 'b'
class Board:
def __init__(self):
self.pieces = [Piece(4, 4, 'b'), Piece(5, 5, 'b'), Piece(4, 5, 'w'), Piece(5, 4, 'w')]
def white_num(self):
count = 0
for i in self.pieces:
if i.color == 'w':
count += 1
return count
def black_num(self):
count = 0
for i in self.pieces:
if i.color == 'b':
count += 1
return count
def display(self):
print(" Board")
print(" +---+---+---+---+---+---+---+---+")
for y in range(8, 0, -1):
print(" " + str(y) + " | ", end = '')
for x in range(1, 9, 1):
if self.get_piece(x, y):
if self.get_piece(x, y).color == 'b':
print('b', end = '')
elif self.get_piece(x, y).color == 'w':
print('w', end = '')
else:
print (' ', end = '')
print(" | ", end = '')
print("\n +---+---+---+---+---+---+---+---+")
print(" 1 2 3 4 5 6 7 8 ")
def get_piece(self, x, y):
for i in self.pieces:
if i.x == x and i.y == y:
return i
return False
def get_color(self, x, y):
for i in self.pieces:
if i.x == x and i.y == y:
return i.color
return False
def in_range(self, x, y):
return x >= 1 and x <= 8 and y >= 1 and y <= 8
def check_move(self, x, y, color): # returns list of legal flips
if self.get_piece(x, y) or not self.in_range(x, y):
return []
tiles_to_flip = []
if color == 'w':
opp_color = 'b'
else:
opp_color = 'w'
for xdir, ydir in [[0, -1], [0, 1], [-1, 0], [1, 0], [-1, 1], [1, 1], [1, -1], [-1, -1]]:
xcurr, ycurr, count = x, y, 0
xcurr += xdir
ycurr += ydir
while self.in_range(xcurr, ycurr) and self.get_color(xcurr, ycurr) == opp_color:
xcurr += xdir
ycurr += ydir
count += 1
if (self.get_color(xcurr, ycurr) == color and count > 0):
xcurr -= xdir
ycurr -= ydir
while xcurr != x or ycurr != y:
tiles_to_flip.append([xcurr, ycurr])
xcurr -= xdir
ycurr -= ydir
return tiles_to_flip
def make_move(self, flips, x, y, color): # flips coordinates in flip list
for i in flips:
self.get_piece(i[0], i[1]).flip()
self.pieces.append(Piece(x, y, color))
def check_legal(self, color): # check_move for all coords of a color
for x in range(1, 9, 1):
for y in range(1, 9, 1):
if self.check_move(x, y, color) != []:
return True
return False
def execute(self):
os.system('cls')
choice = int(input("Choose mode:\n(1)Free Play\n(2)Beginner AI\n(3)Intermediate AI\n"))
x, y, numFlips, turn = 0, 0, 0, 1
col = ["w","b"]
while b.check_legal("w") or b.check_legal("b"):
flips = []
if turn % 2 == 1 or choice == 1:
first = True
while flips == []:
os.system('cls')
self.display()
if choice == 1 and col[turn % 2] == 'w':
print("White's turn\n")
elif choice == 1 and col[turn % 2] == 'b':
print("Black's turn\n")
else:
print("Your turn (black)\n")
if first and turn != 1 and choice != 1:
print("Computer placed a piece at (" + str(x) + ", " + str(y) + ") and flipped " + str(numFlips) + " pieces")
if flips == [] and first == False:
print("Illegal move\n")
x = int(input("X: "))
y = int(input("Y: "))
flips = b.check_move(x, y, col[turn % 2])
print(b.check_legal(col[turn % 2]))
first = False
b.make_move(flips, x, y, col[turn % 2])
elif choice == 2:
x, y, numFlips = b.beginner_AI(turn)
elif choice == 3:
x, y, numFlips = b.intermediate_AI(turn)
if b.check_legal(col[(turn + 1) % 2]):
turn += 1
os.system('cls')
b.display()
print("Game over")
print("Black pieces: " + str(b.black_num()))
print("White pieces: " + str(b.white_num()))
if b.black_num() > b.white_num():
print("Black wins")
elif b.white_num() > b.black_num():
print("White wins")
else:
print("Tie")
def beginner_AI(self, turn):
col = ['w', 'b']
while True:
x = random.randint(1, 8)
y = random.randint(1, 8)
flips = b.check_move(x, y, col[turn % 2])
if flips != []:
break
b.make_move(flips, x, y, col[turn % 2])
return [x, y, len(flips)]
def intermediate_AI(self, turn): # + randint(0, 6) % 8 + 1
col = ['w', 'b']
flips = []
range = [1, 2, 3, 4, 5, 6, 7, 8]
random.shuffle(range)
for x in range:
for y in range:
if len(b.check_move(x, y, col[turn % 2])) > len(flips):
flips = b.check_move(x, y, col[turn % 2])
bestx = x
besty = y
b.make_move(flips, bestx, besty, col[turn % 2])
return [bestx, besty, len(flips)]
b = Board()
b.execute()
|
from PIL import Image
import glob
import os
def rotate(image_path, degrees_to_rotate, saved_location):
"""
Rotate the given photo the amount of given degrees, show it and save it
@param image_path: The path to the image to edit
@param degrees_to_rotate: The number of degrees to rotate the image
@param saved_location: Path to save the cropped image
"""
image_obj = Image.open(image_path)
rotated_image = image_obj.rotate(degrees_to_rotate)
name_directory = saved_location + "test" + ".png"
rotated_image.save(name_directory)
def directory_flip(directory, out):
list_of_images = [os.path.basename(x) for x in glob.glob('{}*.png'.format(directory))]
for filename in list_of_images:
im=Image.open(directory + filename)
im_rotate=im.rotate(180)
im_rotate.save(out + 'rotated_' + filename)
if __name__ == '__main__':
#image = '/Users/jonc101/Desktop/input/brain.png'
#rotate(image, 180, '/Users/jonc101/Desktop/')
#rotate(image, 180, '/Users/jonc101/Desktop/out')
directory_flip('/Users/jonc101/Desktop/input/', '/Users/jonc101/Desktop/out/')
|
# 思考 : 計算每個人的時候 都要重新輸入 身高體重
# 應該以物件(人)為單位
# 好好記得每個人自己的身高體重
def bmi(h, w):
return w / (h / 100) ** 2
print(bmi(175,75))
# Step1 設計圖 __init__ 使用
# 1.1 屬性 1.2 專屬功能
class Person():
# 有了 init 不必再宣告成員變數
# init 初始化的建構
def __init__(self, n, h, w):
self.name = n
self.height = h
self.weight = w
def cbmi(self):
return self.weight / (self.height / 100) ** 2
# Step2 設計圖 -> 資料
# 2.1 填值 2.2 使用
p1 = Person("Elwing",175,75)
print(p1.name, p1.cbmi())
p2 = Person("Fiamma",171,60)
print(p2.name, p2.cbmi())
|
# Import necessary packages and libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Load the passenger data
passengers = pd.read_csv('passengers.csv')
print(passengers)
# Update sex column to numerical
print(passengers['Sex'])
passengers['Sex'] = passengers['Sex'].apply(lambda x: 1 if x == 'female' else 0)
print(passengers['Sex'])
# Fill the nan values in the age column
mean_age = passengers['Age'].mean()
passengers['Age'].fillna(value=mean_age,inplace=True)
print(passengers['Age'].values)
# Create a first class column
passengers['FirstClass'] = passengers['Pclass'].apply(lambda x: 1 if x == 1 else 0)
# Create a second class column
passengers['SecondClass'] = passengers['Pclass'].apply(lambda x: 1 if x == 2 else 0)
# Select the desired features
features = passengers[['Sex', 'Age', 'FirstClass', 'SecondClass']]
survival = passengers['Survived']
# Perform train, test, split
X_train,X_test,y_train,y_test = train_test_split(features,survival)
# Scale the feature data so it has mean = 0 and standard deviation = 1
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Create and train the model
lregr = LogisticRegression()
lregr.fit(X_train,y_train)
# Score the model on the train data
print(lregr.score(X_train,y_train))
# Score the model on the test data
print(lregr.score(X_test,y_test))
# Analyze the coefficients
print(lregr.coef_)
# Sample passenger features
Jack = np.array([0.0,20.0,0.0,0.0])
Rose = np.array([1.0,17.0,1.0,0.0])
You = np.array([0.0,23.0,1.0,0.0])
# Combine passenger arrays
sample_passengers = np.array([Jack,Rose,You])
# Scale the sample passenger features
sample_passengers = scaler.transform(sample_passengers)
print(sample_passengers)
# Make survival predictions!
print(lregr.predict(sample_passengers))
print(lregr.predict_proba(sample_passengers))
|
'''http://rosalind.info/problems/lexv/
In this practice I also tried some implementation of class methods
'''
from itertools import permutations
class lexv():
"""Somehow like building a comination with replacement.
alphabet - a list of element with ordering
n - an int of the maximum output length"""
def __init__(self, alphabet, n):
'''Initialize the input and run the iterations'''
self.alphabet = alphabet
self.alphabet.insert(0, '')
self.n = n
self.out = []
self.iter = 0
for i in range(n):
self.iterate()
def iterate(self):
'''Run an iteration to extend the list in place'''
if self.out == []:
self.out = self.alphabet.copy()
else:
self.tmp = []
for e in self.out:
if e:
if len(e) < self.iter:
self.tmp.append(e)
continue
for i in self.alphabet:
self.tmp.append(e + i)
self.out = self.tmp.copy()
self.iter += 1
def __len__(self):
'''Returns the number of generated strings'''
return len(self.out)
def __getitem__(self, start, stop = None, step = None):
'''Allow using slicing syntax to get items from output'''
if stop == None:
return self.out[start]
else:
end = stop
if step == None:
stride = 1
else:
stride = step
return self.out[start:end:stride]
def __iter__(self):
'''Generates an iterator that go through each string generated in
lexicographical order'''
self._pointer = -1
return self
def __next__(self):
self._pointer += 1
if self._pointer == len(self):
raise StopIteration
return self.out[self._pointer]
def __repr__(self):
'''Returns some text about the summary'''
content = 'lexv build from alphabet ' + str(self.alphabet[1:]) + ', with maximum length ' + str(self.n) + '\n'
if len(self) > 10:
for i in range(5):
content += self.out[i] + '\n'
content += '.' * max(self.n, 3) + '\n'
for i in range(5):
content += self.out[-5 + i] + '\n'
else:
for i in range(len(self)):
content += self.out[i] + '\n'
content += 'Totally %d elements' % len(self)
return content
if __name__ == '__main__':
In = 'D N'.split(' ')
n = 3
l = lexv(In, n)
print('__repr__ test')
print(l)
print('Iterator test')
print('for i in l:\n print(i)')
for i in l:
print(i)
print('__getitem__ test', 'l[::-1] =>', l[::-1])
|
# -*- coding: utf-8 -*-
"""nlp100 in python3"""
__author__ = "Yu Sawai (tuxedocat@github.com)"
__copyright__ = "Copyright 2015, tuxedocat"
__credits__ = ["Naoaki Okazaki", "Inui-Okazaki Lab. at Tohoku University"]
__license__ = "MIT"
import random
def typoglycemia(s):
"""
create typoglycemia for given sequence
args
----
s: string, assuming words are space-separated
returns
-------
shuffled string, space-separated
"""
_t = []
for w in s.split():
if len(w) > 4:
_t.append(_shuffle(w))
else:
_t.append(w)
return " ".join(_t)
def _shuffle(w):
"""
shuffle characters in a word except head and tail
"""
_w = [c for c in w]
head = _w.pop(0)
tail = _w.pop(-1)
random.shuffle(_w)
mid = "".join(_w)
return head + mid + tail
if __name__ == '__main__':
s = ("I couldn't believe that I could actually understand what "
"I was reading : the phenomenal power of the human mind .")
print(typoglycemia(s))
|
import string
num2alpha = dict(zip(range(1, 27), string.ascii_lowercase))
name =[]
s=""
while True:
alph=int(input("enter number: "))
if (alph <=26 and alph >=1):
name.append(num2alpha[alph])
print (name)
else:
print ("Name is %s" %(s.join(name)))
break
|
#!/usr/bin/env python3
def is_leap_year(year):
if year % 4 != 0:
# If not divisible by 4, not a leap year:
return False
elif year % 100 != 0:
# If divisible by 4 but not 100, a leap year
return True
elif year % 400 != 0:
# If divisible by 100 but not 400, not a leap year
return False
else:
# If divisible by 400, a leap year
return True
if __name__ == "__main__":
year = input("Enter a year: ")
if is_leap_year(int(year)):
print("{} is a leap year.".format(year))
else:
print("{} is not a leap year.".format(year))
|
# https://leetcode.com/explore/featured/card/september-leetcoding-challenge/554/week-1-september-1st-september-7th/3445/
from itertools import permutations
class Solution:
def isValid(self, candi):
hh, mm = candi[:2], candi[3:]
return 0 <= int(hh) <= 23 and 0 <= int(mm) <= 59
def largestTimeFromDigits(self, A: List[int]) -> str:
candidates = [f'{c[0]}{c[1]}:{c[2]}{c[3]}'
for c in permutations(A, 4)]
candidates = [c for c in candidates if self.isValid(c)]
if not candidates:
return ''
else:
candidates.sort()
return candidates[-1] |
from gates import NOR, NAND, NOT, AND, XOR, OR
# function to take input
def take_input():
return input('Enter two decimal numbers: (Enter with empty string to exit) :').split()
# validate if there are 2 and only 2 elements entered
def validate_count(nums):
if len(nums) == 2:
return True
else:
print('Error in input format. Enter again.')
return False
# validate if the entered numbers are actually integers
def validate_int(nums):
try:
int(nums[0]) and int(nums[1])
return True
except:
print('Invalid Data Type.')
return False
# validate if the numbers entered are within range of (0 to 255)
def validate_size(nums):
if 0 <= int(nums[0]) <= 255 and 0 <= int(nums[1]) <= 255:
return True
else:
print('The integer is out of bounds (0-255)')
return False
def is_valid(nums):
# return true if all validation rules are satisfied
return validate_count(nums) and validate_int(nums) and validate_size(nums)
# function that adds two bits, along with carry
def add_bits(a, b, cin):
# simulating the bit-adder
m = XOR(a, b)
x = NAND(m, cin)
y = OR(m, cin)
s = AND(x, y)
n = AND(a, b)
p = AND(m, cin)
r = NOR(n, p)
cout = NOT(r)
return (s, cout)
# function that returns binary representation of a number
def get_bin_string(num):
# get binary value of num as string
s = "{0:b}".format(num)
# since we need exactly 8 bits in both numbers
# create new list and apppend 0s in front if there are less than 8 bits
binstr = ['0']*(8 - len(s))
# after that append every bits in s to binstr
for ch in s:
binstr.append(ch)
# at this point, binstr will be exactly have 8 bits
# return a string joining the bits in the list binstr
return ''.join(binstr)
# function that adds two bytes
def add_bytes(a, b):
checker =1
# get binary representation of the numbers in 8 bits
num1 = get_bin_string(a)
num2 = get_bin_string(b)
# initializing carry-in as 0 initially
cin = 0
# list that will store the bits after
res = []
# for every bits in the binary representation (equivalently, every column in addition)
for i in range(1, 8+1):
# take out individual bits from bit-string, as integers, starting from the last (hence, -i)
bit1 = int(num1[-i])
bit2 = int(num2[-i])
# add the bits, get sum and carry-out
s, cout = add_bits(bit1, bit2, cin)
# carry-in for next column will be carry-out for this column
cin = cout
# insert the sum bit at the very beginning
res.insert(0, str(s))
# create a bit-string by joining the bits in the list
res = ''.join(res)
# return the integer value when the bit-string is parsed as binary-string.
return int(res, 2)
# if this file is run as main program
if __name__ == "__main__":
# take the numbers input
nums = take_input()
# while there is something entered,
while nums:
# check if what user entered is valid
if is_valid(nums):
# convert the input numbers from string into integers
num1 = int(nums[0])
num2 = int(nums[1])
# calculate the result of byte addition
result = (add_bytes(num1, num2))
result = (bin(result).replace("0b",""))
# initializing empty list
fill = []
c = 0
n = 8-len(result)
for i in range(0,n):
fill.append("0")
for i in range(n,8):
fill.append(result[c])
c +=1
print("The result is ", fill)
# checking condition to continue next instance
condition = input("Do u want take next instance?(y/n) :")
if condition == "n":
print("Closed")
checker ==0
else:
nums = take_input()
|
#! /usr/bin/env python3
import argparse
import math
from collections import defaultdict
class Day6:
""" Day 6: Universal Orbit Map """
def __init__(self, input_file):
self.process(input_file)
def process(self, input_file):
orbits = defaultdict(list)
# Read data input.
with open(input_file, "r") as input:
for orbit in input:
parent, child = orbit.rstrip().split(")")
orbits[parent].append(child)
print(f"Nb link: {sum(len(v) for v in orbits)}")
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('input', help="File containing day 6 input data")
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
Day6(args.input)
|
#! /usr/bin/env python3
import argparse
import math
class Day10:
""" Day 10: Monitoring Station """
def __init__(self, input_file):
self.x_max = 0
self.y_max = 0
self.grid = []
self.asteroids = set()
self.process(input_file)
def process(self, input_file):
# Read input data, and convert to boolean matrix.
with open(input_file, "r") as input:
for line in input:
self.x_max = max(len(line) - 1, self.x_max)
self.y_max += 1
self.grid.append([True if a == '#' else False
for a in line.rstrip()])
# Find all asteroids.
for y in range(0, self.y_max):
for x in range(0, self.x_max):
if self.grid[y][x]:
self.asteroids.add((x, y))
# Get number of detected asteroids from each posible stations.
stations_data = []
for station in self.asteroids:
detected = set()
# Parse all asteroids (expect station position).
for asteroid in self.asteroids:
if station != asteroid:
dx = asteroid[0] - station[0]
dy = asteroid[1] - station[1]
g = abs(math.gcd(dx, dy))
detected.add((dx // g, dy // g))
stations_data.append((len(detected), station, detected))
stations_data.sort(reverse=True)
max_detected, station, detected = stations_data[0]
print(f"Best location ({station[0]},{station[1]}): {max_detected}")
# Find 200th destroyed asteroid.
destroyed = [((math.atan2(dy, dx) + math.pi) % (math.pi * 2), (dx, dy))
for dx, dy in detected]
destroyed.sort(reverse=True)
dx, dy = destroyed[199][1]
x = station[0] + dx
y = station[1] + dy
while (x, y) not in self.asteroids:
x += dx
y += dy
print(f"200th position: {x * 100 + y}")
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('input', help="File containing day 10 input data")
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
Day10(args.input)
|
#! /usr/bin/env python3
import argparse
class Day22:
""" Day 22: Slam Shuffle """
def __init__(self, input_file, deck_size):
self.deck = Deck(deck_size)
self.process(input_file)
def process(self, input_file):
with open(input_file, "r") as input:
for line in input:
if self.deck.method_cmp(line, "deal_new"):
self.deck.deal_new()
elif self.deck.method_cmp(line, "deal_inc"):
n = self.deck.method_get_int(line, "deal_inc")
self.deck.deal_increment(n)
elif self.deck.method_cmp(line, "cut"):
n = self.deck.method_get_int(line, "cut")
self.deck.cut(n)
print(f"Card 2019 @{self.deck.get_card_position(2019)}")
class Deck:
def __init__(self, size: int, debug=False):
self.deck = [i for i in range(size)]
self.methods = {
'deal_new': "deal into new stack",
'deal_inc': "deal with increment",
'cut': "cut"
}
self.debug = debug
def method_cmp(self, str, method):
return str[:len(self.methods[method])] == self.methods[method]
def method_get_int(self, str, method):
return int(str[len(self.methods[method]):])
def deal_new(self):
if self.debug:
print(f"{self.methods['deal_new']}")
self.deck.reverse()
if self.debug:
print(self.deck)
def deal_increment(self, inc: int):
if self.debug:
print(f"{self.methods['deal_inc']} {inc}")
new_deck = [0] * len(self.deck)
i = 0
run = 0
for c in self.deck:
new_deck[i] = c
i += inc
if i >= len(self.deck):
run += 1
i -= len(self.deck)
if i == inc:
i -= run
elif i == 0:
i = inc - run
self.deck = new_deck
if self.debug:
print(self.deck)
def cut(self, n: int):
if self.debug:
print(f"{self.methods['cut']} {n}")
if n < 0:
n = len(self.deck) + n
tmp = self.deck[0:n]
self.deck = self.deck[n:]
self.deck.extend(tmp)
if self.debug:
print(self.deck)
def get_card_position(self, card):
return self.deck.index(card)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('input', help="File containing day 22 input data")
parser.add_argument('-s', help="Number of cards in deck",
default=10007, type=int, dest="deck_size")
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
Day22(args.input, args.deck_size)
|
#! /usr/bin/env python3
import argparse
import math
class Day3:
""" Day 3: Crossed Wires """
def __init__(self, input_file):
self.grid_len = 40000
self.grid = [[0] * self.grid_len for i in range(self.grid_len)]
self.process(input_file)
def process(self, input_file):
list = []
# Read all input data.
with open(input_file, "r") as input:
for line in input:
list.append(line.split(","))
# Parse wires list and fill grid, check distance at same time.
distance = self.grid_len
wire_id = 0
for wire in list:
row = int(self.grid_len / 2)
col = int(self.grid_len / 2)
wire_id += 1
for data in wire:
direction = data[0]
size = int(data[1:])
for i in range(0, size):
if direction == "R":
col += 1
elif direction == "L":
col -= 1
elif direction == "U":
row -= 1
elif direction == "D":
row += 1
# Check if no wire on grid.
if self.grid[row][col] == 0:
self.grid[row][col] = wire_id
# If another wire (cross), get distance.
elif self.grid[row][col] != wire_id:
dist = math.fabs(int(self.grid_len / 2) - row) \
+ math.fabs(int(self.grid_len / 2) - col)
if dist < distance:
distance = dist
print(f"Distance: {int(distance)}")
return
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('input', help="File containing day 3 input data")
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
Day3(args.input)
|
# -*- coding: utf-8 -*-
""" Contain everything if you want to play with the data
- create color vector for signal and background
- plot one feature VS another feature
- split the data set in one set with only signal and one with only background
- PLot some histograms --> REMOVE OK?????????
"""
import numpy as np
import matplotlib.pyplot as plt
def create_color_vector(labels_train):
"""
To create a vector with colors in order to plot features and see what samples is signal and background
argument: labels_train, it is the labels for the training set
return: a list of b and r, in order to have the same color for all the samples in background or in signal
"""
colors = []
for t in range(labels_train.shape[0]):
if labels_train[t] == 1:
colors.append('b')
else:
colors.append('r')
return colors
def plotFeatVsFeat(f1,f2, features_train, labels_train):
"""
To plot one feature VS another feature
argument:
- the indices of features you want to plot against, f1, f2
- features_train = data
- labels_train = labels of the data
return: nothing, but plot
"""
plt.figure()
colors = create_color_vector(labels_train)
plt.scatter(features_train[:,f1], features_train[:,f2],color = colors)
plt.show()
def split_data(labels, features_data):
"""
To split the data in background and signal
argument:
- labels: labels of the data
- features_data: the data
return:
- signal: data that correspond to the signal
- background: data that correspond to the signal
"""
# Separate the samples that are labeled as "sample" and as "background"
signal_good_ind = []
background_good_ind = []
for index_i, i in enumerate(labels):
if i == 1:
signal_good_ind.append(index_i)
else:
background_good_ind.append(index_i)
signal = features_data[signal_good_ind,:]
background = features_data[background_good_ind,:]
return signal,background
def histo_features(data, labels): # ERROR whit this one --> OK to remove??????????????????
"""
Just to learn some stuff about the data, plot some histogramms
argument:
- data: the data
- labels: labels of the data
return:
- nothing, just plots
"""
# INitiate some variables, list needed
mean_feat_signal = []
mean_feat_back = []
std_feat_signal = []
std_feat_back = []
diff_mean =[]
signal_data, background_data = split_data(labels, data) # get the signal and the background (the 2 classes)
for i in range(data.shape[1]):
# Get the mean for each features for signal and background
mean_feat_signal.append(np.mean(signal_data[:,i]))
mean_feat_back.append(np.mean(background_data[:,i]))
# Get the std for each features for signal and background
std_feat_signal.append(np.std(signal_data[:,i]))
std_feat_back.append(np.std(background_data[:,i]))
# Calculate the difference between the mean of the signal and background for the same feature (each feature)
for index_mean, m in enumerate(mean_feat_signal):
diff_mean.append(abs(m - mean_feat_back[index_mean] ))
# In order to choose only the features that have a difference between signal and background bigger than the average
mean_thediff = np.mean(diff_mean)
ind_featInterest = np.where(diff_mean >= mean_thediff)
features_interst = data[:,np.where(diff_mean >= mean_thediff)[0]]
# Try to make histograms for those features in order to see how well (or not) we can separate the two classes
for ind in ind_featInterest[0]:
print(ind)
plt.figure()
plt.hist(signal_data[:,ind],50)
plt.hist(background_data[:,ind],50)
plt.show()
|
class Relationship(object):
""" defines how two people are related """
def __init__(self, this, that, distance):
super(Relationship, self).__init__()
self.this = this
self.that = that
self.distance = distance
def couple(self):
""" the two considered """
return set(self.this, self.that)
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
@classmethod
def get(cls):
return cls()
class Network(Singleton):
""" """
def neighbors(self, endorser ):
""" get neighbors of endorsers """
raise NotImplementedError("abstract")
def bfs_iterator(self, endorser):
""" return an iterator of Relationship's, since distance is a needed metric not usually stored in bfs operations, but easy to do"""
raise NotImplementedError("abstract") |
string = 'My name is Niteesh Panchal'
alphabets_frequency = dict()
string1 = list(string.upper().replace(" ",""))
string2 = list()
for i in string1:
alphabets_frequency[i] = string1.count(i)
if i not in string2:
string2.append(i)
else:
continue
minimum = sorted(alphabets_frequency.values())
minimum_values = [0]
for i in range(len(minimum)):
if len(minimum) == len(minimum):
x = minimum[0] + minimum[1]
minimum_values.append(x)
minimum.pop(i)
minimum.pop(i+1)
else:
y = minimum[i]
z = minimum_values[0] + x
minimum_values[0] = z
minimum.pop(i)
print('i',i)
print('x',x)
# print(string1)
# print(string2)
# print(alphabets_frequency)
print(minimum)
print(minimum_values)
|
inf = float('inf')
start = 'A'
stop = 'D'
graph = {}
graph['A'] = {}
graph['A']['B'] = 2
graph['A']['F'] = 3
graph['B'] = {}
graph['B']['C'] = 7
graph['C'] = {}
graph['C']['D'] = 1
graph['F'] = {}
graph['F']['E'] = 3
graph['E'] = {}
graph['E']['D'] = 5
graph['D'] = {}
costs = {}
parents = {}
for node in graph:
costs[node] = inf
parents[node] = {}
costs[start] = 0
def find_cheapest_node(costs, not_checked):
cheapest_node = None
lowest_cost = inf
for node in not_checked:
if costs[node] <= lowest_cost:
lowest_cost = costs[node]
cheapest_node = node
return cheapest_node
if __name__ == '__main__':
not_checked = [node for node in costs]
node = find_cheapest_node(costs, not_checked)
while not_checked:
print(f"Not checked: {not_checked}")
cost = costs[node]
child_cost = graph[node]
for c in child_cost:
if costs[c] > cost + child_cost[c]:
costs[c] = cost + child_cost[c]
parents[c] = node
not_checked.pop(not_checked.index(node))
node = find_cheapest_node(costs, not_checked)
print(f"Costs: {costs}")
print(f"The cost to go from {start} to {stop} is {costs[stop]}!")
if costs[stop] < inf:
path = [stop]
i = 0
while start not in path:
path.append(parents[path[i]])
i += 1
print(f"The shortest path is: {path[::-1]}")
else:
print(f"A path could not be found") |
"""
The goal is to classify 2 sets of data according to the distribution
of X1 and X2 in the 2D space, e.g. data points on the left part
of the y-axis will be classified as class 1, and on the right part
as class 2. The points are normally distributed according to the distance h
to the origin.
"""
import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
%matplotlib notebook
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# generating example classification data
h = 1
sd = 1
n = 50
def gen_data(n, h, sd1, sd2):
x1 = ss.norm.rvs(-h, sd1, n)
y1 = ss.norm.rvs(0, sd1, n)
x2 = ss.norm.rvs(h, sd2, n) # right part
y2 = ss.norm.rvs(0, sd2, n)
return x1, y1, x2, y2
(x1, y1, x2, y2) = gen_data(1000, 1.5, 1, 1.5)
def plot_data(x1, y1, x2, y2):
plt.figure()
plt.plot(x1, y2, "o", ms=2)
plt.plot(x2, y2, "o", ms=2)
plt.xlabel("$X_1$")
plt.ylabel("$X_2$")
plt.show()
plot_data(x1, y1, x2, y2)
#logistic regression
#log(p_x / (1-p_x) = beta_0 + beta_1.X1)
def prob_to_odd(p):
"""Converts probability to odds"""
if p<=0 or p>=1:
print("Probabilities must be between 0 and 1.")
return p/(1-p)
#what is the odds that a given data point belongs to class_2 with
#p(class_1)=0.2
print(prob_to_odd(1 - .2))
#logistic regression in code
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression() # classifier
# y is a vector with outcome either 1 or 2
# X is a matrix with n obs with values=covariates (prodictors)
# stack x1 with x2, same for x2 and y2, and stack 1st block on top of 2nd
np.vstack((x1, y1)).shape
np.vstack((x1, y1)).T.shape # ths is the good shape, 2 cols
np.hstack((x1, y1)).shape # concatenate by the right, 1 row...
np.hstack((x1.reshape(-1, 1), y1.reshape(-1, 1))).shape
np.vstack((x1, y1)).T is np.vstack((x1, y1)).reshape(-1, 2)
np.vstack((x1, y1)).T is np.hstack((x1.reshape(-1, 1), y1.reshape(-1, 1)))
X = np.vstack(
(np.hstack(
(x1.reshape(-1, 1), y1.reshape(-1, 1))
), np.hstack((x2.reshape(-1, 1), y2.reshape(-1, 1))))
)
X.shape
n = 1000
y = np.hstack((np.repeat(1, n), np.repeat(2, n))) # building the y vector
y.shape
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=.5,
random_state=1)
y_train.shape
clf.fit(X_train, y_train)
clf.score(X_test, y_test) # gives .894
clf.predict_proba(np.array([-2, 0]).reshape(1, -1))
# array([[0.96701634, 0.03298366]]) proba for the 2 classes
clf.predict(np.array([-2, 0]).reshape(1, -1))
# array([1]) class_1
clf.predict(np.array([4, -2]).reshape(1, -1))
# array([2]) class_2, see how the y vector was build
clf.predict_proba(np.array([.5, -.5]).reshape(1, -1))
#computing predictive probabilities accross the grid
# prediction for each point of the meshgrid
# matrix to vector using.ravel(), and transpose after stacking
def plot_probs(ax, clf, class_no):
xx1, xx2 = np.meshgrid(np.arange(-5, 5, 0.1), np.arange(-5, 5, 0.1))
probs = clf.predict_proba(np.stack((xx1.ravel(), xx2.ravel()), axis=1))
Z = probs[:,class_no]
Z = Z.reshape(xx1.shape)
CS = ax.contourf(xx1, xx2, Z)
cbar = plt.colorbar(CS)
plt.xlabel("$X_1$")
plt.ylabel("$X_2$")
plt.figure(figsize=(5,8))
ax = plt.subplot(211)
plot_probs(ax, clf, 0)
plt.title("Pred. prob for class 1")
ax = plt.subplot(212)
plot_probs(ax, clf, 1)
plt.title("Pred. prob for class 2")
plt.savefig('grid.pdf');
# with up to 2 predictors, the linear classification might work good enough
|
import random
number = random.randint(1, 10)
tries = 1
username = input("Hi there! would you like to share your username ?")
print("Hello ", username + ".")
question = input("would you like to play a guessing game with me ? [y/n]")
if question == "n":
print("Never mind we will play it another time.. ")
if question == "y":
print("I am thinking of a number between 1 & 10")
guess = int(input(" would you like to guess? "))
if guess > number:
print("guess lower a bit !!")
if guess < number:
print("guess a bit higher !!")
while guess != number:
tries += 1
guess = int(input(" incorrect ..try again !"))
if guess == number:
print("Well done..the number was ", number, " and you have made it with ", tries, "tries") |
import heapq
import inspect
import sys
"""
Data structures useful for implementing Best-First Search
"""
class FrontierPriorityQueueWithFunction(object):
'''
FrontierPriorityQueueWithFunction class implement a search frontier using a
PriorityQueue for ordering the nodes and a set for
constant-time checks of states in frontier.
OBSERVATION: it receives as input a function `f` that
itself receives a node and returns the priority for
the given node. Check util.PriorityQueueWithFunction for
more details.
'''
def __init__(self, f):
self._queue = PriorityQueueWithFunction(f)
self._set = set()
def __contains__(self, node):
''' Return true if `node.state` is in the frontier. '''
return node.state in self._set
def __len__(self):
''' Return the number of nodes in frontier. '''
assert(len(self._queue) == len(self._set))
return len(self._queue)
def is_empty(self):
''' Return true if frontier is empty. '''
return self._queue.isEmpty()
def push(self, node):
''' Push `node` to frontier. '''
self._queue.push(node)
self._set.add(node.state)
def pop(self):
''' Pop `node` from frontier. '''
node = self._queue.pop()
self._set.discard(node.state) # antes era remove
return node
def __str__(self):
''' Return string representation of frontier. '''
return str(self._queue)
class PriorityQueue:
"""
Implements a priority queue data structure. Each inserted item
has a priority associated with it and the client is usually interested
in quick retrieval of the lowest-priority item in the queue. This
data structure allows O(1) access to the lowest-priority item.
"""
def __init__(self):
self.heap = []
self.count = 0
def __contains__(self, item):
for (_, _, i) in self.heap:
if i == item:
return True
return False
def __len__(self):
return len(self.heap)
def push(self, item, priority):
entry = (priority, self.count, item)
heapq.heappush(self.heap, entry)
self.count += 1
def pop(self):
(_, _, item) = heapq.heappop(self.heap)
return item
def isEmpty(self):
return len(self.heap) == 0
def update(self, item, priority):
# If item already in priority queue with higher priority, update its priority and rebuild the heap.
# If item already in priority queue with equal or lower priority, do nothing.
# If item not in priority queue, do the same thing as self.push.
for index, (p, c, i) in enumerate(self.heap):
if i == item:
#print("priority in heap: {}, requested priority: {}".format(p, priority))
if p <= priority:
break
del self.heap[index]
self.heap.append((priority, c, item))
heapq.heapify(self.heap)
break
else:
self.push(item, priority)
def __str__(self):
return str([(p, str(item)) for (p, _, item) in self.heap])
class PriorityQueueWithFunction(PriorityQueue):
"""
Implements a priority queue with the same push/pop signature of the
Queue and the Stack classes. This is designed for drop-in replacement for
those two classes. The caller has to provide a priority function, which
extracts each item's priority.
"""
def __init__(self, priorityFunction):
"priorityFunction (item) -> priority"
self.priorityFunction = priorityFunction # store the priority function
PriorityQueue.__init__(self) # super-class initializer
def push(self, item):
"Adds an item to the queue with priority from the priority function"
PriorityQueue.push(self, item, self.priorityFunction(item))
class Queue:
# ref: https://www.pythoncentral.io/use-queue-beginners-guide/
def __init__(self):
self.queue = list()
def push(self,data):
#Checking to avoid duplicate entry (not mandatory)
if data not in self.queue:
self.queue.insert(0,data)
return True
return False
def pop(self):
if len(self.queue)>0:
return self.queue.pop()
return ("Queue Empty!")
def isEmpty(self):
return len(self.queue) == 0
def size(self):
return len(self.queue)
def raiseNotDefined():
fileName = inspect.stack()[1][1]
line = inspect.stack()[1][2]
method = inspect.stack()[1][3]
print("*** Method not implemented: `%s` at line %s of %s" % (method, line, fileName))
sys.exit(1) |
from state import State
class ProgressionPlanning(object):
'''
ProgressionPlanning class implements all necessary components
for implicitly generating the state space in a forward way (i.e., by progression).self
'''
def __init__(self, domain, problem):
self._problem = problem
self._all_actions = problem.ground_all_actions(domain)
@property
def problem(self):
return self._problem
@property
def actions(self):
return self._all_actions
def applicable(self, state):
''' Return a list of applicable actions in a given `state`. '''
app = list()
for act in self.actions:
if State(state).intersect(act.precond) == act.precond:
app.append(act)
return app
def successor(self, state, action):
''' Return the sucessor state generated by executing `action` in `state`. '''
return State(action.pos_effect).union(State(state).difference(action.neg_effect)) |
#!/usr/bin/python
class tree():
def __init__(self, size, trunk, branch):
self.size = size
self.trunk = trunk
self.branch = branch
def drawtree(self):
for i in range(int(self.size/2) + 1):
print(' ' + (int(self.size/2) - i)*' ' + str((2*i + 1)*self.branch))
print(' ' + (int(self.size/2) - 1)*' ' + str(3*self.trunk))
smalltree = tree(3,'#','+')
smalltree.drawtree()
bigtree = tree(21,'%','&')
bigtree.drawtree() |
import re
"""stop_words are words are the most common words of a language and are often removed to improve statistics. """
stop_words = {w.strip() for w in open('data/stops.txt', 'r').readlines()}
# Sentiment analysis data from <https://github.com/jeffreybreen/twitter-sentiment-analysis-tutorial-201107>
"""pos_words contain positive English words """
pos_words = {w.strip() for w in open('data/vendor/pos.txt', 'r').readlines() if not w.startswith(';')}
"""neg_words contain negative English words """
neg_words = {w.strip() for w in open('data/vendor/neg.txt', 'r').readlines() if not w.startswith(';')}
"""participants is a tuple of debate participants """
participants = ('CLINTON', 'TRUMP', 'KAINE', 'PENCE')
"""exparticipants is a tuple of debate participants including moderators """
exparticipants = ('CLINTON', 'TRUMP', 'KAINE', 'PENCE', 'HOLT', 'RADDATZ', 'COOPER', 'QUIJANO', 'WALLACE')
"""moderators is a tuple of debate moderators """
moderators = ('HOLT', 'RADDATZ', 'COOPER', 'QUIJANO', 'WALLACE')
# Regular expressions for processing raw debate files
r_line = {who: re.compile(r"%s:((?:.|\s)*?)(?=\s[A-Z]+:)" % who) for who in participants}
r_tokenize = re.compile(r"[A-Z]{2,}(?![a-z])|[A-Z][a-z]+(?=[A-Z])|[\w\-]+")
r_normalize = re.compile(r"\[(?:Applause|Laughter|Crosstalk|Inaudible)\]")
r_interjections = (
{a: {p: re.compile(r"%s:.*?\.\.\.\s+(?:\[Crosstalk\])?\s+%s:" % (p, a)) for p in exparticipants} for a in exparticipants},
{a: {p: re.compile(r"%s:.*?--?\s+%s:" % (p, a)) for p in exparticipants} for a in exparticipants}
)
r_speaker = re.compile("(%s): " % "|".join(exparticipants))
r_applause = re.compile(r"\[Applause\]")
r_laughter = re.compile(r"\[Laughter\]")
def count_reactions(s, speaker, r_expr):
"""count_reactions counts the number of audience reactions to a participant for some regular expression """
pos = 0
last = r_speaker.search(s)
m = last
count = 0
while m:
s = s[m.start()+1:]
m = r_speaker.search(s)
r = r_expr.search(s)
if r and last.group(1) == speaker and (not m or r.start() < m.start()):
count += 1
last = m
return count
def count_interjections(s, agent, patient):
"""count_interjections counts the number of interjections for a given agent and patient participant """
count = 0
for r_int in r_interjections:
count += len(r_int[agent][patient].findall(s))
return count
def lines(s, who):
"""lines takes a raw debate `s` and a participant `who` and finds all utterances made by `who`. """
return r_line[who].findall(s)
def tokenize(s, stop=False, normalize=False):
"""tokenize splits up the raw string `s` into tokens
tokenize also may apply optional stopping and normalization.
"""
f = (lambda w: w.lower() not in stop_words) if stop else lambda w: True
g = (lambda w: w.isalnum()) if normalize else lambda w: True
if normalize:
s = r_normalize.sub('', s).lower()
return [w for w in r_tokenize.findall(s) if f(w) and g(w)]
def freqdist(tokens):
"""freqdist generates a frequency distribution over tokens """
fd = {}
for w in tokens:
fd[w] = 1 + fd.get(w, 0)
return fd
def freqdistlines(lines):
"""freqdist generates a frequency distribution over tokens in lines format """
fd = {}
for tokens in lines:
for w in tokens:
fd[w] = 1 + fd.get(w, 0)
return fd
def sortedfd(fd):
"""sortedfd returns a sorted copy of a frequency dictionary (as item tuples). """
return sorted(fd.items(), key=lambda i: i[1], reverse=True)
def ngrams(tokens, n, begin='#BEGIN#', end='#END#'):
"""ngrams generates `n`-grams from a token list
You may optionally set the begin and end symbols.
"""
if n <= 0:
raise ValueError('n must be positive: %d' % n)
tokens = [begin] + tokens + [end]
for i in range(len(tokens) - n + 1):
yield tuple(tokens[i:i+n])
|
import json
import argparse
from utils import ACCESS_FILE
def get_access_list():
with open(ACCESS_FILE, 'r') as file:
data = json.load(file)
return data
def save_access_list(data):
with open(ACCESS_FILE, 'w') as file:
json.dump(data, file)
print("Access list saved with success")
def main(args):
data = get_access_list()
if args.add_user:
new_user = input("User name: ")
if new_user in data:
print("This user already is in access list")
return
give_access = input(f"Give access to transfering files to {new_user}? (y/N) ")
data[new_user] = {"send": give_access == 'y'}
save_access_list(data)
elif args.remove_user:
user_remove = input("User name: ")
if user_remove not in data:
print("This user doesn't exist in access list")
return
del data[user_remove]
save_access_list(data)
elif args.change_access:
user = input("User name: ")
if user not in data:
print("This user doesn't exist in access list")
return
choice = input(
f"Choose one of those options:\n" \
"1) Remove transfer access\n" \
"2) Add transfer access\n" \
"> "
)
if not choice.isdigit() or int(choice) not in [1, 2]:
print("Invalid option")
return
choice = int(choice)
data[user]["send"] = choice == 2
save_access_list(data)
elif args.see_list:
for user in data:
print(f"{user} -> access = {data[user]['send']}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Manage users access.")
parser.add_argument("-a", "--add_user", help="Add new user to the access list", action="store_true")
parser.add_argument("-r", "--remove_user", help="Remove user from access list", action="store_true")
parser.add_argument("-c", "--change_access", help="Change user access", action="store_true")
parser.add_argument("-s", "--see_list", help="See access list", action="store_true")
args = parser.parse_args()
main(args)
|
# Function: Date String Formatter
def date_str_formatter(input_date_str, current_format, target_format):
"""
Input:
input_date_str: Input Date in string format e.g "01-Jan-2000"
current_format: Corresponding date format i.e "%d-%b-%Y"
target_format: Target date format e.g: "%d-%m-%Y"
Output:
01-01-2000
"""
import sys
from datetime import datetime
new_date_str = input_date_str
try:
input_date = datetime.strptime(input_date_str, current_format).date()
new_date_str = input_date.strftime(target_format)
except Exception as E:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(f"date_str_formatter Error: {E} at {exc_tb.tb_lineno}, Exception Type: {exc_type}")
return new_date_str
print(date_str_formatter("2020-01-12", "%Y-%m-%d", "%d-%m-%Y"))
|
def key_of_max_value(dt=dict()):
values = list(dt.values()) #[]
print(values)
if not values:
return 'Не передано значень'
M_value = max(values)#5
for k, v in dt.items():
if v == M_value:
return k,v
def myfunc(a=0,b=0):
return a if a>=b else b |
def main():
num = int(input())
for i in range(1, 10):
print(num, "*", i, "=", num * i)
if __name__ == '__main__':
main()
|
"""
封装get、post方法,判断接口是否能请求
"""
import requests
from Pubilc.DoExcel import ReadExcel
from Config import globalconfig
import os
import json
# from Pubilc.DoExcel import WriteExcel
class DoRequest():
def __init__(self, excel_name, sheet_name):
self.excel_name=excel_name
self.sheet_name=sheet_name
self.ini_ip = globalconfig.project_ip # 从配置文件读取项目的IP
self.ini_host = globalconfig.project_host # 从配置文件读取项目的host
self.rows = ReadExcel( self.excel_name, self.sheet_name).get_rows() # 读取测试用例EXCEL的总行数
# 根据读取的EXCEL的方法,判断执行get还是post方法,返回状态码和response
def doRequest(self):
i = 1
result_list =[]
while i < self.rows:
excel_url = ReadExcel(self.excel_name, self.sheet_name).read_excel(i, 1) # 读取测试用例EXCEL的路径
excel_method = ReadExcel(self.excel_name, self.sheet_name).read_excel(i, 2) # 读取测试用例EXCEL的方法
excel_parm = json.loads(
ReadExcel(self.excel_name, self.sheet_name).read_excel(i, 3)) # 读取测试用例EXCEL的传参
url = 'http://' + self.ini_ip + ':' + self.ini_host + excel_url # 拼接测试接口的URL
if excel_method == 'get':
result=DoRequest(self.excel_name, self.sheet_name).getMethod(url, excel_parm)
result_list.append(result)
elif excel_method == 'post':
pass
i = i + 1
return result_list
# print(result_list)
def getMethod(self, url, excel_parm):
try:
r = requests.get(url, params=excel_parm, timeout=30)
r.raise_for_status() # 如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding
# print(r.status_code)
return r.status_code,r.text # 返回状态码和返回值
except Exception as e :
return e
# print('错误类型是', e.__class__.__name__)
# print('错误明细是', e)
# 调试DoRequest类,可注释
if __name__ == '__main__':
demo = DoRequest('bike1.xlsx', 'Sheet1').doRequest()
print(demo)
# print(demo.getMethod())
# WriteExcel(Excelname,Sheetname).write_excel(1,5,demo.get_method())
|
import unittest
from src.quicksort import quicksort
class TestQuicksort(unittest.TestCase):
def test_quicksort_with_ints(self):
self.assertEqual(quicksort([3, 1, 4, 2, -1]), [-1, 1, 2, 3, 4])
def test_quicksort_with_strs(self):
self.assertEqual(quicksort(["a", "j", "e", "z"]), ["a", "e", "j", "z"])
def test_quicksort_with_non_comparable(self):
with self.assertRaises(TypeError):
quicksort([(1, 2), ("a", 3)])
|
import random
class Egg:
def __init__(self, critical_floor):
self.critical_floor = critical_floor
def drop(self, floor):
if (floor >= self.critical_floor):
return True
else:
return False
class FloorAlgorithm:
def __init__(self, floors, critical_floor):
self.egg = Egg(critical_floor)
self.floors = floors
self.rec_comparisons = 0
self.iter_comparisons = 0
def run_iterative(self):
for i in range(0, self.floors):
self.iter_comparisons = self.iter_comparisons + 1
if (self.egg.drop(i)):
return i
def run_rec(self):
return self.run_recursive(self.egg, self.floors / 2, self.floors)
def run_recursive(self, egg, current_floor, total_floors):
self.rec_comparisons = self.rec_comparisons + 1
if (current_floor == 0 or (egg.drop(current_floor) and not egg.drop(current_floor-1))):
return int(current_floor) # assuming at least one floor will break the egg
elif (egg.drop(current_floor)):
return self.run_recursive(egg, current_floor - int(current_floor / 2), current_floor)
else:
return self.run_recursive(egg, current_floor + int((total_floors - current_floor) / 2), total_floors)
def print_history(self):
actual_critical_floor = self.egg.critical_floor
rec_critical_floor = self.run_rec()
iter_critical_floor = self.run_iterative()
print("Results of Egg Comparison:\n")
print(f"Actual Critical Floor: {actual_critical_floor}")
print("---\nIterative Egg:")
print(f"Critical Floor Returned: {iter_critical_floor}")
print(f"Number of Comparisons: {self.iter_comparisons}")
print("---\nRecursive Egg:")
print(f"Critical Floor Returned: {rec_critical_floor}")
print(f"Number of Comparisons: {self.rec_comparisons}")
floors = int(input("Please enter the number of floors in the building: \n"))
floor_algo = FloorAlgorithm(floors, random.randrange(floors))
floor_algo.print_history()
|
"""
LeetCode
#1.TwoSum
Description:Given an array(List) and a target,return indices of two numbers that add up to a specific target
Solution:
Method:
add 160524
"""
"""
"""
class Solution:
def __init__(self):
self.resLessThanHalf=[]
self.resMoreThanHalf=[]
self.finalRes=[]
def twoSum(self,lists,target):
"""
:param arr:List[int]
:param target:int
:return:List[int]
"""
if(lists.count(target/2)>1):
targetHalf=target/2
for (i,x) in enumerate(lists):
if(x == targetHalf):
self.finalRes.append(i)
else:
for (i,x) in enumerate(lists):
if(x < target/2):
self.resLessThanHalf.append(x)
else:
self.resMoreThanHalf.append(x)
for x in self.resLessThanHalf:
y = target-x
if( self.resMoreThanHalf.count(y)):
self.finalRes.append(lists.index(x))
self.finalRes.append(lists.index(y))
if(len(self.finalRes)>1):
return self.finalRes
else:
return "No matching numbers"
|
#Given a number n, provide the fibonnaci sereis value upto n
#use cache(dictionary) to strore the memoization values
#when the value for a particular n is in cache, return cache[n]
#if n is not in cache, carry return the recursive method
class fibonnaci:
def fib(self,n):
cache={}
if n in cache:
return cache[n]
else:
if n<2:
return n
answer=self.fib(n-1)+self.fib(n-2)
cache[n]=answer
return cache[n]
fibo=fibonnaci()
while(1):
n=int(input("enter n:"))
result=fibo.fib(n)
print(str(result))
|
from collections import defaultdict
class MyList(list):
def __len__(self):
# Each time this method is called with a non-existing key, the
# key-value pair is generated with a default value of 0
d = defaultdict(int)
# This value comes from calling "int" without arguments. (Try
# typing int() on Python's console)
# Here we call the original method from the super-class list
for i in range(list.__len__(self)):
d.update({self[i]: d[self[i]] + 1})
# Here we call d's (a defaultdict) len method
return len(d)
L = MyList([1, 2, 3, 4, 5, 6, 6, 7, 7, 7, 7, 2, 2, 3, 3, 1, 1])
print(len(L))
|
# multiple_inheritance.py
class Researcher:
def __init__(self, field):
self.field = field
def __str__(self):
return "Research field: " + self.field + "\n"
class Teacher:
def __init__(self, courses_list):
self.courses_list = courses_list
def __str__(self):
out = "Courses: "
for c in self.courses_list:
out += c + ", "
# the [:-2] selects all the elements
# but the last two
return out[:-2] + "\n"
class Professor(Teacher, Researcher):
def __init__(self, name, field, courses_list):
# This is not completetly right
# Soon we will see why
Researcher.__init__(self, field)
Teacher.__init__(self, courses_list)
self.name = name
def __str__(self):
out = Researcher.__str__(self)
out += Teacher.__str__(self)
out += "Name: " + self.name + "\n"
return out
p = Professor("Steve Iams",
"Meachine Learning",
[
"Python Programming",
"Probabilistic Graphical Models",
"Bayesian Inference"
])
print(p)
|
class Deck:
def __init__(self):
self.cards = []
for p in ['Spades', 'Diamonds', 'Hearts', 'Clubs']:
for n in range(1, 14):
self.cartas.append(Card(n, p))
def __iter__(self):
return iter(self.cards)
for c in Deck():
print(c)
|
# code13.py
import collections
import threading
class MyDeque(collections.deque):
# We inherit from a normal collections module Deque and
# we add the locking mechanisms to ensure thread
# synchronization
def __init__(self):
super().__init__()
# A lock is created for this queue
self.lock = threading.Lock()
def append(self, element):
# The lock is used within a context manager
with self.lock:
super().append(element)
print('[ADD] queue now has {} elements'.format(len(self)))
def popleft(self):
with self.lock:
print('[REMOVE] queue now has {} elements'.format(len(self)))
return super().popleft()
|
def dec_count(n):
print("Counting down from {}".format(n))
while n > 0:
yield n
n -= 1 |
# We create the list with seven numbers
numbers = [6, 7, 2, 4, 10, 20, 25]
print(numbers)
# Ascendence. Note that variable a do not receive
# any value from assignation.
a = numbers.sort()
print(numbers, a)
# Descendent
numbers.sort(reverse=True)
print(numbers)
|
# 8.py
# KeyError exception: incorrect use of key in dictionaries.
# In this example the program ask for an item associated with a key that
# doesn't appears in the dictionary
book = {'author': 'Bob Doe', 'pages': 'a lot'}
print(book['editorial'])
|
import time
import hashlib
import pickle
cache = {}
def is_obsolete(entry, duration):
return time.time() - entry['time'] > duration
def compute_key(function, args, kw):
key = pickle.dumps((function.__name__, args, kw))
# returns the pickle representation of an object as a byte object
# instead of writing it on a file
# creates a key from the "frozen" key generated in the last step
return hashlib.sha1(key).hexdigest()
def memoize(duration=10):
def _memoize(function):
def __memoize(*args, **kw):
key = compute_key(function, args, kw)
# do we have the value on cache?
if key in cache and not is_obsolete(cache[key], duration):
print('we already have the value')
return cache[key]['value']
# if we didn't
print('calculating...')
result = function(*args, **kw)
# storing the result
cache[key] = {'value': result, 'time': time.time()}
return result
return __memoize
return _memoize
|
# 17.py
class Operations:
@staticmethod
def divide(num, den):
if not (isinstance(num, int) and isinstance(den, int)):
raise TypeError('Invalid input type')
if num < 0 or den < 0:
raise Exception('Negative input values')
return float(num) / float(den)
# Open a text file in write mode
fid = open('log.txt', 'w')
try:
# Check if we canwrite a line with the output of each operation.
# This will yield an error beacuse 0 denominator
[fid.write('{}'.format(
Operations().divide(10, i))) for i in range(5, -1, -1)]
except (ZeroDivisionError, TypeError):
# This block handle errors Este bloque opera para los tipos de excepciones
# definidos
print('Error!: Check the input parameters!')
else:
print('No errors!')
finally:
# This block assure that the file be closed correctely, even with a runtime
# error
print('Remember ALWAYS to close your files\n')
fid.close()
|
# 9.py
class Operations:
@staticmethod
def divide(num, den):
if den == 0:
# Here we generate the exception and we include
# information about its meaning.
raise ZeroDivisionError('Denominator is 0')
return float(num) / float(den)
print(Operations().divide(3, 4))
print(Operations().divide(3, 0))
|
import numpy as np
def maximum(values):
temp_max = -np.infty
for v in values:
if v > temp_max:
temp_max = v
yield temp_max
elements = [10, 14, 7, 9, 12, 19, 33]
res = maximum(elements)
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res)) # we've run out of list elements!
|
# operator_overriding_3.py
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other_point):
self_mag = (self.x ** 2) + (self.y ** 2)
other_point_mag = (other_point.x ** 2) + (other_point.y ** 2)
return self_mag < other_point_mag
if __name__ == "__main__":
p1 = Point(2, 4)
p2 = Point(8, 3)
print(p1 < p2)
|
from matplotlib import pyplot as plt
import numpy as np
pow2 = lambda x: x ** 2
# Creates a 100 element numpy array, ranging evenly from -1 to 1
t = np.linspace(-1., 1., 100)
plt.plot(t, list(map(pow2, t)), 'xb')
plt.show()
|
class MyMetaClass(type):
def __init__(cls, name, bases, dic):
print("__init__ of {}".format(str(cls)))
super().__init__(name, bases, dic)
class MyClass(metaclass=MyMetaClass):
def __init__(self, a, b):
print("MyClass object with a=%s, b=%s" % (a, b))
print('creating a new object...')
obj1 = MyClass(1, 2)
|
"""
Tests for the 'abstract_iterator'.
"""
import abstract_iterator as it
import unittest
class TheTests(unittest.TestCase):
def test_1(self):
first = [1,2,3,4]
second = [5,6,7]
third = [8,9,10,11,12]
ideal = [1,2,3,4,5,6,7,8,9,10,11,12]
result_1 = list(it.abstract_iterator([first,second,third]))
result_2 = list(it.abstract_iterator([third,first,second]))
self.assertEqual(result_1,ideal)
self.assertEqual(result_2,ideal)
result_3 = []
with self.assertRaises(TypeError):
# not iterable as an input (outer "list")
for element in it.abstract_iterator(4):
result_3.append(element)
result_4 = []
with self.assertRaises(TypeError):
# not iterable as an input (inner "lists")
for element in it.abstract_iterator([1,2,3,4]):
result_4.append(element)
def test_2(self):
first = [2,6,9,15,100]
second = [3,10,12,16]
third = [0,1,2,15,99]
ideal = [0,1,2,2,3,6,9,10,12,15,15,16,99,100]
result_1 = list(it.abstract_iterator([first,second,third]))
result_2 = list(it.abstract_iterator([third,first,second]))
self.assertEqual(result_1,ideal)
self.assertEqual(result_2,ideal)
def test_3(self):
first = [0,0]
second = [0,0,0]
third = [0,0,0,0]
ideal = [0,0,0,0,0,0,0,0,0]
result_1 = list(it.abstract_iterator([first,second,third]))
result_2 = list(it.abstract_iterator([third,first,second]))
self.assertEqual(result_1,ideal)
self.assertEqual(result_2,ideal)
def test_4(self):
first = [1]
second = [2]
third = [3]
ideal = [1,2,3]
result_1 = list(it.abstract_iterator([first,second,third]))
result_2 = list(it.abstract_iterator([third,first,second]))
self.assertEqual(result_1,ideal)
self.assertEqual(result_2,ideal)
if __name__ == '__main__':
unittest.main()
|
"""
Given a word, we find its stems, template, and template's flections.
This is an intermediate modeule, it is not used anywhere later.
Some ideas from here are used in the "creating_databases" module.
"""
import mwclient as mw
site = mw.Site('ru.wiktionary.org')
def template(word):
"""
Returns a template name, given a word as a string.
"""
page = site.Pages[word]
for obj in page.templates():
if "Шаблон:сущ ru" in obj.name:
return(obj.name)
def stems(word):
"""
Returns a tuple with two stems. The second one may be an empty string.
"""
page = site.Pages[word]
substring = page.text()[:200] # the stems are in the beginning of the article
try: # if there are no spaces like here: основа=дру́г\n|основа1=друз\n|слоги=
first = substring[substring.find("основа=")+7:substring.find("основа1")-2]
second = substring[substring.find("основа1")+8:substring.find("слоги")-2]
except ValueError: # if there are spaces: основа = беготн\n| основа1 = \n|слоги=
first = substring[substring.find("основа =")+8:substring.find("основа1")-3].strip()
second = substring[substring.find("основа1 =")+9:substring.find("слоги")-3].strip()
return((first, second))
def flections(template):
"""
Returns a dict with two keys: "основа" and "основа1".
Their values are also dicts, like {nom-sg: "", gen-sg: "а", ...}.
The dict for "основа1" may be empty.
"""
# here may be some irregularities, for instance:
# two forms for a case, like 'ins-sg' and 'ins-sg2' (ей/ею) - then we include both of them.
# there is 'loc-sg' but neither stem nor flection is written - such cases are not included.
# variation (?) like acc-pl={{{основа1|{{{основа}}}и}}} - then we take the option with "основа",
# because on the template page there is that option (ref. "Шаблон:сущ ru f ina 6a", for example)
page = site.Pages[template]
text = template.text().split("\n")
return_dict = {"основа":{}, "основа1":{}}
for chunk in text:
if "{основа}" in chunk:
case = chunk[1:chunk.find("=")]
flection = chunk[chunk.find("{основа}")+10:].strip()
return_dict["основа"][case]=flection
if "{основа1}" in chunk:
case = chunk[1:chunk.find("=")]
flection = chunk[chunk.find("{основа1}")+11:].strip()
return_dict["основа1"][case]=flection
return(return_dict)
|
"""Create a weak reference with a list.
"""
import weakref
class MyList(list):
"""My list is just inherits from `list`.
Need this because built-in list does not work with weak refs.
"""
pass
def test():
"""Simple test.
"""
my_list = MyList([1, 2, 3])
print('List:', my_list)
print('Weak reference count:', weakref.getweakrefcount(my_list))
weak_list = weakref.ref(my_list)
print('Creating a weak reference.')
print('Weak reference count:', weakref.getweakrefcount(my_list))
print('Calling the weakref object', weak_list())
print('Deleting the original list.')
del my_list
print('Weak reference count:', weak_list())
if __name__ == '__main__':
test()
|
class AppleBasket:
def __init__(self, color: str, amount: int):
self.color_apple = color
self.quantity_apple = amount
def increase(self):
self.quantity_apple += 1
def __str__(self):
return f"A basket of {self.quantity_apple} {self.color_apple} apples."
def main():
example1 = AppleBasket("red", 4)
example2 = AppleBasket("blue", 50)
print(example1)
print(example2)
if __name__ == "__main__":
main()
|
"""
Universidad de El Salvador
Authors:
- Avelar Melgar, José Pablo – AM16015
- Campos Martínez, Abraham Isaac – CM17045
- Lizama Escobar, Oscar Omar – LE17004
- Paredes Pastrán, Carlos Enrique – PP17012
- Quinteros Lemus, Diego Enrique – QL17001
Activity: Application project
Subject: Técnicas de Simulación (TDS115)
Professor: Lic. Guillermo Mejía
Date: 06/11/2021
"""
from simulation import Simulation
def validNumberInput(message, min=None, max=None):
while True:
error = False
try:
value = int(input(message))
# Validating min
if min is not None:
if value < min: error = True
if max is not None:
if value > max: error = True
except ValueError:
error = True
if error:
errorMsg = "Error: you must enter integer values "
if min is not None and max is not None:
errorMsg += f"greater than or equals to {min} and lower than or equals to {max}."
else:
errorMsg += f"greater than or equals to {min}." if min is not None else ""
errorMsg += f"lower than or equals to {max}." if max is not None else ""
print(errorMsg + "\n")
else:
break
return value
def main():
print("**************************************************************\n")
print("The next program makes a simulation of the Customer Service")
print("process of a branch belonging to Banco Agrícola.\n")
steps = validNumberInput("Enter the number of steps to simulate: ", min=1)
simulation = Simulation()
simulation.executeSimulation(steps)
print("\n**************************************************************")
if __name__ == "__main__":
main() |
#creat multiplication table using forloop
number=int(input('ENTER THE VALUE OF TABLE:'))
for count in range(1,11):
result=number*count
print(number ,"*",count,"=",result)
#thanks akhlakansari94@gmail.com |
from utils import today
def myprogram():
name = input("¿cómo te llamas? ")
hoy = today()
print("Hola ", name, ", hoy es ", hoy)
#myprogram() |
from collections import deque
class State:
def __init__(self, symbol=None):
self.children = dict()
self.root = False
if symbol is None:
symbol = "ROOT"
self.root = True
self.symbol = symbol
self.output = list()
self.fail = None
self.results = dict()
self.__counter = 0
self.counts = dict()
def __repr__(self):
return self.symbol
def __str__(self, level=0):
ret = " "*level+repr(self.symbol)+"\n"
for child in self.children.values():
ret += child.__str__(level+1)
return ret
def reset(self):
"""
This function delets results, counts and the counter.
Only the patterns are kept - used to search the same
patterns in another text. Particulary useful if working
with many patterns.
"""
self.results = dict()
self.__counter = 0
self.counts = dict()
def traverse(self, states=None):
"""
a recursive function to traverse the
automaton and return a list of states
Parameters:
- None (self)
Returns:
- list of states in the automaton
"""
if states is None:
states = list()
states.append(self.symbol)
for child in self.children.values():
child.traverse(states)
return states
def find_next_state(self, char):
"""
find the next state in the automaton given a char
Argument:
- char (charachter): the next charachter to be matched
Returns:
- state (object) : if the charachter is a child
of the current state
-None: otherwise
"""
if char in self.children:
return self.children[char]
return None
def add_pattern(self, pattern):
"""
add a new search pattern to the automaton
(algorithm 2 from paper)
Argument:
- pattern (string): a matching pattern to be added to
the automaton
Returns:
- void: If necessary, new states are created to match
the new pattern
"""
this_state = self
for char in pattern:
# if a new state for the char already exists, move there
if this_state.find_next_state(char) is not None:
this_state = this_state.find_next_state(char)
# create a new state and add it to current state as a child
else:
new_state = State(char)
this_state.children[char] = new_state
this_state = new_state
# accepting state! add pattern to state's output
this_state.output.append(pattern)
def fail_connections(self):
"""
calculate for each state the failure connection
(algorithm 3 from paper)
Arguments:
- None (self)
Returns:
- void: creates fail connections between the states
of the automaton to enable pattern matching
"""
root = self
self.fail = root
queue = deque()
for node in self.children.values():
queue.append(node)
node.fail = root
while queue:
r = queue.popleft()
for child in r.children.values():
queue.append(child)
state = r.fail
# if no new state (and no root because root.fail = root)
# --> follow fail links
while (state.find_next_state(child.symbol) is None
and state.root is False):
state = state.fail
# set next state as fail state
child.fail = state.find_next_state(child.symbol)
# if next state does not existe, set fail to root
if child.fail is None:
child.fail = root
# carry over the output
child.output = child.output + child.fail.output
def find_match(self, line, case_insensitive=False):
"""
given a string, run it through the automaton to find a match
(algorithm 1 from the paper)
Parameters:
-line (string): the text to be searched for matches
-case_insentitive (bool): standard = False, if true,
the matching algorithm ignores case differences
in line and search patterns
Returns:
-void (saves the index where the matches begins in
self__results[pattern], index is of type integer)
"""
if case_insensitive:
line = line.lower()
current_state = self
root = self
for i, char in enumerate(line):
# if no new state --> follow fail links
while (current_state.find_next_state(char) is None
and current_state.root is False):
current_state = current_state.fail
# go to the next state
current_state = current_state.find_next_state(char)
# if next state does not exists, go back to root
if current_state is None:
current_state = root
else:
# if we are in a terminal state
# (aka state has output) save result
for pattern in current_state.output:
if pattern not in self.results:
self.results[pattern] = list()
if pattern not in self.counts:
self.counts[pattern] = 0
# add counter to i (for multiline input)
it = i + self.__counter
self.results[pattern].append(it - len(pattern) + 1)
self.counts[pattern] += 1
self.__counter += len(line)
@classmethod
def create_automaton(cls, string_list):
"""
A class method to create and return a complete Aho Corasick Automaton
given a list of patterns to be added as states
Parameters:
- cls (class State):
- string_list (list of strings): each string is a
pattern to be matched
Returns:
- automaton (object): a complete Aho-Corasick Automaton
to match the patterns given as argument
"""
automaton = cls()
for string in string_list:
automaton.add_pattern(string)
automaton.fail_connections()
return automaton
if __name__ == "__main__":
text = (
"The PRADA Christmas Race is a one day knock out series, "
"based on the seeding from the PRADA ACWS Auckland, NZ and "
"the last chance for teams to take on the Defender before "
"the 36th America’s Cup Presented by PRADA."
)
patterns = ["PRADA", "on", "PRACHT", "oboe"]
s = State.create_automaton(patterns)
s.find_match(text)
print(f"Text:\n{text}")
print(f"\nWe want to match these words:\t{patterns}")
print("First we build the automaton:")
print(s)
print("and now we use it to find the indeces:")
for key in s.results:
print(f"{key:<7}{s.results[key]}")
print("\nor count the absolute frequence of the patterns")
for key in s.counts:
print(f"{key:<7}{s.counts[key]}")
|
class sorting:
array = []
def __init__(self, array):
self.array = array
def sort(self, algorithm="bubble"):
array = []
if(algorithm == "bubble"):
array = self.bubble_sort()
elif(algorithm == "insertion"):
array = self.insertion_sort()
elif(algorithm == "selection"):
array = self.selection_sort()
elif(algorithm == "merge"):
array = self.merge_sort()
elif(algorithm == "quick"):
array = self.quick_sort()
return array
def bubble_sort(self):
array = self.array
for i in range(0, len(array)):
for j in range(0, len(array) - 1 - i):
if (array[j] > array[j + 1]):
array[j], array[j + 1] = array[j + 1], array[j]
return array
def insertion_sort(self):
pass
def merge_sort(self):
pass
def quick_sort(self):
pass
def selection_sort(self):
array = self.array
for i in range(0, len(array)):
min_index = i
for j in range(i + 1, len(array)):
if (array[j] < array[min_index]):
min_index = j
array[min_index], array[i] = array[i], array[min_index]
return array
array = [2, 3, 1, 7, 0, 9, 8, 10]
obj = sorting(array)
sorted_array = obj.sort("selection")
print(sorted_array)
|
# My solution
def same_frequency(num1,num2):
num1_list = list(str(num1)[0:])
num2_list = list(str(num2)[0:])
if len(num1_list) != len(num2_list):
return False
dict1 = {}
dict2 = {}
for (i,num) in enumerate(num1_list):
if num in dict1:
dict1[num] += 1
else:
dict1[num] = 1
if num2_list[i] in dict2:
dict2[num2_list[i]] += 1
else:
dict2[num2_list[i]] = 1
if dict1 == dict2:
return True
return False
print(same_frequency(551122,221515)) # True
print(same_frequency(321142,3212215)) # False
print(same_frequency(1212, 2211)) # True
# Instructor's solution
# def same_frequency(num1,num2):
# d1 = {letter:str(num1).count(letter) for letter in str(num1)}
# d2 = {letter:str(num2).count(letter) for letter in str(num2)}
#
# for key,val in d1.items():
# if not key in d2.keys():
# return False
# elif d2[key] != d1[key]:
# return False
# return True
|
import re
def parse_date(text):
pattern = re.compile(r'(?P<d>[0-3][0-9])[,/.](?P<m>[0-1][0-9])[,/.](?P<y>\d{4})')
match = pattern.fullmatch(text)
if match:
return {'d': match.group('d'), 'm': match.group('m'), 'y': match.group('y')}
return None
print(parse_date('01/22/1999'))
print(parse_date('12,04,2003'))
print(parse_date('12.11.2003'))
print(parse_date('12.11.200312'))
|
# Author: Ravi Teja Gannavarapu
#
# Difficulty: Easy
#
# https://leetcode.com/problems/distance-between-bus-stops/submissions/
# https://leetcode.com/contest/weekly-contest-153/problems/distance-between-bus-stops/
class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
start, destination = min(start, destination), max(start, destination)
return min(sum(distance[start:destination]), sum(distance[:start] + distance[destination:])) |
# Author: Ravi Teja Gannavarapu
#
# Difficulty: Easy
#
# https://leetcode.com/problems/number-of-1-bits/
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
cnt = 0
while n:
if (n & 1):
cnt += 1
n >>= 1
return cnt |
a=10
b=100
for n in range(a,b+1):
sum=o
temp=n
while(temp>0):
digit=temp%10
sum=digit**3
if(num==sum):
print(num)
|
a=int(input("enter the number"))
b=int(input("enter the number"))
c=int(input("enter the number"))
if(a>b):
print("a is big")
elif(c<b):
print("b is big")
else:
print("c is big")
|
import datetime
numbers = [1,2,3,4,5,6,7,8,9,10]
print(numbers)
print()
reverse=numbers.sort(reverse=True)
print()
print(reverse)
print(numbers[0:8])
print(len(numbers))
even=list(range(0, 10, 2))
odd=list(range(1, 10, 2))
print(even)
print(odd)
# for i in numbers:
# print("This is Number -> " , i) |
import numpy as np
def zeros_matrix(rows, cols):
m = []
while len(m) < rows:
m.append([])
while len(m[-1]) < cols:
m[-1].append(0.0)
return m
def copy_matrix(m):
rows = len(m)
cols = len(m[0])
mc = zeros_matrix(rows, cols)
for i in range(rows):
for j in range(cols):
mc[i][j] = m[i][j]
return mc
def determinant(a, total=0):
indices = list(range(len(a)))
if len(a) == 2 and len(a[0]) == 2:
val = a[0][0] * a[1][1] - a[1][0] * a[0][1]
return val
for fc in indices:
ac = copy_matrix(a)
ac = ac[1:]
height = len(ac)
for i in range(height):
ac[i] = ac[i][0:fc] + ac[i][fc+1:]
sign = (-1) ** (fc % 2)
sub_det = determinant(ac)
total += sign * a[0][fc] * sub_det
return total
def show_options():
print()
print('1. Add matrices')
print('2. Multiply matrix by a constant')
print('3. Multiply matrices')
print('4. Transpose matrix')
print('5. Calculate a determinant')
print('6. Inverse matrix')
print('0. Exit')
def add_matrices():
try:
raw1, col1 = input('Enter size of first matrix:').split()
nums1 = []
print('Enter first matrix:')
for i in range(int(raw1)):
nums1.extend(input().split())
raw2, col2 = input('Enter size of second matrix:').split()
nums2 = []
print('Enter second matrix:')
for i in range(int(raw2)):
nums2.extend(input().split())
nums1 = [int(x) if '.' not in x else float(x) for x in nums1]
nums2 = [int(x) if '.' not in x else float(x) for x in nums2]
if raw1 != raw2 or int(raw1) * int(col1) != len(nums1) or \
col1 != col2 or int(raw2) * int(col2) != len(nums2):
print('ERROR')
else:
print('The result is:')
for i in range(len(nums1)):
num_sum = nums1[i]+nums2[i]
if i+1 == len(nums1):
print(num_sum, end='')
elif (i+1) % int(col1) == 0:
print(num_sum)
else:
print(num_sum, end=' ')
except ValueError:
print('The operation cannot be performed.')
def multiply_const():
try:
raw1, col1 = input('Enter size of matrix:').split()
nums1 = []
print('Enter matrix:')
for i in range(int(raw1)):
nums1.extend(input().split())
const = int(input('Enter constant:'))
nums1 = [int(x)*const if '.' not in x else float(x)*const for x in nums1]
print('The result is:')
for i in range(len(nums1)):
if i+1 == len(nums1):
print(nums1[i], end='')
elif (i+1) % int(col1) == 0:
print(nums1[i])
else:
print(nums1[i], end=' ')
except ValueError:
print('The operation cannot be performed.')
def multiply_matrices():
try:
raw1, col1 = input('Enter size of first matrix:').split()
nums1 = []
print('Enter first matrix:')
for i in range(int(raw1)):
nums1.extend(input().split())
raw2, col2 = input('Enter size of second matrix:').split()
nums2 = []
print('Enter second matrix:')
for i in range(int(raw2)):
nums2.extend(input().split())
nums1 = [int(x) if '.' not in x else float(x) for x in nums1]
nums2 = [int(x) if '.' not in x else float(x) for x in nums2]
if col1 != raw2:
print('ERROR')
else:
print('The result is:')
for i in range(int(raw1)):
for k in range(int(col2)):
num_sum = 0
for f in range(int(raw2)):
num_sum += nums1[i*int(raw2)+f]*nums2[f*int(col2)+k]
print(num_sum, end=' ')
print()
except ValueError:
print('The operation cannot be performed.')
def transpose_matrix():
print('1. Main diagonal')
print('2. Side diagonal')
print('3. Vertical line')
print('4. Horizontal line')
choice4 = input('Your choice:')
if choice4 == '1':
try:
raw1, col1 = input('Enter matrix size:').split()
nums1 = []
print('Enter matrix:')
for i in range(int(raw1)):
nums1.extend(input().split())
print('The result is:')
for i in range(int(raw1)):
for k in range(int(col1)):
print(nums1[(k*int(raw1))+i], end=' ')
print()
except ValueError:
print('The operation cannot be performed.')
elif choice4 == '2':
try:
raw1, col1 = input('Enter matrix size:').split()
nums1 = []
print('Enter matrix:')
for i in range(int(raw1)):
nums1.extend(input().split())
print('The result is:')
for i in range(int(raw1)):
for k in range(int(col1)):
print(nums1[len(nums1)-1-i-(k*int(raw1))], end=' ')
print()
except ValueError:
print('The operation cannot be performed.')
elif choice4 == '3':
try:
raw1, col1 = input('Enter matrix size:').split()
nums1 = []
print('Enter matrix:')
for i in range(int(raw1)):
nums1.extend(input().split())
print('The result is:')
for i in range(int(raw1)):
for k in range(int(col1)):
print(nums1[(i*int(raw1))+(int(col1)-1-k)], end=' ')
print()
except ValueError:
print('The operation cannot be performed.')
elif choice4 == '4':
try:
raw1, col1 = input('Enter matrix size:').split()
nums1 = []
print('Enter matrix:')
for i in range(int(raw1)):
nums1.extend(input().split())
print('The result is:')
for i in range(int(raw1)):
for k in range(int(col1)):
print(nums1[k+((int(raw1)-1-i)*int(col1))], end=' ')
print()
except ValueError:
print('The operation cannot be performed.')
def calc_determinant():
try:
raw1, col1 = input('Enter size of matrix:').split()
n = []
print('Enter matrix:')
for i in range(int(raw1)):
n.append(input().split())
int_matrix = []
for mat in n:
mat = [int(x) if '.' not in x else float(x) for x in mat]
int_matrix.append(mat)
if raw1 != col1:
print('Error! Use square matrices only!')
else:
print('The result is:')
if len(n) == 1:
print(n[0][0])
else:
print(determinant(int_matrix))
except ValueError:
print('The operation cannot be performed.')
def inverse_matrix():
try:
raw1, col1 = input('Enter size of matrix:').split()
n = []
print('Enter matrix:')
for i in range(int(raw1)):
n.append(input().split())
int_matrix = []
for mat in n:
mat = [int(x) if '.' not in x else float(x) for x in mat]
int_matrix.append(mat)
int_matrix = np.linalg.inv(int_matrix)
if raw1 != col1:
print('Error! Use square matrices only!')
else:
print('The result is:')
for i in int_matrix:
for j in i:
print(j, end=' ')
print()
except ValueError:
print('The operation cannot be performed.')
except np.linalg.LinAlgError:
print("This matrix doesn't have an inverse.")
def main():
while True:
show_options()
choice = input('Your choice:')
if choice == '0':
break
elif choice == '1':
add_matrices()
elif choice == '2':
multiply_const()
elif choice == '3':
multiply_matrices()
elif choice == '4':
transpose_matrix()
elif choice == '5':
calc_determinant()
elif choice == '6':
inverse_matrix()
if __name__ == "__main__":
main()
|
# Karatsuba String Multiplication
# Wanted to implement this algorithm but with strings instead
import unittest
from random import randint
def add(s1, s2):
return str(int(s1) + int(s2))
def sub(s1, s2):
return str(int(s1) - int(s2))
def karatsuba(s1, s2):
if int(s1) < 10 or int(s2) < 10:
return str(int(s1) * int(s2))
m = max(len(s1), len(s2))
# Need to add padding to the front
# of the number that is smaller
s1 = (m - len(s1))*'0' + s1
s2 = (m - len(s2))*'0' + s2
high1, low1 = s1[:m//2], s1[m//2:]
high2, low2 = s2[:m//2], s2[m//2:]
z0 = karatsuba(low1, low2)
z1 = karatsuba(add(high1, low1), add(high2, low2))
z2 = karatsuba(high1, high2)
tmp1 = z2 + (2 * len(low1))*'0' # (z2*10^(2*m2))
tmp2 = sub(z1, add(z0, z2)) + len(low1)*'0' # ((z1-z2-z0)*10^(m2))
tmp3 = add(tmp1, tmp2)
ans = add(tmp3, z0)
return ans
class TestKaratsuba(unittest.TestCase):
def test_random(self):
for i in range(100):
x = str(randint(1, 10000))
y = str(randint(1, 10000))
want = str(int(x) * int(y))
self.assertEqual(karatsuba(x, y), want)
if __name__ == '__main__':
unittest.main() |
"""How to make cash with Python, fast!
The binned Poisson likelihood in astronomy is sometimes called the Cash fit
statistic, because it was described in detail in a paper by Cash 1979
(http://adsabs.harvard.edu/abs/1979ApJ...228..939C).
For observed counts ``n`` and expected counts ``mu`` it is given by:
C = 2 (mu - n log(mu))
and if there are bins with zero predicted counts one has to ignore them via:
C = 0 if mu <= 0
Below you will find a common application example: a 1-dimensional counts
histogram and a Cash statistic fit of a Gaussian model.
"""
import numpy as np
def model(x, amplitude, mean, stddev):
"""Evaluate Gaussian model."""
return amplitude * np.exp(-0.5 * (x - mean) ** 2 / stddev ** 2)
def cash(n, mu):
"""Cash statistic for observed counts `n` and expected counts `mu`."""
term = n * np.log(mu)
stat = 2 * (mu - term)
mask = n > 0
stat = np.where(mask, stat, 0)
return stat.sum()
def benchmark():
# Set parameters
number_of_bins = int(1e6)
number_of_evaluations = 100
amplitude = 10
mean = 0
stddev = 10
# Set up a test case
x = np.linspace(start=-10, stop=+10, num=number_of_bins)
dx = x[1] - x[0]
np.random.seed(0)
n = np.random.poisson(model(x, amplitude, mean, stddev))
# Evaluate likelihood ten times.
# Usually you would do it many times, using for example
# scipy.optimize.minimize to find the best-fit parameters.
for _ in range(number_of_evaluations):
y = model(x, amplitude, mean, stddev)
mu = dx * y
stat = cash(n, mu)
# Check on output for test case. This result shouldn't change as you try out
# different implementations - apart from differences caused by floating point
# rounding differences.
np.testing.assert_allclose(stat, 1.481885e08, rtol=1e-3)
if __name__ == "__main__":
benchmark()
|
import sys
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self._maxSum = -sys.maxsize
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self._dfs(root)
return self._maxSum
def _dfs(self, root):
if not root: return 0
leftMax = self._dfs(root.left)
rightMax = self._dfs(root.right)
maxHere = root.val
maxThruLeft = maxHere + leftMax
maxThruRight = maxHere + rightMax
maxThruBoth = maxThruLeft + rightMax
maxHere = max([maxHere, maxThruLeft, maxThruRight])
self._maxSum = max([self._maxSum, maxHere, maxThruBoth])
return maxHere
|
def findAnagram(A, B):
L = len(B)
if L == 0: return None
mapB = {}
for i in range(L):
b = B[i]
if b not in mapB: mapB[b] = i
anaMap = []
for i in range(L):
a = A[i]
anaMap.append(mapB[a])
return anaMap
|
class Solution:
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
ROW = len(board) - 1 if board != None else -1
COL = len(board[0]) - 1 if ROW >= 0 else -1
if ROW < 0 or COL < 0: return
for c in range(COL+1):
self._traverseBoard(board, 0, c, ROW, COL)
self._traverseBoard(board, ROW, c, ROW, COL)
for r in range(1, ROW):
self._traverseBoard(board, r, 0, ROW, COL)
self._traverseBoard(board, r, COL, ROW, COL)
for r in range(ROW+1):
for c in range(COL+1):
letter = board[r][c]
if letter == "A": board[r][c] = "O"
elif letter == "O": board[r][c] = "X"
def _traverseBoard(self, board, r, c, ROW, COL):
if r < 0 or r > ROW or c < 0 or c > COL: return
if board[r][c] == "O":
board[r][c] = "A"
self._traverseBoard(board, r-1, c, ROW, COL)
self._traverseBoard(board, r+1, c, ROW, COL)
self._traverseBoard(board, r, c-1, ROW, COL)
self._traverseBoard(board, r, c+1, ROW, COL)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
self._quickSortList(head, None)
return head
def _quickSortList(self, head, end):
if head == end: return
pivot = head
current = head.next
while current != None and current != end:
if current.val < head.val:
pivot = pivot.next
self.swapVal(pivot, current)
current = current.next
self.swapVal(head, pivot)
self._quickSortList(head, pivot)
while pivot.next != None and pivot.val == pivot.next.val:
pivot = pivot.next
self._quickSortList(pivot.next, end)
def swapVal(self, a, b):
cache = a.val
a.val = b.val
b.val = cache
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
self._walkBST(root, 0)
return root
def _walkBST(self, root, sumOfGreaters):
if not root: return sumOfGreaters
root.val += self._walkBST(root.right, sumOfGreaters)
return self._walkBST(root.left, root.val)
|
def formatLicenseKey(key, K):
str = ""
for i in range(len(key)):
c = key[i]
if c != "-": str += c
k = K
newKey = ""
l = len(str) - 1
str = str.upper()
while l >= 0:
if k == 0:
newKey = "-" + newKey
k = K
newKey = str[l] + newKey
l -= 1
k -= 1
if newKey[0] == "-": newKey = newKey[:1]
return newKey
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None: return []
maxV = root.val
ans = []
childrenNodes = []
rootNodes = [ root ]
while rootNodes:
ans.append(maxV)
maxV = None
for r in rootNodes:
if r.left:
childrenNodes.append(r.left)
if maxV < r.left.val: maxV = r.left.val
if r.right:
childrenNodes.append(r.right)
if maxV < r.right.val: maxV = r.right.val
rootNodes = childrenNodes
childrenNodes = []
return ans
def largestValuesByListComprehension(self, root):
maxes = []
row = [root]
while any(row):
maxes.append(max(node.val for node in row))
row = [kid for node in row for kid in (node.left, node.right) if kid]
return maxes
|
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0: return '0'
ans = ''
isMinus = False
if num < 0:
num *= -1
isMinus = True
while num > 0:
ans = str(num % 7) + ans
num //= 7
return '-' + ans if isMinus else ans
|
# coding: utf-8
# In[45]:
'''
Since the data have been audited, cleaned and transfered into table and database, the following questions such as :
Number of nodes
Number of unique users
Number of ways
Most contributing users
Number of users who contributed only once
Top 10 amenities in New Delhi
Can be answered using following queries below
'''
import sqlite3
import csv
connect = sqlite3.connect("C:/Users/FAST/Desktop/Data Wrangling/Project 2/new-delhi_india.osm (1)_db.sqlite")
cursor = connect.cursor()
def number_of_nodes():
result = cursor.execute('SELECT COUNT(*) FROM nodes')
return result.fetchone()[0]
print 'Number of nodes: \n' , number_of_nodes()
def number_of_unique_users():
result = cursor.execute('SELECT COUNT(DISTINCT e.uid) FROM
(SELECT uid FROM nodes UNION ALL SELECT uid FROM ways) e')
return result.fetchone()[0]
print 'Number of unique users: \n' , number_of_unique_users()
def number_of_ways():
result = cursor.execute('SELECT COUNT(*) FROM ways')
return result.fetchone()[0]
print 'Number of ways: \n' , number_of_ways()
def number_of_most_contributing_users():
result = cursor.execute('SELECT e.user, COUNT(*) as num FROM
(SELECT user FROM nodes UNION ALL SELECT user FROM ways) e
GROUP BY e.user
ORDER BY num DESC
LIMIT 10')
return result.fetchall()
print 'Number of most contrubuting users: \n' , number_of_most_contributing_users()
def number_of_users_contributing_only_once():
result = cursor.execute('SELECT COUNT(*) FROM
(SELECT e.user, COUNT(*) as num FROM
(SELECT user FROM nodes UNION ALL SELECT user FROM ways) e
GROUP BY e.user
HAVING num = 1) u')
return result.fetchone()[0]
print 'Number of users contributing only once: \n' , number_of_users_contributing_only_once()
def top_10_amenities():
result = cursor.execute('SELECT value, COUNT(*) as num FROM nodes_tags
WHERE key="amenity"
GROUP BY value
ORDER BY num DESC
LIMIT 10')
return result.fetchall()
print 'Top 10 amenities: \n', top_10_amenities()
# Additional queries
## List of postalcodes
def list_of_postcodes():
result = cursor.execute('SELECT e.value, COUNT(*) as num FROM
(SELECT value FROM nodes_tags WHERE key="postcode"
UNION ALL SELECT value FROM ways_tags WHERE key="postcode") e
GROUP BY e.value
ORDER BY num DESC
LIMIT 10')
return result.fetchall()
print 'List of Postcodes: \n', list_of_postcodes()
## Specific address
def top_5_cusines():
result = cursor.execute("SELECT nodes_tags.value, COUNT(*) as num
FROM nodes_tags
JOIN (SELECT DISTINCT(id) FROM nodes_tags WHERE value='restaurant') AS restaurants
ON nodes_tags.id = restaurants.id
WHERE nodes_tags.key = 'cuisine'
GROUP BY nodes_tags.value
ORDER BY num DESC
LIMIT 5")
return result.fetchall()
print 'Top 5 cusines: \n', top_5_cusines()
def top_5_banks():
result = cursor.execute("SELECT nodes_tags.value, COUNT(*) as num
FROM nodes_tags
JOIN (SELECT DISTINCT(id) FROM nodes_tags WHERE value='bank') AS bank
ON nodes_tags.id = bank.id
WHERE nodes_tags.key = 'name'
GROUP BY nodes_tags.value
ORDER BY num DESC
LIMIT 5")
return result.fetchall()
print 'Top 5 banks: \n', top_5_banks()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import csv
input = sys.argv[1]
#csv input
with open("problem.csv", "rb") as f:
fcsv = csv.reader(f, delimiter="\t")
flist = [i for i in fcsv]
class Pilot():
def __init__(self, list):
self.nome = list[1].split("-")
def proc_column_name(line):
sys.stdout.flush()
"""
APRENDIZADO CAUSADO POR UM SIMPLES en-dash
chcp 65001
set PYTHONIOENCODING=utf-8
"\u2013".encode("utf-8") codifica para o bystring \xe2\x80\x93
"\xe2\x80\x93".decode("utf-8") nao codifica por que da erro
e existe sérios problemas de codificação no windows usando o encode para o utf-8
usar python3 pois pelo menos o macete do chcp funciona
""" |
# https://www.hackerrank.com/challenges/merge-the-tools/problem
def merge_the_tools(string, k):
for i in range(0,len(string),k):
s=string[i]
for j in range(i+1,i+k):
if string[j] not in s:
s+=string[j]
print(s) |
class my_class():
def abc(self):
a = str(12345)
print "value of a" ,a
def xyz(self,arg1,arg2):
sum = arg1 + arg2
print "value of sum %s" %(sum)
class child_my_class(my_class):
def abc(self):
my_class.abc(self)
print "pratik"
#Notice that when we call the method1 or method2, we don't have to supply the self-keyword.
#That's automatically handled for us by the Python runtime.
#Python runtime will pass "self" value when you call an instance method on in instance, whether you provide it deliberately or not
#You just have to care about the non-self arguments
def main():
# Calling method from base class
o = my_class()
o.abc()
o.xyz(5,9)
# calling method for derived class
#Notice that the in childClass, xyz is not defined but it is derived from the parent myClass.
z = child_my_class()
z.abc()
z.xyz(8,8)
if __name__== "__main__":
main()
#The self-argument refers to the object itself.
#Hence the use of the word self. So inside this method, self will refer to the specific instance of this object that's being operated on.
#Self is the name preferred by convention by Pythons to indicate the first parameter of instance methods in Python.
#It is part of the Python syntax to access members of objects |
class pizza():
pratik = 1
def __init__(self):
print "hello"
def get_size1(self):
return "123"
class dabali(pizza):
def get_size(self,pratik):
self.pratik = pizza.pratik
print self.pratik
return 123
z = dabali()
z.get_size(5) |
import time
class Man_United:
def Result(Score,MANU,OTHER_TEAM):
Score.MANU=MANU
Score.OTHER_TEAM=OTHER_TEAM
if (MANU > OTHER_TEAM):
print("MANCHASTER UNITED")
elif(MANU < OTHER_TEAM):
print("OTHER TEAM")
else:
print("MATCH DRAW")
print("Pppppeeeeeeeeee......Lets Play")
time.sleep(5)
a=input("please enter the final score of Manu : ")
b=input ("please enter the final score of Other team : ")
print ("And the winer is .....")
time.sleep(3)
match=Man_United()
match.Result(a,b)
c=match.MANU
d=match.OTHER_TEAM
time.sleep(2)
print("So final score is MANU {} and Other team {}".format(c,d))
print("Good Bye....")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.