text
stringlengths 37
1.41M
|
|---|
import threading
import time
# fasdasdasd
def t():
"""Prosta funkcja podająca nazwę aktualnego wątku; skraca zapis poniżej...
:returns nazwa wątku
"""
return threading.current_thread().name
class MyJob(threading.Thread):
def __init__(self, title: str):
threading.Thread.__init__(self)
self.title = title # jakiś napis, który ustalamy przy uruchomieniu wątku; będzie jego własnością
def run(self):
print(f'title:{self.title}; nazwa:{t()} ---- start')
time.sleep(3)
print(f'title:{self.title}; nazwa:{t()} ---- koniec')
print(f'wątek: {t()}') # ten kod jest wykonywany na głównym wątku (MainThread)
job1 = MyJob('sęk')
job1.start() # uruchamiane na osobnym wątku
job1.join() # MainThread czeka na zakończenie wątku Thread-1
job2 = MyJob('pień')
job2.start() # uruchamiane na osobnym wątku
|
from Node import Node
class Tree(object):
def __init__(self):
self.root = None
def insert(self, key, value):
if self.root is None:
self.root = Node(key, value)
return self.root
node = self.root
while True:
if key < node.get_key():
if node.left:
node = node.left
else:
leaf = Node(key, value)
node.left = leaf
return leaf
elif key > node.get_key():
if node.right:
node = node.right
else:
leaf = Node(key, value)
node.right = leaf
return leaf
else:
if not node.has_value(value):
node.add_value(value)
return node
def find(self, key):
node = self.root
while node:
if key == node.get_key():
return node
if key < node.get_key():
node = node.left
else:
node = node.right
def iter(self, node=None):
if node is None:
node = self.root
queue = [(node, 0)]
while queue:
node, depth = queue.pop()
if node is None:
continue
yield node, depth
if node.left:
queue.append((node.left, depth + 1))
if node.right:
queue.append((node.right, depth + 1))
if __name__ == '__main__':
data = [
(1, 'cat'),
(8, 'dog'),
(3, 'tree'),
(10, 'sky'),
(7, 'river'),
(2, 'butterfly'),
(5, 'bird'),
(4, 'rock'),
(6, 'mountain'),
(10, 'cloud'),
]
t = Tree()
for key, value in data:
t.insert(key, value)
for key, value in data:
node = t.find(key)
assert node is not None
assert node.has_value(value)
assert t.find(99) is None
|
from typing import List
def read_file(input) :
data = open(input,"r")
res = data.readlines()
res = list(map(lambda x: x[:-1].split(')'),res))
data.close()
return res
dictNodes = {}
class Node:
def __init__(self, name: str, parent) :
self.name = name
self.parent = parent
self.children = []
self.value = 0
dictNodes[name] = self
def addChildren(self, child) :
self.children.append(child)
def setParent(self, parentNode) :
self.parent = parentNode
noeudVide: Node = Node("vide", None)
def constructTree(L) :
for x in L :
parent, child = x
if parent in dictNodes :
parentNode = dictNodes[parent]
if child in dictNodes :
childNode = dictNodes[child]
childNode.setParent(parentNode)
else :
childNode = Node(child,parentNode)
parentNode.addChildren(childNode)
else :
parentNode = Node(parent, noeudVide)
if child in dictNodes :
childNode = dictNodes[child]
childNode.setParent(parentNode)
else :
childNode = Node(child, parentNode)
parentNode.addChildren(childNode)
return dictNodes["COM"]
def depthFirstSearch(node: Node) :
# print("on regarde le noeud", node.name)
if node.children == [] :
# print("il n'a pas d'enfants, sa value est ",node.value)
return
for x in node.children :
# print("ses enfants sont : ",list(map(lambda x:x.name,node.children)))
x.value = node.value+1
depthFirstSearch(x)
return
data = read_file("input-day6")
root = constructTree(data)
root.value = 0
depthFirstSearch(root)
total = 0
for x in dictNodes :
total+=dictNodes[x].value
#print(x,"enfants : ",dictNodes[x].children, "parent : ",dictNodes[x].parent)
print(total)
def path(a: Node, b: Node, root: Node) :
current = a
distanceToA = 1
parentsOfA = {'a': 0}
while root.name not in parentsOfA :
parentsOfA[current.parent.name] = distanceToA
current = current.parent
distanceToA +=1
current = b
distanceToB = 1
while 1 :
if current.parent.name in parentsOfA :
return parentsOfA[current.parent.name] + distanceToB - 2
else :
distanceToB+=1
current = current.parent
print(path(dictNodes["YOU"],dictNodes["SAN"],root))
|
import turtle
def draw_square(some_turtle):
for i in range(0,4):
some_turtle.forward(100)
some_turtle.right(90)
def draw_art():
window = turtle.Screen()
window.bgcolor("blue")
#brad draws a bunch of squares
brad = turtle.Turtle()
brad.shape("square")
brad.color("black")
brad.speed(350)
for i in range(0,36):
draw_square(brad)
brad.right(10)
# angie draws a circle
#angie = turtle.Turtle()
#angie.hideturtle()
#angie.color("green")
#angie.circle(50)
#angie.speed(10)
# steve draws a triangle
#steve = turtle.Turtle()
#steve.speed(10)
#steve.up()
#steve.setpos(150, 150)
#steve.down()
#for x in range(0,3):
#steve.forward(100)
#steve.right(120)
#ken draws a bunch of circles that do cool things
ken = turtle.Turtle()
ken.color("green")
ken.speed(100)
ken.up()
ken.setpos(200,200)
ken.down()
for i in range (0,19):
ken.circle(50)
ken.right(20)
window.exitonclick()
draw_art()
|
import logging
import time
logging.basicConfig(
# filename='algorithm-output.log',
level=logging.INFO,
format='[%(asctime)s] {%(filename)s:%(funcName)s:%(lineno)d} %(levelname)s - %(message)s',
datefmt='%H:%M:%S'
)
logger = logging.getLogger(__name__)
def knapsack_repeat(weight_list: list,value_list: list,total_capactiy: int) -> int:
""" find the best solution for total_capacity by building up solutions for all capacities up to total_capacity"""
logger.info('knapsack repeat: (weight_list: {}) (value_list: {}) (total_capacity:{})'.format(weight_list,value_list,total_capactiy))
knapsack = []
for b in range(total_capactiy):
logger.info('Checking capacity: {}'.format(b))
knapsack.append(0)
for i in range(len(weight_list)):
logger.info('Checking weight: {} of {}'.format(i,weight_list[i]))
if weight_list[i] <= b & knapsack[b] < value_list[i] + knapsack[b-weight_list[i]]:
logger.info('{} greater than {}'.format(
value_list[i] + knapsack[b-weight_list[i]], knapsack[b]))
knapsack[b] = value_list[i] + knapsack[b-weight_list[i]]
logger.info('Current value: {}'.format(knapsack[-1]))
logger.info('final max value: {}'.format(knapsack[-1]))
return knapsack[-1]
def knapsack_repeat_test():
weight_list = [1,5,2,7,3]
value_list = [5,5,1,10,1]
total_capacity = 100
start_time = time.time()
output = knapsack_repeat(weight_list, value_list, total_capacity)
total_time = time.time() - start_time
logger.info('knapsack_repeat {}: {} in {}s'.format(output, total_time))
def fibonacci_recursive(n):
"""
runtime of n is atleast the nth fibonacci number ,T(n) >= Fn
sub problems recomputed many times
"""
if n == 0:
return 0
if n == 1:
return 1
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
def fibonacci_dp(n):
"""
No recursion, O(n) total time
"""
f = [0,1] # O(1)
for i in range(2,n+1): # O(n)
f.append(f[i-1] + f[i-2]) # O(1)
return f[-1]
def fibonacci_recursive_test():
n = 35
start_time = time.time()
output = fibonacci_recursive(n)
total_time = time.time() - start_time
logger.info('fibonacci_recursive {}: {} in {}s'.format(n,output,total_time))
def fibonacci_dp_test():
n = 35
start_time = time.time()
output = fibonacci_dp(n)
total_time = time.time() - start_time
logger.info('fibonacci_dp {}: {} in {}s'.format(
n, output, total_time))
def longest_increasing_subsequence_dp(input_sequence=[-3,1,4,5,8,9]):
logger.info('input sequence: {}'.format(input_sequence))
subsequences = [[] for _ in range(len(input_sequence))]
subsequence_lengths = []
n = len(input_sequence)
for i in range(0,n): # O(n^2)
subsequence_lengths.append(1)
subsequences[i].append(input_sequence[i])
for j in range(0,i): # O(n) for n
if input_sequence[j] < input_sequence[i]:
if subsequence_lengths[i] < subsequence_lengths[j] + 1:
subsequence_lengths[i] = subsequence_lengths[j] + 1
subsequences[i] = subsequences[j] + [input_sequence[i]]
index_max = 0
for i in range(1,len(input_sequence)): # O(n)
if subsequence_lengths[i] > subsequence_lengths[index_max]:
index_max = i
logger.info('subsequence lengths: {}'.format(subsequence_lengths))
logger.info('all subsequences: {}'.format(subsequences))
logger.info('longest subsequence: {}'.format(subsequences[index_max]))
return subsequence_lengths[index_max]
def longest_increasing_subsequence_dp_test():
# input_sequence = [-3, 1, 4, 5, 8, 9]
input_sequence = [400,-3, 1, 4, 5, 8, 9,1,2,3,4,-1,99,999,5,6,7,8,9]
start_time = time.time()
output = longest_increasing_subsequence_dp(input_sequence=input_sequence)
total_time = time.time() - start_time
logger.info('longest_increasing_subsequence_dp: {} in {}s'.format(output, total_time))
def longest_common_subsequence_dp(x,y):
# get subsequence lengths
lcs = [[0]*(len(y)+1) for _ in range(len(x)+1)] # O(n)
# print('initialized table')
# for r in lcs:
# print(r)
# print()
for i in range(1,len(x)+1): # O(n^2)
for j in range(1,len(y)+1): # O(n)
if x[i-1] == y[j-1]:
lcs[i][j] = 1 + lcs[i-1][j-1]
else:
lcs[i][j] = max(lcs[i][j-1], lcs[i-1][j])
# print('filled table')
# for r in lcs:
# print(r)
# print()
sequence = []
i, j = len(x), len(y)
while i != 0 and j != 0:
if lcs[i][j-1] == lcs[i][j]:
j -= 1
elif lcs[i-1][j] == lcs[i][j]:
i -= 1
elif lcs[i-1][j-1] == lcs[i][j]:
j -= 1
i -= 1
elif lcs[i-1][j-1] < lcs[i][j]:
sequence.insert(0,x[i-1])
j -= 1
i -= 1
sequence = ''.join(sequence)
logger.info('sequence: {}'.format(sequence))
return lcs[-1][-1]
def longest_common_subsequence_dp_test():
# x = [400, -3, 1, 4, 5, 8, 9, 1, 2, 3, 4, -1, 99, 999, 5, 6, 7, 8, 9]
# y = [5, 8, 9, 1, 3, 4, -1, 99]
# x = 'BCDBCDA'
# y = 'ABECBA'
x = 'hdjkgafhsdgfhoiashdufiasdifhaskuidfhgbluiasgdfliasdf'
y = 'aluskidgfhuioasghydfoiu7asghfuiasdfgaisyudfgliasghfuilasghfd'
start_time = time.time()
output = longest_common_subsequence_dp(x,y)
total_time = time.time() - start_time
logger.info('longest_common_subsequence_dp: {} in {}s'.format(
output, total_time))
def main():
# knapsack_repeat_test()
# fibonacci_recursive_test()
# fibonacci_dp_test()
# longest_increasing_subsequence_dp_test()
longest_common_subsequence_dp_test()
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 10:58:12 2020
@author: dalan
"""
# Sequential is the neural-network class, Dense is
# the standard network layer
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras import optimizers # to choose more advanced optimizers like 'adam'
from tqdm import tqdm # progress bar
import numpy as np
import matplotlib.pyplot as plt # for plotting
import matplotlib
matplotlib.rcParams['figure.dpi']=300 # Highres display
# for updating display
# (very simple animation)
from IPython.display import clear_output
from time import sleep
###############################################################
############### Telling Lorentzians from Gaussians! ###########
###############################################################
N = 100 # number of pixels in 'image'
Net = Sequential()
Net.add(Dense(30, input_shape=(N,), activation = "relu"))
Net.add(Dense(20, activation = "relu"))
Net.add(Dense(2, activation = "softmax"))
Net.compile(loss = 'categorical_crossentropy',
optimizer = 'adam',
metrics = ['categorical_accuracy'])
def my_generator1D(batchsize,x): # produce a batch of curves, randomly Lorentzian or Gaussian
R=np.random.uniform(size=batchsize) # width
A=np.random.uniform(size=batchsize) # amplitude
x0=np.random.uniform(size=batchsize,low=-1,high=1) # position
IsLorentzian=(np.random.uniform(size=batchsize)<0.5)*1.0 # Lorentzian? (==1) or Gaussian?
Lorentzians=A[:,None]/(((x[None,:]-x0[:,None])/R[:,None])**2+1) # make many random Lorentzians
Gaussians=A[:,None]*np.exp(-((x[None,:]-x0[:,None])/R[:,None])**2) # make many random Gaussians
inputLayer=IsLorentzian[:,None]*Lorentzians + (1-IsLorentzian[:,None])*Gaussians # now pick whatever type was decided
resultLayer=np.zeros([batchsize,2])
resultLayer[:,0]=IsLorentzian
resultLayer[:,1]=1-IsLorentzian # we could easily have more than just two categories
return(inputLayer, resultLayer)
batchsize = 20
steps = 1000
x = np.linspace(-1, 1, N)
costs = np.zeros(steps)
accuracy = np.zeros(steps)
skipsteps = 10
for j in range(steps):
y_in, y_target = my_generator1D(batchsize, x)
costs[j], accuracy[j] = Net.train_on_batch(y_in, y_target)
if j % skipsteps == 0:
clear_output(wait = True)
plt.plot(costs, color = "darkblue", label = "costs")
plt.plot(accuracy, color = "orange", label = "accuracy")
plt.legend()
plt.show()
# plot some examples:
y_pred = np.array(Net.predict_on_batch(y_in))
n_samples = 10
fig, ax = plt.subplots(ncols = n_samples, nrows = 1, figsize = (10, 1))
Name = {}
Name[True] = "L" # Lorentz
Name[False] = "G" # Gauss
for j in tqdm(range(n_samples)):
ax[j].plot(y_in[j, :])
ax[j].set_ylim([-0.1, 1])
ax[j].axis("off")
ax[j].set_title(Name[y_target[j, 0] > 0.5] + "/" + Name[y_pred[j, 0] > 0.5])
plt.show()
print("True Category / Network Prediction")
|
import time
# My way
# Use oof as an argument in foo - i.e. sum(foo(oof))
# Or foo as an argument of even_nos - i.e. sum(even_nos(foo))
def oof():
seq = [1,1]
for i in seq:
if seq[-1] + seq[-2] < 4000000:
seq.append(seq[-2] + seq[-1])
# if seq[-1] % 2 != 0:
# seq.remove(i)
return seq
def foo(oof):
before = time.time()
my_list=[]
for el in oof():
my_list.append(el)
if el % 2 != 0:
my_list.remove(el)
after = time.time()
print("Time Elapsed:", after - before)
return my_list
# Using even_nos and foo is slower than using oof and foo
def even_nos(foo):
before = time.time()
list_of_evens = [2*x for x in range(4000000)]
after = time.time()
a = sum(set(foo(oof)).intersection(list_of_evens))
print("Time Elapsed:", after - before)
return str(a)
# Some other dudes way
def compute():
before = time.time()
ans = 0
x = 1 # Represents the current Fibonacci number being processed
y = 2 # Represents the next Fibonacci number in the sequence
while x <= 4000000:
if x % 2 == 0:
ans += x
x, y = y, x + y
after = time.time()
print("Time Elapsed:", after - before)
return str(ans)
# def fun(n):
# seq = [1,1]
# if n == 1:
# return 1
# if n == 2:
# return [1,1]
# if n >= 3 and n <= 40:
# seq.append(seq[-2] + seq[-1])
# return seq
# def test():
# seq = [1,1]
# # Need to do a check to make sure the element
# # appended is less than 4000000
# seq.append(seq[-2] + seq[-1])
# def foo(n):
# i = 0
# while i < n:
# yield i
# i += 1
# def oof():
# seq = [1,1]
# for i in seq:
# if seq[-1] + seq[-2] < 4000000:
# seq.append(seq[-2] + seq[-1])
# return seq
|
from shared import *
import re
input_ary = read_input('input.txt')
count = 0
def is_triangle(arr):
largest = max(numbers)
numbers.pop(numbers.index(largest))
return largest < (numbers[0] + numbers[1])
for line in input_ary:
matches = re.findall('(\d{1,3})', line)
numbers = [int(x) for x in matches]
if is_triangle(numbers):
count += 1
print count
count = 0
for i in range(1, len(input_ary), 3):
matches1 = re.findall('(\d{1,3})', input_ary[i-1])
matches2 = re.findall('(\d{1,3})', input_ary[i])
matches3 = re.findall('(\d{1,3})', input_ary[i+1])
set = [[matches1[0], matches2[0], matches3[0]],
[matches1[1], matches2[1], matches3[1]],
[matches1[2], matches2[2], matches3[2]]]
for m in set:
numbers = [int(x) for x in m]
if is_triangle(numbers):
count += 1
print count
|
flag = True
fibval = 0
counter = 0
sum = 0
def fib(n):
if n == 0 :
return 0
elif n == 1:
return 1
else:
temp = fib(n - 1) + fib(n - 2)
return temp
while flag:
fibval = fib(counter)
if fibval > 4000000:
flag = False
else:
if fibval % 2 == 0:
sum += fibval
counter = counter + 1
print fibval
#print counter
print "sum is:"
print sum
|
# Implement binary search
"""
What is it searching for? Ints, Strings, Objects?
What do you want me to return if its not in the list?
- Null, -1, exception?
Should we assume the input is sorted? or do we sort it and then perform binary search? But that would take longer
than the search
Design
Search for: 4.5
0 1 2 3 4 5 6
[1, 3, 4, 5, 6, 7, 23]
^ ^
# Finding midpoint
midpoint = (right + left) // 2
Three cases
midpoint = elem
return
midpoint < elem
look at the right (move left to midpoint + 1)
midpoint > elem
look at the left (move right to midpoint -1)
"""
class BinarySearch:
@staticmethod
def find_element(arr, to_find):
left = 0
right = len(arr) - 1
while left <= right:
midpoint = (left + right) // 2
if arr[midpoint] == to_find:
return midpoint
elif arr[midpoint] < to_find:
left = midpoint + 1
else:
right = midpoint - 1
return -1
def __main__():
b_search = BinarySearch()
# 0 1 2 3 4 5 6
arr = [1, 3, 4, 5, 6, 7, 23]
print(b_search.find_element(arr, 23)) # Return: 6
print(b_search.find_element(arr, 3)) # Return: 1
print(b_search.find_element(arr, 33)) # Return: -1
print(b_search.find_element(arr, 4)) # Return: 2
print(b_search.find_element(arr, 5)) # Return: 3
print(b_search.find_element(arr, 1.5)) # Return: -1
__main__()
|
"""
Kitten is stuck on tree that is numbered
First line is his branch
"""
from collections import defaultdict
stuck_on = int(input())
next_line = input()
graph = defaultdict(list)
while next_line != "-1":
parsed_line = next_line.split(" ")
parsed_line = list(map(lambda x: int(x), parsed_line))
parent = parsed_line[0]
for child in parsed_line[1:]:
graph[child].append(parent)
next_line = input()
# DFS
path = [stuck_on]
def dfs(node, path):
if len(graph[node]) == 0:
return True
for neighb in graph[node]:
path.append(neighb)
if dfs(neighb, path):
return True
path.pop()
return False
dfs(stuck_on, path)
# print(dfs(stuck_on, path))
print(" ".join([str(i) for i in path]))
|
array = [-99, 4, 2, 1, -3, 4, 92, 11, -321, 66, 1, 0]
expected = sorted(array)
def insertion_sort(array):
for i in range(1, len(array)):
j = i
while j - 1 >= 0 and array[j] < array[j - 1]:
array[j - 1], array[j] = array[j], array[j - 1]
j -= 1
return array
print(expected == insertion_sort(array))
|
num_cases = int(input())
for i in range(0, num_cases):
number = input()
reverse = number[::-1]
final = ""
found = False
for num in reverse:
num = int(num)
if num - 1 >= 0 and found == False:
final = str(num-1) + final
found = True
else:
final = str(num) + final
print(int(final))
|
import string
char_map = dict(zip(range(1, 27), string.ascii_lowercase))
first_line = input().split()
length = int(first_line[0])
height = int(first_line[1])
k = int(first_line[2])
laptop_back = [["_" for j in range(length)] for i in range(height)]
def is_oob(row, col):
if not (0 <= row < height):
return True
elif not (0 <= col < length):
return True
return False
def place_sticker(row, col, l, h, char):
for i in range(row, row + h):
for j in range(col, col + l):
if is_oob(i, j):
continue
laptop_back[i][j] = char_map[char + 1]
for index, line in enumerate(range(k)):
row_input = list(map(lambda x: int(x), input().split()))
leng, hei, col, row = row_input[0], row_input[1], row_input[2], row_input[3]
place_sticker(row, col, leng, hei, index)
for row in laptop_back:
print("".join(row))
|
'''
Create a class to represent a patient of a doctor's office.
The Patient class will accept the following information during initialization
Social security number
Date of birth
Health insurance account number
First name
Last name
Address
The first three properties should be read-only.
First name and last name should not be exposed as properties at all,
but instead expose a calculated property of full_name.
Address should have a getter and setter.
'''
class Patient:
def __init__(self, ssn, dob, insur_num, f_name, l_name, addr):
self.__ssn = ssn
self.__dob = dob
self.__insur_num = insur_num
self.full_name = f'{f_name} {l_name}'
self.addr = addr
@property
def social_security_number(self):
try:
return self.__ssn
except AttributeError:
return 0
@property
def dob(self):
try:
return self.__dob
except AttributeError:
return 0
@property
def insur_num(self):
try:
return self.__insur_num
except AttributeError:
return 0
def first_name(self):
return 0
def last_name(self):
return 0
cashew = Patient(
"097-23-1003", "08/13/92", "7001294103",
"Daniela", "Agnoletti", "500 Infinity Way"
)
# This should not change the state of the object
cashew.social_security_number = "838-31-2256"
# Neither should this
cashew.date_of_birth = "01-30-90"
# But printing either of them should work
print(cashew.social_security_number) # "097-23-1003"
# These two statements should output nothing
print(cashew.first_name)
print(cashew.last_name)
# But this should output the full name
print(cashew.full_name) # "Daniela Agnoletti"
|
import csv
def timetable(x, y):
x = int(input)
y = int(input)
for x in range(50):
product = x * y
result = product
return result
def timetable(x, y):
if x < y:
return x
return y
def love(name):
first_name = input("Enter your first name: ")
middle_name = input("Enger your middle name: ")
last_name = input("Enter your last name: ")
name = first_name +" "+ middle_name + " "+ last_name
return name
def read_me(file_name):
with open(file_name) as file:
read_file = list(csv.reader(file))
return read_file
def add(x, y):
if x < y:
sum = x + y
if y < x :
diff = y - x
return diff
return sum
def fun(first_name, last_name):
first_name = input("Enter your name: ")
last_name = input("Enter last name: ")
return first_name, last_name
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 1 16:25:58 2018
@author: yangyang43
"""
alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
alist.sort(key=lambda x:x['age'])
print(alist)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 22:11:27 2019
练习
杨辉三角定义如下:
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
@author: yangyang43
"""
def triangles(n):
mylist = [1]
x = 0
while (x<n+1):
yield mylist
x += 1
mylist = [1] + [mylist[n] + mylist[n+1] for n in range(len(mylist)-1)] + [1]
def main():
for i in triangles(6):
print (i)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 10:25:58 2018
@author: yangyang43
"""
def is_amsteron(num):
if type(num) != int:
print ("Invalid input")
return
mystr = str(num)
lenth = len(mystr)
sum = 0
for x in mystr[:]:
sum += int(x)**lenth
if sum == num:
print ("{0} is an amsteron number".format(num))
else:
print ("{0} is not an amsteron number".format(num))
is_amsteron(408)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 22 16:12:12 2018
@author: yangyang43
"""
def reverse_list(L):
lenth = len(L)
i = 0
while (i < lenth/2):
L[lenth-1-i],L[i] = L[i],L[lenth-1-i]
i += 1
myList = [1,2,3,4,5,6]
reverse_list(myList)
print (myList)
|
from sys import argv
import csv
import os.path
from core import helpers
from core import sudoku
if len(argv) != 3:
print("Two args are mandatory for sudoku command:")
print("1) csv file path for reading input matrix")
print("2) csv file path for writing resolved matrix")
exit()
sourcePath = argv[1]
destPath = argv[2]
if not os.path.isfile(sourcePath):
print ("Source file path not exist")
exit()
initialMatrix = helpers.createArrayOfEmptyArrays()
with open(sourcePath) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
for i in range(0,9):
initialMatrix[line_count].append(int(row[i]))
line_count += 1
sudokuInstance = sudoku.Sudoku(initialMatrix)
resolvedMatrix = sudokuInstance.resolve()
with open(destPath, mode='w') as resolved:
resolved = csv.writer(resolved, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for i in range(0,9):
resolved.writerow(resolvedMatrix[i])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r'''
AddNum2Pic.py
A python test project
Add a number to a picture.
'''
import os, sys
from PIL import Image, ImageFont, ImageDraw
def addNum2Pic( picPath, num):
print( picPath )
print( num )
pic = Image.open( picPath )
w, h = pic.size
fontsize = min( w, h ) // 6
x = w - fontsize
draw = ImageDraw.Draw( pic )
font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSans.ttf", fontsize )
draw.text( ( x, 0 ), str(num), font=font, fill="red" )
del draw
pic.save("newHead.jpg")
pic.show()
if __name__ == '__main__':
addNum2Pic( 'head.jpg', 8 );
|
import os
import csv
# path to collect data from the Resources folder
csvpath = os.path.join('budget_data.csv')
csv_output =os.path.join("results.txt")
with open(csvpath) as csvfile:
reader = csv.reader(csvfile)
header =next(reader)
total_months = 0
total_profit_loss = 0
total_sum = 0
prev_profit_loss = 0
greatest_increase = ["",0]
greatest_decrease = ["" ,9999999]
profit_loss_change = []
for row in reader:
total_months = total_months + 1
total_sum = total_sum + int(row[1])
net_change =int(row[1]) - prev_profit_loss
# Keep track of changes
profit_loss_change += [net_change]
print(profit_loss_change)
# Reset values of prev_profit_loss to complete row
prev_profit_loss = int(row[1])
print(prev_profit_loss)
# Greatest increase in profit (date and amount) over entire period increase_profit = total_profit - int(row[1])
# if (profit_loss_change > greatest_increase[1]):
greatest_increase[1] =profit_loss_change
greatest_increase[0] =row[1]
if (net_change > greatest_decrease[1]):
greatest_decrease[1] =profit_loss_change
greatest_decrease[0] =row[1]
#Add to profit_loss_changes list
profit_loss_change.append(int(row["profit/losses"]))
#Create the profit loss average
profit_loss_avg = sum(profit_loss_change) / len(profit_loss_change)
# Print
print("Financial Analysis")
print("--------------")
print("Total Months: " +str(total_months))
print("Total : " + "$" + str(total_sum))
print("Average Change: " + "$" + str(round(profit_loss_avg, 2)))
print("Greatest Increase: " + str(greatest_increase[0]) + "$" + str(greatest_increase[1]))
print("Greatest Decrease: " + str(greatest_decrease[0]) + "$" + str(greatest_decrease[1]))
# #Output Files
with open(csv_output, "w") as txt_file:
txt_file.write("Total Months: " + str(total_months))
txt_file.write("\n")
txt_file.write("Total: " + "$" + str(total_months))
txt_file.write("\n")
txt_file.write(str(profit_loss_avg))
txt_file.write("Average Change" + str(round(profit_loss_avg, 2)))
txt_file.write("\n")
txt_file.write("Greatest Increase: " + str(greatest_increase))
txt_file.write("\n")
txt_file.write("Greatest decrease: " + str(greatest_decrease[0]) + "($" + str(greatest_decrease[1]) + ")")
|
import sys
def print_puzzle(puzzle):
for row in puzzle:
print(" ".join([str(num) for num in row]))
def find_empty_position(puzzle):
for row in range(9):
for col in range(9):
if puzzle[row][col] == 0:
return row, col
return -1, -1
def can_place_number(number, puzzle, row, col):
for i in range(9):
if puzzle[row][i] == number:
return False
for i in range(9):
if puzzle[i][col] == number:
return False
for i in range(3):
for j in range(3):
if puzzle[i + (row - row % 3)][j + (col - col % 3)] == number:
return False
return True
def solve_puzzle(puzzle):
row, col = find_empty_position(puzzle)
if row == -1:
print_puzzle(puzzle)
return True
for number in range(1, 10):
if can_place_number(number, puzzle, row, col):
puzzle[row][col] = number
if solve_puzzle(puzzle):
return True
puzzle[row][col] = 0
return False
if __name__ == "__main__":
lines = [line.strip('\n') for line in sys.stdin]
num_puzzles = int(lines[0])
puzzles = [
[
[int(c) for c in lines[j*i + 1].replace(" ", "")]
for j in range(9)
]
for i in range(1, num_puzzles + 1)
]
for sudoku_puzzle in puzzles:
solve_puzzle(sudoku_puzzle)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# Going through LinkedList and returning an Integer
def linked_to_int(self, node: ListNode) -> int:
data = ''
current = node
# if the current node is not null continue on
while current != None:
data += str(current.val)
current = current.next
return int(data)
def int_to_linked(self, number: int) -> ListNode:
# return head of LinkedList
number = str(number)[::-1]
current = None
for i in range(len(number)):
if current == None:
current = ListNode(int(number[i]))
elif current != None:
current.next = ListNode(number[i])
current = current.next
return current
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
sum = self.linked_to_int(l1) + self.linked_to_int(l2)
return self.int_to_linked(sum)
'''
Took 48 ms
'''
|
class Solution:
def romanToInt(self, s: str) -> int:
doubles = { 'CM': 900, 'CD': 400, 'XC': 90, 'XL': 40 , 'IX': 9, 'IV': 4}
singles = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I':1}
integer = 0
i = 0
while i < len(s):
if i < len(s)-1 and s[i:i+2] in doubles:
integer += doubles[s[i:i+2]]
i += 2
else:
integer += singles[s[i]]
i += 1
return integer
'''
Runtime: 68 ms, faster than 56.59% of Python3 online submissions.
Memory Usage: 13.4 MB, less than 33.68% of Python3 online submissions.
Given a roman numeral, convert it to an integer.
'''
|
a = int(input ("Digite um número inteiro: "))
if a % 3 == 0:
print ("Fizz")
else:
print (a)
|
a = int(input ("Digite um número inteiro: "))
b = int(input ("Digite outro número inteiro: "))
c = int(input ("Digite outro número inteiro: "))
if a < b and a < c and b < c:
print ("crescente")
else:
print ("não está em ordem crescente")
|
def compara_vogal(letra):
if letra == "a" or letra == "e" or letra == "i" or letra == "o" or letra == "u":
return True
else:
return False
letra = input (str("Digite uma letra: "))
resposta = compara_vogal(letra)
print (resposta)
|
from random import *
def qSort(a):
if len(a) <= 1:
return a
else:
q = choice(a)
return qSort([elem for elem in a if elem < q]) + [q] * a.count(q) + qSort([elem for elem in a if elem > q])
arr = [9, 1, 3, 5]
print qSort(arr)
|
variavel=" "
def parametroString():
variavel=input("Insira os caracteres {[()]}: ")
if "{[()]}" in variavel:
print("Parâmetro ok!",True)
return True
elif "{[()()]}" in variavel:
print("Parâmetro ok!",True)
return True
else:
print("Algo deu errado...",False)
return False
parametroString()
|
import datetime
class UserInput:
def __init__(self):
pass
def addEmpSSN(self, emp_type):
print()
return input("\nEnter the new {}'s ssn: ".format(emp_type)).capitalize()
def addEmpName(self, emp_type):
return input("\nEnter {} first and last name (Non-Icelandic characters): ".format(emp_type))
def addEmpRank(self, emp_type):
if emp_type == "Pilot":
print("\n1: Captain\n2: Copilot")
return input("\nChoose a rank: ")
else:
print("\n1: Flight Service Manager\n2: Flight Attendant")
return input("\nChoose a rank: ")
def addEmpEmail(self, emp_type):
return input("\nEnter {}'s email address (@NaNAir.com will be added to it): ".format(emp_type))
def addEmpLicens(self, emp_type):
if emp_type != "Cabincrew":
print("\n1: FokkerF100\n2: FokkerF28\n3: BAE146")
choice = input("\nChoose a plane type: ")
return choice
else:
return "N/A"
def addEmpAddress(self, emp_type):
return input("\nEnter the new {}'s address (Non-Icelandic characters): ".format(emp_type)).capitalize()
def addEmpMobile(self, emp_type):
return input("\nEnter the new {}'s mobile number (7 digits): ".format(emp_type)).capitalize()
def addHomePhone(self, emp_type):
return input("\nEnter the new {}'s home phone number (7 digits): ".format(emp_type)).capitalize()
def addLocCountry(self):
return input("\nEnter the new location's country (Non-Icelandic characters): ").capitalize()
def addLocCountryAbbrev(self):
return input("\nEnter the new location's airport's id (3 letters, ex.: Keflavik = KEF): ").upper()
def addLocName(self):
return input("\nEnter the new location's internal name (Non-Icelandic characters): ").capitalize()
def addLocAirport(self):
return input("\nEnter the new location's aiport's name (Non-Icelandic characters): ").capitalize()
def addLocFlightTimeHour(self):
return input("\nEnter the new location's flight time (Hours): ")
def addLocFlightTimeMin(self):
return input("\nEnter the new location's flight time (Minutes): ")
def addLocDist(self):
return input("\nEnter the distance from Iceland (est. kilometers): ")
def addLocContactName(self):
return input("\nEnter the new location's contact's name (Non-Icelandic characters): ")
def addLocContactNum(self):
return input("\nEnter the new location's emergency phone number (Non-Icelandic characters): ")
def enterSSN(self, emp_type):
ssn = input("\nEnter a{}'s SSN: ".format(emp_type))
#Check hvort að kennitalan tilheyri einhverjum starfsmanni
return ssn
def addTripDest(self):
return input("\nEnter trip destination id (Not KEF) 'HELP' to show all destinations: ").upper()
def addTripDepTime(self):
print("\nNow entering a departure time and date:")
while True:
work_dep_day = input("\nEnter a day (dd): ").zfill(2)
work_dep_month = input("Enter a month (mm): ").zfill(2)
work_dep_year = input("Enter a year (yyyy): ")
work_dep_hour = input("Enter an hour (HH): ")
work_dep_min = input("Enter minutes (MM): ")
work_dep_sec = "00"
work_departure_time = "{}-{}-{} {}:{}:{}".format(work_dep_year, work_dep_month, work_dep_day, work_dep_hour, work_dep_min, work_dep_sec)
try:
work_date = datetime.datetime.strptime(work_departure_time, '%Y-%m-%d %H:%M:%S')
return work_date
except:
print("There was something wrong with your input, please try again")
def addTripPlaneID(self):
return input("\nEnter plane insignia (3 letters) (Keep empty if you don't want to enter one) 'HELP' to show all planes: TF-").upper()
def addTripCaptain(self):
return input("\nEnter the Captain's SSN (Keep empty if you don't want to enter one) 'HELP' to show all captains: ")
def addTripCopilot(self):
return input("\nEnter the Co-Pilot's SSN (Keep empty if you don't want to enter one) 'HELP' to show all copilots: ")
def addTripFSM(self):
return input("\nEnter a flight service manager's SSN (Keep empty if you don't want to enter one) 'HELP' to show all flight service managers: ")
def addTripFA(self):
return input("\nEnter a flight attendant's SSN (Keep empty if you don't want to enter one): ")
def addPlane(self):
plane_data_list = []
while True:
print("\n1: FokkerF100\n2: FokkerF28\n3: BAE146")
choice = input("\nChoose a plane type: ")
planedict = {"1":"NAFokkerF100","2":"NAFokkerF28","3":"NABAE146"}
try:
plane_type = planedict[choice]
break
except:
print("Input invalid")
plane_data_list.append(plane_type)
planeinsignia = input("\nEnter plane Insignia (3 letters): TF-").upper()
#if __checker.planeinsignia(planeinsignia)
planeinsignia = "TF-" + planeinsignia
plane_data_list.append(planeinsignia)
return plane_data_list
def enterVariable(self, to_enter):
return input("\nEnter a new {}: ".format(to_enter))
def enterEditTripPlaneID(self):
return input("\nEnter plane insignia (3 letters) 'HELP' to show all planes: TF-").upper()
def enterEditTripCaptain(self):
return input("\nEnter the Captain's SSN ('HELP' to show all captains): ")
def enterEditTripCopilot(self):
return input("\nEnter the Co-Pilot's SSN ('HELP' to show all copilots): ")
def enterEditTripFSM(self):
return input("\nEnter a flight service manager's SSN ('HELP' to show all flight service managers): ")
def enterEditTripFA(self):
return input("\nEnter a flight attendant's SSN ('HELP' to show all flight attendants): ")
def enterEmail(self):
return input("\nEnter a new email (@NaNAir.is will be added to it): ")
def askForDate(self):
'''Asking for a specific date to show work trips by day'''
day = input("\nEnter day (DD): ")
month = input("\nEnter month (MM): ")
year = input("\nEnter year (YYYY): ")
date = year + "-" + month + "-" + day
return date
def askForLocID(self):
return input("\nEnter a location's ID (ex.: KEF): ").upper()
|
class Nodes(object):
def __init__(self, treeDict =None):
if(treeDict is None):
self.treeDict = {}
else:
self.treeDict = treeDict
def showNodes(self):
return list(self.treeDict.keys())
def findPath(self, limit, startNode, goalNode, stack=None, path=None, stackyStack=None, cost=0):
if(path==None):
path=[]
if(stack==None):
stack=[startNode]
if(stackyStack==None):
stackyStack=[]
tree = self.treeDict
if(startNode not in tree):
return None
# print(stack)
path = path + [startNode]
stackyStack.append(stack)
# print(stack)
if(startNode==goalNode):
return path,cost,stackyStack
temp = stack.pop(0)
stack = tree[temp] + stack
cost+=1
for value in tree[startNode]:
if(value not in path):
extended_path = self.findPath(limit, value, goalNode, stack, path, stackyStack, cost)
if extended_path:
return extended_path
return None
n = int(input("Enter no of nodes : "))
g={}
for i in range(n):
sNode = input("Enter node => ")
cNodes = input("Enter its child node => ").split()
g[sNode] = cNodes
for key,val in g.items():
print(f'{key} -> {val}')
n = Nodes(g)
n.showNodes() # displays all nodes..
startNode = input("Enter start node : ")
goalNode = input("Enter goal node : ")
limit = int(input("Enter depth : "))
pathy,costy,stackyStacky= n.findPath(limit,startNode,goalNode) #displays
if(limit>=costy):
for i in stackyStacky:
print(i)
print("Pathy -> ",pathy)
print("Costy -> ",costy)
else:
print("Not reachable")
|
import pandas as pd
import datetime
import csv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.style.use('bmh')
df = pd.read_csv("netflix_titles.csv")
df.dataframeName = 'netflix_titles.csv'
nRow, nCol = df.shape
print(f'There are {nRow} rows and {nCol} columns')
# How many movies and TV shows are on the Netflix Platorm?
media = df['type'].value_counts()
media_list = media.tolist()
print(media_list)
df['type'].value_counts().plot(kind='bar')
plt.xlabel("Type", labelpad=14)
plt.ylabel("Count", labelpad=14)
plt.title("Count of Movies and Shows", y=1.02)
|
from math import factorial as fact
from constant import romans, romanLetters
def factorial(numStr):
try:
n = int(numStr)
r = str(fact(n))
except:
r = 'Error!'
return r
def decToBin(numStr):
try:
n = int(numStr)
r = bin(n)[2:]
except:
r = 'Error!'
return r
def binToDec(numStr):
try:
n = int(numStr, 2)
r = str(n)
except:
r = 'Error!'
return r
def decToRoman(numStr):
try:
n = int(numStr)
except:
return 'Error!'
if n >= 4000:
return 'Error!'
result = ''
for value, letters in romans:
while n >= value:
result += letters
n -= value
return result
def romanToDec(numStr):
try:
romanNum = str(numStr)
for num in romanNum:
if num not in romanLetters:
raise ValueError #원래 INDEXERROR였는데 바꿨어
except ValueError:
return 'Error!'
# MMMCMXCIX = 3999
result = 0
for i in range(len(romanNum)):
n = 1
if i+1 <= len(romanNum)-1 and (romanNum[i] + romanNum[i+1]) in romanLetters:
n = (-1)
result += romans[romanLetters.index(romanNum[i])][0] * n
return str(result)
|
import time
# Example 1
# 下面这段代码,实际上是用deco函数在给run函数加一个计时器的功能,而任何包含了@deco的函数,都会有这样的功能
# 这样做的好处主要有:
# 1)每个需要记时的函数,只需要@deco就可以了,这样可以节省很多代码量,
# 2)在不改变run1,run2代码的基础上,就能实现给两个函数加功能
def deco(func):
def wrapper():
start = time.time()
func()
end = time.time()
print(f'{round(end - start, 4)} seconds used.')
return wrapper
@deco
def run1():
for i in range(100):
if i % 10 == 0:
print(i)
@deco
def run2():
time.sleep(2)
run1()
run2()
"""
这里的deco函数就是最原始的装饰器,它的参数是一个函数,然后返回值也是一个函数。
其中作为参数的这个函数func()就在返回函数wrapper()的内部执行。然后在函数func()前面加上@deco,
func()函数就相当于被注入了计时功能,现在只要调用func(),它就已经变身为“新的功能更多”的函数了。
所以这里装饰器就像一个注入符号:有了它,拓展了原来函数的功能既不需要侵入函数内更改代码,也不需要重复执行原函数。
"""
# Example 2
# 装饰器带有参数,这些参数其实就是我想要加功能的函数的参数,这里的wrapper其实可以看作是函数的抽象类
def deco(func):
def wrapper(a, b):
start = time.time()
func(a, b)
end = time.time()
print(f'{round(end - start, 4)} seconds used.')
return wrapper
@deco
def add(a, b):
print(a + b)
@deco
def mul(a, b):
print(a * b)
add(3, 4)
mul(3, 4)
# Example 3
# 装饰器带有不定个数的参数
def deco(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print(f'{round(end - start, 4)} seconds used.')
return wrapper
@deco
def add1(a, b):
print(a + b)
@deco
def add2(a, b, c):
print(a + b + c)
add1(3, 4)
add2(3, 4, 5)
# Example 4
# 多个装饰器
# 多个装饰器执行的顺序就是从最后一个装饰器开始,执行到第一个装饰器,再执行函数本身。
def deco1(func):
def wrapper(*args, **kwargs):
start = time.time()
print('this is deco1.')
func(*args, **kwargs)
end = time.time()
print(f'{round(end - start, 4)} seconds used.')
print('deco1 end.')
return wrapper
def deco2(func):
def wrapper(*args, **kwargs):
start = time.time()
print('this is deco2.')
func(*args, **kwargs)
end = time.time()
print(f'{round(end - start, 4)} seconds used.')
print('deco2 end.')
return wrapper
@deco1
@deco2
def add(a, b):
print(a+b)
add(3, 4)
# Example 5 (类中的装饰器)
class Student(object):
def __init__(self):
self._score = None
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
# 小练习
# 请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution:
class Screen(object):
def __init__(self):
self._width = None
self._height = None
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def resolution(self):
return self.width * self.height
# 测试
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
print('测试通过!')
else:
print('测试失败!')
|
import unittest
from my_bank.account import Account
from my_bank.bank import Bank
class BankTest(unittest.TestCase):
def test_bank_is_initially_empty(self):
bank = Bank()
self.assertEqual({}, bank.accounts)
self.assertEqual(len(bank.accounts),0)
def test_add_account(self):
bank = Bank()
account_1 = Account("001", 50)
account_2 = Account("002", 100)
bank.add_account(account_1)
bank.add_account(account_2)
self.assertEqual(len(bank.accounts),2)
def test_get_account_balance(self):
bank = Bank()
account_1 = Account("001", 50)
bank.add_account(account_1)
self.assertEqual(bank.get_account_balance("001"),50)
if __name__ == "__main__":
unittest.main()
|
'''
列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可
'''
# list1=['Google','Runoob',1997,2000]
# list2=[1,2,3,4,5,6,7]
# list3=["a","b","c",'d']
'''
访问列表中的值
使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符
'''
# print('list1[0]:',list1[0])
# print('list2[1:5]:',list2[1:5])
'''
更新列表
你可以对列表的数据项进行修改或更新
'''
# print('打印第三个元素:',list1[2])
# list1[2]=2001
# print(list1)
'''
删除列表元素
可以使用 del 语句来删除列表的的元素
'''
# list = ['Google', 'Runoob', 1997, 2000]
# del list[2]
# print(list)
'''
Python列表脚本操作符
+ 号用于组合列表,* 号用于重复列表。
'''
# print(len([1,2,3]))
# print([1,2,3]+[4,5,6])
# print(['hello']*4)
# print(3 in [1,2,3])
# for x in [1,2,3]:
# print(x,end=" ")
'''
列表还支持拼接操作
使用嵌套列表即在列表里创建其它列表
'''
# squares = [1, 4, 9, 16, 25]
# squares+=[36, 49, 64, 81, 100]
# print(squares)
# a = ['a', 'b', 'c']
# n = [1, 2, 3]
# x=[a,n]
# print(x)
# print(x[0])
# print(x[0][1])
'''
Python列表函数
len()
max()
min()
list(seq) -- 将元组或字符串转换为列表
'''
# list1 = ['Google', 'Runoob', 'Taobao']
# print (len(list1))
# list2=list(range(5)) # 创建一个 0-4 的列表
# print (len(list2))
# list1, list2 = ['Google', 'Runoob', 'Taobao'], [456, 700, 200]
# print ("list1 最大元素值 : ", max(list1))
# print ("list2 最大元素值 : ", min(list2))
# aTuple = (123, 'Google', 'Runoob', 'Taobao')
# list1 = list(aTuple)
# print ("列表元素 : ", list1)
# str="Hello World"
# list2=list(str)
# print ("列表元素 : ", list2)
'''
Python包含以下方法
list.append(obj)--在列表末尾添加新的对象
'''
# list1 = ['Google', 'Runoob', 'Taobao']
# list1.append('Baidu')
# print ("更新后的列表 : ", list1)
a=[1,2,3]
b=[2,3,4]
diff=list(set(a).difference(set(b)))
print(diff)
|
__author__ = 'Aman'
name = "Lucy"
if name is "Bucky": # this is how you say if name == bucky
print("Hey there Bucky")
elif name is "Lucy":
print("What up Lucedawg")
elif name is "Sammy" :
print("What up Sammy")
else :
print( " Hi ")
|
__author__ = 'kaman'
class Tuna :
def __init__(self): #this is something similar to initialization, so when ever you make an object of class this will be executed
#you can conclude that _init_ is a constructor
print("Initialization function")
def swim(self):
print("Tuna Swiming")
tuna1 = Tuna()
tuna1.swim()
print('New Class')
class Enemy:
def __init__(self,x):
self.energy = x
def get_energy(self):
print(self.energy)
jason = Enemy(10)
jason.get_energy()
sandy = Enemy(20)
sandy.get_energy()
|
class Movie(object):
"""This is a movie object, containing information about a movie
Attributes:
movie_title (str): the title of the movie
poster_image (str): a URL for the movie poster
trailer_youtube (str): a youtube URL for the trailer
genre (str): the movie's genre
release_year (str): the year of the movie's release
"""
def __init__(self, movie_title, poster_image,
trailer_youtube, genre, release_year):
self.title = movie_title
self.poster_image = poster_image
self.summary = ""
self.trailer = trailer_youtube
self.genre = genre
self.year = release_year
|
#Enthalpy Changes
#This program calculates the amount of energy and cost to melt some snow.
#Water c 4.187 kJ/kgK, Ice C 2.108 kJ/kgK
#Enthalpy of Vaporization 2.030 mJ/kg
#Enthalpy of Fusion 334 kJ/kg
print ("This program calculates the amount of energy and cost to melt some snow in a rectangular area.");
print ("<Enter> after every input.")
print ("First the dimensions of the area you want to clear, in metres (m): ")
length = int(input ("Length: "))
width = int(input ("Width: "))
depth = float(input ("Depth: "))
vol = length*width*depth
print ("You have %f cubic metres of snow." % (vol))
print ("How dense is the snow?\n0 for dusting\n1 : light\n2 : medium\n3 : dense\n4 : solid ice")
iRho = int(input ("Density: "))
rho = 3; #default kg m-3
if (iRho == 0):
rho = 50
elif (iRho == 1):
rho = 100
elif (iRho == 2):
rho = 250
elif (iRho == 3):
rho = 400
elif (iRho == 4):
rho = 900
mass = rho*vol
print ("Density is approximately %i kg per cubic metre."%(rho ))
print ("There is %f kg of snow on the ground." % (mass))
temp = int(input("What's the negative temperature outside (Degrees Celcius)? Enter an integer: -"))
eMelt = ((temp+1) * mass * 2.108) + (mass*334000) #energy req to melt and fuse
eVap = (100*mass*4.187) + (mass*2030000) + eMelt
print()
print ("To melt this snow and bring it to 1 degree, it will take %f J of energy. \nThis is equivalent to %f TJ." % (eMelt, eMelt/1e12))
print ("To completely vaporize this snow, it will take %f J of energy.\nThis is equivalent to %f TJ." % (eVap, eVap/1e12))
print()
print("For reference, this is approximately %f nuclear detonations to melt." % (eMelt/1e17))
print("For reference, this is approximately %f nuclear detonations to vaporize." % (eVap/1e17))
choice = int(input ("Press 1 to melt, press 2 to vaporize. "))
time = int(input ("How long do you have? Time in minutes: "))
eChoice = 0
if choice == 1:
eChoice = eMelt
elif choice == 2:
eChoice = eVap
else:
print ("Vaporize is the default. The option has been set to vaporization.")
eChoice = eVap
powerDraw = eChoice/(time*60)
print ("This will draw %f megawatts (MW) of power..." % (powerDraw/1e6))
print()
cpW = float(input ("How much does 1 kWh (kilowatt hour) cost where you live? Cost:$ "))
cost = cpW * eChoice/3.6e6
print ("This will cost you $%f" % (cost))
|
import unittest
from chess.board import Board
from chess.piece import Piece
from chess.pawn import Pawn
from chess.exceptions import InvalidInputException
class TestBoard(unittest.TestCase):
def setUp(self):
self.board = Board()
def test_init(self):
self.assertEqual(self.board.__board__, [[None for x in range(8)] for y in range(8)])
def test_convert_pos_to_array(self):
posx, posy = self.board.convert_pos_to_array('c', 5)
self.assertEqual(posx, 2)
self.assertEqual(posy, 4)
posx, posy = self.board.convert_pos_to_array('h', 1)
self.assertEqual(posx, 7)
self.assertEqual(posy, 0)
self.assertRaises(InvalidInputException, lambda: self.board.convert_pos_to_array('i', 1))
self.assertRaises(InvalidInputException, lambda: self.board.convert_pos_to_array('a', 9))
self.assertRaises(InvalidInputException, lambda: self.board.convert_pos_to_array('a', -1))
self.assertRaises(InvalidInputException, lambda: self.board.convert_pos_to_array('a', 0))
self.assertRaises(InvalidInputException, lambda: self.board.convert_pos_to_array('i', 0))
def test_convert_array_to_pos(self):
self.assertEqual(self.board.convert_array_to_pos(2, 3), '<C:4>')
self.assertRaises(InvalidInputException, lambda: self.board.convert_array_to_pos(0, 8))
self.assertRaises(InvalidInputException, lambda: self.board.convert_array_to_pos(-1, 8))
self.assertRaises(InvalidInputException, lambda: self.board.convert_array_to_pos(-1, 9))
def test_get_piece_at(self):
self.board.__board__[1][2] = 1
self.assertIsNone(self.board.get_pieceAt(0,0))
self.assertIsNotNone(self.board.get_pieceAt(1,2))
self.assertIsNone(self.board.get_pieceAt(-1, 0))
self.assertIsNone(self.board.get_pieceAt(1, 9))
|
# -*- coding: utf-8 -*-
def add_1(xs):
return [x + 1 for x in xs]
def square(xs):
return [x ** 2 for x in xs]
def squared_mean(xs):
return sum((x ** 2 for x in xs)) / len(xs)
|
class Solution(object):
def isMatch(self, s, p):
if p and s:
if p[0] == s[0] or p[0] == ".":
if len(p) > 1 and p[1] == '*':
return self.isMatch(s[1:], p)
return self.isMatch(s[1:], p[1:])
else:
if len(p) > 1 and p[1] == '*':
return self.isMatch(s, p[2:])
elif not p and not s:
return True
elif p and not s:
if len(p) == 2 and p[1] == '*': return True
return False
test = Solution()
print(test.isMatch("aa","a"))
print(test.isMatch("aa","aa"))
print(test.isMatch("aaa","aa"))
print(test.isMatch("aa","a*"))
print(test.isMatch("aa",".*"))
print(test.isMatch("ab",".*"))
print(test.isMatch("aab","c*a*b"))
print(test.isMatch("ab",".*c"))
|
# --- Day 1: The Tyranny of the Rocket Equation ---
import math
fuelTotal= 0
input_file = open('input', 'r')
count_lines = 0
for line in input_file:
#print (line, end = '')
#count_lines += 1
mass = float(line)
fuelNeeded = math.floor(mass / 3) - 2
fuelTotal = fuelTotal + fuelNeeded
print (fuelTotal, end='')
|
from abc import ABCMeta, abstractmethod
class Iterator(metaclass=ABCMeta):
"""
Абстрактный итератор
"""
_error = None # класс ошибки, которая прокидывается в случае выхода за границы коллекции
def __init__(self, collection, cursor) -> None:
"""
Constructor.
:param collection: коллекция, по которой производится проход итератором
:param cursor: изначальное положение курсора в коллекции (ключ)
"""
self._collection = collection
self._cursor = cursor
@abstractmethod
def current(self) -> object:
"""
Вернуть текущий элемент, на который указывает итератор
"""
pass
@abstractmethod
def next(self) -> object:
"""
Сдвинуть курсор на следующий элемент коллекции и вернуть его
"""
pass
@abstractmethod
def has_next(self) -> bool:
"""
Проверить, существует ли следующий элемент коллекции
"""
pass
@abstractmethod
def remove(self) -> None:
"""
Удалить текущий элемент коллекции, на который указывает курсор
"""
pass
def _raise_key_exception(self) -> None:
"""
Прокинуть ошибку, связанную с невалидным индексом, содержащимся в курсоре
"""
raise self._error('Collection of class {} does not have key "{}"'.format(
self.__class__.__name__, self._cursor))
class ListIterator(Iterator):
"""
�тератор, проходящий по обычному списку
"""
_error = IndexError
def __init__(self, collection: list) -> None:
super().__init__(collection, 0)
def current(self) -> object:
if self._cursor < len(self._collection):
return self._collection[self._cursor]
self._raise_key_exception()
def next(self) -> object:
if len(self._collection) >= self._cursor + 1:
self._cursor += 1
return self._collection[self._cursor]
self._raise_key_exception()
def has_next(self) -> bool:
return len(self._collection) >= self._cursor + 1
def remove(self) -> None:
if 0 <= self._cursor < len(self._collection):
self._collection.remove(self._collection[self._cursor])
else:
self._raise_key_exception()
|
def mySqrt(x: int) -> int:
left = 0
right = x
while left <= right:
mid = (right+left)//2
if mid**2 == x:
return mid
elif mid**2 < x:
left = mid + 1
ans = mid
else:
right = mid - 1
return ans
if __name__ == '__main__':
print(mySqrt(8))
|
def returnOdd(array) :
for i in range(0, len(array)) :
if i % 2 != 0 :
print(array[i])
arr = [None]
enter = 0
while enter != "f" :
enter = input("Enter values. Enter f when done. ")
arr.append(enter)
del arr[0]
del arr[-1]
returnOdd(arr)
|
n = int(input("This program prints out the first nth prime numbers. \nEnter n as an integer: "))
x = 1 #The xth number in the list of 1 to n.
cand = 1 #The candidate number, check this for whether prime or not.
nprime = 0 #Boolean for whether to print cand or not.
while x <= n :
for i in range(1, cand) :
if cand % i == 0 and i != 1 and i != cand:
nprime = 1
if nprime == 0 :
print(cand)
x = x + 1
cand = cand + 1
nprime = 0
|
def readText(filename) :
file = open(filename, "r")
text = file.read().lower()
textList = text.split()
return textList
def findWord(string, textList) : #generates a list that contains all the positions (elements of all matching words
return [y for y in range(0, len(textList)) if textList[y] == string]
def cycleSearch(array, count, textList) : #generates a list containing lists of the matching words with "count" words after them
arr = []
for i in range(0, len(array)) :
arr.append(viewAhead(array[i], count, textList))
return arr
def viewAhead(num, count, textList) : #adds "count" words after the matching words to their respective lists.
arr = []
for i in range(num, num + count) :
try :
arr.append(textList[i])
except IndexError :
arr.append(None)
return arr
def mostCommon(array, element, fin) : #returns a list that contains all the words element places after and their occurences in order.
wordList = []
for i in range(0, len(array)) :
wordList.append(array[i][element])
count = wordHelp(wordList)
ordered = []
for x in range(0, len(count)) :
for y in range(0, len(array)) :
if count[x][0] == array[y][element] :
temp = []
for i in array[y] :
temp.append(i)
ordered.append(temp)
for x in range(0, len(count)) :
temp = []
for y in range(0, len(ordered)) :
if count[x][0] == ordered[y][element] :
temp.append(ordered[y])
try :
mostCommon(temp, element + 1, fin)
except IndexError :
for i in ordered :
fin.append(i)
break
return
def wordHelp(wordList) : #returns a list with all strings and their occurences in the given list.
skip = False
count = []
for x in range(0, len(wordList)) :
for y in range(0, len(count)) :
if wordList[x] == count[y][0] :
skip = True
count[y][1] += 1
break
if not skip :
count.append([wordList[x], 1])
else :
skip = False
#randomize(count)
for x in range(0, len(count)) :
for y in range(0, x) :
if count[x][1] > count[y][1] :
temp = count[x]
count[x] = count[y]
count[y] = temp
return count
def randomize(array) :
import random
for x in range(0, len(array)) :
array[x][1] = random.randint(1, array[x][1])
def printFin(fin) :
for x in range(0, len(fin)) :
temp = ""
for y in fin[x] :
try :
temp += y + " "
except TypeError :
break
print(temp)
return
def removeDuplicates(array) :
skip = False
arr = []
for x in array :
for y in arr :
if x == y :
skip = True
break
if not skip :
arr.append(x)
else :
skip = False
return arr
textList = readText("Text2.txt")
enter = input("Search: ")
wordcount = int(input("Number of words to generate: "))
pos = findWord(enter, textList)
arr = cycleSearch(pos, wordcount, textList)
fin = []
mostCommon(arr, 1, fin)
fin = removeDuplicates(fin)
printFin(fin)
|
print("This program tells you the size of a planet and its distance in kilometers from Earth.")
print("Enter the name of a planet in the Solar System: ")
input = input()
if input == "Mercury" :
print("Diameter: 4,878")
print("Distance: 92,000,000")
if input == "Venus" :
print("Diameter: 12,104")
print("Distance: 42,000,000")
if input == "Earth" :
print("Diameter: 12,756")
print("Distance: 0")
if input == "Mars" :
print("Diameter: 6,780")
print("Distance: 78,000,000")
if input == "Jupiter" :
print("Diameter: 139,822")
print("Distance: 628,000,000")
if input == "Saturn" :
print("Diameter: 116,464")
print("Distance: 1,277,000,000")
if input == "Uranus" :
print("Diameter: 50,724")
print("Distance: 2,720,000,000")
if input == "Neptune" :
print("Diameter: 49,248")
print("Distance: 4,347,000,000")
|
import re
def validateEmail(address):
if re.search(pattern = '[a-zA-Z]+@[a-zA-Z]+\.[a-z]+', string = address) != None:
return True
else:
return False
def validateDate(date):
if re.search(pattern = '[1-3]?[0-9]/1?[0-9]/[1-9]+', string = date) != None:
return True
else:
return False
print(validateEmail(r'testTest@gmail.com'))
print(validateDate(r'1/23/2000'))
|
def pluralize(word, num):
"""
Returns a string that holds num in word form and the appropriate pluralization for "word."
"""
word = word.lower().lstrip()
string = ""
numList = ["zero", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninety"]
vowels = ["a", "e", "i", "o", "u", "y"]
multi_exception = {"is": "es", "us": "i", "ix": "ices", "eau": "eaux", "ouse": "ice",
"ch": "es", "sh": "es"}
o_exception = ["hero", "potato", "volcano"]
special = {"goose": "geese", "man": "men", "mouse": "mice",
"tooth": "teeth", "child": "children",
"woman": "women", "ox": "oxen", "wolf" : "wolves"}
unchanging = ["deer", "fish", "sheep", "species", "aircraft", "bison"]
if num <= 20:
string = numList[num]
else:
temp1 = int(num / 10)
temp2 = int(num % 10)
string = numList[temp1 + 18] + "-" + numList[temp2]
string += " "
if num != 1 and word not in unchanging:
if word in special:
word = special[word]
elif multiCheck(word, multi_exception)[0]:
b = multiCheck(word, multi_exception)[1]
word = word[0 : -len(b)] + multi_exception[b]
elif word[-1] == "y":
if word[-2] in vowels:
word += "s"
else:
word = word[0 : -1] + "ies"
elif word[-1] in ["s", "x", "z"] or word in o_exception:
word += "es"
else:
word += "s"
return string + word
def multiCheck(word, multi_exception):
"""
Returns a boolean for whether word has an ending in the multi_exception and the ending itself.
"""
length = 0
a = False
b = ""
for keys in multi_exception:
if len(keys) > length:
length = len(keys)
for i in range(1, length + 1):
if word[-i:] in multi_exception:
a = True
b = word[-i:]
return a, b
print(pluralize(input("Enter a singular noun: "), int(input("Enter a value: "))))
|
from timeit import default_timer as timer
import time
import sys
coffee = ""
size = ""
sugar = -1
wait = 0
price = 0
ans = ""
skip = 0
resetting = 0
tinit = 0
tend = 0
def reset() :
global coffee
coffee = ""
global size
size = ""
global sugar
sugar = -1
global price
price = 0
global skip
skip = 0
global wait
wait = 0
global resetting
resetting = 1
return;
def menu(coffee, size, sugar) :
if coffee == "l" :
print("Coffee: LATTE(l) Americano(a) Expresso(e)")
elif coffee == "a" :
print("Coffee: Latte(l) AMERICANO(a) Expresso(e)")
elif coffee == "e" :
print("Coffee: Latte(l) Americano(a) EXPRESSO(e)")
else :
print("Coffee: Latte(l) Americano(a) Expresso(e)")
if size == "s" :
print("Size: SMALL(s) Big(b)")
elif size == "b" :
print("Size: Small(s) BIG(b)")
else :
print("Size: Small(s) Big(b)")
if sugar == 1 :
print("Sugar: 0 |1| 2 3 4 5 ")
elif sugar == 2 :
print("Sugar: 0 1 |2| 3 4 5 ")
elif sugar == 3 :
print("Sugar: 0 1 2 |3| 4 5 ")
elif sugar == 4 :
print("Sugar: 0 1 2 3 |4| 5 ")
elif sugar == 5 :
print("Sugar: 0 1 2 3 4 |5|")
elif sugar == 0 :
print("Sugar: |0| 1 2 3 4 5 ")
else :
print("Sugar: 0 1 2 3 4 5 ")
return;
while 1 :
menu(coffee, size, sugar)
resetting = 0
tinit = timer()
tend = timer()
while 1 :
if coffee == "l" or coffee == "a" or coffee == "e" or skip :
break
coffee = input("Enter the type of coffee: ")
tend = timer()
if coffee == "c" :
skip = 1
coffee = ""
break
menu(coffee, size, sugar)
if tend - tinit >= 10 or skip :
skip = 0
reset()
if not resetting :
while 1 :
if size == "s" or size == "b" or skip :
break
size = input("Enter the size: ")
tend = timer()
if size == "c" :
skip = 1
size = ""
break
menu(coffee, size, sugar)
if tend - tinit >= 10 or skip :
skip = 0
reset()
if not resetting :
while 1:
if skip or (sugar >= 0 and sugar <= 5) :
break
sugar = int(input("Enter the amount of sugar: "))
tend = timer()
if tend - tinit >= 10 or skip :
skip = 0
reset()
if coffee == "l" :
wait = 6
price = 20
if size == "b" :
price = 30
elif coffee == "a" :
wait = 4
price = 30
if size == "b" :
price = 50
elif coffee == "e" :
wait = 6
price = 25
if size == "b" :
price = 40
if sugar >= 0 and sugar <= 5 :
price += sugar
print("Total Price: " + str(price))
if price != 0 :
while 1 :
ans = input("Your coffee is ready to be made. Start(s) or cancel(c): ")
tend = timer()
if ans == "s" or ans == "c" :
break
if ans == "s" and tend - tinit < 10 :
for i in range(1, wait + 1) :
time.sleep(1)
print(wait + 1 - i)
if i == wait :
print("Done!")
sys.exit()
elif ans == "c" or tend - tinit >= 10 :
skip = 1
|
from pandas import Series
from pandas import DataFrame
from pandas import concat
series = Series.from_csv('daily-minimum-temperatures-in-me.csv', header=0)
temps = DataFrame(series.values)
width = 2
shifted = temps.shift(width - 1)
print(shifted.head(12))
# 向上统计的步长
window = shifted.rolling(window=4)
# 分别取过去四天的最小值,均值,最大值
dataframe = concat([window.min(), window.mean(), window.max(), temps], axis=1)
dataframe.columns = ['min', 'mean', 'max', 't+1']
print(dataframe.head(15))
|
from pandas import Series
from pandas import DataFrame
from pandas import concat
from matplotlib import pyplot
from sklearn.metrics import mean_squared_error
series = Series.from_csv('daily-minimum-temperatures.csv', header=0)
# create lagged dataset
values = DataFrame(series.values)
dataframe = concat([values.shift(1), values], axis=1)
dataframe.columns = ['t-1', 't+1']
# split into train and test sets
X = dataframe.values
train, test = X[1:len(X)-7], X[len(X)-7:]
train_X, train_y = train[:,0], train[:,1]
test_X, test_y = test[:,0], test[:,1]
# persistence model
def model_persistence(x):
return x
# walk-forward validation
predictions = list()
for x in test_X:
yhat = model_persistence(x)
predictions.append(yhat)
test_score = mean_squared_error(test_y, predictions)
print('Test MSE: %.3f' % test_score)
# plot predictions vs expected
pyplot.plot(test_y)
pyplot.plot(predictions, color='red')
pyplot.show()
|
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
def earliest_ancestor(ancestors, starting_node):
# Create an empty queue and enqueue the starting path
queue = Queue()
path = [starting_node]
queue.enqueue(path)
# Create an empty set to track visited parents (first of the pair)
visited = set()
# While the queue is not empty:
while queue.size() > 0:
# get current pair (dequeue from queue)
current_pair = queue.dequeue()
neighbor = []
# iterate through your current pair:
for i in current_pair:
for pairs in ancestors:
if pairs[1] == i and i not in visited:
visited.add(i)
neighbor.append(pairs[0])
queue.enqueue(neighbor)
if len(neighbor) <= 0:
if current_pair[0] == starting_node:
return -1
else:
return current_pair[0]
|
"""
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,
their colleagues and Huiruo Zou.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# DONE: 2.
#
# You should have RUN the PREVIOUS module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOUR WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT your work by using VCS ~ Commit and Push.
########################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
apple = rg.SimpleTurtle('turtle')
apple.pen = rg.Pen('red', 3)
apple.speed = 5
orange = rg.SimpleTurtle()
orange.pen = rg.Pen('orange',6)
orange.speed = 5
path=50
for k in range(5):
apple.right(136)
apple.forward(100)
orange.draw_circle(path)
orange.pen_up()
orange.right(45)
orange.forward(10)
orange.left(45)
orange.pen_down()
path = path+15
window.close_on_mouse_click()
|
import numpy as np
def conv_single_step(image_slice, filt, bias):
"""
Apply one filter defined by parameters filt on a single slice (image_slice) of the output activation
of the previous layer.
Arguments:
image_slice -- slice of input data of shape (f, f, n_C_prev)
filt -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev)
bias -- Bias parameters contained in a window - matrix of shape (1, 1, 1)
Returns:
Z -- a scalar value, the result of convolving the sliding window (W, b) on a slice x of the input data
"""
# Element-wise product between a_slice_prev and W
s = np.multiply(image_slice, filt)
# Sum over all entries of the volume s
Z = np.sum(s)
# Adding bias b to Z
Z = Z + bias
return Z
def convolution(image, filt, bias, stride=1, padding=0):
"""
Implements the forward propagation for a convolution function
Arguments:
image -- output activations of the previous layer,
numpy array of shape (n_H_prev, n_W_prev, n_C_prev)
filt -- Weights, numpy array of shape (f, f, n_C_prev, n_C)
bias -- Biases, numpy array of shape (1, 1, 1, n_C)
Returns:
Z -- conv output, numpy array of shape (n_H, n_W, n_C)
"""
(f, f, n_C_prev, n_C) = filt.shape
(n_H_prev, n_W_prev, n_C_prev) = image.shape
# Computation of the CONV output volume dimensions
n_H = int((n_H_prev + 2 * padding - f) / stride + 1)
n_W = int((n_W_prev + 2 * padding - f) / stride + 1)
Z = np.zeros((n_H, n_W, n_C))
for h in range(n_H): # loop over vertical axis of the output volume
# Vertical start and end of the current "slice"
vert_start = h * stride
vert_end = h * stride + f
for w in range(n_W): # loop over horizontal axis of the output volume
# Horizontal start and end of the current "slice"
horiz_start = w * stride
horiz_end = w * stride + f
for c in range(n_C): # loop over channels (= #filters) of the output volume
# 3D slice of a_prev_pad
image_slice = image[vert_start:vert_end, horiz_start:horiz_end, :]
# Convolution the (3D) slice with the correct filter W and bias b, to get back one output neuron
weights = filt[:, :, :, c]
biases = bias[:, :, :, c]
Z[h, w, c] = conv_single_step(image_slice, weights, biases)
# Making sure output shape is correct
assert (Z.shape == (n_H, n_W, n_C))
return Z
def conv_backward(dZ, A_prev, filt, stride):
"""
Implementation the backward propagation for a convolution function
Arguments:
dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (n_H, n_W, n_C)
Returns:
dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev),
numpy array of shape (n_H_prev, n_W_prev, n_C_prev)
dfilt -- gradient of the cost with respect to the weights of the conv layer (filt)
numpy array of shape (f, f, n_C_prev, n_C)
dbias -- gradient of the cost with respect to the biases of the conv layer (bias)
numpy array of shape (1, 1, 1, n_C)
"""
(n_H_prev, n_W_prev, n_C_prev) = A_prev.shape
(f, f, n_C_prev, n_C) = filt.shape
(n_H, n_W, n_C) = dZ.shape
# Initialization dA_prev, dW, db with the correct shapes
dA_prev = np.zeros((n_H_prev, n_W_prev, n_C_prev))
dfilt = np.zeros((f, f, n_C_prev, n_C))
dbias = np.zeros((1, 1, 1, n_C))
for h in range(n_H): # loop over vertical axis of the output volume
for w in range(n_W): # loop over horizontal axis of the output volume
for c in range(n_C): # loop over the channels of the output volume
# Corners of the current "slice"
vert_start = h * stride
vert_end = h * stride + f
horiz_start = w * stride
horiz_end = w * stride + f
# Using the corners to define the slice from a_prev_pad
a_slice = A_prev[vert_start:vert_end, horiz_start:horiz_end, :]
# Updating gradients for the window and the filter's parameters
dA_prev[vert_start:vert_end, horiz_start:horiz_end, :] += filt[:, :, :, c] * dZ[h, w, c]
dfilt[:, :, :, c] += a_slice * dZ[h, w, c]
dbias[:, :, :, c] += dZ[h, w, c]
# Making sure your output shape is correct
assert (dA_prev.shape == (n_H_prev, n_W_prev, n_C_prev))
return dA_prev, dfilt, dbias
|
# lower function changes letters in a string to lowercase:
print("Angela".lower())
# "count" function will give you number of times a letter occurs in a string (case sensitive)
print("Angela".count("a"))
# example to count all letters (non case-sensitive)
lower_case_name = "Angela".lower()
print(lower_case_name.count("a"))
# Program to check compatibility between two people:
# Take both people's names and check for the number of times the letters in the word TRUE occurs. Then check for the
# number of times the letters in the word LOVE occurs. Then combine these numbers to make a 2 digit number.
# For Love Scores less than 10 or greater than 90, the message should be:
# "Your score is **x**, you go together like coke and mentos."
# For Love Scores between 40 and 50, the message should be:
# "Your score is **y**, you are alright together."
# Otherwise, the message will just be their score. e.g.:
# "Your score is **z**."
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
combined_lowercase = name1.lower() + name2.lower()
TRUE = combined_lowercase.count("t") + combined_lowercase.count("r") + combined_lowercase.count("u") + \
combined_lowercase.count("e")
LOVE = combined_lowercase.count("l") + combined_lowercase.count("o") + combined_lowercase.count("v") + \
combined_lowercase.count("e")
TRUE_LOVE = int(str(TRUE) + str(LOVE))
if (TRUE_LOVE < 10) or (TRUE_LOVE > 90):
print(f"Your score is {TRUE_LOVE}, you go together like coke and mentos.")
elif 40 <= TRUE_LOVE <= 50:
print(f"Your score is {TRUE_LOVE}, you are alright together.")
else:
print(f"Your score is {TRUE_LOVE}.")
|
# Program using math/fstrings that tells us how many days, weeks, months we have left if we live to 90 years
# Example output: You have 12410 days, 1768 weeks and 408 months left.
age = int(input("What is your current age? "))
years_left = 90 - age
days = years_left * 365
weeks = years_left * 52
months = years_left * 12
result = f"You have {days} days, {weeks} weeks and {months} months left."
print(result)
# Instructor answer was exact same, GO ME
|
a=str(input("Cuvantul este "))
b=str(input("Litera este "))
for k in range(0, len(a)):
print(f"{a[:k]}{b}{a[k+1:]}")
|
# Write a function for decompressing string “a4b3c2d” => "aaaabbbccd"
string1 = input(f"Enter a string: ")
def str_decompress(string):
result = ''
for i in range(0, len(string)):
if string[i].isnumeric():
result += ''
else:
if i != len(string) - 1:
if string[i + 1].isnumeric():
result += string[i] * int(string[i + 1])
else:
result += string[i]
else:
result += string[i]
return result
print(str_decompress(string1))
|
# List Slices
square = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(square[2:6])
print(square[3:8])
print(square[0:1])
print(square[:7])
print(square[7:])
print('\n')
sq = (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
print(sq[2:6])
print(sq[:7])
print(sq[7:])
print('\n')
print(square[::2])
print(square[::3])
print(square[2:8:3])
print('\n')
print(square[1:-1])
print(square[2:-3])
# Using [::-1] to reverse a list.
print(square[::-1])
print(square[7:5:-1])
print('\n')
# List Comprehensions
cubes = [i**3 for i in range(5)]
print(cubes)
evens = [i**2 for i in range(10) if i**2 % 2 == 0]
print(evens)
print('\n')
# even = [2*i for i in range(10**100)] ---- result in a MemoryError
# List Functions
# all and any ---- take a list as an argument, and return True if all or any (respectively) of
# their arguments evaluate to True (and False otherwise)
nums = [55, 44, 33, 22, 11]
if all([i > 5 for i in nums]):
print("All larger than 5")
if __name__ == '__main__':
if any([i % 2 == 0 for i in nums]):
print("At least one is even")
# enumerate ---- iterate through the values and indices of a list simultaneously.
for v in enumerate(nums):
print(v)
|
# Data Hiding
# Weakly private methods and attributes
# Have a single underscore at the beginning.
# It's mostly only a convention and does not stop external code from accessing them.
# Actual effect: from module_name import * won't import variables that start with a single underscore.
class Queue:
def __init__(self, contents):
self._hiddenlist = list(contents)
def push(self, value):
self._hiddenlist.insert(0, value)
def pop(self):
return self._hiddenlist.pop(-1)
def __repr__(self):
return "Queue({})".format(self._hiddenlist)
queue = Queue([1, 2, 3])
print(queue)
queue.push(0)
print(queue)
queue.pop()
print(queue)
print(queue._hiddenlist)
print('\n')
# Strongly private methods and attributes
# Have a double underscore at the beginning.
# This causes their name to be mangled, which means that they can't be accessed from outside the class.
# Name mangled method can still be accessed externally by a different name.
# The method __privatemethod of class Spam could be acssesed externally with _Spam__privatemethod.
class Spam:
__egg = 7
def print_egg(self):
print(self.__egg)
s = Spam()
s.print_egg()
print(s._Spam__egg)
# print(s.__egg)
# AttributeError: 'Spam' object has no attribute '__egg'
|
try:
varible = 10
print (varible + "hello")
print (varible / 2)
except ZeroDivisionError:
print("Divided by zero")
except (ValueError, TypeError):
print ("Error occurred")
finally:
print ("This code will run no matter what")
# Raising Exceptions
# num = input(":")
# if float(num) < 0:
# raise ValueError("Negative!")
|
import numpy as np
# map
# Function map takes a function and an iterable as arguments,
# and returns a new iterable with the function applied to each argument.
def add_five(x):
return x + 5
nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))
print(result)
# use lambda
print(list(map(lambda x: x + 5, nums)))
# filter
# Function filter filters an iterable by removing items that don't match a predicate(a function that returns a Boolean).
res = list(filter(lambda x: x % 2 == 0, nums))
print(res)
strings = [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9]]
print(nums[:-1])
print(list(map(lambda x: x[:-1], strings)))
|
# encoding=utf-8
#########################################################################
#File Name: test.py
#Author: Don Hu
#Mail: hudeng@staff.sina.com.cn
#Create Time: 2017-10-18 16:56:44
#Last modified: 2017-10-21 18:42:56
#########################################################################
#!/usr/bin/env python
from functools import reduce
def add(x, y):
return x + y
def fn(x, y):
return x * 10 + y
if __name__ == '__main__':
#r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
#print(list(r))
#print(tuple(r))
#print(set(r))
print(reduce(add, [1, 3, 5, 7, 9]))
print(reduce(fn, [1, 3, 5, 7, 9]))
|
# encoding=utf-8
#########################################################################
#File Name: test.py
#Author: Don Hu
#Mail: hudeng@staff.sina.com.cn
#Create Time: 2017-10-18 16:42:42
#Last modified: 2017-10-18 16:49:34
#########################################################################
#!/usr/bin/env python
if __name__ == '__main__':
print('begin...')
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
print(list(range(5)))
print(tuple(range(5)))
print('#########################################################')
sum = 0
for x in range(101):
sum = sum + x
print(sum)
for x in 'Hello, world':
print(x)
|
import random
array = []
for i in range(0, 10):
array.append(random.randrange(0,100))
print("Array to sort " + str(array))
def bubbleSort():
for i in range(0,len(array)):
for j in range(0,len(array)-i-1):
if array[j] > array[j+1]:
temp = array[j+1]
array[j+1] = array[j]
array[j] = temp
bubbleSort()
print("Sorted array: " + str(array))
|
class matrix:
def __init__(self,m=None,n=None,deflist=None,rowwise=None,displ=0,mode='n'):
'''Constructor for matrix. (default values if not initialised are (self,1,1,[],[],0))'''
self.defset=1
self.rwset=0
if m is None:
self.row=1
else:
self.row=m
if n is None and mode=='n':
self.col=1
elif n is None and mode=='i':
self.col=self.row
else:
self.col=n
x=f"Matrix created. {m}x{n}"
#ANSITerminal only: print('\033[1;32m'+x+'\033[1;m')
if deflist is None:
deflist=[]
self.deflist=deflist
self.defset=0
else:
self.deflist=deflist
if(rowwise is None):
rowwise=[]
self.rowwise=rowwise
else:
self.rowwise=rowwise
self.rwset=1
if mode=='i':
self.fill(self.deflist,mode='i')
self.fill(self.deflist)
if(self.defset==0 and self.rwset==1 and mode=='n'):
self.setdeflist()
fille=0
if(self.rwset==0 and self.defset==1 and mode=='n'):
fill=self.fill(deflist)
if displ==1:
print(x)
if fille==0:
#print('\033[1;31m'+"Warning: Matrix is not filled yet. Use \nobj.fill(linear list(left to right,up to down))\nto fill the matrix."+'\033[1;0m');
print("Warning: Matrix is not filled yet. Use \nobj.fill(linear list(left to right,up to down))\nto fill the matrix.")
else:
self.disp()
def __str__(self):
'''Returns a value if object is printed'''
return f"Matrix object {self.row}x{self.col}\nDefset:{self.defset}\nRWset:{self.rwset}\nDeflist:{self.deflist}\nRowwise:{self.rowwise}"
def add(a,b):
'''Adds two matrices a and b and returns the resulting matrix, or \"NA\" if incompatible.'''
if a.row==b.row and a.col==b.col:
l=[]
for i in range(0,a.row*a.col):
l.append(a.deflist[i]+b.deflist[i])
return matrix(a.row,a.col,l)
else:
return "NA"
def cofactor(self,r,c):
'''Returns cofactor matrix excluding row r and column c from \'self\''''
l=[]
for i in range(0,self.row):
for j in range(0,self.col):
if(r!=self.row and c!=self.col):
l.append(self.rowwise[i][j])
return matrix(self.row-1,self.col-1,l)
def colspace(self):
'''Returns the Column space of the matrix.'''
pass
def colswap(self,s,d):
'''Returns a matrix with a swap of s column with the d column of the source matrix (s,d start from 1)'''
l=[]
for i in range(0,self.row):
for j in range(0,self.col):
if j==s-1:
l.append(self.rowwise[i][d-1])
elif j==d-1:
l.append(self.rowwise[i][s-1])
else:
l.append(self.rowwise[i][j])
return matrix(self.row,self.col,l)
def copymat(self):
return matrix(self.row,self.col,self.deflist)
def det(self):
'''Returns determinant of a matrix (NA if not applicable, number if applicable)'''
if not self.issquare():
return "NA"
else:
if(self.col==2):
return (self.rowwise[0][0]*self.rowwise[1][1] - self.rowwise[0][1]*self.rowwise[1][0])
else:
d=0
for i in range(0,self.col):
d=d+(((self.cofactor(0,i)).det())*i)
return d
def disp(self):
'''Displays the calling matrix object \'self\'.'''
for i in range(0,self.row):
for j in range(0,self.col):
print(self.rowwise[i][j],end=' ')
print()
def disp2(self):
'''disp(), but prints elements with proper spacing.'''
maxv=max([len(str(x)) for x in self.deflist])
print(self.deflist,maxv)
for i in range(0,self.row):
for j in range(0,self.col):
y=self.rowwise[i][j]
x=y-int(y)
if(x==0):
y=int(y)
t=str(y)
s=""
for k in range(0,maxv-len(t)):
s=s+" "
s=s+t
print(s,end=' ')
print()
def fill(self,deflist=None,mode='n'):
'''Fills a matrix \'self\' if a list of numbers \'deflist\' is defined.'''
if(mode=='i'):
l=[]
for i in range(0,self.row):
for j in range(0,self.col):
if(i==j):
l.append(1)
else:
l.append(0)
self.deflist=l
self.defset=1
elif(deflist==[] or deflist is None):
return 0
else:
for i in range(0,self.row):
for j in range(0,self.col):
if j==0:
self.rowwise.append([])
self.rowwise[i].append(deflist[i*self.col + j])
self.rwset=1
if(self.defset==0 and self.rwset==1):
self.setdeflist()
def geliminate(self):
'''Performs Gaussian elimination on the matrix and returns the resulting matrices.'''
mat=self.copymat()
pivot=0
l=[]
el=[]
maxr=0
pivots=0
for i in range(0,self.col):
pivot=mat.rowwise[i][i]
if(i>=maxr):
maxr=i;
if pivot==0 and i==0:
for j in range(i,mat.row):
if mat.rowwise[j][i]!=0:
mat=mat.rowswap(i,j)
break
elif pivot==0 and i!=0:
for j in range(i,mat.row):
if mat.rowwise[j][i]!=0:
pivot=mat.rowwise[j][i]
maxr=j
break
pivots=pivots+1
for j in range(i+1,mat.row):
lterm=-mat.rowwise[j][i]/pivot
li=[lterm,j,i]
for k in range(0,mat.col):
mat.rowwise[j][k]=mat.rowwise[j][k]+lterm*mat.rowwise[i][k]
l.append(li)
if maxr==self.row-1:
break
for i in range(0,pivots):
for j in range(0,pivots):
if i==j:
el.append(1)
elif j>i:
el.append(0)
else:
for k in l:
if k[1]==i and k[2]==j:
el.append(k[0])
break
mat.setdeflist()
return mat,matrix(pivots,pivots,el)
def info(self):
'''Displays various attributes of the matrix \'self\''''
print(f"Matrix:\n{self.row}x{self.col}")
self.disp()
print(f"Determinant: {self.det()}")
print("Transpose:")
self.transpose().disp()
print("Inverse: NPY")
self.inverse()
def inputfill(self): #needs fix
'''Inputs a matrix row wise, and sets parameters automatically with the first row input.'''
print("Enter your matrix row wise:\n(separate entries with spaces, end row with newline)\n")
i=0
while True:
bc=0
while True:
s=input()
if s!="":
s=s.split()
try:
s=[int(k) for k in s]
except:
print("Enter numbers, nothing else. Please reenter row!\n")
continue
if i!=0:
if len(s)==self.col:
break
else:
print("Row length mismatch! Reenter with same length as row 1.")
continue
break
else:
bc=1
break
self.rowwise.append(s)
i=i+1
jc=0
if(bc==1):
break
for j in s:
if(jc==0):
self.deflist.append([])
jc=jc+1
self.deflist[i].append(j)
if(i==1):
self.col=jc
print(jc)
self.row=i
print("Entry is done.")
self.disp()
def inverse(self):
'''Returns the inverse of the matrix \'self\' using Gauss-Jordan method'''
pass
def issquare(self):
'''Checks if matrix is a square matrix. (returns 0 for false, 1 for true)'''
if self.row==self.col:
return 1
else:
return 0
def lnspace(self):
'''Returns Left Null space of the matrix.'''
pass
def mmul(a,b):
'''Returns the product of 2 matrices a.b, or \"NA\" if incompatible'''
if(a.col==b.row):
r=a.row
c=b.col
l=[]
for i in range(0,r):
for j in range(0,c):
sum=0
for k in range(0,a.col):
sum=sum+(a.rowwise[i][k]*b.rowwise[k][j])
l.append(sum)
return matrix(r,c,l)
else:
return "NA"
def multiply(a,b):
'''Combines the smul and mmul features, multiplies a quantity with the other quantity and returns answer, \"NA\" if incompatible.'''
if(isinstance(a,matrix)):
if(isinstance(b,matrix)):
return a.mmul(b)
else:
return a.smul(b)
else:
if(isinstance(b,matrix)):
return b.smul(a)
else:
return a*b
def nullspace(self):
'''Returns null space of the matrix.'''
pass
def revgeliminate(self):
'''Performs Reverse Gaussian elimination (from last pivot on Upper Triangle) on the matrix and returns the resulting matrix.'''
pass
def rowspace(self):
'''Returns Row space of matrix.'''
pass
def rowswap(self,s,d):
'''Returns a matrix with a swap of s row with the d row of the source matrix (s,d start from 1)'''
l=[]
for i in range(0,self.row):
if i==s-1:
l.append(self.rowwise[d-1])
elif i==d-1:
l.append(self.rowwise[s-1])
else:
l.append(self.rowwise[i])
return matrix(self.row,self.col,rowwise=l)
def setdeflist(self):
'''Fills the deflist if the rowwise list of lists is given'''
l=[]
for i in range(0,self.row):
for j in range(0,self.col):
l.append(self.rowwise[i][j])
self.deflist=l
self.defset=1
if(self.rwset==0 and self.defset==1):
fill=self.fill(deflist)
def smul(self,scalar):
'''Returns a matrix having all terms of \'self\' multiplied by a scalar'''
l=[]
for i in self.deflist:
l.append(scalar*i)
return matrix(self.row,self.col,l)
def spaces(self):
'''Displays and returns data about the subspaces of the matrix.'''
pass
def subtract(a,b):
'''Subtracts two matrices a and b and returns the resulting matrices with both differences (a-b,b-a), or \"NA\" if incompatible.'''
if a.row==b.row and a.col==b.col:
l=[]
m=[]
for i in range(0,a.row*a.col):
l.append(a.deflist[i]-b.deflist[i])
m.append(b.deflist[i]-a.deflist[i])
return matrix(a.row,a.col,l,displ=1),matrix(a.row,a.col,m,displ=1)
else:
return "NA"
def transpose(self):
'''Returns the transposed matrix of \'self\''''
l=[]
for j in range(0,self.col):
for i in range(0,self.row):
l.append(self.rowwise[i][j])
t=matrix(self.col,self.row,l)
return t
|
import urllib2
import json
from api_key import YOUTUBE_API_KEY
def load_data(url):
# Load json returned from a url
try:
data = json.load(urllib2.urlopen(url))
return data
except urllib2.HTTPError:
return None
def get_movie(title, year):
"""Constructs a Movie object using title and year.
OMDB API is used to fetch official title and poster image url."""
omdb_url = 'http://www.omdbapi.com/?t=%s&y=%s&plot=short&r=json' \
% (title, year)
omdb_url_no_space = omdb_url.replace(' ', '+')
movie_data = load_data(omdb_url_no_space)
if movie_data is not None:
if movie_data['Response'] == 'True':
title = movie_data['Title']
poster_image_url = movie_data['Poster']
return Movie(title, year, poster_image_url)
else:
print movie_data['Error']
return None
class Movie:
def search_trailers(self):
# Search youtube trailer using self.title
query = ('movie+%s+%s+trailer' %
(self.title, self.year)).replace(' ', '+')
# Get the closest matching video url
search_url = 'https://www.googleapis.com/youtube/v3/search\
?order=relevance&part=snippet&q=%s=EN\
&type=video®ionCode=US&maxResults=1&key=%s' % (query, YOUTUBE_API_KEY)
trailer_data = load_data(search_url)
if (trailer_data['kind'] == 'youtube#searchListResponse'):
trailer_id = trailer_data['items'][0]['id']['videoId']
video_url = 'https://www.youtube.com/watch?v=%s' % trailer_id
print video_url
return video_url
def __init__(self, title, year, poster, trailer=None):
self.title = title
self.year = year
self.poster_image_url = poster
self.trailer_youtube_url = self.search_trailers()
def __repr__(self):
return self.title
def __str__(self):
return self.title
|
class person:
def __init__(self,name,age,sex):#this is constructor default method of the class
self.Name = name#this is python properties
self.Age = age
self.Sex = sex
def person_bio(self):
information = "This is "+ self.Name +" bio data"
name = self.Name
age = self.Age
sex = self.Sex
print(information)
print(name)
print(age)
print(sex)
def normal_func(self,value):
print(value+" this is the word u entered")
person1 = person("madhu",22,"male")
person2 = person("keerthi",20,"female")
person1.person_bio()
person2.person_bio()
show = person("lovely",20,"female")#object created but without calling constructor wont work if exist
value = input("type u want:\n")
show.normal_func(value)
|
a=10
b=3
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a**b)
print(a//b)
|
class Binary_Search_Tree:
class __BST_Node:
def __init__(self, value):
self.value = value
self.right_child = None
self.left_child = None
self.height = 1
def __init__(self):
self.__root = None
def __return_height(self, root):
if root.left_child is None and root.right_child is None:
root.height=1 #need special cases to account
elif root.left_child is None: #for when children are None
root.height=root.right_child.height+1
elif root.right_child is None:
root.height=root.left_child.height+1
else:
root.height=max(root.left_child.height,root.right_child.height)+1
return root.height
def __balance(self, t): #t is root of subtree
if t is None: #tree is already balanced
print('t is none was executed')
return t
#when children are None, set height to 0. otherwise, self.height
if t.right_child is None:
right_child_height=0
else:
right_child_height=t.right_child.height
if t.left_child is None:
left_child_height=0
else:
left_child_height=t.left_child.height
#rotations
if (right_child_height-left_child_height)==-2: #left-heavy
#when subchildren are None, set height to 0
if t.left_child.right_child is None:
small_rchild_height=0
else:
small_rchild_height=t.left_child.right_child.height
if t.left_child.left_child is None:
small_lchild_height=0
else:
small_lchild_height=t.left_child.left_child.height
if (small_rchild_height-small_lchild_height)==1:
#left child is right-heavy, double rotation
#first rotation
small_floater=t.left_child.right_child.left_child
small_new_root=t.left_child.right_child
small_old_root=t.left_child
t.left_child=small_new_root
small_old_root.right_child=small_floater
small_new_root.left_child=small_old_root
#recompute heights of small_new_root and small_old_root
small_old_root.height=self.__return_height(small_old_root)
small_new_root.height=self.__return_height(small_new_root)
#second rotation
floater=t.left_child.right_child
old_root=t
t=small_new_root
old_root.left_child=floater
small_new_root.right_child=old_root
#before returning, recompute height of two nodes, t and old root
old_root.height=self.__return_height(old_root)
t.height=self.__return_height(t)
return t
else:
#left child is balanced or left-heavy, single rotation
floater=t.left_child.right_child
new_root=t.left_child
old_root=t
t=new_root
old_root.left_child=floater
new_root.right_child=old_root
#before returning, recompute height of two nodes, t and old root
old_root.height=self.__return_height(old_root)
t.height=self.__return_height(t)
return t
elif (right_child_height-left_child_height)==2: #right_heavy
#when subchildren are None, set height to 0
if t.right_child.left_child is None:
small_lchild_height=0
else:
small_lchild_height=t.right_child.left_child.height
if t.right_child.right_child is None:
small_rchild_height=0
else:
small_rchild_height=t.right_child.right_child.height
if (small_rchild_height-small_lchild_height)==-1:
#right child is left-heavy, double rotation
#first rotation
small_floater=t.right_child.left_child.right_child
small_new_root=t.right_child.left_child
small_old_root=t.right_child
t.right_child=small_new_root
small_old_root.left_child=small_floater
small_new_root.right_child=small_old_root
#recompute heights of small_new_root and small_old_root
small_old_root.height=self.__return_height(small_old_root)
small_new_root.height=self.__return_height(small_new_root)
#second rotation
floater=t.right_child.left_child
old_root=t
t=small_new_root
old_root.right_child=floater
small_new_root.left_child=old_root
#before returning, recompute height of two nodes, t and old root
old_root.height=self.__return_height(old_root)
t.height=self.__return_height(t)
return t
else:
#right child is balanced or right-heavy, single rotation
floater=t.right_child.left_child
new_root=t.right_child
old_root=t
t=t.right_child
old_root.right_child=floater
new_root.left_child=old_root
#before returning, recompute height of two nodes, t and old root
old_root.height=self.__return_height(old_root)
t.height=self.__return_height(t)
return t
else: #t is right-heavy or left-heavy by 1, or balanced. no rotation.
return t
def insert_element(self, value):
self.__root=self.__recursive_insert(value,self.__root)
def __recursive_insert(self, value, root):
#base case
if root==None:
return self.__BST_Node(value)
#recursive case
if value<root.value:
root.left_child=self.__recursive_insert(value,root.left_child)
elif value>root.value:
root.right_child=self.__recursive_insert(value,root.right_child)
elif value==root.value:
raise ValueError
#update height of root before returning
root.height=self.__return_height(root)
return self.__balance(root)
def remove_element(self, value):
self.__root=self.__recursive_removal(value, self.__root)
def __recursive_removal(self, value, root):
if root==None: #value is not in tree
raise ValueError
#base case
if value==root.value: #found value to remove
#root has zero children
if root.left_child is None and root.right_child is None:
return None
#root has one child
elif root.left_child is None or root.right_child is None:
if root.left_child is not None:
return root.left_child
elif root.right_child is not None:
return root.right_child
#root has two children
elif root.left_child is not None and root.right_child is not None:
t=root.right_child
while t.left_child is not None: #loop through to minimum on right
t=t.left_child
root.value=t.value #copy value into root
#recur again to remove duplicate
root.right_child=self.__recursive_removal(t.value,root.right_child)
#recursive case
elif value<root.value: #val is less than root's val, recur left
root.left_child=self.__recursive_removal(value,root.left_child)
elif value>root.value: #val is greater than root's val, recur right
root.right_child=self.__recursive_removal(value,root.right_child)
#update height of root before returning
root.height=self.__return_height(root)
return self.__balance(root)
def to_list(self): #return list of tree
if self.__root==None:
return []
tree_list=self.__recursive_to_list(self.__root)
return tree_list
def __recursive_to_list(self, root):
#base case
if root==None:
return []
#recursive case (Left, Parent, Right)((just like in_order traversal))
tree_list=self.__recursive_to_list(root.left_child)+[root.value]+ \
self.__recursive_to_list(root.right_child)
return tree_list
def in_order(self): #create string representation of tree (LPR)
if self.__root==None:
return "[ ]"
traversal=self.__recursive_in_order(self.__root)
return ('[ '+traversal)[:-2]+' ]'
def __recursive_in_order(self, root):
#base case
if root==None:
return ''
#recursive case (Left, Parent, Right)
string=str(self.__recursive_in_order(root.left_child))\
+str(root.value)+', '+str(self.__recursive_in_order(root.right_child))
return string
def pre_order(self): #create string representation of tree (PLR)
if self.__root==None:
return "[ ]"
traversal=self.__recursive_pre_order(self.__root)
return ('[ '+traversal)[:-2]+' ]'
def __recursive_pre_order(self, root):
#base case
if root==None:
return ''
#recursive case (Parent, Left, Right)
string=str(root.value)+', '+\
str(self.__recursive_pre_order(root.left_child))\
+str(self.__recursive_pre_order(root.right_child))
return string
def post_order(self): #create string representation of tree (LRP)
if self.__root==None:
return "[ ]"
traversal=self.__recursive_post_order(self.__root)
return ('[ '+traversal)[:-2]+' ]'
def __recursive_post_order(self, root):
#base case
if root==None:
return ''
#recursive case (Left, Right, Parent)
string=str(self.__recursive_post_order(root.left_child))+\
str(self.__recursive_post_order(root.right_child))+str(root.value)+', '
return string
def get_height(self):
if self.__root==None: #special case
return 0
else:
return self.__root.height #return height updated height attribute
def __str__(self):
return self.in_order()
if __name__ == '__main__':
pass #unit tests make the main section unnecessary.
|
def extract(word, text):
firstCharacter = word[0]
firstIndex = text.index(firstCharacter)
return text[firstIndex : firstIndex + len(word)]
website = "http://www.batuhanduzgun.com"
course = "Python Kursu: From Zero to Hero Course"
courseLength = len(course)
print(f"Course word length is {courseLength}")
lastOccurenceIndexOfL = website.rindex("/")
print(f"Last occurence index is : {lastOccurenceIndexOfL}")
firstOccurenceIndexOfL = website.index("/")
print(f"First occurence index is : {firstOccurenceIndexOfL}")
protocolPrefix = website[lastOccurenceIndexOfL + 1 : lastOccurenceIndexOfL + 4]
print(protocolPrefix)
print( extract("www", website) )
print( extract("com", website) )
first15CharacterOfCourse = course[:15]
print(first15CharacterOfCourse)
last15CharacterOfCourse = course[-15:]
print(last15CharacterOfCourse)
# reverse of string is so basic :)
print(course[::-1])
## String Methods
#1
sampleMessage = " Hello word "
print(sampleMessage)
print(sampleMessage.strip())
# sadece sağdan veya soldan boşlukları temizliyor
print(sampleMessage.rstrip())
print(sampleMessage.lstrip())
#2
# index metodu bulamazsa hata fırlatır.
# find metodu ise bulamazsan hata döndürmez, -1 değer döner.
lastIndexOfDot = website.rindex(".")
firstIndexOfDot = website.index(".")
print(website[firstIndexOfDot + 1 : lastIndexOfDot])
# yada
# silinmesini istediğin karakterleri verebiliyorsun.
print( website.strip("w.moc/pht:") )
#3
print(website.lower())
#4
# a harfinden kaç tane olduğunu sayıyor.
print(website.count("a"))
#5
print(website.find(".com"))
print(website.startswith(".com"))
print(website.endswith(".com"))
#6
#karakterlerin hepsi alfanumeric mi kontrol ediyor.
print(website.isalpha())
#karakterlerin hepsi numeric mi kontrol ediyor.
print(website.isdigit())
#7
print(website.center(50, "*"))
#8
print(course.replace(" ", "-"))
print(course.replace("Zero", "Hero"))
print(course.split())
|
x = input('sayi1 giriniz:')
y = input('sayi2 giriniz:')
print(type(x))
print(type(y))
toplam = int(x) + int(y)
print(type(int(x)))
print(type(int(y)))
print(toplam)
a = 5
b = 2.5
name = 'Çınar'
isOnline = True
print(type(a))
print(type(b))
print(type(name))
print(type(isOnline))
aAsFloat = float(a)
print(aAsFloat)
print(type(aAsFloat))
|
x = y = [1, 4, 5, 11, 3, 9]
z = [1, 4, 5, 11, 3, 9]
# == operatorü bellek referanslarını değil, değerleri kıyaslar!
print(x == y)
print(z == x)
# bellek referansını kıyaslamak istersek "is" operatorü kullanmalıyız!
print(x is y)
print(x is z)
# membership operator is "in"
fruits = ["Apple", "Banana", "Orange"]
print("Kiwi" in fruits)
print("Orange" in fruits)
|
from typing import List
delta = [-1, 0, 1, 0, -1]
def search(board, r, c, word) -> bool:
if len(word) == 0:
return True
for i in range(4):
nr, nc = r + delta[i], c + delta[i + 1]
if 0 <= nr < len(board) and 0 <= nc < len(board[0]) and board[nr][nc] == word[0]:
temp = board[nr][nc]
board[nr][nc] = '@'
res = search(board, nr, nc, word[1:])
if res:
return True
board[nr][nc] = temp
return False
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
temp = board[i][j]
board[i][j] = '@'
if search(board, i, j, word[1:]):
return True
board[i][j] = temp
return False
print(Solution().exist([["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], "ABCB"))
|
# -*- coding: utf-8 -*-
# author: sunmengxin
# time: 18-12-12
# file: 函数闭包
# description:
def adder(x):
def wrapper(y):
return x + y
return wrapper
adder5 = adder(5)
adder6 = adder5(10)
print(adder6)
# ==> 15,因为函数最开始封装了x=5
# 输出 11
adder7 = adder5(6)
print(adder7)
# ==> 11,因为函数最开始封装了x=5
|
#Flips a coin 100 times and then reports back the number of heads and tails
import random
number_of_flips = 0
heads = 0
tails = 0
winner = ""
input("We're going to flip a coin 100 times and see whether it's more 'heads' or 'tails', which one do you think it will be?")
while number_of_flips < 100:
if random.randint(0, 1) == 0:
heads += 1
else:
tails += 1
number_of_flips += 1
if heads > tails:
winner = "Heads"
else:
winner = "Tails"
print("It looks like", winner, "won!", "Heads was flipped", str(heads), "times while Tails was flipped", str(tails), "times")
|
'''
#Teste IF
a = int (input("Digite o valor de a: "))
b = 150
c = 151
if (a == b):
print("São Iguai!")
else:
print("São diferentes")
if (a > b and a > c):
print("a é maior que b e c")
elif (b > c ):
print("b é maior que a e c")
else:
print("c é maior que a e b")
exercicio = int(input("Quantos minutos você se exercita por dia: "))
if (exercicio < 30):
print("VocÊ devia se exercitar mais..")
elif ( exercicio >= 30 and exercicio <= 60):
print("Você esta no caminho, Continue assim!")
elif (exercicio > 60 and exercicio <= 120):
print("Você é um atleta nato! Parabens")
else:
print("Você é galatico!")
#Teste LOOPS
trabalho = input("Você vai trabalhar hoje? ")
dia = input("O dia esta bonito? ")
preguica = input("Você esta com preguiça bb? ")
if trabalho == "sim":
print("Que pena")
elif (trabalho == "não"):
print("Obaa, aproveite o dia")
if trabalho == "não" and dia == "sim":
print("Aproveite para pedalar")
elif trabalho == "não" and dia == "não":
print("Aproveite para assistir um filme :)")
if trabalho == "não" and preguica == "sim":
print("Aproveite para dormir mais nenem")
elif trabalho == "não" and preguica == "não":
print("Boaa, aproveite para estudar Python *_* ")
# FOR
# FOR em listas
cor = ["vermelho","amarelo","azul","preto","branco","roxo"]
for x in cor:
print(x)
#FOR em Strings
for y in 'pneumoultramicroscopicossilicovulcanoconiótico':
print(y)
#FOR e break
numeros = (1,2,3,4,5,6,7,8,9,10)
for i in numeros:
print(i)
if i == 7:
break
#While
#Faz um loop enquanto uma condição for verdadeira
i = 0
while i <= 10:
print(i)
i += 1
# while com break
u = 0
v = 0
while u <= 10:
print(u)
if u == 7:
break
u += 1
# while com continue
while v < 10:
v += 1
#Pula o 7
if v == 7:
continue
print(v)
#Range
#Faz o loop a quantidade de vezes dedinida no range
# range(Incio,fim + 1, salto)
for x in range(1,31,2):
print(x)
#def
#Funções em python
def soma (x,y):
return x+y
print('a Soma de x e y é: ' + str(soma(1,2)))
#IMC
peso = float(input("Qual é o seu peso? "))
altura = float(input('Qual é sua altura? '))
def imc(p, a):
imc = p/(a**2)
if imc < 18.5:
print("Você ta magro demais :)")
elif imc > 18.5 and imc <= 24.9:
print("Continue assim seu peso esta de acordo! *_*")
elif imc >25.0 and imc <= 29.9:
print("Sobrepeso :(")
elif imc >30.0 and imc <= 39.9:
print("Obsidade I :(")
else:
print("Obsidade II :(")
print("Seu imc é de " + str(imc))
return
imc(peso,altura)
#Funções lambda ( não precisa nomear as funções)
soma2 = lambda x,y: x+y
print(str(soma2(1,2)))
'''
#Modulos é um conjunto de funções
#Importar modulo
# import nome_do_modulo
# Importar partes de um modulo
# from math import sqrt
#usando os modulos
#nome_do_modulo.funcao()
#exemplo:
import math
raiz_quadrada = math.sqrt(9)
print(raiz_quadrada)
#pacote: Pacotes são conjuntos de modulos
#pip é o gerenciador de pacotes em python (Instalar, atualizar e desinstalar)
#instalar pacotes
#!pip install seaborn
#pip install seaborn
#atualizar pacotes
#pip --upgrade seaborn
#instalar versão especifica
#pip install seaborn==0.90
#importação e pacotes
#import pandas as pd
#import numpy as mp
# utiliza-se o as como alias para apelidar o pacote, para facilicar na hora de chamar
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 31 21:03:45 2019
@author: ece-student
"""
# Copyright 2019 Dingjun Bian braybian@bu.edu
# Copyright 2019 Shiyang Hu shiyangh@bu.edu
import sys
import numpy as np
import math
class Circle():
def __init__(self, name, m, R, position, velocity):
self.name = name
self.m = m
self.R = R
self.pos = position
self.vel = velocity
def __str__(self):
return "{} {} {} {} {} {} {} {} {}".format(self.name, round(self.m,6),
round(self.R),
round(self.pos[0], 6),
round(self.pos[1], 6),
round(self.pos[2], 6),
round(self.vel[0], 6),
round(self.vel[1], 6),
round(self.vel[2], 6))
def move(self, movetime):
#print("before move:",self.pos[0],' ',self.pos[1],' ',self.pos[2])
self.pos = self.pos + movetime * self.vel # r=p+tv
#print("after move:",self.pos[0],' ',self.pos[1],' ',self.pos[2])
# print("self.pos:",self.pos) ######
def colli_time(self, two):
if (self.pos[0]==two.pos[0]) & (self.pos[1]==two.pos[1]) & (self.pos[2]==two.pos[2]):
return np.Inf
subr1=self.pos[0]-two.pos[0]
subr2 = self.pos[1] - two.pos[1]
subr3 = self.pos[2] - two.pos[2]
subv1 = self.vel[0] - two.vel[0]
subv2 = self.vel[1] - two.vel[1]
subv3 = self.vel[2] - two.vel[2]
r1 = float(self.R)
r2 = float(two.R)
midpro1=subv1*subv1+subv2*subv2+subv3*subv3
if midpro1 == 0:
return np.Inf
dr2=subr1*subr1+subr2*subr2+subr3*subr3
midpro2=2*subr1*subv1+2*subr2*subv2+2*subr3*subv3
sqgen=midpro2*midpro2-4*midpro1*(dr2-(r1+r2)**2)
if sqgen < 0:
return np.Inf
root = sqgen ** 0.5
colltime = (-midpro2 - root) / (2 * midpro1)
colltime1 = (-midpro2 + root) / (2 * midpro1)
if (colltime <= 0):
colltime = colltime1
if (colltime > 0) & (colltime1 > 0) & (colltime1 < colltime):
colltime = colltime1
# print("eralytestcolltime:",colltime)
if colltime == 0 and (subr1*subv1+subr2*subv2+subr3*subv3) < 0:
return 0
elif colltime > 0:
# print("collitime:",colltime) ######
return colltime
return np.Inf
def collison_space(self, area):
tmin = np.Inf
# print("a1 b1 c1:",a1,b1,c1)
if (self.vel[0]==0) & (self.vel[1]==0) & (self.vel[2]==0):
pass
else:
a = (self.vel[0] ** 2) + (self.vel[1] ** 2 )+ (self.vel[2] ** 2)
b = (2 * self.vel[0] * self.pos[0]) + (2 * self.vel[1] * self.pos[1]) + (2 * self.vel[2] * self.pos[2])
c = (self.pos[0] ** 2) + (self.pos[1] ** 2) + (self.pos[2] ** 2) - ((area-float(self.R)) ** 2)
sq =( b ** 2) -( 4 * a * c)
if sq < 0:
return 1
sqgen = sq ** 0.5
# print("sq:",sq,"sqgen:",sqgen,"b:",b,"a:",a,"c:",c)
t_mid = (-b - sqgen) / (2 * a)
t_mid2 = (-b + sqgen) / (2 * a)
# print("b sqgen a:",b,sqgen,a)
# print("t_mid:",t_mid,t_mid2)
if (t_mid < tmin) & (t_mid > 0):
tmin = t_mid
if (t_mid2 < tmin) & (t_mid2 > 0):
tmin = t_mid2
# print("collision space tmin:",tmin)
# print("t1:", t1, "t2", t2, "tmin", tmin)
return tmin
def get_argvin():
n_times = sys.argv[2]
global area
area = sys.argv[1]
return area, n_times
def get_circle_data(n_times,area):
circles = []
momentum = np.zeros(3)
energy = 0
st_gtd = 'Here are the initial spheres.\n'
st_gtd=st_gtd+"universe radius "+str(area)+"\n"+"max collsions "+str(n_times)+"\n"
for line in sys.stdin:
try:
m, R, posx, posy, posz, velx, vely, velz, name = line.split()
# name, posx, posy, velx, vely = line.split()
# print(name,posx,posy,velx,vely)
pos = np.array((float(posx), float(posy), float(posz)))
vel = np.array((float(velx), float(vely), float(velz)))
circles.append(Circle(name, m, R, pos, vel))
momentum = momentum + int(m) * vel
# print("momentum:",momentum)
energy = energy + int(m) * vel @ vel / 2
# print("energy:",energy)
st_gtd = st_gtd+ str(name) + " m=" + str(m) + " R=" + str(R) + " p=" + str(pos) + " v=" + str(vel) + " bounce=0\n"
except ValueError:
return None
st_gtd = st_gtd + "energy: " + str(energy) + "\nmomentum: " + str(momentum)
#print("universe radius ", area)
#print("max collision ", n_times)
print(st_gtd)
# print("the first circle:", circles[0], circles[0].vel, len(circles))
return circles
def get_next_collision(cur_time, circles,bounce):
next_collision = np.Inf
colliders = [None, None]
collide4 = [None, None, None, None]
global divide
divide = 1
for i, one in enumerate(circles):
# print("i:",i,"one:",one) #######
for j, two in enumerate(circles):
# print("j:",j,"two:",two) #####
# print("type of j:",type(j))
if i >= j: # make sure it is two different balls
continue
colltime = one.colli_time(two)
# print("colltime",colltime)
if colltime < next_collision:
next_collision = colltime
colliders = i, j
collide4[0] = i
collide4[1] = j
elif (colltime == next_collision) & (colltime < np.Inf) & (collide4[0] != None):
collide4[2] = i
collide4[3] = j
# print("new i j:",i,j)
# print("collide4:",collide4)
divide = 2
# print("type of colliders:", type(colliders))
if divide == 1:
#bounce[i]=bounce[i]+1
return colliders, next_collision, divide # no collision for given time
elif divide == 2:
return collide4, next_collision, divide
def move_ball(circles, movetime):
for circ in circles:
circ.move(movetime)
def collision_report(cur_time, one,two,circles, bounce):
str_col = ""
ener=0
moment=0
str_col = str_col + "time of the event:" + str(cur_time) + "\n"
str_col = str_col + "colliding " + str(one.name) + " " + str(two.name) + "\n"
for i in range(len(circles)):
str_col = str_col + str(circles[i].name) + " m=" + str(circles[i].m) + " R=" + str(circles[i].R) + " p=" + str(circles[i].pos) + " v=" + str(
circles[i].vel) +" bounce="+str(bounce[i])+"\n"
#str_col = str_col + str(two.name) + " m=" + str(two.m) + " R=" + str(two.R) + " p=" + str(two.pos) + " v=" + str(
# two.vel) + " bounce="+bounce[i]+"\n"
for i in range(len((circles))):
ener =ener+ float(circles[i].m) * circles[i].vel @ circles[i].vel / 2
moment =moment+ float(circles[i].m) * circles[i].vel
# print("energy:",ener) #####
# print("momentum:",moment) #####
str_col = str_col + "energy: " + str(ener) + "\nmomentum: " + str(moment)
print(str_col)
def collision_wall_report(cur_time, one,circles,bounce):
str_col = ""
ener=0
moment=0
str_col = str_col + "time of the event:" + str(cur_time) + "\n"
str_col = str_col + "reflecting " + str(one.name) +"\n"
for i in range(len(circles)):
str_col = str_col + str(circles[i].name) + " m=" + str(circles[i].m) + " R=" + str(circles[i].R) + " p=" + str(circles[i].pos) + " v=" + str(
circles[i].vel) +"bounce "+str(bounce[i])+"\n"
for i in range(len(circles)):
ener =ener+ float(circles[i].m) * circles[i].vel @ circles[i].vel / 2
moment =moment+ float(circles[i].m) * circles[i].vel
# print("energy:",ener) #####
# print("momentum:",moment) #####
str_col = str_col + "energy: " + str(ener) + "\nmomentum: " + str(moment)
print(str_col)
def elastic_collision(one, two):
one.m = float(one.m)
two.m = float(two.m)
posub=[one.pos[0]-two.pos[0],one.pos[1]-two.pos[1],one.pos[2]-two.pos[2]]
velsub=[one.vel[0]-two.vel[0],one.vel[1]-two.vel[1],one.vel[2]-two.vel[2]]
ppmul=posub[0]*posub[0]+posub[1]*posub[1]+posub[2]*posub[2]
vpmul=velsub[0]*posub[0]+velsub[1]*posub[1]+velsub[2]*posub[2]
massmul1 = (2 * two.m) / (one.m + two.m)
massmul2 = (2 * one.m) / (one.m + two.m)
one.vel[0]=one.vel[0]-massmul1*(posub[0]*vpmul/ppmul)
one.vel[1] = one.vel[1] - massmul1 * (posub[1] * vpmul / ppmul)
one.vel[2] = one.vel[2] - massmul1 * (posub[2] * vpmul / ppmul)
two.vel[0] = two.vel[0] + massmul2 * (posub[0] * vpmul / ppmul)
two.vel[1] = two.vel[1] + massmul2 * (posub[1] * vpmul / ppmul)
two.vel[2] = two.vel[2] + massmul2 * (posub[2] * vpmul / ppmul)
def collisonspace_vel(one, area): ########## nead modify
# one.vel=-one.vel
# area=float(area)
wall = np.array((0, 0, 0))
# print(wall)
# print(one.pos)
mid = one.pos - wall
# print("one.m:",one.m,"two.m:",two.m) #####
sub = 2 * (one.vel) @ mid / (mid @ mid)
one.vel = one.vel - sub * mid
def main():
print( "Please enter the mass, radius, x/y/z position, x/y/z velocity and name of each sphere When complete, use EOF / Ctrl-D to stop entering")
area, n_times = get_argvin() #n_times=max time of collison for one ball
n_times = int(n_times)
area = float(area)
circles = get_circle_data(n_times,area) # get the data of the circle
#print("Here are the initial conditions.")
global bounce;
bounce=[0]*len(circles)
#print("initial bounce",bounce)
#bounce1=0
#bounce2=0
#bounce3=0
if not circles:
return 1
seperate = 0
cur_time = 0 # init time=0
collide = [0, 0, 0, 0]
while len(circles)>0:
(collide), c_time, divide = get_next_collision(cur_time, circles,bounce) # if no collision c_time=inf
seperate = 0
if divide == 1:
one = collide[0]
two = collide[1]
if divide == 2:
one = collide[0]
two = collide[1]
three = collide[2]
four = collide[3]
# print("c_time", c_time)
lop_cir = 0 # for the loop
tmin = 9999
numb = 0
tmid_list = [] # store the shortest time of collision with wall of each ball
for lop_cir in circles: # get the shortest time of hit the wall
t_mid = lop_cir.collison_space(area)
tmid_list.append(t_mid)
#print("t_mid:",t_mid)
for lop_min in range(len(tmid_list)): # get the shortest of the shortest(hit wall)
if tmid_list[lop_min] < tmin:
tmin = tmid_list[lop_min]
numb = lop_min
#print("tmid_list[lop_min]:",tmid_list[lop_min]," numb:",numb)
if tmin < c_time: # set to deal with hit the wall
c_time = tmin
seperate = 1
cur_time = cur_time + c_time
# print("current_time:", cur_time)
move_ball(circles, c_time) # when c_time<the required to times,go to this point
if seperate == 0:
elastic_collision(circles[one], circles[two]) # change the velocity
if divide == 2:
elastic_collision(circles[three], circles[four])
elif seperate == 1:
#print("numb:",numb,len(circles),'\n')
collisonspace_vel(circles[numb], area) # change the velocity
# print(circles[numb].vel)
for it in range(len(circles)): #if one of the vel euals to nan,return o
if (math.isnan(circles[it].vel[0])) | (math.isnan(circles[it].vel[0])) | (math.isnan(circles[it].vel[0])):
return 0
if seperate == 0:
bounce[one] = bounce[one] + 1
bounce[two] = bounce[two] + 1
collision_report(cur_time, circles[one],circles[two],circles,bounce)
if divide == 2:
bounce[three] = bounce[three] + 1
bounce[four] = bounce[four] + 1
collision_report(cur_time, circles[three],circles[four],circles,bounce)
elif seperate == 1: # next collision is hitting the wall
# print("hit the wall") ####
bounce[numb] = bounce[numb] + 1
collision_wall_report(cur_time,circles[numb], circles,bounce)
#n_times = n_times - 1
tinymove= 0.000001
cur_time = cur_time + tinymove # avoid counting one collison twice
move_ball(circles, tinymove)
#print("len circle",len(circles),len(bounce))
i=len(circles)-1
while i>=0:
if bounce[i]==int(n_times): #check whether we should delete the ball
print("disappear ", circles[i].name)
del circles[i]
del bounce[i]
#deln=deln-1
i=i-1
else:
return 0
if __name__ == '__main__':
main()
|
#! python3
"""
Problem 1
Ask the user to enter a number.
The number is considered "frue" if it is
divisible by 6, but not divisible by 8.
State whether the number is "frue"
(2 marks)
Inputs:
a number
Outputs:
xx is frue
xx is not frue
example:
Enter a number: 48
48 is not frue
Enter a number: 36
36 is frue
Enter a number: 16
16 is not frue
"""
num1 = float( input("Enter a number: "))
div6 = (num1%6)
div8 = (num1%8)
if div6 == 0 and div8 != 0:
print(f"{num1} is frue")
else:
print(f"{num1} is not frue")
|
# > width = 8
# > height = 4
# > number_of_mines = 8
# > generate_board(width, height, number_of_mines)
# *112*100
# 123*3222
# 01**31**
# 013*2122
# board = list
# each row of the board = list - 4 with 8 items inside (start all items with 0)
# randomizing the mines: random index for the row, random index for item inside the row
# iterate through each item, count how many mines next to that item
# if the item is a mine, skip it
# look at the item indexed lower and higher in the row, also look at the rows above and below the item, index higher, the same, and lower
# counting up the mines and replacing the 0 with the new count
# generate in terminal by printing each row
from random import randint
def generate_board(width, height, number_of_mines):
"""Generate minesweeper board"""
board = []
for i in range(height):
row = []
for i in range(width):
row.append(0)
board.append(row)
mines = set()
while len(mines) < number_of_mines:
row_index = randint(0, height - 1)
item_index = randint(0, width - 1)
mines.add((row_index, item_index))
for mine in mines:
board[mine[0]][mine[1]] = '*'
for row in range(height):
for item in range(width):
count = 0
if board[row][item] == '*':
continue
else:
if item > 0:
if board[row][item - 1] == '*':
count += 1
if item < width - 2:
if board[row][item + 1] == '*':
count += 1
board[row][item] = count
print(board)
generate_board(4, 4, 2)
|
import tkinter
width = 500
height = 400
title = "bocharov"
top = tkinter.Tk()
top.minsize(width=width + 10, height=height + 10)
if title:
top.title(title)
canvas = tkinter.Canvas(top, width=width + 2, height=height + 2)
canvas.pack()
canvas.xview_scroll(8, 'units') # hack so (0, 0) works correctly
canvas.yview_scroll(8, 'units') # otherwise it's clipped off
# Написать свой код сюда ----------------------
canvas.create_rectangle(0,300,500,400,fill="green",outline="green")
canvas.create_rectangle(0,0,500,300,fill="lightblue",outline="lightblue")
canvas.create_rectangle(100,275,300,325,fill="yellow",outline="yellow")
canvas.create_rectangle(150,235,250,300,fill="yellow",outline="yellow")
canvas.create_rectangle(155,237,245,275,fill="blue",outline="blue")
canvas.create_rectangle(197,235,202,275,fill="yellow",outline="yellow")
canvas.create_oval(130,300,180,350,fill="black",outline="black")
canvas.create_oval(220,300,270,350,fill="black",outline="black")
# ----------------------------------------------
if tkinter._default_root:
tkinter._default_root.update()
tkinter.mainloop()
|
arr = [0, 3, 24, 2, 3, 7]
for i in range(len(arr)):
minimum = i
for j in range(i + 1, len(arr)):
if int(arr[j]) < int(arr[minimum]):
minimum = j
arr[i], arr[minimum] = arr[minimum], arr[i]
print(arr)
|
def compare (a, b, c):
if a>=b and b>=c:
print ("Samoe bolsho chislo " + str(a) + ", potom " + str(b) + ", potom " + str(c))
elif b>=a and a>=c:
print ("Samoe bolsho chislo " + str(b) + ", potom " + str(a) + ", potom " + str(c))
elif c>=b and b>=a:
print ("Samoe bolsho chislo " + str(c) + ", potom " + str(b) + ", potom " + str(a))
elif a>=c and c>=b:
print ("Samoe bolsho chislo " + str(a) + ", potom " + str(c) + ", potom " + str(b))
elif b>=c and c>=a:
print ("Samoe bolsho chislo " + str(b) + ", potom " + str(c) + ", potom " + str(a))
else :
print ("Samoe bolsho chislo " + str(c) + ", potom " + str(a) + ", potom " + str(b))
print ('Vvedite chislo x')
x = input()
print ('Vvedite chislo y')
y = input()
print ('Vvedite chislo z')
z = input()
compare (x,y,z)
|
import tkinter
width = 350
height = 250
title = "vasyaeva"
top = tkinter.Tk()
top.minsize(width=width + 10, height=height + 10)
if title:
top.title(title)
canvas = tkinter.Canvas(top, width=width + 2, height=height + 2)
canvas.pack()
canvas.xview_scroll(8, 'units') # hack so (0, 0) works correctly
canvas.yview_scroll(8, 'units') # otherwise it's clipped off
# Написать свой код сюда ----------------------
points = [10, 180, 200, 180, 160, 220, 40, 220]
canvas.create_polygon(points, outline='black',
fill='grey', width=1)
canvas.create_line(70, 180, 40, 40, fill='brown', width=2)
points = [70, 180, 150, 150, 170, 120, 160, 70, 120, 50, 40, 40, 90, 80, 100, 120, 90, 150, 70, 180]
canvas.create_polygon(points, outline='black',
fill='red', width=1)
canvas.create_line(40, 40, 30, 30, fill='brown', width=2)
points = [30, 30, 60, 20, 20, 10]
canvas.create_polygon(points, outline='black',
fill='blue', width=1)
canvas.create_oval(260, 10, 300, 50, outline="yellow",
fill="yellow", width=1)
canvas.create_line(250, 20, 220, 20, fill='yellow')
canvas.create_line(250, 30, 220, 40, fill='yellow')
canvas.create_line(260, 40, 230, 60, fill='yellow')
canvas.create_line(270, 50, 250, 80, fill='yellow')
canvas.create_line(280, 50, 280, 90, fill='yellow')
x = 0
y = 0
n = 100
canvas.create_rectangle(x, y, width, height)
if tkinter._default_root:
tkinter._default_root.update()
tkinter.mainloop()
|
def compare(a, b):
if a >= b:
print(str(a) + ' Is bigger')
else:
print(str(b) + ' Is bigger')
x = 34
y = 95
compare(x, y)
def compare(d, f):
if d >= f:
return d
else:
return f
x = 32
y = 99
compare(x, y)
|
mydict = {"comma":",","apostrophe": "'", "dot": ".", "space": " "}
s = 'Sorry{comma}{space}I{space}didn{apostrophe}t{space}understand{space}this{space}task{dot}'.format(**mydict)
print(s)
|
print("Переменные\n")
k=input('Задача1. Перевод секунд в часы и минуты.\nВведите целое число секунд k = ')
while k.isdigit()==False:
k = input('Вы ввели ошибочные данные, введите целое число секунд k = ')
else:
h = int(k) // 3600
m = (int(k) % 3600) // 60
print("Ответ: " + str(k) + " секунд - это " + str(h) + " час(ов) и " + str(m) + " минут(ы)\n")
#---------------------------------------------------------------
d=input('Задача2. Перевод угла поворота стрелки в часы и минуты.\nВведите целое число градусов поворота d = ')
while d.isdigit()==False:
d = input('Вы ввели ошбиочные данные. Введите целое число секунд k = ')
else:
h2 = int(d) // 30
m2 = (int(d) % 30) *2
print("Ответ: " + str(d) + " градусов поворота стрелки - это " + str(h2) + " час(ов) и " + str(m2) + " минут(ы)\n")
#---------------------------------------------------------------
print("\n\nСтроки\n")
s=input('Задача1. Разбор строки.\nВведите строку больше трёх символов s = ')
while len(s)<=3:
s = input('Вы ввели слишком короткую строку, введите строку длинной больше 3 символов: ')
else:
print("1. Третий символ строки: " + s[2])
print("2. Предпоследний символ троки: " + s[len(s) - 2])
print("3. Первые пять символов строки: " + s[0:5])
print("4. Вся строка за исключением двух последних символов: " + s[0:(len(s)-2)])
print("5. Члены строки с чётными индексами, начиная с индекса 0: ")
i=0
while i < len(s):
print(s[i], end=' ')
i+=2
else:
print()
print("6. Члены строки с нечётными индексами, начиная с индекса 1: ")
i = 1
while i < len(s):
print(s[i], end=' ')
i += 2
else:
print()
print("7. Члены строки в обратном порядке: ")
i = len(s)-1
while i>=0:
print(s[i], end=' ')
i-=1
else:
print()
print("8. Члены строки в обратном порядке через один начиная с последнего: ")
i = len(s)-1
while i>=0:
print(s[i], end=' ')
i-=2
else:
print()
print("9. Длина строки равна "+ str(len(s))+" символов\n")
print("Задача 2. Заменить символы 'h' на символы 'H'. ")
s = input("Введите строку, в которой надо заменить символы: ")
while "h" not in s:
print("В ведённой строке нет символов 'h', поэтому ответом будет эта же строка: "+s)
s = input("Введите строку, в которой надо заменить символы 'h': ")
else:
print("Результат: "+ s.replace('h', 'H')+"\n")
print("Задача 3. Переставить местами слова в строке")
s = input("Введите строку, содержащую 2 слова через пробел: ")
# while " " not in s: # Запретили использовать циклы, поэтому проверить, введены ли 2 слова, - не можем )))
# s = input("В ведённой строке нет пробелов, пожалуйста, введите строку с пробелами: ")
s2=s.split(sep=" ", maxsplit = 2)
print("Результат перестановки слов: "+ s2[1]+" "+s2[0])
print("\n\nРешение задач окончено, спасибо.")
|
import turtle
import math
turtle.title ("Run, turtle, run")
width = 500
height = 400
x = -width/2
y = height/2
n = 100
turtle.setup = (width + 10, height + 10)
turtle.speed (10)
turtle.radians ()
turtle.penup ()
turtle.goto (x,y)
turtle.pendown()
# Рисуем красные линии
turtle.color('red')
for i in range(n):
y_add = (i / (n - 1)) * height
l = math.sqrt ((width)**2 + y_add**2)
a = math.asin (y_add/l)
turtle.right (a)
turtle.forward (l)
turtle.penup ()
turtle.back (l)
turtle.left (a)
turtle.pendown ()
# Рисуем зелёные линии
turtle.color('green')
y_prev = 0
for i in range(n):
x_add = (i / (n - 1)) * width
y_add = (i / (n - 1)) * height
turtle.penup ()
turtle.right (math.pi/2)
turtle.forward (y_add - y_prev)
turtle.left (math.pi/2)
turtle.pendown ()
l = math.sqrt (x_add**2 + ((height - y_add)**2))
a = math.asin ((height - y_add)/l)
turtle.right (a)
turtle.forward (l)
turtle.penup ()
turtle.back (l)
turtle.pendown ()
turtle.left (a)
y_prev = y_add
turtle.mainloop()
|
for a in range(1,101): # cоздаем список
if (a%15)==0: #каждое кратное число переименоваем на FizzBuzz
print("FizzBuzz")
elif (a%3)==0: # кратное 3 меняем на Fizz
print("Fizz")
elif (a%5)==0: # кждае кратное 5 переменовать в Buzz
print("Buzz")
else:
print(a) # Вывести результат
|
class Money(object):
value = 0.0
USDexRate=65.31
Rubles=True
def __str__(self):
A = self.value//1
B = self.value%1*101
return (str(int(A))+","+str(int(B)))
def __add__(self, other):
self.value += other
return self.value
def __sub__(self, other):
self.value -= other
return self.value
def __mul__(self, other):
self.value *= other
return self.value
def __truediv__(self, other):
self.value /= other
return self.value
def __eq__(self, other):
return self.value==other
def __ne__(self, other):
return self.value != other
def __lt__(self, other):
return self.value < other
def __gt__(self, other):
return self.value > other
def __le__(self, other):
return self.value <= other
def __ge__(self, other):
return self.value >= other
def Compare(self, other):
if not isinstance(other, int) and not isinstance(other, float):
print('Вы ввели не число, сравнить нельзя')
elif self.value == other:
print ('Значение равно ' + str(other))
elif self.value > other:
print('Значение больше ' + str(other))
elif self.value < other:
print('Значение меньше ' + str(other))
def ChangeCurrency(self):
if self.Rubles:
self.value=self.value/self.USDexRate
print('Переведено из рублей в доллары, составляет ' + self.__str__() + ' доллара(ов)')
else:
self.value = self.value * self.USDexRate
print('Переведено из долларов в рубли, составляет ' + self.__str__() + ' рубля(ей)')
self.Rubles = not self.Rubles
# Код закончен, теперь проверка: ---------------------------------------------------------------------
Salary = Money()
Salary.value = float(input('Введите сумму Значения с копейками через точку: '))
print(Salary)
Salary+4000
print("Прибавим к Значению 4000, будет " + str(Salary))
Salary-34547
print("Вычтем из Значения 34547, будет " + str(Salary))
Salary*3
print("Умножим Значение на 3, будет " + str(Salary))
Salary/2
print("Разделим Значение на 2, будет " + str(Salary))
k = float(input("Введите число, с которым сравнить Значение: "))
Salary.Compare(k)
print('Значение равно '+ str(k) +"? "+ str(Salary == k))
print('Значение больше '+ str(k) +"? "+ str(Salary >= k))
print('Значение меньше '+ str(k) +"? "+ str(Salary <= k))
Salary.ChangeCurrency()
Salary.ChangeCurrency()
|
class Money():
def __init__(self, wholes, cents):
if type(wholes) != int:
raise TypeError('Рубль должен быть целым числом')
if cents not in range(0, 100):
raise ValueError('Копейка должна быть числом от 0 до 99')
self.wholes = int(wholes)
self.cents = int(cents)
self.sum = self.wholes * 100 + self.cents
def __str__(self):
return f'{self.wholes},{self.cents}'
def __add__(self, other):
new_wholes = self.wholes + other.wholes + ((self.cents + other.cents)//100)
new_cents = (self.cents + other.cents) % 100
return Money(new_wholes, new_cents)
def __sub__(self, other):
new_wholes = (self.sum - other.sum) // 100
new_cents = (self.sum - other.sum) % 100
return Money(new_wholes, new_cents)
def __truediv__(self, other):
new_wholes = (self.sum / other.sum) // 100
new_cents = (self.sum / other.sum) % 100
return Money(new_wholes, new_cents)
def __lt__(self, other):
if self.sum < other.sum :
return True
else :
False
def __le__(self, other):
if self.sum <= other.sum :
return True
else :
False
def __eq__(self, other):
if self.sum == other.sum :
return True
else :
False
def __ne__(self, other):
if self.sum != other.sum :
return True
else :
False
def __gt__(self, other):
if self.sum > other.sum :
return True
else :
False
def __ge__(self, other):
if self.sum >= other.sum :
return True
else :
False
def getCourse(self, course):
self.course = int(course)
new_wholes = (int(self.sum/course))//100
new_cents = (int(self.sum/course)) % 100
return Money(new_wholes,new_cents)
bm_1 = Money(80, 98)
print(bm_1)
bm_2 = Money(2, 30)
print(bm_2)
bm_3 = bm_2 + bm_1
print(bm_3)
print(bm_1 - bm_2)
print(bm_1.getCourse(70))
|
#1. Операции со строками
s = "Дана строка."
# Сначала выведите третий символ этой строки.
print(s[2])
# Во второй строке выведите предпоследний символ этой строки.
print(s[-2])
# В третьей строке выведите первые пять символов этой строки.
print(s[0:5:1]) #начало строки 0, кол-во символов 5, шаг - каждый 1й
# В четвертой строке выведите всю строку, кроме последних двух символов.
print(s[0:-2:1])
# В пятой строке выведите все символы с четными индексами (считая, что индексация начинается с 0, поэтому символы выводятся начиная с первого).
print(s[0::2])
# В шестой строке выведите все символы с нечетными индексами, то есть начиная со второго символа строки.
print(s[1::2])
# В седьмой строке выведите все символы в обратном порядке.
print(s[-1::-1])
# В восьмой строке выведите все символы строки через один в обратном порядке, начиная с последнего.
print(s[-1::-2])
# В девятой строке выведите длину данной строки.
print("Длина строки " + str(len(s)) + " символов")
# 2.
# Дана строка. Замените в этой строке все появления буквы h на букву H, кроме первого и последнего вхождения.
#st = "matsushita"
st = "hash shweps push help hash"
fst = st.find("h")
#print(fst)
lst = st.rfind("h")
#print(lst)
strng = ""
for i in range(len(st)):
if i == fst and st[i] == "h":
#print(st[i])
strng = strng + st[i]
elif i == lst and st[i] == "h":
#print(st[i])
strng = strng + st[i]
elif st[i] == "h":
#print(st[i].upper())
strng = strng + st[i].upper()
else:
#print(st[i])
strng = strng + st[i]
print(strng)
# 3.Дана строка, состоящая ровно из двух слов, разделенных пробелом. Переставьте эти слова местами. Результат запишите в строку и выведите получившуюся строку.
# При решении этой задачи нельзя пользоваться циклами и инструкцией if.
str = "два слова"
list = str.split()
print(list[1], list[0])
|
##### 1
def my_len(b):
i = 0
for index in b:
i += 1
print(i)
b =[1, 3, 5, 6, 7]
my_len(b)
print()
##### 2
def my_reserve(a):
rv_list=a[::-1]
return rv_list
print(my_reserve([5,6,5,9]))
###3
def Range(start, stop, step):
a = start
b = step
c = stop
while a <= c:
yield a
a = a + b
if b == 0:
print('step = 0')
break
g = Range(1, 16, 0)
for i in g:
print(i)
#### 4
def to_title (strig):
print(str.title(strig))
to_title(' jfsdjfls kjfsd sdflkjdfksjdfksd')
#### 5
def count_symbol(string,a):
print(string.count(a))
count_symbol('sdsadewhgfjhrshfjkdhjskdh','d')
###### 6
######## 7
#######8
#######9
class User:
name = ''
age = 0
def setname(self,name):
self.name =name
def getname(self):
return self.name
def setage(self,age):
self.age = age
def getage(self):
return self.age
class Worker(User):
salary = 0
def setsalary(self,salary):
self.salary =salary
def getsalary(self):
return self.salary
John = Worker
John.age = 25
John.salary = 1000
Jack = Worker
Jack.age = 26
Jack.salary = 2000
print(Jack.salary+John.salary)
|
d = input("Enter how many degrees the clock has shifted") # Ввод градусов
d = int(d)
if d >= 360:
print("Enter the number of degrees no more than one turn of the arrow (360)")
else:
m = d * 2 #Преобразование градусов в минуты и часы
h = int(m / 60)
m = int(m - (h * 60))
print('It is ' + str(h) + ' hours ' + str(m) + ' minutes.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.