blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
8146a0a68782bf0745c250965e9440689dd3d957
Litao439420999/LeetCodeAlgorithm
/Python/candy.py
3,342
3.640625
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: candy.py @Function: 分发糖果 贪心策略 @Link: https://leetcode-cn.com/problems/candy/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-04 """ # -------------------------------------------------------------- class Solution2: """0、只需要简单的两次遍历即可:把所有孩子的糖果数初始化为 1; 1、先从左往右遍历一遍,如果右边孩子的评分比左边的高, 则右边孩子的糖果数更新为左边孩子的糖果数加 1; 2、再从右往左遍历一遍,如果左边孩子的评分比右边的高,且左边孩子当前的糖果数不大于右边孩子的糖果数, 则左边孩子的糖果数更新为右边孩子的糖果数加 1。 3、通过这两次遍历,分配的糖果就可以满足题目要求了。 这里的贪心策略即为,在每次遍历中,只考虑并更新相邻一侧的大小关系。 """ def candy(self, ratings): # 若只有一个人,则最少需要一个糖果 if len(ratings) < 2: return len(ratings) # 初始化每个人一个糖果 left = [1 for _ in range(len(ratings))] right = left[:] # 第一次遍历,从左往右 for i in range(1, len(ratings)): if ratings[i] > ratings[i - 1]: # 如果右边的评分高于左边,则其糖果数量等于其左边的糖果数量 + 1 left[i] = left[i - 1] + 1 # 计算需要的最小糖果数量 # 因为后面累加计算时索引不到最后一个 count = left[-1] # 第二次遍历,从右往左 for i in range(len(ratings) - 2, -1, -1): # 如果左边的评分高于右边,则左边孩子的糖果数更新为右边孩子的糖果数 + 1 if ratings[i] > ratings[i + 1]: right[i] = right[i + 1] + 1 # 不断累加需要的最小糖果数量 # 每次具体位置的值,取从左往右遍历 和 从右往左遍历 的最大值 count += max(left[i], right[i]) return count # -------------------------------------------------------------- class Solution: def candy(self, ratings): # 初始化每个人一个糖果 nums = [1] * len(ratings) # 第一次遍历,从左往右 for i in range(0, len(ratings)-1): # 如果右边的评分高于左边,则其糖果数量等于其左边的糖果数量 + 1 if ratings[i] < ratings[i+1]: nums[i+1] = nums[i] + 1 # 第二次遍历,从右往左 for i in range(len(ratings)-1, 0, -1): # 如果左边的评分高于右边, if ratings[i] < ratings[i-1]: # 且左边孩子当前的糖果数不大于右边孩子的糖果数 if nums[i] > nums[i-1] or nums[i] == nums[i-1]: # 左边孩子的糖果数更新为右边孩子的糖果数 + 1 nums[i-1] = nums[i] + 1 return sum(nums) if __name__ == "__main__": ratings = [1, 0, 2] # ratings = [1, 2, 2] solution = Solution() num_candy = solution.candy(ratings) print(f"The solution of this problem is : {num_candy}")
268b790641e7a522cc7d2431dcdb28b9a30126c8
Litao439420999/LeetCodeAlgorithm
/Python/MinStack.py
754
3.65625
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: MinStack.py @Function: 最小栈 @Link: https://leetcode-cn.com/problems/min-stack/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-25 """ import math class MinStack: def __init__(self): self.stack = [] self.min_stack = [math.inf] def push(self, x: int) -> None: self.stack.append(x) self.min_stack.append(min(x, self.min_stack[-1])) def pop(self) -> None: self.stack.pop() self.min_stack.pop() def top(self) -> int: return self.stack[-1] def getMin(self) -> int: return self.min_stack[-1] # -------------------------------------- if __name__ == "__main__": # Test on LeetCode online. pass
03a7ff048927334379e9758f3d2e7b43d2ceee43
Litao439420999/LeetCodeAlgorithm
/Python/hammingDistance.py
636
3.78125
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: hammingDistance.py @Function: 两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目 @Link: https://leetcode-cn.com/problems/hamming-distance/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-21 """ class Solution: def hammingDistance(self, x, y): return bin(x ^ y).count('1') # ------------------------- if __name__ == "__main__": x, y = 1, 4 # x, y = 3, 1 solution = Solution() hamming_distance = solution.hammingDistance(x, y) print(f"The solution of this problem is {hamming_distance}")
f04df87810d13395100540e524f48db20db18d52
Litao439420999/LeetCodeAlgorithm
/Python/calculate.py
1,149
3.875
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: calculate.py @Function: 基本计算器 II @Link: https://leetcode-cn.com/problems/basic-calculator-ii/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-28 """ class Solution: def calculate(self, s: str) -> int: n = len(s) stack = [] preSign = '+' num = 0 for i in range(n): if s[i] != ' ' and s[i].isdigit(): num = num * 10 + ord(s[i]) - ord('0') if i == n - 1 or s[i] in '+-*/': if preSign == '+': stack.append(num) elif preSign == '-': stack.append(-num) elif preSign == '*': stack.append(stack.pop() * num) else: stack.append(int(stack.pop() / num)) preSign = s[i] num = 0 return sum(stack) # ---------------------------------- if __name__ == "__main__": str = " 3/2 " solution = Solution() calculate_value = solution.calculate(str) print(f"The solution of this problem is : {calculate_value}")
a39d90db4f8ca2489ce1c157bc075f59aba7c24d
Litao439420999/LeetCodeAlgorithm
/Python/reconstructQueue.py
1,015
3.859375
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: reconstructQueue.py @Function: 根据身高重建队列 贪心策略 @Link: https://leetcode-cn.com/problems/queue-reconstruction-by-height/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-06 """ # --------------------------- class Solution: def reconstructQueue(self, people): people.sort(key=lambda x: (x[0], -x[1])) n = len(people) ans = [[] for _ in range(n)] for person in people: spaces = person[1] + 1 for i in range(n): if not ans[i]: spaces -= 1 if spaces == 0: ans[i] = person break return ans # ------------------------- if __name__ == "__main__": # people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] solution = Solution() reconstruct_queue = solution.reconstructQueue(people) print(reconstruct_queue)
0334614a346b0a1dcddf4da9b585a997ab561dad
Litao439420999/LeetCodeAlgorithm
/Python/matrixReshape.py
850
4.0625
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: matrixReshape.py @Function: 重塑矩阵 @Link: https://leetcode-cn.com/problems/reshape-the-matrix/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-26 """ from typing import List class Solution: def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]: m, n = len(nums), len(nums[0]) if m * n != r * c: return nums ans = [[0] * c for _ in range(r)] for x in range(m * n): ans[x // c][x % c] = nums[x // n][x % n] return ans # ------------------------- if __name__ == "__main__": nums = [[1, 2], [3, 4]] # r, c = 1, 4 r, c = 2, 4 solution = Solution() reshape_matrix = solution.matrixReshape(nums, r, c) print(f"The solutino of this problem is {reshape_matrix}")
7b22af2549e23620e764bfe31cf5fbddf2a6b6bd
Litao439420999/LeetCodeAlgorithm
/Python/dailyTemperatures.py
956
3.96875
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: dailyTemperatures.py @Function: 每日温度 @Link: https://leetcode-cn.com/problems/daily-temperatures/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-25 """ from typing import List class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: length = len(temperatures) ans = [0] * length stack = [] for i in range(length): temperature = temperatures[i] while stack and temperature > temperatures[stack[-1]]: prev_index = stack.pop() ans[prev_index] = i - prev_index stack.append(i) return ans # -------------------------------------- if __name__ == "__main__": temperatures = [30,40,50,60] solution = Solution() daily_temperature = solution.dailyTemperatures(temperatures) print(f"The solution of this problem is {daily_temperature}")
2c3bdd46d4cd3975dfb4cadb5f4f29af6bbd7872
Litao439420999/LeetCodeAlgorithm
/Python/wiggleMaxLength.py
1,074
3.71875
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: wiggleMaxLength.py @Function: 摆动序列 动态规划 @Link:https://leetcode-cn.com/problems/wiggle-subsequence/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-16 """ class Solution: def wiggleMaxLength(self, nums) -> int: n = len(nums) if n < 2: return n up = [1] + [0] * (n - 1) down = [1] + [0] * (n - 1) for i in range(1, n): if nums[i] > nums[i - 1]: up[i] = max(up[i - 1], down[i - 1] + 1) down[i] = down[i - 1] elif nums[i] < nums[i - 1]: up[i] = up[i - 1] down[i] = max(up[i - 1] + 1, down[i - 1]) else: up[i] = up[i - 1] down[i] = down[i - 1] return max(up[n - 1], down[n - 1]) # ------------------------- if __name__ == "__main__": nums = [1, 7, 4, 9, 2, 5] solution = Solution() max_length = solution.wiggleMaxLength(nums) print(f"The solution of this problem is {max_length}")
adb7c6349316892da5414d10a589f891e97bb1e5
Litao439420999/LeetCodeAlgorithm
/Python/constructFromPrePost.py
1,101
3.875
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: constructFromPrePost.py @Function: 根据前序和后序遍历构造二叉树 @Link : https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ @Python Version: 3.8 @Author: Wei Li @Date:2021-08-02 """ # 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(object): def constructFromPrePost(self, pre, post): def make(i0, i1, N): if N == 0: return None root = TreeNode(pre[i0]) if N == 1: return root for L in range(N): if post[i1 + L - 1] == pre[i0 + 1]: break root.left = make(i0 + 1, i1, L) root.right = make(i0 + L + 1, i1 + L, N - 1 - L) return root return make(0, 0, len(pre)) # ------------------------------ if __name__ == "__main__": # test on LeetCode online. pass
97427f841b2215fda35a0110c3323725acace837
Litao439420999/LeetCodeAlgorithm
/Python/findKthLargest.py
1,315
3.953125
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: findKthLargest.py @Function: 数组中的第K个最大元素 快速选择 @Link: https: // leetcode-cn.com/problems/kth-largest-element-in-an-array/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-10 """ import random class Solution: def findKthLargest(self, nums, k): def findTopKth(low, high): pivot = random.randint(low, high) nums[low], nums[pivot] = nums[pivot], nums[low] base = nums[low] i = low j = low + 1 while j <= high: if nums[j] > base: nums[i + 1], nums[j] = nums[j], nums[i + 1] i += 1 j += 1 nums[low], nums[i] = nums[i], nums[low] if i == k - 1: return nums[i] elif i > k - 1: return findTopKth(low, i - 1) else: return findTopKth(i + 1, high) return findTopKth(0, len(nums) - 1) # ------------------------- if __name__ == "__main__": # nums = [3, 2, 1, 5, 6, 4] # k = 2 nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] k = 4 solution = Solution() kth_largest = solution.findKthLargest(nums, k) print(f"The solution of this problem is : {kth_largest}")
b944a375a96ced5824239689a7e7b5f26dc854c4
Litao439420999/LeetCodeAlgorithm
/Python/binaryTreePaths.py
2,102
3.96875
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: binaryTreePaths.py @Function: 二叉树的所有路径 @Link: https://leetcode-cn.com/problems/binary-tree-paths/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-12 """ import collections from typing import List import string # 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 binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ def construct_paths(root, path): if root: path += str(root.val) if not root.left and not root.right: # 当前节点是叶子节点 paths.append(path) # 把路径加入到答案中 else: path += '->' # 当前节点不是叶子节点,继续递归遍历 construct_paths(root.left, path) construct_paths(root.right, path) paths = [] construct_paths(root, '') return paths # 方法二:广度优先搜索 class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: paths = list() if not root: return paths node_queue = collections.deque([root]) path_queue = collections.deque([str(root.val)]) while node_queue: node = node_queue.popleft() path = path_queue.popleft() if not node.left and not node.right: paths.append(path) else: if node.left: node_queue.append(node.left) path_queue.append(path + '->' + str(node.left.val)) if node.right: node_queue.append(node.right) path_queue.append(path + '->' + str(node.right.val)) return paths # ------------------------ if __name__ == "__main__": # test on LeetCode online. pass
6bc5f504ef16bea225cae8f52e818fb96687b002
Litao439420999/LeetCodeAlgorithm
/Python/sumOfLeftLeaves.py
1,006
3.78125
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: sumOfLeftLeaves.py @Function: 左叶子之和 @Link: https://leetcode-cn.com/problems/sum-of-left-leaves/ @Python Version: 3.8 @Author: Wei Li @Date:2021-08-01 """ # 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 sumOfLeftLeaves(self, root: TreeNode) -> int: def isLeafNode(node): return not node.left and not node.right def dfs(node: TreeNode) -> int: ans = 0 if node.left: ans += node.left.val if isLeafNode( node.left) else dfs(node.left) if node.right and not isLeafNode(node.right): ans += dfs(node.right) return ans return dfs(root) if root else 0 # ---------------------------------- if __name__ == "__main__": # test on LeetCode online. pass
8b39bba2440821071ad46e65071a642da9ce5434
Litao439420999/LeetCodeAlgorithm
/Python/lowestCommonAncestor2.py
962
3.65625
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: lowestCommonAncestor2.py @Function: 二叉树的最近公共祖先 @Link : https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/ @Python Version: 3.8 @Author: Wei Li @Date:2021-08-02 """ # 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 lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: if not root or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if not left: return right if not right: return left return root # ------------------------------ if __name__ == "__main__": # test on LeetCode online. pass
fbc71fc9cb47523ce6a7b1aed3f1c24b3723846b
Litao439420999/LeetCodeAlgorithm
/Python/numSquares.py
1,301
3.671875
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: numSquares.py @Function: 完全平方数 动态规划 @Link: https://leetcode-cn.com/problems/perfect-squares/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-14 """ class Solution: def numSquares(self, n: int) -> int: '''版本一''' # 初始化 nums = [i**2 for i in range(1, n + 1) if i**2 <= n] dp = [10**4]*(n + 1) dp[0] = 0 # 遍历背包 for j in range(1, n + 1): # 遍历物品 for num in nums: if j >= num: dp[j] = min(dp[j], dp[j - num] + 1) return dp[n] def numSquares1(self, n: int) -> int: '''版本二''' # 初始化 nums = [i**2 for i in range(1, n + 1) if i**2 <= n] dp = [10**4]*(n + 1) dp[0] = 0 # 遍历物品 for num in nums: # 遍历背包 for j in range(num, n + 1): dp[j] = min(dp[j], dp[j - num] + 1) return dp[n] # ------------------------- if __name__ == "__main__": # n = 12 n = 13 solution = Solution() # num_sequares = solution.numSquares(n) num_sequares = solution.numSquares1(n) print(f"The solution of this problem is : {num_sequares}")
3bb8a813d915675a1aec37019e157674a162dfef
renatovvjr/candidatosDoacaoPython
/main.py
1,269
3.796875
4
#O programa receberá informações de 10 candidatos à doação de sangue. O programa deverá ler a idade e informar a seguinte condição: #- Se menor de 16 ou acima de 69 anos, não poderá doar; #- Se tiver entre 16 e 17 anos, somente poderá doar se estiver acompanhado dos pais ou responsáveis (neste caso criar uma condição: "Está acompanhado de pais ou responsável: 1-sim ou 2-não); #- Se tiver entre 18 e 69 anos, poderá doar. #Ao final o programa deverá mostrar quantos candidatos poderão doar sangue. idade=0 doadorMenorIdoso=0 doadorAdolescente=0 doadorAdulto=0 simNao=0 podeDoar=0 naoPodeDoar=0 adolescente=0 for i in range(0, 10): idade = int(input('Informe a idade do candidato à doação: ')) if idade <16 or idade > 69: doadorMenorIdoso+=1 elif 16<=idade<=17: simNao = int(input('Está acompanhado de pais ou responsável? Digite [1 - SIM] ou [2 - NÃO]')) if simNao == 1: doadorAdolescente+=1 else : adolescente+=1 else : doadorAdulto+=1 naoPodeDoar = doadorMenorIdoso + adolescente podeDoar = doadorAdolescente + doadorAdulto print(naoPodeDoar, ' candidatos não atenderam aos critérios para doação de sangue.') print(podeDoar, ' candidatos atenderam aos critérios para doação de sangue e poderão doar.')
ef1db11ab060501a5f23c772da2e3467889b3fb3
Zetinator/just_code
/python/leetcode/jumping_clouds.py
655
3.84375
4
""" Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. """ def deep(x, jumps): if not x or len(x) == 1: return jumps print(f'STATUS: x: {x}, jumps: {jumps}') if x[0] == 1: return float('inf') return min(deep(x[1:], jumps+1), deep(x[2:], jumps+1)) def play(x): return deep(x, 0) # test # test = [0, 0, 1, 0, 0, 1, 0] test = [0,0,0,1,0,0] print(f'testing with: {test}') print(f'ans: {play(test)}')
dd146b10d8b6c0900a77754d93b0c9231e2737a8
Zetinator/just_code
/python/leetcode/sorting_bubble_sort.py
1,012
4.09375
4
"""https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following three lines: Array is sorted in numSwaps swaps., where is the number of swaps that took place. First Element: firstElement, where is the first element in the sorted array. Last Element: lastElement, where is the last element in the sorted array. """ def countSwaps(x): swaps = 0 for i in x: for j in range(len(x)-1): if x[j] > x[j+1]: x[j], x[j+1] = x[j+1], x[j] swaps += 1 print(f'Array is sorted in {swaps} swaps.') print(f'First Element: {x[0]}') print(f'Last Element: {x[-1]}') # test test = [33, 66, 1, 65, 5, 7, 41, 74, 11, 45, 14, 60, 48, 84, 85, 31, 93, 63] print(f'testing with: {test}') print(f'ans: {countSwaps(test)}')
2dcdbed4df8b0608780c4d3a226c4f25d0de2b38
Zetinator/just_code
/python/leetcode/binary_distance.py
872
4.1875
4
""" The distance between 2 binary strings is the sum of their lengths after removing the common prefix. For example: the common prefix of 1011000 and 1011110 is 1011 so the distance is len("000") + len("110") = 3 + 3 = 6. Given a list of binary strings, pick a pair that gives you maximum distance among all possible pair and return that distance. """ def binary_distance(x: 'binary string', y: 'binary string') -> 'distance': def find_prefix(x, y, n): if not x or not y: return n # print(f'STATUS: x:{x}, y:{y}, n:{n}') if x[0] == y[0]: return find_prefix(x[1:], y[1:], n+1) else: return n prefix_len = find_prefix(x, y, 0) x, y = x[prefix_len:], y[prefix_len:] return len(x) + len(y) # test x = '1011000' y = '1011110' print(f'testing with: x:{x}, y:{y}') print(f'ANS: {binary_distance(x, y)}')
2b9f81e6106ebe23353158a2b4b3f12d034003e7
Zetinator/just_code
/python/leetcode/simple_text_editor.py
1,697
4
4
"""https://www.hackerrank.com/challenges/simple-text-editor/problem In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, . You must perform operations of the following types: append - Append string to the end of . delete - Delete the last characters of . print - Print the character of . undo - Undo the last (not previously undone) operation of type or , reverting to the state it was in prior to that operation. """ class TE(): def __init__(self): self.stack = [''] def append(self, x): """append new string to the past string """ if not x: return self.stack.append(self.stack[-1] + x) def delete(self, k): """delete the last k elements """ self.stack.append(self.stack[-1][:-k]) def print(self, k): """print the last k element """ k -= 1 print(self.stack[-1][k]) def undo(self): """undo the last operation """ self.stack.pop() def execute_query(te, q): """simple interface to process the queries """ if q[0] == '1': return te.append(q[1]) if q[0] == '2': return te.delete(int(q[1])) if q[0] == '3': return te.print(int(q[1])) else: return te.undo() # read from stdin te = TE() for _ in range(int(input())): q = [e for e in input().split()] execute_query(te, q) # local test... test = """1 abc 3 3 2 3 1 xy 3 2 4 4 3 1""" _t = [] for line in test.split('\n'): tmp = [] for e in line.split(): tmp.append(e) _t.append(tmp) test = _t print(f'test with: {test}') te = TE() for q in test: execute_query(te, q)
18b95ddca9704d64627cde69375e30a880efaa95
Zetinator/just_code
/python/leetcode/poisonous_plants.py
3,076
3.921875
4
"""https://www.hackerrank.com/challenges/poisonous-plants/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=stacks-queues There are a number of plants in a garden. Each of these plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left. """ import sys sys.setrecursionlimit(100000) def poisonousPlants(p): """naive solution, recursive almost there, failing because of recursion depth """ def r(x, ans=0): tmp = [x[0]] for i in range(len(x)-1): if x[i] >= x[i+1]: tmp.append(x[i+1]) if tmp == x: return ans return r(tmp, ans+1) return r(p) def poisonousPlants(p): """naive solution, iterative not fast enought... """ for days in range(len(p)): tmp = p[:1] for i in range(len(p)-1): if p[i] >= p[i+1]: tmp.append(p[i+1]) if p == tmp: return days p = tmp from collections import deque def poisonousPlants(p): """stack solution... the solution is a list of stacks working... almost """ # create list of stacks in descendent order stacks = [] tmp = deque(p[:1]) for i in range(len(p)-1): if p[i] < p[i+1]: stacks.append(tmp) tmp = deque([p[i+1]]) else: tmp.append(p[i+1]) # push the remaining stacks.append(tmp) if len(stacks[0]) == len(p): return 0 print(f'stacks: {stacks}') for days in range(1, len(p)): current_min = stacks[0][-1] pop_flag = False for stack in stacks[1:]: if not stack: continue print(f'day: {days}, stack: {stack}, current_min: {current_min}') while stack and stack[0] > current_min: print(f'deque: {stack[0]}') stack.popleft() pop_flag = True current_min = stack[-1] if stack else current_min if not pop_flag: return days from collections import deque def poisonousPlants(p): """optimized solution """ # create list of stacks stacks, days = [deque(p[:1])], 0 for i, v in enumerate(p[1:], 1): if p[i-1] < v: stacks += [deque([v])] else: stacks[-1] += [v] # consecutive pops according to the days while len(stacks) > 1: i = 1 while i < len(stacks): stacks[i].popleft() if not stacks[i]: stacks.pop(i) elif stacks[i-1][-1] >= stacks[i][0]: stacks[i-1] += stacks[i] stacks.pop(i) else: i += 1 days += 1 return days # test test = [6,5,8,4,7,10,9] test = [4, 3, 7, 5, 6, 4, 2,] # test = [3,2,5,4] print(f'testing with {test}') print(f'ans: {poisonousPlants(test)}')
246928be6fa574268809d7291343ff2e7d099234
Zetinator/just_code
/python/classics/max_change.py
654
3.8125
4
""" Coin Change problem: Given a list of coin values in a1, what is the minimum number of coins needed to get the value v? """ from functools import lru_cache @lru_cache(maxsize=1000) def r(x, coins, coins_used): """recursive implementation """ if x <=0: return coins_used return min(r(x-coin, coins, coins_used+1) for coin in coins) def max_change(money: int, coins: tuple) -> int: """finds the minimum combination of 'coins' to reach the 'money' quantity """ return r(money, coins, 0) # test money = 24 coins = (1,3,4,5) print(f'test with: money: {money}, coins: {coins}') print(f'min coins: {max_change(money, coins)}')
319781d2b8b2a6bb1fdbb3070ac71057b4e949a0
Zetinator/just_code
/python/data_structures/radix_trie.py
5,142
3.53125
4
"""custom implementation of a radix trie with the purpose of practice the ADT contains the following methods: - insert - search - delete """ class RTrie(): class Node(): """Node basic chainable storage unit """ def __init__(self, x=None): self.data = x self.children = {} def __init__(self, keys=None): self.root = self.Node() if keys: for key in keys: self.insert(key) def __repr__(self): nodes = [] def r(node, level): if node.data != None: nodes.append('\t'*(level-1) + f'({node.data})\n') for k,child in node.children.items(): nodes.append('\t'*level + f'--<{k}>--\n') r(child, level+1) r(self.root, 0) return ''.join(nodes) def insert(self, key): """insert a new key... recursive attempt """ data = key def lcp(key_1, key_2): """largest common prefix """ for i in range(min(len(key_1),len(key_2))): if key_1[i] != key_2[i]: return i return i+1 def r(current_node, key): """recursive branching... no children -> new branch common root + remainings -> split and extend common root + no remainings -> extend no comomon root -> create new branch """ # base case... no children if not current_node.children: current_node.children.setdefault(key, self.Node()).data = data return # look for similar roots in the children... for k, child in current_node.children.items(): i = lcp(k, key) prefix, suffix, key = k[:i], k[i:], key[i:] if prefix and suffix: # common root found... branching current_node.children[prefix] = self.Node() del(current_node.children[k]) # append suffixs to common root current_node.children[prefix].children[suffix] = self.Node() current_node.children[prefix].children[suffix].data = child.data current_node.children[prefix].children[suffix].children = child.children # recurse on the shared root return r(current_node.children[prefix], key) elif prefix and not suffix: # common root found... extending return r(child, key) # no common root... create new child branch current_node.children.setdefault(key, self.Node()).data = data return r(self.root, key) def predict(self, key=None): """predict all branches of the lowest common ancestor """ if not self.root.children: raise ValueError(f'{key} not found') def lcp(key_1, key_2): """largest common prefix """ i = 0 while i < min(len(key_1),len(key_2)): if key_1[i] != key_2[i]: return i i += 1 return i nodes = [] def dig(node): """explore all the leafs from the current_node """ if node.data != None: nodes.append(f'{node.data}') for k,child in node.children.items(): dig(child) def r(current_node, key): """search recursively the given key """ # base case... no children if not key: return dig(current_node) # look for similar roots in the children... for k, child in current_node.children.items(): i = lcp(k, key) prefix, suffix, key = k[:i], k[i:], key[i:] if prefix in current_node.children: # recurse on the shared root return r(current_node.children[prefix], key) return dig(current_node) r(self.root, key) return nodes def search(self, key): """search for a given key in the trie """ if not self.root.children: raise ValueError(f'{key} not found') def lcp(key_1, key_2): """largest common prefix """ i = 0 while i < min(len(key_1),len(key_2)): if key_1[i] != key_2[i]: return i i += 1 return i _key = key[:] def r(current_node, key): """search recursively """ # base case... no children if not key: return current_node # look for similar roots in the children... for k, child in current_node.children.items(): i = lcp(k, key) prefix, suffix, key = k[:i], k[i:], key[i:] if prefix: # recurse on the shared root return r(current_node.children[prefix], key) raise ValueError(f'{_key} not found') return r(self.root, key)
27db300075e7661296ee4d494f378aac89b21c83
Zetinator/just_code
/python/algorithms/dinic.py
2,041
4
4
"""implementation of the dinic's algorithm computes the max flow possible within a given network gaph https://visualgo.net/en/maxflow https://en.wikipedia.org/wiki/Dinic%27s_algorithm """ from data_structures import network_graph def dinic(graph: network_graph.NGraph) -> int: """computes the maximum flow value of the network """ # set-up residual_network = network_graph.NGraph(graph.inner, graph.source, graph.sink) dinic.max_flow = 0 dinic.parents = {} # retrieve bottle neck function def blocking_flow(node, minimum=float('inf')): """returns the value of the bottleneck once the sink is been reached """ if not node: return minimum minimum = min(minimum, residual_network.capacity(dinic.parents[node], node)) # recursively find minimum to return minimum = blocking_flow(dinic.parents[node], minimum) # update residual graph residual_network.capacities[dinic.parents[node], node] -= minimum return minimum # standard bfs def bfs(start, end): """standard bfs, with implicit queue modified to stop once the sink is been reached and increase the max flow """ dinic.parents = {graph.source:None} frontier = [graph.source] while frontier: _next = [] for current_node in frontier: for node in graph.neighbors(current_node): if node not in dinic.parents\ and residual_network.capacity(current_node, node)>0: dinic.parents[node] = current_node # sink within reach, increase max-flow if node == graph.sink: dinic.max_flow += blocking_flow(graph.sink) return True _next.append(node) frontier = _next # repeat until there are no more augmenting paths... s -> t while(bfs(graph.source, graph.sink)): pass return dinic.max_flow
6fc20cea6cd490bd44af17299584ee0be51356e4
Zetinator/just_code
/python/leetcode/min_swaps_2.py
1,795
3.796875
4
"""https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=arrays You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order. """ # the above was too slow for hackerrank... def minimumSwaps(x): current_pos = {e: i for i, e in enumerate(x)} swaps = 0 for i in range(len(x)): # skip if item is already where it should if x[i] == i+1: continue # standard swap x[i], x[current_pos[i+1]] = i+1, x[i] # update the current position of the swaped item current_pos[x[current_pos[i+1]]] = current_pos[i+1] swaps += 1 return swaps def minimumSwaps(x): sorted_x = sorted(x) right_pos = {e: i for i, e in enumerate(sorted_x)} def entropy(x, right_pos): return [i-right_pos[e] for i,e in enumerate(x)] swaps = 0 while sorted_x != x: swaps += 1 minima = min([i for i in range(len(x))], key=lambda i: i-right_pos[x[i]]) maxima = max([i for i in range(minima, len(x))], key=lambda i: i-right_pos[x[i]]) print(f'entropy current state: x: {x}, entropy: {entropy(x, right_pos)}') print(f'min: {minima}, maxima: {maxima}') x[minima], x[maxima] = x[maxima], x[minima] print(x) return swaps test = [7, 1, 3, 2, 4, 5, 6] test = [2, 1, 3, 1, 2] # test = [2, 1, 3, 7, 4, 5, 6] # test = [1, 2, 3, 7, 4, 5, 6] # test = [1, 2, 3, 4, 7, 5, 6] # test = [1, 2, 3, 4, 5, 7, 6] # test = [1, 2, 3, 4, 5, 6, 7] print(f'testing with: {test}') print(f'ans: {minimumSwaps(test)}')
c1d4def8281d064203472299ab75b786a9261ae2
Zetinator/just_code
/python/leetcode/find_maximum_index_product.py
1,328
3.9375
4
"""https://www.hackerrank.com/challenges/find-maximum-index-product/problem You are given a list of numbers . For each element at position (), we define and as: Sample Input 5 5 4 3 4 5 Sample Output 8 Explanation We can compute the following: The largest of these is 8, so it is the answer. """ def solve(arr): """we keep a stack to access the next biggest in O(1) """ stack_left, stack_right = [], [] left, right = [], [] # left -> right for i,e in enumerate(arr): while stack_left and e >= stack_left[-1][0]: stack_left.pop() left.append(stack_left[-1][1] if stack_left else 0) stack_left.append((e, i+1)) # right -> left for i in reversed(range(len(arr))): while stack_right and arr[i] >= stack_right[-1][0]: stack_right.pop() right.append(stack_right[-1][1] if stack_right else 0) stack_right.append((arr[i], i+1)) # multiply and we are done... res = -float('inf') for i,e in enumerate(left): res = max(res, (left[i])*(right[len(right)-1 -i])) return res test = """5 4 3 4 5""" test = [int(e) for e in test.split()] with open('./test_data.txt', 'r') as f: for line in f: test = [int(n) for n in line.split()] print(f'testing with: {test[:10]}...') print(f'ans: {solve(test)}')
308f485babf73eec8c433821951390b8c2414750
Zetinator/just_code
/python/leetcode/pairs.py
966
4.1875
4
"""https://www.hackerrank.com/challenges/pairs/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=search You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value. Complete the pairs function below. It must return an integer representing the number of element pairs having the required difference. pairs has the following parameter(s): k: an integer, the target difference arr: an array of integers. """ from collections import Counter def pairs(k, arr): counter = Counter() n_pairs = 0 for e in arr: # print(f'e: {e}, counter: {counter}, n_pairs: {n_pairs}') if e in counter: n_pairs += counter[e] counter[e+k] += 1 counter[e-k] += 1 return n_pairs # test k = 2 arr = [1,3,5,8,6,4,2] print(f'testing with: {arr}') print(f'ans: {pairs(k, arr)}')
671ea3e72e4ff94b20aed867eb3c4075b2be4d92
Zetinator/just_code
/python/classics/longest_common_substring.py
828
3.9375
4
"""In computer science, the longest common substring problem is to find the longest string (or strings) that is a substring (or are substrings) of two or more strings. https://en.wikipedia.org/wiki/Longest_common_substring_problem """ from functools import lru_cache @lru_cache(maxsize=1000) def r(x, y, record=0): """recursive implementation """ if not x or not y: return record print(f'STATUs: x: {x}, y: {y}, record: {record}') if x[0] == y[0]: return max(record, r(x[1:], y[1:], record+1)) return max(record, r(x, y[1:], 0), r(x[1:], y, 0)) def lcs(x, y): """returns the longest common substring in O(N*M) """ if not x or not y: return 0 return r(x, y) # test e = 'kim es super bonita' m = 'erick es lo maximo' print(f'testing with: {e}, {m}') print(f'ans: {lcs(e, m)}')
d7927eb47f552113d335a0e1b04f608e852a8c3a
Zetinator/just_code
/python/leetcode/string_comparator.py
910
4.0625
4
"""https://www.hackerrank.com/challenges/ctci-comparator-sorting/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided in the editor below. It has two fields: """ from collections import namedtuple Player = namedtuple('Player', ['name', 'score']) def sort_data(players): players = [Player(*e) for e in players] players = sorted(players, key=lambda x: (x.score, [-ord(e) for e in x.name])) players.reverse() return players # test players = [('amy', 100), ('david', 100), ('heraldo', 50), ('aakansha', 75), ('aleksa', 150)] print(f'testing with: test: {players}') print(f'ans: {sort_data(players)}')
e823b273ed44482d8c05499f66bf76e78b06d842
Zetinator/just_code
/python/leetcode/special_string_again.py
2,477
4.21875
4
"""https://www.hackerrank.com/challenges/special-palindrome-again/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=strings A string is said to be a special string if either of two conditions is met: All of the characters are the same, e.g. aaa. All characters except the middle one are the same, e.g. aadaa. A special substring is any substring of a string which meets one of those criteria. Given a string, determine how many special substrings can be formed from it. """ def is_special(s): """checks if the substring is "special" """ # special case: if len(s) == 1: return True # general case match = s[0] for i in range(len(s)//2): if s[i] != match or s[i] != s[-(1+i)]: return False return True def substrCount(n, s): """counts how many substrings are "special" somehow not fast enought... maybe because of the function call """ n_specials = 0 for i in range(len(s)): for j in range(i, len(s)): n_specials += 1 if is_special(s[i:j+1]) else 0 return n_specials def substrCount(n, s): res = 0 count_sequence = 0 prev = '' for i,v in enumerate(s): # first increase counter for all seperate characters count_sequence += 1 if i and (prev != v): # if this is not the first char in the string # and it is not same as previous char, # we should check for sequence x.x, xx.xx, xxx.xxx etc # and we know it cant be longer on the right side than # the sequence we already found on the left side. j = 1 while ((i-j) >= 0) and ((i+j) < len(s)) and j <= count_sequence: # make sure the chars to the right and left are equal # to the char in the previous found squence if s[i-j] == prev == s[i+j]: # if so increase total score and step one step further out res += 1 j += 1 else: # no need to loop any further if this loop did # not find an x.x pattern break #if the current char is different from previous, reset counter to 1 count_sequence = 1 res += count_sequence prev = v return res # test # s = 'asasd' s = 'abcbaba' n = 5 print(f'testing with: {s}') print(f'ans: {substrCount(n, s)}')
768f200cbdbbbd4808c4eea18004f7e4ff7c912c
Zetinator/just_code
/python/data_structures/double_linked_list.py
3,017
3.96875
4
"""custom implementation of a double linked list with the purpose of practice the ADT contains the following methods: - append - insert - search - delete - traverse """ class DoubleLinkedList(): class Node(): """Node basic chainable storage unit """ def __init__(self, x=None, prev=None): self.value = x self.prev = prev self.next = None def __init__(self, x=[]): self.head = None for e in x: self.append(e) def append(self, x): """append a new node to the tail """ if not self.head: self.head = self.Node(x) return current_node = self.head while current_node.next: current_node = current_node.next current_node.next = self.Node(x, prev=current_node) return def search(self, x): """search for a node with the given 'x' value """ current_node = self.head while current_node: if current_node.value == x: return current_node current_node = current_node.next raise ValueError(f'{x} not found') def insert(self, x, index): """inserts a new node with value 'x' at the 'index' position """ # special case: empty list if not self.head: self.append(x) return # special case: replace head if index == 0: tmp = self.head self.head = self.Node(x) self.head.next = tmp return # general case current_node = self.head while current_node.next and (index-1): current_node = current_node.next index -= 1 tmp = current_node.next current_node.next = self.Node(x, prev=current_node) current_node.next.next = tmp def delete(self, x): """deletes the node with value 'x' """ # special case: empty list if not self.head: raise ValueError(f'{x} not in the list') # special case: delete head if self.head.value == x: self.head = self.head.next return # general case current_node = self.head while current_node.next: if current_node.next.value == x: current_node.next = current_node.next.next return current_node = current_node.next raise ValueError(f'{x} not in the list') def traverse(self): """print all the nodes in the link """ current_node = self.head while current_node: print(f'{current_node.value}', end=' -> ') current_node = current_node.next print('null') def __repr__(self): current_node = self.head ans = [] while current_node: ans.append(f'{current_node.value} -> ') current_node = current_node.next ans.append('null') return ''.join(ans)
51e43263d84055e470d62d41a870972357ab30f2
Zetinator/just_code
/python/leetcode/give_change.py
472
3.671875
4
def give_change(quantity): coins = [25, 10, 5, 1] def go_deep(quantity, coins, change): print('STATUS: quantity: {}, coins:{}, change:{}'.format(quantity, coins, change)) if quantity <= 0: return change n = quantity // coins[0] change[coins[0]] = n quantity -= n*coins[0] return go_deep(quantity, coins[1:], change) return go_deep(quantity, coins, {}) # test print('testing with 2350') print(give_change(2399))
6ee354648d87ca74e3a5c3776c70741bed442799
Zetinator/just_code
/python/leetcode/candies.py
3,186
3.984375
4
"""https://www.hackerrank.com/challenges/candies/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=dynamic-programming Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to minimize the total number of candies she must buy. For example, assume her students' ratings are [4, 6, 4, 5, 6, 2]. She gives the students candy in the following minimal amounts: [1, 2, 1, 2, 3, 1]. She must buy a minimum of 10 candies. """ import time def candies(n, arr): """dev version returns score with traceback """ def r(arr, prev, acc, ans=None): # remember... time.sleep(.1) p_grade, p_candie = prev if not arr: return (acc, (p_grade,p_candie)) c_candie = 1 while True: print(f'arr: {arr}, c: {arr[0]}, p_candie: {p_candie}') # depending on the past state decide if arr[0] <= p_grade: if p_candie - 1 <= 0: print('geht nicht...'); return ans = r(arr[1:], (arr[0], c_candie), acc + c_candie) if arr[0] > p_grade: ans = r(arr[1:], (arr[0], p_candie+1), acc + p_candie+1) # if failure... change current_state if ans: return ans + ((p_grade,p_candie),) else: c_candie += 1 retry = 1 while True: ans = r(arr[1:], (arr[0], retry), retry) if ans: score, *traceback = ans traceback.reverse() print(f'traceback: {traceback}') return score retry += 1 from functools import lru_cache import sys sys.setrecursionlimit(100000) def candies(n, arr): """prod version some good old backtracking... """ candies = [1] * len(arr) def r(i): # accept if i == len(arr): return True if i < len(arr)-1 and arr[i] < arr[i+1]: candies[i+1] = candies[i] + 1 return r(i+1) # reject if arr[i-1] > arr[i] and candies[i-1] - 1 == 0: return # change state while True: if r(i+1): return True candies[i] += 1 # init while True: if r(0): return sum(candies) else: candies[0] += 1 def candies(n, arr): """naive approach """ candies = [1] * len(arr) # left -> right for i in range(len(arr)-1): if arr[i] < arr[i+1]: candies[i+1] = max(candies[i+1], candies[i] + 1) # right -> left for i in reversed(range(1, len(arr))): if arr[i] < arr[i-1]: candies[i-1] = max(candies[i-1], candies[i] + 1) return sum(candies) test = [4, 6, 4, 5, 6, 2] test = [1,2,2] # test = [2,4,2,6,1,7,8,9,2,1] # test = [2,4,3,5,2,6,4,5] n = len(test) print(f'testing with: {test}') print(f'ans: {candies(n, test)}')
7353020b0f9f4e876ad39334bad7953aa1096b44
Zetinator/just_code
/python/leetcode/max_min.py
965
3.953125
4
"""https://www.hackerrank.com/challenges/angry-children/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=greedy-algorithms Complete the maxMin function in the editor below. It must return an integer that denotes the minimum possible value of unfairness. maxMin has the following parameter(s): k: an integer, the number of elements in the array to create arr: an array of integers . """ def maxMin(k, arr): s_arr = sorted(arr) minima = float('inf') for i in range(len(s_arr)-(k-1)): # the begining is inclusive and the end is exclusive print(f'max: {s_arr[i+(k-1)]}, min: {s_arr[i]}') delta = s_arr[i+(k-1)] - s_arr[i] if delta < minima: minima = delta return minima # test k = 4 arr = [1, 2, 3, 4, 10, 20, 30, 40, 100, 200] print(f'testing with: {arr}') print(f'ans: {maxMin(k, arr)}')
44b2c2a5ef7e890d3f38b6ccb1e990ed668930d2
Zetinator/just_code
/python/data_structures/max_heap.py
3,645
3.875
4
"""custom implementation of a max heap tree with the purpose of practice the ADT contains the following methods: - push - peek - pop """ class Heap(): def __init__(self, x=[]): self.v = [] for e in x: self.push(e) def __len__(self): return len(self.v) def __repr__(self): return str(self.v) def push(self, x): """push a new element into the heap can also push tuples with the priority as the first element :) """ # special case: push None element if not x: return # auxiliar function to compute the parent index parent = lambda i: max((i-1)//2, 0) v = self.v # alias because i am lazy to write # special case: empty heap if not v: v.append(x); return # general case i = len(v) v.append(x) # bubble up... while v[parent(i)] < v[i]: v[parent(i)], v[i] = v[i], v[parent(i)] i = parent(i) def peek(self): """peek the maximum """ # special case: empty heap if not self.v: return return self.v[0] def pop(self): """pop the maximum """ v = self.v # alias again # special case: empty heap if not v: return # swap max <-> last v[0], v[-1] = v[-1], v[0] minimum = v.pop() # bubble down i = 0 left = lambda: i*2 + 1 if i*2 + 1 < len(v) else False right = lambda: i*2 + 2 if i*2 + 2 < len(v) else False while left() and v[left()] > v[i] or right() and v[right()] > v[i]: max_child = left() if right() and v[right()] > v[left()]: max_child = right() v[i], v[max_child] = v[max_child], v[i] # swap i = max_child return minimum class Heap(): def __init__(self, x=[]): self._ = [] for e in x: self.push(e) def push(self, x): """push a new element into the heap can also push tuples with the priority as the first element :) """ # special case: push None element if not x: return # auxiliar function to compute the parent index parent = lambda i: max((i-1)//2, 0) _ = self._ # alias because i am lazy to write # special case: empty heap if not _: _.append(x); return # general case i = len(_) _.append(x) while _[parent(i)] < _[i]: # heapify-up # print(f'index: {i}, parent: {_[parent(i)]}, current: {_[i]}') _[parent(i)], _[i] = _[i], _[parent(i)] i = parent(i) def peek(self): """peek the maximum """ # special case: empty heap if not self._: return return self._[0] def pop(self): """pop the maximum """ _ = self._ # alias again # special case: empty heap if not _: return # swap max <-> last _[0], _[-1] = _[-1], _[0] maximum = _.pop() # sift down i = 0 i_left = lambda: i*2 + 1 i_right = lambda: i*2 + 2 while (i_left() < len(_) and _[i_left()] > _[i]) or \ (i_right() < len(_) and _[i_right()] > _[i]): max_child = i_left() if i_right() < len(_) and _[i_right()] > _[i_left()]: max_child = i_right() _[i], _[max_child] = _[max_child], _[i] # swap i = max_child return maximum def __len__(self): return len(self._) def __repr__(self): return str(self._)
e2b8fe6ba7d4d000b5ef8578aae3caf1847efc9d
Zetinator/just_code
/python/leetcode/unique_email.py
1,391
4.375
4
""" Every email consists of a local name and a domain name, separated by the @ sign. For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. Besides lowercase letters, these emails may contain '.'s or '+'s. If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.) If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.) It is possible to use both of these rules at the same time. Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails? """ def unique_email(x: 'array with emails')-> 'array with unique emails': ans = set() for e in x: name, domain = e.split('@') name = e.replace('.','').split('+')[0] ans.add(f'{name}@{domain}') return list(ans) # test test = ["test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com"] print(f'testing with: {test}') print(f'ANS: {unique_email(test)}')
c80ef444ca25f5a4a263ef68b3dfdab39aa85c89
santiagoahc/coderbyte-solutions
/medium/swapII.py
513
3.5
4
def SwapII(str): new_str = [] last_digit = (None, -1) for i, s in enumerate(str): if s.isalpha(): s = s.lower() if s.isupper() else s.upper() elif s.isdigit(): if last_digit[0]: new_str[last_digit[1]] = s s = last_digit[0] last_digit = (None, -1) elif i+1 < len(str) and str[i+1].isalpha(): last_digit = s, i else: last_digit = (None, -1) new_str.append(s) return ''.join(new_str) print SwapII("123gg))((") print SwapII("yolO11")
b1310efca71f5bf0d3daa2d0ae9135a0edc70382
santiagoahc/coderbyte-solutions
/medium/bracket_matcher.py
711
3.96875
4
def BracketMatcher(str): round_brackets = 0 square_brackets = 0 total_pairs = 0 for s in str: if s == '(': round_brackets += 1 total_pairs += 1 elif s == ')': if round_brackets < 1: return 0 round_brackets -= 1 elif s == '[': square_brackets += 1 total_pairs += 1 if s == ']': if square_brackets < 1: return 0 square_brackets -= 1 if square_brackets != 0 or round_brackets != 0: return 0 if total_pairs == 0: return 1 return "1 %d" % total_pairs # code goes here text = "Code must be properly" more = " indented in Python!" return text + more
a8b5da625783c4dc555005d83ebb04dbea1b4e50
santiagoahc/coderbyte-solutions
/medium/most_free_time.py
1,603
4.09375
4
""" Using the Python language, have the function MostFreeTime(strArr) read the strArr parameter being passed which will represent a full day and will be filled with events that span from time X to time Y in the day. The format of each event will be hh:mmAM/PM-hh:mmAM/PM. For example, strArr may be ["10:00AM-12:30PM","02:00PM-02:45PM","09:10AM-09:50AM"]. Your program will have to output the longest amount of free time available between the start of your first event and the end of your last event in the format: hh:mm. The start event should be the earliest event in the day and the latest event should be the latest event in the day. The output for the previous input would therefore be 01:30 (with the earliest event in the day starting at 09:10AM and the latest event ending at 02:45PM). The input will contain at least 3 events and the events may be out of order. "12:15PM-02:00PM","09:00AM-10:00AM","10:30AM-12:00PM" """ def MostFreeTime(strArr): def to_minutes(t): h, m = map(int, t[:-2].split(':')) h = h % 12 + (12 if t[-2] == 'P' else 0) return h * 60 + m events = sorted([[to_minutes(a) for a in p.split('-')] for p in strArr], key=lambda x:x[0]) breaks = [(b[0] - b[1]) for b in zip([e[0] for e in events[1:]], [e[1] for e in events[:-1]])] return '%02d:%02d' % divmod(max(breaks), 60) assert MostFreeTime(["12:15PM-02:00PM","09:00AM-10:00AM","10:30AM-12:00PM"]) == '00:30' # print MostFreeTime(["12:15PM-02:00PM","09:00AM-12:11PM","02:02PM-04:00PM"]) assert MostFreeTime(["12:15PM-02:00PM", "09:00AM-12:11PM", "02:02PM-04:00PM"]) == '00:04'
91f2f7d0ab659ac5454438737642142c3c18af15
santiagoahc/coderbyte-solutions
/hard/bitch.py
2,860
3.625
4
def gcd(a, b): while a % b: a, b = b, a % b return b def frac_reduce(num, den): g = gcd(num, den) return (num/g, den/g) class Fraction: def __init__(self, num, den=1): self.num, self.den = frac_reduce(num, den) def __neg__(self): return Fraction(-self.num, self.den) def __add__(self, other): if type(other) == type(0): return self + Fraction(other) elif type(other) != type(self): raise TypeError return Fraction(self.num * other.den + other.num * self.den, self.den * other.den) def __sub__(self, other): if type(other) == type(0): return self - Fraction(other) elif type(other) != type(self): raise TypeError return self + -other def __mul__(self, other): if type(other) == type(0): return self * Fraction(other) elif type(self) != type(other): raise TypeError return Fraction(self.num * other.num, self.den * other.den) def __div__(self, other): if type(other) == type(0): return self / Fraction(other) elif type(other) != type(self): raise TypeError return Fraction(self.num * other.den, self.den * other.num) def __eq__(self, other): if other == None: return False elif type(other) == type(0): return self == Fraction(other) elif type(other) != type(self): raise TypeError return self.num == other.num and self.den == other.den def __str__(self): return str(self.num) if self.den == 1 else '%d/%d' % (self.num, self.den) class Point: def __init__(self, x, y): self.x = x self.y = y class Line: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 if p1.x == p2.x: self.m = None else: self.m = (p2.y - p1.y) / (p2.x - p1.x) self.b = p1.y - self.m * p1.x def intersection(self, other): if self.m == other.m: return None elif self.m == None or other.m == None: if self.m == None: return other.intersection(self) return (other.p1.x, self.m * other.p1.x + self.b) x = (other.b - self.b) / (self.m - other.m) #mm = sorted([self.p1.x, self.p2.x]) #if x < mm[0] or x > mm[1]: # return None return (x, self.m * x + self.b) def IntersectingLines(strArr): points = [Point(a[0], a[1]) for a in [map(Fraction, map(int, s[1:-1].split(','))) for s in strArr]] l1 = Line(points[0], points[1]) l2 = Line(points[2], points[3]) i = l1.intersection(l2) return '(%s,%s)' % (str(i[0]), str(i[1])) if i else 'no intersection' print (IntersectingLines(["(100,5)","(6,2)","(2,6)","(5,100)"]))
70d7c7e63e2c431192dafc2df18f86ef0551541d
santiagoahc/coderbyte-solutions
/members/kaprekars.py
1,338
3.671875
4
""" Using the Python language, have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits. Your program should perform the following routine on the number: Arrange the digits in descending order and in ascending order (adding zeroes to fit it to a 4-digit number), and subtract the smaller number from the bigger number. Then repeat the previous step. Performing this routine will always cause you to reach a fixed number: 6174. Then performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174). Your program should return the number of times this routine must be performed until 6174 is reached. For example: if num is 3524 your program should return 3 because of the following steps: (1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352, (3) 8532 - 2358 = 6174. """ def KaprekarsConstant(num): def calc(a_num, num_calc): if a_num == 6174: return num_calc num_str = str(a_num) if len(num_str) < 4: a_num *= 10**(4-len(num_str)) num_str = str(a_num) max_num = int("".join(sorted(num_str, reverse=True))) min_num = int("".join(sorted(num_str))) new_num = max_num - min_num return calc(new_num, num_calc+1) return calc(num, 0)
c685e5a1b88a50e5206e108c18453cd8206aa855
santiagoahc/coderbyte-solutions
/medium/polish notation.py
633
3.984375
4
""" "+ + 1 2 3" expr is a polish notation list """ def solve(expr): """Solve the polish notation expression in the list `expr` using a stack. """ operands = [] # Scan the given prefix expression from right to left for op in reversed(expr): if op == "+": operands.append(operands.pop() + operands.pop()) elif op == "-": operands.append(operands.pop() - operands.pop()) else: operands.append(float(op)) return operands.pop() assert solve("+ + 1 2 3".split()) == 6 assert solve("+ 10 5".split()) == 15 assert solve("- 15 - 7 + 1 1".split()) == 10
0bca43812f3d8fcf893ca985c8f5f7db76335a25
santiagoahc/coderbyte-solutions
/medium/arith_geo.py
810
3.609375
4
__author__ = 'osharabi' def ArithGeoII(arr): if len(arr) <= 1: return -1 diff = arr[1] - arr[0] mult = arr[1] / arr[0] i = 1 while (i+1) < len(arr) and not (diff is None and mult is None): cur_diff = arr[i+1] - arr[i] curr_mult = arr[i+1] / arr[i] if cur_diff != diff: diff = None if curr_mult != mult: mult = None i += 1 if diff != None: return 'Arithmetic' if mult != None: return 'Geometric' return -1 assert ArithGeoII([1,2,3,100]) == -1 assert ArithGeoII([-2, -6, -18, -54]) == 'Geometric' assert ArithGeoII([2, 6, 18, 54]) == 'Geometric' assert ArithGeoII([5, 10, 15]) == "Arithmetic" assert ArithGeoII([2, 4, 6]) == "Arithmetic" assert ArithGeoII([-4, 4, 12]) == "Arithmetic"
292d7fcf6be00f2e22950fc9af2abc9f6493bf0d
santiagoahc/coderbyte-solutions
/medium/three_five_mult.py
130
3.875
4
def ThreeFiveMultiples(num): return sum([n for n in range(3, num) if (n % 3 == 0 or n % 5 == 0)]) print ThreeFiveMultiples(16)
2a2acbc1e8bf446dd7b8ac5582d9faa5f4f7f51b
nbonfils/fixed-probe
/sensor-server.py
6,956
3.5625
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- """Server that reads values from differents sensors. This script is a server that is supposed to run on a RPi with the adequate sensors hooked to it via GPIO. It reads the value of the sensors then store them on disk or on the usb drive if one is plugged, it also always export local data on the usb drive if there are local data. The measurements are stored in csv format in the file called : "sensors_data.csv" either locally in "/srv/sensors/" or directly at the root of the usb. The sensors are: BMP180 from adafruit : ambient temperature and barometric pressure DS18B : water temperature Turbidity Sensor (dishwasher) : turbidity of water It also records the time and date of the measure. """ import os import sys from csv import DictWriter, DictReader from time import sleep from datetime import datetime from w1thermsensor import W1ThermSensor from Adafruit_BMP.BMP085 import BMP085 from turbsensor import TurbiditySensor # Constants DATA_FILENAME = 'sensors_data.csv' PATH_TO_MEDIA = '/media/root' MEASURE_INTERVAL = 60 # Global variables need_to_export = None data_file_exists = None turbidity_sensor = None def init(): """Initialization for the server to run properly.""" global need_to_export global data_file_exists global turbidity_sensor # Don't know if data file exists yet data_file_exists = False # Init working directory os.chdir('/srv/sensors') # Check if a local file is to be exported dirents = os.listdir() need_to_export = False for ent in dirents: if ent == DATA_FILENAME: need_to_export = True break # Create and start the Turbidity Sensor thread on analog pin 0 pin = 0 mes_per_interval = 20 sleep = MEASURE_INTERVAL / mes_per_interval turbidity_sensor = TurbiditySensor(pin, sleep) turbidity_sensor.start() def find_dev(path): """Find usb device absolute path. Note: Also check if data already exists on device and update global variable data_file_exists. Args: path (str): The path to the dir where the device might be. Returns: str: Full path to the correct usb device. """ global data_file_exists data_file_exists = False dev = '' # Get full path of all devices connected dirents = [os.path.join(path, e) for e in os.listdir(path)] # Pick first one by default if data don't exists on others if dirents: dev = dirents[0] # Try to find if data file already exists on one device for ent in dirents: found = False for subent in os.listdir(ent): if subent == DATA_FILENAME: dev = ent data_file_exists = True found = True break if found: break return dev def write_data(data): """Write data in the file and eventually export the local file. Note: Change 2 global variables to know where to write next time. Args: data (dict): The dict containing the data for each parameter. """ global need_to_export global data_file_exists path = find_dev(PATH_TO_MEDIA) fieldnames = [ 'time', 'date', 'air_temp', 'air_pressure', 'water_temp', 'turb' ] if path == '': # If there is no storage device, write on disk (sd card) with open(DATA_FILENAME, 'a', newline='') as f: writer = DictWriter(f, fieldnames) if not need_to_export: # If data file will be created, add headers writer.writeheader() writer.writerow(data) # As written on disk data will need to be exported now need_to_export = True else: # If storage device available, check if need to export # Create the full path to the file on the device path = os.path.join(path, DATA_FILENAME) if need_to_export: # Open the 2 files and transfer the data with open(DATA_FILENAME, 'r', newline='') as e, \ open(path, 'a+', newline='') as f: reader = DictReader(e) writer = DictWriter(f, fieldnames) if not data_file_exists: # New data file will be created on device writer.writeheader() data_file_exists = True # Write data on device for row in reader: writer.writerow(row) writer.writerow(data) # Once exported remove the local data file os.remove(DATA_FILENAME) # No more local file to be exported need_to_export = False else: # No need to export with open(path, 'a', newline='') as f: writer = DictWriter(f, fieldnames) if data_file_exists: writer.writerow(data) else: writer.writeheader() writer.writerow(data) # Data file created on disk data_file_exists = True def get_data(): """Get the data from the sensors, also get the date and time. Data recorded: time (str): the time of the record in HH:MM:SS format. date (str): the date of the record in DD-MM-YYYY format. air_temp (float): the ambient temperature in Celsius. air_pressure (float): the barometric pressure in Pascal. water_temp (float): the temperature of the water in Celsius. turb (int): the analog value of the turbidity (from 0 to 1024). Returns: dict: The data in the order of the fieldnames. """ global turbidity_sensor # Date (DD-MM-YYY) and time (HH:MM:SS) d = datetime.now() time = '{:%H:%M:%S}'.format(d) date = '{:%d-%m-%Y}'.format(d) # (DS18B) Water temperature try: w = W1ThermSensor() water_temp = str(w.get_temperature()) except: water_temp = '0' # (BMP180) Air temperature + pressure try: b = BMP085() air_temp = str(b.read_temperature()) air_pressure = str(b.read_pressure()) except: air_temp = '0' air_pressure = '0' # Turbidity of the water turb = turbidity_sensor.read_turbidity() if turb > 1023: turb = 0 return { 'time' : time, 'date' : date, 'air_temp' : air_temp, 'air_pressure' : air_pressure, 'water_temp' : water_temp, 'turb' : turb } def main(): """The main function of the program.""" init() while True: data = get_data() write_data(data) sleep(MEASURE_INTERVAL) return 0 if __name__ == "__main__": sys.exit(main())
ca54ebba62347e2c3a4107872889e4746c51a922
malbt/PythonFundamentals.Exercises.Part5
/anagram.py
497
4.375
4
def is_anagram(first_string: str, second_string: str) -> bool: """ Given two strings, this functions determines if they are an anagram of one another. """ pass # remove pass statement and implement me first_string = sorted(first_string) second_string = sorted(second_string) if first_string == second_string: print("anagram") else: print("not anagram") first_string = "dormitory" second_string = "dirtyroom" is_anagram(first_string, second_string)
c093ea69bbcc1a304b3d9d65580f3930ac9aeefc
jpages/twopy
/tests/quick_sort.py
987
3.96875
4
import random # Very inefficient bubble sort def bubble_sort(array): for i in range(len(array)): for j in range(i, len(array)): if array[i] > array[j]: # Swap these elements temp = array[i] array[i] = array[j] array[j] = temp return array # More efficient quick sort (with a pivot) def quick_sort(array): less = [] equal = [] greater = [] if len(array) > 1: # Chose a pivot pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: greater.append(x) return quick_sort(less) + equal + quick_sort(greater) else: return array random.seed() array = [12, 4, 5, 6, 7, 3, 1, 15] for i in range(10000): array.append(int(random.random()*100000)) print(quick_sort(array)) print(bubble_sort(array))
e7e5c25404dcbd2c211d1ac67d59909bc48c81f7
jpages/twopy
/tests/sum35.py
917
3.75
4
def sum35a(n): 'Direct count' # note: ranges go to n-1 return sum(x for x in range(n) if x%3==0 or x%5==0) def sum35b(n): "Count all the 3's; all the 5's; minus double-counted 3*5's" # note: ranges go to n-1 return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15)) def sum35c(n): 'Sum the arithmetic progressions: sum3 + sum5 - sum15' consts = (3, 5, 15) # Note: stop at n-1 divs = [(n-1) // c for c in consts] sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)] return sums[0] + sums[1] - sums[2] #test for n in range(1001): sa, sb, sc = sum35a(n), sum35b(n), sum35c(n) assert sa == sb == sc # python tests aren't like those of c. print('For n = %7i -> %i\n' % (n, sc)) # Pretty patterns for p in range(7): print('For n = %7i -> %i' % (10**p, sum35c(10**p))) # Scalability p = 20 print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))
7530cd3094d1a69ac8a8ec7f8aff2555875167ba
Fashgubben/TicTacToe
/test_program.py
12,276
3.578125
4
import unittest import check_input import check_for_winner import game_functions from class_statistics import Statistics, Player from random import randint class TestCases(unittest.TestCase): """Test "check_input" functions""" def test_strip_spaces(self): test_value1 = '1 1 ' test_value2 = ' 1 1' test_value3 = ' 1 1 ' expected_value = '1 1' function_value = check_input.strip_spaces(test_value1) self.assertEqual(expected_value, function_value) function_value = check_input.strip_spaces(test_value2) self.assertEqual(expected_value, function_value) function_value = check_input.strip_spaces(test_value3) self.assertEqual(expected_value, function_value) def test_splits_on_space(self): test_value = '1 2' expected_result = ['1', '2'] function_value = check_input.splits_on_space(test_value) self.assertEqual(expected_result, function_value) def test_convert_to_int(self): test_value1 = ['1', '2'] test_value2 = ['1', 'a'] expected_result = [1, 2] function_value = check_input.convert_to_int(test_value1) self.assertEqual(expected_result, function_value) with self.assertRaises(ValueError): check_input.convert_to_int(test_value2) def test_check_coordinates_count(self): test_value1 = [randint(0, 10), randint(0, 10)] test_value2 = [1, 2, 3] test_value3 = [1] expected_result = 2 function_value = check_input.check_coordinates_count(test_value1) self.assertEqual(expected_result, len(function_value)) with self.assertRaises(ValueError): check_input.check_coordinates_count(test_value2) with self.assertRaises(ValueError): check_input.check_coordinates_count(test_value3) def test_check_coordinates_range(self): grid_size = 4 test_value1 = [randint(0, 3), randint(0, 3)] test_value2 = [8, 9] function_value = check_input.check_coordinates_range(test_value1, grid_size) self.assertIn(function_value[0] and function_value[1], range(grid_size)) with self.assertRaises(ValueError): check_input.check_coordinates_range(test_value2, grid_size) def test_is_coordinates_occupied(self): test_coordinates = [0, 1] name1 = 'Name' name2 = 'Skynet' game_board1 = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] game_board2 = [['_', '_', '_'], ['X', '_', '_'], ['_', '_', '_']] expected_value1 = [0, 1] function_value = check_input.is_coordinates_occupied(test_coordinates, game_board1, name1) self.assertEqual(expected_value1, function_value) function_value = check_input.is_coordinates_occupied(test_coordinates, game_board2, name2) self.assertFalse(function_value) with self.assertRaises(ValueError): check_input.is_coordinates_occupied(test_coordinates, game_board2, name1) def test_get_valid_coordinates(self): game_board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] grid_size = 3 user_input = "0 0" name = 'Name' expected_result = [0, 0] function_value = check_input.get_valid_coordinates(game_board, grid_size, user_input, name) self.assertEqual(expected_result, function_value) def test_check_x(self): game_board1 = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] game_board2 = [['_', '_', '_'], ['X', 'X', 'X'], ['_', '_', '_']] grid_size = 3 symbol = 'X' function_value = check_for_winner.check_x(game_board1, grid_size, symbol) self.assertNotEqual(function_value, True) function_value = check_for_winner.check_x(game_board2, grid_size, symbol) self.assertTrue(function_value) def test_check_y(self): game_board1 = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] game_board2 = [['_', '_', 'X'], ['_', '_', 'X'], ['_', '_', 'X']] grid_size = 3 symbol = 'X' function_value = check_for_winner.check_y(game_board1, grid_size, symbol) self.assertNotEqual(function_value, True) function_value = check_for_winner.check_y(game_board2, grid_size, symbol) self.assertTrue(function_value) def test_check_diagonal_1(self): game_board1 = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] game_board2 = [['X', '_', '_'], ['_', 'X', '_'], ['_', '_', 'X']] grid_size = 3 symbol = 'X' function_value = check_for_winner.check_diagonal_1(game_board1, grid_size, symbol) self.assertNotEqual(function_value, True) function_value = check_for_winner.check_diagonal_1(game_board2, grid_size, symbol) self.assertTrue(function_value) def test_check_diagonal_2(self): game_board1 = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] game_board2 = [['_', '_', 'X'], ['_', 'X', '_'], ['X', '_', '_']] grid_size = 3 symbol = 'X' function_value = check_for_winner.check_diagonal_2(game_board1, grid_size, symbol) self.assertNotEqual(function_value, True) function_value = check_for_winner.check_diagonal_2(game_board2, grid_size, symbol) self.assertTrue(function_value) """Test "class_statistics" functions""" def test_add_win(self): test_value = test_player.wins test_player.add_win() self.assertEqual(test_player.wins, test_value + 1) def test_add_total_move(self): test_value = test_player.total_moves test_player.add_total_move() self.assertEqual(test_player.total_moves, test_value + 1) def test_add_last_game_moves(self): test_value = test_player.last_game_moves test_player.add_last_game_moves() self.assertEqual(test_player.last_game_moves, test_value + 1) def test_calculate_total_average_moves(self): test_player.total_moves = 3 test_player.games = 1 test_player.calculate_total_average_moves() self.assertEqual(test_player.total_average_moves, round(test_player.total_moves / test_player.games, 2)) test_player.total_moves = 0 test_player.games = 0 test_player.calculate_total_average_moves() self.assertEqual(test_player.total_average_moves, 0.0) def test_calculate_average_win_moves(self): test_player.total_moves_winning_games = 3 test_player.wins = 1 test_player.calculate_average_win_moves() self.assertEqual(test_player.average_win_moves, round(test_player.total_moves_winning_games / test_player.wins, 2)) test_player.total_moves_winning_games = 0 test_player.wins = 0 test_player.calculate_average_win_moves() self.assertEqual(test_player.total_moves_winning_games, 0.0) def test_update_player_moves(self): test_player.total_moves = 3 test_player.last_game_moves = 3 expected_result = test_player.total_moves + test_player.last_game_moves test_player.update_player_moves() self.assertEqual(expected_result, test_player.total_moves) def test_update_percent(self): test_player.games = 2 test_player.wins = 1 test_player.ties = 1 expected_result = '50.0%' function_value = test_player.update_percent(test_player.wins, test_player.games) self.assertEqual(expected_result, function_value) function_value = test_player.update_percent(test_player.ties, test_player.games) self.assertEqual(expected_result, function_value) test_player.games = 0 test_player.wins = 0 expected_result = '0.0%' function_value = test_player.update_percent(test_player.wins, test_player.games) self.assertEqual(expected_result, function_value) def test_update_scoreboard(self): test_player.games = 2 test_player.wins = 1 test_player.ties = 1 expected_result = '50.0%' test_player.update_scoreboard() self.assertEqual(expected_result, test_player.win_percent) self.assertEqual(expected_result, test_player.tie_percent) def test_get_total_win(self): test_player.wins = randint(0, 10) test_player2.wins = randint(0, 10) expected_result = test_player.wins + test_player2.wins total.get_total_win(test_player.wins, test_player2.wins) self.assertEqual(expected_result, total.wins) def test_get_total_last_moves(self): test_player.last_game_moves = randint(0, 10) test_player2.last_game_moves = randint(0, 10) expected_result = test_player.last_game_moves + test_player2.last_game_moves total.get_total_last_moves(test_player.last_game_moves, test_player2.last_game_moves) self.assertEqual(expected_result, total.last_game_moves) def test_get_total_moves(self): test_player.total_moves = randint(0, 10) test_player2.total_moves = randint(0, 10) expected_result = test_player.total_moves + test_player2.total_moves total.get_total_moves(test_player.total_moves, test_player2.total_moves) self.assertEqual(expected_result, total.total_moves) def test_get_total_winning_moves(self): test_player.total_moves_winning_games = randint(0, 10) test_player2.total_moves_winning_games = randint(0, 10) expected_result = test_player.total_moves_winning_games + test_player2.total_moves_winning_games total.get_total_winning_moves(test_player.total_moves_winning_games, test_player2.total_moves_winning_games) self.assertEqual(expected_result, total.total_moves_winning_games) """Test "game_turn" functions""" def test_create_board(self): test_value1 = 3 test_value2 = 1 expected_result1 = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] expected_result2 = [['_']] function_value = game_functions.create_board(test_value1) self.assertEqual(expected_result1, function_value) function_value = game_functions.create_board(test_value2) self.assertEqual(expected_result2, function_value) def test_reset_move_count(self): test_player.last_game_moves = 5 test_player2.last_game_moves = 4 total.last_game_moves = 3 game_functions.reset_move_count(test_player, test_player2, total) self.assertEqual(test_player.last_game_moves, 0) self.assertEqual(test_player2.last_game_moves, 0) self.assertEqual(total.last_game_moves, 0) def test_get_random_numbers(self): grid_size = 3 expected_list = game_functions.get_random_numbers(grid_size) self.assertIn(expected_list[0], range(0, grid_size)) self.assertIn(expected_list[1], range(0, grid_size)) def test_check_for_available_moves(self): grid_size = 3 game_board1 = [['X', 'X', 'X'], ['X', 'X', 'X'], ['X', 'X', 'X']] function_value1 = game_functions.check_for_available_moves(game_board1, grid_size) game_board2 = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] function_value2 = game_functions.check_for_available_moves(game_board2, grid_size) self.assertFalse(function_value1) self.assertTrue(function_value2) def test_place_mark(self): game_board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] coordinates = [0, 0] symbol = 'X' expected_result = [['X', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] game_functions.place_mark(game_board, coordinates, symbol) self.assertEqual(expected_result, game_board) test_player = Player('Test', 'T') test_player2 = Player('Test2', 'T2') total = Statistics() unittest.main()
a3ee45b658838526491e85141bc219b4e8a8d31e
Vipulhere/Python-practice-Code
/Module 10/3.1 insertinto.py
322
3.796875
4
import sqlite3 conn=sqlite3.connect("database.db") query="INSERT into STD(name,age,dept)values ('bob',20,'CS');" try: cursor=conn.cursor() cursor.execute(query) conn.commit() print("Our record is inserted into database") except: print("Error in database insert record") conn.rollback() conn.close()
cc779c69d84dc9ea2afc1249646caef9f589c15e
Vipulhere/Python-practice-Code
/Module 3/12.1 loops with else block of code.py
254
4.0625
4
for a in range(5): print(a) else: print("The loop has completed execution") print("_______________________") t=0 n=10 while (n<=10): t=t+n n=n+1 print("Value of total while loop is",t) else: print("You have value is equal to 10")
e777115b8048caa29617b9b0e99d6fbac3beef99
Vipulhere/Python-practice-Code
/Module 8/11.1 inheritance.py
643
4.3125
4
#parent class class parent: parentname="" childname="" def show_parent(self): print(self.parentname) #this is child class which is inherites from parent class Child(parent): def show_child(self): print(self.childname) #this object of child class c=Child() c.parentname="BOB" c.childname="David" c.show_parent() c.show_child() print("___________________") class car: def __init__(self,name="ford",model=2015): self.name=name self.model=model def sport(self): print("this is sport car") class sportcar(car): pass c=sportcar("sportcar") print(c.name) print(c.model) c.sport()
3db13f56cd5cac39e2e32ba3a5aa460d3cd957c4
Vipulhere/Python-practice-Code
/Module 8/7.1 object method.py
237
3.84375
4
class car: def __init__(self,name,color): self.name=name self.color=color def car_detail(self): print("Name of car",self.name) print("Color of car",self.color) c=car("ford","white") c.car_detail()
e549aca0a2c1b27dcde960f56b65da2eb6632fbd
Vipulhere/Python-practice-Code
/Module 6/6.1 tuple.py
169
3.75
4
tuple=() tuple2=(1,2,3,4,5,6) tuple3=("python","java","php") tuple4=(10,20,"java","php") print(tuple) print(tuple2) print(tuple3) del tuple3 print(tuple3) print(tuple4)
bcabbb2b0ed927d608c3bd8a832aded14e53738f
Vipulhere/Python-practice-Code
/Module 7/2.1 exception handling.py
209
3.796875
4
try: text=input("Enter a value or something you like") except EOFError: print("EOF Error") except KeyboardInterrupt: print("You cancelled the operation") else: print("you enterd".format(text))
5e9af0fd6c370d21c0ce17a5d6ccffad245abaf2
Vipulhere/Python-practice-Code
/Module 8/16.1 encapsulation.py
609
3.890625
4
class encapsulation: __name=None def __init__(self,name): self.__name=name def getname(self): return self.__name e=encapsulation("Encapsulation") print(e.getname()) print("________________") class car(object): def __init__(self,name="BMw",year=2020,mileage="250",color="white"): self.__name=name self.__year=year self.__mileage=mileage self.__color=color def cardetail(self,speed): print("your car spreed is %s" %(self.__name,speed)) def speeds(self,speed): print("meter speed is %s"%speed) c=car() print(car.__name)
f37f6cfbbe1ca3542992c7a6673284d9b59666a1
Vipulhere/Python-practice-Code
/Module 6/17.1 sort a dict.py
172
3.921875
4
dict={ "BMW":"2020", "Ford":"2019", "Toyota":"2018", "BMW": "2012", "Honda": "2015" } for key1 in sorted(dict,key=dict.get): print(key1,dict[key1])
391625ce1ccb63a4471ba41a184c346114168c46
Vipulhere/Python-practice-Code
/Module 2/5.1 Short Hand of operator.py
83
3.71875
4
var=2 var+=10 print(var) var*=10 print(var) var/=10 print(var) var-=10 print(var)
7b49801dcfbc7feeadb92bf9a9c8de86a7a90d48
Vipulhere/Python-practice-Code
/Module 3/5.1 nested if else.py
137
3.6875
4
var=-10 if var>0: print("Postive Number") else: print("Negative Number") if -10<=var: print("Two Digit are Negative")
3c2b47f35531074d47b6e3022ae94d8c30d5e99d
Vipulhere/Python-practice-Code
/Module 8/2.1 Classes and Object.py
170
3.921875
4
class car: model=2020 name="ford" c=car() print(c.model,c.name) class animal: age=20 name="dog" color="Black" a=animal() print(a.name,a.age,a.color)
3e49fd765e0672df380c18249f1b1cada092b1d9
pivacik/leetcode-algorithms
/plan_calc.py
272
3.71875
4
import sys def calculate_plan(a, b, c, d): if d > b: return a + c * (d - b) else: return a string = '' for line in sys.stdin: string += line lst = list(string.split()) a, b, c, d = lst print(a, b, c, d) print(calculate_plan(a, b, c, d))
aae533ba404018f1c31e8fb949d44741fc54c792
frigusgulo/F4_Architecture
/VM_Control_Only.py
1,540
3.71875
4
def Main(): pass # VM Control def goto(labelname): return "@" + str(labelname) + "\n0;JMP\n" def if_goto(labelname): return pop_D() + "D=D+1\n@" + str(labelname) + "\nD;JGT\n" # my understanding is if-goto jumps if top of stack is -1 (true) i.e. pop_D() + D=D+1 + D;JEQ def label(labelname): return "(" + str(labelname) + ")\n" RETURN_ADDRESSES = [] callnum = -1 def callFunction(FunctionName, nArgs): callnum += 1 RETURN_ADDRESS = str(FunctionName) + str(callnum) RETURN_ADDRESSES.append(RETURN_ADDRESS) str = "@" + RETURN_ADDRESS + "\nD=A\n" + push_D() str += saveFrame(LCL) + saveFrame(ARG) + saveFrame(THIS) + saveFrame(THAT) str += "@SP\nD=M\n@" + (5 + int(nArgs)) + "\nD=D-A\n@ARG\nM=D\n" str += "@SP\nD=M\n@LCL\nM=D\n" str += goto(str(FunctionName)) str += "(" + RETURN_ADDRESS + ")\n" return str # Helper function for callFunction def saveFrame(name): return "@" + str(name) + "\nD=M\n" + push_D() def makeFunction(FunctionName, nVars): str = label(str(FunctionName)) for i in range(nVars): str += "D=0\n" + push_D() return str def return_control(): str = "@LCL\nD=M\n@endFrame\nM=D\n" str += "@5\nD=A\n@endFrame\nD=M-D\n@returnAddress\nM=D\n" str += pop_D() + "@ARG\nM=D\n" str += "@SP\nM=D+1\n" str += "@endFrame\nD=M\n" + "@THAT\nDM=D-1\n" + "@THIS\nDM=D-1\n" + "@ARG\nDM=D-1\n" + "@LCL\nM=D-1\n" str += goto(RETURN_ADDRESSES[-1]) RETURN_ADDRESSES.pop() return str if __name__ == '__main__': main()
78f055ae60f4eaa45424f8f9dea223ff1d5c667c
yukimiii/competitive-programming
/typical90/solved/75.py
378
3.703125
4
def prime_factorize(n): a = [] while n % 2 == 0: a.append(2) n //= 2 f = 3 while f * f <= n: if n % f == 0: a.append(f) n //= f else: f += 2 if n != 1: a.append(n) return a n = int(input()) a=prime_factorize(n) b=len(a) count=0; while(b>1): b=-(-b//2) count+=1 print(count)
b8585391d0425578a059c18ccd8399eaa4db1581
Bullsquid/gitTask-1
/halves.py
693
3.8125
4
import numpy as np import matplotlib.pyplot as plt def min_halves(f, a, b, eps): if b < a: tmp = a a = b b = tmp t = np.arange(a-1.0, b+1.0, 0.02) right = [] left = [] plt.plot(t, f(t)) while b-a >= eps: center = (a + b) / 2.0 delta = (b-a) / 4.0 x1 = center - delta x2 = center + delta if f(x1) < f(x2): b = x2 right.append(x2) else: a = x1 left.append(x1) plt.plot(right, map(f, right), 'rs') plt.plot(left, map(f, left), 'bs') plt.show() x_min = (a+b) / 2.0 return {"x": x_min, "f": f(x_min) }
b0032fa5aa5281354ec4cd92162dc9ac2e1e2e78
lohe987/ECE366Group4Project3
/simulator_z.py
5,921
3.640625
4
import sys import collections # Class CPU will hold the information of the CPU class CPU: PC = 0 # Program Counter DIC = 0 # Insturction Counter R = [0] * 4 # Register Values instructions = [] # instructions in array memory = [] # memory in array def check_parity_bit(machine_line): # Count the number of zeros and ones one_zero_dict = collections.Counter(machine_line) # Make sure an even number of ones exist in the instructions if one_zero_dict["1"] % 2 == 0: return True return False def convert_imm_value(number): if number < 0: number = 0xFFFF + number + 1 return format(int(number), "016b") def xor(a, b): result = "" for c,d in zip(a,b): if c == d: result = result + "0" else: result = result + "1" return result def load_program(cpu, instr_file_name, memory_file_name): instr_file = open(instr_file_name, "r") memory_file = open(memory_file_name, "r") for line in instr_file: line = line.strip() if len(line) < 1 or line.startswith("#") or line.startswith("U"): continue line = line.split(" ") cpu.instructions.append(line[0]) for line in memory_file: line = line.strip() if len(line) < 1 or line.startswith("#"): continue number = int(line,2) if line.startswith("1"): number = (0xFFFF - int(line,2) + 1) * -1 cpu.memory.append(number) for i in range(128-len(cpu.memory)): cpu.memory.append(0) instr_file.close() memory_file.close() return cpu def run_program(cpu): finished = False while(not finished): instr = cpu.instructions[cpu.PC] if not check_parity_bit(instr): print(instr) print("ERROR: Parity Bit Error") sys.exit() if instr[1:8] == "1110111": ''' cpu.R[3] = cpu.R[3] ^ cpu.R[2] cnt = str(bin(cpu.R[3])).count("1") cpu.R[3] = 16 - cnt # 16 bit integers ''' a = convert_imm_value(cpu.R[3]) b = convert_imm_value(cpu.R[2]) result = collections.Counter(xor(a,b)) cpu.R[3] = result["0"] cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:8] == "1110000": # Halt Command finished = True cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:6] == "01100": # AddR instruction Rx = registers[instr[6:8]] cpu.R[2] = cpu.R[Rx] + cpu.R[Rx] cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:6] == "01111": # AddR3 instruction Rx = registers[instr[6:8]] cpu.R[3] = cpu.R[Rx] + cpu.R[Rx] cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:6] == "01110": # AddR2 instruction Rx = registers[instr[6:8]] cpu.R[2] = cpu.R[2] + cpu.R[Rx] cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:6] == "01101": # Sub R3 instruction Rx = registers[instr[6:8]] cpu.R[3] = cpu.R[3] - cpu.R[Rx] # R3 = R3 - RX cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:4] == "001": # Load instruction Rx = registers[instr[4:6]] Ry = registers[instr[6:8]] cpu.R[Rx] = cpu.memory[cpu.R[Ry]] cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:4] == "010": # Store instruction Rx = registers[instr[4:6]] Ry = registers[instr[6:8]] cpu.memory[cpu.R[Ry]] = cpu.R[Rx] cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:4] == "000": # Init instruction Rx = registers[instr[3:5]] # Bit 4 picks whether or not this should be cpu.R[Rx] = int(instr[5:8], 2) # Cast the imm value into base ten cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:3] == "11": # Branch Equal R0 Rx = registers[instr[3:5]] imm = imm_mux[instr[5:8]] if cpu.R[Rx] == cpu.R[0]: cpu.PC = cpu.PC + imm else: cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:4] == "100": # Add immediate Rx = registers[instr[4:6]] imm = registers[instr[6:8]] # imm value is [0,3] in this case encoded the same way as the registers cpu.R[Rx] = cpu.R[Rx] + imm cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 elif instr[1:4] == "101": # Set less than, if so R0 = 1 Rx = registers[instr[4:6]] Ry = registers[instr[6:8]] if cpu.R[Rx] < cpu.R[Ry]: cpu.R[0] = 1 else: cpu.R[0] = 0 cpu.PC = cpu.PC + 1 cpu.DIC = cpu.DIC + 1 else: print("Error Unknown command") sys.exit() #print(cpu.R) #print(cpu.memory[0:10]) return cpu registers = {"00" : 0, "01" : 1, "10" : 2, "11" : 3} imm_mux = {"000": -22, #P1 JMP "001": -9, #P2 JMP "010": -5, #P1 JMP "011": -6, #P2 JMP (X2) "100": 3, #P1 JMP "101": -17, #P2 JMP "110": 16, #P2 JMP (X3) "111": 21} #P1 JMP if __name__ == "__main__": cpu1 = CPU() cpu1 = load_program(cpu1, "prog1_group_4_p2_bin.txt", "patternA.txt") print(cpu1.memory[0:10]) print(cpu1.R) print(cpu1.instructions) cpu1 = run_program(cpu1) print("Registers: " + str(cpu1.R)) print("DIC: " + str(cpu1.DIC)) print(cpu1.memory[0:10])
1dd2bc4d81e2f09a5dec71127ac5eade13be3dd8
mayanksingh2233/ML-algo
/ML Algorithms/linear regression.py
899
3.546875
4
#!/usr/bin/env python # coding: utf-8 # # linear regression # In[17]: import pandas as pd import numpy as np import matplotlib.pyplot as plt # In[115]: df=pd.read_csv('E:\\python\\datasets\\cars.csv',delimiter=';',skiprows=[1]) df.head() # In[118]: x=df[['Displacement']] x # In[120]: y=df[['Acceleration']] y # In[121]: from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression # In[122]: x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3) # In[123]: lr=LinearRegression() # In[124]: lr.fit(x_train,y_train) # In[125]: y_pred=lr.predict(x_test) # In[126]: y_pred # In[127]: y_test # In[110]: from sklearn.metrics import mean_squared_error # In[128]: mean_squared_error(y_pred,y_test) # In[130]: plt.scatter(x_test,y_test) plt.plot(x_test,y_pred,color='r') plt.show() # In[ ]:
b59bb752bfdc1b3fdd2c2f2c961b79b27dcc9188
935375572/python_study
/1基础/13成员运算符in_notin.py
146
3.65625
4
# in 判断数据是否在序列之中 # not in 判断数据是否不再序列中 numbers = ["A", "B", "C"] if "B" in numbers: print("对的")
3a40e487e84bdd009f31a2606a1261bf8d81ebaf
935375572/python_study
/1基础/4在字符串上使用乘法.py
563
3.78125
4
info = "msg" * 5 # 重复5遍 print(info) """使用与逻辑运算符 and""" name = "张三" age = 13 result = name == "张三" and age == 13 print(result) """使用或逻辑运算符 or""" name = "张三" age = 13 result = name == "张三" or age == 13 print(result) """使用非逻辑运算符 and""" name = "张三" age = 13 result = not age == 13 print(result) """身份运算符:通过一个id()函数以获取数据对应的内存地址""" nub = 2 print("nub的内存地址是:%s" % id(nub)) nub = 100 print("nub的内存地址是:%s" % id(nub))
883c2914bec7eb100a9d1eb5be239b04793af6d9
935375572/python_study
/1基础/3定义布尔型变量.py
610
3.828125
4
flag = True print(type(flag)) # 获取变量的类型 if flag: print("你好啊老哥") # 条件满足时执行 """字符串的连接操作""" info = "hello" info = info + "world" info += "python" info = "优拓软件学院\"www.yootk.com\"\n\t极限IT程序员:\'www.jixianit.com\'" print(info) """input()函数 获取键盘输入的数据""" msg = input("请输入你的内容:") wc = int(msg) # 将字符串转为int类型 if wc > 12: print("可以了") print(msg) # 打印输入的内容 """格式化输出""" name = "abc" age = 13 print("姓名是:%s 年龄有:%d" % (name, age))
13398c4ff7dad957ac14f32791f942f9c9ed4b58
AlSakharoB/easy_list_v1
/ft_even_index_list.py
265
3.640625
4
def ft_len_mass(mass): count = 0 for i in mass: count += 1 return count def ft_even_index_list(mass): mass1 = [] for i in range(ft_len_mass(mass)): if i % 2 == 0: mass1.append(mass[i]) return mass1
13e0b3ecf515c7e7f35e947e6ae523eb40320e5e
sraghus/Python_examples
/triangle.py
440
3.625
4
#!usr/bin/env python #import modules used here - sys is a very standard one import sys def area(base, height): return (base * height) / 2 if __name__ == '__main__': print('Area :', area(12,23)) def perimeter(side1, side2, side3): return (side1 + side2 + side3) if __name__ == '__main__': print ('Perimeter :', perimeter(12,83,95)) #def name(): # input("What is your name? ") #if __name__ == '__main__': # print name()
979fb7ce2ecbf9672d9674f8da264b6e3d870e50
chelseasenter/custom-dice-roller
/dice.py
6,846
3.515625
4
import random run='y' while run == 'y': ## introduction for user -------------------------------------------------------------------------------------------- # print(".") # print(".") # print(".") # print(".") # print(".") # print(".") # print(".-------------------------------------------------------------------------------------------------------*") # print("| Welcome to the Dice Roller 5000! There are several different ways to roll dice. See below for details.|") # print("*-------------------------------------------------------------------------------------------------------.") # print(" ") # print("_._._._._._._._._._._._._._._._._._._._._._") # print(" ") # print("5e Rolls") # print(" ") # print("To roll a pre-created D20 dice roll (initiative, saving throws, attack rolls, skill checks):") # print("1. decide the type of roll you want: i = _I_nitiative, c = skill _C_heck, t = saving _T_hrow, or a = _A_ttack roll") # print("2. followed by a = advantage, d = disadvantage, n = none") # print("3. add any modifiers at the end with a + or - followed by the value of your modifier.") # print("**check out these examples:**") # print(" id+3 means rolling initiative at disadvantage adding a +3 modifier") # print(" tn-1 means rolling a normal saving throw with a -1 modifier") # print(" ") # print("_._._._._._._._._._._._._._._._._._._._._._") # print(" ") # print("Custom Dice") # print(" ") # print("To roll a custom dice:") # print("1. Input your dice type (D4, D6, D8, D10, D12, D20, or custom)") # print("2. Input the number of dice you'd like to roll (ie. 1, 3, infinity and beyond") # print("3. Indicate what kind of modifier (if any) you are using and if you'd like it ") # print(" added to each dice roll or just once at the end of the calculation.") # print(".") # print(".") # print(".") # print(".") # print(".") # print(".") ## dice type -------------------------------------------------------------------------------------------- dice_type = input("Which would you like to use? Type e for 5e Rolls, c for Custom Dice, a number to roll a basic dice or n to end this script: ") dice_type = dice_type.lower() ## 5e Roller logic -------------------------------------------------------------------------------------------- if dice_type == "e": # print("_._._._._._._._._._._._._._._._._._._._._._") # print("5e Roller") # print(' ') # print("Type out your preferences using the following instructions:") # print("1. decide the type of roll you want: ") # print(" i = _I_nitiative, c = skill _C_heck, t = saving _T_hrow, or a = _A_ttack roll") # print("2. followed by a = advantage, d = disadvantage, or n = none") # print("3. add any modifiers at the end with a + or - followed by the value of your modifier.") # print("**check out these examples:**") # print(" id+3 means rolling initiative at disadvantage adding a +3 modifier") # print(" tn-1 means rolling a normal saving throw with a -1 modifier") try: formula = input("Enter your preferences here: ") print(' ') formula = formula.lower().strip() print(formula) output = list(formula) number1 = random.randint(1,20) onewithmod = number1 + int(output[3]) number2 = random.randint(1,20) twowithmod = number2 + int(output[3]) roll_types = {'i': 'initiative', 'c': 'skill check', 't': 'saving throw', 'a': 'attack roll'} adv_dis_num = {'a': max([onewithmod, twowithmod]), 'd': min([onewithmod, twowithmod])} adv_dis = {'a' : 'advantage', 'd' : 'disadvantage'} if output[1] == 'a' or output[1] == 'd': print(' ') print(f"{number1} {output[2]} {output[3]} = {onewithmod}") print(f"{number2} {output[2]} {output[3]} = {twowithmod}") print(' ') # new advantage/disadvantage logic print(f"Final results ({roll_types.get(output[0])}, {adv_dis.get(output[1])}): {adv_dis_num.get(output[1])}") print(' ') # old advantage/disadvantage logic # if output[1] == 'a': # print(' ') # print(f"Final results ({roll_types.get(output[0])}, advantage): {max([onewithmod, twowithmod])}") # print(' ') # elif output[1] == 'd': # print(' ') # print(f"Final results ({roll_types.get(output[0])}, disadvantage): {min([onewithmod, twowithmod])}") # print(' ') else: print(' ') print(f"Your roll result for {roll_types.get(output[0])}: {number1} {output[2]} {output[3]} = {onewithmod}") finally: run='n' ## FUTURE: Custom Dice -------------------------------------------------------------------------------------------- elif dice_type == "c": # print("_._._._._._._._._._._._._._._._._._._._._._") # print("Custom Dice") # print(" ") # print("To roll a custom dice:") # print("1. If more than one dice: Start with the number of dice you'd like to roll (1, 5, 100) followed by an 'x'") # print("2. Type the dice type you'd like to use (ie. 20 for D20, 10 for D10, 100 for D100)") # print("3. Include the modifier you are using (ie. +1, 0, -2). If you'd like it used just once at the end,") # print(" include a space between the dice type number and modifier number.") # print(' ') formula = input("Enter your custom roll here: ") print(' ') formula = formula.lower().strip() print(formula) output = list(formula) find_x = formula.find('x') # find_mod_type = formula.find(' ') find_mod_plus = formula.find('+') find_mod_minus = formula.find('-') ## stopped here: need to figure out way to pull dice face number from ALL inputs # dice_faces = mod_dict = {'+': output[find_mod_plus], '-': output[find_mod_minus]} #find function note: .find(value, start, end) if value doesn't exist in string, comes back -1 if '+' in formula or '-' in formula: print("this string contains a modifier") else: print("this string doesn't contain a modifier") run='n' elif dice_type == "n": run='n' elif dice_type.isdigit(): print(" ") print(f"Roll results: {random.randint(1,int(dice_type))}") print(" ") else: print("input not recognized") run='n'
854bb5826a378627b9041b230607e51da2905cd8
tberhanu/green_book
/ch2_LinkedLists/check_llist_palindrome.py
772
3.984375
4
# from LinkedList import LinkedList def check_llist_palindrome(llist): curr = llist runner = llist stack = [] #In python we use 'lists' as 'stacks' while runner and runner.next: stack.append(curr.data) curr = curr.next runner = runner.next.next if runner: curr = curr.next while curr: top = stack.pop() if top != curr.data: return False curr = curr.next return True class Node(): def __init__(self, data, next=None): self.data = data self.next = next ll1 = Node(1, Node(2, Node(3, Node(2, Node(1, None))))) print(check_llist_palindrome(ll1)) ll2 = Node(1, Node(2, Node(3, Node(3, Node(2, Node(1, None)))))) print(check_llist_palindrome(ll2)) ll3 = Node(1, Node(2, Node(3, Node(2, Node(2, Node(1, None)))))) print(check_llist_palindrome(ll3))
b1858530c96c0ff053d78237695ac3764ccc5362
tberhanu/green_book
/ch1_Arrays&Strings/check_permutation3_counter.py
690
3.859375
4
from collections import Counter def check_permutation3_counter(str1, str2): if len(str1) != len(str2): return False cntr1 = Counter(str1) #gives a dictionary of each CHAR:FREQUENCY cntr2 = Counter(str2) for key1 in cntr1: for key2 in cntr2: if key1 == key2 and cntr1[key1] != cntr2[key2]: return False elif key1 == key2 and cntr1[key1] == cntr2[key2]: break return True print(cntr1) print(cntr2) print(check_permutation3_counter("hello", "ohhhh")) print(check_permutation3_counter("strr", "rrst")) print(check_permutation3_counter("strra", "rarst")) print(check_permutation3_counter("strcra", "raxrst")) print(check_permutation3_counter("astrcra", "raxrste"))
4380cb3cb4bbdace75f27ff7059a0505e17687b7
ToxaRyd/WebCase-Python-course-
/7.py
1,757
4.3125
4
""" Данный класс создан для хранения персональной (смею предположить, корпоративной) информации. Ниже приведены doc тесты/примеры работы с классом. >>> Employee = Person('James', 'Holt', '19.09.1989', 'surgeon', '3', '5000', 'Germany', 'Berlin', 'male') >>> Employee.name James Holt >>> Employee.age 29 years old >>> Employee.work He is a surgeon >>> Employee.money 180 000 >>> Employee.home Lives in Berlin, Germany """ class Person: def __init__(self, first_name, last_name, birth_date, job, working_years, salary, country, city, gender='uknown'): self.__first_name = first_name self.__last_name = last_name self.__birth_date = birth_date self.__job = job self.__working_years = working_years self.__salary = salary self.__country = country self.__city = city self.__gender = gender @property def name(self): print(f'{self.__first_name} {self.__last_name}') @property def age(self): a = list(self.__birth_date.split('.')) b = 2018 - int(a[2]) print(f'{b} years old') @property def work(self): ci = {'male': 'He', 'female': 'She', 'uknown': 'He/She'} print('{0} is a {1}'.format(ci[self.__gender], self.__job)) @property def money(self): m = int(self.__working_years) * int(self.__salary) * 12 print('{0:,}'.format(m).replace(',', ' ')) @property def home(self): print(f'Lives in {self.__city}, {self.__country}') if __name__ == '__main__': import doctest doctest.testmod()
eb44d31501175cf09d4eac5bfc3ab2e8784168f9
jasonfhill/cronwatch
/app/utils.py
1,391
3.953125
4
import os import re import sys _filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]') PY2 = sys.version_info[0] == 2 if PY2: text_type = unicode else: text_type = str def secure_filename(filename): r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt' The function might return an empty filename. It's your responsibility to ensure that the filename is unique and that you generate random filename if the function returned an empty one. :param filename: the filename to secure """ if isinstance(filename, text_type): from unicodedata import normalize filename = normalize('NFKD', filename).encode('ascii', 'ignore') filename = filename.decode('ascii') for sep in os.path.sep, os.path.altsep: if sep: filename = filename.replace(sep, ' ') filename = str(_filename_ascii_strip_re.sub('', '_'.join( filename.split()))).strip('._') return filename
d5532a8bf440890fd844ee1f0cdd02f06ea4dc55
ckfChao/My-First-git-Repository
/main.py
451
3.953125
4
from op import op #input a = int(input("Enter value of a:")) input_op = input("Enter operater:") b = int(input("Enter value of b:")) calc = op(a, b) if (input_op == "+"): print("%d + %d = %d"%(a, b, calc.add())) elif (input_op == "-"): print("%d - %d = %d"%(a, b, calc.sub())) elif (input_op == "*"): print("%d * %d = %d"%(a, b, calc.mult())) elif (input_op == "/"): print("%d / %d = %d"%(a, b, calc.div())) else: print("Error")
9efdeb16d054511cf515531db3eb805fc690f4a5
logchi/scrach_zone
/python/data_structure_algorithms/breath_first_serach.py
1,055
3.78125
4
from collections import deque def search_queue(graph, dq, right, searched=[]): def addnextlevel(dq, node): next_level = graph.get(node) if next_level: dq += next_level if dq: node = dq.popleft() if node in searched: return search_queue(graph, dq, right, searched) else: if right(node): print("This is the appropriate node:", node) return True else: searched.append(node) addnextlevel(dq, node) return search_queue(graph, dq, right, searched) else: print("We can't find the appropriate node") return False def breath_first_search_demo(): def right(node): return node[-1] == 'm' graph = {} graph["you"] = ["alice", "bob", "claire"] graph["bob"] = ["anuj", "peggy"] graph["alice"] = ["peggy"] graph["claire"] = ["thom", "jonny"] dq = deque(['you']) print(search_queue(graph, dq, right)) breath_first_search_demo()
0147ba4f123a05170e4ed99fea9f2741974301e4
akashzcoder/coding_discipline
/CoderPro/day3/solution.py
413
3.53125
4
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: return self._permute_helper(nums, []) def _permute_helper(self, nums: list, values: list = []) -> list: if len(nums) == 0: return [values] result = [] for i in range(len(nums)): result += self._permute_helper(nums[:i] + nums[i + 1:], values + [nums[i]]) return result
4fe543b01436500dd6ca7b3d2ff27746fc2508a5
Wibbo/voting
/main.py
240
3.515625
4
from election import election choices = ['Salad', 'Burger', 'Pizza', 'Curry', 'Pasta', 'BLT'] campaign = election(300, choices) print('NEW ELECTION') print(f'Number of voters is {campaign.voter_count}') print(campaign.vote_counts)
9ae6c4d2f37119e7f90db29b3db050b40d5dff8b
nnicexplsz/python
/Work/test4.py
606
3.578125
4
a = input('enter number 1 \n') b = input('enter number 2 \n') c = input('enter number 3 \n') d = input('enter number 4 \n') c = input('enter number 5 \n') a1 = float(a) a2 = complex(a) a3 = float(b) a4 = complex(b) a5 = float(c) a6 = complex(c) a7 = float(d) a8 = complex(d) a9 = float(c) a10 = complex(c) print('float of 1 = %.1f'%a1) print('complex of 1 = %s'%a2) print('float of 2 = %.1f'%a3) print('complex of 2 = %s'%a4) print('float of 3 = %.1f'%a5) print('complex of 3 = %s'%a6) print('float of 4 = %.1f'%a7) print('complex of 4 = %s'%a8) print('float of 5 = %.1f'%a9) print('complex of 5 = %s'%a10)
fcedb2e85cb1283c77421a2f9aed8fd1b77af591
nnicexplsz/python
/Work/4_2.py
2,336
3.8125
4
t = 5 vocadulary = { "rose apple":" n.คำนาม ชมพู่ ", "keyboard":" n.คำนาม คีย์บอร์ด", "drink":" v.คำกริยา ดื่ม ", "speak":" v.คำกริยา พูด", "These":" adj.ขยายคำนาม พวกนี้", } while(True): print("พจนานุกรม\n 1)เพิ่มคำศัพท์\n 2)แสดงคำศัพท์\n 3)ลบคำศัพท์\n 4)ออกจากโปรแกรม\n") data = int(input("Input Choice :")) if data == 1 : t += 1 terminology = input("เพิ่มคำศัพท์\t:") work_type = input("ชนิดของคำ (ชนิดของคำ(n.,v.,adj.,adv.) :") if work_type == "n.": work_type = "n.คำนาม" elif work_type == "v." : work_type = "v.คำกริยา" elif work_type == "adj." : work_type = "adj.ขยายคำนาม" elif work_type == "adv." : work_type = "adv.กริยาวิเศษณ์" meaning = input("ความหมาย\t :") vocadulary[terminology] = " "+work_type+" "+meaning print("เพิ่มคำศัพท์เรียบร้อยแล้ว") elif data == 2 : print(15*"-"+"\n คำศัพท์มีทั้งหมด ",t," คำ\n",15*"-") print("คำศัพท์ ประเภท ความหมาย") for i in vocadulary : print (i+vocadulary[i]) elif data == 3: delete = input("พิมพ์คำศัพท์ที่ต้องการลบ :") x = input("ต้องการลบ"+delete+"ใช่หรือไม่ (yes / no):") if x == "yes": vocadulary.pop(delete) t -= 1 print("ลบ"+delete+"เรียบร้อยแล้ว") else: yes = input("ต้องการออกจากโปรแกรมใช่หรือไม่ (yes / no):") if yes == "yes": print("ออกจากโปรแกรมเรียบร้อยแล้ว") break
f46ef7a473eaa019a376c7312864168d63e06ef5
nnicexplsz/python
/week3/week3_2.py
896
3.703125
4
value = int(input("กรุณากรอกจำนวนครั้งการรับค่า")) # แบบฝึกหัด 3.2 i = 1 a = 0 while(i <= value) : number = int(input("กรอกตัวเลข :")) i=i+1 a=a+number print("ผลรวมที่รับค่ามาทั้งหมด = %d"%a) print("ป้อนชื่ออาหารโปรดของคุณ หรือ exit เพื่อออกจากโปรแกรม") foodlist[] i = 0 while(True): i = i +1 print("อาหารโปรดลำดับที่",i,end="") choose = input("คือ\t") foodlost.append(choose) if choose == "exit" : break print("รายการอาหารสุพดโปรดของคุณ มีดังนี้",end="") for z in range(1,i) : print(i,".",foodlist[z-1],end=" ")
b3f0da91062c2cef4b18f75077bacb5b9b555d02
JFincher42/RandomStuff
/sairam-test.py
493
3.53125
4
import pygame pygame.init() window = pygame.display.set_mode([500,500]) x_speed = 7 y_speed = 3 b_x = 15 b_y = 15 frames = 0 while frames < 750: frames += 1 b_x += x_speed b_y += y_speed if b_x >= 485: b_x = 15 elif b_x <= 15: b_x = 485 if b_y >= 485: b_y = 15 elif b_y <= 15: b_y = 485 window.fill((255,255,255)) pygame.draw.circle(window, (255,0,0), (b_x, b_y), 15) pygame.display.flip() pygame.time.wait(10)
e66d6267baedca2ed407055dec553fc524811e0c
abhinavgairola/PowerSimData
/powersimdata/utility/helpers.py
3,071
3.59375
4
import copy import importlib import os import sys class MemoryCache: """Wrapper around a dict object that exposes a cache interface. Users should create a separate instance for each distinct use case. """ def __init__(self): """Constructor""" self._cache = {} def put(self, key, obj): """Add or set the value for the given key. :param tuple key: a tuple used to lookup the cached value :param Any obj: the object to cache """ self._cache[key] = copy.deepcopy(obj) def get(self, key): """Retrieve the value associated with key if it exists. :param tuple key: the cache key :return: (*Any* or *NoneType*) -- the cached value if found, or None """ if key in self._cache.keys(): return copy.deepcopy(self._cache[key]) def list_keys(self): """Return and print the current cache keys. :return: (*list*) -- the list of cache keys """ keys = list(self._cache.keys()) print(keys) return keys def cache_key(*args): """Creates a cache key from the given args. The user should ensure that the range of inputs will not result in key collisions. :param args: variable length argument list :return: (*tuple*) -- a tuple containing the input in heirarchical structure """ kb = CacheKeyBuilder(*args) return kb.build() class CacheKeyBuilder: """Helper class to generate cache keys :param args: variable length arguments from which to build a key """ def __init__(self, *args): """Constructor""" self.args = args def build(self): """Combine args into a tuple, preserving the structure of each element. :return: (*tuple*) -- container which can be used as a cache key """ return self._build(self.args) def _build(self, arg): if arg is None: return "null" if isinstance(arg, (str, int, bool)): return arg if isinstance(arg, (list, set, tuple)): return tuple(self._build(a) for a in arg) raise ValueError(f"unsupported type for cache key = {type(arg)}") class PrintManager: """Manages print messages.""" def __init__(self): """Constructor""" self.stdout = sys.stdout def __enter__(self): self.block_print() def __exit__(self, exc_type, exc_value, traceback): self.enable_print() @staticmethod def block_print(): """Suppresses print""" sys.stdout = open(os.devnull, "w") def enable_print(self): """Enables print""" sys.stdout = self.stdout def _check_import(package_name): """Import a package, or give a useful error message if it's not there.""" try: return importlib.import_module(package_name) except ImportError: err_msg = ( f"{package_name} is not installed. " "It may be an optional powersimdata requirement." ) raise ImportError(err_msg)
68f964fde72113fea68ff42de7cb33db2e7f4e86
abhinavgairola/PowerSimData
/powersimdata/utility/distance.py
2,790
3.703125
4
from math import acos, asin, cos, degrees, radians, sin, sqrt def haversine(point1, point2): """Given two lat/long pairs, return distance in miles. :param tuple point1: first point, (lat, long) in degrees. :param tuple point2: second point, (lat, long) in degrees. :return: (*float*) -- distance in miles. """ _AVG_EARTH_RADIUS_MILES = 3958.7613 # noqa: N806 # unpack latitude/longitude lat1, lng1 = point1 lat2, lng2 = point2 # convert all latitudes/longitudes from decimal degrees to radians lat1, lng1, lat2, lng2 = map(radians, (lat1, lng1, lat2, lng2)) # calculate haversine lat = lat2 - lat1 lng = lng2 - lng1 d = ( 2 * _AVG_EARTH_RADIUS_MILES * asin(sqrt(sin(lat * 0.5) ** 2 + cos(lat1) * cos(lat2) * sin(lng * 0.5) ** 2)) ) return d def great_circle_distance(x): """Calculates distance between two sites. :param pandas.dataFrame x: start and end point coordinates of branches. :return: (*float*) -- length of branch (in km.). """ mi_to_km = 1.60934 return haversine((x.from_lat, x.from_lon), (x.to_lat, x.to_lon)) * mi_to_km def ll2uv(lon, lat): """Convert (longitude, latitude) to unit vector. :param float lon: longitude of the site (in deg.) measured eastward from Greenwich, UK. :param float lat: latitude of the site (in deg.). Equator is the zero point. :return: (*list*) -- 3-components (x,y,z) unit vector. """ cos_lat = cos(radians(lat)) sin_lat = sin(radians(lat)) cos_lon = cos(radians(lon)) sin_lon = sin(radians(lon)) uv = [cos_lat * cos_lon, cos_lat * sin_lon, sin_lat] return uv def angular_distance(uv1, uv2): """Calculate the angular distance between two vectors. :param list uv1: 3-components vector as returned by :func:`ll2uv`. :param list uv2: 3-components vector as returned by :func:`ll2uv`. :return: (*float*) -- angle (in degrees). """ cos_angle = uv1[0] * uv2[0] + uv1[1] * uv2[1] + uv1[2] * uv2[2] if cos_angle >= 1: cos_angle = 1 if cos_angle <= -1: cos_angle = -1 angle = degrees(acos(cos_angle)) return angle def find_closest_neighbor(point, neighbors): """Locates the closest neighbor. :param tuple point: (lon, lat) in degrees. :param list neighbors: each element of the list are the (lon, lat) of potential neighbor. :return: (*int*) -- id of the closest neighbor """ uv_point = ll2uv(point[0], point[1]) id_neighbor = None angle_min = float("inf") for i, n in enumerate(neighbors): angle = angular_distance(uv_point, ll2uv(n[0], n[1])) if angle < angle_min: id_neighbor = i angle_min = angle return id_neighbor
c210c723687f3b80583ad336bcdbc0b9f737af0d
mytbk/xgboost-learning
/convert_data.py
895
3.5625
4
#!/usr/bin/env python2 import pandas import sys from types import * def getDataFromCSV(csv): table = pandas.read_csv(csv) column_names = table.columns working = pandas.DataFrame() for col in column_names: print(col) if type(table[col][0]) is not StringType: working = pandas.concat([working, table[col]], axis=1) else: dummy = pandas.get_dummies(table[col], prefix=col) working = pandas.concat([working, dummy], axis=1) return working if __name__ == '__main__': working = getDataFromCSV(sys.argv[1]) fo = open(sys.argv[2], 'w') for row in working.values: fo.write('%d' % row[1]) data = row[2:] for i in range(0,len(data)): if data[i] != 0: fo.write(' %d:%d' % (i+1, data[i])) fo.write('\n') fo.close()
308f36d76762dfc539ff391c11c3464963ac7e4c
mattbaumann1/contractors
/main.py
1,173
3.96875
4
#!/usr/bin/python3 # main.py authored by Matt Baumann for COMP 412 Loyola University #The following video was very helpful for this assignment: https://www.youtube.com/watch?v=mlt7MrwU4hY import csv #Creation of list objects. contractorList = [] lobbyistList = [] #Reading in the contractorList with contracts for the city cr = open('contractors.csv') csvCR = csv.reader(cr) #contractorList name is element 1 or the second element for i in csvCR: contractorList.append(i[1]) cr.close() #Reading in the lobbbyist's clients lr = open('lobbyist.csv') csvLR = csv.reader(lr) #lobbyist's client's names are element 0 for i in csvLR: lobbyistList.append(i[0]) lr.close() #Comparison of the two sets #print(len(contractorList)) #print command to check how many contractors were appended to the list. #print(len(lobbyistList)) #print command to check how many lobbyists were appended to the list. contractorSet = set(contractorList) lobbyistSet = set(lobbyistList) print('The following names are contractors that have contracts with the city and are clients of registered lobbyists.') for i in contractorSet.intersection(lobbyistSet): print(i)
f7269f85dbc1ec9a43880f49efa09b193e080aee
bopopescu/PycharmProjects
/shashi/7) Mebership & indentity operators.py
1,117
4.0625
4
# Membership Operators 15/05/2018 #a = '1' #if (a === 1): # print(a) #if(a == '1'): # print(a) '''l1 = [1,2,3,4] if 1 in l1: print(1 in l1) d1 = {'a': 1 , 'b': 2} print('a' in d1) print('aa' in d1) print('a' not in d1) print('aa' not in d1)''' # Indentity operators '''a = 1 print(a is 1) print(a is not 1) print(a is not 1) print(a is not 11)''' # reverse a string '''a = 'abc' print(a[::-1]) print(a[ :-1]) b = 'def' print(b[ ::2])''' '''a = 101 # Decision making # if loop if a == 10: print("a: {0}".format(a)) # if else loop if a == 10: print("a: {0}".format(a)) else: print("else block")''' # nested if '''a = 12 if a == 10: print("a: {0}".format(a)) elif a == 11: print("a: {0}".format(a)) elif a == 12: print("a: {0}".format(a)) else: print("else block")''' # Nested if statement '''a = 10 b = 11 c = 12 if a == 10: if b == 11: if c == 12: print("done") else: print("failed at C check point") else: print("failed at B check point") else: print("failed at A check point")'''
347460f3edf3af4e5601a45b287d1a086e1a3bc3
bopopescu/PycharmProjects
/Class_topic/7) single_inheritance_ex2.py
1,601
4.53125
5
# Using Super in Child class we can alter Parent class attributes like Pincode # super is like update version of parent class in child class '''class UserProfile(Profile): # Child Class def __init__(self,name,email,address,pincode): # constructor of child Class super(UserProfile, self).__init__(name,email,address) # parent containing three attributes self.pincode = pincode''' class Profile: # Parent Class def __init__(self, name, email, address): # constructor of parent class self.name = name self.email = email self.address = address def displayProfile(self): # display method in parent class return "Name:{0}\nEmail:{1}\nAddress:{2}".format( self.name, self.email, self.address ) class UserProfile(Profile): # Child Class def __init__(self,name,email,address,pincode): # constructor of child class super(UserProfile, self).__init__(name,email,address) # parent containing three attributes self.pincode = pincode def setCity(self, city): # setCity method of child lass self.city = city def displayProfile(self): # display method in child class return "Name:{0}\nEmail:{1}\nAddress:{2}\nCity:{3}\nPincode:{4}".format( self.name, self.email, self.address, self.city, self.pincode ) user = UserProfile("Raju","raju@gmail.com","BTM","580045") # object of child class user.setCity("Bangalore") # adding attribute value to child class temp = user.displayProfile() print(temp)
55f9eb36b8d77e7adfa28e1d27a5922dfddf1206
bopopescu/PycharmProjects
/shashi/17) ExceptionHandling_try& _except.py
840
4
4
'''try: int("sds") print(name) name = "aaaa" open('dddddd') import asdfg print("went good...") except (NameError, ValueError, ImportError): print("something went Wrong") except NameError: print("NameError") #except: except ValueError: print("exception") except ImportError: print("Importerror") finally: print("i am always here.....")''' # try example '''try: num = input("number?") num = int(num) if num < 0: raise ValueError except (NameError, ImportError): print("something went wrong") except ValueError: print("Number can't be negative") finally: print("i am always here")''' # to enter a no ''' while True: try: i = int(input("please enter a no")) break except ValueError: print("please enter a correct no ") '''
2329f20248f4ab62b23828caae234b23dad10ab8
bopopescu/PycharmProjects
/shashi/14) import_3_methods & packages .py
552
3.515625
4
# import 3 methods # 1) import PackageName '''import test print(test.email) test.name()''' # 2) from PackageName import VarName ,functions ,Classes '''from test import name,email name() print((email))''' # 3) from PackageName import * '''from test import * name() print(email)''' # 4) from PackageName import VarName as NewVarNme, ClassName as NewClassName, functionName as NewfunctionName '''from test import name as newName,email as newEmail email = "rahul@gmail.com" def name(): print("rahul") newName() name() print(email) print(newEmail)'''
6a6b1394a960ba09ff2c97fa71e61b78a1c45858
bopopescu/PycharmProjects
/shashi/10) functions_1( lambda) .py
1,902
4.25
4
#Nested function '''def func1(): def func2(): return "hello" return func2 data = func1() print(data())''' #global function '''a = 100 def test(): global a # ti use a value in function a = a + 1 print(a) #print(a) test()''' '''a = 100 def test(): global a # ti use a value in function b = 100 a = a + 1 print(a) #print(a) test() print(b)''' # doc string / documentation function '''def add(a,b): # """ enter then the it will execute :param a: # :par b: # :return:am """ :param a: :par b: :return:am """ return a + b print(add.__doc__) add(1,2)''' # default parameter intialization '''def add(a,b = 100): return a + b temp = add(1) print(temp)''' # closure function '''def func1(a): def func2(b): return "iam function2" def func3(c): return "i am from func3" return [func2,func3] data = func1(11) #print(data[0]) #print(data[1]) print(data[0](11)) print(data[1](11))''' '''def test(a,b): if a > b: return" ai s largest" else: return "b is largest" large = test(10,20) print(large) print("============")''' #lamda - terinary expression : True if condition False #lambda p1,p2,pn:expression #exp ? value1 : value2 # to find largest to two no's using lambda function '''data = lambda a,b: 'a is largest' if a > b else "b is largest" #print(data) #print(data()) # error statement print(data(200,300))''' # to find largest to three no's using lambda function '''data = lambda a,b,c: a if a > b and a > c else b if b > c else c #print(data) #print(data()) # error statement print(data(2000,3000,500))''' # to find largest to four no's using lambda function data = lambda a,b,c,d: a if a > b and a > c and a > d else b if b > c and b > d else c if c > d else d #print(data) #print(data()) # error statement print(data(200,700,9000,6))
ee3776a9a10899adb7ca4e6979145114c979dabf
bopopescu/PycharmProjects
/Class_topic/class_assigment.py
351
3.75
4
'''class A: def __init__(self,file): self.file = open("Demo") data = self.file.read() print(data) def f1(self,f): m = input("enter a string") self.f = open("demo")as w: self.f = m.writeable() def __del__(self): print("i am here") a = A("file2") temp = a.f1("h") print(temp)'''
2001b07997daf96893b9885f14bff85c97f59d2d
danniekot/programming
/Practice/21/Python/21.py
281
3.875
4
def BMI(weight: float, height: float): return weight/(height*height/10000) def printBMI(bmi: float): if BMI < 18.5 print('Underweight') elif BMI < 25 print('Normal') elif BMI < 30 print('Overweight') else print('Obesity') w,h=map(float,input().split()) printBMI(BMI(w,h))
1f6a9e033c3a3b8c5c278cb4a96d5900ef8a994e
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/optional-labs/roadtrip/roadtrip-v1.py
1,130
4.15625
4
city_dict = { 'Boston': {'New York', 'Albany', 'Portland'}, 'New York': {'Boston', 'Albany', 'Philadelphia'}, 'Albany': {'Boston', 'New York', 'Portland'}, 'Portland': {'Boston', 'Albany'}, 'Philadelphia': {'New York'} } city_dict2 = { 'Boston': {'New York': 4, 'Albany': 6, 'Portland': 3}, 'New York': {'Boston': 4, 'Albany': 5, 'Philadelphia': 9}, 'Albany': {'Boston': 6, 'New York': 5, 'Portland': 7}, 'Portland': {'Boston': 3, 'Albany': 7}, 'Philadelphia': {'New York': 9}, } class Trip(): def __init__(self, starting_city, hops=1, city_dict=city_dict, city_dict2=city_dict2): self.starting_city = starting_city self.hops = hops self.city_dict = city_dict self.city_dict2 = city_dict2 def show_cities(self): one_hop_set = self.city_dict[self.starting_city] one_hop_list = [city for city in one_hop_set] two_hops = [self.city_dict[city] for city in one_hop_list] print(f"one hop: {one_hop_set}") print(f"two hops: {two_hops}") start_city = input("Starting city: ") this_trip = Trip(start_city) this_trip.show_cities()
0f6a5f4930f4a7ef9ce28e4fe790d79b1e77561b
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/lab15/lab15-number-to-phrase-v2.py
1,819
3.984375
4
''' lab15-number-to-phrase-v2 Version2: Handle numbers from 100-999 ''' print("Welcome to Number to Phrase v2.0. We'll convert your number between 0-999 to easily readable letters.") while True: n = int(input("Please enter an integer between 0 and 999: ")) if n not in range(0, 1000): print("Please enter an acceptable number.") continue else: break x = n // 100 #hundreds_digit y = n % 100 // 10 #tens_digit z = n % 10 #ones_digit tn = n % 100 #teen exception finder x2a = {# this is the dictionary to convert 100s to hundreds 9: 'nine-hundred', 8: 'eight-hundred', 7: 'seven-hundred', 6: 'six-hundred', 5: 'five-hundred', 4: 'four-hundred', 3: 'three-hundred', 2: 'two-hundred', 1: 'one-hundred', 0: '', } y2b = {# this is the dictionary to convert 10s to tens 9: 'ninety-', 8: 'eighty-', 7: 'seventy-', 6: 'sixty-', 5: 'fifty-', 4: 'forty-', 3: 'thirty-', 2: 'twenty-', 1: 'ten', 0: '', } z2c = {# this is the dictionary to convert 1s to ones 9: 'nine', 8: 'eight', 7: 'seven', 6: 'six', 5: 'five', 4: 'four', 3: 'three', 2: 'two', 1: 'one', 0: '', } a = x2a[x] b = y2b[y] if n % 10 == 0:#this if statement gets rid of unecessary hyphens b = b.strip('-') c = z2c[z] l = a + ' ' + b + c if 20 > tn > 10:#this addresses the teen exceptions if tn == 19: bc = 'nineteen' if tn == 18: bc = 'eighteen' if tn == 17: bc = 'seventeen' if tn == 16: bc = 'sixteen' if tn == 15: bc = 'fifteen' if tn == 14: bc = 'fourteen' if tn == 13: bc = 'thirteen' if tn == 12: bc = 'twelve' if tn == 11: bc = 'eleven' l = a + ' ' + bc print(f"{n} is {l}.")
7c693a0fe73b2fe3cbeeddf1551bf3d2f0250ab2
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/lab12/lab12-guess_the_number-v3.py
694
4.34375
4
''' lab12-guess_the_number-v3.py Guess a random number between 1 and 10. V3 Tell the user whether their guess is above ('too high!') or below ('too low!') the target value.''' import random x = random.randint(1, 10) guess = int(input("Welcome to Guess the Number v3. The computer is thinking of a number between 1 and 10.\nEnter your guess: ")) count = 0 while True: count = count + 1 if guess == x: print(f"Congrats. You guessed the computer's number and it only took you {count} times!") break else: if guess > x: guess = int(input("Too high... Try again: ")) if guess < x: guess = int(input("Too low... Try again: "))
ffa71514a68193fcebd2c4939dfeaa28529d5f75
pjz987/2019-10-28-fullstack-night
/Assignments/dj/lab10-v1.py
390
4.09375
4
""" Name: DJ Thomas Lab: 11 version 1 Filename: lab10-v1.py Date: 10-31-2019 Lab covers the following: - input() - float() - for/in loop - fstring - range """ num = int(input("how many numbers?: ")) total_sum = 0 for i in range(num): numbers = float(input('Enter number: ')) total_sum += numbers avg = total_sum/num print(f"Average of {num} numbers is {avg}")
f4da5503cbbf47772f9bcccdbfc7487c6efdc13f
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab14-gambling_pick6v2.py
2,237
4.09375
4
''' lab14-pick6-v1.py v2 The ROI (return on investment) is defined as (earnings - expenses)/expenses. Calculate your ROI, print it out along with your earnings and expenses. ''' #1.Generate a list of 6 random numbers representing the winning tickets...so define a pick6() function here. import random def pick6(): ticket = [] count = 0 while count != 6: ticket.append(random.randint(0, 100)) count = count + 1 return ticket #I HAD to do this to make ANYTHING work winning_ticket = pick6() print(f"Welcome to pick6. The winning ticket is:{winning_ticket}.") #2. Start your balance at 0. balance = 0 earnings = 0 expenses = 0 #3. Loop 100,000 times, for each loop: count = 0 while count != 100000: #4. Generate a list of 6 random numbers representing the ticket ticket = pick6() #5. Subtract 2 from your balance (you bought a ticket) balance = balance - 2 expenses = expenses + 2 #6. Find how many numbers match match = 0 if ticket[0] == winning_ticket[0]: match = match + 1 if ticket[1] == winning_ticket[1]: match = match + 1 if ticket[2] == winning_ticket[2]: match = match + 1 if ticket[3] == winning_ticket[3]: match = match + 1 if ticket[4] == winning_ticket[4]: match = match + 1 if ticket[5] == winning_ticket[5]: match = match + 1 #7. Add to your balance the winnings from your matches if match == 1: balance = balance + 4 earnings = earnings + 4 if match == 2: balance = balance + 7 earnings = earnings + 7 if match == 3: balance = balance + 100 earnings = earnings + 100 if match == 4: balance = balance + 50000 earnings = earnings + 50000 if match == 5: balance = balance + 1000000 earnings = earnings + 1000000 if match == 6: balance = balance + 25000000 earnings = earnings + 25000000 count = count + 1 #8. After the loop, print the final balance print(f"Your current ${balance}...you lost") roi = round((earnings - expenses) / earnings) * 0.01 print(f"Your earnings were ${earnings} but your expenses were ${expenses} so your ROI (return on investment) is {roi}%... Not great. ")
82ef1519965203526bf480fc9b989e73fb955f54
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab17-palidrome_anagramv2.py
312
4.5625
5
# Python Program to Check a Given String is Palindrome or Not string = input("Please enter enter a word : ") str1 = "" for i in string: str1 = i + str1 print("Your word backwards is : ", str1) if(string == str1): print("This is a Palindrome String") else: print("This is Not a Palindrome String")