text
stringlengths 37
1.41M
|
---|
"""
梯度可以用来找到局部最优点
f(x)=log(x)的导数只能无限接近0
"""
import numpy as np
import matplotlib.pyplot as plt
# Define function f(x)
def f(x):
return np.log(x)
# compute f(x) for x=-10 to x=10
x = np.linspace(-10, 10, 500)
y = f(x)
# f'(x) using the rate of change
delta_x = 0.0001
y_derivative = (f(x + delta_x) - f(x)) / delta_x
# Plot
fig = plt.figure(figsize=(12, 5))
plt.plot(x, y, 'k-', label="$f(x)=log(x)$")
plt.plot(x, y_derivative, c="r", alpha=0.5, label="$f'(x)= \\frac {1} {x}$")
# plt.vlines(optim_point, y.min(), y.max(), color='gray', linestyles='--')
plt.title("Derivative to find optim")
plt.xlabel("x")
plt.legend()
plt.show() |
# -- coding = 'utf-8' --
# Author Kylin
# Python Version 3.7.3
# OS macOS
"""
龙格库塔算法
成员变量:
x0: x的初值
xn: x的终值
y0: y的初值
h: 步长
"""
class RungeKutta(object):
x0 = 0.0
xn = 0.0
y0 = 0.0
h = 0.0
def __init__(self, x0, xn, y0, h):
self.x0 = x0
self.xn = xn
self.y0 = y0
self.h = h
def calculate(self, Func):
x = self.x0
y = self.y0
xlist = [self.x0]
ylist = [self.y0]
while abs(self.xn - x) > 1.0e-5:
k1 = Func.getFunction(x, y)
k2 = Func.getFunction(x + self.h / 2, y + self.h * k1 / 2)
k3 = Func.getFunction(x + self.h / 2, y + self.h * k2 / 2)
k4 = Func.getFunction(x + self.h, y + self.h * k3)
yn = y + self.h * (k1 + 2 * k2 + 2 * k3 + k4) / 6
x += self.h
y = yn
xlist.append(x)
ylist.append(y)
return y, xlist, ylist
|
# -*- coding:utf-8 -*-
"""
manualGroupby 手动实现groupby的功能
:Author: [email protected]
:Last Modified by: [email protected]
"""
from operator import itemgetter
from collections import defaultdict
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'address': '5800 E 58TH', 'date': '07/02/2012'},
{'address': '2122 N CLARK', 'date': '07/03/2012'},
{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
{'address': '1060 W ADDISON', 'date': '07/02/2012'},
{'address': '4801 N BROADWAY', 'date': '07/01/2012'},
{'address': '1039 W GRANVILLE', 'date': '07/04/2012'}]
# groupby()函数扫描整个序列并且查找连续相同值(或者根据指定key函数返回值相同)的元素序列。
def groupby(items, key=None):
# 构建一个多值字典
d = defaultdict(list)
for item in items:
d[key(item)].append(item)
# 在每次迭代的时候,它会返回一个值和一个迭代器对象
for key, value in sorted(d.items()):
yield (key, value)
# 1. 一个非常重要的准备步骤是要根据指定的字段将数据排序
rows = sorted(rows, key = itemgetter('date'))
groupby(rows, key=itemgetter('date'))
# 2. 查看groupby效果
for date, items in groupby(rows, key=itemgetter('date')):
print(date)
for item in items:
print(item)
|
# -- coding = 'utf-8' --
# Author Kylin
# Python Version 3.7.3
# OS macOS
"""
近似计算pai与e
"""
import numpy as np
import matplotlib.pyplot as plt
def main():
# 1. 近似求解pai
n = np.sum(1 / np.arange(1, 10000) ** 2)
pai = np.sqrt(n * 6)
print("------The value of pai-------")
print("计算值 = {:.10f}, 真实值 = {:.10f}".format(pai, np.pi))
# 2. 近似求解e
n = np.arange(1, 20)
e_value = np.sum(1 / n.cumprod()) + 1
print("------The value of e-------")
print("计算值 = {:.10f}, 真实值 = {:.10f}".format(e_value, np.e))
if __name__ == "__main__":
main() |
"""
积分是微分的逆过程~
"""
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 2 * x
# Set up x from -10 to 10 with small steps
delta_x = 0.1
x = np.arange(-10, 10, delta_x)
# Find f(x) * delta_x
fx = f(x) * delta_x
# Compute the running sum
y = fx.cumsum()
# Plot
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("y")
plt.title("$f(x)=\int 2x = x^2$")
plt.show() |
# Finds the sum of all the numbers less than 10**6 which are palindroes
# in both base 10 and base 2
# Checks if an integer is a palindrome
def isPalindrome(int_to_check):
if len(int_to_check) <= 1:
return(True)
elif int_to_check[0] == int_to_check[-1]:
return(isPalindrome(int_to_check[1:-1]))
else:
return(False)
# Converts a decimal integer into a binary integer
def convertToBinString(int_to_convert):
binary_version = ''
while int_to_convert > 0:
binary_version = str(int_to_convert % 2) + binary_version
(int_to_convert) = int(int_to_convert / 2)
return(binary_version)
palindromes = []
# Only odd integers can be binary palindromes, because no integer
# starts with '0'
for number in range(1,500001):
test_int = (2*number - 1)
if isPalindrome(str(test_int)):
binary_test = convertToBinString(test_int)
if isPalindrome(str(binary_test)):
palindromes.append(test_int)
print(sum(palindromes))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 21:59:55 2020
@author: Sahil
"""
import turtle
tur=turtle.Turtle()
tur.color("red")
for i in range(5):
tur.forward(50)
tur.right(90)
tur1=turtle.Turtle()
tur1.color("blue")
for i in range(5):
tur1.forward(50)
tur1.right(144)
turtle.done()
|
import turtle
import random
X = -300
Y = -100
GOAL = 300
colors = ["cyan","coral","mediumblue","greenyellow","black","indigo","darkviolet"]
def draw_goal_line():
t = turtle.Turtle()
t.penup()
t.setposition(GOAL, 300)
t.right(90)
t.pendown()
t.forward(600)
def draw_fresh_penstroke(t):
t.pensize(random.randint(0, 10)+5)
t.forward(random.randint(0, 100))
def draw_turtle_movement(t):
draw_fresh_penstroke(t)
t.left(90)
draw_fresh_penstroke(t)
t.right(90)
draw_fresh_penstroke(t)
t.right(90)
draw_fresh_penstroke(t)
t.left(90)
def build_turtles():
turtles = []
for i in range(len(colors)):
t = turtle.Turtle()
t.penup()
t.setposition(X,Y + i*25)
t.pendown()
t.color(colors[i])
turtles.append(t)
return turtles
def did_any_turtle_reach_goal(turtles):
for t in turtles:
if t.position()[0] >= GOAL:
return True
return False
def which_turtle_moved_farthest(turtles):
farthest_turtle = turtles[0]
for t in turtles:
if t.position()[0] >= farthest_turtle.position()[0]:
farthest_turtle = t
return farthest_turtle
if __name__ == '__main__':
draw_goal_line()
turtles = build_turtles()
while did_any_turtle_reach_goal(turtles) == False:
for t in turtles:
draw_turtle_movement(t)
t = which_turtle_moved_farthest(turtles)
print("Our winning turtle was the", t.color()[0], "turtle.")
turtle.update() #render image
turtle.exitonclick() #wait for mouse click
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 CESAR SINCHIGUANO <[email protected]>
#
# Distributed under terms of the BSD license.
"""
"""
class Name():
def __init__(self,name=None,lastname=None):
self.firstname=name
self.lastname=lastname
class BankAccount:
def __init__(self, name=None,lastname=None, balance = 0.0):
self.log("Bank account has been created!")
self.name = Name(name,lastname)
self.balance = balance
self.money=0.0
def get_Balance(self):
self.log("Balance checked at " + str(self.balance))
return self.balance
def deposit(self, amount):
self.balance += amount
self.money=amount
self.log("+" + str(amount) + ": " + str(self.balance))
def withdraw(self, amount):
self.balance -= amount
self.money=amount
self.log("-" + str(amount) + ": " + str(self.balance))
def log(self, data):
file=open('bankStatement.txt','a')
file.write(data+'\n')
file.close()
|
#"inheriting from Queue"
#self.item is the thing of items
#self.items is the list itself
import Queue
class Deque(Queue.Queue):
def __init__(self):
super().__init__()#invokes the parent method
def addRear(self, item):
super().enqueue(item)
def removeFront(self):
return super().dequeue()
def addFront(self,item):
self.items.append(item)
def removeRear(self):
return (self.items.pop(0))
#don't need to implement size or isEmpty because we can
#get them from queue
|
from turtle import Turtle
from scoreboard import Scoreboard
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 2
MOVE_INCREMENT = .1
class CarManager(Turtle):
def __init__(self):
self.all_cars = []
super().__init__()
self.ht()
self.penup()
self.total = 0
def make_car(self):
random_chance = random.randint(1, 6)
if random_chance == 1:
car = Turtle()
car.shape("square")
car.color(random.choice(COLORS))
car.shapesize(stretch_len=2)
car.penup()
car.left(180)
car.goto(300, random.randint(-250, 250))
self.all_cars.append(car)
def move(self):
for car in self.all_cars:
car.forward(STARTING_MOVE_DISTANCE + self.total * MOVE_INCREMENT)
def score(self):
self.total += 1
|
#!/usr/bin/env python
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
def pow_helper(x,n):
if n==1:
return x
else:
temp = pow_helper(x,n/2)
temp = temp * temp
if n%2==1:
temp *= x
return temp
if n==0:
return 1
elif n<0:
return 1.0/pow_helper(x,-n)
else:
return pow_helper(x,n)
if __name__ == '__main__':
s0 = Solution()
print s0.myPow(3,-3)
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n<=0:
return []
ret = [[None], [TreeNode(1)]]
for i in range(2,n+1): #ith dp
dp = []
for j in range(1,i+1):# choose root
for left in ret[j-1]:
for right in ret[i-j]:
root = TreeNode(j)
root.left = self.copy_node(left )
root.right = self.copy_node(right)
dp.append(root)
ret.append(dp)
return ret[n]
def copy_node(self, node, offset):
if node==None:
return None
new_node = TreeNode(node.val + offset)
new_node.left = self.copy_node(node.left, offset)
new_node.right = self.copy_node(node.right, offset)
return new_node
if __name__ == '__main__':
s0 = Solution()
print s0.generateTrees(1)
|
# REVERSEDNS.PY checks if the MX records behind the domain has PTR.
# If PTR is missing, the domain's SMTP connection might be rejected due to Reverse DNS test.
# IP TEST
# Modules
import dns.resolver
# Init
mxRecord = None
aRecord = None
ptrRecord = None
maxScore = 0
totalScore = 0
# user input: Domain name
domain = input("Enter domain for Reverse DNS check:")
# Query for the domain MX
try:
# Querying for the domain's MX records
mxRecord = dns.resolver.query(domain, 'MX')
# Enumaretes through all the domain's MX records
for rdata in mxRecord:
splitMX = (rdata.to_text().split(" "))[1]
splitMX = splitMX[:-1]
# Pulls the A records behind the MX records
try:
aRecord = dns.resolver.query(splitMX,'A')
# for each A record, check if a PTR record is present.\
for adata in aRecord:
# Builds the PTR record string
ptrString = adata.to_text()
ptrString = '.'.join(reversed(ptrString.split("."))) + ".in-addr.arpa"
print (ptrString)
# Pulls the PTR record
try:
ptrRecord = dns.resolver.query(ptrString,'PTR')
print(ptrRecord)
maxScore+=1
totalScore+=1
# If no PTR record
except (dns.resolver.NXDOMAIN):
print('No PTR records for the SMTP server', adata)
maxScore += 1
# If there are no MX records available for that domain
except (dns.resolver.NoAnswer):
print('There are no A records for domain', mxRecord)
print('Total ReverseDNS score for domain', domain, 'is', totalScore, '/', maxScore)
# If there is no such domain
except (dns.resolver.NXDOMAIN):
print('There is no domain', domain)
# If there are no MX records available for that domain
except (dns.resolver.NoAnswer):
print('There are no MX records for domain', domain)
# If no nameServers available
except (dns.resolver.NoNameservers):
print('No name servers found') |
def postfix(s):
stack = []
s = s.split()
for i in s:
if i.isdigit():
stack.append(int(i))
elif i == "+":
old = stack.pop()
stack.append(stack.pop() + old)
elif i == "-":
old = stack.pop()
stack.append(stack.pop() - old)
elif i == "*":
old = stack.pop()
stack.append(stack.pop() * old)
elif i == "/":
old = stack.pop()
stack.append(stack.pop() / old)
return stack[-1]
print("2 3 + 4 * =>"postfix("2 3 + 4 *")) |
'''
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = 1
if x < 0:
sign = -1
b = 0
x = x*sign
while x:
b = b*10+x % 10
if b*sign <-2**31 or b*sign > 2**31-1:
return 0
x = int(x / 10 )
return b*sign
x = -123
print(Solution().reverse(x))
|
#LAB 14
#Due Date: 04/05/2019, 11:59PM
########################################
#
# Name: Hojin Ryoo
# Collaboration Statement:
#
########################################
def bubbleSort(numList):
'''
Takes a list and returns 2 values
1st returned value: a dictionary with the state of the list after each complete pass of bubble sort
2nd returned value: the sorted list
>>> bubbleSort([9,3,5,4,1,67,78])
({1: [3, 5, 4, 1, 9, 67, 78], 2: [3, 4, 1, 5, 9, 67, 78], 3: [3, 1, 4, 5, 9, 67, 78], 4: [1, 3, 4, 5, 9, 67, 78], 5: [1, 3, 4, 5, 9, 67, 78]}, [1, 3, 4, 5, 9, 67, 78])
'''
# Your code starts here
if type(numList)!= list:
return "error, input is not a list"
for x in numList:
if type(x) != int:
return "error, element is not an integer"
else:
continue
pass_number = 0
swapped = True
exit_index = len(numList) -1
current_status = {}
swapped_counter = 0
while swapped != False:
pass_number += 1
for index, element in enumerate(numList):
if index == exit_index:
break
elif element > numList[index+1]:
numList[index], numList[index+1] = numList[index+1], numList[index]
current_status[pass_number]=numList[:]
swapped_counter += 1
else:
continue
if swapped_counter == 0:
current_status[pass_number]=numList[:]
swapped = False
else:
swapped = True
swapped_counter = 0
return (current_status, numList) |
#Lab #5
#Due Date: 02/08/2019, 11:59PM
########################################
#
# Name: Hojin Ryoo
# Collaboration Statement: I did not work with anyone!
#
########################################
import math
class SodaMachine:
'''
>>> m = SodaMachine('Coke', 10)
>>> m.purchase()
'Product out of stock'
>>> m.restock(2)
'Current soda stock: 2'
>>> m.purchase()
'Please deposit $10'
>>> m.deposit(7)
'Balance: $7'
>>> m.purchase()
'Please deposit $3'
>>> m.deposit(5)
'Balance: $12'
>>> m.purchase()
'Coke dispensed, take your $2'
>>> m.deposit(10)
'Balance: $10'
>>> m.purchase()
'Coke dispensed'
>>> m.deposit(15)
'Sorry, out of stock. Take your $15 back'
'''
def __init__(self, product, price):
#-- start code here ---
self.product = product
self.price = price
self.depo = 0
self.stock = 0
def purchase(self):
#-- start code here ---
if self.stock == 0:
return "Product out of stock"
else:
if self.deposit == 0:
return "Please deposit $" + str(self.price)
elif self.depo < self.price:
return "Please deposit $" + str(self.price - self.depo)
elif self.depo > self.price:
remainder = self.depo - self.price
self.depo = 0
self.stock -= 1
return self.product + " dispensed, take your $" + str(remainder)
else:
self.depo = 0
self.stock -= 1
return self.product + " dispensed"
def deposit(self, amount):
#-- start code here ---
self.depo += amount
if self.stock == 0:
return "Sorry, out of stock. Take your $" + str(amount) + " back"
else:
return "Balance: $" + str(self.depo)
def restock(self, amount):
#-- start code here ---
self.stock += amount
return "Current soda stock: " + str(self.stock)
class Line:
'''
Creates objects of the class Line, takes 2 tuples. Class must have 2 PROPERTY methods
>>> line1=Line((-7,-9),(1,5.6))
>>> line1.distance
16.648
>>> line1.slope
1.825
>>> line2=Line((2,6),(2,3))
>>> line2.distance
3.0
>>> line2.slope
'Infinity'
'''
def __init__(self, coord1, coord2):
#-- start code here ---
self.x1 = coord1[0]
self.y1 = coord1[1]
self.x2 = coord2[0]
self.y2 = coord2[1]
@property
def distance(self):
#-- start code here ---
d = math.sqrt((self.x2-self.x1)**2 + (self.y2-self.y1)**2)
d = round(d, 3)
return d
#-- ends here ---
@property
def slope(self):
#-- start code here ---
num = self.y2 - self.y1
denom = self.x2 - self.x1
if denom == 0:
return "Infinity"
s = (num)/(denom)
s = round(s, 3)
return s
#-- ends here --- |
from Interop import classes
class MyClass(object):
x = 5
def method(self):
"""effects only the instance of the class"""
return 'instance method called', self
@classmethod
def classmethod(cls):
"""effects the class and instances of that class"""
cls.x = 10
return 'class method called', cls
@staticmethod
def staticmethod():
return 'static method called'
obj = MyClass()
obj2 = MyClass()
print MyClass.method(obj)
obj.classmethod()
print obj2.x |
"""Creating a class with property decorator"""
class MyProperty(object):
def __init__(self):
self.value = 5
pass
@property
def value_a(self):
return self.value
@value_a.setter
def value_a(self, value):
self.value = value
@value_a.deleter
def value_a(self):
self.value = None
print 'deleting'
this = MyProperty()
del this.value_a
print this.value_a
|
def swap(A, i, j):
"""Helper function to swap elements i and j of list A."""
if i != j:
A[i], A[j] = A[j], A[i]
def bubblesort(A):
"""In-place bubble sort."""
if len(A) == 1:
return
swapped = True
for i in range(len(A) - 1):
if not swapped:
break
swapped = False
for j in range(len(A) - 1 - i):
if A[j] > A[j + 1]:
swap(A, j, j + 1)
swapped = True
yield A
def insertionsort(A):
"""In-place insertion sort."""
for i in range(1, len(A)):
j = i
while j > 0 and A[j] < A[j - 1]:
swap(A, j, j - 1)
j -= 1
yield A
def mergesort(A, start, end):
"""Merge sort."""
if end <= start:
return
mid = start + ((end - start + 1) // 2) - 1
yield from mergesort(A, start, mid)
yield from mergesort(A, mid + 1, end)
yield from merge(A, start, mid, end)
yield A
def merge(A, start, mid, end):
"""Helper function for merge sort."""
merged = []
leftIdx = start
rightIdx = mid + 1
while leftIdx <= mid and rightIdx <= end:
if A[leftIdx] < A[rightIdx]:
merged.append(A[leftIdx])
leftIdx += 1
else:
merged.append(A[rightIdx])
rightIdx += 1
while leftIdx <= mid:
merged.append(A[leftIdx])
leftIdx += 1
while rightIdx <= end:
merged.append(A[rightIdx])
rightIdx += 1
for i, sorted_val in enumerate(merged):
A[start + i] = sorted_val
yield A
def quicksort(A, start, end):
"""In-place quicksort."""
if start >= end:
return
pivot = A[end]
pivotIdx = start
for i in range(start, end):
if A[i] < pivot:
swap(A, i, pivotIdx)
pivotIdx += 1
yield A
swap(A, end, pivotIdx)
yield A
yield from quicksort(A, start, pivotIdx - 1)
yield from quicksort(A, pivotIdx + 1, end)
def selectionsort(A):
"""In-place selection sort."""
if len(A) == 1:
return
for i in range(len(A)):
# Find minimum unsorted value.
minVal = A[i]
minIdx = i
for j in range(i, len(A)):
if A[j] < minVal:
minVal = A[j]
minIdx = j
yield A
swap(A, i, minIdx)
yield A
def E_sort(InputList):
for i in range(1, len(InputList)):
j = i - 1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j + 1] = InputList[j]
j = j - 1
InputList[j + 1] = nxt_element
return InputList |
#programma funzionante
def calcolatrice_di_margini():
a = 0
while a == 0:
print(
'--------------------------------------------------------------------------------------------------------------')
int = input("Cosa voui fare? Se vuoi calcolare i margini premi [m] + invio, se vuoi trovare il prezzo di vendita con il 40% di margine partendo dal costo premi [v]+ invio!")
if int == "m":
from sys import exit
def error():
print("Devi scrivere un numero!")
def get_number(question):
# start the loop and only break out of it if the input given is a number
while True:
try:
cost = float(input(question))
except ValueError:
error()
continue
except Exception as err:
print(err)
exit()
# just to make sure!
if isinstance(cost, float):
break
else:
error()
return cost
def calc(cost, sale):
if cost > sale:
print("Nessun margine, hai pagato piu di quanto hai speso! ")
elif cost == sale:
print("Sei andato in pari! ")
elif cost < sale:
print("Il margine di guadagno e' del ", ((sale - cost) / sale) * 100, "%")
if True:
# call the get_number function as pass the question to it
print(
'--------------------------------------------------------------------------------------------------------------')
cost = get_number('Quali sono stati i costi? ')
sale = get_number("A quanto e' stato venduto? ")
# run the calc function and pass the two values to it
calc(cost, sale)
elif int == "v":
try:
num1 = float (input("Inserisci la cifra a cui vuoi aggiungere il 40% di marigine: "))
except:
print("Devi inserire un numero! ")
print("Va venduto ad un prezzo netto di euro ", num1 * 1.66666666667)
else:
print(
'--------------------------------------------------------------------------------------------------------------')
print("Devi inserire o [v] o [m] e premere invio!")
'''''''''
a = 0
while a == 0:
print("-----------------------------------------------------------------------------------------------------")
try:
cost = float(input("Quali sono stati i costi? "))
sale = float(input("A quanto è stato venduto? "))
except:
print("Devi inserire un numero! ")
if cost > sale:
print("Nessun margine di guadagno, i costi superano i guadagni! ")
elif cost == sale:
print("Sei andato in pari! ")
elif cost < sale:
print("Il margine con cui hai venduto è del ",((sale - cost) / sale) * 100, "%")
#post reddit
#! /usr/bin/python
from sys import exit
def error():
print("Devi scrivere un numero!")
def get_number(question):
# start the loop and only break out of it if the input given is a number
while True:
try:
cost = float(input(question))
except ValueError:
error()
continue
except Exception as err:
print(err)
exit()
# just to make sure!
if isinstance(cost, float):
break
else:
error()
return cost
def calc(cost, sale):
if cost > sale:
print("Nessun margine, hai pagato piu di quanto hai speso! ")
elif cost == sale:
print("Sei andato in pari! ")
elif cost < sale:
print("Il margine di guadagno e' del ", ((sale - cost) / sale) * 100, "%")
while True:
# call the get_number function as pass the question to it
print('--------------------------------------------------------------------------------------------------------------')
cost = get_number('Quali sono stati i costi? ')
sale = get_number("A quanto e' stato venduto? ")
# run the calc function and pass the two values to it
calc(cost, sale)
'''''''''
|
import os
import re
def camel_case_to_snake(text):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def camel_case_to_hyphenated(text):
""""
CamelCase -> camel-case
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', text)
return re.sub('([a-z0-9])([A-Z])', r'\1-\2', s1).lower()
def hyphenated_to_camel_case(text):
""""
camel-case -> camelCase
"""
first, *rest = text.split("-")
return first + ''.join(word.capitalize() for word in rest)
def remove_indentation(text):
"""
removes indentation from a multi line string
"""
return "".join("{}\n".format(x.strip()) for x in text.split("\n"))
def indent(text, tabs):
"""
indents text
"""
return "".join("{}{}\n".format(" " * tabs, x) for x in text.split("\n"))
def file_dir(filepath):
filepath = os.path.abspath(filepath)
reversed = filepath[::-1]
splitted = re.split("\/|\\\\", reversed, 1)
if len(splitted) == 1:
return "./"
return splitted[1][::-1] + "/"
def filename(filepath):
return re.split("\/|\\\\", filepath[::-1], 1)[0][::-1]
def split_preserve_substrings(string, separator):
if len(string) == 0:
return [""]
splitted = []
in_sub_string = False
opening_char = None
length = len(string)
sep_len = len(separator)
prev_i = 0
for i in range(len(string)):
char = string[i]
is_last = i == length - 1
if char == "'" or char == '"':
if char == opening_char:
in_sub_string = False
else:
in_sub_string = True
opening_char = char
if in_sub_string and not is_last:
continue
found_sep = string[i:i+sep_len] == separator
if found_sep or is_last:
splitted.append(
string[
(prev_i + sep_len if prev_i > 0 else 0):(i if found_sep else i + 1)
]
)
prev_i = i
return splitted
|
import math
print("Ievadi skaitli:")
x = int(input())
a = x ** 2 + (x / 2) * 2
print("Atbilde:",int(a)) |
import math
from time import sleep
class Circle:
def __init__(self, x0, y0, x1, y1, R, r,):
self.x0 = x0
self.y0 = y0
self.x1 = x1
self.y1 = y1
self.R = R
self.r = r
if self.x0 > 0 and self.y0 > 0 and self.x1 > 0 and self.y1 > 0 and self.x0 is None:
if self.R > 0 and self.r > 0:
width = self.R - self.r
if width >= 1:
aver1 = (self.x0 + self.x1)
aver2 = (self.y0 + self.y1)
d1 = abs(self.x0 - self.x1)
d2 = abs(self.y0 - self.y1)
if d1 == d2 and d1 >= 4 and d2 >= 4:
xo = aver1 / 2
yo = aver2 / 2
print("Координаты круга: (", xo, "; ", yo, ")")
half_D = d1 / 2
if self.R <= half_D and self.r >= 1:
print("x0 = ", self.x0, "\n"
"y0 = ", self.y0, "\n"
"x1 = ", self.x1, "\n"
"y1 = ", self.y1, "\n"
"R = ",
self.R, "см.\n"
"r = ", self.r, "см.")
def square_perimeter(self):
P = round((2 * math.pi * (self.R + self.r)), 2)
print("Периметр круга: ", P, ".")
sleep(3)
Sq = round((math.pi * (self.R ** 2 - self.r ** 2)), 2)
print("Площадь круга: ", Sq, ".")
if __name__ == '__main__':
x0 = 5
print(x0)
y0 = 8
print(y0)
x1 = 12
print(x1)
y1 = 20
print(y1)
R = abs(x0 - x1) / 2
print("Внешний радиус (R):", R)
r = 5
|
def longest(word):
stac = []
result = []
length = len(word)
i = 0
while i < length:
current = word[i]
if i == 0:
stac.append(current)
result.append(1)
i+=1
continue
if current not in stac:
if len(stac) and ord(current) > ord(stac[-1]):
stac.append(current)
result.append(len(stac))
else:
if len(stac):
result.append(len(stac))
else:
result.append(1)
stac = []
else:
result.append(1)
stac = []
stac.append(current)
i+=1
# print(result)
return result
longest("ABACDA")
# longest("ABBC")
|
# CONSTRUCTOR
# -->A constructor is a special kind of method that Python calls when it instantiates an object using the definitions found in your class
# illustration of Constructor
class Student:
id = 0
name = "Default name"
email = "[email protected]"
schoolName = "Default school name"
no_of_leaves = 10
# this __init__ is called a constuctor
def __init__(self, id=id, name=name, email=email, schoolName=schoolName):
self.id = id
self.name = name
self.email = email
self.schoolName = schoolName
def printDetails(self):
return(f"ID = {self.id}\nName = {self.name}\nEmail = {self.email}\nSechool name = {self.schoolName}\n")
student1 = Student()
student2 = Student(1, "David", "[email protected]", "St. Xavious")
print(student1.printDetails())
print(student2.printDetails())
# to access the default values provided inside a Student class
print(Student.id)
print(Student.name)
print(Student.email)
print(Student.schoolName)
print(Student.no_of_leaves)
print(student1.no_of_leaves)
# DESTRUCTOR
# -->Destructors are called when an object gets destroyed
# illustration of Destructor
class Sample:
def __init__(self):
print("sample created")
def __del__(self):
print("Destructor called, Sample deleted")
sample1 = Sample()
del sample1 |
#!/usr/bin/env python3
class Shape(object):
LIZT = []
def __init__(self):
Shape.LIZT.append(self)
def __str__(self):
return('SHAPE:from __str__: {}'.format(Shape.LIZT))
def __repr__(self):
return('SHAPE: from __repr__: {} {}'.format(self,Shape.LIZT))
class Circle(Shape):
def __init__(self,radius):
super().__init__()
self.radius = radius
if __name__ == '__main__':
a = Circle(5)
print(a)
b = Circle(2)
print(b)
print(Shape)
|
#!/usr/bin/env python3
class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, delta_x, delta_y):
self.x = self.x + delta_x
self.y = self.y + delta_y
class Square(Shape):
def __init__(self, side=1, x=0, y=0):
super().__init__(x,y)
self.__id = 123
self.side = side
class Circle(Shape):
def __init__(self, radius=1, x=0, y=0):
super().__init__(x,y)
self.__id = 123
self.radius = radius
if __name__ == '__main__':
mySquare = Square(10,10,10)
myCircle = Circle(5,5,5)
print(mySquare)
print(myCircle)
|
"""cs module: class scope demonstration module."""
mv ="module variable: mv"
def mf():
return "module function (can be used like a class method in " \
"other languages): MF()"
class SC:
scv = "superclass class variable: self.scv"
__pscv = "private superclass class variable: no access"
def __init__(self):
self.siv = "superclass instance variable: self.siv " \
"(but use SC.siv for assignment)"
self.__psiv = "private superclass instance variable: " \
"no access"
def sm(self):
return "superclass method: self.SM()"
def __spm(self):
return "superclass private method: no access"
class C(SC):
cv = "class variable: self.cv (but use C.cv for assignment)"
__pcv = "class private variable: self.__pcv (but use C.__pcv " \
"for assignment)"
def __init__(self):
SC.__init__(self)
self.__piv = "private instance variable: self.__piv"
def m2(self):
return "method: self.m2()"
def __pm(self):
return "private method: self.__pm()"
def m(self, p="parameter: p"):
lv = "local variable: lv"
self.iv = "instance variable: self.xi"
print("Access local, global and built-in " \
"namespaces directly")
print("local namespace:", list(locals().keys()))
print(p) # parameter
print(lv) # instance variable
print("global namespace:", list(globals().keys()))
print(mv) # module variable
print(mf()) # module function
print("Access instance, class, and superclass namespaces " \
"through 'self'")
print("Instance namespace:",dir(self))
print(self.iv) # instance variable
print(self.__piv) # private instance variable
print(self.siv) # superclass instance variable
print("Class namespace:",dir(C))
print(self.cv) # class variable
print(self.m2()) # method
print(self.__pcv) # private class variable
print(self.__pm()) # private module
print("Superclass namespace:",dir(SC))
print(self.sm()) # superclass method
print(self.scv) # superclass variable through the instance
|
class Student:
def __init__(self,name):
self.name = name
self.exp = 0
self.lesson = 0
self.AddEXP(10)
def Hello(self):
print('สวัสดีจ้าาา ผมชื่อ{}'.format(self.name))
def Coding(self):
print('{} กำลังเขียนโปรแกรม'.format(self.name))
self.exp += 5
self.lesson += 1
def ShowEXP(self):
print('- {} มีประสบการณ์ {} EXP'.format(self.name,self.exp))
print('- เรียนไป {} ครั้งแล้ว'.format(self.lesson))
def AddEXP(self,score):
self.exp += score
self.lesson += 1
class SpecialStudent(Student):
def __init__(self,name,farther):
super().__init__(name)
self.farther = farther
mafia = ['Bill Gates','Thomas Edison']
if farther in mafia:
self.exp += 100
def AddEXP(self,score):
self.exp += (score*3)
self.lesson += 1
def Askexp(self,score=10):
print('ขอเพิ่มคะแนน')
self.AddEXP(score)
if __name__ == '__main__':
print('======= 1 Jan 2020 =======')
stname0 = SpecialStudent('Mark','Bill Gates')
stname0.ShowEXP()
stname1 = Student('Albert')
print(stname1.name)
stname1.Hello()
print('-----------------')
stname2 = Student('Steve')
print(stname2.name)
stname2.Hello()
print('======= 2 Jan 2020 =======')
print('-----Coding----get 10exp----')
# stname1.exp += 10
stname1.AddEXP(10)
# stname1.lesson += 1
print('======= 3 Jan 2020 =======')
print('ตอนนี้ exp ของแต่ละคนมีเท่าไร')
print(stname1.name,stname1.exp)
print(stname2.name,stname2.exp)
print('======= 4 Jan 2020 =======')
for i in range(5):
stname2.Coding()
stname1.ShowEXP()
stname2.ShowEXP()
|
import socket
print("For client side")
HOST=socket.gethostname()
PORT=12345
s=socket.socket()
s.connect((HOST,PORT))
while True:
def menu():
value = input(
'1. Find customer \n2. Add customer \n3. Delete customer \n4. Update customer age \n5. Update customer address \n6. Update customer phone\n7. Print Report \n8. Exit\n')
if value == '1':
print('value 1')
name = input().strip()
message = '|' + value +'|'+name
s.send(message.encode())
reply = s.recv(4096).decode()
print("Received", repr(reply))
# menu()
elif value == '2':
name = input().strip()
age = input().strip()
address = input().strip()
phone = input().strip()
if name=='':
print('please enter name.')
# menu()
else:
message = '|' + value + '|' + name + '|' + age + '|' + address+ '|' + phone
s.send(message.encode())
reply = s.recv(4096).decode()
print("Received", repr(reply))
# menu()
elif value == '3':
name = input().strip()
message = '|' + value + '|' + name
s.send(message.encode())
reply = s.recv(4096).decode()
print("Received", repr(reply))
# menu()
elif value == '4':
name = input().strip()
age = input().strip()
message = '|' + value + '|' + name + '|' + age
s.send(message.encode())
reply = s.recv(4096).decode()
print("Received", repr(reply))
# menu()
elif value == '5':
name = input().strip()
address = input().strip()
message = '|' + value + '|' + name + '|' + address
s.send(message.encode())
reply = s.recv(4096).decode()
print("Received", repr(reply))
# menu()
elif value == '6':
name = input().strip()
phone = input().strip()
message = '|' + value + '|' + name + '|' + phone
s.send(message.encode())
reply = s.recv(4096)
print("Received", repr(reply))
# menu()
elif value == '7':
message = '|' + value
s.send(message.encode())
reply = s.recv(4096).decode()
print("Received", repr(reply))
# menu()
elif value == '8':
message = '|' + value +'|abc'
s.send(message.encode())
reply = s.recv(4096).decode()
print("Received", repr(reply))
s.close()
exit()
menu()
# message=input("Ur msg: ")
# s.send(message.encode())
# if message=='end':
# break
# import socket
# import select
# import errno
#
# HEADER_LENGTH = 10
#
# IP = socket.gethostname()
# PORT = 60000
# my_username = input("Username: ")
#
# # Create a socket
# # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX
# # socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets
# client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# # Connect to a given ip and port
# client_socket.connect((IP, PORT))
#
# # Set connection to non-blocking state, so .recv() call won;t block, just return some exception we'll handle
# client_socket.setblocking(False)
#
# # Prepare username and header and send them
# # We need to encode username to bytes, then count number of bytes and prepare header of fixed size, that we encode to bytes as well
# username = my_username.encode('utf-8')
# username_header = f"{len(username):<{HEADER_LENGTH}}".encode('utf-8')
# client_socket.send(username_header + username)
#
# while True:
#
# # Wait for user to input a message
# message = input(f'{my_username} > ')
#
# # If message is not empty - send it
# if message:
#
# # Encode message to bytes, prepare header and convert to bytes, like for username above, then send
# message = message.encode('utf-8')
# message_header = f"{len(message):<{HEADER_LENGTH}}".encode('utf-8')
# client_socket.send(message_header + message)
#
# try:
# # Now we want to loop over received messages (there might be more than one) and print them
# while True:
#
# # Receive our "header" containing username length, it's size is defined and constant
# username_header = client_socket.recv(HEADER_LENGTH)
#
# # If we received no data, server gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR)
# if not len(username_header):
# print('Connection closed by the server')
# sys.exit()
#
# # Convert header to int value
# username_length = int(username_header.decode('utf-8').strip())
#
# # Receive and decode username
# username = client_socket.recv(username_length).decode('utf-8')
#
# # Now do the same for message (as we received username, we received whole message, there's no need to check if it has any length)
# message_header = client_socket.recv(HEADER_LENGTH)
# message_length = int(message_header.decode('utf-8').strip())
# message = client_socket.recv(message_length).decode('utf-8')
#
# # Print message
# print(f'{username} > {message}')
#
# except IOError as e:
# # This is normal on non blocking connections - when there are no incoming data error is going to be raised
# # Some operating systems will indicate that using AGAIN, and some using WOULDBLOCK error code
# # We are going to check for both - if one of them - that's expected, means no incoming data, continue as normal
# # If we got different error code - something happened
# if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
# print('Reading error: {}'.format(str(e)))
# sys.exit()
#
# # We just did not receive anything
# continue
#
# except Exception as e:
# # Any other exception - something happened, exit
# print('Reading error: '.format(str(e)))
# sys.exit() |
gameResult = input('Please enter game results: ').lower()
def count(coin):
H = coin.count('h')
T = coin.count('t')
if H > T:
return 'H wins!'
elif H < T:
return 'T wins'
else:
return 'Draw!'
print (count(gameResult))
|
import math
array = [0, 3, 4, 5, 6, 15, 18, 22, 25, 27, 31, 33, 34, 35, 37, 42, 53, 60]
def binarySearch(array, number):
middleIndexOfArray = int(math.floor(len(array) / 2))
if middleIndexOfArray == 0:
return False
if array[middleIndexOfArray] == number:
return True
elif array[middleIndexOfArray] > number:
return binarySearch(array[:middleIndexOfArray], number)
elif array[middleIndexOfArray] < number:
return binarySearch(array[middleIndexOfArray:], number)
# _bool = binarySearch(array, 47)
# print _bool |
file = open("01.txt")
seen = set()
requiredSumEntry = 2020
for line in file:
entry = int(line)
for seenEntry in seen:
supplement = requiredSumEntry - entry - seenEntry
if supplement in seen:
print("{} {} {} {}".format(entry, seenEntry, supplement, entry*seenEntry*supplement))
break
seen.add(entry)
|
file = open("02.txt")
numValid = 0
for line in file:
tokens = line.split(":")
policy = tokens[0].split(" ")
policyMinMax = policy[0].split("-")
policyMin = int(policyMinMax[0])
policyMax = int(policyMinMax[1])
policyLetter = policy[1]
password = tokens[1].strip()
count = { policyLetter: 0}
for char in password:
if char not in count:
count[char] = 0
count[char] += 1
#print(count)
if count[policyLetter] >= policyMin and count[policyLetter] <= policyMax:
numValid += 1
print(numValid)
|
file = open("01.txt")
freqs = [int(line) for line in file]
#freqs = [+3, +3, +4, -2, -4]
#print(freqs)
seen = set()
done = False
sumFreq = 0
numCycle = 0
seen.add(sumFreq)
while not done:
for freq in freqs:
sumFreq += freq
if sumFreq in seen:
print(sumFreq)
done = True
break
else:
seen.add(sumFreq)
numCycle += 1
print("numCycle:%d" % numCycle)
|
def trimPems(pem):
lines = pem.splitlines()
concatenated = ''
for x in range(1, len(lines) - 1):
concatenated += lines[x]
return concatenated
def isNumber(input):
try:
# Convert it into integer
val = int(input)
return True
except ValueError:
try:
# Convert it into float
val = float(input)
return True
except ValueError:
return False
|
# -*- coding: utf-8 -*-
"""
@author: Jung Soo
"""
monthInt = int(input("Enter an integer.\n"))
"""print(monthNumb)"""
if (monthInt == 1):
print("January")
elif (monthInt == 2):
print("February")
elif (monthInt == 3):
print("March")
elif (monthInt == 4):
print("April")
elif (monthInt == 5):
print("May")
elif (monthInt == 6):
print("June")
elif (monthInt == 7):
print("July")
elif (monthInt == 8):
print("August")
elif (monthInt == 9):
print("September")
elif (monthInt == 10):
print("October")
elif (monthInt == 11):
print("November")
elif (monthInt == 12):
print("December")
else: print("Integer does not map to a month") |
my_set = ['chair', 'table', 'wardrobe', 'sofa', 'bed']
for furniture in my_set:
print(furniture)
print('############################')
for furniture in my_set:
if furniture != 'sofa':
print(furniture)
my_list = my_set + ['door', 'mirror']
print(my_set)
for furniture in my_set:
if furniture == 'table':
print('I am wtiting here')
elif furniture == 'chair':
print('I am sitting here') |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
#import excel files and construct numpy array
s1 = pd.read_excel (r'C:\Users\lenovo\OneDrive\桌面\Physics\Pioneer Academics\Independent Project\Data\sasph008.xlsx') #place "r" before the path string to address special character, such as '\'. Don't forget to put the file name at the end of the path + '.xlsx'
s2 = pd.read_excel (r'C:\Users\lenovo\OneDrive\桌面\Physics\Pioneer Academics\Independent Project\Data\sdbs034.xlsx')
s3 = pd.read_excel (r'C:\Users\lenovo\OneDrive\桌面\Physics\Pioneer Academics\Independent Project\Data\sdbso042.xlsx')
s4 = pd.read_excel (r'C:\Users\lenovo\OneDrive\桌面\Physics\Pioneer Academics\Independent Project\Data\sdbt029.xlsx')
s5 = pd.read_excel (r'C:\Users\lenovo\OneDrive\桌面\Physics\Pioneer Academics\Independent Project\Data\sfeso4051.xlsx')
s6 = pd.read_excel (r'C:\Users\lenovo\OneDrive\桌面\Physics\Pioneer Academics\Independent Project\Data\sdbso2.xlsx')
def back_subs(df, end, num):
"""
Parameters
----------
df : Pandas DataFrame
df is the dataframe that is directly read from excel file. After the
execution of this function, two more columns will be added to the
DataFrame. The first is "mu", recording the linear absorption coef.
The second is "substracted_mu", recording the linear absorption coef
after doing background substraction
end : int
it records the index of the last element in pre-tail energy in df
num : int
it records how much elements are considered as pre-tail energy
Returns
-------
dict : Python dictionary
"mu_subs": it records the linear absorption coef
after doing background substraction.
"r2": it records the coef of determination for the linear regression
line used in the background substraction
"range": it records the energy range of pre-tail
"Ep": it records the energy associated with the highest
linear absorption coef (peak) in df after background substraction.
"msg": the message that can be printed indicating information
about r2, range, and Ep
"""
df_energy=df.Energy.to_numpy()
df_I0=df.I0.to_numpy()
df_PIPS=df.PIPS.to_numpy()
df_mu=df_PIPS/df_I0
df['mu']=df_mu
#determine the end and start energy
start=end-num
df_energy_pre=df_energy[start:end].reshape((-1,1))
df_mu_pre=df_mu[start:end]
df_model = LinearRegression().fit(df_energy_pre, df_mu_pre)
df_mu_back=df_model.intercept_+df_model.coef_*df_energy
df_mu_subs=df_mu-df_mu_back
df['substracted_mu']=df_mu_subs
df_musubs_min=np.amin(-1*df_mu_subs)
i_max=np.where(-df_musubs_min==df_mu_subs)[0].item()
df_energy_min=df_energy[i_max]
df_r2=df_model.score(df_energy_pre, df_mu_pre)
msg=("the r sqaured for regression of is "+
str(df_r2)+"\n energy for pre-tails are between" +str(df_energy[start])+
" eV and "+str(df_energy[end])+" eV"+"\n the energy of peak in s2 is "
+str(df_energy_min)+"eV")
return {"mu_subs":df_mu_subs,"r2":df_r2,"range":[df_energy[start],df_energy[end]],
"Ep":df_energy_min,"msg":msg}
s1_info=back_subs(s1,30,20)
s2_info=back_subs(s2,24,20)
s3_info=back_subs(s3,68,20)
s4_info=back_subs(s4,80,20)
s5_info=back_subs(s5,99,20)
s6_info=back_subs(s6,40,20)
#plot a superposed figure
space=0.065
plt.plot(s1['Energy'],back_subs(s1,30,20)["mu_subs"]+0*space,label="sasph008")
plt.plot(s2['Energy'],back_subs(s2,24,20)["mu_subs"]+1*space,label="sdbs034")
plt.plot(s3['Energy'],back_subs(s3,68,20)["mu_subs"]+2*space,label="sdbso042")
plt.plot(s4['Energy'],back_subs(s4,80,20)["mu_subs"]+3*space,label="sdbt029")
plt.plot(s5['Energy'],back_subs(s5,99,20)["mu_subs"]+4*space,label="sfeso4051")
plt.plot(s6['Energy'],back_subs(s6,40,20)["mu_subs"]+5*space,label="sdbso2")
plt.legend(loc="upper right")
plt.set_xlabel="energy"
plt.set_ylabel="absorption"
plt.show()
def normalization(df,start,end):
"""
Parameters
----------
df : Pandas DataFrame
df is the dataframe that is directly read from excel file.
start : int
it records the start of data taken for average when normalization
end : int
it records the end of data taken for average when normalization
Returns
-------
[df_norm_mu] : list
it is a list with only 1 element df_norm_mu
it is a DataFrame of width 1 that records the data after background substraction
and normalization
"""
df_fac=np.mean(df['substracted_mu'][start:end])
df_norm_mu=df['substracted_mu']/df_fac
return [df_norm_mu]
def normalization1(df,start,end):
"""
Parameters
----------
df : Pandas DataFrame
df is the dataframe that is directly read from excel file.
start : int
it records the start of data taken for regression when normalization
end : int
it records the end of data taken for regression when normalization
Returns
-------
[norm_mu,eq(df.Energy)] : list
it is a list with 2 elements
norm_mu is a DataFrame of width 1 that records the data after background substraction
and normalization
eq(df.Energy) is a column pandas DataFrame of length (df.Energy).shape[0]
it records the associated regression linear equation
"""
quad=np.polyfit(df.Energy[start:end],df['substracted_mu'][start:end],1)
eq=np.poly1d(quad)
norm_mu=df['substracted_mu']/eq(df.Energy)
return [norm_mu,eq(df.Energy)]
def normalization2(df,start,end):
"""
Parameters
----------
df : Pandas DataFrame
df is the dataframe that is directly read from excel file.
start : int
it records the start of data taken for regression when normalization
end : int
it records the end of data taken for regression when normalization
Returns
-------
[norm_mu,eq(df.Energy)] : list
it is a list with 2 elements
norm_mu is a DataFrame of width 1 that records the data after background substraction
and normalization
eq(df.Energy) is a column pandas DataFrame of length (df.Energy).shape[0]
it records the associated regression quadratic equation
"""
quad=np.polyfit(df.Energy[start:end],df['substracted_mu'][start:end],2)
eq=np.poly1d(quad)
norm_mu=df['substracted_mu']/eq(df.Energy)
return [norm_mu,eq(df.Energy)]
#define the start and legth of post-edge
energy_start=2510
energy_end=2515
def close_index(df,value):
"""
Parameters
----------
df : pandas DataFrame
a 1-width column of DataFrame within which you want to find the
closest number to value
value : float
the number that you want to approach
Returns
-------
index : int
such that df[index] is the closest number in df to the value input.
"""
index=abs(df - value).idxmin(axis=1,skipna=True)
return index
s6_start=close_index(s6['Energy'],energy_start)
s6_end=close_index(s6['Energy'],energy_end)
s1["mu_norm"]=normalization(s1,close_index(s1['Energy'],energy_start),close_index(s1['Energy'],energy_end))[0]
s2["mu_norm"]=normalization(s2,close_index(s2['Energy'],energy_start),close_index(s2['Energy'],energy_end))[0]
s3["mu_norm"]=normalization(s3, close_index(s3['Energy'],energy_start),close_index(s3['Energy'],energy_end))[0]
s4["mu_norm"]=normalization(s4, close_index(s4['Energy'],energy_start),close_index(s4['Energy'],energy_end))[0]
s5["mu_norm"]=normalization(s5, close_index(s5['Energy'],energy_start),close_index(s5['Energy'],energy_end))[0]
s6["mu_norm"]=normalization(s6,s6_start,s6_end)[0]
#define the start and end of spectra calculating chi2
start_energy=2461
end_energy=2525
def norm_merge(df1,df2):
"""
Parameters
----------
df1 : Pandas DataFrame
The "base" dataframe for merging. It is suggested that you take the dataframe
with fewer elements as df1 for higher accuracy. df1 should have only
one target to merge. (You cannot do a nested method for norm_merge)
df2 : Pandas DataFrame
df2 is being merged into df1.
Returns
-------
merged : Pandas DataFrame
first slice df1 and df2 so that they have the same starting and ending
energy start_energy and end_energy specified before
based on taking averages, more rows will be added to df2 so that there is
a corresponding value in df2 for every energy in df1. Those rows with energy not
present in df1 will be deleted. merged is the DataFrame after merging
df1 and df2. df2 should have only one target to merge.
(You cannot do a nested method for norm_merge)
"""
df1=df1[close_index(df1['Energy'],start_energy):close_index(df1['Energy'],end_energy)]
df1=df1.sort_index().reset_index(drop=True)
df2=df2[close_index(df2['Energy'],start_energy):close_index(df2['Energy'],end_energy)]
df2=df2.sort_index().reset_index(drop=True)
i=0
j=0
while((i<df1.shape[0]-1)and(j<df2.shape[0]-1)):
while(df1.Energy[i]>df2.Energy[j]):
if(not(df2.Energy[j+1])>df1.Energy[i]):
j=j+1
else:
df2_value=(df1.Energy[i]-df2.Energy[j])*(df2.mu_norm[j+1]-df2.mu_norm[j])
df2_value=df2_value/(df2.Energy[j+1]-df2.Energy[j])
df2_value=df2_value+df2.mu_norm[j]
data=pd.DataFrame({'Energy':df1.Energy[i],
'mu_norm':df2_value},index=[j+0.5])
df2=df2.append(data,ignore_index=False)
df2=df2.sort_index().reset_index(drop=True)
j=j+1
i=i+1
merged=pd.merge(df1,df2,how="inner",on="Energy")
return merged
norm=pd.DataFrame({'Energy':norm_merge(s1,s2)['Energy'],"s1_norm_mu":norm_merge(s1,s2)['mu_norm_x'],
"s2_norm_mu":norm_merge(s1,s2)['mu_norm_y'],
"s3_norm_mu":norm_merge(s1,s3)['mu_norm_y'],
"s4_norm_mu":norm_merge(s1,s4)['mu_norm_y'],
"s5_norm_mu":norm_merge(s1,s5)['mu_norm_y'],
"s6_norm_mu":norm_merge(s1,s6)['mu_norm_y']})
#plot the superposed normalized merged figures
plt.plot(norm['Energy'],norm['s1_norm_mu'],label="sasph008")
plt.plot(norm['Energy'],norm['s2_norm_mu'],label="sdbs034")
plt.plot(norm['Energy'],norm['s3_norm_mu'],label="sdbso042")
plt.plot(norm['Energy'],norm['s4_norm_mu'],label="sdbt029")
plt.plot(norm['Energy'],norm['s5_norm_mu'],label="sfeso4051")
plt.plot(norm['Energy'],norm['s6_norm_mu'],label="sdbso2")
plt.legend(loc="upper right")
plt.set_xlabel="energy"
plt.set_ylabel="absorption"
plt.show()
# export the excel file
norm.to_excel(r'C:\Users\lenovo\OneDrive\桌面\norm.xlsx', index = False, header=True)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#UNAM-CERT
"""
Manejo de tuplas y conjuntos
"""
from random import choice
list1=[]
list2=[]
note_bec = {}
con=set()
notes = (0,1,2,3,4,5,6,7,8,9,10)
becarios = ['Alonso',
'Eduardo',
'Gerardo',
'Rafael',
'Antonio',
'Fernanda',
'Angel',
'Itzel',
'Karina',
'Esteban',
'Alan',
'Samuel',
'Jose',
'Guadalupe',
'Angel',
'Ulises']
def asigna_calificaciones():
for b in becarios:
note_bec[b] = choice(notes)
def imprime_calificaciones():
for alumno in note_bec:
print '%s obtuvo la calificacion %s\n' % (alumno,note_bec[alumno])
def reprobados():
for alumno in note_bec:
if note_bec[alumno]>=8:
#aprobados
list1.append(alumno)
else:
#reprobados
list2.append(alumno)
tupla2=tuple(list2)
tupla1=tuple(list1)
return tupla1,tupla2
def prom():
n=0
for alumno in note_bec:
n+=note_bec[alumno]
promedio=n/(len(note_bec))
return promedio
def conjuntocal():
for alumno in note_bec:
conj.add(note_bec[alumno])
return conj
asigna_calificaciones()
imprime_calificaciones()
tup,tup2=reprobados()
promedio=prom()
con=conjuntocal()
print "Aprobados "+ str(tup)
print "Reprobados "+str(tup2)
print "Promedio : " + str(promedio)
print con
|
# making custom exceptions
class UppercaseException(Exception):
pass
words = ['eenie', 'meenie', 'MINY', 'MO']
for word in words:
if word.isupper():
try:
raise UppercaseException(word)
except UppercaseException as e:
print(e.message)
continue
|
# create a generator function to generate 1000 even numbers
def gen_Even_numbers(first=0, last=1000, step=1):
n = first
while n < last:
if n%2 == 0:
yield n
n += step
print 'Type of gen_Even_numbers = ', type(gen_Even_numbers)
# set a new variable object generator
ge = gen_Even_numbers(first=1,last=999)
print 'Type of ge = ', type(ge)
for i in ge:
print i
#TODO
# n = yield n --> check this out on Jeff Knupp's blog its about
# sending values to generator function, yet to learn this concept
print """
*****proper understanding of generators
A generator is a function which returns a iterable
any function with yield keyword is a generator
Generator input arguments optional
variable = some_generator_function() returns iterable object that
can be consumed using next(variable)
For example:
a = gen_list_nums()
print next(a) , next(a),next(a) , next(a),next(a) , next(a)
print a.next(), a.next(), a.next(), a.next()
"""
def gen_list_nums():
n = 0
while n < 100:
yield n
n += 1
a = gen_list_nums()
print next(a) , next(a),next(a) , next(a),next(a) , next(a)
print a.next(), a.next(), a.next(), a.next()
|
# list comprehensions
# zero based list
a = [num for num in range(11)]
print(a)
# n-based list
a = [num for num in range(1, 11)]
print(a)
# todo: write a function to generate n random words
# given limit of m letters in each word
|
from collections import namedtuple
d = namedtuple('Address','street city zipcode')
a1 = d('Street Address Whatever', 'Fayetteville', '72703')
print(a1)
print a1.street, a1.city , a1.zipcode
a2 = a1
print(a2)
a3 = a2._replace(city='Bentonville')
a2 = None
print a1, a2, a3
|
# -*- coding: utf-8 -*-
#
#To run this spider, from command line type 'scrapy crawl AlexaSpider -o <output_file_name>.json'
#
#This spider uses the scrapy framework to crawl sites
import scrapy
from alexa1m.items import Alexa1MItem
#Below methods used to put Alexa 1M in format that can be used by scrapy
from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen
from csv import DictReader
from chardet import detect
class AlexaSpider(scrapy.Spider):
name = "AlexaSpider"
#scrapy requires a start URL, so why not a top 10 university
start_urls = ( 'http://gatech.edu',)
#
# This parse function gets the current Alexa Top 1M from Amazon, asks how many you want to crawl, and store info in a dictionary
# The dictionary keys are 'rank', 'url', 'content' where content is string of raw source code
#
def parse(self, response):
#Asks for number of sites to get. Any random input returns 10 sites
try:
numsites = int(input("Enter number of sites you would like to get (Default is 10): "))
except:
numsites = 10
#Set a counter to 0 (used to control how sites we get during development)
count=0
#Get the current list of Alexa 1M and store as a string in memory
alexaurl = urlopen("http://s3.amazonaws.com/alexa-static/top-1m.csv.zip")
alexa_zip = ZipFile(StringIO(alexaurl.read()))
#put the Alexa 1M in a dictionary with keys 'rank' and 'url'
fieldnames=('rank','url')
reader = DictReader(alexa_zip.open("top-1m.csv"), fieldnames)
#Iterate over the Alexa 1M and store them as a list of dictionaries
for row in reader:
site = Alexa1MItem()
site['rank'] = row['rank']
site['url'] = "http://"+row['url']
# execute method to parse the current URL
yield scrapy.Request(site['url'], self.parse_Alexa1M, meta={'item': site})
#Exit the loop based on how many sites we want to get during development
count = count + 1
if (count==numsites):
break
# This method stores the content of the input URL as a string
def parse_Alexa1M(self, response):
site = response.meta['item']
site['encoding'] = detect(response.body)['encoding']
# this if..else used to store website content as a unicode string (added this due to some issues with chinese sites)
if (site['encoding'] == 'GB2312'):
# some sites come back as deprecated GB2312, so use current charset
site['encoding'] = 'GB18030'
site['content'] = response.body.decode(site['encoding'])
else:
site['content'] = response.body.decode(site['encoding'])
yield site
|
def exponent (base, count):
if count == 1:
return base
else:
return base * factorial(base, count-1)
print(exponent(2, 4)) #expect
|
# a, b = 0, 1
# for i in range(1, 10):
# print(a)
# a, b = b, a + b
# x = [1, [1, ['a', 'b']]]
# print(x)
# def search_list(list_of_tuples, value):
# for comb in list_of_tuples:
# for x in comb:
# if x == value:
# print(x)
# return comb
# else:
# return 0
# prices = [('AAPL', 96.43), ('IONS', 39.28), ('GS', 159.53)]
# ticker = 'GS'
# print(search_list(prices, ticker))
import datetime
date = '01-Apr-03'
date_object = datetime.datetime.strptime(date, '%d-%b-%y')
print((date_object).date())
|
class A:
def __init__(self):
super().__init__()
print("A")
class B:
def __init__(self):
super().__init__()
print("B")
class C(A, B):
def __init__(self):
super().__init__()
c = C()
|
class Prop(property):
def __init__(self, attr_name):
hide_attr_name = "_" + attr_name
def getter(inst):
return getattr(inst, hide_attr_name)
def setter(inst, value):
print(inst, value)
setattr(inst, hide_attr_name, value)
super().__init__(getter, setter)
def __get__(self, instance, owner):
print(instance, owner)
return super().__get__(instance, owner)
class A:
a = Prop("a")
def __init__(self):
self._a = 2
def __setattr__(self, name, value):
if name[0] == '_':
object.__setattr__(self, name, value)
else:
print("new")
object.__setattr__(self, name, value)
a = A()
print(a.a)
a.a = 42
|
# Look_and_say_problem
'''
the look an say sequence starts with 1. Subsequent numbers are derived by describing the previous
number in terms of consecutive digits. Specifically, to generate an entry of the subsequence from
the previous entry,read off the digits of the previous entry, counting the number of digits in groups
of the same digit.
e.g. 1; one 1
two 1s
one 2 and two ones
1,11,21,1211,111221,312211,13112221,1112213211
write a program that takes as input an integer n and returns nth integer in the look and say
sequence. return the result as a string.
hint: you need to return a string.
'''
def look_and_say(n):
def next_number(s):
result = []
i = 0
while i < len(s):
count = 1
while i + 1 < len(s) and s[i] == s[i+1]:
i += 1
count += 1
result.append(str(count) + str[i])
i += 1
return ''.join(result)
s = '1'
for _ in range(1,n):
s = next_number(s)
return s
# precise complexity is very hard to compute. time = O(n*2^n)
|
# Search_cyclically_sorted_array
'''
an array is said to be cyclically sorted if it is possible to cyclically shift its entries so that
it becomes sorted. e.g. [6,7,8,9,1,2,3,4,5] if you cyclically left shift for 4 times then it leads
to sorted array.
Design O(log n) algorithm for finding the position of the smallest element in a cyclically sorted
array. Assume all elements are distinct. e.g. above arraay should return 4.
'''
'''
for any m, if A[m] > A[n-1], then th minimum value must be an index in the range [m+1:n-1].
Conversy, if A[m] < A[n-1], then no in index [m+1, n-1] can be the index of the minimum value.
Note that, it is not possible for A[m] = A[n-1], since it is given that all elements are distinct.
These two observations are the basis for a binary search algorithm.
'''
def search_smallest(A):
left, right = 0, len(A) - 1
while left < right:
mid = (left + right) // 2
if A[mid] > A[right]:
# min must be in A[mid+1:right+1]
left = mid + 1
else: # A[mid] < A[right]
# min cant be in A[mid +1:right+1] so it must be in A[left: mid +1]
right = mid
# loop ends when left == right
return left
# time = O(log n)
# this problem cant, in general, be solved in less than linear time when elements are repeated.
# e.g. [1,1,1,1,1,0,1] 0 cant be detected without inspecting every element.
|
# Simple_Queue
class Queue:
def __init__(self):
self._data = collections.deque()
def enqueue(self, x):
self._data.append(x)
def dequeue(self):
return self._data.popleft()
def max(self):
return max(self._data)
# time complexity of enqueue, dequeue = O(1)
# time complexity of finding the maximum is O(n), n = # of entries
|
# Test_if_binary_tree_is_height_balanced
'''
a binary tree is said tobe height balanced if for each node in the tree, the difference in the height
of its left and right subtree is at most one. A perfect binary is height-balanced,as is a complete
binary tree. However, a height balanced binary tree does not have to be perfect or complete.
write a program that takes as input the root of a binary tree and checks whether a tree is height
balanced.
Hint: think of a classic binary tree algorithm.
'''
'''
brute force algorithm: compute a height for the tree rooted at each node x recursively. the basic
computation is to compute the height for each node starting from the leaves, and proceeding upwards.
for each node, we check if the difference in heights of left and right children is greater than one.
we can store heights in a hash table, or a new field in the nodes. this entails O(n) sorage and O(n)
time, where n is number of nodes.
we can solve this problem using less storage by observing that we do not need to store the heigts
of all nodes at the same time. Once we are done with a subtree, all we need to know whether it is
height balanced, and if so what its height is. we dont need any information about descendants of the
subtree's root.
'''
def is_balanced_binary_tree(tree):
BalancedStatusWithHeight = collections.namedtuple(
'BalancedStatusWithHeight', ('balanced','height'))
# first value of return value indicates if tree is balanced, and if balanced the second value
# of the return value is the height of tree.
def check_balanced(tree):
if not tree:
return BalancedStatusWithHeight(True, -1) # base case
left_result = check_balanced(tree.left)
if not left_result.balanced:
# left subtree is not balanced
return BalancedStatusWithHeight(False, 0)
right_result = check_balanced(tree.right)
if not right_result.balanced:
# right subtree is not balanced
return BalancedStatusWithHeight(False, 0)
is_balanced = abs(left_result.height - right_result.height) <= 1
height = max(left_result.height, right_result.height) + 1
return BalancedStatusWithHeight(is_balanced, height)
return check_balanced(tree).balanced
'''
the program implements a postorder traversal with some calls possibly being eliminated because of
early termination. O(h) = space bound, time = O(n)
|
# Enumerate_all_primes_to_n
'''
write a program that takes an integer argument and returns all the primes between 1 and that integer
Hint: exclude multiples of primes.
'''
''' solution 1: brute force
iterate over all i from 2 to n.
for each i, we test if i is prime; if so we add to results.
we can use trial divisionto test if i is prime, i.e. dividing i by each integer from 2 to square
root of i, and checking if the reminder is 0.
complexity --> O(n^ 3/2)
'''
'''
brute force tests each number independently and doesn't exploit the fact that we need to compute ALL
primes from 1 to n.
A better approach is to compute the primes ad when a number is identified as prime, to 'seive' it.
i.e. remove all its multiples from future considerations.
we use a boolean array to encode the candidates, i.e. ith entry in the array is true, then i is
potentially prime. Initially every number greater than or equal to two is a candidate. Whenever we
determine a number is prime, we will add it to the result, which is an array.
'''
# beautiful solution
# time complexity = O(n/2 + n/3 + n/5 + n/7 + ...) ~ O(nloglogn)
# space complexity = O(n)
def generate_primes(n):
primes = []
# is_prime[p] represents if p is prime or not.
# initially set each to true except 0 and 1.
# then use seiving to elinimate non primes.
is_prime = [False, False] + [True] * (n -1)
for p in range(2, n+1):
if is_prime[p]:
primes.append(p)
# seive p's multiples
for i in range(p, n+1, p):
is_prime[i] = False
return primes
''' more optimized solution is given in the book. ''' |
# Delete_duplicates_from_sorted_array
''' write a program that takes input as a sorted array and updates it so that all duplicates have
been removed and the remaining elements have been shifted left to fill the emptied indices.
Return the number of valid elements.
O(n) time and O(1) space complexities.
'''
'''
if O(1) space complexity was not concerned then we could have simply solve the problem by iterating
through A recording values that hve not appeared before into a dictionary. (dictionary is used to
determine if a value is new). New values are also written to list.The list is then copied back to A.
Brute force that uses O(1) additional space
irerate through A testing if A[i] equals A[i+1], and, if so, shift all elements at and after i+2
to left by one. (only possible because the array is sorted)
If all entries are equal time complexity becomes O(n^2)
'''
def delete_duplicate(A):
if not A:
return 0
write_index = 1
for i in range(len(A)):
if A[write_index - 1] != A[i]:
A[write_index] = A[i]
write_index += 1
return write_index |
# Palindrome
# palindrome string is one which reads tthe same when it is reversed.
# space = O(1) time = O(n)
def is_palindromic(s):
# note that s[~i] = s[-i - 1]
return all(s[i] == s[~i] for i in range(len(s) // 2))
|
# Compute_all_valid_IP_addresses
'''
decimal string is a string consisting of digitss between 0 and 9.
write a program that determines where to add periods to a decimal string so that the resulting string
is a valid IP address. There may be more than one valid IP addresses corresponding to a string,
in which case you should print all possibilities.
Hint: use nested loops
'''
'''
there are three periods in a valid IP address, so we can enumerate all possible placements of these
periods, and check whether all four corresponding substrings are between 0 and 255. We can reduce the
number of placements considered by spacing the periods 1 to 3 characters apart. We can also prune by
stoppoing as soon as substring is not valid.
'''
def get_valid_ip_address(s):
def is_valid_part(s):
# '00', '000', '01', etc arenot valid but '0' is valid
return len(s) == 0 or (s[0] != '0' and int(s) <= 255)
result = []
parts = [None] * 4
for i in range(1,min(4,len(s))):
parts[0] = s[:i]
if is_valid_part(parts[0]):
for j in range(1, min(len(s)-i, 4)):
parts[1] = s[i:i + j]
if is_valid_part(parts[1]):
for k in range(1, min(len(s)-i-j, 4)):
parts[2] = s[i+j:i+j+k]
parts[3] = s[i+j+k:]
if is_valid_part(parts[2]) and is_valid_part(parts[3]):
result.append('.'.join(parts))
return result
# total number of IP addresses is constant(2^32) therefore, time complexity = O(1)
|
num=int(input("Enter a number:")
factorial=1
if num=0:
print("The factorial value is 1")
else:
for i in range (1,num+1`):
factorial=factorial*i
print("Factorial value is:")
|
lower=int(input('Enter lower value")
upper=int(input("Enter upper value")
for i in range(lower,upper):
if(i%2!=0):
print(i)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 22:08:26 2018
@author: praveen
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv('C:/Users/praveen/Desktop/machine-learning udemy a-z/Machine Learning A-Z Template Folder\Part 2 - Regression/Section 4 - Simple Linear Regression/Simple_Linear_Regression/salary_data.csv')
x=dataset.iloc[:, :-1].values
y=dataset.iloc[:, 1].values
x=pd.DataFrame(x)
y=pd.DataFrame(y)
#spliting the data set into training set and test set
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=1/3,random_state=0)
#to defining regressor
from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(x_train,y_train)
#prediction of salary on x_test data
y_pred=regressor.predict(x_test)
y1_pred=regressor.predict(x_train)
#visulazing the training set result
plt.scatter(x_test,y_test,color='red')
plt.plot(x_train,y1_pred,color='blue')
plt.xlabel('years of experience')
plt.ylabel('salary')
plt.title('salary vs experience (training set)')
plt.show() |
a = int(input("Enter number1:: "))
b = int(input("Enter number2:: "))
c = int(input("Enter number3:: "))
if a>b and a>c:
print(a," is largest among ",a,", ",b," and ",c)
elif b>c:
print(b," is largest among ",a,", ",b," and ",c)
else:
print(c," is largest among ",a,", ",b," and ",c) |
text = input("Enter the line of text: ").split(" ")
list1 = []
for i in text:
if i not in list1:
list1.append(i)
text = " ".join(text)
for i in list1:
print("No: of occurences of ", i, " :: ", text.count(i))
|
# Nome: Felipe de Carvalho Alves
# RA: N2864F-5
import argparse
import Extensions as calc
import re
# Used to specify the .txt path that will be used
# Usado para especificar o arquivo que será usado
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--file", required=True, help="Caminho do arquivo texto")
args = vars(ap.parse_args())
# Opens the file and read the lines
# Abre o arquivo e lê as linhas
file = open(args["file"], "r")
lines = file.readlines()
# Variables declaration
# Declaralçao de variaveis
lineCalc = []
error = []
# Method to create a new file to save all equation results
# Método para criar um novo arquivo para salvar o resultado de todas as equações
def open_file():
file = open("result.txt", "w+")
return file
# method to close the result file
# Método para fechar o arquivo de resultados
def Close(file):
file.close()
# Method to write the lines in the result file
# Método para escrever as linhas no arquivo de resultado
def WriteLine(file, line):
file.write("{} \n".format(line))
# Method to call the extension script and calculate (or try to) the line equation
# Método para chamar o script de extensão e calcular (ou tentar) a equação da linha
def Calculate(char, lineCalc):
try:
calc.CalculateRPN(char, lineCalc)
except:
error.append(
'Linha com erro de calculo')
# Process start
# Inicio do processo
resultFile = open_file()
# To each line of the file lines, do something
# Para cada linha das linhas do arquivo, faça algo
for line in lines:
# If the line is blank/empty, jump to the next line
# Se for apenas uma linha em branco, pular o processamento
if line.isspace():
WriteLine(resultFile, "")
continue
# Remove the break line symbol at the end of the line
# Remove quebra linha presente no final da linha
line = re.sub('\r?\n', '', line)
# To each char in the line, do something
# Para cada caracter da linha, faça algo
for char in line:
# Keeps all chars lower case
# Deixa todos os caracteres minusculos
char.lower()
# If the char is numeric, add to calculation list
# Se o caracter for numérico, adiciona para a lista de calculo
if char.isnumeric():
lineCalc.append(int(char))
# If the char is a space, jump to the next char
# Se o caracter for um espaço, pula para o próximo caracter
elif char.isspace():
continue
# If the char is alphabetic and NOT x, return an invalid char error
# Se o caracter for alfabético e não ser X, retornar um erro de caracter inválido
elif char.isalpha():
if char is not 'x':
error.append('O caracter {} é inválido'.format(char))
break
# Execute the calculation when the char is x
# Efetua o calculo quando o caracter for x
else:
Calculate(char, lineCalc)
# Execute the calculation when is a special char
# Efetua o calculo sempre que for algum caracter especial
else:
Calculate(char, lineCalc)
# If the calculation list has more than one value, add an error for that line
# Se a lista de calculos tiver mais de um valor, adiciona um erro para aquela linha
if len(lineCalc) > 1:
error.append('Linha inconsistente, não retornou apenas um resultado. Resultado: {}'.format(
lineCalc))
# If the error list has an error, write the error in the result file
# Se a lista de erros tiver algum erro, escreva o erro no arquivo de resultado
if len(error) > 0:
WriteLine(
resultFile, "{} => ERRO: {}".format(line, error[0]))
# If the error list has 0 items, write the line result in the result file
# Se a lista de erros for 0, escreva o resultado da linha no arquivo de resultados
else:
WriteLine(resultFile, "{} => Result: {}".format(line, lineCalc[0]))
# Clear the calcualtion list and error list
# Limpa as listas de calculo e erro da linha
lineCalc.clear()
error.clear()
# Close the result file and ends the script
# Fecha o arquivo de resultado e finaliza o script
Close(resultFile)
print("Processo concluído, arquivo 'result.txt' gerado dentro da pasta 'src' do projeto")
|
"""
Revisão IF ELSE
IF - SE
ELSE - SE NÃO
ELIF - SE NÃO SE
# IF / ELIF /ELSE - Juntos formas a estrutura de condição no Python para tomada de decisão
Traduzindo a estrutura
------------
SE algo for verdadeiro, faça isso:
comandos
comandos
Se não faça aquilo:
comandos
comandos
------------
"""
# Exemplo:
# Desenvolva um algoritmo que receba a média de um aluno (0 - 100) e informe se ele está aprovado
# ou reprovado, a média para aprovação é 60
media = float(input('Digite a sua média: '))
if media > 60: # Se for verdadeiro
print(f"Você está aprovado média acima de 60: {media}")
elif media == 60:
print("Passou na rapa em amigão")
else:
print(f"Você está reprovado com a média {media}")
valor1,valor2 = 10, 8
if valor1 > valor2:
# Comando
else:
# Comando |
"""
Funções de física versão 2
"""
def calculo_densidade():
def valor_massa():
print('Então vamos descobrir o valor da massa, para isso preciso que você: ')
v = float(input("Digite o valor do volume"))
d = float(input('Digite o valor da densidade'))
return v * d
def valor_volume():
print('Então vamos descobrir o valor do volume, para isso preciso que você: ')
m = float(input("Digite o valor da massa"))
d = float(input('Digite o valor da densidade'))
return m/d
def valor_densidade():
print('Então vamos descobrir o valor da densidade, para isso preciso que você: ')
m = float(input("Digite o valor da massa"))
v = float(input('Digite o valor do volume'))
return m/v
def help_densidade():
print('Densidade é blablabla')
while True:
opcao = input("Você quer descorbrir \n(m)massa,\n(v)volume,\n(d)densidade?\nDigite (h) para ajuda)\n")
if opcao.lower() == 'm':
print(f' Valor da massa = {valor_massa()}')
elif opcao.lower() == 'v':
print(f' Valor do volume = {valor_volume()}')
elif opcao.lower() == 'd':
print(f'Valor da densidade: {valor_densidade()}')
elif opcao.lower() == 'h':
help_densidade()
else:
print('Comando inválido')
sair = input("Deseja sair? s/n")
if sair.lower() == 's':
break
|
def leapYear(year):
if year % 4 == 0: # use == to compare values. = is to assign
if (year % 100 != 0) or (year % 400 == 0): # make sure the conditions are correct. you had 100 != instead of 100 ==
print(year, " is a leap year")
else:
print(year, 'is not a leap year')
else:
print(year, 'is not a leap year')
userYear = int(input('Please enter a year to check if it is a leap year or not: '))
leapYear(userYear)
'''
a leap year is on every year that is evenly divisible by 4
except every year that is evenly divisible by 100
unless the year is also evenly divisible by 400
def leapYear(year):
if year % 4 == 0: # use == to compare values. = is to assign
if (year % 100 == 0) and (year % 400 != 0): #
print(year, " is a leap year")
else:
print(year, 'is not a leap year')
''' |
'''
Write a program that prompts for weight (in pounds) and height (in inches) of a person, and
prints the weight status of that person.
Body mass index (BMI) is a number calculated from a person’s weight and height using the
following formula: 𝑤𝑒𝑖𝑔ℎ𝑡/ℎ𝑒𝑖𝑔ℎ𝑡^2. Where 𝑤𝑒𝑖𝑔ℎ𝑡 is in kilograms and ℎ𝑒𝑖𝑔ℎ𝑡 is in meters.
Note: 1 pound is 0.453592 kilograms and 1 inch is 0.0254 meters.
'''
def bmi():
weight = int(input('Please enter your weight in pounds: '))
height = int(input('Please enter your height in inches: '))
x = (weight * 0.453592) / ((height * 0.0254) ** 2) # this is the formula to calculate bmi (wight/height^2)
if x < 18.5:
print('Your bmi is ', x, 'and you are underweight')
elif x >= 18.5 and x < 25:
print('Your bmi is ', x, 'and your weight is normal')
elif x >= 25 and x < 30:
print('Your bmi is ', x, 'and you are overweight')
else:
print('Your bmi is ', x, 'and you are obese')
bmi()
|
"""Implement fig_subplot for matplotlib."""
import matplotlib.pyplot as plt
def fig_subplot(nrows=1, ncols=1, sharex=False, sharey=False,
subplot_kw=None, **fig_kw):
"""Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Parameters
----------
nrows : int, optional
Number of rows of the subplot grid. Defaults to 1.
nrows : int, optional
Number of columns of the subplot grid. Defaults to 1.
sharex : bool, optional
If True, the X axis will be shared amongst all subplots.
sharex : bool, optional
If True, the Y axis will be shared amongst all subplots.
subplot_kw : dict, optional
Dict with keywords passed to the add_subplot() call used to create each
subplots.
fig_kw : dict, optional
Dict with keywords passed to the figure() call. Note that all keywords
not recognized above will be automatically included here.
Returns
-------
fig_axes : list
A list containing [fig, ax1, ax2, ...], where fig is the Matplotlib
Figure object and the rest are the axes.
Examples
--------
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Just a figure and one subplot
f, ax = fig_subplot()
ax.plot(x, y)
ax.set_title('Simple plot')
# Two subplots, unpack the output immediately
f, ax1, ax2 = fig_subplot(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Four polar axes
fig_subplot(2, 2, subplot_kw=dict(polar=True))
"""
if subplot_kw is None:
subplot_kw = {}
fig = plt.figure(**fig_kw)
# Create first subplot separately, so we can share it if requested
ax1 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)
if sharex:
subplot_kw['sharex'] = ax1
if sharey:
subplot_kw['sharey'] = ax1
# Valid indices for axes start at 1, since fig is at 0:
axes = [ fig.add_subplot(nrows, ncols, i, **subplot_kw)
for i in range(2, nrows*ncols+1)]
return [fig, ax1] + axes
if __name__ == '__main__':
# Simple demo
import numpy as np
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
plt.close('all')
# Just a figure and one subplot
f, ax = fig_subplot()
ax.plot(x, y)
ax.set_title('Simple plot')
# Two subplots, grab the whole fig_axes list
fax = fig_subplot(2, sharex=True)
fax[1].plot(x, y)
fax[1].set_title('Sharing X axis')
fax[2].scatter(x, y)
# Two subplots, unpack the output immediately
f, ax1, ax2 = fig_subplot(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Three subplots sharing both x/y axes
f, ax1, ax2, ax3 = fig_subplot(3, sharex=True, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing both axes')
ax2.scatter(x, y)
ax3.scatter(x, 2*y**2-1,color='r')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
# Four polar axes
fig_subplot(2, 2, subplot_kw=dict(polar=True))
plt.show()
|
"""Simple vector implementation."""
class Vector(object):
#: esto es tal cosa...
comun = 1
def __init__(self, *components):
"""Initialize a vector."""
print "initializing vector"
if len(components)==1:
# If we are given a single sequence, try to make it into a tuple to
# support initialization with regular sequences.
try:
components = tuple(components[0])
except TypeError:
# This is the exception raised by tuple(x) if x is not iterable
pass
self.components = components
def __eq__(self, other):
return self.components == other.components
def __str__(self):
return 'Vector%s' % (self.components,)
__repr__ = __str__
def __len__(self):
self.longitud = 10
return len(self.components)
def __add__(self, other):
c = [x+y for x,y in zip(self.components, other.components)]
return Vector(c)
def __mul__(self, other):
if isinstance(other, Vector):
# Dot product
return sum(x*y for x,y in zip(self.components, other.components))
else:
# Product with a scalar
c = [other*x for x in self.components]
return Vector(c)
def __rmul__(self, other):
return self.__mul__(other)
|
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
def search(l, n):
if not l:
return False
if len(l) == 1:
return l[0] == n
while 1:
mid = len(l) / 2
mid_n = l[mid]
if mid == 0:
return mid_n == n
if mid_n > n:
l = l[:mid]
continue
if mid_n < n:
l = l[mid:]
continue
return mid_n == n
if __name__ == '__main__':
l = [1, 3, 5, 2, 7, 0, 3]
l.sort()
print len(l)
print l
print search(l, 3)
print search(l, 9)
|
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class Solution(object):
def longestCommonPrefix(self, strs):
if not strs:
return ""
pre = None
for s in strs:
if pre is None:
pre = s
else:
j = len(pre) if len(pre) < len(s) else len(s)
pre = pre[:j]
for i in range(j):
if pre[i] != s[i]:
pre = pre[:i]
break
if pre == "":
break
return pre
def longestCommonPrefix2(self, strs):
if not strs:
return ""
diff = False
i = 0
while True:
c = None
for s in strs:
if i >= len(s):
diff = True
break
if c == None:
c = s[i]
elif c != s[i]:
diff = True
break
else:
diff = False
if diff:
break
i += 1
return strs[0][: i]
if __name__ == '__main__':
so = Solution()
l1 = ["flower","flow","flight"]
print so.longestCommonPrefix(l1)
l1 = ["dog","racecar","car"]
print so.longestCommonPrefix(l1)
l1 = ["dog"]
print so.longestCommonPrefix(l1)
l1 = ["aa","a"]
print so.longestCommonPrefix(l1)
|
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
ret, seq = {}, []
while head:
v = head.val
if v not in ret:
ret[v] = head
seq.append(v)
head = head.next
root = ListNode(0)
head = root
for i in seq:
head.next = ret[i]
head.next.next = None
head = head.next
return root.next
def deleteDuplicates2(self, head):
if not head:
return
root = ListNode(0)
root.next = head
last, head = head, head.next
while head and head.next:
if head.val != last.val:
last.next = head
last = last.next
head = head.next
if head and last.val == head.val:
last.next = None
elif head:
last.next = head
return root.next
def genList(l):
root = ListNode(0)
c = root
for x in l:
n = ListNode(x)
c.next = n
c = n
return root.next
def printList(n):
if not n:
print "None"
return
s = ''
while n:
s += str(n.val) + '->'
n = n.next
print s[:-2]
if __name__ == '__main__':
so = Solution()
def test(l):
l = genList(l)
printList(l)
l = so.deleteDuplicates(l)
printList(l)
test([1, 1, 2, 2, 3, 4, 5, 6, 6, 6, 7, 8, 9, 9])
test([1])
test([2, 2, 2, 2, 2])
test([2, 2])
test([1, 1, 1, 1, 4, 4, 4, 7, 5])
test([1, 1, 2])
|
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
if not root:
return True
def valid(left, right):
if not left and not right:
return True
elif not left or not right:
return False
return left.val == right.val and valid(left.left, right.right) and valid(left.right, right.left)
return valid(root.left, root.right)
if __name__ == '__main__':
so = Solution()
def test():
root = TreeNode(1)
assert so.isSymmetric(root)
root.left = TreeNode(2)
assert not so.isSymmetric(root)
root.right = TreeNode(2)
assert so.isSymmetric(root)
root.right = TreeNode(3)
assert not so.isSymmetric(root)
root.left = TreeNode(2)
root.left.left = TreeNode(3)
root.right = TreeNode(3)
root.right.left = TreeNode(2)
assert not so.isSymmetric(root)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.right.right = TreeNode(3)
root.left.right = TreeNode(4)
root.right.left = TreeNode(4)
assert so.isSymmetric(root)
test()
|
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
class Solution(object):
def romanToInt(self, s):
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
rule = {'V': 'I', 'X': 'I', 'L': 'X', 'C': 'X', 'D': 'C', 'M': 'C'}
if not s:
return 0
if len(s) == 1:
return roman[s]
ret, length = 0, len(s)
i = 0
while i < length:
c = s[i]
if i + 1 < length:
d = s[i + 1]
if d != 'I' and c == rule[d]:
ret += roman[d] - roman[c]
i += 2
continue
ret += roman[c]
i += 1
return ret
def romanToInt2(self, s):
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
rule = {'I': ['V', 'X'], 'X': ['L', 'C'], 'C':['D', 'M']}
rules = rule.keys()
if not s:
return 0
if len(s) == 1:
return roman[s]
ret, length = 0, len(s)
i = 0
while i < length:
c = s[i]
if i + 1 < length:
if c in rules and s[i + 1] in rule[c]:
ret += roman[s[i + 1]] - roman[c]
i += 2
continue
ret += roman[c]
i += 1
return ret
if __name__ == '__main__':
so = Solution()
print so.romanToInt('III')
print so.romanToInt('IV')
print so.romanToInt('LVIII')
print so.romanToInt('MCMXCIV')
|
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
"""
https://leetcode-cn.com/problems/add-two-numbers/
"""
def add_next(self, l):
last = l
extra = 1
while True:
val = l.val + extra
if val >= 10:
val = val - 10
extra = 1
else:
extra = 0
l.val = val
if extra == 0:
if not l.next:
break
else:
l = l.next
elif not l.next:
n = ListNode(1)
l.next = n
break
else:
l = l.next
return last
def addTwoNumbers(self, l1, l2):
l3 = ListNode(0)
last = l3
extra = 0
while l1 or l2 :
val1 = 0 if not l1 else l1.val
val2 = 0 if not l2 else l2.val
val = val1 + val2 + extra
if val >= 10:
val = val - 10
extra = 1
else:
extra = 0
last.next = ListNode(val)
last = last.next
l1 = None if not l1 else l1.next
l2 = None if not l2 else l2.next
if extra == 1:
last.next = ListNode(1)
return l3.next
def addTwoNumbers2(self, l1, l2):
l3 = ListNode(0)
last = l3
extra = 0
while True:
val = l1.val + l2.val + extra
if val >= 10:
val = val - 10
extra = 1
else:
extra = 0
n = ListNode(val)
last.next = n
last = n
if not l1.next and l2.next:
if extra == 1:
last.next = self.add_next(l2.next)
else:
last.next = l2.next
break
if l1.next and not l2.next:
if extra == 1:
last.next = self.add_next(l1.next)
else:
last.next = l1.next
break
if not l1.next and not l2.next:
if extra == 1:
n = ListNode(1)
last.next = n
last = n
break
l1 = l1.next
l2 = l2.next
return l3.next
def gen_node(nums):
l = ListNode(nums[0])
last = l
for i in nums[1:]:
n = ListNode(i)
last.next = n
last = n
return l
def output_node(n):
str1 = ''
while True:
str1 = str1 + str(n.val)
if not n.next:
break
n = n.next
str1 = str1 + '->'
print str1
if __name__ == '__main__':
n1 = [2, 4, 3]
n2 = [5, 6, 4]
l1 = gen_node(n1)
output_node(l1)
l2 = gen_node(n2)
output_node(l2)
so = Solution()
l3 = so.addTwoNumbers(l1, l2)
output_node(l3)
l1 = gen_node([6])
l2 = gen_node([5])
l3 = so.addTwoNumbers(l1, l2)
output_node(l3)
l1 = gen_node([6,9])
l2 = gen_node([5])
l3 = so.addTwoNumbers(l1, l2)
output_node(l3)
|
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class Solution(object):
def permute(self, nums):
if not nums:
return []
def arrange(nums0, total):
if total == 1:
return [nums0]
ret, t = [], total - 1
for i, v in enumerate(nums0):
res = arrange(nums0[:i] + nums0[i + 1:], t) #[[...],[...]]
v = [v]
for item in res:
ret.append(v + item)
return ret
return arrange(nums, len(nums))
if __name__ == '__main__':
so = Solution()
def test(nums):
print 'nums:',nums,' ret:\n', len(so.permute(nums))
test([1])
test([1, 2])
test([1, 2, 3])
test([0, 1, 2, 3])
test([-1, 0, 1, 2, 3])
test([1, 2, 3,4,5,6])
|
''' Schemdraw drawing segments.
Each element is made up of one or more segments.
'''
from collections import namedtuple
import numpy as np
from .transform import mirror_point, mirror_array, flip_point
BBox = namedtuple('BBox', ['xmin', 'ymin', 'xmax', 'ymax'])
def roundcorners(verts, radius=.5):
''' Round the corners of polygon defined by verts.
Works for convex polygons assuming radius fits inside.
Parameters
----------
verts : list
List of (x,y) pairs defining corners of polygon
radius : float
Radius of curvature
Adapted from:
https://stackoverflow.com/questions/24771828/algorithm-for-creating-rounded-corners-in-a-polygon
'''
poly = []
for v in range(len(verts))[::-1]:
p1 = verts[v]
p2 = verts[v-1]
p3 = verts[v-2]
dx1 = p2[0]-p1[0]
dy1 = p2[1]-p1[1]
dx2 = p2[0]-p3[0]
dy2 = p2[1]-p3[1]
angle = (np.arctan2(dy1, dx1) - np.arctan2(dy2, dx2))/2
tan = abs(np.tan(angle))
segment = radius/tan
def getlength(x, y):
return np.sqrt(x*x + y*y)
def getproportionpoint(point, segment, length, dx, dy):
factor = segment/length
return np.asarray([point[0]-dx * factor,
point[1]-dy * factor])
length1 = getlength(dx1, dy1)
length2 = getlength(dx2, dy2)
length = min(length1, length2)
if segment > length:
segment = length
radius = length * tan
p1cross = getproportionpoint(p2, segment, length1, dx1, dy1)
p2cross = getproportionpoint(p2, segment, length2, dx2, dy2)
dx = p2[0]*2 - p1cross[0] - p2cross[0]
dy = p2[1]*2 - p1cross[1] - p2cross[1]
L = getlength(dx, dy)
d = getlength(segment, radius)
circlepoint = getproportionpoint(p2, d, L, dx, dy)
startangle = np.arctan2(p1cross[1] - circlepoint[1], p1cross[0]-circlepoint[0])
endangle = np.arctan2(p2cross[1] - circlepoint[1], p2cross[0]-circlepoint[0])
startangle, endangle = np.unwrap([startangle, endangle])
arc = []
for i in np.linspace(startangle, endangle, 100):
arc.append([circlepoint[0] + np.cos(i)*radius,
circlepoint[1] + np.sin(i)*radius])
poly.extend(arc)
poly.append(poly[0]) # Close the loop
return np.asarray(poly)
class Segment(object):
''' A segment (path), part of an Element.
Parameters
----------
path : array-like
List of [x,y] coordinates making the path
Keyword Arguments
-----------------
color : string
Color for this segment
lw : float
Line width for the segment
ls : string
Line style for the segment '-', '--', ':', etc.
capstyle : string
Capstyle for the segment: 'round', 'miter', or 'bevel'
joinstyle : string
Joinstyle for the segment: 'round', 'miter', or 'bevel'
fill : string
Color to fill if path is closed
zorder : int
Z-order for segment
'''
def __init__(self, path, **kwargs):
self.path = np.asarray(path) # Untranformed path
self.zorder = kwargs.get('zorder', None)
self.color = kwargs.get('color', None)
self.fill = kwargs.get('fill', None)
self.lw = kwargs.get('lw', None)
self.ls = kwargs.get('ls', None)
self.capstyle = kwargs.get('capstyle', None)
self.joinstyle = kwargs.get('joinstyle', None)
def end(self):
''' Get endpoint of this segment, untransformed '''
return self.path[-1]
def xform(self, transform, **style):
''' Return a new Segment that has been transformed
to its global position
Parameters
----------
transform : schemdraw.Transform
Transformation to apply
style : Style keyword arguments from Element to apply as default
'''
params = {'zorder': self.zorder,
'color': self.color,
'fill': self.fill,
'lw': self.lw,
'ls': self.ls,
'capstyle': self.capstyle,
'joinstyle': self.joinstyle}
params.update(style)
return Segment(transform.transform(self.path), **params)
def get_bbox(self):
''' Get bounding box (untransformed)
Returns
-------
xmin, ymin, xmax, ymax
Bounding box limits
'''
x = [p[0] for p in self.path]
y = [p[1] for p in self.path]
return BBox(min(x), min(y), max(x), max(y))
def doreverse(self, centerx):
''' Reverse the path (flip horizontal about the center of the path) '''
self.path = mirror_array(self.path, centerx)[::-1]
def doflip(self):
''' Vertically flip the element '''
flipped = []
for p in self.path:
flipped.append(flip_point(p))
self.path = flipped
def draw(self, fig, transform, **style):
''' Draw the segment
Parameters
----------
fig : schemdraw.Figure
Figure to draw on
transform : Transform
Transform to apply before drawing
'''
path = transform.transform_array(self.path)
zorder = self.zorder if self.zorder is not None else style.get('zorder', 2)
color = self.color if self.color else style.get('color', 'black')
fill = self.fill if self.fill is not None else style.get('fill', None)
ls = self.ls if self.ls else style.get('ls', '-')
lw = self.lw if self.lw else style.get('lw', 2)
capstyle = self.capstyle if self.capstyle else style.get('capstyle', 'round')
joinstyle = self.joinstyle if self.joinstyle else style.get('joinstyle', 'round')
if fill: # Check if path is closed
tlist = list(map(tuple, path)) # Need path as tuples for set()
dofill = len(tlist) != len(set(tlist)) # Path has duplicates, can fill it
if not dofill:
fill = None
elif fill is True:
fill = color
elif fill is False:
fill = None
fig.plot(path[:, 0], path[:, 1], color=color, fill=fill,
ls=ls, lw=lw, capstyle=capstyle, joinstyle=joinstyle,
zorder=zorder)
class SegmentText(object):
''' A text drawing segment
Parameters
----------
pos : [x, y] array
Coordinates for text
label : string
Text to draw
Keyword Arguments
-----------------
align : tuple
Tuple of (horizontal, vertical) alignment where horizontal
is ['center', 'left', 'right'] and vertical is ['center',
'top', 'bottom']
rotation : float
Rotation angle (degrees)
rotation_mode : string
See Matplotlib documentation. 'anchor' or 'default'.
color : string
Color for this segment
fontsize : float
Font size
font : string
Font name/family
zorder : int
Z-order for segment
'''
def __init__(self, pos, label, **kwargs):
self.xy = pos
self.text = label
self.align = kwargs.get('align', None)
self.font = kwargs.get('font', None)
self.fontsize = kwargs.get('fontsize', None)
self.color = kwargs.get('color', None)
self.rotation = kwargs.get('rotation', None)
self.rotation_mode = kwargs.get('rotation_mode', None)
self.zorder = kwargs.get('zorder', None)
def doreverse(self, centerx):
''' Reverse the path (flip horizontal about the centerx point) '''
self.xy = mirror_point(self.xy, centerx)
def doflip(self):
''' Vertically flip the element '''
self.xy = flip_point(self.xy)
def xform(self, transform, **style):
''' Return a new Segment that has been transformed with all
styling applied
'''
params = {'align': self.align,
'font': self.font,
'fontsize': self.fontsize,
'color': self.color,
'rotation': self.rotation,
'rotation_mode': self.rotation_mode,
'zorder': self.zorder}
params.update(style)
return SegmentText(transform.transform(self.xy),
self.text, **params)
def end(self):
''' Get endpoint of this segment, untransformed '''
return self.xy
def get_bbox(self):
''' Get bounding box (untransformed)
Returns
-------
xmin, ymin, xmax, ymax
Bounding box limits
'''
# Matplotlib doesn't know text dimensions until AFTER it is drawn
return BBox(np.inf, np.inf, -np.inf, -np.inf)
def draw(self, fig, transform, **style):
''' Draw the segment
Parameters
----------
fig : schemdraw.Figure
Axis to draw on
transform : Transform
Transform to apply before drawing
'''
xy = transform.transform(self.xy)
color = self.color if self.color else style.get('color', 'black')
fontsize = self.fontsize if self.fontsize else style.get('fontsize', style.get('size', 14))
font = self.font if self.font else style.get('font', 'sans-serif')
align = self.align if self.align else style.get('align', ('center', 'center'))
rotation = self.rotation if self.rotation else style.get('rotation', 0)
rotmode = self.rotation_mode if self.rotation_mode else style.get('rotation_mode', 'anchor')
zorder = self.zorder if self.zorder is not None else style.get('zorder', 3)
fig.text(self.text, xy[0], xy[1],
color=color, fontsize=fontsize, fontfamily=font,
rotation=rotation, rotation_mode=rotmode,
halign=align[0], valign=align[1], zorder=zorder)
class SegmentPoly(object):
''' A polygon segment
Parameters
----------
xy : array-like
List of [x,y] coordinates making the polygon
Keyword Arguments
-----------------
closed : bool
Draw a closed polygon (default True)
cornerradius : float
Round the corners to this radius (0 for no rounding)
color : string
Color for this segment
lw : float
Line width for the segment
ls : string
Line style for the segment
fill : string
Color to fill if path is closed
zorder : int
Z-order for segment
'''
def __init__(self, verts, **kwargs):
self.verts = verts
self.closed = kwargs.get('closed', None)
self.cornerradius = kwargs.get('cornerradius', 0)
self.color = kwargs.get('color', None)
self.fill = kwargs.get('fill', None)
self.joinstyle = kwargs.get('joinstyle', None)
self.capstyle = kwargs.get('capstyle', None)
self.zorder = kwargs.pop('zorder', None)
self.lw = kwargs.get('lw', None)
self.ls = kwargs.get('ls', None)
def doreverse(self, centerx):
''' Reverse the path (flip horizontal about the centerx point) '''
self.verts = mirror_array(self.verts, centerx)[::-1]
def doflip(self):
''' Vertically flip the element '''
flipped = []
for p in self.verts:
flipped.append(flip_point(p))
self.verts = flipped
def xform(self, transform, **style):
''' Return a new Segment that has been transformed '''
params = {'color': self.color,
'fill': self.fill,
'joinstyle': self.joinstyle,
'capstyle': self.capstyle,
'lw': self.lw,
'ls': self.ls,
'cornerradius': self.cornerradius,
'zorder': self.zorder}
params.update(style)
return SegmentPoly(transform.transform(self.verts), **params)
def end(self):
''' Get endpoint of this segment, untransformed '''
return self.verts[-1]
def get_bbox(self):
''' Get bounding box (untransformed)
Returns
-------
xmin, ymin, xmax, ymax
Bounding box limits
'''
x = [p[0] for p in self.verts]
y = [p[1] for p in self.verts]
return BBox(min(x), min(y), max(x), max(y))
def draw(self, fig, transform, **style):
''' Draw the segment
Parameters
----------
fig : schemdraw.Figure
Axis to draw on
transform : Transform
Transform to apply before drawing
'''
closed = self.closed if self.closed is not None else style.get('closed', True)
fill = self.fill if self.fill is not None else style.get('fill', None)
color = self.color if self.color else style.get('color', 'black')
joinstyle = self.joinstyle if self.joinstyle else style.get('joinstyle', 'round')
capstyle = self.capstyle if self.capstyle else style.get('capstyle', 'round')
zorder = self.zorder if self.zorder is not None else style.get('zorder', 1)
lw = self.lw if self.lw else style.get('lw', 2)
ls = self.ls if self.ls else style.get('ls', '-')
fill = color if fill is True else None if fill is False else fill
verts = transform.transform(self.verts)
if self.cornerradius > 0:
verts = roundcorners(verts, self.cornerradius)
fig.poly(verts, closed=closed, color=color, fill=fill, lw=lw, ls=ls,
capstyle=capstyle, joinstyle=joinstyle, zorder=zorder)
class SegmentCircle(object):
''' A circle drawing segment
Parameters
----------
center : [x, y] array
Center of the circle
radius : float
Radius of the circle
Keyword Arguments
-----------------
color : string
Color for this segment
lw : float
Line width for the segment
ls : string
Line style for the segment
fill : string
Color to fill if path is closed
zorder : int
Z-order for segment
ref: string
Flip reference ['start', 'end', None].
'''
def __init__(self, center, radius, **kwargs):
self.center = np.asarray(center)
self.radius = radius
self.zorder = kwargs.pop('zorder', None)
self.color = kwargs.get('color', None)
self.fill = kwargs.get('fill', None)
self.lw = kwargs.get('lw', None)
self.ls = kwargs.get('ls', None)
# Reference for adding things AFTER lead extensions
self.endref = kwargs.get('ref', None)
def end(self):
''' Get endpoint of this segment, untransformed '''
return self.center
def doreverse(self, centerx):
''' Reverse the path (flip horizontal about the centerx point) '''
self.center = mirror_point(self.center, centerx)
self.endref = {None: None, 'start': 'end', 'end': 'start'}.get(self.endref)
def doflip(self):
''' Flip the segment up/down '''
self.center = flip_point(self.center)
def xform(self, transform, **style):
''' Return a new Segment that has been transformed '''
params = {'zorder': self.zorder,
'color': self.color,
'fill': self.fill,
'lw': self.lw,
'ls': self.ls,
'ref': self.endref}
params.update(style)
return SegmentCircle(transform.transform(self.center, self.endref),
self.radius, **params)
def get_bbox(self):
''' Get bounding box (untransformed)
Returns
-------
xmin, ymin, xmax, ymax
Bounding box limits
'''
xmin = self.center[0] - self.radius
xmax = self.center[0] + self.radius
ymin = self.center[1] - self.radius
ymax = self.center[1] + self.radius
return BBox(xmin, ymin, xmax, ymax)
def draw(self, fig, transform, **style):
''' Draw the segment
Parameters
----------
fig : schemdraw.Figure
Axis to draw on
transform : Transform
Transform to apply before drawing
'''
center = transform.transform(self.center, self.endref)
radius = transform.zoom * self.radius
zorder = self.zorder if self.zorder is not None else style.get('zorder', 1)
color = self.color if self.color else style.get('color', 'black')
fill = self.fill if self.fill is not None else style.get('fill', None)
ls = self.ls if self.ls else style.get('ls', '-')
lw = self.lw if self.lw else style.get('lw', 2)
fill = color if fill is True else None if fill is False else fill
fig.circle(center, radius, color=color, fill=fill,
lw=lw, ls=ls, zorder=zorder)
class SegmentArrow(object):
''' An arrow drawing segment
Parameters
----------
start : [x, y] array
Start coordinate of arrow
end : [x, y] array
End (head) coordinate of arrow
Keyword Arguments
-----------------
headwidth : float
Width of arrowhead
headlength : float
Lenght of arrowhead
color : string
Color for this segment
lw : float
Line width for the segment
ls : string
Line style for the segment
zorder : int
Z-order for segment
'''
def __init__(self, tail, head, **kwargs):
self.tail = tail
self.head = head
self.zorder = kwargs.pop('zorder', None)
self.headwidth = kwargs.get('headwidth', None)
self.headlength = kwargs.get('headlength', None)
self.color = kwargs.get('color', None)
self.lw = kwargs.get('lw', None)
self.ls = kwargs.get('ls', None)
self.endref = kwargs.get('ref', None)
def doreverse(self, centerx):
''' Reverse the path (flip horizontal about the centerx point) '''
self.tail = mirror_point(self.tail, centerx)
self.head = mirror_point(self.head, centerx)
self.endref = {None: None, 'start': 'end', 'end': 'start'}.get(self.endref)
def doflip(self):
self.tail = flip_point(self.tail)
self.head = flip_point(self.head)
def xform(self, transform, **style):
''' Return a new Segment that has been transformed '''
params = {'zorder': self.zorder,
'color': self.color,
'ls': self.ls,
'lw': self.lw,
'headwidth': self.headwidth,
'headlength': self.headlength,
'ref': self.endref}
params.update(style)
return SegmentArrow(transform.transform(self.tail, ref=self.endref),
transform.transform(self.head, ref=self.endref),
**params)
def get_bbox(self):
''' Get bounding box (untransformed)
Returns
-------
xmin, ymin, xmax, ymax
Bounding box limits
'''
hw = self.headwidth if self.headwidth else .1
xmin = min(self.tail[0], self.head[0])
ymin = min(self.tail[1], self.head[1])
xmax = max(self.tail[0], self.head[0])
ymax = max(self.tail[1], self.head[1])
return BBox(xmin, ymin, xmax, ymax)
def end(self):
''' Get endpoint of this segment, untransformed '''
return self.head
def draw(self, fig, transform, **style):
''' Draw the segment
Parameters
----------
fig : schemdraw.Figure
Axis to draw on
transform : Transform
Transform to apply before drawing
'''
tail = transform.transform(self.tail, ref=self.endref)
head = transform.transform(self.head, ref=self.endref)
zorder = self.zorder if self.zorder is not None else style.get('zorder', 1)
color = self.color if self.color else style.get('color', 'black')
ls = self.ls if self.ls else style.get('ls', '-')
lw = self.lw if self.lw else style.get('lw', 2)
headwidth = self.headwidth if self.headwidth else style.get('headwidth', .2)
headlength = self.headlength if self.headlength else style.get('headlength', .2)
fig.arrow(tail[0], tail[1], head[0]-tail[0], head[1]-tail[1],
headwidth=headwidth, headlength=headlength,
color=color, lw=lw, zorder=zorder)
class SegmentArc(object):
''' An arc drawing segment
Parameters
----------
center : [x, y] array
Center of the circle
width : float
Width of the arc ellipse
height : float
Height of the arc ellipse
reverse : bool
Element has been reversed
Keyword Arguments
-----------------
theta1 : float
Starting angle (degrees)
theta2 : float
Ending angle (degrees)
angle : float
Rotation of the ellipse defining the arc
arrow : [None, 'cw', 'ccw']
Direction of arrowhead
color : string
Color for this segment
lw : float
Line width for the segment
ls : string
Line style for the segment
fill : string
Color to fill if path is closed
zorder : int
Z-order for segment
'''
def __init__(self, center, width, height, **kwargs):
self.center = center
self.width = width
self.height = height
self.theta1 = kwargs.get('theta1', 35)
self.theta2 = kwargs.get('theta2', -35)
self.arrow = kwargs.get('arrow', None) # cw or ccw
self.angle = kwargs.get('angle', 0)
self.color = kwargs.get('color', None)
self.lw = kwargs.get('lw', None)
self.ls = kwargs.get('ls', None)
self.zorder = kwargs.get('zorder', None)
def doreverse(self, centerx):
''' Reverse the path (flip horizontal about the centerx point) '''
self.center = mirror_point(self.center, centerx)
self.theta1, self.theta2 = 180-self.theta2, 180-self.theta1
self.arrow = {'cw': 'ccw', 'ccw': 'cw'}.get(self.arrow, None)
def doflip(self):
''' Vertically flip the element '''
self.center = flip_point(self.center)
self.theta1, self.theta2 = -self.theta2, -self.theta1
self.arrow = {'cw': 'ccw', 'ccw': 'cw'}.get(self.arrow, None)
def xform(self, transform, **style):
''' Return a new Segment that has been transformed '''
angle = self.angle + transform.theta
params = {'color': self.color,
'lw': self.lw,
'ls': self.ls,
'zorder': self.zorder}
params.update(style)
return SegmentArc(transform.transform(self.center),
self.width, self.height, angle=angle,
theta1=self.theta1, theta2=self.theta2, **params)
def end(self):
''' Get endpoint of this segment, untransformed '''
return self.center
def get_bbox(self):
''' Get bounding box (untransformed)
Returns
-------
xmin, ymin, xmax, ymax
Bounding box limits
'''
# Who wants to do trigonometry when we can just brute-force the bounding box?
theta1, theta2 = self.theta1, self.theta2
while theta2 < theta1:
theta2 += 360
t = np.deg2rad(np.linspace(theta1, theta2, num=500))
phi = np.deg2rad(self.angle)
rx = self.width/2
ry = self.height/2
xx = self.center[0] + rx * np.cos(t)*np.cos(phi) - ry * np.sin(t)*np.sin(phi)
yy = self.center[1] + rx * np.cos(t)*np.sin(phi) + ry * np.sin(t)*np.cos(phi)
return BBox(xx.min(), yy.min(), xx.max(), yy.max())
def draw(self, fig, transform, **style):
''' Draw the segment
Parameters
----------
fig : schemdraw.Figure
Axis to draw on
transform : Transform
Transform to apply before drawing
'''
center = transform.transform(self.center)
angle = self.angle + transform.theta
zorder = self.zorder if self.zorder is not None else style.get('zorder', 1)
color = self.color if self.color else style.get('color', 'black')
ls = self.ls if self.ls else style.get('ls', '-')
lw = self.lw if self.lw else style.get('lw', 2)
fig.arc(center, width=self.width, height=self.height,
theta1=self.theta1, theta2=self.theta2, angle=angle,
color=color, lw=lw, ls=ls, zorder=zorder, arrow=self.arrow)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 17 23:04:59 2018
@author: hyq92
"""
import pandas as pd
import numpy as np
# sklearn preprocessing for dealing with categorical variables
from sklearn.preprocessing import LabelEncoder
# import lifelines
application_train = pd.read_csv("application_train.csv", header=0)
application_test = pd.read_csv("application_test.csv", header=0)
list(application_train)
application_train.ix[1:5, 0:2]
##################### EDA #####################
# out of 307511, 282686 repaid & 24825 had payment difficulties
application_train["TARGET"].value_counts()
############## Label Encoding and One-Hot Encoding ##############
# Create a label encoder object
le = LabelEncoder()
le_count = 0
# Iterate through the columns
for col in application_train:
if application_train[col].dtype == 'object':
# If 2 or fewer unique categories
if len(list(application_train[col].unique())) <= 2:
# Train on the training data
le.fit(application_train[col])
# Transform both training and testing data
application_train[col] = le.transform(application_train[col])
application_test[col] = le.transform(application_test[col])
# Keep track of how many columns were label encoded
le_count += 1
print('%d columns were label encoded.' % le_count)
# one-hot encoding of categorical variables
application_train = pd.get_dummies(application_train)
application_test = pd.get_dummies(application_test)
print('Training Features shape: ', application_train.shape)
print('Testing Features shape: ', application_test.shape)
################ Aligning Training and Testing Data ################
# One-hot encoding has created more columns in the training data because there were
# some categorical variables with categories not represented in the testing data.
# To remove the columns in the training data that are not in the testing data,
# we need to align the dataframes. First we extract the target column from the training
# data (because this is not in the testing data but we need to keep this information).
# When we do the align, we must make sure to set axis = 1 to align the dataframes based
# on the columns and not on the rows!
train_labels = application_train['TARGET']
# Align the training and testing data, keep only columns present in both dataframes
application_train, application_test = application_train.align(application_test, join = 'inner', axis = 1)
print('Training Features shape: ', application_train.shape)
print('Testing Features shape: ', application_test.shape)
############ Back to EDA ############
# Age information into a separate dataframe
age_data = application_train[["TARGET", "DAYS_BIRTH"]]
age_data['YEARS_BIRTH'] = age_data['DAYS_BIRTH'] / 365
# Bin the age data
age_data['YEARS_BINNED'] = pd.cut(age_data['YEARS_BIRTH'], bins = np.linspace(20, 70, num = 11))
age_data.head(10)
################ Analysis ###############
from sklearn.model_selection import KFold
from sklearn.metrics import roc_auc_score
from lightgbm import LGBMClassifier
import gc
# Format the training and testing data
train = np.array(application_train)
# train = np.array(application_train.drop('TARGET', axis=1))
test = np.array(application_test)
train_labels = application_train['TARGET']
train_labels = np.array(train_labels).reshape((-1, ))
# 10 fold cross validation
folds = KFold(n_splits=5, shuffle=True, random_state=50)
# Validation and test predictions
valid_preds = np.zeros(train.shape[0])
test_preds = np.zeros(test.shape[0])
# Iterate through each fold
for n_fold, (train_indices, valid_indices) in enumerate(folds.split(train)):
# Training data for the fold
train_fold, train_fold_labels = train[train_indices, :], train_labels[train_indices]
# Validation data for the fold
valid_fold, valid_fold_labels = train[valid_indices, :], train_labels[valid_indices]
# LightGBM classifier with hyperparameters
clf = LGBMClassifier(
n_estimators=10000,
learning_rate=0.1,
subsample=.8,
max_depth=7,
reg_alpha=.1,
reg_lambda=.1,
min_split_gain=.01,
min_child_weight=2
)
# Fit on the training data, evaluate on the validation data
clf.fit(train_fold, train_fold_labels,
eval_set= [(train_fold, train_fold_labels), (valid_fold, valid_fold_labels)],
eval_metric='auc', early_stopping_rounds=100, verbose = False
)
# Validation preditions
valid_preds[valid_indices] = clf.predict_proba(valid_fold, num_iteration=clf.best_iteration_)[:, 1]
# Testing predictions
test_preds += clf.predict_proba(test, num_iteration=clf.best_iteration_)[:, 1] / folds.n_splits
# Display the performance for the current fold
print('Fold %d AUC : %0.6f' % (n_fold + 1, roc_auc_score(valid_fold_labels, valid_preds[valid_indices])))
# Delete variables to free up memory
del clf, train_fold, train_fold_labels, valid_fold, valid_fold_labels
gc.collect()
# Make a submission dataframe
submission = application_test[['SK_ID_CURR']]
submission['TARGET'] = test_preds
# Save the submission file
submission.to_csv("light_gbm_baseline.csv", index=False) |
""" Put together the "outbreak" aspect of Python """
from citiesandcolors2 import *
import sys
import time
Outbreaks = 0
from Tkinter import *
# Which city we are current updating
from citiesandcolors2 import *
from citylocs import CityLocs
from time import sleep
# A place to remember all the IDs of the canvas objects
CubeIds = { }
CubeTextIds = { }
for city in Cities :
CubeTextIds[city] = {'red':None, 'blue':None, 'black':None, 'yellow':None }
CubeIds[city] = {'red':None, 'blue':None, 'black':None, 'yellow':None }
def space_to_draw_cube(city, color) :
""" FInd the x,y of the city, then find where I would draw a cube of
the appropriate color"""
(x,y) = CityLocs[city]
ColorOffsets = {'red':(0,0),'blue': (15,0),'black':(0,15),'yellow':(15,15)}
return (x + ColorOffsets[color][0], y + ColorOffsets[color][1])
def draw_cube_on_board(can, city, color) :
""" If there is no cube of that color on the city"""
(nx, ny) = space_to_draw_cube(city, color)
# print nx, ny, city, color
size = 15
# Draw all disease cubes tokens, saving the ids in the list
if CubeIds[city][color] == None :
# draw the appropriate color square with the a number in there
id = can.create_rectangle(nx, ny, nx+size, ny+size, fill=color)
CubeIds[city][color] = id
# create a text thingee to print there
fill_color = 'white'
if color=='yellow' : fill_color = 'black'
text_id = can.create_text(nx, ny, text="7777777", font="monospace-6",
fill=fill_color, anchor = NW)
CubeTextIds[city][color] = text_id
# Assertion: the color background is there, and a text thingee is installed
# Just output the number
text_id = CubeTextIds[city][color]
can.itemconfigure(text_id, text=str(CubesOnBoard[city][color]))
def undraw_cube_on_board(can, city, color) :
"""Undraw the cube and color """
id = CubeIds[city][color]
CubeIds[city][color] = None
can.delete(id)
text_id = CubeTextIds[city][color]
CubeTextIds[city][color] = None
can.delete(text_id)
def add_cube_to_city(can, city, color=None) :
"""Attempt to add a cube of the given color (if the color is None,
it uses the cube color of the given city) to the given city. If the
given city already has three cubes, this returns the string "outbreak"
indicating we couldn't add the cube to the given city because there
was an outbreak. If the cube was successfully added, then this
returns the string "success" indicating we successfully moved a cube
from off board onto the city. It's also possible, when trying to
take a cube from off the board, that we run out. In that case, we
should return the string "nocubes". We assume that color and city
are legal.
"""
# Get color
if color==None : color = get_card_color(city)
if CubesOffBoard[color] == 0 :
print '*** No more cubes of',color,":aborting ... "
print "PLAYERS LOSE!"
sys.exit(1)
return 'nocubes'
elif CubesOnBoard[city][color] == 3 :
print "*** Outbreak!"
return "outbreak"
else :
print '...moving',color,'cube to',city
CubesOffBoard[color] -= 1
CubesOnBoard[city][color] += 1
if can : draw_cube_on_board(can, city, color)
return 'success'
def remove_cube_from_city(can, city, color=None) :
# Get color
if color==None : color = get_color(city)
if CubesOnBoard[city][color] == 0 :
print '*** No more cubes of',color,'on',city,':aborting'
return 'nocubes'
else :
print '...moving',color,'cube offboard'
CubesOffBoard[color] += 1
CubesOnBoard[city][color] -= 1
# Either update or undraw
if CubesOnBoard[city][color] == 0 :
if can != None :
undraw_cube_on_board(can, city, color)
else :
if can != None :
draw_cube_on_board(can, city, color)
return 'success'
def outbreak (can, current_city, color) :
"""The given city has outbroken. We perform the outbreak, infecting
cities around us (potentially again and again). Once a city has had an
outbreak, then the city will not outbreak again this turn. If we run
out of cubes, we return False indicating the game is over. Otherwise
we return True after having performed multiple outbreaks.
"""
global Outbreaks
Outbreaks += 1
# Initialize the work queues: there are cities to infect. Once a
# city has had an outbreak, you don't reinfect it, so we need to keep
# track of all cities that HAVE ALREADY outbroken so they won't
# outbreak again.
# To start, the current city was just about to outbreak (that's what
# started the process!). All of its neighbors need to be infected!
cities_to_infect = list(AdjacentCities[current_city])
cities_already_outbroken = [current_city]
print 'cities_to_infect', cities_to_infect
print 'cities_broke', cities_already_outbroken
# Note that this is color cube that gets tossed around:
# During a particular instance of an outbreak ONLY THIS COLOR
# cube is moving on the board.
# Continue until all need cities have been infected
while len(cities_to_infect) != 0 :
# Get a city and infect it:
city_to_infect = cities_to_infect.pop()
print 'city to infect', city_to_infect
status = add_cube_to_city(can, city_to_infect, color)
if status == "outbreak" :
# Watch the number of them!
Outbreaks += 1
if Outbreaks ==8 :
print 'Too many outbreaks .. . Players Lose!'
sys.exit(1)
# If there's an outbreak, all adjacent cities
# THAT HAVE NOT HAD an outbreak, get scheduled for a cube
adjacent_cities = list(AdjacentCities[city_to_infect])
for city in adjacent_cities :
if city not in cities_already_outbroken :
cities_to_infect.append(city)
cities_already_outbroken.append(city_to_infect)
elif status == "nocubes" :
return False
elif status == "success" :
# Cube was added, everything okay, no further things to do
pass
else :
print "Unknown return code?"
sys.exit(1)
# Successfully outbroke without game ending
return True
LocationsId = { }
def initialize_player_token(can, player, color) :
x0, y0 = CityLocs["atlanta"]
x = x0-5+player*10
y = y0-5
LocationsId[player] = can.create_oval(x,y,x+10, y+10, fill=color)
def move_player_token(Locations, can, player, to_city) :
"""Move player token from city to another"""
from_city = Locations[player]
player_id = LocationsId[player]
x0,y0 = CityLocs[to_city]
x = x0-5+player*10
y = y0-5
can.coords(player_id, x,y, x+10, y+10)
Locations[player] = to_city
can.update()
class GPlayerDeck(object) :
def __init__(self, player, root, initial_cards) :
self.cards = initial_cards
self.root = root
self.player = player
self.top = Toplevel(root)
self.top.title = "Player "+str(player)
self.cards = []
self.buttons = []
self.extend(initial_cards)
def pop(self, which=-1) :
"""Remove the top card and return it"""
card = self.cards.pop(which)
button = self.button.pop(which)
button.destroy()
return card
def append(self, card) :
"""Plop a card on top of the deck"""
self.cards.append(card)
color = get_card_color(card)
if color==None : color = "orange"
text_color = "white"
if color=="yellow" : text_color = "black"
button = Button(self.top, text=card, bg=color, foreground=text_color)
button.pack()
self.buttons.append(button)
def remove(self, card) :
"""Remove a particular card from the deck."""
where = self.cards.index(card)
self.cards.pop(where)
button = self.buttons[where]
self.buttons.pop(where)
button.destroy()
def extend(self, cards) :
"""Add a bunch of cards in"""
for x in cards :
self.cards.append(x)
color = get_card_color(x)
if color==None : color = "orange"
text_color = "white"
if color=="yellow" : text_color = "black"
button = Button(self.top, text=x, bg=color, fg=text_color)
button.pack()
self.buttons.append(button)
def __str__(self) :
""" stringize just the list"""
return str(self.cards)
def __len__(self) :
return len(self.cards)
def __contains__(self, item) :
return item in self.cards
if __name__=="__main__" :
# 3 blue on Atlanta
for x in range(3) :
add_cube_to_city("atlanta", "blue")
# 2 blue on Chicago
for x in range(2) :
add_cube_to_city("chicago", "blue")
# 2 yellow cubes on Miami
for x in range(2) :
add_cube_to_city("chicago", "yellow")
print outbreak("atlanta", "blue")
time.sleep(1)
print outbreak("atlanta", "blue")
time.sleep(1)
print outbreak("atlanta", "blue")
time.sleep(1)
print outbreak("atlanta", "blue")
time.sleep(1)
|
from stack import Stack
def DecToBin(num):
'''This function converts an integer in base 10 to an integer in base 2 or say its binary value'''
stk=Stack()
while(num!=0):
stk.push(num%2)
num=num//2
s=""
while(not stk.isEmpty()):
s+=str(stk.pop())
return s
if __name__=="__main__":
decimal_val=int(input())
binary_val=DecToBin(decimal_val)
print(f"Binary value of {decimal_val} is {binary_val}")
|
'''This module contains the function to reverse a string'''
def reverseString(original_string):
'''This method takes a string and reverses and returns it'''
if len(original_string)<2:
return original_string
else:
return reverseString(original_string[1:])+original_string[0]
if __name__=="__main__":
string=input()
reversed_string=reverseString(string)
print(f"The reverse of {string} is {reversed_string}") |
class Queue:
def __init__(self):
self.items=[]
def enqueue(self,data):
self.items.insert(0,data)
def dequeue(self):
if self.items!=[]:
return self.items.pop()
else:
return None
def size(self):
return len(self.items)
def isEmpty(self):
return self.items==[]
if __name__=="__main__":
queue=Queue()
print(queue.isEmpty())
print(queue.size())
queue.enqueue(1)
queue.enqueue(2)
print(queue.isEmpty())
queue.enqueue(3)
print(queue.size())
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue()) |
"""This module contains the code to implement a breadth first search algorithm on a graph"""
import collections
def bfs(graph,start_vertex):
"""This function is used to run breadth first search on a graph"""
visited,queue=[start_vertex],collections.deque([start_vertex])
while queue:
current_vertex=queue.popleft()
marked(current_vertex)
for vertex in graph[current_vertex]:
if vertex not in visited:
visited.append(vertex)
queue.append(vertex)
def marked(vertex):
"""This function marks a vertex to be visited by printing it"""
print(vertex)
if __name__=="__main__":
gdict = { "a" : set(["b","c"]),
"b" : set(["a", "d"]),
"c" : set(["a", "d"]),
"d" : set(["e"]),
"e" : set(["a"])
}
bfs(gdict,"a")
|
'''This is the implementation of LinkedList only but according to what I studied
on Runestone academy. Here the Linked List items do not follow an arrangement,hence it is
Unordered'''
class Node:
def __init__(self,data):
self.data=data
self.next=None
def getData(self):
return self.data
def setData(self,data):
self.data=data
def getNext(self):
return self.next
def setNext(self,next):
self.next=next
class UnorderedList:
def __init__(self):
self.head=None
def isEmpty(self):
return self.head==None
def add(self,new_data):
new_node=Node(new_data)
if self.head==None:
new_node.setNext(None)
self.head=new_node
else:
new_node.setNext(self.head)
self.head=new_node
def size(self):
if self.head==None:
return 0
else:
temp=self.head
count=0
while(temp!=None):
temp=temp.next
count+=1
return count
def search(self,item):
if self.head==None:
return False
else:
temp=self.head
found=False
while(temp!=None and not found):
if temp.getData()==item:
found=True
break
temp=temp.getNext()
return found
def remove(self,item):
if self.head==None:
print("Unordered list empty")
else:
temp=self.head
previous=None
found=False
while(not found):
if temp.getData()==item:
found=True
else:
previous=temp
temp=temp.next
if previous==None:
self.head=temp.getNext()
else:
previous.setNext(temp.getNext())
def index(self,item):
if self.head==None:
print("Unordered list empty")
else:
temp=self.head
found=False
index=0
while(found==False and temp!=None):
if temp.getData()==item:
found=True
else:
temp=temp.getNext()
index+=1
if found==True:
return index
else:
return -1
if __name__=="__main__":
node_list=UnorderedList()
print(node_list.isEmpty())
print(node_list.size())
print(node_list.search(1))
node_list.add(4)
node_list.add(3)
node_list.add(2)
node_list.add(1)
print(node_list.index(2))
print(node_list.isEmpty())
print(node_list.size())
print(node_list.search(1))
node_list.remove(1)
|
from stack import Stack
def doMath(first,second,operator):
if operator=='+':
return first+second
elif operator=='-':
return first-second
elif operator=='*':
return first*second
elif operator=='/':
return first/second
else:
return first%second
def evaluatePostfix(postfix_string):
opstack=Stack()
print(postfix_string)
for token in postfix_string:
if token in "0123456789":
opstack.push(int(token))
else:
second_operand=opstack.pop()
first_operand=opstack.pop()
op_result=doMath(first_operand,second_operand,token)
opstack.push(op_result)
return opstack.pop()
if __name__=="__main__":
postix_expression=input()
result=evaluatePostfix(postix_expression)
print(f"The result of postfix expression {postix_expression} is {result}")
|
class Solution:
def reverseString(self, s: list[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if s == []:
return
def helper(start,end,s):
if start > end:
return
helper(start+1,end-1,s)
s[start] ,s[end] = s[end],s[start]
helper(0,len(s)-1,s) |
'''
第8节 链表指定值清除练习题
现在有一个单链表。链表中每个节点保存一个整数,再给定一个值val,把所有等于val的节点删掉。
给定一个单链表的头结点head,同时给定一个值val,请返回清除后的链表的头结点,
保证链表中有不等于该值的其它值。请保证其他元素的相对顺序。
测试样例:
{1,2,3,4,3,2,1},2
{1,3,4,3,1}
'''
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class ClearValue:
def clear(self, head, val):
# write code here
headNode = ListNode(0)
headNode.next = head
pre = headNode
while head:
if head.val == val:
pre.next = head.next
else:
pre = pre.next
head = head.next
return headNode.next |
'''
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
'''
class Solution:
def maxSubArray(self, nums: list[int]) -> int:
# 以num[i]结尾的最大子串和,一开始方法是对的,状态转移写错了
dp = nums
for i in range(1,len(nums)):
if dp[i-1]+ nums[i] > nums[i]:
dp[i] = dp[i-1]+nums[i]
else:
dp[i] = nums[i]
return max(dp)
'''
动态规划的是首先对数组进行遍历,当前最大连续子序列和为 sum,结果为 ans
如果 sum > 0,则说明 sum 对结果有增益效果,则 sum 保留并加上当前遍历数字
如果 sum <= 0,则说明 sum 对结果无增益效果,需要舍弃,则 sum 直接更新为当前遍历数字
每次比较 sum 和 ans的大小,将最大值置为ans,遍历结束返回结果
时间复杂度:O(n)O(n)
'''
class Solutionx1:
def maxSubArray(self, nums: list[int]) -> int:
# 参考之后: 考察的不是 num对最终的增益了,而是前置子串和对当前num的增益,如果前置对当前有增益
# 则留用,如果没增益不如以当前num为首,开始新的子串。
# 思路,动态规划? 这个方法有问题,不是连续子串,改进一下(如果变小了,就归0)
maxscore = nums[0]
sum = 0
for i in range(len(nums)) :
if sum > 0:
sum += nums[i]
else:
# 前置的置零
sum = nums[i]
maxscore = max(maxscore,sum)
return maxscore
|
'''
题目描述:计算让一组区间不重叠所需要移除的区间个数。
先计算最多能组成的不重叠区间个数,然后用区间总个数减去不重叠区间的个数。
在每次选择中,区间的结尾最为重要,选择的区间结尾越小,留给后面的区间的空间越大,那么后面能够选择的区间个数也就越大。
Input: [ [1,2], [1,2], [1,2] ]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Input: [ [1,2], [2,3] ]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
'''
class Solution:
def eraseOverlapingIntervals(self,intervals):
if len(intervals) == 0: return 0
# 按照区间 尾数排序,小的考前,尽可能给后面留下更多的
b= sorted(intervals,key=lambda x:x[-1])
# 遍历去除不重复的区间
cnt = 1
end = b[0][-1]
for i in b[1:]:
if i[0] < end:
continue
else:
end = i[-1]
cnt += 1
return len(intervals)-cnt
a = Solution()
out = a.eraseOverlapingIntervals( [ [1,2], [1,2], [1,2] ])
print(out)
|
'''
有一棵二叉树,其中所有节点的值都不一样,找到含有节点最多 的搜索二叉子树,并返回这棵子树的头节点.
给定二叉树的头结点root,请返回所求的头结点,若出现多个节点最多的子树,返回头结点权值最大的。
'''
'''
基本情况分析:
1. 以Node节点为头,整棵树是最大搜索二叉树:
左子树:以Node左孩子为头,最大搜索二叉树的最大值小于Node的节点值
右子树:以Node右孩子为头,最大搜索二叉树的最小值大于Node的节点值
2. 不满足上述: 以Node为头整体不能连成搜索二叉树,此时最大搜索二叉树 = 两侧子树的最大搜索二叉树里 节点数较多的
'''
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class MaxSubtree:
def getMax(self, root):
# write code here
node, count, max, min = self.printout(root)
return node
def printout(self, root):
if root == None:
return None, 0, None, None
else:
Rnode, Rcount, Rmax, Rmin = self.printout(root.right)
Lnode, Lcount, Lmax, Lmin = self.printout(root.left)
if Lnode == None and Rnode == None:
return root, 1, root.val, root.val
elif Lnode == None and Rnode != None:
if root.val < Rmin and Rnode == root.right:
return root, Rcount + 1, Rmax, root.val
else:
return Rnode, Rcount, Rmax, Rmin
elif Lnode != None and Rnode == None:
if root.val > Lmax and Lnode == root.left:
return root, Lcount + 1, root.val, Lmin
else:
return Lnode, Lcount, Lmax, Lmin
else:
if Lmax < root.val and root.val < Rmin and Lnode == root.left and Rnode == root.right:
return root, Lcount + Rcount + 1, Rmax, Lmin
elif Lcount > Rcount:
return Lnode, Lcount, Lmax, Lmin
elif Lcount < Rcount:
return Rnode, Rcount, Rmax, Rmin
else:
if Lnode.val >= Rnode.val:
return Lnode, Lcount, Lmax, Lmin
else:
return Rnode, Rcount, Rmax, Rmin |
'''
链表的快速排序实现 ,空间复杂度是O(1)
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def quickSortList(self,head):
if head is None or head.next is None:
return head
tmpHead = ListNode(0)
tmpHead.next =head
self.qsortList(tmpHead,head,None)
return tmpHead.next
def qsortList(self,headPre,head,tail):
if head!= tail and head.next !=tail:
mid = self.partitionList(headPre,head,tail) # 这里Head不能指向链表表头
self.qsortList(headPre,headPre.next,mid)
self.qsortList(mid,mid.next,tail)
def partitionList(self,lowPre,low,hight):
key = low.val
node1 ,node2 = ListNode(0),ListNode(0)
little = node1
big = node2
tmp = low.next
while tmp!=hight:
if tmp.val <key:
little.next = tmp
little =tmp
else:
big.next = tmp
big = tmp
tmp=tmp.next
big.next=hight # 保证后半部分
little.next=low
low.next =node2.next
lowPre.next = node1.next # 保证前半部分
return low
|
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# __all__ = ['栈(顺序表)',
# '栈(链接表)',
# '队列']
# 栈(顺序表)
class SStack:
def __init__(self):
self._elems = []
def is_empty(self):
return self._elems == []
def top(self):
if self._elems == []:
raise Exception('Empty!')
return self._elems[-1]
def push(self, elem):
self._elems.append(elem)
def pop(self):
if self._elems == []:
raise Exception('Empty!')
return self._elems.pop()
class LNode:
def __init__(self, elem, next_=None):
self.elem = elem
self.next = next_
# 栈(链接表)
class LStack:
def __init__(self):
self._top = None
def is_empty(self):
return self._top is None
def top(self):
if self._top is None:
raise Exception('Empty!')
return self._top.elem
def push(self, elem):
self._top = LNode(elem, self._top)
def pop(self):
if self._top is None:
raise Exception('Empty!')
p = self._top
self._top = p.next
return p.elem
# 队列
class SQueue:
def __init__(self, init_len=8):
self._len = init_len
self._elems = [0] * init_len
self._head = 0
self._num = 0
def is_empty(self):
return self._num == 0
def peek(self):
if self._num == 0:
raise Exception('Empty!')
return self._elems[self._head]
def dequeue(self):
if self._num == 0:
raise Exception('Empty!')
e = self._elems[self._head]
self._head = (self._head + 1) % self._len
self._num -= 1
return e
def enqueue(self, e):
if self._num == self._len:
self.__extend()
self._elems[(self._head + self._num) % self._len] = e
self._num += 1
def __extend(self):
old_len = self._len
self._len *= 2
new_elems = [0] * self._len
for i in range(old_len):
new_elems[i] = self._elems[(self._head + i) % old_len]
self._elems, self._head = new_elems, 0
|
'''
求a/b的小数表现形式。如果a可以整除b则不需要小数点。
如果是有限小数,则可以直接输出。如果是无限循环小数,则需要把小数循环的部分用"()"括起来。
两个整数a和b,其中
0 <= a <= 1000 000
1 <= b <= 10 000
'''
class Solution:
def demicalString(self):
a,b = [int(i) for i in input().split()]
if a%b==0:
print(a//b)
else:
cache=[]
decimal = ''
print(a//b,end='.')
a = a%b
while True:
if a in cache:
p = cache.index(a)
finite =True
break
cache.append(a)
a=a*10
decimal=decimal+'{}'.format(a//b)
a=a%b
if a == 0:
finite =False
break
if finite:
print('{0}({1})'.format(decimal[:p] , decimal[p:]))
else:
print(decimal)
a=Solution()
a.demicalString() |
'''
输出所有和为 S 的连续正数序列。
例如和为 100 的连续序列有:
[9, 10, 11, 12, 13, 14, 15, 16]
[18, 19, 20, 21, 22]。
双指针思路
//左神的思路,双指针问题
//当总和小于sum,大指针继续+
//否则小指针+
'''
class Solution1:
def FindContinuousSequence(self, tsum):
phigh ,plow =2,1
allres= []
while phigh > plow:
cur = (phigh+plow)*(phigh-plow+1)/2
if cur < tsum:
phigh+=1
if cur == tsum:
res = []
for i in range(plow,phigh):
res.append(i)
allres.append(res)
plow+=1
if cur> tsum:
plow+=1
return allres
# -*- coding:utf-8 -*-
class Solution1:
def FindContinuousSequence(self, tsum):
if tsum < 3:
return []
small = 1
big = 2
middle = (tsum + 1)>>1
curSum = small + big
output = []
while small < middle:
if curSum == tsum:
output.append(range(small, big+1))
big += 1
curSum += big
elif curSum > tsum:
curSum -= small
small += 1
else:
big += 1
curSum += big
return output
# 粗暴方法,两次遍历,第一次遍历半组数据,因为当大于其中一半的时候,两个数相加就大于和了
# 第二次遍历,就是从第一次遍历的位置,向后递增,用正序列求和公式求和,符合加入结果,大于退出循环
# -*- coding:utf-8 -*-
class Solution2:
def FindContinuousSequence(self, tsum):
# write code here
res = []
for i in range(1, tsum / 2 + 1):
for j in range(i, tsum / 2 + 2):
tmp = (j + i) * (j - i + 1) / 2 # 求和公式
if tmp > tsum:
break
elif tmp == tsum:
res.append(range(i, j + 1))
return res
'''
其他思路
1)由于我们要找的是和为S的连续正数序列,因此这个序列是个公差为1的等差数列,而这个序列的中间值代表了平均值的大小。假设序列长度为n,那么这个序列的中间值可以通过(S / n)得到,知道序列的中间值和长度,也就不难求出这段序列了。
2)满足条件的n分两种情况:
n为奇数时,序列中间的数正好是序列的平均值,所以条件为:(n & 1) == 1 && sum % n == 0;
n为偶数时,序列中间两个数的平均值是序列的平均值,而这个平均值的小数部分为0.5,所以条件为:(sum % n) * 2 == n.
3)由题可知n >= 2,那么n的最大值是多少呢?我们完全可以将n从2到S全部遍历一次,但是大部分遍历是不必要的。为了让n尽可能大,我们让序列从1开始,
''' |
class ChkLoop:
def chkLoop(self, head, adjust):
# write code here
if head is None or head.next is None:
return False
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next if fast.next else None
slow = slow.next
# 第一次判定是 确定有环
if fast == slow:
return True
return False
if __name__ == '__main__':
# 根据题意输入,依次输入每个链表节点,无需使用链表确认方法
# 直接对链表节点进行检测
import sys
link = sys.stdin.readline().strip().split(',')
if len(link)-len(set(link)):
print(False)
else:
print(True) |
# -*- coding:utf-8 -*-
import random;
class Random5:
@staticmethod
def randomNumber():
return random.randint(0, 1000000) % 5 + 1
class Random7:
# 随机产生[1,5]
def rand5(self):
return Random5.randomNumber()
# 请通过self.rand5()随机产生[1,7]
def randomNumber(self):
# return self.rand5() % 7
a = (self.rand5() - 1) * 5 + self.rand5()
while a > 21:
a = (self.rand5() - 1) * 5 + self.rand5()
result = a % 7 + 1
return result
|
"""
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
"""
# -*- coding:utf-8 -*-
class Solution1:
def minNumberInRotateArray(self, rotateArray):
# write code here
if len(rotateArray)==0:
return 0
#cur_min = rotateArray[0]
for i in range(1,len(rotateArray)):
if rotateArray[i]<rotateArray[i-1]:
return rotateArray[i]
return rotateArray[0]
''' 降低时间复杂度,使用O(logN)的方法'''
class Soulution:
def minNumberInRotateArray(self,rotateArray):
length = len(rotateArray)
if length ==0:
return length
i= 0
j= length-1
while i<j:
m = i+(j-i)/2
if rotateArray[m]<= j:
j= m
else:
i= m
return rotateArray[i]
'''
nums[l] == nums[m] == nums[h]
特殊情况,如果发生这个情况,只能进行遍历,也就是之前的
'''
"""完整版 """
class MinValue:
def getMin(self, arr, n):
low = 0
high = n - 1
if arr[low] < arr[high]: # 说明有序循环数组是从小到大排序的,第一个元素是最小值,特殊情况单独讨论
return arr[low]
# arr[low] >= arr[high]
while low <= high: # 和寻找元素最左出现的位置”这部分是一样的
mid = low + (high - low) / 2
if arr[low] > arr[mid]: # 左一半
high = mid
elif arr[mid] > arr[high]: # 右一半
low = mid + 1
else: # arr[low]==arr[mid]==arr[right] 特殊情况 只能挨个遍历,之前两个if最后到了一个元素的也会到达这里进行最终的判断
cur = arr[low]
# 在这种情况下,此处的 从左到右遍历
while low < high:
if cur > arr[low + 1]:
cur = arr[low + 1]
low = low + 1
return cur |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''
链表转二叉树
'''
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def sortedListToBST(head):
"""
:type head: ListNode
:rtype: TreeNode
"""
if not head:
return
if not head.next:
return TreeNode(head.val)
slow, fast = head, head.next.next
# 找到中间位置,断开分两部分,划分两个子树,数组同思路。
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
midtree = TreeNode(mid.val)
midtree.left = sortedListToBST(head)
midtree.right = sortedListToBST(mid.next)
return midtree
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.