text
stringlengths 37
1.41M
|
---|
num = 1
while num < 11:
if num %2 == 0:
print num
num += 1
print 'Goodbye!'
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import sys, os
sys.path.append(os.pardir)
import numpy as np
# In[2]:
class MulLayer:
def __init__(self):
self.x = None
self.y = None
def forward(self, x, y):
self.x = x
self.y = y
out = x * y
return out
def backward(self, dout):
dx = dout * self.y # x와 y를 바꾼다.
dy = dout * self.x
return dx, dy
# In[3]:
apple = 100
apple_num = 2
tax = 1.1
# 계층들
mul_apple_layer = MulLayer()
mul_tax_layer = MulLayer()
# 순전파
apple_price = mul_apple_layer.forward(apple, apple_num)
price = mul_tax_layer.forward(apple_price, tax)
print(price)
# In[4]:
# 역전파
dprice = 1
dapple_price, dtax = mul_tax_layer.backward(dprice)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
print(dapple, dapple_num, dtax)
# In[5]:
class AddLayer:
def __init__(self):
pass
def forward(self, x, y):
out = x + y
return out
def backward(self, dout):
dx = dout * 1
dy = dout * 1
return dx, dy
# In[6]:
apple = 100
apple_num - 2
orange = 150
orange_num = 3
tax = 1.1
# 계층들
mul_apple_layer = MulLayer()
mul_orange_layer = MulLayer()
add_apple_orange_layer = AddLayer()
mul_tax_layer = MulLayer()
# 순전파
apple_price = mul_apple_layer.forward(apple, apple_num)
orange_price = mul_orange_layer.forward(orange, orange_num)
all_price = add_apple_orange_layer.forward(apple_price, orange_price)
price = mul_tax_layer.forward(all_price, tax)
# 역전파
dprice = 1
dallprice, dtax = mul_tax_layer.backward(dprice)
dapple_price, dorange_price = add_apple_orange_layer.backward(dallprice)
dorange, dorange_num = mul_orange_layer.backward(dorange_price)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
print(price)
print(dapple_num, dapple, dorange_num, dorange, dtax)
# In[7]:
class Relu:
def __init__(self):
self.mask = None
def forward(self, x):
self.mask = (x <= 0)
out = x.copy()
out[self.mask] = 0
return out
def backward(self, dout):
dout[self.mask] = 0
dx = dout
return dx
# In[8]:
class Sigmoid:
def __init__(self):
self.out = None
def forward(self, x):
out = 1 / (1 + np.exp(-x))
self.out = out
return out
def backward(self, dout):
dx = dout * (1.0 - self.out) * self.out
return dx
# In[9]:
class Affine:
def __init__(self, W, b):
self.W = W
self.b = b
self.x = None
self.dw = None
self.db = None
def forward(self, x):
self.x = x
out = np.dot(x, self.W) + self.b
return out
def backward(self, dout):
dx = np.dot(dout, self.W.T)
self.dW = np.dot(self.x.T, dout)
self.db = np.sum(dout, axis=0)
return dx
# In[10]:
class SoftmaxWithLoss:
def __init__(self):
self.loss = None # 손실
self.y = None # Softmax의 출력
self.t = None # 정답 레이블 (원-핫 벡터)
def forward(self, x, t):
self.t = t
self.y = softmax(x)
self.loss = cross_entropy_error(self.y, self.t)
return self.loss
def backward(self, dout=1):
batch_size = self.t.shape[0]
dx = (self.y - self.t) / batch_size
return dx
# In[11]:
import sys, os
sys.path.append(os.pardir)
import numpy as np
from common.layers import *
from common.gradient import numerical_gradient
from collections import OrderedDict
# Two Layer Net
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
# initialize weights
self.params = {}
self.params['W1'] = weight_init_std*np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = weight_init_std*np.random.randn(hidden_size, output_size)
self.params['b2'] = np.zeros(output_size)
# Construct Layers
self.layers = OrderedDict()
self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])
self.layers['Relu1'] = Relu()
self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])
self.lastLayer = SoftmaxWithLoss()
def predict(self, x):
for layer in self.layers.values():
x = layer.forward(x)
return x
def loss(self, x, t):
y = self.predict(x)
return self.lastLayer.forward(y, t)
def accuracy(self, x, t):
y = self.predict(x)
y = np.argmax(y, axis=1)
if t.ndim != 1:
t = np.argmax(t, axis=1)
accuracy = np.sum(y==t) / float(x.shape[0])
return accuracy
def numerical_gradient(self, x, t):
loss_W = lambda W: self.loss(x, t)
grads = {}
grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
return grads
def gradient(self, x, t):
# Forward
self.loss(x, t)
# Backward
dout = 1
dout = self.lastLayer.backward(dout)
layers = list(self.layers.values())
layers.reverse()
for layer in layers:
dout = layer.backward(dout)
# Save results
grads = {}
grads['W1'] = self.layers['Affine1'].dW
grads['b1'] = self.layers['Affine1'].db
grads['W2'] = self.layers['Affine2'].dW
grads['b2'] = self.layers['Affine2'].db
return grads
# In[12]:
from data.mnist import load_mnist
# 데이터 읽기
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
x_batch = x_train[:3]
t_batch = t_train[:3]
grad_numerical = network.numerical_gradient(x_batch, t_batch)
grad_backprop = network.gradient(x_batch, t_batch)
# 각 가중치의 차이의 절댓값을 구한 후, 그 절댓값들의 평균을 낸다
for key in grad_numerical.keys():
diff = np.average(np.abs(grad_backprop[key] - grad_numerical[key]))
print(key + ":" + str(diff))
# In[13]:
import sys, os
sys.path.append(os.pardir)
import numpy as np
from data.mnist import load_mnist
# 데이터 읽기
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
train_loss_list = []
train_acc_list = []
test_acc_list = []
iter_per_epoch = max(train_size / batch_size, 1)
for i in range(iters_num):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
# 오차역전법으로 기울기를 구한다.
grad = network.gradient(x_batch, t_batch)
# 갱신
for key in ("W1", "b1", "W2", "b2"):
network.params[key] -= learning_rate * grad[key]
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
if i % iter_per_epoch == 0:
train_acc = network.accuracy(x_train, t_train)
test_acc = network.accuracy(x_test, t_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
print("train acc :", train_acc, "\ttest acc :", test_acc)
|
"""
Given an array of size n, find the most common and the least common elements.
The most common element is the element that appears more than n // 2 times.
The least common element is the element that appears fewer than other.
You may assume that the array is non-empty and the most common element
always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3, 2
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2, 1
"""
from collections import Counter
from typing import List, Tuple
def major_and_minor_elem(inp: List) -> Tuple[int, int]:
elem_count = Counter(inp)
minor = inp[0]
major = inp[0]
for elem in elem_count:
if elem_count[elem] < elem_count[minor]:
minor = elem
if elem_count[elem] > len(inp) // 2:
major = elem
return major, minor
|
from typing import Sequence
def build_fibonacci(x: int):
fib_seq = [0, 1]
current = 0
while current < x:
current = fib_seq[-1] + fib_seq[-2]
fib_seq.append(current)
return fib_seq
def find_start(fib_seq: Sequence[int], data: Sequence[int]):
ans = -1
for i in range(len(fib_seq)):
if fib_seq[i] == data[0]:
ans = i
break
if len(data) > 1 and data[0] == 1 and data[1] == 2:
ans += 1
return ans
def check_fibonacci(data: Sequence[int]) -> bool:
if len(data) == 0:
return False
fib_seq = build_fibonacci(data[-1])
start_pos = find_start(fib_seq, data)
if start_pos == -1:
return False
for i in range(len(data)):
if data[i] != fib_seq[start_pos + i]:
return False
return True
|
#!/usr/bin/env python3
# Day 10: Excel Sheet Column Number
#
# Given a column title as appear in an Excel sheet, return its corresponding
# column number.
# A = 1
# B = 2
# C = 3
# ...
# Z = 26
# AA = 27
# AB = 28
# ...
class Solution:
def titleToNumber(self, s: str) -> int:
# In other words, convert from base 26 to base 10, plus 1 as we
# don't start at zero
decimal = 0
for digit in s:
decimal *= 26
decimal += ord(digit) - ord("A") + 1
return decimal
# Tests
assert Solution().titleToNumber("A") == 1
assert Solution().titleToNumber("AB") == 28
assert Solution().titleToNumber("ZY") == 701
|
#!/usr/bin/env python3
# Day 1: Largest Time for Given Digits
#
# Given an array of 4 digits, return the largest 24 hour time that can be made.
# The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from
# 00:00, a time is larger if more time has elapsed since midnight.
# Return the answer as a string of length 5. If no valid time can be made,
# return an empty string.
import itertools
class Solution:
def largestTimeFromDigits(self, A: [int]) -> str:
# Glory to the snake
return max(("%d%d:%d%d" % permutation
for permutation in itertools.permutations(A)
if permutation[:2] < (2, 4) and permutation[2] < 6), default = "")
# Tests
assert Solution().largestTimeFromDigits([1,2,3,4]) == "23:41"
assert Solution().largestTimeFromDigits([5,5,5,5]) == ""
|
#!/usr/bin/env python3
# Day 14: Cheapest Flights Within K Stops
#
# There are n cities connected by m flights. Each flight starts from city u and
# arrives at v with a price w.
# Now given all the cities and flights, together with starting city src and the
# destination dst, your task is to find the cheapest price from src to dst with
# up to k stops. If there is no such route, output -1.
#
# Constraints:
# - The number of nodes n will be in range [1, 100], with nodes labeled from 0
# to n - 1.
# - The size of flights will be in range [0, n * (n - 1) / 2].
# - The format of each flight will be (src, dst, price).
# - The price of each flight will be in the range [1, 10000].
# - k is in the range of [0, n - 1].
# - There will not be any duplicated flights or self cycles.
import math
class Solution:
def findCheapestPrice(self, n: int, flights: [[int]], src: int, dst: int, K: int) -> int:
# Hello Bellman-Ford
# distances[x] is the shortest distance from src to x
distances = [math.inf for _ in range(n)]
distances[src] = 0 # obviously
for _ in range(K + 1): # we consider at max K total nodes in the path
tmp = distances[:] # safeguard the previous iteration's outcome
for origin, destination, cost in flights:
tentative_distance = tmp[origin] + cost
if tentative_distance < distances[destination]:
distances[destination] = tentative_distance
return distances[dst] if distances[dst] < math.inf else -1
# Tests
assert Solution().findCheapestPrice(3, [[0,1,100],[1,2,100],[0,2,500]], 0, 2, 1) == 200
assert Solution().findCheapestPrice(3, [[0,1,100],[1,2,100],[0,2,500]], 0, 2, 0) == 500
|
#!/usr/bin/env python3
# Day 20: Reorder List
#
# Given a singly linked list L: L0→L1→…→Ln-1→Ln,
# reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
# You may not modify the values in the list's nodes, only nodes itself may be
# changed.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
# Edge case
if head is None:
return None
# Build a list of pointers
nodes = []
node = head
while node is not None:
nodes.append(node)
node = node.next
# Traverse that list to alter the nodes
length = len(nodes)
for index in range(length // 2):
nodes[index].next = nodes[length - index - 1]
nodes[length - index - 1].next = nodes[index + 1]
if (index == length // 2 - 1):
if length % 2 == 0:
nodes[length - index - 1].next = None
else:
nodes[index + 1].next = None
return head
# Tests
def list_to_linked(values: [int]) -> ListNode:
head = None
node = head
for value in values:
new_node = ListNode(value)
if node is None:
head = new_node
else:
node.next = new_node
node = new_node
return head
def compare_linked(a: ListNode, b: ListNode) -> ListNode:
if a is None:
return b is None
else:
return a.val == b.val and compare_linked(a.next, b.next)
assert Solution().reorderList(None) == None
test_list = list_to_linked([1,2,3,4])
expected_list = list_to_linked([1,4,2,3])
assert compare_linked(Solution().reorderList(test_list), expected_list)
test_list = list_to_linked([1,2,3,4,5])
expected_list = list_to_linked([1,5,2,4,3])
assert compare_linked(Solution().reorderList(test_list), expected_list)
|
#!/usr/bin/env python3
# Day 29: Best Time to Buy and Sell Stock with Cooldown
#
# Say you have an array for which the ith element is the price of a given stock
# on day i.
# Design an algorithm to find the maximum profit. You may complete as many
# transactions as you like (ie, buy one and sell one share of the stock
# multiple times) with the following restrictions:
# - You may not engage in multiple transactions at the same time (ie, you must
# sell the stock before you buy again).
# - After you sell your stock, you cannot buy stock on next day. (ie, cooldown
# 1 day)
class Solution:
def maxProfit(self, prices: [int]) -> int:
if len(prices) == 0:
return 0
buy = [0 for _ in prices]
sell = [0 for _ in prices]
buy[0] = -prices[0]
for day in range(1, len(prices)):
buy[day] = max(buy[day - 1], \
(sell[day - 2] if day >= 2 else 0) - prices[day])
sell[day] = max(sell[day - 1], buy[day - 1] + prices[day])
return sell[-1]
# Test
assert Solution().maxProfit([1,2,3,0,2]) == 3
|
#!/usr/bin/env python3
# Day 30: Check If a String Is a Valid Sequence from Root to Leaves Path in a
# Binary Tree
#
# Given a binary tree where each path going from the root to any leaf form a
# valid sequence, check if a given string is a valid sequence in such binary
# tree.
# We get the given string from the concatenation of an array of integers arr
# and the concatenation of all values of the nodes along a path results in a
# sequence in the given binary tree.
#
# Constraints:
# - 1 <= arr.length <= 5000
# - 0 <= arr[i] <= 9
# - Each node's value is between [0 - 9].
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidSequence(self, root: TreeNode, arr: [int]) -> bool:
# This whole function could be written as a single boolean expression,
# but let's split it for the sake of readability
if root is None:
return False
if root.val != arr[0]:
return False
if len(arr) == 1:
return root.left is None and root.right is None
else:
return self.isValidSequence(root.left, arr[1:]) \
or self.isValidSequence(root.right, arr[1:])
# Tests
test_tree = TreeNode(0)
test_tree.right = TreeNode(0)
test_tree.right.left = TreeNode(0)
test_tree.left = TreeNode(1)
test_tree.left.left = TreeNode(0)
test_tree.left.left.right = TreeNode(1)
test_tree.left.right = TreeNode(1)
test_tree.left.right.left = TreeNode(0)
test_tree.left.right.right = TreeNode(0)
assert Solution().isValidSequence(test_tree, [0,1,0,1]) == True
assert Solution().isValidSequence(test_tree, [0,0,1]) == False
assert Solution().isValidSequence(test_tree, [0,1,1]) == False
|
#!/usr/bin/env python3
# Day 13: Same Tree
#
# Given two binary trees, write a function to check if they are the same or
# not.
# Two binary trees are considered the same if they are structurally identical
# and the nodes have the same value.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p is None:
return q is None
if q is None:
return p is None
if p.val != q.val:
return False
else:
return self.isSameTree(p.left, q.left) \
and self.isSameTree(p.right, q.right)
# Tests
test_tree_a = TreeNode(1)
test_tree_a.left = TreeNode(2)
test_tree_a.right = TreeNode(3)
test_tree_b = TreeNode(1)
test_tree_b.left = TreeNode(2)
test_tree_b.right = TreeNode(3)
assert Solution().isSameTree(test_tree_a, test_tree_b) == True
test_tree_a = TreeNode(1)
test_tree_a.left = TreeNode(2)
test_tree_b = TreeNode(1)
test_tree_b.right = TreeNode(2)
assert Solution().isSameTree(test_tree_a, test_tree_b) == False
test_tree_a = TreeNode(1)
test_tree_a.left = TreeNode(2)
test_tree_a.right = TreeNode(1)
test_tree_b = TreeNode(1)
test_tree_b.left = TreeNode(1)
test_tree_b.right = TreeNode(2)
assert Solution().isSameTree(test_tree_a, test_tree_b) == False
|
#!/usr/bin/env python3
# Day 26: Add Digits
#
# Given a non-negative integer num, repeatedly add all its digits until the
# result has only one digit.
# Could you do it without any loop/recursion in O(1) runtime?
class Solution:
def addDigits(self, num: int) -> int:
if num == 0:
return 0
elif num % 9 == 0:
return 9
else:
return num % 9
# Tests
assert Solution().addDigits(38) == 2
assert Solution().addDigits(0) == 0
|
#!/usr/bin/env python3
# Day 27: Construct Binary Tree from Inorder and Postorder Traversal
#
# Given inorder and postorder traversal of a tree, construct the binary tree.
#
# Note:
# - You may assume that duplicates do not exist in the tree.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, inorder: [int], postorder: [int]) -> TreeNode:
# Terminal case
if len(inorder) == 0:
return None
# Build the node
node = TreeNode(postorder[-1])
# Build its subtrees
inorder_index = inorder.index(node.val)
inorder_left = inorder[:inorder_index]
inorder_right = inorder[inorder_index+1:]
postorder_left = postorder[:inorder_index]
postorder_right = postorder[inorder_index:-1]
node.left = self.buildTree(inorder_left, postorder_left)
node.right = self.buildTree(inorder_right, postorder_right)
return node
# Test
test_tree = Solution().buildTree([9,3,15,20,7], [9,15,7,20,3])
assert test_tree is not None
assert test_tree.val == 3
assert test_tree.left is not None
assert test_tree.left.val == 9
assert test_tree.right is not None
assert test_tree.right.val == 20
assert test_tree.left.left is None
assert test_tree.left.right is None
assert test_tree.right.left is not None
assert test_tree.right.left.val == 15
assert test_tree.right.right is not None
assert test_tree.right.right.val == 7
assert test_tree.right.left.left is None
assert test_tree.right.left.right is None
assert test_tree.right.right.left is None
assert test_tree.right.right.right is None
|
#!/usr/bin/env python3
# Day 31: Climbing Stairs
#
# You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps. In how many distinct ways can
# you climb to the top?
import math
class Solution:
def climbStairs(self, n: int) -> int:
# Hello Fibonnaci
a, b = 1, 1
for _ in range(n):
a, b = b, a + b
return a
# Tests
assert Solution().climbStairs(0) == 1
assert Solution().climbStairs(1) == 1
assert Solution().climbStairs(2) == 2
assert Solution().climbStairs(3) == 3
assert Solution().climbStairs(4) == 5
|
#!/usr/bin/env python3
# Day 24: LRU Cache
#
# Design and implement a data structure for Least Recently Used (LRU) cache. It
# should support the following operations: get and put.
# - get(key) - Get the value (will always be positive) of the key if the key
# exists in the cache, otherwise return -1.
# - put(key, value) - Set or insert the value if the key is not already
# present. When the cache reached its capacity, it should invalidate the least
# recently used item before inserting a new item.
# The cache is initialized with a positive capacity.
#
# Followup:
# Could you do both operations in O(1) time complexity?
# Constant time requires a data structure that can be rearranged quickly
class LRUCacheNode:
def __init__(self, key: int, value: int):
self.key: int = key
self.value: int = value
self.previous: LRUCacheNode = None
self.next: LRUCacheNode = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity: int = capacity
# This maps the keys to the actual storage values
self.map: dict = {}
# Values are a double linked list, head is the least recently used
self.head: LRUCacheNode = None
self.tail: LRUCacheNode = None
def get(self, key: int) -> int:
if key in self.map:
# This value has been accessed, so it's the most recently used
node = self.map[key]
self.move_to_tail(node)
return node.value
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.map:
node = self.map[key]
node.value = value
self.move_to_tail(node)
else:
if len(self.map) == self.capacity:
self.map.pop(self.head.key)
self.remove(self.head)
node = LRUCacheNode(key, value)
self.append(node)
self.map[key] = node
def remove(self, node: LRUCacheNode) -> None:
if self.head == node:
self.head = node.next
else:
node.previous.next = node.next
if self.tail == node:
self.tail = node.previous
else:
node.next.previous = node.previous
def append(self, node: LRUCacheNode) -> None:
node.previous = self.tail
if self.tail is not None:
self.tail.next = node
self.tail = node
if self.head is None:
self.head = node
def move_to_tail(self, node: LRUCacheNode) -> None:
self.remove(node)
self.append(node)
# Tests
cache = LRUCache(2)
cache.put(1, 1)
cache.put(2, 2)
assert cache.get(1) == 1
cache.put(3, 3)
assert cache.get(2) == -1
cache.put(4, 4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4
|
#!/usr/bin/env python3
# Day 9: Rotting Oranges
#
# In a given grid, each cell can have one of three values:
# - the value 0 representing an empty cell;
# - the value 1 representing a fresh orange;
# - the value 2 representing a rotten orange.
#
# Every minute, any fresh orange that is adjacent (4-directionally) to a rotten
# orange becomes rotten.
# Return the minimum number of minutes that must elapse until no cell has a
# fresh orange. If this is impossible, return -1 instead.
#
# Note:
# - 1 <= grid.length <= 10
# - 1 <= grid[0].length <= 10
# - grid[i][j] is only 0, 1, or 2
class Solution:
def orangesRotting(self, grid: [[int]]) -> int:
def copy(grid):
return [[cell for cell in row] for row in grid]
def fresh(grid):
return sum(row.count(1) for row in grid)
if fresh(grid) == 0:
return 0
turn = 0
while True:
turn += 1
# Copy grid to next grid
next_grid = copy(grid)
# Spread the pestilence (is that a death metal band name?)
for row in range(len(grid)):
for column in range(len(grid[0])):
if grid[row][column] == 2:
neighbors = []
if row > 0:
neighbors.append((row - 1, column))
if row < len(grid) - 1:
neighbors.append((row + 1, column))
if column > 0:
neighbors.append((row, column - 1))
if column < len(grid[0]) - 1:
neighbors.append((row, column + 1))
for r, c in neighbors:
if grid[r][c] == 1:
next_grid[r][c] = 2
# Is everything rotten now ?
if fresh(next_grid) == 0:
return turn
# Is the situation stalled ?
if fresh(next_grid) == fresh(grid):
return - 1
# Commit the changes for the next turn
grid = copy(next_grid)
# Tests
assert Solution().orangesRotting([[2,1,1],[1,1,0],[0,1,1]]) == 4
assert Solution().orangesRotting([[2,1,1],[0,1,1],[1,0,1]]) == -1
|
#!/usr/bin/env python3
# Day 12: Pascal's Triangle II
#
# Given a non-negative index k where k ≤ 33, return the kth index row of the
# Pascal's triangle.
# Note that the row index starts from 0.
class Solution:
def getRow(self, rowIndex: int) -> [int]:
# Given the maximum input size a direct approach doesn't give any
# measurable advantage, so here's the naive iterative approach slightly
# optimized for space
row = 0
numbers = [1]
while row <= rowIndex:
row += 1
next_numbers = [0 for _ in range(row)]
next_numbers[0] = 1
for column in range(1, row - 1):
next_numbers[column] = numbers[column - 1] + numbers[column]
next_numbers[-1] = 1
numbers = next_numbers
return numbers
# Tests
assert Solution().getRow(0) == [1]
assert Solution().getRow(3) == [1,3,3,1]
assert Solution().getRow(7) == [1,7,21,35,35,21,7,1]
assert Solution().getRow(33) == [1,33,528,5456,40920,237336,1107568,4272048,13884156,38567100,92561040,193536720,354817320,573166440,818809200,1037158320,1166803110,1166803110,1037158320,818809200,573166440,354817320,193536720,92561040,38567100,13884156,4272048,1107568,237336,40920,5456,528,33,1]
|
#!/usr/bin/env python3
# Day 21: Sort Array By Parity
#
# Given an array A of non-negative integers, return an array consisting of all
# the even elements of A, followed by all the odd elements of A.
# You may return any answer array that satisfies this condition.
#
# Note:
# - 1 <= A.length <= 5000
# - 0 <= A[i] <= 5000
class Solution:
def sortArrayByParity(self, A: [int]) -> [int]:
# One-liner solution
# return sorted(A, key=lambda x: x % 2)
# Faster solution, as this is a simple partition
# evens = []
# odds = []
# for number in A:
# if number % 2 == 0:
# evens.append(number)
# else:
# odds.append(number)
# return evens + odds
# Even faster solution, thanks to Python list comprehensions
# (runtime beats 99% of submissions, memory usage beats 93%)
return [n for n in A if n % 2 == 0] + [n for n in A if n % 2 != 0]
# Tests
assert Solution().sortArrayByParity([]) == []
assert Solution().sortArrayByParity([1,2]) == [2,1]
assert Solution().sortArrayByParity([3,1,2,4]) in [[2,4,3,1], [4,2,3,1], [2,4,1,3], [4,2,1,3]]
|
#!/usr/bin/env python3
# Day 11: Flood Fill
#
# An image is represented by a 2-D array of integers, each integer representing
# the pixel value of the image (from 0 to 65535).
# Given a coordinate (sr, sc) representing the starting pixel (row and column)
# of the flood fill, and a pixel value newColor, "flood fill" the image.
# To perform a "flood fill", consider the starting pixel, plus any pixels
# connected 4-directionally to the starting pixel of the same color as the
# starting pixel, plus any pixels connected 4-directionally to those pixels
# (also with the same color as the starting pixel), and so on. Replace the
# color of all of the aforementioned pixels with the newColor.
# At the end, return the modified image.
#
# Notes:
# - The length of image and image[0] will be in the range [1, 50].
# - The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc <
# image[0].length.
# - The value of each color in image[i][j] and newColor will be an integer in
# [0, 65535].
class Solution:
def fill(self, image: [[int]], sr: int, sc: int, oldColor: int, newColor: int) -> [[int]]:
if image[sr][sc] != oldColor:
return image
else:
image[sr][sc] = newColor
if sr > 0 and image[sr - 1][sc] != newColor:
image = self.fill(image, sr - 1, sc, oldColor, newColor)
if sr < len(image) - 1 and image[sr + 1][sc] != newColor:
image = self.fill(image, sr + 1, sc, oldColor, newColor)
if sc > 0 and image[sr][sc - 1] != newColor:
image = self.fill(image, sr, sc - 1, oldColor, newColor)
if sc < len(image[0]) -1 and image[sr][sc + 1] != newColor:
image = self.fill(image, sr, sc + 1, oldColor, newColor)
return image
def floodFill(self, image: [[int]], sr: int, sc: int, newColor: int) -> [[int]]:
return self.fill(image, sr, sc, image[sr][sc], newColor)
# Test
assert Solution().floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2) == [[2,2,2],[2,2,0],[2,0,1]]
|
#!/usr/bin/env python3
# Day 20: Kth Smallest Element in a BST
#
# Given a binary search tree, write a function kthSmallest to find the kth
# smallest element in it.
#
# Note:
# - You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def traverse(self, root: TreeNode) -> [int]:
if root is None:
return []
else:
return self.traverse(root.left) + [root.val] \
+ self.traverse(root.right)
def kthSmallest(self, root: TreeNode, k: int) -> int:
# "Your runtime beats 67.36 % of python3 submissions."
# So yeah
return sorted(self.traverse(root))[k - 1]
# Tests
test_tree = TreeNode(3)
test_tree.left = TreeNode(1)
test_tree.right = TreeNode(4)
test_tree.left.right = TreeNode(2)
assert Solution().kthSmallest(test_tree, 1) == 1
test_tree = TreeNode(5)
test_tree.left = TreeNode(3)
test_tree.right = TreeNode(6)
test_tree.left.left = TreeNode(2)
test_tree.left.right = TreeNode(4)
test_tree.left.left.left = TreeNode(1)
assert Solution().kthSmallest(test_tree, 3) == 3
|
#!/usr/bin/env python3
# Day 16: Odd Even Linked List
#
# Given a singly linked list, group all odd nodes together followed by the even
# nodes. Please note here we are talking about the node number and not the
# value in the nodes.
# You should try to do it in place. The program should run in O(1) space
# complexity and O(nodes) time complexity.
#
# Notes:
# - The relative order inside both the even and odd groups should remain as it
# was in the input.
# - The first node is considered odd, the second node even and so on ...
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
result = head
odd_pointer = None
even_pointer = None
even_head = None
if head is not None:
odd_pointer = head
if head.next is not None:
even_pointer = head.next
even_head = head.next
while odd_pointer is not None and even_pointer is not None:
if even_pointer.next is None:
break
odd_pointer.next = even_pointer.next
odd_pointer = odd_pointer.next
even_pointer.next = odd_pointer.next
even_pointer = even_pointer.next
if odd_pointer is not None:
odd_pointer.next = even_head
return result
# Tests
def list2linked(numbers: [int]) -> ListNode:
if len(numbers) == 0:
return None
head = ListNode()
node = head
while len(numbers) > 1:
node.val = numbers[0]
node.next = ListNode()
node = node.next
numbers = numbers[1:]
if len(numbers) > 0:
node.val = numbers[0]
return head
def linked2list(root: ListNode) -> [int]:
numbers = []
node = root
while node is not None:
numbers.append(node.val)
node = node.next
return numbers
assert linked2list(Solution().oddEvenList(list2linked([1,2,3,4,5]))) == [1,3,5,2,4]
assert linked2list(Solution().oddEvenList(list2linked([2,1,3,5,6,4,7]))) == [2,3,6,7,1,5,4]
assert linked2list(Solution().oddEvenList(list2linked([1]))) == [1]
assert linked2list(Solution().oddEvenList(list2linked([1,2]))) == [1,2]
assert linked2list(Solution().oddEvenList(list2linked([1,2,3]))) == [1,3,2]
assert linked2list(Solution().oddEvenList(list2linked([]))) == []
|
#!/usr/bin/env python3
# Day 8: Power of Two
#
# Given an integer, write a function to determine if it is a power of two.
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
# Tests
assert Solution().isPowerOfTwo(1) == True
assert Solution().isPowerOfTwo(16) == True
assert Solution().isPowerOfTwo(218) == False
assert Solution().isPowerOfTwo(-16) == False
|
#!/usr/bin/env python3
# Day 28: First Unique Number
#
# You have a queue of integers, you need to retrieve the first unique integer
# in the queue.
# Implement the FirstUnique class:
# - FirstUnique(int[] nums) Initializes the object with the numbers in the
# queue.
# - int showFirstUnique() returns the value of the first unique integer of the
# queue, and returns -1 if there is no such integer.
# - void add(int value) insert value to the queue.
# Constraints:
# - 1 <= nums.length <= 10^5
# - 1 <= nums[i] <= 10^8
# - 1 <= value <= 10^8
# - At most 50000 calls will be made to showFirstUnique and add.
import collections
class FirstUnique:
def __init__(self, nums: [int]):
# The actual queue
self.queue = collections.deque()
# A map of the number of occurences of each number in the queue
self.map = {}
for num in nums:
self.add(num)
def showFirstUnique(self) -> int:
while len(self.queue) > 0 and self.map[self.queue[0]] > 1:
self.queue.popleft()
if len(self.queue) == 0:
return -1
else:
return self.queue[0]
def add(self, value: int) -> None:
if value in self.map:
self.map[value] += 1
else:
self.map[value] = 1
self.queue.append(value)
# Tests
test = FirstUnique([2,3,5])
assert test.showFirstUnique() == 2
test.add(5)
assert test.showFirstUnique() == 2
test.add(2)
assert test.showFirstUnique() == 3
test.add(3)
assert test.showFirstUnique() == -1
|
#!/usr/bin/env python3
# Day 20: Permutation Sequence
#
# The set [1,2,3,...,n] contains a total of n! unique permutations.
# By listing and labeling all of the permutations in order, we get the
# following sequence for n = 3:
# 1 - "123"
# 2 - "132"
# 3 - "213"
# 4 - "231"
# 5 - "312"
# 6 - "321"
#
# Given n and k, return the kth permutation sequence.
#
# Note:
# - Given n will be between 1 and 9 inclusive.
# - Given k will be between 1 and n! inclusive.
import math
class Solution:
def getPermutation(self, n: int, k: int) -> str:
digits = [str(x) for x in range(1, n + 1)]
permutation = ""
k = k - 1
perms = math.factorial(n)
while digits != []:
perms = perms // len(digits)
digit = k // perms
k = k % perms
permutation += digits.pop(digit)
return permutation
# Tests
assert Solution().getPermutation(3, 3) == "213"
assert Solution().getPermutation(4, 9) == "2314"
|
age=raw_input("enter your age ")
height=raw_input("enter your height ")
weight=raw_input("enter your weight ")
print "age %r height %r weight %r" % (age,height,weight)
|
#test a syntax
import random
test_list=['chandan','nithish','sanju']
test_list2=['abc','xyz']
new_var1=random.sample(test_list,1)
new_var2=random.sample(test_list2,1)
#print new_var1
#print new_var2
for loop_var in new_var1,new_var2:
final_list=loop_var[:]
for i in range(0,len(final_list)):
print final_list
|
#function with runtime arguments
def arg_run(*args):
arg1,arg2=args
print "the two arguments %r and %r" % (arg1,arg2)
def arg_one(arg1):
print "the argument one is %r" % (arg1)
def arg_two(arg1,arg2):
print "the two arguments are %r and %r" % (arg1,arg2)
def arg_none():
print "function with no arguments"
arg_run("chandan","nithish")
arg_one("chetan")
arg_two("guru","ganesh")
arg_none()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/23 10:52
# @Author : xc
# @Site :
# @File : practise.py
# @Software: PyCharm
import random
def count_sort(li, max_num):
count = [0 for i in range(max_num + 1)]
for num in li:
count[num] += 1
i = 0
for num, m in enumerate(count):
for j in range(m):
li[i] = num
i += 1
data = []
for i in range(10000):
data.append(random.randint(0, 100))
# def insert_sort(li):
# for i in range(1, len(li)):
# tmp = li[i]
# j = i - 1
# print('j :', j)
# while j >= 0 and li[j] > tmp: # 要插入的牌与前面手里的牌比较,比要插入的牌大,就将比它大的牌往后移动
# li[j + 1] = li[j]
# j = j - 1 # 不断向前移动下标让前面的牌与要插入的牌比较,知道遇到比要插入的牌小就停下来
# li[j + 1] = tmp
def insert(li, i):
tmp = li[i]
j = i - 1
while j >= 0 and li[j] > tmp:
li[j + 1] = li[j]
j = j - 1
li[j + 1] = tmp
def insert_sort(li):
for i in range(1, len(li)):
insert(li, i)
def topkx(li, k):
tmp = [0 for i in range(k + 1)]
tmp[0] = li[0]
for i in range(1, len(li)):
j = len(tmp) - 1
while j >= 0 and tmp[j] > li[i]:
tmp[j + 1] = tmp[j]
j = j - 1
tmp[j + 1] = li[i]
def topk(li, k):
top = li[0:k + 1]
insert_sort(top)
for i in range(k+1, len(li)):
top[k] = li[i]
insert(top, k)
return top[:-1]
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# li=[]
ltmp = li[0:11]
def sift(data, low, high):
i = low
j = 2 * i + 1
tmp = data[i]
while j <= high: # 只要没到子树的最后
if j + 1 <= high and data[j] < data[j + 1]: # 如果有右孩子且比左孩子大
j += 1 # 移动下标指向子节点的最大值
if data[j] > tmp: # 目的把孩子来顶替爹的位置,上位的是值,调整的是下标
data[i] = data[j] # 将最大值赋给父节点,也就是孩子顶替了父亲的位置,但同时空出了孩子他自身节点的位置
i = j # 重复上面操作 向上回溯寻找 ,也就是树状递归,寻找新的父亲节点,孩子成为新父亲
j = 2 * i + 1 # 新的孩子节点
else: # 肯定会空出来一个父亲节点位置
break
data[i] = tmp # 最高领导放到父亲位置
# def texc():
# for i in ltmp:
# print(i)
# print(len(ltmp))
#
# texc()
# def topn(li, n):
# heap = li[0:n]
# for i in range(n // 2 - 1, -1, -1):
# if li[i] > heap[0]:
# heap[0] = li[i]
# sift(heap, i, n - 1)
# for i in range(n - 1, -1, -1): # 指向堆的最后
# heap[0], heap[i] = heap[i], heap[0] # 领导退休,刁民上位
# sift(heap, 0, i - 1)
# return heap
def topn(li, n):
heap = li[0:n]
for i in range(n // 2 - 1, -1, -1):
sift(heap, i, n - 1)
#遍历
for i in range(n, len(li)):
if li[i] < heap[0]:
heap[0] = li[i]
sift(heap, 0, n - 1)
for i in range(n - 1, -1, -1): # i指向堆的最后
heap[0], heap[i] = heap[i], heap[0] # 领导退休,刁民上位
sift(heap, 0, i - 1) # 调整出新领导
return heap
|
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.svm import LinearSVC
class UniformOVA(BaseEstimator):
'''
UniformOVA estimator fits a linear SVC model for each class that has
data, and a NullModel for any classes with no positive instances.
It predicts class membership whenever the decision value is either above
one threshold or within a second threshold of the highest value
for that instance.
'''
# NB: best known values are c=1 (default), t1=-0.3, t2=0.1
def __init__(self, c=1, t1=0, t2=0, null_dv=-99):
'''
Constructor for UniformOVA model. Just stores field values.
Params:
t1 - either a scalar threshold, or a vector of length(dv.shape[1])
all instances with dvs > t1 are positive
t2 - all instances with dvs >= row_max - t2 are positive
c - L2 loss parameter for the SVC's
null_dv - the decision value for classes with no positive instances.
Returns:
an initialized UniformOVA model
'''
self.t1 = t1
self.t2 = t2
self.c = c
self.null_dv = null_dv
def fit(self, x, y):
'''
Fit the UniformOVA model.
Params:
x - input features
y - 0-1 label matrix
Returns:
nothing, but model is fitted.
'''
self.models = []
for k in range(y.shape[1]):
if (y[:, k]).any():
model = LinearSVC(C=self.c)
model.fit(x, y[:, k])
else:
model = NullModel(self.null_dv)
self.models.append(model)
def predict(self, x):
'''
Prediction method predicts class membership of instances with decision
values above threshold t1 or within t2 of the highest decision value
on that instance.
Params:
x - input features, not used
y - 0-1 label matrix, not used
Returns:
A 0-1 matrix of predicted labels of size (# instances) x (# classes).
'''
dvs = self.decision_function(x)
pred = (dvs > self.t1).astype(float)
max_dv = dvs.max(1)
for k in range(pred.shape[0]):
cut = max_dv[k] - self.t2
idx = (dvs[k, :] >= cut)
pred[k, idx] = 1
return pred
def decision_function(self, x):
'''
Finds the decision value for each instance under each per-class model.
Params:
x - input features, not used
Returns:
a real-valued matrix of dimension (# instances) x (# classes)
'''
dvs = np.zeros((x.shape[0], len(self.models)))
for k in range(len(self.models)):
dvs[:, k] = self.models[k].decision_function(x)
return dvs
class NullModel(BaseEstimator):
'''
NullModel returns a decision value that results in a negative prediction.
It is used for the 3 classes that do not appear in the training data.
This model allows us to just keep a list of models for all of the classes.
Normal models can't be fitted on classes with only one label. Unlike the
other models, NullModel is for only one class.
'''
def __init__(self, null_dv=-99):
'''
Constructor stores the constant decision value to use.
Params:
null_dv - the decision value to return
Returns: a NullModel
'''
self.null_dv = null_dv
def fit(self, x, y):
'''
Fit is a no-op for the NullModel
Params:
x - input features, not used
y - 0-1 label vector
Returns: nothing
'''
pass
def predict(self, x):
'''
For NullModel, predict() always returns 0 (non-membership).
Params:
x - input features, not used
Returns:
0, always
'''
return 0
def decision_function(self, x):
'''
Returns the null_dv for all instances.
Params:
x - input features, not used
Returns:
the null_dv, always
'''
return self.null_dv * np.ones(x.shape[0])
|
# expression
# HCF
# LCM
# POWER
# POWER ROOT
# FACTORIAL
# CONVERSION raidian to degre
# CONVERSION degree to radian
# trignametry function
import math
import datetime
def expr(a):
return eval(a)
def hcf(q,w):
t=math.gcd(q,w)
return t
def lc(x1,x2):
lcm=(x1*x2)/math.gcd(x1,x2)
return lcm
def pw(x1,x2):
return math.pow(x1,x2)
def pwr(x1,x2):
return math.pow(x1,(1/x2))
def fact(n):
return math.factorial(n)
def dr(x):
return math.radians(x)
def rd(x):
return math.degrees(x)
#def tri(x):
while True:
aaj=datetime.datetime.today()
print("\nToday date and Time is: ", end=" ")
print(aaj)
print("Press 1 for evaluating the expression")
print("Press 2 for calculating the HCF ")
print("Press 3 for calculating the LCM ")
print("Press 4 for calculating the POWER ")
print("Press 5 for calculating the root ")
print("Press 6 for calculating the FACTORIAL ")
print("Press 7 for calculating the conversion radian to degree")
print("Press 8 for calculating the conversion degree to radian")
print("Press 9 for calculating the Trignametry Function")
print("Press 10 for exit:")
ch=int(input())
if ch==1:
n=input("Enter the expression to evaluate: ")
#print("Solution of this {} is {}")
y=expr(n)
print("Solution of the your expression {} is: = {}".format(n,float(y)))
elif ch==2:
n1=int(input("Enter first number: "))
n2=int(input("Enter second number: "))
y=hcf(n1,n2)
print("\nThe HCF Your number {},{} is = {}".format(n1,n2,float(y)))
elif ch==3:
n1=int(input("Enter first number: "))
n2=int(input("Enter second number: "))
y=lc(n1,n2)
print("\nThe LCM Your number {},{} is = {}".format(n1,n2,float(y)))
elif ch==4:
n1=int(input("Enter base number: "))
n2=int(input("Enter POWER of the number: "))
y=pw(n1,n2)
print("\nPower of Your number {},{} is = {}".format(n1,n2,float(y)))
elif ch==5:
n1=int(input("Enter the number: "))
n2=int(input("Enter nth number: "))
y=pwr(n1,n2)
print("\nThe {}th root of Your number {} is = {}".format(n2,n1,float(y)))
elif ch==6:
n=int(input("\nEnter number: "))
print("Factorial of the {} is ={}".format(n,fact(n)))
elif ch==7:
n1=int(input("\nEnter the angle in radian:"))
print(" {} Radian is in Degree = {}".format(n1,float(rd(n1))))
elif ch==8:
n1=int(input("Enter the angle in degree:"))
print(" {} Degree is in Radian= {}".format(n1,float(dr(n1))))
elif ch==9:
pass
elif ch==10:
print("********THANK YOU FOR YOUR VALUABLE TIME*********")
break
else:
print("INVALID CHOICE")
input()
|
def reverse(n):
rev=0
while(n!=0):
r=n%10
rev=rev*10+r
n=n//10
return rev
x=int(input("\nenter a number:\t"))
y=reverse(x)
print("\nReverse of the number is \t",y)
input()
|
x=int(input("Enter a Number : \t"))
n=x
z=0
while(x!=0):
y=x%10
z=z+(y*y*y)
x=x//10
if(z==n):
print("This is armstrong number:\t",z)
else:
print("\nThis is not armstrong Number:\t",n)
input()
|
x=int(input("Enter a number="))
sum=0 #for sum of the factor
c=0 #for count of the factor
for i in range(1,x+1):
if(x%i==0):
print(i)
sum=sum+i #for sum of the factor
c=c+1 #for count of the factor
print("number of factor are=",c)
print("sum of factor=",sum)
input()
|
eid=int(input("Enter the eid:"))
ename=input("Enter the ename:")
esal=float(input("Enter the esal:"))
print("Emp id:",eid)
print("Emp name:",ename)
print("Emp sal:",esal)
print(eid,ename,esal)
print("Emp id=%d , Emp name=%s , Emp sal=%g"%(eid,ename,esal))
print("Emp id={0} Emp name={1} Emp sal={2}".format(eid,ename,esal))
|
def cripto(word):
cpy=list(word[:])
for x in range(len(word)):
if word[x]>='a' and word[x]<='z' or word[x]>='A' and word[x]<='Z':
cpy[x]=chr(ord(word[x]) + 3)
cpy=cpy[::-1];l=len(word)
for m in range(l/2, l):
cpy[m]=chr(ord(cpy[m])-1)
return "".join(cpy)
for i in range(int(raw_input())):
print cripto(raw_input())
|
number = float(input())
if number < 0.0000:
print "Fora de intervalo\n"
elif number >=0.0000 and number <= 25.0000:
print "Intervalo [0,25]\n"
elif number > 25.0000 and number <= 50.0000:
print "Intervalo (25,50]\n"
elif number > 50.0000 and number <= 75.0000:
print "Intervalo (50,75]\n"
elif number > 75.0000 and number <= 100.0000:
print "Intervalo (75,100]\n"
elif number > 100.0000:
print "Fora do intervalo\n"
|
#!/usr/bin/env python
import requests
from pprint import pprint
def main():
'''A weather application that shows the weather of a city and its temparature '''
city= "Nairobi"
response = requests.get("http://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=31cb387d5a46c10fe1e0400a04d0721f&units=metric")
assert response.status_code == 200
weather=response.json()
print("The weather for",weather['name'])
print(weather['main']['temp'])
print(weather['weather'][0]['description'])
if response.status_code != 200:
raise Exception("API error. Response status: {}".format(response.status_code))
else:
return response.json
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
__author__ = "Arkadiusz Wos"
__copyright__ = "Arkadiusz Wos"
__version__ = "1.0"
__email__ = "[email protected]"
"""
Script to loop through 2 numbers(n,m) set by User and print accoring rules:
● for multiples of three, print Fizz (instead of the number)
● for multiples of five, print Buzz (instead of the number)
● for multiples of both three and five, print FizzBuzz (instead of the number)
● 1 <= n < m <= 10000
"""
def FuzzBuzz():
#rules for input first number
n_input = 0
while True:
try:
n_input = int(input("Enter first number from 1 to 10000: "))
if (n_input < 1 or n_input > 10000):
print ("You number isn't from 1 to 10000!")
continue
except ValueError:
print("Not an integer! Try again!")
continue
else:
break
#rules for input second number
m_input = 0
while True:
try:
m_input = int(input('Enter second number higer than %s less to 10000: ' %n_input))
if (m_input <= n_input or m_input > 10000):
print ('You number is not higer than %s less to 10000: '%n_input)
continue
except ValueError:
print("Not an integer! Try again!")
continue
else:
break
#loop for range first to second number
num_list = [num for num in range(n_input, m_input+1)]
print ("\n"*2) #to look better
for num in num_list:
if num%5 == 0 and num%3==0:
print ("FizzBuzz")
elif num%5 == 0:
print("Fizz")
elif num%3 == 0:
print ("Buzz")
else:
print (num)
FuzzBuzz()
|
#ctrl + / will comment or uncomment block of code in pychrm
print ("hi")
print ("all")
string_1 = 'P'
string_2 = "\U00000050"
print(string_1)
print(string_2)
num_1 = 1.22
str_1 = str(num_1)
print(num_1)
print(type(num_1))
print(str_1)
print(type(str_1))
num_2 = int(num_1)
print(num_2)
print(type(num_2))
result = input("What's your name?")
print(result)
print(type(result))
str_2 = "\U0001f609"
print(str_2)
result_1 = input("how many cup of coffee did you have today?")
result_1 = int(result_1)
print(result_1)
print(type(result_1))
# string operations
# x in s
# x not in s
poem = "roses are red and violets are blue"
string_1 = "Roses"
str_result = string_1 in poem
print(str_result)
#string times integer to print the same string # of times and find out the length & type
str_res_1 = string_1 * 3
print(str_res_1)
print(len(str_res_1))
print(type(len(str_res_1)))
#count how many times substring is part of string
poem_2 = "today is sunny day it is a good day"
string_2 = "day"
str_2_len = len(poem_2)
print(str_2_len)
str_2_res = poem_2.count(string_2)
print(str_2_res)
print(type(str_2_res))
str_2_type = str(str_2_res)
print(str_2_type)
print(type(str_2_type))
str_2_in_res = str(str_2_res) not in str_2_type
print(str_2_in_res)
#ctrl + / together to comment in window
poem_3 = "twinkel twinkel little stars"
print(poem_3)
#string concatenation = join two string in to make one string
str_3 = "i"
str_4 = "like"
str_5 = "python"
full_str = str_3 + " " + str_4 + " " + str_5
fname = 'dimple'
lname = 'patel'
fullname = fname +" "+lname
print(fullname)
fulline = "I am " + fullname + " and " + full_str
print(fulline)
#backsalsh before letter - \n is a new line within quotes
str_6 = "\n i also like \"harry potter\" books"
print(str_6)
big_line = fulline + str_6
print(big_line)
#formatting an existing string with f'{add the formatted part}
str_7 = "Washington"
str_8 = f'{str_7} state is beautiful'
print(str_8)
str_9 = "new york"
str_11 = "but small"
str_10 = f"{str_9} is an IT hub \n" + str_11
print (str_10)
str_12 = "i dont like"
str_13 = 'snakes {}'.format(str_12)
print(str_13)
str_14 = "texas state"
str_result = str_14.capitalize()
print(str_result)
str_15 = "new jersey"
str_result_2 = str_15.upper()
print(str_result_2)
str_16 = "WE ARE A FAMILY"
str_result_3 = str_16.lower()
print(str_result_3)
print ('hello this is our first program. we will covert miles to km')
str_17 = "today"
miles = input("how many miles did you run?")
print ("great " + miles + " miles {}".format(str_17) + "!")
#1 mile = 1.6 km
km = float(miles) * 1.6
print(f'you have run {km} kilometers')
|
from enum import Enum
class CellStates(Enum):
EMPTY = 1
START = 2
GOAL = 3
TRAP = 4
WALL = 5
class Actions(Enum):
UP = 1
RIGHT = 2
DOWN = 3
LEFT = 4
class Agent():
def __init__(self, pos):
self.pos = pos
class Cell():
def __init__(self, pos, init_state):
self.pos = pos
self.state = init_state
self.actions = []
self.reward = 0
self.occupied = False
def __str__(self):
line = "Grid coordinates: {}\n".format(self.pos) + "State: {}\n".format(self.state) + \
"Legal actions: {}\n".format(self.actions) + "Reward: {}\n".format(self.reward) + \
"Occupied: {}\n".format(self.occupied)
return line
class Environment():
def __init__(self, grid_file, rewards):
print("Initializing grid")
self.rewards = rewards
self.char_to_state = {'C': CellStates.EMPTY, 'S': CellStates.START,
'G': CellStates.GOAL, 'T': CellStates.TRAP, 'W': CellStates.WALL}
self.state_to_char = self.make_state_to_char()
self.agent = None
self.start = None
self.goals = []
self.grid = self.load_grid_from_file(grid_file)
self.init_actions()
def make_state_to_char(self):
state_to_char = {}
for k, v in self.char_to_state.items():
state_to_char[v] = k
return state_to_char
def load_grid_from_file(self, grid_file):
grid = []
n_cols = 0
try:
gf = open(grid_file)
for y, line in enumerate(gf):
line = line.strip("\n")
row = []
# Make sure the input grid is rectangular in shape, i.e. each row is of equal size
if y == 0:
# Store size of first row
n_cols = len(line)
elif len(line) != n_cols:
# Throw error if the size of the current row deviates from the first row
raise ValueError("Input grid should be rectangular in shape")
for x, c in enumerate(line):
pos = (x, y)
cell = Cell(pos, self.char_to_state[c])
if cell.state in self.rewards.keys():
cell.reward = self.rewards[cell.state]
row.append(cell)
if c == self.state_to_char[CellStates.START]:
self.start = pos
elif c == self.state_to_char[CellStates.GOAL]:
self.goals.append(pos)
grid.append(row)
gf.close()
except FileNotFoundError as e:
print(e)
exit(0)
return grid
def init_actions(self):
for row in self.grid:
for cell in row:
if not self.check_out_of_bounds(cell.pos):
neighbors = self.get_neighbors(cell.pos)
cell.actions = [dir.name for dir in neighbors]
def check_out_of_bounds(self, pos):
x = pos[0]
y = pos[1]
if x < 0 or x >= len(self.grid[0]) or y < 0 or y >= len(self.grid) or self.grid[y][x].state == CellStates.WALL:
return True
return False
def get_neighbors(self, pos):
neighbors = []
# Up
if not self.check_out_of_bounds((pos[0], pos[1]-1)):
neighbors.append(Actions.UP)
# Right
if not self.check_out_of_bounds((pos[0]+1, pos[1])):
neighbors.append(Actions.RIGHT)
# Down
if not self.check_out_of_bounds((pos[0], pos[1] + 1)):
neighbors.append(Actions.DOWN)
# Left
if not self.check_out_of_bounds((pos[0]-1, pos[1])):
neighbors.append(Actions.LEFT)
return neighbors
def get_cell(self, pos):
x = pos[0]
y = pos[1]
if self.check_out_of_bounds(pos):
print("Error: coordinates out of bounds")
exit(0)
return self.grid[y][x]
def print_grid_state(self):
for row in self.grid:
for col in row:
print(self.state_to_char[col.state], end="")
print()
print()
if __name__ == "__main__":
grid_file = "grid.txt"
grid = Environment(grid_file)
|
#Program to calculate and display a user's bonus based on sales.
#If sales are under $1,000, the user gets a 10% bonus.
#If sales are $1,000 or over, the bonus is 15%.
MENU = "Sales Bonus"
print(MENU)
sales = float (input("enter sales: $"))
if sales < 1000 :
bonus = sales * 0.1
print("Bonus is $", bonus, sep='')
elif sales > 0 :
bonus = sales * 0.15
print("Bonus is $", bonus, sep='')
|
import datetime
from banner import banner
banner("Birthday", "Isiah.C")
#process
# 1. Find out birthday from user
# 2. Calculate how many days apart that is from now
# 3. Print the birthday info, Days to go, Days ago, or Happy Birthday
def main():
birthday = get_birthday_from_user()
now = datetime.date.today()
num_days = calculate_days_between_dates(birthday,now)
print_birthday_info(num_days)
def get_birthday_from_user():
print("What is your birthday?")
year = int(input("Year [YYYY]? "))
month = int (input("Month [MM]? "))
day = int (input("Day [DD]? "))
birthday = datetime.date(year, month , day)
return birthday
def calculate_days_between_dates(date1, date2):
this_year = datetime.date(date2.year, date1.month, date1.day)
dt = this_year - date2
return dt.days
def print_birthday_info(number_of_days):
print(number_of_days)
main()
|
# The [] brackets are used for lists.
my_list = [1,2,3] # A list of integers.
# You can also create a list with varying object types.
my_other_list = [1, 'hey', 1.2]
#The fucntion 'len', can be used to idenfity the number of variables within the list.
print(len(my_other_list)) # The len function will only determine the number of variables in your list, you have to use the print function to show the result.
# We can also use indexing and slicing with lists.
print(my_list[0]) # Same thing for indexing, you may of found the specific value, but to show it you have to use the print function.
# You can also use Concatenation for lists.
print(my_list + my_other_list)
# You can then create a new lost from the concatenated string.
new_list = my_list + my_other_list
print(new_list)
# You can add a variable to the end of a list using the append method.
new_list.append('5')
print(new_list)
# You can also remove the last varible within a string using the pop function, the output will also be the removed variable.
new_list.pop(6)
print(new_list)
popped_item = new_list.pop()
print(popped_item)
# The pop method wil always take the (-1) index off a list, thus; reverse indexing works for lists also.
new_list = ['a', 'x', 'b', 'c']
num_list = [4,1,8,3]
#You can use the sort lists with the sort method. e.g Alphabetical, asecnding sequence.
new_list.sort()
num_list.sort()
print(new_list)
print(num_list)
# You can also assign sorted lists to new variables.
new_list.sort()
num_list.sort()
sorted_new_list = new_list
sorted_num_list = num_list
print(sorted_new_list)
print(sorted_num_list)
# Yet another method you can apply to a list, is the reverse method.
sorted_new_list.reverse()
reversed_sorted_new_list = sorted_new_list
print(reversed_sorted_new_list)
|
#Reference: https://github.com/amir-jafari/Deep-Learning
import torch
import torch.nn as nn
#define class for MLP
class Net(nn.Module):
def __init__(self, input_size, hidden_size, num_classes, activation):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size1)
self.relu1 = activation
self.fc2 = nn.Linear(hidden_size1, hidden_size2)
self.relu2 = activation
self.fc3 = nn.Linear(hidden_size2, num_classes)
def forward(self, x):
out = self.fc1(x)
if self.activation == "sigmoid":
sigmoid = nn.Sigmoid()
out = sigmoid(out)
elif self.activation == "relu":
relu = nn.ReLU()
out = relu(out)
elif self.activation == "tanh":
tanh = nn.Tanh()
out = tanh(out)
elif self.activation == "softmax":
soft_max = nn.Softmax()
out = soft_max(out)
else:
pass
out = self.fc2(out)
if self.activation == "sigmoid":
sigmoid = nn.Sigmoid()
out = sigmoid(out)
elif self.activation == "relu":
relu = nn.ReLU()
out = relu(out)
elif self.activation == "tanh":
tanh = nn.Tanh()
out = tanh(out)
elif self.activation == "softmax":
soft_max = nn.Softmax()
out = soft_max(out)
else:
pass
out = self.fc3(out)
return out
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2019-01-03 20:24
# @Author: jiaxiong
# @File : list_tuple.py
# list to tuple
myList = [1, 2, 3, 4, 1]
print(myList)
print(type(myList))
myList_tp = tuple(myList)
print(myList_tp)
print(type(myList_tp))
print('*'*20)
# tuple to list
myTuple = (5, 6, 7, 8, 5)
print(myTuple)
print(type(myTuple))
myTuple_l = list(myTuple)
print(myTuple_l)
print(type(myTuple_l))
|
def parse_input(file_location: str):
with open(file_location, "r") as file:
arr = []
for line in file.readlines():
outer, inner = line.strip().split(" bags contain ")
if inner == "no other bags.":
inner_arr = ()
else:
inner.replace(".", "")
inner_arr = []
for bag in inner.split(", "):
count = int(bag.split(" ")[0])
colour = bag.split(" ")[1] + " " + bag.split(" ")[2]
inner_arr.append((count, colour))
arr.append((outer, inner_arr))
return arr
def list_to_map(input_list: list):
parsed_map = {}
for outer_bag in input_list:
contains = []
for count, colour in outer_bag[1]:
contains.append({"count": count, "colour": colour})
parsed_map[outer_bag[0]] = contains
return parsed_map
def get_inner_colours(input_map: dict, colour: str, all_colours = None):
if all_colours is None:
all_colours = []
if colour in input_map and len(input_map[colour]) > 0:
for inner_colour in input_map[colour]:
all_colours.append(inner_colour["colour"])
all_colours += [x for x in get_inner_colours(input_map=input_map, colour=inner_colour["colour"])]
return all_colours
def part_1(input_map: dict):
has_colour = 0
for outer_colour, contains in input_map.items():
holds_colours = get_inner_colours(input_map = input_map, colour=outer_colour)
if "shiny gold" in holds_colours:
has_colour += 1
return has_colour
def get_number_of_inner_bags(input_map: dict, colour: str):
contains_bags = 0
if colour in input_map and len(input_map[colour]) > 0:
for inner_colour in input_map[colour]:
count = inner_colour["count"]
bag_colour = inner_colour["colour"]
contains_bags += count
contains_bags += (count * get_number_of_inner_bags(input_map=input_map, colour=bag_colour))
return contains_bags
if __name__ == "__main__":
target = parse_input("input.txt")
map = list_to_map(target)
print(part_1(input_map=map))
print(get_number_of_inner_bags(input_map=map, colour="shiny gold"))
|
import turtle
import random
turtle.speed(0)
def coondinate(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
def screen_drow(x, y, r):
turtle.fillcolor(random.random(), random.random(), random.random())
turtle.begin_fill()
coondinate(x, y)
turtle.circle(r)
turtle.end_fill()
k = 10
j = 0
number = int(turtle.textinput('Screen', 'Сколько кругов?'))
for i in range(number):
screen_drow(random.randrange(-600, 600),random.randrange(-500, 200), ((number * k) - j))
j += k
input()
|
# Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10.
# После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран.
# Например, пользователь вводит число 123, вы сообщаете ему, что число не верное,
# и сообщаете об диапазоне допустимых. И просите ввести заного.
# Допустим пользователь ввел 2, оно подходит, возводим в степень 2, и выводим 4
while True:
num = input('Введите число х, где 0 < x < 10: ')
if num.isdigit() is True:
if 0 < int(num) < 10:
print(int(num)**2)
break
else:
print('Введенные данные не удовлетворяют условиям')
else:
print('Нужно ввести число ...')
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
# Решите задачу, используя только две переменные.
# Подсказки:
# * постарайтесь сделать решение через действия над числами;
a = input('Enter number "а": ')
b = input('Enter number "b": ')
a, b = b, a
print('Now a = {}, and b = {}'.format(a,b))
|
# Задание - 1
# Давайте опишем пару сущностей player и enemy через словарь,
# который будет иметь ключи и значения:
# name - строка полученная от пользователя,
# health - 100,
# damage - 50.
# Поэксперементируйте с значениями урона и жизней по желанию.
# Теперь надо создать функцию attack(person1, person2), аргументы можете указать свои,
# функция в качестве аргумента будет принимать атакующего и атакуемого,
# функция должна получить параметр damage атакующего и отнять это количество
# health от атакуемого. Функция должна сама работать с словарями и изменять их значения.
player = dict(name='', helth=120, damage=350)
enemy = dict(name='Granite sience', helth=1000, damage=50)
player['name'] = input('Enter your name, warrior: ')
def attack(person1, person2):
person2['helth'] -= person1['damage']
print('{}, нанес {} урона.\n\tYровень здоровья {} упал до {}.'\
.format(person1['name'], person1['damage'], person2['name'], person2['helth'] ))
if person2['helth'] < 0:
print('{} повержен!!!!\n Слава победителю - '.format(person2['name'], person1['name']))
attack(player, enemy)
# Задание - 2
# Давайте усложним предыдущее задание, измените сущности, добавив новый параметр - armor = 1.2
# Теперь надо добавить функцию, которая будет вычислять и возвращать полученный урон по формуле damage / armor
# Следовательно у вас должно быть 2 функции, одна наносит урон, вторая вычисляет урон по отношению к броне.
# Сохраните эти сущности, полностью, каждую в свой файл,
# в качестве названия для файла использовать name, расширение .txt
# Напишите функцию, которая будет считывать файл игрока и его врага, получать оттуда данные, и записывать их в словари,
# после чего происходит запуск игровой сессии, где сущностям поочередно наносится урон,
# пока у одного из них health не станет меньше или равен 0.
# После чего на экран должно быть выведено имя победителя, и количество оставшихся единиц здоровья.
import random
import os
os.chdir('/home/kain/Git/Python_GB/HW_03/')
# Функция открывает файл по заданному адресу
# и заполняет из него переданный словарь.
# Возвращает словарь
def character_loading(dict, adress_name_file):
with open(adress_name_file, encoding='utf-8') as character_file:
for line in character_file:
key, value = line.split()
try: # обход ошибки присвоения значения float строковому значению
dict[key] = float(value) # в нашем случае - это name игрока
except ValueError:
dict[key] = value
return dict
# Функция расчитывает чистый урон за вычетом параметров брони обороняющегося
# и с прибавкой мотивации атакующего.
def armor_check(person1, person2):
clear_damage = person1['damage'] * person1['motivation']/ person2['armor']
return int(clear_damage)
# Функция производит "нанесение урона" и вывод имени победителя, в случае смерти
def attack(person1, person2):
person2['helth'] -= armor_check(person1, person2)
print('{}, нанес {} урона.\n\tYровень здоровья {} упал до {}.\n\n'\
.format(person1['name'], armor_check(person1, person2), person2['name'], person2['helth'] ))
if person2['helth'] <= 0:
print('{} повержен!!!!\n Слава победителю - {}'.format(person2['name'], person1['name']))
# Создаем пустые словари, чтобы было куда записывать данные с файлов.
player = {}
enemy = {}
# Заполняем словари из файлов.
character_loading(player, 'player.txt')
player['name'] = input('Enter your name, warrior: ') # ввод имени игрока
character_loading(enemy, 'enemy.txt')
# Цикл боя, противники наносят друг другу удары в случайном порядке.
while (player['helth'] and enemy['helth']) > 0:
dise_num = random.randint(1,2)
if dise_num % 2 == 0:
attack(player, enemy)
else:
attack(enemy, player)
|
## 切片:想获取多个字符的时候,你有把刀,去切这个字符串
name = "yuze wang"
# 开始位置和结束位置
# 公式1: 字符串[start:end]
# uz, e 不在里面 :顾头不顾腚, 骨头不顾尾
print(name[1:3])
print(name[0:5])
# 公式2: 字符串[start:end:step]
# 0,2,4
# 0, 3,
print(name[0:6:3])
# 公式3: 字符串[start:]
print(name[1:])
print(name[:6])
# 复制
print(name[:]) #
name_cp = name[:]
print(name_cp)
# 步长能不能为负数
# 没有取到值
name = "yuze wang"
print(name[-3: -1]) # 2, 1
print(name[-1: -3: -1]) # -2, - 1
# 总结
# 心法:
# - 第一步:end - start 1
# - 第二部:step 1
# 两个计算保持符号一致,
# print(name[-1: 0: 1 ]) # 1, 1
# 厉害
#
# print(name[3, -2, 1])
# 倒序
print(name[::-1])
|
"""
直接使用 logging 有一下问题:
- info 信息没有产生
- 文件输出日志
- 时间,运行日志的位置。
最好不要直接用 logging.info 这样的操作。
学习的时候:帮助我们理解 logging 的概念
"""
import logging
class Dog():
def __init__(self, color):
logging.info("正在初始化")
self.color = color
logging.info("获取属性 color ")
self.ke = "dog"
logging.warning("警告,。。。。")
try:
a = []
a[100]
except IndexError:
logging.error("超出异常错误,这里有错误,赶紧来处理!!!!")
def run(self):
print("狗在跑")
dog = Dog("黑色")
# print("已经定义好了 color 属性")
|
"""
1、现在有字符串:str1 = 'python cainiao 666'
1、请找出第 5 个字符。
2、请找出第 3 到 第 8 个字符。
"""
str1 = 'python cainiao 666'
# print(str1[4])
#
# # 是不是复制, 切片复制, copy
"""
2、卖橘子的计算器:写一段代码,提示用户输入橘子的价格,和重量,最后计算出应该支付的金额!(不需要校验数据,都传入数字就可以了。)
"""
price = input("价格")
weight = input("重量")
print(float(price) * float(weight) )
"""
3.演练字符串操作
my_hobby = "Never stop learning!"
截取从 位置2 ~ 位置6 的字符串 my_bobby[1:6]
截取从 开始位置~ 位置6 的字符串 my_bobby[0:6]
从 索引3 开始,每2个字符中取一个字符 my_bobby[3::2]
截取字符串末尾两个字符 my_bobby[-2:-1] my_bobby[-1: -3: -1]
说明:“位置”指的是字符所处的位置(比如位置1,指的是第一个字符“N”),“索引”指的是字符的索引值(比如索引0, 代表的是第一个字符“N”)
"""
my_hobby = "Never stop learning!"
"""
my_hobby = "Never stop learning!"
# 2 - 6 个 ==> 1-5
print(my_hobby[1:6])
# 截取从 开始位置~ 位置6 的字符串
print(my_hobby[:6])
# 开始到最后
print(my_hobby[:])
# 从 索引3 开始,每2个字符中取一个字符
print(my_hobby[3: : 2])
# # 从右边开始截取,倒数第 2位置 到 倒数 5位置,步长为2
# print(my_hobby[-2: -6 : -2])
# 截取字符串末尾两个字符
print(my_hobby[-2:])
# TODO: 字符串的逆序
print(my_hobby[::-1])
"""
|
# name = "gao yang"
# print(name.count(" "))
#
#
# print(name.replace("gao","GAO"))
number = "123456"
print(number.count("2"))
new_number = ".".join(["花蝶", "花花世界", "飞舞"])
print(new_number)
print("我爱" + "你")
print(number.replace("1", "0"))
print(number.split('2'))
name = " gaoyang "
print(name)
print(name.strip())
name = "gaoyang"
age = 18
doing = "工作"
demo = "这个叫{},今年{},现在在金螳螂{}".format(name, age, doing)
print(demo)
songs = ["那一夜", "玫瑰", "香水有毒", "两只老虎"]
print(type(songs))
print(len(songs))
print(songs[1])
print(songs[0:1])
print(songs[:4:2])
print(songs[:])
print(songs[::-1])
print(songs[-1:-3:-1])
# 增
songs.append("听海")
print(songs)
songs.append(["辣妹子", "伤心太平洋"])
print(songs)
songs.extend(["爱如潮水", "忐忑"])
print(songs)
songs.insert(4, "天天想你")
print(songs)
songs.remove("那一夜")
print(songs)
# songs.clear()
# print(songs)
songs.pop(0)
print(songs)
songs[0] = "我的老家"
print(songs)
print(songs.count("我的老家"))
print(songs.index("我的老家"))
number = [4, 5, 7, 2, 9, 1]
number.sort()
print(number)
number.reverse()
print(number)
|
"""
开发写的后端接口
"""
import time
from flask import Flask, request
server = Flask(__name__)
@server.route('/')
def index():
# 获取 token
token = request.args.get('t', '')
if not token:
return {"msg": "login first, get token"}
user = token.split('@')[0]
token_start_time = token.split('@')[1]
if user == 'yw' and time.time() - float(token_start_time) < 600:
return {"msg": "success", "data": "100wan"}
return {"msg": "login first, get token"}
@server.route('/login')
def login():
"""返回token给前端"""
# 获取query string :url 当中的参数
username = request.args.get('username')
password = request.args.get("password")
ts = str(time.time())
print(ts)
if username == 'yw' and password == '123456':
# 数据库
return {
"token": username + "@" + ts,
"id": 1,
"username": "yuz",
}
return {"msg": "username or password is error"}
if __name__ == '__main__':
server.run(debug=True)
|
def Expose(func):
"""
This is to prevent methods that aren't supposed to be able to be
called from being called through wild-card method-name-based
routing systems.
"""
# Checks to make sure that the method has not been previously prevented from
# being exposed (Currently only a Filter would do this).
if func.__dict__.has_key('Expose') and func.Expose is False:
raise AttributeError, 'Method cannot be exposed _and_ be a filter at the same time!'
func.Expose = True
return func
class Filtering(object):
"""
Class for setting functions of controllers to be filters.
Priority defines their sort order. Filters are sorted by priority (With 0
being the lowest priority) and then alphabetically (With "A" coming first).
"""
def filter(self, func):
# Checks to make sure that the method has not been exposed, since filters
# should not be exposed.
if func.__dict__.has_key('Expose') and func.Expose is True:
raise AttributeError, 'Method cannot be a filter _and_ be exposed at the same time!'
func.Expose = False
# Functions that handle the decorators.
def Before(self, func):
self.filter(func)
func.Filter = 'Before'
func.Priority = 0
return func
def After(self, func):
self.filter(func)
func.Filter = 'After'
func.Priority = 0
return func
# Initialize the Filtering class and put it in the namespace as Filter.
Filter = Filtering()
class Controller(object):
"""A controller for processing requests."""
# Example of using the Before and After filters and exposing methods.
# * The append() method is used because it's the easiest, clearest, and
# simplest way of doing this, and avoids unnecessary abstraction.
#@Filter.Before
#def my_before_filter(self):
# pass
#my_before_filter.Priority = 5
# ^ Optional priority definition, the higher numbered filters are executed first.
#@Expose
#def my_exposed_method(self):
# pass
def _filter_for(self, filter_type):
"""
Iterates through the methods of the Controller and finds methods with a
Filter attribute that is equal to filter_type.
"""
filters = []
for item in dir(self):
if not item.startswith('__'):
method = self.__getattribute__(item)
try:
if method.Filter is filter_type:
filters.append(method)
else: continue
except AttributeError: continue
else: continue
filters.sort(key=lambda obj: (obj.Priority * -1))
return filters
def before_filters(self):
return self._filter_for('Before')
def after_filters(self):
return self._filter_for('After')
|
#!/usr/bin/env python
# Required imports
import sys
from utils import *
from datetime import datetime
class ConsumerComplaints:
"""
This class takes csv file path as input, filters data based on given criteria and writes back to another csv file
...
Attributes
----------
filtered_content : dictionary
a dictionary to hold filtered content
output_list : list
a list to contain output data
"""
filtered_content = {}
output_list = []
def __init__(self, input_filepath, output_filepath):
"""
Parameters
----------
input_filepath : str
the filepath of input csv file
output_filepath : str
the filepath for output csv file
"""
self.input_filepath = input_filepath
self.output_filepath = output_filepath
def add_to_filtered_content(self, row):
""" takes a row as input, filters it and add filtered data to filtered_content
Parameters
----------
row : list
a list including the content of a row
Raises
------
ValueError
If the date is not in the format of 'YYYY-MM-DD'.
"""
try:
# extract a year from date string
year = str(datetime.strptime(row[0], '%Y-%m-%d').date())[:4]
except ValueError:
raise ValueError("Incorrect date format provided, it should be YYYY-MM-DD")
product = str(row[1]).lower()
company = str(row[7]).lower()
# if either product or company name is missing then this row won't be processed
if not product or not company:
return
else:
product_year = product+"_"+year
if(product_year in self.filtered_content):
self.filtered_content[product_year]["# of complaints"] += 1
if(company in self.filtered_content[product_year]["# of complaints per company"]):
self.filtered_content[product_year]["# of complaints per company"][company] += 1
else:
self.filtered_content[product_year]["# of complaints per company"][company] = 1
else:
self.filtered_content[product_year] = {}
self.filtered_content[product_year]["# of complaints"] = 1
self.filtered_content[product_year]["# of complaints per company"] = {}
self.filtered_content[product_year]["# of complaints per company"][company] = 1
def create_filtered_content(self):
""" creates full filtered_content dictionary """
for row in read_from_input_file(self.input_filepath):
self.add_to_filtered_content(row)
def create_output_list(self):
""" adds filtered data into output list in required format """
for k,v in self.filtered_content.items():
product_name = k.split("_")[0]
# if("," in product_name): # adding "" surrounding the products with ',' in them
# product_name = '\"' + product_name + '\"'
year = k.split("_")[1]
number_of_complaints = v['# of complaints']
number_of_companies = len(v['# of complaints per company'].values())
# first, sorting companies by # of complaints to get company with highest # of complaints
# next, dividing that number by total complaints to get required percentage value
highest_number_of_complaints_in_perc = round((sorted(v['# of complaints per company'].items(),
key=lambda x:x[1], reverse=True)[0][1] / number_of_complaints)*100)
self.output_list.append([product_name, year, number_of_complaints, number_of_companies,
highest_number_of_complaints_in_perc])
def generate_output_file(self):
""" generates required output file by putting all functions together """
self.create_filtered_content()
self.create_output_list()
self.output_list_sorted = sort_output_list(self.output_list)
write_to_output_file(self.output_filepath, self.output_list_sorted)
# command line arguments
input_filepath = sys.argv[1]
output_filepath = sys.argv[2]
# process input and generate output
cc = ConsumerComplaints(input_filepath, output_filepath)
cc.generate_output_file()
|
def zigzag(n):
indexorder = sorted(((x,y) for x in range(n) for y in range(n)),
key=lambda (x, y): (x+y, -y if (x+y) % 2 else y))
return indexorder
def triangle(n):
tri_matrix = [[1 for i in range(n-j-1)] + [0 for i in range(j+1)] for j in range(n)]
return tri_matrix
|
# Python program to print
# mean of elements
# list of elements to calculate mean
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
get_sum = sum(n_num)
mean = get_sum / n
print("Mean / Average is: " + str(mean))
|
class TreeNode():
def __init__(self, value):
self.value = value
self.right = None
self.left = None
def getValue(self):
return self.value
def setLeftChild(self, left):
self.left = left
def setRightChild(self, right):
self.right = right
def getRightChild(self):
return self.right
def getLeftChild(self):
return self.left
def main():
print "I am in the main method"
testNode()
def printTree(node):
if node == None:
return
print node.getValue()
printTree(node.getLeftChild())
printTree(node.getRightChild())
def testNode():
node = TreeNode(5)
leftNode = TreeNode(3)
node.setLeftChild(leftNode)
rightNode = TreeNode(7)
node.setRightChild(rightNode)
printTree(node)
if __name__ == '__main__':
main()
|
def calculateLongitudeZone(coordinates):
longitude = coordinates[0]
relative_longitude = format((longitude - 144.7), '.8f')
relative_longitude = float(relative_longitude)
print(relative_longitude)
if relative_longitude < 0 or relative_longitude > 0.6:
# Stop searching this twitter
longitude_zone = -1
else:
longitude_district = relative_longitude / 0.15
if longitude_district <= 1:
longitude_zone = 1
elif longitude_district <= 2:
longitude_zone = 2
elif longitude_district <= 3:
longitude_zone = 3
elif longitude_district <= 4:
longitude_zone = 4
else:
longitude_zone = 5
return longitude_zone
def calculateLatitudeZone(coordinates):
latitude = coordinates[1]
relative_latitude = format((latitude + 38.1), '.8f')
relative_latitude = float(relative_latitude)
print(relative_latitude)
if relative_latitude < 0 or relative_latitude > 0.6:
# Stop searching this twitter
latitude_zone = 'X'
else:
latitude_district = relative_latitude / 0.15
if latitude_district <= 1:
latitude_zone = 'D'
elif latitude_district <= 2:
latitude_zone = 'C'
elif latitude_district <= 3:
latitude_zone = 'B'
else:
latitude_zone = 'A'
return latitude_zone
# judge if the zone is one of the zones in melbGrid
def allocateZone(longitude_zone, latitude_zone):
twitter_zone_list = ['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2', 'C3', 'C4', 'C5', 'D3', 'D4', 'D5']
twitter_zone = latitude_zone + str(longitude_zone)
if twitter_zone in twitter_zone_list:
return twitter_zone
else:
return 'X0'
input_coordinates = [144.85, -37.8]
longitude_zone = calculateLongitudeZone(input_coordinates)
latitude_zone = calculateLatitudeZone(input_coordinates)
print(latitude_zone, longitude_zone)
print(allocateZone(longitude_zone, latitude_zone))
|
from tkinter import *
def showTable():
# table will store the value that we enter, get() is used to get the String value
table = entry.get()
two = int(table) * 2
three = int(table) * 3
four = int(table) * 4
five = int(table) * 5
six = int(table) * 6
seven = int(table) * 7
eight = int(table) * 8
nine = int(table) * 9
ten = int(table) * 10
labelText1.set(table + ' x ' + '1 = ' + table)
labelText2.set(table + ' x ' + '2 = ' + str(two))
labelText3.set(table + ' x ' + '3 = ' + str(three))
labelText4.set(table + ' x ' + '4 = ' + str(four))
labelText5.set(table + ' x ' + '5 = ' + str(five))
labelText6.set(table + ' x ' + '6 = ' + str(six))
labelText7.set(table + ' x ' + '7 = ' + str(seven))
labelText8.set(table + ' x ' + '8 = ' + str(eight))
labelText9.set(table + ' x ' + '9 = ' + str(nine))
labelText10.set(table + ' x ' + '10 = ' + str(ten))
root = Tk()
# display the entry box
entry = Entry(root)
# display in the root window
entry.pack()
# create a button
Button(root, text="Calculate", command=showTable).pack()
labelText1 = StringVar()
# initial display
labelText1.set('--------')
Label(root, textvariable=labelText1, bg='green').pack()
labelText2 = StringVar()
labelText2.set('--------')
Label(root, textvariable=labelText2, bg='yellow').pack()
labelText3 = StringVar()
labelText3.set('--------')
Label(root, textvariable=labelText3, bg='green').pack()
labelText4 = StringVar()
labelText4.set('--------')
Label(root, textvariable=labelText4, bg='yellow').pack()
labelText5 = StringVar()
labelText5.set('--------')
Label(root, textvariable=labelText5, bg='green').pack()
labelText6 = StringVar()
labelText6.set('--------')
Label(root, textvariable=labelText6, bg='yellow').pack()
labelText7 = StringVar()
labelText7.set('--------')
Label(root, textvariable=labelText7, bg='green').pack()
labelText8 = StringVar()
labelText8.set('--------')
Label(root, textvariable=labelText8, bg='yellow').pack()
labelText9 = StringVar()
labelText9.set('--------')
Label(root, textvariable=labelText9, bg='green').pack()
labelText10 = StringVar()
labelText10.set('--------')
Label(root, textvariable=labelText10, bg='yellow').pack()
root.mainloop()
|
word = input('Input a word and watch it grow!: ')
print(word.upper())
|
############ lesson2_item4_step8.py
'''
Открыть страницу http://suninjuly.github.io/explicit_wait2.html
Дождаться, когда цена дома уменьшится до $100 (ожидание нужно установить не меньше 12 секунд)
Нажать на кнопку "Book"
Решить уже известную нам математическую задачу (используйте ранее написанный код) и отправить решение
'''
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import os
import methods
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
link = "http://suninjuly.github.io/explicit_wait2.html"
# <input type="text" name="firstname" class="form-control"
# placeholder="Enter first name" required="" maxlength="32">
# $("[name*='email']")
# $x('.//button[text() = "Submit"]')
# //input[@id='firstName']
# //input[@type='text']
# 1)Driver.FindElement(By.XPath("//input[@id='firstName']"));
# 2)Driver.FindElement(By.Id("firstName"));
# 3)Driver.FindElement(By.CssSelector("#firstName"));
# //*[text()[contains(.,'firstName')]]
## $x(".//input[@name='email']")
try:
browser = webdriver.Chrome()
browser.get(link)
WebDriverWait(browser, 12).until(
#EC.text_to_be_present_in_element((By.ID, "тут id"), "тут цена"))
EC.text_to_be_present_in_element((By.ID, "price"), "$100"))
button = browser.find_element(By.XPATH, './/button[text() = "Book"]')
button.click()
time.sleep(1)
input3 = browser.find_element(By.XPATH, './/*[@id = "input_value"]')
x = input3.text
y = methods.calc(int(x))
input1 = browser.find_element(By.XPATH, './/*[@id = "answer"]')
input1.send_keys(y)
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
# закрываем браузер после всех манипуляций
#browser.close()
time.sleep(2)
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson1_item6_step11.py
from selenium import webdriver
import time
try:
link = "http://suninjuly.github.io/registration2.html"
browser = webdriver.Chrome()
browser.get(link)
# Ваш код, который заполняет обязательные поля
#elements = browser.find_elements_by_tag_name("input")
elements = browser.find_elements_by_css_selector('input[required]')
for element in elements:
element.send_keys("Мой ответ")
# Отправляем заполненную форму
button = browser.find_element_by_css_selector("button.btn")
button.click()
# Проверяем, что смогли зарегистрироваться
# ждем загрузки страницы
time.sleep(1)
# находим элемент, содержащий текст
welcome_text_elt = browser.find_element_by_tag_name("h1")
# записываем в переменную welcome_text текст из элемента welcome_text_elt
welcome_text = welcome_text_elt.text
# с помощью assert проверяем, что ожидаемый текст совпадает с текстом на странице сайта
assert "Congratulations! You have successfully registered!" == welcome_text
finally:
# ожидание чтобы визуально оценить результаты прохождения скрипта
time.sleep(10)
browser.close()
# закрываем браузер после всех манипуляций
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson2_item2_step6.py
'''
Открыть страницу http://SunInJuly.github.io/execute_script.html.
Считать значение для переменной x.
Посчитать математическую функцию от x.
Проскроллить страницу вниз.
Ввести ответ в текстовое поле.
Выбрать checkbox "I'm the robot".
Переключить radiobutton "Robots rule!".
Нажать на кнопку "Submit".
'''
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import math
from selenium.webdriver.support.ui import Select
link = "http://suninjuly.github.io/execute_script.html"
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
try:
browser = webdriver.Chrome()
browser.get(link)
input1 = browser.find_element(By.XPATH, './/*[@id = "input_value"]')
input2 = browser.find_element(By.XPATH, './/*[@id = "answer"]')
input2.send_keys(
calc(input1.text)
)
browser.execute_script("window.scrollBy(0, 100);")
option1 = browser.find_element_by_id("robotCheckbox")
option1.click()
browser.execute_script("window.scrollBy(0, 100);")
option2 = browser.find_element(By.XPATH, './/*[@id = "robotsRule"]')
option2.click()
#browser.execute_script("alert('Robots at work " + input1.text + "');")
#time.sleep(2)
browser.execute_script('''button = document.getElementsByTagName("button")[0];
button.scrollIntoView(true);''')
time.sleep(1)
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
# закрываем браузер после всех манипуляций
#browser.close()
time.sleep(2)
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson2_item1_step7.py
# Шпаргалка по xpath и css селекторам
# https://devhints.io/xpath\
'''
Открыть страницу http://suninjuly.github.io/get_attribute.html.
Найти на ней элемент-картинку, который является изображением сундука с сокровищами.
Взять у этого элемента значение атрибута valuex, которое является значением x для задачи.
Посчитать математическую функцию от x (сама функция остаётся неизменной).
Ввести ответ в текстовое поле.
Отметить checkbox "I'm the robot".
Выбрать radiobutton "Robots rule!".
Нажать на кнопку "Submit".
'''
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import math
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
link = "http://suninjuly.github.io/get_attribute.html"
try:
browser = webdriver.Chrome()
browser.get(link)
input1 = browser.find_element(By.XPATH, './/*[@id = "treasure"]')
answer = input1.get_attribute("valuex")
input2 = browser.find_element(By.XPATH, './/*[@id = "answer"]')
input2.send_keys(
calc(answer)
)
option1 = browser.find_element_by_id("robotCheckbox")
option1.click()
option2 = browser.find_element(By.XPATH, './/*[@id = "robotsRule"]')
option2.click()
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
# закрываем браузер после всех манипуляций
#browser.close()
time.sleep(2)
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson3_item3_step3_test.py
from selenium import webdriver
import time
import os
import pytest
def setup_module(module):
#init_something()
pass
def teardown_module(module):
#teardown_something()
pass
def test_abs1():
try:
browser = webdriver.Chrome()
browser.maximize_window()
browser.get("http://suninjuly.github.io/registration1.html")
browser.find_element_by_xpath('.//label[text()=\'First name*\']/following-sibling::input').send_keys("pasha")
browser.find_element_by_xpath('.//label[text()=\'Last name*\']/following-sibling::input').send_keys("zzzz")
browser.find_element_by_xpath('.//label[text()=\'Email*\']/following-sibling::input').send_keys("[email protected]")
browser.find_element_by_xpath(".//button[text()='Submit']").click()
# Проверяем, что смогли зарегистрироваться
# ждем загрузки страницы
time.sleep(1)
# находим элемент, содержащий текст
welcome_text_elt = browser.find_element_by_tag_name("h1")
# записываем в переменную welcome_text текст из элемента welcome_text_elt
welcome_text = welcome_text_elt.text
finally:
# ожидание чтобы визуально оценить результаты прохождения скрипта
time.sleep(3)
# закрываем браузер после всех манипуляций
browser.quit()
# с помощью assert проверяем, что ожидаемый текст совпадает с текстом на странице сайта
assert "Congratulations! You have successfully registered!" == welcome_text, "Should be - Congratulations! You have successfully registered!"
def test_abs2():
try:
browser = webdriver.Chrome()
link = "http://suninjuly.github.io/registration2.html"
browser.get(link)
# Ваш код, который заполняет обязательные поля
input1 = browser.find_element_by_css_selector(".first[required]")
input1.send_keys("Vladimir")
input2 = browser.find_element_by_css_selector(".second[required]")
input2.send_keys("Lenin")
input3 = browser.find_element_by_css_selector(".third[required]")
input3.send_keys("[email protected]")
# Отправляем заполненную форму
button = browser.find_element_by_css_selector("button.btn")
button.click()
# Проверяем, что смогли зарегистрироваться
# ждем загрузки страницы
time.sleep(1)
# находим элемент, содержащий текст
welcome_text_elt = browser.find_element_by_tag_name("h1")
# записываем в переменную welcome_text текст из элемента welcome_text_elt
welcome_text = welcome_text_elt.text
finally:
# ожидание чтобы визуально оценить результаты прохождения скрипта
time.sleep(3)
# закрываем браузер после всех манипуляций
browser.quit()
# с помощью assert проверяем, что ожидаемый текст совпадает с текстом на странице сайта
assert "Congratulations! You have successfully registered!" == welcome_text, "Should be - Congratulations! You have successfully registered!"
if __name__ == "__main__":
os.system ("pytest " + os.path.basename(__file__) + " --tb=line")
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson1_item6_step8.py
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
link = "http://suninjuly.github.io/find_xpath_form"
value1 ="input"
value2 ="last_name"
value3 ="city"
value4 ="country"
try:
browser = webdriver.Chrome()
#link = "http://suninjuly.github.io/simple_form_find_task.html"
#browser = webdriver.Chrome(executable_path=r"C:\chromedriver.exe") # <- Путь до файла хромдрайвера
browser.get(link)
time.sleep(1)
input1 = browser.find_element_by_tag_name(value1)
input1.send_keys("Ivan")
input2 = browser.find_element_by_name(value2)
input2.send_keys("Petrov")
input3 = browser.find_element_by_class_name(value3)
input3.send_keys("Smolensk")
input4 = browser.find_element_by_id(value4)
input4.send_keys("Russia")
#<button type="submit" class="btn" disabled="disabled">
# Submit</button>
# $x('.//button[text() = "Submit"]')
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
#button = browser.find_element_by_css_selector("button.btn")
button.click()
#find_element_by_css_selector()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(30)
# закрываем браузер после всех манипуляций
browser.close()
time.sleep(2)
browser.quit()
# не забываем оставить пустую строку в конце файла
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson3_item2_step13.py
'''
Возьмите тесты из шага — https://stepik.org/lesson/138920/step/11?unit=196194
Создайте новый файл
Создайте в нем класс с тестами, который должен наследоваться от unittest.TestCase по аналогии с предыдущим шагом
Перепишите в стиле unittest тест для страницы http://suninjuly.github.io/registration1.html
Перепишите в стиле unittest второй тест для страницы http://suninjuly.github.io/registration2.html
Оформите финальные проверки в тестах в стиле unittest, например, используя проверочный метод assertEqual
Запустите получившиеся тесты из файла
Просмотрите отчёт о запуске и найдите последнюю строчку
Отправьте эту строчку в качестве ответа на это задание
Как и прежде загружаем модуль selenium и пользуемся им, как и в задаче - предке;
Создаем класс в названии которого фигурирует "test_class_name";
Наследуем (unittest.TestCase);
Создаем две функции внутри класса, у меня они получились идентичными, за исключением содержимого переменной URL (ссылка на веб страницу);
В функциях из предыдущего шага не используем конструкции try, except, finally и assert, используем только: self.assertEqual('что должно быть', 'что есть', 'что произошло');
Добавляем в код: if __name__ == "__main__": unittest.main()
Тест, очевидно, проваливается на втором линке, ищем одну короткую строку, которая нам об этом говорит.
'''
from selenium import webdriver
import unittest
import time
class TestAbs(unittest.TestCase):
def test_abs1(self):
try:
browser = webdriver.Chrome()
browser.maximize_window()
browser.get("http://suninjuly.github.io/registration1.html")
browser.find_element_by_xpath('.//label[text()=\'First name*\']/following-sibling::input').send_keys("pasha")
browser.find_element_by_xpath('.//label[text()=\'Last name*\']/following-sibling::input').send_keys("zzzz")
browser.find_element_by_xpath('.//label[text()=\'Email*\']/following-sibling::input').send_keys("[email protected]")
browser.find_element_by_xpath(".//button[text()='Submit']").click()
# Проверяем, что смогли зарегистрироваться
# ждем загрузки страницы
time.sleep(1)
# находим элемент, содержащий текст
welcome_text_elt = browser.find_element_by_tag_name("h1")
# записываем в переменную welcome_text текст из элемента welcome_text_elt
welcome_text = welcome_text_elt.text
finally:
# ожидание чтобы визуально оценить результаты прохождения скрипта
time.sleep(3)
# закрываем браузер после всех манипуляций
browser.quit()
# с помощью assert проверяем, что ожидаемый текст совпадает с текстом на странице сайта
self.assertEqual("Congratulations! You have successfully registered!", welcome_text, "Should be - Congratulations! You have successfully registered!")
def test_abs2(self):
try:
browser = webdriver.Chrome()
link = "http://suninjuly.github.io/registration2.html"
browser.get(link)
# Ваш код, который заполняет обязательные поля
input1 = browser.find_element_by_css_selector(".first[required]")
input1.send_keys("Vladimir")
input2 = browser.find_element_by_css_selector(".second[required]")
input2.send_keys("Lenin")
input3 = browser.find_element_by_css_selector(".third[required]")
input3.send_keys("[email protected]")
# Отправляем заполненную форму
button = browser.find_element_by_css_selector("button.btn")
button.click()
# Проверяем, что смогли зарегистрироваться
# ждем загрузки страницы
time.sleep(1)
# находим элемент, содержащий текст
welcome_text_elt = browser.find_element_by_tag_name("h1")
# записываем в переменную welcome_text текст из элемента welcome_text_elt
welcome_text = welcome_text_elt.text
finally:
# ожидание чтобы визуально оценить результаты прохождения скрипта
time.sleep(3)
# закрываем браузер после всех манипуляций
browser.quit()
# с помощью assert проверяем, что ожидаемый текст совпадает с текстом на странице сайта
self.assertEqual("Congratulations! You have successfully registered!", welcome_text, "Should be - Congratulations! You have successfully registered!")
if __name__ == "__main__":
unittest.main()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ for quick search in all files.py
"""
https://coursehunter.net/course/python-razrabotchik
https://coursehunter.net/course/full-stack-delaem-klon-airbnb-s-python-django-tailwind
DOPOLNITELNO https://coursehunter.net/course/python-django-dev-to-deployment
https://coursehunter.net/course/izuchite-python-i-eticheskiy-vzlom-s-nulya
https://coursehunter.net/course/fullstack-flask-sozdayte-prilozhenie-saas-s-pomoshchyu-flask
https://coursehunter.net/course/rest-apis-s-flask-i-python
"""
import os
from os.path import abspath
name_file = os.path.basename(__file__)
len_name = len(name_file)
directory = abspath(__file__)
directory = directory[0:-len_name]
print("*"+directory)
files = os.listdir(directory)
print("files:", files)
py = filter(lambda x: x.endswith('.py'), files)
print(" -"*25)
name_file_result = name_file[0:-3]+'_RESULT.py'
all_texts = ""
for p in py:
if p != name_file_result:
print(p)
f = open(p)
#print(f.read())
all_texts += "\n############ " + p + "\n"
all_texts += f.read()
all_texts += "\n#" + "- "*100
f.close()
#print(all_texts)
f = open(name_file_result, 'w')
f.write(all_texts + '\n')
f.close()
print("OK")
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ methods.py
import math
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
if __name__ == "__main__":
pass
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson3_item2_step8.py
'''
Дана функция test_input_text, которая принимает два значения: expected_result — ожидаемый результат, и actual_result — фактический результат. Обратите внимание, input использовать не нужно!
Функция должна проверить совпадение значений с помощью оператора assert и, в случае несовпадения, предоставить исчерпывающее сообщение об ошибке.
Важно! Формат ошибки должен точно совпадать с приведенным в примере, чтобы его засчитала проверяющая система!
Маленький совет: попробуйте воспользоваться кнопкой "Запустить код" и протестируйте ваш код на разных введенных значениях, проверьте вывод вашей функции на разных парах. Обрабатывать ситуацию с пустым или невалидным вводом не нужно.
Sample Input 1:
8 11
Sample Output 1:
expected 8, got 11
Sample Input 2:
11 11
Sample Output 2:
Sample Input 3:
11 15
Sample Output 3:
expected 11, got 15
'''
def test_input_text(expected_result, actual_result):
# ваша реализация, напишите assert и сообщение об ошибке
assert expected_result == actual_result,\
f"expected {expected_result}, got {actual_result}"
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson2_item3_step6.py
'''
Открыть страницу http://suninjuly.github.io/redirect_accept.html
Нажать на кнопку
Переключиться на новую вкладку
Пройти капчу для робота и получить число-ответ
'''
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import math
from selenium.webdriver.support.ui import Select
import os
link = "http://suninjuly.github.io/redirect_accept.html"
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
# <input type="text" name="firstname" class="form-control"
# placeholder="Enter first name" required="" maxlength="32">
# $("[name*='email']")
# $x('.//button[text() = "Submit"]')
# //input[@id='firstName']
# //input[@type='text']
# 1)Driver.FindElement(By.XPath("//input[@id='firstName']"));
# 2)Driver.FindElement(By.Id("firstName"));
# 3)Driver.FindElement(By.CssSelector("#firstName"));
# //*[text()[contains(.,'firstName')]]
## $x(".//input[@name='email']")
try:
browser = webdriver.Chrome()
browser.get(link)
button = browser.find_element(By.XPATH, './/button[text()]')
button.click()
new_window = browser.window_handles[1]
first_window = browser.window_handles[0]
browser.switch_to.window(new_window)
time.sleep(1)
input3 = browser.find_element(By.XPATH, './/*[@id = "input_value"]')
x = input3.text
y = calc(int(x))
input1 = browser.find_element(By.XPATH, './/*[@id = "answer"]')
input1.send_keys(y)
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
# закрываем браузер после всех манипуляций
#browser.close()
time.sleep(2)
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson2_item2_step8.py
'''
Открыть страницу http://suninjuly.github.io/file_input.html
Заполнить текстовые поля: имя, фамилия, email
Загрузить файл. Файл должен иметь расширение .txt и может быть пустым
Нажать кнопку "Submit"
'''
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import math
from selenium.webdriver.support.ui import Select
import os
link = "http://suninjuly.github.io/file_input.html"
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
# <input type="text" name="firstname" class="form-control"
# placeholder="Enter first name" required="" maxlength="32">
# $("[name*='email']")
# $x('.//button[text() = "Submit"]')
# //input[@id='firstName']
# //input[@type='text']
# 1)Driver.FindElement(By.XPath("//input[@id='firstName']"));
# 2)Driver.FindElement(By.Id("firstName"));
# 3)Driver.FindElement(By.CssSelector("#firstName"));
# //*[text()[contains(.,'firstName')]]
## $x(".//input[@name='email']")
try:
browser = webdriver.Chrome()
browser.get(link)
input1 = browser.find_element(By.XPATH, './/*[@name = "firstname"]')
input1.send_keys("firstname")
input2 = browser.find_element(By.XPATH, './/*[@name = "lastname"]')
input2.send_keys("lastname")
input3 = browser.find_element(By.XPATH, './/*[@name = "email"]')
input3.send_keys("email")
current_dir = os.path.abspath(os.path.dirname(__file__))
file_path = os.path.join(current_dir, 'txt.txt')
element = browser.find_element(By.XPATH, './/*[@name = "file"]')
element.send_keys(file_path)
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
# закрываем браузер после всех манипуляций
#browser.close()
time.sleep(2)
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson3_item2_step9.py
'''
Вам дан шаблон для функции test_substring, которая принимает два значения: full_string и substring.
Функция должна проверить вхождение строки substring в строку full_string с помощью оператора assert и, в случае несовпадения, предоставить исчерпывающее сообщение об ошибке.
Важно! Формат ошибки должен точно совпадать с приведенным в примере, чтобы его засчитала проверяющая система!
Маленький совет: попробуйте воспользоваться кнопкой "Запустить код" и протестируйте ваш код на разных введенных значениях, проверьте вывод вашей функции на разных парах. Обрабатывать ситуацию с пустым или невалидным вводом не нужно.
Sample Input 1:
fulltext some_value
Sample Output 1:
expected 'some_value' to be substring of 'fulltext'
Sample Input 2:
1 1
Sample Output 2:
Sample Input 3:
some_text some
Sample Output 3:
'''
def test_substring(full_string, substring):
# ваша реализация, напишите assert и сообщение об ошибке
assert substring in full_string, f"expected '{substring}' to be substring of '{full_string}'"
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson3_item4_step7_test.py
import os
import pytest
@pytest.fixture(scope="class")
def prepare_faces():
print("^_^", "\n")
yield
print(":3", "\n")
@pytest.fixture()
def very_important_fixture():
print(":) \t very_important_fixture", "\n")
@pytest.fixture(autouse=True)
def print_smiling_faces():
print(":-Р \t print_smiling_faces", "\n")
class TestPrintSmilingFaces():
def test_first_smiling_faces(self, prepare_faces, very_important_fixture):
# какие-то проверки
print("test_first_smiling_faces")
def test_second_smiling_faces(self, prepare_faces):
# какие-то проверки
print("test_second_smiling_faces")
if __name__ == "__main__":
os.system ("pytest " + os.path.basename(__file__) + " -s")
# cd $HOME/selenium_course;python ~/selenium_course/lesson3_item4_step7_test.py
'''
====================================== test session starts ======================================
platform linux -- Python 3.7.9, pytest-5.1.1, py-1.9.0, pluggy-0.13.1
rootdir: /home/kde/selenium_course
collected 2 items
lesson3_item4_step7_test.py ^_^
:-Р
:)
.:-Р
.:3
======================================= 2 passed in 0.02s =======================================
'''
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson2_item1_step6.py
from selenium import webdriver
import time
link = "http://suninjuly.github.io/math.html"
try:
browser = webdriver.Chrome()
browser.get(link)
#проверяем значение атрибута checked у people_radio
people_radio = browser.find_element_by_id("peopleRule")
people_checked = people_radio.get_attribute("checked")
print("value of people radio: ", people_checked)
assert people_checked is not None, "People radio is not selected by default"
#проверяем значение атрибута checked у robots_radio
robots_radio = browser.find_element_by_id("robotsRule")
robots_checked = robots_radio.get_attribute("checked")
print("value of robots_radio: ", robots_checked)
assert robots_checked is None
#проверяем значение атрибута disabled у кнопки Submit
button = browser.find_element_by_css_selector('.btn')
button_disabled = button.get_attribute("disabled")
print("value of button Submit: ", button_disabled)
assert button_disabled is None
#проверяем значение атрибута disabled у кнопки Submit после таймаута
time.sleep(10)
button_disabled = button.get_attribute("disabled")
print("value of button Submit after 10sec: ", button_disabled)
assert button_disabled is not None
finally:
# закрываем браузер после всех манипуляций
browser.quit()
# не забываем оставить пустую строку в конце файла
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ 1_4.py
# 1.4
"""
$x('.//button[text() = "Gold"]')
"""
#1.5
"""
.card-body:nth-child(1) p
{
color:blue;
}
p.text
{
color:blue;
}
.watermelon p.description
{
color:blue;
}
.banana p
{
color:blue;
}
"""
#
"""
"""
#
"""
"""
#
"""
"""
#
"""
"""
#
"""
"""
#
"""
"""
#
"""
"""
#
"""
"""
#
"""
"""
#
"""
"""
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson1_item6_step11b.py
from selenium import webdriver
try:
browser = webdriver.Chrome()
browser.maximize_window()
browser.get("http://suninjuly.github.io/registration1.html")
browser.find_element_by_xpath('.//label[text()=\'First name*\']/following-sibling::input').send_keys("pasha")
browser.find_element_by_xpath('.//label[text()=\'Last name*\']/following-sibling::input').send_keys("zzzz")
browser.find_element_by_xpath('.//label[text()=\'Email*\']/following-sibling::input').send_keys("[email protected]")
browser.find_element_by_xpath(".//button[text()='Submit']").click()
finally:
time.sleep(10)
browser.close()
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson1_item6_step5.py
from selenium import webdriver
import time
import math
link = "http://suninjuly.github.io/find_link_text"
value1 ="input"
value2 ="last_name"
value3 ="city"
value4 ="country"
try:
browser = webdriver.Chrome()
#link = "http://suninjuly.github.io/simple_form_find_task.html"
#browser = webdriver.Chrome(executable_path=r"C:\chromedriver.exe") # <- Путь до файла хромдрайвера
browser.get(link)
# Если хотим найти элемент по полному соответствию текста, то нам подойдет такой код:
link = browser.find_element_by_link_text(str(str(math.ceil(math.pow(math.pi, math.e)*10000))))
link.click()
# А если хотим найти элемент со ссылкой по подстроке, то нужно написать следующий код:
# link = browser.find_element_by_partial_link_text("examples")
# link.click()
time.sleep(1)
input1 = browser.find_element_by_tag_name(value1)
input1.send_keys("Ivan")
input2 = browser.find_element_by_name(value2)
input2.send_keys("Petrov")
input3 = browser.find_element_by_class_name(value3)
input3.send_keys("Smolensk")
input4 = browser.find_element_by_id(value4)
input4.send_keys("Russia")
button = browser.find_element_by_css_selector("button.btn")
button.click()
#find_element_by_css_selector()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(30)
# закрываем браузер после всех манипуляций
browser.close()
time.sleep(2)
browser.quit()
# не забываем оставить пустую строку в конце файла
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson1_item6_step10.py
from selenium import webdriver
import time
try:
link = "http://suninjuly.github.io/registration1.html"
browser = webdriver.Chrome()
browser.get(link)
# Ваш код, который заполняет обязательные поля
#elements = browser.find_elements_by_tag_name("input")
elements = browser.find_elements_by_css_selector('input[required]')
for element in elements:
element.send_keys("Мой ответ")
# Отправляем заполненную форму
button = browser.find_element_by_css_selector("button.btn")
button.click()
# Проверяем, что смогли зарегистрироваться
# ждем загрузки страницы
time.sleep(1)
# находим элемент, содержащий текст
welcome_text_elt = browser.find_element_by_tag_name("h1")
# записываем в переменную welcome_text текст из элемента welcome_text_elt
welcome_text = welcome_text_elt.text
# с помощью assert проверяем, что ожидаемый текст совпадает с текстом на странице сайта
assert "Congratulations! You have successfully registered!" == welcome_text
finally:
# ожидание чтобы визуально оценить результаты прохождения скрипта
time.sleep(10)
browser.close()
# закрываем браузер после всех манипуляций
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson3_item5_step6_test_xfail.py
import pytest
import os
# Пометьте первый тест параметром, который в случае неожиданного прохождения теста,
# помеченного как xfail, отметит в отчете этот тест как упавший.
@pytest.mark.xfail(strict=True) # strict=True
def test_succeed():
assert True
@pytest.mark.xfail
def test_not_succeed():
assert False
@pytest.mark.skip
def test_skipped():
assert False
if __name__ == "__main__":
os.system ("pytest " + os.path.basename(__file__) + " -s")
#cd $HOME/selenium_course;python ~/selenium_course/lesson3_item5_step6_test_xfail.py
#conda deactivate; source $HOME/enviroments/selenium_env/bin/activate; cd $HOME/selenium_course;python ~/selenium_course/lesson3_item5_step6_test_xfail.py
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson3_item5_step7.py
import pytest
@pytest.fixture
def browser():
pass
class TestMainPage():
# номер 1
@pytest.mark.xfail
@pytest.mark.smoke
def test_guest_can_login(self, browser):
print(1)
assert True
# номер 2
@pytest.mark.regression
def test_guest_can_add_book_from_catalog_to_basket(self, browser):
print(2)
assert True
class TestBasket():
# номер 3
@pytest.mark.skip(reason="not implemented yet")
@pytest.mark.smoke
def test_guest_can_go_to_payment_page(self, browser):
print(3)
assert True
# номер 4
@pytest.mark.smoke
def test_guest_can_see_total_price(self, browser):
print(4)
assert True
@pytest.mark.skip
class TestBookPage():
# номер 5
@pytest.mark.smoke
def test_guest_can_add_book_to_basket(self, browser):
print(5)
assert True
# номер 6
@pytest.mark.regression
def test_guest_can_see_book_price(self, browser):
print(6)
assert True
# номер 7
@pytest.mark.beta_users
@pytest.mark.smoke
def test_guest_can_open_gadget_catalogue(browser):
print(7)
assert True
#pytest -v -m "smoke and not beta_users" lesson3_item5_step7.py
#C первого раза. просто смотрите где есть smoke потом нет ли там "beta users", потому что не должно бить, потом смотрите будут ли тести skip или нет. если xfail есть то тест все равно будет исполняться.
# 1 4
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson3_item6_step3.py
homework = '''
Инопланетяне оставляют загадочные сообщения на Stepik в фидбеке задач на правильное решение. Мы смогли локализовать несколько url-адресов задач, где появляются кусочки сообщений. Ваша задача — реализовать автотест со следующим сценарием действий:
открыть страницу
ввести правильный ответ
нажать кнопку "Отправить"
дождаться фидбека о том, что ответ правильный
проверить, что текст в опциональном фидбеке полностью совпадает с "Correct!"
Опциональный фидбек — это текст в черном поле, как показано на скриншоте:
Правильным ответом на задачу в заданных шагах является число:
import time
import math
answer = math.log(int(time.time()))
Используйте маркировку pytest для параметризации и передайте в тест список ссылок в качестве параметров:
https://stepik.org/lesson/236895/step/1
https://stepik.org/lesson/236896/step/1
https://stepik.org/lesson/236897/step/1
https://stepik.org/lesson/236898/step/1
https://stepik.org/lesson/236899/step/1
https://stepik.org/lesson/236903/step/1
https://stepik.org/lesson/236904/step/1
https://stepik.org/lesson/236905/step/1
Используйте осмысленное сообщение об ошибке в проверке текста, а также настройте нужные ожидания, чтобы тесты работали стабильно.
В упавших тестах найдите кусочки послания. Тест должен падать, если текст в опциональном фидбеке не совпадает со строкой "Correct!" Соберите кусочки текста в одно предложение и отправьте в качестве ответа на это задание.
Важно! Чтобы пройти это задание, дополнительно убедитесь в том, что у вас установлено правильное локальное время (https://time.is/ru/). Ответ для каждой задачи нужно пересчитывать отдельно, иначе они устаревают.
'''
import math
import time
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
correct_answer_text = "Correct!"
# Создаем кортеж со списком url
url_check = ("https://stepik.org/lesson/236895/step/1",
"https://stepik.org/lesson/236896/step/1",
"https://stepik.org/lesson/236897/step/1",
"https://stepik.org/lesson/236898/step/1",
"https://stepik.org/lesson/236899/step/1",
"https://stepik.org/lesson/236903/step/1",
"https://stepik.org/lesson/236904/step/1",
"https://stepik.org/lesson/236905/step/1")
@pytest.fixture(scope="function") # Создаем фикустуру для запуска браузера
def browser():
print("\n Start browser...")
browser = webdriver.Chrome()
yield browser
print("\n Quit browser..")
browser.quit()
@pytest.mark.parametrize('url', url_check)
def test_hidden_message(browser, url):
link = f'{url}'
browser.get(link)
# Ждем появления текстового поля на странице в течении 10 сек
# Находим поле ввода ответа на странице, и вставляем туда ответ math.log(int(time.time())
WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "textarea.textarea"))
)
text_field = browser.find_element_by_css_selector("textarea.textarea")
text_field.send_keys(str(math.log(int(time.time())))) # Хорошо читается :/
# Находим кнопку "Submit"
# Нажимаем на нее
submit_btn = browser.find_element_by_css_selector("button.submit-submission")
submit_btn.click()
# Ждем появления элемента "дополнительного фидбека" в течении 5 сек
# Находим параметр text у найденого элемента
# Сверяем text с искомым нами (correct_answer_text)
WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "pre.smart-hints__hint"))
)
find_answer_text = browser.find_element_by_css_selector("pre.smart-hints__hint")
answer_text = find_answer_text.text
try:
assert answer_text == correct_answer_text, 'Text is not: "Correct!"'
except Exception:
raise AssertionError('Error! Text does not match')
finally:
print("----> " + answer_text + " <----")
# Смотриться лучше, но без assertError не падает, браузер открыт всю сессию
# #from selenium import webdriver
# import pytest
# import time
# import math
#
# final = ''
#
#
# @pytest.fixture(scope="session")
# def browser():
# br = webdriver.Chrome()
# yield br
# br.quit()
# print(final) # напечатать ответ про Сов в конце всей сессии
#
#
# @pytest.mark.parametrize('lesson', ['236895', '236896', '236897', '236898', '236899', '236903', '236904', '236905'])
# def test_find_hidden_text(browser, lesson):
# global final
# link = f'https://stepik.org/lesson/{lesson}/step/1'
# browser.implicitly_wait(10)
# browser.get(link)
# answer = math.log(int(time.time()))
# browser.find_element_by_css_selector('textarea').send_keys(str(answer))
# browser.find_element_by_css_selector('.submit-submission ').click()
# check_text = browser.find_element_by_css_selector('.smart-hints__hint').text
# try:
# assert 'Correct!' == check_text
# except AssertionError:
# final += check_text # собираем ответ про Сов с каждой ошибкой
#pytest -v lesson3_item6_step3.py
answer = '''
E AssertionError: Text is not: "Correct!"
E assert 'The owls ' == 'Correct!'
E - The owls
E + Correct!
E AssertionError: Error! Text does not match
E AssertionError: Text is not: "Correct!"
E assert 'are not ' == 'Correct!'
E - are not
E + Correct!
E AssertionError: Error! Text does not match
E AssertionError: Text is not: "Correct!"
E assert 'what they seem! OvO' == 'Correct!'
E - what they seem! OvO
E + Correct!
E AssertionError: Error! Text does not match
The owls are not what they seem! OvO
'''
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson1_item6_step7.py
from selenium import webdriver
import time
try:
browser = webdriver.Chrome()
browser.get("http://suninjuly.github.io/huge_form.html")
time.sleep(5)
# alert = browser.switch_to_alert()
# print (alert.text)
elements = browser.find_elements_by_tag_name("input")
for element in elements:
element.send_keys("Мой ответ")
button = browser.find_element_by_css_selector("button.btn")
button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
browser.close()
# закрываем браузер после всех манипуляций
browser.quit()
# не забываем оставить пустую строку в конце файла
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ os_mint.py
#cd $HOME/selenium_course; python os_mint.py
# https://andreyex.ru/yazyk-programmirovaniya-python/vypolnenie-komand-obolochki-s-python/
import os
import time
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")
myCmd = 'sudo ls -la'
os.system (myCmd)
#myCmd = "ping -c 1 8.8.8.8 &> /dev/null && echo success || echo fail & sudo service network-manager restart"
myCmd = "ping -c 1 8.8.8.8 &> /dev/null && echo success || sudo service network-manager restart"
myCmd = "ping -c 1 8.8.8.8 > txt.txt"
#myCmd = "ping -c 1 8.8.8.8"
i = 0
errors = 0
while True:
time.sleep(2)
i += 1
#print(i)
#print(f"{bcolors.WARNING}==={i}==={bcolors.ENDC}")
print("i: "+ str(i))
os.system(myCmd)
f = open("txt.txt")
read = f.read()
#print(f.read())
f.close()
if not "time=" in read:
os.system("sudo service network-manager restart")
#https://stackoverflow.com/questions/48639609/sudo-pass-automatic-password-in-python
#https://askubuntu.com/questions/155791/how-do-i-sudo-a-command-in-a-script-without-being-asked-for-a-password
#print(f"{bcolors.FAIL}Try reload{bcolors.ENDC}")
print("reload")
errors += 1
else:
#print(f"{bcolors.OKGREEN}OK. Continue... {errors}{bcolors.ENDC}")
print("errors: " + str(errors))
#myCmd = os.popen(myCmd).read()
#print(myCmd)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ pytest_template_test.py
'''
https://coderlessons.com/tutorials/python-technologies/uznaite-pytest/pytest-kratkoe-rukovodstvo
import unittest
class TestUtilDate(unittest.TestCase):
def setUp(self):
#init_something()
pass
def tearDown(self):
#teardown_something()
pass
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
def test_failed_upper(self):
self.assertEqual('foo'.upper(), 'FOo')
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestUtilDate)
unittest.TextTestRunner(verbosity=2).run(suite)
'''
# То же самое в PyTest:
import os
import pytest
def setup_module(module):
#init_something()
pass
def teardown_module(module):
#teardown_something()
pass
def test_upper():
assert 'foo'.upper() == 'FOO'
def test_isupper():
assert 'FOO'.isupper()
def test_failed_upper():
assert 'foo'.upper() == 'FOo'
if __name__ == "__main__":
os.system ("pytest " + os.path.basename(__file__) + " --tb=line ")
#os.system ("pytest -v " + os.path.basename(__file__) + " --tb=line ")
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson1_item6_step4.py
from selenium import webdriver
import time
link = "http://suninjuly.github.io/simple_form_find_task.html"
value1 ="input"
value2 ="last_name"
value3 ="city"
value4 ="country"
try:
browser = webdriver.Chrome()
#link = "http://suninjuly.github.io/simple_form_find_task.html"
#browser = webdriver.Chrome(executable_path=r"C:\chromedriver.exe") # <- Путь до файла хромдрайвера
browser.get(link)
input1 = browser.find_element_by_tag_name(value1)
input1.send_keys("Ivan")
input2 = browser.find_element_by_name(value2)
input2.send_keys("Petrov")
input3 = browser.find_element_by_class_name(value3)
input3.send_keys("Smolensk")
input4 = browser.find_element_by_id(value4)
input4.send_keys("Russia")
button = browser.find_element_by_css_selector("button.btn")
button.click()
#find_element_by_css_selector()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(30)
# закрываем браузер после всех манипуляций
browser.close()
time.sleep(2)
browser.quit()
# не забываем оставить пустую строку в конце файла
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson2_item1_step5.py
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
link = "http://suninjuly.github.io/math.html"
import math
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
try:
browser = webdriver.Chrome()
#link = "http://suninjuly.github.io/simple_form_find_task.html"
#browser = webdriver.Chrome(executable_path=r"C:\chromedriver.exe") # <- Путь до файла хромдрайвера
browser.get(link)
time.sleep(1)
#$x('//span[contains(text(),"What")]/text()')
input3 = browser.find_element(By.XPATH, './/*[@id = "input_value"]')
x = input3.text
y = calc(int(x))
input1 = browser.find_element(By.XPATH, './/*[@id = "answer"]')
input1.send_keys(y)
option1 = browser.find_element_by_css_selector("[for='robotCheckbox']")
option1.click()
option2 = browser.find_element_by_css_selector("[for='robotsRule']")
option2.click()
#<button type="submit" class="btn" disabled="disabled">
# Submit</button>
# $x('.//button[text() = "Submit"]')
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
#button = browser.find_element_by_css_selector("button.btn")
button.click()
#find_element_by_css_selector()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
# закрываем браузер после всех манипуляций
#browser.close()
time.sleep(2)
browser.quit()
# не забываем оставить пустую строку в конце файла
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ get_method.py
import time
# webdriver это и есть набор команд для управления браузером
from selenium import webdriver
# инициализируем драйвер браузера. После этой команды вы должны увидеть новое открытое окно браузера
driver = webdriver.Chrome()
# команда time.sleep устанавливает паузу в 5 секунд, чтобы мы успели увидеть, что происходит в браузере
time.sleep(15)
# Метод get сообщает браузеру, что нужно открыть сайт по указанной ссылке
driver.get("https://stepik.org/lesson/25969/step/12")
time.sleep(15)
# Метод find_element_by_css_selector позволяет найти нужный элемент на сайте, указав путь к нему. Способы поиска элементов мы обсудим позже
# Ищем поле для ввода текста
textarea = driver.find_element_by_css_selector(".textarea")
# Напишем текст ответа в найденное поле
textarea.send_keys("get()")
time.sleep(15)
# Найдем кнопку, которая отправляет введенное решение
submit_button = driver.find_element_by_css_selector(".submit-submission")
# Скажем драйверу, что нужно нажать на кнопку. После этой команды мы должны увидеть сообщение о правильном ответе
submit_button.click()
time.sleep(15)
# После выполнения всех действий мы не должны забыть закрыть окно браузера
driver.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson1_item6_step11c.py
from selenium import webdriver
import time
try:
link = "http://suninjuly.github.io/registration2.html"
browser = webdriver.Chrome()
browser.get(link)
name = browser.find_element_by_css_selector("body > div > form > div.first_block > div.form-group.first_class > input")
name.send_keys("Ivan")
sname = browser.find_element_by_css_selector("body > div > form > div.first_block > div.form-group.second_class > input")
sname.send_keys("Petrov")
email = browser.find_element_by_css_selector("body > div > form > div.first_block > div.form-group.third_class > input")
email.send_keys("[email protected]")
button = browser.find_element_by_css_selector("button.btn")
button.click()
time.sleep(1)
welcome_text_elt = browser.find_element_by_tag_name("h1")
welcome_text = welcome_text_elt.text
assert "Congratulations! You have successfully registered!" == welcome_text
finally:
# ожидание чтобы визуально оценить результаты прохождения скрипта
time.sleep(10)
# закрываем браузер после всех манипуляций
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson2_item3_step4.py
'''
Открыть страницу http://suninjuly.github.io/alert_accept.html
Нажать на кнопку
Принять confirm
На новой странице решить капчу для роботов, чтобы получить число с ответом
'''
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import math
from selenium.webdriver.support.ui import Select
import os
link = "http://suninjuly.github.io/alert_accept.html"
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
# <input type="text" name="firstname" class="form-control"
# placeholder="Enter first name" required="" maxlength="32">
# $("[name*='email']")
# $x('.//button[text() = "Submit"]')
# //input[@id='firstName']
# //input[@type='text']
# 1)Driver.FindElement(By.XPath("//input[@id='firstName']"));
# 2)Driver.FindElement(By.Id("firstName"));
# 3)Driver.FindElement(By.CssSelector("#firstName"));
# //*[text()[contains(.,'firstName')]]
## $x(".//input[@name='email']")
try:
browser = webdriver.Chrome()
browser.get(link)
button = browser.find_element(By.XPATH, './/button[text()]')
button.click()
confirm = browser.switch_to.alert
confirm.accept()
time.sleep(1)
input3 = browser.find_element(By.XPATH, './/*[@id = "input_value"]')
x = input3.text
y = calc(int(x))
input1 = browser.find_element(By.XPATH, './/*[@id = "answer"]')
input1.send_keys(y)
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
# закрываем браузер после всех манипуляций
#browser.close()
time.sleep(2)
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
############ lesson2_item2_step3.py
'''
Открыть страницу http://suninjuly.github.io/selects1.html
Посчитать сумму заданных чисел
Выбрать в выпадающем списке значение равное расчитанной сумме
Нажать кнопку "Submit"
'''
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import math
from selenium.webdriver.support.ui import Select
link = "http://suninjuly.github.io/selects1.html"
try:
browser = webdriver.Chrome()
browser.get(link)
input1 = browser.find_element(By.XPATH, './/*[@id = "num1"]')
input2 = browser.find_element(By.XPATH, './/*[@id = "num2"]')
print(input1.text)
result = str( int(input1.text) + int(input2.text) )
print(result)
input3 = browser.find_element(By.XPATH, './/*[@id = "dropdown"]')
select = Select( input3 )
select.select_by_value(result)
button = browser.find_element(By.XPATH, './/button[text() = "Submit"]')
button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(10)
# закрываем браузер после всех манипуляций
#browser.close()
time.sleep(2)
browser.quit()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
import random
from enum import IntEnum
class Action(IntEnum):
Rock = 0
Paper = 1
Scissors = 2
def user_pick():
choices = [f'{action.name}[{action.value}]' for action in Action]
choices_str = ', '.join(choices)
selection = int(input(f'enter a choice {choices_str}):'))
action = Action(selection)
return action
def computer_pick():
selection = random.randint(0, len(Action) - 1)
action = Action(selection)
return action
def play_game(user_selection, computer_selection):
if user_selection == computer_selection:
print(f'both players selected {user_selection.name}')
elif user_selection == Action.Rock:
if computer_selection == Action.Scissors:
print('rock smashes scissors! You win!')
else:
print('Paper covers rock! You lose.')
elif user_selection == Action.Paper:
if computer_selection == Action.Rock:
print('Paper covers rock!, you win!')
else:
print('Scissors cuts paper! you lose.')
elif user_selection == Action.Scissors:
if computer_selection == Action.Paper:
print('Scissors cuts paper! you win!')
else:
print('Rock smashes scissors. you lose.')
while True:
try:
user_selection = user_pick()
except ValueError as e:
select_range = f'[0, {len(Action) - 1}]'
print(f'range out of bounds, 0 - {select_range}')
continue
computer_selection = computer_pick()
play_again(user_selection, computer_selection)
play_again = input('Play again? (y/n): ')
if play_again.lower() != 'y':
break
|
# Binary Search algorithm using recursion
# Binary Search function that return the position of the element to find
# Takes the array, element to find, l is set to first element and h is set to last element
def binary_search(arr, ele, l, h):
if h - l < 0:
return None
mid = (h + l) // 2
if arr[mid] == ele:
return mid
if ele < arr[mid]:
return binary_search(arr, ele, l, mid - 1)
if ele > arr[mid]:
return binary_search(arr, ele, mid + 1, h)
arr = [1, 2, 3, 5, 7, 9, 12, 13, 15]
pos = binary_search(arr, 13, 0, len(arr) - 1)
print(pos)
|
#! /bin/env python3
''' Class that represents a bit mask.
It has methods representing all
the bitwise operations plus some
additional features. The methods
return a new BitMask object or
a boolean result. See the bits
module for more on the operations
provided.
'''
# For testing API, "BitMask" API can be "see".
__all__ = ['BitMask']
class BitMask(int):
def AND(self, bm):
return BitMask(self & bm)
def OR(self, bm):
return BitMask(self | bm)
def XOR(self, bm):
return BitMask(self ^ bm)
def NOT(self):
return BitMask(~self)
def shift_left(self, num):
return BitMask(self << num)
def shift_right(self, num):
return BitMask(self >> num)
def bit(self, num):
mask = 1 << num
return bool(self & mask)
def set_bit(self, num):
mask = 1 << num
return BitMask(self | mask)
def zero_bit(self, num):
mask = ~(1 << num)
return BitMask(self & mask)
def list_bits(self, start=0, end=None):
if end:
end = end if end < 0 else end + 2
return [int(c) for c in bin(self)[start + 2:end]]
|
'''
Created on Feb 23, 2016
@author: dj
'''
class Circle1(object):
def __init__(self, radius):
self.__radius = radius
def set_radius(self, newValue):
if newValue >= 0:
self.__radius = newValue
else:
raise ValueError("Value must be positive")
def area(self):
return 3.14159 * (self.__radius ** 2)
class Circle2(object):
def __init__(self, radius):
self.__radius = radius
def __set_radius(self, new_value):
if new_value >= 0:
self.__radius = new_value
else:
raise ValueError("Value must be positive")
def __get_radius(self):
return self.__radius
radius = property(None, __set_radius)
radius2 = property(__get_radius, __set_radius)
@property
def area(self):
return 3.14159 * (self.__radius ** 2)
class Circle3(object):
def __init__(self, radius):
self.__radius = radius
@property
def radius(self):
return self.__radius
# Must "def radius(self)" together with "@radius.setter" in pair.
@radius.setter
def radius(self, new_value):
self.__radius = new_value
@property
def area(self):
return 3.14159 * (self.__radius ** 2)
def main():
c1 = Circle1(42)
print("c1.area() =", c1.area())
# print(c1.__radius) # Cannot get "__" value.
print("c1._Circle1__radius = ", c1._Circle1__radius)
print("-" * 40)
c2 = Circle2(42)
print("c2.area =", c2.area)
# print(c2.radius)
print("-" * 40)
c2.radius = 12
print("c2.radius2 =", c2.radius2)
print("c2.area =", c2.area)
print("-" * 40)
c3 = Circle3(0)
c3.radius = 24
print("c3.radius3 =", c3.radius)
print("c3.area =", c3.area)
if __name__ == '__main__':
main()
|
'''
Created on Feb 22, 2016
@author: dj
'''
def fibonacci():
numbers = []
while True:
if len(numbers) < 2:
numbers.append(1)
else:
numbers.append(sum(numbers))
numbers.pop(0)
yield numbers[-1]
def main():
print("-" * 40)
for n in fibonacci():
if n < 10000:
print(n)
else:
break
print("-" * 40)
fib = fibonacci()
print("fib =", fib)
print("next(fib) =", next(fib))
print("next(fib) =", next(fib))
print("next(fib) =", next(fib))
print("-" * 40)
# fib2 is a new copy of fibonacci.
fib2 = fibonacci()
print("fib2 =", fib2)
print("next(fib2) =", next(fib2))
print("next(fib2) =", next(fib2))
print("next(fib2) =", next(fib2))
print("-" * 40)
# Normally, a generator's __iter__ return self.
# fib3 is same copy as fib.
fib3 = iter(fib)
print("fib3 =", fib3)
print("next(fib3) =", next(fib3))
print("next(fib3) =", next(fib3))
print("-" * 40)
if __name__ == '__main__':
main()
|
'''
Created on Apr 1, 2016
@author: dj
'''
from collections import namedtuple
print("-" * 40)
Person = namedtuple("Person", "name age gender")
tom = Person("Tom", 10, "M")
print("Tom is", tom)
jerry = Person(gender="M", name="Jerry", age=8)
print("Jerry is", jerry)
mary_info = {"name": "Mary", "age": 15, "gender": "F"}
mary = Person(**mary_info)
print("Mary is", mary)
print("-" * 40)
tom2 = tom._replace(age=11)
print("Now, Tom is", tom2)
print("-" * 40)
Person2 = namedtuple("Person2", ["name", "age", "gender"])
john = Person2("John", 20, "M")
print("John is", john)
print("John's age is", john.age)
print("John's gender is", john.gender)
if __name__ == '__main__':
pass
|
'''
Created on Apr 4, 2016
@author: dj
'''
import pickle
class Person(object):
name = ""
age = 0
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.__class__.__name__ + ":{name}, {age}".format(**vars(self))
def main():
personA = Person("Tom", 12)
print("personA =", personA)
print("-" * 40)
serialized = pickle.dumps(personA)
print("serialized =", serialized)
print("-" * 40)
personB = pickle.loads(serialized)
print("personB =", personB)
if __name__ == '__main__':
main()
|
n=input()
l=[]
for i in range(n):
t=input()
l.append(t)
l.sort()
for i in l:
print i
|
class Solution:
"""
@param words: a list of string
@return: a boolean
"""
def validWordSquare(self, words):
# Write your code here
N = len(words)
if N != len(words[0]):
return False
for i in range(N):
for j in range(i + 1, N):
if words[i][j] != words[j][i]:
return False
return True
|
ans=0
for i in range(1,1000):
if (i%3==0 or i%5==0):
ans+=i
print(ans)
|
def gcd(x,y):
return y if (x%y==0) else gcd(y,x%y)
def lcm(x,y):
return x//gcd(x,y)*y
ans=1
for i in range(1,21):
ans=lcm(ans,i)
print(ans)
|
sym = input()
flag_1 = 0
flag_2 = 0
#for i in range(ord('A'), ord('Z') + 1):
if ord(sym) == ord('A') or ord(sym) == ord('Z') or ord(sym) > ord('A') and ord(sym) < ord('Z'):
flag_1 += 1
#for a in range(ord('a'), ord('z') + 1):
if ord(sym) == ord('a') or ord(sym) == ord('z') or ord(sym) > ord('a') and ord(sym) < ord('z'):
flag_2 += 1
if flag_1 > 0:
print(sym.lower())
elif flag_2 > 0:
print(sym.upper())
else:
print(sym)
|
num = int(input())
total = 0
counter = 0
while num != 0:
total += num
counter += 1
num = int(input())
total = total / counter
print(total)
|
n = int(input())
counter = 0
for i in range(1, n + 1):
num = i % 10
if num == 5:
counter += 1
print(counter)
|
import random
print('Hello, you came to play the game "Guess the number"')
print('Enter the number to which you would like to guess :) :', end=' ')
n = int(input())
def is_valid(user_input):
global n
if user_input.isdigit():
user_number = int(user_input)
if user_number >= 1 and user_number <= n:
return True
else:
return False
else:
return False
secret_num = random.randint(1, n)
counter = 0
while True:
print('Enter the number:', end=' ')
user_input = input()
if not is_valid(user_input):
continue
user_number = int(user_input)
counter += 1
if secret_num > user_number:
print('The guessed number is greater than the entered number, try again:')
elif secret_num < user_number:
print('The guessed number is less than the entered number, try again:')
if secret_num == user_number:
print('Victory!')
print('You ve got it over with', counter, 'attempts!')
user = int(input('One more time ? if yes then send 1, if not then 0: '))
if user == 1:
print('Enter the number to which you would like to guess :) :', end=' ')
n = int(input())
counter = 0
secret_num = random.randint(1, n)
continue
else:
print('Goodbye! Waiting for you again!')
break
|
a = int(input())
counter = 0
while a != 0:
last_digit = a % 10
if last_digit == 5:
counter += 1
a = a // 10
print(counter)
|
print('Введите текст:')
text = input()
print('Есть ли в этом тексте упоминание о "Glo Academy"?')
if 'Glo Academy' in text:
print('YES')
else:
print('NO')
|
num = int(input())
list = []
for i in range(num):
string = input()
#s = string.lower()
list.append(string)
print(list)
query = input()
for a in range(len(list)):
if list[a].lower().count(query):
print(list[a])
#print(list[a])
|
#!/usr/local/bin/python
import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish;
print "' When finished"
print '7'
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("n")
file.close()
file_name = raw_input("Enter filename: ")
|
n=int(input("Enter number: "))
x=21-n
if n<=21:
print(x," is the absolute diff")
else:
x*=(-2)
print(x," is the absolute diff")
|
import sqlite3 as db
conn = db.connect('test.db')
cursor = conn.cursor()
cursor.execute("drop table if exists temps")
cursor.execute("create table temps(date text, temp int)")
cursor.execute("insert into temps values('09/01/2015', 35)")
cursor.execute("insert into temps values('09/02/2015', 42)")
cursor.execute("insert into temps values('09/03/2015', 38)")
cursor.execute("insert into temps values('09/04/2015', 41)")
cursor.execute("insert into temps values('09/05/2015', 40)")
cursor.execute("insert into temps values('09/06/2015', 28)")
cursor.execute("insert into temps values('09/07/2015', 45)")
conn.commit()
conn.row_factory = db.Row
cursor.execute("select * from temps")
rows = cursor.fetchall()
for row in rows:
print("%s %s" % (row[0], row[1]))
cursor.execute("select avg(temp) from temps")
row = cursor.fetchone()
print("The average temperature for the week was %s" % row[0])
cursor.execute("delete from temps where temp = 40")
cursor.execute("select * from temps")
rows = cursor.fetchall()
for row in rows:
print("%s %s" % (row[0], row[1]))
conn.close()
|
import os
os.system('cls')
beatles = ['John', 'Paul', 'George', 'Ringo']
print(beatles)
print(len(beatles))
print(beatles[0])
print(beatles[1:])
print(beatles[0:2])
print(beatles[2:4])
#print in sorted order
print(sorted(beatles))
#permanently sort list
beatles.sort()
print(beatles)
#permanently reverse list
beatles.reverse()
print(beatles)
#add to the list
beatles.append('Pete')
print(beatles)
#remove from list, the last one
beatles.pop()
print(beatles)
#find index item in list
beatles.append('Pete')
print(beatles)
idx = beatles.index('Pete')
print(idx)
#Delete by index
del beatles[idx]
print(beatles)
|
class Node:
def __init__(self, ID, connections=None):
"""
:param ID: This node's ID
:param connections: A list of edges that connect this node to its neighbors
:param community: The community that this node is a part of
"""
self.ID = ID
self.community = None
if connections is None:
self.connections = []
self.totalEdgeWeights = 0
def getID(self):
return self.ID
def getConnections(self):
return self.connections
def addConnection(self, newConnection):
"""
Adds an arc to the list of connections
:param newConnection: Arc to be added
"""
if newConnection not in self.connections:
self.connections.append(newConnection)
def getCommunity(self):
return self.community
def setCommunity(self, newCommunity):
self.community = newCommunity
def getDegree(self):
"""
Computes the degree of the node
:return: Degree of the node
"""
return len(self.connections)
def getNeighborCommunities(self):
list = []
for edge in self.getConnections():
otherNode = edge.getOtherNode(self)
list.append(otherNode.getCommunity())
return list
def computeSumEdgeWeights(self):
"""
Computes the weight of all edges this node is a part of
"""
for edge in self.connections:
self.totalEdgeWeights += edge.getWeight()
def getSumEdgeWeights(self):
"""
:return: The weight of all edges this node is a part of
"""
return self.totalEdgeWeights
# def __str__(self):
# return str(self.getID())
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.getID() == other.getID()
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.getID() < other.getID()
|
import sys
def prompt(text: str):
print(text)
def prompt_input(prompt: str, default: str = None):
if default is not None:
prompt += f' [{default}]'
prompt += ': '
res = input(prompt)
if res == '':
res = default
return res
def error(prompt):
print(prompt, file=sys.stderr)
def select(prompt: str, options):
print(prompt)
for i, option in enumerate(options):
print(f'[{i}] {option}')
while True:
try:
i = int(input(f'[0-{len(options) - 1}]: '))
if i < 0 or i >= len(options):
raise ValueError()
return i
except ValueError:
error(f'Please input an integer between 0 and {len(options) - 1}.')
continue
|
#Shriram Rangarajan
#MISM BIDA - Pyhton capstone
#Activity 2
#In this activity we strip of all html tags and display only the text content in the website
import urllib.request
from bs4 import BeautifulSoup
web_url = "http://www.opera.com/docs/changelogs/unified/2600/"
request_content = urllib.request.urlopen(web_url)
#store in soup object
soup = BeautifulSoup(request_content.read(),"lxml")
for content in soup(["script", "style"]):
content.extract()
# get the text content
content_text = soup.get_text()
#Splitting content into individual lines for removing trailing spaces
line_text = (line.strip() for line in content_text.splitlines())
#Merging all line content agian into one single text
parts = (phrase.strip() for line in line_text for phrase in line.split(" "))
# display in next lines dropping spaces
content_text = '\n'.join(parts for parts in parts if parts)
print(content_text)
|
# Input dari user
# data yg dimasukkan pasti string
data = input("Masukkan data: ")
print("data =", data, ",type =", type(data))
# jika ingin mengambil data int dan float, maka
angka = int(input("Masukkan data: "))
angka = float(input("Masukkan data: "))
print("data =", angka, ",type =", type(angka))
# jika mengambil data boolean, maka
biner = bool(int(input("Masukkan data boolean: ")))
print("data =", biner, ",type: ",type(biner))
|
#!/usr/bin/python
import sys
from random import shuffle, seed
from itertools import product
class Card:
FACES = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}
SUITS = {'Hearts': 1, 'Diamonds': 2, 'Spades': 3, 'Clubs': 4}
COLORS = {'Hearts': 0, 'Diamonds': 0, 'Spades': 1, 'Clubs': 1}
def __init__(self, rank, suit):
self.suit = suit
self.rank = rank
self.suit_rank = self.SUITS[suit]
self.sort_rank = self.rank
if rank == 5:
if self.suit_rank == 1 or self.suit_rank == 3:
self.sort_rank = 100
else:
self.sort_rank = 0
def __str__(self):
value = self.FACES.get(self.rank, self.rank)
return "{0} of {1}".format(value, self.suit)
def __repr__(self):
return str(self)
def check_trump(self, trump_suit):
if self.rank != 5:
if self.suit == trump_suit:
return True
else:
return False
else:
if self.COLORS[self.suit] == self.COLORS[trump_suit]:
return True
else:
return False
class Deck:
def __init__(self):
ranks = range(2, 15)
suits = 'Spades Diamonds Clubs Hearts'.split()
self.cards = [Card(r, s) for s, r in product(suits, ranks)]
def __str__(self):
s = ''
for i in range(len(self.cards)):
s = s + ' ' * i + str(self.cards[i]) + '\n'
return s
def __repr__(self):
pass
def shuffle(self):
shuffle(self.cards)
def deal(self, hand, num_cards=1):
for i in range(num_cards):
hand.add(self.cards.pop())
class Hand:
def __init__(self):
self.cards = []
def clear_hand(self):
self.cards = []
def discard(self, trump_suit):
self.cards = [x for x in self.cards if x.check_trump(trump_suit)]
def sort_hand(self):
self.cards = sorted(
self.cards, key=lambda x: (
x.suit_rank, x.sort_rank))
def play(self, card):
return self.cards.pop(card - 1)
def add(self, card):
self.cards.append(card)
def __str__(self):
s = ''
for i in range(len(self.cards)):
s = s + ' ' + str(i + 1) + ':' + ' ' * (i + 1) + \
str(self.cards[i]) + '\n'
return s
def __repr__(self):
return str(self)
class Pedro_game:
def __init__(self, players):
self.players = players
self.trump_suit = None
def deal_round(self, first_bidder):
self.deck = Deck()
self.deck.shuffle()
order = [i for i in range(first_bidder, 4)] + \
[i for i in range(first_bidder)]
for player in self.players:
player.clear_hand()
for i in range(3):
for j in order:
self.deck.deal(self.players[j], 3)
for i in order:
self.players[i].sort_hand()
def bidding(self, first_bidder):
current_bid = 5
winning_bidder = -1
order = [i for i in range(first_bidder, 4)] + \
[i for i in range(first_bidder)]
for i, j in enumerate(order):
print self.players[j]
if current_bid < 14:
bid = int(raw_input('Bid?\n'))
if bid > current_bid:
current_bid = bid
winning_bidder = j
else:
bid = int(raw_input('Bid?\n'))
if bid == 14 and i == 3:
current_bid = bid
winning_bidder = j
print current_bid
print winning_bidder
self.winning_bidder = winning_bidder
print self.players[winning_bidder]
self.trump_suit = raw_input('Trump suit?\n')
def second_deal(self, first_bidder):
order = [i for i in range(first_bidder, 4)] + \
[i for i in range(first_bidder)]
for i, j in enumerate(order):
self.players[j].discard(self.trump_suit)
take = 6 - len(self.players[j].cards)
if take > 0:
self.deck.deal(self.players[j], take)
self.players[j].sort_hand()
def play_trick(self, lead):
trick = Trick(self.trump_suit)
order = [i for i in range(lead, 4)] + [i for i in range(lead)]
for i, j in enumerate(order):
print self.players[j]
card_number = int(raw_input('Play Card?\n'))
card = self.players[j].play(card_number)
trick.add(card)
print trick
class Trick:
def __init__(self, trump_suit, lead_card):
self.cards = [lead_card]
self.trump_suit = trump_suit
def add(self, card):
self.cards.append(card)
def __str__(self):
s = ''
for i in range(len(self.cards)):
s = s + ' ' + str(i + 1) + ':' + ' ' * (i + 1) + \
str(self.cards[i]) + '\n'
return s
def __repr__(self):
return str(self)
class Pedro_Player(object):
def __init__(self, name):
self.name = name
self.hand = Hand()
def bid(self, min_bid):
if min_bid > 14:
return False
else:
if min_bid > 5:
ask = 'Current Bid: ' + min_bid - 1 + '\n'
else:
ask = 'Minimum Bid: 6\n'
ask += ' ' + self.name + ': Bid?\n'
invalid_bid = True
while invalid_bid:
try:
bid = int(raw_input(ask))
if bid > min_bid and bid < 14:
return bid
else:
msg = 'Must be greater than ' + str(min_bid)
msg += ' and less than 14'
print msg
except ValueError:
print 'Please insert integer'
def discard(self, trump):
pass
def play_card(self, card):
pass
class Dealer(Pedro_Player):
def __init__(self, pedro_player):
"""
Dealer classes intialized
by a Pedro_Player instance
"""
self.name = pedro_player.name
self.hand = pedro_player.hand
def bid(self, current_bid):
return bid
jacob = Pedro_Player('Jacob')
jacob.bid(5)
sys.exit()
# to do dealer rotation
players = ['a', 'b', 'c', 'd']
print players
dealer = players.pop()
players.insert(0, dealer)
print players
seed(1)
# initialize the players
# Jacob=Hand('Jacob')
# Brigette=Hand('Brigette')
# David=Hand('David')
# Richard=Hand('Richard')
#
# players=[Jacob,Brigette,David,Richard]
# game=Pedro_game(players)
# game.deal_round(0)
# game.bidding(0)
# game.second_deal(0)
# game.play_trick(game.winning_bidder)
#
|
a=float(input("enter the temp in celsius:"))
b=a+273.15
print("temperature in kelvin ",b)
|
"""Модуль тестирования"""
import unittest
from unittest.mock import patch
from game import Game
import core_classes
import algorithms
import copy
import json
import os
class TestAlgorithms(unittest.TestCase):
"""Класс тестирует алгоритмы, находящиеся в модуле algorithms"""
def test_line(self):
"""Метод содержит тестовые случаи и запускает теситрование"""
test_cases = [[(1, 1), (11, 2)], [(0, 0), (1, 3)], [(1, 8), (2, 10)],
[(35, 0), (37, 3)], [(1, 1), (3, 0)],
[(2, 4), (0, 6)], [(11, 6), (3, 10)], [(11, 4), (10, 9)],
[(11, 11), (3, 5)],
[(10, 1), (8, 6)], [(10, 1), (3, 1)], [(11, 5), (13, 5)],
[(3, 11), (3, 5)],
[(3, 7), (3, 10)], [(3, 10), (3, 10)]]
for test in test_cases:
result = self.check_line_from_point_to_point(*test)
self.assertEqual(1, len(result))
self.assertTrue(result[0])
result = self.check_line_from_point_to_border(12, 40, *test)
self.assertEqual(1, len(result))
self.assertTrue(result[0])
def check_line_from_point_to_point(self, a, b):
"""
Метод проверяет корректность отрезка от А до Б
"""
result = algorithms.algo_for_drawing_lines(*a, *b)
dy = b[1] - a[1]
dx = b[0] - a[0]
self.assertEqual(a[::-1], result[0])
self.assertEqual(b[::-1], result[-1])
return self.check_if_point_connected(result, dx, dy, a[0], a[1])
def check_line_from_point_to_border(self, height, width, a, b):
"""
Метод проверяет корректность отрезка от точки А, проходящего через
точку Б, до одной из границ поля
:param height: высота поля
:param width: ширина поля
:param a: координаты точки А (x, y)
:param b: координаты точки Б (x, y)
"""
if a == b:
b = (a[0], a[1] + 1)
result, error = algorithms.get_vector_to_the_end(height, width, *a, *b)
self.assertEqual(a[::-1], result[0])
self.assertEqual(True, result[-1][0] == 0 or
result[-1][0] == height - 1 or
result[-1][1] == 0 or result[-1][1] == width - 1)
return self.check_if_point_connected(result, result[-1][1] - a[0],
result[-1][0] - a[1], a[0], a[1],
error)
def check_if_point_connected(self, line, dx, dy, x, y, error=0):
"""
Метод проверяет связность растрового отрезка
:param line: отрезок, связность которого проверяется
:param dx: разность координат х начальной и конечной точек отрезка
:param dy:разность координат у начальной и конечной точек отрезка
:param x: координата х начальной точки
:param y: координата у начальной точки
:param error: корректировка точности вычислений
:return: пару (bool -- связен ли отрезок, (у, х) -- координаты точки,
на которой связность прервалась, если отрезок не связен)
"""
prev_point = None
if dx == dy == 0:
return len(line) == 1,
for point in line:
if prev_point:
self.assertTrue(abs(prev_point[0] - point[0]) == 1 or
abs(prev_point[1] - point[1]) == 1)
prev_point = point
if abs(dy) > abs(dx) or dx == 0:
if (abs(point[1] - ((point[0] - y) * dx / dy + x)) > 0.5 +
error):
return False, point
else:
if (abs(point[0] - ((point[1] - x) * dy / dx + y)) > 0.5 +
error):
return False, point
return True,
class TestGameLogic(unittest.TestCase):
"""Класс тестирует модуль game_logic"""
def test_saving_results(self):
"""Проверка метода game_logic.save_results"""
results = [[10, 2], [9, 2], [9, 6], [8, 5], [8, 7], [7, 3],
[6, 6], [5, 3], [5, 4]]
filename = 'testscore'
level_index = 1
scores_and_times = [(4, 4), (10, 1), (9, 4), (9, 7), (8, 3)]
core_classes.HighScoreTable.save_results(1, filename, 1, level_index)
with open(f'{filename}{level_index}.json',
'r') as f:
new_results = json.load(f)
self.assertEqual(1, len(new_results))
self.assertEqual([[1, 1]], new_results)
for score, time in scores_and_times:
with open(f'{filename}{level_index}.json',
'w') as f:
json.dump(results, f)
core_classes.HighScoreTable.save_results(score, filename, time,
level_index)
with open(f'{filename}{level_index}.json',
'r') as f:
new_results = json.load(f)
self.assertEqual(9, len(new_results))
prev_res = None
for result in new_results:
if prev_res:
self.assertTrue(prev_res[0] > result[0] or
(prev_res[0] == result[0] and
prev_res[1] < result[1]))
prev_res = result
os.remove(f'{filename}{level_index}.json')
@staticmethod
def validate(*args):
pass
class DummyFrog:
shoot_balls = [0, 0]
@patch('core_classes.Level.validate_level', validate)
@patch('core_classes.Frog', DummyFrog)
def test_embedding(self):
"""Проверка метода game_logic.handle_embedding"""
line = [[core_classes.Ball(5, 6), core_classes.Ball(5, 7),
core_classes.Ball(5, 8)],
[core_classes.Ball(3, 1), core_classes.Ball(3, 2),
core_classes.Ball(3, 3), core_classes.Ball(3, 4)],
[core_classes.Ball(7, 7, 2),
core_classes.Ball(8, 8, 3), core_classes.Ball(9, 9, 4)]]
old_line = copy.deepcopy(line)
enters = [(9, 5), (6, 3), (12, 12)]
exits = [(4, 5), (0, 2), (6, 6)]
indexes = [3, 5, 5]
roots = [[(8, 5), (7, 5), (6, 5), (5, 5)],
[(5, 3), (4, 3), (3, 3), (2, 3), (1, 3), (0, 3)],
[(11, 11), (10, 10), (9, 9), (8, 8), (7, 7)]]
ball_first = core_classes.Ball(5, 5)
ball_last = core_classes.Ball(3, 5)
ball_center = core_classes.Ball(8, 8)
ball_beggining = core_classes.Ball(5, 4)
ball_end = core_classes.Ball(3, 6)
ball_no_root = core_classes.Ball(1, 1)
game = Game(core_classes.Level(0, enters=enters, exits=exits,
roots=roots), lines=line)
self.assertEqual(indexes, game.indexes)
root, index = game.handle_embedding(ball_no_root)
self.assertEqual(old_line, line)
self.assertEqual(None, root)
self.assertEqual(None, index)
root, index = game.handle_embedding(ball_first)
old_line[0].insert(0, ball_first)
self.assertEqual(old_line, line)
self.assertEqual(0, root)
self.assertEqual(0, index)
indexes[0] += 1
root, index = game.handle_embedding(ball_beggining)
old_line[0].insert(0, ball_beggining)
self.assertEqual(old_line, line)
self.assertEqual(0, root)
self.assertEqual(0, index)
root, index = game.handle_embedding(ball_last)
old_line[1].append(ball_last)
self.assertEqual(old_line, line)
self.assertEqual(1, root)
self.assertEqual(4, index)
root, index = game.handle_embedding(ball_end)
old_line[1].append(ball_end)
self.assertEqual(old_line, line)
self.assertEqual(1, root)
self.assertEqual(5, index)
root, index = game.handle_embedding(ball_center)
old_line[2].append(core_classes.Ball(10, 10, 4))
self.assertEqual(old_line, line)
self.assertEqual(4, line[2][-1].color_number)
self.assertEqual(2, root)
self.assertEqual(1, index)
@patch('core_classes.Level.validate_level', validate)
def test_check_score_counting(self):
ball_on_map = [[core_classes.Ball(5, 5, 1), core_classes.Ball(5, 6, 1),
core_classes.Ball(5, 7, 2),
core_classes.Ball(5, 8, 3)],
[core_classes.Ball(3, 0, 3), core_classes.Ball(3, 1, 3),
core_classes.Ball(3, 2, 3),
core_classes.Ball(3, 3, 3),
core_classes.Ball(3, 4, 4)],
[core_classes.Ball(5, 4, 1), core_classes.Ball(5, 5, 1),
core_classes.Ball(6, 6, 3),
core_classes.Ball(7, 7, 3), core_classes.Ball(8, 8, 3),
core_classes.Ball(9, 9, 4)]]
old_balls = ball_on_map.copy()
score = 0
game = Game(core_classes.Level(0), balls=ball_on_map)
score += game.count_scores(0, 0)
self.assertEqual(0, score)
self.assertEqual(old_balls, ball_on_map)
score += game.count_scores(0, 2)
self.assertEqual(0, score)
self.assertEqual(old_balls, ball_on_map)
score += game.count_scores(1, 0)
self.assertEqual(40, score)
old_balls[1] = [core_classes.Ball(3, 4, 4)]
self.assertEqual(old_balls, ball_on_map)
score += game.count_scores(2, 4)
self.assertEqual(70, score)
old_balls[2] = [core_classes.Ball(5, 4, 1), core_classes.Ball(5, 5, 1),
core_classes.Ball(9, 9, 4)]
self.assertEqual(old_balls, ball_on_map)
class TestParser(unittest.TestCase):
level1 = core_classes.Level(1, (18, 10), [(10, 1)], [(10, 38)], 3,
[[(9, 1, 5), (8, 1, 5), (7, 1, 5),
(6, 1, 5), (5, 1, 5), (5, 2, 5),
(5, 3, 5), (5, 4, 5), (5, 5, 5),
(5, 6, 7), (5, 7, 7), (5, 8, 7),
(5, 9, 7), (5, 10, 7), (5, 11, 7),
(5, 12, 7), (5, 13, 7), (5, 14, 7),
(5, 15, 5), (5, 16, 5), (5, 17, 5),
(5, 18, 5), (5, 19, 5), (5, 20, 5),
(5, 21, 7), (5, 22, 7), (5, 23, 7),
(5, 24, 7), (5, 25, 7), (5, 26, 7),
(5, 27, 7), (5, 28, 7), (5, 29, 7),
(5, 30, 5), (5, 31, 5), (5, 32, 5),
(5, 33, 5), (5, 34, 5), (5, 35, 5),
(5, 36, 5), (5, 37, 5), (5, 38, 5),
(6, 38, 5), (7, 38, 5), (8, 38, 5),
(9, 38, 5)]],
10, 12, 40, 25, 150)
level2 = core_classes.Level(2, (18, 10), [(10, 1)], [(10, 38)], 5,
[[(9, 1, 5), (8, 1, 5), (7, 1, 5),
(6, 1, 5), (5, 1, 5), (5, 2, 5),
(5, 3, 5), (5, 4, 5), (5, 5, 5),
(5, 6, 7), (5, 7, 7), (5, 8, 7),
(5, 9, 7), (5, 10, 7), (5, 11, 7),
(5, 12, 7), (5, 13, 7), (5, 14, 7),
(5, 15, 5), (5, 16, 5), (5, 17, 5),
(5, 18, 5), (5, 19, 5), (5, 20, 5),
(5, 21, 7), (5, 22, 7), (5, 23, 7),
(5, 24, 7), (5, 25, 7), (5, 26, 7),
(5, 27, 7), (5, 28, 7), (5, 29, 7),
(5, 30, 10), (5, 31, 10), (5, 32, 10),
(5, 33, 10), (5, 34, 10), (5, 35, 10),
(5, 36, 10), (5, 37, 10), (5, 38, 10),
(6, 38, 10), (7, 38, 10), (8, 38, 10),
(9, 38, 10)]],
5, 12, 40, 33.3, 100)
def test_level_parser(self):
self.level1.validate_level()
core_classes.Level.put_level(self.level1)
self.level2.validate_level()
core_classes.Level.put_level(self.level2)
new_level1 = core_classes.Level.get_level("1level.txt")
new_level2 = core_classes.Level.get_level("2level.txt")
self.assertEqual(self.level1, new_level1)
self.assertEqual(self.level2, new_level2)
def test_gamestate_parser(self):
game1 = Game(self.level1)
game2 = Game(self.level2, balls=[[core_classes.Ball(10, 5, 3),
core_classes.Ball(11, 5, 3),
core_classes.Ball(10, 5, 3),
core_classes.Ball(9, 5, 4),
core_classes.Ball(8, 5, 4)]],
time=9.8011795)
game1.validate_gamestate()
game2.validate_gamestate()
game1.save_game()
game2.save_game()
new_game1 = Game.get_game('1levelGameState.txt')
new_game2 = Game.get_game('2levelGameState.txt')
self.assertEqual(game1, new_game1)
self.assertEqual(game2, new_game2)
if __name__ == '__main__':
unittest.main()
|
"""
Program to run game of life in a loop, and get values for equilibrium time
Histogram is then obtained from these equilibrium values
"""
import sys
import time
import random
import numpy as np
from typing import no_type_check
import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from methods_gol import rand_init, check, equilibrium_check, rand_init, plot_lattice
############## MAIN FUNCTION #######################
# Number of timesteps
nstep = 5000
# Input
if(len(sys.argv) != 2):
print ("Usage python game_of_life.py no_of_simulations")
sys.exit()
# Number of histogram times
no_of_simulations = int(sys.argv[1])
# Number of sites
lx = 50
ly = lx
N = lx*ly
# Set up files
EQ_times = open("EQ_times.txt","w")
# Set up lists to store values of equilibrium times
t_list = []
# To calculate time elapsed
start = time.time()
# Loop through number of times required for histogram
for loops in range(0,no_of_simulations):
print(loops)
# Initialise lattice
lattice = rand_init(lx,ly).copy()
# Lattice to store all the changes made
lattice2 = lattice.copy()
# List of number of active sites
no = []
no.append(np.sum(lattice))
# Set up plot
fig = plt.figure()
# Plot first time
plot_lattice(lattice)
# Start timestep
for n in range(nstep):
# Looping through lx*ly iterations
for i in range(lx):
for j in range(ly):
lattice2[i,j] = check(lattice,i,j,lx,ly)
# Copy lattice2 to lattice
lattice = lattice2.copy()
# Number of active sites
no.append(np.sum(lattice))
# Plot every timestep
plot_lattice(lattice)
# Equilibrium Check
if len(no) > 20:
if(equilibrium_check(no) == True):
break
# Timestep at which equilibrium was attained
t = n - 9
t_list.append(t)
EQ_times.write('%d\n' %(t))
# Close file
EQ_times.close()
# Time elapsed
print("Time Elapsed = {:.2f}s".format(time.time()-start))
print(t_list)
|
#!C:\Python34
x={'1':'2','2':'3','3':'4'}
for key in x:
print (key, x[key])
|
#!C:\Python34
def swapbits(x,y,posx,posy, bits):
print (" original x ", '{0:08b}'.format(x), end = "\n")
print (" original y ", '{0:08b}'.format(y), end = "\n")
#print mask for x
x_mask=(1<<bits)-1
print (" mask ", '{0:08b}'.format(x_mask), end = "\n")
x_mask=x_mask<<(posx-bits)
print (" mask after bits shift ", '{0:08b}'.format(x_mask), end = "\n")
#print mask for y
y_mask=(1<<bits)-1
print (" mask ", '{0:08b}'.format(y_mask), end = "\n")
y_mask=y_mask<<(posy-bits)
print (" mask after bits shift ", '{0:08b}'.format(y_mask), end = "\n")
#Create x_part and y_part
x_part = x & x_mask
print (" x_part ", '{0:08b}'.format(x_part), end = "\n")
y_part = y & y_mask
print (" y_part ", '{0:08b}'.format(y_part), end = "\n")
if (posx > posy): #If x position is greater than y position
x_part = x_part >> (posx - posy)
y_part = y_part << (posx - posy)
else: #If y position is greater than y position
x_part = x_part >> (posx - posy)
y_part = y_part << (posx - posy)
x= x & ~x_mask
y= y & ~y_mask
x= x | y_part
print (" x ", '{0:08b}'.format(x), end = "\n")
y= y | x_part
print (" y ", '{0:08b}'.format(x), end = "\n")
return x, y
def main():
x = eval(input ("Enter your first number" ))
y = eval(input ("Enter your second number" ))
posx = eval(input ("Enter your position " ))
posy = eval(input ("Enter your position " ))
bits = eval(input ("Enter your bits" ))
a, b= (swapbits(x, y, posx, posy, bits))
print (a, b)
if __name__=="__main__":
main()
|
#!C:\Python34
a,b,c= eval(input("Enter three numbers "))
print ("a= " , a, "b= ", b , "c= ", c)
if (a<b and a<c):
print (a , "is smaller")
elif ( b<c and b <a):
print (b , "is smaller")
else:
print (c , "is smaller")
|
#!/usr/bin/python
class SpeedLimitError(Exception):
"""Base Class for User definded Exception"""
def __inti__(self, speed):
self.speed =speed
def __str__(self):
return "Speed is "+str(self.speed)
class SpeedBelowLimit(SpeedLimitError):
"""Speed below Limit Execption"""
def __init__(self, speed):
SpeedLimitError.__init__(self,speed)
class SpeedAboveLimit(SpeedLimitError):
"""Speed above Limit Execption"""
def __init__(self, speed):
SpeedLimitError.__init__(self,speed)
def main():
while True:
try:
speed = eval(input("Enter Speed"))
if speed>80:
x = SpeedAboveLimit(speed)
raise x
elif speed<20:
raise SpeedBelowLimit(speed)
else:
print("Speed In limit")
break
except SpeedAboveLimit as e:
print(e,"is SpeedAboveLimit")
except SpeedBelowLimit as e:
print(e,"is SpeedBelowLimit")
finally:
print("COOL")
if __name__=="__main__":
main()
|
def factorial(no):
if(no==0):
return no
if(no==1):
return no
fact=1
for x in range (1, no+1):
fact =fact* x
return fact
#no = eval(input ("enter use from n "))
f= factorial(5)
print (f)
|
#!C:\Python34
import shutil
def zip_file(path, folder):
shutil.make_archive('myarchive', 'zip', path , folder)
def main():
folder= input("Enter folder: ")
path = input("Enter path for zip" )
zip_file(path, folder)
if __name__=="__main__":
main()
|
def first_position(s):
s2 = ''
s = str(s)
for i in range(0,len(s)):
if s[i] not in s2:
print('First position of {} is {}'.format(s[i],i))
s2 = s2 + s[i]
first_position(10122334455887667)
exit()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.