text stringlengths 37 1.41M |
|---|
# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
def fib_iterative(n):
if n == 1:
print(0)
return
if n == 2:
print(1)
return
a = 0
b = 1
print(a, b, end=" ")
for i in range(n - 2):
summ = a + b
a = b
b = summ
print(summ, end=" ")
# return summ
def fib_recursion(n):
if n == 1:
return 0
if n == 2:
return 1
return fib_recursion(n - 1) + fib_recursion(n - 2)
# fib_iterative(3)
print(fib_recursion(5)) # answer=3 -> 0, 1, 1, 2, 3
|
array = [88, 2, 65, 34, 2, 1, 7, 8]
array_2 = [88, 2, 65, 34, 2, 1, 7, 8]
def bubble(arr):
arr_len = len(arr)
for i in range(arr_len):
for j in range(i + 1, arr_len):
if arr[j] < arr[i]:
arr[j], arr[i] = arr[i], arr[j]
def bubble_v2(arr):
arr_len = len(arr)
for i in range(arr_len):
for j in range(arr_len - 1):
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
bubble(array)
# bubble_v2(array_2)
print(array)
|
def factorial_recursive(number):
if number == 2:
return 2
return number * factorial_recursive(number - 1)
def factorial_iterative(number):
summ = 1
while number > 1:
summ *= number
number -= 1
print(summ)
factorial_iterative(10)
print(factorial_recursive(5))
|
from cs50 import get_int
x = get_int("Enter Int: ")
y = get_int("Enter Int: ")
print(f"{x} + {y} = {x + y}")
print(f"{x} - {y} = {x - y}")
print(f"{x} * {y} = {x * y}")
print(f"Floor divided = {x // y}")
print(f"Truly divided = {x / y}")
print(f"remainder of {x} by {y} = {x % y}")
|
#######################################################
# 1.21
# 思路:把输入的值存入列表中
#######################################################
def read_line():
lines = []
while True:
try:
lines.insert(0, input("input:").strip())
except EOFError:
for i in lines:
print(i)
break
if __name__ == '__main__':
read_line()
|
import re
def polynomial_derivative(p: str):
"""Return the first derivative of the polynomial.
p a polynomial in standard algebraic notation
"""
# use `re` module, matching method as the follow:
# sign [-+]?
# factor \d*\.*\d*
# variable x?\^?
# power \d*
items = re.findall(r'[-+]?\d*\.*\d*x?\^?\d*', p.replace(' ', ''))
result_list = []
for item in items: # type: str
if not item:
continue
elif 'x' not in item: # constant
continue
elif '^' not in item: # the power is 1
result_list.append(item.replace("x", ''))
else:
factor, power = item.split('x^')
new_factor = float(factor) * int(power)
if new_factor.is_integer():
new_factor = int(new_factor)
new_power = int(power) - 1
if new_power == 1:
res = [str(new_factor), 'x']
else:
res = [str(new_factor), 'x^', str(int(power) - 1)]
result_list.append(''.join(res))
return ''.join(result_list)
if __name__ == '__main__':
p = "3.14x^4-9x^3 - 4x^2 + 1.2x + 4"
print('original polynomial:', p)
print('the first derivative of polynomial:', polynomial_derivative(p))
|
#######################################################
# 1.28
# 思路:
#######################################################
def norm(v, p=2):
return pow(sum(pow(i, p) for i in v), 1/p)
def test():
test_list = [4, 3]
print(f'p=2,v={tuple(test_list)}, ||v||={norm(test_list)}')
print(f'p=3,v={tuple(test_list)}, ||v||={norm(test_list, p=3)}')
print(f'p=4,v={tuple(test_list)}, ||v||={norm(test_list, p=4)}')
if __name__ == '__main__':
test() |
# cass inheritance diagram:
#
# object
# / \
# Book User
#
class Book(object):
"""Create a new e-book."""
def __init__(self, name, price, publisher):
"""Return a new book instance."""
self.name = name
self.price = price
self.publisher = publisher
def __str__(self):
"""print book info."""
return f"{self.name} - {self.price} - {self.publisher}"
class User(object):
def __init__(self, name, sex):
self.name = name
self.sex = sex
self.books = []
def buy(self, book: Book):
self.books.append(book)
def list_books(self):
for book in self.books:
print(book)
def read(self, book):
"""read purchased books."""
print('read books')
|
#######################################################
# 1.26
# 思路:使用内置函数eval执行字符串命令
#######################################################
def formula(a: int, b: int, c: int):
for operator in '+-*/':
expresses = [
f'{a} {operator} {b} == {c}',
f'{a} == {b} {operator} {c}'
]
for express in expresses:
if eval(express):
return express.replace("==", '=')
def test():
test_list = [
(1, 2, 3), (2, 3, 4), (6, 3, 2)
]
for a, b, c in test_list:
if formula(a, b, c):
print(f"{a, b, c} result: True, {formula(a, b, c)}")
else:
print(f"{a, b, c} result: False")
if __name__ == '__main__':
test()
|
def multiply_uniques(a,b,c):
"""
set in python always store unique value
a:3
b:2
c:3
Reult:6 becasue 3 is repated
"""
if a==b==c:
return 0
result = 1
a={a,b,c}
for i in a:
result *= i
return result
print(multiply_uniques(3,2,3))
print(multiply_uniques(3,3,3))
print(multiply_uniques(3,2,1))
print(multiply_uniques(2,2,10))
print(multiply_uniques.__doc__) |
'''
otimização por colonia de formiga aplicado ao problema de caixeiro viajante
'''
import random, math
# Classe que representa uma formiga
class formiga:
def __init__(self, cidade):
self.cidade = cidade
self.solucao = []
self.custo = None
#super().__init__()
@property
def cidade(self):
return self.cidade
@cidade.setter
def cidade(self, cidade):
self.cidade = cidade
@property
def solucao(self):
return self.solucao
@solucao.setter
def solucao(self, solucao, custo):
if not self.custo:
elf.solucao = solucao[:]
self.custo = custo
else:
if custo < self.custo:
self.custo = custo
@property
def custo(self):
return self.custo
# classe que representa uma aresta
class Aresta:
def __init__(self, origem, destino, custo):
#super().__init__()
self.origem, self.destino, self.custo, self.feromonio = origem,destino,custo,None
@property
def origem(self):
return self.origem
@property
def destino(self):
return self.destino
@property
def custo(self):
return self.custo
@property
def feromonio(self):
return self.feromonio
@feromonio.setter
def feromonio(self, feromonio):
self.feromonio = feromonio
# classe qu representa um grafo
|
a = int(input())
b = int(input())
if a > b:
print(a, " is largest")
else:
print(b, "is largest")
|
# Content from: https://www.w3schools.com/python/python_strings.asp
#Array concept
a = "Hello, World!"
print(a[0])
print(a[1])
#Slicing concepts, positive index starts from 0th position
b = "Hello, World!"
print(b[2:5])
print(b[2:6])
#Slicing concepts, negative index starts from -1 position
b = "Hello, World!"
print(b[-5:-2])
#length method, remember does not work for int / float values.
a = "Hello"
print(len(a))
#remove white spaces before / after
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
#Also recall uppper(), swapcase() methods
a = "Hello, World!"
print(a.lower())
#Replace at position...
a = "Hello, World!"
print(a.replace("H", "J"))
#split through a delimiter..
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
#String conctenation, to be careful with integer values..
a = "Hello"
b = "World"
c = a + b
print(c)
#string.format(), to watch the flower parentheses {}
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
|
import math
a=2
b=5
print(a*b)
print(a**b)
print(b**a)
print(abs(-4/3))
print(pow(2,3))
print(math.sqrt(25))
if math.sqrt(25) > math.sqrt(16) + math.sqrt(9):
print("True")
else:
print("False")
print(round(3.7))
print(round(4.2))
#others ceil floor etc.
|
def fahrenheit_to_celsius(fahrenheit):
return float(fahrenheit-32)*5/9
n = float(input())
fahrenheitTemperature = fahrenheit_to_celsius(n)
print("%.2f" %fahrenheitTemperature) |
numOne = int(input())
numTwo = int(input())
for i in range(numOne,numTwo+1):
print("{0} ".format(chr(i)),end= '') |
number = int(input())
if number >=100 and number<=200:
print()
elif number !=0:
print("invalid") |
n = int(input())
for firstLetter in range(ord('a'), ord('a') + n):
for secondLetter in range(ord('a'), ord('a') + n):
for thirdLetter in range(ord('a'), ord('a') + n):
print("{0}{1}{2}".format(chr(firstLetter),chr(secondLetter),chr(thirdLetter)))
|
import math
n = int(input())
for i in range(2,n+1):
mathSqrt = int(math.sqrt(i))
isPrime = True
for j in range(2,mathSqrt+1):
if i % j == 0:
isPrime = False
print("{0} -> {1}".format(i,isPrime))
|
n=int(input())
stars = 1
if n% 2 ==0:
stars += 1
# roof
for i in range(0,int((n+1)/2)):
padding = int((n-stars)/2)
print("-"*padding,end='')
print("*" * stars, end='')
print("-" * padding)
stars +=2
# body
for y in range(0,int(n/2)):
print("|"+"*"*(n-2)+"|") |
n = int(input())
integers = []
for i in range (0,n):
integers.append(int(input()))
# integers.reverse() or
print(integers[::-1]) |
amount = float(input())
currencyFrom = input()
currencyTo = input()
def switch(amount,currencyFrom,currencyTo):
result = 0.0
toLeva = 0.0
if currencyFrom == "BGN":
toLeva = amount
if currencyFrom == "USD":
toLeva = amount * 1.79549
if currencyFrom == "EUR":
toLeva = amount * 1.95583
if currencyFrom == "GBP":
toLeva = amount * 2.53405
if currencyTo == "BGN":
result = toLeva
if currencyTo == "USD":
result = toLeva / 1.79549
if currencyTo == "EUR":
result = toLeva /1.95583
if currencyTo == "GBP":
result = toLeva / 2.53405
return result
# print("{0:.2f} ".format(result)+currencyTo)
result = switch(amount,currencyFrom,currencyTo)
print("{0:.2f} ".format(result)+currencyTo) |
n = int(input())
# top
mid = int(n / 2)
midSize = 2 * n - 2 * mid - 4
# bottom
if n <= 4:
print("/{0}\\/{0}\\".format('^'*int(mid)))
else:
print("/{0}\\{1}/{0}\\".format('^'*int(mid),'_'*int(midSize)))
if n <= 4:
for i in range(0,n-2):
print("|{0}|".format(' '*int(n*2-2)))
print("\{0}/\{0}/".format('_'*int(mid)))
elif n>4:
for i in range(0,n-3):
print("|{0}|".format(' ' * int(2*n-2)))
print("|{0}{1}{0}|".format(' ' * int(mid+1),'_' *int(midSize)))
print("\{0}/{1}\{0}/".format('_'*int(mid),' '*int(midSize)))
|
numOne = int(input())
numTwo = int(input())
print(numOne)if numOne>numTwo else print(numTwo)
|
word = input()
sumOfChars = 0
for i in word:
if i == 'a':
sumOfChars+=1
elif i == 'e':
sumOfChars+=2
elif i == 'i':
sumOfChars+=3
elif i == 'o':
sumOfChars+=4
elif i == 'u':
sumOfChars+=5
print(sumOfChars)
|
speed = float(input())
if speed <= 10:
print("slow")
elif speed >10 and speed<=50:
print("average")
elif speed >50 and speed<=150:
print("fast")
elif speed >150 and speed<=1000:
print("ultra fast")
else:
print("extremely fast")
|
n = int(input())
factorial = 1
for i in range (1,n+1):
factorial *= i
print(factorial) |
n = int(input())
for row in range(0,n+1):
stars = "*"*row
space = " "*(n-row)
print(space ,end='')
print(stars, end='')
print(" | ",end='')
print(stars, end='')
print(space, end='')
print()
|
def iscircular(linked_list):
"""
Determine whether the Linked List is circular or not
"""
slow_runner = linked_list.head
fast_runner = linked_list.head
while fast_runner and fast_runner.next:
slow_runner = slow_runner.next
fast_runner = fast_runner.next.next
if slow_runner == fast_runner:
return True
return False
|
#!/usr/bin/env python3
# ================= 代码实现开始 =================
N = 100005
class node:
def __init__(self):
self.val = self.left = self.right = 0
t = [node() for i in range(N)]
root, cnt = 0, 0
def insert(v, x):
if x == 0:
global cnt
x = node()
x.val = v
return x
if (x.val > v):
x.left = insert(v, x.left)
else:
x.right = insert(v, x.right)
return x
def dlr(x, ans):
if x != 0:
ans.append(x.val)
dlr(x.left, ans)
dlr(x.right, ans)
def lrd(x, ans):
if x != 0:
lrd(x.left, ans)
lrd(x.right, ans)
ans.append(x.val)
# 给定一个1到n的排列,依次插入到二叉树中,返回前序遍历和后序遍历
# n:如题意
# sequence:给定的排列,大小为n
# 返回值:将要输出的元素依次加入到返回值中
def getAnswer(n, sequence):
global root, cnt
root = cnt = 0 # init
for i in range(n):
root = insert(sequence[i], root)
ans = []
dlr(root, ans)
lrd(root, ans)
return ans
# ================= 代码实现结束 =================
n = int(input())
sequence = list(map(int, input().split(' ')))
ans = getAnswer(n, sequence)
print(' '.join(map(str, ans[0:n])))
print(' '.join(map(str, ans[n:n+n])))
|
#!/usr/bin/env python3
# ================= 代码实现开始 =================
Mod = 1000003
table = [[] for i in range(Mod)]
def Hash(x):
return x % Mod
# 执行操作时会调用这个函数
# op:对应该次操作的 op(具体请见题目描述)
# x:对应该次操作的 x(具体请见题目描述)
# 返回值:如果输出为"Succeeded",则这个函数返回 1,否则返回 0
def check(op, x):
h = Hash(x)
ptr = -1
for it in range(len(table[h])):
if table[h][it] == x:
ptr = it
break
if op == 1:
if ptr == -1:
table[h].append(x)
return 1
return 0
else: # op = 2
if ptr > -1:
table[h][ptr] = table[h][-1]
table[h].pop()
return 1
return 0
# ================= 代码实现结束 =================
Q = int(input())
for _ in range(Q):
op, x = map(int, input().split())
print("Succeeded" if check(op, x) else "Failed")
|
## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self, n_values=136): #n_classes=10):
super(Net, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
#self.conv1 = nn.Conv2d(1, 32, 5)
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
n=32
self.conv11 = nn.Conv2d(1, n, kernel_size=3, padding=1)
self.bn11 = nn.BatchNorm2d(n)
self.conv12 = nn.Conv2d(n, n, kernel_size=3, padding=1)
self.bn12 = nn.BatchNorm2d(n)
self.mp1 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.conv21 = nn.Conv2d(n, 2*n, kernel_size=3, padding=1)
self.bn21 = nn.BatchNorm2d(2*n)
self.conv22 = nn.Conv2d(2*n, 2*n, kernel_size=3, padding=1)
self.bn22 = nn.BatchNorm2d(2*n)
self.mp2 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.conv31 = nn.Conv2d(2*n, 4*n, kernel_size=3, padding=1)
self.bn31 = nn.BatchNorm2d(4*n)
self.conv32 = nn.Conv2d(4*n, 4*n, kernel_size=3, padding=1)
self.bn32 = nn.BatchNorm2d(4*n)
self.mp3 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.conv41 = nn.Conv2d(4*n, 8*n, kernel_size=3, padding=1)
self.bn41 = nn.BatchNorm2d(8*n)
self.conv42 = nn.Conv2d(8*n, 8*n, kernel_size=3, padding=1)
self.bn42 = nn.BatchNorm2d(8*n)
self.mp4 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.conv51 = nn.Conv2d(8*n, 16*n, kernel_size=3, padding=1)
self.bn51 = nn.BatchNorm2d(16*n)
self.conv52 = nn.Conv2d(16*n, 16*n, kernel_size=3, padding=1)
self.bn52 = nn.BatchNorm2d(16*n)
self.mp5 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc1 = nn.Linear(16*n, n_values)
# Initialization
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
# a modified x, having gone through all the layers of your model, should be returned
out = F.relu( self.bn11( self.conv11(x)))
out = F.relu( self.bn12( self.conv12(out)))
out = self.mp1( out)
out = F.relu( self.bn21( self.conv21(out)))
out = F.relu( self.bn22( self.conv22(out)))
out = self.mp2( out)
out = F.relu( self.bn31( self.conv31(out)))
out = F.relu( self.bn32( self.conv32(out)))
out = self.mp3( out)
out = F.relu( self.bn41( self.conv41(out)))
out = F.relu( self.bn42( self.conv42(out)))
out = self.mp4( out)
out = F.relu( self.bn51( self.conv51(out)))
out = F.relu( self.bn52( self.conv52(out)))
out = self.mp5( out)
out = self.avgpool( out)
out = out.reshape( out.size(0), -1)
out = self.fc1(out)
return out
|
"""
Easy JSON Web Token implementation for Flask
"""
import re
import jwt
from datetime import datetime, timedelta
from flask import current_app, request
from .security import Security
class JWT:
""" Gets request information to validate JWT """
token = None
app_key = None
app_secret = None
request = None
data = None
errors = []
def __init__(self):
self.token = None
self.data = None
self.errors = []
self.app_key = current_app.config['KEY']
self.app_secret = current_app.config['SECRET']
self.request = request
def get_http_token(self):
if 'Authorization' in request.headers:
token = request.headers['Authorization']
parsed_token = re.search('Bearer (.+)', token)
if parsed_token:
return parsed_token.group(1)
else:
return None
return None
def create_token(self, data, token_valid_for=180) -> str:
""" Create encrypted JWT """
jwt_token = jwt.encode({
'data': data,
'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)},
self.app_secret, algorithm="HS256")
return Security.encrypt(jwt_token)
def verify_token(self, token) -> bool:
""" Verify encrypted JWT """
try:
self.data = jwt.decode(Security.decrypt(token), self.app_secret,
algorithms=["HS256"])
return True
except (Exception, BaseException) as error:
self.errors.append(error)
return False
return False
def verify_http_auth_token(self) -> bool:
""" Use request information to validate JWT """
authorization_token = self.get_http_token()
if authorization_token is not None:
if self.verify_token(authorization_token):
if self.data is not None:
self.data = self.data['data']
return True
return False
else:
return False
return False
def create_token_with_refresh_token(self, data, token_valid_for=180,
refresh_token_valid_for=86400):
""" Create an encrypted JWT with a refresh_token """
refresh_token = None
refresh_token = jwt.encode({
'exp':
datetime.utcnow() +
timedelta(seconds=refresh_token_valid_for)},
self.app_secret).decode("utf-8")
jwt_token = jwt.encode({
'data': data,
'refresh_token': refresh_token,
'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)},
self.app_secret)
return Security.encrypt(jwt_token)
def verify_refresh_token(self, expired_token) -> bool:
""" Use request information to validate refresh JWT """
try:
decoded_token = jwt.decode(
Security.decrypt(expired_token),
self.app_secret,
options={'verify_exp': False})
if 'refresh_token' in decoded_token and \
decoded_token['refresh_token'] is not None:
try:
jwt.decode(decoded_token['refresh_token'], self.app_secret)
self.data = decoded_token
return True
except (Exception, BaseException) as error:
self.errors.append(error)
return False
except (Exception, BaseException) as error:
self.errors.append(error)
return False
return False
def verify_http_auth_refresh_token(self) -> bool:
""" Use expired token to check refresh token information """
authorization_token = self.get_http_token()
if authorization_token is not None:
if self.verify_refresh_token(authorization_token):
if self.data is not None:
self.data = self.data['data']
return True
return False
else:
return False
return False
|
#!usr/bin/python3
# Simple tkinter Calculator
from tkinter import *
from tkinter import font as tkFont
# Clear function
def clearScreen():
display.set("")
# Display function
def dataDisplay(key):
if display.get() == "ERROR":
clearScreen()
word = display.get() + key
display.set(word)
# Answer function
def calculate():
try:
word = eval(display.get())
display.set(word)
except:
word = "ERROR"
display.set(word)
root = Tk()
# Geometry settings
root.geometry("260x256")
root.title("Calc")
root.resizable(0, 0)
root.columnconfigure(0, weight=1)
# Font
text_font = tkFont.Font(family='Arial', size=15, weight=tkFont.NORMAL)
# Display
display = StringVar()
display_area = Entry(root, width=46, bd=15, textvariable=display, relief=FLAT,
justify="right", font=text_font, bg="gray80")
display_area.grid(row=0, column=0, columnspan=4)
# First row
percent_btn = Button(root, text="%", width=5, font=text_font, relief=FLAT,
bg="light grey", fg="black", command=lambda: dataDisplay(" / 100"))
percent_btn.grid(row=1, column=0, sticky="E")
pow_of_two_btn = Button(root, text="x^2", width=5, font=text_font, relief=FLAT,
bg="light grey", fg="black", command=lambda: dataDisplay(" ** 2"))
pow_of_two_btn.grid(row=1, column=1, sticky="w")
clear_btn = Button(root, text="Clear", width=11, font=text_font, relief=FLAT,
bg="dark grey", command=clearScreen)
clear_btn.grid(row=1, column=2, columnspan=2)
# Second row
seven_btn = Button(root, text="7", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("7"))
seven_btn.grid(row=2, column=0, sticky="e")
eight_btn = Button(root, text="8", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("8"))
eight_btn.grid(row=2, column=1, sticky="w")
nine_btn = Button(root, text="9", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("9"))
nine_btn.grid(row=2, column=2)
division_btn = Button(root, text="/", width=5, font=text_font, relief=FLAT,
bg="light grey", fg="black", command=lambda: dataDisplay("/"))
division_btn.grid(row=2, column=3)
# Third row
four_btn = Button(root, text="4", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("4"))
four_btn.grid(row=3, column=0, sticky="e")
five_btn = Button(root, text="5", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("5"))
five_btn.grid(row=3, column=1, sticky="w")
six_btn = Button(root, text="6", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("6"))
six_btn.grid(row=3, column=2)
multi_btn = Button(root, text="*", width=5, font=text_font, relief=FLAT,
bg="light grey", fg="black", command=lambda: dataDisplay("*"))
multi_btn.grid(row=3, column=3)
# Fourth row
one_btn = Button(root, text="1", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("1"))
one_btn.grid(row=4, column=0, sticky="e")
two_btn = Button(root, text="2", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("2"))
two_btn.grid(row=4, column=1, sticky="w")
three_btn = Button(root, text="3", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("3"))
three_btn.grid(row=4, column=2)
minus_btn = Button(root, text="-", width=5, font=text_font, relief=FLAT,
bg="light grey", fg="black", command=lambda: dataDisplay("-"))
minus_btn.grid(row=4, column=3)
# Fifth row
dot_btn = Button(root, text=".", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("."))
dot_btn.grid(row=5, column=0, sticky="e")
zero_btn = Button(root, text="0", width=5, font=text_font, relief=FLAT,
bg="ghost white", fg="black", command=lambda: dataDisplay("0"))
zero_btn.grid(row=5, column=1, sticky="w")
equal_btn = Button(root, text="=", width=5, bg="light sky blue", relief=FLAT,
fg="white", font=text_font, command=calculate)
equal_btn.grid(row=5, column=2)
plus_btn = Button(root, text="+", width=5, font=text_font, relief=FLAT,
bg="light grey", fg="black", command=lambda: dataDisplay("+"))
plus_btn.grid(row=5, column=3)
root.mainloop()
|
# AoC 2019 - Day 1 - Part 2
f = open('input.txt', 'r')
sum = 0
def fuel_adder(amount):
partial = int(amount/3)-2
if partial < 1:
return 0
return partial + fuel_adder(partial)
for l in f:
sum += fuel_adder(int(l))
print(sum) |
#Amir Afzali
#Counting Sundays Project Euler Question 19
import datetime
#The best way to approach the problem would be to take advantage of the datetime library as it should have all the info I need so import it
def countingsundays():
#Setting up the ranges for month and years
sundays = sum(1
for year in range(1901,2001)
for month in range(1,13)
if datetime.date(year, month, 1).weekday() == 6)
#for this module sunday is 6 and monday is 0, utilize the module
return str(sundays)
|
import math
a=int(input("enter the element:"))
print(a)
print(math.factorial(a))
|
"""
This module is used in identifying the cuisine a particular dish belongs
to. It does so by converting a dish's ingredients to a vectorized format
using the TF-IDF method, and then uses KNN with a choice of similarity
measure to get the cuisine.
"""
import sys
import copy
import json
import math
import random
import difflib
from sklearn.feature_extraction.text import CountVectorizer
import taster
from utilities import read_json
vectorizer = CountVectorizer()
def get_cuisine_tags(food):
"""
This retrieves the cuisine tags from the JSON file which contains the
list of dishes with their tags.
It first tries to get the closest matching dish name and then retrives
the tags. Tries it at thresholds of 0.7 and falls back to 0.4.
If the tag is not found, returns unknown
Keyword arguments:
food -- The name of the dish
Returns:
A list that contains tags if a match is found
['unknown'] otherwise
"""
with open('cuisine_tags.json') as json_file:
tags = json.load(json_file)
closest_match = difflib.get_close_matches(food, list(tags), cutoff=0.7)
if len(closest_match) > 0 and closest_match[0] in tags:
return tags[closest_match[0]]
closest_match = difflib.get_close_matches(food, list(tags), cutoff=0.4)
if len(closest_match) > 0 and closest_match[0] in tags:
return tags[closest_match[0]]
return ['unknown']
def get_neighbors(food, foods_list, vector, distance_metric, limit=100):
"""
Returns a dictionary of dishes and their distance from the dish
specified in descending order of distances
Keyword arguments:
food -- The dish specified for finding neighbors
foods_list -- The list of all dishes
vector -- The list of dish vectors that are created for all
dishes from CountVectorizer. It is a numeric
representation of all dishes
distance_metric -- A function object that is to be passed, that
compares two vectors, and gets the distance
limit -- Parameter that limits the top neighbors when
sorted by distance
Returns:
A sorted dictionary of dish_names that the distance as value
"""
distances = dict()
food_bitstring = vector.toarray()[food['dish_id'] - 1]
for index, bitstring in enumerate(vector.toarray()):
if index != food['dish_id']:
distances[(foods_list[index]['dish_name'])] = compare_distance(
food_bitstring, bitstring, distance_metric)
return sorted(distances.items(), key=lambda x: x[1], reverse=True)[:limit]
def knn(neighbors_cuisines):
"""
This is the weighted KNN algorithm that identifies the cuisines
of the k closest neighbors.
Keyword arguments:
neighbors_cuisines -- A list of tuples that contains the cuisine
tags and the distance from the target dish
Returns:
nearest_neighbor_dict -- A dictionary that contains the cuisine
tag and the distance of the closest
obtained from the closest neighbor
"""
nearest_neighbor_dict = dict()
for item in neighbors_cuisines:
key = item[0]
if len(key) == 1:
key = key[0]
if key in nearest_neighbor_dict:
nearest_neighbor_dict[key] += 1 / float(math.pow(item[1], 2))
else:
nearest_neighbor_dict[key] = 1 / float(math.pow(item[1], 2))
elif len(key) == 2:
if key[0] in nearest_neighbor_dict and key[1] in nearest_neighbor_dict:
nearest_neighbor_dict[key[0]] = 1 / float(math.pow(item[1], 2))
nearest_neighbor_dict[key[1]] = 1 / float(math.pow(item[1], 2))
elif key[0] not in nearest_neighbor_dict:
nearest_neighbor_dict[key[0]] = 1 / float(math.pow(item[1], 2))
else:
nearest_neighbor_dict[key[1]] = 1 / float(math.pow(item[1], 2))
return sorted(nearest_neighbor_dict.items(), key=lambda x: x[1])
def compare_distance(vector1, vector2, distance_metric):
"""
A function that employs a callback mechanism to compare the distance
between two vectors
Keyword arguments:
vector1, vector2 -- The vectors to be compared
distance_metric -- A function object that is used to compare
distance
Returns:
Distance between the 2 vectors
"""
return distance_metric(vector1, vector2)
def euclidean(vector1, vector2):
"""
Implementation of Euclidean Distance
Keyword arguments:
vector1, vector2 -- The vectors to be compared
Returns :
Distance between the 2 vectors
"""
return math.sqrt(
sum(
pow(a - b, 2) for a, b in zip(vector1, vector2)
)
)
def cosine_similarity(vector1, vector2):
"""
Implementation of Cosine Similarity. It gets the dot product
between the 2 vectors and divides by the square root of their
magnitudes
Keyword arguments:
vector1, vector2 -- The vectors to be compared
Returns :
Distance between the 2 vectors
"""
dot_product = sum(p * q for p, q in zip(vector1, vector2))
magnitude = math.sqrt(
sum([val ** 2
for val
in vector1
]
)
) * math.sqrt(sum([val**2 for val in vector2]))
if not magnitude:
return 0
return dot_product / magnitude
def jaccard_similarity(vector1, vector2):
"""
Implementation of Jaccard similarity to get distance between the
2 vectors
Keyword arguments:
vector1, vector2 -- The vectors to be compared
Returns :
Distance between the 2 vectors
"""
intersection_size = len(set(vector1).intersection(set(vector2)))
union_size = len(set(vector1).union(set(vector2)))
return intersection_size / float(union_size)
def create_training_set(foods_list, test_set):
"""
Creates a training set from the list of dishes with cuisine tags
Appends the ingredient strings to help ease comparison
Modifies the test set passed to bring it to a uniform format
Keyword arguments:
foods_list -- List of all dishes from which the training set is
generated
test_set -- List of dishes to be used for testing
Returns:
training_set -- List of dishes used
"""
training_set = list()
total = 0
count = dict()
count['north indian'] = 0
count['south indian'] = 0
for food in test_set:
item = dict()
item['dish_name'] = food['dish_name']
item['dish_id'] = total
item['ingredient'] = food['ingredient_str']
training_set.append(item)
total += 1
random.shuffle(foods_list)
for food in foods_list:
cuisine_tag = get_cuisine_tags(food['dish_name'])
if len(cuisine_tag) > 0 and cuisine_tag[0] not in count:
count[cuisine_tag[0]] = 0
if total < 400 and len(cuisine_tag) > 0:
item = dict()
item['dish_name'] = food['dish_name']
item['dish_id'] = total
item['ingredient'] = food['ingredient_str']
item['cuisine'] = cuisine_tag
# Uncomment this to restrict amount of north indian tags
# if 'north indian' in cuisine_tag and count['north indian'] < 61:
# count['north indian'] += 1
# training_set.append(item)
# elif 'south indian' in cuisine_tag and count['south indian'] < 61:
# count['south indian'] += 1
# training_set.append(item)
# else:
# count[cuisine_tag[0]] += 1
# training_set.append(item)
# total += 1
return training_set
def classify_cuisine(
all_dishes,
test_dishes,
similarity_measure=cosine_similarity):
"""
Main function to be run to identify cuisine of test dishes
Appends the parsed ingredients to each object in both the
all_dishes and test_dishes for convenience
Retrieves the distances from other dishes for a test dish,
and uses KNN to identify cuisine based on the other dishes
Keyword arguments:
all_dishes -- List of all dishes
test_dishes -- List of dishes used for testing
similarity_measure -- Function object that is used as a
callback. Default is cosine_similarity
Returns:
cuisines_dict -- A dictionary that contains the dish and its
predicted cuisine
"""
foods_list = list()
test_list = list()
for food in all_dishes:
foods_list.append(taster.append_parsed(food))
for food in test_dishes:
test_list.append(taster.append_parsed(food))
copy_foods_list = copy.deepcopy(foods_list)
cuisines_dict = dict()
training_set = create_training_set(copy_foods_list, test_dishes)
test_indices = [i['dish_id'] for i in training_set if 'cuisine' not in i]
all_recipes = [i['ingredient'] for i in training_set]
vector = vectorizer.fit_transform(all_recipes)
for index in test_indices:
test_dish = training_set[test_indices[index]]
neighbors = get_neighbors(test_dish,
training_set,
vector,
similarity_measure)
neighbors_cuisines = [(get_cuisine_tags(dish_name[0]), dish_name[1])
for dish_name
in neighbors
][:7]
cuisines_dict[test_dish['dish_name']] = knn(neighbors_cuisines)
return cuisines_dict
if __name__ == '__main__':
if len(sys.argv) == 3 or len(sys.argv) == 4:
all_recipes = list()
sample_size = 1300
if len(sys.argv) == 4:
sample_size = int(sys.argv[3])
all_dishes = read_json(sys.argv[1])
test_dishes = read_json(sys.argv[2])
for dish, value in classify_cuisine(
all_dishes[:sample_size],
test_dishes,
cosine_similarity).items():
print(dish)
print("------------")
print(value)
print()
else:
print("python3 cuisine_classifier.py <path_do_dish_database> <path_to_test_dishes> <sample_size>(OPTIONAL)")
|
import cv2
import numpy as np
def resize(image: np.ndarray, width: int = None, height: int = None, inter: int = cv2.INTER_AREA) -> np.ndarray:
"""
Resize image proportionally
:param image: image to resize
:param width: new width
:param height: new height
:param inter: interpolation method
:return: resized image
"""
(h, w) = image.shape[:2]
if width is None and height is None:
return image
if width is None:
ratio = height / float(h)
dim = (int(w * ratio), height)
else:
ratio = width / float(w)
dim = (width, int(h * ratio))
resized = cv2.resize(image, dim, interpolation=inter)
return resized
|
# importing another py file
import openpyxl
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
from email.mime.image import MIMEImage
import smtplib
from email.mime.text import MIMEText
# mime = multipurpose internet mail extension
from email.mime.multipart import MIMEMultipart
import webbrowser
import string
import random
from datetime import datetime
import json
import csv
import shutil
from pathlib import Path
from sales import func1, func2
# or
import sales
# now use like this
sales.func1()
# python standard library
path = Path("hello.py")
path.exists() # returns boolean if this directory exists or not
path.is_file() # to check if this path represents a file or not
path.is_dir() # to check if this path represents a directory or no
path.absolute() # returns the absolute directory of the path
path.name # returns the file name
path.parent # returns the parent folder
path.suffix # returns the extension
path.stem # returns the file name w/o the extension
path.with_name("file.txt") # creates a file
path.rename() # pass parameters of the new name
path.read_text() # returns the content of the file as string
path.write_text() # writes file
# for copying a file use shutil module
shutil.copy(source, target)
# writing csv file
with open("daraz.csv", "w") as file: # opening a csv, "w" means to write the file
writer = csv.writer(file)
writer.writerow("a", "b") # 1 row 2 colums will be added
# to read a csv
with open("daraz.csv", "w") as file:
reader = csv.reader(file)
# will convert all data into a list of lists (each line is a list)
print(list(reader))
for row in reader: # reading by row
print(row)
# working with json files
movies = [{"id": 1, "name": "a"}, {
"id": 2, "name": "b"}, {"id": 3, "name": "c"}]
movie_file = json.dumps(movies) # converts it to json data
# create a json file
Path("movies.json").write_text(movie_file)
# read a json file
readingJsonFile = Path("movies.json").read_text()
# converts it to list of dictionaries
movies_dictionaries = json.loads(readingJsonFile)
# data time
now = datetime.now()
# generate random valus
random.random() # generates a double
random.randint(1, 10) # generates between this range
random.choice([1, 25, 7]) # picks a number from this list
random.choices([1, 5, 3, 9, 6], k=2) # pick k numbers from this list
# generating password using random
# join metho joins these strings
"".join(random.choices(["abaaabdkdojiwjiojw"], k=6))
string.ascii_letters # this returns all ascii characters
string.digits # returns 0 to 9
"".join(random.choices(string.ascii_letters+string.digits, k=8))
num = [1, 2, 3, 4]
# shuffle a list
random.shuffle(num)
# open a browser
webbrowser.open("http://google.com")
# sending emails
message = MIMEMultipart()
message["from"] = "Nayeem Rafsan"
message["to"] = "teset@gamil.com"
message["subject"] = "this is testing"
message.attach(MIMEText("Body")) # can't add body of the message
# we have attach the txt, image file here
# we have created a text with MIMEText constructor
# now we need a SMTP server
with smtplib.SMTP(host="smtp.gmail.com", port=465) as smtp:
smtp.ehlo() # sending hello message to server
smtp.starttls() # puts smtp to transport layer security
smtp.login("username@gmail.com", "passwordhere")
smtp.send_message(message)
print("sent") # for confirmation
# attach image
# this only takes byte so convert image to byte
message.attach(MIMEImage(Path("image1.jpg").read_bytes))
# first https://myaccount.google.com/u/1/lesssecureapps and turn off less secure app
# virtual environments:
# for certain dependencies (ex: requests is version 20.0 bt you need 18.0 for your app)
# so we create a virtual environment and create these dependencies
# for this we use pipenv
# pip3 install pipenv
# then activate it
# YELP API
# install requests using pip3 or pipenv
url = "https://api.yelp.com/v3/businesses/search"
api_key = "aaaaaaaaaaaaaaaaaaaaa"
head = {
"Authorization": "Bearer "+api_key
}
param = {
"location": "NYC"
}
# this will take 3 parameters to work, url, header, params
# this will return a json file
r = requests.get(url, headers=head, params=param)
# now extract information from the json file
r.json() # this converts the json to dictionary
business = r.json()["businesses"]
for b in business:
print(b['name'])
# or use list comphrehension
[b["name"] for b in business]
[b["name"] for b in business if business["rating"] > 4] # filtering the businesses
# hiding the API key
# create config.py create variable for api_key
# import config in app.py and replace api_key with config.api_key
# create .gitignore file and write config.py
# webscarping
req = requests.get("http://stackoverflow.com/questions")
soup = BeautifulSoup(req.text, "html.parser")
# find container thqat contains all info
qs = soup.select(".question-summary") # . dot means class
# under question-summary
print(qs[0].select_one(".question-hyperlink").getText())
for q in qs:
print(q.select_one(".question-hyperlink").getText())
# browser automation using Selenium
browser = webdriver.Chrome()
browser.get("http://github.com")
# we can get elements by their className/ tags or text
# get elements by text
sign_in = browser.find_elements_by_link_text("Sign in")
# now click it
sign_in.click()
# now get elements by id
user_name = browser.find_element_by_id("login_field")
# for typing use send_keys()
user_name.send_keys("rafu01")
user_pass = browser.find_element_by_id("password")
user_pass.send_keys("password")
user_pass.submit()
# checking if this text exists in this page or not
assert "rafu01" in browser.page_source
# working with excel sheet
wp = openpyxl.load_workbook("myExcel.xlsx")
wp.sheetnames # prints all sheet names
sheet = wb["Sheet1"]
cell = sheet["a1"]
# or use
cell = sheet.cell(row=1, column=1)
# sheet[row,colum]
sheet[1:3] # only row
|
def binary_search(array, target):
start = 0
end = n - 1
while start <= end:
mid = (start + end) // 2
if array[mid] == target:
return 1
elif array[mid] < target:
start = mid + 1
else:
end = mid - 1
return 0
t = int(input())
for tc in range(t):
n = int(input())
array = sorted(list(map(int, input().split())))
m = int(input())
req_array = list(map(int, input().split()))
for target in req_array:
print(binary_search(array,target))
# 되도록 함수 써서 제출
|
str = input()
print(1) if str == str[::-1] else print(0)
|
str = input()
tmp = ""
answer = ""
is_tag = False
for i in str:
if i == '<':
is_tag = True
answer += tmp[::-1] + "<"
tmp = ''
elif i == '>':
is_tag = False
answer += ">"
elif i == ' ':
if is_tag:
answer += ' '
else:
answer += tmp[::-1] + ' '
tmp = ''
else:
if is_tag:
answer += i
else:
tmp += i
answer += tmp[::-1]
print(answer)
|
T=int(input())
for i in range(T):
str = list(input())
if str == str[::-1]:
result = 1
else:
result= 0
print(f"#{i+1} {result}")
|
class Node:
def __init__(self,item,left=None, right=None):
self.item=item
self.left=left
self.right=right
class binarytree:
def __init__(self):
self.root=None
def preorder(self,n):
if n!= None:
print(str(n.item),end=' ')
if n.left:
self.preorder(n.left)
if n.right:
self.preorder(n.right)
def inorder(self,n):
if n!=None:
if n.left:
self.inorder(n.left)
print(str(n.item),end=' ')
if n.right:
self.inorder(n.right)
def postorder(self,n):
if n!=None:
if n.left:
self.postorder(n.left)
if n.right:
self.postorder(n.right)
print(str(n.item), end=' ')
def levelorder(self,root):
q=[]
q.append(root)
while q!=[]:
temp=q.pop()
print(str(temp.item),end=' ')
if temp.left:
q.append(temp.letf)
if temp.right:
q.append(temp.right)
def height(self,root):
if root==NOne:
return 0
return max(self.height(root.left),self.height(root.right))+1
sample=binarytree()
n1=Node(1)
n2=Node(2)
n3=Node(3)
n4=Node(4)
n5=Node(5)
n6=Node(6)
n7=Node(7)
n8=Node(8)
n1.left=n2
n1.right=n3
n2.left=n4
n2.right=n5
n3.left=n6
n3.right=n7
n4.left=n8
sample.root=n1
print('전위')
sample.preorder(sample.root)
|
from copy import deepcopy
print("hello ")
#문제 설명
#리스트가 주어졌을 때
#동일 요소가 포함되지 않은 연속된 수열의 개수
#단순하게 생각하면 그냥 새로운 원소 나올 때마다 set에 추가하고 비교...?
inp = list(map(int,input().split()))
sum = 0
print('input',inp)
all = []
for i in range(len(inp)):
temp = set([inp[i]])
sum +=1
all.append(deepcopy(temp))
print('one',all)
#print('current', temp,sum)
j = i
while (j != len(inp) -1 ):
j +=1
#print('j',j)
if inp[j] not in temp:
temp.add(inp[j])
all.append(deepcopy(temp))
print('add',all)
sum += 1
#print('add',temp,sum)
else:
#sum +=1
#all.append(temp)
#print(all)
#print(sum,temp, i, j)
break
print(sum)
print(all)
|
class Solution:
def reverse(self, x: int) -> int:
temp=str(x)
if temp[0].isdigit():
result=temp[::-1]
result=int(result)
if result<pow(2,31)-1 : return result
else: return 0
else:
result=temp[:0:-1]
result=int(result)
if -result>pow(-2,31): return -result
else : return 0
|
from human import Human
from ai import AI
import time
class Game:
def __init__(self):
self.player_one = Human()
self.player_two = None
self.run_game()
self.game_state = None
def display_welcome(self):
print("Hello and welcome to Rock, Paper, Scissors, Lizard, Spock!")
def display_rules(self):
print("The rules are similar to your standard game of rock paper scissors. However, we have two added two more options: lizard and Spock")
time.sleep(.75)
print("Your standard rock, paper, scissors rules apply with the following additional rules:\n"
"Rock crushes Lizard\n"
"Lizard poisons Spock\n"
"Spock smashes Scissors\n"
"Scissors decapitates Lizard\n"
"Lizard eats Paper\n"
"Paper disproves Spock\n"
"Spock vaporizes Rock")
time.sleep(1.5)
print("We will play best of three rounds to decide our winner!")
def run_game(self):
# Intro & Instructions
self.display_welcome()
time.sleep(.75)
self.display_rules()
#Pick game mode - single player or multiplayer
self.choose_game_mode()
while self.game_state == True:
#Game Rounds
#Player one and two choose gesture
self.player_one.display_gestures()
if self.player_two.value == "human":
self.player_two.display_gestures()
else:
self.player_two.choose_gesture()
#determine winner of round, give winner score
self.check_gestures()
#loop to continue gameplay until best of three
print("Would you like to play again?")
play_again = input("Enter '1' for yes or '2' for no: ")
while play_again != "1" and play_again != "2":
print("Please enter either '1' or '2'")
play_again = input("Enter '1' for yes or '2' for no: ")
if play_again == "1":
self.run_game()
else:
print("Thank you for playing! Goodbye!")
def check_gestures(self):
if self.player_one.chosen_gesture.name == self.player_two.chosen_gesture.name:
print(f"Both players picked {self.player_one.chosen_gesture}. This round is a draw")
elif (self.player_one.chosen_gesture.name == self.player_two.chosen_gesture.gets_beat_by[0]) or (self.player_one.chosen_gesture.name == self.player_two.chosen_gesture.gets_beat_by[1]):
self.player_one.score += 1
print(f"{self.player_one.name} won the round! {self.player_one.name} chose {self.player_one.chosen_gesture}, which beats {self.player_two.name}'s {self.player_two.chosen_gesture}!")
if self.player_one.score == 2:
print(f"{self.player_one.name} Wins! with a score of {self.player_one.score} to {self.player_two.score}")
self.game_state = False
else:
print(f"With that win, {self.player_one.name} now has {self.player_one.score} point(s)!")
elif (self.player_one.chosen_gesture.name == self.player_two.chosen_gesture.beats[0]) or (self.player_one.chosen_gesture.name == self.player_two.chosen_gesture.beats[1]):
print(f"{self.player_two.name} won the round! {self.player_two.name} chose {self.player_two.chosen_gesture}, which beats {self.player_one.name}'s {self.player_one.chosen_gesture}!")
self.player_two.score += 1
if self.player_two.score == 2:
print(f"{self.player_two.name} Wins! with a score of {self.player_two.score} to {self.player_one.score}")
self.game_state = False
else:
print(f"With that win, {self.player_two.name} now has {self.player_two.score} point(s)!")
def choose_game_mode(self):
print("What game mode would you like to play?")
game_mode = input("Please enter '1' for Single player or '2' for Two player: ")
while game_mode != "1" and game_mode != "2":
print("Please enter either '1' or '2'")
game_mode = input("Please enter '1' for Single player or '2' for Two player: ")
self.game_state = True
if game_mode == "1":
self.player_one.get_name("One")
self.player_two = AI()
else:
self.player_one.get_name("One")
self.player_two = Human()
self.player_two.get_name("Two")
|
# 文本文件与二进制文件的区别
textFile = open("7.1.txt","rt")
print(textFile.readline())
textFile.close()
binFile = open("7.1.txt","rb")
print(binFile.readline())
binFile.close()
# 结果:
# 中国是一个伟大的国家
# b'\xd6\xd0\xb9\xfa\xca\xc7\xd2\xbb\xb8\xf6\xce\xb0\xb4\xf3\xb5\xc4\xb9\xfa\xbc\xd2'
# 文本文件逐行打印
fname = input("请输入要打开的文件:")
fo = open(fname, "r")
for line in fo:
print(line)
fo.close()
# 向文件写入一个列表
fname = input("请输入要写入的文件:")
fo = open(fname, "w+")
ls = ["唐诗", "宋词", "元曲"]
fo.writelines(ls)
fo.seek(0)
for line in fo:
print(line)
fo.close()
|
import collections
from functools import reduce
from io import StringIO
import random
from . import AbstractTeam
from .. import datamodel
class Team(AbstractTeam):
""" Simple class used to register an arbitrary number of (Abstract-)Players.
Each Player is used to control a Bot in the Universe.
SimpleTeam transforms the `set_initial` and `get_move` messages
from the GameMaster into calls to the user-supplied functions.
Parameters
----------
team_name :
the name of the team (optional)
players : functions with signature (datadict, storage) -> move
the Players who shall join this SimpleTeam
"""
def __init__(self, *args):
if not args:
raise ValueError("No teams given.")
if isinstance(args[0], str):
self.team_name = args[0]
team_move = args[1]
else:
self.team_name = ""
team_move = args[0]
self._team_move = team_move
def set_initial(self, team_id, universe, game_state):
""" Sets the bot indices for the team and returns the team name.
Currently, we do not call _set_initial on the user side.
Parameters
----------
team_id : int
The id of the team
universe : Universe
The initial universe
game_state : dict
The initial game state
Returns
-------
Team name : string
The name of the team
"""
#: Storage for the team state
self._team_state = None
self._team_game = [None, None]
#: Storage for the random generator
self._bot_random = [None] * len(universe.bots)
#: Store the last known bot positions
self._last_know_position = [b.current_pos for b in universe.bots if b.team_index == team_id]
#: Store a history of bot positions
self._bot_track = [[], []]
#: Store if we have been eaten before our move
self._bot_eaten = [False, False]
# To make things a little simpler, we also initialise a random generator
# for all enemy bots
for bot in universe.bots:
# we take the bot’s index as a value for the seed_offset
self._bot_random[bot.index] = random.Random(game_state["seed"] + bot.index)
return self.team_name
def get_move(self, bot_id, universe, game_state):
""" Requests a move from the Player who controls the Bot with id `bot_id`.
This method returns a dict with a key `move` and a value specifying the direction
in a tuple. Additionally, a key `say` can be added with a textual value.
Parameters
----------
bot_id : int
The id of the bot who needs to play
universe : Universe
The initial universe
game_state : dict
The initial game state
Returns
-------
move : dict
"""
bots = bots_from_universe(universe,
rng=self._bot_random,
round=game_state['round_index'],
team_name=game_state['team_name'],
timeout_count=game_state['timeout_teams'])
me = bots[bot_id]
team = bots[bot_id]._team
turn = bot_id // 2
for idx, mybot in enumerate(team):
# we assume we have been eaten, when we’re on our initial_position
# and we could not move back to our previous position
if mybot.position == mybot._initial_position:
last_pos = self._last_know_position[idx]
try:
mybot.get_move(last_pos)
except ValueError:
self._bot_eaten[idx] = True
self._bot_track[idx] = []
self._last_know_position[idx] = mybot.position
# Add our track
if len(self._bot_track[turn]) == 0:
self._bot_track[turn] = [me.position]
for idx, mybot in enumerate(team):
# If the track of any bot is empty,
# Add its current position
if turn != idx:
self._bot_track[idx].append(mybot.position)
mybot.track = self._bot_track[idx][:]
mybot._eaten = self._bot_eaten[idx]
self._team_game = team
move, state = self._team_move(self._team_game[turn], self._team_state)
self._bot_eaten[turn] = False
# restore the team state
self._team_state = state
return {
"move": move,
"say": me._say
}
def __repr__(self):
return "Team(%r, %s)" % (self.team_name, repr(self._team_move))
def create_homezones(width, height):
return [
[(x, y) for x in range(0, width // 2)
for y in range(0, height)],
[(x, y) for x in range(width // 2, width)
for y in range(0, height)]
]
class Bot:
def __init__(self, *, bot_index,
position,
initial_position,
walls,
homezone,
food,
is_noisy,
score,
random,
round,
is_blue,
team_name,
timeout_count):
self._bots = None
self._say = None
#: The previous positions of this bot including the current one.
self.track = []
self._eaten = False
self._initial_position = initial_position
self.random = random
self.position = position
self.walls = walls
self.is_noisy = is_noisy
self.homezone = homezone
self.food = food
self.score = score
self.bot_index = bot_index
self.round = round
self.is_blue = is_blue
self.team_name = team_name
self.timeout_count = timeout_count
@property
def legal_moves(self):
""" The legal moves that the bot can make from its current position,
including no move at all.
"""
legal_moves = [(0, 0)]
for move in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
new_pos = (self.position[0] + move[0], self.position[1] + move[1])
if not new_pos in self.walls:
legal_moves.append(move)
return legal_moves
@property
def _team(self):
""" Both of our bots.
"""
if self.is_blue:
return [self._bots[0], self._bots[2]]
else:
return [self._bots[1], self._bots[3]]
@property
def turn(self):
""" The turn of our bot. """
return self.bot_index // 2
@property
def other(self):
""" The other bot in our team. """
return self._team[1 - self.turn]
@property
def enemy(self):
""" The list of enemy bots
"""
if self.is_blue:
return [self._bots[1], self._bots[3]]
else:
return [self._bots[0], self._bots[2]]
def say(self, text):
""" Print some text in the graphical interface. """
self._say = text
def get_move(self, position):
""" Return the move needed to get to the given position.
Raises
======
ValueError
If the position cannot be reached by a legal move
"""
direction = (position[0] - self.position[0], position[1] - self.position[1])
if direction not in self.legal_moves:
raise ValueError("Cannot reach position %s (would have been: %s)." % (position, direction))
return direction
def get_position(self, move):
""" Return the position reached with the given move
Raises
======
ValueError
If the move is not legal.
"""
if move not in self.legal_moves:
raise ValueError("Move %s is not legal." % move)
position = (move[0] + self.position[0], move[1] + self.position[1])
return position
@property
def eaten(self):
""" True if this bot has been eaten in the last turn. """
return self._eaten
def _repr_html_(self):
""" Jupyter-friendly representation. """
bot = self
width = max(bot.walls)[0] + 1
height = max(bot.walls)[1] + 1
with StringIO() as out:
out.write("<table>")
for y in range(height):
out.write("<tr>")
for x in range(width):
if (x, y) in bot.walls:
bg = 'style="background-color: {}"'.format(
"rgb(94, 158, 217)" if x < width // 2 else
"rgb(235, 90, 90)")
else:
bg = ""
out.write("<td %s>" % bg)
if (x, y) in bot.walls: out.write("#")
if (x, y) in bot.food: out.write('<span style="color: rgb(247, 150, 213)">●</span>')
if (x, y) in bot.enemy[0].food: out.write('<span style="color: rgb(247, 150, 213)">●</span>')
for idx in range(4):
if bot._bots[idx].position == (x, y):
if idx == self.bot_index:
out.write('<b>' + str(idx) + '</b>')
else:
out.write(str(idx))
out.write("</td>")
out.write("</tr>")
out.write("</table>")
return out.getvalue()
def __str__(self):
bot = self
width = max(bot.walls)[0] + 1
height = max(bot.walls)[1] + 1
header = ("{blue}{you_blue} vs {red}{you_red}.\n" +
"Playing on {col} side. Current turn: {turn}. Round: {round}, score: {blue_score}:{red_score}. " +
"timeouts: {blue_timeouts}:{red_timeouts}").format(
blue=bot._bots[0].team_name,
red=bot._bots[1].team_name,
turn=bot.turn,
round=bot.round,
blue_score=bot._bots[0].score,
red_score=bot._bots[1].score,
col="blue" if bot.is_blue else "red",
you_blue=" (you)" if bot.is_blue else "",
you_red=" (you)" if not bot.is_blue else "",
blue_timeouts=bot._bots[0].timeout_count,
red_timeouts=bot._bots[1].timeout_count,
)
with StringIO() as out:
out.write(header)
layout = Layout(walls=bot.walls[:],
food=bot.food + bot.enemy[0].food,
bots=[b.position for b in bot._team],
enemy=[e.position for e in bot.enemy])
out.write(str(layout))
return out.getvalue()
def _rebuild_universe(bots):
""" Rebuilds a universe from the list of bots.
"""
if not len(bots) == 4:
raise ValueError("Can only build a universe with 4 bots.")
uni_bots = []
zones = []
for idx, b in enumerate(bots):
homezone = (min(b.homezone)[0], max(b.homezone)[0] + 1)
if idx < 2:
zones.append(homezone)
bot = datamodel.Bot(idx,
initial_pos=b._initial_position,
team_index=idx%2,
homezone=homezone,
current_pos=b.position,
noisy=b.is_noisy)
uni_bots.append(bot)
uni_teams = [
datamodel.Team(0, zones[0], bots[0].score),
datamodel.Team(1, zones[1], bots[1].score)
]
width = max(bots[0].walls)[0] + 1
height = max(bots[0].walls)[1] + 1
maze = datamodel.Maze(width, height)
for pos in maze:
if pos in bots[0].walls:
maze[pos] = True
food = bots[0].food + bots[0].enemy[1].food
game_state = {
'round_index': bots[0].round,
'team_name': [bots[0].team_name, bots[1].team_name],
'timeout_teams': [bots[0].timeout_count, bots[1].timeout_count]
}
return datamodel.CTFUniverse(maze, food, uni_teams, uni_bots), game_state
# def __init__(self, *, bot_index, position, initial_position, walls, homezone, food, is_noisy, score, random, round, is_blue):
def make_bots(*, walls, food, positions, initial_positions, score, is_noisy, rng, round, team_name, timeout_count):
""" Creates a set of 4 bots with the given specification. """
width = max(walls)[0] + 1
height = max(walls)[1] + 1
homezones = create_homezones(width, height)
bots = []
for i, position in enumerate(positions):
homezone = homezones[i % 2]
bot = Bot(bot_index=i,
position=positions[i],
initial_position=initial_positions[i],
walls=walls,
homezone=homezone,
food=[f for f in food if f in homezone],
is_noisy=is_noisy[i],
score=score[i % 2],
random=rng[i],
round=round,
is_blue=(i % 2 == 0),
team_name=team_name[i % 2],
timeout_count=timeout_count[i % 2])
bots.append(bot)
for bot in bots:
bot._bots = bots
return bots
def bots_from_universe(universe, rng, round, team_name, timeout_count):
""" Creates 4 bots given a universe. """
return make_bots(walls=[pos for pos, is_wall in universe.maze.items() if is_wall],
food=universe.food,
positions=[b.current_pos for b in universe.bots],
initial_positions=[b.initial_pos for b in universe.bots],
score=[t.score for t in universe.teams],
is_noisy=[b.noisy for b in universe.bots],
rng=rng,
round=round,
team_name=team_name,
timeout_count=timeout_count)
def bots_from_layout(layout, is_blue, score, rng, round, team_name, timeout_count):
""" Creates 4 bots given a layout. """
if is_blue:
positions = [layout.bots[0], layout.enemy[0], layout.bots[1], layout.enemy[1]]
else:
positions = [layout.enemy[0], layout.bots[0], layout.enemy[1], layout.bots[1]]
# initial positions are grouped by [blue_initials, red_initials] in the layout
# we have to reorder them.
initial_positions=[layout.initial_positions[0][0], layout.initial_positions[1][0],
layout.initial_positions[0][1], layout.initial_positions[1][1]]
return make_bots(walls=layout.walls[:],
food=layout.food,
positions=positions,
initial_positions=initial_positions,
score=score,
is_noisy=[False] * 4,
rng=rng,
round=round,
team_name=team_name,
timeout_count=timeout_count)
def new_style_team(module):
""" Looks for a new-style team in `module`.
"""
# look for a new-style team
move = getattr(module, "move")
name = getattr(module, "TEAM_NAME")
if not callable(move):
raise TypeError("move is not a function")
if type(name) is not str:
raise TypeError("TEAM_NAME is not a string")
return lambda: Team(name, move)
# @dataclass
class Layout:
def __init__(self, walls, food, bots, enemy):
if not food:
food = []
if not bots:
bots = [None, None]
if not enemy:
enemy = [None, None]
# input validation
for pos in [*food, *bots, *enemy]:
if pos:
if len(pos) != 2:
raise ValueError("Items must be tuples of length 2.")
if pos in walls:
raise ValueError("Item at %r placed on walls." % (pos,))
else:
walls_width = max(walls)[0] + 1
walls_height = max(walls)[1] + 1
if not (0 <= pos[0] < walls_width) or not (0 <= pos[1] < walls_height):
raise ValueError("Item at %r not in bounds." % (pos,))
if len(bots) > 2:
raise ValueError("Too many bots given.")
self.walls = sorted(walls)
self.food = sorted(food)
self.bots = bots
self.enemy = enemy
self.initial_positions = self.guess_initial_positions(self.walls)
def guess_initial_positions(self, walls):
""" Returns the free positions that are closest to the bottom left and
top right corner. The algorithm starts searching from (1, -2) and (-2, 1)
respectively and uses the manhattan distance for judging what is closest.
On equal distances, a smaller distance in the x value is preferred.
"""
walls_width = max(walls)[0] + 1
walls_height = max(walls)[1] + 1
left_start = (1, walls_height - 2)
left_initials = []
right_start = (walls_width - 2, 1)
right_initials = []
dist = 0
while len(left_initials) < 2:
# iterate through all possible x distances (inclusive)
for x_dist in range(dist + 1):
y_dist = dist - x_dist
pos = (left_start[0] + x_dist, left_start[1] - y_dist)
# if both coordinates are out of bounds, we stop
if not (0 <= pos[0] < walls_width) and not (0 <= pos[1] < walls_height):
raise ValueError("Not enough free initial positions.")
# if one coordinate is out of bounds, we just continue
if not (0 <= pos[0] < walls_width) or not (0 <= pos[1] < walls_height):
continue
# check if the new value is free
if not pos in walls:
left_initials.append(pos)
if len(left_initials) == 2:
break
dist += 1
dist = 0
while len(right_initials) < 2:
# iterate through all possible x distances (inclusive)
for x_dist in range(dist + 1):
y_dist = dist - x_dist
pos = (right_start[0] - x_dist, right_start[1] + y_dist)
# if both coordinates are out of bounds, we stop
if not (0 <= pos[0] < walls_width) and not (0 <= pos[1] < walls_height):
raise ValueError("Not enough free initial positions.")
# if one coordinate is out of bounds, we just continue
if not (0 <= pos[0] < walls_width) or not (0 <= pos[1] < walls_height):
continue
# check if the new value is free
if not pos in walls:
right_initials.append(pos)
if len(right_initials) == 2:
break
dist += 1
# lower indices start further away
left_initials.reverse()
right_initials.reverse()
return left_initials, right_initials
def merge(self, other):
""" Merges `self` with the `other` layout.
"""
if not self.walls:
self.walls = other.walls
if self.walls != other.walls:
raise ValueError("Walls are not equal.")
self.food += other.food
# remove duplicates
self.food = list(set(self.food))
# update all newer bot positions
for idx, b in enumerate(other.bots):
if b:
self.bots[idx] = b
# merge all enemies and then take the last 2
enemies = [e for e in [*self.enemy, *other.enemy] if e is not None]
self.enemy = enemies[-2:]
# if self.enemy smaller than 2, we pad with None again
for _ in range(2 - len(self.enemy)):
self.enemy.append(None)
# return our merged self
return self
def _repr_html_(self):
walls = self.walls
walls_width = max(walls)[0] + 1
walls_height = max(walls)[1] + 1
with StringIO() as out:
out.write("<table>")
for y in range(walls_height):
out.write("<tr>")
for x in range(walls_width):
if (x, y) in walls:
bg = 'style="background-color: {}"'.format(
"rgb(94, 158, 217)" if x < walls_width // 2 else
"rgb(235, 90, 90)")
elif (x, y) in self.initial_positions[0]:
bg = 'style="background-color: #ffffcc"'
elif (x, y) in self.initial_positions[1]:
bg = 'style="background-color: #ffffcc"'
else:
bg = ""
out.write("<td %s>" % bg)
if (x, y) in walls: out.write("#")
if (x, y) in self.food: out.write('<span style="color: rgb(247, 150, 213)">●</span>')
for idx, pos in enumerate(self.bots):
if pos == (x, y):
out.write(str(idx))
for pos in self.enemy:
if pos == (x, y):
out.write('E')
out.write("</td>")
out.write("</tr>")
out.write("</table>")
return out.getvalue()
def __str__(self):
walls = self.walls
walls_width = max(walls)[0] + 1
walls_height = max(walls)[1] + 1
with StringIO() as out:
out.write('\n')
# first, print walls and food
for y in range(walls_height):
for x in range(walls_width):
if (x, y) in walls: out.write('#')
elif (x, y) in self.food: out.write('.')
else: out.write(' ')
out.write('\n')
out.write('\n')
# print walls and bots
# Do we have bots/enemies sitting on each other?
# assign bots to their positions
bots = {}
for pos in self.enemy:
bots[pos] = bots.get(pos, []) + ['E']
for idx, pos in enumerate(self.bots):
bots[pos] = bots.get(pos, []) + [str(idx)]
# strip all None positions from bots
try:
bots.pop(None)
except KeyError:
pass
while bots:
for y in range(walls_height):
for x in range(walls_width):
if (x, y) in walls: out.write('#')
elif (x, y) in bots:
elem = bots[(x, y)].pop(0)
out.write(elem)
# cleanup
if len(bots[(x, y)]) == 0:
bots.pop((x, y))
else: out.write(' ')
out.write('\n')
out.write('\n')
return out.getvalue()
def __eq__(self, other):
return ((self.walls, self.food, self.bots, self.enemy, self.initial_positions) ==
(other.walls, other.food, other.bots, self.enemy, other.initial_positions))
def create_layout(*layout_strings, food=None, bots=None, enemy=None):
""" Create a layout from layout strings with additional food, bots and enemy positions.
Walls must be equal in all layout strings. Food positions will be collected.
For bots and enemy positions later specifications will overwrite earlier ones.
Raises
======
ValueError
If walls are not equal in all layouts
"""
# layout_strings can be a list of strings or one huge string
# with many layouts after another
layouts = [
load_layout(layout)
for layout_str in layout_strings
for layout in split_layout_str(layout_str)
]
merged = reduce(lambda x, y: x.merge(y), layouts)
additional_layout = Layout(walls=merged.walls, food=food, bots=bots, enemy=enemy)
merged.merge(additional_layout)
return merged
def split_layout_str(layout_str):
""" Turns a layout string containing many layouts into a list
of simple layouts.
"""
out = []
current_layout = []
for row in layout_str.splitlines():
stripped = row.strip()
if not stripped:
# found an empty line
# if we have a current_layout, append it to out
# and reset it
if current_layout:
out.append(current_layout)
current_layout = []
continue
# non-empty line: append to current_layout
current_layout.append(row)
# We still have a current layout at the end: append
if current_layout:
out.append(current_layout)
return ['\n'.join(l) for l in out]
def load_layout(layout_str):
""" Loads a *single* (partial) layout from a string. """
build = []
width = None
height = None
food = []
bots = [None, None]
enemy = []
for row in layout_str.splitlines():
stripped = row.strip()
if not stripped:
continue
if width is not None:
if len(stripped) != width:
raise ValueError("Layout has differing widths.")
width = len(stripped)
build.append(stripped)
height = len(build)
mesh = datamodel.Mesh(width, height, data=list("".join(build)))
# Check that the layout is surrounded with walls
for i in range(width):
if not (mesh[i, 0] == mesh[i, height - 1] == '#'):
raise ValueError("Layout not surrounded with #.")
for j in range(height):
if not (mesh[0, j] == mesh[width - 1, j] == '#'):
raise ValueError("Layout not surrounded with #.")
walls = []
# extract the non-wall values from mesh
for idx, val in mesh.items():
# We know that each val is only one character, so it is
# either wall or something else
if '#' in val:
walls.append(idx)
# free: skip
elif ' ' in val:
continue
# food
elif '.' in val:
food.append(idx)
# other
else:
if 'E' in val:
# We can have several undefined enemies
enemy.append(idx)
elif '0' in val:
bots[0] = idx
elif '1' in val:
bots[1] = idx
else:
raise ValueError("Unknown character %s in maze." % val)
walls = sorted(walls)
return Layout(walls, food, bots, enemy)
|
""" Advanced container classes. """
from collections import Mapping
class Mesh(Mapping):
""" A mapping from a two-dimensional coordinate system into object space.
Using a list of lists to represent a matrix is memory inefficient, slow,
(ugly) and requires much effort to keep all lists the same length. Instead
we store the matrix data in a single list and provide accessor and mutator
methods (`__getitem__()` and `__setitem__()`) to access the elements in a
matrixy style.
Parameters
----------
width : int
desired width for Mesh
height : int
desired height for Mesh
data : list, optional
If given, will try to set this as contents, using the width and height.
May raise a `ValueError` or a `TypeError`, see `_set_data()` for
details.
Attributes
----------
shape : (int, int)
tuple of width and height
Notes
-----
Once the container has been allocated, it cannot be resized.
The container can store arbitrary type objects and even mix types.
The constructor will preallocate a container with an appropriate shape, and
populate this with `None`.
The container cannot be sliced.
The items are stored row-based (C-order).
Since this container inherits from `collections.Mapping` you can use
methods similar to those of the dictionary:
* `keys()`
* `values()`
* `items()`
* `iterkeys()`
* `itervalues()`
* `iteritems()`
The method `_set_data()` is semi-public API. You can use it to modify the
underlying data inside this container if you know what you are doing. The
method has some additional checks for type and length of the new data and
should therefore be safer than just modifying the _data member directly.
Examples
--------
>>> m = Mesh(2, 2)
>>> print m
[None, None]
[None, None]
>>> m[0, 0] = True
>>> m[1, 1] = True
>>> print m
[True, None]
[None, True]
>>> m[0, 1] = 'one'
>>> m[1, 0] = 1
>>> print m
[True, 1]
['one', True]
>>> m.values()
True
1
one
True
>>> m.keys()
[(0, 0), (1, 0), (0, 1), (1, 1)]
"""
def __init__(self, width, height, data=None):
self.width = width
self.height = height
if data:
self._set_data(data)
else:
self._data = [None] * (self.width * self.height)
@property
def shape(self):
""" The shape (width, height) of the Mesh.
Returns
-------
shape : tuple of (int, int)
shape of the Mesh
"""
return (self.width, self.height)
def __contains__(self, index):
return 0 <= index[0] < self.width and 0 <= index[1] < self.height
def _index_linear_to_tuple(self, index_linear):
""" Convert a linear index to a tuple.
Parameters
----------
index_linear : int
index into the underlying list
Returns
-------
index_tuple : tuple of (int, int)
index in two dimensional space (x, y)
"""
x = index_linear % self.width
y = index_linear // self.width
return (x, y)
def _index_tuple_to_linear(self, index_tuple):
""" Convert a tuple index to linear index
Parameters
----------
index_tuple : tuple of (int, int)
index in two dimensional space (x, y)
Returns
-------
index_linear : int
index into the underlying list
Raises
------
KeyError
if the index is not within the range of the Mesh
"""
if index_tuple not in self:
raise KeyError(
'Mesh indexing error, requested coordinate: %r, but size is: (%i, %i)'
% (index_tuple, self.width, self.height))
return index_tuple[0] + index_tuple[1] * self.width
def _set_data(self, new_data):
""" Set the underlying data for this container.
Parameters
----------
new_data : list of appropriate length
the new data
Raises
------
TypeError
if new_data is not a list
ValueError
if new_data has inappropriate length
"""
if not isinstance(new_data, list):
raise TypeError(
'The new_data has the wrong type: %s, ' % type(new_data) +\
'currently only lists are supported.')
if len(new_data) != len(self):
raise ValueError(
'The new_data has wrong length: %i, expected: %i'
% (len(new_data), len(self)))
self._data = new_data
def __getitem__(self, index):
return self._data[self._index_tuple_to_linear(index)]
def __setitem__(self, index, item):
self._data[self._index_tuple_to_linear(index)] = item
def __iter__(self):
return iter(self._index_linear_to_tuple(idx)
for idx in range(len(self)))
def __len__(self):
return self.width * self.height
def __repr__(self):
return ('%s(%i, %i, data=%r)'
% (self.__class__.__name__, self.width, self.height, self._data))
def __str__(self):
output = str()
for i in range(self.height):
start = i * self.width
end = start + self.width
output += str(self._data[start:end])
output += '\n'
return output
def __eq__(self, other):
return (type(self) == type(other) and
self.width == other.width and
self.height == other.height and
self._data == other._data)
def __ne__(self, other):
return not (self == other)
@property
def compact_str(self):
""" Return a compact string representation of the Mesh.
This is useful in case the maze contains components that can be
represented with single character strings. See the following examples
for details.
Non-compact string::
['#', '#', '#', '#', '#', '#']
['#', ' ', ' ', '#', '0', '#']
['#', ' ', '3', ' ', '#', '#']
['#', '2', ' ', ' ', '1', '#']
['#', '#', '#', '#', '#', '#']
Compact string::
######
# #0#
# 3 ##
#2 1#
######
Returns
-------
compact : str
compact string representation
"""
output = str()
for i in range(self.height):
start = i * self.width
end = start + self.width
output += ''.join([str(i) for i in self._data[start:end]])
output += '\n'
return output
def copy(self):
return Mesh(self.width, self.height, list(self._data))
def _to_json_dict(self):
return {"width": self.width,
"height": self.height,
"data": list(self._data)}
@classmethod
def _from_json_dict(cls, item):
return cls(**item)
|
""" Basic graph module """
import heapq
from collections import deque, UserDict
class NoPathException(Exception):
pass
def move_pos(position, move):
""" Adds a position tuple and a move tuple.
Parameters
----------
position : tuple of int (x, y)
current position
move : tuple of int (x, y)
direction vector
Returns
-------
move_pos : tuple of int (x, y)
new position coordinates
"""
pos_x = position[0] + move[0]
pos_y = position[1] + move[1]
return (pos_x, pos_y)
def diff_pos(initial, target):
""" Return the move required to move from one position to another.
Will return the move required to transition from `initial` to `target`. If
`initial` equals `target` this is `stop`.
Parameters
----------
initial : tuple of (int, int)
the starting position
target : tuple of (int, int)
the target position
Returns
-------
move : tuple of (int, int)
the resulting move
"""
return (target[0]-initial[0], target[1]-initial[1])
def manhattan_dist(pos1, pos2):
""" Manhattan distance between two points.
Parameters
----------
pos1 : tuple of (int, int)
the first position
pos2 : tuple of (int, int)
the second position
Returns
-------
manhattan_dist : int
Manhattan distance between two points
"""
return abs(pos1[0]-pos2[0]) + abs(pos1[1]-pos2[1])
def iter_adjacencies(initial, adjacencies_for_pos):
""" Returns an adjacency list starting at the initial positions.
Given some starting positions and a method which returns the adjacencies
per position, we iterate over all reachable positions and their respective
neighbours.
Parameters
----------
initial : list(pos)
List of initial positions
adjacencies_from_pos : callable
Given a position, this function should return all reachable positions.
Returns
-------
adjacency_list : generator of (pos, list(pos))
Generator which contains all reachable positions and their adjacencies
"""
reached = set()
todo = set(initial)
while todo:
pos = todo.pop()
legal_moves = adjacencies_for_pos(pos)
for move in legal_moves:
if move not in reached:
todo.add(move)
reached.add(pos)
yield (pos, legal_moves)
class Graph(UserDict):
""" Adjacency list [1] representation of a Maze.
The `Graph` is mostly a wrapper for a `dict`. Given a position,
it returns the positions reachable from there.
[1] http://en.wikipedia.org/wiki/Adjacency_list
"""
def __init__(self, *args):
super().__init__()
if len(args) == 1:
adjacencies = args[0]
self.update(adjacencies)
return
initial, maze = args
def legal_neighbors(maze, pos):
neighbor_moves = [(-1, 0), (1, 0), (0, 1), (0, -1)]
legal = []
for move in neighbor_moves:
neighbor = move_pos(pos, move)
if neighbor not in maze:
# this is not a wall
legal.append(neighbor)
return legal
self.update(it for it in iter_adjacencies([initial], lambda pos: legal_neighbors(maze, pos)))
def __copy__(self):
# needed to override the default __copy__ dict implementation and to
# return a Graph instance
return self.__class__(self.data)
def pos_within(self, position, distance):
""" Positions within a certain distance.
Calculates all positions within a certain distance of a target
`position` in maze space. Within means strictly less than (`<`) in this
case.
Parameters
----------
position : tuple of (int, int)
the first position
distance : int
the distance in maze space
Returns
-------
pos_within : set of tuple of (int, int)
the positions within the given distance
Raises
------
NoPathException
if `position` does not exist in the adjacency list
"""
self._check_pos_exist([position])
positions = set([position])
to_visit = [position]
for i in range(distance):
local_to_visit = []
for pos in to_visit:
if pos not in positions:
positions.add(pos)
local_to_visit.extend(self[pos])
to_visit = local_to_visit
return positions
def _check_pos_exist(self, positions):
for pos in positions:
if pos not in self.keys():
raise NoPathException("Position %s does not exist in adjacency list." %
repr(pos))
def bfs(self, initial, targets):
""" Breadth first search (bfs).
Breadth first search [1] from one position to multiple targets. The
search will return a path from the `initial` position to the closest
position in `targets`.
Parameters
----------
initial : tuple of (int, int)
the first position
targets : list of tuple of (int, int)
the target positions
Returns
-------
path : lits of tuple of (int, int)
the path from `initial` to the closest `target`
Raises
------
NoPathException
if no path from `initial` to one of `targets`
NoPositionException
if either `initial` or `targets` does not exist
[1] http://en.wikipedia.org/wiki/Breadth-first_search
"""
# First check that the arguments were valid.
self._check_pos_exist([initial] + targets)
# Initialise `to_visit` of type `deque` with current position.
# We use a `deque` since we need to extend to the right
# but pop from the left, i.e. its a fifo queue.
to_visit = deque([initial])
# `seen` is a list of nodes we have seen already
# We append to right and later pop from right, so a list will do.
# Order is important for the back-track later on, so don't use a set.
seen = []
found = False
while to_visit:
current = to_visit.popleft()
if current in seen:
# This node has been seen, ignore it.
continue
elif current in targets:
# We found some food, break and back-track path.
found = True
break
else:
# Otherwise keep going, i.e. add adjacent nodes to seen list.
seen.append(current)
to_visit.extend(self[current])
# if we did not find any of the targets, raise an Exception
if not found:
raise NoPathException("BFS: No path from %r to %r."
% (initial, targets))
# Now back-track using seen to determine how we got here.
# Initialise the path with current node, i.e. position of food.
path = [current]
while seen:
# Pop the latest node in seen
next_ = seen.pop()
# If that's adjacent to the current node
# it's in the path
if next_ in self[current]:
# So add it to the path
path.append(next_)
# And continue back-tracking from there
current = next_
# The last element is the current position, we don't need that in our
# path, so don't include it.
return path[:-1]
def a_star(self, initial, target):
""" A* search.
A* (A Star) [1] from one position to another. The search will return the
shortest path from the `initial` position to the `target` using the
Manhattan distance as a heuristic.
Algorithm here is partially taken from [2] and inlined for speed.
Parameters
----------
initial : (int, int)
the initial position
target : (int, int)
the target position
Returns
-------
path : list of (int, int)
one of the the shortest paths from `initial` to the closest `target`
(excluding the `initial` position itself)
Raises
------
NoPathException
if no path from `initial` to one of `targets`
[1] http://en.wikipedia.org/wiki/A*_search_algorithm
[2] http://www.redblobgames.com/pathfinding/a-star/implementation.html#python
"""
# First check that the arguments were valid.
self._check_pos_exist([initial, target])
# Initialize the dicts that help us keep track
came_from = {}
cost_so_far = {}
came_from[initial] = None
cost_so_far[initial] = 0
# Since it’s A* we use a heap queue to ensure that we always get the next node
# with to lowest *guesstimated* distance to the current node.
to_visit = []
heapq.heappush(to_visit, (0, initial))
while to_visit:
old_prio, current = heapq.heappop(to_visit)
if current == target:
break
for next in self[current]:
new_cost = cost_so_far[current] + 1 # 1 is the cost to the neighbor
if next not in cost_so_far or new_cost < cost_so_far[next]: # only choose unvisited and ‘worthy’ nodes
cost_so_far[next] = new_cost
came_from[next] = current
# Add the node with an estimated distance to the heap
priority = new_cost + manhattan_dist(target, next)
heapq.heappush(to_visit, (priority, next))
else:
# no target found
raise NoPathException("a_star: No path from %r to %r." % (initial, target))
# Now back-track using seen to determine how we got here.
# Initialise the path with current node, i.e. position of food.
current = target
path = [current]
while current != initial:
current = came_from[current]
path.append(current)
# The last element is the current position, we don’t need that in our
# path, so don’t include it.
return path[:-1]
|
#!/usr/bin/env python3
import itertools
import random
def initial_state(teams):
rr = []
for pair in itertools.combinations(teams, 2):
match = list(pair)
random.shuffle(match)
rr.append(tuple(match))
# shuffle the matches for more fun
random.shuffle(rr)
return rr
# def round_robin(state, teams):
# if not state:
# state = initial_state
|
import pygame
from time import *
from helper import *
from introFunctions import *
#start menu
running = startMenu()
#main game loop begins
while running:
#Draw #screen.fill(BG) #Background
background(season(day))
statBar(day, age, money, exp,jobs[jobIndex]) #stats
#conditional buttons#
colour = hovering(school, pygame.mouse.get_pos())
if age <= 18:
createButton("School", colour, schoolX, schoolY, button1X, button1Y)
elif not educated:
createButton("", colour, schoolX, schoolY, button1X, button1Y)
screen.blit(schoolText,(schoolX + button1X // 8, schoolY + button1Y // 4))
screen.blit(schoolText2,(schoolX + button1X // 8, schoolY + button1Y // 4 + 25))
screen.blit(schoolText3,(schoolX + button1X // 8, schoolY + button1Y // 4 + 50))
if exp >= jobExps[1]:
colour = hovering(jobOffer,pygame.mouse.get_pos())
createButton("Job Offer", colour, jobOfferX, jobOfferY, button2X,button2Y)
jobTitle = myFont.render(jobs[jobIndex+1],1,BLACK) #change title depending on exp
screen.blit(jobTitle,(jobOfferX + button1X // 2, jobOfferY + button1Y // 4+25))
#constant button #check hovered
colour = hovering(work, pygame.mouse.get_pos())
createButton("Work", colour, workX, workY, button1X, button1Y)
pygame.display.flip() #actually draw
#collect player action
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False #quit if player wants
if event.type == pygame.MOUSEBUTTONDOWN: #collect clicked coords
buttonClick = pygame.mouse.get_pressed() #check what button
mouse_pos = event.pos
#check collisions on buttons
#work button click
if work.collidepoint(mouse_pos) and buttonClick[0] ==1:
#print('work')
buttonPressed(mouse_pos, workX, workY, button1X, button1Y)
money += pay(jobWages,jobIndex, workHour, mouse_pos)
exp += jobExpFactors[jobIndex]
click = True
#school button click
if age <= 18 and school.collidepoint(mouse_pos)and buttonClick[0] ==1:
#print('School')
buttonPressed(mouse_pos, schoolX, schoolY, button1X, button1Y)
exp += learnExp
click = True
elif school.collidepoint(mouse_pos)and buttonClick[0] ==1 and not educated:
#print('educated')#post secondary
createButton("", GREEN, schoolX, schoolY, button1X,button1Y)
educated, age, money, exp = education(age,money,exp,schoolCost, schoolExp)
click = True
#job offer to level up when enough exp
if exp >= jobExps[1] and jobOffer.collidepoint(mouse_pos) and buttonClick[0] ==1:
#print('applied')
del jobExps[0] #dont need anymore
jobIndex += 1 #update job
createButton("", GREEN, jobOfferX, jobOfferY,button2X, button2Y)
click = True
if click == True: #check if any button pressed to update stats
time.sleep(0.1)
day, age, money, exp = timePass(day, age, money, exp, intrest)
click = False
clock.tick(60)
pygame.display.flip()#draw changes
#print(day, age, money, exp) #temporary
#end game screen?
pygame.quit()#end of program |
""" How many connected components result after performing the following sequence of union operations on a set of 1010
items? 1–2 3–4 5–6 7–8 7–9 2–8 0–5 1–9 """
def dynamic_connectivity():
# input_list = [(1, 2), (3, 4), (5, 6), (7, 8), (7, 9), (2, 8), (0, 5), (1, 9)]
input_list = [(1, 2), (4, 5)]
x = input_list[0][0]
print(x)
y = input_list[0][1]
print(y)
connections = 0
total = []
for item in input_list:
if (item[0] == x + 1 or item[0] == x - 1) or (item[0] == y + 1 or item[0] == y - 1) \
or (item[1] == x + 1 or item[1] == x - 1) or (item[1] == y + 1 or item[1] == y - 1):
connections += 1
print('checked_in', connections)
else:
pass
total.append(connections + 1)
grand_total = len(total)
print(total)
print(grand_total)
dynamic_connectivity()
|
# Given an integer n, return True if n is within 10 of either 100 or 200
def almost_there(input_int):
check_1 = 100
check_2 = 200
if input_int > check_1-10 and input_int < check_1+10:
return True
elif input_int > check_2-10 and input_int < check_2+10:
return True
else:
return False
print(almost_there(210))
|
"""
Write a function, that reads an array of strings which will represent a list of comma-separated numbers sorted in
ascending order, the second element will represent a second list of comma-separated numbers(also sorted). Your goal is
to return a string of numbers that occur in both elements of the input array in sorted order. If there is no
intersection, return the string 'false'.
For example: if the input array is ['1, 3, 4, 7, 13', '1, 2, 4, 13, 15'] the output string should be '1, 4, 13' because
those number appear in both strings. The array given will not be empty, and each string inside the array will be of
numbers sorted in ascending order and may contain negative numbers.
"""
# SOLUTION-1 : BRUTE FORCE
import array as arr
def find_intersection(input_arr1, input_arr2):
input_array1 = arr.array('u', input_arr1)
input_array2 = arr.array('u', input_arr2)
print(input_array1)
print(input_array2)
input_array1_list = list
find_intersection('1, 3, 4, 7, 13', '1, 2, 4, 13, 15')
|
# -*-coding:utf-8-*-
__author__ = "pawpawDu"
# 60 sec/min,60min/hr,24hr/day
#oython外壳:代码结构
import time
print time.timezone
print time.localtime()
alphabet = ""
alphabet +="abdc"
alphabet +="efgj"
print(alphabet)
#使用\连接,仍是一行
alphabet = "abcd"+\
"efjk"+\
"QEWQEQ"+\
"ddf"
print alphabet
#4.3使用if elif else
#单值真假输入:0,1
#print("请输入:True or False")
#disaster = input()#输入参数:False假,输入数字或布尔值0,1
disaster = 1
if disaster:
print "正确的选择!"
else:
print "错误的选择!"
print disaster
#多层嵌套
#双值,4中关系,00,01,10,11
furry = False
small = True
if furry:
if small:
print ("11,it's a cat.")
else:
print ("10,it' a bear")
else:
if small:
print ("01,it's a skink")
else:
print ("00,it's a human ,or a hairless bear")
#三个条件以上的判定if\elif \else
color ="puce"
if color == "red":
print "it's a tomato"
elif color=="green":
print "it's a grenn pepper"
elif color =="bee purple":
print "I don't what it is ,but only bees can see it "
else:
print "I've never heard of the color",color
#4.4 while循环
#从1打印至5
count =1
while count <=5:
print count
count +=1
|
from tkinter import *
import time
import string
class Menu_game(Tk):
def __init__(self):
Tk.__init__(self)
self.geometry("500x500")
self.iconbitmap("Pythonsignev.ico")
self.title("Game for Bdouilleurs")
self.config(background='#3FAC17')
self.resizable(width=False, height=False)
self.create_text_button()
def create_text_button(self):
self.text = Label(self, text = 'Welcome, \n wich level would you play ?', bg='#3FAC17', font=('Impossible', 20))
self.button_level1 = Button(self, text='Level 1', bg='#3FAC17', font=('Impossible', 20))
self.text.pack()
self.button_level1.pack()
# can = tk.Canvas(win, width=500, height=500, bg='#3FAC17')
# text = can.create_text(50, 50, text='Hello', font=('Impossible', 30), fill='white')
#can.pack()
menu = Menu_game()
menu.mainloop()
|
current_users = ['Yuva','Ravi','basha','Sahil','Lakshman']
new_users = ['sahil','ravi','aravind','pankaj','santosh']
existing_users = [value.lower() for value in current_users]
for new_user in new_users:
if new_user.lower() in existing_users:
print("user name had already taken, enter a new user name")
else:
print("user name available")
|
#time complexity:O(n)
#SC:O(1)
#Algo://At each step I need to find the leftmax and rightmax. Then I need to pick minimum of them and add their difference between them and the corresponding left or right element and add it to the count. This is because the water can be trapped upto the height of the minimum of two pillars.
class Solution:
def trap(self, height: List[int]) -> int:
l=0
r=len(height)-1
leftmax=0
rightmax=0
if len(height)==0:
return 0
amount=0
while l<r:
leftmax=max(height[l],leftmax)
rightmax=max(height[r],rightmax)
if leftmax<rightmax:
amount+=leftmax-height[l]
l+=1
else:
amount+=rightmax-height[r]
r-=1
return amount
|
from enum import Enum
class ConstraintType(Enum):
"""
ConstraintType is a callable Enum for use in the integer programming solver.
"""
@staticmethod
def __eq(x, y):
return x == y
@staticmethod
def __leq(x, y):
return x <= y
@staticmethod
def __less(x, y):
return x < y
@staticmethod
def __geq(x, y):
return x >= y
@staticmethod
def __grtr(x, y):
return x > y
@staticmethod
def __neq(x, y):
return x != y
@staticmethod
def __am1(x, y):
return x + y <= 1
@staticmethod
def __ex1(x, y):
return x + y == 1
EQ = __eq
LEQ = __leq
LESS = __less
GEQ = __geq
GRTR = __grtr
NEQ = __neq
AM1 = __am1
EX1 = __ex1
def __call__(self, *args):
return self.value(*args)
|
#
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers_1(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = ListNode(0)
while(l1 and l2):
r = l1.val + l2.val
if(r < 10):
ans.val = r
ans.next = self.addTwoNumbers(l1.next, l2.next)
return ans
else:
ans.val = r - 10
l1.next = self.addTwoNumbers(l1.next,ListNode(1))
ans.next = self.addTwoNumbers(l1.next, l2.next)
return ans
if(l1):
return l1
if(l2):
return l2
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = ListNode(0)
re = ans
carry = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = carry + x + y
carry = sum // 10
re.next = ListNode(sum % 10)
re = re.next
if l1 : l1 = l1.next
if l2 : l2 = l2.next
if carry > 0:
re.next = ListNode(1)
return ans.next
|
# -*- coding: UTF-8 -*-
import time
# Conditions / recursif
def f_Meg_recur(a,b,c=0):
if b == 0 :
return c
else :
if b%2 == 0:
return f_Meg_recur(2*a,b/2,c)
else:
return f_Meg_recur(a,b-1,c+a)
# Conditions / Iteratif
def f_Meg_iter(a,b):
c=0
while b != 0 :
if b%2 == 0:
a=2*a
b=b/2
else :
b = b-1
c = c+a
return c
# Equation / Recursif
def s_Meg_recur(a,b,c=0):
if b == 0 :
return c
else :
return int(s_Meg_recur(a*(2-b%2),(b-b%2)/(2-b%2),c + a*(b%2)))
# Equation / Iteratif
def s_Meg_iter(a,b):
c=0
while b != 0 :
c = c + a*(b%2)
a = a*(2-b%2)
b = (b-b%2)/(2-b%2)
return int(c)
# fonction de test
def Test():
#Definition de a et b
a=2016
b=1337
#init des variables de temps cumulé
t_s_Meg_iter=0
t_s_Meg_recur=0
t_f_Meg_iter=0
t_f_Meg_recur=0
#Definition du nombre de run
run=10
#definition du nombre de cycles / run
Cycles=100000
#boucles de test
for i in range(run):
print('-----')
t0=time.time()
for t in range(Cycles):
s_Meg_iter(a,b)
t1=time.time()-t0
print('s_meg_iter ', i ," : ", t1 ,' Secondes')
t_s_Meg_iter+=t1
t0=time.time()
for t in range(Cycles):
s_Meg_recur(a,b)
t1=time.time()-t0
print('s_Meg_recur ', i ," : ", t1 ,' Secondes')
t_s_Meg_recur+=t1
t0=time.time()
for t in range(Cycles):
f_Meg_iter(a,b)
t1=time.time()-t0
print('f_Meg_iter ', i ," : ", t1 ,' Secondes')
t_f_Meg_iter+=t1
t0=time.time()
for t in range(Cycles):
f_Meg_recur(a,b)
t1=time.time()-t0
print('f_Meg_recur ', i ," : ", t1 ,' Secondes')
t_f_Meg_recur+=t1
# Print des temps totaux
print('~~~~~~~~~~~~~')
print('Total s_meg_iter : ', t_s_Meg_iter ,' Secondes')
print('Total s_Meg_recur : ', t_s_Meg_recur ,' Secondes')
print('Total f_Meg_iter : ', t_f_Meg_iter ,' Secondes')
print('Total f_Meg_recur : ', t_f_Meg_recur ,' Secondes')
print('~~~~~~~~~~~~~')
# lance le test
Test() |
"""
Advent 2020
Mission 6 Part 2:
The point of this mission is to count every different caracter into different group seperate by empty line
and sum all the count to get the answer.
"""
file = open("input.txt").read().split("\n\n")
file = [i.splitlines() for i in file]
rep = 0
first = []
for x in range(len(file)):
rep += len(first)
first = []
main = []
count = 0
for y in file[x]:
main.append(set(y))
for k in range(len(main)):
if count == 0:
first = main[k]
count += 1
else:
first = first.intersection(main[k])
print(rep)
|
class Dog:
def __init__(self,breed,color): # "self" is the brain of the object
self.breed=breed
self.color=color
def speak(self):
print("bhou...bhou")
def jump(self):
print("I am jumping")
def __del__(self):
print("Good Bye!")
tommy=Dog("german shepherd","brown")
tommy.speak()
tommy.jump()
print(tommy.breed)
print(tommy.color)
|
def get_indices(word,char):
indices = []
for index,letter in enumerate(word):
if letter == char:
indices.append(index)
return indices
print(get_indices("banana","a")) |
#!/usr/bin/python
import sys
# Open a file
input = open(sys.argv[1], "r+")
valid_tri_count = 0;
for line in input:
#print line
s1 = line[:5].strip()
s2 = line[5:10].strip()
s3 = line[10:15].strip()
if int(s1) + int(s2) > int(s3) and int(s1) + int(s3) > int(s2) and int(s2) + int(s3) > int(s1):
valid_tri_count += 1
# Close opend file
input.close()
print "Valid triangles = {}".format(valid_tri_count)
# 869 - first answer
|
"""
Boucle "for" va au suivant à chaque tour,
Boucle "while" on doit indiquer l'incrément de chacun des tours
exemple -->
"""
sequence = range(10, 20)
print("for") #ici le i est optionnel et ne sert qu'à l'affichage
i = 0
for elt in sequence: #elt = element
print(i, elt, sep = "->")
i += 1
print("while") #ici le i est essentiel
i = 0 # i = index
while i < len(sequence):
print(i, sequence[i], sep = "->")
i += 1
i = 0
while i < len(sequence): #s'assurer que l'on peut sortir de la boucle, pas de boucle infinie
if i % 2 == 0:
print("nombre pair")
print(sequence[i])
i += 1
else:
print(sequence[i])
i +=2
"""
Exercice:
Écrire un script Python qui indique le nombre de fois qu’apparait
chaque entier d’une liste d’entiers saisie au clavier (une seule saisie).
"""
saisie = input("Entrez une série de nombre : ")
listEntier = []
for i in range(0, len(saisie)):
a = saisie[i]
for j in range(0, len(listEntier)):
if a == listEntier[j]:
a = 0
elif a == " ":
a = 0
if a != 0:
listEntier += [a]
for i in range(0, len(listEntier)):
print(listEntier[i], saisie.count(listEntier[i]))
"""
Solution professeur
+
déterminer si une liste contient seulement des entiers
"""
# Validation
erreur = False
i = 0
while erreur == False and i < len(saisie):
if "0" <= saisie[i] <= "9":
n = 1
i += 1
print("nombre valide", saisie[i-1])
elif saisie[i] == " ":
i += 1
print("C'est un séparateur")
else:
erreur = True
print("ce n'est pas un nombre", saisie[i])
if erreur == True:
quit()
#entiers = input("Mes entiers: ")
listeEntiers = saisie.split(" ")
dict = {}
for entier in listeEntiers:
if entier in dict:
dict[entier] += 1
else:
dict[entier] = 1
for cle,valeur in dict.items():
print(cle, ":", valeur)
print(dict.items())
"""
Matrice et dictionnaire
"""
Mat = matrice[(1,2)]
for i in range(5): #Jcomprend pas vraiment cet exemple à revoir
for j in range(5):
matrice[(i,j)] = 0
|
"""
Definitions of each of the different chess pieces.
"""
from abc import ABC, abstractmethod
from chessington.engine.data import Player, Square
class Piece(ABC):
"""
An abstract base class from which all pieces inherit.
"""
def __init__(self, player):
self.player = player
@abstractmethod
def get_available_moves(self, board):
"""
Get all squares that the piece is allowed to move to.
"""
pass
def move_to(self, board, new_square):
"""
Move this piece to the given square on the board.
"""
current_square = board.find_piece(self)
board.move_piece(current_square, new_square)
class Pawn(Piece):
"""
A class representing a chess pawn.
"""
def get_available_moves(self, board):
position = board.find_piece(self)
piece = board.get_piece(position)
moves = []
if piece.player == Player.WHITE:
direction = 1
start_row = 1
elif piece.player == Player.BLACK:
direction = -1
start_row = 6
move = Square.at(position.row + direction, position.col)
if board.check_square_is_available(move):
moves.append(move)
if position.row == start_row:
move = Square.at(position.row + 2 * direction, position.col)
if board.check_square_is_available(move):
moves.append(move)
capture_moves = [
Square.at(position.row + direction, position.col + direction),
Square.at(position.row + direction, position.col - direction)
]
for move in capture_moves:
if board.check_square_has_opponent_piece(move, piece.player):
moves.append(move)
return moves
class Knight(Piece):
"""
A class representing a chess knight.
"""
def get_available_moves(self, board):
return []
class Bishop(Piece):
"""
A class representing a chess bishop.
"""
def get_available_moves(self, board):
return []
class Rook(Piece):
"""
A class representing a chess rook.
"""
def get_available_moves(self, board):
return []
class Queen(Piece):
"""
A class representing a chess queen.
"""
def get_available_moves(self, board):
return []
class King(Piece):
"""
A class representing a chess king.
"""
def get_available_moves(self, board):
position = board.find_piece(self)
piece = board.get_piece(position)
directions = [-1, 0, 1]
moves = []
for i in directions:
for j in directions:
move = Square.at(position.row + i, position.col + j)
if (board.check_square_is_available(move) or
board.check_square_has_opponent_piece(move, piece.player)):
moves.append(move)
return moves
|
from collections import deque
def BFS(graph,root):
visited = []
queue = deque([root])
while queue:
n = queue.popleft()
if n not in visited:
visited.append(n)
queue += graph[n] - set(visited)
return visited
graph_list = {1:set([3,4]),
2:set([3,4,5]),
3:set([1,5]),
4:set([1]),
5:set([2,6]),
6:set([3,5])
}
root_node = 1
k = BFS(graph_list,root_node)
print(" ".join(str(i) for i in k))
def BFS_N(graph,root,visited):
queue = deque([root])
visited[root] = True
while queue:
n = queue.popleft()
print(n, end=' ')
for i in graph[n]:
if not visited[i]:
queue.append(i)
visited[i] = True
visited = [False] * 9
graph_list = [[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7]
]
BFS_N(graph_list,1,visited)
|
nome = input("Seu nome:")
print ("Olá", nome)
resposta = (str(input("Tudo bem com você ?, S/N:")))
if resposta == 'N' or resposta == 'n':
resposta2 = input("Porque você não se sente bem?:")
print ("Vai ficar tudo bem, não se preocupe com ", resposta2)
else: print ("Que bom que você se sente bem,",nome)
|
# Simple Linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
#Splitting the datasets into train 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)
#Fitting simple linear regression to the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,y_train)
#Predicting the test set
y_pred = regressor.predict(X_test)
print(regressor.coef_)
#Visualizing the Test set results
plt.scatter(X_test,y_test,color='red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title("Salary Vs Experience (Training set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show() |
'''
Bubble sort.
Reference: https://medium.com/@george.seif94/a-tour-of-the-top-5-sorting-algorithms-with-python-code-43ea9aa02889
Written by Junzheng
1/13/2020
'''
def bubble_sort(list_to_sort):
swapped = True
while swapped:
length = len(list_to_sort)
swapped = False
for i in range(length - 1):
if list_to_sort[i] > list_to_sort[i + 1]:
list_to_sort[i], list_to_sort[i + 1] = list_to_sort[i + 1], list_to_sort[i]
swapped = True
return list_to_sort
|
# The answer for the question is in code using Separator to highlight.
# just like this
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
'''
what I did here is that I calculate all the possible probability in each
round for each team. So if I have all the probability, I could do any
questions, just limited by time.
By the way, all possible results is stored in a 4*16*16*8 matrixs
as for 4 round * 16 teams * 16 teams (against with each other) * 8
outcomes (wins in 4,5,6,7 games, and the winner could be either)
'''
import numpy as np
from random import random
from openpyxl import load_workbook, Workbook
import matplotlib.pyplot as plt
wb = load_workbook(filename = 'win_probabilities.xlsx')
ws = wb['win_probabilities.csv']
wins = np.ndarray(shape=(16,16), dtype=float)
for i in range(16):
for j in range(16):
wins[i][j] = 0.0
i = 1
# west team will have small numbers
while i < len(ws['A']):
if ws['A'][i].value[0] == 'W':
home = int(ws['A'][i].value[4]) - 1
else:
home = int(ws['A'][i].value[4]) + 7
if ws['B'][i].value[0] == 'W':
away = int(ws['B'][i].value[4]) - 1
else:
away = int(ws['B'][i].value[4]) + 7
wins[home][away] = ws['C'][i].value
wins[away][home] = 1-ws['D'][i].value
i += 1
wb = load_workbook(filename = 'Business-Track-Application-Datasets.xlsx')
ws = wb['Hypothetical Playoff Gate Data']
rev = np.ndarray(shape=(16,4), dtype=float)
for i in range(3, 19):
for j in range(2, 6):
if i >= 11:
k = i - 8
else:
k = i + 8
rev[k-3][j-2] = ws[i][j].value
def t2wins8(ph, pa):
pa = 1 - pa
w4 = ph**2 * pa**2
w5 = (2*ph*(1-ph)*pa**2+2*ph**2*pa*(1-pa))*ph
w6 = (3*ph*(1-ph)**2*pa**2+ph**3*(1-pa)**2+3*2*ph**2*(1-ph)*pa*(1-pa))*pa
w7 = ((1-ph)**3*pa**3
+ ph**3*(1-pa)**3
+ 9*ph**2*(1-ph)*pa*(1-pa)**2
+ 9*ph*(1-ph)**2*pa**2*(1-pa)) * ph
ph, pa = 1-ph, 1-pa
l4 = ph**2 * pa**2
l5 = (2*ph*(1-ph)*pa**2+2*ph**2*pa*(1-pa))*ph
l6 = (3*ph*(1-ph)**2*pa**2+ph**3*(1-pa)**2+3*2*ph**2*(1-ph)*pa*(1-pa))*pa
l7 = ((1-ph)**3*pa**3
+ ph**3*(1-pa)**3
+ 9*ph**2*(1-ph)*pa*(1-pa)**2
+ 9*ph*(1-ph)**2*pa**2*(1-pa)) * ph
return [w4, w5, w6, w7, l4, l5, l6, l7]
# get a op[i][j]
# it stores the teams that in i round the team j probably will against with
from copy import deepcopy
i = 0
op = []
a0 = []
for j in range(8):
a0.append([7-j])
for j in range(8):
a0.append([15-j])
op.append(a0)
a1 = [[3,4],[2,5],[1,6],[0,7],[0,7],[1,6],[2,5],[3,4]]
b1 = deepcopy(a1)
for i in range(8):
for j in range(2):
b1[i][j] = a1[i][j] + 8
for ele in b1:
a1.append(ele)
op.append(a1)
a2 = [[1,2,5,6],[0,3,4,7],[0,3,4,7],[1,2,5,6],[1,2,5,6],[0,3,4,7],[0,3,4,7],[1,2,5,6]]
b2 = deepcopy(a2)
for i in range(8):
for j in range(4):
b2[i][j] = a2[i][j] + 8
for ele in b2:
a2.append(ele)
op.append(a2)
a3 = [[8,9,10,11,12,13,14,15],[8,9,10,11,12,13,14,15],[8,9,10,11,12,13,14,15],[8,9,10,11,12,13,14,15],[8,9,10,11,12,13,14,15],[8,9,10,11,12,13,14,15],[8,9,10,11,12,13,14,15],[8,9,10,11,12,13,14,15]]
b3 = deepcopy(a3)
for i in range(8):
for j in range(8):
b3[i][j] = a3[i][j] - 8
for ele in b3:
a3.append(ele)
op.append(a3)
# init
round_results = np.ndarray(shape=(4,16,16,8), dtype=float)
enter_pro = np.ndarray(shape=(4,16), dtype=float)
for i in range(4):
for ii in range(16):
for iii in range(16):
for iiii in range(8):
round_results[i,ii,iii,iiii] = 0.0
for i in range(4):
for ii in range(16):
enter_pro[i,ii] = 0.0
for ii in range(16):
enter_pro[0,ii] = 1.0
# calculate all the possible results in each round for each team
for i in range(4):
for ii in range(16):
for iii in op[i][ii]:
if not((iii < ii and ii < 8) or (iii >= 8 and ii > iii) or (iii + 8 < ii)):
round_results[i,ii,iii] = (t2wins8(wins[ii][iii],wins[iii][ii]))
for iiii in range(8):
round_results[i,ii,iii,iiii] = round_results[i,ii,iii,iiii] * enter_pro[i][ii] * enter_pro[i][iii]
if i == 3:
break
for ii in range(16):
for iii in range(16):
for iiii in range(4):
if not((iii < ii and ii < 8) or (iii >= 8 and ii > iii) or (iii + 8 < ii)):
enter_pro[i+1][ii] += round_results[i,ii,iii,iiii]
else:
enter_pro[i+1][ii] += round_results[i,iii,ii,iiii+4]
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
# 0 8 meet in final probablity is :
# p = enter_pro[3][0] * enter_pro[3][8]
# 0 8 meet in finals
round_results = np.ndarray(shape=(4,16,16,8), dtype=float)
enter_pro = np.ndarray(shape=(4,16), dtype=float)
for i in range(4):
for ii in range(16):
for iii in range(16):
for iiii in range(8):
round_results[i,ii,iii,iiii] = 0.0
for i in range(4):
for ii in range(16):
enter_pro[i,ii] = 0.0
for ii in range(16):
enter_pro[0,ii] = 1.0
for i in range(3):
for ii in range(16):
for iii in op[i][ii]:
if not((iii < ii and ii < 8) or (iii >= 8 and ii > iii) or (iii + 8 < ii)):
round_results[i,ii,iii] = (t2wins8(wins[ii][iii],wins[iii][ii]))
if ii==0 or ii==8:
sums = 0
for iiii in range(4):
sums += round_results[i,ii,iii,iiii]
for iiii in range(4):
round_results[i,ii,iii,iiii] = round_results[i,ii,iii,iiii] / sums
for iiii in range(4):
round_results[i,ii,iii,iiii+4] = 0.0
for iiii in range(8):
round_results[i,ii,iii,iiii] = round_results[i,ii,iii,iiii] * enter_pro[i][ii] * enter_pro[i][iii]
for ii in range(16):
for iii in range(16):
for iiii in range(4):
if not((iii < ii and ii < 8) or (iii >= 8 and ii > iii) or (iii + 8 < ii)):
enter_pro[i+1][ii] += round_results[i,ii,iii,iiii]
else:
enter_pro[i+1][ii] += round_results[i,iii,ii,iiii+4]
for i in range(3,4):
for ii in range(16):
for iii in op[i][ii]:
if not((iii < ii and ii < 8) or (iii >= 8 and ii > iii) or (iii + 8 < ii)):
round_results[i,ii,iii] = (t2wins8(wins[ii][iii],wins[iii][ii]))
for iiii in range(8):
round_results[i,ii,iii,iiii] = round_results[i,ii,iii,iiii] * enter_pro[i][ii] * enter_pro[i][iii]
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
# this is the total revenue when East1 meets West1 in the finals
total = 0
for i in range(4):
for ii in range(16):
for iii in range(16):
if iii > ii:
w4 = round_results[i,ii,iii,0] + round_results[i,ii,iii,4]
w5 = round_results[i,ii,iii,1] + round_results[i,ii,iii,5]
w6 = round_results[i,ii,iii,2] + round_results[i,ii,iii,6]
w7 = round_results[i,ii,iii,7] + round_results[i,ii,iii,7]
r4 = w4 * (2*rev[ii][i]+2*rev[iii][i])
r5 = w5 * (3*rev[ii][i]+2*rev[iii][i])
r6 = w6 * (3*rev[ii][i]+3*rev[iii][i])
r7 = w7 * (4*rev[ii][i]+4*rev[iii][i])
total = total + r4 + r5 + r6 + r7
#
#total
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------
'''
Due to time limits, I could not write the answer for the last two
questions, it is too complicated. However, I could give my idea.
From what we did above, we get all the possible results from the
teams. And we can make change who wins or lose, when it is necessary.
So if we want to know W1 doesn’t meet E1, I could calculate the
probability that W1 lose in the first round, but W1 wins in the
first round. And let W1 loses and E1 wins so that I could get a
expected revenue in this situation. So I could have one probability
and the expected revenue of that probability.
So we now need 8 more. They are:
W1 wins in 1st round, not E1.
W1 lose in 1st round, and E1.
Both wins in 1st round, W1 lose in 2nd, not E1
Both wins in 1st round, E1 lose in 2nd, not w1
Both wins in 1st round, both lose in 2nd
Both wins in 1st round, both wins in 2st round, W1 lose in 3rd, not E1
Both wins in 1st round, both wins in 2st round, E1 lose in 3rd, not W1
Both wins in 1st round, both wins in 2st round, both lose in 3rd
I could have all the probability and expected revenue of them. So I
could calculate the results.
As for how E5 defeat E4 in the 1st round will change the result. I just
simply need to change that game to a certain case, the rest will be the
same.
'''
|
#!/usr/bin/python
def search(searched,N):
cnt =0
if len(searched) == N+1:
return 1
dir = [[0,1],[0,-1],[1,0],[-1,0]]
for i in range(len(dir)):
next_pos = [searched[-1][0]+dir[i][0],searched[-1][1]+dir[i][1]]
if next_pos not in searched:
print(searched+[next_pos])
cnt = cnt + search(searched+[next_pos],N)
return cnt
if __name__ == '__main__':
print(search([[0, 0]], 2)) |
##"""First programm"""
##s= 'Nisl scelerisque justo per hac cras purus lectus maecenas litora facilisi potenti.'
##if len(s)%2 == 0:
## print("Symbols amount is chetnoe")
##else: print("Symbols amount is nechetnoe")
"""The 2 program"""
##i = True
##num = str([0,2,4,6,8])
##s1 = input("Enter the value\n")
##while i == True:
## if len(s1)!= 10:
## print("The string has not 10 symbols")
## s1 = input("Enter the value\n")
## if len(s1)== 10:
## for i in range(0, len(s1)):
## if i%2 == 0 and s1[i] in num and i+1%2 ==1 and (s1[i].isalpha s1[i] not in num):
## print("String has correct format"))
##"""The 3 program"""
##res = []
##s1 = input("Enter the value\n")
##a = s1[-1]
##for i in range(0,len(s1)):
## if s1[i] == a:
## res.append(i)
##print(res)
##"""The 4 program"""
##x_list=[]
##y_list=[]
##s1 = input("Enter the value\n")
##for i in range(0,len(s1)):
## if s1[i] == "x":
## x_list.append(i)
## elif s1[i] == "y":
## y_list.append(i)
##if len(x_list)>0 and len(y_list)>0:
## xmin = min(x_list)
## ymin = min(y_list)
## if xmin>ymin:
## print("The y value is first")
## elif xmin<ymin:
## print("The x value is first")
##if len(x_list) == 0 and len(y_list)>0:
## print("There is no x in the list. The y value is first")
##elif len(y_list) == 0 and len(x_list)>0:
## print("There is no y in the list. The x value is first")
##else:print("There are no x and y values")
"""fifth programm"""
##s = input("Enter symbols\n")
##if len(s)> 10:
## s = s[:6]
##else:
## while len(s)<12:
## s = s+'o'
##''.join(s)
##print(s)
##
##"""sixth programm"""
##s = input("Enter symbols\n")
##counter = 0
##for i in s:
## if i == " ":
## counter +=1
##print(f'There amount of words is:',counter+1)
##"""seventh programm"""
##s = input("Enter the value\n")
##new_s = list(s)
##if new_s[0]=="a" and new_s[1]=="b" and new_s[2]=="c":
## new_s[0]="w"
## new_s[1]="w"
## new_s[2]="w"
##else: new_s.extend(["zzz"])
##print("".join(new_s))
##
"""eigth programm"""
##s = input("Enter the value\n")
##new_s = list(s)
##if new_s[0]=="a" and new_s[1]=="b" and new_s[2]=="c":
## new_s[0]="w"
## new_s[1]="w"
## new_s[2]="w"
##else: new_s.extend(["zzz"])
##print("".join(new_s))
##
"""Progr 9"""
##s1 = input("Enter the value\n")
##s2 = input("Enter the value\n")
##s1_StartSlice = s1[:4]
##s2_StartSlice = s2[:4]
##s1_EndSlice = s1[-4:]
##s2_EndSlice = s2[-4:]
##if s1_StartSlice == s2_StartSlice and s1_EndSlice == s2_EndSlice:
## print("The first 4 symbols and the last 4 symbols are equal in both")
##else: print("The first 4 symbols and the last 4 symbols are NOT equal in both"
##"""The 10 program"""
##s1 = input("Enter the value\n")
##res = s1[round(len(s1)/2)].lower()
##print(res)
|
# Exercise 97
file = open("file.txt", "rU")
lines = file.readlines()
file.close()
result = list()
for line in lines:
l = line.split("|")
numbers = l[1].split(" ")
values = list()
for x in numbers:
values.append(int(x))
for y in values:
result.append(l[0][y - 1])
result.append("\n")
res = ''.join(result)
print(res.format("{0} \n {1}", res[0], res[1]))
# Exercise 116
code = {
'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..',
'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..', '1': '.----',
'2': '..---', '3': '...--', '4': '....-',
'5': '.....', '6': '-....', '7': '--...',
'8': '---..', '9': '----.', '0': '-----',
'.': '.-.-.-', ',': '--..--', ':': '---...',
';': '-.-.-.', '?': '..--..', '!': '-.-.--',
'"': '.-..-.', "'": '.----.', '+': '.-.-.',
'-': '-....-', '/': '-..-.', '=': '-...-',
'_': '..--.-', '$': '...-..-', '@': '.--.-.',
'&': '.-...', '(': '-.--.', ')': '-.--.-'
}
file = open("fileMorse.txt", "rU")
lines = file.readlines()
file.close()
translate = ""
for line in lines:
words = line.split(" ")
for x in words:
word = x.split(" ")
for c in word:
for k, v in code.items():
if v == c:
translate += k
print(translate)
# Exercise 30
file = open("fileSet.txt", "rU")
lines = file.readlines()
file.close()
for line in lines:
both = line.split(";")
set1 = set(both[0].split(","))
set2 = set(both[1].split(","))
print(set1.intersection(set2))
# Exercise 173
file = open("fileRep.txt", "rU")
lines = file.readlines()
file.close()
for line in lines:
l = list(line)
result = ""
i = 0
while i < len(l) - 1:
if l[i] != l[i + 1]:
result += l[i]
i += 1
result += l[i]
print(result) |
__author__ = 'Julián'
def ordena(l):
ordenada = list()
for i in l:
if len(ordenada) == 0:
ordenada.insert(0,i)
else:
for x in l:
if i < x:
ordenada.insert(l.index(x),i)
break
return ordenada
print(ordena([1,3,2,5,4])) |
import math
# Exercise 1
def get_data():
sequence = []
print("Write a sequence of numbers (type 0 for exit): ")
while True:
number = int(input())
if number != 0:
sequence.append(number)
else:
break
return sequence
def get_mean(sequence):
aux = 0
for x in sequence:
aux += x
return aux / len(sequence)
def get_max(sequence):
max = sequence[0]
for i in sequence:
if(max < i):
max = i
return max
def get_min(sequence):
min = sequence[0]
for i in sequence:
if(min > i):
min = i
return min
def get_typical_deviation(sequence):
aux = 0
for x in sequence:
aux += math.pow(x, 2)
mean = get_mean(sequence)
variance = aux / len(sequence) - math.pow(mean, 2)
return variance
def calc():
sequence = get_data()
print("Mean: {mean}, Max: {max}, Min: {min}, Deviation: {deviation}".format(mean = get_mean(sequence), max = get_max(sequence), min = get_min(sequence), deviation = get_typical_deviation(sequence)))
#calc()
# Exercise 2
def get_expr():
print("Write a expression: ")
expr = input().split()
return expr
def get_result(expr):
if len(expr) > 1:
x = int(expr[len(expr) - 2])
y = int(expr[len(expr) - 1])
op = expr[len(expr) - 3]
if op == '+':
res = x + y
elif op == '-':
res = x - y
elif op == '*':
res = x * y
else:
res = x / y
#del expr[len(expr) - 3 : len(expr) - 1]
del expr[len(expr) - 1]
del expr[len(expr) - 1]
del expr[len(expr) - 1]
expr.append(res)
return get_result(expr)
else:
return expr
def calc2():
print("Result: {res}".format(res = get_result(get_expr())))
calc2()
|
""" FUNCIONES CON PARAMETROS
Limites al declarar funciones
Los nombres no pueden comenzar con digitos
No pueden utilizar una palabra reservada
Las variables deben tener diferentes nombres
Los nombres de las funciones deben ser descriptivas de lo que hacen las funciones
"""
hello = 'hola'
print(hello)
def hello:
print('paltzi')
##type(hello)
def __name__ = '__name__':
hello() |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.results = []
"""
Exhaustive appproach: create a list at every node
TC - O(n^2)
SC - O(n^2)
"""
def approach1(self, root, targetSum, path):
if root == None:
return
path.append(root.val)
if root.left == None and root.right == None:
if targetSum - root.val == 0:
self.results.append(path)
self.approach1(root.left, targetSum - root.val, path.copy())
self.approach1(root.right, targetSum - root.val, path.copy())
"""
Backtracking approach: maintaing one list
TC - O(n)
SC - O(n^2)
"""
def approach1(self, root, targetSum, path):
if root == None:
return
path.append(root.val)
if root.left == None and root.right == None:
if targetSum - root.val == 0:
self.results.append(path.copy())
self.approach1(root.left, targetSum - root.val, path)
self.approach1(root.right, targetSum - root.val, path)
path.pop()
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if root == None:
return []
self.approach2(root, targetSum, [])
return self.results
|
def eggs(cheese):
cheese.append('Hello')
spam = list(range(1,4)) # spam = [1, 2, 3]
eggs(spam)
print(spam)
# Deep copy list
import copy
ham = ['A', 'B', 'C', 'D']
cheese = copy.deepcopy(ham)
cheese[1] = 42
print('ham:\t',end = '')
print(ham)
print('cheese:\t',end = '')
print(cheese)
|
print('My name is')
#for i in range(5):
#for i in range(12, 16):
for i in range(0, 10, 2):
print('Jimmy Five Times ' + str(i))
i = 0
while i < 5:
print('Jimmy Five Times ' + str(i))
i += 1
|
from file_loader.file_loader import load_lists_from_file
from algorithm3.algorithm3 import divide_and_conquer, max_crossing_subarray
import unittest
class Algorithm3Test(unittest.TestCase):
def test_algorithm3_providedInput_shouldReturnMatchProvidedOutput(self):
test_lists = load_lists_from_file('Problems/MSS_TestProblems-1.txt')
expected = [(3, 14, 34), (0, 5, 30), (6, 12, 50), (2, 7, 187), (0, 4, 7), (0, 3, 210), (3, 7, 6)]
actual = []
for test_list in test_lists:
actual.append(divide_and_conquer(test_list))
message = "For the instructor provided input, should return the max sum of the provided output \n%s, but was \n%s" % (expected, actual)
self.assertEqual(expected, actual, message)
def test_algorithm3_len1_2_should_return_0_1_2(self):
test_list = [2]
expected = (0, 1, 2)
actual = divide_and_conquer(test_list)
message = "For a single element array with value 2, the max subarray should be the first element"
self.assertEqual(expected, actual, message)
def test_algorithm3_len2_1_1_should_return_0_2_2(self):
test_list = [1, 1]
expected = (0, 2, 2)
actual = divide_and_conquer(test_list)
message = "For array [1, 1], the max subarray should be the sum of both elements, but was %s" % str(actual)
self.assertEqual(expected, actual, message)
def test_algorithm3_len3_2_neg1_2_should_return_0_3_3(self):
test_list = [2, -1, 2]
expected = (0, 3, 3)
actual = divide_and_conquer(test_list)
message = "For array [2, -1, 2], the max subarray should be the sum of all three elements, but was %s" % str(actual)
self.assertEqual(expected, actual, message)
def test_max_crossing_subarray(self):
test_list = [2, -1, -3, 5]
p = 0
q = 2
r = 4
expected_max_left = 0
expected_max_right = 4
expected_sum = 3
expected = [expected_max_left, expected_max_right, expected_sum]
actual = max_crossing_subarray(test_list, p, q, r)
message = "for %s p = %d q = %d r = %d, expected %s, but received %s" % (test_list, p, q, r, expected, actual)
self.assertEqual(expected, actual, message)
|
"""
递归:
让方案更清晰,没有性能上的优势
"""
class find_the_key(object):
def look_for_key_normal(self,main_box):
pile = main_box.make_a_pile_to_look_through()
while pile is not empty:
box = pile.grab_a_box():
for item in box:
if item.is_a_box():
pile.append(item)
elif item.is_a_key():
print("found the key!")
def look_for_key_recursive(self,box):#使用递归
for item in box:
if item.is_a_box():
self.look_for_key_recursive(item)
elif item.is_a_key():
print('found the key!')
#基线条件与递归条件
def countdown(i):
print(i)
if i <= 0: #基线条件
return
else: #递归条件
countdown(i-1)
#栈:后进先出
class stack_test(object):
def greet(self,name):
print("hello,"+name+"!")
self.greet2(name)
print("getting ready to say bye...")
self.bye()
def greet2(self,name):
print("how are you,"+name+"?")
def bye(self):
print('ok,bye!')
test = stack_test()
test.greet('hwh')
#递归调用栈
def fact(x):
if x == 1:
return x
else:
return x*fact(x-1)
|
"""
Mini-application: Buttons on a Tkinter GUI tell the robot to:
- Go forward at the speed given in an entry box.
This module runs on your LAPTOP.
It uses MQTT to SEND information to a program running on the ROBOT.
Authors: David Mutchler, his colleagues, and Landon Bundy.
"""
# ------------------------------------------------------------------------------
# TOsDO: 1. PUT YOUR NAME IN THE ABOVE LINE. Then delete this TODsO.
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# aTODO: 2. With your instructor, discuss the "big picture" of laptop-robot
# TOaDO: communication:
# TODOa: - One program runs on your LAPTOP. It displays a GUI. When the
# TODOa: user presses a button intended to make something happen on the
# TODOa: ROBOT, the LAPTOP program sends a message to its MQTT client
# TODOa: indicating what it wants the ROBOT to do, and the MQTT client
# TODOa: SENDS that message TO a program running on the ROBOT.
# TODOa:
# TODOa: - Another program runs on the ROBOT. It stays in a loop, responding
# TODOa: to events on the ROBOT (like pressing buttons on the IR Beacon).
# TODOa: It also, in the background, listens for messages TO the ROBOT
# TODOa: FROM the program running on the LAPTOP. When it hears such a
# TODOa: message, it calls the method in the DELAGATE object's class
# TODOa: that the message indicates, sending arguments per the message.
# TODOa:
# TODOa: Once you understand the "big picture", delete this TaODO (if you wish).
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# aTODO: 3. One team member: change the following in mqtt_remote_method_calls.py:
# a LEGO_NUMBER = 99
# TOaDO: to use YOUR robot's number instead of 99.
# TODaO: Commit and push the change, then other team members Update Project.
# TODOa: Then delete this TOaDO.
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# TaODO: 4. Run this module.
# TOaDO: Study its code until you understand how the GUI is set up.
# TODaO: Then delete this TOaDO.
# ------------------------------------------------------------------------------
import tkinter
from tkinter import ttk
import mqtt_remote_method_calls as com
def main():
""" Constructs and runs a GUI for this program. """
root = tkinter.Tk()
mqtt_client = com.MqttClient()
mqtt_client.connect_to_ev3()
set_remote_control_gui(root, mqtt_client)
root.mainloop()
def setup_gui(root_window, mqtt_client):
""" Constructs and sets up widgets on the given window. """
frame = ttk.Frame(root_window, padding=20)
frame.grid()
speed_entry_box = ttk.Entry(frame)
go_forward_button = ttk.Button(frame, text="Go forward")
speed_entry_box.grid()
go_forward_button.grid()
go_forward_button['command'] = \
lambda: handle_forward(speed_entry_box, mqtt_client)
def set_remote_control_gui(root_window, mqtt_client):
main_frame = ttk.Frame(root_window, padding=10)
main_frame.grid()
speed_entry_box = ttk.Entry(main_frame)
speed_entry_box.insert(0, "60")
forward_button = ttk.Button(main_frame, text="Go forward")
left_button = ttk.Button(main_frame, text="Go left")
right_button = ttk.Button(main_frame, text="Go right")
stop_button = ttk.Button(main_frame, text="Stop")
back_button = ttk.Button(main_frame, text="Go back")
exit_button = ttk.Button(main_frame, text="Exit")
raise_arm_button = ttk.Button(main_frame, text="Raise Arm")
lower_arm_button = ttk.Button(main_frame, text="Lower Arm")
speak_button = ttk.Button(main_frame, text="Speak")
color_sensor_button = ttk.Button(main_frame, text="Color Sensor")
speed_entry_box.grid(row=1, column=2)
forward_button.grid(row=2, column=2)
left_button.grid(row=2, column=1)
right_button.grid(row=2, column=3)
stop_button.grid(row=3, column=1)
back_button.grid(row=3, column=2)
exit_button.grid(row=3, column=3)
raise_arm_button.grid(row=4, column=1)
lower_arm_button.grid(row=4, column=3)
speak_button.grid(row=4, column=2)
color_sensor_button.grid(row=5, column=1)
forward_button['command'] = \
lambda: handle_forward(speed_entry_box, mqtt_client)
left_button['command'] = \
lambda: handle_left(speed_entry_box, mqtt_client)
right_button['command'] = \
lambda: handle_right(speed_entry_box, mqtt_client)
stop_button['command'] = \
lambda: handle_stop(mqtt_client)
back_button['command'] = \
lambda: handle_back(speed_entry_box, mqtt_client)
exit_button['command'] = lambda: exit()
raise_arm_button['command'] = \
lambda: handle_raise_arm(mqtt_client)
lower_arm_button['command'] = \
lambda: handle_lower_arm(mqtt_client)
speak_button['command'] = \
lambda: handle_speak(mqtt_client)
color_sensor_button['command'] = \
lambda: handle_color_sensor(mqtt_client)
def handle_forward(entry_box, mqtt_client):
"""
Tells the robot to go forward at the speed specified in the given entry box.
"""
speed_string = entry_box.get()
print('Sending the go_forward message with speed')
mqtt_client.send_message('forward', [speed_string])
def handle_left(entry_box, mqtt_client):
speed_string = entry_box.get()
print('Sending the go_left message with speed')
mqtt_client.send_message('left', [speed_string])
def handle_right(entry_box, mqtt_client):
speed_string = entry_box.get()
print('Sending the go_right message with speed')
mqtt_client.send_message('right', [speed_string])
def handle_stop(mqtt_client):
print('Sending the stop message')
mqtt_client.send_message('stop')
def handle_back(entry_box, mqtt_client):
speed_string = entry_box.get()
print('Sending the go_back message with speed')
mqtt_client.send_message('back', [speed_string])
def handle_raise_arm(mqtt_client):
print('Sending the arm_up message')
mqtt_client.send_message('raise_arm')
def handle_lower_arm(mqtt_client):
print('Sending the arm_down message')
mqtt_client.send_message('lower_arm')
def handle_speak(mqtt_client):
print('Sending the speak message')
mqtt_client.send_message('speak')
def handle_color_sensor(mqtt_client):
print('Sending the color_sensor message')
mqtt_client.send_message('color_sensor')
main()
|
import networking
import socket
# We are creating a socket object here for the connection
socketOBJ = socket.socket()
# Get local machine name
localM = socket.gethostname()
# This is the port that we will be working on (in this case it's TCP/UDP netbus)
port = 12345
# We have to use the bind function to activate IP
socketOBJ.bind((localM, port))
# We use the listen function to wait for the client connection (5 seconds)
# The shorter the time waited the less vulnerabilities ((that's why 5)
socketOBJ.listen(5)
# Connection being established
while True:
connection, address = socketOBJ.accept()
print('Connection Received From: ', address)
connection.send('Connection Established ')
connection.close()
|
def my_sum(my_integers):
result = 0
for x in my_integers:
result += x
return result
def sum_of_args(*args):
result = 0
for x in args:
result += x
return result
def concatenate(**kwargs):
print(f'kwargs={kwargs}')
result = ''
for x in kwargs.values():
result += x
return result
def sum_of_3(a, b, c):
return a + b + c
if __name__ == '__main__':
list_of_ints = [1, 2, 3]
sum1 = my_sum(list_of_ints)
print(sum1)
sum2 = sum_of_args(10, 11, 12)
print(sum2)
str1 = concatenate(a='This', b='Is', c='An', d='Example', e='!')
print(str1)
my_list = [44, 55, 66]
print(my_list)
print(*my_list)
sum3 = sum_of_3(*my_list)
print(sum3)
list1 = [1, 2, 3]
list2 = [4, 5]
list3 = [6, 7, 8, 9]
list_sum = sum_of_args(*list1, *list2, *list3)
print(list_sum)
my_list = [1, 2, 3, 4, 5, 6, 7]
a, *b, c = my_list
print(f'my_list={my_list} a={a} b={b} c={c}')
my_first_dict = {"A": 1, "B": 2}
my_second_dict = {"C": 3, "D": 4}
my_merged_dict = {**my_first_dict, **my_second_dict}
print(f'first={my_first_dict} second={my_second_dict} merged={my_merged_dict}')
name = [*'John Anderson']
print(f'name={name}')
|
import numpy as np
from knn import KNN
############################################################################
# DO NOT MODIFY ABOVE CODES
############################################################################
# TODO: implement F1 score
def f1_score(real_labels, predicted_labels):
"""
Information on F1 score - https://en.wikipedia.org/wiki/F1_score
:param real_labels: List[int]
:param predicted_labels: List[int]
:return: float
"""
product_sum = np.dot(real_labels, predicted_labels)
real_sum = np.sum(real_labels)
predicted_sum = np.sum(predicted_labels)
f1 = 2 * product_sum / (real_sum + predicted_sum)
return f1
class Distances:
@staticmethod
# TODO
def minkowski_distance(point1, point2):
"""
Minkowski distance is the generalized version of Euclidean Distance
It is also know as L-p norm (where p>=1) that you have studied in class
For our assignment we need to take p=3
Information on Minkowski distance - https://en.wikipedia.org/wiki/Minkowski_distance
:param point1: List[float]
:param point2: List[float]
:return: float
"""
vector1 = np.array(point1)
vector2 = np.array(point2)
return np.linalg.norm(vector1-vector2, 3)
@staticmethod
# TODO
def euclidean_distance(point1, point2):
"""
:param point1: List[float]
:param point2: List[float]
:return: float
"""
vector1 = np.array(point1)
vector2 = np.array(point2)
distance = np.sqrt(np.sum(np.square(vector1 - vector2)))
return distance
@staticmethod
# TODO
def inner_product_distance(point1, point2):
"""
:param point1: List[float]
:param point2: List[float]
:return: float
"""
distance = np.dot(point1, point2)
return distance
@staticmethod
# TODO
def cosine_similarity_distance(point1, point2):
"""
:param point1: List[float]
:param point2: List[float]
:return: float
"""
if np.linalg.norm(point1) == 0 or np.linalg.norm(point2) == 0:
return 0
cos_sim = np.dot(point1, point2) / (np.linalg.norm(point1) * np.linalg.norm(point2))
distance = 1 - cos_sim
return distance
@staticmethod
# TODO
def gaussian_kernel_distance(point1, point2):
"""
:param point1: List[float]
:param point2: List[float]
:return: float
"""
euclidean_square = np.square(Distances.euclidean_distance(point1, point2))
distance = -np.exp(- euclidean_square / 2)
return distance
class HyperparameterTuner:
def __init__(self):
self.best_k = None
self.best_distance_function = None
self.best_scaler = None
self.best_model = None
# TODO: find parameters with the best f1 score on validation dataset
def tuning_without_scaling(self, distance_funcs, x_train, y_train, x_val, y_val):
"""
In this part, you should try different distance function you implemented in part 1.1, and find the best k.
Use k range from 1 to 30 and increment by 2. Use f1-score to compare different models.
:param distance_funcs: dictionary of distance functions you must use to calculate the distance.
Make sure you loop over all distance functions for each data point and each k value.
You can refer to test.py file to see the format in which these functions will be
passed by the grading script
:param x_train: List[List[int]] training data set to train your KNN model
:param y_train: List[int] train labels to train your KNN model
:param x_val: List[List[int]] Validation data set will be used on your KNN predict function to produce
predicted labels and tune k and distance function.
:param y_val: List[int] validation labels
Find(tune) best k, distance_function and model (an instance of KNN) and assign to self.best_k,
self.best_distance_function and self.best_model respectively.
NOTE: self.best_scaler will be None
NOTE: When there is a tie, choose model based on the following priorities:
Then check distance function [euclidean > minkowski > gaussian > inner_prod > cosine_dist]
If they have same distance function, choose model which has a less k.
"""
max_f1 = -1
distance_sequence = ['euclidean', 'minkowski', 'gaussian', 'inner_prod', 'cosine_dist']
for dist in distance_sequence:
for k in range(1, 30, 2):
current_knn = KNN(k, distance_funcs[dist])
current_knn.train(x_train, y_train)
predicted_labels = current_knn.predict(x_val)
current_f1 = f1_score(y_val, predicted_labels)
if current_f1 > max_f1:
max_f1 = current_f1
self.best_k = k
self.best_distance_function = dist
self.best_model = current_knn
# TODO: find parameters with the best f1 score on validation dataset, with normalized data
def tuning_with_scaling(self, distance_funcs, scaling_classes, x_train, y_train, x_val, y_val):
"""
This part is similar to Part 1.3 except that before passing your training and validation data to KNN model to
tune k and distance function, you need to create the normalized data using these two scalers to transform your
data, both training and validation. Again, we will use f1-score to compare different models.
Here we have 3 hyperparameters i.e. k, distance_function and scaler.
:param distance_funcs: dictionary of distance funtions you use to calculate the distance. Make sure you
loop over all distance function for each data point and each k value.
You can refer to test.py file to see the format in which these functions will be
passed by the grading script
:param scaling_classes: dictionary of scalers you will use to normalized your data.
Refer to test.py file to check the format.
:param x_train: List[List[int]] training data set to train your KNN model
:param y_train: List[int] train labels to train your KNN model
:param x_val: List[List[int]] validation data set you will use on your KNN predict function to produce predicted
labels and tune your k, distance function and scaler.
:param y_val: List[int] validation labels
Find(tune) best k, distance_funtion, scaler and model (an instance of KNN) and assign to self.best_k,
self.best_distance_function, self.best_scaler and self.best_model respectively
NOTE: When there is a tie, choose model based on the following priorities:
For normalization, [min_max_scale > normalize];
Then check distance function [euclidean > minkowski > gaussian > inner_prod > cosine_dist]
If they have same distance function, choose model which has a less k.
"""
max_f1 = -1
distance_sequence = ['euclidean', 'minkowski', 'gaussian', 'inner_prod', 'cosine_dist']
scaling_sequence = ['min_max_scale', 'normalize']
for scaler in scaling_sequence:
scale_instance = scaling_classes[scaler]()
scaled_x_train = scale_instance(x_train)
scaled_x_val = scale_instance(x_val)
for dist in distance_sequence:
for k in range(1, 30, 2):
current_knn = KNN(k, distance_funcs[dist])
current_knn.train(scaled_x_train, y_train)
predicted_labels = current_knn.predict(scaled_x_val)
current_f1 = f1_score(y_val, predicted_labels)
if current_f1 > max_f1:
max_f1 = current_f1
self.best_k = k
self.best_distance_function = dist
self.best_model = current_knn
self.best_scaler = scaler
class NormalizationScaler:
def __init__(self):
pass
# TODO: normalize data
def __call__(self, features):
"""
Normalize features for every sample
Example
features = [[3, 4], [1, -1], [0, 0]]
return [[0.6, 0.8], [0.707107, -0.707107], [0, 0]]
:param features: List[List[float]]
:return: List[List[float]]
"""
scaled_features = [0 * len(features[0])] * len(features)
for i in range(len(features)):
current_feature = np.array(features[i])
length = np.linalg.norm(current_feature)
if length != 0:
scaled_features[i] = (np.array(features[i]) / length).tolist()
else:
scaled_features[i] = features[i]
return scaled_features
class MinMaxScaler:
"""
Please follow this link to know more about min max scaling
https://en.wikipedia.org/wiki/Feature_scaling
You should keep some states inside the object.
You can assume that the parameter of the first __call__
will be the training set.
Hints:
1. Use a variable to check for first __call__ and only compute
and store min/max in that case.
Note:
1. You may assume the parameters are valid when __call__
is being called the first time (you can find min and max).
Example:
train_features = [[0, 10], [2, 0]]
test_features = [[20, 1]]
scaler1 = MinMaxScale()
train_features_scaled = scaler1(train_features)
# train_features_scaled should be equal to [[0, 1], [1, 0]]
test_features_scaled = scaler1(test_features)
# test_features_scaled should be equal to [[10, 0.1]]
new_scaler = MinMaxScale() # creating a new scaler
_ = new_scaler([[1, 1], [0, 0]]) # new trainfeatures
test_features_scaled = new_scaler(test_features)
# now test_features_scaled should be [[20, 1]]
"""
def __init__(self):
self.never_been_called = True
self.max = None
self.min = None
def __call__(self, features):
"""
normalize the feature vector for each sample . For example,
if the input features = [[2, -1], [-1, 5], [0, 0]],
the output should be [[1, 0], [0, 1], [0.333333, 0.16667]]
:param features: List[List[float]]
:return: List[List[float]]
"""
if self.never_been_called:
self.max = features[0][:]
self.min = features[0][:]
for i in range(len(features)):
for j in range(len(features[0])):
self.max[j] = np.maximum(self.max[j], features[i][j])
self.min[j] = np.minimum(self.min[j], features[i][j])
self.never_been_called = False
arr_min = np.array(self.min)
arr_max = np.array(self.max)
arr_length = arr_max - arr_min
for i in range(len(arr_length)):
if arr_length[i] == 0:
arr_min[i] = 0
arr_length[i] = 1
scaled_features = ((np.array(features) - arr_min) / arr_length).tolist()
return scaled_features
|
import math
def intersection(
function, x0, x1
): # function is the f we want to find its root and x0 and x1 are two random starting points
x_n = x0
x_n1 = x1
while True:
x_n2 = x_n1 - (
function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n))
)
if abs(x_n2 - x_n1) < 10 ** -5:
return x_n2
x_n = x_n1
x_n1 = x_n2
def f(x):
return math.pow(x, 3) - (2 * x) - 5
if __name__ == "__main__":
print(intersection(f, 3, 3.5))
|
"""
Counting Summations
Problem 76
It is possible to write five as a sum in exactly six different ways:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
How many different ways can one hundred be written as a sum of at least two
positive integers?
"""
def partition(m):
"""Returns the number of different ways one hundred can be written as a sum
of at least two positive integers.
>>> partition(100)
190569291
>>> partition(50)
204225
>>> partition(30)
5603
>>> partition(10)
41
>>> partition(5)
6
>>> partition(3)
2
>>> partition(2)
1
>>> partition(1)
0
"""
memo = [[0 for _ in range(m)] for _ in range(m + 1)]
for i in range(m + 1):
memo[i][0] = 1
for n in range(m + 1):
for k in range(1, m):
memo[n][k] += memo[n][k - 1]
if n > k:
memo[n][k] += memo[n - k - 1][k]
return memo[m][m - 1] - 1
if __name__ == "__main__":
print(partition(int(str(input()).strip())))
|
"""
Python implementation of bogobogosort, a "sorting algorithm
designed not to succeed before the heat death of the universe
on any sizable list" - https://en.wikipedia.org/wiki/Bogosort.
Author: WilliamHYZhang
"""
import random
def bogo_bogo_sort(collection):
"""
returns the collection sorted in ascending order
:param collection: list of comparable items
:return: the list sorted in ascending order
Examples:
>>> bogo_bogo_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> bogo_bogo_sort([-2, -5, -45])
[-45, -5, -2]
>>> bogo_bogo_sort([420, 69])
[69, 420]
"""
def is_sorted(collection):
if len(collection) == 1:
return True
clone = collection.copy()
while True:
random.shuffle(clone)
ordered = bogo_bogo_sort(clone[:-1])
if clone[len(clone) - 1] >= max(ordered):
break
for i in range(len(ordered)):
clone[i] = ordered[i]
for i in range(len(collection)):
if clone[i] != collection[i]:
return False
return True
while not is_sorted(collection):
random.shuffle(collection)
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(bogo_bogo_sort(unsorted))
|
"""Find mean of a list of numbers."""
def average(nums):
"""Find mean of a list of numbers."""
sum = 0
for x in nums:
sum += x
avg = sum / len(nums)
print(avg)
return avg
def main():
"""Call average module to find mean of a specific list of numbers."""
average([2, 4, 6, 8, 20, 50, 70])
if __name__ == "__main__":
main()
|
"""Password generator allows you to generate a random password of length N."""
from random import choice
from string import ascii_letters, digits, punctuation
def password_generator(length=8):
"""
>>> len(password_generator())
8
>>> len(password_generator(length=16))
16
>>> len(password_generator(257))
257
>>> len(password_generator(length=0))
0
>>> len(password_generator(-1))
0
"""
chars = tuple(ascii_letters) + tuple(digits) + tuple(punctuation)
return "".join(choice(chars) for x in range(length))
# ALTERNATIVE METHODS
# ctbi= characters that must be in password
# i= how many letters or characters the password length will be
def alternative_password_generator(ctbi, i):
# Password generator = full boot with random_number, random_letters, and
# random_character FUNCTIONS
pass # Put your code here...
def random_number(ctbi, i):
pass # Put your code here...
def random_letters(ctbi, i):
pass # Put your code here...
def random_characters(ctbi, i):
pass # Put your code here...
def main():
length = int(input("Please indicate the max length of your password: ").strip())
print("Password generated:", password_generator(length))
print("[If you are thinking of using this passsword, You better save it.]")
if __name__ == "__main__":
main()
|
"""
Greater Common Divisor.
Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor
"""
def gcd(a, b):
"""Calculate Greater Common Divisor (GCD)."""
return b if a == 0 else gcd(b % a, a)
def main():
"""Call GCD Function."""
try:
nums = input("Enter two Integers separated by comma (,): ").split(",")
num_1 = int(nums[0])
num_2 = int(nums[1])
except (IndexError, UnboundLocalError, ValueError):
print("Wrong Input")
print(f"gcd({num_1}, {num_2}) = {gcd(num_1, num_2)}")
if __name__ == "__main__":
main()
|
import numpy as np
import nnfs # See below for details of nnfs
# https://www.youtube.com/watch?v=gmjzbpSVY1A
from nnfs.datasets import spiral_data
nnfs.init()
# X Feature Set
# y target or classification
X = [[1, 2, 3, 2.5],
[2.0, 5.0, -1.0, 2.0],
[-1.5, 2.7, 3.3, -0.8]]
X, y = spiral_data(100, 3) # 100 Feature sets of 3 classes
class Layer_Dense:
def __init__(self, n_inputs, n_neurons):
self.weights = 0.1*np.random.randn(n_inputs, n_neurons)
self.biases = np.zeros((1, n_neurons))
def forward(self, inputs):
self.output = np.dot(inputs, self.weights) + self.biases
class Activation_ReLU:
def forward(self, inputs):
self.output = np.maximum(0, inputs)
# layer1 = Layer_Dense(4, 5) # 4 is the Number of features per sample
layer1 = Layer_Dense(2, 5)
activation1 = Activation_ReLU()
layer1.forward(X)
# print(layer1.output)
activation1.forward(layer1.output) # This will set all the-ve values to 0
print(activation1.output)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# NNFS
# ----
#
# pip install nnfs
# nnfs allows you to get the code from that is being used in the tutorial:
# Inputs are X; our inout data to the neural network
# (venv) PS C:\Users\rchotalia\Documents\VisualStudioCode\AIandML> pip install nnfs
# Collecting nnfs
# Downloading nnfs-0.5.0-py3-none-any.whl (9.1 kB)
# Requirement already satisfied: numpy in c:\users\rchotalia\documents\visualstudiocode\aiandml\venv\lib\site-packages (from nnfs) (1.18.4)
# Installing collected packages: nnfs
# Successfully installed nnfs-0.5.0
# (venv) PS C:\Users\rchotalia\Documents\VisualStudioCode\AIandML> nnfs
# Neural Networks from Scratch in Python Tool.
# Basic usage:
# nnfs command [parameter1 [parameter2]]
# Detailed usage:
# nnfs info | code video_part [destination]
# Commands:
# info Prints information about the book
# code Creates a file containing the code of given video part
# in given location. Location is optional, example:
# nnfs code 2 nnfs/p02.py
# will create a file p02.py in a nnfs folder containing
# the code of part 2 of video tutorial
# (venv) PS C:\Users\rchotalia\Documents\VisualStudioCode\AIandML>
|
#暴力搜索(不推荐),与动态规划均可解
class Solution(object):
def longestPalindrome(self, s):
"""
:s的类型: str
:返回值类型: str
"""
left = right = 0
n = len(s)
for i in range(n - 1):
if 2 * (n - i) + 1 < right - left + 1:
break
l = r = i
while l >= 0 and r < n and s[l] == s[r]:
l -= 1
r += 1
if r - l - 2 > right - left:
left = l + 1
right = r - 1
l = i
r = i + 1
while l >= 0 and r < n and s[l] == s[r]:
l -= 1
r += 1
if r - l - 2 > right - left:
left = l + 1
right = r - 1
return s[left:right + 1]
|
x = input('Введите х: ')
y = input('Введите y: ')
x=float(x)
y=float(y)
y=y+x
print (y)
|
name = input('Введите имя: ')
fam = input('Введите фамилию: ')
stud = input('Введите номер студенческого билета:')
print('Привет, ' + name)
print(fam)
print(stud)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.