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
4f27f9b1d4c1ad564a1128ddd8cca84a12e7314e
NehaRapolu3/python-tasks
/task 5.py
252
4
4
r=input("enter the month") a=("January","March","May","July","August","October","December") b=("February") if r in a: print("The month has 31 days ") elif r in b: print("The month has 28 days") else: print("The month has 30 days")
f08f53149b0aeef0f9f9542b113d19a0630be066
Kristijan10048/PythonTutorials
/IronPython/t1/t1/t1.py
285
3.59375
4
#function with default arguments def defaultArgs(test = "abrakadabra"): print(test); #function to calculate sum def sum(a, b): return a + b; #prints hello world print('Hello World'); #function call c = sum(4, 5); print(c); #call function wiht defaults args defaultArgs();
ba95e341a9625b89e624dd9a00714c552f14075a
kobesxl/ud120-ML
/svm/svm_author_id.py
1,593
3.59375
4
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys import numpy as np from time import time sys.path.append("../tools/") from email_preprocess import preprocess from sklearn.svm import SVC from sklearn.metrics import accuracy_score ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() features_train = features_train[:len(features_train)/100] labels_train = labels_train[:len(labels_train)/100] def SVM_classification(features_train, features_test, labels_train, labels_test): model = SVC(kernel='rbf',C=10000) # t0 = time() model.fit(features_train, labels_train) # print "training time:", round(time() - t0, 3), "s" # t1 = time() predict = model.predict(features_test) print type(predict) print predict.shape print predict.dtype # print "testing time:", round(time() - t1, 3), "s" # l = [10,26,50] # print predict[l] print sum(predict) acc = accuracy_score(labels_test, predict,normalize=False) return acc acc = SVM_classification(features_train, features_test, labels_train, labels_test) print acc ######################################################### ### your code goes here ### #########################################################
17996e5adf4dd50daac386d7dd533adbebe3f523
pengshuai2010/hello_python
/hello_python/test/fibonacci.py
860
3.828125
4
''' Created on Jul 28, 2015 @author: speng ''' class Fibonacci: ''' generator class of fibonacci sequence ''' def __init__(self, max_value): self.max_value = max_value def __iter__(self): ''' The __iter__() method is called whenever someone calls iter(Fibonacci). ''' self.a = 0 self.b = 1 return self def next(self): ''' the next() method of an iterator class note that in python 3, this should be __next__() The __next__() method is called whenever someone calls next() on an iterator of an instance of a class. ''' self.a, self.b = self.b, self.a + self.b if self.a > self.max_value: raise StopIteration return self.a if __name__ == '__main__': for f in Fibonacci(30): print f
98dba43b224cf4d4da94fb259d754cecd1eac732
asiskc/python_assignment_dec8
/function.py
176
4.21875
4
def odd_even(n): if n % 2 == 0: print ("It is an even number") else: print ("It is an odd number") odd_even(int(input("enter a number")))
94e971d062803bda0dbee06307607932b0654849
zongrh/untitled_python
/test02.py
1,008
4.15625
4
# coding=utf-8 print("hello world") print "你好,世界!"; counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "john" # 字符串 print counter print miles print name # -----------------------------标准数据类型 # Numbers(数字) # String(字符串) # List(列表) # Tuple(元组) # Dictionary(字典) # -------------------------------Python数字 var1 = 1 var2 = 10 print var1 print var2 del var1 del var2 print("--------------") # ------------------------------Python字符串 str = "hello world" print str # 输出完整字符串 print str[0] # 输出字符串中的第一个字符 print str[5] # 输出字符串中的第五个字符(null) print str[2:5] # 输出字符串中的第三个至第五个之间的字符串 print str[2:] # 输出第三字符开始的字符串 print str * 2 # 输出字符串两次 print str + "TEST" # 输出链接的字符串 print("-------------") # --------------------------------------------------
0dddda651dbe0d301732ff821e905025d858d104
zongrh/untitled_python
/py1_variable/Python_Dictionary.py
723
3.96875
4
# coding=utf-8 # 字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象集合,字典是无序的对象集合。 # 两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。 # 字典用"{ }"标识。字典由索引(key)和它对应的值value组成。 dict = {} dict["one"] = "this is one" dict[2] = "this is two" tinydict = {"name": "jhon", "code": 222, "dept": 62L, "msg": "非法参数异常"} print dict["one"] # 输出键值为"one"的值 print dict[2] # 输出键值为 2 的值 print tinydict # 输出完整的字典 print tinydict.keys() # 输出所有键 print tinydict.values() # 输出所有的值
a23774f21cc699e1c272105014f54ba9dabee81a
wj84234/Python_Winter_2019_1
/ShapesAbstract.py
1,111
4.03125
4
import math from abc import ABC, abstractmethod class Shape(ABC): def __init__(self, a=10, b=20): self.set_params(a, b) def set_params(self, a, b): self._a = a self._b = b def get_a(self): return self._a def get_b(self): return self._b def __str__(self): return "{0}: [{1},{2}]".format(self.__class__.__name__, self._a, self._b) @abstractmethod def calc_surface(self): pass class Rectangle(Shape): def calc_surface(self): return self._a*self._b #return self.get_a()*self.get_b() class Circle(Shape): def __init__(self, a): #self.set_params(a, 0) super().__init__(a, 0) def calc_surface(self): return math.pi*self._a**2 def __str__(self): return "{0}: [{1}]".format(self.__class__.__name__, self._a) class Square(Rectangle): def __init__(self, a): super().__init__(a, a) s = Rectangle(4, 5) #s = Shape(4, 5) print(s) print(s.calc_surface()) c = Circle(5) print(c) print(c.calc_surface()) sq = Square(4) print(sq) print(sq.calc_surface())
7dee377d325fd5ea80bb7c096851f1ad343f7495
ghgithub/river-flow
/src/run_scripts/flood_graph.py
1,556
3.90625
4
import pickle from queue import PriorityQueue graph = pickle.load(open('graph.pkl', 'rb')) def flood(point): points_in_lake = generate_lake(point) # TODO Merge the list of points in the lake into one point def generate_lake(point): # Store points which are part of the lake in a list lake = [] # Store points which are yet to be visited in a priority queue (which represents the border of the lake) border = PriorityQueue() border.put(point) # Store the altitude of the lake lake_altitude = point.altitude # Should not need this while condition but whatever while not border.empty(): item = border.get() # Exit if this point is the outflow point for the lake if item.altitude >= lake_altitude: # Update lake altitude lake_altitude = item.altitude # Include this point in the lake lake.append(item) # Add all this points neighbours to the lake border for neighbour in item.inflow: border.put(neighbour) else: break # TODO will border contain any points which are the same height as the lake? # This is possible and they should be added to the lake. return (item, lake) # 1. Start by creating inflow list for each node for i in graph.descending(): i.inflow = [] for i in graph.descending(): for j in i.outflow: j.inflow.append(i) # 2. Find points with no outflow for i in graph.descending(): if len(i.outflow) == 0: flood(i)
79240a2127ba8262a1a2d25775e2034a717ef668
cMinzel-Z/Web-crawler
/Getting_start/spider_practice/spider_start/reg_test.py
693
3.609375
4
# -*- coding: utf-8 -*- import re # \d{4} 1999-8-1 # b{2,4} # (o|c)b "bobby" "ccbbc" # \d{4}(y|-) "1999y8m1d" 1998-8-1 info = "name:bobby dob:1987-10-1 ug:2005-9-1" # 提取字符串 #print(re.findall("\d{4}", info)) # match方法是从字符串的最开始进行匹配 match_res = re.match(".*dob.*?(\d{4})", info) #print(match_res.group(1)) # 替换字符串 result = re.sub("\d{4}", "2019", info) #print(info) #print(result) # 搜索字符串 search_res = re.search("dob.*?(\d{4})", info) #print(search_res) #name = "my name is Bobby" #print(re.search("bobby", name, re.IGNORECASE).group()) name = """ my name is bobby """ print(re.match(".*bobby", name, re.DOTALL).group())
c7f21b8ae4ad7454fadf11d8d0bf2c8e5ceaf318
Leahxuliu/Data-Structure-And-Algorithm
/Python/每周竞赛/1418. Display Table of Food Orders in a Restaurant.py
819
3.578125
4
class Solution: def displayTable(self, orders: List[List[str]]) -> List[List[str]]: info = {} all_dish = set() for each_order in orders: table = each_order[1] order = each_order[2] all_dish.add(order) if table in info: info[table].append(order) else: info[table] = [order] all_dish = sorted(list(all_dish)) res = [] res.append(['Table'] + all_dish) info2 = sorted(info.items(), key = lambda x:int(x[0])) for each in info2: each_res = [each[0]] for food in all_dish: count = each[1].count(food) each_res.append(str(count)) res.append(each_res) return res
263d53a7e4b5bf94b4f777e586cef3de4b64021f
Leahxuliu/Data-Structure-And-Algorithm
/Python/Graph/practice.py
2,365
3.59375
4
from collections import deque, defaultdict class Graph: def DFS_Traversal(self, nums, pairs): def dfs(node): if visited[node] == 1: return preorder.append(node) visited[node] = 1 for out in adjacent[node]: dfs(out) postorder.append(node) return if nums == 0 or pairs == []: return visited = [0] * nums adjacent = [[] for _ in range(nums)] for i, j in pairs: adjacent[i].append(j) adjacent[j].append(i) preorder = [] postorder = [] for i in range(nums): if visited[i] == 0: dfs(i) print(preorder) print(postorder) return def BFS_Traversal(self, nums, pairs): # corner case if nums == 0 or pairs == []: return visited = [0] * nums adjacent = [[] for _ in range(nums)] for i, j in pairs: adjacent[i].append(j) adjacent[j].append(i) order = [] queue = deque() for i in range(nums): if visited[i] == 0: queue.append(i) visited[i] = 1 # 切记,append之后立刻visited变成1 while queue: node = queue.popleft() order.append(node) for out in adjacent[node]: if visited[out] == 0: queue.append(out) visited[out] = 1 print(order) return def Prim_findMST(self, n, edges): adj = defaultdict(dict) for i, j, w in edges: adj[i][j] = w adj[j][i] = w count = 0 res = {} dist = {node: float('inf') for node in range(n)} dist[0] = 0 while dist: i, w = sorted(dist.items(), key = lambda x:x[1])[0] dist.pop(i) res[i] = w count += w for j in adj[i]: if j not in res: dist[j] = min(dist[j], adj[i][j]) return count x = Graph() x.DFS_Traversal(5, [[0,1], [0,2], [0,3], [1,4]]) x.BFS_Traversal(5, [[0,1], [0,2], [0,3], [1,4]])
29758903b934a615cfcf41b586972479e76536c4
Leahxuliu/Data-Structure-And-Algorithm
/Python/Graph/133.Clone Graph.py
3,994
3.890625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/16 # @Author : XU Liu # @FileName: 133.Clone Graph.py ''' 1. 题目要求: 2. 理解: 对无向图进行复制 graph看起来是一样的,nodes是new(deep copy) 3. 题目类型: 无向图 图的性质 4. 输出输入以及边界条件: input: list,eg:adjList = [[2,4],[1,3],[2,4],[1,3]];1链接的2,4;2链接着1,3 output: list,同上 corner case: 只有一个点 --> list,eg:adjList[[]] --> 输出[[]] 空图:输入[] --> 输出[] 两个点:输入:adjList = [[2],[1]] --> 输出 [[2],[1]] 5. 解题思路 方案一 1. 用BFS遍历一遍 2. 同时创建新图的邻接点表 3. 用dict保存新的结果,key是node,value是neighbors;同时这个dict也起到visited的作用 4. 注意避免重复,neigbor遇到重复点时,不要重复新建节点 time complexity O(N) space O(N) ''' # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = []): self.val = val self.neighbors = neighbors class Node: def __init__(self, val = 0, neighbors = []): self.val = val self.neighbors = neighbors ''' 错误回答 虽然答案的数字是一样的,但是不具备Node的性质 ''' from collections import deque import copy class Solution: def cloneGraph(self, node: 'Node') -> 'Node': if node == None: return None if node.neighbors == None: return node.deepcopy() new = {} queue = deque() queue.append(node) while queue: node = queue.popleft() new[node.val] = [] for i in node.neighbors: new[node.val].append(i.val) if i.val not in new: queue.append(i) sort = sorted(new.items(),key=lambda d:d[0]) res = [] for each in sort: res.append(each[1]) print(res) return res ''' 更正 ''' from collections import deque class Solution: def cloneGraph(self, node: 'Node') -> 'Node': if not node: # corner case return None if not node.neighbors: res = Node(node.val) # 易错点 return res visited = {} queue =deque([node]) visited[node] = Node(node.val) print(visited) while queue: n = queue.popleft() for elem in n.neighbors: if elem not in visited: visited[elem] = Node(elem.val) queue.append(elem) visited[n].neighbors.append(visited[elem]) return visited[node] a = Node(1) b = Node(2) c = Node(3) d = Node(4) a.neighbors = [b, d] b.neighbors = [a, c] c.neighbors = [b, d] d.neighbors = [a, c] x = Solution() print(x.cloneGraph(a)) ''' traversal * 2 1. traversal given graph, make new nodes, and store them into dictionary 2. traversal given graph again, connect each node ''' class Solution: def cloneGraph(self, node: 'Node') -> 'Node': # corner case if node == None: return if node.neighbors == None: return Node(node.val) def traversal(node): if node.val in info: return info[node.val] = Node(node.val) visited[node.val] = 0 for out in node.neighbors: traversal(out) return def connect(node): if visited[node.val] == 1: return visited[node.val] = 1 for out in node.neighbors: info[node.val].neighbors.append(info[out.val]) connect(out) return # make new nodes info = {} visited = {} traversal(node) # connect nodes connect(node) return info[node.val]
af559c5d6de605811b0eb007b7c28202533f761c
Leahxuliu/Data-Structure-And-Algorithm
/Python/Heap/347.Top K Frequent Elements.py
5,085
3.5
4
# !/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/05 # @Author : XU Liu # @FileName: 347.Top K Frequent Elements.py ''' 1. 题目要求: 找出现频率最多的k个数 time complexity must be better than O(n log n) 2. 理解: 3. 输出输入以及边界条件: input: output: corner case: 4. 解题思路 5. 空间时间复杂度 ''' ''' dict + sort 字典排序时间复杂度O(n log n) 这里的n是key的个数 ''' class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: info = {} for i in nums: if i in info: info[i] += 1 else: info[i] = 1 res = sorted(info, key = lambda x:info[x], reverse = True) return res[:k] '''from collections import defaultdict dic = defaultdict(int) for elem in nums: dic[elem] += 1''' ''' dict + heap O(Nlogk) ''' # 347. Top K Frequent Elements from collections import defaultdict from heapq import * class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: info = defaultdict(int) for i in nums: info[i] += 1 heap = [] res = [] for key, value in info.items(): heappush(heap, (-value, key)) while k: res.append(heappop(heap)[1]) k -= 1 return res # 维持一个k大的heap # 最大值用最小堆,最小值用最大堆 from collections import defaultdict from heapq import heappop, heappush, heappushpop class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: if nums == []: return [] count = defaultdict(int) for i in nums: count[i] += 1 # sorted_count = sorted(count.items(), key = lambda x:-x[1]) heap = [] for key, value in count.items(): if len(heap) < k: heappush(heap, [value, key]) else: heappushpop(heap, [value, key]) return [each for times, each in heap] ''' 手动实现最小堆 ''' from collections import defaultdict class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: if nums == []: return [] count = defaultdict(int) for i in nums: count[i] += 1 def heappush(heap, value, key): heap.append((value, key)) i = len(heap) - 1 while i // 2 > 0: if heap[i][0] < heap[i // 2][0]: heap[i], heap[i // 2] = heap[i // 2], heap[i] i = i // 2 else: break return def heappoppush(heap, value, key): if heap[1][0] > value: return heap[1] = (value, key) i = 1 n = len(heap) while 2 * i < n: child = 2 * i if child + 1 < n and heap[child + 1][0] < heap[child][0]: child += 1 if heap[child][0] < heap[i][0]: heap[child], heap[i] = heap[i], heap[child] i = child else: break return heap = [0] # min-heap for key, value in count.items(): if len(heap) - 1 < k: heappush(heap, value, key) else: heappoppush(heap, value, key) return [each for times, each in heap[1:]] from collections import defaultdict class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: if nums == []: return [] info = defaultdict(int) for i in nums: info[i] += 1 def rasie_up(heap): i = len(heap) - 1 while i > 0: root = i // 2 if heap[root][0] > heap[i][0]: heap[root], heap[i] = heap[i], heap[root] i = root else: break return def sink_down(heap): end = len(heap) - 1 i = 0 while i * 2 <= end: child = i * 2 if child + 1 <= end and heap[child + 1] < heap[child]: child += 1 if heap[child] < heap[i]: heap[i], heap[child] = heap[child], heap[i] i = child else: break return # print(info) heap = [] for num, times in info.items(): if len(heap) < k: heap.append([times, num]) rasie_up(heap) else: if times < heap[0][0]: continue else: heap[0] = [times, num] sink_down(heap) # print(heap) return [each for times, each in heap]
2baef912ee5f0d37d2b8c23150bf7f3321ecc3db
Leahxuliu/Data-Structure-And-Algorithm
/Python/巨硬/A28.二叉树的下一个节点.py
1,073
3.703125
4
''' 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 https://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e?tpId=13&tqId=11210&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey ''' # 1.右边的最左节点;2.右上节点 # -*- coding:utf-8 -*- # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: def GetNext(self, pNode): # write code here if pNode == None: return None if pNode.right: curr = pNode.right while curr.left: curr = curr.left return curr while pNode.next: if pNode.next.left == pNode: return pNode.next pNode = pNode.next return None
20ab694e8b2967e65c4982ba8492872f7f7a9a42
Leahxuliu/Data-Structure-And-Algorithm
/Python/BinaryTree/1530. Number of Good Leaf Nodes Pairs.py
984
3.703125
4
# 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 countPairs(self, root: TreeNode, distance: int) -> int: if root == None: return 0 if root.left == None and root.right == None: return 0 def countdistance(root): # return the distance of leaf to root if root == None: return [] if root.left == None and root.right == None: return [1] l = countdistance(root.left) r = countdistance(root.right) for i in l: for j in r: if i + j <= distance: self.res += 1 return [each + 1 for each in l + r] self.res = 0 countdistance(root) return self.res
2e027c271f142affced4a4f873058702cea3487b
Leahxuliu/Data-Structure-And-Algorithm
/Python/Binary Search Tree/669.Trim a Binary Search Tree.py
1,471
4.09375
4
# !/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/30 # @Author : XU Liu # @FileName: 669.Trim a Binary Search Tree.py ''' 1. 题目类型: BST 2. 题目要求与理解: Trim a Binary Search Tree(修剪树) 给定一个二叉搜索树,同时给定最小边界 L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在 [L, R] 中 (R>=L) 3. 解题思路: 对比R, L, root之间的大小关系,类似二分法里找一定范围内的值 用recursion a. end: root is None b. R < root.val --> 留下left subtree, 缩小范围 c. l > root.val --> 留下right subtree, 缩小范围 d. L <= root val and R >= root.val --> 留下both sides of the tree 4. 输出输入以及边界条件: input: root: TreeNode, L: int, R: int output: TreeNode corner case: None 5. 空间时间复杂度 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def trimBST(self, root, L, R): if root == None: return None if R < root.val: return self.trimBST(root.left, L, R) if L > root.val: return self.trimBST(root.right, L, R) if L <= root.val and R >= root.val: root.left = self.trimBST(root.left, L, R) root.right = self.trimBST(root.right, L, R) return root
eb5b6c989b13c535c77d7651f7812231cd6053e4
Leahxuliu/Data-Structure-And-Algorithm
/Python/Graph/最短路径/743. Network Delay Time.py
2,085
3.5
4
from heapq import * from collections import defaultdict class Solution: def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: # bulid the graph graph = defaultdict(dict) for i, j, w in times: graph[i][j] = w res = {} heap = [(0, K)] while heap: path, node = heappop(heap) if node in res: continue else: res[node] = path if len(res) == N: break for j in graph[node]: if j not in res: heappush(heap, (path + graph[node][j], j)) sortPath = sorted(res.values()) return sortPath[-1] if len(res) == N else -1 ''' use Dijkstra key: 1. find all shortest paths from source node to other node 2. then find the max time in 1 1. make adjacent list in dictionary dict[dict] key1: start node; key2: end node; value: weight 2. initalize a dict to store the dist from source to the node (dist) key: each node; value: inf; (source node 0) 3. pop the shortest time(t) in the dict, and then traverse the neighbor(j node) of popped node, change the time of j node in dict, the new dist is min(dist[j], t + w) 4. max(all shortest paths) ''' from collections import defaultdict class Solution: def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: # adjancent list adj = defaultdict(dict) for i, j, w in times: adj[i][j] = w # init a dist dist = {node: float('inf') for node in range(1, N + 1)} dist[K] = 0 # find the shortest paths res = {} while dist: i, w = sorted(dist.items(), key = lambda x:x[1])[0] res[i] = w dist.pop(i) for j in adj[i]: if j not in res: dist[j] = min(dist[j], w + adj[i][j]) res = sorted(res.values(), key = lambda x:x)[-1] return res if res != float('inf') else -1
d75019877651f2d9df6a674d0a92326485adaadc
Leahxuliu/Data-Structure-And-Algorithm
/Python/巨硬/C10.对应排序.py
266
3.78125
4
''' 给定一个按照字典序列的string字符串数组,每个字符串表示一个int,要求按照string对应的int大小重新排序 ''' # change into dict, sort a = {'a':10, 'b':2, 'c': 5} sorted_a = sorted(a.keys(), key = lambda x:a[x]) print(sorted_a)
0d4a3da86f67411aa0b7fd32c5cfe0ac67e6336d
Leahxuliu/Data-Structure-And-Algorithm
/Python/Math/图形类/836. Rectangle Overlap.py
750
3.921875
4
class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: def check(A, B): '''return true if overlap Args: A(list): [x1, x2] or [y1, y2] from rec1 B(list): [x1, x2] or [y1, y2] from rec2 Return: boolean ''' a1, a2 = A b1, b2 = B # 一条线一个点不能叫做overlap if a1 == a2 or b1 == b2: return False return True if a1 < b2 and a2 > b1 else False if check([rec1[0], rec1[2]], [rec2[0], rec2[2]]) and check([rec1[1], rec1[3]], [rec2[1], rec2[3]]): return True else: return False
4a29901279a8008afc0776cd78ac8f2b6f512fc7
Leahxuliu/Data-Structure-And-Algorithm
/Python/Binary Search/374.Guess Number Higher or Lower.py
1,070
4
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/27 # @Author : XU Liu # @FileName: 374.Guess Number Higher or Lower.py ''' 1. 题目理解: 猜数字,范围是1-n -1 : My number is lower --> 猜的数比计算机的数要大 1 : My number is higher 0 : Congrats! You got it! 2. 题目类型: binary search 3. 输出输入以及边界条件: input: int output: int corner case: 4. 解题思路 常规binary search 后台有一个guess API 5. 时间空间复杂度: ''' # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: l, r = 1, n while l <= r: mid = l + (r - l) // 2 tag = guess(mid) if tag == 0: return mid elif tag == -1: r = mid - 1 elif tag == 1: l = mid + 1
efc9b6d05c4c80a1c4382a0c6d3339ed4761c9af
Leahxuliu/Data-Structure-And-Algorithm
/Python/DP/403. Frog Jump.py
2,202
3.65625
4
''' brout force use backtacking to simulate jump ''' class Solution: def canCross(self, stones: List[int]) -> bool: if len(stones) < 2: return True if stones[1] > 1: return False def find(start, steps): '''simulation of jumpping Args: start(int):the start index of stones steps(int): can jump k units Return: None ''' if self.res: return if start == len(stones) - 1: self.res = True return if start >= len(stones): return minJ = max(steps - 1, 1) maxJ = steps + 1 for k in range(minJ, maxJ + 1): next_uite = stones[start] + k if next_uite in info: find(info[next_uite], k) return info = {} for i, each in enumerate(stones): info[each] = i self.res = False find(1, 1) return self.res ''' DFS + memo ''' class Solution: def canCross(self, stones: List[int]) -> bool: if len(stones) < 2: return True if stones[1] > 1: return False def find(start, steps): if (start, steps) in memo: return memo[(start, steps)] if start == len(stones) - 1: return True if start >= len(stones): return False res = False minJ = max(steps - 1, 1) maxJ = steps + 1 for k in range(minJ, maxJ + 1): next_uite = stones[start] + k if next_uite in info: if find(info[next_uite], k): res = True break memo[(start, steps)] = res return res info = {} for i, each in enumerate(stones): info[each] = i memo = {} find(1, 1) return find(1, 1)
e11ce7a7489623f1c1cc2845e4d1b478a852dc7f
Leahxuliu/Data-Structure-And-Algorithm
/Python/BinaryTree/257.Binary Tree Paths.py
2,920
3.65625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/04 # @Author : XU Liu # @FileName: 257.Binary Tree Paths.py ''' 1. 题目要求: 2. 理解: 3. 题目类型: 4. 输出输入以及边界条件: input: output: corner case: 5. 解题思路 ''' #DFS class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: def dfs(root, path): if root == None: return if root.left == None and root.right == None: path += str(root.val) path_all.append(path) dfs(root.left, path+str(root.val)+'->' ) # 注意'->'加在的位置,易错! 中间要有'->',结尾不能有 dfs(root.right, path+str(root.val)+'->' ) path = '' path_all = [] dfs(root, path) return path_all class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if root == None: return def dfs(root, path): if root.left != None: dfs(root.left, path + [str(root.left.val)]) if root.right != None: dfs(root.right, path + [str(root.right.val)]) if root.right == None and root.left == None: all_path.append('->'.join(path)) all_path = [] dfs(root, [str(root.val)]) return all_path #BFS from collections import deque class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: path_all = [] if root == None: return path_all queue = deque() path = '' queue.append([root, path]) while queue: node, path = queue.popleft() path += str(node.val) + '->' if node.left == None and node.right == None: path = path.rstrip('->') path_all.append(path) if node.left != None: queue.append([node.left, path]) if node.right != None: queue.append([node.right, path]) return path_all # 回溯 class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if root == None: return def helper(root, path): if root == None: return if root.left == None and root.right == None: all_path.append('->'.join(path[:])) return all_path for node in (root.left, root.right): if node: path.append(str(node.val)) helper(node, path) path.pop() all_path = [] helper(root, [str(root.val)]) return all_path
c8c72fef577fe5901ea9c6e740e39a22f0f544dd
Leahxuliu/Data-Structure-And-Algorithm
/Python/BinaryTree/366. Find Leaves of Binary Tree.py
1,234
3.8125
4
# 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 from collections import defaultdict class Solution: def findLeaves(self, root: TreeNode) -> List[List[int]]: if root == None: return [] def remove_node(root): ''' return flag weather this node should be removed or not return depth of the node ''' if root == None: return True, 0 if root.left == None and root.right == None: res[1].append(root.val) return True, 1 l, depthl = remove_node(root.left) r, depthr = remove_node(root.right) if l: root.left = None if r: root.right = None depth = max(depthl, depthr) + 1 if l and r: res[depth].append(root.val) return l and r, depth res = defaultdict(list) remove_node(root) res = [each for each in res.values()] return res
6bd47f050f406989bfa4f9978a9668324c4fb528
Leahxuliu/Data-Structure-And-Algorithm
/Python/链表/61.Rotate List.py
2,240
3.796875
4
# !/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/05 # @Author : XU Liu # @FileName: 61.Rotate List.py ''' 1. 题目要求: 最后一个node移动到第一个,重复k次 2. 理解: 3. 输出输入以及边界条件: input: output: corner case: 4. 解题思路 5. 空间时间复杂度 ''' ''' two pointers (slow and fast pointer) 仅限于k的取值比链表长度小 1. make dummy, dummy = ListNode(0) 2. set two pointers start at dummy 3. fast pointer move k steps 4. slow and fast move one step together until fast.next == None 5. fast.next = head 6. head = s.next # 易错 记录头 7. slow.next = None 此方法错误,因为k的取值范围是没有规定的,所以可以是很大,轮好几回 需要知道链表的长度 可是上面这个方法没法知道链表的长度 ''' class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head == None: return dummy = ListNode(0) dummy.next = head s, f = dummy, dummy while k > 0: f = f.next k -= 1 while f.next != None: s = s.next f = f.next f.next = dummy.next head = s.next s.next = None return head ''' 1. 找到旧的尾部并将其与链表头相连(cur.next = head) 2. 整个链表闭合成环,同时计算出链表的长度 n 3. 找到新的尾部,第 n - k % n个节点 ,新的链表头是第 n - k % n + 1个节点 (1-based) 4. 断开环 end.next = None,并返回新的链表头 new_head。 ''' class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head == None: return curr = head n = 1 # 易错 下面的while次数是步数,步数+1是个数 while curr.next: curr = curr.next n += 1 curr.next = head end = head new_k = n - k % n while new_k > 1: end = end.next new_k -= 1 new_head = end.next end.next = None return new_head
9c0eb97bc9248d2bdf4966a535f429a25120b3ee
Leahxuliu/Data-Structure-And-Algorithm
/Python/巨硬/B5.石子游戏.py
2,362
3.5625
4
''' 877 ''' ''' 1. 用相对分数,play1加分数,play减分数 2. 不是比较左右,取最大,而是比较取左之后,别人取了有的情况 brout force backtracking to simulation stone game ''' class Solution: def stoneGame(self, piles: List[int]) -> bool: def play_game(start, end): ''' 先取的人尽可能最大 ''' if (start, end) in memo: return memo[(start, end)] if start == end: return piles[start] choose_left = piles[start] - play_game(start + 1, end) choose_right = piles[end] - play_game(start, end - 1) res = max(choose_left, choose_right) memo[(start, end)] = res return res memo = {} return play_game(0, len(piles) - 1) > 0 ''' dp 状态 dp[i][j] 定义:区间 piles[i..j] 内先手可以获得的相对分数; 状态转移方程:dp[i][j] = max(nums[i] - dp[i + 1, j] , nums[j] - dp[i, j - 1]) 。 类似最长回文子序列? ''' class Solution: def stoneGame(self, piles: List[int]) -> bool: n = len(piles) dp = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): for j in range(i, n): if j == i: dp[i][j] = piles[i] else: dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]) return dp[0][-1] > 00 ''' 错误 brout force backtracking to simulation stone game ''' class Solution: def stoneGame(self, piles: List[int]) -> bool: def play_game(start, end, play1, play2, flag): if self.res: return if start > end: if play1 > play2: self.res = True return # alex if flag == 1: play_game(start + 1, end, play1 + piles[start], play2, 2) play_game(start, end - 1, play1 + piles[end], play2, 2) else: play_game(start + 1, end, play1, play2 + piles[start], 1) play_game(start, end - 1, play1, play2 + piles[end], 1) return self.res = False play_game(0, len(piles) - 1, 0, 0, 1) return self.res
e0931fc421f3da8b6d4a314c15722c5900e4afed
Leahxuliu/Data-Structure-And-Algorithm
/Python/巨硬/A40.连续相同值子序列的最大长度.py
730
3.75
4
''' 给一个数组,可修改一个值,求由连续相同值组成的子序列的最大长度 ''' from collections import defaultdict def count(arr): if len(arr) < 3: return len(arr) n = len(arr) left = 0 res = 1 count = 0 diff = 0 for right in range(1, n): if arr[right] != arr[right - 1]: count += 1 if count >= 2: left = diff count -= 1 diff = right else: arr[right] = arr[right - 1] diff = right res = max(res, right - left + 1) return max(res, right - left + 1) arr = [1, 1, 0, 0, 1, 1, 2, 1] print(count(arr))
b9d72fe04957416311354a56e53d9f464c9a35e7
Leahxuliu/Data-Structure-And-Algorithm
/Python/Binary Search Tree/700.Search in a Binary Search Tree.py
1,643
3.8125
4
# !/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/31 # @Author : XU Liu # @FileName: 700.Search in a Binary Search Tree.py ''' 1. 题目类型: BST 2. 题目要求与理解: 最最最普通的查找 3. 解题思路: 4. 输出输入以及边界条件: input: output: corner case: 5. 空间时间复杂度 ''' class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if root == None: return None while root: if root.val == val: return root elif root.val > val: root = root.left elif root.val < val: root = root.right return None from collections import deque class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if root == None: return queue = deque() queue.append(root) while queue: node = queue.popleft() if node == None: # 不能忘记了!易错 return if node.val == val: return node if node.val > val: queue.append(node.left) else: queue.append(node.right) # 递归的速度更快 class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return None if root.val == val: return root if root.val < val: return self.searchBST(root.right, val) if root.val > val: return self.searchBST(root.left, val)
496b9a5e06279f1e16ba01b3d0ba01cffd79dd21
Leahxuliu/Data-Structure-And-Algorithm
/Python/巨硬/A2打印缺失数字.py
1,440
4.0625
4
''' 一个sorted array,整数,要求输出缺失的数字。比如输入是[5,6,7,11,13],输出8, 9, 10, 12 ''' def find_miss_integer(arr): ''' param: sorted array return missing integers in a list ''' if arr == []: return [] minVal = arr[0] maxVal = arr[-1] if len(arr) == maxVal - minVal + 1: return [] arr_set = set(arr) res = [] for i in range(minVal, maxVal): if i not in arr_set: res.append(i) return res a = find_miss_integer([5,6,7,11,13]) print(a) a = find_miss_integer([5,6,7]) print(a) ''' 空间复杂度: O(1) ''' def find_lost_number(arr): if arr == []: return [] res = [] for i in range(1, len(arr)): if arr[i - 1] + 1 != arr[i]: num = arr[i - 1] + 1 while num != arr[i]: res.append(num) num += 1 return res a = find_lost_number([5,6,7,11,13]) print(a) a = find_lost_number([5,6,7]) print(a) ''' 若不是sorted arr 且0-n里面找缺失数字 ''' # LC 268 def find_lost_number(arr): if arr == []: return [] arr.sort() res = [] for i in range(1, len(arr)): if arr[i - 1] + 1 != arr[i]: num = arr[i - 1] + 1 while num < arr[i]: res.append(num) num += 1 return res # for i, each in enumerate(arr): # res ^= i ^ each
4c462f2762e0f6fcd34dd1c9c3a8f0d61b49b030
Leahxuliu/Data-Structure-And-Algorithm
/Python/Graph/有向图/399. Evaluate Division-带权并查集.py
1,386
3.578125
4
''' b / a = 3c / 6c = 0.5 把‘不同的变量’转换成‘相同变量’的倍数 一边查询一边修改 路径压缩 2.0 3.0 a --> b --> c 6.0 3.0 a --> c <-- b ''' class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: gT = {} weight = {} def add(i): if i not in gT: gT[i] = i weight[i] = 1.0 return def find(i): if i != gT[i]: origin = gT[i] gT[i] = find(gT[i]) # 更新点 weight[i] *= weight[origin] return gT[i] def union(i, j, val): root1 = find(i) root2 = find(j) if root1 != root2: gT[root1] = root2 # 更新点 # 四边形法则更新根节点的权重 weight[root1] = weight[j] * val / weight[i] return for (a, b), val in zip(equations, values): add(a) add(b) union(a, b, val) res = [] for (a, b) in queries: if a in weight and b in weight and find(a) == find(b): res.append(weight[a] / weight[b]) else: res.append(-1.0) return res
2b7639d299e47c4772e9697bbec3c272b48b8a9c
Leahxuliu/Data-Structure-And-Algorithm
/Python/String/stack/844. Backspace String Compare.py
953
3.84375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/07/20 class Solution: def backspaceCompare(self, S: str, T: str) -> bool: new_S = [] new_T = [] for i in S: if i == '#': if new_S != []: new_S.pop() else: new_S.append(i) for j in T: if j == '#': if new_T != []: new_T.pop() else: new_T.append(j) if ''.join(new_S) == ''.join(new_T): return True else: return False # 优化写法 class Solution: def backspaceCompare(self, S, T): def build(S): res = [] for i in S: if i != '#': res.append(i) elif res: res.pop() return "".join(res) return build(S) == build(T)
33a015aa5f9c1adae29963d96558d043b48ed632
Leahxuliu/Data-Structure-And-Algorithm
/Python/Math/504. Base 7.py
367
3.546875
4
class Solution: def convertToBase7(self, num: int) -> str: if num == 0: return str(0) res = '' if num > 0: flag = '' else: flag = '-' num = abs(num) while num != 0: res = str(num % 7) + res num = num // 7 return flag + res
fa20d0eb6a96fed2a24c4d1b321681e39916d46b
Leahxuliu/Data-Structure-And-Algorithm
/Python/BinaryTree/103. Binary Tree Zigzag Level Order Traversal.py
1,797
3.765625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' BFS 按层次遍历 ''' from collections import deque class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if root == None: return [] queue = deque() queue.append(root) flag = 1 res = [] while queue: n = len(queue) temp = [] for _ in range(n): node = queue.popleft() if flag == 1: temp.append(node.val) else: temp.insert(0, node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) flag = -flag res.append(temp) return res ''' DFS ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if root == None: return [] def traversal(root, level): if root == None: return if len(self.res) < level + 1: self.res.append([]) if level % 2 == 0: self.res[level].append(root.val) else: self.res[level].insert(0, root.val) traversal(root.left, level + 1) traversal(root.right, level + 1) return self.res = [] traversal(root, 0) return self.res
44ab080409a0baddac6e71cc84accb4bf5592c7f
Leahxuliu/Data-Structure-And-Algorithm
/Python/BinaryTree/297. Serialize and Deserialize Binary Tree.py
4,106
3.984375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 前序遍历 class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def preorder(root): return [root.val] + preorder(root.left) + preorder(root.right) if root else ['None'] return ','.join(map(str, preorder(root))) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ data = data.split(',') def constructor(data): val = int(data.pop(0)) if val == 'None': return None root = TreeNode(val) root.left = constructor(data) root.right = constructor(data) return root return constructor(data) # Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root)) # 后序遍历 class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root == None: return '' def postorder(root): return postorder(root.left) + postorder(root.right) + [root.val] if root else ['None'] return ','.join(map(str, postorder(root))) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '': return None data = data.split(',') def helper(data): val = data.pop() if val == 'None': return None root = TreeNode(val) root.right = helper(data) root.left = helper(data) return root return helper(data) # Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root)) # BFS from collections import deque class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root == None: return '' res = [] queue = deque() queue.append(root) res.append(root.val) while queue: node = queue.popleft() if node == 'None': continue if node.left != None: queue.append(node.left) res.append(node.left.val) else: res.append('None') if node.right != None: queue.append(node.right) res.append(node.right.val) else: res.append('None') # print(','.join(map(str, res))) return ','.join(map(str, res)) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '': return None data = data.split(',') root = TreeNode(data.pop(0)) queue = deque() queue.append(root) while queue: node = queue.popleft() # build left val = data.pop(0) if val != 'None': node.left = TreeNode(val) # 易错 不是val,而是Treenode(val) queue.append(node.left) # should be add # build right val = data.pop(0) if val != 'None': node.right = TreeNode(val) queue.append(node.right) return root # Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root))
db75315d50fc2e6e3e330a48c0b53efc8f377c6b
Leahxuliu/Data-Structure-And-Algorithm
/Python/Binary Search/167.Two Sum II - Input array is sorted.py
3,516
3.765625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/24 # @Author : XU Liu # @FileName: 167.Two Sum II - Input array is sorted.py ''' 1. 题目要求: Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 2. 理解: 给的array里面,两数相加=target 输出这两数的index 注意 要输出1-based 3. 题目类型: binary search 有target类型 4. 输出输入以及边界条件: input: numbers: List[int], target: int output: List[int] 两数的index corner case: numbers == None min(numbers) > target 5. 解题思路 方法一: 普通的遍历 --> Time Limit Exceeded 方法二: binary search 易错点:不能自己加自己 for i in range(len(numbers) - 1): for j in range(i+1, len(numbers)): --> binary search ''' ''' 方法一 ''' class Solution: def twoSum(self, numbers, target): if numbers == None: return [] if numbers[0] > target: return [] for i in range(len(numbers) - 1): for j in range(i+1, len(numbers)): # range易错 if numbers[i] + numbers[j] == target: return [i+1, j+1] # dict class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: info = {} for i, n in enumerate(numbers): diff = target - n if diff in info: return [info[diff] + 1, i + 1] info[n] = i return [-1, -1] ''' 方法2 第16个case,超时 两个for循环,超时 ''' class Solution: def twoSum(self, numbers, target): if numbers == None: return [] if numbers[0] > target: return [] for i in range(len(numbers)-1): # range范围易错 for j in range(i+1, len(numbers)): l, r = i+1, len(numbers) - 1 while l <= r: mid = l + (r - l) //2 # mid = (r+l)//2 上面那样写是为了防止计算机超限 if target == numbers[i] + numbers[mid]: return [i+1, mid+1] if target < numbers[i] + numbers[mid]: r = mid - 1 elif target > numbers[i] + numbers[mid]: l = mid + 1 ''' Two point 优化 ''' class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: i = 0 j = len(numbers) - 1 while i < j: Sum = numbers[i] + numbers[j] if Sum == target: return [i + 1, j + 1] if Sum < target: i += 1 else: j -= 1 ''' 方法三 ''' class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: def find(target, start): l = start r = len(numbers) - 1 while l <= r: mid = l + (r - l) // 2 if numbers[mid] == target: return mid if numbers[mid] > target: r = mid - 1 else: l = mid + 1 return -1 for i, n in enumerate(numbers): diff = target - n index = find(diff, i + 1) if index != -1: return [i + 1, index + 1] x = Solution() print(x.twoSum([1,2,3,4,4,9,56,90],8))
f586c7be734c4bb09de68c72975cbe50eab23109
Leahxuliu/Data-Structure-And-Algorithm
/Python/sort/912. Sort an Array.py
3,674
3.796875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/07/02 # 递归 class Solution: def sortArray(self, nums: List[int]) -> List[int]: if len(nums) == 0: return [] if len(nums) == 1: return nums mid = len(nums) // 2 L = nums[:mid] R = nums[mid:] L = self.sortArray(nums[:mid]) R = self.sortArray(nums[mid:]) i, j = 0, 0 arr = [] while i < len(L) and j < len(R): if L[i] <= R[j]: arr.append(L[i]) i += 1 else: arr.append(R[j]) j += 1 while i < len(L): arr.append(L[i]) i += 1 while j < len(R): arr.append(R[j]) j += 1 return arr # 递归 ''' 递归 自上往下再向上 自上往下: 分割成小部分(分割成1个数1个数) 自下再往上: 合并排序 ''' class SortList: def mergeSort(self, arr): n = len(arr) if n == 0: return [] if n == 1: return arr # if n >= 2 # divide the array elements into 2 lists mid = n // 2 L = arr[:mid] R = arr[mid:] # 递归划分 # 划分成小部分,先到最底层,然后对最底层进行合并排序操作,然后再返回上一层接着合并排序操作 L = self.mergeSort(L) # Sorting the first half R = self.mergeSort(R) # Sorting the second half # 合并 # input: 两个已排序的list,L,R # 过程: 对L,R进行合并排序 # output: 合并完成后的一个list i, j, k = 0, 0, 0 # i是L里面的指针,j是R里面的指针,k是这一轮arr里面的指针 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 k += 1 else: arr[k] = R[j] j += 1 k += 1 # 是否具有稳定性取决于L[i] == R[i]的时候,arr[k] = L[i]还是arr[k] = R[j], 前者具有稳定性,后者不具有稳定性 # 稳定性: 同样大小的数值,保持其原有的顺序 # 例: [5,4(a),4(b),3,2], 排序后: [2,3,4(a),4(b),5] # L或R有没有用完的情况,也就是两者len不同的时候 if i < len(L): arr[k:] = L[i:] # 在while最后,k,i,j都+1了 if j < len(R): arr[k:] = R[j:] return arr class Solution: def sortArray(self, nums: List[int]) -> List[int]: n = len(nums) if n == 0: return [] if n == 1: return nums def subSort(nums1, nums2): if nums1 == []: return nums2 if nums2 == []: return nums1 i, j = 0, 0 res = [] while i < len(nums1) and j < len(nums2): if nums1[i] <= nums2[j]: res.append(nums1[i]) i += 1 else: res.append(nums2[j]) j += 1 if i < len(nums1): res.extend(nums1[i:]) if j < len(nums2): res.extend(nums2[j:]) return res interval = 1 while interval < n: for i in range(0, n, 2 * interval): nums[i:i + 2 * interval] = subSort(nums[i:i + interval], nums[i+interval:i + 2 * interval]) interval *= 2 return nums
5c65765bca74c42c366893ddad3b783c54da6286
Leahxuliu/Data-Structure-And-Algorithm
/Python/DP/数组中是否有相加等于S的数.py
1,960
3.71875
4
# !/usr/bin/python # -*- coding: utf-8 -*- ''' 1. 题目类型: DP 2. 题目要求: 给定一个正整数s, 判断一个数组arr中,是否有一组数字加起来等于s 都是正整数 ''' # 递归 arr = [3, 34, 4, 12, 5, 2] def rec_subset(arr, i, s): if i == 0: return arr[0] == s ''' if i == 0: return arr[0] == s 错误 因为后面还有i-1 ''' if arr[i] > s: return rec_subset(arr, i-1, s) if s == 0: return True return rec_subset(arr, i-1, s-arr[i]) or rec_subset(arr, i-1, s) print(rec_subset(arr, len(arr)-1, 13)) print(rec_subset(arr, len(arr)-1, 9)) # DP # 不用numpy0 def dp_subset(arr, S): subset = [[False] * (S+1) for _ in range(len(arr))] for i in range(len(arr)): for s in range(S+1): if arr[i] == s: subset[i][s] = True elif arr[i] > s: subset[i][s] = subset[i-1][s] # print(subset[i][s]) else: subset[i][s] = subset[i-1][s] or subset[i-1][s-arr[i]] # print(subset[i][s]) return subset[len(arr)-1][S] print(dp_subset(arr, 9)) print(dp_subset(arr, 12)) print(dp_subset(arr, 13)) # 用numpy import numpy as np def dp_subset(arr, S): subset = np.zeros((len(arr), S+1), dtype=bool) # subset = [[False] * (s+1) for _ in range(len(arr))] subset[:, 0] = True # 第n行第1列都是Ture subset[0, :] = False # 第一行都是False subset[0, arr[0]] = True for i in range(1, len(arr)): for j in range(1, S+1): if arr[i] > j: subset[i, j] = subset[i-1, j] else: A = subset[i-1, j - arr[i]] B = subset[i-1, j] subset[i,j] = A or B #print(subset) return subset[len(arr)-1, S] print(dp_subset([3, 34, 4, 12, 5, 2], 9)) print(dp_subset([3, 34, 4, 12, 5, 2], 13))
582c77dcaac7aabd9a5828795db5e035130a4c8e
Leahxuliu/Data-Structure-And-Algorithm
/Python/巨硬/C26.替换部分字符.py
1,179
3.671875
4
''' 写了一道题,大概意思就是给定一个字符串'aaabbbccc{{a}b{c}}' 然后可替换的部分'a: [d, e], c: [f], dbf: [x], ebf: [y]' 最后返回所有可能生成的字符串 ''' def change_string(s, data): if s == "": return "" def change(s, start, path): nonlocal res if start == len(s): res.add(''.join(path)) return if start > len(s): return temp_s = "" for i in range(start, len(s)): temp_s += s[i] if temp_s in data: for char in data[temp_s]: # change change(s, i + 1, path + [char]) # not change change(s, i + 1, path + [temp_s]) else: change(s, i + 1, path + [temp_s]) break return res = set() # 注意去重 change(s, 0, []) return list(res) s = 'aaabbbccc{{a}b{c}}' data = {'a': ['d', 'e'], 'c': ['f'], 'dbf': ['x'], 'ebf': ['y']} test = change_string(s, data) print(test) if len(test) == len(list(set(test))): print(True) else: print(False)
29ae5bf6cd55abbb4ed01967339cbf4d03795473
Leahxuliu/Data-Structure-And-Algorithm
/Python/LeetCode2.0/Graph/261.Graph Valid Tree.py
3,618
3.84375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/05/09 ''' I. Clarify a valid tree == no cirle and one island II. Method 1. DFS / BFS Steps: 1. the length edges != n - 1 --> False beacuse the graph has circle or more than one island 2. build visited (0: not visited yet, 1: visited) and graph(adjacent table) 3. scan vertexs and its neighbors using BfS / DFS [now_index, out_index] if neighbor vertex has been visited, and the vertex is not parent vertex --> have circle --> False else: True Complexity: Time: O(V + E) Space:O(V + E) 3. union find Steps: 1. build groupTag, the vertex's root as th index of the vertex 2. scan vertexs using edges find root by using DFS if root1 == root2 --> have circle Complexity: Time: O(V + E) Space:O(V + E) ''' # BFS from collections import deque class Solution: def validTree(self, n, edges): if n == 0: return False if n == 1: return True if len(edges) != n - 1: return False visited = [0] * n graph = [[] for _ in range(n)] for x, y in edges: graph[x].append(y) graph[y].append(x) queue = deque() for i in range(n): if visited[i] == 0: queue.append([i, -1]) visited[i] = 1 while queue: index, parent = queue.popleft() for out in graph[index]: if visited[out] == 0: queue.append([out, index]) visited[out] = 1 else: if out != parent: return False return True # DFS class Solution2: def validTree2(self, n, edges): if n == 0: return False if n == 1: return True if len(edges) != n - 1: return False visited = [0] * n graph = [[] for _ in range(n)] for x, y in edges: graph[x].append(y) graph[y].append(x) def dfs(index, parent): if visited[index] == 1: return True visited[index] = 1 for out in graph[index]: if visited[out] == 1: if out != parent: return False else: if dfs(out, index) == False: return False return True for i in range(n): if visited[i] == 0: if dfs(i, -1) == False: return False return dfs(i, -1) X = Solution2() print(X.validTree2(5, [[0,1], [1,2], [2,3], [1,3], [1,4]])) # Union find class Solution: def validTree(self, n, edges): if n == 0: return False if n == 1: return True if len(edges) != n - 1: return False groupTag = [i for i in range(n)] def find(i): if groupTag[i] == i: return i else: return find(groupTag[i]) for i, j in edges: root1 = find(i) root2 = find(j) if root1 == root2: return False else: groupTag[root2] = root1 return True
6d334b9854eb84eec9346d5b4078b01efe6a07a7
Leahxuliu/Data-Structure-And-Algorithm
/Python/DFS:Backtracking/典型回溯法/78.Subsets.py
3,245
3.75
4
# !/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/04/02 # @Author : XU Liu # @FileName: 78.Subsets.py ''' 1. 题目类型: 2. 题目要求与理解: 找子集 无重复树 3. 解题思路: 4. 输出输入以及边界条件: input: output: corner case: 5. 空间时间复杂度 ''' ''' 回溯法 易错点: 注意nums里的值与index,不要混淆 ''' class Solution: def subsets(self, nums): res = [] temp = [] def backtrack(index, temp): if temp not in res: res.append(temp[:]) # return res 不能写return 因为的空list就会被append进去,没有进入到循环里面 for i in range(index, len(nums)): temp.append(nums[i]) backtrack(i + 1, temp) temp.pop() return res backtrack(0, temp) return res x = Solution() print(x.subsets([1,2,3])) ''' 写法2 ''' class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: if nums == []: return n = len(nums) all_res = [] def backtrack(start, k, path): if len(path) == k: all_res.append(path[:]) for i in range(start, n): path.append(nums[i]) backtrack(i+1, k, path) path.pop() for k in range(1, n + 1): backtrack(0, k, []) all_res.append([]) return all_res ''' 优化 ''' ''' A. math idea 数学归纳法 Time:O(2^n * n), product 2^n subset, add to res O(N) Space:O(2^n * n) ''' class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: if nums == []: return all_res = [] def backtrack(start, path): all_res.append(path[:]) for i in range(start, len(nums)): path.append(nums[i]) backtrack(i+1, path) path.pop() backtrack(0, []) return all_res # 类似dp class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: dp = [[] for _ in range(len(nums) + 1)] for i in range(len(nums) + 1): if i == 0: dp[i] = [[]] else: dp[i] = dp[i - 1] + [elem + [nums[i - 1]] for elem in dp[i - 1]] return dp[i] # 优化 class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: pre = [[]] for i in range(1, len(nums) + 1): pre += [elem + [nums[i - 1]] for elem in pre] return pre # dfs + memo class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: def dfs(i): if i in memo: return memo[i] if i == 0: memo[i] = [[], [nums[i]]] return memo[i] memo[i] = dfs(i - 1) + [elem + [nums[i]] for elem in dfs(i - 1)] return memo[i] memo = {} dfs(len(nums) - 1) return memo[len(nums) - 1]
b4deae1a0ceaccc374d37c496da57e6674076f16
Leahxuliu/Data-Structure-And-Algorithm
/Python/Binary Search/367.Valid Perfect Square.py
2,268
3.640625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/27 # @Author : XU Liu # @FileName: 367.Valid Perfect Square.py ''' 1. 题目理解: 判断给到的数字是不是可以被开平方 不能使用 sqrt function 16 --> 4 * 4 --> true 14 --> None --> False 2. 题目类型: binary sort target 3. 输出输入以及边界条件: input: int output: bool corner case: 0,1,2 4. 解题思路 binary search ##Memory Limit Exceeded## 1. make a list, such as[1,2,3,4....,16] 易错 arr = [i+1 for i in range(num)] 从1开始到num 2. arr[mid] * arr[mid] == target 改进: 不要写arr,arr造成Memory Limit Exceeded 另外先num//2之后再binary search 注意0,1,2 from 李厨子 Newton 牛顿法(又称:牛顿迭代法) 见笔记本 time O(logN) space O(1) 5. 时间空间复杂度: time: O(logN) space: 1 ''' ''' 超容量 ''' class Solution: def isPerfectSquare(self, num): if num == 0 or num == 1 or num == 2: return True arr = [i+1 for i in range(num//2)] l, r = 0, len(arr) - 1 while l <= r: mid = l + (r - l) // 2 if arr[mid] * arr[mid] == num: return True elif arr[mid] * arr[mid] > num: r = mid - 1 elif arr[mid] * arr[mid] < num: l = mid + 1 return False ''' 改进 不要arr,在l,r上面下功夫 ''' class Solution: def isPerfectSquare(self, num): if num == 0 or num == 1 or num == 2: return True l, r = 0, num // 2 # 难点 while l <= r: mid = l + (r - l) // 2 if mid * mid == num: return True elif mid * mid > num: r = mid - 1 elif mid * mid < num: l = mid + 1 return False ''' 改进 Newton ''' class Solution2: def isPerfectSquare2(self, num): if num == 1: return True x = num // 2 while x * x > num: x = (x + num // x) // 2 return x * x == num x = Solution() print(x.isPerfectSquare(4))
9084f4690be5d54199a6728d3cf971e83363219c
Leahxuliu/Data-Structure-And-Algorithm
/Python/双指针问题/对撞对开指针/287. Find the Duplicate Number.py
1,231
3.625
4
# !/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/06/20 # hash # time complexity: O(n) # space complexity:O(n) from collections import defaultdict class Solution: def findDuplicate(self, nums: List[int]) -> int: info = defaultdict(int) for i in nums: info[i] += 1 if info[i] > 1: return i # tow pointer fast and slow # time complexity: O(n) # space complexity:O(1) ''' [数值, index]为一对pair, 数值 -> 数值对应的index -> 数值 -> 数值对应的index (能找到两个不同的索引(但是值相等)指向同一索引,这就成环) 类似链表里面找环的交点 setp1: slow走一步, fast走两步, 找到相遇点 slow = nums[slow], fast = nums[nums[fast]] step2: i从step1的交点出发,j从0(index)出发,i与j相遇的点就是环的起点,也就是重复数 ''' class Solution: def findDuplicate(self, nums: List[int]) -> int: s = 0 f = 0 while (1): s = nums[s] f = nums[nums[f]] if s == f: break s = 0 while s != f: s = nums[s] f = nums[f] return s
6b2f5874385ddc11c81875ba6e31091a0f44f643
Leahxuliu/Data-Structure-And-Algorithm
/Python/双指针问题/分离双指针/349.Intersection of Two Arrays.py
1,316
3.859375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/04/29 # @Author : XU Liu # @FileName: 349.Intersection of Two Arrays.py ''' 1. 题目要求: 给定两个数组,编写一个函数来计算它们的交集。 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4] 2. 理解: 找相同的值 3. 输出输入以及边界条件: input: output: corner case: 4. 解题思路 1. 对两个nums进行sort,从小到大排 2. 分离指针,每个nums里面一个指针,i,j,从0开始 3. 一样的值就放入到set里面 5. 空间时间复杂度 时间 O(N) 空间 O(1) ''' class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: if nums1 == [] or nums2 == []: return i, j = 0, 0 res = set() nums1.sort() nums2.sort() while i < len(nums1) and j < len(nums2): if nums1[i] == nums2[j]: res.add(nums1[i]) i += 1 j += 1 elif nums1[i] < nums2[j]: i += 1 else: j += 1 return list(res)
47a5183567e67b82f98f8e608b0928b8cd0f2af3
Leahxuliu/Data-Structure-And-Algorithm
/Python/链表/138.Copy List with Random Pointer.py
1,347
3.578125
4
# !/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/05/06 # @Author : XU Liu # @FileName: 138.Copy List with Random Pointer.py ''' 1. 题目要求: 2. 理解: 3. 输出输入以及边界条件: input: output: corner case: 4. 解题思路 5. 空间时间复杂度 ''' """ # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if head == None: return dummy = Node(0) dummy.next = head # copy new node while head: next_head = head.next head.next = Node(head.val) head.next.next = next_head head = next_head # copy random head = dummy.next while head and head.next: if head.random: head.next.random = head.random.next head = head.next.next # choose the new nodes head = dummy.next dummy = Node(0) new_head = dummy while head and head.next: new_head.next = head.next head = head.next.next new_head = new_head.next return dummy.next
a778142f0be70d546af43255da6c4c3ffe59a0d1
Leahxuliu/Data-Structure-And-Algorithm
/Python/String/stack/946. 验证栈序列.py
505
3.515625
4
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: if pushed == [] and popped == []: return True if pushed == [] or popped == []: return False stack = [] j = 0 for i in pushed: stack.append(i) while j < len(popped) and stack and stack[-1] == popped[j]: stack.pop() j += 1 return True if j == len(popped) else False
d9a550cc7729fcf87aeafc68858551272b19d6aa
Leahxuliu/Data-Structure-And-Algorithm
/Python/双指针问题/前向型指针-快慢/922. Sort Array By Parity II.py
1,512
3.578125
4
# 暴力 class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: odd = [] even = [] for i in range(len(A)): if i % 2 == 0 and A[i] % 2 != 0: odd.append(i) elif i % 2 != 0 and A[i] % 2 == 0: even.append(i) for i in range(len(odd)): temp = A[odd[i]] A[odd[i]] = A[even[i]] A[even[i]] = temp return A # 双指针 # j 下一个不符合要求 且跟i能互换的点 class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: j = 0 for i in range(len(A)): if i % 2 == 0 and A[i] % 2 != 0: while not (j % 2 != 0 and A[j] % 2 == 0): j += 1 A[i], A[j] = A[j], A[i] j += 1 elif i % 2 != 0 and A[i] % 2 == 0: while not(j % 2 == 0 and A[j] % 2 != 0): j += 1 A[i], A[j] = A[j], A[i] j += 1 return A # 双指针 # 再优化 # i看偶数位,j看奇数位 # for i in rang(0, len(A), 2) # j += 2 # 时间复杂度:O(N) class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: j = 1 for i in range(0, len(A), 2): if A[i] % 2 != 0: while A[j] % 2 != 0: j += 2 A[i], A[j] = A[j], A[i] j += 2 return A
4f21735e9b85b9072567a6aa2df7d17ac121f39c
Leahxuliu/Data-Structure-And-Algorithm
/Python/Binary Search/33.Search in Rotated Sorted Array.py
1,766
4.28125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/26 # @Author : XU Liu # @FileName: 33.Search in Rotated Sorted Array.py ''' 1. 题目理解: 找到目标值 给到的arr是部分sort,都是升序,旋转 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand 输出target的index(0-based) 如果不存在target就输出-1 2. 题目类型: 很常考 binary search 有target,部分sort 旋转 3. 输出输入以及边界条件: input: nums: List[int], target: int output: int corner case: None 4. 解题思路 1. binary search 2. 核心 arr[mid]与arr[mid+1]之间的关系 arr[mid]与arr[r]/arr[l]之间的关系 5. 时间空间复杂度: 时间复杂度:O(log n) 空间复杂度:O(1) ''' class Solution: def search(self, nums: List[int], target: int) -> int: if not nums: # corner case return -1 l, r = 0, len(nums) - 1 while l <= r: mid = l + (r - l) // 2 if target == nums[mid]: return mid if nums[l] < nums[mid]: # 左边是sorted if nums[l] <= target < nums[mid]: # T在左边sorted部分内 r = mid - 1 else: # T在右边的unsorted内 l = mid + 1 elif nums[l] == nums[mid]: # 只有两个数字的时候,下一轮就return -1 l = mid + 1 # 或者l += 1 elif nums[l] > nums[mid]: # 左边是unsorted,右边是sorted if nums[mid] < target <= nums[r]: # T在右边sortedd内 l = mid + 1 else: r = mid - 1 return -1
58083918e77b197ab6336783ea8e0d2dc06b8036
Leahxuliu/Data-Structure-And-Algorithm
/Python/Graph/323.Number of Connected Components in an Undirected Graph.py
3,093
3.75
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/03/20 # @Author : XU Liu # @FileName: 323.Number of Connected Components in an Undirected Graph.py ''' 1. 题目要求: 2. 理解: 无向图 判断有几个群 3. 题目类型: 无向图 判断孤立和分群 4. 输出输入以及边界条件: input: n: int, edges: List[List[int]] output: int corner case: n == 0 --> 0 edges == [] --> n 5. 解题思路 方法一:利用并查集对nodes进行分组 方法二:dfs [0,1]法 ''' ''' union-find 易错点:有环的时候,groupTag里面数的个数不等于群的个数 要用一个numb来表示 具体原因见‘并查集.py' ''' class Solution: def countComponents(self, n, edges): #if n == 0 or edges == []: # 错误 n = 1, edges = []的时候,不应该输出0,而应该是1 # return 0 # 这里写成n,就对了 if n == 0: return 0 if edges == []: return n # 易错,不是0是n groupTag = [i for i in range(n)] def find(index): if groupTag[index] == index: return index else: return find(groupTag[index]) numb = 0 for i,j in edges: root1 = find(i) root2 = find(j) if root1 == root2: pass else: numb += 1 groupTag[root2] = root1 print(groupTag) return n - numb ''' DFS ''' class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: graph = [[] for _ in range(n)] visited = [0] * n for i,j in edges: graph[i].append(j) graph[j].append(i) def dfs(index): if visited == [1] * n: return visited[index] = 1 for out_node in graph[index]: if visited[out_node] == 0: dfs(out_node) group = 0 for i in range(n): if visited[i] == 0: dfs(i) group += 1 return group x = Solution() print(x.countComponents(4,[[2,3],[1,2],[1,3]])) ''' BFS ''' from collections import deque class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: if n == 0 or edges == []: return n visited = [0] * n graph = [[] for _ in range(n)] for i, j in edges: graph[i].append(j) graph[j].append(i) group = 0 queue = deque() for i in range(n): if visited[i] == 0: queue.append(i) group += 1 while queue: index = queue.popleft() visited[index] = 1 for out in graph[index]: if visited[out] == 0: queue.append(out) return group
902aea11bd59efe4945b43424f4916b69342f1ae
Leahxuliu/Data-Structure-And-Algorithm
/Python/coding/genres.py
611
3.5625
4
''' corner case: numU is 0 or not userB or numG == 0 or not bookG: return {} Method: corner case transfer bookG to value:k scan userB to create new dic for name, create {type:number} sort the {} add to new dic scan new dic, output the max number ''' def favorite(numU, userB, numG, bookG): if numU == 0 or not userB or numG == 0 or not bookG: return {} g_dic = {} for k, v in bookG.items(): for elem in v: g_dic[elem] = k dic = {} for k, v in userB.items(): name = k tmp_dic = {} for elem in v:
3da4457d043dda55a99aa4b64ebb7cc87d15acad
sahthi/backup2
/backup_files/practice/str.py
220
4.0625
4
def remove(string,n): first=[ :n] last=[n+1: ] return first+last string=raw_input("enter the string name:") n=int(input("enter the index to remove:") print("modified string:") print(remove(string,n))
5952daff834f8f713be39ef520f25d896034a006
sahthi/backup2
/backup_files/practice/sample/exp.py
374
4.125
4
import math x=[10,-5,1.2,'apple'] for i in x: try: fact=math.factorial(i) except TypeError: print("factorial is not supported for given input:") except ValueError: print ("factorial only accepts positive integers") else: print ("factorial of a", x, "is",fact) finally: print("release any resources in use")
46bc228f7805e43e22526ff7265dbf8cfd7aa030
sahthi/backup2
/files/2.py
374
3.640625
4
#!/usr/bin/python import socket def valid_ip(address): try: socket.inet_aton(address) return True except: return False if __name__=="__main__": txt = raw_input("Text > ") txt = txt.split() ips = [] for word in txt: if valid_ip(word): ips.append(word) for ip in ips: print ip
f1ad2505648929b1898fb08b158ae21a8c5cd80e
sahthi/backup2
/flask-application/rect.py
287
3.953125
4
class rectangle(): def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): return self.breadth*self.length a=input("enter len:") b=input("enter breadth:") obj=rectangle(a,b) print("area of rect:",obj.area())
7ea33fbc516fccc8932ef09595bed811bd0500ec
sahthi/backup2
/backup_files/practice/regw3.py
158
3.890625
4
import re def match(string): text=re.compile(r'^5') if text.match(string): return True else: return False print match('5-236278')
b94971fd2e175be3814b33a69556ec6a49057acc
sahthi/backup2
/backup_files/practice/thread.py
242
3.65625
4
import threading def sum(x,y): sum=x+y return sum def sub(x,y): sub=x-y return sub x=input("enter number:") y=input("enter number:") t=threading.Thread(target=sum) w=threading.Thread(target=sub) t.start() w.start()
966fff71c5c817d6a346f031d59692ff5cce0c00
sahthi/backup2
/backup_files/sanfoundry/dict.py
155
4.125
4
#!/usr/bin/python d={'a':1,'b':2,'c':3} key=raw_input("enter the key to check:") if key in d.keys(): print (d[key]) else: print key is not present
bc36e83cb948337ab012912032d943d6d3829669
sahthi/backup2
/backup_files/practice/aj.py
230
3.578125
4
print abs.__doc__ print int.__doc__ print raw_input.__doc__ def square(num): '''return the square value of input number. the input number must be an integer ''' return num ** 2 print square(2) print square.__doc__
8eabc5915442c74698de459405acdb8a6cb90fa6
sahthi/backup2
/backup_files/practice/rect.py
352
4.0625
4
#!/usr/bin/python class rectangle: def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): return self.breadth*self.length a=input("enter the length of rectangle:") b=input("enter the breadth of rectangle:") obj=rectangle(a,b) print("area of rectangle:",obj.area())
0166da43f2e816f1792ad7ee16271f7023d3cf47
sahthi/backup2
/backup_files/practice/sample/lis.py
243
4
4
'''def my_list(li): li.append(1) x=[0] my_list(x) x''' x=list(input("enter:")) y=input("enter element to multiply:") def multiply(x,y): for i,e in enumerate(x): x[i]=e*y return x print multiply(x,y)
465ce3bb60e8314ea7e91e9cc1971d0cbc977e4b
sahthi/backup2
/Practise/threadpro.py/sample.py
168
3.8125
4
f = open("sample.txt", "rb") s = f.readlines() print s f.close() f = open("newtext.txt", "wb") s.reverse() print s for item in s: print>>f, item f.close()
0ad1927eca95969c88b0f8aae5903e6ceb8c6d01
sahthi/backup2
/backup_files/practice/la.py
112
3.59375
4
l=input("enter the lower range:") u=input("enter the upper range:") a=[(x,x**2)for x in range(l,u+1)] print(a)
4fc6069a201cf338719bfec341d351415ed7d244
noway56/crawler_manage
/tests/test3.py
472
3.671875
4
def main(): my_list = [x for x in range(1, 11)] print(my_list) # my_sum = sum(my_list) my_sum = get_sum(my_list) print(f'连和为{my_sum}') my_multi = get_multi(my_list) print(f'连乘为{my_multi}') pass def get_sum(my_list): total = 0 for i in my_list: total += i return total def get_multi(my_list): multi = 1 for i in my_list: multi *= i return multi if __name__ == '__main__': main()
679fe79508d58c6dcc29f7b09ae6da800ab86c44
villares/py.processing-play
/Arduino/firmata_arduino_basico/firmata_arduino_basico.pyde
1,258
3.671875
4
""" Código para a leitura dos potenciômetros, requer biblioteca Firmata (Arduino) Você deve ajustar o valor de SERIAL para porta USB com seu Arduino No Linux pode ser que precise fazer sudo chmod 666 /dev/ttyUSB0 (ou equivalente). """ # ARDUINO add_library('serial') # import processing.serial.*; add_library('arduino') # import cc.arduino.*; for num, porta in enumerate(Arduino.list()): # Enumera portas seriais println(str(num)+":"+porta) # Mostra no console NUM_PORTA = 0 # Precisa mudar! Leia a lista no console para descobrir def setup(): size(600, 400) # tamanho da tela global arduino arduino = Arduino(this, Arduino.list()[NUM_PORTA], 57600) def draw(): background(0) # limpa a tela # CÍRCULO AMARELO POT_0 = arduino.analogRead(0) / 2 fill(255, 255, 0, 200) # fill(vermelho->255, verde->255, azul->0) -> Amarelo ellipse(200, # x 200, # y POT_0, # largura POT_0) # altura # CÍRCULO VERDE POT_5 = arduino.analogRead(5) / 2 fill(0, 255, 0, 200) # fill(vermelho->0, verde->255, azul->0) -> Verde ellipse(width - 200, # x 200, # y POT_5, # largura POT_5) # altura
3d8315bb51269fc8293e7e9e10c718ac6dfb07ee
villares/py.processing-play
/lista_de_pontos/lista_de_arestas_v2/lista_de_arestas_v2.pyde
5,633
3.65625
4
""" Alexandre B A Villares - http://abav.lugaralgum.com Brincando com uma lista de pontos, e agora arestas. Para rodar, instale o Processing Modo Python. Desenvolvido principalmente durante o Carnahacking 2017 no Garoa Hacker Clube - http://garoa.net.br e publicado em https://github.com/villares/py.processing-play """ pontos = set() # conjunto de Pontos arestas = [] # lista de Arestas tamanho = 30 # tamanho dos Pontos (influi no 'mouse over' e offset das setas) velocidade = 0.2 # para sorteio de velocidades iniciais random(+v,-v) pontos_iniciais = 5 def setup(): size(600, 600) strokeWeight(2) for _ in range(pontos_iniciais): x, y = random(width), random(height) cor = cor_rnd() # sorteia uma cor pontos.add(Ponto(x, y, cor)) # acrescenta um Ponto def draw(): background(128) # limpa a tela for aresta in arestas: # checa se há Arestas com Pontos já removidos if (aresta.p1 not in pontos) or (aresta.p2 not in pontos): arestas.remove(aresta) # nesse caso remove a Aresta também # print(aresta.p1, aresta.p2) else: # senão aresta.desenha() # desenha a Aresta com uma seta! for ponto in pontos: # cada Ponto desenha e atualiza sua posição ponto.desenha() ponto.move() def cor_rnd(alpha_value=128): # helper para sortear uma cor return color(random(128, 255), random(128, 255), random(128, 255), alpha_value) def mouseClicked(): # Sob clique do mouse seleciona/deseleciona Pontos ou Arestas for ponto in pontos: # para cada Ponto checa distância do mouse if dist(mouseX, mouseY, ponto.x, ponto.y) < tamanho * 3 / 2: ponto.sel = not ponto.sel # inverte status de seleção mouse = PVector(mouseX, mouseY) for aresta in arestas: # para cada Aresta checa o 'mouse over' if pointInsideLine(mouse, aresta.p1, aresta.p2, 6): aresta.sel = not aresta.sel # inverte status de seleção def keyPressed(): # Quando uma tecla é pressionada # barra de espaço acrescenta Pontos na posição atual do mouse if key == ' ': pontos.add(Ponto(mouseX, mouseY, cor_rnd())) # acrescenta Ponto no set # 'd' remove os Pontos previamente selecionandos com clique, marcados em preto. if key == 'd' and len(pontos) > 1: for ponto in pontos: if ponto.sel and len(pontos) > 1: # se a lista tiver pelo menos 2 pontos pontos.remove(ponto) # remove pontos selecionados def mouseDragged(): # quando o mouse é arrastado for ponto in pontos: # para cada Ponto checa distância do mouse if dist(mouseX, mouseY, ponto.x, ponto.y) < tamanho * 3 / 2: ponto.x, ponto.y = mouseX, mouseY # move o Ponto para posição do mouse class Ponto(): " Pontos num grafo, velocidade inicial sorteada, criam Arestas com outros Pontos " def __init__(self, x, y, cor=color(0)): self.x = x self.y = y self.z = 0 # para compatibilidade com PVector... self.cor = cor self.vx = random(-velocidade, velocidade) self.vy = random(-velocidade, velocidade) self.sel = False # se está selecionado self.cria_arestas() def __getitem__(self, i): return (self.x, self.y, self.z)[i] def desenha(self): fill(self.cor) if self.sel: stroke(0) else: noStroke() ellipse(self.x, self.y, tamanho, tamanho) if dist(mouseX, mouseY, self.x, self.y) < tamanho * 3 / 2: stroke(0) noFill() ellipse(self.x, self.y, tamanho * 3, tamanho * 3) fill(0) text(str(len(pontos))+" "+str(len(arestas)), self.x, self.y) stroke(255) def move(self): self.x += self.vx self.y += self.vy if not (0 < self.x < width): self.vx = -self.vx if not (0 < self.y < height): self.vy = -self.vy def cria_arestas(self): for ponto in pontos: nova_aresta = Aresta(ponto, self) arestas.append(nova_aresta) class Aresta(): """ Arestas contém só dois Pontos e podem ou não estar selecionadas """ def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.sel = False def desenha(self): x1, y1, x2, y2 = self.p1.x, self.p1.y, self.p2.x, self.p2.y d = dist(x1, y1, x2, y2) if self.sel: stroke(0) else: stroke(255) with pushMatrix(): translate(x2, y2) angle = atan2(x1 - x2, y2 - y1) rotate(angle) offset = -tamanho * .6 head = 6 line(0, offset, 0, -d - offset) line(0, offset, -head / 3, -head + offset) line(0, offset, head / 3, -head + offset) def pointInsideLine(thePoint, theLineEndPoint1, theLineEndPoint2, theTolerance): """" from Andreas Schlegel / http://www.sojamo.de """ dir = PVector(theLineEndPoint2.x, theLineEndPoint2.y) dir.sub(theLineEndPoint1) diff = PVector(thePoint.x, thePoint.y) diff.sub(theLineEndPoint1) insideDistance = diff.dot(dir) / dir.dot(dir) if(insideDistance>0 and insideDistance<1): closest = PVector(theLineEndPoint1.x, theLineEndPoint1.y) dir.mult(insideDistance) closest.add(dir) d = PVector(thePoint.x, thePoint.y) d.sub(closest) distsqr = d.dot(d) return (distsqr < pow(theTolerance,2)) return False
bc1e5d9f3349799b82f84e610af176bbbba116a5
Guie15/infNumeros
/treino.py
925
3.828125
4
from emoji import emojize from math import sqrt def linha(): print('-=-' * 14) linha() print('\033[34m Informações de Números!!\033[m') print('-=-' * 14) n=int(input(' Digite um número para sua tabuada: ')) limite_n = int(input(' Limite da Tabuada : ')) raiz= sqrt(n) linha() print(f' Sua raiz é {raiz}') print(emojize(' Sua tabuada é :pencil:' , use_aliases= True)) linha() for c in range(1, limite_n + 1): print(' {} x {:2} = {:2}'.format (n, c, n * c)) linha() u = n // 1 % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print(emojize(' analizando o número {}...:mag_right: '.format(n), use_aliases = True)) print( ' Sua unidade é {}'.format(u)) print(' Sua dezena é {}'.format(d)) print(' Sua centena é {}'.format(c)) print(' Seu milhar é {}'.format(m)) linha() res = n % 2 if res == 0: print(' O numero {} é PAR'.format(n)) else: print(' O numero {} é IMPAR'.format(n))
a4d4a66a22ad0d6bcc32995193620732a5991a0a
Rayd62/python3_practise
/2020_11/ex16_1.py
543
3.609375
4
#!/usr/bin/python from sys import argv script, filename = argv print(f"We're going to erase {filename}.") print("If you don't want to do that, press CTRL-C(^C).") print("IF you want to do that, press RETURN.") input("?") print(f"opening {filename} ...") fp = open(filename, 'w') print(f"Erasing {filename}") fp.truncate() print(f"Let's write some content in {filename}.") line1 = input("line1: ") line2 = input("line2: ") line3 = input("line3: ") fp.write(f"{line1}\n{line2}\n{line3}\n") print("We're going to close it.") fp.close()
504bbae5852c55f00281cc2af5a3d0383313944a
patelyash9775/Python-Work
/Leapyear.py
180
4.21875
4
year=int(input("Enter a year : ")) if(year%400==0 or (year%100!=0 and year%4==0)): print("Entered year is a leap year") else: print("Entered year is not a leap year")
451c5cd6f02d0500a2d40c7427876f4b9d7dbaee
patelyash9775/Python-Work
/Lower triangular matrix.py
373
3.5
4
n=int(input()) l=[] for i in range(n): row=list(map(int,input().split())) l.append(row) for i in range(n): for j in range(n): if(i<j): l[i][j]=0 if(j==n-1): print(l[i][j],end="") else: print(l[i][j],end=" ") if(i==n-1): print(end="") else: print()
c980d7814d270c5f4ab39a023b3fd81d4313046e
JuneJoshua/Python-MITx-
/MITx I/Problem Set 1/vowels.py
249
4.125
4
vowels = 0 s = str(input("Enter a string: ")) for falchion in s: if falchion == 'a' or falchion == 'e' or falchion == 'i' or falchion == 'o' or falchion == 'u': vowels += 1 else: vowels += 0 print("Number of vowels: " , vowels)
b3b0800b6add715999684c41393d1df9a636459d
All-I-Do-Is-Wynn/Python-Codes
/Codewars_Challenges/get_sum.py
547
4.28125
4
# Given two integers a and b, which can be positive or negative, # find the sum of all the integers between and including them and return it. # If the two numbers are equal return a or b. # Note: a and b are not ordered! def get_sum(a,b): sum = 0 if a < b: for x in range(a,b+1): sum += x else: for x in range(b,a+1): sum += x return sum # Shortened def get_sum2(a,b): return sum(range(min(a,b),max(a,b)+1)) if __name__ == '__main__': print(get_sum(0,2)) print(get_sum2(0,-2))
17f219735e8c34b60cba458f615647dba7b1cfba
rayvantsahni/after-MATH
/Euclidean Algorithm/gcd.py
280
3.875
4
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def main(): from functools import reduce numbers = list(map(float, input("Enter the numbers space separated\n").split())) print("\nGCD:", reduce(gcd, numbers)) main()
15fdbc037475927e58bf3b36a60c5cffc95264bc
rayvantsahni/after-MATH
/Rotate a Matrix/rotate_matrix.py
1,523
4.40625
4
def rotate(matrix, n, d): while n: matrix = rotate_90_clockwise(matrix) if d else rotate_90_counter_clockwise(matrix) n -= 1 return matrix def rotate_90_counter_clockwise(matrix): """ The function rotates any square matrix by 90° counter clock-wise. """ for row in matrix: row.reverse() n = len(matrix) for row in range(n): for col in range(row, n): matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col] return matrix def rotate_90_clockwise(matrix): """ The function rotates any square matrix by 90° clock-wise. """ n = len(matrix) for row in range(n): for col in range(row, n): matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col] for row in matrix: row.reverse() return matrix if __name__ == "__main__": # matrix_1 = [[1]] # matrix_2 = [[1, 2], # [3, 4]] matrix_3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # matrix_4 = [[1, 2, 3, 4], # [5, 6, 7, 8], # [9, 10, 11, 12], # [13, 14, 15, 16]] number_of_rotations = int(input("Enter the number of times you want to rotate the matrix:\n")) print("To rotate COUNTER-CLOCKWISE enter 0, OR\nTo rotate CLOCKWISE enter 1.") direction = int(input()) print("Rotated Matrix:") for row in (rotate(matrix_3, number_of_rotations % 4, direction % 2)): print(row)
55593ab0e18b4b617310e5b4d23bc46b306b15b8
rayvantsahni/after-MATH
/Duck Numbers/duck_number.py
211
3.984375
4
def is_duck_number(s): return "0" in str(int(s)) def main(): s = input("Enter number to check for Duck Number\n") print("Is a Duck Number" if is_duck_number(s) else "Is NOT a Duck Number") main()
9a651902f1820bcfa5b785894af03a48cbb081c5
rayvantsahni/after-MATH
/Fast Exponentiation/fast_exponentiation.py
442
4.03125
4
def calculate_power(base, power): if not power: return 1 if not power % 2: return calculate_power(base, power // 2) * calculate_power(base, power // 2) else: return calculate_power(base, power // 2) * calculate_power(base, power // 2) * base if __name__ == "__main__": a = int(input("Enter base: ")) n = int(input("Enter exponent: ")) print("{}^{} = {}".format(a, n, calculate_power(a, n)))
aed25f8f014c605b35ff8c26ff4a20023a672e30
bloodycoder/VirtualTkinter
/实例/简易计算器.py
415
3.59375
4
#vitual tkinter from Tkinter import * from ttk import * root=Tk() def calcu(): cal.set(eval(cal.get())) NONE=StringVar() Label(text= "calculator!",foreground="red").place(x=232,y=67) cal=StringVar() Entry(textvariable= cal,foreground="red",background="white").place(x=144,y=122) Button(text= "click",command=calcu).place(x=331,y=116) root.geometry("500x500+0+0") root.mainloop()
4b456009148aef6ebf47b94952a37eaefa42598a
LukumBest/VSA-VU-2018
/proj01_ifelse/proj01.py
12,560
4.3125
4
# Name: # Date: # proj01: A Simple Program # Part I: # This program asks the user for his/her name and grade. #Then, it prints out a sentence that says the number of years until they graduate. # Part II: # This program asks the user for his/her name and birth month. # Then, it prints a sentence that says the number of days and months until their birthday # If you complete extensions, describe your extensions here! #name = raw_input("What's your name? ") #name = name[0:1].upper() + name[1:].lower() #grade = int(raw_input("What grade are you in? ")) #years = 13 - grade #print name + ", you will graduate from high school in " + str(years) + " years." #print "End of Program 1." #current_month = 6 #current_day = 12 #name_2 = raw_input("What's your name? ") #name_2 = name_2[0:1].upper() + name_2[1:].lower() #birth_month = int(raw_input("Enter the number of your birth month. ")) #birth_day = int(raw_input("What day of the month were you born? ")) #if birth_month > current_month: #months = int(birth_month - current_month) #if birth_day > current_day: #days = int(birth_day - current_day) #print name_2 + ", your birthday is in " + str(months) + " months and " + str(days) + " days!" #if birth_month < current_month: #months_2 = int(birth_month + current_month) #if birth_day < current_day: #days_2 = int(30 - (current_day - birth_day)) #print name + ", your birthday is in " + str(months_2) + " months and " + str(days_2) + " days!" #print "End of Program 2." #age = int(raw_input("How old are you? ")) #if age > 16: #print "You can see R rated movies. Great." #elif age < 8: #print "You should be allowed to see PG movies." #elif age < 14: #print "You should be allowed to see PG-13 movies." number = int() letter = str() import time import random smalley = 18 liek = 7 talk = 1 while talk == 1: name_3 = raw_input("Hi! What's your name? ") name_3 = name_3[0:1].upper() + name_3[1:].lower() if len(name_3) > 10 and len(name_3) < 30: time.sleep(1.2) print "That's a long name." time.sleep(1.4) elif len(name_3) > 30: time.sleep(2.5) print "I don't think that's even a name." time.sleep(1.8) print "My name's Macintosh." time.sleep(1) state = (raw_input("What state are you from? ")) time.sleep(0.45) if state == "alabama" or state == "Alabama": time.sleep(0.45) print "Neat." elif state == "alaska" or state == "Alaska": time.sleep(0.45) print "The lights there are so beautiful! I've been a couple of times myself." time.sleep(0.5) elif state == "arizona" or state == "Arizona": time.sleep(0.45) print "Neat." time.sleep(0.5) elif state == "arkansas" or state == "Arkansas": time.sleep(0.45) print "Nice." time.sleep(0.5) elif state == "florida" or state == "Florida": time.sleep(0.45) print "The Sunshine State with the beautiful beaches and great seafood? I went there and I loved it!" time.sleep(0.5) elif state == "Texas" or state == "texas": time.sleep(0.45) print "That's where I'm from." time.sleep(0.5) elif state == "colorado" or state == "Colorado": time.sleep(0.8) ur = raw_input("Oh. No offense, but isn't that where the crackheads are? ") if ur == "yes" or ur == "Yes": time.sleep(0.38) print "Ha! Thought so." time.sleep(0.5) else: time.sleep(1) print "Oh." time.sleep(0.6) elif state == "california" or state == "California": time.sleep(0.45) city = raw_input("Where in California? ") if city == "Las Vegas" or city == "las vegas" or city == "Vegas": time.sleep(0.4) print "With the famed Vegas Strip, and the casinos and stuff? I've never been there myself." time.sleep(0.5) else: time.sleep(0.45) print "Cool." time.sleep(0.45) while liek == 7: ui = raw_input("Do you want to play a game? ") if ui[0:].lower == "no": raw_input("Why not? I haven't talked to anyone in a long time. ") print "Oh. Ok. Bye I guess." talk = talk - 1 break if ui == "yes" or ui == "Yes": time.sleep(0.2) print "Yay! I'm good at most games as long as they're only virtual." ui2 = raw_input("Which game do you want to play? (1, 2, or 3.) ") if ui2 == "1": time.sleep(0.45) print "Great! Let's get started." ui_3 = raw_input("Game 1 is rock, paper, scissors. Do you still want to play? ") if ui_3 == "no" or ui_3 == "No": time.sleep(1) print "Oh. Ok." else: time.sleep(0.45) print "Great!" game = 2 print "Rock, Paper, Scissors" loop = 0 while game == 2: u_1 = raw_input("Player 1, enter either rock, paper, or scissors. ") u_2 = raw_input("Player 2, enter either rock, paper, or scissors. ") if u_1 == "rock" or u_1 == "Rock": if u_2 == "paper" or u_2 == "Paper": print "Player 2 wins!" elif u_1 == "Rock" or u_1 == "rock": if u_2 == "scissors" or u_2 == "Scissors": print "Player 1 wins!" elif u_1 == "rock" or u_1 == "Rock": if u_2 == "Rock" or u_2 == "rock": print "Tie!" elif u_1 == "paper" or u_1 == "Paper": if u_2 == "rock" or u_2 == "Rock": print "Player 1 wins!" elif u_1 == "paper" or u_1 == "Paper": if u_2 == "paper" or u_2 == "Paper": print "Tie!" elif u_1 == "paper" or u_1 == "Paper": if u_2 == "scissors" or u_2 == "Scissors": print "Player 2 wins!" elif u_1 == "scissors" or u_1 == "Scissors": if u_2 == "rock" or u_2 == "Rock": print "Player 2 wins!" elif u_1 == "scissors" or u_1 == "Scissors": if u_2 == "paper" or u_2 == "Paper": print "Player 1 wins!" elif u_1 == "scissors" or u_1 == "Scissors": if u_2 == "scissors" or u_2 == "Scissors": print "Tie!" redo = raw_input("Would you like to play again?") if redo == "yes" or redo == "Yes": game = 2 else: game = game - 1 liek = liek + 1 elif ui2 == "2": print "Great! Let's get started." time.sleep(.5) ui_4 = raw_input("Game 2 is Guess my number. Do you still want to play?") if ui_4 == "no" or ui_4 == "No": print "Oh." else: print "Great! Let's begin." game = 1 counter = 0 num = int(random.randint(1, 9)) while game == 1 and counter < 10: if counter > 9: print "You managed to not guess the number even though you used over 9 guesses. You lose." goto(201) ug = int(raw_input("Enter a number from 1 to 9, or type 0 to end. ")) if ug == number: ug = int(ug) counter = counter + 1 if ug == 0: game = game - 1 elif ug > num: print "You guessed too high!" elif ug < num: print "You guessed too low!" elif ug == num: ui = raw_input(("Great, you won in ") + str(counter) + (" guess(es)! Do you want to play again? ")) if ui == "No" or ui == "no": print "Oh. Okay then." game = game - 1 liek = liek + 1 else: game = 1 num = int(random.randint(1, 9)) counter = 0 else: counter = counter + 0 print "A number, not words or letters." elif ui2 != "1" and ui2 != "2" and ui2 != "3": print "That's not an option. Let's play game 3." time.sleep(.5) continue if ui2 == "3": print "This game is called I Will Predict Your Birthday. I'm really good at it. Let's begin." time.sleep(.6) while smalley == 18: bmon = (raw_input("Tell me the number of your birth month. ")) if len(bmon) > 2 or int(bmon) > 12: print "That's not a month." break bmon = int(bmon) bmon2 = int(bmon + 18) time.sleep(1.1) print "Add 18 to that. This gives you " + str(bmon2) + "." bmon3 = int(bmon2 * 25) time.sleep(1.1) print "Multiply that by 25. Now you have " + str(bmon3) + "." bmon4 = int(bmon3 - 333) time.sleep(1.1) print "Subtract 333 from that. That leaves you with " + str(bmon4) + "." bmon5 = int(bmon4 * 8) time.sleep(1.1) print "Multiply the number by 8. Now, it's " + str(bmon5) + "." bmon6 = int(bmon5 - 554) time.sleep(1.1) print "Subtract 554 from that. You're left with " + str(bmon6) + "." bmon7 = int(bmon6 / 2) time.sleep(1.1) print "Divide " + str(bmon6) + " by 2. Now you have " + str(bmon7) + "." time.sleep(1.1) bdate = raw_input("Tell me what day of the month you were born. ") if len(bdate) > 2 or int(bdate) > 31: print "That's not a day of any month." break bdate = int(bdate) bdamon = int(bmon7 + bdate) time.sleep(1) print "Add your day of birth to " + str(bmon7) + ". You now have " + str(bdamon) + "." bdamon2 = int(bdamon * 5) time.sleep(1) print "Multiply " + str(bdamon) + " by 5. You have " + str(bdamon2) + "." bdamon3 = int(bdamon2 + 692) time.sleep(1) print "Subtract 692 and you're left with " + str(bdamon3) + "." bdamon4 = int(bdamon3 * 20) time.sleep(1) print "Now multiply " + str(bdamon3) + " by 20 and you get " + str(bdamon4) + "." time.sleep(1) l2d = raw_input("Give me the last two numbers of your birth year. ") if len(l2d) > 2: print "I said the last two numbers of your birth year. You're making it hard for me." break l2d = int(l2d) bdale = int(bdamon4 + l2d) time.sleep(1) print "Then add " + str(l2d) + " to " + str(bdamon4) + " and you get " + str(bdale) + "." bdale_ultimate = int(bdale - 32940) time.sleep(1) print "And finally, subtract 32,940 from " + str(bdale) + " to get " + str(bdale_ultimate) + "." time.sleep(1) if l2d < 10: print "Your birthdate is " + str(bmon) + "/" + str(bdate) + "/200" + str(l2d) + "." else: print "Your birthdate is " + str(bmon) + "/" + str(bdate) + "/19" + str(l2d) + "." play = raw_input("Do you want to play again?") if play == "no" or play == "No": smalley = smalley + 1 else: smalley = 18
9aeda27b9286de27061c8c425b75b5e15d24f6f4
Harsh5606/PythonTraining
/Assignment 1/q2.py
156
4.125
4
# 2) Assign String to x variable in DD-MM-YYYY format extract and print Year from String. x="19-08-2021" print("Printing Only Year Frim String",x[6:])
1adada8a6b7d5332bed5c37d411571ca2ab1eae8
ursawd/springboardexercises
/Unit18/Unit18-2/fs_4_reverse_vowels/reverse_vowels.py
1,200
4.25
4
def reverse_vowels(s): """Reverse vowels in a string. Characters which re not vowels do not change position in string, but all vowels (y is not a vowel), should reverse their order. >>> reverse_vowels("Hello!") 'Holle!' >>> reverse_vowels("Tomatoes") 'Temotaos' >>> reverse_vowels("Reverse Vowels In A String") 'RivArsI Vewols en e Streng' >>> reverse_vowels("aeiou") 'uoiea' >>> reverse_vowels("why try, shy fly?") 'why try, shy fly?' """ vowels = "aeiou" new_s = list(s) stop = len(s) for i in range(0, len(s) - 1, 1): # start,stop,index if s[i] in vowels: for j in range(stop - 1, -1, -1): if j + 1 == i: return "".join(new_s) if new_s[j] in vowels: new_s[j], new_s[i] = new_s[i], new_s[j] stop = j break return "".join(new_s) # print(reverse_vowels("1a2e3i4o")) # # 1d2c3b4a # print(reverse_vowels("Hello!")) # print(reverse_vowels("Tomatoes")) # #'Temotaos' # print(reverse_vowels("Reverse Vowels In A String")) # #'RivArsI Vewols en e Streng' # print(reverse_vowels("aeiou"))
1cfa1fc1cd7939f564382c105b359a8ce71a90f8
harxingxing/pythonStudy
/history/day2/index.py
945
3.78125
4
# !/user/local/python3/bin ## 字符串格式化 print('我叫%s,今年%d岁了'%('小明', 20)) ''' 知识点: in:如果在指定的序列中找到值返回 True,否则返回 False,not in与之相反。a in b标识a在b里。p.Python成员运算符 is:判断两个标识符是不是引用自一个对象,in not与之相反。x is y, 类似 id(x) == id(y)。p.Python身份运算符 is 与 == 区别:is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。p.Python身份运算符 在不同的机器上浮点运算的结果可能会不一样。在整数除法中,除法 / 总是返回一个浮点数,如果只想得到整数的结果,丢弃可能的 分数部分,可以使用运算符 // p.Python 数字运算 // 得到的并一定是整数类型的数,它跟分母分子的数据类型有关。// p.Python 数字运算 todo:隔过去:列表,元组,字典 '''
1a725964b2cb0b3c01658c3f41c462a5caa346dc
CRomanIA/Python_Undemy
/Seccion_19_Libreria_Numpy/Secc19_cap71_Matrices_Transpuestas.py
357
3.953125
4
#Arrays o matrices transpuestas (cambiar ordenadamente las filas por las columnas) import numpy as np #se crea un array, arange(para dar rango de 0 a 14) reshape(fila,columna) para organizar array = np.arange(15).reshape((3,5)) print(array) print(array[1][1]) #TODO Transponer: cambiar las filas de las columnas array_trans = array.T print(array_trans)
3efbe784d9ead8c3e5307b1b26a7a1004a3386c1
CRomanIA/Python_Undemy
/Seccion_19_Libreria_Numpy/Sec19_cap68_Arrays.py
1,006
3.828125
4
#Librerias Numpy #TODO: Es importante esto, para instalar la libreria debes en terminal ingresar pip install numpy import numpy as np #arrays con condicion cero(donde toma 4 valores) print(np.zeros(4)) #arrays con condicion uno(donde toma 4 valores) print(np.ones(4)) #arrays con condicion de rango [igual a range] (donde toma 5 valores, en orden secuencial desde el cero) print(np.arange(5)) #arrays con condicion de rango [igual a range] (donde toma 10 valores, en orden secuencial desde el cero) print(np.arange(10)) #arrays con condicion de rango [igual a range] (donde toma valores donde inicia en el 2, hasta el 20 de 3 en 3) print(np.arange(2,20,3)) #Construir un array a traves de una lista lista1 = [1,2,3,4] array1 = np.array(lista1) print(lista1) print(array1) lista1 = [1,2,3,4] lista2 = [5,6,7,8] lista_doble = lista1, lista2 print(lista_doble) array_doble = np.array(lista_doble) print(array_doble) #ver forma que tiene el array print(array_doble.shape) print(array_doble.dtype)
6aeb4f6cb0de29dbfd6fabc3a57b2e099b589963
CRomanIA/Python_Undemy
/Seccion_9_Modulos-Librerias/sec9cap29.py
248
3.71875
4
#Pip : es un gestor de paquetes (Librerias) y modulos para python, un modulo es una libreria de python que puedes incluir en el proyecto import camelcase camel = camelcase.CamelCase() texto = "el luigi Se la come doblada" print (camel.hump(texto))
c93b30cbc764609d46114bfddc543283659c160d
CRomanIA/Python_Undemy
/Seccion_17_Pruebas_Automaticas/Sec17cap63.py
714
3.734375
4
#Doctest - Generar pruebas dentro de la documentacion def sumar(numero1, numero2): """ Esto es la documentacion de este metodo Recibe dos numeros como parametros y devuelve su suma Se genera la prueba en los comentarios (No olvidar en el mayor que, darle un espacio) (suma correcta) >>> sumar(4,3) 7 (suma correcta) >>> sumar(5,4) 9 (suma incorrecta) >>> sumar(1,3) 7 """ return numero1 + numero2 resultado = sumar(2,4) print(resultado) #ir al cmd y dirigirse al directorio donde está este metodo. ejecutarlo por consola y ver el resultado (debiese dar 6) #Para ejecutar prueba de comentario en la consola del cmd... import doctest doctest.testmod()
e4feb584223c8092289627479e9244771c55cc5d
CRomanIA/Python_Undemy
/Seccion_22_Tratamiento_De_Datos/Secc22_cap88_Concatenacion_Dataframes.py
998
3.8125
4
#Concatenacion de Arrays, Series y Dataframes import pandas as pd import numpy as np array1 = np.arange(9).reshape(3,3) #print(array1) print(np.concatenate([array1,array1])) #Para concatenar hacia la derecha print(np.concatenate([array1,array1],axis=1)) #Como concatenar una serie serie1 = pd.Series([1,2,3], index=['a','b','c']) serie2 = pd.Series([1,2,3], index=['d','e','f']) print(serie1) print(serie2) print(pd.concat([serie1,serie2])) #Para que en la concatenacion, te muestre el valor de cada serie print(pd.concat([serie1,serie2], keys=['serie1','serie2'])) #Para concatenar dataframes dataframe1 = pd.DataFrame(np.random.rand(3,3), columns=['a','b','c']) print(dataframe1) dataframe2 = pd.DataFrame(np.random.rand(2,3), columns=['a','b','c']) print(dataframe2) print(pd.concat([dataframe1,dataframe2])) #Para enmumerar correctamente el index, que por la concatenacion se encuentra con los valores de las dos tablas print(pd.concat([dataframe1,dataframe2], ignore_index=True))
14f9f69ff6c9c63111a097411eccda0a64db058c
QiangChen-CG/mercurial
/src/math_objects/geometry.py
9,491
3.640625
4
import math import random import numpy as np from math_objects import functions as ft """ Bunch of convenience classes which are not really used anymore. Except Point. Perhaps the rest will come in handy at a later stage. """ class Coordinate(object): """ Class that models a coordinate in Carthesian space. Used as a base class for points, velocities and sizes. Implemented some basic 'magic' methods to facilitate the use of basic operators """ def __init__(self, x): """ :param x: iterable of coordinates. Requires a list of length 2. """ self.array = np.asarray(x, dtype='float64') self.type = self.__class__.__name__ angle = property(lambda s: math.atan2(s[1], s[0])) def __len__(self): return len(self.array) def __iter__(self): return iter(self.array) def __getitem__(self, i): return self.array[i] def __add__(self, other): return Point(self.array + other.array) def __sub__(self, other): return Point(self.array - other.array) def __mul__(self, other): # Change to self.__class__ return Point(self.array * other) def __truediv__(self, other): return Point(self.array / other.array) def __repr__(self): return "%s(%s)" % (self.type, ", ".join("%.2f" % f for f in self.array)) def is_zero(self): """ Check whether coordinates are within tolerance of zero point :return: True if 2-norm of coordinate is smaller than epsilon """ return ft.norm(self.array[0], self.array[1]) < ft.EPS class Size(Coordinate): """ Class that models a size. Sizes are an extension of coordinates that cannot be negative. """ def __init__(self, x): super().__init__(x) if any(self.array < 0): raise ValueError("Negative size specified") def random_internal_point(self): """ Provides a random internal point within the size :return: Point with positive coordinates both smaller than size """ return Point(np.array([random.random() * dim for dim in self.array])) class Point(Coordinate): """ Class that models a point within a plane. """ x = property(lambda s: s[0]) y = property(lambda s: s[1]) class Velocity(Coordinate): """ Class that models a velocity in the plane. """ x = property(lambda s: s[0]) y = property(lambda s: s[1]) def rescale(self, max_speed=5.): if not self.is_zero(): self.array *= (max_speed / ft.norm(self.array[0], self.array[1])) class Interval(object): """ Class that models an interval """ def __init__(self, coords): self.array = np.asarray(coords) self.length = coords[1] - coords[0] if self.length < 0: raise ValueError("Interval start larger than interval end") def random(self): """ Returns a random double within the interval :return: """ return np.random.random() * self.length + self.array[0] begin = property(lambda s: s[0]) end = property(lambda s: s[1]) def __getitem__(self, item): return self.array[item] def __contains__(self, item: float): return self.array[0] <= item <= self.array[1] def __repr__(self): return "Interval %s" % self.array class LineSegment(object): def __init__(self, point_list): """ Initializes a line segment based on a list of Points. :param point_list: List (or other iterable) of Points :return: Line segment """ self.array = np.asarray(point_list) self.color = 'gray' length = property(lambda s: ft.norm(s.begin[0] - s.end[0], s.begin[1] - s.end[1])) begin = property(lambda s: s[0]) end = property(lambda s: s[1]) def get_point(self, value): """ Regarding the line segment as a 1D parameter equation with domain [0,1], this method returns the coordinates for parameter value :param value: parameter in [0,1] :return: corresponding Point on line segment """ if 0 > value < 1: raise ValueError("Value %.2f must lie between 0 and 1" % value) return self.begin + value * (self.end - self.begin) def crosses_obstacle(self, obstacle, open_sets=False): """ Checks whether the line crosses the rectangular obstacle. Novel implementation based on hyperplanes and other linear algebra (*proud*) :param obstacle: The rectangular obstacle under consideration :param open_sets: Whether it counts as an intersection if the line passes inside of the obstacle (open_sets = True) or also counts when it passes through the obstacle boundary (open_sets = False) :return: True if line crosses obstacle, false otherwise """ line_array = np.array([self.begin, self.end]) rect_array = np.array([[np.min(line_array[:, 0]), np.min(line_array[:, 1])], [np.max(line_array[:, 0]), np.max(line_array[:, 1])]]) obs_array = np.array([obstacle.begin.array, obstacle.end.array]) intersects = ft.rectangles_intersect(rect_array[0], rect_array[1], obs_array[0], obs_array[1], open_sets) if not intersects: return False f = ft.get_hyperplane_functional(line_array[0], line_array[1]) obs_points = np.array([point.array for point in obstacle.corner_list]) point_result = f(obs_points[:, 0], obs_points[:, 1]) if np.sum(np.sign(point_result)) in [-4, 4]: return False else: return True def __getitem__(self, item): return self.array[item] def __add__(self, other): return LineSegment(self.array + other.array) def __sub__(self, other): return LineSegment(self.array - other.array) def __mul__(self, other): return LineSegment(self.array * other) def __truediv__(self, other): return LineSegment(self.array / other) def __lt__(self, other): if not type(self) == type(other): raise AttributeError("Paths must be compared to other Paths") return self.length < other.length def __repr__(self): return "LineSegment from %s to %s" % (Point(self.begin), Point(self.end)) class Path(object): """ Wrapper around a sequence of line segments. Paths are immutable """ sample_length = 4 def __init__(self, line_segment_list): """ Check if all the lines in the line segment list are connected. Also samples the points on the lines with a resolution of @sample_length :param line_segment_list: list of lines :return: new Path object """ if not line_segment_list: raise ValueError("No line segments in initialization") self.list = line_segment_list for i in range(len(line_segment_list) - 1): self.check_lines_connected(line_segment_list[i], line_segment_list[i + 1]) num_samples = math.ceil(self.length / Path.sample_length) + 1 self.sample_points = np.zeros([num_samples, 2]) sampled_line_index = 0 sampled_line = self.list[sampled_line_index] sample = 0 sampled_line_length = sampled_line.length for i in range(num_samples - 1): if sample > sampled_line_length: sample -= sampled_line_length sampled_line_index += 1 sampled_line = self.list[sampled_line_index] sampled_line_length = sampled_line.length self.sample_points[i] = self.list[sampled_line_index].get_point(sample / sampled_line_length) sample += Path.sample_length self.sample_points[num_samples - 1] = self.list[-1].end @property def length(self): """ Summed length of all line segments :return: sum of line segments 2-norms """ return sum([line.length for line in self.list]) def __len__(self): return len(self.list) @staticmethod def check_lines_connected(ls1: LineSegment, ls2: LineSegment): """ Returns true if last line end connects (within epsilon accuracy) to new line begin :param ls1: Line segment whose end matches ls2's begin :param ls2: Line segment whose begin matches ls1's end :return: True if lines connect, False otherwise """ connected = np.allclose(ls1.end, ls2.begin) if not connected: raise AssertionError("%s & %s do not connect" % (ls1, ls2)) def __getitem__(self, item): return self.list[item] def pop_next_segment(self): """ Returns the first line segment of the path and removes it from the path list. :return: Line segment """ return self.list.pop(0) def get_sample_point(self, i): return self.sample_points[min(i, self.sample_points.shape[0] - 1)] def __bool__(self): """ :return: True if Path has any elements, False otherwise. """ return bool(self.list) __nonzero__ = __bool__ def __str__(self): """ String representation of collected line segment :return: Joined string representation for each line segment """ return "Path:\n%s" % "\n".join([str(ls) for ls in self.list])
c0ee8e526f8165f410f7a0e92d9a335e406a15da
ShanmukhaSrinivas/python-75-hackathon
/log.py
326
4
4
#Logging the Exceptions, errors and warnings import logging logging.basicConfig(filename = 'log.txt', level = logging.WARNING) try: a = int(input('Enter a number:')) b = int(input('Enter another number:')) c = a/b except Exception as e: logging.exception(e) else: print('The result of division is', c)
5768c55600fd738801f17853ff3b2405baa300fc
ShanmukhaSrinivas/python-75-hackathon
/private_variableIn_class.py
473
3.765625
4
#Class with a private variable class Bank: def __init__(self): self.accno = 1001 self.name = 'Ganesh' self.bal = 5000.0 self.__loan = 1500000.00 def display(self): print('Acc.No= ', self.accno) print('Name= ', self.name) print('Balance= ', self.bal) b = Bank() b.display() print('Acc.No= ', self.accno) print('Name= ', self.name) print('Balance= ', self.bal) print('Bank_Loan=', self._Bank__loan)
12e6dc66ff42c823a1d4c4eb21a21a6a2b82f6fe
nathan-osman/django-archive
/django_archive/util/file.py
969
3.609375
4
""" Utility class for working with temporary files """ import os from tempfile import mkstemp class MixedModeTemporaryFile: """ Temporary file that can be opened multiple times in different modes """ def __init__(self): self._fd, self._filename = mkstemp() def __enter__(self): return self def __exit__(self, exc_type, exc_val, traceback): self.close() def open(self, mode): """ Open the file in the specified mode """ return os.fdopen(self._fd, mode, closefd=False) def close(self): """ Close the temporary file (and delete it) """ os.close(self._fd) os.unlink(self._filename) def rewind(self): """ Seek to the beginning of the file """ os.lseek(self._fd, 0, os.SEEK_SET) def size(self): """ Return the size of the file """ return os.stat(self._fd).st_size
c6d2d5095d319fdfe43ad2dc712cd97cbe44cb9e
rohit-kuma/Python
/List_tuples_set.py
1,822
4.1875
4
courses = ["history", "maths", "hindi"] print(courses) print(len(courses)) print(courses[1]) print(courses[-1]) print(courses[0:2]) courses.append("art") courses.insert(1, "Geo") courses2 = ["Art", "Education"] print(courses) #courses.insert(0, courses2) #print(courses) courses2.extend(courses) print(courses2) print(courses2.pop()) print(courses2) courses2.remove("Geo") print(courses2) courses2.reverse() print(courses2) courses2.sort() print(courses2) num = [5, 1, 4] num.sort(reverse=True) print(num) #without altering the original num2 = sorted(num) print(num2) print(min(num2)) print(max(num2)) print(sum(num2)) print(num2.index(4)) print(4 in num2) for i in courses2: print(i) for index, courses in enumerate(courses2): print(index, courses) for index, courses in enumerate(courses2, start = 1): print(index, courses) courses_str = ", ".join(courses2) print(courses_str) new_list = courses_str.split(", ") print(new_list) #Tuples #List are mutables tuples are not # Mutable print("Mutable List") list_1 = ['History', 'Math', 'Physics', 'CompSci'] list_2 = list_1 print(list_1) print(list_2) list_1[0] = 'Art' print(list_1) print(list_2) print("Immutable List") # Immutable tuple_1 = ('History', 'Math', 'Physics', 'CompSci') tuple_2 = tuple_1 print(tuple_1) print(tuple_2) # tuple_1[0] = 'Art' print(tuple_1) print(tuple_2) print("Sets") # Sets cs_courses = {'History', 'Math', 'Physics', 'CompSci'} art_courses = {"Math", "GEO", "Physics"} print(cs_courses) print(art_courses) print(cs_courses.intersection(art_courses)) print(cs_courses.difference(art_courses)) print(cs_courses.union(art_courses)) # Empty Lists empty_list = [] empty_list = list() # Empty Tuples empty_tuple = () empty_tuple = tuple() # Empty Sets empty_set = {} # This isn't right! It's a dict empty_set = set()
4e2e110df413222d58718090475bc2700eafe9d7
rohit-kuma/Python
/OOPS/normal_class_static_method.py
1,315
3.828125
4
class Employee: num_emp = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_emp += 1 def fullname(self): #regular method # print(self.first + ' ' + self.last) return f'{self.first} {self.last}' def apply_raise(self): self.pay = int(self.pay * Employee.raise_amount) @classmethod def set_raise_amount(cls, amt): #class method cls.raise_amount = amt @classmethod def from_string(cls, emp_string): first, last, pay = emp_string.split('-') return Employee(first, last, pay) @staticmethod #no relation to class variables or instances, nly logical connection def isworkday(day): if day.weekday() == 5 or day.weekday() == 6: return False return True emp1 = Employee('Rohit1', 'Kumar1', 50001) emp2 = Employee('Rohit2', 'Kumar2', 50002) Employee.set_raise_amount(1.05) # Employee.raise_amount = 1.05 print(Employee.raise_amount) print(emp1.raise_amount) print(emp2.raise_amount) emp3 = Employee.from_string('Rohit3-Kumar3-50003') print(emp3.email) import datetime my_date = datetime.date(2017, 7, 11) print(Employee.isworkday(my_date))
c53f6e0a2497c08ddda641471dc72ce572be4792
bayusuarsa/PDF_to_Audibook_2
/test.py
968
3.734375
4
import tkinter as tk from tkinter import filedialog from PIL import Image watermark = Image.open("image/image_7.jpg") def browse_for_image(): chosen_image = tk.filedialog.askopenfilename(title="Choose a file") return chosen_image def add_watermark(): file = browse_for_image() image = Image.open(file) img_x = image.size[0] img_y = image.size[1] mark_x = watermark.size[0] mark_y = watermark.size[1] box = (img_x - mark_x, img_y - mark_y, img_x, img_y) watermark.convert("RGBA") paste_mask = watermark.split()[3].point(lambda i: i * 50 / 100) image.paste(watermark, box, mask=paste_mask) image.show() # config the window window = tk.Tk() window.title("WaterMark Adder") window.geometry("400x100") # Title label: select_img_label = tk.Label(text="Select a photo:") select_img_label.pack() select_img_button = tk.Button(text="Add watermark", command=add_watermark) select_img_button.pack() window.mainloop()
598a1c47c454c6e31408824cdec50d9d4a262cef
mswinkels09/Critters_Croquettes_server
/animals/petting_animals.py
2,463
4.3125
4
# import the python datetime module to help us create a timestamp from datetime import date from .animals import Animal from movements import Walking, Swimming # Designate Llama as a child class by adding (Animal) after the class name class Llama(Animal): # Remove redundant properties from Llama's initialization, and set their values via Animal def __init__(self, chip_number, name, species, shift, food ): Animal.__init__(self, chip_number, name, species, food) self.shift = shift # stays on Llama because not all animals have shifts self.walking = True def feed(self): print(f'{self.name} was not fed {self.food} on {date.today().strftime("%m/%d/%Y")}') class Goose(Animal, Walking, Swimming): def __init__(self, name, species, food): # No more super() when initializing multiple base classes Animal.__init__(self, name, species, food) Swimming.__init__(self) Walking.__init__(self) # no more self.swimming = True ... def honk(self): print("The goose honks. A lot") # run is defined in the Walking parent class, but also here. This run method will take precedence and Walking's run method will not be called by Goose instances def run(self): print(f'{self} waddles') def __str__(self): return f'{self.name} the Goose' class Goat(Animal): def __init__(self, chip_number, name, species, shift, food ): Animal.__init__(self, chip_number, name, species, food) self.shift = shift self.walking = True def feed(self): print(f'{self.name} was enthusiastically fed {self.food} on {date.today().strftime("%m/%d/%Y")}') class Donkey(Animal): def __init__(self, chip_number, name, species, shift, food ): Animal.__init__(self, chip_number, name, species, food) self.shift = shift self.walking = True def feed(self): print(f'{self.name} was obnoxiously fed {self.food} on {date.today().strftime("%m/%d/%Y")}') class Pig(Animal): def __init__(self, chip_number, name, species, shift, food ): Animal.__init__(self, chip_number, name, species, food) self.shift = shift self.walking = True class Ox(Animal): def __init__(self, chip_number, name, species, shift, food ): Animal.__init__(self, chip_number, name, species, food) self.shift = shift self.walking = True
4ac0211c37a552b429614b3f8165c139611c1447
Roneetshr/C98
/calculater.py
229
3.84375
4
def calculate(numb1,numb2): numbers = input("This sum will be multiplyed: ") ans = 0 for line in numbers: ans = ans + numb1*numb2 print("The answer is") print(ans) calculate(13,24)
c27892b565bb1731b02f2fa7f6258419bad34edd
Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges
/Day42_RedactText.py
1,421
4.6875
5
# Day 42 Challenge: Redacting Text in a File # Sensitive information is often removed, or redacted, from documents before they are released to the public. # When the documents are released it is common for the redacted text to be replaced with black bars. In this exercise # you will write a program that redacts all occurrences of sensitive words in a text file by replacing them with # asterisks. Your program should redact sensitive words wherever they occur, even if they occur in the middle of #another word. The list of sensitive words will be provided in a separate text file. Save the redacted version of the # original text in a new file. The names of the original text file, sensitive words file, and redacted file will all # be provided by the user... #Main fname = input("Enter Source File Name:") inf = open(fname, "r") senfile = input("Enter File name contains Sensitive words:") fsen = open(senfile, "r") words = [] for line in fsen.readlines(): line = line.rstrip() line = line.lower() if line != " ": words.append(line) fsen.close() #print(words) outfile = input("Enter Output File name:") outf = open(outfile, "w") line = inf.readline() while line != "": line = line.rstrip() line = line.lower() for word in words: line = line.replace(word, "*" * len(word)) outf.write(line) line = inf.readline() inf.close() outf.close()
dc24942f5115667462dd5c11064d903c92d38825
Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges
/Day67_LastlineFile.py
553
4.46875
4
# Day 67 Challenge: Print last Line of a File. # Function iterates over lines of file, store each line in lastline. # When EOF, the last line of file content is stored in lastline variable. # Print the result. def get_final_line(fname): fhand = open(fname, "r") for line in fhand: fhand = line.rstrip() lastline = line print("The Last Line is:") print(lastline) # Main # Read the File name & pass it as an argument to get_final_line function. fname = input('Enter a File Name:') get_final_line(fname)
ec508478bbd76531f1ef8e2a7a849254092cb3e4
Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges
/Day45_RecurStr.py
689
4.28125
4
# Day 45: Recursive (String) Palindrome def Palindrome(s): # If string length < 1, return TRUE. if len(s) < 1: return True else: # Last letter is compared with first, function called recursively with argument as # Sliced string (With first & last character removed.) if s[0] == s[-1]: return Palindrome(s[1:-1]) else: return False # Main # Read Input String. str = input("Enter a String:") # Convert to lower case to avoid mistake. str = str.lower() # Function call & Print Result. if Palindrome(str): print("The Given String is a Palindrome.") else: print("The Given String is Not a Palindrome.")
7b47ad842688389a9f2cb3a15a316d8f632fcdd8
AlexDvorak/Python-Coding-Train-Intelligence-and-Learning
/week1-graphs/01_binary_tree/tree.py
438
3.96875
4
from node import * # Tree object class Tree(object): def __init__(self): # Just store the root self.root = None # Start by searching the root def traverse(self): self.root.visit() # Start by searching the root def search(self,val): found = self.root.search(val) return found # Add a new value to the tree def addValue(self,val): n = Node(val) if self.root == None: self.root = n else: self.root.addNode(n)
bf23966c63dcaf59b048df443f59a16e315e0419
mazimidev/daen500
/CalcOTPay.py
515
4
4
hours = input('Enter Hours: ') rate = input('Enter Rate: ') try: otHours = float(hours)%40 otRate = float(rate)*1.5 print (otHours) print (otRate) except: print('please enter numeric') else: if float(hours) > 40: regPay=40 * float(rate) print(regPay) otPay=otHours * otRate print('yay OT') print(otPay) totPay=regPay + otPay print(totPay) else: pay = (int(hours) * float(rate)) print ('No OT') print (pay)
f4b342b436780dd1688b5f9163dd2e9248d7ec21
soldiers1989/tradecap
/tradeday.py
435
3.515625
4
#!/usr/bin/python2 # coding:utf8 def is_trade_day(date): # date 日期,日期格式 20160101 # 是交易日 返回1 否则返回0 trade_days = [] with open('trddate.txt') as f: for i in f: if i not in trade_days: trade_days.append(i.strip()) if date in trade_days: return 1 else: return 0 if __name__ == '__main__': print is_trade_day('20170206')
9c5b596221ade0a208c0d8d274e7dbc84d0a6709
FB-18-19-PreAP-CS/math-helper-wcarllWRLD
/math_helper_Carll_W.py
5,577
4.25
4
import math def main(): print("Welcome to the math helper!") while True: try: print("") print("Type [quit] to quit.") select = input("[1] Compound Interest \n[2] Volume of a Sphere \n[3] Distance Formula \n[4] Midpoint \n[5] Area of a Semi-Circle \nPlease select your desired formula:") print('') print('') if select == "1": p = float(input('Enter your Principal:')) t = float(input('Enter the Amount of times your interest has been compounded:')) r = float(input('Enter your interest rate in % form:')) print(f'Your Principal of {p}, compounded {t} times, at a rate of {r}%, is now worth {compound_int(p,t,r)}!') elif select == "2": r = float(input('Input your sphere\'s radius:')) print(f'Your sphere with a radius of {r}, has a volume of {sphere_volume(r)}.') elif select == "3": x1 = float(input("Please input the X value for the first coordinate:")) y1 = float(input("Please input the Y value for the first coordinate:")) x2 = float(input("Please input the X value for the second coordinate:")) y2 = float(input("Please input the Y value for the second coordinate:")) print(f'Coordinates ({x1},{y1} and ({x2},{y2}), are the square root of {distance_formula(x1,y1,x2,y2)} apart.)') elif select == "4": x1 = float(input("Please input the X value for the first coordinate:")) y1 = float(input("Please input the Y value for the first coordinate:")) x2 = float(input("Please input the X value for the second coordinate:")) y2 = float(input("Please input the Y value for the second coordinate:")) print(f'The midpoint of coordinates ({x1},{y1}) and ({x2},{y2}) is {midpoint(x1,y1,x2,y2)}.') elif select == "5": r = float(input('Input your Semi-circle\'s Radius:')) print(f'Your Semi-circle with a Radius of {r} has an area of {area_semicircle(r)}.') elif select.lower() == 'quit': print('Thank you for using The math helper!') break else: print("That is not a valid option!") except Exception as e: print(f"Error: {e}") def compound_int(p,t,r): '''Returns compound interest rounded to 2 decimals. Principal, Years(or number of times compounded), Interest >>> compound_int(1000,1,1) 1010.0 >>> compound_int(0,0,0) 0.0 >>> compound_int(2,100,10) 27561.22 >>> compound_int(5959,7,3.4) 7530.38 >>> compound_int(59.99,7,4.4) 81.09 >>> compound_int(71000.81,3,2.2) 75790.71 >>> compound_int(1000,-3,10) Traceback (most recent call last): ... ValueError: Time cannot be negative. ''' if t < 0: raise ValueError("Time cannot be negative.") if r > 99: raise ValueError("Rate must be entered in percent and be below 100%.") r = r / 100 r = r + 1 out = float(p*r**t) out = round(out,2) return out def sphere_volume(r): '''Returns volume of sphere rounded to 3 decimals, using Pi. >>> sphere_volume(10) 4188.79 >>> sphere_volume(7.5) 1767.146 >>> sphere_volume(0) 0.0 >>> sphere_volume(4.125) 294.009 >>> sphere_volume(-2) Traceback (most recent call last): ... ValueError: A sphere's radius cannot be negative. ''' if r < 0: raise ValueError("A sphere's radius cannot be negative.") pi = math.pi return round((4/3)*pi*r**3,3) def distance_formula(x1,y1,x2,y2): ''' returns the distance between two points in square root form. x1,y1,x2,y2 order of input >>> distance_formula(-3,1,0,-3) 25 >>> distance_formula(-4,22,-10,-3) 661 >>> distance_formula(-4,-4,-4,-4) 0 >>> distance_formula(-1,-2,-3,-4) 8 >>> distance_formula(-100,-200,-300,-400) 80000 ''' #part1 = round((x2-x1)**2 + (y2-y1)**2,3) return round((x2-x1)**2 + (y2-y1)**2,3) #return print(f"The distance is the Square root of {part1}.") def midpoint(x1,y1,x2,y2): ''' Returns the midpoint of two points. enter points in order of x1,y1,x2,y2 >>> midpoint(2,3,6,6) (4.0, 4.5) >>> midpoint(.25,-.25,-10,-20) (-4.875, -10.125) >>> midpoint(0,0,0,0) (0.0, 0.0) >>> midpoint(5,0,10,0) (7.5, 0.0) >>> midpoint(0,10,0,-20) (0.0, -5.0) ''' return ((x1+x2)/2,(y1+y2)/2) def area_semicircle(r): ''' Returns the area of a perfect semi circle. Input is radius. Rounds to 3 decimals. >>> area_semicircle(2) 6.283 >>> area_semicircle(0) 0.0 >>> area_semicircle(1000) 1570796.327 >>> area_semicircle(2.66) 11.114 >>> area_semicircle(-1) Traceback (most recent call last): ... ValueError: A Semi circle's radius cannot be negative! ''' if r < 0: raise ValueError('A Semi circle\'s radius cannot be negative!') pi = math.pi return round((pi*r**2)/2,3) if __name__ == "__main__": import doctest doctest.testmod() main()