text
stringlengths 37
1.41M
|
---|
def string_before(str1, str2, case_sensitive = True):
s1=str1
s2=str2
if case_sensitive == True:
s1 = str1
s2 = str2
else:
s1=str1.lower()
s2=str2.lower()
if s2 in s1:
i=s1.find(s2)
S=str1[:i]
else:
S = ''
return S
def string_after(str1,str2, case_sensitive = True):
s1=str1
s2=str2
if case_sensitive == True:
s1 = str1
s2 = str2
else:
s1=str1.lower()
s2=str2.lower()
if s2 in s1:
i=s1.find(s2)
S=str1[i+len(s2):]
else:
S = ''
return S
# str1 = "aaabbbaaaaaaaBbbaaaaa"
# str2 = "Bbb"
#
# print string_before(str1,str2,False)
# print string_after(str1,str2,False) |
i = 1
while i <= 10:
print(i)
i = i + 1
websites = ["facebook.com", "google.com", "amazon.com"]
for site in websites:
print(site)
for i in range(5):
print(i)
|
import unittest
import math
from vector3dm import Vector3dm
class TestVector3dm(unittest.TestCase):
# tests from https://www.math.utah.edu/lectures/math2210/9PostNotes.pdf
def test_convert_to_cartesian(self):
r = 8
theta = math.pi/4
phi = math.pi/6
v = Vector3dm(r,theta,phi,"s")
# the expected answer
tx = 2*math.sqrt(2)
ty = tx
tz = 4*math.sqrt(3)
v2 = v.convert_to_cartesian()
x,y,z = v2.vals
self.assertAlmostEqual(x,tx,6,"s2c bad x: is {} should be {}".format(x,tx))
self.assertAlmostEqual(y,ty,6,"s2c bad y: is {} should be {}".format(y,ty))
self.assertAlmostEqual(z,tz,6,"s2c bad z: is {} should be {}".format(z,tz))
x,y,z = v2.convert_to_cartesian().vals # should do nothing
self.assertAlmostEqual(x,tx,6,"s2c #2 bad x: is {} should be {}".format(x,tx))
self.assertAlmostEqual(y,ty,6,"s2c #2 bad y: is {} should be {}".format(y,ty))
self.assertAlmostEqual(z,tz,6,"s2c #2 bad z: is {} should be {}".format(z,tz))
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
self.assertEqual(type(v.vals),type([]),"test changed vals type")
def test_convert_to_spherical(self):
x = 2*math.sqrt(3)
y = 6
z = -4
v = Vector3dm(x,y,z,"c")
# the expected answer
tr = 8.0
ttheta = math.pi/3.0
tphi = 2*math.pi/3.0
v2 = v.convert_to_spherical()
r,theta,phi = v2.vals
self.assertAlmostEqual(r,tr,6,"c2s bad r: is {} should be {}".format(r,tr))
self.assertAlmostEqual(theta,ttheta,6,"c2s bad theta: is {} should be {}".format(theta,ttheta))
self.assertAlmostEqual(phi,tphi,6,"c2s bad phi: is {} should be {}".format(phi,tphi))
r,theta,phi = v2.convert_to_spherical().vals # should do nothing
self.assertAlmostEqual(r,tr,6,"c2s #2 bad r: is {} should be {}".format(r,tr))
self.assertAlmostEqual(theta,ttheta,6,"c2s #2 bad theta: is {} should be {}".format(theta,ttheta))
self.assertAlmostEqual(phi,tphi,6,"c2s bad #2 phi: is {} should be {}".format(phi,tphi))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
def test_conversion_inversion_c2s_s2c(self):
tx = 2*math.sqrt(3)
ty = 6
tz = -4
v = Vector3dm(tx,ty,tz,"c")
x,y,z = v.convert_to_spherical().convert_to_cartesian().vals
self.assertAlmostEqual(x,tx,6,"inversion1 bad x: is {} should be {}".format(x,tx))
self.assertAlmostEqual(y,ty,6,"inversion1 bad y: is {} should be {}".format(y,ty))
self.assertAlmostEqual(z,tz,6,"inversion1 bad z: is {} should be {}".format(z,tz))
tr = 8
ttheta = math.pi/4
tphi = math.pi/6
v = Vector3dm(tr,ttheta,tphi,"s")
r,theta,phi = v.convert_to_cartesian().convert_to_spherical().vals
self.assertAlmostEqual(r,tr,6,"inversion2 #2 bad r: is {} should be {}".format(r,tr))
self.assertAlmostEqual(theta,ttheta,6,"inversion2 #2 bad theta: is {} should be {}".format(theta,ttheta))
self.assertAlmostEqual(phi,tphi,6,"inversion2 bad #2 phi: is {} should be {}".format(phi,tphi))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
def test_magnitude(self):
expected_mag = 18.78829423
v1 = Vector3dm(7,4,1,"c")
v2 = Vector3dm(13,18,-10,"c")
mag = v1.magnitude(v2)
self.assertAlmostEqual(mag,expected_mag,6,"magnitude1 bad mag: is {} should be {}".format(mag,expected_mag))
expected_mag = 29.06888371
v1 = Vector3dm(-3,18,6,"c")
v2 = Vector3dm(8,-2,-12,"c")
mag = v1.magnitude(v2)
self.assertAlmostEqual(mag,expected_mag,6,"magnitude2 bad mag: is {} should be {}".format(mag,expected_mag))
expected_mag = 23.53720459
v1 = Vector3dm(12,-19,7,"c")
mag = v1.magnitude()
self.assertAlmostEqual(mag,expected_mag,6,"magnitude3 bad mag: is {} should be {}".format(mag,expected_mag))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
def test_origin_distance(self):
expected_dist = 1.7320508075688772935274463415059
v1 = Vector3dm(-1,1,1,"c")
dist = v1.origin_distance()
self.assertAlmostEqual(dist,expected_dist,6,"origindist bad distance: is {} should be {}".format(dist,expected_dist))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
def test_add(self):
expected_sum_x = -6
expected_sum_y = 13
expected_sum_z = -25
v1 = Vector3dm(13,-5,-20,"c")
v2 = Vector3dm(-19,18,-5,"c")
v3 = v1.add(v2)
x,y,z = v3.vals
self.assertAlmostEqual(x,expected_sum_x,6,"origindist bad distance: is {} should be {}".format(x,expected_sum_x))
self.assertAlmostEqual(y,expected_sum_y,6,"origindist bad distance: is {} should be {}".format(y,expected_sum_y))
self.assertAlmostEqual(z,expected_sum_z,6,"origindist bad distance: is {} should be {}".format(z,expected_sum_z))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
self.assertEqual(type(v3.vals),type([]),"test changed vals type")
def test_sub(self):
expected_sum_x = 10
expected_sum_y = -21
expected_sum_z = 9
v1 = Vector3dm(-9,-4,10,"c")
v2 = Vector3dm(-19,17,1,"c")
v3 = v1.sub(v2)
x,y,z = v3.vals
self.assertAlmostEqual(x,expected_sum_x,6,"origindist bad distance: is {} should be {}".format(x,expected_sum_x))
self.assertAlmostEqual(y,expected_sum_y,6,"origindist bad distance: is {} should be {}".format(y,expected_sum_y))
self.assertAlmostEqual(z,expected_sum_z,6,"origindist bad distance: is {} should be {}".format(z,expected_sum_z))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
self.assertEqual(type(v3.vals),type([]),"test changed vals type")
def test_neg(self):
expected_sum_x = 5
expected_sum_y = 13
expected_sum_z = -4
v1 = Vector3dm(-5,-13,4,"c")
v3 = v1.neg()
x,y,z = v3.vals
self.assertAlmostEqual(x,expected_sum_x,6,"origindist bad distance: is {} should be {}".format(x,expected_sum_x))
self.assertAlmostEqual(y,expected_sum_y,6,"origindist bad distance: is {} should be {}".format(y,expected_sum_y))
self.assertAlmostEqual(z,expected_sum_z,6,"origindist bad distance: is {} should be {}".format(z,expected_sum_z))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v3.vals),type([]),"test changed vals type")
def test_mult(self):
v = Vector3dm(1,1,1,"c")
v_mult = v.mult(6.0)
x,y,z = v_mult.vals
self.assertAlmostEqual(x,6.0,6,"mult x: is {} should be {}".format(x,6.0))
self.assertAlmostEqual(y,6.0,6,"mult y: is {} should be {}".format(y,6.0))
self.assertAlmostEqual(z,6.0,6,"mult z: is {} should be {}".format(z,6.0))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
r = v_mult.get_r()
self.assertAlmostEqual(r, 10.392304845413264,6,"mult r: is {} should be {}".format(r,6.0))
def test_where_from_here(self):
#example from http://mathonline.wikidot.com/determining-a-vector-given-two-points; rearranged
x1 = 2
y1 = 2
z1 = 1
x2 = 4
y2 = 1
z2 = 1
exp_x = 6
exp_y = 3
exp_z = 2
v1 = Vector3dm(x1,y1,z1,"c")
v2 = Vector3dm(x2,y2,z2,"c")
res_v = v1.where_from_here(v2).convert_to_cartesian()
rx = res_v.vals[0]
ry = res_v.vals[1]
rz = res_v.vals[2]
self.assertAlmostEqual(rx,exp_x,6,"where_from_here x bad result: is {} should be {}".format(rx,exp_x))
self.assertAlmostEqual(ry,exp_y,6,"where_from_here y bad result: is {} should be {}".format(ry,exp_y))
self.assertAlmostEqual(rz,exp_z,6,"where_from_here z bad result: is {} should be {}".format(rz,exp_z))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
self.assertEqual(type(res_v.vals),type([]),"test changed vals type")
def test_dot(self):
# got example from https://chortle.ccsu.edu/VectorLessons/vch07/vch07_14.html
expected_dot = -14.0
x1 = -1
y1 = 2
z1 = -3
x2 = 1
y2 = -2
z2 = 3
v1 = Vector3dm(x1,y1,z1,"c")
v2 = Vector3dm(x2,y2,z2,"c")
dot = v1.dot(v2)
self.assertAlmostEqual(dot,expected_dot,6,"Dot bad result: is {} should be {}".format(dot,expected_dot))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
def test_point_at_that(self):
#example from http://mathonline.wikidot.com/determining-a-vector-given-two-points
x1 = 2
y1 = 2
z1 = 1
x2 = 6
y2 = 3
z2 = 2
exp_x = 4
exp_y = 1
exp_z = 1
v1 = Vector3dm(x1,y1,z1,"c")
v2 = Vector3dm(x2,y2,z2,"c")
res_v = v1.point_at_that(v2).convert_to_cartesian()
rx = res_v.vals[0]
ry = res_v.vals[1]
rz = res_v.vals[2]
self.assertAlmostEqual(rx,exp_x,6,"point_at_that x bad result: is {} should be {}".format(rx,exp_x))
self.assertAlmostEqual(ry,exp_y,6,"point_at_that y bad result: is {} should be {}".format(ry,exp_y))
self.assertAlmostEqual(rz,exp_z,6,"point_at_that z bad result: is {} should be {}".format(rz,exp_z))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
def test_inner(self):
expected_dot = -14.0
x1 = -1
y1 = 2
z1 = -3
x2 = 1
y2 = -2
z2 = 3
v1 = Vector3dm(x1,y1,z1,"c")
v2 = Vector3dm(x2,y2,z2,"c")
dot = v1.dot(v2)
self.assertAlmostEqual(dot,expected_dot,6,"Dot bad result: is {} should be {}".format(dot,expected_dot))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
def test_get_x(self):
x = 1
y = 2
z = 3
v1 = Vector3dm(x,y,z,"c")
res_x = v1.get_x()
self.assertAlmostEqual(res_x,x,6,"get_x bad result: is {} should be {}".format(res_x,x))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
def test_get_y(self):
x = 1
y = 2
z = 3
v1 = Vector3dm(x,y,z,"c")
res_y = v1.get_y()
self.assertAlmostEqual(res_y,y,6,"get_y bad result: is {} should be {}".format(res_y,y))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
def test_get_z(self):
x = 1
y = 2
z = 3
v1 = Vector3dm(z,y,z,"c")
res_z = v1.get_z()
self.assertAlmostEqual(res_z,z,6,"get_z bad result: is {} should be {}".format(res_z,z))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
def test_get_r(self):
r = 1
theta = 2
phi = 3
v1 = Vector3dm(r,theta,phi,"s")
res_r = v1.get_r()
self.assertAlmostEqual(res_r,r,6,"get_r bad result: is {} should be {}".format(res_r,r))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
def test_get_theta(self):
r = 1
theta = 2
phi = 3
v1 = Vector3dm(r,theta,phi,"s")
res_theta = v1.get_theta()
self.assertAlmostEqual(res_theta,theta,6,"get_r bad result: is {} should be {}".format(res_theta,theta))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
def test_get_phi(self):
r = 1
theta = 2
phi = 3
v1 = Vector3dm(r,theta,phi,"s")
res_phi = v1.get_phi()
self.assertAlmostEqual(res_phi,phi,6,"get_phi bad result: is {} should be {}".format(res_phi,phi))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
def test_set_phi(self):
r = 1
theta = 2
phi = 3
v = Vector3dm(r,theta,phi,"s")
v.set_phi(10)
phi = v.get_phi()
self.assertAlmostEqual(10,phi,6,"set_phi bad result: is {} should be {}".format(phi,10))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
def test_set_theta(self):
r = 1
theta = 2
phi = 3
v = Vector3dm(r,theta,phi,"s")
v.set_theta(10)
theta = v.get_theta()
self.assertAlmostEqual(10,theta,6,"set_phi bad result: is {} should be {}".format(theta,10))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
def test_set_r(self):
r = 1
theta = 2
phi = 3
v = Vector3dm(r,theta,phi,"s")
v.set_r(10)
r = v.get_r()
self.assertAlmostEqual(10,r,6,"set_phi bad result: is {} should be {}".format(r,10))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
def test_set_x(self):
x = 1
y = 2
z = 3
v = Vector3dm(x,y,z,"c")
v.set_x(10)
x = v.get_x()
self.assertAlmostEqual(10,x,6,"set_x bad result: is {} should be {}".format(x,10))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
def test_set_y(self):
x = 1
y = 2
z = 3
v = Vector3dm(x,y,z,"c")
v.set_y(10)
y = v.get_y()
self.assertAlmostEqual(10,y,6,"set_y bad result: is {} should be {}".format(y,10))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
def test_set_z(self):
x = 1
y = 2
z = 3
v = Vector3dm(x,y,z,"c")
v.set_z(10)
z = v.get_z()
self.assertAlmostEqual(10,z,6,"set_z bad result: is {} should be {}".format(z,10))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
def test_zero_vector(self):
zero_vector = Vector3dm.zero_vector()
vx = zero_vector.get_x()
vy = zero_vector.get_y()
vz = zero_vector.get_z()
vr = zero_vector.get_r()
self.assertAlmostEqual(vx,0.0,6,"test_zero_vector bad result: is {} should be {}".format(vx,0.0))
self.assertAlmostEqual(vy,0.0,6,"test_zero_vector bad result: is {} should be {}".format(vy,0.0))
self.assertAlmostEqual(vz,0.0,6,"test_zero_vector bad result: is {} should be {}".format(vz,0.0))
self.assertAlmostEqual(vr,0.0,6,"test_zero_vector bad result: is {} should be {}".format(vr,0.0))
self.assertEqual(type(zero_vector.vals),type([]),"test changed vals type")
def test_cross_product(self):
v1 = Vector3dm(2,3,4,"c")
v2 = Vector3dm(5,6,7,"c")
r_x = -3.0
r_y = 6.0
r_z = -3.0
v1_x_v2 = v1.cross(v2)
x = v1_x_v2.get_x()
y = v1_x_v2.get_y()
z = v1_x_v2.get_z()
self.assertAlmostEqual(x,r_x,6,"test_cross bad result: is {} should be {}".format(x,r_x))
self.assertAlmostEqual(y,r_y,6,"test_cross bad result: is {} should be {}".format(y,r_y))
self.assertAlmostEqual(z,r_z,6,"test_cross bad result: is {} should be {}".format(z,r_z))
self.assertEqual(type(v1.vals),type([]),"test changed vals type")
self.assertEqual(type(v2.vals),type([]),"test changed vals type")
def test_unit_vector(self):
v = Vector3dm(12,-3,-4,"c").unit()
r_x = 12/13
r_y = -3/13
r_z = -4/13
x,y,z = v.get_x(),v.get_y(),v.get_z()
self.assertAlmostEqual(x,r_x,6,"test_unit bad result: is {} should be {}".format(x,r_x))
self.assertAlmostEqual(y,r_y,6,"test_unit bad result: is {} should be {}".format(y,r_y))
self.assertAlmostEqual(z,r_z,6,"test_unit bad result: is {} should be {}".format(z,r_z))
self.assertEqual(type(v.vals),type([]),"test changed vals type")
if __name__ == '__main__':
unittest.main()
|
'''coleccion= {1:"Frank",2:"Jose",3:"Maria",4:"Thomas",5:"Javier"}
for clave,valor in coleccion.items():
print(f"EElemento :{clave}->{valor}")'''
coleccion= "Frank"
for i in coleccion:
print(f"{i}",end=".")
|
'''print("Tienen dos elementos ,clave y valor")
diccionario={ "azul":"blue", "rojo": "red","verde":"green"}
diccionario["amarillo"]="yellow"
diccionario["azul"]="BLUE"
del(diccionario["verde"])
print(diccionario)'''
equipo = {10:"Paulo Dybala",11:"Douglas Costa", 7:"Cristiano Ronaldo"}
print(equipo.get(6,"No existe un jugador con ese dorzal"))
|
print("No existen pero se simulan en python")
pila =[1,2,3]
#aGREGANDO ELEMENTOS POR EL FINALDE LA PILA
pila.append(4)
pila.append(5)
print(pila)
#Eliminar elemetos del final de la "pila"
n=pila.pop()
print("Sacando el elemento",n)
print(pila)
|
a=5
b=10
a,b=b,a
print(f"El valor de A es:{a} y de B es:{b}")
|
# sales by match
# https://www.hackerrank.com/challenges/sock-merchant/problem
def sock_merchant(socks: list[int]) -> int:
"""Determine how many pairs of socks with matching colors.
Given an array of integers representing the color of each sock,
determine how many pairs of socks with matching colors there are.
Args:
socks (int): color_id of each socks
Returns:
int: pairs of socks
"""
socks_pile: dict[int, int] = {} # {color_id: count}
for color_id in socks:
if color_id not in socks_pile:
socks_pile[color_id] = 1
else:
socks_pile[color_id] += 1
pairs: int = 0
for color_id in socks_pile:
pairs += socks_pile[color_id] // 2
return pairs
|
# find digits
# https://www.hackerrank.com/challenges/find-digits/problem
def find_digits(n: int) -> int:
"""Count the number of divisors for each digit that makes up the integer.
Args:
n (int): value to analyze
Returns:
int: number of digits in `n` that are divisors of `n`
"""
return len([int(x) for x in str(n) if int(x) != 0 and n % int(x) == 0])
|
# number line jumps
# https://www.hackerrank.com/challenges/kangaroo/problem
def kangaroo(x1: int, v1: int, x2: int, v2: int) -> str:
"""Determine if two kangaroos will meet
Args:
x1 (int): kangaroo 1 starting position
v1 (int): kangaroo 1 jumping distance
x2 (int): kangaroo 2 starting position
v2 (int): kangaroo 2 jumping distance
Returns:
str: "YES" or "NO"
"""
# kangaroo 1 won't be able to catch up kangaroo 2
if x2 > x1 and v2 >= v1:
return "NO"
# Naive O(n) solution
#
# k1 = x1
# k2 = x2
# while True:
# k1 += v1
# k2 += v2
# if k1 == k2:
# return "YES"
# Better O(1) solution
# i = jump
#
# x1 + v1 * i == x2 + v2 * i
# x1 - x2 == v2 * i - v1 * i
# x1 - x2 == (v2 - v1) * i
# (x1 - x2) / (v2 - v1) == i
#
# they will meet if i jump is an integer, thus
# (x1 - x2) % (v2 - v1) == 0
if (x1 - x2) % (v2 - v1) == 0:
return "YES"
else:
return "NO"
|
# staircase
# https://www.hackerrank.com/challenges/staircase/problem
def staircase(n: int):
for i in range(1, n + 1):
print(" " * (n - i) + "#" * i)
|
# electronics shop
# https://www.hackerrank.com/challenges/electronics-shop/problem
def get_money_spent(keyboards: list[int], drives: list[int], budget: int) -> int:
"""Find the cost to buy the most expensive computer keyboard and USB drive that can be purchased with a given budget
Args:
keyboards (list[int]): keyboard prices
drives (list[int]): drive prices
budget (int): budget
Returns:
int: the maximum that can be spent, or `-1` if it is not possible to buy both items
"""
max_price: int = -1
for i in range(len(keyboards)):
for j in range(len(drives)):
price: int = keyboards[i] + drives[j]
if price <= budget and price > max_price:
max_price = price
return max_price
|
# designer pdf viewer
# https://www.hackerrank.com/challenges/designer-pdf-viewer/problem
def designer_pdf_viewer(heights: list[int], word: str) -> int:
"""Determine the area of the highlighted word.
Args:
heights (list[int]): the heights of each letter
word (str): string
Returns:
int: the size of the highlighted area
"""
word_heights: list[int] = []
for char in word:
word_heights.append(heights[ord(char) - ord("a")])
return max(word_heights) * len(word)
|
from NeuralNetwork import NeuralNetwork
import pandas as pd
# Data 1
print('Starting training data 1')
data = pd.read_csv('dataset.csv').values
N, d = data.shape
X = data[:, 0:d - 1].reshape(-1, d - 1)
y = data[:, 2].reshape(-1, 1)
p = NeuralNetwork([X.shape[1], 5, 1], 0.1)
p.fit(X, y, 10000, 100)
# This will print the result = 0
print('Result for x = [5 0.1] ', p.predict([5, 0.1]))
# This will print the result = 1
print('Result for x = [10 0.8] ', p.predict([10, 0.8]))
|
# 开发者:Lingyu
# 开发时间:2020/12/26 9:56
# Location:C:\Users\admin\anaconda3\envs\Numpy
# Conda executable:C:\Users\admin\anaconda3\Scripts\conda.exe
# 创建数组,得到ndarray的数据类型
from random import random
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, ])
b = np.array(range(1, 8))
c = np.arange(1, 8)
# a, b, c内容相同
d = np.arange(2, 24, 2) # 2为步长
print(a, b, c, d)
print(type(a), type(b), type(c), type(d))
print('*' * 100)
# numpy中的数据类型
t1 = np.array(range(1, 4), dtype=float)
print(t1)
print(t1.dtype)
t2 = np.array(range(1, 6), dtype='float32') # 指定数据类型
print(t2)
print(t2.dtype)
t3 = np.array(range(3, 6), dtype='i1') # 1个字节对应8位
print(t3)
print(t3.dtype)
print('*' * 100)
# numpy中的布尔类型
t4 = np.array([1, 0, 1, 1, 0, ], dtype=bool)
print(t4)
print(t4.dtype)
print('*' * 100)
# 调整数据类型
t5 = t4.astype('i8')
print(t5)
print(t5.dtype)
print('*' * 100)
# numpy中的小数
import random
t6 = np.array([random.random() for i in range(13)])
print(t6)
print(t6.dtype)
t7 = np.round(t6, 3)
print(t7)
print(t7.dtype)
print(round(random.random(), 4))
print(round(random.random(), 4))
print(round(random.random(), 4))
print(round(random.random(), 4))
|
from unittest import TestCase
from controller.command_interpreter import Controller
from model.toy_robot import Robot
# Tests the Robot Model
class RobotModelTest(TestCase):
# Validates that the robot object is created with no parameters
def test_create_empty_robot(self):
robot = Robot()
self.assertIsNone(robot.get_x())
self.assertIsNone(robot.get_y())
self.assertIsNone(robot.get_facing())
# Validates that the robot object is created with the parameteres given
def test_create_robot(self):
robot = Robot(x=0, y=0, facing='NORTH')
self.assertEqual(robot.get_x(), 0)
self.assertEqual(robot.get_y(), 0)
self.assertEqual(robot.get_facing(), 'NORTH')
# Tests Robot methods
class RobotUnitTest(TestCase):
# Validates that the get_location function returns the coordinates tuple
def test_get_location_function(self):
robot = Robot(x=0, y=0, facing='NORTH')
self.assertEqual(robot.get_location(), (0,0))
# Validates that is_valid_y_movement function returns False for a not valid movement to North
def test_valid_y_movement_north(self):
robot = Robot(x=0, y=4, facing='NORTH')
self.assertFalse(robot.is_valid_y_movement())
# Validates that is_valid_y_movement function returns False for a not valid movement to South
def test_valid_y_movement_south(self):
robot = Robot(x=4, y=0, facing='SOUTH')
self.assertFalse(robot.is_valid_y_movement())
# Validates that is_valid_x_movement function returns False for a not valid movement to East
def test_valid_x_movement_east(self):
robot = Robot(x=4, y=4, facing='EAST')
self.assertFalse(robot.is_valid_x_movement())
# Validates that is_valid_x_movement function returns False for a not valid movement to West
def test_valid_y_movement_west(self):
robot = Robot(x=0, y=0, facing='WEST')
self.assertFalse(robot.is_valid_x_movement())
# Validates that place function locates the robot correctly
def test_place_function(self):
robot = Robot()
self.assertTrue(robot.place([4,3,'NORTH']))
self.assertEqual(robot.get_x(), 4)
self.assertEqual(robot.get_y(), 3)
self.assertEqual(robot.get_facing(), 'NORTH')
# Validates that place function doesn't locate the robot correctly
def test_place_function_to_false(self):
robot = Robot()
self.assertFalse(robot.place([-1,5,'NORTH']))
self.assertIsNone(robot.get_x())
self.assertIsNone(robot.get_y())
self.assertIsNone(robot.get_facing())
# Validates that move function increments the correct coordinate based on the facing value
def test_move_function(self):
robot = Robot(x=0, y=0, facing='EAST')
robot.move()
self.assertEqual(robot.get_x(), 1)
self.assertEqual(robot.get_y(), 0)
self.assertEqual(robot.get_facing(), 'EAST')
# Validates that left function rotates the robot correctly
def test_left_function(self):
robot = Robot()
robot.place([4,3,'NORTH'])
robot.left()
self.assertEqual(robot.get_facing(), 'WEST')
# Validates that right function rotates the robot correctly
def test_right_function(self):
robot = Robot()
robot.place([4,3,'WEST'])
robot.right()
self.assertEqual(robot.get_facing(), 'NORTH')
# Validates that report function returns the correct robot location
def test_report_function(self):
robot = Robot()
robot.place([1,1,'SOUTH'])
robot.move()
robot.move()
robot.left()
robot.move()
self.assertEqual(robot.report(), '2,0,EAST')
# Test Controller commands
class RobotControllerTest(TestCase):
# Validates that the first command is PLACE
def test_first_command_place(self):
first_command = 'PLACE 0,0,EAST'
robot = Robot()
controller = Controller()
self.assertTrue(controller.read_command(robot, first_command))
# Validates that the first command is not PLACE
def test_first_command_not_place(self):
non_valid_first_commands = [
'MOVE',
'LEFT',
'RIGHT',
'REPORT'
]
robot = Robot()
controller = Controller()
for command in non_valid_first_commands:
self.assertFalse(controller.read_command(robot, command))
# Validates that any non-defined command is not a valid one
def test_non_valid_command(self):
non_valid_command = 'JUMP'
robot = Robot()
controller = Controller()
self.assertFalse(controller.read_command(robot, non_valid_command))
# Validates that a non-valid facing value given as a parameter returns False
def test_non_valid_facing(self):
command = 'PLACE 4,2,NORTH-EAST'
robot = Robot()
controller = Controller()
self.assertFalse(controller.read_command(robot, command))
# Validates that the robot is not placed with wrong coordinates
def test_non_valid_place_function_coordinates(self):
command = 'PLACE -1,5,SOUTH'
robot = Robot()
controller = Controller()
self.assertFalse(controller.read_command(robot, command))
# Validates that the move command works properly
def test_command_series(self):
commands = [
'PLACE 0,0,EAST',
'LEFT',
'MOVE',
'RIGHT',
'MOVE',
'REPORT'
]
robot = Robot()
controller = Controller()
for command in commands:
if command != 'REPORT':
self.assertTrue(controller.read_command(robot, command))
else:
self.assertEqual(controller.read_command(robot, command), '1,1,EAST')
|
numero_1=int(input("Entre com um número: "))
numero_2=int(input("Entre com outro número: "))
numeros = [5,2,3,1]
print("Conjunto de números: ", numeros)
print("\nUsando / para divisão: ",numero_1/numero_2)
print("\nUsando // para divisão: ",numero_1//numero_2)
print("\nUsando % para divisão: ",numero_1%numero_2)
print("\nPrimeiro número é igual ao segundo: ",numero_1 == numero_2)
print("Números identicos: ",numero_1 is numero_2)
print("Números não identicos: ",numero_1 is not numero_2)
print("Primeiro número é membro do conjunto: ",numero_1 in numeros)
print("Segundo número não é membro do conjunto: ",numero_2 not in numeros)
print("\nPrimeiro número é >= a 8 e o segundo < que 10: ",numero_1>=8 and numero_2<10)
print("\nUsando not... Primeiro número é igual a 8: ",not(numero_1==8)) |
numero = int(input("Digite o número \n--> "))
cont = numero+10
while(numero < cont):
numero+=1
print(numero)
|
produto = float(input("Digite o valor do produto: R$"))
if(produto < 20):
print("O lucro será de 45%, o valor de venda do produto é de: R${}".format(produto*0.45 + produto))
elif(produto >= 20):
print("O lucro será de 30%, o valor de venda do produto é de: R${}".format(produto*0.30 + produto)) |
import stack_class
topA = stack_class.stack_class()
topB = stack_class.stack_class()
topC = stack_class.stack_class()
def move(A,B):
if B.empty():
B.push(A.top())
A.pop()
else:
if A.top() > B.top():
print("이동이 불가능합니다.")
return 0
else:
B.push(A.top())
A.pop()
return B.size()
def match(A,B):
if A =="A":
if (B=="B"):
return move(topA,topB)
else:
return move(topA,topC)
elif A=="B":
if (B=="A"):
return move(topB,topA)
else:
return move(topB,topC)
else:
if (B=="A"):
return move(topC,topA)
else:
return move(topC,topB)
if __name__ == "__main__":
cnt= int(input("원판의 개수를 입력하시오 : "))
s_cnt = cnt
while cnt!=0:
topA.push(cnt)
cnt -=1
topA.print_stack()
while True:
A, B = input("\n3개의 기둥 A, B, C 가 있습니다.\n1)옮기고자 하는 원판이 있는기둥과 2)원판의 목적지가 될 기둥을 순서대로 입력하시오 ex, A C : ").split()
if match(A, B) == s_cnt:
print("성공!")
break
topA.print_stack()
topB.print_stack()
topC.print_stack()
|
# coding: utf-8
# In[ ]:
# 반복문 fun
# In[ ]:
def add(a,b):
return a+b;
#f리턴이 없는 함수는, 프로시져 => 전역변수를 이용해서 값 변경하는 경우에 많이 사용됨
#프로시저는 변수에 값을 할당하면 안됨.
# In[ ]:
#namespace
#local 지역변수
#global 전역변수
#상수와 비슷한 느낌..
#지역변수에서 전역변수값을 바꾸고 싶을 때는, global a , a = 3
a =3
def add(a,b):
global a = 2;
return a+b;
#built-in 내장변수
#__init__, ...
# In[1]:
def sub1(a,b):
return a-b
def sub2(a,b):
print(a-b)
print(sub1(1,2))
sub2(1,2)
# In[19]:
a = 5
def sub1(a,b):
global a
a = 3
return a-b
print(sub1(7,1))
# In[18]:
import this
#import가 되는지 test하기 위한 기본 라이브러리
# In[ ]:
def add(a,b):
return a+b;
def sub1(a,b):
return a-b
|
# coding: utf-8
# In[1]:
#self object만의 값
# In[3]:
class Person:
# class Person의 멤버변수
name = "홍길동"
number = "01077499954"
age = "20"
# class Person의 메소드
def info(self):
print("제 이름은 " + self.name + "입니다.")
print("제 번호는 " + self.number + "입니다.")
print("제 나이는 " + self.age + "세 입니다.")
if __name__ == "__main__":# main namespace를 의미합니다.
customer = Person()#Person의 객체 customer 생성
customer.info()#info 함수 호출
# In[4]:
class Person:
# class Person의 멤버변수
# __(double underscore)
# __는 클래스외부에서 클래스 멤버에 접근하지 못하게 하기위함
__name = "홍길동"
__number = "01077499954"
__age = "20"
@property #property 값을 갖고 옴
def name(self):
return self.__name
@name.setter #setter 값을 바꿔줌
def name(self, newName):
self.__name = newName
# class Person의 메소드
def info(self):
print("제 이름은 " + self.__name + "입니다.")
print("제 번호는 " + self.__number + "입니다.")
print("제 나이는 " + self.__age + "세 입니다.")
if __name__ == "__main__":# main namespace를 의미합니다.
customer = Person()#Person의 객체 customer 생성
customer.info()#info 함수 호출
print(customer.name)
customer.name="이태일"
print(customer.name)
# __gkgk__ : 매직메소드
# In[27]:
class Person :
def __init__(self, name):
self.__name = name
#def setname(self, newName):
# self.name = newName
@property
def name(self):
return self.__name
@name.setter
def name(self, newName):
self.__name = newName
if __name__ == "__main__":
p1 = Person("양승희")
p2 = Person("양승희")
p1.name="홍길동"
print (p1.name)
print (p2.name)
# In[30]:
#이터레이터
#매직메소드
#__iter__
#__next__
class Fibo :
def __init__(self) :
self.prv = 0
self.cur = 1
def __iter__(self):
return self
def __next__(self):
self.cur, self.prv = self.cur + self.prv , self.cur
return self.prv
f = Fibo()
for i in range(10):
print(next(f))
# In[31]:
#yield 반환값. yield를 만나면 ajacna => 제너레이터. 리터레이터화가됨.(셀수있는집합)
def fib():
prv = 0
cur = 1
while 1:
yield cur
cur, prv = cur+prv, cur
f = fib()
for i in range(10):
print(next(f))
#따로 next를 정의 해 주지 않아도 됨
# In[ ]:
#클래스
|
#----------
# Devin Suy
#----------
from Algorithm.GameState import GameState
# Human player optimizes for minimal score
# Bot optimizes for maximum score
class MiniMax:
def __init__(self, game_states):
self.game_states = game_states
self.initial_state = game_states[-1] # Last state in the list is the initial state
# Used for scoring leaf nodes
def score_node(self, state_node):
t = (len(state_node.game_state.board.avail_cell_nums)+1) # Remaining empty squares + 1
human_went_last = not state_node.turn
if human_went_last:
human_won = state_node.game_state.game_over(state_node.game_state.human)
if human_won:
state_node.state_score = -1 * t
else:
bot_won = state_node.game_state.game_over(state_node.game_state.bot)
if bot_won:
state_node.state_score = 1 * t
# Neither human nore bot have won in this board configuration
if state_node.state_score is None:
state_node.state_score = 0
# Implement minimax algorithm. Human player is min, Bot is max
# To reach a leaf node there are 8 moves that follow the initial state before
# the game board is filled, or we reach an end game before values
# propagate upward as we backtrack to the given state_node
def rank_states(self, state_node):
# Base case is reached
if state_node.leaf_node:
return state_node.state_score
# It is Human's turn (X), we will minimize
if state_node.turn:
min_score = float('inf')
# Recursively evaluate each "child" state
for successor_state in state_node.successors:
backed_score = self.rank_states(successor_state)
if backed_score < min_score:
min_score = backed_score
# Assign the optimal score at this level
state_node.state_score = min_score
print("Assigned MIN @ depth ", state_node.depth, ": ", state_node.state_score)
return min_score
# It is Bot's turn (O), we will maximize
else:
max_score = float('-inf')
# Recursively evaluate each "child" state
for successor_state in state_node.successors:
backed_score = self.rank_states(successor_state)
if backed_score > max_score:
max_score = backed_score
# Assign the optimal score
state_node.state_score = max_score
print("Assigned MAX @ depth ", state_node.depth, ": ", state_node.state_score)
return max_score
|
"""
Triangle Classification
@author: Sanjeev Rajasekaran
"""
import unittest
def classifyTriangle(a, b, c):
"""
takes three sides of the triangle as input
"""
if a+b < c or a+c < b or b+c < a:
return "Not a Triangle"
RightTriangle = "Not Right Triangle"
if (pow(a, 2) + pow(b, 2) == pow(c, 2)) or (pow(a, 2) + pow(c, 2) == pow(b, 2)) or (pow(c, 2) + pow(b, 2) == pow(a, 2)):
RightTriangle = "Right Triangle"
if a == b == c:
return 'Equilateral' + " " + RightTriangle
elif a == b or a == c or b == c:
return 'Isoceles' + " " + RightTriangle
else:
return 'Scalene' + " " + RightTriangle
def runClassifyTriangle(a, b, c):
""" call classifytriangle """
print(classifyTriangle(a, b, c))
class TestTriangles(unittest.TestCase):
def testSet1(self): # test invalid inputs
self.assertEqual(classifyTriangle(3, 4, 5), 'Scalene Right Triangle')
self.assertEqual(classifyTriangle(3, 4, 12), 'Not a Triangle')
def testMyTestSet2(self):
self.assertEqual(classifyTriangle(1, 1, 1), 'Equilateral Not Right Triangle')
self.assertNotEqual(classifyTriangle(10, 10, 10), 'Isoceles Right Triangle')
self.assertEqual(classifyTriangle(10, 15, 24), 'Scalene Not Right Triangle')
if __name__ == '__main__':
runClassifyTriangle(1, 2, 3)
runClassifyTriangle(1, 1, 1)
unittest.main(exit=False)
|
from turtle import *
class Ball(Turtle):
def __init__(self,x,y,dx,dy,r,color):
Turtle.__init__(self)
self.pu()
self.x=x
self.goto(x,y)
self.y=y
self.dx=dx
self.dy=dy
self.r=r
self.shape("circle")
self.color(color)
self.shapesize(r/10)
def move(self, width, height):
current_x = self.xcor()
current_y = self.ycor()
new_x = current_x+self.dx
new_y = current_y+self.dy
right_side_ball = new_x + self.r
left_side_ball = new_x - self.r
up_side_ball = new_y + self.r
down_side_ball = new_y - self.r
self.goto(new_x, new_y)
if(left_side_ball<=-width or right_side_ball>=width):
self.dx*=-1
if(up_side_ball <= - height or down_side_ball>=height):
self.dy*=-1
|
import csv
from array import array
from collections import defaultdict
# def main(f, col=0):
# return get_file_max(f, col)
def get_file_max(f, col):
"""
gets the row with the maximum value at column col in file f
"""
with open(f) as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader) # skip header row
return max(csv_reader, key = lambda x: int(x[col]))
def get_file_min(f, col):
"""
gets the row with the minimum value at column col in file f
"""
with open(f) as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader) # skip header row
return min(csv_reader, key = lambda x: int(x[col]))
def print_lines(f):
# used for file inspection, not important to main program
# leaving this in
with open(f) as csv_file:
csv_reader = csv.reader(csv_file)
for i, row in enumerate(csv_reader):
print(i, end = ', ')
for col in row:
print(col, end = ', ')
if i == 5:
print()
return col
print(row[0], row[1])
print()
def make_buckets(f, start_col, len_col) -> array:
"""
makes an array large enough to hold all keys based on numerical values from
a file column
"""
return array('i', [ 0 for _ in range(
int(get_file_max(f, start_col)[start_col]) +
int(get_file_max(f, len_col)[len_col])
+ 2)])
def fill_lookup(f, start_col, len_col, lookup=defaultdict(int)):
"""
fills in the given lookup table, must have __getitem__() implimented
"""
with open(f) as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader)
print("starting table fill")
for i, row in enumerate(csv_reader):
if i % 200000 == 0:
print("reading in row", i)
for key in range(int(row[start_col]), int(row[start_col]) + int(row[len_col])):
lookup[key] += 1
return lookup
# def do_lookup(lookup):
# print(lookup[101844980])
def fill_lookup_file(f, f_output, lookup, lookup_col):
"""
Makes a version of lookup file f at f_output with the lookup values from
passed lookup variable from file f at column lookup_col. Lookup must have
__getitem__ implimented.
"""
with open(f) as lookup_file, open(f_output, 'w') as output_file:
csv_reader = csv.reader(lookup_file)
csv_writer = csv.writer(output_file, delimiter=',')
headers = next(csv_reader)
csv_writer.writerow(headers)
for i, row in enumerate(csv_reader):
lookup_val = int(row[lookup_col])
csv_writer.writerow(
[lookup_val ,
lookup[int(lookup_val)]])
if __name__ == "__main__":
# print("main", main("./data/loci.csv"))
# print("max reads.csv", get_file_max("./data/reads.csv", 1))
# print("min reads.csv", get_file_min("./data/reads.csv", 1))
# print("max reads.csv", get_file_max("./data/reads.csv", 0))
# print("min reads.csv", get_file_min("./data/reads.csv", 0))
# print("print_lines", print_lines("./data/reads.csv"))
#foo = int(get_file_max("./data/reads.csv", 0)[0]) - int(get_file_min("./data/reads.csv", 0)[0])
# lookup = make_buckets("./data/reads.csv", 0, 1)
# fill_lookup("./data/reads.csv", 0, 1, lookup = lookup)
lookup = fill_lookup("./data/reads.csv", 0, 1)
fill_lookup_file('./data/loci.csv', './data/loci_filled.csv', lookup, 0)
|
import sys
import pygame
from settings import Settings
from paddle import Paddle
from paddle_ai import PaddleAI
from ball import Ball
from scoreboard import Scoreboard
class Pong:
"""Overall class managing game assets and behavior."""
def __init__(self):
"""Initialize the game and create game resources."""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height
pygame.display.set_caption('Pong')
self.line_length = self.settings.screen_height // 25
self.x_middle = self.settings.screen_width // 2
self.quadrant3 = self.settings.screen_width * 0.75
self.y_middle = self.settings.screen_height // 2
self.game_over = False
self.player_points = 0
self.ai_points = 0
self.paddle = Paddle(self)
self.ball = Ball(self)
# The paddle_ai requires the ball so that it can know its attributes
self.paddle_ai = PaddleAI(self)
self.sb = Scoreboard(self)
def run_game(self):
while not self.game_over:
self._check_events()
self.paddle.update()
self.paddle_ai.update()
self.ball.update()
self._check_endgame()
self._update_screen()
def _check_endgame(self):
"""Tests if the player or the AI has reached 11 points"""
if self.player_points >= 11:
print('Player wins!')
self.game_over = True
elif self.ai_points >= 11:
print('AI wins!')
self.game_over = True
def _check_events(self):
"""Check for and respond to events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_keydown_events(self, event):
"""Respond to key presses"""
if event.key == pygame.K_UP:
self.paddle.moving_up = True
elif event.key == pygame.K_DOWN:
self.paddle.moving_down = True
def _check_keyup_events(self, event):
"""Respond to key releases"""
if event.key == pygame.K_UP:
self.paddle.moving_up = False
elif event.key == pygame.K_DOWN:
self.paddle.moving_down = False
def _update_screen(self):
"""Update images on the screen and flip to a new screen"""
# Redraw the screen at each pass in the loop
self.screen.fill(self.settings.bg_color)
self._draw_net()
self.sb.show_points()
self.paddle.draw_paddle()
self.paddle_ai.draw_paddle()
self.ball.draw_ball()
# Make the most recently drawn screen visible
pygame.display.flip()
def _draw_net(self):
"""Draws the dotted net down the center of the screen"""
# Draw 8 lines
for i in range(0, 25, 2):
# Set start and end positions
y_start_pos = i * self.line_length
y_end_pos = y_start_pos + self.line_length
# Draw line
pygame.draw.line(self.screen, self.settings.paddle_color, (self.x_middle, y_start_pos), (self.x_middle, y_end_pos))
if __name__ == "__main__":
pong = Pong()
pong.run_game() |
a=int(input("Enter the A value"));
b=int(input("Enter the b"));
c=int(input("Enter the C"));
if(a==b==c):
print(a," The Entered Three values are Equel");
elif(a==b>c):
print("A and B is equel and biggest");
elif(a<b==c):
print("B and C is equel and biggest");
elif(a==c>b):
print("A and C is equel and biggest");
elif (a>b>c):
print(a," is big");
elif(b<c):
print(c," is big");
elif(b>c):
print(c," is big");
|
t=(1,2,3,4,3,5,3,7,8);
print("The tuple is ",t);
s=str(t);
print("The converted string from the tuple is ",s);
l=list(t);
print("The converted list from the tuple is ",l);
length=len(t);
print("The 4th length in tuple is ",t[3]);
print("The 4th length in tuple from the last is ",t[length-4]);
print("The repeated elements are ");
for i in range(0,length-1):
for j in range(i+1,length):
if(t[i]==t[j]):
print(t[j])
k=int(input("enter the element to searched in tuple"));
for i in range(0,length):
if(k==t[i]):
flag=1;
else:
flag=0;
if(flag):
print("The element is present");
else:
print("The element is present");
l.pop();
t=tuple(l);
print("The last element is removed in tuple");
n=int(input("Enter the range from which the tuple is sliced"));
print("The tuple after the slice is ",t[0:n]);
print("The length of the tuple is ",len(t));
l1=[(1,2,3,40),(93,4,5),(0,1,2,3,4)];
for i in l1:
print(list(i));
l=list(t);
print(l);
l.reverse();
print("The reserve of tuple is",l);
|
def abcd(a):
l=sorted(a)
b=[]
for i in a:
b.append(i)
if(b==ls):
return True
else:
return False
s=input("Enter the word to check whether it is alpabatical order");
if(abcd(s)):
print("It is in alpabatical order");
else:
print("It is not in alpabatical order");
|
p=float(input("Enter the Principle Amount"));
r=float(input("Enter the Interst Rate"));
n=int(input("Enter the Time value"));
print("The Compunt Interest Value is ",(p*n*r)/100);
|
class upper:
def __init__(self,s):
self.s=s;
def print_string(self):
print(self.s.upper());
s=input("Enter the string to be printed in upper case");
u=upper(s);
u.print_string(); |
class Solution(object):
def wordBreak(self, s, wordDict):
sz = len(s)
dp = [False for _ in range(sz)]
for i in range(sz):
for word in wordDict:
if not cmp(word,s[i-len(word)+1:i+1]) and (i==len(word)-1 or dp[i-len(word)]):
dp[i] = True
return dp[-1]
s = 'leetcodeleet'
wordDict = set(['leet','code'])
print Solution().wordBreak(s,wordDict) |
import sys
class ListNode(object):
def __init__(self,x=sys.maxint):
self.val = x
self.next = None
def printList(head):
while head:
print head.val, ' ',
head = head.next
print
class Solution(object):
def mergeKLists(self, lists):
def divideLists(s,e):
if s > e: return None
elif s == e:
return lists[s]
mid = (e-s)/2+s
p = divideLists(s,mid)
q = divideLists(mid+1,e)
return mergeTwoLists(p,q)
def mergeTwoLists(p,q):
if not p: return q
if not q: return p
head = ListNode(0)
curr = head
while p or q:
if not p:
curr.next = q
q = q.next
elif not q:
curr.next = p
p = p.next
else:
if p.val <= q.val:
curr.next = p
p = p.next
else:
curr.next = q
q = q.next
curr = curr.next
return head.next
return divideLists(0, len(lists)-1)
head1 = ListNode(-2)
tail1 = print1 = head1
n1_1 = ListNode(3)
tail1.next = n1_1
tail1 = tail1.next
n1_2 = ListNode(5)
tail1.next = n1_2
tail1 = tail1.next
head2 = ListNode(1)
tail2 = print2 = head2
n2_1 = ListNode(2)
tail2.next = n2_1
tail2 = tail2.next
n2_2 = ListNode(7)
tail2.next = n2_2
tail2 = tail2.next
printList(print1)
printList(print2)
printList(Solution().mergeKLists([head1,head2]))
|
from collections import defaultdict
class Solution(object):
def wordBreak(self, s, wordDict):
d = {len(s):['']}
def parse(i):
if i not in d:
d[i] = [s[i:j] + (word and ' ' + word)
for j in range(i+1, len(s)+1)
if s[i:j] in wordDict
for word in parse(j)]
return d[i]
return parse(0)
s = 'catsanddog'
wordDict = set(["cat", "cats", "and", "sand", "dog"])
print Solution().wordBreak(s,wordDict) |
#!python3
#coding: utf-8
import fileinput
input_obj = fileinput.input()
for data in input_obj:
A, B = data.strip().split()
print(int(A.find(B) >= 0)) |
import sqlite3
connect = sqlite3.connect('college.db')
cursor = connect.cursor()
query="select*from studentDetails"
cursor.execute(query)
for rows in cursor.fetchall():
print(rows[1],rows[2])
cursor.close()
connect.close()
|
import math, logging
from Error_info import *
from Log import LogConfig
class Cal(BuildError):
@classmethod
def __init__(self):
logging.info("Start")
# 正方形面积
def Square_Area(self, length):
try:
if length < 0:
raise PositiveIntegerError
except Exception as e:
print(e)
logging.error("-----****边长%d不合法***-----" % length, exc_info=True, stack_info=True)
else:
area = length * length
print('正方形的面积是:%.2f' % area)
# 矩形面积
def Rectangle_Area(self, length_a, length_b):
try:
if length_b < 0 or length_a < 0:
raise PositiveIntegerError
except Exception as e:
print(e)
if length_b < 0:
logging.error("-----****边长%d不合法***-----" % length_b, exc_info=True, stack_info=True)
elif length_a < 0:
logging.error("-----****边长%d不合法***-----" % length_a, exc_info=True, stack_info=True)
else:
area = length_a * length_b
print('矩形的面积是:%.2f' % area)
# 圆形面积
def Circle_Area(self,radius):
try:
if radius < 0:
raise PositiveIntegerError
except Exception as e:
print(e)
logging.error("-----****半径%d不合法***-----" % radius, exc_info=True, stack_info=True)
else:
print('圆形的面积是:%.4f' % (math.pi * radius * radius))
# 三角形面积
def Triangle_Area(self, length_a, length_b, length_c):
try:
if (length_a + length_b > length_c and length_b + length_c > length_b and
length_a + length_c > length_b):
# 海伦公式
half_length = (length_a + length_b + length_c) / 2.0
Area = math.sqrt(
half_length * (half_length - length_a) * (half_length - length_b) * (half_length - length_c))
print("三角形面积为:%.2f" % Area)
else:
msg = '三角形'
raise BuildError(msg)
except Exception as e:
print(e)
logging.error("-----****边长%d %d %d不合法***-----" % (length_a, length_b, length_c),
exc_info=True, stack_info=True)
if __name__ == '__main__':
newShape = Cal()
newShape.Circle_Area(-4)
newShape.Rectangle_Area(23,44)
|
citizen = input("Are you a U.S. citizen (or born in Puerto Rico, Guam, or U.S. Virgin Islands)? ")
if citizen[0].lower() == "n":
print(" You are ineligible to vote in NY.")
if citizen[0].lower() == "y":
age= input("Are you at least 18 years of age? ")
if age[0].lower() =="n":
print(" You are ineligible to vote in NY.")
if age[0].lower() =="y":
prison = input("Are you currently in prison or on parole for a felony conviction? ")
if prison[0].lower() == "y":
print(" You are ineligible to vote in NY.")
if prison[0].lower() == "n":
mental = input("Are you adjudged mentally incompetent by a court? ")
if mental[0].lower() == "y":
print(" You are ineligible to vote in NY.")
if mental[0].lower() == "n":
location = input("Will you vote or did you vote in another state? ")
if location[0].lower() == "y":
print(" You are ineligible to vote in NY.")
citizen = "no"
if location[0].lower() == "n":
print(" You are eligible to vote in NY. ")
moreinfo = input("Would you like to know more information on your local representatives? ")
citizen = "yes"
if moreinfo[0].lower() == "n":
print(" Have a nice day!")
def rep_find(zipcode):
if citizen == "yes":
numbers = {
"Yvette Clarke":[11203,11218,11210,11226,11212,11213,11215,11216,11217,11225,11226,11229,11230,11233,11234,11235,11236,11238],
"Gregory Meeks":[11411,11412,11413,11419,11420,11422,11423,11429,11430],
"Grace Meng":[11351,11355,11364,11365,11367,11374,11379,11415,11424,],
"John Faso":[12015,12017,12017,12022,12024,12029,12031,12035,12036,12037,12040,12042,12043,12051,12052],
"Nita Lowey":[10503,10510,10511,10514,10517,10520,10522,10523,10532,10533,10535,10545,10546,10547,10548]
}
for rep in numbers:
if zipcode in numbers[rep]:
return("Your local representative is "+rep)
else:
return("Your zipcode is not in our database. Feel free to use this alternative http://www.mygovnyc.org/")
zipcode = int(input(" Please provide your zipcode "))
print(rep_find(zipcode))
#Code debugged by Tyler Robinson
#Code debugged by Nazmul Hoq
|
class Car():
"""Object """
def __init__(self):
self.model = None
self.tires = None
self.engine = None
def __str__(self):
return '{} | {} | {}'.format(self.model, self.engine, self.tires)
class Director:
def __init__(self, builder):
self._builder = builder
def construct_car(self):
self._builder.create_new_car()
self._builder.add_model()
self._builder.add_engine()
self._builder.add_tires()
return self._builder.car;
class Builder:
"""Abstract builder"""
def __init__(self):
self.car = None
def create_new_car(self):
self.car = Car()
def add_model(self): pass
def add_engine(self): pass
def add_tires(self): pass
class ToyotaBuilder(Builder):
"""Concrete builder """
def add_model(self):
self.car.model = 'Toyota'
return self.car
def add_engine(self):
self.car.engine = 'Diesel'
return self.car
def add_tires(self):
self.car.tires = 'Good Year'
return self.car
|
N=float(input('Enter the N value : '))
if N>=0: print('The entered value',N,'is an positive number')
else: print('The entered value',N,'is an not a positive number')
|
import asyncio
import asyncpg
from datetime import date
async def main():
# conn = await asyncpg.connect(
# user='admin1', password='12345678',
# database='demo1', host='127.0.0.1'
# )
conn = await asyncpg.connect(
"postgresql://admin1:12345678@localhost/demo1"
)
## values = await conn.fetch()
# await conn.execute(
# "INSERT INTO users_2(name, birth_date) VALUES($1, $2)",
# "John",
# date(1972, 3, 15),
#
# )
# await conn.execute(
# "INSERT INTO users_2(name, birth_date) VALUES($1, $2)",
# "Ann",
# date(1972, 3, 5),
# )
rows = await conn.fetch("SELECT * FROM users_2;")
today = date.today()
for r in rows:
print(r)
print(r['name'], today - r['birth_date'])
john = await conn.fetchrow("SELECT * FROM users_2 WHERE name = $1", "John")
print(john)
print(conn)
await conn.close()
if __name__ == "__main__":
asyncio.run(main()) |
from collections import namedtuple
from dataclasses import dataclass
@dataclass(frozen=False) #если Ложь, можем менять объекты
class User:
id: int
username: str
is_staff: bool= False
u = User(id=1, username='john')
admin = User(id=42, username='admin', is_staff=True)
print("user", u)
print("admin", admin)
print(admin.is_staff)
|
import csv
def read_csv_cars():
with open('cars.csv') as f:
csv_reader = csv.reader(f, delimiter=',')
lines_count = 0
print("csv_reader:", csv_reader)
for row in csv_reader:
# print(repr(row))
if lines_count == 0:
print("Columns:", " | ".join(row))
else:
# print("values:",', '.join(row))
print(f"Car from {row[0]} by {row[1]} ({row[2]}) [{row[3]}] ${row[4]}")
lines_count += 1
print("Read", lines_count, 'lines.')
def read_csv_cars_to_dict():
with open('cars.csv') as f:
csv_reader = csv.DictReader(f, delimiter=',')
lines_count = 0
print("csv_reader", csv_reader)
for row in csv_reader:
# print(repr(row))
if lines_count == 0:
print("Columns:", " | ".join(row.keys()))
print(f"Car from {row['year']} by {row[' vendor']} ({row[' name']}) [{row[' comment']}] ${row[' price']}")
lines_count += 1
print("Got", lines_count, 'data lines.')
def write_csv_dict():
FIELD_NAME = "name"
FIELD_DEPARTMENT = "department"
FIELD_BM = "birth month"
with open("employee_birth_month.csv", "w") as f:
fieldnames = [
FIELD_NAME,
FIELD_DEPARTMENT,
FIELD_BM,
]
csv_writer = csv.DictWriter(f,
fieldnames=fieldnames,
# delimiter=",",
# quotechar='"',
# quoting=csv.QUOTE_MINIMAL,
)
csv_writer.writeheader()
csv_writer.writerow({
FIELD_NAME : 'John Smith',
FIELD_DEPARTMENT : 'IT Department',
FIELD_BM : 'march',
})
csv_writer.writerow({
FIELD_NAME : 'Ann White',
FIELD_DEPARTMENT : 'Accounting',
FIELD_BM : 'may',
})
#quote chars
csv_writer.writerow({
FIELD_NAME : 'Ann Black',
FIELD_DEPARTMENT : 'Accounting,Management',
FIELD_BM : '',
})
if __name__ == '__main__':
# read_csv_cars()
# print('-'*10)
# read_csv_cars_to_dict()
write_csv_dict() |
#
# @lc app=leetcode id=557 lang=python3
#
# [557] Reverse Words in a String III
#
# @lc code=start
class Solution:
def reverseWords(self, s: str) -> str:
new = ""
split = s.split() # split the words
split_list_reversed = split[::-1]
# print(split_list_reversed)
split_string = " ".join(split_list_reversed)
# print(split_string)
return split_string[::-1]
# for letter in split: # traverse each word in words
# new = letter + " " + new
# new = new.rstrip()
# print(new)
# return "".join(new[::-1])
# @lc code=end
|
# Programmed by Kevin Wallace
# Bioinformatics Assignment 1 part 3
# This program gives you the complimentary DNA strand for a given DNA sequence
# and prints both for the user
DNASequence = "ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT"
#change to lowercase to prevent re replacing what you already changed.
compliment = DNASequence.replace("A","t")
compliment = compliment.replace("T", "a")
compliment = compliment.replace("C","g")
compliment = compliment.replace("G","c")
print "The orignal DNA sequence is %s" % DNASequence
print "The complimentar DNA sequence is %s " % compliment.upper() |
#####################################################
# No code change allowed
#####################################################
import math
import random as rnd
class Stop:
def __init__(self, x, y):
self.x = x
self.y = y
@property
def get_id(self):
return str(self.x) + "-" + str(self.y)
class Road:
def __init__(self, source: Stop, dest: Stop, weight: int = 1):
self.source = source
self.dest = dest
self.weight = weight
@property
def get_source_id(self):
return self.source.get_id
@property
def get_dest_id(self):
return self.dest.get_id
class Maze:
def __init__(self, width=5, height=5):
self.stops = list()
self.roads = list()
self.start = None
self.gold = None
self.generate(width, height)
@staticmethod
def distance_stops(s1: Stop, s2: Stop):
return math.sqrt(math.pow(s1.x - s2.x, 2) + math.pow(s1.y - s2.y, 2))
def generate(self, width=5, height=5):
# Creating stops in __maze
for j in range(0, height):
for i in range(0, width):
stop = Stop(i, j)
self.stops.append(stop)
self.start = self.stops[0]
self.gold = self.stops[rnd.randint(0, len(self.stops) - 1)]
# generate real __maze
unvisited_stops = self.stops.copy()
myStack = []
current = next((x for x in unvisited_stops if x.get_id == self.start.get_id), None)
if current is None:
return self
unvisited_stops.remove(current)
while len(unvisited_stops) > 0:
# finding unvisited neighbors
neighbors = [x for x in unvisited_stops if self.distance_stops(x, current) <= 1 ]
if len(neighbors) == 0:
if len(myStack) <= 0:
return self
# --- Connecting death end
neighborRoads = [x for x in self.roads if current.get_id == x.get_source_id]
neighborRoads.extend([x for x in self.roads if current.get_id == x.get_dest_id])
lastNeighbors = [x for x in self.stops if abs(self.distance_stops(current, x) - 1) < 0.0001]
lastNeighbors = [x for x in lastNeighbors if x.get_id not in [s.get_source_id for s in neighborRoads]]
lastNeighbors = [x for x in lastNeighbors if x.get_id not in [s.get_dest_id for s in neighborRoads]]
lastCount = len(lastNeighbors)
if lastCount > 0 and (lastCount > 2 or rnd.randint(1, 100) < 25):
randStopIdx = rnd.randint(0, len(lastNeighbors) - 1)
nextStop = lastNeighbors[randStopIdx]
self.roads.extend([Road(current, nextStop), Road(nextStop, current)])
# --- end Connecting death end
current = myStack.pop()
continue
randStopIdx = rnd.randint(0, len(neighbors)-1)
nextStop = neighbors[randStopIdx]
self.roads.extend([Road(current, nextStop), Road(nextStop, current)])
myStack.append(current)
current = nextStop
unvisited_stops.remove(current)
|
def print_max(a,b):
if a > b:
print(a," is maximun")
elif a == b:
print(a," is equal to ", b)
else:
print(a," is minimun")
print_max(3,4)
x = 5
y = 5
print_max(x,y)
x = 7
y = 2
print_max(x,y)
|
import math
import itertools
num1 = input('enter number 1\n')
num2 = input('enter number 2\n')
num3 = input('enter number 3\n')
num4 = input('enter number 4\n')
numbers = [int(num1), int(num2), int(num3), int(num4)]
# solution is a brute-force method computing possible permutations, taken from LeetCode
class solution():
def findOps(self, nums):
if len(nums) == 1:
# determines if the end result is close to 24
if (math.isclose(nums[0], 24) == True):
print(nums[0])
return math.isclose(nums[0], 24)
return any(self.findOps([x] + rest)
for a, b, *rest in itertools.permutations(nums)
for x in {a+b, a-b, a*b, b and a/b})
sol1 = solution()
print(sol1.findOps(numbers))
# displaying solution through brute forcing possible results
# I will probably change this into a more elegant solution in the future
class myShittySolution():
def checkNumbers(self, a, b, c, d):
for a, b, c, d in itertools.permutations(numbers, 4):
sa = str(a)
sb = str(b)
sc = str(c)
sd = str(d)
# possible combinations of a,b,c,d
#a + b + c + d
#(a+b) * c + d
#(a+b) * c * d
#
if (a + b + c + d > 23.99999 and a + b + c + d < 24.0000001):
print("solution found: " + sa + " + " +
sb + " + " + sc + " + " + sd)
if ((a+b) * c * d) == 24:
print("solution found: (" + sa + " + " +
sb + ") * " + sc + " * " + sd)
if (((a+b) * c/d) == 24):
print("solution found: (" + sa + " + " +
sb + ") * " + sc + " / " + sd)
if (a * b * c * d == 24):
print("solution found: " + sa + " * " +
sb + " * " + sc + " * " + sd)
if ((a+b+c)*d == 24):
print("solution found: (" + sa + " + " +
sb + " + " + sc + ") + " + sd)
if (a+b+c*d == 24):
print("solution found: " + sa + " + " +
sb + " + " + sc + " * " + sd)
if ((a*b)+(c*d) == 24):
print("solution found: (" + sa + " * " +
sb + ") + " + sc + " * " + sd)
if (a*b+c-d == 24):
print("solution found: " + sa + " * " +
sb + " + " + sc + " - " + sd)
if (a+b+c-d == 24):
print("solution found: " + sa + " + " +
sb + " + " + sc + " - " + sd)
if (a*b-c*d == 24):
print("solution found: " + sa + " * " +
sb + " - " + sc + " * " + sd)
if (a*b*(c-d) == 24):
print("solution found: " + sa + " * " +
sb + " * (" + sc + " - " + sd + ")")
if ((a - b) * c + d == 24):
print("solution found: (" + sa + " - " +
sb + ") * " + sc + " + " + sd)
if (a*b*c+d == 24):
print("solution found: " + sa + " * " +
sb + " * " + sc + " + " + sd)
if (a*b/c+d == 24):
print("solution found: " + sa + " * " +
sb + " / " + sc + " + " + sd)
if (c-d != 0 and a*b/c-d == 24):
print("solution found: " + sa + " * " +
sb + " / " + sc + " - " + sd)
if (c-d != 0 and a*b/(c-d) == 24):
print("solution found: " + sa + " * " +
sb + " / (" + sc + " - " + sd + ")")
if (a*b*c - d == 24):
print("solution found: " + sa + " * " +
sb + " * " + sc + " + " + sd)
if (b-d/c != 0 and a/(b-d/c) > 23.999 and a/(b-d/c) < 24.0001):
print("solution found: " + sa + " / (" +
sb + " - (" + sc + " / " + sd + "))")
if (b/c != 0 and a-(b/c) * d < 24.001 and a-(b/c) * d > 23.99):
print("solution found: " + sa + " - (" +
sb + " / " + sc + ") * " + sd)
if (b/c != 0 and (a-b/c) * d < 24.001 and (a-b/c) * d > 23.99):
print("solution found: (" + sa + " - " +
sb + " / " + sc + ") * " + sd)
print("solution found: " + sa + " * " +
sb + " * (" + sc + " - " + sd + ")")
if ((a - b) * c + d == 24):
print("solution found: (" + sa + " - " +
sb + ") * " + sc + " + " + sd)
if (a*b*c+d == 24):
print("solution found: " + sa + " * " +
sb + " * " + sc + " + " + sd)
if (a*b/c+d == 24):
print("solution found: " + sa + " * " +
sb + " / " + sc + " + " + sd)
if (a*b/c-d == 24):
print("solution found: " + sa + " * " +
sb + " / " + sc + " - " + sd)
if (a*b/(c-d) == 24):
print("solution found: " + sa + " * " +
sb + " / (" + sc + " - " + sd + ")")
sol2 = myShittySolution()
print(sol2.checkNumbers(num1, num2, num3, num4))
|
import collections
import numpy as np
import pandas as pd
import re
from patsy import dmatrices
def movies(filepath):
'''
Converts raw data in movies.dat download file (of form
"<MovieID><Title><MoviePopularity>", as noted in Tag Genome README)
to pandas DataFrame.
Separates movie title and release year into two separate columns for
easier manipulation down the line.
Substitutes `0` for missing years.
Parameters
----------
filepath : .dat file
MovieID, Title (and year), MoviePopularity (i.e., number of
ratings on MovieLens) for movies in MovieLens Tag Genome.
Returns
-------
movies_df : DataFrame
MovieID, NumRatings, and ReleaseYear for movies in
MovieLens Tag Genome. Titles are indices.
'''
movies_df = pd.read_csv(filepath, sep='\t', header=None,
names=['MovieID', 'Title', 'NumRatings'])
release_year = movies_df['Title']
release_year = [year[year.find('(')+1:year.find(')')]
for year in release_year]
release_year = [re.sub('[^0-9]','', year) for year in release_year]
release_year = [int(year) for year in release_year if year != '']
release_year = pd.Series(release_year)
movies_df['ReleaseYear'] = release_year
movies_df['ReleaseYear'] = movies_df['ReleaseYear'].fillna(0)
movies_df['ReleaseYear'] = movies_df['ReleaseYear'].astype(int)
movies_df['Title'] = movies_df['Title'].str[:-6]
titles = movies_df.pop('Title')
movies_df.index = titles
return movies_df
def tags(filepath):
'''
Converts raw data in tags.dat download file (of form
"<TagID><Tag><TagPopularity>", as noted in Tag Genome README)
to pandas DataFrame.
Separates movie title and release year into two separate columns for
easier manipulation down the line.
Parameters
----------
filepath : .dat file
TagID, Tag name, and TagPopularity (i.e., number of taggings on
MovieLens) for tags in MovieLens Tag Genome.
Returns
-------
tags_df : DataFrame
TagID, NumTaggings for tags in MovieLens Tag Genome.
Tags are indices.
'''
tags_df = pd.read_csv(filepath, sep='\t', header=None,
names=['TagID', 'Tag', 'NumTaggings'])
#tag_names = tags_df.pop('Tag')
#tags_df.index = tag_names
return tags_df
def tag_relevance(filepath):
'''
Converts raw data in tag-relevance.dat download file (of form
"<MovieID><TagID><Relevance>", as noted in Tag Genome README)
to pandas DataFrame.
Separates movie title and release year into two separate columns for
easier manipulation down the line.
Parameters
----------
filepath : .dat file
MovieID, TagID, and Relevance (0-1 relevance score for tags)
for movies and tags in MovieLens Tag Genome.
Returns
-------
tag_relevance_df : DataFrame
MovieID, TagID, TagRelevance for movies and tags in MovieLens
Tag Genome.
'''
tag_relevance_df = pd.read_csv(filepath, sep='\t', header=None,
names=['MovieID', 'TagID', 'TagRelevance'])
return tag_relevance_df
def popularity(tags_or_movies_df, top_percent):
'''Sorts tags or movies in a dataframe according to the number of
times each has been tagged or rated. Returns top percent of tags
or movies.
Parameters
----------
tags_or_movies_df : DataFrame
Either the DataFrame of tags or that of movies.
top_percent : float
Decimal percentage of movies or tags to return,
based on popularity.
Returns
-------
by_pop : DataFrame
TagID or MovieID; ReleaseYear; and NumTaggings or NumRatings
for Tags or Titles.
'''
headers = tags_or_movies_df.columns.tolist()
try:
if len(headers) == 2:
by_pop = tags_or_movies_df.sort_values(
'NumTaggings', ascending=False)
print 'Computing top ' + str(cutoff) + ' tags.'
if len(headers) == 3:
by_pop = tags_or_movies_df.sort_values(
'NumRatings', ascending=False)
print 'Computing top ' + str(cutoff) + ' titles.'
cutoff = int(float(len(by_pop)) * top_percent)
by_pop = by_pop[:cutoff]
return by_pop
except Exception:
print 'Input either `movies` or `tags` DataFrame.'
|
"""
Build graph of substrings of texts
For every word:
1) word S=s1s2..sn-1sn creates n-2 words of length 3: w1 = s1s2s3, w2 = s2s3s4,
w3 = s3s4s5, wn-2 = sn-2sn-1sn
2) if word wi is not in graph, it will create
3) for every pair of words (wi, wi+1) add oriented edge of weight = 1, or increase the weight by 1
"""
from typing import Optional, Dict
class Vertex:
def __init__(self, node):
self._id = node
self._adjacent = {}
def __str__(self):
return str(self.id)
def add_neighbor(self, neighbor, weight=1) -> bool:
if neighbor not in self._adjacent:
self._adjacent[neighbor] = weight
return True
else:
self._adjacent[neighbor] += 1
return False
def get_connections(self):
return self._adjacent.keys()
@property
def id(self) -> int:
return self._id
@property
def adjacent(self) -> {}:
return self._adjacent
def get_weight(self, neighbor) -> int:
return self.adjacent[neighbor]
class Graph:
def __init__(self):
self._vert_dict = {}
self._amount_of_edges = 0
self._num_vertices = 0
def __iter__(self):
return iter(self._vert_dict.values())
def add_vertex(self, node) -> Vertex:
if node not in self._vert_dict:
self._num_vertices = self._num_vertices + 1
new_vertex = Vertex(node)
self._vert_dict[node] = new_vertex
return new_vertex
else:
return self._vert_dict[node]
def get_vertex(self, n) -> Optional[Vertex]:
if n in self._vert_dict:
return self._vert_dict[n]
else:
return None
def add_edge(self, frm, to, cost=1) -> None:
if frm not in self._vert_dict:
self.add_vertex(frm)
if to not in self._vert_dict:
self.add_vertex(to)
new_edge = self._vert_dict[frm].add_neighbor(self._vert_dict[to], cost)
if new_edge:
self._amount_of_edges += 1
# self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)
@property
def vert_dict(self) -> Dict[Vertex]:
return self._vert_dict
@property
def num_vertices(self) -> int:
return self._num_vertices
@property
def amount_of_edges(self) -> int:
return self._amount_of_edges
T = int(input())
g = Graph()
for _ in range(T):
s = input()
previous = None
if len(s) > 0:
word = s[0:3]
g.add_vertex(word)
previous = word
for i in range(1, len(s) - 2):
word = s[i:i + 3]
g.add_vertex(word)
g.add_edge(previous, word)
previous = word
print(g.num_vertices)
print(g.amount_of_edges)
vert_dict = g.vert_dict
for vertex in vert_dict.values():
adjacent = vertex.adjacent
for key, value in adjacent.items():
print(str(vertex.id) + " " + str(key) + " " + str(value))
|
def sucesionFibonacci(n):
f0 = 0
f1 = 1
fibonacci=[f0,f1]
for numeros in range(n):
aux = f0 + f1
fibonacci.append(aux)
f0 = f1
f1 = aux
def sucesionPadovan(n):
sucesion = []
for i in range(n):
if i == 0 or i == 1 or i == 2:
sucesion.append(1)
else:
valor = sucesion[-2] + sucesion[-3]
sucesion.append(valor)
return sucesion
|
#Crea una funcion que simule el juego de Piedra, papel o Tijeras
def Piedra_Papel_Tijeras():
jugador1 = input("Jugador 1, ¿Cuál es tu elección?")
jugador2 = input("Jugador 2, ¿Cuál es tu eleccion?")
if jugador1 != jugador2:
if(jugador1 == "piedra" and jugador2 == "tijeras") or (jugador1 == "papel" and jugador2 == "piedra") or (jugador1 == "tijeras" and jugador2 == "papel"):
print("Gana el jugador 1")
else:
print("Gana el jugador 2")
else:
print("Empate")
Piedra_Papel_Tijeras()
|
#crea una funcion que dada una secuencia de numeros devuelva la suma de todos los elementos
def Devuelve_Suma(lista):
return sum(lista)
lista = [2,4,4,5]
print(Devuelve_Suma(lista)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Ctf.pediy.com ctf2017 crackme 2 keygen
# python 3.6.0 32bit
# written by ٺ
# 2017/06/14
import time
def main():
start_time = time.clock()
for sn in range(11111111,100000000):
if check_input(sn) == 1:
if check_answer(sn,calchash(sn)) == 1:
print ('found sn:',str(sn)[::-1])
break
print ('use time: %.3f second' % (time.clock()-start_time))
return
#У8λԸλҪԳƣͼʡ
def check_answer(input1,out1):
input1_str = str(input1)
out1_str = str(out1)
count = len(out1_str) // 2
if len(out1_str) % 2 == 1:
if out1_str[count] == input1_str[7]:
if out1_str[0:7] == input1_str[0:7]:
input1_str = input1_str[::-1]
if out1_str[10:17] == input1_str[1:8]:
return 1
else:
return 0
else:
return 0
else:
return 0
#Ƿ0
def check_input(input2):
input2_str = str(input2)
count1 = 1
while count1 <= len(input2_str):
if input2 % 10 == 0:
return 0
else:
input2 //= 10
count1 += 1
return 1
#ûתΪʮ֮г˷ۼ
def calchash(input):
input_str = str(input)
calchash1 = input * 9
calchash2 = 0
count2 = 1
while count2 <= len(input_str):
calchash2 = calchash2 + calchash1 * (input % 10)
calchash1 *= 10
input //= 10
count2 += 1
calchash2 *= 9
return calchash2
if __name__=="__main__":
main() |
#For the following practice question you will need to write code in Python in the workspace below. This will allow you to practice the concepts discussed in the Scripting lesson, such as reading and writing files. You will see some older concepts too, but again, we have them there to review and reinforce your understanding of those concepts.
#Question: Create a function that opens the flowers.txt, reads every line in it, and saves it as a dictionary. The main (separate) function should take user input (user's first name and last name) and parse the user input to identify the first letter of the first name. It should then use it to print the flower name with the same first letter (from dictionary created in the first function).
#Sample Output:
#>>> Enter your First [space] Last name only: Bill Newman
#>>> Unique flower name with the first letter: Bellflower
# Write your code here
# HINT: create a dictionary from flowers.txt
def flowers_dict(filename):
"""
This function opens the flowers.txt, reads every line in it, and saves it as a dictionary.
"""
flowers = {} #initialize the flowers' dictionary
with open(filename) as f: # open the text file as f.
for line in f: # reads every line in text file.
letter = line.split(": ")[0].lower() # splits the line by ":" and takes the first index i.e letter in lower case
flower = line.split(": ")[1] # splits the line by ":" and takes the second index i.e flower
#print(flower)
flowers[letter] = flower # enters the letter and flower as value pairs in the flowers' dictionary.
return flowers
# HINT: create a function
def main():
"""
The main function as described in the instructions.
"""
flowers = flowers_dict('flowers.txt') # creates the dictionary
full_name = input("Enter your First [space] Last name only: ") # user input
first_name = full_name[0].lower() # takes the first index of the full_name i.e first name.
first_letter = first_name[0] # takes the first letter (index) of the first name.
print("Unique flower name with the first letter: {}".format(flowers[first_letter])) # prints the flower name that matches the first letter
main() # call the main function |
#Multiples of Three
#Use a list comprehension to create a list multiples_3 containing the first 20 multiples of 3.
multiples_3 = [num * 3 for num in range(1,21)]# write your list comprehension here
print(multiples_3)
|
#Write a function named readable_timedelta. The function should take one argument, an integer days, and return a string that says how many weeks and days that is. For example, calling the function and printing the result like this:
#print(readable_timedelta(10))
#should output the following:
#1 week(s) and 3 day(s).
# write your function here
def readable_timedelta(num):
weeks = int(num/7)
days = num%7
result = '{} week(s) and {} day(s).'.format(weeks, days)
return result
# test your function
print(readable_timedelta(10))
|
#Create a numpy array of strings containing letters 'a' through 'j' (inclusive) of the alphabet. Then, use numpy array attributes to print the following information about this array:
#dtype of array
#shape of array
#size of array
#The code you submit in the code editor below will not be graded. Use the results from your code below, along with what you remember from the previous video, to complete the quiz below the code editor.
import numpy as np
# create numpy array of letters a-j
letter_array =
print("Letter Array: ", letter_array)
# get dtype of array
# get shape of array
# get size of array |
#Write a for loop that iterates over the names list to create a usernames list. To create a username for each name, make everything lowercase and replace spaces with underscores. Running your for loop over the list:
#names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
#should create
#usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"]
#HINT: Use the .replace() method to replace the spaces with underscores. Check out how to use this method in this:
#https://stackoverflow.com/a/12723785
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = [] # initializes an empty list for the usernames
# write your for loop here
for name in names:
usernames.append(name.lower().replace(" ", "_")) # converts the names to lowercase and replaces the space in each name to an underscore and appends it to the usernames list.
print(usernames)
|
#Factorials with For Loops
#Now use a for loop to find the factorial!
#It will now be great practice for you to try to revise the code you wrote above to find the factorial of a number, but this time, using a for loop. Try it in the code editor below!
# number to find the factorial of
number = 6
# start with our product equal to one
product = 1
# write your for loop here
for num in range(2, number + 1): # This range returns [2,3,4,..., number]
product *= num # compute the product at each iteration
# print the factorial of number
print(product)
|
# l = ['magical unicorns',19,'hello',98.98,'world']
#
# def typelist(x):
# newlist=[]
#
# for i in range (0, len(x)):
#
# print "The array you entered is integer type"
# print "Sum:", sum(x)
#
#
# typelist([1,2,38,6, "charlie"])
def typeList(x):
# Useage of Int and Str here is great. Consider this, would a simple change in boolean value work better or worse that 0 or not 0? Why or why not?
Int = 0 # False -> flag
Str = 0 # False -> flag
newString = ""
summ = 0
for i in range (0, len(x)):
if type(x[i]) == int or type(x[i]) == float:
Int += 1 # Int = True -> flag change
summ += x[i]
elif type(x[i]) == str:
Str += 1
newString = newString + x[i] + " "
# if Str and Int -> compare flag
if Str > 0 and Int > 0:
print "The array you entered is of mixed type"
print "String:", newString
print "Sum:", summ
elif Str > 0:
print "The array you entered is of string type"
print "string:", newString
else:
print "The array you entered is of integer type"
print "Sum:", summ
typeList(['magical unicorns',19,'hello',98.98,'world'])
|
#Multiples
#Part 1
for odds in range (1,1000,2):
print odds
#Part 2
x = 5
while x < 1000005:
print x
x = x + 5
#Sum list & Average List
a = [1, 2, 5, 10, 255, 3]
b = sum(a) / len(a)
print sum(a)
print b
|
for e in range (0,10):
if e % 2 == 0:
print("*" + " " + "*" + " " + "*" + " " + "*" + " " + "*")
else:
print (" " + "*" + " " + "*" + " " + "*" + " " + "*" + " "+ "*")
tupl = (2,99,0,5,5)
print tuple(enumerate(tupl))
capitals = {} #create an empty dictionary then add values
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"
print capitals
for data in capitals:
print data
for key in capitals.itervalues():
print key
friends = ["Erin", "Faith", "Rachel", "Katrina"]
last_names = ["Fuhr", "Carter", "Abrego", "Keay"]
friend_names = zip(friends, last_names)
print friend_names
friend_names_dict = dict(friend_names)
print friend_names_dict
|
#
# counter = 0
# x = [1,2,5,6,5,16]
# y = [1,2,5,6,5,16]
#
# for i in range (0, len(x)):
# if x[i] == y[i]:
# counter = counter + 1
# if counter == len(y):
# print "The lists are the same"
# else:
# print "The lists are different"
#
#############################################################
# Consider what each line of code is doing in this function.#
# Write short comments in your code! #
#############################################################
def compareArray(x,y):
counter = 0
# before you run a for loop, could you write a quick fail that quickly checks if list lenghts are different? If they are different would that mean that the lists are not the same?
for i in range (0, len(x)):
# for each iteration, compare the values at x and y and sub i, are the lengths going to change on each iteration?
if x[i] == y[i] and len(x) == len(y):
counter = counter + 1
if counter == len(y): # would the quick fail you write above your for loop make it so that you don't need a counter?
print "The lists are the same"
else:
print "The lists are different"
compareArray([1,2,5,6,5,3],[1,2,5,6,5,3]
)
|
import unittest
class Histogram:
def draw(self,size):
return '*'*size
def draw_list(self,sizes):
histogram = []
for size in sizes:
row = self.draw(size)
histogram.append(row)
return histogram
class Test_Histogram(unittest.TestCase):
def draw_histogram(self,number):
histo = Histogram()
return histo.draw(number)
def draw_histogram_list(self,numbers):
histo_list = Histogram()
return histo_list.draw_list(numbers)
def test_given_3_then_draw_3_symbols(self):
draw_value = self.draw_histogram(3)
self.assertEqual(draw_value, "***")
def test_given_list_then_draw_list_symbols2(self):
sizes = [4,7]
draw_histogram = self.draw_histogram_list(sizes)
self.assertEqual(len(draw_histogram),len(sizes))
if __name__ == '__main__':
unittest.main()
|
import sys
"""
파괴되지 않은 건물
https://programmers.co.kr/learn/courses/30/lessons/92344?language=python3
"""
def solution(board, skill):
answer = 0
R, C = len(board), len(board[0])
mat = [[0] * (C + 1) for _ in range(R + 1)]
for s in skill:
type, r1, c1, r2, c2, degree = map(int, s)
if type == 1:
mat[r1][c1] -= degree
mat[r2 + 1][c2 + 1] -= degree
mat[r1][c2 + 1] += degree
mat[r2 + 1][c1] += degree
else:
mat[r1][c1] += degree
mat[r2 + 1][c2 + 1] += degree
mat[r1][c2 + 1] -= degree
mat[r2 + 1][c1] -= degree
for r in range(0, R + 1):
for c in range(1, C + 1):
mat[r][c] += mat[r][c - 1]
for c in range(0, C + 1):
for r in range(1, R + 1):
mat[r][c] += mat[r - 1][c]
for r in range(R):
for c in range(C):
board[r][c] += mat[r][c]
if board[r][c] > 0:
answer += 1
return answer
board = [[5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5]]
skill = [[1, 0, 0, 3, 4, 4], [1, 2, 0, 2, 3, 2], [2, 1, 0, 3, 1, 2], [1, 0, 1, 3, 3, 1]]
print(solution(board, skill))
|
import requests
# getting user input for link
print("Enter Url to be shortened")
url = input()
# hiding my api key use provided executable file for testing
api_key = "my api key"
# using cuttly api with key and given url to make shortened link
api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}"
# response is given as json
response = requests.get(api_url).json()["url"]
# various error checking if link is not valid
if response["status"] == 7:
print("Shortened URL is: ", response["shortLink"])
elif response["status"] == 2:
print("Error link is incorrect")
elif response["status"] == 1:
print("Error link is already shortened")
else:
print("error")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def solve(a, b, c):
return tuple([(a*i+b)%c for i in range(6)]) == (0, 4, 2, 5, 3, 1)
def go():
for c in range(1, 20000):
print(c)
for a in range(0, c):
for b in range(0, c):
if solve(a, b, c):
print(a, b, c)
return
go()
|
def add(a,b):
return a+b
def evenList(a):
l=[]
for i in range(1,a):
if i%2==0:
l.append(i)
return l |
# -*- coding: utf-8 -*-
skritoStevilo = 8
vnos = 0
konec = False
nadaljevanje = True
budget = int(raw_input("Vnesi koliko denarja želš porabiti. Za vsako igro avtomat pobere 1\xe2\x82\xac: "))
while budget != 0 and konec != True:
while (vnos != skritoStevilo and konec != True):
budget = budget - 1
vnos = int(raw_input("Vnesi skrito število: "))
if vnos == skritoStevilo:
print ("Čestitke zadeli ste 20\xe2\x82\xac!")
konec = True
break
elif vnos != skritoStevilo:
print "Ni bilo zadetka"
while nadaljevanje == True:
if (budget > 0):
print "Imate še " + str(budget) + "\xe2\x82\xac"
nadaljuje = str(raw_input("Želite nadaljevati (Da/Ne): ")).upper()
if nadaljuje == "NE":
print ("Vračamo vam preostanek denarja: " + str(budget) + "\xe2\x82\xac")
print ("Nasvidenje")
nadaljevanje = False
konec = True
break
elif nadaljuje == "DA":
break
elif budget == 0:
print "Porabili ste denar! Lep dan se naprej!"
nadaljevanje = False
konec = True
break
print "Napačen ukaz! Ali želiš nadaljevati (Da/Ne)"
|
import pdftotext
# Load your PDF
with open("Untitled.pdf", "rb") as f:
pdf = pdftotext.PDF(f)
# # If it's password-protected
# with open("secure.pdf", "rb") as f:
# pdf = pdftotext.PDF(f, "secret")
# How many pages?
print(len(pdf))
# Iterate over all the pages
for page in pdf:
print(page)
|
def print_progress(cur, tol, _l=20):
"""
小工具打印进度
cur 现在进行了多少
tol 一共有多少
_l 进度条长度默认20
使用:
if __name__ == '__main__':
lis = range(777)
for i in lis:
print_progress(i, len(lis))
time.sleep(0.01)
print_progress(1, 1)
print('next')
"""
print(f"\r|{''*(int((cur/tol)*_l))}{' '*(_l-int((cur/tol)*_l))}|{cur/tol*100:.2f}%", end='\n'if cur == tol else'')
if __name__ == '__main__':
import time
for i in range(100):
print_progress(i, 100)
time.sleep(0.1)
print_progress(1, 1)
|
#! /usr/bin/env python2
def robot_move(moves):
moves = [('N', 2), ('E',4), ('S', 1), ('W', 3)]
x = 0
y = 0
for move in moves:
if move[0] == "N":
y = y + move[1]
if move[0] == "S":
y = y - move[1]
if move[0] == "E":
x = x + move[1]
if move[0] == "W":
x = x - move[1]
return(x, y)
|
def sum_of_divisible_naturals(limit):
total = 0
for n in range(1, limit):
if n % 3 == 0 or n % 5 == 0:
total = total + n
return total
if __name__ == '__main__':
print(sum_of_divisible_naturals(1000))
|
def sort(l):
if len(l) > 1:
mid = len(l) // 2
left_list = l[:mid]
right_list = l[mid:]
sort(left_list)
sort(right_list)
i, j, k = 0, 0, 0
while i < len(left_list) and j < len(right_list):
if left_list[i] <= right_list[j]:
l[k] = left_list[i]
i += 1
else:
l[k] = right_list[j]
j += 1
k += 1
while i < len(left_list):
l[k] = left_list[i]
i += 1
k += 1
while j < len(right_list):
l[k] = right_list[j]
j += 1
k += 1
return l
|
import math
import random
from lib_randomgraph import RandomGraph
from lib_heap import Heap
def main():
graph = RandomGraph('Gnp', 20, edge_spec=.5)
print(graph)
budget = 40
nodes, value = spanning_tree(graph, budget)
print('selected nodes ', nodes)
print('total value ', value)
def prim_MST(graph, budget, node_set):
"""Runs Prim's algorithm to find a maximum spanning tree (MST).
Four modifications to standard minimum spanning tree:
1) Edge weights are negated to go from minimum to maximum ST
2) Node value is added to edge weight for consideration of candidate edges
3) The value of the MST is not its length but the sum of all node values plus the sum of all edge values of edges between those nodes, including edges that are additional to the spanning tree
4) The algorithm terminates if there are only nodes left that would have a negative impact on the current solution, i.e., infer a cost. Such termination might be preliminary, since addition of future (bad) nodes might be worthwhile due to complementarity effects.
Args:
s (int): Index of starting node
Returns:
tuple (set, int): ({node IDs in MST}, value of MST)
"""
node_list = list(node_set)
s = random.choice(node_list)
val_s = -graph.node_weights[s][1] + graph.node_weights[s][0] # value of starting node
value = 0 # MST value
cost = 0 # MST cost
compensation = 0 # compensation for edges that are counted twice
prev = [0]*graph.size
dist = [math.inf]*graph.size
S = set()
H = Heap(graph.size)
H.insert(s, val_s, 0)
dist[s] = val_s
for v in range(graph.size):
H.insert(v, math.inf, 0)
while H.size > 0:
v = H.delete_min()
if v[1] > 0: # min in Heap is of positive value, i.e., a cost, abort
break
# abort if out of budget
cost += graph.node_weights[v[0]][0]
if cost > budget:
MST_value = -(value-compensation)
return S, MST_value, cost-graph.node_weights[v[0]][0]
# complementarity
for node in S:
for adjacent in graph.graph[node]:
if adjacent[0] == v[0]:
value -= adjacent[1]
S.add(v[0])
value += v[1]
compensation += v[2] # necessary since edge weight was added to node quality already
for adj, weight in graph.graph[v[0]]:
if not adj in S:
if dist[adj] > weight:
d = -weight - graph.node_weights[adj][1] + graph.node_weights[adj][0] # negate for maximum spanning tree
if d > 0: # bad/costly node # perhaps try d > 6
continue
dist[adj] = d
comp = -weight
prev[adj] = v[0]
H.decrease_key(adj, dist[adj], comp)
MST_value = -(value-compensation)
del H
# print('return', S, MST_value, cost)
return S, MST_value, cost
def spanning_tree(graph, budget):
remaining_budget = budget
value = 0
nodes = set()
node_set = set(range(graph.size))
# 6 because currently max cost of a node
# Florian: imagine you have less than that money left but still nodes
# that cost more than that. you would never terminate
while node_set and remaining_budget >= max([graph.node_weights[node][0] for node in node_set]):
MST_nodes, MST_value, MST_cost = prim_MST(graph, remaining_budget, node_set)
value += MST_value
nodes.update(MST_nodes)
node_set -= MST_nodes
remaining_budget -= MST_cost
# LILY NOTE: had to comment this out. otherwise, MST was not reaching optimal with high budget
# if len(MST_nodes) == 0:
# break
return (nodes, value)
if __name__ == '__main__':
main()
'''
# start with most promising node
best_val = -math.inf
best_ind = -math.inf
for ind, weight in enumerate(graph.node_weights):
current_val = weight[1] - weight[0]
if current_val > best_val:
best_val = current_val
best_ind = ind
'''
|
import csv
import time
import sys
import math
from datetime import time
def get_csv():
with open("data.csv", 'r') as csvfile:
# opening reader
reader = csv.reader(csvfile, delimiter = ',')
# read into list
data = []
for row in reader:
data.append(row)
# return the data
return data
# creates a datetime object
def get_datetime(data_str):
vals = data_str.split()
#get time string
time_str = vals[1]
# create datetime object
hour = int(time_str[:2])
minute = int(time_str[3:5])
second = int(time_str[6:8])
millisecond = int(time_str[9:])
# return time object
return time(hour, minute, second, millisecond)
# gets standard deviation, sum of squares and creats a 95% confidence interval for distance
def std_dev(mean, data, count):
differences = []
mean_square = 0
for x in data:
if x is -1:
continue
differences.append((mean - x)**2)
for x in differences:
mean_square += x
print("SUM OF SQUARES | ", round(mean_square, 2))
dev = math.sqrt(mean_square)
print("STANDARD DEVIATION | ", round(dev, 2))
dev *= 2
print("95% CONFIDENCE INTERVAL | (", round(mean - dev, 2), ", ", round(mean + dev, 2), ")")
return
def main():
print("[GETTING CSV FILE]\n")
# Data section
data = get_csv()
time_variables = []
distance_variables = []
mean = 0
for dt in data:
# get time object
time_variables.append(get_datetime(dt[1]))
distance_variables.append(float(dt[0]))
count = len(distance_variables)
for x in distance_variables:
if x == -1:
count -= 1
continue
mean += x
mean /= count
print("DATA\n----------------")
print("DISTANCE MEAN | ", round(mean, 3))
std_dev(mean, distance_variables, count)
print("NUMBER OF USABLE DATA POINTS | ", count)
print("\nFINISHED\n----------------")
# parse into separate data objects
if __name__ == "__main__":
main()
|
class Bodybuilder:
"""
This builds a bodybuilder class.
A bodybuilder has a name, weighs certain amount of pounds
,and attends a certain gym.
"""
def __init__(self, name, weight, gym):
self.name = name
self.weight = weight
self.gym = gym
# a bodybuilder can add, maintain or lose weight
def add_lose_weight(self, new_weight):
added_weight = new_weight - self.weight
if new_weight>self.weight:
return f'{self.name} added a weight of {added_weight} pounds.'
elif new_weight==self.weight:
return f'{self.name} maintained weight.'
else:
return f'{self.name} lost a weight of {added_weight} pounds.'
# This is the string representation of the class
def __str__(self):
return f'Name: {self.name} \nWeight:{self.weight} pounds \nGym Attending: {self.gym}' |
from random import randint
class tickets():
def __init__(self):
self.holders ={}
def Purchase_ticket (self,Name,Category):
self.ticket_num =randint(10000,99999)
self.Name= Name
if Category=="1":
print("You have to pay $100 for VIP")
self.price=100
self.rank="VIP"
self.holders[self.ticket_num] = [self.price, self.Name, self.rank]
elif Category=="2":
print("You have to pay $50 for Gold")
self.price= 50
self.rank ="Gold"
self.holders[self.ticket_num] = [self.price, self.Name, self.rank]
elif Category== "3":
print("You have to pay $30 for Regular")
self.price =30
self.rank ="Regular"
self.holders[self.ticket_num] = [self.price, self.Name, self.rank]
print(Name,"your ticket no. is ",self.ticket_num,"and is of type:",self.rank,"")
def authenticate(self,name,ticket_number):
if ticket_number in self.holders.keys():
if self.holders[ticket_number][1]==name:
print("you are allowed to enter")
return True
else:
print("You are not allowed!!!")
return False
else:
print("You are not allowed!!!")
return False
def upgrade(self,ticket_number,new_price,new_rank):
if new_price<=self.holders[ticket_number][0]:
print("You cant downgrade your ticket")
else:
print("You have to pay ",new_price-self.holders[ticket_number][0],"more")
self.holders[ticket_number][0] = new_price
self.holders[ticket_number][2] = new_rank
def check_status(self,ticket_number):
print("You have purchased",self.holders[ticket_number][2])
client1 = tickets()
while True:
ans=input("To buy press 1 or press 2 to enter or 3 to upgrade/check status or any other key to exit: ")
if ans =="1":
nam=input("Enter your name: ").title()
Cat=input("Press 1 to buy Vip , 2 for Gold or 3 for regular: ")
client1.Purchase_ticket(nam,Cat)
elif ans =="2":
chk_nam =input("Enter your name: ").title()
chk_tckt =int(input("Enter your ticket no."))
client1.authenticate(chk_nam,chk_tckt)
elif ans== "3":
chk_nam = input("Enter your name: ").title()
chk_tckt = int(input("Enter your ticket no.: "))
if client1.authenticate(chk_nam, chk_tckt):
client1.check_status(chk_tckt)
upgrade_rank=input("Press 1 for Gold, 2 for VIP or 3 for exit: ")
if upgrade_rank=="1":
client1.upgrade(chk_tckt,50,"Gold")
continue
elif upgrade_rank== "2":
client1.upgrade(chk_tckt,100,"VIP")
continue
elif upgrade_rank=="3":
exit()
else:
print("Invalid Input!!")
pass
else:
print("You are not authorized")
continue
else:
exit()
|
def team_olympiad():
n = int(input())
members = [int(x) for x in input().split(' ')]
programming = []
maths = []
pe = []
for i, member in enumerate(members):
if member == 1:
programming.append(i + 1)
if member == 2:
maths.append(i + 1)
if member == 3:
pe.append(i + 1)
min_number_of_possible_teams = min(len(programming), len(maths), len(pe))
if min_number_of_possible_teams:
print(min_number_of_possible_teams)
for i in range(min_number_of_possible_teams):
print(f'{programming[i]} {maths[i]} {pe[i]}')
else:
print(0)
if __name__ == '__main__':
while True:
team_olympiad()
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root: TreeNode, min_depth=0) -> int:
if not root:
return 0
queue = []
queue.append(root)
while queue:
min_depth += 1
count = len(queue)
while count:
temp = queue.pop()
if temp.right:
queue.insert(0, temp.right)
if temp.left:
queue.insert(0, temp.left)
if not (temp.right or temp.left):
queue.clear()
count = 1
count -= 1
return min_depth
t1 = TreeNode(1)
t2 = TreeNode(2)
t3 = TreeNode(2)
t1.left = t2
t1.right = t3
t4 = TreeNode(3)
t5 = TreeNode(3)
t2.left = t4
t2.right = t5
t6 = TreeNode(3)
t7 = TreeNode(3)
t3.left = t6
t3.right = t7
t8 = TreeNode(4)
t9 = TreeNode(4)
t10 = TreeNode(4)
t11 = TreeNode(4)
t12 = TreeNode(4)
t13 = TreeNode(4)
t4.left = t8
t4.right = t9
t5.left = t10
t5.right = t11
t6.left = t12
t6.right = t13
t14 = TreeNode(5)
t15 = TreeNode(5)
t16 = TreeNode(5)
t7.left = t14
t14.right = t15
t15.right = t16
# t6.right = None
sol = Solution()
print(sol.minDepth(t1))
|
import collections
class HashSolution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
char_hash = {}
for char in s:
if char not in char_hash:
char_hash[char] = 1
else:
char_hash[char] += 1
for char in t:
if char not in char_hash or not char_hash[char]:
return False
else:
char_hash[char] -= 1
return True
# sol = HashSolution()
# print(sol.isAnagram('anagram', 'nagaram'))
class HashSolutionWithCounter:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return collections.Counter(list(s)) == collections.Counter(list(t))
class ArraySolution:
def isAnagram(self, s: str, t: str) -> bool:
arr = [0] * 26
for char in s:
arr[ord(char) - 97] += 1
for char in t:
if arr[ord(char) - 97] == 0:
return False
else:
arr[ord(char) - 97] -= 1
return len(s) == len(t)
# print(ord('z'))
|
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 insertNewNode(self, head: TreeNode, newNode: TreeNode):
if newNode.val < head.val:
if head.left:
self.insertNewNode(head.left, newNode)
else:
head.left = newNode
else:
if head.right:
self.insertNewNode(head.right, newNode)
else:
head.right = newNode
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
head = TreeNode(preorder[0])
for val in preorder[1:]:
self.insertNewNode(head, TreeNode(val))
return head |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def __init__(self):
self.nodes = []
def swapTailWithNext(self, current: ListNode, oddNext: ListNode, oddTail: ListNode):
next_of_current = current.next
current.next = oddNext
if next_of_current:
next_of_current.next = oddTail.next
oddTail.next = next_of_current
def sortOddEven(self, head: ListNode):
if head.next and head.next.next:
self.sortOddEven(head.next.next)
else:
self.nodes = [head, head]
return
self.swapTailWithNext(head, self.nodes[0], self.nodes[1])
self.nodes[0] = head
return
def oddEvenList(self, head: ListNode):
if not head:
return head
self.sortOddEven(head)
return self.nodes[0]
class Solution2:
def oddEvenList(self, head: ListNode) -> ListNode:
temp_odd = ListNode(0)
temp_even = ListNode(0)
oddHead = temp_odd
evenHead = temp_even
isOdd = True
while head:
if isOdd:
temp_odd.next = head
temp_odd = head
else:
temp_even.next = head
temp_even = head
isOdd = not isOdd
head = head.next
temp_even.next = None
temp_odd.next = evenHead.next
return oddHead.next
temp = None
for i in range(6, 0, -1):
node = ListNode(i, temp)
temp = node
Head = temp
# while temp:
# print(temp.val)
# temp = temp.next
sol = Solution2()
odd_even = sol.oddEvenList(Head)
while odd_even:
print(odd_even.val)
odd_even = odd_even.next
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.diameter = 0
def diameterOfBinaryTree(self, root: TreeNode, is_root=True) -> int:
if not root:
return 0
if is_root:
self.diameter = 0
left_length = 0
right_length = 0
if root.left:
left_length = self.diameterOfBinaryTree(root.left, False) + 1
if root.right:
right_length = self.diameterOfBinaryTree(root.right, False) + 1
if left_length + right_length > self.diameter:
self.diameter = left_length + right_length
if is_root:
return self.diameter
return max(left_length, right_length)
sol = Solution()
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n1.left = n2
n1.right = n3
#
n4 = TreeNode(4)
n5 = TreeNode(5)
#
n2.left = n4
n2.right = n5
#
n6 = TreeNode(6)
n7 = TreeNode(7)
n4.left = n6
n6.left = n7
#
n8 = TreeNode(6)
n9 = TreeNode(7)
n5.right = n8
n8.right = n9
#
# n31 = TreeNode(31)
# n32 = TreeNode(31)
# n3.right = n31
# n31.right = n32
print(sol.diameterOfBinaryTree(n1))
|
# Find a sequence of transpositions of letters that transform
# the sequence MARINE (letters are numbered 0..5) to the sequence AIRMEN.
# Transpositions are represented by pairs of integers. For example, the pair (0,1) transforms MARINE to AMRINE.
# Transpositions are performed from left to right.
# You should define the sequence by writing something like
# this (the dots should be replaced by numbers, each pair in parentheses specifies one permutation,
# and these permutations are performed sequentially, from left to right):
# def sequence():
# return [(...,...),..., (...,...)]
def sequence(from_phrase='MARINE', to_phrase="AIRMEN"):
to_phrase_dict = {x: i for i, x in enumerate(to_phrase)}
seq = []
from_phase_arr = list(from_phrase)
pointer = 0
while ''.join(from_phase_arr) != to_phrase:
if pointer == len(from_phrase):
pointer %= len(from_phrase)
swap_with_index = to_phrase_dict[from_phase_arr[pointer]]
if swap_with_index != pointer:
from_phase_arr[swap_with_index], from_phase_arr[pointer] = from_phase_arr[pointer], from_phase_arr[
swap_with_index]
for i in range(pointer, swap_with_index):
seq.append((i, i+1))
for i in range(swap_with_index-1, pointer, -1):
seq.append((i, i-1))
pointer += 1
return seq
print(sequence())
|
import re
def hey(phrase):
stripped = phrase.strip()
if not stripped:
return "Fine. Be that way!"
question = __is_question(stripped)
shouting = __is_shouting(stripped)
if question and shouting:
return "Calm down, I know what I'm doing!"
elif question:
return "Sure."
elif shouting:
return "Whoa, chill out!"
else:
return "Whatever."
def __is_shouting(phrase):
return (bool(re.match(r'[A-Z\s\W\d]+\Z', phrase)) and
bool(re.search(r'[A-Z]', phrase)))
def __is_question(phrase):
return bool(re.match(r'.*\?\Z', phrase))
|
import math
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Square(Shape):
def __init__(self, length = 0):
self.length = length
def area(self):
return self.length ** 2
def perimeter(self):
return self.length * 4
def message(self):
print ('This is a Square class')
class Circle(Shape):
def __init__(self,radius = 0):
self.radius = radius
def area(self):
return math.pi*(self.radius**2)
def perimeter(self):
return 2*math.pi*self.radius
def message(self):
print ('This is a Circle class')
if __name__ == "__main__":
new_square = Square(5)
new_square.message()
print('perimeter:',new_square.perimeter())
print('area:',new_square.area())
new_circle = Circle(8)
new_circle.message()
print('perimeter:',new_circle.perimeter())
print('area:',new_circle.area()) |
class Chat:
chat_room = []
robot_text = ''
human_text = ''
counter = 0
conversation = {}
def connect_human(self,human):
self.human_name = human.name
self.chat_room.append(self.human_name)
def connect_robot(self, robot):
self.robot_name = robot.name
self.chat_room.append(self.human_name)
def show_human_dialogue(self):
for key, value in self.conversation.items():
if 'H' in key:
print(self.human_name + " said: "+ value)
else:
print(self.robot_name + " said: "+ value)
def show_robot_dialogue(self):
new_val = ''
for key, value in self.conversation.items():
for char in value:
if char in 'aeouiAEOUI':
new_val += '0'
else:
new_val += '1'
if 'H' in key:
print(self.human_name + " said: "+ new_val)
else:
print(self.robot_name + " said: "+ new_val)
new_val = ''
class Human(Chat):
def __init__(self, name):
self.name = name
def send(self, message):
Chat.conversation['H'+str(Chat.counter)] = message
Chat.counter += 1
class Robot(Chat):
def __init__(self, name):
self.name = name
def send(self, message):
Chat.conversation['R'+ str(Chat.counter)] = message
Chat.counter += 1
chat = Chat()
majd = Human('MAJD')
bot = Robot('R2D2')
chat.connect_human(majd)
chat.connect_robot(bot)
majd.send('Hello Im Majd')
majd.send('24 years old')
bot.send('Im the robot')
majd.send('I dont care')
bot.send('why?')
print('Human Dialogue:\n---------')
chat.show_human_dialogue()
print('\n')
print('Robot Dialogue:\n---------')
chat.show_robot_dialogue() |
class Person(object):
def __init__(self, education, name):
self. education = education
self.name = name
def work(self):
print("%s goes to work." % self.name)
print("%s has a %s education." % (self.name, self.education))
class Employee(Person):
def __init__(self, education, name, uniform):
super(Employee, self).__init__(education, name)
self.uniform = uniform
def reads(self):
print("%s can read an article." % self.name)
print("%s wears a %s uniform." % (self.name, self.uniform))
print("%s has a %s education." % (self.name, self.education))
class Programmer(Employee):
def __init__(self, computer, uniform, name, education):
super(Programmer, self).__init__(education, name, uniform)
self.computer = computer
def types(self):
print("%s is typing on a %s." % (self.name, self.computer))
print("%s wears a %s uniform." % (self.name, self.uniform))
print("%s has a %s education." % (self.name, self.education))
programmer1 = Programmer('Surface Pro', 'dress', 'Sophia', 'college')
employee1 = Employee('high school', 'Robert', 'shirt and jeans')
person1 = Person('college', 'Charles the 23rd')
print("This is the programmer:")
programmer1.types()
print('')
print("This is the employee:")
employee1.reads()
print('')
print("This is the person:")
person1.work()
|
import itertools
def reachable_states(uso):
"""
Given a set of edges and a start state, return list of reachable states.
"""
reach = set([uso.start_state])
for i in range(uso.k - 1):
reach.update(q2 for ((q1, a), (q2, b)) in uso.table.iteritems() if q1 in reach)
return reach
def hopcroft_fingerprint(uso):
"""
Produce a fingerprint of an uso based on a variant of Hopcroft's algorithm.
States are first split into even and odd, then iteratively into more refined classes depending on their
own class and the class of their neighbors. At each point, those classes form an equivalence relation
on the set of states, and if the transducer is minimal, each state will be in its own class after k-1
iterations.
The purpose of the original hopcroft algorithm is to test whether an automaton is minimal. However,
writing a (size n^2) log of the process according to a standardised format (lexical ordering of classes)
produces a unique fingerprint for each transducer.
The only failure mode is when comparing transducers with a different number of states. This is
remedied by rejecting all transducers that are not minimal with a dummy fingerprint (the empty string).
"""
# doesn't work if there are unreachable states, as the ordering of those can be different and won't
# be taken into account
if len(reachable_states(uso)) < uso.k:
return ""
# initially, separate states by their parities
class_index = {"+": "0", "-": "1"}
state_index = dict((q, class_index[uso.table[q, "0"][1]]) for q in uso.states)
for i in range(max(1, uso.k)):
# assign a class triple to each state, namely the class of the state itself, of its
# 0-neighbor and of its 1-neighbor
state_lst = [(q, (state_index[q], state_index[uso.table[q, "0"][0]], state_index[uso.table[q, "1"][0]]))
for q in uso.states]
# assign an index to each class (basically a reverse lookup of the list of classes)
# the order doesn't matter, as we're only interested in whether or not there are redundant states
classes = set(c for (state, c) in state_lst)
class_index = dict((c, str(i)) for (i,c) in enumerate(classes))
# assign to each state the index of its class
state_index = dict((q, class_index[c]) for (q, c) in state_lst)
if len(classes) < uso.k:
# transducer can be realized with fewer states, return dummy fingerprint
return ""
# build the FST
edges = []
indices = {}
new_index = (str(i) for i in itertools.count()).next
def DFS(q):
i = new_index()
indices[q] = i
q_left, b_left = uso.table[q, "0"]
q_right, b_right = uso.table[q, "1"]
if q_left not in indices:
DFS(q_left)
if q_right not in indices:
DFS(q_right)
edges.extend(( (i, "0", b_left, indices[q_left]), (i, "1", b_right, indices[q_right]) ))
DFS(uso.start_state)
# edges are fine and good, but the fingerprint can be more compact
#return tuple(edges)
return "".join("".join(edge[2:] if i%2 else edge)
for (i, edge) in enumerate(edges))
return "".join("".join(e) for e in edges)
def uniq(usos, quiet=False):
"""
Take an uso iterator, and produce an iterator that filters out repeated usos.
"""
test = set([""])
count = 0
uniq_count = 0
if not quiet:
print " #Total #Uniq"
for uso in usos:
count += 1
if (not quiet) and (not count % 1000):
print "%8d %8d" % (count, uniq_count)
fingerprint = hopcroft_fingerprint(uso)
if fingerprint in test:
continue
test.add(fingerprint)
uniq_count += 1
yield uso
if not quiet:
print "%8d %8d" % (count, uniq_count)
|
#######################Happy Numbers##########################
# #
# square each digit, then add the results together #
# repeat with new number until reduced to single digit #
# if single digit is 1, then number is happy #
# #
##############################################################
def Recycler():
for Integer in range(10001):
IntegerList = SplitInteger(Integer)
HappyCheck = SquareInteger(IntegerList)
DisplayHappiness(Integer, HappyCheck)
def SplitInteger(Integer):
IntegerString = str(Integer)
# print(IntegerString)
IntegerList = list(IntegerString)
# print(IntegerList)
return IntegerList
def SquareInteger(IntegerList):
Total = 0
for Squares in IntegerList:
Total += int(Squares)**2
HappyCheck = RecheckTotal(Total)
# print("sqint",HappyCheck)
if HappyCheck == True:
return HappyCheck
def RecheckTotal(Total):
TotalString = str(Total)
IntegerList = list(TotalString)
HappyCheck = None
# print(len(IntegerList))
# print(IntegerList)
if len(IntegerList) > 1:
HappyCheck = SquareInteger(IntegerList)
if len(IntegerList) == 1 and IntegerList[0] == "1":
HappyCheck = True
# print("Happy")
# print("rechecktotal",HappyCheck)
return HappyCheck
def DisplayHappiness(Integer, HappyCheck):
if HappyCheck == True:
print(Integer,"is Happy")
def RunCode():
Recycler()
##############################################################
RunCode() |
from collections import Counter
from random import choice
class hangman_solver:
all_words = dict() #Sorted by length
min_len = 3
max_len = 3
used_letters = set() #Set of letters that are not in the word
pattern = []
game_over = False
alphabet = set('abcdefghijklmnopqrstuvwxyz')
def __init__(self, dict_path):
raw_word_list = []
with open(dict_path, 'r') as f:
for word in f:
if len(word) >= self.min_len:
raw_word_list.append(word.strip())
if len(word) > self.max_len:
self.max_len = len(word)
# print raw_word_list
print 'Max length is', self.max_len
for x in range(self.min_len, self.max_len + 1):
words = set([word.lower() for word in raw_word_list if len(word) == x])
self.all_words[x] = words
def begin_solving(self, length):
self.word_set = self.all_words[length]
self.pattern = '_' * length
while (1):
self.word_set = self.find_possible_words(self.pattern, self.used_letters, self.word_set)
next_letter = self.get_next_letter(self.word_set, self.used_letters)
print 'Guessed letter:',next_letter
self.used_letters.add(next_letter)
#raw_input()
yield self.pattern, next_letter
self.pattern = (yield)
print 'New pattern =', self.pattern
def get_next_letter(self, word_set, used_letters):
'''
Builds the table of letter frequency to letter given a set of words.
Letter frequency refers to how many possible words contain the letter.
E.g.
Possible words = 'element',
'letters',
'acrobat'
freq('l') = 2
freq('t') = 3
freq('z') = 0
Returns letter with highest frequency
'''
if len(word_set) == 0:
unused_letters = list(set(self.alphabet).difference(used_letters))
ret = choice(unused_letters)
else:
letter_count = Counter()
for word in word_set:
letter_count += Counter(set(word))
# c = letter_count.most_common()
result = 0
ret = ''
for key,value in letter_count.iteritems():
if value > result and key not in used_letters:
result = value
ret = key
#print key,':',value
return ret
# return c[0][0]
def find_possible_words(self, pattern, used_letters, word_set):
'''
Find all remaining possible words, by filtering out words which
- don't match the currently known pattern
- contain a wrong letter
Returns set of words.
'''
q = set()
#print word_set
print 'Finding words...'
for word in word_set:
for index, x in enumerate(word):
if x in used_letters and x not in pattern: break
if pattern[index] != '_' and pattern[index] != x: break
else:
print word
q.add(word)
return q
def main():
path = r'./dictionary.txt'
solver = hangman_solver(path)
length = int(raw_input('How many letters does the word have?\n'))
solver.begin_solving(length)
if __name__ == "__main__":
import cProfile
cProfile.run("main()")
|
print("Welcome to Ivan Malkov's Naughts and Crosses!")
gamemode=input(
'''
Enter one of the following numbers in order to select its corresponding option
1 Tutorial
2 1 player
3 2 players
: '''
)
if gamemode=="1":
def tutorial(x)
tutorial.gametutorial()
if gamemode=="2":
import singleplayerfile
if gamemode=="3":
import multiplayerfile
else:
print("You entered an unrecognised option")
|
x = 11
if x < 10: print ('less than ten')
if x > 10: print ('greater than ten') |
#!/usr/bin/env python3
from multiprocessing.pool import ThreadPool as Pool
import matplotlib.pyplot as plt
import subprocess as sp
import platform
import time
import os
class address_checker():
"""This is a class to evaluate responsativity of multiple addresses to a
ping and find addresses with same host but different networks addresses
that have different responses to a ping.
This library has only been tested on Windows OS.
:param network_addresses: a list of network addresses to check such as
['192.168.1.', '192.168.2.']. There should at
least be two network addresses.
:type network_addresses: list
:param host_addresses: a list of integers containing all host addresses,
defaults to [0, ..., 255]
:type host_addresses: list, optional
:param host_unwanted: a list of host addresses that should not be evaluates
, defaults to []
:type host_unwanted: list, optional
:param number_threads: number of threads to accelerate the processes of
pinging all addresses. For optimal performance,
utilize self.optimal_thread_number() for optimal
thread number, defaults to 130
:type number_threads: int, optional
:param n_echos: specifies the number of echo request messages sent,
defaults to 1
:type n_echos: int, optional
:param wait: specifies the amount of time, in milliseconds, to wait for
the echo, defaults to 2 ms
:type wait: int, optional
:param n_attempts: number of attempts in case an address is not responsive
to the ping, defaults to 2
:type n_attempts: int, optional
Examples
--------
>>> import address_checker from networking
>>> host_unwanted = [15, 56]
>>> network_addresses = ['192.168.1.', '192.168.2.']
>>> c = address_checker(network_addresses)
>>> c.ping_all()
"""
def __init__(self, network_addresses, host_addresses=list(range(256)),
host_unwanted=[], number_threads=130, n_echos=1, wait=2,
n_attempts=2):
"""Constructor method.
"""
# Assign properties
self.network_addresses = network_addresses
self.host_addresses = host_addresses
self.host_unwanted = host_unwanted
self.number_threads = number_threads
self.n_attempts = n_attempts
self.n_echos = n_echos
self.wait = wait
# Option for the number of packets as a function of OS
if platform.system().lower() == 'windows':
self.param = '-n'
else:
self.param = '-c'
# Check if inputs are properly formatted
self._check_inputs()
def _check_inputs(self):
'''Evaluates if inputs are the correct format. This is evaluated when
the object is created. The attribute is also invoked before any
major operation (ping multiple addresses) just in case the user
changed the variables.
'''
# Check if OS is Windows. It should run for Linux, but was not tested
if platform.system().lower() != 'windows':
raise TypeError(
'This library has not been verified for non-Windows OS')
# Check if all list inputs are properly formatted
for name in ['network_addresses', 'host_addresses', 'host_unwanted']:
values = getattr(self, name)
# Check if inputs are lists
if not isinstance((values), (list, tuple)):
raise TypeError(
name + " should be an indexable format such as a list")
# Check for empty lists
if name in ['network_addresses', 'host_addresses']:
if len((values)) == 0:
raise TypeError(name + " should not be empty")
if name == 'network_addresses':
# At least two network addresses should be provided
if len(values) < 2:
raise TypeError(
name + " should have at least two network addresses.")
for value in values:
# network_addresses should consist only of strings
if not isinstance(value, (str)):
raise TypeError(name + " should consists of strings" +
" such as '192.168.1.'")
split_value = value.split('.')
# network_addresses should follow a quad-dotted address
if len(split_value) != 4:
raise TypeError(name + " should consists of strings" +
" such as '192.168.1.'")
# the host address in network_addresses should be missing
if split_value[-1] != '':
raise TypeError(
name + " should be missing the last octet of IP")
# Each octet should be less than 256
if not all(int(oct) < 256 for oct in split_value[:-1]):
raise TypeError("Each octet should be lower than 256")
# host_addresses and host_unwanted should consists only of integers
else:
if not all(isinstance(value, (int)) for value in values):
if not all((val >= 0 and val < 256) for val in values):
raise TypeError(name + "should consists of positive" +
" integers lower than 256")
# Check if all list inputs are properly formmated
for name in ['number_threads', 'n_echos', 'n_attempts']:
values = getattr(self, name)
if not isinstance((values), (int)):
raise TypeError(name + " should be an integer")
if values < 1:
raise TypeError(
name + " should be an integer equal to or more than one")
def show(self):
"""Prints all attributes from object.
"""
attrs = vars(self)
print(''.join("%s: %s\n" % item for item in attrs.items()))
def ping(self, address):
"""Pings address.
:param address: a string in dot-decimal notation is expected
:type address: string
:return: True if an echo is received
:rtype: bool
Notes:
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/ping
"""
self._check_inputs()
exit_code = False
attempts = 0
while attempts < self.n_attempts and not exit_code:
# Building the command. Ex: "ping -n 2 -w 2 [IP]"
# (sp.call returns False positives)
ping = sp.Popen("ping {} {} -w {} {}".format(self.param,
self.n_echos, self.wait, address),
stdout=sp.PIPE, stderr=sp.PIPE)
# If adress responds, exit_code is True
exit_code = ping.wait() == 0
attempts += 1
return exit_code
def _ping_networks(self, host_address):
"""Pings the same host address for all specified network addresses.
:param host_address: the host address (last octect of dot-decimal
notation). It should be positive and less than 256
:type host_address: int
:return: True if an echo is received
:rtype: bool
"""
if host_address not in self.host_unwanted:
p = []
for network_address in self.network_addresses:
address = network_address + '%i' % host_address
pi = self.ping(address)
p.append(pi)
if not all(pi == p[0] for pi in p):
return host_address
def ping_all(self, runtime=False):
'''pings all addresses for all networks.
:param runtime: if True, will runtime (default is False)
:type runtime: bool, optional
'''
self._check_inputs()
# Keep track of time
if runtime:
start_time = time.time()
# Ping utilizing multithreading
p = Pool(self.number_threads)
unmatched_hosts = p.map(self._ping_networks, self.host_addresses)
p.close()
p.join()
# Networks addresses with same ping results return None and are removed
self.unmatched_hosts = [i for i in unmatched_hosts if i]
# Find out time run
if runtime:
self.runtime = time.time() - start_time
def optimal_thread_number(self, thread_range=list(range(10, 210, 10)),
plot=False):
"""Determines number of thread for best performance.
:param address: a string in dot-decimal notation is expected
:type address: string
:return: (optimal runtime, optimal thread number)
:rtype: float, int
"""
runtimes = []
for self.number_threads in thread_range:
self.ping_all(runtime=True)
runtimes.append(self.runtime)
if plot:
plt.figure()
plt.plot(thread_range, runtimes)
plt.xlabel('Number of threads')
plt.ylabel('Runtime (s)')
plt.show()
optimal_runtime = min(runtimes)
return optimal_runtime, (thread_range[runtimes.index(optimal_runtime)])
|
# Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array.
# There is only one majority number in the array.
# O(n) time and O(k) extra space.
class Solution:
"""
@param nums: A list of integers
@param k: An integer
@return: The majority number
"""
def majorityNumber(self, nums, k):
# write your code here
count = collections.defaultdict(int)
for n in nums:
if n in count or len(count) < k:
count[n] += 1
else:
for key in dict(count):
count[key] -= 1
if count[key] == 0:
count.pop(key)
if len(count) < k:
count[n] = 1
for key in count:
count[key] = 0
res = 0
m = -1
for n in nums:
if n in count:
count[n] += 1
if count[n] > m:
m = count[n]
res = n
return res
|
"""
406. 根据身高重建队列
假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对 (h, k) 表示,其中 h 是这个人的身高,k 是应该排在这个人前面且身高大于或等于 h 的人数。 例如:[5,2] 表示前面应该有 2 个身高大于等于 5 的人,而 [5,0] 表示前面不应该存在身高大于等于 5 的人。
编写一个算法,根据每个人的身高 h 重建这个队列,使之满足每个整数对 (h, k) 中对人数 k 的要求。
示例:
输入:[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
输出:[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
提示:
总人数少于 1100 人。
"""
from typing import List
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
res = []
people = sorted(people, key=lambda x: (-x[0], x[1]))
for p in people:
if len(res) <= p[1]:
res.append(p)
elif len(res) > p[1]:
res.insert(p[1], p)
return res
s = Solution()
res = s.reconstructQueue([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]])
print(res)
|
"""
19. 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0, head)
first = head
second = dummy
for i in range(n):
first = first.next
while first:
first = first.next
second = second.next
second.next = second.next.next
return dummy.next
s = Solution()
h = ListNode(1)
h.next = ListNode(2)
h.next.next = ListNode(3)
h.next.next.next = ListNode(4)
h.next.next.next.next = ListNode(5)
res = s.removeNthFromEnd(h, 2)
print(res)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.