text
stringlengths 37
1.41M
|
---|
"""Task 2
The birthday greeting program.
Write a program that takes your name as input, and then your age as input and greets you with the following:
“Hello <name>, on your next birthday you’ll be <age+1> years” """
user_name, user_age = input("Enter your name, please!\n"), input("And enter your age, please!\n")
print(f"Hello, {user_name}!\nOn your next birthday you’ll be {int(user_age) + 1}, oldie =D")
|
"""Task 2
Exclusive common numbers.
Generate 2 lists with the length of 10 with random integers from 1 to 10, and make a third list
containing the common integers between the 2 initial lists without any duplicates.
Constraints: use only while loop and random module to generate numbers"""
from random import randint
list_of_numbers_1 = []
list_of_numbers_2 = []
list_of_numbers_3 = set()
while len(list_of_numbers_1) < 11:
list_of_numbers_1.append(randint(1, 10))
list_of_numbers_2.append(randint(1, 10))
for i in list_of_numbers_1:
if i in list_of_numbers_2:
list_of_numbers_3.add(i)
print(f"The 1st list contains: {list_of_numbers_1}.\nThe 2nd list contains: {list_of_numbers_2}.\n"
f"The uniq list of numbers contains: {list_of_numbers_3}.")
|
"""Task 1
Extend UnorderedList
Implement append, index, pop, insert methods for UnorderedList. Also implement a slice method, which will take two
parameters `start` and `stop`, and return a copy of the list starting at the position and going up to but not including
the stop position."""
from node import Node
class UnorderedList:
def __init__(self):
self._head = None
def is_empty(self):
return self._head is None
def append(self, item):
if self.head == None:
self.head = Node(item)
else:
newnode = Node(item)
newnode.next = self.head
self.head = newnode
def size(self):
current = self._head
count = 0
while current is not None:
count += 1
current = current.get_next()
return count
def index(self, item):
pass
def pop(self, item):
current = self.head
previous = None
found = False
while not found:
if current.get_data() == item:
found = True
else:
previous = current
current = current.get_next()
if previous == None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
|
"""Task 1
The Guessing Game.
Write a program that generates a random number between 1 and 10 and lets the user guess what number was generated.
The result should be sent back to the user via a print statement."""
import random
guessed_number = random.randint(1, 11)
entered_number = int(input('Enter number, please. \n'))
try_again = True
while True:
if entered_number == guessed_number:
print(f'You guessed. Number is {guessed_number}.')
break
elif guessed_number != entered_number:
print(f"You did not guess right. Great Random says {guessed_number}")
break
else:
print("You do not enter anything!")
|
# 字符串
a = 'hello word';
b = 'python 你好';
print("a[0]", a[0])
print('b[0]', b[8]);
# 字符串运算符
'''
+ 字符串连接
* 重复输入字符串
[] 通过索引获取字符串中字符
[:] 截取字符串中的一部分
in 成员运算符-如果包含该字符返回Ture
not in 成员运算符-如果不包含改字符返回True
r/R 原始字符串-原始
'''
print("a + b 输出结果:", a + b)
print(
"a * 2 输出结果:", a * 2)
print(
"a[1] 输出结果:", a[1])
print(
"a[1:4] 输出结果:", a[1:4])
if ("H" in a):
print(
"H 在变量 a 中")
else:
print(
"H 不在变量 a 中")
if ("M" not in a):
print(
"M 不在变量 a 中")
else:
print(
"M 在变量 a 中")
print(
r'\n')
print(
R'\n')
|
suma=0
while 1:
x=int(input("ingrese el numero a sumar "))
suma+=x
if x==0:
break
print("la sumatoria de los numeros es",suma) |
import math
print("ingrese el radio de la esfera")
radio=float(input())
area=4*math.pi*math.pow(radio,2)
volumen=4/3*math.pi*math.pow(radio,3)
print("el area de la esfera es: "+str(area))
print("el volumen de las esferas: "+str(volumen)) |
def crearlista():
num=int(input("ingrese la cantidad de numeros que desea ingresar"))
suma=0
nums=[]
for i in range(1,num+1):
nuevo=float(input("ingrese el valor "+str(i)+":"))
nums.append(nuevo)
suma+=nuevo
promedio=suma/num
for i in range(1,num):
desviacion=(abs(nums[i]-promedio))**2
desviacionestandar=(desviacion/num)**(1/2)
print("la desviacion estandar es",desviacionestandar)
crearlista() |
seleccion=0
def Cargar_Valores():
nom=input("ingrese el nombre del libro :")
auto=input("ingrese el nombre del autor :")
editorial=input("ingrese la editorial :")
with open("biblioteca.txt","r+") as file :
file.write(nom+", "+auto+", "+editorial+"\n")
def Mostrar_Valores():
with open("biblioteca.txt","r+") as file :
lineas=file.readlines()
for i in range(len(lineas)):
print(str(i+1),".-",lineas[i])
def Buscar_Valores():
x=input("ingrese el titulo del libro que desea buscar ")
x=x.capitalize()
encontrados=0
with open("biblioteca.txt","r+") as file :
lineas=file.readlines()
clean=lineas.copy()
for i in range(len(lineas)):
lineas[i]=lineas[i].replace("\n","")
lineas[i]=lineas[i].split(", ")
for i in range(len(lineas)):
lineas[i][0]=lineas[i][0].split(" ")
for y in range(len(lineas[i][0])):
if x==lineas[i][0][y]:
encontrados=encontrados+1
print(clean[i])
if encontrados==0:
print("no se han encontrado resultados")
while True:
print("1.Capturar Libros\n2.Mostrar Libros\n3.Buscar Libro\n4.Salir\n")
seleccion=int(input("seleccione que accion desea realizar: "))
if seleccion==1:
Cargar_Valores()
elif seleccion==2:
Mostrar_Valores()
elif seleccion==3:
Buscar_Valores()
elif seleccion==4:
break
else:
print("intente una opcion valida")
|
"""
Sample Model File
A Model should be in charge of communicating with the Database.
Define specific model method that query the database for information.
Then call upon these model method in your controller.
Create a model using this template.
"""
from system.core.model import Model
import re
from datetime import date
class User(Model):
def __init__(self):
super(User, self).__init__()
"""
Below is an example of a model method that queries the database for all users in a fictitious application
def get_all_users(self):
print self.db.query_db("SELECT * FROM users")
Every model has access to the "self.db.query_db" method which allows you to interact with the database
"""
"""
If you have enabled the ORM you have access to typical ORM style methods.
See the SQLAlchemy Documentation for more information on what types of commands you can run.
"""
def create(self, user_info):
email_query = "SELECT email FROM users WHERE email = %s"
email_data = [user_info['email']]
email = self.db.query_db(email_query, email_data)
errors = []
EMAIL_REGEX = re.compile(r'^[a-za-z0-9\.\+_-]+@[a-za-z0-9\._-]+\.[a-za-z]*$')
if not user_info['first_name']:
errors.append('First name cannot be blank')
elif not user_info['first_name'].isalpha():
errors.append('First name cannot contain numbers')
elif len(user_info['first_name']) < 2:
errors.append('First name must be at least 2 characters long')
if not user_info['last_name']:
errors.append('Last name cannot be blank')
elif not user_info['last_name'].isalpha():
errors.append('Last name cannot contain numbers')
elif len(user_info['last_name']) < 2:
errors.append('Last name must be at least 2 characters long')
if not user_info['email']:
errors.append('E-mail cannot be blank')
elif len(user_info['email']) < 2:
errors.append('E-mail must be at least 2 characters long')
elif not EMAIL_REGEX.match(user_info['email']):
errors.append('E-mail is not valid')
if email:
errors.append('E-mail already registered')
if not user_info['password']:
errors.append('Password cannot be blank')
elif not user_info['password_confirmation']:
errors.append('Password confirmation cannot be blank')
elif len(user_info['password']) < 8:
errors.append('Password must be at least 8 characters long')
elif user_info['password'] != user_info['password_confirmation']:
errors.append('Passwords must match')
if not user_info['dob']:
errors.append('Date of birth cannot be blank')
if not user_info['gender']:
errors.append('Gender cannot be blank')
if not user_info['feet']:
errors.append('Height cannot be blank')
if not user_info['weight']:
errors.append('Weight cannot be blank')
if not user_info['activity']:
errors.append('Activity cannot be blank')
if errors:
return {'status': False, 'errors': errors}
height = (int(user_info['feet']) * 12) + int(user_info['inches']) #convert feet and inches from html form to be stored to database and used in calculation of calorie threshold
today = date.today() # this section is to calculate the user's approx. age
year = today.year
born_year = int((str(user_info['dob']))[0:4])
age = year - born_year
if len(user_info['activity']) == 3: # for activity level
activity_level = 1.2
elif len(user_info['activity']) == 4:
activity_level = 1.725
else:
activity_level = 1.55
if len(user_info['gender']) == 4: # different formulas to calculate threshold depending on gender
calorie_threshold = 66.47 + (13.75 * int(user_info['weight'])) + (5 * height) - (6.75 * age) # need function to calculate age from dob
else:
calorie_threshold = 665.09 + (9.56 * int(user_info['weight'])) + (1.84 * height) - (4.67 * age)
hashed_pw = self.bcrypt.generate_password_hash(user_info['password'])
insert_query = "INSERT INTO users (first, last, email, password, created_at, updated_at, dob, gender, height, weight, activity, calories_threshold) VALUES (%s, %s, %s, %s, NOW(), NOW(), %s, %s, %s, %s, %s, %s)"
insert_data = [user_info['first_name'], user_info['last_name'], user_info['email'], hashed_pw, user_info['dob'], user_info['gender'], height, user_info['weight'], user_info['activity'], calorie_threshold]
self.db.query_db(insert_query, insert_data)
get_user_query = "SELECT * FROM users ORDER BY id DESC LIMIT 1"
user = self.db.query_db(get_user_query)
insert_weight_query = "INSERT INTO weight (weight, created_at, updated_at, users_id) VALUES (%s, NOW(), NOW(), %s)" # section to enter weight into database (to store weight history)
weight_data = [user[0]['weight'], user[0]['id']]
self.db.query_db(insert_weight_query, weight_data)
return {'status': True, 'user': user[0]}
def login(self, user_info):
login_query = "SELECT * FROM users WHERE email = %s"
login_data = [user_info['email']]
user = self.db.query_db(login_query, login_data)
if user and self.bcrypt.check_password_hash(user[0]['password'], user_info['password']):
return {'status': True, 'user': user[0]}
else:
return {'status': False}
def user_info(self, id):
all_users_query = "SELECT * FROM users WHERE id = %s"
user_id = [id]
return self.db.query_db(all_users_query, user_id)
|
# Written by RF
import math
a = float(input("a = "))
T = float(input("T = "))
B = float(input("B = "))
aT = (a/T)
aTB = (aT+B)
print("aTB = ", aTB)
print("R = ", math.log(aTB, 10))
|
# Written by RF
while True:
answer = str(input("Is it a right triangle? (y/n) : "))
if answer in ('y', 'n'):
print("invalid input")
break
if answer == 'y':
continue
else:
# skip to other code
# Calculation of Right Triangle
def loopfunc(1)
answer = str(input("Do we know the hypotenuse? (y/n) : "))
if answer in ('y', 'n'):
print("invalid input")
break
if answer == 'y':
continue
else:
# skip to other code
# We know the hyp
answer = str(input("Is the known angle opposite the hypotenuse? (y/n) : "))
if answer in ('y', 'n'):
print("invalid input")
break
if answer == 'y':
continue
else:
# skip
# We know the hyp and angle opposite it
H=float(input("What is the length of the hypotenuse?"))
v=float(input("What is the value of the angle?"))
|
# Written by RF
while True:
s1=float(input("What is the length of side one in cm?"))
s2=float(input("What is the length of side two in cm?"))
A=(s1*s2)
print("The area is", A, "cm^2")
while True:
answer = str(input('Anything else? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Godspeed")
break
|
def contained(elem, list) :
"""
return true if the element is contained in the list
"""
if elem in "\n".join(list) :
return True
return False
def mass_category(mass) :
"""
return the mass category depending on the value of mass. Currently we
will have only one mass category for the pt sub-categorization.
"""
# Temprorarily only use 1 mass cat.
return 0
value = float(mass)
category = 0
if 150<value and value<=250 :
category = 0
elif 250<value :
category = 0
return category
def is_integer(elem):
try:
int(elem)
except ValueError:
return False
if abs(int(elem) - float(elem)) < 1e-6:
return True
return False
def parseArgs(args) :
"""
parse a list of arguments which can be intergers or of type intA-intB
where intA<=intB and fill this list of arguments into a list if ints
"""
list = []
for elem in args :
if elem.find("-") > -1 :
if elem.find(":") > -1 :
step = float(elem[elem.find(":")+1:])
min = float(elem[:elem.find("-") ])
max = float(elem[elem.find("-")+1:elem.find(":")])
else :
step = 1
min = float(elem[:elem.find("-") ])
max = float(elem[elem.find("-")+1:])
while min <= max :
if is_integer(min):
list.append(int(min))
else:
list.append(min)
min=min+step
else :
if is_integer(elem):
list.append(int(elem))
else:
list.append(elem)
return list
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 24 19:39:39 2017
@author: nbt264
Introduction to plotting in Python
"""
import numpy as np, numpy.random as randn, matplotlib.pyplot as plt
#Just to begin
plt.plot(np.arange(10,21))
"""
For most charts, we need to begin with a figure object - that's
just a container for our chart or plot
Some of the options availabe:
figsize - size of the figure & relationship to display
dpi - resolution of the figure and plots within
You can have multiple figure objects, each with unique plots
A reference to active figure using matplotlib.gcf() - get current figure
in order to actually disply, a plot must be added to the figure. Use
sub_plot to add a plot to a figure.
"""
fig = plt.figure() # create a figure container
ax1 = fig.add_subplot(2, 2, 1) # add aplot at position 1 of a 2x2 grid
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(223) # add plot at position 3 of 2x2
print(np.arange(10))
#Let's add some data to plot
plt.plot(np.random.rand(50).cumsum(), 'k--')
ax1.hist(np.random.rand(100), bins=20, color='k',
axe2.scatter(np.arange(30), nparange(30)+3*np.random
fig, axes = plt.subplots(2,3)
print(axes)
print(figs) |
import numpy as np
def power_method(A, iter_num=1):
"""
Calculate the first singular vector/value of a target matrix based on the power method.
Parameters
----------
A : numpy array
Target matrix
iter_num : int
Number of iterations
Returns
-------
u : numpy array
first left singular vector of A
s : float
first singular value of A
v : numpy array
first right singular vector of A
"""
# set initial vector q
q = np.random.normal(size=A.shape[1])
q = q / np.linalg.norm(q)
for i in range(iter_num):
q = np.dot(np.dot(A.T, A), q)
v = q / np.linalg.norm(q)
Av = np.dot(A, v)
s = np.linalg.norm(Av)
u = Av / s
return u, s, v
def tridiagonalize_by_lanczos(P, m, k):
"""
Tridiagonalize matrix by lanczos method
Parameters
----------
P : numpy array
Target matrix
q : numpy array
Initial vector
k : int
Size of the tridiagonal matrix
Returns
-------
T : numpy array
tridiagonal matrix
"""
# Initialize variables
T = np.zeros((k, k))
r0 = m
beta0 = 1
q0 = np.zeros(m.shape)
for i in range(k):
q1 = r0 / beta0
C = np.dot(P, q1)
alpha1 = np.dot(q1, C)
r1 = C - alpha1 * q1 - beta0 * q0
beta1 = np.linalg.norm(r1)
T[i, i] = alpha1
if i + 1 < k:
T[i, i + 1] = beta1
T[i + 1, i] = beta1
q0 = q1
beta0 = beta1
r0 = r1
return T
def tridiag_eigen(T, iter_num=1, tol=1e-3):
"""
Calculate eigenvalues and eigenvectors of tridiagonal matrix
Parameters
----------
P : numpy array
Target matrix (tridiagonal)
iter_num : int
Number of iterations
tol : float
Stop iteration if the target matrix converges to a diagonal matrix with acceptable tolerance `tol`
Returns
-------
eigenvalue : numpy array
Calculated eigenvalues
eigenvectors : numpy array
Calculated eigenvectors
"""
eigenvectors = np.identity(T.shape[0])
for i in range(iter_num):
Q, R = tridiag_qr_decomposition(T)
T = np.dot(R, Q)
eigenvectors = np.dot(eigenvectors, Q)
eigenvalue = np.diag(T)
if np.all((T - np.diag(eigenvalue) < tol)):
break
return eigenvalue, eigenvectors
def tridiag_qr_decomposition(T):
"""
QR decomposition for a tridiagonal matrix
Ref. http://www.ericmart.in/blog/optimizing_julia_tridiag_qr
Parameters
----------
T : numpy array
Target matrix (tridiagonal)
Returns
-------
Qt.T : numpy array
R : numpy array
"""
R = T.copy()
Qt = np.eye(T.shape[0])
for i in range(T.shape[0] - 1):
u = householder(R[i:i + 2, i])
M = np.outer(u, u)
R[i:i + 2, :(i + 3)] -= 2 * np.dot(M, R[i:i + 2, :(i + 3)])
Qt[i:i + 2, :(i + 3)] -= 2 * np.dot(M, Qt[i:i + 2, :(i + 3)])
return Qt.T, R
def householder(x):
"""
Householder projection for vector.
Parameters
----------
x : numpy array
Target vector
Returns
-------
x : numpy array
"""
x[0] = x[0] + np.sign(x[0]) * np.linalg.norm(x)
x = x / np.linalg.norm(x)
return x
|
'''
You are teaching kindergarten! You wrote down the numbers from 1 to n,
in order, on a whiteboard. When you weren’t paying attention, one of your
students erased one of the numbers. Can you tell which number your
mischievous student erased?
Input
The first line of input contains a single integer n (2≤n≤100), which is
the number of numbers that you wrote down.
The second line of input contains a string of digits, which represents
the numbers you wrote down (minus the one that has been erased). There
are no spaces in this string. It is guaranteed to contain all of the numbers
from 1 to n, in order, except for the single number that the student erased.
Output
Output a single integer, which is the number that the tricky student erased.
'''
numbers = input()
sizeNum = len(numbers)
num = int(numbers)
givenList = input()
ourList = "123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"
if givenList[-sizeNum:]==numbers:
# when the number of digits changes, change the number of characters compared
if num<10: # if biggest number is <=9
for j in range(num):
if givenList[j:j+1]!=ourList[j:j+1]:
print(ourList[j:j+1])
exit()
elif num<=100: # if biggest number is 100
for j in range(10):
if givenList[j:j+1]!=ourList[j:j+1]:
print(ourList[j:j+1])
exit()
for j in range(10,len(givenList),2):
if givenList[j-1:j+1]!=ourList[j-1:j+1]:
print(ourList[j-1:j+1])
exit()
else:
print(num)
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 10:58:07 2018
@author: Mac
"""
#Question 1: Plotting sports data
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('UWvMSU_1-22-13.txt', sep = '\t')
out = pd.DataFrame(columns=['time','scoreMSU','scoreUW'])
scoreMSU = 0
scoreUW = 0
for i in range(0,len(data)):
if data.team.iloc[i] == 'UW':
scoreUW += data.score[i]
out.loc[len(out)]=[data.time[i],scoreMSU,scoreUW]
elif data.team.iloc[i] == 'MSU':
scoreMSU += data.score[i]
out.loc[len(out)]=[data.time[i],scoreMSU,scoreUW]
plt.plot(out.time,out.scoreMSU,'g-',out.time,out.scoreUW,'r-')
#Question 2: Guess this number!
import random
num = random.randint(1,100)
guess = 0
while guess != num:
guess = input("Please enter a number between 1 and 100: ")
if (guess > num):
print("too high")
elif (guess < num):
print("too low")
else:
print("got it!")
break |
class Solution:
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
"""
复杂度:O(n^2)
"""
for i in range(len(nums)):
temp=nums[i]
for j in range(i):
if nums[j] == temp:
return temp
def findDuplicate1(self, nums):
"""
:param nums:
:return:
"""
"""
将nums看作链表,nums[a]=b看作a.next=b,参考Problem142,查找链表环入口即可
"""
slow, fast = nums[0], nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while fast != slow:
fast, slow = nums[fast], nums[slow]
return fast
def findDuplicate2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
"""
二分查找:首先搜索空间固定为[1,n],每次选择1,n之间的值mid,然后遍历nums数组,记录数组中比不小于mid值的数量,记录为count,
然后判断,如果count值大于mid,则搜索空间修改为[1,mid],否则空间为[mid+1,n],重复以上过程,直至搜索空间变成一个数字。
复杂度:O(nlogn)
"""
left, right = 1, len(nums) - 1
while left < right:
mid = left + (right - left) // 2
count = 0
for i in nums:
if i <= mid:
count += 1
if count > mid:
right = mid
else:
left = mid + 1
return nums[left]
s=Solution()
nums=[1,3,4,2,2]
print(s.findDuplicate2(nums)) |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
pairs={
")":"(",
"]":"[",
"}":"{"
}
listStack=[]
for i in s:
if i not in pairs:
listStack.append(i)
else:
if listStack:
if listStack[-1] == pairs[i]:
listStack.pop()
else:
return False
else:
return False
if listStack:
return False
else:
return True
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head.next or m == n:
return head
dummy = ListNode(0)
dummy.next = head
mark = dummy
temp = None
for i in range(m-1):
mark = mark.next
head = head.next
for i in range(n-m+1):
newNode = ListNode(head.val)
newNode.next = temp
temp = newNode
head = head.next
mark.next = temp
while mark.next:mark = mark.next
mark.next = head
return dummy.next |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
"""
先确定行数,然后二分查找
"""
if matrix == [] or matrix == [[]]:return False
if target > matrix[-1][-1] or target < matrix[0][0]:
return False
column=[matrix[i][0] for i in range(len(matrix))]
row=0
for i in range(1,len(column)):
if target < column[i]:
break
else:
row=i
# 二分查找
low = 0
height = len(matrix[0])-1
while low <= height:
mid = (low+height)//2
if matrix[row][mid] < target:
low = mid + 1
elif matrix[row][mid] > target:
height = mid - 1
else:
return True
return False |
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
"""
将整数转换为二进制数,若整数是4的指数,则满足:
1.最高位为1,其余位为0(num & (num) ==0)
2.0的个数为偶数(num & 0x55555555 > 1)
"""
return num & (num-1) ==0 and num & 0x55555555 > 0
Solution1 = Solution()
num = 64
print(Solution1.isPowerOfFour(num)) |
from leetcode.structures.singly_linked_list import ListNode
class Solution:
def __call__(self, l1, l2):
def gen_add(a, b):
"""generator based solution"""
carry = 0
while a and b:
lsum = a.val + b.val + carry
carry = lsum // 10
yield ListNode(lsum % 10)
a, b = a.next, b.next
r = a or b
while carry > 0:
if r:
lsum = carry + r.val
carry = lsum // 10
yield ListNode(lsum % 10)
r = r.next
else:
yield ListNode(carry)
carry = 0
yield r
r = None
head = ListNode(0)
curr = head
for node in gen_add(l1, l2):
curr.next = node
curr = curr.next
return head.next
|
import pandas as pd
from datetime import datetime, timedelta
class TimeZoneConvertor:
def __init__(self, input_file, output_file):
self.input_file = input_file
self.output_file = output_file
def convert(self):
pd_A = pd.read_csv(self.input_file,delimiter=',')
output = open(self.output_file, 'w')
output.write("Time, Humidity, Temperature, Pressure, Light, IR Temperature, Noise\n")
for index, row in pd_A.iterrows():
value = datetime.fromtimestamp(row[0]/1000)
value = value - timedelta(hours=8)
time_s = value.strftime('%H:%M:%S')
output.write(str(time_s) + ',' + str(row[1]) + ',' + str(row[2]) + ',' + str(row[3]) + ',' + str(row[4]) + ',' + str(row[5]) + ',' + str(row[6]) + '\n')
|
#-------------------------------------------------------------------------------
# Name: calender.py
# Purpose: print the calender of the given year
#
# Author: Akshay
#
# Created: 11-06-2015
#-------------------------------------------------------------------------------
DAYS_OF_THE_WEEK = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
MONTHS_OF_THE_YEAR = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
DAYS_IN_MONTH = (31,28,31,30,31,30,31,31,30,31,30,31)
def is_leap_year(y):
return (y%4 == 0) and (not (y%100 == 0) or y%400 == 0)
def get_day_of_the_week(pos):
return DAYS_OF_THE_WEEK(pos)
def day_for_date(d, m, y):
"""Return number corresponding to day of the week for given date. Month is 0-11."""
assert 0 <= m <= 11
assert 0 < d <= DAYS_IN_MONTH[m]
assert 1800 <= y <= 2999
century_digits = y//100
year_digits = y%100
value = year_digits + year_digits//4
if century_digits == 18:
value += 2
if century_digits == 20:
value += 6
if m == 0 and not is_leap_year(y): #Jan and NOT a leap year
value += 1
elif m == 1 and is_leap_year(y): #Feb + Leap year
value += 3
elif m == 1 and not is_leap_year(y): #Feb
value += 4
elif m == 2 or m == 10: #March and November
value += 4
elif m == 4: #May
value += 2
elif m == 5: #june
value += 5
elif m == 7: #Aug
value += 3
elif m == 9: #Oct
value += 1
elif m == 8 or m == 11: #Sept or Dec
value += 6
value += (d-1)
value = (value+7)%7
return value
def print_calender_month(m, y):
"""Month is 1-12"""
m -= 1 #Work with 0-11
assert 0 <= m <= 11
assert 1800 <= y <= 2999
s = ''
## list_repr = []
## s_prime = ''
## #Print the title
print('{} {}'.format(MONTHS_OF_THE_YEAR[m],y))
s += '{} {}'.format(MONTHS_OF_THE_YEAR[m],y)
## s_prime += '{} {}'.format(MONTHS_OF_THE_YEAR[m],y)
## list_repr.append('{0:^27}'.format(s_prime))
## s_prime = ''
s += '\n'
##
for day in DAYS_OF_THE_WEEK:
print(day,end=' ')
s += (day + ' ')
## s_prime += (day + ' ')
s = s.strip()
## s_prime = s_prime.strip()
print()
## list_repr.append(s_prime)
## s_prime = ''
s += '\n'
first_of_month = day_for_date(1,m,y)
i = 0
count = 0
while i < first_of_month:
print(' '*3, end = ' ')
## s_prime += ' '*3
## s_prime += ' '
s += ' '*3
s += ' '
count += 1
i += 1
i = 1
days_in_this_month = DAYS_IN_MONTH[m]
if is_leap_year(y) and m == 1:
days_in_this_month += 1
while i <= days_in_this_month:
#i holds the date being currently printed.
if count > 6:
print()
## list_repr.append(s_prime.rstrip())
## s_prime = ''
s = s[:-1] +'\n'
count = 0
##
print('{0:>3}'.format(i), end = ' ')
s += '{0:>3}'.format(i)
## s_prime += '{0:>3}'.format(i)
## s_prime += ' '
s += ' '
i += 1
count += 1
##
print()
s = s[:-1]
## if s_prime:
## if len(s_prime) < 27:
## s_prime += ' '*(27 - len(s_prime))
##
## list_repr.append(s_prime)
##
## if len(list_repr) < 8:
## while len(list_repr) < 8:
## list_repr.append(' '*27)
##
## return list_repr
lines = s.split('\n')
lines[0] = '{0:^27}'.format(lines[0])
print(lines)
for line in lines:
print(len(line))
return s
def get_calender_month(m, y):
"""Month is 1-12"""
m -= 1 #Work with 0-11
assert 0 <= m <= 11
assert 1800 <= y <= 2999
## s = ''
list_repr = []
s_prime = ''
#Print the title
## print('{} {}'.format(MONTHS_OF_THE_YEAR[m],y))
## s += '{} {}'.format(MONTHS_OF_THE_YEAR[m],y)
s_prime += '{} {}'.format(MONTHS_OF_THE_YEAR[m],y)
list_repr.append('{0:^27}'.format(s_prime))
s_prime = ''
## s += '\n'
for day in DAYS_OF_THE_WEEK:
## print(day,end=' ')
## s += (day + ' ')
s_prime += (day + ' ')
## s = s.strip()
s_prime = s_prime.strip()
## print()
list_repr.append(s_prime)
s_prime = ''
## s += '\n'
first_of_month = day_for_date(1,m,y)
i = 0
count = 0
while i < first_of_month:
## print(' '*3, end = ' ')
s_prime += ' '*3
s_prime += ' '
## s += ' '*3
## s += ' '
count += 1
i += 1
i = 1
days_in_this_month = DAYS_IN_MONTH[m]
if is_leap_year(y) and m == 1:
days_in_this_month += 1
while i <= days_in_this_month:
#i holds the date being currently printed.
if count > 6:
## print()
list_repr.append(s_prime.rstrip())
s_prime = ''
## s += '\n'
count = 0
## print('{0:>3}'.format(i), end = ' ')
## s += '{0:>3}'.format(i)
s_prime += '{0:>3}'.format(i)
s_prime += ' '
## s += ' '
i += 1
count += 1
if s_prime:
if len(s_prime) < 27:
s_prime += ' '*(27 - len(s_prime))
elif len(s_prime) >= 28:
s_prime = s_prime[:27]
list_repr.append(s_prime)
if len(list_repr) < 8:
while len(list_repr) < 8:
list_repr.append(' '*27)
return list_repr
def print_calender_year(y):
"""Return a list of lists, each inner list containing a list of strings for the calender of a single month."""
assert 1800 <= y <= 2999, 'Choose a year between 1800 and 2999 only.'
print('{0:^117}'.format(y))
print()
p = []
#Call each month, format and print.
for i in range(12):
p.append(get_calender_month(i+1,y))
## for q in p:
## print(q[0])
## for x in q[1:]:
## print(len(x), end = ' ')
## print()
## assert False
for j in range(3):
for k in range(len(p[0])):
for i in range(4):
print(p[j*4 + i][k], end = ' '*3)
print()
print()
def get_int(prompt, low = None,high = None):
"""Return the user-inputted integer between low and high (inclusive)."""
assert (low == None or high == None) or low <= high
done = False
x = None
while not done:
x = int(input(prompt))
flag1 = False
flag2 = False
if low is not None:
if x < low:
print('Sorry, the number must be greater than {}.'.format(low))
else:
flag1 = True
else:
flag1 = True
if high is not None:
if x > high:
print('Sorry, the number must be greater than {}.'.format(high))
else:
flag2 = True
else:
flag2 = True
if flag1 and flag2:
done = True
return x
def main():
year = get_int('Welcome to the calender centre. \n Enter a year between 1800 and 2999 for the calender of that year. ', 1800, 2999)
print_calender_year(year)
if __name__ == '__main__':
main()
|
# newton's method to find roots of any function
dx = 1e-8
EPSILON = 1e-8
def deriv(g):
"""Return a function f such that f(x) is approximately dg/dx(x)"""
return lambda x: (g(x+dx) - g(x))/dx
def fixed_point(f, start, max):
"""
Find x such that f(x) is approximately x.
start is the initial guess.
max is the maximum number of iterations.
"""
def average_damp(g):
return lambda x: (x + g(x))/2.0
def good_enough(x):
return abs(f(x) - x) < EPSILON
curr = 0
guess = start
ad = average_damp(f)
while curr < max:
if good_enough(guess):
break
guess = ad(guess)
curr += 1
return guess
def newton_root(g, initial_guess, max_iter=1000):
"""Given a function g: Float -> Float, estimate x such that g(x) = 0"""
def newton_modify(f):
return lambda x: x - f(x)/(deriv(f))(x)
d = deriv(g)
return fixed_point(newton_modify(g),initial_guess,max_iter)
#Using this newton root, we can define many functions!
newton_sqrt = lambda x: newton_root(lambda y: y*y - x, 1.0)
|
def insert(ls, pos):
"""
Insert ls[pos] into ls[:pos].
ASSUME: pos >= 1, ls[:pos] is sorted, len(ls) > pos"""
if pos == 0:
return ls
assert pos >= 1
elem = ls.pop(pos)
j = pos - 1
while j >= 0 and ls[j] > elem:
j -= 1
ls.insert(j + 1, elem) #WHY j+1? The prev loop ends when j < 0 or ls[j] <= elem. Our elem should be at ls[j+1]
def insertion_sort(a):
#sorted = [14 17] [16 18 20]
if len(a) <= 1:
return a
i = 1
l = len(a)
while i < l:
#insert a[i] in a[0:i]
insert(a, i)
i+=1
return a
def rev_recursive(ls):
if len(ls) < 2:
return ls
return rev_recursive(ls[1:]) + [ls[0]]
def gray_codes(n):
"""
A list of n-bit Gray codes.
Gray code -> two successive bit patterns differ one by only 1 character.
>>> gray_codes(3)
['000', '001', '011', '010', '110', '111', '101', '100']
"""
if n == 1:
return ['0', '1']
p = gray_codes(n-1)
return list(map(lambda s: '0' + s,p)) + list(map(lambda s: '1' + s, p[::-1]))
import operator
def merge(l1, l2, less_than):
"""Merge two sorted lists l1 and l2"""
if not l1:
return l2
if not l2:
return l1
p1 = 0
p2 = 0
res = []
#print("l1: {}, l2: {}".format(l1, l2))
#print("lt == operator.lt {}".format(less_than==operator.lt))
while p1 < len(l1) and p2 < len(l2):
if less_than(l1[p1], l2[p2]):
res.append(l1[p1])
p1 += 1
else:
res.append(l2[p2])
p2 += 1
if p1 < len(l1):
res.extend(l1[p1:])
if p2 < len(l2):
res.extend(l2[p2:])
#print("res: {}".format(res))
return res
def merge_sort_r(a, less_than = operator.lt):
"""Sort a, Assumption: a is a list."""
if len(a) < 2:
return a
#print(less_than)
return merge(merge_sort_r(a[:len(a)//2], less_than), merge_sort_r(a[len(a)//2:], less_than), less_than)
def merge_sort_desc(a):
return merge_sort_r(a, operator.gt)
def scrabble_sort(ls):
"""Sort list of strings according to length, and then arrange words of same length in alphabetical order."""
def f(s1, s2):
if len(s1) == len(s2):
return s1 < s2
return len(s1) < len(s2)
return merge_sort_r(ls, f)
def gcd(a,b):
assert isinstance(a,int) and isinstance(b, int), "Cannot compute gcd if both not natural numbers"
if a <= 0 or b <= 0:
return None
a, b = (a,b) if a < b else (b,a) #ensure a < b
while b%a:
a, b = b%a, a
return a
ITERATION_LIMIT = 100
def collatz(n, lim = ITERATION_LIMIT):
results = []
results.append(n)
i = 0
while n != 1 and i < lim:
i += 1
if n%2:
n = 3*n + 1
else:
n = n//2
results.append(n)
return results
import random
def qsort(a, less_than=operator.lt):
def partition(a, pos):
"""Partition a into elements < a[pos], a[pos] and elements >= a[pos]"""
e = a.pop(pos)
lesser = [x for x in a if less_than(x, e)]
greater = [x for x in a if not less_than(x, e)]
return (lesser + [e] + greater, len(lesser))
if len(a) < 2:
return a
pos = random.choice(range(len(a)))
a, splitter = partition(a, pos)
return qsort(a[:splitter], less_than) + [a[splitter]] + qsort(a[splitter + 1:], less_than)
|
from battalion_types import BattalionType
from typing import List
from collections import defaultdict
class Army:
"""Army holds all the battalions along with their strength.
Army can update, add new battalions and their strength
"""
def __init__(self, **battalions):
self.battalion_strength = defaultdict(int)
for k, v in battalions.items():
if BattalionType.is_valid_battalion(k) and isinstance(v, int):
self.battalion_strength[BattalionType(k)] = v
def get_battalion_strength(self, battalion_type: BattalionType) -> int:
"""Returns the strength of the battalion in this army
Arguments:
battalion_type {BattalionType} -- [type of battalion whose
strength needs to be found]
Raises:
KeyError: [Raises when battalion_type is not present in the army]
Returns:
[int] -- [strength of battalion_type]
"""
if battalion_type not in self.battalion_strength:
raise KeyError("{0} not found".format(battalion_type))
return self.battalion_strength.get(battalion_type)
def update_battalion_strength(self, battalion_type: BattalionType,
change: int):
"""adds a new battalion_type battalion if not present else
updates the strength of the battalion
Arguments:
battalion_type {BattalionType} -- [Type of battalion to be added or updated]
change {int} -- [represents change in the strength of the battalion]
"""
self.battalion_strength[battalion_type] += change
def get_battalions(self) -> List[BattalionType]:
return list(self.battalion_strength.keys())
def has_battalion(self, battalion_type: BattalionType) -> bool:
return battalion_type in self.battalion_strength
def get_all_battalion_with_strength(self):
return self.battalion_strength
def __eq__(self, other):
if not isinstance(other, Army):
return False
return self.battalion_strength == other.battalion_strength
|
class Address:
def __init__(self, address, apt, state, city, zip_code):
self.__address = address
self.__apt = apt
self.__city = city
self.__state = state
self.__zip_code = zip_code
@property
def full_address(self):
return f'{self.__address} {self.__apt} {self.__city}, {self.__state} {self.__zip_code}'
@property
def address(self):
return f'{self.__address} {self.__apt}'
@property
def city(self):
return f'{self.__city}'
@property
def state(self):
return f'{self.__state}'
@property
def zip_code(self):
return f'{self.__zip_code}'
class Person:
def __init__(self, first_name, last_name, age, phone, email, address: Address):
self.__first_name = first_name
self.__last_name = last_name
self.__age = age
self.__phone = phone
self.__email = email
self.__address = address
self.__work = []
self.__symptoms = []
@property
def name(self):
return f'{self.__last_name.capitalize()}, {self.__first_name.capitalize()}'
@property
def age(self):
return f'{self.__age}'
@property
def phone(self):
return f'{self.__phone}'
@property
def email(self):
return f'{self.__email}'
@property
def where(self):
return self.__address.full_address
@property
def get_address(self):
return self.__address
def add_work(self, name, phone, email, work_address) -> dict:
new_work = {'name': name, 'email': email, 'phone': phone, 'address': work_address}
self.__work.append(new_work)
return new_work
@property
def list_of_work(self) -> list:
return self.__work
def add_symptoms(self, symptoms: dict):
self.__symptoms = symptoms
@property
def symptoms(self):
return self.__symptoms
|
import random
class Food:
def __init__(self):
self.x_coordinate = random.randint(0,60)
self.y_coordinate = random.randint(0,20)
type = random.randint(0,40)
if type <=5 :
self.type_food = 0 #0 == bad food (*)
else:
self.type_food = 1 #1 == good food (+)
def print(self):
print('x-coordinate: ', self.x_coordinate)
print('y-coordinate: ', self.y_coordinate)
if self.type_food==1:
print('food: good')
else:
print('food: bad')
for x in range(0, 10):
food = Food()
food.print()
|
import turtle as t
# 写了一个移动画笔的函数
def GoTo(x,y):
t.up()
t.goto(x, y)
t.down()
# 准备工作
GoTo(-100,100) #设置起点 可直接调用之前写的移动画笔的函数
#t.pencolor() #设置画笔颜色
t.pensize(40) #设置画笔粗细
# 画左边的小人
#==============================
# 画小人的头
t.circle(13)
# 画小人的身体
GoTo(-130,50)
t.right(105)
t.pensize(60)
t.fd(80)
# 画小人的左腿
t.pensize(32)
GoTo(-170,-35)
t.fd(100)
# 画小人的右腿
GoTo(-140,-48)
t.left(45)
t.fd(40)
t.right(30)
t.fd(50)
# 画小人的手臂
GoTo(-105,50)
t.left(60)
t.fd(90)
# 画右边的小人
#==============================
#画小人的左手
t.left(105)
t.fd(70)
# 画小人的身体
GoTo(-5,0)
t.right(60)
t.pensize(60)
t.fd(80)
# 画小人的左腿
t.pensize(32)
GoTo(78,30)
t.left(75)
t.fd(100)
# 画小人的右腿
GoTo(78,10)
t.right(30)
t.fd(90)
# 画小人的右手
GoTo(-5,-20)
t.right(105)
t.fd(55)
t.left(60)
t.fd(60)
# 画小人的头
GoTo(-75,-35)
t.circle(13)
t.done() |
words = []
for _ in range(int(input())):
word = input()
l = len(word)
words.append((word, l))
words = list(set(words)) # set 으로 만들기위해 () 이형태로 좌표를 넣어주고
# 중복 없애기 위해 set -> 다음 list
words.sort(key= lambda x: (x[1], x[0])) # 길이, 단어 순
for w in words:
print(w[0])
|
arr = ['a','b','c','d','e']
n = len(arr)
# 5C3
for i in range(n-2): # 3개 뽑기
for j in range(i+1, n-1): # 2
for k in range(j+1, n): # 1
print(arr[i], arr[j], arr[k])
|
from itertools import permutations
n=int(input())
number=list(map(str,range(1,n+1)))
a=list(map(' '.join,permutations(number,n)))
for i in a:
print(i)
# for i in range(1,n+1):
# number+=[i]
#
# a=list(permutations(number,n))
# for j in a:
# print(*j)
|
def maketree(i): #4 2 6 1 3 5
global count
if i<=N: #중위
maketree(i*2) #왼 맨밑부터
matrix[i]=count
count+=1
maketree(i*2+1)
t=int(input())
for tc in range(1,t+1):
N=int(input())
tree=[i for i in range(1,N+1)]
matrix=[0]*(N+1)
count=1
#트리를 만들어준다 제일 낮은 순서부터
maketree(1)
print(matrix)
print(f'#{tc} {matrix[1]} {matrix[N//2]}')
|
# 시간복잡도 nlonn -> 힙정렬, 병합정렬, 퀵정렬 등으로 풀어야함.
# sys.stdin... 이거 차이큼
# 시간초과는 안나지만 효율성은 좀 떨어짐
import sys
n = int(sys.stdin.readline())
li = []
for _ in range(n):
li.append(int(sys.stdin.readline()))
li.sort()
print("\n".join(list(map(str, li)))) # 하나씩 출력해줌
# for a in li:
# print(a)
|
arr=[3,6,7,1,5,4]
n=len(arr)
for i in range(1<<n):
for j in range(n+1):
if i & (1<<j):
print(arr[j],end=', ')
print()
print() |
#최소힙만 지원한다 (heapq)
import heapq
heap=[7,2,5,3,4,6] #list
print(heap)
heapq.heapify(heap) #최소힙으로 만들어줌
print(heap)
heapq.heappush(heap,1) #삽입
print(heap)
while heap:
print(heapq.heappop(heap),end=' ') #오름차순으로 뽑혀서 만들어줌
print()
#####################################
#최대힙은 ?
temp=[7,2,5,3,4,6]
heap2=[]
for i in range(len(temp)):
heapq.heappush(heap2,(-temp[i],temp[i])) #앞순서 먼저
heapq.heappush(heap2,(-1,1))
print(heap2)
while heap2:
print(heapq.heappop(heap2)[1],end=' ')
# print(heapq.heappop(heap2)*-1, end=' ')
|
while True:
num = input()
if num == '0':
break
elif num[::-1] == num:
print('yes')
else:
print('no')
'''
def check(str):
length = len(str)
for i in range(0, length):
if (str[i] != str[length -i -1]):
return 'no'
return 'yes'
''' |
def check(n, s):
global minv
if n > 12: # 12달 이상은 없으니깐 !
if s < minv:
minv = s
else:
check(n+1, s+ month[n]*d)
check(n + 1, s+m)
check(n + 3, s+three_m)
# 완전 탐색
for tc in range(1, int(input())+1):
d, m, three_m, y = map(int, input().split())
month = [0] + list(map(int, input().split()))
minv = y
check(1, 0)
print(f'#{tc} {minv}')
'''
10
10 40 100 300
0 0 2 9 1 5 0 0 0 0 0 0
10 100 50 300
0 0 0 0 0 0 0 0 6 2 7 8
''' |
def check_blank(string):
for i in range(len(string)):
if string[i] == '{' or string[i] == '(':
check.append(string[i])
elif string[i] == '}' or string[i] == ')':
if len(check) == 0:
return 0
tmp=check.pop()
if string[i]=='}' and tmp=='{':
continue
if string[i]==')' and tmp=='(':
continue
return 0
if len(check) !=0:
return 0
return 1
t=int(input())
for tc in range(1,t+1):
string=input()
check=[]
print(f'#{tc} {check_blank(string)}') |
# print("abc" in "abcba")
#
# print("cabcd".find("abc", 1)) # индекс первого вхождения или -1
# print("cabcd"[1:].find("abc"))
#
# print("cabcd".index("abc")) # индекс первого вхождения или ValueError
# print("cabcd".index("abe"))
# s = "The man in black fled across the desert,"
# print(s.startswith(("The woman", "The dog", "The man")))
# print(s.lower().count("the"))
# print(s.replace(",", "."))
# print(s.split(" "))
#
# s = "ababa"
# print(s.count("aba")) # 1
# print(s.rfind("aba")) # 2
# s = "_*__1, 2, 3, 4__*_"
# print(repr(s.rstrip("*_")))
# print(repr(s.lstrip("*_")))
# print(repr(s.strip("*_")))
#
# numbers = map(str, [1, 2, 3, 4, 5])
# print(repr(" ".join(numbers)))
# capital = "London is the capital of Great Britain"
# template = "{0} is the capital of {country}"
# print(template.format("London", country="Great Britain"))
# print(template.format("Vaduz", country="Liechtenstein"))
"""
import requests
template = "Response from {0.url} with code {0.status_code}"
res = requests.get("https://docs.python.org/3.5/")
print(template.format(res))
res = requests.get("https://docs.python.org/3.5/random")
print(template.format(res))
"""
from random import random
x = random()
print(x)
print("{:.3}".format(x))
|
#============SCIENTIFIC CALCULATOR===========================================================
from tkinter import*
import math
import parser
from tkinter import messagebox
root = Tk()
root.title("Scientific Calculator")
root.geometry("480x568+0+0")
root.configure(background="powder blue")
calc = Frame(root)
calc.grid()
#==========object and methods==========================================================================
class Calc():
def __init__(self):
self.total = 0
self.current = ""
self.input_value = True
self.check_sum = False
self.op = ""
self.result = False
def numberEnter(self, num):
self.result = False
firstnum = txtDisplay.get()
secondnum = str(num)
if self.input_value:
self.current = secondnum
self.input_value = False
else:
if secondnum == ".":
if secondnum in firstnum:
return
self.current = firstnum + secondnum
self.display(self.current)
def sum_of_total(self):
self.result = True
self.current = float(self.current)
if self.check_sum == True:
self.valid_function()
def display(self, value):
txtDisplay.delete(0, END)
txtDisplay.insert(0, value)
def valid_function(self):
if self.op == "add":
self.total += self.current
if self.op == "Sub":
self.total -= self.current
if self.op == "multi":
self.total *= self.current
if self.op == "divide":
self.total /= self.current
if self.op == "mod":
self.total %= self.current
self.input_value = True
self.check_sum = False
self.display(self.total)
def operation(self, op):
self.current = float(self.current)
if self.check_sum:
self.valid_function()
elif not self.result:
self.total = self.current
self.input_value = True
self.check_sum = True
self.op = op
self.result = False
def clear_Entry(self):
self.result = False
self.current = "0"
self.display(0)
self.input_value = True
def all_clear_Entry(self):
self.clear_Entry()
self.total = 0
def mathsPM(self):
self.result = False
self.current = - (float(txtDisplay.get()))
self.display(self.current)
def squared(self):
self.result = False
self.current = math.sqrt (float(txtDisplay.get()))
self.display(self.current)
def cos(self):
self.result = False
self.current = math.cos(math.radians(float(txtDisplay.get())))
self.display(self.current)
def cosh(self):
self.result = False
self.current = math.cosh(math.radians(float(txtDisplay.get())))
self.display(self.current)
def tan(self):
self.result = False
self.current = math.tan(math.radians(float(txtDisplay.get())))
self.display(self.current)
def tanh(self):
self.result = False
self.current = math.tanh(math.radians(float(txtDisplay.get())))
self.display(self.current)
def sin(self):
self.result = False
self.current = math.sin(math.radians(float(txtDisplay.get())))
self.display(self.current)
def sinh(self):
self.result = False
self.current = math.sinh(math.radians(float(txtDisplay.get())))
self.display(self.current)
def log(self):
self.result = False
self.current = math.log(float(txtDisplay.get()))
self.display(self.current)
def exp(self):
self.result = False
self.current = math.exp(float(txtDisplay.get()))
self.display(self.current)
def expm1(self):
self.result = False
self.current = math.expm1(float(txtDisplay.get()))
self.display(self.current)
def lgamma(self):
self.result = False
self.current = math.lgamma(float(txtDisplay.get()))
self.display(self.current)
def degrees(self):
self.result = False
self.current = math.degrees(float(txtDisplay.get()))
self.display(self.current)
def log2(self):
self.result = False
self.current = math.log2(float(txtDisplay.get()))
self.display(self.current)
def log10(self):
self.result = False
self.current = math.log10(float(txtDisplay.get()))
self.display(self.current)
def log1p(self):
self.result = False
self.current = math.log1p(float(txtDisplay.get()))
self.display(self.current)
def acosh(self):
self.result = False
self.current = math.acosh(float(txtDisplay.get()))
self.display(self.current)
def asinh(self):
self.result = False
self.current = math.asinh(float(txtDisplay.get()))
self.display(self.current)
def pi(self):
self.result = False
self.current = math.pi
self.display(self.current)
def tau(self):
self.result = False
self.current = math.tau
self.display(self.current)
def e(self):
self.result = False
self.current = math.e
self.display(self.current)
added_value = Calc()
#=============DISPLAY===========================================================================
txtDisplay = Entry(calc, font=('arial', 20, 'bold'), bd=30, width=28, bg="powder blue", justify='right')
txtDisplay.grid(row=0, column=0, columnspan=4, pady=1)
txtDisplay.insert(0,"0")
#==============NUMBER BUTTONS=================================================================================
numberpad = "789456123"
i = 0
btn = []
for j in range (2, 5):
for k in range (3):
btn.append(Button(calc, width=6, height= 2, font=('arial', 20, 'bold'), bd= 4, text= numberpad[i]))
btn[i].grid(row= j, column = k, pady = 1)
btn[i]["command"] = lambda x = numberpad[i]: added_value.numberEnter(x)
i += 1
#================TOP BUTTONS==========================================================================================
btnClear = Button(calc, command = added_value.clear_Entry, text=chr(67), width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 1, column= 0, pady= 1)
btnAllClear = Button(calc, command = added_value.all_clear_Entry, text="CE", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 1, column= 1, pady= 1)
btnSqr = Button(calc, command = added_value.squared, text="SqRt", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 1, column= 2, pady= 1)
btnAdd = Button(calc, command = lambda: added_value.operation("add"), text=chr(247), width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 1, column= 3, pady= 1)
btnSub = Button(calc, command = lambda: added_value.operation("sub"), text="-", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 2, column= 3, pady= 1)
btnMult = Button(calc, command = lambda: added_value.operation("multi"), text="*", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 3, column= 3, pady= 1)
btnDiv = Button(calc, command = lambda: added_value.operation("divide"), text="/", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 4, column= 3, pady= 1)
btnZero = Button(calc, command = lambda: added_value.numberEnter(0), text="0", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 5, column= 0, pady= 1)
btnDot = Button(calc, command = lambda: added_value.numberEnter("."), text=".", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 5, column= 1, pady= 1)
btnPM = Button(calc, command = added_value.mathsPM, text=chr(177), width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 5, column= 2, pady= 1)
btnEquals = Button(calc, command = added_value.sum_of_total, text="=", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 5, column= 3, pady= 1)
#================SCIENTIFIC CALCULATOR========================================================================================
btnPi = Button(calc, command = added_value.pi, text="Pi", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 1, column= 4, pady= 1)
btncos = Button(calc, command = added_value.cos, text="cos", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 1, column= 5, pady= 1)
btntan = Button(calc, command = added_value.tan, text="tan", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 1, column= 6, pady= 1)
btnsin = Button(calc, command = added_value.sin, text="sin", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 1, column= 7, pady= 1)
btn2Pi = Button(calc, command = added_value.tau, text="2Pi", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 2, column= 4, pady= 1)
btncosh = Button(calc, command = added_value.cosh, text="cosh", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 2, column= 5, pady= 1)
btntanh = Button(calc, command = added_value.tanh, text="tanh", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 2, column= 6, pady= 1)
btnsinh = Button(calc, command = added_value.sinh, text="sinh", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 2, column= 7, pady= 1)
btnlog = Button(calc, command = added_value.log, text="log", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 3, column= 4, pady= 1)
btnExp = Button(calc, command = added_value.exp, text="Exp", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 3, column= 5, pady= 1)
btnMod = Button(calc, command = lambda: added_value.operation("mod") , text="Mod", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 3, column= 6, pady= 1)
btnE = Button(calc, command = added_value.e, text="e", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 3, column= 7, pady= 1)
btnlog2 = Button(calc, command = added_value.log2, text="log2", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 4, column= 4, pady= 1)
btndeg = Button(calc, command = added_value.degrees, text="deg", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 4, column= 5, pady= 1)
btnacosh = Button(calc, command = added_value.acosh, text="acosh", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 4, column= 6, pady= 1)
btnasinh = Button(calc, command = added_value.asinh, text="asinh", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 4, column= 7, pady= 1)
btnlog10 = Button(calc, command = added_value.log10, text="log10", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 5, column= 4, pady= 1)
btndeg = Button(calc, command = added_value.degrees, text="log1p", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 5, column= 5, pady= 1)
btnexpm1 = Button(calc, command = added_value.expm1, text="expml", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 5, column= 6, pady= 1)
btnlgamma = Button(calc, command = added_value.lgamma, text="lgamma", width=6, height= 2, background="powder blue", font=('arial', 20, 'bold'), bd= 4,).grid(row= 5, column= 7, pady= 1)
lblDisplay = Label(calc, text="Scientific Calculator", font=('arial', 30, 'bold'), justify=CENTER)
lblDisplay.grid(row= 0, column= 4, columnspan=4)
#=============MENU==============================================================
def iExit():
qExit = messagebox.askyesno("Scientific Calculator", "Do you want to EXIT the system")
if qExit == 1:
root.destroy()
return
def Scientific():
root.resizable(width=False, height=False)
root.geometry("944x568+0+0")
def Standard():
root.resizable(width=False, height=False)
root.geometry("480x568+0+0")
menubar = Menu(calc)
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label = "File", menu=filemenu)
filemenu.add_command(label = "Standard", command=Standard)
filemenu.add_command(label = "Scientific", command=Scientific)
filemenu.add_separator()
filemenu.add_command(label = "Exit", command= iExit)
editmenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label = "Edit", menu=editmenu)
editmenu.add_command(label = "Cut")
editmenu.add_command(label = "Copy")
editmenu.add_separator()
editmenu.add_command(label = "Paste")
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_cascade(label = "Help", menu=helpmenu)
helpmenu.add_command(label = "View Help")
root.configure(menu = menubar)
root.mainloop()
|
#==============4TH SCRIPT=================================
import sqlite3 as lit
db = lit.connect('employee.db')
with db:
cur = db.cursor()
selectquery = "SELECT * FROM users"
cur.execute(selectquery)
rows = cur.fetchall()
for data in rows:
print (data)
|
from src.heap import Heap
def test_initialize_empty_heap():
heap = Heap()
expected = [0]
output = heap.heap
assert output == expected
def test_heapify_empty_list():
list_to_heapify = []
heap = Heap(list_to_heapify)
expected = [0]
output = heap.heap
assert output == expected
def test_heapify_list_with_two_elements():
list_to_heapify = [1, 3]
heap = Heap(list_to_heapify)
expected = [0, 3, 1]
output = heap.heap
assert output == expected
def test_heapify_full_list():
list_to_heapify = [3, 1, 7, 4]
heap = Heap(list_to_heapify)
expected = [0, 7, 4, 3, 1]
output = heap.heap
assert output == expected
def test_heapify_larger_list():
list_to_heapify = [1, 9, 7, 4, 3, 8]
heap = Heap(list_to_heapify)
expected = [0, 9, 4, 8, 1, 3, 7]
output = heap.heap
assert output == expected
def test_heapify_heap_list():
list_to_heapify = [9, 4, 8, 1, 3, 7]
heap = Heap(list_to_heapify)
expected = [0, 9, 4, 8, 1, 3, 7]
output = heap.heap
assert output == expected
def test_insert_empty_heap():
heap = Heap()
heap.insert(4)
expected = [0, 4]
output = heap.heap
assert output == expected
def test_insert_empty_heap_two_elements():
heap = Heap()
heap.insert(1)
heap.insert(3)
expected = [0, 3, 1]
output = heap.heap
assert output == expected
def test_insert_into_heap():
heap = Heap([8, 5, 2, 4, 3, 1])
heap.insert(6)
expected = [0, 8, 5, 6, 4, 3, 1, 2]
output = heap.heap
assert output == expected
def test_delete_from_empty_heap():
heap = Heap()
heap.delete()
expected = [0]
output = heap.heap
assert output == expected
def test_delete_from_one_element_heap():
heap = Heap([1])
heap.delete()
expected = [0]
output = heap.heap
assert output == expected
def test_delete_from_two_element_heap():
heap = Heap([5, 1])
deleted_node = heap.delete()
expected = [0, 1]
output = heap.heap
assert output == expected
assert deleted_node == 5
def test_delete_from_full_heap():
heap = Heap([9, 7, 5, 6, 2])
deleted_node = heap.delete()
expected = [0, 7, 6, 5, 2]
output = heap.heap
assert output == expected
assert deleted_node == 9
def test_heap_sort_empty_heap():
heap = Heap()
expected = []
output = heap.heap_sort()
assert output == expected
def test_heap_sort_one_element_heap():
heap = Heap([9])
expected = [9]
output = heap.heap_sort()
assert output == expected
def test_heap_sort_with_already_sorted():
heap = Heap([1, 3, 4, 7, 8, 9])
expected = [1, 3, 4, 7, 8, 9]
output = heap.heap_sort()
assert output == expected
def test_heap_sort_with_full_heap():
heap = Heap([9, 4, 8, 1, 3, 7])
expected = [1, 3, 4, 7, 8, 9]
output = heap.heap_sort()
assert output == expected
def test_heap_sort_with_heap_construction():
heap = Heap([1, 9, 7, 4, 3, 8])
expected = [1, 3, 4, 7, 8, 9]
output = heap.heap_sort()
assert output == expected
|
class Heap:
def __init__(self, from_list=None):
self.heap = [0]
if from_list:
self.heap.extend(from_list)
self.heapify()
def heapify(self):
if len(self.heap) > 2:
current_sub_heap_index = (len(self.heap) - 1) // 2
while current_sub_heap_index > 0:
self.down_heap(current_sub_heap_index)
current_sub_heap_index = current_sub_heap_index - 1
def down_heap(self, root_index):
while root_index * 2 < len(self.heap):
left_child_index = root_index * 2
right_child_index = (root_index * 2) + 1
if right_child_index > len(self.heap) - 1:
index_of_largest_child = left_child_index
else:
if self.heap[right_child_index] > self.heap[left_child_index]:
index_of_largest_child = right_child_index
else:
index_of_largest_child = left_child_index
if self.heap[root_index] < self.heap[index_of_largest_child]:
self.swap(root_index, index_of_largest_child)
root_index = index_of_largest_child
else:
break
def swap(self, index_of_first_number, index_of_second_number):
temp = self.heap[index_of_first_number]
self.heap[index_of_first_number] = self.heap[index_of_second_number]
self.heap[index_of_second_number] = temp
def insert(self, value_to_insert):
if value_to_insert:
self.heap.append(value_to_insert)
starting_index = len(self.heap) - 1
self.up_heap(starting_index)
def up_heap(self, root_index):
while root_index > 1:
parent_index = root_index // 2
if self.heap[root_index] > self.heap[parent_index]:
self.swap(root_index, parent_index)
root_index = parent_index
else:
break
def heap_sort(self):
sorted_list = []
while len(self.heap) > 1:
max_node = self.delete()
sorted_list.insert(0, max_node)
return sorted_list
def delete(self):
if len(self.heap) > 1:
root_index = 1
temp = self.heap[root_index]
index_of_last_node = len(self.heap) - 1
self.swap(root_index, index_of_last_node)
del self.heap[index_of_last_node]
self.down_heap(root_index)
return temp
|
#!/usr/bin/env python
#-*-coding=utf-8-*-
'''
@author [email protected] (jiangdapeng)
@date 2014-10-14
@from netease interview problem
'''
'''
problem:
calculate f(a,b) = f(a-1,b) + f(a,b-1)
given:
f(0,b) = b
f(a,0) = 1
for a >=0 , b>=0
'''
# using closure
def gen_calculator(a,b):
table = [[0 for j in range(b+1)] for i in range(a+1)]
for i in range(b+1):
table[0][i] = i
for i in range(a+1):
table[i][0] = 1
def do_fab(a,b):
if a == 0:
return b
if b == 0:
return 1
if table[a][b] == 0:
table[a][b] = do_fab(a-1,b) + 2*do_fab(a,b-1)
return table[a][b]
return do_fab
def test():
f = gen_calculator(10,10)
print "f(0,0) = %d" % (f(0,0))
print "f(0,1) = %d" % (f(0,1))
print "f(1,0) = %d" % (f(1,0))
print "f(1,1) = %d" % (f(1,1))
print "f(2,3) = %d" % (f(2,3))
print "f(10,10) = %d" % (f(10,10))
if __name__ == '__main__':
test()
|
class ListNode:
def __init__(self, val=None, next=None):
if val is None:
val = 0
self.val = val
self.next = next
def reverse(self):
if self.next is None:
return self
first = self
prev = None
while first is not None:
_next = first.next
first.next = prev
prev = first
first = _next
return prev
def __str__(self):
return str(self.val)
class LinkedList:
def __init__(self, *values):
self.head = None
self.tail = None
if len(values) > 0:
self.head = ListNode(values[0])
self.tail = self.head
if len(values) > 1:
node = self.head
for i in range(1, len(values)):
node.next = ListNode(values[i])
node = node.next
self.tail = node
def __len__(self):
length = 1
node = self
while True:
if node.next is None:
break
else:
length += 1
node = node.next
return length
def __reversed__(self):
if self.head:
self.head.reverse()
def __iter__(self):
node = self.head
while True:
if node is None:
break
yield node.val
node = node.next
def printAll(self):
x = str(self.head.val)
if self.head.next is None:
print(x)
return x
else:
head = self.head.next
while head:
x = x + " -> " + str(head.val)
head = head.next
# print(x)
return x
def prepend(self, val):
if self.head is None:
self.head = ListNode(val)
self.tail = self.head
else:
temp = self.head
self.head = ListNode(val=val, next=temp)
def append(self, val):
if self.head is None:
self.head = ListNode(val)
self.tail = self.head
else:
self.tail.next = ListNode(val)
self.tail = self.tail.next
def insert(self, index, val):
if index == 0:
self.prepend(val)
return
node = ListNode(val)
prev = self.head
for i in range(index - 1):
prev = prev.next
_next = prev.next
prev.next = node
node.next = _next
def add_by_popularity(self, string, called_times):
node = self.head
index = 0
while True:
if node is None:
self.append((string,called_times))
break
if node.val[1] <= called_times:
self.insert(index,(string,called_times))
break
node = node.next
index += 1
def sort_by_popularity(self, node_index: int, called_times: int):
if node_index == 0: # if node already at the beginning
return
node = self.head
index = 0
selected_node = None
selected_index = None
while True:
if index == node_index - 1:
selected_node = node.next # save selected_node
if node.val.called_times <= called_times and selected_index is None:
selected_index = index
node = node.next
index += 1
if node is None:
break
if selected_node and selected_index is not None:
self.insert(selected_index, selected_node.val)
self.remove(node_index+1)
def remove(self, index: int):
if index == 0: # if head
head = self.head
self.head = self.head.next
del head
return
i = 0
node = self.head
while True:
if i == index - 1:
node.next = node.next.next # remove selected_node from position
if node.next is None:
self.tail = node
node = node.next
i += 1
if node is None:
break
# def replace(self, node1: ListNode = None, node2: ListNode = None, prev1: ListNode = None, prev2: ListNode = None):
# prev2.next = node1
#
# if prev1 is not None:
# prev1.next = node2
# else: # node1 is head
# self.head = node2
#
# node1.next, node2.next = node2.next, node1.next
# tail is not finished
|
#Program berikut menggunakan Tkinter Widget GUI
#Source code yang digunakan adalah Python
#Source code berikut digunakan untuk mengecek informasi memori (RAM)
from tkinter import * #memanggil library Tkinter
import subprocess as sub #memanggil library subprocess dan dinyatakan sebagai sub
p = sub.Popen(('cat', '/proc/meminfo'), stdout=sub.PIPE) #code untuk mengecek informasi memori pada Linux
keluaran = sub.check_output(('head', '-6'), stdin=p.stdout) #meminta hasil keluaran hanya sebanyak 6 informasi memori
root = Tk() #memanggil program Tkinter
text = Text(root) #mendklarasikan text ke dalam Tkinter
text.pack() #membuat garis pinggir pada Tkinter
text.insert(END, keluaran) #memasukkan text berupa hasil pada code keluaran
l = Label(root, text="Alvin Memory Usage") #membuat judul Label
l.config(font =("Courier", 14)) #mengatur font judul Label
l.pack() #menampilkan judul Label
root.mainloop() #menjalankan program Tkinter Widget GUI
|
class SNode:
def __init__(self, value):
self.value = value
self.next = None
class SList:
def __init__(self):
self.head = None
def add_to_front(self, val):
new_node = SLNode(val)
current_head = self.head
new_node.next = current_head
self.head = new_node # SET the list's head TO the node we created in the last step
return self # return self to allow for chaining
#______________________________________________________________________________________________________
my_list = SList() |
class BankAccount:
def __init__(self, balance=0.00 ,int_rate=0.01): # don't forget to add some default values for these parameters!
self.accountBalance = balance
self.accountInterestRate =int_rate
# increases the account balance by the given amount
def deposit(self, amount):
self.accountBalance += amount
return self
# decreases the account balance by the given amount if there are sufficient funds; if there is not enough money, print a message "Insufficient funds: Charging a $5 fee" and deduct $5
def withdraw(self, amount):
if self.accountBalance <=0:
print("Insufficient funds: Charging a $5 fee")
self.accountBalance -=5
self.accountBalance -= amount
return self
# print to the console: eg. "Balance: $100"
def display_account_info(self):
print("Balance:","$"+ str(self.accountBalance))
return self
# increases the account balance by the current balance * the interest rate (as long as the balance is positive)
def yield_interest(self):
if self.accountBalance >0 :
self.accountBalance += (self.accountBalance * self.accountInterestRate)
return self
# ****************************************************************************************************************
acount1 = BankAccount(1500,0.02)
acount2 = BankAccount(3000)
acount1.display_account_info()
acount2.display_account_info()
#_________________________________________
print("-------"*9)
acount1.deposit(300).deposit(200).deposit(100).withdraw(100).yield_interest().display_account_info()
#_________________________________________
print("-------"*9)
acount2.deposit(1000).deposit(500).withdraw(100).withdraw(50).withdraw(150).withdraw(200).yield_interest().display_account_info() |
def mergesort(arr, start, end):
if end - start > 1:
mid = (start + end)//2
mergesort(arr, start, mid)
mergesort(arr, mid, end)
merge_arr(arr, start, mid, end)
def merge_arr(arr, start, mid, end):
left = arr[start:mid]
right = arr[mid:end]
k = start
i = 0
j = 0
while (start + i < mid and mid + j < end):
if (left[i] <= right[j]):
arr[k] = left[i]
i = i + 1
else:
arr[k] = right[j]
j = j + 1
k = k + 1
if start + i < mid:
while k < end:
arr[k] = left[i]
i = i + 1
k = k + 1
else:
while k < end:
arr[k] = right[j]
j = j + 1
k = k + 1
arr = input('Enter elements: ').split()
arr = [int(x) for x in arr]
mergesort(arr, 0, len(arr))
print('Sorted list: ', end='')
print(arr) |
class Node(object):
def __init__(self, val, parent, color):
self.val = val
self.left = None
self.right = None
self.color = color
self.parent = parent
class RB_tree(object):
#RR rotation:
def RR(self,node):
t = node.left
parent = node.parent
p = t.right
t.right = node
node.left = p
return t
#LL rotation:
def LL(self,node):
t = node.right
p = t.left
t.left = node
node.right = p
return t
#LR rotation:
def LR(self,node):
t = node.right
null = node.left
p = t.left
p.right = t
p.left = node
node.right = null
t.left = null
return p
#RL rotation
def RL(self,node):
t = node.left
null = node.right
p = t.right
p.left = t
p.right = node
node.left = null
t.right = null
return p
def Balance(self,root,node):
if (node.parent is None):
return root
#If node's parent is black no need of balancing:
if(node.parent.color == 'B'):
return root
#loop till node is not root and node's parent color is red:
while (node.parent != None) and (node.parent.color == 'R'):
#get the uncle node :
if (node.parent == node.parent.parent.left):
uncle = node.parent.parent.right
#case: when uncle is absent or black:
if(uncle == None) or (uncle.color == 'B'):
if(node.parent.parent.parent == None) and (node != node.parent.right):
if(root.right == node.parent):
tnode = self.RR(node.parent.parent)
color = tnode.color
tnode.parent = None
tnode.right.parent = tnode
tnode.color = tnode.right.color
tnode.right.color = color
root = tnode
return root
elif(node != node.parent.right):
if(node.parent.parent.parent.right == node.parent.parent):
tnode = self.RR(node.parent.parent)
node.parent.parent.parent.right = tnode
else:
tnode = self.RR(node.parent.parent)
node.parent.parent.parent.left = tnode
if(node == node.parent.right):
if(node.parent.parent.parent.right == node.parent.parent):
tnode = self.RL(node.parent.parent)
node.parent.parent.parent.right = tnode
else:
tnode = self.RL(node.parent.parent)
node.parent.parent.parent.left = tnode
tnode.parent = node.parent.parent.parent
tnode.right.parent = tnode
tnode.left.parent = tnode
color = tnode.color
tnode.color = tnode.right.color
tnode.right.color = color
return root
elif(uncle != None) and (uncle.color == 'R'):
node.parent.color = 'B'
uncle.color = 'B'
if(node.parent.parent.parent != None):
node.parent.parent.color = 'R'
node = node.parent.parent
else:
break
else:
if(node.parent == node.parent.parent.left):
uncle = node.parent.parent.right
else:
uncle = node.parent.parent.left
#case: when uncle is absent or black:
if(uncle == None) or (uncle.color == 'B'):
if(node == node.parent.right) and (node.parent != node.parent.parent.left):
if(node.parent.parent.parent == None):
if(root.right == node.parent):
tnode = self.LL(node.parent.parent)
tnode.parent = None
tnode.left.parent = tnode
color = tnode.color
tnode.color = tnode.left.color
tnode.left.color = color
root = tnode
return root
else:
if(node.parent.parent.parent.right == node.parent.parent):
tnode = self.LL(node.parent.parent)
node.parent.parent.parent.right = tnode
else:
tnode = self.LL(node.parent.parent)
node.parent.parent.parent.left = tnode
elif(node == node.parent.left):
if(node.parent.parent.parent.right == node.parent.parent):
tnode = self.LR(node.parent.parent)
node.parent.parent.parent.right = tnode
else:
tnode = self.LR(node.parent.parent)
node.parent.parent.parent.left = tnode
tnode.parent = node.parent.parent.parent
tnode.left.parent = tnode
tnode.right.parent = tnode
color = tnode.color
tnode.color = tnode.left.color
tnode.left.color = color
return root
elif(uncle != None) and (uncle.color == 'R'):
node.parent.color = 'B'
uncle.color = 'B'
if(node.parent.parent.parent != None):
node.parent.parent.color = 'R'
node = node.parent.parent
return root
def add_node(self,root,node) :
if root is None:
return
else:
if root.val < node.val:
if root.right is None:
node.parent = root
root.right = node
else:
self.add_node(root.right, node)
else:
if root.left is None:
node.parent = root
root.left = node
else:
self.add_node(root.left, node)
def insert(self,root, val):
if root is None:
return Node(val,None,'B')
else :
node = Node(val,None,'R')
self.add_node(root,node)
root = self.Balance(root,node)
return root
def Search(root,key):
if root is None:
return
if(root.val == key):
print('Element found !')
if(root.val < key):
Search(root.right,key)
elif (root.val> key):
Search(root.left,key)
def Preorder(root):
if root is None:
return
print(root.val,'(',root.color,')', end = " ")
Preorder(root.left)
Preorder(root.right)
def main():
list = [1,2,3,4,5,6,7]
rb_tree = RB_tree()
root = None
for i in list:
root = rb_tree.insert(root,i)
print('Preorder Traversal of RED BLACK TREE:')
Preorder(root)
x = int(input('\n Enter key to be searched:'))
Search(root,x)
if __name__ == "__main__":
main() |
from random import randint
def start():
user_numbers = get_lottery_numbers()
randomized_numbers = randomize_lottery_numbers()
print(f"\nUser numbers {user_numbers}")
print(f"\nRandomized numbers {randomized_numbers}")
result = set.intersection(user_numbers, randomized_numbers)
print(f"\nYou got {result} numbers right, price of winning is {100 * len(result)}£.")
def get_lottery_numbers():
numbers = input("\nEnter 6 numbers, separated by comma: ")
splitted_numbers = numbers.split(",")
int_set = {int(number) for number in splitted_numbers}
return int_set
def randomize_lottery_numbers():
# Set will be initialized using set() not {}
numbers = set()
while len(numbers) < 6:
numbers.add(randint(1, 20))
return numbers
start()
|
data = {"name": "Demo", "marks": [10, 20, 30]}
#print(len(["Demo"]))
print(len(data["marks"]))
print(sum(data["marks"]))
marks_sum = sum(data["marks"])
marks_added = len(data["marks"])
print(marks_sum / marks_added)
def print_data(data):
print({data["name"], data["marks"]})
print_data(data) |
from calc import Calculadora
from geo import Geometria
menup = ('''SUB - Linguagem de Programação - Menu Inicial
[1] - Menu Calculadora
[2] - Menu Geometria
[0] - Sair do programa ''')
menuc = ('''SUB - Linguagem de Programação - Menu Calculadora
[1] - Somar
[2] - Subtrair
[3] - Multiplicar
[4] - Dividir
[0] - Retorna ao menu anterior ''')
menug = ('''SUB - Linguagem de Programação - Menu Geometria
[1] - Identificar triângulo
[2] - Área do Triângulo
[3] - Área do Retângulo
[4] - Perímetro do Retângulo
[0] - Retorna ao menu anterior ''')
opção = 1
while opção != 0: # Menu inicial
print(menup)
opção = int(input())
if opção==0:
print('Sair do programa')
break
elif opção==1: # Menu calculadora
cal=1
while cal !=0:
print(menuc)
cal = int(input())
if cal == 1: # Somar
A = int(input('Informe o primeiro numero '))
B = int(input('Informe o segundo numero '))
mycalc = Calculadora(A,B)
r = mycalc.somar()
print('A soma dos numeros digitados é {} \n'.format(r))
elif cal == 2: # Subtrair
A = int(input('Informe o primeiro numero '))
B = int(input('Informe o segundo numero '))
mycalc = Calculadora(A,B)
r = mycalc.subtrair()
print('A diferença entre os numeros digitados é {} \n'.format(r))
elif cal == 3: # Multiplicar
A = int(input('Informe o primeiro numero '))
B = int(input('Informe o segundo numero '))
mycalc = Calculadora(A,B)
r = mycalc.multiplicar()
print('A multiplicação entre os numeros digitados é {} \n'.format(r))
elif cal == 4: # Dividir
A = int(input('Informe o primeiro numero '))
B = int(input('Informe o segundo numero '))
mycalc = Calculadora(A,B)
r = mycalc.dividir()
print('A divisão do primeiro numero digitado pelo segundo numero é {} \n'.format(r))
else:
print('Opção inválida! Escolha uma opção válida no menu \n')
elif opção==2: # Menu geometria
geo=1
while geo !=0:
print(menug)
geo = int(input())
if geo == 1: # Identificar triangulo
X=int(input('Informe a medida do primeiro lado do triangulo '))
Y=int(input('Informe a medida do segundo lado do triangulo '))
Z=int(input('Informe a medida do terceiro lado do triangulo '))
triangulo = Geometria(X,Y,Z)
triangulo.identificarTriangulo()
elif geo == 2: # Calcular area triangulo
X=int(input('Informe a medida da base do triangulo '))
Y=int(input('Informe a medida da altura do triangulo '))
Z=2
triangulo = Geometria(X,Y,Z)
r = triangulo.calcularAreaTriangulo()
print('A área deste triangulo é {} \n'.format(r))
elif geo == 3: # Calcular area retangulo
X=int(input('Informe a medida da base do retangulo '))
Y=int(input('Informe a medida da altura do retangulo '))
Z=1
triangulo = Geometria(X,Y,Z)
r = triangulo.calcularAreaRetangulo()
print('A área deste retangulo é {} \n'.format(r))
elif geo == 4: # Calcular perimetro retangulo
X=int(input('Informe a medida da base do retangulo '))
Y=int(input('Informe a medida da altura do retangulo '))
Z=2
triangulo = Geometria(X,Y,Z)
r = triangulo.calcularPerietroRetangulo()
print('O perímetro deste retangulo é {} \n'.format(r))
else:
print('Opção inválida! Escolha uma opção válida no menu \n')
else:
print('Opção inválida! Escolha uma opção válida no menu \n') |
# coding=utf-8
"""
__Arthur Marble__
This is the game manager class. It includes the main game loop and runs until
the program ends. It is a parent class to GameView classes.
"""
import pygame
from . import ResourceLoader
class GameManager:
"""
GameManager Class
"""
def __init__(self):
pygame.init()
self.fullscreen = False
self.screen_width = 640
self.screen_height = 400
self.fps = 60
self.playing = True
self.caption = "Hangman Clone!"
self.sample_rate = 8000 # This should remain at 8000.
self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))
self.screen_rect = self.screen.get_rect()
pygame.display.set_caption(self.caption)
pygame.mixer.init(self.sample_rate) # All sound effects will have this sample rate
# Hardcoded to SplashScreen because that is how the game is designed to
# start. If you want another GameView class make your own set or modify
# my code.
self.resource_loader = ResourceLoader()
self.current_screen = self.resource_loader.load_class('splash screen',
self)
self.previous_screen = None
def get_input(self):
"""
Handle Input
"""
self.current_screen.get_input(self)
def recalculate(self):
"""
Handle Logic
"""
self.screen_rect = self.screen.get_rect()
self.current_screen.recalculate(self)
def render(self):
"""
Render Screen
"""
self.current_screen.render(self)
def run_game_loop(self):
"""
Game loop
This runs forever until self.playing is equal to false or when
self.current_screen = None (Would cause crash/not clean exit atm.)
"""
while self.playing:
# Handle input
self.get_input()
# Logic handling
self.recalculate()
# Render screen
self.render()
pygame.time.Clock().tick(self.fps)
else:
pygame.quit()
|
import turtle
my_turtle = turtle.Turtle()
my_turtle.pencolor("red")
for i in range(50):
my_turtle.forward(50)
my_turtle.right(123)
my_turtle.pencolor("blue")
for i in range(50):
my_turtle.forward(100)
my_turtle.right(123)
turtle.done()
|
#!/usr/bin/env python
"""The data structures to store a schedule (task system), along with all
the job releases and other events that have occurred for each task. This gives
a high-level representation of a schedule that can be converted to, say, a
graphic."""
from graph import *
import util
import copy
EVENT_LIST = None
SPAN_EVENTS = None
class TimeSlotArray(object):
"""Represents another way of organizing the events. This structure organizes events by
the (approximate) time at which they occur. Events that occur at approximately the same
time are assigned the same ``slot'', and each slot organizes its events by task number
as well as by CPU."""
TASK_LIST = 0
CPU_LIST = 1
def __init__(self, time_per_maj=None, num_tasks=0, num_cpus=0):
if time_per_maj is None:
self.array = None
return
self.time_per_maj = time_per_maj
self.list_sizes = { TimeSlotArray.TASK_LIST : num_tasks, TimeSlotArray.CPU_LIST : num_cpus }
self.array = {}
for type in self.list_sizes:
num = self.list_sizes[type]
self.array[type] = []
for j in range(0, num):
# for each slot in the array, we need a list of all events under this type
# (for example, a list of all events that occur in this time slot, indexed
# by task).
self.array[type].append(dict(zip(EVENT_LIST, \
[{} for j in range(0, len(EVENT_LIST))])))
def get_time_slot(self, time):
return int(time // self.time_per_maj)
def _put_event_in_slot(self, list_type, no, klass, slot, event):
if slot not in self.array[list_type][no][klass]:
self.array[list_type][no][klass][slot] = []
self.array[list_type][no][klass][slot].append(event)
def add_event_to_time_slot(self, event):
task_no = event.get_job().get_task().get_task_no()
cpu = event.get_cpu()
time_slot = self.get_time_slot(event.get_time())
self._put_event_in_slot(TimeSlotArray.TASK_LIST, task_no, event.__class__, time_slot, event)
self._put_event_in_slot(TimeSlotArray.CPU_LIST, cpu, event.__class__, time_slot, event)
if event.__class__ in SPAN_END_EVENTS:
self.fill_span_event_from_end(event)
def fill_span_event_from_end(self, event):
start_slot = None
if event.corresp_start_event is None:
start_slot = self.get_time_slot(event.get_job().get_task().get_schedule().start) - 1
else:
start_slot = self.get_time_slot(event.corresp_start_event.get_time())
end_slot = self.get_time_slot(event.get_time())
for slot in range(start_slot + 1, end_slot):
task_no = event.get_job().get_task().get_task_no()
cpu = event.get_cpu()
dummy = SPAN_END_EVENTS[event.__class__](task_no, cpu)
dummy.corresp_start_event = event.corresp_start_event
dummy.corresp_end_event = event
self._put_event_in_slot(TimeSlotArray.TASK_LIST, task_no, dummy.__class__, slot, dummy)
self._put_event_in_slot(TimeSlotArray.CPU_LIST, cpu, dummy.__class__, slot, dummy)
def fill_span_event_from_start(self, event):
end_slot = None
if event.corresp_end_event is None:
end_slot = self.get_time_slot(event.get_job().get_task().get_schedule().end) + 1
else:
end_slot = self.get_time_slot(event.corresp_end_event.get_time())
start_slot = self.get_time_slot(event.get_time())
for slot in range(start_slot + 1, end_slot):
task_no = event.get_job().get_task().get_task_no()
cpu = event.get_cpu()
dummy = SPAN_START_EVENTS[event.__class__](task_no, cpu)
dummy.corresp_start_event = event
dummy.corresp_end_event = event.corresp_end_event
self._put_event_in_slot(TimeSlotArray.TASK_LIST, task_no, dummy.__class__, slot, dummy)
self._put_event_in_slot(TimeSlotArray.CPU_LIST, cpu, dummy.__class__, slot, dummy)
def get_events(self, slots, list_type, event_types):
for type in event_types:
for slot in slots:
for no in slots[slot]:
if slot in self.array[list_type][no][type]:
for event in self.array[list_type][no][type][slot]:
yield event
def get_slots(self, slots, start, end, start_no, end_no, list_type):
if self.array is None:
return # empty schedule
if start > end:
raise ValueError('Litmus is not a time machine')
if start_no > end_no:
raise ValueError('start no should be less than end no')
start_slot = self.get_time_slot(start)
end_slot = self.get_time_slot(end) + 1
start_no = max(0, start_no)
end_no = min(self.list_sizes[list_type] - 1, end_no)
for slot in xrange(start_slot, end_slot + 1):
if slot not in slots:
slots[slot] = {}
for no in xrange(start_no, end_no + 1):
slots[slot][no] = None
class Schedule(object):
"""The total schedule (task system), consisting of a certain number of
tasks."""
def __init__(self, name, num_cpus, task_list=[]):
self.name = name
self.tasks = {}
self.task_list = []
self.selected = {}
self.time_slot_array = None
self.cur_task_no = 0
self.num_cpus = num_cpus
self.jobless = []
for task in task_list:
self.add_task(task)
def get_selected(self):
return self.selected
def set_selected(self, selected):
self.selected = selected
def add_selected(self, selected):
for layer in selected:
if layer not in self.selected:
self.selected[layer] = {}
for event in selected[layer]:
if event not in self.selected:
self.selected[layer][event] = {}
for graph in selected[layer][event]:
self.selected[layer][event][graph] = selected[layer][event][graph]
def remove_selected(self, selected):
for layer in selected:
if layer in self.selected:
for event in selected[layer]:
if event in self.selected[layer]:
del self.selected[layer][event]
def set_time_params(self, time_per_maj=None):
self.time_per_maj = time_per_maj
if self.time_per_maj is None:
self.time_slot_array = TimeSlotArray()
return
self.time_slot_array = TimeSlotArray(self.time_per_maj, \
len(self.task_list), self.num_cpus)
def get_time_slot_array(self):
return self.time_slot_array
def get_time_bounds(self):
return (self.start, self.end)
def scan(self, time_per_maj):
self.start = None
self.end = None
self.set_time_params(time_per_maj)
# we scan the graph task by task, and job by job
for task_no, task in enumerate(self.get_task_list()):
switches = {}
for event in EVENT_LIST:
switches[event] = None
cur_cpu = [Event.NO_CPU]
for job_no in sorted(task.get_jobs().keys()):
job = task.get_jobs()[job_no]
for event_time in sorted(job.get_events().keys()):
# could have multiple events at the same time (unlikely but possible)
for event in job.get_events()[event_time]:
event.scan(cur_cpu, switches)
# What if one of the initial "span events" (switch to or inversion starting) never got a
# corresponding end event? Well, then we assume that the end event was simply outside of
# the range of whatever we read in. So we need to fill dummies starting from the initial
# event all the way to the end of the graph, so that the renderer can see the event no matter
# how far the user scrolls to the right.
for span_event in SPAN_START_EVENTS:
event = switches[span_event]
if event is not None:
self.time_slot_array.fill_span_event_from_start(event)
def add_task(self, task):
if task.name in self.tasks:
raise ValueError("task already in list!")
self.tasks[task.name] = task
self.task_list.append(task)
task.schedule = self
task.task_no = self.cur_task_no
self.cur_task_no += 1
def add_jobless(self, event):
self.jobless.append(event)
def sort_task_nos_numeric(self):
# sort task numbers by the numeric value of the task names.
nums = []
for task_name in self.tasks:
nums.append((int(task_name), task_name))
nums.sort(key=lambda t: t[0])
for no, task in enumerate(nums):
self.tasks[task[1]].task_no = no
def get_jobless(self):
return self.jobless
def get_tasks(self):
return self.tasks
def get_task_list(self):
return self.task_list
def get_name(self):
return self.name
def get_num_cpus(self):
return self.num_cpus
def deepcopy_selected(selected):
selected_copy = {}
for layer in selected:
selected_copy[layer] = copy.copy(selected[layer])
return selected_copy
class Task(object):
"""Represents a task, including the set of jobs that were run under
this task."""
def __init__(self, name, job_list=[]):
self.name = name
self.jobs = {}
self.task_no = None
self.schedule = None
for job in job_list:
self.add_job(job)
def add_job(self, job):
if job.job_no in self.jobs:
raise ScheduleError("a job is already being released at this time for this task")
self.jobs[job.job_no] = job
job.task = self
def get_schedule(self):
return self.schedule
def get_jobs(self):
return self.jobs
def get_task_no(self):
return self.task_no
def get_name(self):
return self.name
class Job(object):
"""Represents a job, including everything that happens related to the job"""
def __init__(self, job_no, event_list=[]):
self.job_no = job_no
self.events = {}
self.task = None
for event in event_list:
self.add_event(event)
def add_event(self, event):
if event.time not in self.events:
self.events[event.time] = []
self.events[event.time].append(event)
event.job = self
def get_events(self):
return self.events
def get_task(self):
return self.task
def get_job_no(self):
return self.job_no
class DummyEvent(object):
"""Represents some event that occurs, but might not actually be
a full-fledged ``event'' in the schedule. It might instead be a dummy
event added by the application to speed things up or keep track of
something. Such an event won't be added to the schedule tree, but
might appear in the time slot array."""
def __init__(self, time, cpu):
self.time = time
self.cpu = cpu
self.job = None
self.layer = None
self.saved_schedule = None
def __str__(self):
return '[Dummy Event]'
def get_time(self):
return self.time
def get_cpu(self):
return self.cpu
# Refactor, shouldn't depend on job
def get_schedule(self):
if self.saved_schedule is not None:
return self.saved_schedule
elif self.get_task() is not None:
return self.get_task().get_schedule()
else:
return None
# Needed for events not assigned to specific tasks
def set_schedule(self, schedule):
self.saved_schedule = schedule
def get_task(self):
if self.get_job() is not None:
return self.get_job().get_task()
else:
return None
def get_job(self):
return self.job
def get_layer(self):
return self.layer
def render(self, graph, layer, prev_events, selectable=False):
"""Method that the visualizer calls to tell the event to render itself
Obviously only implemented by subclasses (actual event types)
``Rendering'' can mean either actually drawing the event or just
adding it as a selectable region. This is controlled by the
``selectable'' parameter"""
raise NotImplementdError
class Event(DummyEvent):
"""Represents an event that occurs while a job is running (e.g. get scheduled
on a CPU, block, ...)"""
NO_CPU = -1
NUM_DEC_PLACES = 2
def __init__(self, time, cpu):
super(Event, self).__init__(time, cpu)
self.erroneous = False
def get_name(self):
raise NotImplementedError
def __str__(self):
return self.get_name() + self._common_str() + ', TIME=' + util.format_float(self.get_time(), Event.NUM_DEC_PLACES)
def str_long(self, unit):
if self.get_job() is not None:
"""Prints the event as a string, in ``long'' form."""
return 'Event Information\n-----------------\n' + \
'Event Type: ' + self.get_name() + \
'\nTask Name: ' + str(self.get_job().get_task().get_name()) + \
'\n(Task no., Job no.): ' + str((self.get_job().get_task().get_task_no(), \
self.get_job().get_job_no())) + \
'\nCPU: ' + str(self.get_cpu()) + \
'\nTime: ' + _format_time(self.get_time(), unit) + \
'\n\n' + self.get_job().str_long(unit)
else:
"""Prints the event as a string, in ``long'' form."""
return 'Event Information\n-----------------\n' + \
'Event Type: ' + self.get_name() + \
'\nTask Name: None' + \
'\nCPU: ' + str(self.get_cpu()) + \
'\nTime: ' + _format_time(self.get_time(), unit)
def _common_str(self):
if self.get_job() is not None:
job = self.get_job()
task = job.get_task()
return ' for task ' + str(task.get_name()) + ': (TASK, JOB)=' + \
str((task.get_task_no(), job.get_job_no())) + \
', CPU=' + str(self.get_cpu())
else:
return ', Cpu=' + str(self.get_cpu())
def is_erroneous(self):
"""An erroneous event is where something with the event is not quite right,
something significantly wrong that we don't have logical information telling
us how we should render the event."""
return self.erroneous
def is_selected(self):
"""Returns whether the event has been selected by the user. (needed for rendering)"""
selected = self.get_job().get_task().get_schedule().get_selected()
return self.get_layer() in selected and self in selected[self.get_layer()]
def scan(self, cur_cpu, switches):
"""Part of the procedure that walks through all the events and sets
some parameters that are unknown at first. For instance, a SwitchAwayEvent
should know when the previous corresponding SwitchToEvent occurred, but
the data does not tell us this, so we have to figure that out on our own
by scanning through the events. ``cur_cpu'' gives the current CPU at this
time in the scan, and ``switches'' gives the last time a certain switch
(e.g. SwitchToEvent, InversionStartEvent) occurred"""
time = self.get_time()
sched = self.get_schedule()
if sched is not None:
if sched.start is None or time < sched.start:
sched.start = time
if sched.end is None or time > sched.end:
sched.end = time
if item_nos is None:
item_nos = { TimeSlotArray.TASK_LIST : self.get_task().get_task_no(),
TimeSlotArray.CPU_LIST : self.get_cpu() }
sched.get_time_slot_array().add_event_to_time_slot(self, item_nos)
self.fill_span_event_from_end()
def fill_span_event_from_start(self):
"""This method exists for events that can ``range'' over a period of time
(e.g. SwitchAway and SwitchTo). In case a start event is not paired with
an end event, or vice versa, we want to fill in dummy events to range all
the way to the beginning or end. Since most events occur only at a specific
time, this is usually a no-op."""
pass
def fill_span_event_from_end(self):
"""The mirror image of the last method."""
pass
class SpanEvent(Event):
def __init__(self, time, cpu, dummy_class):
super(SpanEvent, self).__init__(time, cpu)
self.dummy_class = dummy_class
class SpanDummy(DummyEvent):
def __init__(self):
super(SpanDummy, self).__init__(None, None)
def get_task(self):
if self.corresp_start_event is not None:
return self.corresp_start_event.get_task()
if self.corresp_end_event is not None:
return self.corresp_end_event.get_task()
return None
def get_schedule(self):
if self.corresp_start_event is not None:
return self.corresp_start_event.get_schedule()
if self.corresp_end_event is not None:
return self.corresp_end_event.get_schedule()
return None
class ErrorEvent(Event):
pass
class SuspendEvent(Event):
def __init__(self, time, cpu):
super(SuspendEvent, self).__init__(time, cpu)
self.layer = Canvas.MIDDLE_LAYER
def get_name(self):
return 'Suspend'
def scan(self, cur_cpu, switches):
if self.get_cpu() != cur_cpu[0]:
self.erroneous = True
#fprint "suspending on a CPU different from the CPU we are on!"
super(SuspendEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
if layer == self.layer:
prev_events[self] = None
if selectable:
graph.add_sel_suspend_triangle_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self.get_cpu(), self)
else:
graph.draw_suspend_triangle_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self.get_cpu(), self.is_selected())
class ResumeEvent(Event):
def __init__(self, time, cpu):
super(ResumeEvent, self).__init__(time, cpu)
self.layer = Canvas.MIDDLE_LAYER
def get_name(self):
return 'Resume'
def scan(self, cur_cpu, switches):
if cur_cpu[0] != Event.NO_CPU and cur_cpu[0] != self.get_cpu():
self.erroneous = True
#print "Resuming when currently scheduled on a CPU, but on a different CPU from the current CPU!"
super(ResumeEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
if layer == self.layer:
prev_events[self] = None
if selectable:
graph.add_sel_resume_triangle_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self.get_cpu(), self)
else:
graph.draw_resume_triangle_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self.get_cpu(), self.is_selected())
class CompleteEvent(Event):
def __init__(self, time, cpu):
super(CompleteEvent, self).__init__(time, cpu)
self.layer = Canvas.TOP_LAYER
def get_name(self):
return 'Complete'
def scan(self, cur_cpu, switches):
super(CompleteEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
if layer == Canvas.TOP_LAYER:
prev_events[self] = None
if selectable:
graph.add_sel_completion_marker_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self.get_cpu(), self)
else:
graph.draw_completion_marker_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self.get_cpu(), self.is_selected())
class SwitchToEvent(Event):
def __init__(self, time, cpu):
super(SwitchToEvent, self).__init__(time, cpu)
self.layer = Canvas.BOTTOM_LAYER
self.corresp_end_event = None
def get_name(self):
if self.corresp_end_event is None:
return 'Switch To (w/o Switch Away)'
else:
return 'Scheduled'
def __str__(self):
if self.corresp_end_event is None:
return super(SwitchToEvent, self).__str__()
return self.get_name() + self._common_str() + ', START=' \
+ util.format_float(self.get_time(), Event.NUM_DEC_PLACES) \
+ ', END=' + util.format_float(self.corresp_end_event.get_time(), Event.NUM_DEC_PLACES)
def str_long(self):
if self.corresp_end_event is None:
return super(SwitchToEvent, self).str_long()
else :
return 'Event Type: ' + self.get_name() + \
'\nTask Name: ' + str(self.get_job().get_task().get_name()) + \
'\n(Task no., Job no.): ' + str((self.get_job().get_task().get_task_no(), \
self.get_job().get_job_no())) + \
'\nCPU: ' + str(self.get_cpu()) + \
'\nStart: ' + str(self.get_time()) + \
'\nEnd: ' + str(self.corresp_end_event.get_time())
def scan(self, cur_cpu, switches):
old_cur_cpu = cur_cpu[0]
cur_cpu[0] = self.get_cpu()
switches[SwitchToEvent] = self
self.corresp_end_event = None
if old_cur_cpu != Event.NO_CPU:
self.erroneous = True
#print "currently scheduled somewhere, can't switch to a CPU"
super(SwitchToEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
if layer == self.layer:
end_time = None
clip = None
if self.corresp_end_event is None:
end_time = self.get_job().get_task().get_schedule().end
clip = AlignMode.RIGHT
else:
end_time = self.corresp_end_event.get_time()
prev_events[self] = None
cpu = self.get_cpu()
task_no = self.get_job().get_task().get_task_no()
if selectable:
graph.add_sel_bar_at_time(self.get_time(), end_time,
task_no, cpu, self)
else:
graph.draw_bar_at_time(self.get_time(), end_time,
task_no, cpu, self.get_job().get_job_no(),
clip, self.is_selected())
class SwitchAwayEvent(Event):
def __init__(self, time, cpu):
super(SwitchAwayEvent, self).__init__(time, cpu)
self.layer = Canvas.BOTTOM_LAYER
self.corresp_start_event = None
def get_name(self):
if self.corresp_start_event is None:
return 'Switch Away (w/o Switch To)'
else:
return 'Scheduled'
def __str__(self):
if self.corresp_start_event is None:
return super(SwitchAwayEvent, self).__str__()
return str(self.corresp_start_event)
def str_long(self):
if self.corresp_start_event is None:
return super(SwitchAwayEvent, self).str_long()
return self.corresp_start_event.str_long()
def scan(self, cur_cpu, switches):
old_cur_cpu = cur_cpu[0]
self.corresp_start_event = switches[SwitchToEvent]
cur_cpu[0] = Event.NO_CPU
switches[SwitchToEvent] = None
if self.corresp_start_event is not None:
self.corresp_start_event.corresp_end_event = self
if self.get_cpu() != old_cur_cpu:
self.erroneous = True
#print "switching away from a CPU different from the CPU we are currently on"
if self.corresp_start_event is None:
self.erroneous = True
#print "switch away was not matched by a corresponding switch to"
elif self.get_time() < self.corresp_start_event.get_time():
self.erroneous = True
#print "switching away from a processor before we switched to it?!"
super(SwitchAwayEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
if self.corresp_start_event is None:
# We never found a corresponding start event. In that case, we can assume it lies
# in some part of the trace that was never read in. So draw a bar starting from
# the very beginning.
if layer == self.layer:
prev_events[self] = None
cpu = self.get_cpu()
task_no = self.get_job().get_task().get_task_no()
start = self.get_job().get_task().get_schedule().start
if selectable:
graph.add_sel_bar_at_time(start, self.get_time(),
task_no, cpu, self)
else:
graph.draw_bar_at_time(start, self.get_time(),
task_no, cpu, self.get_job().get_job_no(),
AlignMode.LEFT, self.is_selected())
else:
if self.corresp_start_event in prev_events:
return # already rendered the bar
self.corresp_start_event.render(graph, layer, prev_events, selectable)
class ReleaseEvent(Event):
def __init__(self, time, cpu):
super(ReleaseEvent, self).__init__(time, cpu)
self.layer = Canvas.TOP_LAYER
def get_name(self):
return 'Release'
def scan(self, cur_cpu, switches):
super(ReleaseEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
prev_events[self] = None
if layer == Canvas.TOP_LAYER:
if selectable:
graph.add_sel_release_arrow_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self)
else:
graph.draw_release_arrow_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self.get_job().get_job_no(), self.is_selected())
class DeadlineEvent(Event):
def __init__(self, time, cpu):
super(DeadlineEvent, self).__init__(time, cpu)
self.layer = Canvas.TOP_LAYER
def get_name(self):
return 'Deadline'
def scan(self, cur_cpu, switches):
super(DeadlineEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
prev_events[self] = None
if layer == Canvas.TOP_LAYER:
if selectable:
graph.add_sel_deadline_arrow_at_time(self.get_time(), self.get_job().get_task().get_task_no(),
self)
else:
graph.draw_deadline_arrow_at_time(self.get_time(),
self.get_job().get_task().get_task_no(),
self.get_job().get_job_no(), self.is_selected())
class ActionEvent(Event):
def __init__(self, time, cpu, action):
super(ActionEvent, self).__init__(time, cpu)
self.layer = Canvas.TOP_LAYER
self.action = int(action)
def get_name(self):
return 'Action'
def scan(self, cur_cpu, switches):
item_nos = { TimeSlotArray.TASK_LIST : self.get_task().get_task_no(),
TimeSlotArray.CPU_LIST : TimeSlotArray.POST_ITEM_NO }
super(ActionEvent, self).scan(cur_cpu, switches, item_nos)
def render(self, graph, layer, prev_events, selectable=False):
prev_events[self] = None
if layer == Canvas.TOP_LAYER:
# TODO: need a more official way of doing this
task_no = -1
job_no = -1
if self.get_job() is not None:
task_no = self.get_job().get_task().get_task_no()
job_no = self.get_job().get_job_no()
if selectable:
graph.add_sel_action_symbol_at_time(self.get_time(), task_no,
self.get_cpu(), self)
else:
graph.draw_action_symbol_at_time(self.get_time(), task_no,
self.get_cpu(), self.action,
job_no, self.is_selected())
class InversionStartEvent(ErrorEvent):
def __init__(self, time):
super(InversionStartEvent, self).__init__(time, Event.NO_CPU)
self.layer = Canvas.BOTTOM_LAYER
self.corresp_end_event = None
def get_name(self):
if self.corresp_end_event is None:
return 'Inversion Start (w/o Inversion End)'
else:
return 'Priority Inversion'
def __str__(self):
if self.corresp_end_event is None:
return super(InversionStartEvent, self).__str__()
return self.get_name() + self._common_str() + ', START=' \
+ util.format_float(self.get_time(), Event.NUM_DEC_PLACES) \
+ ', END=' + util.format_float(self.corresp_end_event.get_time(), Event.NUM_DEC_PLACES)
def str_long(self):
if self.corresp_end_event is None:
return super(InversionStartEvent, self).str_long()
else :
return 'Event Type: ' + self.get_name() + \
'\nTask Name: ' + str(self.get_job().get_task().get_name()) + \
'\n(Task no., Job no.): ' + str((self.get_job().get_task().get_task_no(), \
self.get_job().get_job_no())) + \
'\nCPU: ' + str(self.get_cpu()) + \
'\nStart: ' + str(self.get_time()) + \
'\nEnd: ' + str(self.corresp_end_event.get_time())
def scan(self, cur_cpu, switches):
switches[InversionStartEvent] = self
self.corresp_end_event = None
# the corresp_end_event should already be set
super(InversionStartEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
if layer == self.layer:
end_time = None
clip = None
if self.corresp_end_event is None:
end_time = self.get_job().get_task().get_schedule().end
clip = AlignMode.RIGHT
else:
end_time = self.corresp_end_event.get_time()
if layer == self.layer:
prev_events[self] = None
cpu = self.get_cpu()
task_no = self.get_job().get_task().get_task_no()
if selectable:
graph.add_sel_mini_bar_at_time(self.get_time(), end_time,
task_no, cpu, self)
else:
graph.draw_mini_bar_at_time(self.get_time(), end_time,
task_no, cpu, self.get_job().get_job_no(),
clip, self.is_selected())
class InversionEndEvent(ErrorEvent):
def __init__(self, time):
super(InversionEndEvent, self).__init__(time, Event.NO_CPU)
self.layer = Canvas.BOTTOM_LAYER
self.corresp_start_event = None
def get_name(self):
if self.corresp_start_event is None:
return 'Inversion End (w/o Inversion Start)'
else:
return 'Priority Inversion'
def __str__(self):
if self.corresp_start_event is None:
return super(InversionEndEvent, self).__str__()
return str(self.corresp_start_event)
def str_long(self):
if self.corresp_start_event is None:
return super(InversionEndEvent, self).str_long()
return self.corresp_start_event.str_long()
def scan(self, cur_cpu, switches):
self.corresp_start_event = switches[InversionStartEvent]
cur_cpu[0] = Event.NO_CPU
switches[InversionStartEvent] = None
if self.corresp_start_event is not None:
self.corresp_start_event.corresp_end_event = self
if self.corresp_start_event is None:
self.erroneous = True
#print "inversion end was not matched by a corresponding inversion start"
super(InversionEndEvent, self).scan(cur_cpu, switches)
def render(self, graph, layer, prev_events, selectable=False):
if self.corresp_start_event is None:
# We never found a corresponding start event. In that case, we can assume it lies
# in some part of the trace that was never read in. So draw a bar starting from
# the very beginning.
if layer == self.layer:
prev_events[self] = None
cpu = self.get_cpu()
task_no = self.get_job().get_task().get_task_no()
start = self.get_job().get_task().get_schedule().start
if selectable:
graph.add_sel_mini_bar_at_time(start, self.get_time(),
task_no, cpu, self)
else:
graph.draw_mini_bar_at_time(start, self.get_time(),
task_no, cpu, self.get_job().get_job_no(),
AlignMode.LEFT, self.is_selected())
else:
if self.corresp_start_event in prev_events:
return # already rendered the bar
self.corresp_start_event.render(graph, layer, prev_events, selectable)
class InversionDummy(DummyEvent):
def __init__(self, time, cpu):
super(InversionDummy, self).__init__(time, Event.NO_CPU)
self.layer = Canvas.BOTTOM_LAYER
def render(self, graph, layer, prev_events, selectable=False):
if self.corresp_start_event is None:
if self.corresp_end_event in prev_events:
return # we have already been rendered
self.corresp_end_event.render(graph, layer, prev_events, selectable)
else:
if self.corresp_start_event in prev_events:
return # we have already been rendered
self.corresp_start_event.render(graph, layer, prev_events, selectable)
class IsRunningDummy(DummyEvent):
def __init__(self, time, cpu):
super(IsRunningDummy, self).__init__(time, Event.NO_CPU)
self.layer = Canvas.BOTTOM_LAYER
def render(self, graph, layer, prev_events, selectable=False):
if self.corresp_start_event is None:
if self.corresp_end_event in prev_events:
return # we have already been rendered
self.corresp_end_event.render(graph, layer, prev_events, selectable)
else:
if self.corresp_start_event in prev_events:
return # we have already been rendered
self.corresp_start_event.render(graph, layer, prev_events, selectable)
EVENT_LIST = {SuspendEvent : None, ResumeEvent : None, CompleteEvent : None,
SwitchAwayEvent : None, SwitchToEvent : None, ReleaseEvent : None,
DeadlineEvent : None, IsRunningDummy : None,
InversionStartEvent : None, InversionEndEvent : None,
InversionDummy : None, TaskDummy : None, CPUDummy : None, ActionEvent: None}
SPAN_START_EVENTS = { SwitchToEvent : IsRunningDummy, InversionStartEvent : InversionDummy }
SPAN_END_EVENTS = { SwitchAwayEvent : IsRunningDummy, InversionEndEvent : InversionDummy}
|
#!/usr/bin/python
"""Miscellanious utility functions that don't fit anywhere."""
def format_float(num, numplaces):
if abs(round(num, numplaces) - round(num, 0)) == 0.0:
return '%.0f' % float(num)
else:
return ('%.' + numplaces + 'f') % round(float(num), numplaces)
|
"""Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
"""
if __name__ == "__main__":
sum = 0
i = 1
backone = 2
temp = 0
while i <= 4000000:
if i % 2 == 0:
sum = sum + i
if i == 1 or i == 2:
i = i + 1
else:
temp = i
i = i + backone
backone = temp
print(sum)
|
# 29 Feb 2020
# CopyRight: WANG Hongru
if __name__ == '__main__':
a = int(input("please input a:"))
hire, salary, fired = map(int, input("Please input the cost, salary, fired cost of individual person: ").strip().split())
needed = list(map(int, input("Please input the minimum person needed per month: ").strip().split()))
|
"""
定义LCS(S,T)为字符串S和字符串T最长公共子序列的长度,即一个最长的序列W既是S的子序列也是T的子序列的长度。
小易给出一个合法的括号匹配序列s,小易希望你能找出具有以下特征的括号序列t:
1、t跟s不同,但是长度相同
2、t也是一个合法的括号匹配序列
3、LCS(s, t)是满足上述两个条件的t中最大的
因为这样的t可能存在多个,小易需要你计算出满足条件的t有多少个。
"""
s = input().strip()
class Solution:
def __init__(self):
self.res = []
def reset(self):
self.res = []
def generate(self, n, t, left, right):
# 产生所有与s相同长度的合法的括号序列,并且与s不相同 -> t
if len(t) == n:
if left == right and s != t:
self.res.append(t)
return
if left > right:
self.generate(n, t + "(", left + 1, right)
self.generate(n, t + ")", left, right + 1)
else:
self.generate(n, t + "(", left + 1, right)
def lcs(self, i, j, s, t, v):
print(i, j, s, t, v)
if i == len(s) or j == len(t):
print("+++++++++weird++++++++++")
if j < len(t):
v += len(t) - j
if i < len(s):
v += len(s) - i
if v < self.v:
print("------res--------:", v)
self.v = v
# max()
return
if s[i] == t[j]:
self.lcs(i+1, j+1, s, t, v+1)
else:
self.lcs(i, j+1, s, t, v)
self.lcs(i+1, j, s, t, v)
def lcs_geek(self, s, n, t, m):
maxlcs = [[0 for _ in range(m)] for _ in range(n)]
for j in range(0, m):
if s[0] == t[j]:
maxlcs[0][j] = 1
elif j != 0:
maxlcs[0][j] = maxlcs[0][j-1]
else:
maxlcs[0][j] = 0
for i in range(0, n):
if s[i] == t[0]:
maxlcs[i][0] = 1
elif i != 0:
maxlcs[i][0] = maxlcs[i-1][0]
else:
maxlcs[i][0] = 0
for i in range(1, n):
for j in range(1, m):
if s[i] == t[j]:
maxlcs[i][j] = max(maxlcs[i-1][j], maxlcs[i][j-1], maxlcs[i-1][j-1]+1)
else:
maxlcs[i][j] = max(maxlcs[i-1][j], maxlcs[i][j-1], maxlcs[i-1][j-1])
return maxlcs[n-1][m-1]
solution = Solution()
solution.generate(len(s), "", 0, 0)
cans = solution.res
length = []
for i in range(len(cans)):
solution.v = float('inf')
solution.lcs(0, 0, s, cans[i], 0)
print(solution.v)
print("==========end===========")
value = solution.v
length.append(value)
print(length)
print(length.count(max(length))) |
# 리스트 : 많은 양의 데이터를 한꺼번에 다루기 위해서!
# 순서를 가지고 있음.
name = ['홍길동', '박길동', '송길동']
print(name[0]) #리스트 중 첫번째 값, 위치값
print(name[1])
print(name[2])
print(type(name[0]))
#위치값: index는 0부터 시작, 마지막 위치는 전체개수-1
|
# 극장 예매시스템
# 1. 화면을 만든다.
# --0이 10개 들어간 리스트 필요!
seat = [0] * 10
# print(seat)
count = 0 # 예매 상황을 카운트
name = input('고객님의 성함을 입력해주세요.>> ')
while True:
# 자리 번호 프린트
print('-----------------------------')
for x in range(0, len(seat)):
print(x, end=" ")
print('\n-----------------------------')
# 자리 예약 상태 프린트(0=>예약x, 1=>예약o)
for x in seat:
print(x, end=" ")
print('\n-----------------------------')
print('참고: 0=>예약x, 1=>예약o')
choice = input('원하는 좌석 번호 입력(종료: x)>> ')
if choice == 'x':
print('예매 프로그램을 종료합니다.')
print(name, '님의 예매 확인 영수증입니다.')
print('----------------------------------')
print('예매된 좌석 번호는 ', end='')
for index in range(0, len(seat)): #seat리스트에 있는 값들을 하나씩 꺼낸다.
if seat[index] == 1:
print(index, '번', end=' ')
print()
print('전체 예매된 좌석수는 ', count, '석')
print('전체 결제 금액은 ', count * 10000, '원')
print('----------------------------------')
break
#입력값은 리스트의 index로 사용될 예정
#index == 좌석번호
print(choice, '를 선택하셨군요!')
choice = int(choice)
# 이미 예매처리가 된 경우, 불가능하다고 처리
if seat[choice] == 1:
print('이미 예매가 된 좌석입니다.')
print('다시 다른 좌석을 선택해주세요.')
else:
# 이미 그 자리에
# 예매처리가 안된 경우
# 입력받은 좌석번호로 예매처리
seat[choice] = 1
print('예매 처리를 완료하였습니다.')
count = count + 1
print('현재 예매 좌석수 : ', count, '석')
print()
|
# 극장 예매시스템
# 1. 화면을 만든다.
# --0이 10개 들어간 리스트 필요!
seat = [0] * 10
# print(seat)
while True:
# 자리 번호 프린트
print('-----------------------------')
for x in range(0, len(seat)):
print(x, end=" ")
print('\n-----------------------------')
# 자리 예약 상태 프린트(0=>예약x, 1=>예약o)
for x in seat:
print(x, end=" ")
print('\n-----------------------------')
print('참고: 0=>예약x, 1=>예약o')
choice = input('원하는 좌석 번호 입력(종료: x)>> ')
if choice == '':
print('입력하지 않았습니다.입력을 다시 해주세요.')
elif choice == 'x':
print('예매 프로그램을 종료합니다.')
break
else:
choice = int(choice)
if choice not in range(0, 10):
print('잘못된 범위의 값입니다.')
#입력값은 리스트의 index로 사용될 예정
#index == 좌석번호
else:
print(choice, '를 선택하셨군요!')
# 이미 예매처리가 된 경우, 불가능하다고 처리
if seat[choice] == 1:
print('이미 예매가 된 좌석입니다.')
print('다시 다른 좌석을 선택해주세요.')
else:
# 이미 그 자리에
# 예매처리가 안된 경우
# 입력받은 좌석번호로 예매처리
seat[choice] = 1
print('예매 처리를 완료하였습니다.')
print()
|
class SortedList(list):
def __init__(self,lista,sorttype=False):
self.sorttype=sorttype
lista.sort(reverse=self.sorttype)
super().__init__(lista)
def _sort(self):
self.sort(reverse=self.sorttype)
return self
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._sort
def append(self, *value):
super().append(value)
self._sort
def extend(self, value):
super().extend(value)
self._sort
def pop(self,*lit):
super().pop(*lit)
self._sort
import sys
args = sys.argv[1:]
for a,i in enumerate(args):
args[a] = float(i)
i = SortedList(args)
print(i)
i = SortedList(args,True)
print(i)
|
def volume(length):
if(isinstance(length, int) or isinstance(length, float)):
if(not length > 0):
print("Length of edge must be greater than 0")
return None
return length**3
else:
print("Invalid input")
return None
|
#!/usr/bin/python3
if __name__ == "__main__":
import sys
lenght = len(sys.argv)
if lenght == 1:
print("0 arguments.")
elif lenght == 2:
print("1 argument:\n1: {}".format(sys.argv[1]))
elif lenght > 2:
print("{} arguments:".format(lenght - 1))
for x in range(1, len(sys.argv)):
print("{}: {}".format(x, sys.argv[x]))
|
#!/usr/bin/python3
"""
function that reads a text file (UTF8) and prints it to stdout
"""
def read_file(filename=""):
"""
myfile: the variable use to store the open file
"""
with open(filename, mode="r", encoding="UTF8") as my_file:
print(my_file.read(), end="")
|
valeur = 1
for loop in range(100):
print(valeur)
valeur = valeur +1
print("J'arrive !") |
from listnode import ListNode
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head:
return head
dummy = ListNode(-1)
dummy.next = head
left, cur = dummy, head
k = n - m + 1
while m > 1:
left = cur
cur = cur.next
m -= 1
# reserve k times
start = cur
prev = None
while k:
tmp = cur.next
cur.next = prev
prev = cur
cur = tmp
k -= 1
# connect together
left.next = prev
start.next = cur
return dummy.next |
class MissingNumber(object):
'''
Solution:
1. Use binary search as the array is sorted. Calculate low, mid and high as usual. Calculate the differences of
array[low] - low and array[mid] - mid.
2. If first one is smaller, reject the second half else reject the first half and update mid until low is 1 element
lesser than high.
3. The missing element would be the middle value between array[low] and array[high].
--- Assumed array size greater than 1, first and last elements cannot be missing (given during mock interview)
--- Checked edge cases like [1, 3] and also generic cases, passed all of them.
'''
def search(ar, size):
# O(logn) Time Complexity | O(1) Space Complexity
low = 0
high = size - 1
while (low < high):
mid = low + int((high - low) / 2)
diffLow = ar[low] - low
diffMid = ar[mid] - mid
if (low == high - 1):
break
if (diffLow < diffMid):
high = mid
else:
low = mid
return int((ar[low] + ar[high]) / 2) |
class Student():
# class variable
# the number of students
# all changes amde by other objects and instances,
# can be seen
pop = 0
def __init__(self, name, avg):
self.name = name
self.avg = avg
print('Hi, how are you? My name is', self.name)
# remember to b=put the class that defines the cls var
Student.pop += 1
#when this is created, the student adds to the population
def leave(self):
Student.pop -= 1
if Student.pop == 0:
print('No students available')
else:
print(Student.pop, ':students left')
def grades(self):
print('My avg is', self.avg)
@classmethod
def how_many(cls):
print('Total Students:', cls.pop)
stu_1 = Student('Bob', '72')
stu_1.grades()
Student.how_many()
stu_1.leave()
Student.how_many()
|
#!/usr/bin/python
# coding: utf-8
import argparse
import sys
import time
my_parser = argparse.ArgumentParser(
description='Slowly output the lines of a text file.',
epilog='Parameters can be in a file, one per line, using @"file name"',
fromfile_prefix_chars='@')
my_parser.add_argument(
'fileNames',
nargs='+',
type=argparse.FileType(mode='r'),
default=sys.stdin,
help='File to parse.'
' (type %(type)s)')
args = my_parser.parse_args()
def main():
for fd in args.fileNames:
with fd:
try:
for line in fd:
print line,
sys.stdout.flush()
time.sleep(0.5)
except KeyboardInterrupt:
break
if __name__ == '__main__':
main()
|
seq = [1,2,3,4,5]
print(1 in seq)
for item in seq:
print(item)
for x in range(0,11,2):
print(x)
i = 1
while i<5:
print("i is currently: {}".format(i))
i = i + 1 |
from Disk import *
# import disk
from Core import *
def print_inventory(inventory):
for item in inventory:
print(inventory)
def load_inventory(inventory):
for item in inventory:
car = inventory[item]
print(item)
print(' rental:', car['rental'])
print(' in-stock:', car['in-stock'])
print(' price:', car['price'])
print(' replacement:', car['replacement'])
while True:
item = input('\nWhich car would you like?\n')
if item in inventory:
print('That\'s an amazing choice!')
exit()
elif item == 'quit':
break
else:
print(
'\nSorry we do not have this in stock please choose another car!\n'
)
def which():
while True:
response = input('\nAre you an [em]ployee or a [cu]stomer?\n')
if response == 'cu':
customer()
elif response == 'em':
employee()
else:
print('****Please Try Again, Announcement 1****')
def customer():
print('\nGreat!')
response = input('\nWould you like to rent a car or buy one?\n')
if response == 'yes, I would like to rent a car.':
load_inventory(inventory)
response = input('Which car would you like to rent?')
print(inventory)
if response == 'Camaro 2018':
print('1200')
camaro_2018()
elif response == 'Audi r8':
print('14300')
audi_r8()
elif response == 'Bugatti Chiron':
print('15500')
bugattI_chiron()
response = input('\nHow many days would you like to ')
def employee():
print('\nHey, employee!\n')
response = input('\nWould you like to view the inventory?\n')
if response == 'yes':
print(inventory)
exit()
elif response == 'no':
print('\nThAnK YoU, Have a Blessed day!\n')
exit()
elif response == 'quit':
print('\nHave a Blessed day!\n')
exit()
# else:
# print('\nPlease provide an valid answer cause your is invalid!\n')
def rental_payments():
def main():
inventory = open_inventory()
print('\n~*~*~ Welcome to Desma\'s Rental Shop ~*~*~\n')
which()
customer()
employee()
rental_payments()
# response = input('\nAre you an employee or a customer?\n')
# if response == 'customer':
# print('\nGreat!')
# response = input('\nWould you like to rent a car or buy one?\n')
# if response == 'yes, I would like to rent a car.':
# load_inventory(inventory)
# response = input('\nWhich car would you like to rent?\n')
# which = input 'Audi r8'
# response = input('How many days would you like to rent the car?')
# elif response == 'employee':
# print('\nHey, employee!\n')
# response = input('\nWould you like to view the inventory?\n')
# if response == 'yes':
# print(inventory)
# exit()
# elif response == 'no':
# print('\nThAnK YoU, Have a Blessed day!\n')
# exit()
# elif response == 'quit':
# print('\nHave a Blessed day!\n')
# exit()
# else:
# print('\nPlease provide an valid answer cause your is invalid!\n')
# print_inventory(inventory)
# save_inventory(inventory)
def main():
if __name__ == '__main__':
main()
|
x = 'Carro'
print(x.lower()=='carro')
# Vai dar True porque eu converti a variavel com a letra maiuscula para colocar todas as
#letras minusculas |
s = 'Sorte'
if s != 'sorte':
print('Sua string é diferente da string comparada')
# Se string s, for diferente de 'sorte' ele vai exibir a mensagem |
import random
choice = ["paper", "scissor", "rock"]
tie = 0
win = 0
lose = 0
while True:
q = str(input("Paper,Scissor,or Rock? ")).lower()
c = random.choice(choice) # good info...here it get overwritten everytime the loop start over
while (q != "paper" and q != "scissor" and q != "rock"):
q = str(input("Paper,Scissor,or Rock? ")).lower()
if (q == c):
print(c)
print("Draw!")
tie = tie + 1
elif ((q == "paper" and c == "rock")
or (q == "scissor" and c == "paper")
or (q == "rock" and c == "scissor")):
print(c)
print("You won")
win = win + 1
else:
print(c)
print("you lost")
lose = lose + 1
print(f"Wins : {win}\nLoses : {lose}\nTies : {tie}")
p = int(input("Do you want to play again...enter 1 for 'Yes', otherwise for 'No'? "))
if (p == 1):
continue
else:
print("Game ended")
break
|
import heapq
# def heapify(i):
# sp = swap(i, min(2 * i + 1, 2 * i + 2))
# if (sp != -1):
# heapify(sp)
# def buildHeap(arr, n):
# for i in range(n / 2, -1, -1):
# heapify(i)
# # def delete_min(arr):
# # elt = arr[0]
# # swap(arr, 0, h.size)
# # h.size -= 1
# # heapify(0)
# # return elt
# # todo
# # insert, use reverseheapify
# def reverseHeapify(i):
# sp = swap(i, min(i, (i - 1) / 2))
# if sp != -1:
# reverseHeapify(sp)
# def heapSort(arr, n):
# buildHeap(arr, n)
# for i in range(arr):
# delete_min(arr)
# return arr.reverse()
def mergeArrays(arr):
max_heap = False
if arr[0][0] > arr[0][-1]:
max_heap = True
temp = arr[0]
for i in range(1, len(arr)):
temp += arr[i]
if not max_heap:
heapq.heapify(temp)
else:
heapq._heapify_max(temp)
res = []
while temp:
if not max_heap:
res.append(heapq.heappop(temp))
else:
res.append(heapq._heappop_max(temp))
return res
res = mergeArrays([[26, -15, -20], [27, 19, -18]])
print res
|
from node import Node
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
# adds to end
def add(self, data):
n = Node(data)
if self.head is None:
self.head = n
self.length += 1
return
tmp = self.head
while tmp.next:
tmp = tmp.next
tmp.next = n
self.length += 1
# add to beginning
def add_start(self, data):
n = Node(data)
n.next = self.head
self.head = n
self.length += 1
# add at nth position
def add_at(self, data, n):
if n > self.length:
raise ValueError("not long enough")
if n == 0:
self.add_start(data)
elif n == self.length:
self.add(data)
else:
node = Node(data)
tmp = self.head
for i in range(n - 1):
tmp = tmp.next
a = tmp.next
tmp.next = node
node.next = a
self.length += 1
# removes last item
def remove(self):
if self.length == 0:
return
elif self.length == 1:
self.head = None
return
tmp = self.head.next
prev = self.head
while tmp.next:
prev = tmp
tmp = tmp.next
prev.next = None
self.length -= 1
def remove_at(self, n):
if n > self.length:
raise ValueError("list not long enough")
if n == self.length:
self.remove()
pre = self.head
nex = self.head.next
for i in range(n - 1 - 1):
pre = nex
nex = nex.next
pre.next = nex.next
self.length -= 1
def reverse_copy(self):
prev = self.head
curr = self.head.next
prev.next = None
while curr:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
a = LinkedList()
while prev:
a.add(prev)
prev = prev.next
return a
[1, 2, 3, 4, 5]
def rec_helper(self, curr, nex):
if nex is None:
return
split = nex.next
nex.next = curr
curr = nex
self.head = nex
self.rec_helper(curr, split)
def reverse_copy_r(self):
if self.length == 0:
return LinkedList()
elif self.length == 1:
return
else:
curr = self.head
nex = self.head.next
curr.next = None
self.rec_helper(curr, nex)
def size(self):
return self.length
def start(self):
return self.head
def show(self):
tmp = self.head
while tmp:
print tmp
tmp = tmp.next
l = LinkedList()
for i in range(5):
l.add(i)
l.show()
print "----"
# a = l.reverse_copy()
l.reverse_copy_r()
l.show()
# a.show()
|
import tensorflow as tf
import pickle
import numpy as np
import matplotlib.pyplot as plt
"""
You have to implement an image classification neural network for the same dataset as before. Feel free to reduce
the number of examples for each class in your dataset, if it takes too long to train on your hardware.
For this task, you should make at least two neural networks: the fully connected one that works on the same extracted
features as before and another one convolutional with class prediction at the end.
You can do it either in Keras or Pytorch. Better to do both.
As an output, you should provide your code, trained model files (2 pcs. at least), your dataset, and the same precision
metrics [calculated on test images] as you did before.
Your code should provide 3 execution modes/functions: train (for training new model), test (for testing the trained
and saved model on the test dataset), and infer (for inference on a particular folder with images or a single image).
"""
def save_the_model(model, fname):
import json
print('Saving the model')
json_string = model.to_json()
with open(fname + '.txt', 'w', encoding='utf-8') as f:
json.dump(json_string, f, ensure_ascii=False)
print('Saving the weights')
model.save_weights(fname + '.hdf5')
print('Done')
def get_model_from_files(fnm):
import json
from tensorflow.keras.models import model_from_json
with open(fnm + '.txt') as infile:
json_string = json.load(infile)
model = model_from_json(json_string)
model.load_weights(fnm + '.hdf5', by_name=False)
model.compile(loss='binary_crossentropy', optimizer='Adagrad', metrics=['accuracy'])
model.summary()
return model
def fully_connected_model():
# Uploaded features from the last homework. The number of features reduced from 546 to 40 with L1 regularization.
with open('train_dataset.pickle', 'rb') as f:
train_dataset_df = pickle.load(f)
target = train_dataset_df.pop('y')
Y = np.asarray(target).astype(np.float32)
X = np.asarray(train_dataset_df).astype(np.float32)
dataset = tf.data.Dataset.from_tensor_slices((X, Y)).batch(16)
features, labels = next(iter(dataset))
train_dataset = dataset.shuffle(len(train_dataset_df)).batch(1)
# The code for a moder training
# model2 = tf.keras.Sequential([
# tf.keras.layers.Dense(30, activation=tf.nn.relu, input_shape=(40,)), # input shape required
# tf.keras.layers.Dense(20, activation=tf.nn.relu),
# tf.keras.layers.Dense(17)
# ])
#
# loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
#
# def loss(model, x, y, training):
# # training=training is needed only if there are layers with different
# # behavior during training versus inference (e.g. Dropout).
# y_ = model(x, training=training)
#
# return loss_object(y_true=y, y_pred=y_)
#
# def grad(model, inputs, targets):
# with tf.GradientTape() as tape:
# loss_value = loss(model, inputs, targets, training=True)
# return loss_value, tape.gradient(loss_value, model.trainable_variables)
#
# optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
#
# loss_value, grads = grad(model2, features, labels)
# optimizer.apply_gradients(zip(grads, model2.trainable_variables))
#
# # Keep results for plotting
# train_loss_results = []
# train_accuracy_results = []
#
# num_epochs = 201
#
# for epoch in range(num_epochs):
# epoch_loss_avg = tf.keras.metrics.Mean()
# epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
#
# # Training loop - using batches of 32
# for x, y in train_dataset:
# # Optimize the model
# loss_value, grads = grad(model2, x, y)
# optimizer.apply_gradients(zip(grads, model2.trainable_variables))
#
# # Track progress
# epoch_loss_avg.update_state(loss_value) # Add current batch loss
# # Compare predicted label to actual label
# # training=True is needed only if there are layers with different
# # behavior during training versus inference (e.g. Dropout).
# epoch_accuracy.update_state(y, model2(x, training=True))
#
# # End epoch
# train_loss_results.append(epoch_loss_avg.result())
# train_accuracy_results.append(epoch_accuracy.result())
#
# if epoch % 50 == 0:
# print("Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}".format(epoch,
# epoch_loss_avg.result(),
# epoch_accuracy.result()))
# Training log:
""" Epoch 000: Loss: 2.813, Accuracy: 12.292%
Epoch 050: Loss: 2.133, Accuracy: 51.979%
Epoch 100: Loss: 1.946, Accuracy: 61.667%
Epoch 150: Loss: 1.785, Accuracy: 68.750%
Epoch 200: Loss: 1.673, Accuracy: 73.125%"""
with open('train_accuracy_results.pickle', 'rb') as f2:
train_accuracy_results = pickle.load(f2)
with open('train_loss_results.pickle', 'rb') as f3:
train_loss_results = pickle.load(f3)
fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))
fig.suptitle('Training Metrics')
axes[0].set_ylabel("Loss", fontsize=14)
axes[0].plot(train_loss_results)
axes[1].set_ylabel("Accuracy", fontsize=14)
axes[1].set_xlabel("Epoch", fontsize=14)
axes[1].plot(train_accuracy_results)
plt.show()
# save_the_model(model2, 'model_fully_connected')
#-------------------------------------------------------------------------------------
with open('test_dataset.pickle', 'rb') as f2:
test_dataset_df = pickle.load(f2)
target_test = test_dataset_df.pop('y')
Y_test = np.asarray(target_test).astype(np.float32)
X_test = np.asarray(test_dataset_df).astype(np.float32)
dataset_t = tf.data.Dataset.from_tensor_slices((X_test, Y_test))
test_dataset = dataset_t.shuffle(len(test_dataset_df)).batch(1)
model3 = get_model_from_files('model_fully_connected')
test_accuracy = tf.keras.metrics.Accuracy()
for (x, y) in test_dataset:
# training=False is needed only if there are layers with different
# behavior during training versus inference (e.g. Dropout).
logits = model3(x, training=False)
prediction = tf.argmax(logits, axis=1, output_type=tf.int32)
test_accuracy(prediction, y)
print("Test set accuracy: {:.3%}".format(test_accuracy.result())) # Test set accuracy: 15.625%
if __name__ == '__main__':
fully_connected_model() |
from Hashtable import Hashtable
import random
# The objective of this program is to determine the efficiency of the simple hash function
# by inserting a random string of random length into a hashtable of a given size and determining
# the number of collisions in each spot
SIZE = 1000
MAX_WORD_LENGTH = 10
AMMOUNT_WORDS = 10000
tbl = Hashtable(SIZE)
for i in range(1,AMMOUNT_WORDS):
string = ""
for i in range(0, random.randint(1, MAX_WORD_LENGTH)):
string+= chr(random.randint(65, 90)) #ascii A-Z
print("%i for word: %s"%(tbl.hashWord(string),string)) |
def cells():
from sympy import *
init_printing()
%matplotlib notebook
import matplotlib.pyplot as mpl
from util.plot_helpers import plot_augmat, plot_plane, plot_point, plot_line, plot_vec, plot_vecs
Vector = Matrix # define alias Vector so I don't have to explain this during video
Point = Vector # define alias Point for Vector since they're the same thing
'''
'''
'''
### E4.7
'''
'''
'''
# Setup the variables of the exercise:
p = Point([10,10,10])
pL1 = Point([3,0,5]) # an arbitrary point on L1
pL2 = Point([6,0,0]) # an arbitrary point on L2
d = Vector([1,-2,0]) # direction vector of L1 and L2
'''
'''
'''
a) Projection of $p$ onto $\ell_1$
'''
'''
'''
# define a vector from a point on L1 to p:
v1 = p - pL1
# proj_{L1}(p) = proj_{L1}(v1) + pL1
p_proj_L1 = (d.dot(v1)/d.norm()**2)*d + pL1
p_proj_L1
'''
'''
'''
^ This is the point on the line $\ell_1$ that is closes to the point $p$
'''
'''
'''
'''
b) (shortest) distance form $p$ to $\ell_1$
'''
'''
'''
# d(p, L1) = subtract from v1 the part that is perp to L1 and compute the length:
(v1 - (d.dot(v1)/d.norm()**2)*d).norm()
'''
'''
# ... or compute the distance directly:
(p_proj_L1-p).norm()
'''
'''
(p_proj_L1-p).norm().n() # numeric approx.
'''
'''
plot_line(d, pL1) # Line L1
# vector v1 and it's decomposition into parallel-to-L1 and perp-to-L1 components
plot_vec(v1, at=pL1)
plot_vec(p_proj_L1-pL1, at=pL1, color='b')
plot_vec(p-p_proj_L1, at=p_proj_L1, color='r')
ax = mpl.gca()
mpl.xlim([0,10])
mpl.ylim([0,10])
ax.set_zlim([0,10])
ax.grid(True,which='both')
'''
'''
'''
Answer to a) is the tip of the blue vector; answer to b) is the length of the red vector.
'''
'''
'''
'''
'''
'''
Use a similar approach for c) and d)
'''
'''
'''
# define a vector from a point on L2 to p:
v2 = p - pL2
'''
'''
# p_proj_L2 =
(d.dot(v2)/d.norm()**2)*d + pL2
'''
'''
# d(p, L2) =
(v2 - (d.dot(v2)/d.norm()**2)*d).norm()
'''
'''
(v2 - (d.dot(v2)/d.norm()**2)*d).norm().n()
'''
'''
'''
'''
'''
'''
'''
e) distance $\ell_1$ to $\ell_2$
'''
'''
'''
# first define a vector from a point on L1 to a point on L2:
v3 = pL2 - pL1
v3
'''
'''
# d(L1, L2) =
d_L1L2 = (v3 - (d.dot(v3)/d.norm()**2)*d).norm()
d_L1L2
'''
'''
d_L1L2.n()
'''
'''
'''
'''
'''
'''
'''
'''
|
#https://selftaught.blog/python-tutorial-build-hangman/
def hangman(word):
wrong = 0
stages = ["", "__________ ", "| ", "| | ", "| 0 ", "| /|\ ", "| / \ ", "| "]
rletters = list(word)
board = ["_"] * len(word)
win = False
print("Welcome to HANGMAN!")
while wrong < len(stages)-1:
print("\n")
msg = "Guess a letter in the word..."
char = input(msg)
if char in rletters:
cind = rletters \ .index(char)
board[cind] = char
#rletters[cind] =
#need to put if win
if not win:
print("\n" .join(stages[0: \ wrong]))
print("Oh no! You lost! It was {}.".format(word))
|
## Problem3 (https://leetcode.com/problems/search-a-2d-matrix-ii/)
#Time Complexity : O(m+n), m=number of rows and n=number of columns
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix)==0:
return False
m=len(matrix)
n=len(matrix[0])
i=0
j=n-1;
while(i<m and j>=0):
if matrix[i][j]==target:
return True
# if greater then you should move to smaller element in that list
elif matrix[i][j]> target:
j-=1
else:
i+=1
return False
|
import tkinter as tk
import math
from random import randint, choice
WIDTH = 800
HEIGHT = 600
class Ball:
#def __init__(self, r, x, y, dx, dy):
def __init__(self):
"""
self.r = r
self.x = x
self.y = y
self.dx = dx
self.dy = dy
"""
self.r = randint(50, 50)
self.x = randint(self.r, WIDTH - self.r)
self.y = randint(self.r, HEIGHT - self.r)
self.dx = choice([-5, -4, -3, 3, 4, 5])
self.dy = choice([-5, -4, -3, 3, 4, 5])
"""
self.color = "#%02x%02x%02x" % (randint(0, 255),
randint(0, 255),
randint(0, 255))
"""
# self.w = (randint(0, 255), randint(0, 255), randint(0, 255))
self.w = tuple((randint(0, 255) for i in range(3)))
self.color = "#%02x%02x%02x" % (self.w)
self.ball_id = c.create_oval(self.x - self.r,
self.y - self.r,
self.x + self.r,
self.y + self.r, fill=self.color)
def move(self):
# Прямолинейное движение
self.x += self.dx
self.y += self.dy
# Столкновение шаров со стенами
if self.x >= WIDTH - self.r or self.x <= self.r:
self.dx = -self.dx
if self.y >= HEIGHT - self.r or self.y <= self.r:
self.dy = -self.dy
# Столкновения шаров друг с другом
# Берем массив всех шаров
for another_ball in bs:
# Удаляем из массива этот шар
if another_ball.ball_id != self.ball_id:
# определяем, что шар столкнулся с другим шаром
if (self.x - another_ball.x) ** 2 + (self.y - another_ball.y) ** 2 <= (self.r + another_ball.r) ** 2:
self.dist = ((self.x - another_ball.x) ** 2 + (self.y - another_ball.y) ** 2)**0.5
# print(self.dist)
self.a = self.x - another_ball.x
self.b = self.y - another_ball.y
self.p1 = (self.a*self.b)/(self.dist**2)
self.p2 = (self.a/self.dist)**2
self.p3 = (self.b/self.dist)**2
self.d1 = self.dy*self.p1 + self.dx*self.p2 - another_ball.dy*self.p1 - another_ball.dx*self.p2
self.d2 = self.dx*self.p1 + self.dy*self.p3 - another_ball.dx*self.p1 - another_ball.dy*self.p3
self.dx = self.dx - self.d1
self.dy = self.dy - self.d2
another_ball.dx = another_ball.dx + self.d1
another_ball.dy = another_ball.dy + self.d2
def show(self):
c.move(self.ball_id, self.dx, self.dy)
def tick():
for b in bs:
b.move()
b.show()
root.after(20, tick)
def main():
global root, c, bs
root = tk.Tk()
c = tk.Canvas(root, width=WIDTH, height=HEIGHT)
c.pack()
bs = [Ball() for i in range(2)]
"""
bs = [
Ball(50, 150, 500, 4, -5),
Ball(50, 500, 500, -5, -4)
]
"""
"""
bs = []
for i in range(5):
bs.append(Ball())
"""
# print(math.degrees(calc_angle(4,3)))
# print((bs))
tick()
root.mainloop()
if __name__ == "__main__":
main()
|
import tkinter as tk
import math
def calc_angle(ddx, ddy):
if ddx > 0 and ddy > 0:
return math.atan(ddy / ddx) + 3 * math.pi / 2
elif ddx > 0 and ddy < 0:
return -(math.atan(ddy / ddx))
elif ddx < 0 and ddy < 0:
return math.atan(ddy / ddx) + math.pi / 2
elif ddx < 0 and ddy > 0:
return -(math.atan(ddy / ddx) - math.pi)
elif ddx == 0 and ddy > 0:
return 3 * math.pi / 2
elif ddx == 0 and ddy < 0:
return math.pi / 2
elif ddx > 0 and ddy == 0:
return 0
elif ddx < 0 and ddy == 0:
return math.pi
else:
return None
def create_line_(angle, x0, y0, line):
x1 = x0 - math.cos(angle) * line
y1 = y0 - math.sin(angle) * line
x2 = x0 + math.cos(angle) * line
y2 = y0 + math.sin(angle) * line
c.create_line(x1, y1, x2, y2, fill="black", width=1, arrow=tk.LAST)
root = tk.Tk()
c = tk.Canvas(root, width=800, height=600, bg="white")
c.pack()
# Нулевая координата новой системы координат (начало всех векторов), угол
x0 = 400
y0 = 300
anglePhi = math.radians(10)
print("Угол anglePhi: %.f гр." % math.degrees(anglePhi))
c.create_oval(x0-2, y0-2, x0+2, y0+2, fill="red")
# Рисуем новую систему координат
create_line_(anglePhi, x0, y0, 250)
create_line_(anglePhi + math.pi/2, x0, y0, 250)
# Рисуем произвольный вектор из центра координат, задавая координаты его второй точки
vx1 = 500
vy1 = 400
c.create_line(x0, y0, vx1, vy1, fill="blue", width=2, arrow=tk.LAST)
# Определяем новые координаты на новой системе отсчета и рисуем новый вектор
nx1 = vx1*math.cos(anglePhi) - vy1*math.sin(anglePhi)
ny1 = vx1*math.sin(anglePhi) + vy1*math.cos(anglePhi)
c.create_line(x0, y0, nx1, ny1, fill="green", width=2)
root.mainloop() |
# author: Grechnev Sergey
"""Module for test
"""
class FirstClass:
def __init__(self, age, name):
self.__age = age
self.name = name
assert type(age) == str, "Переменная равна строке"
def __str__(self):
return f"IPAddress: {self.name}"
def modyfy(self):
self.__age += 5
def show(self):
print(self.name, self.__age, end=" ")
class SecondClass(FirstClass):
def __init__(self, age, name, height):
super().__init__(age, name)
# self.height = int(input("Введите рост:\n"))
self.height = height
def show(self):
super().show()
print("А ты высокий! - ", self.height)
ob = SecondClass(12, "sergey", 186)
# FirstClass.show(ob)
ob.modyfy()
# ob.input_height()
# ob.__age = 107
ob.show()
# print(dir(ob), sep='\n')
# print('\n'.join(dir(ob)))
# print(ob._FirstClass__age) |
__author__ = 'ManiKanta Kandagatla'
import sqlite3
mails = {}
conn = sqlite3.connect('D:\Languages\python\SQLite\emaildb.sqlite')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS Counts''')
cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')
fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'mbox-short.txt'
fh = open(fname)
for line in fh:
if not line.startswith('From: ') : continue
pieces = line.split()
email = pieces[1].split('@')[1]
if email not in mails.keys():
mails[email] = 1
else:
mails[email] = mails[email] + 1
for mail in mails.keys():
cur.execute('''INSERT INTO Counts (org, count)
VALUES ( ?, ? )''', ( mail,mails[mail] ) )
conn.commit()
# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT org, count FROM Counts ORDER BY count desc'
print
print "Counts:"
for row in cur.execute(sqlstr) :
print str(row[0]), row[1]
cur.close()
|
import pygame
'''
Class that defines the squares on the board of the Checker GUI
'''
class Square():
def __init__(self, root, area, color, x, y):
self.root = root
self.area = area
self.color = color
self.x = x
self.y = y
self.is_selected = False
def draw(self, square_edge):
if self.is_selected:
color = [50, 200, 30]
else:
color = self.color
pygame.draw.rect(self.root, color, self.area)
pygame.draw.rect(self.root, [205, 155, 29], self.area, 3)
def pressed(self, mouse_pos, mouse_click):
hovered = (mouse_pos[0] >= self.area.left and mouse_pos[0] <= self.area.right
and mouse_pos[1] >= self.area.top and mouse_pos[1] <= self.area.bottom)
return (hovered and mouse_click[0] == 1)
if is_pressed:
# Switch on!
for p in pieces:
if (self != p):
p.is_pressed = False
p.can_change = True
self.is_pressed = not(self.is_pressed)
self.can_change = False
return self.is_pressed
else:
self.can_change = (mouse_click[0] == 0)
return self.is_pressed
|
from __future__ import division
from piece import *
""" Class that determines the rules and structure of the Checkers game """
class Game():
def __init__(self, rows=8, columns=8, set_board=True):
# Set structure of the board
self.rows = rows
self.columns = columns
# Reset board to begin position
if set_board:
self.init_board()
'''
Initializes the board with the begin position
'''
def init_board(self):
s = ""
for _ in range(self.rows):
for _ in range(self.columns):
s += "0"
self.board = s
self.pieces_one = list()
self.pieces_two = list()
for x in range(1, self.rows, 2):
for j in range(1, 4):
if (j == 2):
i = x+1
else:
i = x
self.pieces_one.append( Piece(i, j, 1) )
self.set(i, j, '1')
self.pieces_two.append( Piece(self.columns - (i-1), self.rows - (j-1), -1) )
self.set(self.columns - (i-1), self.rows - (j-1) , '2')
self.current_player = 1
self.moves_since_hit = 0
self.path = dict()
'''
Sets the position x,y on the board with value
'''
def set(self, x, y, value):
cut = (self.rows - (y))*self.columns + (x-1)
self.board = self.board[0:cut] + value + self.board[cut+1::]
'''
Gets on position x,y the value on the board
'''
def get(self, x, y):
if (x-1 >= 0 and x-1 < self.columns and (self.rows - y) >= 0
and (self.rows - y) < self.rows):
index = (self.rows - (y))*self.columns + (x-1)
return self.board[index]
return ''
'''
Returns a list of every piece on the board
'''
def get_pieces(self):
return self.pieces_one + self.pieces_two
'''
Moves a piece from its initial position to the current position on the board
'''
def move(self, move):
# Unpack move
(x1, y1, x2, y2) = move
# Determine allies and enemy pieces
if self.current_player == 1:
own_pieces = self.pieces_one
enemy_pieces = self.pieces_two
else:
own_pieces = self.pieces_two
enemy_pieces = self.pieces_one
# Find what piece moved
piece = own_pieces[0]
for p in own_pieces:
if (p.x == x1) and (p.y == y1):
piece = p
break
# Increment moves since hit (checks for draw)
self.moves_since_hit += 1
# If forced, determine which piece is killed
if self.forced_move:
self.moves_since_hit = 0
# Coordinates of to kill
(a, b) = (x1 + int((x2 - x1)/2), y1 + int((y2-y1)/2))
self.set(a, b, '0')
# Remove that piece
to_remove = enemy_pieces[0]
for p in enemy_pieces:
if (p.x == a) and (p.y == b):
to_remove = p
break
enemy_pieces.remove(to_remove)
# Perform actual move
self.set(x1, y1, '0')
if (self.current_player == 1):
self.set(x2, y2, '1')
else:
self.set(x2, y2, '2')
# Remember that this state was seen (another time)
self.path[self.board] = self.path.get(self.board, 0) + 1
# Update coordinates of piece
piece.x = x2
piece.y = y2
# Crown the stone if reached the opposite side
if ( (self.current_player == 1 and y2 == self.rows) or
(self.current_player == -1 and y2 == 1)):
piece.is_king = True
# If move was forced find if still forced moves left
if self.forced_move:
(_, forced_moves) = self.get_piece_moves(piece)
# Only switch turn if current player cannot keep on hitting
if len(forced_moves) <= 0:
self.current_player = self.current_player*-1
else:
self.current_player = self.current_player*-1
'''
Returns a list of all possible moves in the current game state
'''
def get_moves(self):
free_moves = list()
forced_moves = list()
if self.current_player == 1:
pieces = self.pieces_one
else:
pieces = self.pieces_two
for piece in pieces:
(free, forced) = self.get_piece_moves(piece)
free_moves += free
forced_moves += forced
if len(forced_moves) > 0:
self.forced_move = True
return forced_moves
else:
self.forced_move = False
return free_moves
'''
Returns all possible moves for a specific piece in the current game state
'''
def get_piece_moves(self, piece):
(x, y) = (piece.x, piece.y)
if piece.is_king:
moves = [(1, 1), (-1, 1), (1, -1), (-1, -1)]
else:
moves = [(1, piece.value), (-1, piece.value)]
free_moves = [] # Moves if there are no forced moves
forced_moves = [] # Will make sure piece will capture for sure
for (a, b) in moves:
if self.get(x+a, y+b) == '0':
free_moves.append( (x, y, x+a, y+b) )
elif (piece.value == 1
and (self.get(x + a, y + b) == '2'
and self.get(x+2*a, y+2*b) == '0')):
forced_moves.append( (x, y, x+2*a, y+2*b))
elif (piece.value == -1
and (self.get(x + a, y + b) == '1'
and self.get(x+2*a, y+2*b) == '0')):
forced_moves.append( (x, y, x+2*a, y+2*b))
return (free_moves, forced_moves)
'''
Returns a boolean whether this game state is the end of the game
'''
def game_over(self):
return (len(self.pieces_one) == 0
or len(self.pieces_two) == 0
or len(self.get_moves()) == 0
or self.moves_since_hit >= 40
or self.path.get(self.board, 0) >= 3)
'''
Returns the winner of the ended game state
'''
def get_score(self):
# If no move has been killed for 40 moves
# or a 3-repeat of the same position
if self.moves_since_hit >= 40 or self.path.get(self.board, 0) >= 3:
return 0
# If the current player has no legal moves,
# that means that the other player won
elif len(self.get_moves()) == 0:
return self.current_player * -1
elif (self.current_player == 1) and (len(self.pieces_one) == 0):
return -1
else:
return 1
|
from collections import defaultdict
def vocab(df):
dictionary = df.to_dict(orient='index')
all_names = set()
for k in dictionary:
all_names.add(k[0])
return all_names
def counts_dict(df, name_list):
dictionary = df.to_dict(orient='index')
names_vals = defaultdict(int)
for k in dictionary:
names_vals[k[0]] += dictionary[k]['Count']
return names_vals
def name_counter(values_dict, name_list):
output_dict = defaultdict(int)
for k in values_dict:
row_name = k[0]
year = k[1]
if row_name in name_list:
output_dict[year] += values_dict[k]['Count']
return output_dict
|
import statistics as st
count=int(input(" "))
array=list(map(int,input().split()))
result=False
for i in range(1,count):
list1=array[:i]
list2=array[i:]
if st.mean(list1)==st.mean(list2):
result=True
if result==True:
print("yes")
else:
print("no")
|
from models.blog import Blog
class Menu(object):
def __init__(self):
self.user_blog = None
self.user = input("Enter your author name: ")
if self._user_has_account():
print("Welcome back {}".format(self.user))
else:
self._setup_new_user()
def _user_has_account(self):
"""
This method will return True if a user exists and set the self.user_blog object for the user if the user exists.
Otherwise the method will return False
:return:
"""
blog_id = Blog.find_author_id(self.user)
if blog_id is not None:
self.user_blog = Blog.get_blog_from_ID(blog_id)
return True
else:
return False
def _setup_new_user(self):
"""
This prompts for the user for info required to setup a new account,
adds the account to the database, and sets the self.user_blog to the users new blog
:return:
"""
title = input("Enter title for the new blog: ")
description = input("Enter the description of the blog: ")
self.user_blog = Blog(author=self.user,
title=title,
description=description)
self.user_blog.save_to_mongo() #seems like the blog class should do this itself on create of a new blog
def run_menu(self):
"""
Allows the user to Read or Write blogs
:return: True unless the user elects to Quit then returns False
"""
rtnVal = True
read_or_write = input("Do you want to (R)ead blogs, (W)rite blogs, or (Q)uit? ")
if read_or_write == 'R':
self._list_blogs()
self._view_posts()
elif read_or_write == 'W':
self.user_blog.new_post()
elif read_or_write =='Q':
print("Thank you for blogging!")
rtnVal = False
else:
print("I did not recognize the input, please try again.")
self.run_menu()
return rtnVal
def _list_blogs(self):
blog_list = Blog.get_all_blogs()
for blog in blog_list:
self.__print_blog(blog)
def _view_posts(self):
blog_to_see = input("Enter the blog_id you'd like to see: ")
blog = Blog.get_blog_from_ID(blog_to_see) #get a blog associated with this blog_id
posts = blog.get_posts() #get a list of all Post() objects in that blog
if posts is not None:
for post in posts:
print("Date: {}\nTitle: {}\nContent: {}\n\n".format(post.created_date,
post.title, post.content))
else:
print("No posts found")
def __print_blog(self,blog):
print("blog_id: {}".format(blog.blog_id))
print("Title: {}".format(blog.title))
print("Author: {}".format(blog.author))
print("Description: {}".format(blog.description))
print("\n")
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def middle_node(head):
if not head:
return
fast_ptr = head
slow_ptr = head
while fast_ptr.next and fast_ptr.next.next:
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next
if fast_ptr.next:
slow_ptr = slow_ptr.next
print(slow_ptr.val)
if __name__ == '__main__':
node_1 = ListNode(1)
node_2 = ListNode(2)
node_3 = ListNode(3)
node_4 = ListNode(4)
node_5 = ListNode(5)
node_1.next = node_2
node_2.next = node_3
node_3.next = node_4
node_4.next = node_5
middle_node(node_1) |
def get_next_greater_element_list(nums1, nums2):
next_greater_element_list = []
next_greater_element_list = []
for num in nums1:
found_flag = False
nums_2_index = nums2.index(num)
if nums_2_index == len(nums2)-1:
next_greater_element_list.append(-1)
continue
for i in range(nums_2_index+1, len(nums2)):
if nums2[i] > num:
next_greater_element_list.append(nums2[i])
found_flag = True
break
if not found_flag:
next_greater_element_list.append(-1)
print(next_greater_element_list)
if __name__ == '__main__':
get_next_greater_element_list([1,3,5,2,4], [5,4,3,2,1])
|
from collections import defaultdict
import math
def majority_element(nums):
count_dict = defaultdict(int)
arr_length = math.floor(len(nums)/2)
for element in nums:
count_dict[element] += 1
if count_dict[element] > arr_length:
return element
if __name__ == '__main__':
print(majority_element([3,2,3]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.