text stringlengths 37 1.41M |
|---|
"""
输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
示例1:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
提示:
1 <= arr.length <= 10^5
-100 <= arr[i] <= 100
注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
min_cum = 0
cum = 0
res = -float("inf")
nums = [0] + nums
for num in nums[1:]:
cum += num
res = max(res, cum - min_cum)
if cum < min_cum:
min_cum = cum
return res |
"""
1081. Smallest Subsequence of Distinct Characters
Medium
271
52
Add to List
Share
Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once.
Example 1:
Input: "cdadabcc"
Output: "adbc"
Example 2:
Input: "abcd"
Output: "abcd"
Example 3:
Input: "ecbacba"
Output: "eacb"
Example 4:
Input: "leetcode"
Output: "letcod"
Constraints:
1 <= text.length <= 1000
text consists of lowercase English letters.
"""
from collections import defaultdict
class Solution:
def smallestSubsequence(self, text: str) -> str:
count = defaultdict(int)
for c in text:
count[c] += 1
visited = set()
stack = []
for c in text:
if c in visited:
count[c] -= 1
continue
while stack and stack[-1] > c and count[stack[-1]] > 0:
visited.remove(stack.pop())
stack.append(c)
visited.add(c)
count[c] -= 1
return "".join(stack)
# "cdadabcc"
# c = [0,6,7]
# b = [5]
# d = [1,3]
# a = [2,4]
|
"""
给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
示例:
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912
进阶:假设这些数位是正向存放的,请再做一遍。
示例:
输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-lists-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def helper(l1,l2,carry):
if not l1 and not l2:
if carry:
return ListNode(carry)
else:
return None
if not l1:
return helper(l2, ListNode(carry), 0)
if not l2 :
return helper(l1, ListNode(carry), 0)
carry, l1.val = divmod(l1.val + l2.val + carry, 10)
l1.next = helper(l1.next, l2.next, carry)
return l1
return helper(l1,l2, 0)
|
#!/usr/bin/env python3
# info
# -name : zhangruochi
# -email : zrc720@gmail.com
"""
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
"""
class Solution(object):
def addBinary_1(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a,2) + int(b,2))[2:]
def addBinary(self,a,b):
if len(a) == 0; return b
if len(b) == 0; return a
if a[-1] == '1' and b[-1] == '1':
return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1')+'0'
elif a[-1] == '0' and b[-1] == '0':
return self.addBinary(a[0:-1],b[0:-1]) + "0"
else:
return self.addBinary(a[0:-1],b[0:-1]) + "1"
if __name__ == '__main__':
solution = Solution()
print(solution.addBinary("0","1")) |
"""
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
提示:
你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。
注意:本题与主站 239 题相同:https://leetcode-cn.com/problems/sliding-window-maximum/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
queue = deque()
res = []
for i, num in enumerate(nums):
while len(queue) != 0 and num > nums[queue[-1]]:
queue.pop()
while len(queue) > 0 and i - queue[0] >= k:
queue.popleft()
queue.append(i)
if i >= k - 1:
res.append(nums[queue[0]])
return res
from heapq import *
from collections import namedtuple
from functools import total_ordering
class MyHeap():
def __init__(self):
self.data = []
def push(self, x):
heappush(self.data, x)
def pop(self):
return heappop(self.data)
@property
def size(self):
return len(self.data)
def top(self):
return self.data[0]
# @total_ordering
class Item():
def __init__(self, num, i):
self.num = num
self.priority = -num
self.index = i
def __eq__(self, other):
return self.priority == other.priority
def __lt__(self, other):
return self.priority < other.priority
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
heap = MyHeap()
res = []
for i, num in enumerate(nums):
while heap.size > 0 and i - heap.top().index >= k:
heap.pop()
heap.push(Item(num, i))
if i >= k - 1:
res.append(heap.top().num)
return res
|
"""
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
from collections import defaultdict
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
level = 0
queue = deque([(root,level)])
ans_table = defaultdict(list)
while queue:
cur,level = queue.popleft()
ans_table[level].append(cur.val)
if cur.left:
queue.append((cur.left,level+1))
if cur.right:
queue.append((cur.right,level+1))
return [ans_table[i] if i % 2 == 0 else list(reversed(ans_table[i])) for i in range(len(ans_table)) ]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
from collections import deque
from collections import defaultdict
queue = deque([])
level_map = defaultdict(list)
queue.append([root, 0])
while queue:
root, level = queue.popleft()
level_map[level].append(root.val)
if root.left:
queue.append([root.left, level + 1])
if root.right:
queue.append([root.right, level + 1])
return [ v if k % 2 == 0 else v[::-1] for k,v in level_map.items()]
|
"""
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
4 -> 5 -> 1 -> 9
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list
should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list
should become 4 -> 5 -> 9 after calling your function.
Note:
The linked list will have at least two elements.
All of the nodes' values will be unique.
The given node will not be the tail and it will always be a valid node of the linked list.
Do not return anything from your function.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
return "{}->{}".format(self.val, self.next)
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
if node and node.next:
delete_node = node.next
node.next = delete_node.next
node.val = delete_node.val
del delete_node
if __name__ == '__main__':
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
a.next = b
b.next = c
c.next = d
print(a)
Solution().deleteNode(b)
print(a)
|
"""
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Example 1:
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Example 2:
Input: nums = [1,2,3], k = 0
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
"""
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
return 0
product = 1
res = left = 0
for right, val in enumerate(nums):
product *= val
while product >= k:
product /= nums[left]
left += 1
res = res + (right - left) + 1
return res |
"""
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.
"""
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
visited_rows = set()
visited_cols = set()
m,n = len(matrix), len(matrix[0])
for r in range(m):
for c in range(n):
if matrix[r][c] == 0:
visited_cols.add(c)
visited_rows.add(r)
for i in visited_cols:
for r in range(m):
matrix[r][i] = 0
for j in visited_rows:
for c in range(n):
matrix[j][c] = 0
|
"""
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
Input:
["a","a","b","b","c","c","c"]
Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
Example 2:
Input:
["a"]
Output:
Return 1, and the first 1 characters of the input array should be: ["a"]
Explanation:
Nothing is replaced.
Example 3:
Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.
Note:
All characters have an ASCII value in [35, 126].
1 <= len(chars) <= 1000.
"""
class Solution:
def get_value_digits(self,value):
result = []
while value != 0:
value,digit = divmod(value,10)
result.insert(0,str(digit))
return result
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
current_char,count,index,i = None,0,0,0
while i<len(chars):
if current_char != chars[i]:
current_char = chars[i]
count = 0
while i<len(chars) and current_char == chars[i]:
i+=1
count += 1
chars[index] = current_char
index += 1
if count == 1:
pass
elif count < 10:
chars[index] = str(count)
index += 1
else:
chars[index:index+len(str(count))] = self.get_value_digits(count)
index += len(str(count))
#print(chars[:index])
return index
def compress2(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
current_char,count,index,i = None,0,0,0
while i<len(chars):
if current_char != chars[i]:
current_char = chars[i]
count = 0
while i<len(chars) and current_char == chars[i]:
i+=1
count += 1
chars[index] = current_char
index += 1
if count == 1:
pass
else:
for digit in str(count):
chars[index] = digit
index += 1
print(chars[:index])
return index
class Solution:
def compress(self, chars: List[str]) -> int:
prev = chars[0]
index = 0
count = 0
for char in chars:
if char == prev:
count += 1
else:
chars[index] = prev
index += 1
if count > 1:
for num in str(count):
chars[index] = num
index += 1
prev = char
count = 1
chars[index] = char
index += 1
if count > 1:
for num in str(count):
chars[index] = num
index += 1
return index
if __name__ == '__main__':
print(Solution().compress2(["a","a","b","b","c","c","c","c","c","c","c","c","c","c","c","c","a","a"]))
print(Solution().compress2(['a','b']))
print(Solution().compress2([]))
|
"""
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
示例 1:
输入:A = [1,2,3], B = [3,1]
输出:false
示例 2:
输入:A = [3,4,5,1,2], B = [4,1]
输出:true
限制:
0 <= 节点个数 <= 10000
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
res = False
if not B:
return res
def helper(A,B):
if not B:
return True
if not A or A.val != B.val:
return False
return helper(A.left,B.left) and helper(A.right, B.right)
def pre_order(A,B):
nonlocal res
if not A:
return
if A.val == B.val:
if helper(A,B):
res = True
pre_order(A.left, B)
pre_order(A.right, B)
return False
pre_order(A,B)
return res
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def is_same(root_a, root_b):
if not root_a and not root_b:
return True
elif not root_b and root_a:
return True
elif not root_a and root_b:
return False
else:
return root_a.val == root_b.val and is_same(root_a.left, root_b.left) and is_same(root_a.right, root_b.right)
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
if not A or not B:
return False
else:
return is_same(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
|
"""
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
cache = {}
def helper(x,n):
nonlocal cache
if n in cache:
return cache[n]
if n == 0:
return 1
if n == 1:
return x
if n % 2 != 0:
res = x * helper(x, n//2) * helper(x, n//2)
else:
res = helper(x, n//2) * helper(x, n//2)
cache[n] = res
return res
if n >= 0:
return helper(x,n)
else:
return 1/helper(x,-n)
|
"""
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.
Note:
Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
As long as a house is in the heaters' warm radius range, it can be warmed.
All the heaters follow your radius standard and the warm radius will the same.
Example 1:
Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Example 2:
Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
"""
import bisect
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
houses.sort()
heaters.sort()
max_radius = 0
for house in houses:
pos = bisect.bisect_left(heaters,house)
if pos == 0:
radius = heaters[pos] - house
elif pos == len(heaters):
radius = house - heaters[pos-1]
else:
radius = min([house-heaters[pos-1],heaters[pos]-house])
if radius > max_radius:
max_radius = radius
return max_radius
|
"""
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
"""
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
return "{}->{}".format(self.val,self.next)
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = dummy = ListNode(0)
dummy.next = head
while cur.next:
tmp = cur.next
if not tmp.next:
break
cur.next = cur.next.next
tmp.next = cur.next.next
cur.next.next = tmp
cur = cur.next.next
return dummy.next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy = cur = ListNode(0)
dummy.next = head
while cur.next and cur.next.next:
f = cur.next
s = f.next
tmp = s.next
cur.next = s
f.next = tmp
s.next = f
cur = f
return dummy.next
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head:
return head
dummy = cur = ListNode()
dummy.next = head
while cur.next and cur.next.next:
print(cur.val)
nn = cur.next.next.next
# 取
f = cur.next
s = cur.next.next
# 断、连
cur.next = s
s.next = f
f.next = nn
cur = f
return dummy.next
if __name__ == '__main__':
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
one.next = two
two.next = three
three.next = four
print(Solution().swapPairs(one))
|
weight = [10,20,15,8]
values = [2,7,4,8]
Max_ = 29
max_value = 0
max_value_path = None
def backpack( path, cur_weight, cur_value, pos):
global max_value, max_value_path, Max_
if pos == len(weight):
if cur_weight <= Max_:
if max_value < cur_value:
max_value = cur_value
max_value_path = path[:]
return
backpack(path, cur_weight, cur_value, pos+1)
if cur_weight + weight[pos] <= Max_:
backpack(path + [pos], cur_weight + weight[pos], cur_value + values[pos], pos+1)
return ;
# backpack([], 0, 0, 0)
# print(max_value_path)
# print(max_value)
def backpack( path, cur_weight, cur_value, pos):
global max_value, max_value_path, Max_
if pos == len(weight):
if cur_weight <= Max_:
if max_value < cur_value:
max_value = cur_value
max_value_path = path[:]
return
for i in range(pos, len(weight)):
path.append(i)
backpack(path, cur_weight + weight[i], cur_value + values[i], i+1)
path.pop()
return ;
backpack([], 0, 0, 0)
print(max_value_path)
print(max_value)
|
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
from collections import deque
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.nestedList = deque(nestedList)
self.flatted = []
self.recursive_flatted(self.nestedList)
self.flatted = deque(self.flatted)
def recursive_flatted(self,nestedList):
while nestedList:
item = nestedList.popleft()
if item.isInteger():
self.flatted.append(item.getInteger())
else:
self.recursive_flatted(deque(item.getList()))
def next(self):
"""
:rtype: int
"""
return self.flatted.popleft()
def hasNext(self):
"""
:rtype: bool
"""
return True if self.flatted else False
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next()) |
"""
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def replaceSpace(self, s: str) -> str:
res = ""
for char in s:
if char == " ":
res += "%20"
else:
res += char
return res
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(" ", "%20") |
"""
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
输入:m = 2, n = 3, k = 1
输出:3
示例 2:
输入:m = 3, n = 1, k = 0
输出:1
提示:
1 <= n,m <= 100
0 <= k <= 20
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
res = 0
visited = set()
def sum_digit(num):
cum = 0
while num:
num, _ = divmod(num, 10)
cum += _
return cum
def helper(r,c,k):
nonlocal res, visited
if r < 0 or r >= m or c < 0 or c >= n or sum_digit(r) + sum_digit(c) > k or (r,c) in visited:
return
# print(r,c)
res += 1
visited.add((r,c))
for new_r, new_c in ((r-1,c),(r+1,c),(r, c-1),(r,c+1)):
helper(new_r, new_c, k)
helper(0,0,k)
return res
|
"""
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
"""
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
vis = set(nums)
max_len = 0
for num in nums:
if (num-1) in vis:
continue
else:
length = 0
while num in vis:
num += 1
length += 1
max_len = max(length, max_len)
return max_len |
"""
Design and implement a data structure for a compressed string iterator. It should support the following operations: next and hasNext.
The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.
next() - if the original string still has uncompressed characters, return the next letter; Otherwise return a white space.
hasNext() - Judge whether there is any letter needs to be uncompressed.
Note:
Please remember to RESET your class variables declared in StringIterator, as static/class variables are persisted across multiple test cases. Please see here for more details.
Example:
StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1");
iterator.next(); // return 'L'
iterator.next(); // return 'e'
iterator.next(); // return 'e'
iterator.next(); // return 't'
iterator.next(); // return 'C'
iterator.next(); // return 'o'
iterator.next(); // return 'd'
iterator.hasNext(); // return true
iterator.next(); // return 'e'
iterator.hasNext(); // return false
iterator.next(); // return ' '
"""
class StringIterator(object):
def __init__(self, compressedString):
"""
:type compressedString: str
"""
self.num = 0
self.string = self.get_string(compressedString)
self.gen = self.my_gen()
def get_string(selif,compressedString):
res = []
num = ""
prev = compressedString[0]
for char in compressedString:
if char.isdigit():
num += char
if num and char.isalpha():
res.append((int(num),prev))
num = ""
prev = char
res.append((int(num),prev))
return res[::-1]
def my_gen(self):
while self.string:
self.num, char = self.string.pop()
while self.num > 0:
self.num -= 1
yield char
def next(self):
"""
:rtype: str
"""
return next(self.gen) if self.hasNext() else " "
def hasNext(self):
"""
:rtype: bool
"""
return True if self.string or self.num else False
# Your StringIterator object will be instantiated and called as such:
# obj = StringIterator(compressedString)
# param_1 = obj.next()
# param_2 = obj.hasNext()
class StringIterator:
def __init__(self, compressedString):
"""
:type compressedString: str
"""
self.position = 0
self.compressedString = compressedString
self.num = self.__next_num()
def __next_num(self):
i,num = 0, ""
flag = False
while i < len(self.compressedString):
while i < len(self.compressedString) and self.compressedString[i].isdecimal():
num += self.compressedString[i]
i+=1
flag = True
if flag:
self.position = i
break
i += 1
return int(num)
def next(self):
"""
:rtype: str
"""
ans = " "
if not self.hasNext():
return ans
ans = self.compressedString[0]
self.num -= 1
if self.num == 0:
self.compressedString = self.compressedString[self.position:]
if self.hasNext():
self.num = self.__next_num()
return ans
def hasNext(self):
"""
:rtype: bool
"""
return self.compressedString != ""
# Your StringIterator object will be instantiated and called as such:
# obj = StringIterator(compressedString)
# param_1 = obj.next()
# param_2 = obj.hasNext() |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
from collections import defaultdict
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
table = defaultdict(list)
level = 0
queue = deque([(level,root)])
while queue:
level,root = queue.popleft()
table[level].append(root.val)
if root.left:
queue.append((level+1,root.left))
if root.right:
queue.append((level+1,root.right))
return [table[i] for i in range(len(table)-1,-1,-1)] |
"""
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
""
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
"""
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return
table = {}
cur = head
while cur:
table[cur] = RandomListNode(cur.label)
cur = cur.next
cur = head
while cur:
table[cur].next = table.get(cur.next,None)
table[cur].random = table.get(cur.random,None)
cur = cur.next
return table[head]
"""
# Definition for a Node.
class Node:
def __init__(self, x, next=None, random=None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution(object):
def __init__(self):
self.table = {}
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return
if not head in self.table:
self.table[head] = Node(head.val)
self.table[head].next = self.copyRandomList(head.next)
self.table[head].random = self.copyRandomList(head.random)
return self.table[head]
|
"""
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Input: S = "3z4"
Output: ["3z4", "3Z4"]
Input: S = "12345"
Output: ["12345"]
Note:
S will be a string with length between 1 and 12.
S will consist only of letters or digits.
"""
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
res = []
def DFS(S,i):
if i == len(S):
res.append(S)
return
DFS(S, i+1)
if S[i].isalpha():
a = chr(ord(S[i]) ^ (1<<5))
DFS(S[:i] + a + S[i+1:],i+1)
DFS(S,0)
return res
|
"""
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Input: "Hello World"
Output: 5
"""
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
if not s:
return 0
else:
return len(s.split(" ")[-1])
def lengthOfLastWord2(self, s):
last = True
i = len(s) -1
count = 0
while i >= 0:
if s[i] == ' ' and last:
i -= 1
elif s[i] == ' ' and (not last):
return count
else:
count += 1
last = False
i -= 1
return count
class Solution:
def lengthOfLastWord(self, s: str) -> int:
count = 0
flag = True
for i in range(len(s)-1,-1,-1):
if flag and s[i] == ' ':
continue
if ord('a') <= ord(s[i]) <= ord('z') or ord('A') <= ord(s[i]) <= ord('Z'):
count += 1
flag = False
if s[i] == ' ':
break
return count
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.strip().split()[-1])
|
"""
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
Example:
Input: n = 12, primes = [2,7,13,19]
Output: 32
Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12
super ugly numbers given primes = [2,7,13,19] of size 4.
Note:
1 is a super ugly number for any given primes.
The given numbers in primes are in ascending order.
0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
"""
import heapq
class Solution:
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
count = 0
heap = [1]
pool = set([1])
while True:
num = heapq.heappop(heap)
for ugly in (num*prime for prime in primes):
if ugly in pool:
continue
else:
pool.add(ugly)
heapq.heappush(heap,ugly)
count += 1
if count == n:
return num
import heapq
class Solution:
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
pointers = [0] * len(primes)
ugly_seris = [1]
while len(ugly_seris) < n:
min_ = float("inf")
tmp_i = -1
for i in range(len(primes)):
if primes[i] * ugly_seris[pointers[i]] < min_:
min_ = primes[i] * ugly_seris[pointers[i]]
tmp_i = i
ugly_seris.append(min_)
pointers[tmp_i] += 1
return ugly_seris[-1]
class Solution:
"""时间复杂度高"""
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
pointers = [0] * len(primes)
ugly_seris = [1]
while len(ugly_seris) < n:
min_ = float("inf")
tmp_i = -1
for i in range(len(primes)):
tmp_nums = primes[i] * ugly_seris[pointers[i]]
if tmp_nums < min_:
min_ = tmp_nums
tmp_i = i
pointers[tmp_i] += 1
if min_ != ugly_seris[-1]:
ugly_seris.append(min_)
return ugly_seris[-1] |
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
ans = defaultdict(list)
for word in strs:
ans["".join(sorted(word))].append(word)
return list(ans.values())
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
table = {char:num for char,num in zip("abcdefghijklmnopqrstuvwxyz",range(26))}
def hash_num(string):
res = [0]*26
for char in string:
res[table[char]] += 1
return "".join(map(str,res))
res = defaultdict(list)
for string in strs:
res[hash_num(string)].append(string)
return list(res.values())
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
from collections import defaultdict
res_dict = defaultdict(list)
for str_ in strs:
s_str_ = "".join(sorted(list(str_)))
res_dict[s_str_].append(str_)
return [res_dict[_] for _ in res_dict ]
|
'''
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
'''
import operator
from functools import reduce
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for i in range(0,len(nums)-1,2):
if nums[i] != nums[i+1]:
return nums[i]
return nums[-1]
def singleNumber2(self,nums):
return reduce(operator.xor,nums)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
from functools import reduce
return reduce(lambda x, y: x^y, nums)
if __name__ == '__main__':
solution = Solution()
print(solution.singleNumber([4,1,2,1,2]))
print(solution.singleNumber2([4,1,2,1,2]))
|
"""
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
"""
class Solution:
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
if not wordDict:
return False
memo = {"":True}
wordSet = set(wordDict)
def rec_dp(s,wordSet,memo):
if s in memo:
return memo[s]
for i in range(len(s)):
if rec_dp(s[:i],wordSet,memo) and (s[i:] in wordSet):
memo[s] = True
return True
else:
memo[s] = False
return False
return rec_dp(s,wordSet,memo) |
"""
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
"""
def two2one(i, j, n):
return i * n + j
def one2two(k, n):
i = k // n
j = k % n
return [i, j]
def binary_search(matrix, target, l, r):
n = len(matrix[0])
l_, r_ = two2one(l[0], l[1], n), two2one(r[0], r[1], n)
if l_ > r_:
return False
mid = (l_ + r_) // 2
mid_i, mid_j = one2two(mid, n)
if matrix[mid_i][mid_j] == target:
return True
elif matrix[mid_i][mid_j] > target:
return binary_search(matrix, target, l, one2two(mid -1, n))
else:
return binary_search(matrix, target, one2two( mid +1, n), r)
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
return binary_search(matrix, target, [0,0], [len(matrix)-1, len(matrix[0])-1])
##
def search_column(matrix, target, l, r):
if l > r:
return -1
mid = (l + r) // 2
if matrix[mid][0] <= target:
if mid+1 < len(matrix) and matrix[mid+1][0] > target:
return mid
elif mid+1 >= len(matrix):
return mid
else:
return search_column(matrix, target, mid+1, r)
else:
return search_column(matrix, target, l, mid-1)
def seach_row(matrix, target, row, l, r):
if l > r:
return False
mid = (l + r) // 2
if matrix[row][mid] == target:
return True
elif matrix[row][mid] < target:
return seach_row(matrix, target, row, mid+1, r)
else:
return seach_row(matrix, target, row, l, mid-1)
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
row = search_column(matrix, target, 0, len(matrix)-1)
if row == -1:
return False
return seach_row(matrix, target, row, 0, len(matrix[0])-1)
|
"""
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。
进阶:
如果不得使用临时缓冲区,该怎么解决?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
visited = set()
dummy = tail = ListNode(0)
dummy.next = head
while head:
if head.val not in visited:
visited.add(head.val)
tail.next = head
tail = tail.next
head = head.next
tail.next = None
return dummy.next |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def merge(self,list1,list2):
dummy = ListNode(0)
cur = dummy
while list1 and list2:
if list1.val <= list2.val:
cur.next = list1
list1 = list1.next
else:
cur.next = list2
list2 = list2.next
cur = cur.next
if list1:
cur.next = list1
if list2:
cur.next = list2
return dummy.next
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
fast = head.next
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
middle = slow.next
slow.next = None
return self.merge(self.sortList(head),self.sortList(middle))
class Solution:
def merge(self,list1,list2):
dummy = ListNode(0)
tail = dummy
while list1 and list2:
if list1.val <= list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
if list1:
tail.next = list1
if list2:
tail.next = list2
while tail.next : tail = tail.next
return dummy.next,tail
# split the list into two parts, first n elements and the rest
def split(self,head,n):
while n > 1 and head:
head = head.next
n -= 1
rest = head.next if head else None
if head:
head.next = None
return rest
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
length = 0
cur = head
while cur:
length += 1
cur = cur.next
dummy = ListNode(0)
dummy.next = head
n = 1
while n < length:
cur = dummy.next
tail = dummy
while cur:
first = cur
cur = self.split(first,n)
second = cur
cur = self.split(second,n)
merged = self.merge(first,second)
tail.next = merged[0]
tail = merged[1]
n = n << 1
return dummy.next
|
"""
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
示例 2:
输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
限制:
1 <= k < s.length <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
n = n % len(s)
return s[n:] + s[:n]
|
"""
Given an array of integers A, consider all non-empty subsequences of A.
For any sequence S, let the width of S be the difference between the maximum and minimum element of S.
Return the sum of the widths of all subsequences of A.
As the answer may be very large, return the answer modulo 10^9 + 7.
Example 1:
Input: [2,1,3]
Output: 6
Explanation:
Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.
Note:
1 <= A.length <= 20000
1 <= A[i] <= 20000
"""
## TLE
class Solution:
def sumSubseqWidths(self, A: List[int]) -> int:
res = 0
def get_width(sub):
return max(sub) - min(sub)
def recursive(A, seq, pos):
nonlocal res
for i in range(pos, len(A)):
seq.append(A[i])
res += get_width(seq)
recursive(A, seq, i+1)
seq.pop()
recursive(A, [], 0)
return res % (10**9 + 7)
class Solution:
def sumSubseqWidths(self, A: List[int]) -> int:
"""
1. key obervation: sorting will not change the answer
2. A[i]'s contribution: A[i] * 2^i - A[i] * 2^(n-i-1)
"""
res = 0
init_prod = 2 ** len(A)
A.sort()
for i in range(len(A)):
if i == 0:
cum_prod_upper = 1
cum_prod_lower = (init_prod // cum_prod_upper) >> 1
else:
cum_prod_upper *= 2
cum_prod_lower >>= 1
res += (A[i] * cum_prod_upper - A[i]*cum_prod_lower)
return res % (10**9 + 7)
|
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedLIst:
def __init__(self):
self.ll = []
def add_last(self, item):
node = Node(item)
if self.ll != []:
self.ll[-1].next = node
self.ll.append(node)
def remove(self, index):
self.ll[index - 1].next = self.ll[index + 1]
self.ll.pop(index)
def count(self):
return len(self.ll)
def traverse(self):
rslt = []
for item in self.ll:
rslt.append(item.val)
return rslt
def peek(self):
return self.ll[0]
if __name__ == "__main__":
ll = LinkedLIst()
for i in range(10):
ll.add_last(i)
ll.add_last(20)
ll.add_last(0)
print(ll.count())
print(ll.traverse())
|
name = input('Enter your name: ')
print('hello', name)
hours = input('Enter Hours: ')
rate = input('Enter Rate: ')
pay = float(hours) * float(rate)
print(name, 'your pay is', pay)
|
f = float(input('Digite a temperatura em graus Fahrenheit: '))
c = 5.0 * (f - 32) / 9.0
print(f'A temperatura º{f} em Celsius é º{c}')
|
s = float(input('Salário atual: '))
ns = s + (s * 0.25)
print(f'Novo salário: {ns}')
|
n = int(input('Digite um número PAR: '))
if n % 2 != 0:
print(f'{n} não é PAR!')
else:
for i in range(0, n + 1):
if i % 2 == 0:
print(f'{i}')
|
d = int(input('Mês do ano 1 a 12: '))
if d == 1:
print('Janeiro')
elif d == 2:
print('Fevereiro')
elif d == 3:
print('Março')
elif d == 4:
print('Abril')
elif d == 5:
print('Maio')
elif d == 6:
print('Junho')
elif d == 7:
print('Julho')
elif d == 8:
print('Agosto')
elif d == 9:
print('Setembro')
elif d == 10:
print('Outubro')
elif d == 11:
print('Novembro')
elif d == 12:
print('Dezembro')
elif d < 0 or d > 12:
print('Mês inválido')
|
import math
n = 1
while n > 0:
n = int(input('Informe um número: '))
print(f'Quadrado: {n * n} \n'
f'Cubo: {n * n * n} \n'
f'Raiz quadrada: {round(math.sqrt(n), 2)}')
|
r = float(input('Valor R$: '))
d = float(input('Cotação U$: '))
print(f'Valor R${r} em U${r / d}.')
|
ag = int(input('Informe sua idade: '))
tt = int(input('Informe o tempo de trabalho: '))
if ag >= 65:
print(f'Aposentadoria aprovada, {ag} anos de idade.')
elif tt >= 30:
print(f'Aposentadoria aprovada, {tt} anos trabalhados.')
elif ag >= 60 and tt >= 25:
print(f'Aposentadoria aprovada!\n'
f'{ag} anos de idade\n'
f'{tt} anos trabalhados.')
else:
print('Aposentadoria negada por tempo de trabalho ou idade insuficiente.')
|
n = int(input('Informe um número: '))
e = 1 + 1 / (1 * 1) + 1 / (2 * 2) + 1 / (3 * 3) + n + 1 / (n * n)
print(f'Valor de E: {round(e, 2)}')
|
age = int(input('Informe a idade do nadador: '))
# noinspection PyChainedComparisons
if age >= 5 and age < 8:
print(f'Infantil A: {age} anos de idade.')
elif age >= 8 and age < 11:
print(f'Infantil B: {age} anos de idade.')
elif age >= 11 and age < 14:
print(f'Juvenil A: {age} anos de idade.')
elif age >= 14 and age < 18:
print(f'Juvenil B: {age} anos de idade.')
else:
print(f'Sênior: {age} anos de idade.')
|
n = int(input('Digite um número para saber se Par ou Impar: '))
if n % 2 != 0:
print(f'Número {n} é IMPAR.')
else:
print(f'Número {n} é PAR.')
|
import math
a = float(input('Valor de A: '))
b = float(input('Valor de B: '))
h = math.sqrt(a * a) + math.sqrt(b * b)
print(f'Teste {h}')
|
r1 = 0
r2 = 0
r = 1
while r != 0:
r1 = int(input('Resistor 1: '))
r2 = int(input('Resistor 2: '))
r = (r1 * r2) / (r1 + r2)
print(f'Resistor: {round(r, 2)}')
|
a = 0
b = 0
c = 0
d = 0
mArit = 0
while a < 10 or a > 20 or b < 10 or b > 20 or c < 10 or c > 20 or d < 10 or d > 20:
a = int(input('A: '))
b = int(input('B: '))
c = int(input('C: '))
d = int(input('D: '))
if a < 10 or a > 20 or b < 10 or b > 20 or c < 10 or c > 20 or d < 10 or d > 20:
break
else:
mArit = (a + b + c + d) / 4
print(f'Média aritmética: {mArit}')
|
#Class that communicate with database in sqlite
import sqlite3
import random
class Database:
def __init__(self):
self.conn = sqlite3.connect('lista_dan.db')
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS dania (id INTEGER PRIMARY KEY, danie TEXT, skladniki TEXT)")
self.conn.commit()
def draw(self):
self.cur.execute('SELECT MAX(id) FROM dania')
rows_amount = self.cur.fetchall()
x = rows_amount[0][0]
if not x:
return 'Baza pomysłów jest pusta'
row = False
while not row:
random_id = random.randint(0, x)
self.cur.execute("SELECT * FROM dania WHERE id=?", (random_id,))
row = self.cur.fetchall()
return row
def all(self):
self.cur.execute("SELECT * FROM dania ORDER BY danie")
rows = self.cur.fetchall()
if not rows:
return ['Baza pomysłów jest pusta']
return rows
def show_ingredients(self, danie):
self.cur.execute("SELECT skladniki FROM dania WHERE danie=?", (danie,))
row = self.cur.fetchall()
print(row)
return row
def insert(self, danie, skladniki):
self.cur.execute("INSERT INTO dania VALUES (NULL,?,?)", (danie, skladniki))
self.conn.commit()
def delete(self, danie):
self.cur.execute("DELETE FROM dania WHERE danie=?", (danie,))
self.conn.commit()
def check(self, danie):
self.cur.execute("SELECT 1 WHERE EXISTS (SELECT danie FROM dania WHERE danie=?)", (danie,))
result = self.cur.fetchone()
print(result)
return result
def __del__(self):
self.conn.close()
|
import urllib
from BeautifulSoup import BeautifulSoup as bs
response = urllib.urlopen('http://www.jiandan.net','r')
html = response.read()
soup = bs(html)
for a in soup('a'):
print a
|
#coding=utf-8
'''
定义一个集合的操作类:Setinfo
包括的方法:
1 集合元素添加: add_setinfo(keyname) [keyname:字符串或者整数类型]
2 集合的交集:get_intersection(unioninfo) [unioninfo :集合类型]
3 集合的并集: get_union(unioninfo)[unioninfo :集合类型]
4 集合的差集:del_difference(unioninfo) [unioninfo :集合类型]
set_info = Setinfo(你要操作的集合)
'''
a = set([1,3,4,5])
class Setinfo(object):
def add_setinfo(self,keyname):
self.keyname = keyname
a.add(keyname)
return a
def get_intersection(self,s):
self.s = s
return a & self.s
def get_union(self,b):
self.b = b
return a | self.b
setinfo = Setinfo()
print setinfo.add_setinfo('abc')
print setinfo.get_intersection(set([3,4,1,7,12]))
print setinfo.get_union(set([1,5,'heeeello']))
|
#coding=utf-8
class boy(object):
genous = 1
def __init__(self,name):
self.name = name
class girl(object):
genous = 0
def __init__(self,name):
self.name = name
class love():
def __init__(self,first,second):
self.first = first
self.second = second
def meet(self):
return '这是%s和%s的恋爱'%(self.first.name,self.second.name)
class normal_love(love):
def __init__(self,first,second):
if 1 != first.genous + second.genous:
print '对象引入错误'
else:
love.__init__(self,first, second)
class gay_love(love):
def __init__(self,first,second):
if 2 != first.genous + second.genous:
print '对象引入错误'
else:
love.__init__(self,first, second)
class girl_love(love):
def __init__(self,first,second):
if 0 != first.genous + second.genous:
print '对象引入错误'
else:
love.__init__(self,first, second)
xiaoming = boy('小明')
xiaohong = girl('小红')
normal = normal_love(xiaoming, xiaohong)
print normal.meet()
|
"""
Sample donors
"""
def get_donors():
thomas = 'Thomas', {'donations': '500', 'email': 'thomas@thomas.com', 'city': 'Athens', 'state': 'GA', 'zip': '30606'}
ted = 'Ted', {'donations': '1', 'email': 'ted@ted.com', 'city': 'Memphis', 'state': 'TN', 'zip': '38104'}
bailey = "Bailey", {'donations': '1000', 'email': 'bailey@bailey.com', 'city': 'Washington', 'state': 'DC', 'zip': '12345'}
return thomas, ted, bailey
if __name__ == "__main__":
donors = get_donors()
for item in donors:
print(item) |
#!/usr/bin/env python3
__author__ = "roy_t githubtater"
import pandas as pd
music = pd.read_csv('featuresdf.csv')
def danceable_closure():
"""Return a function of songs of given danceability"""
def danceable(danceability=0.8):
"""Generator returning songs with danceability over a given value"""
tracks = ((round(dance, 3), artist, song_name)
for dance, artist, song_name in zip(music.danceability, music.artists, music.name)
if dance >= danceability)
return tracks
return danceable
def print_danceables(iterable):
"""Function to print an iterable, including generators"""
print('Top Danceable Tracks of 2017')
format_str = '{:<15}{:<20}{:<20}'
print(format_str.format('Danceability', 'Artist', 'Song'))
for artist_combo in sorted(iterable, reverse=True):
print(format_str.format(*artist_combo))
print('\n')
def main():
# create the intial generator object
danceable_tracks = danceable_closure()
print_danceables(danceable_tracks())# passing no arguments with danceable_tracks uses default danceability == 0.8
# Using the same generator object, get danceable tracks over 0.9 by passing the parameter
print_danceables(danceable_tracks(0.9))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# Lesson 03 - Context Manager
"""
Write a context manager class Locke to simulate the overall functioning of the system.
When the locke is entered it stops the pumps, opens the doors, closes the doors,
and restarts the pumps.
Likewise when the locke is exited it runs through the same steps:
it stops the pumps, opens the doors, closes the doors, and restarts the pumps.
Don’t worry for now that in the real world there are both upstream and downstream doors,
and that they should never be opened at the same time; perhaps you’ll get to that later.
During initialization the context manger class accepts the locke’s capacity in number of boats.
If someone tries to move too many boats through the locke, anything over its established capacity,
raise a suitable error. Since this is a simulation you need do nothing more
than print what is happening with the doors and pumps, like this:
"""
class Locke:
def __init__(self, boats):
self.boats = boats
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is ValueError:
print(exc_val)
return True
def move_boats_through(self, num_boats):
if num_boats < self.boats:
print("There is still room for your boats! Proceed")
print("Stopping the pumps.")
print("Opening the doors.")
print("Closing the doors.")
print("Restarting the pumps.")
else:
raise ValueError(
"Too many boats have come through today. Try again tomorrow!")
if __name__ == "__main__":
small_locke = Locke(5)
large_locke = Locke(10)
boats = 8
print("Large Locke Test")
print()
# A lock with sufficient capacity can move boats without incident.
with large_locke as locke:
locke.move_boats_through(boats)
print()
print("Small Locke Test")
# Too many boats through a small locke will raise an exception
with small_locke as locke:
locke.move_boats_through(boats)
|
# ------------------------------------------------- #
# Title: Lesson 1, pt 1, Song Assignment
# Dev: Craig Morton
# Date: 11/5/2018
# Change Log: CraigM, 11/5/2018, Song Assignment
# ------------------------------------------------- #
# !/usr/bin/env python3
import pandas as pd
music = pd.read_csv("featuresdf.csv")
songs_for_dancing = [x for x in zip(music.name, music.danceability, music.loudness) if x[1] > 0.8 and x[2] < -5]
def song_getter(dance):
"""Get songs with danceability scores above 0.8"""
return dance[1]
song_list = sorted(songs_for_dancing, key=song_getter, reverse=True)
print("\nSongs list:\n")
for songs in songs_for_dancing[0:5]:
print(songs[0])
|
#!/usr/bin/env python3
import pandas as pd
music = pd.read_csv("featuresdf.csv")
ml = [x for x in zip(music.name, music.artists, music.danceability, music.loudness) if x[2]>0.8 and x[3]<-5]
# use sort instead of sorted .. --> sort does not return a list, it sorts the list itself
ml.sort(key=lambda x:x[2], reverse=True)
print ("\n\tmusic.name\tmusic.artist\tdanceability > 0.8\tloudness < -5.0", "\n\t", "**"*30)
for top_song in ml[0:5]: print("\t", top_song)
|
'''
Lesson 3 Assignment #2
Recursive
'''
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(10))
|
#!/usr/bin/env python3
__author__ = "roy_t githubtater"
import unittest
import generators as gen
class TestGenerators(unittest.TestCase):
def test_sum_of_integers(self):
sum_gen = gen.sum_of_integers()
assert next(sum_gen) == 0
assert next(sum_gen) == 1
assert next(sum_gen) == 3
assert next(sum_gen) == 6
assert next(sum_gen) == 10
assert next(sum_gen) == 15
def test_doubler(self):
dub_gen = gen.doubler()
assert next(dub_gen) == 1
assert next(dub_gen) == 2
assert next(dub_gen) == 4
assert next(dub_gen) == 8
assert next(dub_gen) == 16
assert next(dub_gen) == 32
def test_fibonacci_sequence(self):
fib_gen = gen.fibonacci_sequence()
assert next(fib_gen) == 0
assert next(fib_gen) == 1
assert next(fib_gen) == 1
assert next(fib_gen) == 2
assert next(fib_gen) == 3
assert next(fib_gen) == 5
assert next(fib_gen) == 8
assert next(fib_gen) == 13
assert next(fib_gen) == 21
assert next(fib_gen) == 34
def test_prime_numbers(self):
prim_gen = gen.prime_numbers()
assert next(prim_gen) == 2
assert next(prim_gen) == 3
assert next(prim_gen) == 5
assert next(prim_gen) == 7
assert next(prim_gen) == 11
assert next(prim_gen) == 13
def test_squared_nums(self):
sq_gen = gen.squared_nums()
for i in range(1, 10):
assert next(sq_gen) == i*i
def test_cubed_nums(self):
cube_gen = gen.cubed_nums()
for i in range(1, 10):
assert next(cube_gen) == i**3
def test_count_by_threes(self):
vals = [0, 3, 6, 9, 12, 15, 18]
c = gen.count_by_threes()
for i in range(len(vals)):
assert next(c) == vals[i]
def test_minus_7(self):
vals = [0, -7, -14, -21, -28, -35, -42, -49]
m = gen.minus_7()
for i in range(len(vals)):
assert next(m) == vals[i]
if __name__ == "__main__":
unittest.main() |
"""Divides two numbers"""
class Divider():
"""Class for divider"""
@staticmethod
def calc(operand_1, operand_2):
"""Perform division"""
try:
return operand_1/operand_2
except ZeroDivisionError:
return False
|
"""
Lesson 9 submision file.
Uses News API to get titles with multithreading.
"""
#orioginal API = "0c90527956054643acefdedb6587d07f"
#alt API 1 = "74c1d999b2bb43feaabb8c3c194fe5b3"
import time
import requests
import threading
import queue
WORD = "Boeing"
NEWS_API_KEY = "74c1d999b2bb43feaabb8c3c194fe5b3"
base_url = 'https://newsapi.org/v1/'
def get_sources():
url = base_url + "sources"
params = {"language": "en", "apiKey": NEWS_API_KEY}
response = requests.get(url, params=params).json()
sources = [src['id'].strip() for src in response['sources']]
print("all the sources")
print(sources)
return sources
def get_articles(source):
url = base_url + "articles"
params = {'source': source,
'apiKey': NEWS_API_KEY,
'sortBy': 'top',
}
print("requesting (get articles):", source)
resp = requests.get(url, params=params)
if resp.status_code != 200:
print('something went wrong with {}'.format(source))
print(resp)
print(resp.text)
return[]
data = resp.json()
titles = [str(art['title']) + ' ' + str(art['description']) for art in data['articles']]
#print(titles)
return titles
def count_word(word, titles):
word = word.lower()
count = 0
#print(word)
for title in titles:
#print(title)
if word in title.lower():
count += 1
return count
def queue_handler(source):
q.put(get_articles(source))
q = queue.Queue()
start = time.time()
sources = get_sources()
#test with partial sources because of API limits
#sources = ['the-new-york-times','associated-press', 'bbc-news','google-news','reuters']
art_count = 0
word_count = 0
threads = []
for source in sources:
thread = threading.Thread(target=queue_handler, args=(source,))
thread.start()
threads.append(thread)
#added to see threads
print(thread.name)
for thread in threads:
print("join", thread.name)
thread.join()
while not q.empty():
queue_titles = q.get()
for title in queue_titles:
art_count += 1
#print(title)
if WORD.lower() in title.lower():
word_count += 1
#print(count)
print(WORD, 'found {} times in {} articles'.format(word_count, art_count))
print('Process took {:.0f} seconds'.format(time.time()-start)) |
# implements a recursive factorial function
def factorial(n):
return 1 if (n < 1) else n * factorial(n-1)
print(factorial(0))
print(factorial(5))
print(factorial(10))
print(factorial(15))
|
#!/usr/bin/env python3
__author__ = 'roy_t'
# this function was 'borrowed' from the following text:
# Lott, S. (2015) Chapter 6. Recursions and Reductions. In Functional Python Programming.
def factorial(n):
"""Return the factorial of n"""
if n == 0: return 1
# otherwise: recurse through the function until the final call, n*1, stopping the recursion.
else: return n*factorial(n-1)
def factorial_report(n, fac):
"""Print a report of factorials and their values"""
format_str = '{:>5}! = {:<10}'
print(format_str.format(n, fac))
def main():
# begin by printing a title
title = ' Factorials '
print('\n{:*^20}'.format(title))
# start the loop and print the resulting factorial
for i in range(10):
factorial_report(i, factorial(i))
if __name__ == '__main__':
main() |
"""
Module to populate our sqlite database with people.
"""
import logging
import db_printer
from database_ex import *
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(name=__name__)
database = SqliteDatabase('personjob.db')
def calc_days(day_1, day_2):
""" Calculates the number of days between two dates using datetime. """
date1, date2 = datetime.strptime(day_1, '%Y-%m-%d'), datetime.strptime(day_2, '%Y-%m-%d')
return abs((date2 - date1).days)
def populate_people():
"""
Populates the database with people info.
"""
PERSON_NAME = 0
LIVES_IN_TOWN = 1
NICKNAME = 2
info = [
("Theodore", "Charleston", "Ted"),
("Theo", "Memphis", None),
("Michael", "Athens", "Mike")
]
logger.info("Populating people database")
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for person in info:
with database.transaction():
new_person = Person.create(
person_name = person[PERSON_NAME],
lives_in_town = person[LIVES_IN_TOWN],
nickname = person[NICKNAME]
)
new_person.save()
logger.info("Database person saved.")
for saved_person in Person:
logger.info(f'{saved_person.person_name} lives in {saved_person.lives_in_town} ' +\
f'and likes to be known as {saved_person.nickname}')
except Exception as e:
logger.error(f"Unable to make database changes:\n{e}")
finally:
logger.info("Database closed.")
database.close()
def populate_department():
"""
Populates the database with department info.
"""
DEPARTMENT_NUMBER = 0
DEPARTMENT_NAME = 1
DEPARTMENT_MANAGER = 2
info = [
("BANK", "Banking", "Toby"),
("ACCT", "Accounting", "Chris"),
("TCHR", "Teaching", "Teddy")
]
logger.info("Populating department database.")
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for dept in info:
with database.transaction():
new_dept = Department.create(
department_number = dept[DEPARTMENT_NUMBER],
department_name = dept[DEPARTMENT_NAME],
department_manager = dept[DEPARTMENT_MANAGER]
)
new_dept.save()
logger.info("Printing department records saved.")
for saved_department in Department:
logger.info(f"{saved_department.department_name}'s number is {saved_department.department_number} and managed by {saved_department.department_manager}")
except Exception as e:
logger.error(f"Unable to make database changes:\n{e}")
finally:
logger.info("Database closed.")
database.close()
def populate_jobs():
"""
Populates the database with job info.
"""
# Tuple positions
JOB_NAME = 0
START_DATE = 1
END_DATE = 2
SALARY = 3
PERSON_EMPLOYED = 4
DEPARTMENT = 5
# List of tuples containing static database info
info = [
('Bank Teller', '2018-01-01', '2018-08-31', 30000, 'Theo', 'BANK'),
('Bean Counter', '2014-05-01', '2017-12-31', 80000, 'Theodore', 'ACCT'),
('Musician', '2013-05-01', '2016-12-31', 90000, 'Michael', 'TCHR')
]
logger.info("Populating job database.")
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for job in info:
with database.transaction():
new_job = Job.create(
job_name = job[JOB_NAME],
start_date = job[START_DATE],
end_date = job[END_DATE],
job_duration = calc_days(job[END_DATE], job[START_DATE]),
salary = job[SALARY],
person_employed = job[PERSON_EMPLOYED],
job_department = job[DEPARTMENT]
)
new_job.save()
logger.info("Job info saved.")
logger.info("Printing job records saved.")
logger.info('Print the Job records we saved...')
for saved_job in Job:
logger.info(f'{saved_job.person_employed} worked in the '
f'{saved_job.job_department} department as a '
f'{saved_job.job_name} for {saved_job.job_duration} '
f'days, from {saved_job.start_date} to '
f'{saved_job.end_date} with a salary of '
f'{saved_job.salary}.')
except Exception as e:
logger.error(f"Unable to make JOB changes : JOBS :\n{e}")
finally:
logger.info("Database closed.")
database.close()
if __name__ == "__main__":
populate_people()
populate_department()
populate_jobs()
db_printer.printer()
|
from operations_database import *
choices = {1: send_thankyou,
2: create_report,
3: send_letters,
4: close_program
}
def user_input():
try:
action = int(input("\nChoose one of four actions: \n"+
"1. Send a Thank You \n" +
"2. Create a Report \n"+
"3. Send Letter to Everyone \n"+
"4. Quit\n"
))
except ValueError:
print("\nEnter 1 to 'Send a Thank You', 2 to 'Create a Report',3 to 'Send Letter to Everyone', " +
"4 to 'Quit'\n")
else:
if action not in choices:
print("\nEnter 1 to 'Send a Thank You', 2 to 'Create a Report',3 to 'Send Letter to Everyone', " +
"4 to 'Quit'\n")
return action
def main():
action = 0
while action != 4:
try:
action = user_input()
choices[action]()
except KeyError:
print("Please enter a number from the options given")
if __name__ == "__main__":
main()
|
# ------------------------------------------------- #
# Title: Lesson 3, Recursion/Factorial Assignment
# Dev: Craig Morton
# Date: 11/25/2018
# Change Log: CraigM, 11/25/2018, Recursion/Factorial Assignment
# ------------------------------------------------- #
#!/usr/bin/env python3
def factorial(n):
""""Determines factorial of n recursively"""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
if __name__ == '__main__':
print(factorial(3))
print(factorial(6))
print(factorial(12))
print(factorial(24))
|
'''
Lesson 1 Generator Draft 1
'''
def intsum(x=0, total=0):
while True:
total += x
yield total
x += 1
def doubler(x=1):
while True:
yield x
x *= 2
def fib(a=0, b=1):
while True:
a, b = b, a+b
yield a
def prime(x=2):
while True:
for i in range(2,x):
if x%i == 0:
break
else:
yield x
x += 1
|
"""
Unit tests for the water-regulation module
"""
import unittest
from unittest.mock import MagicMock
from pump import Pump
from sensor import Sensor
from .controller import Controller
from .decider import Decider
class DeciderTests(unittest.TestCase):
"""
Unit tests for the Decider class
"""
def test_actions(self):
"""
Just some example syntax that you might use
"""
actions = {
'PUMP_IN': Pump.PUMP_IN,
'PUMP_OUT': Pump.PUMP_OUT,
'PUMP_OFF': Pump.PUMP_OFF
}
pump_off = Pump.PUMP_OFF
pump_in = Pump.PUMP_IN
pump_out = Pump.PUMP_OUT
target = 100
margin = 0.05
above = 106
below = 94
meet = 100
decider = Decider(target, margin)
self.assertEqual(decider.decide(below, pump_off, actions), pump_in)
self.assertEqual(decider.decide(above, pump_off, actions), pump_out)
self.assertEqual(decider.decide(meet, pump_off, actions), pump_off)
self.assertEqual(decider.decide(above, pump_in, actions), pump_off)
self.assertEqual(decider.decide(below, pump_in, actions), pump_in)
self.assertEqual(decider.decide(meet, pump_in, actions), pump_in)
self.assertEqual(decider.decide(above, pump_out, actions), pump_out)
self.assertEqual(decider.decide(below, pump_out, actions), pump_off)
self.assertEqual(decider.decide(meet, pump_out, actions), pump_out)
class ControllerTests(unittest.TestCase):
"""
Unit tests for the Controller class
"""
def setUp(self):
"""Setup docstring."""
address = "127.0.0.1"
port = "8000"
self.sensor = Sensor(address, port)
self.pump = Pump(address, port)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
def tearDown(self):
"""Teardown docstring."""
pass
def test_tick(self):
"""Method docstring."""
self.sensor.measure = MagicMock(return_value=90)
self.pump.get_state = MagicMock(return_value=Pump.PUMP_OFF)
self.decider.decide = MagicMock(return_value=Pump.PUMP_IN)
self.pump.set_state = MagicMock(return_value=True)
self.controller.tick()
self.sensor.measure.assert_called_with()
self.pump.get_state.assert_called_with()
self.decider.decide.assert_called_with(90, self.pump.PUMP_OFF,
self.controller.actions)
self.pump.set_state.assert_called_with(self.pump.PUMP_IN)
|
#!/usr/bin/env python
""" Simple iterator examples """
class IterateMe_1:
"""
Simple iterator - returns the sequence of numbers from zero to 4
( like range(4) )
"""
def __init__(self, stop=5):
self.current = -1
self.stop = stop
def __iter__(self):
return self
def __next__(self):
self.current += 1
if self.current < self.stop:
return self.current
else:
raise StopIteration
class IterateMe_2():
""" Iterator designed to match functionality of 'range' """
def __init__(self, start, stop, step=1):
self.start = start
self.stop = stop
self.step = step
self.values = [val for val in self.collection()]
def collection(self):
current = self.start
while current < self.stop:
yield(current)
current += self.step
def __iter__(self):
return iter(self.values)
def __getitem__(self, index):
return self.values[index]
def __repr__(self):
return "IterateMe_2({}, {}, {})".format(self.start, self.stop, self.step)
if __name__ == "__main__":
print("Testing iterator_1")
for i in IterateMe_1():
print(i)
print("\nTesting iterartor_2")
it = IterateMe_2(2, 20, 2)
for i in it:
if i > 10: break
print(i)
print("Breaking after 10...\n")
print("Picking up after breaking...")
for i in it:
print(i)
|
#!/usr/bin/env python3
import pandas as pd
music = pd.read_csv("featuresdf.csv")
def main():
string_format = "{:<20} | {:<20}"
songs = drake_generator()
print("{:<20} | {:<20}".format("Tracks", "Artist"))
print("-"*35)
for i in songs:
print(string_format.format(*i))
# Generator that finds all of Drake's songs
def drake_generator():
for x in zip(music.name, music.artists):
if (x[1] == "Drake"):
yield x
if __name__ == "__main__":
main()
|
import math
def intsum():
i = sum = 0
while True:
sum += i
i += 1
yield sum
def intsum2():
i = sum = 0
while True:
sum += i
i += 1
yield sum
def doubler():
i = sum = 1
while True:
yield i
i = i * 2
def fib():
i, j = 0, 1
while True:
i, j = j, i + j
yield i
def prime():
n = 1
# see if n is divisible by any number up to the square root of n
while True:
prime = False
while not prime:
n += 1
cnt = [i for i in range(2, int(math.sqrt(n)) + 1) if n % i == 0]
if not cnt: prime = True
yield n
|
#!/usr/bin/env python3
# Lesson 01, Comprehensions
import pandas as pd
music = pd.read_csv("featuresdf.csv")
toptracks = sorted([x for x in zip(music.danceability, music.loudness, music.artists, music.name) if x[0] > 0.8 and x[1] < -5], reverse=True)
for track in toptracks[:5]:
print(track[3] + " by " + track[2]) |
def factorial(num):
if num <= 1:
return 1
else:
return num * factorial(num-1)
if __name__ == "__main__":
results = (1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200)
for i in range(0, len(results)):
assert results[i] == factorial(i)
|
"""defines adder object"""
class Adder:
"""adder object to be used in calculator"""
@staticmethod
def calc(operand_1, operand_2):
"""runs addtion for calc call"""
return operand_1 + operand_2
|
#!/usr/bin/env python
"""
Get artists and song names for for tracks with danceability scores over 0.8 and loudness scores below -5.0.
In other words, quiet yet danceable tracks.
Also, these tracks should be sorted in descending order by danceability so that the most danceable tracks are up top.
"""
import pandas as pd
music = pd.read_csv("featuresdf.csv")
# Songs with danceability scores over 0.8
danceable = [x for x in music.danceability if x > 0.8]
# Get the artist and song name from 'music' where danceability > 0.8 and loudness < -5.0
results = sorted([(a, b, c, d) for a, b, c, d in zip(music.name, music.artists, music.danceability, music.loudness) if
c > 0.8 and d < -5], key=lambda tup: tup[2], reverse=True)
final_results = [(a[0], a[1]) for a in results]
print(final_results)
|
"""This is an Adder"""
class Adder(object):
"""Do the adding"""
@staticmethod
def calc(operand_1, operand_2):
"""Add"""
return operand_1 + operand_2
|
"""
mongodb homework assignment
"""
import pprint
import login_database
import utilities
log = utilities.configure_logger('default', '../logs/mongodb_assignment.log')
def add_furniture():
"""
mongodb assignment - add furniture items, separate the product field into
two fields: product type and color. Write a mongodb query to retrieve and
print just the red products, then just the couches.
"""
furniture_data = [
{
'product type': 'couch',
'color': 'red',
'description': 'Leather low back',
'monthly_rental_cost': 12.99,
'in_stock_quantity': 10
},
{
'product type': 'couch',
'color': 'blue',
'description': 'Cloth high back',
'monthly_rental_cost': 9.99,
'in_stock_quantity': 3
},
{
'product type': 'Coffee table',
'color': 'brown',
'description': 'Plastic',
'monthly_rental_cost': 2.50,
'in_stock_quantity': 25
},
{
'product type': 'couch',
'color': 'red',
'description': 'Leather high back',
'monthly_rental_cost': 15.99,
'in_stock_quantity': 17
},
{
'product type': 'recliner',
'color': 'blue',
'description': 'Leather high back',
'monthly_rental_cost': 19.99,
'in_stock_quantity': 6
},
{
'product type': 'Chair',
'color': 'red',
'description': 'Plastic',
'monthly_rental_cost': 1.00,
'in_stock_quantity': 45
},
{
'product type': 'barstool',
'color': 'orange',
'description': 'metal',
'monthly_rental_cost': 3.00,
'in_stock_quantity': 23
},
{
'product type': 'desk',
'color': 'purple',
'description': 'wood',
'monthly_rental_cost': 200.00,
'in_stock_quantity': 1
},
{
'product type': 'bed',
'color': 'white',
'description': 'wood',
'monthly_rental_cost': 89.99,
'in_stock_quantity': 5
}
]
with login_database.login_mongodb_cloud() as client:
log.info('Step 1: We are going to use a database called dev')
log.info('But if it doesnt exist mongodb creates it')
db = client['dev']
log.info('And in that database use a collection called furniture')
log.info('If it doesnt exist mongodb creates it')
furniture = db['furniture']
log.info('Step 2: Now we add data from the dictionary above')
furniture.insert_many(furniture_data)
log.info('Step 3: Find the products that are red.')
query = {'color': 'red'}
results = furniture.find(query)
log.info('Step 4: Print the red products')
print('Red products')
for result in results:
pprint.pprint(result)
log.info('Step 5: Find the couches.')
query = {'product type': 'couch'}
results = furniture.find(query)
log.info('Step 6: Print the couches.')
print('Couches')
for result in results:
pprint.pprint(result)
log.info('Step 7: Delete the collection so we can start over')
db.drop_collection('furniture')
|
"""Module for dividing two numbers"""
class Divider(object):
"""Class for division of 2 numbers."""
@staticmethod
def calc(operand_1, operand_2):
""" Perforn the division step."""
return operand_1/operand_2
|
"""
Student: Jared Mulholland
Assignment: Calculator Unit Tests
Date: 7/17/2019
"""
from unittest import TestCase
from unittest.mock import MagicMock
from calculator.adder import Adder
from calculator.subtracter import Subtracter
from calculator.divider import Divider
from calculator.multiplier import Multiplier
from calculator.calculator import Calculator
from calculator.exceptions import InsufficientOperands
class AdderTests(TestCase):
"""tests for adder method"""
def test_adding(self):
"""confirm adder returns expected result"""
adder = Adder()
for i in range(-10, 10):
for j in range(-10, 10):
self.assertEqual(i+j, adder.calc(i, j))
class SubtracterTests(TestCase):
"""tests for subtractor method"""
def test_subtracter(self):
"""confirm subtracter returns expected result"""
subtracter = Subtracter()
for i in range(-10, 10):
for j in range(-10, 10):
self.assertEqual(i-j, subtracter.calc(i, j))
class MultiplierTests(TestCase):
"""tests for multiplier method"""
def test_multiplier(self):
"""confirm multiplier returns expected result"""
multiplier = Multiplier()
for i in range(-10, 10):
for j in range(-10, 10):
self.assertEqual(i*j, multiplier.calc(i, j))
class DividerTests(TestCase):
"""tests for divider method"""
def test_divider(self):
"""confirm divider returns expected result"""
divider = Divider()
for i in range(-10, 10):
for j in range(1, 10):
self.assertEqual(i/j, divider.calc(i, j))
class CalculatorTests(TestCase):
"""Tests for calculator method"""
def setUp(self):
"""setup for calculator tests"""
self.adder = Adder()
self.subtracter = Subtracter()
self.multiplier = Multiplier()
self.divider = Divider()
self.calculator = Calculator(self.adder, self.subtracter, self.multiplier, self.divider)
def test_insufficient_operands(self):
"""error raised when only one number entered"""
self.calculator.enter_number(0)
with self.assertRaises(InsufficientOperands):
self.calculator.add()
def test_adder_call(self):
"""tests adder method is called correctly"""
self.adder.calc = MagicMock(return_value=0)
self.calculator.enter_number(1)
self.calculator.enter_number(2)
self.calculator.add()
self.adder.calc.assert_called_with(1, 2)
def test_subtracter_call(self):
"""tests subtracter method is called correctly"""
self.subtracter.calc = MagicMock(return_value=0)
self.calculator.enter_number(1)
self.calculator.enter_number(2)
self.calculator.subtract()
self.subtracter.calc.assert_called_with(1, 2)
def test_divider_call(self):
"""tests divider method is called correctly"""
self.divider.calc = MagicMock(return_value=0)
self.calculator.enter_number(1)
self.calculator.enter_number(2)
self.calculator.divide()
self.divider.calc.assert_called_with(1, 2)
def test_multiplier_call(self):
"""tests multiplier method is called correctly"""
self.multiplier.calc = MagicMock(return_value=0)
self.calculator.enter_number(1)
self.calculator.enter_number(2)
self.calculator.multiply()
self.multiplier.calc.assert_called_with(1, 2)
|
"""
This module provides a subtraction operator
"""
class Subtracter(object):
"""
Provides a subtraction method
"""
@staticmethod
def calc(operand_1, operand_2):
"""
Subtracts the second number input from the first
"""
return operand_1 - operand_2
|
"""A simple calculator."""
from .exceptions import InsufficientOperands
class Calculator(object):
"""An object to encapsulate a simple calculator."""
def __init__(self, adder, subtracter, multiplier, divider):
"""Initializor for the calculator."""
self.adder = adder
self.subtracter = subtracter
self.multiplier = multiplier
self.divider = divider
self.stack = []
def enter_number(self, number):
"""API to push a # onto the calculator's stack."""
self.stack.insert(0, number)
def _do_calc(self, operator):
"""Helper to run a calculation (e.g., add, subtract)."""
try:
result = operator.calc(self.stack[1], self.stack[0])
except IndexError:
raise InsufficientOperands
self.stack = [result]
return result
def add(self):
"""Add operation."""
return self._do_calc(self.adder)
def subtract(self):
"""Subtract operation."""
return self._do_calc(self.subtracter)
def multiply(self):
"""Multiply operation."""
return self._do_calc(self.multiplier)
def divide(self):
"""Divide operation."""
return self._do_calc(self.divider)
|
import pandas as pd
# Read in Spotify's top 100 songs
music = pd.read_csv("featuresdf.csv")
def sheeran_songs(df):
"""Generator returns Ed Sheeran songs from the provided dataframe."""
for title, artists in zip(df.name, df.artists):
if 'Ed Sheeran' in artists:
yield title
# Print Ed Sheeran songs with header
print('Ed Sheeran Songs From the Spotify Top 100 List')
for song in sheeran_songs(music):
print(song)
def make_energy_limit(df, energy_limit):
"""
Closure returns a function that generates songs above the specified
energy level.
"""
def energy_above():
nonlocal df
nonlocal energy_limit
for title, artists, energy in zip(df.name, df.artists, df.energy):
if energy > energy_limit:
yield title, artists, energy
return energy_above
# Create generator for songs with energy above 0.8
energy_fun = make_energy_limit(music, 0.8)
# Print songs with energy above 0.8 with header
print('\n\nSpotify Top 100 Songs with Energy > 0.8')
for title, artists, energy in energy_fun():
print('{}, {}, {:.2f}'.format(title, artists, energy))
|
"""Multiplier class"""
class Multiplier(object):
"""perform multiplication"""
@staticmethod
def calc(operand_1, operand_2):
"""multiplication"""
return operand_1*operand_2
|
"""
This module provides a subtraction operator
"""
class Subtracter(object):
"""
Subtractor class
Produces operand 1 - operand 2
"""
@staticmethod
def calc(operand_1, operand_2):
"""
method to subtract operand2 from operand1
:param operand_1: first operand (a number)
:param operand_2: second operand (a number)
:return: result of subtraction
"""
return operand_1 - operand_2
|
"""Adder Function"""
class Adder(object):
"""Adder Class used for calculator"""
@staticmethod
def calc(operand_1, operand_2):
"""Adds two numbers"""
return operand_1 + operand_2
|
import pandas as pd
music = pd.read_csv("featuresdf.csv")
"""Write a closure to capture high energy tracks. High energy default is 0.8"""
def high_energy(min_energy1 = 0.8):
min_energy = min_energy1
def find_favorite():
for artist, song, energy in zip(music.artists, music.name, music.energy):
if energy >= min_energy:
yield (artist, song, energy)
return find_favorite()
if __name__ == '__main__':
print('\n\nUsing a Generator to find your favorite Artist')
favorites = high_energy()
for x in favorites:
print(x)
|
#!/usr/bin/env python3
# complicated_example.py
def main():
x = 'main'
one()
def one():
y = 'one'
two()
def two():
z = 'two'
long_loop()
def long_loop():
z_count = 0
for i in range(2, 1001, 5):
for j in range(3, 1001, 7):
for k in range(12, 1001):
z = k / (i % k + j % k)
# secret_print(z)
z_count += 1
print (z_count, 'z:', z, ' i, j, k:', i, j, k)
def secret_print(num):
num
if __name__ == '__main__':
print(main())
print('last statement')
|
"""
ORIGINAL AUTHOR: INSTRUCTOR
CO-AUTHOR: Micah Braun
PROJECT NAME: integrationtest.py
DATE CREATED: File originally created by instructor, date unknown
UPDATED: 10/18/2018
PURPOSE: Lesson 6
DESCRIPTION: Tests for Calculator class and its methods.
"""
from unittest import TestCase
from calculator.adder import Adder
from calculator.subtracter import Subtracter
from calculator.multiplier import Multiplier
from calculator.divider import Divider
from calculator.calculator import Calculator
class ModuleTests(TestCase):
def test_module(self):
calculator = Calculator(Adder(), Subtracter(), Multiplier(), Divider())
calculator.enter_number(5)
calculator.enter_number(2)
calculator.multiply()
calculator.enter_number(46)
calculator.add()
calculator.enter_number(8)
calculator.divide()
calculator.enter_number(1)
result = calculator.subtract()
self.assertEqual(6, result)
|
"""
Calculator module
"""
from .exceptions import InsufficientOperands
class Calculator():
"""
Create the calculator object.
"""
def __init__(self, adder, subtracter, multiplier, divider):
"""
Initialize the calculator
"""
self.adder = adder
self.subtracter = subtracter
self.multiplier = multiplier
self.divider = divider
self.stack = []
def enter_number(self, number):
"""
Insert the input to the front of self.stack
"""
# self.stack.insert(0, number)
self.stack.append(number)
def _do_calc(self, operator):
"""
Return result of the operation of the first 2 elements of self.stack
"""
try:
result = operator.calc(self.stack[0], self.stack[1])
except IndexError:
raise InsufficientOperands
except ZeroDivisionError:
result = 0
self.stack = [result]
return result
def add(self):
"""
Return the sum of the first 2 elements of self.stack
"""
return self._do_calc(self.adder)
def subtract(self):
"""
Return the difference of the first 2 elements of self.stack
"""
return self._do_calc(self.subtracter)
def multiply(self):
"""
Return the product of the first 2 elements of self.stack
"""
return self._do_calc(self.multiplier)
def divide(self):
"""
Return the quotient of the first 2 elements of self.stack
"""
return self._do_calc(self.divider)
|
def intsum():
isum = [0, 0]
while True:
yield isum[1]
isum[0] += 1
isum[1] += isum[0]
def intsum2(n=1):
while True:
yield (n*(n-1)) / 2
n += 1
def doubler(n=0):
while True:
yield 2 ** n
n += 1
def fib():
f_n = [0, 1]
while True:
yield f_n[1]
f_n[1] = sum(f_n)
f_n[0] = f_n[1] - f_n[0]
def prime(n=2):
prime_n = True
while True:
for i in range(3, n, 2):
if n % i == 0:
prime_n = False
break
if prime_n:
yield n
if n > 2:
prime_n = True
n += 2
else:
n += 1
def to_power(pwr=1):
n = 0
while True:
yield n ** pwr
n += 1
def count_by(factor=1):
n = 0
while True:
yield n * factor
n += 1
def factor_powers(factor=1):
n = 0
while True:
yield factor ** n
n += 1
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
"""
Simple iterator examples
"""
class IterateMe_1:
"""
About as simple an iterator as you can get:
returns the sequence of numbers from zero to 4
( like range(4) )
"""
def __init__(self, stop=5):
self.current = -1
self.stop = stop
def __iter__(self):
return self
def __next__(self):
self.current += 1
if self.current < self.stop:
return self.current
else:
raise StopIteration
class IterateMe_2(IterateMe_1):
def __init__(self, start=0, stop=5, step=1):
self.start = start
self.step = step
super().__init__(stop=stop)
self.current = self.start - 1
def __iter__(self):
return self
def __next__(self):
self.current += self.step
if self.current < self.stop:
return self.current
else:
raise StopIteration
if __name__ == "__main__":
print("Testing the iterator_1")
for i in IterateMe_1():
print(i)
print("\nTesting the iterator_2")
for i in IterateMe_2(3, 20, 2):
print(i)
print("\nTesing a 'Break' after 10")
it = IterateMe_2(2, 20, 2)
for i in it:
if i > 10:
break
print(i)
# Stops printing when it hits 10
print("\nPrint 'it'; picks up generator at 11")
for i in it:
print(i)
# Since the generator state is at "11", picks up at 13.
|
# Nebiat
# hw2 Generators and Closures
import pandas as pd
music = pd.read_csv("featuresdf.csv")
# Lists favorite artists using generator
def fav_artists_wGen(name):
# rows that favorite artist appears
rows = music.index[music.artists == name]
# returns name of song in that row
song_name = (music.at[x, "name"] for x in rows)
return song_name
# Using closure to find high energy songs
def high_energy(name, artists, danceability):
def energy_songs(level):
music = pd.read_csv("featuresdf.csv")
music = music[[name, artists, danceability]]
return music[music.danceability > level]
return energy_songs
# Loops through generator
for each_song in fav_artists_wGen("Ed Sheeran"):
print(each_song)
# Finds songs with danceability higher than .8 using closure
energy = high_energy("name", "artists", "danceability")
energy(.8)
|
#!/usr/bin/env python3
"""
json_save
metaclass based system for saving objects in a JSON format
This could be useful, but it's kept simple to show the use of metaclasses
The idea is that you subclass from JsonSavable, and then you get an object
that be saved and reloaded to/from JSON
"""
import json
# import * is a bad idea in general, but helpful for a modules that's part
# of a package, where you control the names.
from .saveables import *
class MetaJsonSaveable(type):
"""
The metaclass for creating JsonSavable classes
Deriving from type makes it a metaclass.
Note: the __init__ gets run at compile time, not run time.
(module import time)
"""
def __init__(cls, name, bases, attr_dict):
# it gets the class object as the first param.
# and then the same parameters as the type() factory function
# you want to call the regular type initilizer:
super().__init__(name, bases, attr_dict)
# here's where we work with the class attributes:
# these will the attributes that get saved and reconstructed from json.
# each class object gets its own dict
cls._attrs_to_save = {}
for key, attr in attr_dict.items():
if isinstance(attr, Saveable):
cls._attrs_to_save[key] = attr
# special case JsonSaveable -- no attrs to save yet
if cls.__name__ != "JsonSaveable" and (not cls._attrs_to_save):
raise TypeError(f"{cls.__name__} class has no saveable attributes.\n"
" Note that Savable attributes must be instances")
# register this class so we can re-construct instances.
Saveable.ALL_SAVEABLES[attr_dict["__qualname__"]] = cls
class JsonSaveable(metaclass=MetaJsonSaveable):
"""
mixin for JsonSavable objects
"""
def __new__(cls, *args, **kwargs):
"""
This adds instance attributes to assure they are all there, even if
they are not set in the subclasses __init__
"""
# create the instance
obj = super().__new__(cls)
# set the instance attributes to defaults
for attr, typ in cls._attrs_to_save.items():
setattr(obj, attr, typ.default)
return obj
def __eq__(self, other):
"""
default equality method that checks if all of the saved attributes
are equal
"""
for attr in self._attrs_to_save:
try:
if getattr(self, attr) != getattr(other, attr):
return False
except AttributeError:
return False
return True
def to_json_compat(self):
"""
converts this object to a json-compatible dict.
returns the dict
"""
# add and __obj_type attribute, so it can be reconstructed
dic = {"__obj_type": self.__class__.__qualname__}
for attr, typ in self._attrs_to_save.items():
dic[attr] = typ.to_json_compat(getattr(self, attr))
return dic
@classmethod
def from_json_dict(cls, dic):
"""
creates an instance of this class populated by the contents of
the json compatible dict
the object is created with __new__ before setting the attributes
NOTE: __init__ is not called.
There should not be any extra initialization required in __init__
"""
# create a new object
obj = cls.__new__(cls)
for attr, typ in cls._attrs_to_save.items():
setattr(obj, attr, typ.to_python(dic[attr]))
# make sure it gets initialized
# obj.__init__()
return obj
def to_json(self, fp=None, indent=4):
"""
Converts the object to JSON
:param fp=None: an open file_like object to write the json to.
If it is None, then a string with the JSON
will be returned as a string
:param indent=4: The indentation level desired in the JSON
"""
if fp is None:
return json.dumps(self.to_json_compat(), indent=indent)
else:
json.dump(self.to_json_compat(), fp, indent=indent)
def __str__(self):
msg = ["{} object, with attributes:".format(self.__class__.__qualname__)]
for attr in self._attrs_to_save.keys():
msg.append("{}: {}".format(attr, getattr(self, attr)))
return "\n".join(msg)
def from_json_dict(j_dict):
"""
factory function that creates an arbitrary JsonSavable
object from a json-compatible dict.
"""
# determine the class it is.
obj_type = j_dict["__obj_type"]
obj = Saveable.ALL_SAVEABLES[obj_type].from_json_dict(j_dict)
return obj
def from_json(_json):
"""
factory function that re-creates a JsonSavable object
from a json string or file
"""
if isinstance(_json, str):
return from_json_dict(json.loads(_json))
else: # assume a file-like object
return from_json_dict(json.load(_json))
if __name__ == "__main__":
# Example of using it.
class MyClass(JsonSaveable):
x = Int()
y = Float()
l = List()
def __init__(self, x, lst):
self.x = x
self.lst = lst
class OtherSaveable(JsonSavable):
foo = String()
bar = Int()
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
# create one:
print("about to create a instance")
mc = MyClass(5, [3, 5, 7, 9])
print(mc)
jc = mc.to_json_compat()
# re-create it from the dict:
mc2 = MyClass.from_json_dict(jc)
print(mc2 == "fred")
assert mc2 == mc
print(mc.to_json())
# now try it nested...
mc_nest = MyClass(34, [OtherSaveable("this", 2),
OtherSaveable("that", 64),
])
mc_nest_comp = mc_nest.to_json_compat()
print(mc_nest_comp)
# can we re-create it?
mc_nest2 = MyClass.from_json_dict(mc_nest_comp)
print(mc_nest)
print(mc_nest2)
assert mc_nest == mc_nest2
|
#!/usr/bin/env python
# Lesson1 - Aurel Perianu
class IterateMe_2:
"""
A more complex iterator:
returns the sequence of numbers from start to stop with step
"""
def __init__(self, start=1, stop=10, step=1):
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
self.current = self.start - self.step
return self
def __next__(self):
self.current += self.step
if self.current < self.stop:
return self.current
else:
raise StopIteration
if __name__ == "__main__":
print("Testing the iterator (default values):")
for i in IterateMe_2():
print(i)
print("\nTesting the iterator (2, 20, 2):")
for i in IterateMe_2(2, 20, 2):
print(i)
print('\n\nIterator vs range with break:\n')
it = IterateMe_2(1, 11, 1)
for i in it:
if i > 5:
print("interrupt iterator at: ", i)
break
print(i)
print("\nIterator after break (restart count):")
#iterator continues from the value where we break
for i in it:
print(i)
print ('\nPrint range with break:')
range_x = range(1,11,1)
for i in range_x:
if i > 5:
print("interrupt range at: ", i)
break
print(i)
print ("\nprint using range after break ")
for i in range_x:
print (i)
#print(dir(range))
#print("range vs iterator: range has no __next__ method")
|
"""
Assignment 1: populate the database table
"""
import logging
from create_db import *
from datetime import datetime
def duration_calculator(start_date, end_date):
start = datetime.strptime(''.join(start_date.split('-')), '%Y%m%d')
end= datetime.strptime(''.join(end_date.split('-')), '%Y%m%d')
return (end - start).days
def populate_db_person():
"""
populate person database table
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
database = SqliteDatabase('personjob.db')
logger.info('Working with Person class')
logger.info('Note how I use constants and a list of tuples as a simple schema')
logger.info('Normally you probably will have prompted for this from a user')
PERSON_NAME = 0
LIVES_IN_TOWN = 1
NICKNAME = 2
people = [
('Andrew', 'Sumner', 'Andy'),
('Peter', 'Seattle', None),
('Susan', 'Boston', 'Beannie'),
('Pam', 'Coventry', 'PJ'),
('Steven', 'Colchester', None)]
logger.info('Creating Person records: iterate through the list of tuples')
logger.info('Prepare to explain any errors with exceptions')
logger.info('and the transaction tells the database to fail on error')
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for person in people:
with database.transaction():
new_person = Person.create(
person_name = person[PERSON_NAME],
lives_in_town = person[LIVES_IN_TOWN],
nickname = person[NICKNAME])
new_person.save()
logger.info('Database add successful')
logger.info('Print the Person records we saved...')
for person in Person:
logger.info(f'{person.person_name} lives in {person.lives_in_town} ' +\
f'and likes to be known as {person.nickname}')
except Exception as e:
logger.info(f'Error creating = {person[PERSON_NAME]}')
logger.info(e)
logger.info('See how the database protects our data')
finally:
logger.info('database closes')
database.close()
def populate_db_job():
"""
populate job database table
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
database = SqliteDatabase('personjob.db')
logger.info('Working with Job class')
logger.info('Creating Job records: just like Person. We use the foreign key')
JOB_NAME = 0
START_DATE = 1
END_DATE = 2
SALARY = 3
PERSON_EMPLOYED = 4
DEPARTMENT_ID = 5
jobs = [
('Analyst', '2001-09-22', '2003-01-30', 65500, 'Andrew','A123'),
('Senior analyst', '2003-02-01', '2006-10-22', 70000, 'Andrew', 'B123'),
('Senior business analyst', '2006-10-23', '2016-12-24', 80000, 'Andrew', 'C123'),
('Admin supervisor', '2012-10-01', '2014-11,10', 45900, 'Peter','D123'),
('Admin manager', '2014-11-14', '2018-01,05', 45900, 'Peter', 'E123')
]
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for job in jobs:
with database.transaction():
new_job = Job.create(
job_name = job[JOB_NAME],
start_date = job[START_DATE],
end_date = job[END_DATE],
duration = duration_calculator(job[START_DATE], job[END_DATE]),
salary = job[SALARY],
person_employed = job[PERSON_EMPLOYED],
department_id = job[DEPARTMENT_ID])
new_job.save()
logger.info('Database add successful')
logger.info('Print the Job records we saved...')
for job in Job:
logger.info(f'{job.job_name} : {job.start_date} to {job.end_date} for {job.person_employed}')
except Exception as e:
logger.info(f'Error creating = {job[JOB_NAME]}')
logger.info(e)
finally:
logger.info('database closes')
database.close()
def populate_db_department():
"""
populate department database table
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
database = SqliteDatabase('personjob.db')
logger.info('Working with Department class')
logger.info('Creating Department records: just like Person. We use the foreign key')
DEPARTMENT_ID = 0
DEPARTMENT_NAME = 1
DEPARTMENT_MANAGER = 2
#START_DATE_DEPARTMENT = 3
#END_DATE_DEPARTMENT = 4
#DURATION = 5
departments = [
('A123', 'Operations', 'Andrew'),
('B123', 'Marketing', 'Peter'),
('C123', 'Finance', 'Susan'),
('D123', 'HR', 'Pam'),
('E123', 'Sales', 'Steven')
]
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for department in departments:
with database.transaction():
new_department = Department.create(
department_id = department[DEPARTMENT_ID],
department_name = department[DEPARTMENT_NAME],
department_manager = department[DEPARTMENT_MANAGER])
new_department.save()
logger.info('Database add successful')
logger.info('Print the Department records we saved...')
for department in Department:
logger.info(f'{department.department_id} is {department.department_name} ' +\
f'and the manager is {department.department_manager}')
except Exception as e:
logger.info(f'Error creating = {department[DEPARTMENT_NAME]}')
logger.info(e)
logger.info('See how the database protects our data')
finally:
logger.info('database closes')
database.close()
if __name__ == '__main__':
populate_db_person()
populate_db_department()
populate_db_job()
|
"""
1. Create Data structure that holds Donor, Donation Amount.
2. Prompt user to Send a Thank You, Create a Report, or quit.
3. At any point, the user should be able to quit their current task and return
to the original prompt
4. From the original prompt, the user should be able to quit the scipt cleanly
"""
import sys
import os
import datetime
from donor import Donor
from donor_dict import Donor_Dict
from redis_mailroom import Redis_Mailroom_Client
d = Donor_Dict.from_file("dict_init.txt")
divider = "\n" + "*" * 50 + "\n"
validater = Redis_Mailroom_Client()
def main_menu(user_prompt=None):
"""
Prompt user to send a Thank You, Create a report, create letters, or quit.
"""
valid_prompts = {"1": add_donation,
"2": create_donor_report,
"3": simulate,
"4": mr_exit}
options = list(valid_prompts.keys())
print(divider + "We're a Pyramid Scheme & So Are You! E-Mailroom" +
divider)
while user_prompt not in valid_prompts:
options_str = ("{}" + (", {}") * (len(options)-1)).format(*options)
print(f"Please choose from the following options ({options_str}):")
print("1. Add new donation")
print("2. Show Report")
print("3. Run Projections")
print("4. Quit")
user_prompt = input(">")
print(divider)
return valid_prompts.get(user_prompt)
def verify_user():
name = ''
while True:
print('Please input who is accessing this mailroom.')
name = input('>')
if name in validater.keys:
print('Please input any of the following to verify: '
'Email, Phone Number, What is your favorite beverage?')
answ = input('>')
if (validater.validate_email(name, answ)
or validater.validate_phone_num(name, answ)
or validater.validate_security_q(name, answ)):
break
print('Could not verify')
return d[name.lower()]
def user_input(some_str=""):
"""
Display exit reminder and prompt user for input.
"""
while not some_str:
print("Return to the main menu by entering 'exit'")
some_str = input(">")
return check_not_exit(some_str) * some_str
def check_not_exit(check_str):
"""
Check whether or not given string is "exit"
"""
return check_str.lower() != "exit"
def conv_str(conv_str, conv_type=int):
"""
Convert string to given conv_type.
If it's unable to convert, return original string.
"""
try:
conv_yes = conv_type(conv_str)
return conv_yes
except ValueError:
return None
def input_donor_float(d_amt=0):
"""
Prompt user for valid float
If input cannot be converted to float, prompt again.
"""
while True:
d_amt = user_input()
if d_amt:
d_amt = conv_str(d_amt, float)
if d_amt is not None:
break
print("Enter a valid amount")
return d_amt
def add_donation(donor):
"""
Compose and print a thank you letter to the donor for their donation.
Return to main
"""
print(divider)
print("\nEnter a Donation Amount:")
gift_amt = input_donor_float()
if gift_amt != "":
d.add_donor(donor.name, gift_amt)
print(donor.thank_u_letter_str(1))
return
def create_donor_report(donor, d_dict=d):
"""
Print a list of donors sorted by method chosen in sort_report_by.
Donor Name, Num Gifts, Average Gift, Total Given
"""
report = donor.donor_report()
print(divider + report + divider)
return
def simulate(donor, d_dict=d):
"""
Display Donor Report altered by user's specifications.
"""
print("Input a factor to multiply contributions by.")
fctr = input_donor_float()
if fctr != "":
print("Input a min donation such that all donations above" +
" this amount will be altered.")
print("Enter -1 for default value")
min_g = input_donor_float()
if min_g != "":
print("Input a max donation such that all donations below" +
" this amount will be altered")
print("Enter -1 for default value")
max_g = input_donor_float()
while max_g < min_g:
print("Please enter a valid amount")
max_g = input_donor_float()
if max_g != "":
if min_g == -1:
min_g = None
if max_g == -1:
max_g == None
sim_d = donor.challenge(fctr, min_g, max_g)
create_donor_report(sim_d)
return
def write_txt_to_dir(f_name, content, wrt_dir=os.getcwd()):
"""
Write a personalized thank you letter for all the donors.
Letters will be written to letter_dir.
"""
curdate = (datetime.datetime.now()).strftime("%Y_%m_%d")
file_name = f_name.replace(' ', '_') + "_" + curdate + ".txt"
file_path = os.path.join(wrt_dir, file_name)
with open(file_path, 'w+') as text:
text.write(content)
return "Wrote to " + file_path
def mr_exit(donor):
"""
Prompt user to save donor dict before exiting program.
"""
print("Before exiting would you like to save the donor info?[y/n]")
save_confirm = ""
while save_confirm not in ['y', 'n']:
save_confirm = input('>').lower()
if save_confirm == 'y':
print(write_txt_to_dir("dict_init", d.dict_to_txt(), os.getcwd()))
validater.write_lookup_file('lookup_list.txt')
sys.exit()
if __name__ == '__main__':
donor = verify_user()
while True:
main_menu()(donor)
input("Press Enter to continue...........")
|
"""
This module compasses the Calculator class
"""
from .exceptions import InsufficientOperands
class Calculator(object):
""" This class provides the basic functionality of a calculator.
Attributes:
adder (object): Instance of Adder class
subtracter (object): Instance of Subtracter class
multiplier (object): Instance of Multiplier class
divider (object): Instance of Divider class
"""
def __init__(self, adder, subtracter, multiplier, divider):
self.adder = adder
self.subtracter = subtracter
self.multiplier = multiplier
self.divider = divider
self.stack = []
def enter_number(self, number):
""" This method inserts a number in the stack at position 0.
Parameters:
number (float): Number to be inserted in the stack
"""
self.stack.insert(0, number)
def _do_calc(self, operator):
""" Wrapper for all the 4 calculations.
Parameters:
operator (operator): Type of operation to be done on the numbers.
Returns:
number (float): The result of the operation.
"""
try:
result = operator.calc(self.stack[1], self.stack[0])
except IndexError:
raise InsufficientOperands
self.stack = [result]
return result
def add(self):
"""
The function adds two numbers.
Returns:
number (float): The result of the operation.
"""
return self._do_calc(self.adder)
def subtract(self):
"""
The function subtracts two numbers.
Returns:
number (float): The result of the operation.
"""
return self._do_calc(self.subtracter)
def multiply(self):
"""
The function multiplies two numbers.
Returns:
number (float): The result of the operation.
"""
return self._do_calc(self.multiplier)
def divide(self):
"""
The function divides two numbers.
Returns:
number (float): The result of the operation.
"""
return self._do_calc(self.divider)
|
"""
Unit tests for the water-regulation module
"""
import unittest
from unittest.mock import MagicMock
from pump import Pump
from sensor import Sensor
from .controller import Controller
from .decider import Decider
class DeciderTests(unittest.TestCase):
"""
Unit tests for the Decider class
"""
actions = {'PUMP_IN': 1, 'PUMP_OUT': -1, 'PUMP_OFF': 0}
def test_pump_off_h_below_margin(self):
"""
test PUMP_OFF + height below lower margin = PUMP_IN
"""
decider = Decider(10, .1)
action = decider.decide(8, self.actions['PUMP_OFF'], self.actions)
self.assertEqual(self.actions['PUMP_IN'], action)
def test_pump_off_h_at_low_margin(self):
"""
test PUMP_OFF + height at lower margin = PUMP_OFF
"""
decider = Decider(10, .1)
action = decider.decide(9, self.actions['PUMP_OFF'], self.actions)
self.assertEqual(self.actions['PUMP_OFF'], action)
def test_pump_off_h_at_target(self):
"""
test PUMP_OFF + height at target = PUMP_OFF
"""
decider = Decider(10, .1)
action = decider.decide(10, self.actions['PUMP_OFF'], self.actions)
self.assertEqual(self.actions['PUMP_OFF'], action)
def test_pump_off_h_at_high_margin(self):
"""
test PUMP_OFF + height at upper margin = PUMP_OFF
"""
decider = Decider(10, .1)
action = decider.decide(11, self.actions['PUMP_OFF'], self.actions)
self.assertEqual(self.actions['PUMP_OFF'], action)
def test_pump_off_h_above_margin(self):
"""
test PUMP_OFF + height above upper margin = PUMP_OUT
"""
decider = Decider(10, .1)
action = decider.decide(12, self.actions['PUMP_OFF'], self.actions)
self.assertEqual(self.actions['PUMP_OUT'], action)
def test_pump_in_h_below_target(self):
"""
test PUMP_IN + height below target = PUMP_IN
"""
decider = Decider(10, .1)
action = decider.decide(9, self.actions['PUMP_IN'], self.actions)
self.assertEqual(self.actions['PUMP_IN'], action)
def test_pump_in_h_at_target(self):
"""
test PUMP_IN + height at target = PUMP_IN
"""
decider = Decider(10, .1)
action = decider.decide(10, self.actions['PUMP_IN'], self.actions)
self.assertEqual(self.actions['PUMP_IN'], action)
def test_pump_in_h_above_target(self):
"""
test PUMP_IN + height above target = PUMP_OFF
"""
decider = Decider(10, .1)
action = decider.decide(11, self.actions['PUMP_IN'], self.actions)
self.assertEqual(self.actions['PUMP_OFF'], action)
def test_pump_out_h_below_target(self):
"""
test PUMP_OUT + height below target = PUMP_OFF
"""
decider = Decider(10, .1)
action = decider.decide(9, self.actions['PUMP_OUT'], self.actions)
self.assertEqual(self.actions['PUMP_OFF'], action)
def test_pump_out_h_at_target(self):
"""
test PUMP_OUT + height below target = PUMP_OUT
"""
decider = Decider(10, .1)
action = decider.decide(10, self.actions['PUMP_OUT'], self.actions)
self.assertEqual(self.actions['PUMP_OUT'], action)
def test_pump_out_h_above_target(self):
"""
test PUMP_OUT + height above target = PUMP_OUT
"""
decider = Decider(10, .1)
action = decider.decide(11, self.actions['PUMP_OUT'], self.actions)
self.assertEqual(self.actions['PUMP_OUT'], action)
class ControllerTests(unittest.TestCase):
"""
Unit tests for the Controller class
"""
def test_tick_true(self):
"""
Test that tick return True if pump.set_state returns True
"""
sensor = Sensor('127.0.0.1', 8000)
pump = Pump('127.0.0.1', 8000)
decider = Decider(10, .1)
controller = Controller(sensor, pump, decider)
sensor.measure = MagicMock(return_value=10)
pump.get_state = MagicMock(return_value=pump.PUMP_OFF)
pump.set_state = MagicMock(return_value=True)
self.assertTrue(controller.tick())
def test_tick_false(self):
"""
Test that tick return False if pump.set_state returns False
"""
sensor = Sensor('127.0.0.1', 8000)
pump = Pump('127.0.0.1', 8000)
decider = Decider(10, .1)
controller = Controller(sensor, pump, decider)
sensor.measure = MagicMock(return_value=10)
pump.get_state = MagicMock(return_value=pump.PUMP_OFF)
pump.set_state = MagicMock(return_value=False)
self.assertFalse(controller.tick())
|
#!/usr/bin/env python
"""
Simple iterator examples
"""
class IterateMe_1:
"""
About as simple an iterator as you can get:
returns the sequence of numbers from zero to 4
( like range(4) )
"""
def __init__(self, stop=5):
self.current = -1
self.stop = stop
def __iter__(self):
return self
def __next__(self):
self.current += 1
if self.current < self.stop:
return self.current
else:
raise StopIteration
class IterateMe_2:
def __init__(self, start, stop, step=1):
self.stop = stop
self.step = step
if step == 0:
raise ValueError
elif step == 1:
self.current = -step
else:
self.current = start-step
def __iter__(self):
return self
def __next__(self):
self.current += self.step
if self.current < self.stop:
return self.current
else:
raise StopIteration
class IteratorLikeRange:
def __init__(self, start, stop, step=1):
self.stop = stop
self.step = step
if step == 0:
raise ValueError
elif step == 1:
self.current = -step
else:
self.current = start-step
def __iter__(self):
# return self
self.next = self.current + self.step
return IteratorLikeRange(self.next, self.stop, self.step)
def __next__(self):
self.current += self.step
if self.current < self.stop:
return self.current
else:
raise StopIteration
if __name__ == "__main__":
print("Testing the iterator")
for i in IterateMe_1():
print(i)
print("Testing the iterator 2")
it = IterateMe_2(-1, 5)
for i in it:
print(i)
print("Testing the iterator 2 with step")
it = IterateMe_2(2, 20, 2)
for i in it:
if i > 10:
break
print(i)
for i in it:
print(i)
# range returns an iterable
# that can be converted to an iterator with iter(range(2, 20, 2))
print("Testing range")
r = range(2, 20, 2)
for i in r:
if i > 10:
break
print(i)
for i in r:
print(i)
print("Testing IteratorLikeRange")
ir = IteratorLikeRange(2, 20, 2)
for i in ir:
if i > 10:
break
print(i)
for i in ir:
print(i)
|
def factorial(n):
if n < 0 or not isinstance(n, int):
raise ValueError('n must be a non-negative intiger')
if n == 0:
return 1
else:
return factorial(n-1) * n
if __name__ == "__main__":
print('9 Factorial: {}'.format(factorial(9)))
print('5 Factorial: {}'.format(factorial(5)))
print('1 Factorial: {}'.format(factorial(1)))
print('0 Factorial: {}'.format(factorial(0))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.