text stringlengths 37 1.41M |
|---|
#----------------------------selection sort---------------------------------------
a=[]
for i in range(0,5):
q=int(input("the input is :"))
a.append(q)
print(a)
for i in range(len(a)):
min_index=i
for j in range(i+1, len(a)):
if a[min_index]>a[j]:
min_index=j
a[i],a[min_index]=a[min_index],a[i]
print( "sorted array is :",a)
|
from functions import Maze
n = int(input("Quanti labirinti vuoi generare? "))
for i in range(0, n):
numRows = int(input("Inserisci il numero di righe "))
numColumns = int(input("Inserisci il numero di colonne "))
G = Maze.generateGraph(numRows, numColumns)
print("Il numero dei vertici ", G.number_of_nodes())
print("Il numero degli archi ", G.number_of_edges())
print("L'insieme dei vertici ",G.nodes())
print("L'insieme degli archi ",G.edges(data=True))
T = Maze.kruskalAlgorithm(G)
print("L'insieme degli archi del MST", T.edges())
color1 = input("Inserisci il colore dello sfondo ")
color2 = input("Inserisci il colore del labirinto ")
Maze.drawMaze(T, color1, color2, numRows, numColumns) |
from pprint import pprint
# PASTE THE CHOSEN NUMBERS HERE
numbers = [
[1, 16, 27, 40, 44, 1],
[1, 16, 27, 40, 44, 7],
[1, 16, 27, 40, 44, 15],
[6, 16, 27, 33, 44, 1],
[6, 16, 27, 33, 44, 7],
[6, 16, 27, 33, 44, 15],
[8, 16, 27, 33, 44, 1],
[8, 16, 27, 33, 44, 7],
[8, 16, 27, 33, 44, 15]
]
# PASTE THE WINNING NUMBERS HERE
winners = [
[19,25,41,45,46,12], # PB
[6,12,17,31,43,12] # PBP
]
scorePB = 0
powerPB = 0
scorePBP = 0
powerPBP = 0
result = []
for row in numbers:
for num in row:
if num in winners[0][:-1]:
scorePB += 1
if num in winners[1][:-1]:
scorePBP += 1
if row[-1] == winners[0][-1]:
powerPB = 1
if row[-1] == winners[1][-1]:
powerPBP = 1
if (powerPBP + powerPB > 0 or scorePB > 2 or scorePBP > 2):
result.append({
'Matched PB Nums': scorePB,
'Matched PB': powerPB,
'Matched PBP Nums': scorePBP,
'Matched PBP': powerPBP
})
scorePB = 0
powerPB = 0
scorePBP = 0
powerPBP = 0
if (len(result) > 0):
print('You won something! :)')
for row in result:
print(' ')
print(row)
else:
print('You did not win :(') |
"""
Learn about dictionaries
"""
from pprint import pprint as pp
def main():
"""
Test function
:return:
"""
urls = {
"google": "www.google.com",
"yahoo": "www.yahoo.com",
"twitter": "www.twitter",
"wsu": "weber.edu"
}
print(urls, type(urls))
# Access by key: [key]
print(urls["wsu"])
# Build dict with dict() constructor
names_age = [('Alice', 32), ('Mario', 23), ('Hugo', 21)]
d = dict(names_age)
print(d)
# Another method
phonetic = dict(a='alpha', b='bravo', c='charlie', d='delta')
print(phonetic)
# make a copy
e = phonetic.copy()
print(e)
# Updating a dictionary: update() method
stocks = {'GOOG':891, 'AAPL':416, 'IBM':194}
print(stocks)
stocks.update({'GOOG':999, 'YHOO':2})
print(stocks)
# Iteration default is by key value
for key in stocks:
print("{k} => {v}".format(k=key, v=stocks[key]))
# Iterate by values
for val in stocks.values():
print("val = ", val)
# Iterate by both key and value with: items()
for items in stocks.items():
print(items)
for key, val in stocks.items():
print(key, val)
# test for membership via key
print('GOOG' in stocks)
print('WINDOWS' not in stocks)
# Deleting: del keyword
print(stocks)
del stocks['YHOO']
print(stocks)
# Mutability of dictionaries
isotopes = {
'H': [1, 2, 3],
'He': [3, 4],
'Li': [6, 7],
'Be': [7, 9, 10],
'B': [10, 11],
'C': [11, 12, 13, 14]
}
print("\n\n\n") # 3 empty lines
pp(isotopes)
isotopes['H'] += [4, 5, 6, 7]
pp(isotopes)
isotopes['N'] = [13, 14, 15]
pp(isotopes)
if __name__ == '__main__':
main()
exit(0) |
"""
Generator Objects are a cross between comprehensions and generator functions
Syntax: Similar to list comprehension, but with parenthesis:
(expr(item) for item in iterable)
"""
from list_comprehensions import is_prime
def main():
"""
Test function
:return:
"""
# list with first 1 million square numbers
m_sq = (x*x for x in range(1, 1000001))
print(m_sq, type(m_sq))
print('The sum of the first 1M square numbers is:', sum(m_sq))
print('The sum of the first 1M square numbers is:',
sum(x*x for x in range(1, 1000001)))
# The sum of the prime numbers between 1 to 10K
print('The sum of the prime numbers from 1 to 10K:',
sum(x for x in range(1, 10001) if is_prime(x)))
if __name__ == '__main__':
main()
exit(0) |
"""
File learn about collection: Tuples, Strings, Range, List, Dictionaries, Sets
"""
def do_tuples():
"""
Practice tuples
:return: nothing
"""
# Immutable sequence of arbitrary objects
# Use () to define a tuple
t = ("Ogden", 1.99, 2)
print(t, type(t))
print("Size ", len(t))
print("One member:", t[0]) # by index notation
# To iterate over a tuple
for item in t:
print(item)
# Single tuples, must end with comma
t1 = (6,)
print(t1, type(t1))
# Another way to create tuples
# Parenthesis are optional
t2 = 1, 2, 3, 5
print(t2, type(t2))
# Tuple constructor: tuple()
t_from_l = tuple([3, 77, 11])
print(t_from_l, type(t_from_l))
# test for membership
print(5 in (3, 6, 8, 5, 12))
print(5 not in (3, 6, 8, 5, 12))
def min_max(items):
"""
Return the minimum and maximum elements of a collection
:param items: collection
:return: the minimum and maximum
"""
return min(items), max(items)
def swap(obj1, obj2):
"""
Swap value of the objects
:param obj1: first
:param obj2: second
:return: values swapped
"""
return obj2, obj1
def main():
"""
Test function
:return:
"""
do_tuples()
# output = min_max([56, 76, 11, 12, 90])
# print("min", output[0])
# print("max", output[1])
# # Tuple unpacking
# lower, upper = min_max([56, 76, 11, 12, 90])
# print("min", lower)
# print("max", upper)
#
# # Swap values
# a = "jelly"
# b = "bean"
# print(a, b)
# # Call your function
# a, b = swap(a, b)
# print(a, b)
# a, b = b, a
# print(a, b)
if __name__ == '__main__':
main()
exit(0) |
"""
Simulate 6000 rolls of a die (1-6)
"""
import random
import statistics
def roll_die(num):
"""
Random roll of a die
:param num: number of rolls
:return: a list of frequencies.
Index 0 maps to 1
Index 1 maps to 2
etc
"""
freq = [0] * 6 # initial val to 0
for roll in range(num):
n = random.randrange(1, 7)
freq[n - 1] += 1
# print(random.randrange(1,7))
return freq
def main():
"""
Test function
:return:
"""
num = int(input("How many times you need to roll: "))
result = roll_die(num)
for roll, total in enumerate(result):
print("Total rolls of {} = {}".format(roll + 1, total))
print("Average = {}".format(sum(result)/len(result)))
print("Mean = {}".format(statistics.mean(result)))
print("Median = {}".format(statistics.median(result)))
if __name__ == '__main__':
main()
exit(0) |
'''
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor,
and you can either start from the step with index 0, or the step with index 1.
'''
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
if len(cost)==0:
return 0
if len(cost)==1:
return cost[0]
if len(cost)==2:
return min(cost[0], cost[1])
f2=cost[0]
f1=cost[1]
for i in range(2,len(cost)):
f0=min(f1, f2) + cost[i]
f2=f1
f1=f0
return min(f1,f2)
# return self.minCostClimbingStairs(cost[:cur_index-1]) + cost[cur_index] \
# if self.minCostClimbingStairs(cost[:cur_index-1]) < self.minCostClimbingStairs(cost[:cur_index-2]) \
# else self.minCostClimbingStairs(cost[:cur_index-2]) + cost[cur_index]
if __name__=='__main__':
solution = Solution()
testCase1 = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
print(solution.minCostClimbingStairs(testCase1))
testCase2 = [10, 15, 20]
print(solution.minCostClimbingStairs(testCase2)) |
'''
191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
'''
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
que=[]
offset = 2
while n!=0:
if n%offset == 1:
que.append(1)
n=n//2
return len(que)
if __name__ == '__main__':
solution = Solution()
t1=11
print(solution.hammingWeight(t1))
|
'''
26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
2 pointers
'''
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n==0:
return 0
p1=0
p2=0
while p1 < n-1:
if nums[p1]!=nums[p1+1]:
p2+=1
nums[p2]=nums[p1+1]
p1+=1
del nums[p2+1:]
return p2+1
if __name__ == "__main__":
solution = Solution()
t1 = [1,1,2,2,2,3,3,4]
print(solution.removeDuplicates(t1))
print(t1) |
'''
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
'''
class Solution:
def dfs(self, i, j, board, word, word_index):
# the word is consumed which means we have passed the false test
if word_index==len(word):
return True
# make sure we are still in the board and current char is equal to current cell
if i<0 or i>len(board)-1 or j<0 or j>len(board[0])-1 or board[i][j]!=word[word_index]:
return False
tmp = board[i][j]
board[i][j]="#" # visited
# check different direction
result = self.dfs(i-1, j, board, word, word_index+1) or self.dfs(i+1, j, board, word, word_index+1) or self.dfs(i, j-1, board, word, word_index+1) or self.dfs(i, j+1, board, word, word_index+1)
board[i][j] = tmp
return result
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
rows = len(board)
cols = len(board[0])
for row in range(rows):
for col in range(cols):
if board[row][col] == word[0]:
if self.dfs(row, col, board, word, 0): return True
return False
if __name__ == "__main__":
s = Solution()
board =[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
assert s.exist(board, 'A') == True
assert s.exist(board,'ABCCED')==True
assert s.exist(board,'ABCCEC')==False
assert s.exist(board, 'SEE')==True
assert s.exist(board, 'ABCB')==False
|
import unittest
from typing import Optional, List, Union
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left: Optional[TreeNode] = None
self.right: Optional[TreeNode] = None
class Tree:
def __init__(self, data: Union[List, TreeNode, None]):
if isinstance(data, List):
self.root = self.genTree(data)
elif isinstance(data, TreeNode):
self.root = data
else:
self.root = None
@staticmethod
def genTree(arr):
'''
input: list[int]
output: treeNode of the root
the binary tree should always with length 2^k
'''
if len(arr) <= 0:
return None
def helper(i)->Optional[TreeNode]:
if i < len(arr):
if arr[i] is None:
return None
else:
root = TreeNode(arr[i])
root.left = helper(2 * i + 1)
root.right = helper(2 * i + 2)
return root
return helper(0)
def viewTreeBFS(self, root:Optional[TreeNode]=None):
if not root:
if not self.root:
return
else:
self.viewTreeBFS(self.root)
return
if not isinstance(root, TreeNode):
print("Root of the tree should be TreeNode type")
return
que = [root]
cur_end_node = root
next_end_node = root
while len(que) > 0:
cur_node = que.pop(0)
if cur_node.left is not None:
next_end_node = cur_node.left
que.append(cur_node.left)
if cur_node.right is not None:
next_end_node = cur_node.right
que.append(cur_node.right)
if cur_node == cur_end_node:
cur_end_node = next_end_node
print(cur_node.val)
else:
print(cur_node.val, end=' ')
class TestCases(unittest.TestCase):
def setUp(self):
self.testCase1 = Tree([3, 9, 20, None, None, 15, 7])
self.testCase2 = Tree([1, None, 2, None, None, 3, None])
def testGenTree(self):
self.assertEqual(3, getattr(self.testCase1.root, "val"))
self.testCase1.viewTreeBFS(self.testCase1.root)
def testViewTree(self):
self.testCase2.viewTreeBFS()
if __name__ == '__main__':
unittest.main()
|
'''
find how many combinations that sum up to a given total
None negative elements
'''
def rec(arr, total, last_index):
'''
Recursive function that add up to a given total
'''
if total==0:
return 1
elif total < 0:
return 0
elif last_index<0:
return 0
return rec(arr, total - arr[last_index], last_index-1) + rec(arr, total, last_index-1)
def count_sets(arr, total):
return rec(arr, total, len(arr)-1)
def dp(arr, total, last_index, mem):
key = str(total) + ":" + str(last_index)
if mem.get(key):
return mem.get(key)
elif total==0:
return 1
elif last_index<0:
return 0
elif total < arr[last_index]:
temp_result = dp(arr, total, last_index-1, mem)
else:
temp_result = dp(arr, total-arr[last_index], last_index-1, mem) + dp(arr, total, last_index-1, mem)
mem.update({key:temp_result})
return temp_result
def count_sets_dp(arr, total):
mem = {}
# passing a memory for memoization
return dp(arr, total, len(arr)-1, mem)
if __name__ == "__main__":
result = count_sets_dp([2,4,6,10], 16)
print(result) |
'''
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
'''
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
rows = len(board)
cols = len(board[0])
row_check = [{} for _ in range(rows)]
col_check = [{} for _ in range(cols)]
grid_check = [[{} for _ in range(3)] for _ in range(3)]
for row in range(rows):
for col in range(cols):
cur_val = board[row][col]
if cur_val == '.':
continue
cur_grid_row = row//3
cur_grid_col = col//3
if row_check[row].get(cur_val) or col_check[col].get(cur_val) or grid_check[cur_grid_row][cur_grid_col].get(cur_val):
return False
else:
row_check[row].update({cur_val:True})
col_check[col].update({cur_val:True})
grid_check[cur_grid_row][cur_grid_col].update({cur_val:True})
return True
if __name__ == "__main__":
s = Solution()
t1 = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
assert s.isValidSudoku(t1)==True
t2 = [
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
assert s.isValidSudoku(t2)==False
|
'''
796. Rotate String
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.
Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true
Example 2:
Input: A = 'abcde', B = 'abced'
Output: false
Note:
A and B will have length at most 100.
'''
class Solution:
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
n = len(A)
A = 2*A
for i,v in enumerate(A):
if i<n and A[i:i+n] == B:
return True
return False
if __name__ == "__main__":
solution = Solution()
t1=("abcde","cdeab")
print(solution.rotateString(t1[0], t1[1]))
t2=("abcde", "abced")
print(solution.rotateString(t2[0], t2[1])) |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inOrder(self, root, bstArr):
if not root:
return
if root.left:
self.inOrder(root.left, bstArr)
bstArr.append(root.val)
if root.right:
self.inOrder(root.right, bstArr)
return bstArr
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
ordered_tree = self.inOrder(root, [])
p1 = 0
p2 = len(ordered_tree)-1
while p1 < p2:
if ordered_tree[p1]+ordered_tree[p2]==k:
return True
elif ordered_tree[p1]+ordered_tree[p2]<k:
p1+=1
else:
p2-=1
return False
if __name__ == "__main__":
solution = Solution()
head1 = TreeNode(5)
head1.left = TreeNode(3)
head1.right = TreeNode(6)
head1.left.left = TreeNode(2)
head1.left.right = TreeNode(4)
head1.right.right = TreeNode(7)
print(solution.inOrder(head1, []))
print(solution.findTarget(head1, 9))
|
'''
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
'''
from leetcode.tree_utils import Tree
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def dfs(self, cur, cur_sum, sum):
if not cur:
return False
cur_sum += cur.val
if not cur.left and not cur.right and cur_sum==sum:
return True
return self.dfs(cur.left, cur_sum, sum) or self.dfs(cur.right, cur_sum, sum)
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
return self.dfs(root, 0, sum)
if __name__ == "__main__":
solution = Solution()
tree1 = [5,4,8,11,None, 13, 4, 7,2,None, None, None,1]
t1 = Tree(tree1)
target1 = 22
print(solution.hasPathSum(t1.root, target1))
tree2 = [1,2]
t2 = Tree(tree2)
target2 = 1
print(solution.hasPathSum(t2.root, target2))
|
'''
a - 1
b - 2
...
z - 24
given a number, return how many possible ways to decode it
'''
from functools import wraps
import time
def timmer(func):
@wraps(func)
def clock(*args, **wargs):
start = time.clock()
print(func(*args, **wargs))
end = time.clock()
print("Time duration of ", func.__name__, " is ", end-start)
return clock
@timmer
def decodeRecursion(num):
'''
Devide and conquer
'''
def helper(num,l):
"""
@param num the number represented encoded string
@param l the length of the rest of the string
"""
if l == 0:
return 1
s = len(num) - l
if num[s]=="0":
return 0
result = helper(num, l-1)
if l >=2 and int(num[s:s+2])<=26:
result += helper(num, l-2)
return result
return helper(num, len(num))
@timmer
def decodeMemo(num):
"""
Since there are a lot of unnecessary repeation, we can bypass them with a memo
The memo's index represent the length of the current substring and the value is the number of ways to decode it
"""
memo = [None for _ in range(len(num)+1)]
def helper(num, l, mem):
# initialize
if l == 0:
return 1
s = len(num) - l
if num[s]=="0":
return 0
if mem[l]:
return mem[l]
result = helper(num, l-1, mem)
if l >= 2 and int(num[s:s+2])<=26:
result += helper(num, l-2, mem)
# remember the state
mem[l] = result
return result
return helper(num, len(num), memo)
if __name__ == "__main__":
test_case1="1213213213123423412424132422"
test_case2="12345"
test_case3="011"
test_case4="2789"
print(decodeRecursion(test_case1))
print(decodeRecursion(test_case2))
print(decodeRecursion(test_case3))
print(decodeRecursion(test_case4))
print(decodeMemo(test_case1))
print(decodeMemo(test_case2))
print(decodeMemo(test_case3))
print(decodeMemo(test_case4)) |
''' Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships. '''
class Solution:
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
if not board:
return 0
rows = len(board)
cols = len(board[0])
count = 0
for x in range(rows):
for y in range(cols):
if board[x][y]=='X' and (x==0 or board[x-1][y]=='.') and (y==0 or board[x][y-1]=='.'):
count+=1
return count
if __name__=='__main__':
testcase1=[['X','.','.','X'],
['.','.','.','X'],
['.','.','.','X']]
solution = Solution()
print(solution.countBattleships(testcase1)) |
"""
Given an array, rotate the array to the right by k steps, where k is non-negative.
"""
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
while k > 0:
last = nums.pop()
nums.insert(0, last)
k -= 1
return nums
if __name__ == "__main__":
s = Solution()
t1 = ([1,2,3,4,5,6,7], 3)
assert s.rotate(t1[0], t1[1]) == [5,6,7,1,2,3,4]
t2 = ([-1,-100,3,99], 2)
assert s.rotate(t2[0], t2[1]) == [3,99,-1,-100] |
'''
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Floyd's cycle-finding algorithm
https://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow_ptr = head
fast_ptr = head
iteration = 1
while True:
if fast_ptr:
fast_ptr = fast_ptr.next
else:
return False
if iteration%2==0 and slow_ptr:
slow_ptr = slow_ptr.next
if slow_ptr==fast_ptr:
return True
iteration+=1
if __name__ == "__main__":
solution = Solution()
|
'''
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()".
And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
Solutions: might use dfs
'''
from collections import deque
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class Solution:
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if t is None:
return ''
if t.left and t.right:
return str(t.val) + "(" + self.tree2str(t.left) + ")" + "(" + self.tree2str(t.right) + ")"
if t.left and not t.right:
return str(t.val) + "(" + self.tree2str(t.left) + ")"
elif not t.left and t.right:
return str(t.val) + "()" + "(" + self.tree2str(t.right) + ")"
elif not t.left and not t.right:
return str(t.val)
if __name__=='__main__':
solution = Solution()
test1=TreeNode(1)
test1.left=TreeNode(2)
test1.right=TreeNode(3)
test1.left.left=TreeNode(4)
print(solution.tree2str(test1))
test2=TreeNode(1)
test2.left=TreeNode(2)
test2.right=TreeNode(3)
test2.left.right=TreeNode(4)
print(solution.tree2str(test2)) |
"""
Four divisors
"""
import math
from typing import List
class Solution:
def divisors(self, n:int) -> List[int]:
"""
this is the core algo to list all the divisors with O(sqrt(n)) instead of O(n)
"""
i = 1
result = []
while i <= math.sqrt(n):
if n % i == 0:
result.append(i)
if i != n//i:
result.append(n//i)
i += 1
return result
def sumFourDivisors(self, nums: List[int]) -> int:
answer = 0
for n in nums:
result = self.divisors(n)
if len(result) == 4:
answer += sum(result)
return answer |
'''
19. Remove Nth Node From End of List
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next:ListNode|None = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
head1 = dummy
head2 = dummy
distance = 0
while head1.next:
if distance==n and head2.next:
head2=head2.next
else:
distance+=1
head1 = head1.next
head2.next = head2.next.next if head2.next else None
return dummy.next
def removeNthFromEnd1(self, head, n):
total_nodes = 0
while head:
total_nodes+=1
cur_node = head
cur_pos = 1
while cur_pos!=total_nodes-n:
cur_node=cur_node.next
cur_pos+=1
cur_node.next = cur_node.next.next
return head
if __name__ == "__main__":
solution = Solution()
t1 = [1,2,3,4,5]
head = ListNode(t1[-1])
|
'''
We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element.
Given an array, count the number of inversions it has. Do this faster than O(N^2) time.
You may assume each element in the array is distinct.
For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion.
'''
count=0
def merge(left, right, len_left, len_right):
global count
i = 0
j = 0
result = []
while i<len_left and j<len_right:
# inversion
if left[i]>right[j]:
result.append(right[j])
j+=1
# this is the key point:
count += len_right-j
else:
result.append(left[i])
result.append(right[j])
i+=1
j+=1
if i<len_left:
result += left[i:]
count+=len(left[i:])
if j<len_right:
result += right[j:]
return result
def find_invension(arr):
if len(arr) <= 1:
return arr
l = len(arr)
mid = int(l/2)
left = find_invension(arr[:mid])
right = find_invension(arr[mid:])
return merge(left,right, len(left), len(right))
if __name__=="__main__":
test1= [2, 4, 1, 3, 5,-1]
res = find_invension(test1)
print(count)
print(res) |
"""
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from typing import Optional
class Solution:
def minDepth(self, root)->int:
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if root and not root.left and not root.right:
return 1
if root.left:
left_depth = 1 + self.minDepth(root.left)
else:
left_depth = 0
if root.right:
right_depth = 1 + self.minDepth(root.right)
else:
right_depth = 0
if right_depth and left_depth:
return min(left_depth, right_depth)
elif right_depth:
return right_depth
else:
return left_depth
if __name__ == "__main__":
from leetcode import Tree
s = Solution()
t1 = Tree([1,2])
t1.viewTreeBFS()
print(s.minDepth(t1.root))
|
"""
154. Find Minimum in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Would allow duplicates affect the run-time complexity? How and why?
Not really for the O(n) solution
"""
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if __name__ == "__main__":
s = Solution()
t = [2,2,2,0,1]
assert s.findMin(t) == 0
t = [1,3,5]
assert s.findMin(t) == 1 |
"""
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
"""
class Solution:
def dfs(self, result, s, temp_set):
print(len(temp_set), s)
if len(temp_set)>4 and s:
return
if len(temp_set)==4 and not s:
print('.'.join(temp_set))
result.append('.'.join(temp_set))
if len(s)>=3 and int(s[:3])<=255:
temp_set.append(s[:3])
self.dfs(result, s[3:], temp_set)
temp_set.pop()
if len(s)>=2 and int(s[:2])<=255:
temp_set.append(s[:2])
self.dfs(result, s[2:], temp_set)
temp_set.pop()
if len(s)>=1 and int(s[:1])<=255:
temp_set.append(s[:1])
self.dfs(result, s[1:], temp_set)
temp_set.pop()
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
result = []
self.dfs(result, s, [])
return result
if __name__ == "__main__":
s = Solution()
t1= "25525511135"
print(s.restoreIpAddresses(t1))
t2 = "010010"
print(s.restoreIpAddresses(t2)) # ["0.10.0.10","0.100.1.0"] |
'''
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
'''
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
words_in_rows={
'q':1, 'w':1, 'e':1, 'r':1, 't':1, 'y':1, 'u':1, 'i':1, 'o':1, 'p':1,
'a':2, 's':2, 'd':2, 'f':2, 'g':2, 'h':2, 'j':2, 'k':2, 'l':2,
'z':3, 'x':3, 'c':3, 'v':3, 'b':3, 'n':3, 'm':3
}
result=[]
for word in words:
row=words_in_rows[word[0].lower()]
is_in_the_same_row=True
for c in word:
if words_in_rows[c.lower()]!=row:
is_in_the_same_row=False
break
if is_in_the_same_row:
result.append(word)
return result
if __name__=='__main__':
solution=Solution()
testCase1=["Hello", "Alaska", "Dad", "Peace"]
print(solution.findWords(testCase1)) |
#!/bin/python
'''
Utilized a concept of stack
'''
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
round_points=[0,0]
for op in ops:
if op == 'C':
round_points.pop()
elif op=='+':
# notice how to get the last 2 value
round_points.append(round_points[-1]+round_points[-2])
elif op=='D':
round_points.append(2*round_points[-1])
else:
round_points.append(int(op))
return sum(round_points)
if __name__ == "__main__":
solution = Solution()
testCase1=["5","2","C","D","+"]
print(solution.calPoints(testCase1))
testCase2=["5","-2","4","C","D","9","+","+"]
print(solution.calPoints(testCase2)) |
'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
'''
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s)==0:
return True
p1 = 0
p2 = len(s)-1
while p1 < p2:
'''
isalnum(): Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
similar:
isalnum( isalpha( isdecimal( isdigit( isidentifier( islower( isnumeric( isprintable( isspace( istitle( t.isupper(
'''
# notice the p1<p2 must be required here
# otherwise will raise index error
while not s[p1].isalnum() and p1<p2:
p1+=1
while not s[p2].isalnum() and p1<p2:
p2-=1
if s[p1].lower()!=s[p2].lower():
return False
p1+=1
p2-=1
return True
if __name__ == "__main__":
solution = Solution()
t1 = "A man, a plan, a canal: Panama"
print(solution.isPalindrome(t1))
t2 = "race a car"
print(solution.isPalindrome(t2))
t3 = " "
print(solution.isPalindrome(t3))
t4 = ".,"
print(solution.isPalindrome(t4)) |
'''
Matrix:
Count the number of islands in a matrix
'''
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def getIsland(i,j):
if 0<=i<len(grid) and 0<=j<len(grid[0]) and grid[i][j]=='1':
grid[i][j]='0'
return 1+getIsland(i-1,j)+getIsland(i+1,j)+getIsland(i,j+1)+getIsland(i,j-1)
return 0
result=0
for row, cols in enumerate(grid):
for col, val in enumerate(cols):
if getIsland(row,col)>0:
result+=1
return result
if __name__=='__main__':
solution = Solution()
t1=[
[1,1,1,1,0],
[1,1,0,1,0],
[1,1,0,0,0],
[0,0,0,0,0]]
print(solution.numIslands(t1)) |
import random
import unittest
userList = []
def listUsers():
for x in userList:
print(x.accountID)
groupList = []
def listGroups(self):
for x in Group.groupList:
print("group ", x.groupID)
def storeAccount(account, password, file): #function to store user in database
f = open(file, "a+") #open database, and append given input
f.write(account.name + "," + account.email + "," + password + "," + str(account.phone) + "," + str(account.nrShift) + str(account.accountID) + "\n")
f.close() #close
def stringerror(string, attribute):
if not string:
raise ValueError("Invalid input " + attribute + " must not be an empty string")
if not type(string) is str:
raise ValueError("Invalid input " + attribute + " must be a string")
def phoneerror(string):
if not string:
raise ValueError("Invalid input phone must not be an empty string")
if len(string) != 8:
raise ValueError("valid phone number must be 8 digits long")
if string.isdigit() == False:
raise ValueError("input given for phone must be an Integer")
class User:
Type = "Volenteer"
def __init__(self,name,email,phone):
stringerror(name,"name")
stringerror(email, "email")
if isinstance(phone, int) == True:
phone = str(phone)
phoneerror(phone)
self.name = name
self.email = email
self.phone = phone
self.nrShift = 0
self.accountID = self.createID()
userList.append(self)
def __repr__(self):
return "<User info: name:%s - email:%s, number:%s, total nr of shifts:%s, his personal id is: %s>" % (self.name, self.email,self.phone,self.nrShift,self.accountID)
def createID(self):
id = "0-"+str(random.randint(2,2000))+"-"+str(self.name)
if self.checkUnique(id) != 0:
return id
else:
self.createID()
def checkUnique(self,id):
for x in userList:
if x.accountID == id:
return 0
else:
pass
def grouperror(string):
if int(string)!=True:
raise ValueError("input must be an Integer")
class Group:
def __init__(self,groupID):
grouperror(groupID)
self.groupID = groupID
self.checkID()
groupList.append(self)
self.members = []
self.supers = []
self.activesuper = "None"
def checkID(self):
for x in groupList:
if self.groupID==x.groupID:
raise Exception("this ID is already chosen, please choose another ID for the group")
def __repr__(self):
return "<Group info: members:%s - supers:%s - schedule:%s, activesuper is:%s>" % (
self.members,self.super,self.schedule,self.activesuper)
def add_user(self, User):
for x in self.members:
if User.accountID == x:
raise Exception("user already added to this group")
pass
self.members.append(User.accountID)
def listMembers(self):
for x in self.members:
print(x, "is a member of",self.groupID)
class Schedule:
def __init__(self,groupNr,Month):
self.groupnr = groupNr
self.month = Month
class TestUser(unittest.TestCase):
def setUp(self):
self.user1 = User("John","john@shit.com","22334455")
self.user2 = User("Carl", "carl@shit.com", "55443322")
def test_email(self):
self.assertEqual(self.user1.email,"john@shit.com")
self.assertEqual(self.user2.email, "carl@shit.com")
def test_name(self):
self.assertEqual(self.user1.name, "John")
self.assertEqual(self.user2.name,"Carl")
def test_phone(self):
self.assertEqual(self.user1.phone,"22334455")
self.assertEqual(self.user2.phone, "55443322")
def test_UserID(self):
self.assertEqual(self.user1.checkUnique(self.user1.accountID),0)
self.assertEqual(self.user1.checkUnique(self.user2.accountID), 0)
def test_stringTest(self):
self.assertRaises(ValueError, stringerror, "", "user")
self.assertRaises(ValueError, stringerror, 2, "user")
self.assertRaises(ValueError, stringerror, ["dum"], "user")
def test_phoneTest(self):
self.assertRaises(ValueError,phoneerror,"")
self.assertRaises(ValueError, phoneerror, "2233445b")
self.assertRaises(ValueError, phoneerror, "2233445")
self.assertRaises(ValueError, phoneerror, "223344555")
self.assertRaises(ValueError, phoneerror, 223344555)
if __name__ == '__main__':
John = User("john","john",22222222)
unittest.main()
|
#Script constructs the plural of an English noun according to various plural rules
#Not conclusive, some rules not taken care of
#use of iterators
import re
def build_apply_match_functions(pattern, search, replace):
'''A closure function that build two function dynamicaly;
match_rule => matches a pattern against a noun, returns true or None
apply_rule => applies the plural rule if the corresponding match_rule was succesful
'''
def match_rule(word):
return re.search(pattern, word)
def apply_rule(word):
return re.sub(search, replace, word)
return (match_rule, apply_rule)
class LazyRules:
''' Iterator that uses build_apply_match_functions to constrcuts functions
lazily
'''
rules_filename = 'plural-rules.txt'
def __init__(self):
self.pattern_file = open(self.rules_filename, encoding='utf-8')
self.cache = []
def __iter__(self):
self.cache_index = 0
return self
def __next__(self):
self.cache_index += 1
if len(self.cache) >= self.cache_index:
return self.cache[self.cache_index - 1]
if self.pattern_file.closed:
raise StopIteration
line = self.pattern_file.readline()
if not line:
self.pattern_file.close()
raise StopIteration
pattern, search, replace = line.split(None, 3)
funcs = build_apply_match_functions(pattern, search, replace)
self.cache.append(funcs)
return funcs
rules = LazyRules()
def plural(noun):
'''Generic function that takes an English noun and constructs the plural'''
for match_rule, apply_rule in rules:
if match_rule(noun):
return apply_rule(noun)
if __name__ == '__main__':
noun = input("English noun: ")
print('Plural: {}'.format(plural(noun.lower())))
|
class Operators:
def __init__(self):
self.MONTHLY = False
self.DAILY = False
self.END_OF_MONTHLY = False
self.operations = []
self.currentDay = None
self.currentMonth = None
self.currentYear = None
def init_date(self, year, month, day):
self.currentYear = year
self.currentMonth = month
self.currentDay = day
for oper in self.operations:
oper.day()
def new_year(self, year, month, day):
#print "Year %s" % year
self.currentYear = year
self.currentMonth = month
self.currentDay = day
for oper in self.operations:
oper.year()
if oper.monthly or oper.end_of_monthly:
oper.rotate(save_last=oper.end_of_monthly)
def new_month(self, month, day):
#print "Month %s" % month
self.currentMonth = month
self.currentDay = day
for oper in self.operations:
oper.month()
if oper.monthly or oper.end_of_monthly:
oper.rotate(save_last=oper.end_of_monthly)
def new_day(self, day):
self.currentDay = day
for oper in self.operations:
oper.day()
if oper.daily:
oper.rotate()
def newTransaction(self, transac):
for op in self.operations:
if op.accept(transac):
op.process(transac)
class Operator:
def __init__(self, ops):
self.monthly = ops.MONTHLY
self.daily = ops.DAILY
self.end_of_monthly = ops.END_OF_MONTHLY
self.registered = False
self.ops = ops
self.ops.operations.append(self)
def accept(self, transac):
return True
def process(self, transac): pass
def year(self): pass
def month(self): pass
def day(self): pass
def raw(self): pass
def dump(self): pass
def register(self):
self.registered = True
def rotate(self, save_last=False): pass
|
from stack import Stack
def reverse(input_string):
s = Stack()
print(input_string[::-1])
for i in range(len(input_string)):
s.push(input_string[i])
reverse_string = ""
while not s.is_empty():
reverse_string += s.pop()
return reverse_string
print(reverse("siddhartha")) |
n=int(input("n="))
"""def nchiziq(n):
txt=''
for i in range(n):
txt+='-'
print(txt)"""
# 2-usul
def nchiziq(n):
print("-"*n)
nchiziq(n) |
# berilgan n sonidan kicik bolgan sonlarning darajasi n sonidan kichik sonlarni chiqarish
n=int(input("n="))
def daraja(n):
qiymat=[]
for i in range(1,n):
if i**2<n:
qiymat.append(i)
return qiymat
print(daraja(n))
|
number=(1,2,3,4,5,6,9,8,7,4,6,5)
print(number.count(5))
print(number.index(9))
print(any(number))
print(max(number))
print(min(number))
print(len(number))
print(sorted(number))
print(sum(number))
|
def PowerA3(n):
return n**3
A=1.1
B=2.2
C=3.3
D=1
E=2
print(PowerA3(A))
print(PowerA3(B))
print(PowerA3(C))
print(PowerA3(D))
print(PowerA3(E)) |
#1-misol 10 raqmini chiqarish
numbersList = [[1, 2, 3, 4], [0, [1, 2, [4, 5, [10, 11]], 4], 5], 12]
print(numbersList[1][1][2][2][0])
#2-miol 5 ni chiqaring
numbersList1=[[1,2,3],[4,5,6],[7,8,9]]
print(numbersList1[1][1])
|
# # namunaviy masala
# a = [1, 2, 3, 4]
# b = [1, 2, 3, 4]
# c = [1, 2, 3, 4]
#
#
# # ro'yhatlarni 2 dan katta elementlarini ekranga chiqaring
# def myFunction(x):
# for i in x:
# if i > 2:
# print(i)
#
#
# myFunction(a)
# myFunction(b)
# myFunction(c)
""" funcksiyalar va protseduralar """
# funksiyani yaratish
# def <funksiya_nomi> (<parametrlari>):
# <amallar>
# return <o'zgaruvchi>
#
# def salom():
# print("salom")
#
# # funskiyani chaqirish
# salom()
#
#
# # argument va parametr
# # 1) funksiyani e'lon qilish
# def salom(name): # bu yerda name parameter
# print(f"Salom {name}")
#
# # 2) funksiyani chaqirish
# ism = input("ismingizni kiritng: ")
# salom(ism)
# """ ko'p parameterli funksiya"""
#
#
# def tuliq_ism(ism, familiyani):
# tuliq = ism + ' ' + familiyani
# print(tuliq)
#
#
# tuliq_ism("Oybek", "Narzullayev")
# tuliq_ism("John", "Doe")
#
# """ *args -> bu parametrlar to'plami """
#
#
# def ismlar_ruyhati(*ism):
# print(ism)
#
#
# ismlar_ruyhati("Oybek", "Shoxzod", "Muhammad", "Ibrohim")
#
#
# def fanlar_ruyhati(*fan):
# print(fan)
#
#
# fanlar_ruyhati("Matematika", "Fizika", "Informatika")
#
# """ keyword -> kalit so'z """
#
#
# def tuliq_ism(ism, famliya):
# print(f"{ism} {famliya}")
#
#
# firstname = input("ism : ")
# lastname = input("familiya : ")
# tuliq_ism(famliya=lastname, ism=firstname)
# """ many keyword **args-> kalit so'zlar to'plami """
#
#
# def uquvchi(**x):
# print(x)
#
#
# malumot = dict({})
# uquvchi(ismi="Ibrohim", yoshi=18, millati="O'zbek")
#
#
# def myfunction(tulov=0):
# print(f"sizdan {tulov} so'm")
#
#
# myfunction(20000)
# myfunction(10000)
# myfunction()
#
#
# def rang(r="qora"):
# print(f"men yoqtirgan rang: {r}")
#
#
# rang("oq")
# rang()
# """ ro'yhat argument sifatida """
#
#
# def uquvchilar(x):
# for i in x:
# print(i)
#
#
# uquvchi = ["Oybek", "Shoxzod", "Madinabonu"]
#
# uquvchilar(uquvchi)
# """ pass """
#
#
# def main1():
# pass
#
#
# main1()
# print("salom") |
"""kortej berilgan ularning toq o'rindagi elementlari """
d=(1,2,3,4,5,6)
juft=[]
for i in range(1,len(d),2):
juft.append(d[i]**2)
print(tuple(juft))
|
x=int(input("x kiriting="))
y=int(input("y kiriting="))
if x%2==0 and y%2==0:
print(f"{x} juft son {y} juft son")
elif
x % 2 != 0 and y % 2 == 0:
print(f"{x} toq son {y} juft son")
elif
x % 2 != 0 and y % 2 == 0:
print(f"{x} toq son {y} juft son")
else:
print(f"{x} toq son {y} toq son")
|
class Player:
def __init__(self, piece):
self.piece = piece
def move(self, board):
valid = False
while not valid:
try:
position = input("Enter column to play: ")
if int(position) >= board.cols:
raise ValueError
moves = board.get_add_moves()
if int(position) not in moves:
raise ValueError
else:
valid = True
except KeyboardInterrupt:
break
except:
print("Invalid selection.")
continue
board.add_piece(int(position), self.piece)
return board |
def sum(a):
global n
for i in range(a+1):
n = n + i
return n
n = 0
print(sum(5))
|
class goldar():
def __init__(self, antiA, antiB, antiAB, antiD, darah, rhesus):
self.antiA = antiA
self.antiB = antiB
self.antiAB = antiAB
self.antiD = antiD
self.darah = darah
self.rhesus = rhesus
def findgoldar(self):
if (self.antiA == "Menggumpal") and (self.antiB == "Tidak Menggumpal") and (self.antiAB == "Menggumpal"): #Goldar A
self.darah = "A"
elif (self.antiA == "Tidak Menggumpal") and (self.antiB == "Menggumpal") and (self.antiAB == "Menggumpal"): #Goldar B
self.darah = "B"
elif (self.antiA == "Menggumpal") and (self.antiB == "Menggumpal") and (self.antiAB == "Menggumpal"): #Goldar AB
self.darah = "AB"
elif (self.antiA == "Tidak Menggumpal") and (self.antiB == "Tidak Menggumpal") and (self.antiAB == "Tidak Menggumpal"): #Goldar O
self.darah = "O"
else:
self.darah = "ERROR"
def findrh(self):
if (self.antiD == "Menggumpal"):
self.rhesus = "+"
elif (self.antiD == "Tidak Menggumpal"):
self.rhesus = "-"
else :
self.rhesus = "ERROR"
def setantiA(self, antiA):
self.antiA = antiA
pass
def setantiB(self, antiB):
self.antiB = antiB
pass
def setantiAB(self, antiAB):
self.antiAB = antiAB
pass
def setantiD(self, antiD):
self.antiD = antiD
pass
def getdarah(self):
return self.darah
def getrhesus(self):
return self.rhesus |
class KAryLevel:
def __init__(self):
self.isLeaf = True
self.size = 0
self.rootNode = None
class KAryNode:
def __init__(self,val,right_of_root):
self.right_of_root = False
self.data = val
self.left = None
self.right = None
self.left_level = None
self.right_level = None
class KAryTree:
def __init__(self, val):
self.root = KAryLevel()
self.root.rootNode = KAryNode(val, False)
self.root.size = 1
def leftmostnode(node):
prev_node = node
while node.left is not None:
prev_node = node
node = node.left
return prev_node
def thirdnode(root_node):
leftnode = leftmostnode(root_node)
return (leftnode.right).right
def fifthnode(root_node):
leftnode = leftmostnode(root_node)
return (((leftnode.right).right).right).right
def seventhnode(root_node):
leftnode = leftmostnode(root_node)
return (((((leftnode.right).right).right).right).right).right
def sixthnode(root_node):
leftnode = leftmostnode(root_node)
return (((((leftnode.right).right).right).right).right)
def ninethnode(root_node):
leftnode = leftmostnode(root_node)
return (((((((leftnode.right).right).right).right).right).right).right).right
def insert_between_nodes(l, r, new):
assert(l.right == r and r.left == l)
if l is None:
r.left = new
new.right = r
return
if r is None:
l.right = new
new.left = l
return
l.right = new
new.left = l
new.right = r
r.left = new
# (Addition for parent, l level, r level, child level)
def rebalance(parent_level, level):
# Rebalancing the root
#assert(level.size == 11)
if level.size > 10:
new_left_level = KAryLevel()
new_right_level = KAryLevel()
new_left_level.size = 5
new_left_level.isLeaf = level.isLeaf
new_right_level.size = 5
new_left_level.isLeaf = level.isLeaf
new_left_level.rootNode = thirdnode(level.rootNode)
new_right_level.rootNode = ninethnode(level.rootNode)
clearleftnode = fifthnode(level.rootNode)
clearrightnode = seventhnode(level.rootNode)
new_root = sixthnode(level.rootNode)
new_root.left = None
new_root.right = None
clearleftnode.right = None
clearrightnode.left = None
if parent_level is None or parent_level.size >= 10:
# Make a new level and put root in it
new_root_level = KAryLevel()
new_root_level.rootNode = new_root
new_root_level.size = 1
new_root_level.isLeaf = False
new_root.left_level = new_left_level
new_root.right_level = new_right_level
return (None, None, None, new_root_level)
else:
return (new_root, new_left_level, new_right_level, None)
# Otherwise the new root gets added to the parent
# No rebalance needed here, search through rest of the tree
else:
search_node = leftmostnode(level.rootNode)
(insert, new_left, new_right, new_level) = rebalance(level, search_node.left_level)
search_node.left_level = new_level
if insert is not None:
insert_between_nodes(search_node.left, search_node, insert)
search_node.left_level = new_left
search_node.right_level = new_right
return
while search_node != level.rootNode:
search_node = search_node.r
(insert, new_left, new_right, new_level) = rebalance(level, search_node.right_level)
search_node.left_level = new_level
if insert is not None:
insert_between_nodes(search_node, search_node.right, insert)
search_node.right_level = new_left
insert.right_level = new_right
return (None, None, None, level)
search_node = search_node.right
while search_node.right != None:
(insert, new_left, new_right, new_level) = rebalance(level, search_node.left_level)
if insert is not None:
insert_between_nodes(search_node.left, search_node, insert)
search_node.left_level = new_left
insert.left_level = new_right
return (None, None, None, level)
search_node = search_node.right
(insert, new_left, new_right, new_level) = rebalance(level, search_node.left_level)
if insert is not None:
if insert is not None:
insert_between_nodes(search_node.left, search_node, insert)
search_node.left_level = new_left
insert.left_level = new_right
return (None, None, None, level)
(insert, new_left, new_right, new_level) = rebalance(level, search_node.right_level)
if insert is not None:
insert_between_nodes(search_node, search_node.right, insert)
insert.left_level = new_left
insert.right_level = new_right
return (None, None, None, level)
# ( Data to compare, new node, data added to this level, level added)
def _traverse_insert_node(node, encoding, val, right_of_root, is_leaf):
#print("Node")
if encoding == []:
if node is None:
# Add node
print("Adding node with value: " + str(val) + " to our level")
return (None, KAryNode(val, right_of_root), True, False)
else:
if val == node.data:
#Found the data
return (None, node, False, False)
else:
# Need to decrypt data at this node to continue
return (node.data, node, False, False)
else:
if node is None:
raise ValueError("Encoding points beyond this tree")
# Search the left branch
elif encoding[0] == 0:
# Left edge of level
if node.left is None and not is_leaf:
(out_data, new_level) = _traverse_insert_level(node.left_level, encoding[1:], val)
node.left_level = new_level
return (out_data, node, False, True)
# Left of root stay on this level
if not right_of_root:
(out_data, new_node, data_added, level_added) = _traverse_insert_node(node.left, encoding[1:], val, right_of_root, is_leaf)
node.left = new_node
return (out_data, node, data_added, level_added)
# Right of root go down left child level
if right_of_root:
(out_data, new_level) = _traverse_insert_level(node.left_level, encoding[1:], val)
node.left_level = new_level
return (out_data, node, False, True)
# Search the right branch
else:
# Right edge of level
if node.right is None and not is_leaf:
(out_data, new_level) = _traverse_insert_level(node.right_level, encoding[1:], val)
node.right_level = new_level
return (out_data, node, False, True)
# Right of root stay on this level
if right_of_root:
print("We are staying on this level moving right ")
(out_data, new_node, data_added, level_added) = _traverse_insert_node(node.right, encoding[1:], val, right_of_root, is_leaf)
node.right = new_node
return (out_data, node, data_added, level_added)
# Left of root go down right child level
if not right_of_root:
print("We are going down a level because we are left of the root")
(out_data, new_level) = _traverse_insert_level(node.right_level, encoding[1:], val)
node.right_level = new_level
return (out_data, node, False, True)
# (Data to compare, new level)
def _traverse_insert_level(level, encoding, val):
#print("level")
if encoding == []:
#print("Enc []")
if level is None:
level = KAryLevel()
level.rootNode = KAryNode(val, False)
level.size += 1
return (None, level)
node = level.rootNode
if val == node.data:
# Found the value
return (None, level)
else:
# Need to decrypt data at this node to continue traversal
return (node.data, level)
else:
if level is None:
raise ValueError("Encoding points beyond tree")
#Traverse the next level
# Search to the left
node = level.rootNode
if encoding[0]==0:
#print("Enc 0")
# Case where root is left end
if node.left is None and not level.isLeaf:
(out_data, new_level) = _traverse_insert_level(node.left_level, encoding[1:], val)
node.left_level = new_level
level.isLeaf = False
return (out_data, level)
(out_data, new_node, data_added, level_added) = _traverse_insert_node(node.left, encoding[1:], val, False, level.isLeaf)
node.left = new_node
new_node.right = node
if level_added:
level.isLeaf = False
if data_added:
level.size += 1
return (out_data, level)
# Search to the right
else:
#print("Enc 1")
# Case where root is right end
if node.right is None and not level.isLeaf:
(out_data, new_level) = _traverse_insert_level(node.right_level, encoding[1:], val)
node.right_level = new_level
level.isLeaf = False
return (out_data, level)
print("traversing nodes at this level")
(out_data, new_node, data_added, level_added) = _traverse_insert_node(node.right, encoding[1:], val, True, level.isLeaf)
node.right = new_node
new_node.left = node
if level_added:
level.isLeaf = False
if data_added:
level.size += 1
return (out_data, level)
def traverse_insert(ktree, encoding, val):
if ktree is None:
print("Starting up")
return (None, KAryTree(val), False)
print(ktree.root)
data, new_top_level = _traverse_insert_level(ktree.root, encoding, val)
ktree.root = rebalance(None, new_top_level)[3]
return data, ktree, True
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# Hyper parameters
step_size = 0.01 # How much should the network weights change in case of a wrong prediction?
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# Construct network graph according to given parameters
#nn.Affine(#Inputs,#Outputs)
self.fc1 = nn.Linear(input_size,120)
self.fc2 = nn.Linear(120,84)
self.fc3 = nn.Linear(84,10)
def forward(self,x):
# Forward pass through network
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Create Network object to pass data to
net = Net()
input_to_network = torch.randn(1, 32)
# Get target values
target = torch.randn(10) # a dummy target, for example
target = target.view(1, -1) # make it the same shape as output
# Network paramaters for gradient computation
criterion = nn.MSELoss() # Define loss criteron
optimizer = torch.optim.SGD(net.parameters(),
step_size) # Optimizer selection
for i in range(iterations):
'''
Steps:
- Set gradient of all layers to be 0
- Compute prediction on given inputs by forward pass through the network
- Calculate loss between predictions and truth values
- Calculate gradients for all layers with backpropagation
- Change values of weights in layers according to optimizer and step size
'''
net.zero_grad()
output = net(input_to_network)
loss = criterion(output, target)
loss.backward()
optimizer.step()
# END OF CODE -----------------------------------------------------------------
# Ways to update weights :
# Explicitly
def update(net):
for f in net.parameters():
f.data.sub_(f.grad.data*step_size)
# Using package
optimizer = optim.SGD(net.parameters(),step_size)
|
# TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(i+1, len(arr)):
if arr[j] < arr[cur_index]:
cur_index = j
arr[i], arr[cur_index] = arr[cur_index], arr[i]
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n - 1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n - i - 1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
# Your code here
return arr
|
"""
Provides class for checking if a bot is shadow banned
"""
try:
from urllib.request import urlopen
from urllib.error import HTTPError
except:
from urllib2 import urlopen
from urllib2 import HTTPError
from .utils import ColoredOutput
import os
class Shadow(object):
"""
Class providing methods for checking is a user is shadow banned
"""
def __init__(self):
"""
Initializes instance.
"""
pass
def check_user(self, username):
"""
Checks if username is shadowbanned or non-existant
:param str username: Username to check
:return: False if not banned, True if banned
:rtype: bool
"""
while True:
try:
r = urlopen('https://www.reddit.com/u/{}'.format(username)).read()
return False
except HTTPError as e:
if e.code == 404:
return True
elif e.code == 429:
continue
else:
print(e)
continue
|
def missingel(slist):
# returns the missing element of a sorted list
# considering mini and maxi variables, we fix the "front and back seats" issue
mini = slist[0]
maxi = slist[-1]
for i in range(mini, maxi):
if not (i in slist):
return i
# this should not be reached
return(-1)
def getid(board):
# returns a boarding pass's id
# we separate the two components
row = board[:-3]
col = board[-3:]
# we replace the letters with binary digits
row = row.replace('F', '0')
row = row.replace('B', '1')
col = col.replace('L', '0')
col = col.replace('R', '1')
# now we simply convert them
irow = int(row, 2)
icol = int(col, 2)
return(8*irow + icol)
with open("input.txt", "r") as f:
lines = f.readlines()
# c stands for "clean" as we get rid of the '\n' character
clines = [l.split('\n')[0] for l in lines]
# we build the list of the ids and then we sort it
id = [getid(l) for l in clines]
sortedid = sorted(id)
print(missingel(sortedid))
|
#SLOT: 4
#Write a program to find the nth value in the series.
#Problem description
#here position starts at ( 0,0 ) and it will move in the direction right, top, left , bottom at the multiples of 10 .
#( consider a graph with origin and directions as x, y, -x, -y on moving in x, y it will be positive term and in -x
#and - y it will be in negative terms )
#Example-1
#Input: 1
#Expected Output: (10,0)
#Example-2
#Input: 4
#Expected Output: (-20 , -20 )
#Example-3
#Input: 3
#Expected Output: (-20 , 20 )
#PROGRAM IN python :
def find(num):
x,y = 0,0
for i in range(num):
rem = i%4
if (rem == 0):
x = x + 10*(i+1);
elif (rem == 1):
y = y + 10*(i+1);
elif (rem == 2):
x = x - 10*(i+1);
elif (rem == 3):
y = y - 10*(i+1);
print(x,",",y )
number = input()
find(int(number))
|
list1 = [10, 20, 30, 40, 51, 55, 20, 32, 521, 45, 84, 54, 65, 625]
list2 = [10, 20, 30, 40, 51, 55, 20, 32, 521, 45, 84, 54, 65, 740]
# bubble sort
def bubble_sort(lister):
for i in range(len(lister) - 1):
for j in range(len(lister) - i - 1):
if lister[j] > lister[j + 1]:
lister[j], lister[j + 1] = lister[j + 1], lister[j]
# selection sort
def selection_sort(array):
for i in range(len(array)):
min_index = i
for j in range(i + 1, len(array)):
if array[min_index] > array[j]:
min_index = j
array[i], array[min_index] = array[min_index], array[i]
# to print top 5 scores from list
def top5(iterable):
print("Top 5 scores are :")
for i in range(1, 6):
print(iterable[0 - i], end=" ")
print()
bubble_sort(list1)
selection_sort(list2)
top5(list1)
top5(list2)
Top 5 scores are :
625 521 84 65 55
Top 5 scores are :
740 521 84 65 55
|
__author__ = 'asdis'
from random import *
from ascending import *
from descending import *
table = []
for i in range (0, 50):
table.append(randrange(0, 99))
print (table)
choice = int(input("wybierz sortowanie rosnace (1) lub malejace (2): "))
if choice == 1:
print (ascending(table))
elif choice == 2:
print(descending(table))
else:
print("You've chosen wrong number")
|
import sys
# Defining the Grader class
class Grader:
# Creating the constructor
def __init__(self):
# Getting the user data from the command line in the constructor
self.name = raw_input("What is your name? ")
self.assignment_name = raw_input("What is the name of your assignment? ")
self.grade = float(raw_input("What was your grade in " + self.assignment_name + "? "))
# Determine the users letter grade based on the grade they entered
def getGrade(self):
letter_grade = ''
if self.grade < 60:
letter_grade = 'F'
elif self.grade < 70:
letter_grade = 'D'
elif self.grade < 80:
letter_grade = 'C'
elif self.grade < 90:
letter_grade = 'B'
else:
letter_grade = 'A'
return letter_grade
# Instantiate the Grader class
myGrade = Grader()
# Display the letter grade for the user
print("Your letter grade in " + myGrade.assignment_name + " was a(n) " + myGrade.getGrade())
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
visited=dict()
def getneighbours(edgelist,v):
for key in edgelist[v]:
yield key
def dfs(graph,start):
count=0
stack=list()
stack.append(start)
while len(stack)!=0:
v=stack.pop()
if not visited.has_key(v):
count=count+lst[v-1]
visited[v]=True
for vx in getneighbours(graph,v):
if not visited.has_key(vx):
stack.append(vx)
return count
N=int(raw_input().strip().split(" "))
lst=[int(i) for i in raw_input().strip().split(" ")]
total=0
for i in lst:
total=total+i
edgelist=dict()
edges=list()
for i in range(N):
(key,value)=(int(k) for k in raw_input().strip().split(" "))
edges.append((key,value))
if edgelist.has_key(key):
edgelist[key].append(value)
else:
edgelist[key]=[value]
print dfs(edgelist,1) |
# Python3 implementation of program to count
# minimum number of steps required to measure
# d litre water using jugs of m liters and n
# liters capacity.
def gcd(a, b):
if b==0:
return a
return gcd(b, a%b)
''' fromCap -- Capacity of jug from which
water is poured
toCap -- Capacity of jug to which
water is poured
d -- Amount to be measured '''
def Pour(toJugCap, fromJugCap, d):
# Initialize current amount of water
# in source and destination jugs
fromJug = fromJugCap
toJug = 0
# Initialize steps required
step = 1
while ((fromJug is not d) and (toJug is not d)):
# Find the maximum amount that can be
# poured
temp = min(fromJug, toJugCap-toJug)
# Pour 'temp' liter from 'fromJug' to 'toJug'
toJug = toJug + temp
fromJug = fromJug - temp
step = step + 1
if ((fromJug == d) or (toJug == d)):
break
# If first jug becomes empty, fill it
if fromJug == 0:
fromJug = fromJugCap
step = step + 1
# If second jug becomes full, empty it
if toJug == toJugCap:
toJug = 0
step = step + 1
return step
# Returns count of minimum steps needed to
# measure d liter
def minSteps(n, m, d):
if m> n:
temp = m
m = n
n = temp
if (d%(gcd(n,m)) is not 0):
return -1
# Return minimum two cases:
# a) Water of n liter jug is poured into
# m liter jug
return(min(Pour(n,m,d), Pour(m,n,d)))
# Driver code
if __name__ == '__main__':
n = 12
m = 11
d = 2
print('Minimum number of steps required is',minSteps(n, m, d))
|
#list program
list1 = ['physics', 'chemistry', 'maths', 'science', 'social', 'zoology', 'geography', 'botany', 'computer science','economics'];
print(list1)
#perform slicing
list1[1:4]
#perform repeatition using * operator
newlist = [list1] * 2
#concatenate two list
new = list1+newlist |
I)
#program to check prime or not
num = int(input("Enter a number to check prime or not: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
II)
#program to print between 1 to n prime numbers
r=int(input("Enter the limit: "))
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a) |
"""
面试题15:二进制中1的个数
题目:请实现一个函数,输入一个整数,输出该数二进制表示中1的个数。例如
把9表示成二进制是1001,有2位是1。因此如果输入9,该函数输出2
"""
def num_of_1(n):
ret = 0
while n:
ret += 1
n = n & n-1
return ret
if __name__ == '__main__':
print(num_of_1(12)) |
'''
题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个
格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路
径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含
"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
'''
from numpy import *
import numpy as np
#主函数
def has_path(matrix,rows,cols,s):
# visited=array()
path_length=0
#visited是大小与str_matrix相同的矩阵,用来记录矩阵中已经访问过得节点
visited=np.zeros((3, 4))
for row in range(rows):
for col in range(cols):
if has_core(matrix,rows,cols,row,col,path_length,s,visited):
return True
else:
return False
#判断矩阵的坐标是否等于字符串对应的索引值
def has_core(matrix,rows,cols,row,col,path_length,s,visited):
if path_length>= len(s):
return True
#是存路径
is_has_path=False
#如果存在对应坐标
if row>=0 and row<rows and col>=0 and col<cols and matrix[row][col]==s[path_length] and not visited[row][col]:
# 路径前进一步
path_length+=1
#坐标标记为已经访问过
visited[row][col]=True
is_has_path= has_core(matrix,rows,cols,row,col-1,path_length,s,visited) or\
has_core(matrix,rows,cols,row,col+1,path_length,s,visited) or \
has_core(matrix,rows,cols,row+1,col,path_length,s,visited) or \
has_core(matrix,rows,cols,row-1,col,path_length,s,visited)
#如果不存在路径,返回上一坐标,并将visited中对应坐标指为未访问状态
if not is_has_path:
path_length-=1
visited[row][col] = False
return is_has_path
if __name__ == '__main__':
# 生成矩阵
str_matrix = array([['a', 'b', 't', 'g'], ['c', 'f', 'c', 's'], ['j', 'd', 'e', 'h']])
# str_matrix = array([['a', 'b', 't', 'g'], ['b', 'f', 'c', 's'], ['j', 'd', 'e', 'h']])
# 矩阵的行数
rows = str_matrix.shape[0]
# 矩阵列数
cols = str_matrix.shape[1]
# print(has_path(str_matrix, rows, cols, 'abjdfb'))
print(has_path(str_matrix, rows, cols, 'acjdfb'))
|
def printEmployes(empList):
print "There are {0} employees".format(len(empList))
for emp in empList:
print emp
employees = [
"Mac", "Yasmin", "Gail", "Linda", "Doug", "Trevor", "Kalvin", "Susan"
]
while True:
printEmployes(employees)
remove = raw_input("Who do you wanna remove?")
if remove in employees:
employees.remove(remove)
print "Removed {0}".format((remove));
else:
print "Couldn't find them"
|
def namesFilledIn(name):
if len(name) == 0:
return False
return True
def namesAtLeast2(name):
if len(name) < 2:
return False
return True
def validID(ID):
length = len(ID)
if length != 7:
print "ID Not the right length"
return False
if "-" not in ID:
print "No hyphen in ID"
return False
split = ID.split('-')
left = split[0]
right = split[1]
if len(left) != 2:
print "left side of the hyphen isn't two long"
return False
if len(right) != 4:
print "right side of the hypen isn't 4 long"
return False
if not left.isalpha():
print "First two digits must be alpha"
return False
if not right.isdigit():
print "Last 4 digits must be digits"
return False
return True
def controller(first, last, zip, id):
if not namesFilledIn(first):
print "first name isnt filled in"
return
if not namesFilledIn(last):
print "last name isn't filled in"
return
if not namesAtLeast2(first):
print "first name isn't at least 2"
if not namesAtLeast2(last):
print "last name isn't at least 2"
if not validID(id):
return
print "It's clean"
print controller("", "", 0, "")
print controller("hi", "h", 0, "")
print controller("hi", "ha", 0, "hi1234")
print controller("hi", "ha", 0, "hi1-234")
print controller("hi", "ha", 0, "h1-1234")
print controller("hi", "ha", 0, "hi-1a34")
print controller("hi", "ha", 0, "hi-1234")
|
def main():
try:
f = open("C:/Users/Student 2/Documents/Assignment1.txt", "r")
print(f.read(1))
print(f.readline())
print(f.read())
f.close()
except:
print("Error opening file")
f2 = open("C:/Users/Student 2/Documents.txt", "r")
my_list = []
for line in f2:
my_list.append(line)
print(my_list)
f2.close()
f3 = open("C:/Users/Student 2/Documents.txt", "r")
my_list3 = []
for line in f3:
my_list3.append(line)
for a in range(0,b):
print(my_list3[a])
f3.close()
main()
|
first_name = str(input("Enter your name "))
current_balance = float(input("Enter your current balance in the bank account: "))
deposited_amount = float(input("Enter the deposited amount: $"))
total = current_balance + deposited_amount
print (first_name, total "${0.2f}.format(total))
|
# Based on: https://github.com/ageitgey/face_recognition/blob/master/examples/web_service_example.py
# This is a _very simple_ example of a web service that recognizes faces in uploaded images.
# Upload an image file and it will check if the image contains a known face.
# Pictures of known faces must be stored in the specific folder.
# The filename should be the name of the person.
# The result is returned as json. For example:
# {
# "status": "'OK' or 'ERROR'",
# "number_of_known_faces": "number",
# "face_found_in_image": "boolean",
# "number_faces_found_in_image": "number",
# "known_face_found_in_image": "boolean",
# "number_known_faces_found_in_image": "number",
# "persons_name": "list"
# }
# This example is based on the Flask file upload example: http://flask.pocoo.org/docs/0.12/patterns/fileuploads/
import face_recognition
from flask import Flask, jsonify, request, redirect
import os
# You can change this to any folder on your system
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
# Detect known faces
pictures_known_faces = os.listdir("./known_faces/")
known_face_encodings = []
known_persons = [] # list of names of known persons
for picture in pictures_known_faces:
file = "./known_faces/" + picture
known_persons.append(picture[0:picture.index('.')])
picture_loaded = face_recognition.load_image_file(file)
known_face_encoding = face_recognition.face_encodings(picture_loaded)[0]
known_face_encodings.append(known_face_encoding)
number_known_faces = len(known_face_encodings)
# Webserver
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_image():
# Check if a valid image file was uploaded
if request.method == 'POST':
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
# The image file seems valid! Detect faces and return the result.
return detect_faces_in_image(file)
# If no valid image file was uploaded, show the file upload form:
return '''
<!doctype html>
<title>Gesichtserkennung</title>
<h1>Lade ein Foto hoch und du erfährst, ob die Person dem System bekannt ist</h1>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
'''
# Face Recognition
def detect_faces_in_image(file_stream):
# Load the uploaded image file
img = face_recognition.load_image_file(file_stream)
# Get face encodings for any faces in the uploaded image
unknown_face_encodings = face_recognition.face_encodings(img)
# Initialize some variables
face_found = False
known_face_found = False
name_of_known_faces = []
number_known_faces_found = 0
number_faces_found = len(unknown_face_encodings)
if number_faces_found > 0:
face_found = True
if number_known_faces > 0:
if face_found:
# See if some faces in the uploaded image matches a known face
for unknown_face_encoding in unknown_face_encodings:
i = 0
for known_face_encoding in known_face_encodings:
match_results = face_recognition.compare_faces([known_face_encoding], unknown_face_encoding)
if match_results[0]:
known_face_found = True
name_of_known_faces.append(known_persons[i])
break
i += 1
if known_face_found:
number_known_faces_found = len(name_of_known_faces)
result = {
"status": "OK",
"number_of_known_faces": number_known_faces,
"face_found_in_image": face_found,
"number_faces_found_in_image": number_faces_found,
"known_face_found_in_image": known_face_found,
"number_known_faces_found_in_image": number_known_faces_found,
"persons_names": name_of_known_faces
}
else:
# folder with known faces is empty
result = {
"status": "ERROR",
"number_of_known_faces": number_known_faces,
"face_found_in_image": face_found,
"number_faces_found_in_image": number_faces_found
}
# Return the result as json
return jsonify(result)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5001, debug=True)
|
#!/usr/bin/env python3
from math import floor
def main():
vals = input().split()
carbon = int(vals[0])
hydrogen = int(vals[1])
oxygen = int(vals[2])
carbon_diox = 0.25 * (2 * oxygen - hydrogen)
glucose = (carbon - carbon_diox) / 6
water = -carbon + carbon_diox + hydrogen / 2
if water < 0 or carbon_diox < 0 or glucose < 0:
print('Error')
else:
print(floor(water), floor(carbon_diox), floor(glucose))
main()
|
#!/usr/bin/env python3
# Jonathan De Leon
# CSCI 531 Applied Cryptography
# April, 2021
import sys
import random
import math
import json
sys_random = random.SystemRandom()
# Default rounds to 40 due to following stack overflow
# https://stackoverflow.com/questions/6325576/how-many-iterations-of-rabin-miller-should-i-use-for-cryptographic-safe-primes
def miller_rabin_primality(number, rounds=40):
# Even numbers, other than 2 are composite
if number == 2:
return True
if not number & 1:
return False
k, exp = 0, number - 1
while not exp & 1: # exponent is not odd
k += 1
exp >>= 1 # bit-wise right shift - divide by 2
def check_primality(a, exp, k, n):
x = pow(a, exp, n) # a**exp % number
if x == 1:
return True
for i in range(k-1):
if x == n - 1:
return True
x = pow(x, 2, n)
return x == number - 1
for round in range(rounds):
a = sys_random.randrange(2, number - 1)
if not check_primality(a, exp, k, number):
return False
return True
def test_prime(number):
return miller_rabin_primality(number)
# use SystemRandom to generate a random number with x bits and test it for primeness
def generate_prime(bits):
found = False
while not found:
number = sys_random.randrange(2**(bits-1), 2**bits)
if test_prime(number):
found = True
return number
# find an `e` which is co-prime or relatively prime to phi
# Note: Two integers are co-prime if the only positive integer that divides them is 1
def find_coprime(phi, bits):
found = False
while not found:
e = sys_random.randrange(2**(bits-1), 2**bits)
if math.gcd(e, phi) == 1:
found = True
return e
# Adapted the extendended Euclidean algorithm for modular integers
# Note: not computing the Bezout coefficient
def extended_gcd(a, n):
d, new_d = 0, 1
r, new_r = n, a
while new_r != 0:
quotient = r // new_r
d, new_d = new_d, d - quotient * new_d
r, new_r = new_r, r - quotient * new_r
# to get a positive number
if d < 0:
d += n
return d
# find d such that e*d = 1 mod modulus
def compute_modular_inverse(e, modulus):
if math.gcd(e, modulus) != 1:
raise AssertionError('Modular inverse does not exist')
return extended_gcd(e, modulus)
def generate_keys(bits=1024):
print ('-'*20+' Generating p prime '+'-'*20)
p = generate_prime(bits)
# print ('p prime: %s' % p)
print ('-'*20+' Generating q prime '+'-'*20)
q = generate_prime(bits)
# print ('q prime: %s' % q)
n = p * q
print ('*'*20+' Computing keys '+'*'*20)
phi = (p-1) * (q-1)
e = find_coprime(phi, bits)
# print ('e prime: %s' % e)
d = compute_modular_inverse(e, phi)
# print ('e mod inverse: %s' % d)
public_key = { 'e': e, 'n': n }
private_key = { 'd': d, 'n': n }
return (public_key, private_key)
if __name__ == "__main__":
public, private = generate_keys()
# print('Public: %s' % str(public))
# print('Private: %s' % str(private))
if len(sys.argv) > 1:
user_name = sys.argv[1]
print('Creating output files', user_name + '.pub', user_name + '.prv')
with open(user_name + '.pub', 'w') as f:
f.write(json.dumps(public))
with open(user_name + '.prv', 'w') as f:
f.write(json.dumps(private)) |
'''
Linked List 의 장단점
장점은 배열처럼 정해진 데이터 공간을 할당하지 않아도 사용가능하다는 점
단점은 pointer 를 위한 별도의 주소 공간이 필요하기 때문에 저장공간의 효율 자체가 높은 편은 아니고,
연결된 주소 위치를 찾는데 있어서 접근 시간이 필요하므로 접근 속도가 늦어짐
또한 중간 노드 삭제시 연결을 재구성해야됨
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
node1 = Node(1)
node2 = Node(2)
node1.next = node2
head = node1
def add(data):
node = head
while node.next:
node = node.next
node.next = Node(data)
for i in range(3, 10):
add(i)
def printAll():
node = head
while node.next:
print(node.data)
node = node.next
print(node.data)
# 노드 중간에 데이터를 넣는 방법
node3 = Node(1.5) # 1 과 2 사이에 넣어보기 위한 값
node = head
Search = True
while Search:
if node.data == 1:
Search = False
else:
node = node.next
node_next = node.next
node.next = node3
node3.next = node_next
printAll()
|
'''
Insertion Sort
삽입 정렬은 Bubble Sort 나 Selection Sort 처럼
모두 자리를 바꾸는 형식이 아니라,
비교를 하려고 하는 현 위치 인덱스 이하의 인덱스들에 대한 원소들 비교를 수행해서
자신이 들어갈 위치를 선정해주는 정렬알고리즘
아래의 코드는 오름 차순 예시임
'''
def InsertionSort(data):
for i in range(len(data) - 1):
j = i
while(j >= 0 and data[j] > data[j + 1]):
temp = data[j + 1]
data[j + 1] = data[j]
data[j] = temp
j -= 1
print(data)
listA = [1, 10, 2, 3, 5, 6, 7, 8, 9, 4]
InsertionSort(listA)
|
'''
소수 찾기 코드
가장 기본적인 내용만을 사용한 파이썬 코드
(1과 자기 자신의 수 외의 수로 나눠지는 경우 소수가 아님을 활용하여
입력된 특정한 숫자 하나가 소수인지 아닌지 판별하는 단순한 코드)
'''
def FindPrime(x):
for i in range(2, x):
if(x % i == 0):
return False
return True
print(FindPrime(67))
|
"""
文本序列化
将文本转化成对应的张量才能进行处理
"""
class WordSequence():
UNK_TAG = "<UNK>"
PAD_TAG = "<PAD>"
# unk用来标记词典中未出现过的字符串
# pad用来对不到设置的规定长度句子进行数字填充
UNK = 0
PAD = 1
def __init__(self):
# self.dict用来对于词典中每种给一个对应的序号
self.dict = {
self.UNK_TAG: self.UNK,
self.PAD_TAG: self.PAD
}
# 统计每种单词的数量
self.count = {}
def fit(self,sentence):
"""
统计词频
:param sentence: 一个句子
:return:
"""
for word in sentence:
# 字典(Dictionary) get(key,default=None) 函数返回指定键的值,如果值不在字典中返回默认值
self.count[word] = self.count.get(word,0) + 1
def build_vocab(self,min_count=0,max_count=None,max_features=None):
"""
根据条件构建词典
:param min_count: 最小词频
:param max_count: 最大词频
:param max_features: 最大词语数
:return:
"""
if min_count is not None:
# items()函数以列表返回可遍历的(键,值)元组数组
self.count = {word:count for word,count in self.count.items() if count>=min_count}
if max_count is not None:
self.count = {word:count for word,count in self.count.items() if count<=max_count}
if max_features is not None:
# 排序
self.count = dict(sorted(self.count.items(),lambda x:x[-1],reverse=True)[:max_features])
for word in self.count:
self.dict[word] = len(self.dict)
# 把dict进行反转,就是键值和关键字进行反转
self.inverse_dict = dict(zip(self.dict.values(),self.dict.keys()))
def transform(self,sentence,max_len=None):
"""
把句子转化为数字序列
:param sentence: 句子
:param max_len: 句子最大长度
:return:
"""
if len(sentence) > max_len:
# 句子太长时进行截断
sentence = sentence[:max_len]
else:
# 句子长度不够标准长度时,进行填充
sentence = sentence + [self.PAD_TAG] * (max_len - len(sentence))
# 句子中的单词没有出现在词典中设置为数字0(self.UNK)
return [self.dict.get(word,self.UNK) for word in sentence]
def inverse_transform(self,incides):
"""
把数字序列转化为字符
:param incides: 数字序列
:return:
"""
return [self.inverse_dict.get(i,"<UNK>") for i in incides]
def __len__(self):
# 返回词典个数
return len(self.dict)
if __name__ == '__main__':
sentences = [
["今天","天气","很","好"],
["我们","出去","玩","网球"]
]
ws = WordSequence()
for sentence in sentences:
# 统计词频
ws.fit(sentence)
# 构建词典
ws.build_vocab(min_count=0)
print(ws.dict)
# 将一句话转化成数字序列表示
ret = ws.transform(["今天","我们","吃","很","好","的"],20)
print(ret)
|
"""
Cookie Clicker Simulator
"""
import simpleplot
import math
# Used to increase the timeout, if necessary
import codeskulptor
codeskulptor.set_timeout(20)
import poc_clicker_provided as provided
# Constants
SIM_TIME = 10000000000.0
#SIM_TIME = 10000.0
class ClickerState:
"""
Class to keep track of the game state.
"""
def __init__(self):
self._total_cookies = 0.0
self._current_cookies = 0.0
self._current_time = 0.0
self._current_cps = 1.0
self._history = [(0.0,None,0.0,0.0)]
def __str__(self):
"""
Returns human readable state
"""
return ("Total cookies: " + str(self._total_cookies)+
". \nCurrent cookies: " + str(self._current_cookies) +
". \nCurrent CPS: " + str(self._current_cps) +
". \nCurrent time: " + str(self._current_time))
def get_cookies(self):
"""
Returns current number of cookies
(not total number of cookies)
Should return a float
"""
return self._current_cookies
def get_cps(self):
"""
Gets current CPS
Should return a float
"""
return self._current_cps
def get_time(self):
"""
Gets current time
Should return a float
"""
return self._current_time
def get_history(self):
"""
Returns history list
a list of tuples of the form:
(time, item, cost of item, total cookies)
For example: [(0.0, None, 0.0, 0.0)]
Should return a copy of any internal data structures,
so that they will not be modified outside of the class.
"""
return list(self._history)
def time_until(self, cookies):
"""
Returns time until you have the given number of cookies
(could be 0.0 if you already have enough cookies)
Should return a float with no fractional part
"""
if self._current_cookies >= cookies:
return 0.0
cookies_left = cookies - self._current_cookies
return math.ceil(cookies_left/self._current_cps)
def wait(self, time):
"""
Waits for given amount of time and updates state
Should do nothing if time <= 0.0
"""
if time > 0.0:
self._current_time += time
self._total_cookies += time * self._current_cps
self._current_cookies += time * self._current_cps
def buy_item(self, item_name, cost, additional_cps):
"""
Buys an item and updates state
Should do nothing if you cannot afford the item
"""
if self._current_cookies >= cost:
self._current_cookies -= cost
self._current_cps += additional_cps
self._history.append((self._current_time, item_name, cost,self._total_cookies))
def simulate_clicker(build_info, duration, strategy):
"""
Function to run a Cookie Clicker game for the given
duration with the given strategy. Returns a ClickerState
object corresponding to the final state of the game.
"""
info = build_info.clone()
new_clicker = ClickerState()
while new_clicker.get_time() <= duration:
if new_clicker.get_time() > duration:
break
left_time = duration - new_clicker.get_time()
strateg_item = strategy (new_clicker.get_cookies(), new_clicker.get_cps(),
new_clicker.get_history(), left_time, info)
if strateg_item == None:
break
time_elapse = new_clicker.time_until(info.get_cost(strateg_item))
if time_elapse > left_time:
break
else:
new_clicker.wait(time_elapse)
while new_clicker.get_cookies() >= info.get_cost(strateg_item):
new_clicker.buy_item(strateg_item, info.get_cost(strateg_item),
info.get_cps(strateg_item))
info.update_item(strateg_item)
new_clicker.wait(left_time)
return new_clicker
def strategy_cursor_broken(cookies, cps, history, time_left, build_info):
"""
Always pick Cursor!
This simplistic (and broken) strategy does not properly
check whether it can actually buy a Cursor in the time left.
"""
return "Cursor"
def strategy_none(cookies, cps, history, time_left, build_info):
"""
Always return None
This is a pointless strategy that will never buy anything, but
helps to debug simulate_clicker function.
"""
return None
def strategy_cheap(cookies, cps, history, time_left, build_info):
"""
Always buy the cheapest item you can afford in the time left.
"""
cookies += time_left * cps
cheapest_price = float('inf')
cheapest_item = None
for item in build_info.build_items():
cost_item = build_info.get_cost(item)
if (cost_item < cheapest_price) and (cost_item <= cookies):
cheapest_price = cost_item
cheapest_item = item
return cheapest_item
def strategy_expensive(cookies, cps, history, time_left, build_info):
"""
Always buy the most expensive item you can afford in the time left.
"""
cookies += time_left * cps
most_price = 0.0
items = build_info.build_items()
most_item = None
for item in items:
cost_item = build_info.get_cost(item)
if (cost_item <= cookies) and (cost_item > most_price) :
most_price = cost_item
most_item = item
return most_item
def strategy_best(cookies, cps, history, time_left, build_info):
"""
The best strategy.
"""
cookies += time_left * cps
best_ratio = 0.0
best_option = None
items = build_info.build_items()
for item in items:
cost_item = build_info.get_cost(item)
if cookies >= cost_item:
ratio = build_info.get_cps(item) / cost_item
if ratio > best_ratio:
best_ratio = ratio
best_option = item
return best_option
def run_strategy(strategy_name, time, strategy):
"""
Simulation for the given time with one strategy.
"""
state = simulate_clicker(provided.BuildInfo(), time, strategy)
print strategy_name, ":", state
# Plot total cookies over time
history = state.get_history()
print history
history = [(item[0], item[3]) for item in history]
simpleplot.plot_lines(strategy_name, 1000, 400, 'Time', 'Total Cookies', [history], True)
def run():
"""
Run the simulator.
"""
#run_strategy("Cursor", SIM_TIME, strategy_cursor_broken)
#run_strategy("Cheap", SIM_TIME, strategy_cheap)
#run_strategy("Expensive", SIM_TIME, strategy_expensive)
run_strategy("Best", SIM_TIME, strategy_best)
run()
|
"""
2.1 Write a Python program using function concept that maps list of words into a list of integers
representing the lengths of the corresponding words.
Hint: If a list [ ab,cde,erty] is passed on to the python function output should come as [2,3,4]
Here 2,3 and 4 are the lengths of the words in the list.
"""
def lengthOfWords(bagOfWords):
wordLengthList = [len(word) for word in bagOfWords]
return wordLengthList
print(lengthOfWords(['Betty', 'bought', 'some', 'butter']))
|
try:
print('try...')
r = 10 / 2
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
except ValueError as e:
print('ValueError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
import logging
def foo(s):
return 1 / int(s)
def bar(s):
return foo(s) * 2
def main():
try:
bar(2)
except Exception as e:
logging.exception(e)
main()
print('END')
class FooError(ValueError):
pass
def foo1(s):
n = int(s)
if n == 0:
raise FooError('invalid value: %s' % s)
return 10 / n
foo1('0')
def foo2(s):
n = int(s)
if n == 0:
raise ValueError('invalid value : %s' % s)
return 10 / n
def bar2():
try:
foo2('0')
except ValueError as e:
print('ValueError!')
raise
bar2() |
#1
# def foo(s):
# n = int(s)
# assert n != 0, 'n is zero'
# return 10 / n
#
# def main():
# foo('0')
#
# main()
# 2
# import logging
# logging.basicConfig(level=logging.INFO)
# s = '0'
# n = int(s)
# logging.info('n = %d' % n)
# print(10 / n)
#3
import pdb
s= '0'
n = int(s)
pdb.set_trace()
print(10 / n)
|
# merge sort algorithm
# divide and conquer algorithm, once broken down, compares indexes and merges back into one array
# recursive function, calls itself to keep dividing itself till size becomes one
def merge_sort(arr): # this whole chunk breaks down the array
if len(arr) > 1:
# finds the mid of the array
mid = len(arr) // 2
# break the list into 2 halves
left = arr[:mid]
right = arr[mid:]
# calling itself to divide even further
left = merge_sort(left)
right = merge_sort(right)
arr = []
# copying data to temp arrays
while len(left) > 0 and len(right) > 0:
# checking if left index is smaller, if it is I want to remove from original array and place it as the
# first thing on my new array
if left[0] < right[0]:
arr.append(left[0])
left.pop(0)
else:
# if the right index was smaller
arr.append(right[0])
right.pop(0)
# forming the array with a for loop by iterating it
for i in left:
arr.append(i)
for i in right:
arr.append(i)
return arr
# Input list
a = [12, 11, 13, 5, 6, 7]
print("Given array is")
print(*a)
a = merge_sort(a)
# Print output
print("Sorted array is : ")
print(*a)
|
# 一些乱七八糟的函数与库
from itertools import combinations
from itertools import permutations
import csv
def output(A):
'''
输出矩阵
'''
for i in range(len(A)):
for j in range(len(A[i])):
print(A[i][j], end = ' ')
print('\n')
for i in range((len(A[0])-1)*5+1):
print('-', end = '')
print('\n')
return None
def inpt(file):
'''
file is the name of the inputed csv file
'''
C = []
# 从文件中读取数据
with open(file) as c_file:
c_reader = csv.reader(c_file, delimiter = ' ')
for row in c_reader:
C.append(row)
for i in range(len(C)):
for j in range(len(C[i])):
C[i][j] = int(C[i][j])
return C
def assign(i, S, I, O):
'''
输入 assignment S 和个体,返回在该分配下,他所分配的物品
如果一个人分配到了多个物品,返回效用最高的那个
返回零代表该分配下他什么都没得到
'''
if not i in I:
print('player is out of range')
return None
A = []
for a in O:
if S[i-1][a-1]:
A.append(a)
if not len(A):
return 0
elif len(A)==1:
return A[0]
else:
t = A[0]
for a in A:
if P_c(i, a, t):
t = a
return t
def R_c(i, a, b, P):
'''
判断对i来说,是否偏好a
'''
if a>0:
ua = P[i-1][a-1]
else:
ua = 0
if b>0:
ub = P[i-1][b-1]
else:
ub = 0
if ua>=ub:
return True
else:
return False
def P_c(i, a, b, P):
'''
判断对i来说,是否严格偏好a
'''
if a>0:
ua = P[i-1][a-1]
else:
ua = 0
if b>0:
ub = P[i-1][b-1]
else:
ub = 0
if ua>ub:
return True
else:
return False
def private_own(coalition, Omega, I, O):
'''
输入所有权结构/分配
返回物品集(在该所有权结构/分配下被该集团完全所有的物品)
'''
A = []
for a in O:
k = 1
for i in I:
if Omega[i-1][a-1] and not (i in coalition):
k = 0
break
if k:
A.append(a)
return A
def transpose(A):
'''
transpose a matrix
'''
n = len(A)
m = len(A[0])
ans = empty(m, n)
for i in range(m):
for j in range(n):
ans[i][j] = A[j][i]
return ans
def empty(n, m):
'''
创建 n*m 的零矩阵
'''
A = []
for i in range (n):
A.append([])
for j in range(m):
A[i].append(0)
return A
def inverse(mu, object_set, I):
'''
返回物品集涉及的所有人(集合)
'''
peop = []
for a in object_set:
for i in I:
if mu[i-1][a-1]:
peop.append(i)
return peop
def ext_private_own(coalition, mu, C, I, O):
coal = []
coal.append(set(coalition))
coal_j = coal[0]
coal_k = coal[0]|set(inverse(mu, private_own(coal[0], C,I,O),I))
while coal_j!=coal_k:
coal.append(coal_k)
coal_j = coal_k
coal_k = coal[-1]|set(inverse(mu, private_own(coal[-1], C,I,O),I))
return list(coal[-1])
def check_example(mu, C, P):
print('\nCheck:')
if if_in_strong_core(mu, C, P):
print('s', end=' ')
if if_in_weak_core(mu, C, P):
print('w', end=' ')
if if_in_effective_core(mu, C, P):
print('e', end=' ')
if if_in_direct_exclusion_core(mu, C, P):
print('dex', end=' ')
if if_in_exclusion_core(mu, C, P):
print('idex', end=' ')
return None
def weakly_block(coalition, M, S, C, P, I, O):
'''
check is assignment Mu is weakly blocked by coalition via Sigma
'''
k1 = 1
k2 = 0
for i in coalition:
if not R_c(i, assign(i, S, I, O), assign(i, M, I, O), P):
k1 = 0
for i in coalition:
if P_c(i, assign(i, S, I, O), assign(i, M, I, O), P):
k2 = 1
k3 = 0
if set(private_own(coalition, S, I, O))<=set(private_own(coalition, C, I, O)):
k3 = 1
if k1 and k2 and k3:
return True
else:
return False
def if_in_strong_core(mu, C, P, detail = False):
n_player = len(C)
I = []
for i in range(n_player):
I.append(i+1)
n_object = len(C[0])
O = []
for a in range(n_object):
O.append(a+1)
# check if the strong core is empty
# 对coalition进行组合
COALITION = []
for popu in range(1, n_player):
for coalition in combinations(I, popu+1):
COALITION.append(list(coalition))
ans = True
T_list = []
I_plus = [0]+I
for i in I_plus:
T = []
for j in I:
if j==i:
T.append(1)
else:
T.append(0)
T_list.append(T)
for TT in permutations(T_list, len(O)):
T = transpose(list(TT))
for coalition in COALITION:
if weakly_block(coalition, mu, T, C, P, I, O):
if detail:
print('Coalition: '+str(coalition)+'\n')
output(T)
ans = False
return ans
def strongly_block(coalition, M, S, C, P, I, O):
'''
check is assignment Mu is strongly blocked by coalition via Sigma
'''
k1 = 1
for i in coalition:
if not P_c(i, assign(i, S, I, O), assign(i, M, I, O), P):
k1 = 0
k3 = 0
if set(private_own(coalition, S, I, O))<=set(private_own(coalition, C, I, O)):
k3 = 1
if k1 and k3:
return True
else:
return False
def if_in_weak_core(mu, C, P, detail = False):
n_player = len(C)
I = []
for i in range(n_player):
I.append(i+1)
n_object = len(C[0])
O = []
for a in range(n_object):
O.append(a+1)
# check if the strong core is empty
# 对coalition进行组合
COALITION = []
for popu in range(1, n_player):
for coalition in combinations(I, popu+1):
COALITION.append(list(coalition))
ans = True
T_list = []
I_plus = [0]+I
for i in I_plus:
T = []
for j in I:
if j==i:
T.append(1)
else:
T.append(0)
T_list.append(T)
for TT in permutations(T_list, len(O)):
T = transpose(list(TT))
for coalition in COALITION:
if strongly_block(coalition, mu, T, C, P, I, O):
if detail:
print('Coalition: '+str(coalition)+'\n')
output(T)
ans = False
return ans
def effectively_block(coalition, mu, sigma, C, P, I, O):
'''
coalition effectively blocks mu via sigma
'''
# 集团中所有人都不变差
k1 = 1
for i in coalition:
if not R_c(i, assign(i, sigma, I, O), assign(i, mu, I, O), P):
k1 = 0
# 集团中有人严格变好
k2 = 0
for i in coalition:
if P_c(i, assign(i, sigma, I, O), assign(i, mu, I, O), P):
k2 = 1
# 进行的是集团内部分配
k3 = 0
if set(private_own(coalition, sigma, I, O))<=set(private_own(coalition, C, I, O)):
k3 = 1
# 新要求
k4 = 1
# 这里要加入新的判定条件
for popu in range(len(coalition)):
for coal in combinations(coalition, popu+1):
coal = list(coal)
if set(private_own(coal, sigma, I, O))<=set(private_own(coal, C, I, O)):
obj = set(private_own(coal, C, I, O))-set(private_own(coal, sigma, I, O))
if len(obj):
for a in obj:
if a in private_own(coalition, sigma, I, O):
k4 = 0
if coalition == I:
k4 = 1
if k1 and k2 and k3 and k4:
return True
else:
return False
def if_in_effective_core(mu, C, P, detail = False):
n_player = len(C)
I = []
for i in range(n_player):
I.append(i+1)
n_object = len(C[0])
O = []
for a in range(n_object):
O.append(a+1)
# check if the strong core is empty
# 对coalition进行组合
COALITION = []
for popu in range(1, n_player):
for coalition in combinations(I, popu+1):
COALITION.append(list(coalition))
ans = True
T_list = []
I_plus = [0]+I
for i in I_plus:
T = []
for j in I:
if j==i:
T.append(1)
else:
T.append(0)
T_list.append(T)
for TT in permutations(T_list, len(O)):
T = transpose(list(TT))
for coalition in COALITION:
if effectively_block(coalition, mu, T, C, P, I, O):
if detail:
print('Coalition: '+str(coalition)+'\n')
output(T)
ans = False
return ans
def directly_exclusion_block(coalition, M, S,C,P,I,O):
k1 = 1
for i in coalition:
if not P_c(i, assign(i, S,I,O), assign(i, M,I,O),P):
k1 = 0
k2 = 1
for j in I:
if P_c(i, assign(i, M,I,O), assign(i, S,I,O),P) and not (assign(i, M,I,O) in private_own(coalition, C,I,O)):
k2 = 0
if k1 and k2:
return True
else:
return False
def if_in_direct_exclusion_core(mu,C,P, detail = False):
n_player = len(C)
I = []
for i in range(n_player):
I.append(i+1)
n_object = len(C[0])
O = []
for a in range(n_object):
O.append(a+1)
# check if the strong core is empty
# 对coalition进行组合
COALITION = []
for popu in range(1, n_player):
for coalition in combinations(I, popu+1):
COALITION.append(list(coalition))
ans = True
T_list = []
I_plus = [0]+I
for i in I_plus:
T = []
for j in I:
if j==i:
T.append(1)
else:
T.append(0)
T_list.append(T)
for TT in permutations(T_list, len(O)):
T = transpose(list(TT))
for coalition in COALITION:
if directly_exclusion_block(coalition, mu, T,C,P,I,O):
if detail:
print('Coalition: '+str(coalition)+'\n')
output(T)
ans = False
return ans
def indirectly_exclusion_block(coalition, M, S,C,P,I,O):
k1 = 1
for i in coalition:
if not P_c(i, assign(i, S,I,O), assign(i, M,I,O),P):
k1 = 0
k2 = 1
for j in I:
if P_c(i, assign(i, M,I,O), assign(i, S,I,O),P) and not (assign(i, M,I,O) in ext_private_own(coalition, M, C,I,O)):
k2 = 0
if k1 and k2:
return True
else:
return False
def if_in_exclusion_core(mu,C,P, detail = False):
n_player = len(C)
I = []
for i in range(n_player):
I.append(i+1)
n_object = len(C[0])
O = []
for a in range(n_object):
O.append(a+1)
# check if the strong core is empty
# 对coalition进行组合
COALITION = []
for popu in range(1, n_player):
for coalition in combinations(I, popu+1):
COALITION.append(list(coalition))
ans = True
T_list = []
I_plus = [0]+I
for i in I_plus:
T = []
for j in I:
if j==i:
T.append(1)
else:
T.append(0)
T_list.append(T)
for TT in permutations(T_list, len(O)):
T = transpose(list(TT))
for coalition in COALITION:
if indirectly_exclusion_block(coalition, mu, T,C,P,I,O):
if detail:
print('Coalition: '+str(coalition)+'\n')
output(T)
ans = False
return ans |
p = float(input('请输入税前月收入:'))
i = float(input('请输入五险一金:'))
def CalcOld():
threshold = 3500
pt = p - i - threshold
tax = 0
if pt > 0:
if pt > 80000:
tax = pt*0.45 - 13505
elif pt > 55000:
tax = pt*0.35 - 5505
elif pt > 35000:
tax = pt*0.3 - 2755
elif pt > 9000:
tax = pt*0.25 - 1005
elif pt > 4500:
tax = pt*0.2 - 555
elif pt > 1500:
tax = pt*0.1 - 105
else:
tax = pt*0.03
return tax
else:
return tax
def CalcNew():
threshold = 5000
pt = p - i - threshold
tax = 0
if pt > 0:
if pt > 80000:
tax = pt*0.45 - 15160
elif pt > 55000:
tax = pt*0.35 - 7160
elif pt > 35000:
tax = pt*0.3 - 4410
elif pt > 25000:
tax = pt*0.25 - 2660
elif pt > 12000:
tax = pt*0.2 - 1410
elif pt > 3000:
tax = pt*0.1 - 210
else:
tax = pt*0.03
return tax
else:
return tax
def main():
old = CalcOld()
new = CalcNew()
print(f'税前月收入:{p}')
print(f'五险一金:{i}')
print(f'旧税率应纳税:{old}元,税后收入:{p-i-old}元')
print(f'新税率应纳税:{new}元,税后收入:{p-i-new}元')
if __name__ == '__main__':
main()
input('按下回车退出程序')
|
__author__ = 'aferreiradominguez'
class Persoa:
"""Clase que definae unha persoa """
def __init__(self, nome):
self.nome = nome
def sauda(self):
print("Ola " + self.nome)
persona = Persoa("aaron")
persona.sauda()
class Oficio:
"""Clase que define oficio"""
def __init__(self, oficio):
self.oficio = oficio
def mostraOfi(self):
print("O oficio e: " + self.oficio)
class Traballador(Persoa, Oficio):
"""Herdanza multiple"""
def __init__(self, nome, oficio, soldo):
Persoa.__init__(self, nome)
Oficio.__init__(self, oficio)
self.soldo = soldo
"""chamamos ao metodo privado"""
self.__mostraDatos()
def mostraSoldo(self):
print("O soldo e: " + str(self.soldo))
"""Metodo privado"""
def __mostraDatos(self):
print("O soldo e: " + str(self.soldo) + " O nome e: " + self.nome + " O oficio e: " + str(self.oficio))
t = Traballador("Pepinho", "Canteiro", 1000)
t.sauda()
t.mostraOfi()
t.mostraSoldo()
"""chamamos ao metodo privado"""
t._Traballador__mostraDatos()
class Fecha(object):
def __init__(self):
self.__dia = 1
def getDia(self):
return self.__dia
def setDia(self, dia):
if dia > 0 and dia < 31:
self.__dia = dia
else:
print("error")
dia = property(getDia, setDia)
data = Fecha()
print(data.dia)
data.setDia(23)
print(data.getDia())
data.dia = 33
|
# -----------------------------------------------------START------------------------------------------------------------
# function initialised
def speedCheck(speed):
if 70 > speed:
print("OK")
print('\n')
else:
demPoint = (speed - 70) / 5
if demPoint > 12:
print("LICENSE SUSPENDED!!")
print("You overspeeded! The demerit points are: ",demPoint)
print('\n')
elif 12 >= demPoint >= 10:
print("WARNING!! your license is on verge to get suspended!")
print("The total number of demerit points are: ",demPoint)
print('\n')
else:
print("The total number of demerit points are: ",demPoint)
print('\n')
# ----------------------------------------------------------------------------------------------------------------------
# input speed
n = int(input("enter the times you want to enter the data\n"))
for i in range(0,n,1):
speed = int(input("Enter the speed\n"))
speedCheck(speed)
# -------------------------------------------------END------------------------------------------------------------------
|
# ------------------------------------------------------START-----------------------------------------------------------
# string user-initialised
inputStrng = input("Enter the string\n")
# string length
strngLen = len(inputStrng)
# values initialised
wordCount = 1
# logic
for i in range(0,strngLen,1):
if inputStrng[i] == " ":
wordCount = wordCount + 1
elif inputStrng[i] == '\0':
break
else:
continue
# printing data according to user-initialised string
print("The number of words in the entered string is : ",wordCount)
# ------------------------------------------------------END-------------------------------------------------------------
|
name = ('mudit','deepak','riya','rahul','mudit')
# tuple initiated
print(name)
# tuples are immutable whereas lists are mutable
# counting function
total = name.count('mudit')
# count() will count the data in the tuple
print("total count of mudit in the tuple :",total)
# converting tuple into list
lname = list(name)
print(lname)
# length function
length = len(name)
# len() will print the length of the tuple
print(length)
# index function
x = name.index('riya')
# index() will tell the index of the data
print(x)
lst = [1,2,3,4,5,6] # list initiated
print(lst)
# converting list into tuple
tname = tuple(lst)
# list is converted to tuple
print(tname)
|
import numpy as np
from module import Module
class Linear(Module):
"""
Linear layer, including activation.
function F: R^n => R^p
"""
def __init__(self, in_dim, out_dim, activation: Module = None):
"""
W size (n, p)
b size (p,)
:param in_dim = n
:param out_dim = p
"""
self.W = np.random.randn(in_dim, out_dim)
self.b = np.random.randn(out_dim, 1)
self.activation = activation
self.X = None
self.forward_res = None
def forward(self, X):
"""
Linear layer
:param X: (n, m), n - in channels of the layer, m - batch-size
:return: return tensor size (p, m), p - out_dim, m - batch size
"""
self.X = X
self.forward_res = self.W.T @ X + self.b # (p,n) * (n, m) => (p, m)
return self.activation.forward(self.forward_res) if self.activation is not None else self.forward_res
def backward(self, v):
"""
Computing the gradient of the layer multiplied by v
Restricted to "forward" first.
:param dx = v[0]: size (p, m), where: p - out dim of the layer , m - batch size
:param dw = v[1]: size (n, m), where: n - in dim of the layer , m - batch size
:param db = v[2]: size (p, 1), where: p - out dim of the layer
:return: dx, dw, db
"""
# Our forward definition is W.T * X + b.
m = v[0].shape[1]
res = self.activation.backward(self.forward_res) if self.activation is not None else 1
res = res * v[0] # element-wise, res size (p, m)
dx = self.W @ res # (n, p) x (p, m) => (n, m)
dw = self.X @ res.T # (n, m) x (m, p) => (n, p)
db = (np.sum(res, axis=1) / m).reshape(len(self.b), 1) # average over all batch
if self.activation is None:
db = (np.sum(res, axis=1)).reshape(len(self.b), 1)
return dx, dw, db
def parameters(self):
"""
Returns all the parameters in the layer
:return:
"""
return [self.W, self.b]
|
mylist = ["A", "B", "C"]
copied_list_1 = mylist
copied_list_2 = mylist.copy()
mylist = ["A", "X", "C"]
print(copied_list_1)
print(copied_list_2) |
# ISSUE ONE
class Restaurant():
""""
1.Initialize the class with the attributes
name, type_restaurant, address. This info comes through the paramerters.
2. add and atribute called number_people_served and
initialize it with zero.
"""
def __init__(self,name,type_restaurant,address):
self.name=name
self.type_restaurant=type_restaurant
self.address=address
self.number_people_served=0
def print_restaurant_info(self):
""" This method prints the restaurant
info.
Include the atrributes and add
any other info you like
make sure proper capitalization is used
"""
print(f"Name : {self.name}\nType : {self.type_restaurant}\nAddress : {self.address}\nNumber of People Served:{self.number_people_served}")
def set_number_people_served(self,n_served):
""" this methods recieves the
number of people served
and adds it to the attribute number_people_served """
self.number_people_served+=n_served
def print_number_people_served(self):
print(f"The number of people served by {self.name} are {self.number_people_served}")
# ISSUE TWO
class CoffeeStore(Restaurant):
""" CoffeeStore class inherits Restraunt Class"""
def __init__(self,name, address, type_restaurant = "coffe_store"):
"""initialize it with an attribute called name and using a variable called
restaurant_type with the default value 'coffe_store'. These are received through parameters. Make sure to call the super() method and pass the right parameters"""
"""
add an attribute called coffe_types. This will store a list with at least 3 types of coffe of your choice"""
super().__init__(name, address, type_restaurant)
self.coffee_types = [
"Decaf",
"Espresso"
"Latte",
"Cappuccino",
"Irish Coffee"
]
def print_coffe_store_info(self):
"""
This methods prints the coffee store info,
ie, the types of cofees served in the store.
"""
for coffee_type in self.coffee_types:
print("* "+ coffee_type)
# ISSUE 3
""" Write the main part of the program
make an instace of the class Restaurante
and call the methods
Make an instance of the class CoffeeStore
call
"""
# write your code here
if __name__=='__main__':
restaurant=Restaurant('My Palace','Fast Food','12th Street ZYZ, ABC')
restaurant.set_number_people_served(200)
restaurant.print_restaurant_info()
restaurant.print_number_people_served()
cafe=CoffeeStore("The espresso","GFH Street, KFC","coffee_store")
cafe.set_number_people_served(300)
cafe.print_coffe_store_info()
cafe.print_restaurant_info()
cafe.print_number_people_served() |
import sqlite3
from selenium import webdriver
from bs4 import BeautifulSoup
conn = sqlite3.connect("covid_database.sqlite")
cur = conn.cursor()
cur.executescript(
"""
DROP TABLE IF EXISTS Covid;
CREATE TABLE Covid(
country TEXT UNIQUE,
cases INTEGER,
new INTEGER
);
"""
)
driver = webdriver.Chrome(
executable_path=r"C:\Users\Navaneeth R\programs\web scraping\projects\chromedriver_win32\chromedriver.exe"
)
driver.get("https://www.worldometers.info/coronavirus/?utm_campaign=homeAdvegas1?")
content = driver.page_source
soup = BeautifulSoup(content, "html.parser")
countries = []
cases = []
new_cases = []
for data in soup.find_all("tr", {"class": "odd"}):
country = data.find_all("td")[1]
case = data.find("td", {"class": "sorting_1"})
new = data.find_all("td")[3]
countries.append(country.text)
cases.append(case.text)
new_cases.append(new.text)
for data in soup.find_all("tr", {"class": "even"}):
country = data.find_all("td")[1]
case = data.find("td", {"class": "sorting_1"})
new = data.find_all("td")[3]
countries.append(country.text)
cases.append(case.text)
new_cases.append(new.text)
driver.close()
for i in range(len(countries)):
if countries[i] is None or cases[i] is None:
continue
cur.execute(
"""INSERT OR IGNORE INTO Covid (country, cases, new)
VALUES ( ?, ?, ? )""",
(countries[i], cases[i], new_cases[i]),
)
conn.commit()
cur.close()
|
from socket import * # Socket goodies
from Prime import is_prime
# Set up server port address and socket
server_port = 12000
server_socket = socket(AF_INET, SOCK_STREAM) # SOCK_STREAM indicates TCP
# Bind the server port address to the socket to give it an identity
server_socket.bind(('', server_port))
# Tells socket to listen for TCP connection requests from the client
server_socket.listen(1) # Maximum number of connections given by parameter "1"
print "The server is ready to receive"
while 1:
# Creates another socket dedicated for the pipe between client and server
connection_socket, client_address = server_socket.accept()
# Store data from client
number = connection_socket.recv(1024)
# Cast number to an int
number = int(number)
# Check if number from client is prime
if is_prime(number):
result = "Number is prime! :-)"
else:
result = "Number is NOT prime. :-("
# Send data back to client
connection_socket.send(result)
# Close pipe connection between client and server. Note that the server can still accept new connections from the
# initial socket
connection_socket.close()
|
"""Customers at Hackbright."""
class Customer(object):
"""Ubermelon customer."""
# TODO: need to implement this
def __init__(self, firstname, lastname, email, password):
self.email = email
self.password = password
def read_customer_from_file(filepath):
"""Read customer data and populate dictionary of customers.
Dictionary will be {email: Customer object}
"""
customers_data = {}
for line in open(filepath):
(firstname, lastname, email, password) = line.strip().split("|")
customers_data[email] = Customer(firstname, lastname, email, password)
return customers_data
def get_by_email(email):
"""Returns email."""
return customer_file.get(email)
customer_file = read_customer_from_file("customers.txt")
|
# https://www.codewithharry.com/videos/python-tutorials-for-absolute-beginners-120
import pyttsx3 # it is a text-to-speech library.
import datetime
import speech_recognition as sr
# import wikipedia
import webbrowser
import os
# sapi5 is an speech api provided by microsoft to use inbuilt voices
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[2].id)
# Voice id helps us to select different voices.
engine.setProperty('voice', voices[2].id)
# This function will take audio as an argument, and then, it will pronounce it.
def speak(audio):
engine.say(audio)
# Without this command, speech will not be audible to us.
engine.runAndWait()
# Congratulations! With this, our J.A.R.V.I.S. has its own voice, and it is ready to speak.
def wishMe():
hour = int(datetime.datetime.now().hour)
if(hour >= 0 and hour < 12):
speak("Good Morning!")
elif(hour >= 12 and hour < 18):
speak("Good Afternoon!")
else:
speak("Good Evening!")
speak("I am Zira sir ! How could i help you ?")
# With the help of the takeCommand() function, our A.I. assistant will be able to return a string output by taking microphone input from the user.
def takeCommand():
# it takes microphone input from user and gives output as a string
# Before defining the takeCommand() function, we need to install a module called speechRecognition.
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening....")
# r.pause_threshold=1
r.adjust_for_ambient_noise(source)
# r.energy_threshold = 500
audio = r.listen(source)
try:
print("Recognising...")
# google speech API #Using google for voice recognition
query = r.recognize_google(audio, language="en-in")
print(f"User said:{query}\n")
except Exception as e:
print("Say it again please")
return "none"
return query
if __name__ == "__main__":
wishMe()
# while True:
query = takeCommand().lower()
if 'open youtube' in query:
webbrowser.open("youtube.com")
# logic
# if 'wikipedia' in query:
# speak('Searching wikipedia...')
# query=query.replace('wikipedia','')
# results=wikipedia.summary(query,sentences=2)
# speak('According to wikipedia')
# print(results)
# speak(results)
elif 'open google' in query:
# speak("Your request is")
# speak(query)
webbrowser.get(
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open("google.com")
elif 'open stackoverflow' in query:
speak("Your request is")
speak(query)
webbrowser.get(
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open("stackoverflow.com")
elif 'open my github account' in query:
speak("Your request is")
speak(query)
webbrowser.get(
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open("github.com/shivam2001pandey")
elif 'play a song' in query:
speak("Your request is")
speak(query)
webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open(
"music.youtube.com/watch?v=i4IWLCJmbfY&list=RDAMVMi4IWLCJmbfY")
elif 'the time' in query:
speak("Sir ,the current time is ")
strTime = datetime.datetime.now().strftime("%H:%M:%S")
speak(strTime)
elif 'open code' in query:
# speak("sir! I am opening vs code for you.")
codePath = "D:\\Microsoft VS Code\\_\\Code.exe"
os.startfile(codePath)
elif 'reference of the code' in query:
speak("Your request is")
speak(query)
webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open(
"codewithharry.com/videos/python-tutorials-for-absolute-beginners-120")
|
from singly import Node, SinglyLinkedList
class DNode(Node):
def __init__(self, value, prev_node=None, next_node=None):
super().__init__(value, next_node=next_node)
self.prev_node = prev_node
def set_prev_node(self, node):
self.prev_node = node
def get_prev_node(self):
return self.prev_node
class DoublyLinkedList(SinglyLinkedList):
def __init__(self):
self.head = DNode(None, None, None)
self.tail = DNode(None, None, None)
self.initialized = False
def insert_at_head(self, value):
elem = DNode(value, self.head, self.head.get_next_node())
if(not self.initialized):
self.tail.set_prev_node(elem)
elem.set_next_node(self.tail)
self.initialized = True
else:
self.head.get_next_node().set_prev_node(elem)
self.head.set_next_node(elem)
# print(elem)
def insert_at_tail(self, value):
elem = DNode(value, self.tail.get_prev_node(), self.tail)
if(not self.initialized):
self.head.set_next_node(elem)
elem.set_prev_node(self.head)
self.initialized = True
else:
self.tail.get_prev_node().set_next_node(elem)
self.tail.set_prev_node(elem)
# print(elem)
def __repr__(self) -> str:
result = ''
x = self.head.get_next_node()
while x != None and x != self.tail and x != self.head:
result += str(x.get_value()) + ' <-> '
x = x.get_next_node()
return result[:-4].strip()
def reverseRepr(self) -> str:
result = ''
x = self.tail.get_prev_node()
while x != None and x != self.tail and x != self.head:
result += str(x.get_value()) + ' <-> '
x = x.get_prev_node()
return result[:-4].strip()
def get_head_elem(self):
return self.head.get_next_node().get_value()
def get_tail_elem(self):
return self.tail.get_prev_node().get_value()
if __name__ == "__main__":
l = DoublyLinkedList()
# l.insert_at_tail(30)
l.insert_at_head(1)
l.insert_at_head(2)
l.insert_at_head(3)
l.insert_at_tail(4)
l.insert_at_head(20)
l.insert_at_tail(30)
l.insert_at_head(100)
l.insert_at_tail(500)
print(l.get_head_elem())
print(l.get_tail_elem())
print(l.reverseRepr()) |
"""
Compute the Sieve of Eratosthenes.
List all the prime numbers given a ``limit`` which are greater than 1 and smaller-equal
``limit``.
"""
import bisect
from typing import List
from icontract import require, ensure
@ensure(lambda a, result: result == -1 or 0 <= result < len(a))
def find(a: List[int], x: int) -> int:
"""
Locate the leftmost value in ``a`` exactly equal to ``x``.
Return -1 if the element was not found in ``a``.
"""
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
def naive_is_prime(number: int) -> bool:
"""Check naively whether the ``number`` is a prime number."""
result = True
for another in range(number - 1, 1, -1):
if number % another == 0:
result = False
break
return result
# fmt: off
@require(lambda limit: limit > 1)
@ensure(
lambda result:
all(
naive_is_prime(number)
for number in result
)
)
@ensure(
lambda limit, result:
all(
1 < number <= limit
for number in result
)
)
@ensure(
lambda result:
len(result) == len(set(result)),
"Unique results"
)
# fmt: on
def sieve(limit: int) -> List[int]:
"""
Apply the Sieve of Eratosthenes on the numbers up to ``limit``.
:return: list of prime numbers till ``limit``
"""
candidates = list(range(2, limit + 1))
result = [] # type: List[int]
while candidates:
prime = candidates.pop(0)
result.append(prime)
for i in range(2, limit):
index = find(candidates, prime * i)
if index != -1:
candidates.pop(index)
if prime * i > limit:
break
return result
|
"""
Analyze the grades of the students.
Here's an example of the data
.. code-block::
111111004 5.0 5.0 6.0
111111005 3.75 3.0 4.0
111111006 4.5 2.25 4.0
Every line represents a grading of a student. It starts with her matriculation number,
followed by space-delimited grades (between 1.0 and 6.0, floats). The grades correspond
to lectures 1, 2 and 3, respectively.
Provide the function ``critical`` which accepts two arguments, ``bound1`` and
``bound2``. The function lists all the students which have "critical" grades.
A student should appear only once in the list.
A student is "critical" if the grade for the first lecture is smaller-equal ``bound1``
and the sum of the grades for the lecture 2 and 3 is smaller than ``bound2``.
On the above example, ``critical(4, 8)`` gives:
.. code-block::
111111005
Provide the function ``top`` which lists the students with the best grades. The
parameter ``limit`` determines the number of the "top" students. If the number of
students is less than ``limit``, return the list of all the students.
A student should appear only once in the resulting list. The students are compared
based on the sum of the grades in all the three lectures. If the sum of grades is
equal for two students, the order in the list is undefined (*i.e.* does not matter).
On the above example, ``top(2)`` might return both the output:
.. code-block::
111111004
111111005
and:
.. code-block::
111111004
111111006
(Both outputs are valid.)
The parameter ``limit`` is always greater than 0. Both ``bound1`` and ``bound2`` are
expected in the range ``[0.0, 100.0]``.
"""
import re
from decimal import Decimal
from numbers import Rational
from typing import List, cast, Union
from icontract import require, ensure, DBC
from correct_programs.common import Lines
ALL_GRADES = [Decimal("0.25") * i for i in range(0, 25)] #: List all possible grades.
ALL_GRADES_SET = set(ALL_GRADES) #: Provide a set of all possible grades.
# fmt: off
assert all(
grade % 1 in (Decimal('0.0'), Decimal('0.25'), Decimal('0.5'), Decimal('0.75'))
for grade in ALL_GRADES
)
# fmt: on
assert min(ALL_GRADES) == Decimal("0.0")
assert max(ALL_GRADES) == Decimal("6.0")
class Grade(DBC, Decimal):
"""Represent a grade in Swiss educational system."""
@require(lambda value: value in ALL_GRADES_SET)
@require(lambda value: not value.is_nan())
def __new__(cls, value: Decimal) -> "Grade":
"""Enforce the grade properties on ``value``."""
return cast(Grade, value)
def __le__(self, other: Union[Decimal, float, Rational, "Grade"]) -> bool:
"""Return ``True`` if ``self`` is smaller than ``other``."""
return self < other
def __add__(self, other: Union[Decimal, int, "Grade"]) -> Decimal:
"""Add ``self`` and ``other``."""
return self + other
class Grading:
"""Represent the grading of a student."""
def __init__(
self, identifier: str, grade1: Grade, grade2: Grade, grade3: Grade
) -> None:
"""Initialize with the given values."""
self.identifier = identifier
self.grade1 = grade1
self.grade2 = grade2
self.grade3 = grade3
@ensure(lambda result: result >= 0)
def sum_grades(self) -> Decimal:
"""Sum all grades of the student."""
return self.grade1 + self.grade2 + self.grade3
#: Express a grading entry for a student as a text.
#:
#: .. note::
#:
#: The function :py:attr:`re.Pattern.__repr__` truncates at 200 characters
#: so that the pattern in the docs (based on ``__repr__`` function) is possibly
#: incorrect.
#: See `Python issue #13592 <https://bugs.python.org/issue13592>`_.
GRADING_RE = re.compile(
"([a-zA-Z0-9]+) +"
"(0.0|0.25|0.5|0.75|1.0|1.25|1.5|1.75|2.0|2.25|2.5|2.75|3.0|3.25|3.5|3.75|4.0|"
"4.25|4.5|4.75|5.0|5.25|5.5|5.75|6.0) +"
"(0.0|0.25|0.5|0.75|1.0|1.25|1.5|1.75|2.0|2.25|2.5|2.75|3.0|3.25|3.5|3.75|4.0|"
"4.25|4.5|4.75|5.0|5.25|5.5|5.75|6.0) +"
"(0.0|0.25|0.5|0.75|1.0|1.25|1.5|1.75|2.0|2.25|2.5|2.75|3.0|3.25|3.5|3.75|4.0|"
"4.25|4.5|4.75|5.0|5.25|5.5|5.75|6.0)"
)
@require(lambda lines: all(GRADING_RE.fullmatch(line) for line in lines))
@ensure(
lambda result: (
identifiers := [grading.identifier for grading in result],
len(identifiers) == len(set(identifiers)),
)[1],
"Unique identifiers",
)
@ensure(lambda lines, result: len(result) == len(lines))
def parse(lines: Lines) -> List[Grading]:
"""Parse the grading entries given as ``lines``."""
result = [] # type: List[Grading]
for line in lines:
parts = [part for part in line.split(" ") if part.strip() != ""]
assert len(parts) == 4, f"{parts=}"
identifier = parts[0]
grades = [Grade(Decimal(part)) for part in parts[1:]]
result.append(
Grading(
identifier=identifier,
grade1=grades[0],
grade2=grades[1],
grade3=grades[2],
)
)
return result
# fmt: off
@require(
lambda gradings:
(
identifiers := [grading.identifier for grading in gradings],
len(identifiers) == len(set(identifiers))
)[1],
"Students appear only once"
)
@ensure(
lambda result:
(
identifiers := [grading.identifier for grading in result],
len(identifiers) == len(set(identifiers))
)[1],
"Students appear only once"
)
# fmt: on
def critical(gradings: List[Grading], bound1: Grade, bound2: Decimal) -> List[Grading]:
"""
List critical gradings among the ``gradings`` based on ``bound1`` and ``bound2``.
Note that ``bound1`` and ``bound2`` have special semantics.
Please consult the text of the problem.
"""
result = [] # type: List[Grading]
for grading in gradings:
if grading.grade1 <= bound1 and grading.grade2 + grading.grade3 < bound2:
result.append(grading)
return result
# fmt: off
@require(
lambda gradings:
(
identifiers := [grading.identifier for grading in gradings],
len(identifiers) == len(set(identifiers))
)[1],
"Students appear only once"
)
@require(lambda limit: limit > 0)
@ensure(
lambda result:
(
identifiers := [grading.identifier for grading in result],
len(identifiers) == len(set(identifiers))
)[1],
"Students appear only once"
)
@ensure(
lambda gradings, limit, result:
len(result) == min(limit, len(gradings))
)
@ensure(
lambda result:
all(
result[i].sum_grades() >= result[i + 1].sum_grades()
for i in range(len(result) - 1)
)
)
# fmt: on
def top(gradings: List[Grading], limit: int) -> List[Grading]:
"""Find the top ``limit`` students among the ``gradings``."""
sorted_gradings = sorted(
gradings, key=lambda grading: grading.sum_grades(), reverse=True
)
return sorted_gradings[:limit]
|
"""
Compute a greatest common divisor (GCD) between two positive integers ``x`` and ``y``.
Please note:
1) If ``x`` is greater-equal ``y`` and ``x`` is divisible by ``y``, the GCD between
``x`` and ``y`` is ``y``.
2) Otherwise, the GCD between ``x`` and ``y`` is ``GCD(y, x % y)``.
For ``x == 36`` and ``y == 44``, the GCD is 4.
Do not use ``math.gcd`` function.
"""
import math
from icontract import require, ensure
@require(lambda x: x > 0)
@require(lambda y: y > 0)
@ensure(lambda x, y, result: result == math.gcd(x, y))
def gcd(x: int, y: int) -> int:
"""Compute the greatest common divisor (GCD) between ``x`` and ``y``."""
if x >= y and x % y == 0:
return y
return gcd(y, x % y)
|
"""
Implement a linked list which stores integers.
Provide the following operations:
* ``add_first``,
* ``remove_first``,
* ``remove_last``,
* ``clear``,
* ``is_empty``,
* ``get`` (at index),
* ``set`` (at index), and
* ``iterate`` (over all the elements of the list).
(We substantially shortened the text of this problem to only give the crux of the
problem and leave out the parts with user input/output. Please refer to the original
exercise in German for exact details.)
"""
from typing import Optional, Iterator
from icontract import require, ensure, invariant, snapshot, DBC
class Node:
def __init__(self, value: int, next_node: Optional['Node']) -> None:
self.value = value
self.next_node = next_node
# fmt: off
@invariant(
lambda self:
self.is_empty() ^ (self._first is not None and self._last is not None)
)
@invariant(lambda self: len(list(self.iterate())) != 0 ^ self.is_empty())
@invariant(lambda self: self._last is None or self._last.next_node is None)
@invariant(lambda self: len(list(self.iterate())) == self.count())
# fmt: on
class LinkedList(DBC):
def __init__(self) -> None:
self._first = None # type: Optional[Node]
self._last = None # type: Optional[Node]
self._count = 0
@snapshot(lambda self: self.count(), name="count")
@snapshot(lambda self: list(self.iterate()), name="items")
@ensure(lambda value, self, OLD: [value] + OLD.items == list(self.iterate()))
@ensure(lambda self: not self.is_empty())
@ensure(lambda self, OLD: self.count() == OLD.count + 1)
def add_first(self, value: int) -> None:
if self._first is None:
self._first = Node(value=value, next_node=None)
self._last = self._first
else:
self._first = Node(value=value, next_node=self._first)
self._count += 1
def count(self) -> int:
return self._count
@require(lambda self: not self.is_empty())
@snapshot(lambda self: list(self.iterate()), name="items")
@snapshot(lambda self: self.count(), name="count")
@ensure(lambda self, OLD: OLD.items[1:] == list(self.iterate()))
@ensure(lambda self, OLD: self.count() == OLD.count - 1)
@ensure(lambda result, OLD: OLD.items[0] == result)
def remove_first(self) -> int:
value = self._first.value
self._first = self._first.next_node
self._count -= 1
return value
@require(lambda self: not self.is_empty())
@snapshot(lambda self: self.count(), name="count")
@snapshot(lambda self: list(self.iterate()), name="items")
@ensure(lambda self, OLD: OLD.items[:-1] == list(self.iterate()))
@ensure(lambda self, OLD: self.count() == OLD.count - 1)
@ensure(lambda result, OLD: OLD.items[-1] == result)
def remove_last(self) -> int:
if self._first == self._last:
self._count -= 1
value = self._first.value
self._first = None
self._last = None
return value
cursor = self._first
prev = None # type: Optional[Node]
while cursor != self._last:
# ERROR (mristin):
# I got the assignment of prev wrong, it should come befure cursor is
# assigned to a new value.
cursor = cursor.next_node
prev = cursor
value = self._last.value
self._last = prev
prev.next_node = None
self._last = prev
self._count -= 1
return value
@require(lambda self: not self.is_empty())
@ensure(lambda self: self.is_empty())
@ensure(lambda self: self.count() == 0)
def clear(self) -> None:
self._first = None
self._last = None
self._count = 0
def is_empty(self) -> bool:
return self._first is None
@require(lambda self, index: 0 <= index < self.count())
@ensure(lambda self, index, result: list(self.iterate())[index] == result)
def get(self, index: int) -> int:
cursor = self._first
for _ in range(index):
cursor = cursor.next_node
return cursor.value
@require(lambda self, index: 0 <= index < self.count())
@ensure(lambda self, index, value: list(self.iterate())[index] == value)
def set(self, index: int, value: int):
cursor = self._first
for _ in range(index):
cursor = cursor.next_node
cursor.value = value
def iterate(self) -> Iterator[int]:
cursor = self._first
while cursor is not None:
yield cursor.value
cursor = cursor.next_node
|
from typing import List, Dict
from icontract import require, ensure
LAST_STEP = 2020 #: The last relevant step of the game
@require(lambda starting_numbers: len(starting_numbers) > 0)
@ensure(lambda result: 0 <= result <= LAST_STEP - 2)
def solve(starting_numbers: List[int]) -> int:
"""Play the memory game starting with the ``starting_numbers`` to``LAST_STEP``."""
d: Dict[int, int] = dict()
last = starting_numbers[0]
for index, number in enumerate(starting_numbers[1:]):
d[last] = index + 1
last = number
for step in range(len(starting_numbers), LAST_STEP):
if last not in d:
d[last] = step
last = 0
else:
difference = step - d[last]
d[last] = step
last = difference
return last
|
"""
Input: list of actions
Output: position, Manhattan distance
"""
from dataclasses import dataclass
from icontract import invariant, require, ensure
from typing import List
import re
from enum import Enum
"""
Error
ValueError: 3.977777777777778 is not a valid Orientation
"""
class Orientation(Enum):
EAST = 0
SOUTH = 1
WEST = 2
NORTH = 3
@dataclass
class ShipPosition:
horizontal: int = 0
vertical: int = 0
orientation: Orientation = Orientation.EAST
def __repr__(self):
result = ""
if self.horizontal < 0:
result += "west {}".format(abs(self.horizontal))
else:
result += "east {}".format(self.horizontal)
if self.vertical >= 0:
result += ", north {}".format(self.vertical)
else:
result += ", south {}".format(abs(self.vertical))
result += ", orientation {}".format(self.orientation.name)
return result
@require(lambda puzzle_input: re.match(r'^[NSEWLRF][0-9]+(\n[NSEWLRF][0-9]+)*$', puzzle_input))
@ensure(lambda result, puzzle_input: "\n".join(result) == puzzle_input)
def parse_input(puzzle_input: str) -> List[str]:
return list(map(lambda l: l, puzzle_input.split('\n')))
@require(lambda move: re.match(r'^[NSEWLRF][0-9]+', move))
@require(lambda move: not (move[0] == 'L' or move[0] == 'R') or move[1:] in [0, 90, 180, 270, 360])
def update_position(current_position: ShipPosition, move: str) -> ShipPosition:
action, value = move[0], int(move[1:])
next_position = current_position
if action == 'N':
next_position.vertical += value
elif action == 'S':
next_position.vertical -= value
elif action == 'E':
next_position.horizontal += value
elif action == 'W':
next_position.horizontal -= value
elif action == 'L':
next_position.orientation = Orientation(
((next_position.orientation).value - (value / 90)) % 4)
elif action == 'R':
next_position.orientation = Orientation(
((next_position.orientation).value + (value / 90)) % 4)
elif action == 'F':
if next_position.orientation == Orientation.NORTH:
next_position.vertical += value
elif next_position.orientation == Orientation.SOUTH:
next_position.vertical -= value
elif next_position.orientation == Orientation.EAST:
next_position.horizontal += value
elif next_position.orientation == Orientation.WEST:
next_position.horizontal -= value
return next_position
@require(lambda puzzle_input: re.match(r'^[NSEWLRF][0-9]+(\n[NSEWLRF][0-9]+)*$', puzzle_input))
def solve(puzzle_input: str) -> ShipPosition:
current_position = ShipPosition(0, 0, Orientation.EAST)
for command in parse_input(puzzle_input):
current_position = update_position(current_position, command)
return current_position
example_input = """F10
N3
F7
R90
F11"""
if __name__ == '__main__':
print(solve(example_input))
|
# pylint: disable=line-too-long
"""
Implement a compiler for the interpreter developed in Exercise 12, Problem 1.
The program should be compiled in a language based on operand stack.
The following operations are supported:
* ``CONST c``: push the value ``c`` on the stack,
* ``LOAD v``: load the value of the variable ``v`` and push it on the stack,
* ``STORE v``: pop a value from the stack and store it to the variable ``v``,
* ``OP {operation}``: pop two values ("left" and "right"), apply the operation and
push the result on the stack, and
* ``FUNC f``: pop a value from the stack, apply the function ``f`` on it and push the
result on the stack.
Please see `page 5`_ of the exercise for an example.
.. _page 5: https://ethz.ch/content/dam/ethz/special-interest/infk/inst-cs/lst-dam/documents/Education/Classes/Fall2019/0027_Intro/Homework/u12.pdf?page=5
"""
import math
from typing import List, MutableMapping, Mapping
from icontract import DBC, snapshot, ensure, require, ViolationError
from correct_programs.ethz_eprog_2019.exercise_12 import problem_01
class Instruction:
"""Represent the bytecode instruction."""
class Const(Instruction, DBC):
"""Push the constant on the stack."""
def __init__(self, value: float) -> None:
self.value = value
class Load(Instruction, DBC):
"""Load a variable from the registry and push it on the stack."""
def __init__(self, identifier: problem_01.Identifier) -> None:
self.identifier = identifier
class Store(Instruction, DBC):
"""Pop a value from the stack and store it in the registry."""
def __init__(self, identifier: problem_01.Identifier) -> None:
"""Initialize with the given values."""
self.identifier = identifier
class UnaryOperation(Instruction, DBC):
"""Pop the value from the stack, apply the operation and push the result."""
def __init__(self, operator: problem_01.UnOp) -> None:
"""Initialize with the given values."""
self.operator = operator
class BinaryOperation(Instruction, DBC):
"""Pop the two values from the stack, apply the operation and push the result."""
def __init__(self, operator: problem_01.BinOp) -> None:
"""Initialize with the given values."""
self.operator = operator
class Call(Instruction, DBC):
"""Pop the value from the stack, apply the function and push the result."""
def __init__(self, function: problem_01.Function) -> None:
"""Initialize with the given values."""
self.function = function
class _CompileVisitor(problem_01._Visitor[None]):
def __init__(self) -> None:
self.instructions = [] # type: List[Instruction]
def visit_constant(self, node: problem_01.Constant) -> None:
self.instructions.append(Const(value=node.value))
def visit_variable(self, node: problem_01.Variable) -> None:
self.instructions.append(Load(identifier=node.identifier))
def visit_unary_operation(self, node: problem_01.UnaryOperation) -> None:
self.visit(node.target)
self.instructions.append(UnaryOperation(operator=node.operator))
def visit_binary_operation(self, node: problem_01.BinaryOperation) -> None:
self.visit(node.left)
self.visit(node.right)
self.instructions.append(BinaryOperation(operator=node.operator))
def visit_call(self, node: problem_01.Call) -> None:
self.visit(node.argument)
self.instructions.append(Call(function=node.function))
def visit_assign(self, node: problem_01.Assign) -> None:
self.visit(node.expr)
self.instructions.append(Store(identifier=node.target))
def visit_program(self, node: problem_01.Program) -> None:
for stmt in node.body:
self.visit(stmt)
def visit_default(self, node: problem_01.Node) -> None:
raise NotImplementedError(repr(node))
def compile_program(program: problem_01.Program) -> List[Instruction]:
"""Compile the given program into bytecode instructions."""
visitor = _CompileVisitor()
visitor.visit(program)
return visitor.instructions
@snapshot(lambda stack: stack[:])
@ensure(lambda instr, stack, OLD: stack == OLD.stack + [instr.value])
def _execute_const(instr: Const, stack: List[float]) -> None:
stack.append(instr.value)
# fmt: off
@require(
lambda instr, variables: instr.identifier in variables,
error=lambda instr: NameError(
f"Unexpected LOAD on variable "
f"which is not available: {instr.identifier}")
)
@snapshot(lambda stack: stack[:])
@ensure(
lambda instr, variables, stack, OLD:
stack == OLD.stack + [variables[instr.identifier]]
)
# fmt: on
def _execute_load(instr: Load, variables: Mapping[str, float],
stack: List[float]) -> None:
stack.append(variables[instr.identifier])
# fmt: off
@require(
lambda stack: len(stack) > 0,
error=lambda instr: RuntimeError(
f"Unexpected empty stack on STORE "
f"to variable: {instr.identifier}")
)
@snapshot(lambda stack: stack[:])
@ensure(
lambda stack, OLD:
all(
(math.isnan(old) and math.isnan(new)) or old == new
for old, new in zip(OLD.stack[:-1], stack)
)
)
@ensure(lambda stack, OLD: len(stack) == len(OLD.stack) - 1)
@ensure(lambda instr, variables: instr.identifier in variables)
# fmt: on
def _execute_store(
instr: Store, variables: MutableMapping[str, float], stack: List[float]
) -> None:
value = stack.pop()
variables[instr.identifier] = value
# fmt: off
@require(
lambda stack: len(stack) > 0,
error=lambda instr: RuntimeError(
f"Unexpected empty stack on unary operation {instr.operator}")
)
@snapshot(lambda stack: stack[:])
@ensure(
lambda stack, OLD:
all(
(math.isnan(old) and math.isnan(new)) or old == new
for old, new in zip(OLD.stack[:-1], stack[:-1])
)
)
@ensure(lambda stack, OLD: len(stack) == len(OLD.stack))
# fmt: on
def _execute_unary_operation(instr: UnaryOperation, stack: List[float]) -> None:
value = stack.pop()
if instr.operator == problem_01.UnOp.MINUS:
result = -value
else:
raise NotImplementedError(f"{instr.operator=}")
stack.append(result)
# fmt: off
@require(
lambda stack: len(stack) >= 2,
error=lambda instr, stack: RuntimeError(
f"Unexpected stack with only {len(stack)} element(s) "
f"on binary operation {instr.operator}")
)
@snapshot(lambda stack: stack[:])
@ensure(
lambda stack, OLD:
all(
(math.isnan(old) and math.isnan(new)) or old == new
for old, new in zip(OLD.stack[:-2], stack[:-2])
)
)
@ensure(lambda stack, OLD: len(stack) == len(OLD.stack) - 1)
# fmt: on
def _execute_binary_operation(instr: BinaryOperation, stack: List[float]) -> None:
left_value = stack.pop()
right_value = stack.pop()
if instr.operator == problem_01.BinOp.ADD:
result = left_value + right_value
elif instr.operator == problem_01.BinOp.SUB:
result = left_value - right_value
elif instr.operator == problem_01.BinOp.MUL:
result = left_value * right_value
elif instr.operator == problem_01.BinOp.DIV:
result = left_value / right_value
elif instr.operator == problem_01.BinOp.POW:
result = left_value ** right_value
else:
raise NotImplementedError(f"{instr.operator=}")
stack.append(result)
# fmt: off
@require(
lambda stack: len(stack) > 0,
error=lambda instr: RuntimeError(
f"Unexpected empty stack on call to function {instr.function}")
)
@snapshot(lambda stack: stack[:])
@ensure(
lambda stack, OLD:
all(
(math.isnan(old) and math.isnan(new)) or old == new
for old, new in zip(OLD.stack[:-1], stack[:-1])
)
)
@ensure(lambda stack, OLD: len(stack) == len(OLD.stack))
# fmt: on
def _execute_call(instr: Call, stack: List[float]) -> None:
value = stack.pop()
if instr.function == problem_01.Function.SIN:
result = math.sin(value)
elif instr.function == problem_01.Function.COS:
result = math.cos(value)
elif instr.function == problem_01.Function.TAN:
result = math.tan(value)
else:
raise NotImplementedError(f"{instr.function=}")
stack.append(result)
def execute(
instructions: List[Instruction]
) -> MutableMapping[problem_01.Identifier, float]:
"""Execute the given instructions."""
variables = dict() # type: MutableMapping[problem_01.Identifier, float]
if len(instructions) == 0:
return variables
stack = [] # type: List[float]
for instr in instructions:
if isinstance(instr, Const):
_execute_const(instr=instr, stack=stack)
elif isinstance(instr, Load):
_execute_load(instr=instr, variables=variables, stack=stack)
elif isinstance(instr, Store):
_execute_store(instr=instr, variables=variables, stack=stack)
elif isinstance(instr, UnaryOperation):
_execute_unary_operation(instr=instr, stack=stack)
elif isinstance(instr, BinaryOperation):
_execute_binary_operation(instr=instr, stack=stack)
elif isinstance(instr, Call):
_execute_call(instr=instr, stack=stack)
else:
raise NotImplementedError(f"{instr=}")
return variables
# ERROR:
# icontract.errors.ViolationError:
# result == problem_01.interpret(program):
# problem_01.interpret(program) was {'x': -1.0}
# program was Program([Assign('x', BinaryOperation(Constant(5e-324), '-', Constant(1.0)))])
# result was {'x': 1.0}
#
# Falsifying example: execute(
# kwargs={'left': 5e-324, 'operator': <BinOp.SUB: '-'>, 'right': 1.0},
# )
@ensure(lambda program, result: result == problem_01.interpret(program))
def compile_and_execute(
program: problem_01.Program
) -> MutableMapping[problem_01.Identifier, float]:
"""Compile and execute the given program."""
instructions = compile_program(program)
return execute(instructions)
|
"""
Draw the following pattern:
.. code-block::
**..**..**..
..**..**..**
**..**..**..
..**..**..**
**..**..**..
..**..**..**
You are given the size of the image (as width).
"""
import re
from typing import List
from icontract import require, ensure
from correct_programs.common import Lines
ALLOWED_CHARS = re.compile(r"[.*]+") #: Express every line of the pattern
# fmt: off
@require(lambda width: width > 0)
@require(lambda width: width % 4 == 0)
@ensure(
lambda result:
all(
ALLOWED_CHARS.fullmatch(line)
for line in result
)
)
@ensure(lambda result: result[-1].startswith('.'))
@ensure(lambda result: result[-1].endswith('*'))
@ensure(lambda result: result[0].startswith('*'))
@ensure(lambda result: result[0].endswith('.'))
@ensure(lambda width, result: all(len(line) == width for line in result))
@ensure(lambda width, result: len(result) == width / 2)
# fmt: on
def draw(width: int) -> Lines:
"""Draw the pattern with the size given as ``width`` and return the text lines."""
result = [] # type: List[str]
for i in range(1, int(width / 2) + 1):
if i % 2 == 1:
pattern = "**.."
else:
pattern = "..**"
result.append(pattern * int(width / 4))
return Lines(result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.