text
stringlengths
37
1.41M
#!/usr/bin/env python import argparse # Create a parser object and add the arguments that are part of the program parser = argparse.ArgumentParser(description='Read in some entries and add them.') parser.add_argument('a', metavar='float_1', type=float, help='a float') parser.add_argument('b', metavar='float_2', type=float, help='another float') # return an object with all of the arguments args = parser.parse_args() print (args.a + args.b)
#!/usr/bin/env python3 # coding=utf-8 import re while True: print('Enter passwd to check: ') passwd = input() # chek passwd length if passwd == '' or (len(passwd)) < 8: print('password is not null or password length small then 8') break if re.search("[\d{8}]", passwd): print('weak password') break # if re.search("[\w{8}]", passwd): # print('weak password') # break if not re.search("[!@#$%^&*]", passwd): print('weak passwd') break else: print('complex password') break # pw_re = re.compile(r'''( # [a-zA-z\d{1:}]+ # )''', re.VERBOSE) # if pw_re.search(passwd): # print("Complex password") # else: # print("weak password")
"""If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.""" x = 0 for n in range(1000): if ((n % 3) == 0) or ((n% 5) ==0): x += n print "Adding " + str(n) + "\n" print str(x) + "\n" print "The sum of all this mess is: " print x
"""Utility functions used in at least 2 exercises""" import math def count_factors(number): x = int(math.sqrt(number)) + 2 factor_count = 0 while x > 1: if (number % x) == 0: factor_count += 1 x -= 1 return factor_count def is_prime(number): if number == 2: return True elif number == 3: return True elif number == 1: return False x = int(math.sqrt(number)) + 2 if x > number: x = number n = 2 while n < x: if (number % n) == 0: return False n += 1 return True
import unittest from Tweet import Tweet,TweetUser class TestStringMethods(unittest.TestCase): def test_create_user(self): user=TweetUser("TestUser") self.assertEqual(user.Name, 'TestUser') def test_add_follower(self): user1=TweetUser("TestUser1") user2=TweetUser("TestUser2") user1.addFollower(user2) self.assertEqual(user1.showFollowing(), 'TestUser2 ') def test_create_tweet(self): tweet=Tweet("TestUser1","Test Message") self.assertEqual(tweet.tweetuser, "TestUser1") self.assertEqual(tweet.message, "Test Message") if __name__ == '__main__': unittest.main()
cars = ['audi', 'bmw', 'subaru', 'toyota'] #if 条件使用 for car in cars: if car == "bmw": print(car.upper()) else: print(car) #数字比较 age = 18 if 20 > age: print("more than age", age) else: print("null") #使用多个条件 and if age >= 17 and age <=20: print("17<=age<=20") else: print("null") if age >=18 or age <=7: print("age>=18 or age<=7") else: print("null") #检查特定字段是否包含 print("subaru" in cars) print("chenp" not in cars) age = 20 if age < 4: print("age < 4") elif age < 40: print("age < 40") else: print("age null") #strs = ['audi', 'bmw', 'subaru', 'toyota'] strs = [] for str in strs: print(str)
dimensions = (200, 50, 200, 300, 412) for dimension in dimensions: print(dimension) dimensions = (1, 2, 5, 1, 7, 8) print(dimensions) #可以是不同类型 tuples = ("a", 1, 5, "fdjs", "9", 6) for v in tuples: print(v)
#二叉树 #pip install binarytree from binarytree import tree, build, Node, bst #t = build([2, 5, 8, 3, 1, 9, 10, 13, 6, 7, 34, 19, 23, 45, 31, 24]) t = build([2, 5, 8, 3, 1, 9, 10, 13, 14, 12]) print(t) # 求二叉树节点个数 def GetNodeNum(t): if t == None: return 0 left = GetNodeNum(t.left) right= GetNodeNum(t.right) return left + right + 1 re = GetNodeNum(t) print('节点个数:{}'.format(re)) # 求二叉树深度 def GetDepth(t): if t == None: return 0 left = GetDepth(t.left) right = GetDepth(t.right) return max(left, right) + 1 re = GetDepth(t) print('深度:{}'.format(re)) # 二叉树最小深度(从根节点到叶子节点最短距离) def GetMinDepth(t): if t == None: return 0 left = GetMinDepth(t.left) right = GetMinDepth(t.right) return min(left, right) + 1 re = GetMinDepth(t) print('最小深度:{}'.format(re)) #前序遍历,中序遍历,后序遍历 def PreOrderTraverse(t): if t == None: return print(t.value, end=', ') PreOrderTraverse(t.left) PreOrderTraverse(t.right) print('前序遍历: ') PreOrderTraverse(t) print() #前序遍历非递归写法 def PreOrderTraverse1(t): if t == None: return stack = [] cur = t while cur != None or len(stack) != 0: while cur != None: print(cur.value, end=', ') stack.append(cur) cur = cur.left if len(stack) != 0: cur = stack.pop() cur = cur.right PreOrderTraverse1(t) print() def InOrderTraverse(t): if t == None: return InOrderTraverse(t.left) print(t.value, end=', ') InOrderTraverse(t.right) print('中序遍历: ') InOrderTraverse(t) print() def PostOrderTraverse(t): if t == None: return PostOrderTraverse(t.left) PostOrderTraverse(t.right) print(t.value, end=', ') print('后序遍历: ') PostOrderTraverse(t) print() #分层遍历二叉树(从上到下) def LevelTraverse(t): if t == None: return l = list() l.append(t) while len(l) != 0: node = l.pop(0) print(node.value, end=', ') if node.left != None: l.append(node.left) if node.right != None: l.append(node.right) #print('------------', l) return print('分层遍历(从上到下):') LevelTraverse(t) print() #分层遍历二叉树(从下到上,从左到右) def LevelTraverse1(t): if t == None: return l = list() l.append(t) out = [] #所有层list path = [] #每一层路劲 cur_count, next_count = 1, 0 while len(l) != 0: node = l.pop(0) path.append(node.value) cur_count -= 1 if node.left != None: l.append(node.left) next_count += 1 if node.right != None: l.append(node.right) next_count += 1 if cur_count == 0: #当前层最后一个元素 out.append(path) path = [] cur_count = next_count next_count = 0 out.reverse() return out print('分层遍历(从下到上):') re = LevelTraverse1(t) print(re) #求二叉树第K层的节点个数 def GetNodeNumKthLevel(t, k): if t == None or k == 0: return 0 if k == 1: return 1 left = GetNodeNumKthLevel(t.left, k - 1) right = GetNodeNumKthLevel(t.right, k - 1) #print('-----------', left, right) return left + right n = 3 re = GetNodeNumKthLevel(t, n) print('第{}层数据个数:{}'.format(n, re)) #叶子节点的个数 def GetLeafNodeNum(t): if t == None: return 0 if t.left == None and t.right == None: return 1 left = GetLeafNodeNum(t.left) right = GetLeafNodeNum(t.right) return left + right re = GetLeafNodeNum(t) print('叶子节点的个数:{}'.format(re)) # 判断两棵二叉树是否(结构)相同,不需要判断值 def StructureCmp(t1, t2): if t1 == None and t2 == None: return True if t1 == None or t2 == None: return False l1 = StructureCmp(t1.left, t2.left) l2 = StructureCmp(t1.right, t2.right) return l1 and l2 re = StructureCmp(t, t) print(re) t2 = build([2, 5, 8, 13, 14, 10, 1, 3, 45, 39, 11, 15, 18, 19, 23, 20]) re = StructureCmp(t, t2) print(re) #判断一棵二叉树是不是平衡二叉树 #(1)如果二叉树为空,返回真 #(2)如果二叉树不为空,如果左子树和右子树都是AVL树并且左子树和右子树高度相差不大于1,返回真,其他返回假 def IsAVL(t): if t == None: return True left = GetDepth(t.left) right = GetDepth(t.right) # 深度差1不满足 if abs(left - right) > 1: return False #在递归左边和右边 return IsAVL(t.left) and IsAVL(t.right) re = IsAVL(t) print(re) re = IsAVL(t2) print(t2, re) # 二叉树的镜像 def Mirror(t): if t == None: return None t.left, t.right = t.right, t.left Mirror(t.left) Mirror(t.right) print('二叉树镜像:', t) Mirror(t) print(t) # 二叉树的右视图,即打印每层最后一个节点 def LeftView(t): if t == None: return l = list() l.append(t) count = 0 #当前层处理的个数 cur_level, next_level = 1, 0 #记录当前层和下一层个数 while len(l) != 0: node = l.pop(0) count += 1 if node.left != None: l.append(node.left) next_level += 1 if node.right != None: l.append(node.right) next_level += 1 if count == cur_level: #下一层个数 cur_level = next_level #计数器清零 count = next_level = 0 #打印右边最后一个节点 print(node.value, end=', ') return # 递归的方式 # 因为每层只打印一个节点,我们可以使用一个记录每层节点的队列,同时把层数作为一个参数,当打印到某层时, # 如果层数刚好等于队列的长度,就说明该节点就是该层遇到的第一个节点,将它加入队列并向子树递归。 def LeftView1(t, level, out): if t == None: return None if level == len(out): out.append(t.value) LeftView1(t.left, level + 1, out) LeftView1(t.right, level + 1, out) print('右视图遍历:') LeftView(t) print() print('左视图遍历:') re = [] LeftView1(t, 0, re) print(re) print() # 二叉树的宽度 # 宽度定义:二叉树各层节点个数的最大值 def Weith(t): if t == None: return 0 qu = [] qu.append(t) count = 0 #计数器 max_count = 0 #最大宽度 cur_count, next_count = 1, 0 while len(qu) != 0: v = qu.pop(0) count += 1 if v.left != None: qu.append(v.left) next_count += 1 if v.right != None: qu.append(v.right) next_count += 1 if count == cur_count: # 下一层, 清零计数器,更新最大宽度 max_count = max(max_count, cur_count) cur_count = next_count next_count = count = 0 return max_count re = Weith(t) print('二叉树的宽度:{}'.format(re)) print() # 二叉树节点间最大距离 # 二叉树中节点的最大距离必定是两个叶子节点的距离。求某个子树的节点的最大距离,有三种情况: # 1.两个叶子节点都出现在左子树; # 2.两个叶子节点都出现在右子树; # 3.一个叶子节点在左子树,一个叶子节点在右子树。只要求得三种情况的最大值,结果就是这个子树的节点的最大距离。 # int find_max_len(Node * root) # case 1: 两个叶子节点都出现在左子树。find_max_len(root -> pLeft) # case 2: 两个叶子节点都出现在右子树。find_max_len(root -> pRight) # case 3: 一个出现在左子树,一个出现在右子树。distance(root -> pLeft) + distance(root -> pRight) + 2 # 其中,distance()计算子树中最远的叶子节点与根节点的距离,其实就是左子树的高度减1。 def MaxHigh(t): if t == None: return 0 return GetDepth(t) #高度等于深度减1 def MaxDistance(t): if t == None: return 0 if t.left == None and t.right == None: return 0 #case1 两个叶子节点都在左子树 lmax = MaxDistance(t.left) #case2 两个叶子节点都在右子树 rmax = MaxDistance(t.right) #case3 一个在根节点左边、一个在右边 lrmax = MaxHigh(t.left) + MaxHigh(t.right) #print(lmax, rmax, lrmax) return max(lmax, rmax, lrmax) re = MaxDistance(t) print(t) print('最大节点距离:{}'.format(re)) print() # 最低公共 两个节点的最低公共祖先 # 如果是二叉搜索树 # 对于二叉搜索树来说,公共祖先的值一定大于等于较小的节点,小于等于较大的节点。换言之, # 在遍历树的时候,如果当前结点大于两个节点,则结果在当前结点的左子树里,如果当前结点小于两个节点,、 # 则结果在当前节点的右子树里 def lowestCommonAncestorOfBST(t, n1, n2): if t == None: return None if t.value > n1 and t.value > n2: return lowestCommonAncestorOfBST(t.left, n1, n2) if t.value < n1 and t.value < n2: return lowestCommonAncestorOfBST(t.right, n1, n2) return t # 如果是普通二叉树 # 我们可以用深度优先搜索,从叶子节点向上,标记子树中出现目标节点的情况。如果子树中有目标节点, # 标记为那个目标节点,如果没有,标记为null。显然,如果左子树、右子树都有标记,说明就已经找到最小公共祖先了。 # 如果在根节点为p的左右子树中找p、q的公共祖先,则必定是p本身。 # 换个角度,可以这么想:如果一个节点左子树有两个目标节点中的一个,右子树没有, # 那这个节点肯定不是最小公共祖先。如果一个节点右子树有两个目标节点中的一个,左子树没有, # 那这个节点肯定也不是最小公共祖先。只有一个节点正好左子树有,右子树也有的时候,才是最小公共祖先。 # 类似于后续遍历的方式 def lowestCommonAncestorOfBST1(t, n1, n2): # 发现目标节点则通过返回值标记该子树发现了某个目标结点 if t == None or t.value == n1 or t.value == n2: return t # 查看左子树中是否有目标结点,没有为null left = lowestCommonAncestorOfBST1(t.left, n1, n2) # 查看右子树是否有目标节点,没有为null right = lowestCommonAncestorOfBST1(t.right, n1, n2) # 都不为空,说明做右子树都有目标结点,则公共祖先就是本身 if left != None and right != None: return t # 没找到继续往上找 if left != None: return left return right #写成 re = lowestCommonAncestorOfBST1(t, 8, 1) print('最低公共祖先:{}'.format(re.value)) # 树的子结构(剑指offer26) # 思路先找到子树根节点,然后在对比两个树是否相等 # 匹配子树结构,t1是主树,t2是子树 def matchSubTree(t1, t2): if t2 == None: return True if t1 == None: return False if t1.value != t2.value: return False return matchSubTree(t1.left, t2.left) and matchSubTree(t1.right, t2.right) # 采用前序遍历先访问根节点的方式 def IsSubTree(t1, t2): if t1 == None or t2 == None: return False # 找到一个根节点相同的,则继续判断 result = False if t1.value == t2.value: result = matchSubTree(t1, t2) # 没有找到根节点相同的继续查找 if result == False: result = IsSubTree(t1.left, t2) if result == False: result = IsSubTree(t1.right, t2) return result subTree = Node(5) subTree.left = Node(1) subTree.left.right = Node(12) print('----------------', t, subTree) print('子树:', IsSubTree(t, subTree)) # 二叉树搜索树第K打的节点 # 思路:二叉搜索树中序遍历,判断k是否等于1 def FindKthNode(t, k): if t == None or k <= 0: return None return FindKthNodeCore(t, k) def FindKthNodeCore(t, k): target = None if t.left != None: target = FindKthNodeCore(t.left, k) print(t.value ) if target == None: if k == 1: #命中目标 target = t k -= 1 if target == None and t.right != None: target = FindKthNodeCore(t.right, k) return target bst_tree = bst(3) print(bst_tree) n = 5 re = FindKthNode(bst_tree, n) print('二叉搜索树第{}大数: {}'.format(n, re)) # 合并二叉树 # https://leetcode-cn.com/problems/merge-two-binary-trees/comments/ # 输入: # Tree 1 Tree 2 # 1 2 # / \ / \ # 3 2 1 3 # / \ \ # 5 4 7 # 输出: # 合并后的树: # 3 # / \ # 4 5 # / \ \ # 5 4 7 # 注意: 合并必须从两个树的根节点开始。 def mergeTree(t1, t2): if t1 == None: return t2 if t2 == None: return t1 t1.value += t2.value t1.left = mergeTree(t1.left, t2.left) t1.right = mergeTree(t1.right, t2.right) return t1 t1, t2 = bst(3), bst(2) print(t1, t2) print(mergeTree(t1, t2)) # 打印二叉树所有路劲,有点类似路径和 def allPath(t): if t == None: return out = [] path = "" core(t, path, out) return out def core(t, path, out): if t == None: return path += str(t.value) if t.left == None and t.right == None: out.append(path) if t.left != None: core(t.left, path + "->", out) if t.right != None: core(t.right, path + "->", out) print(t) re = allPath(t) print('所有路劲是{}'.format(re)) #求二叉树每层的平均值 def averageOfLevels(t): if t == None: return l = list() l.append(t) next_level, cur_level = 0, 1 out, path = [], [] while len(l) != 0: node = l.pop(0) cur_level -= 1 path.append(node.value) if node.left != None: l.append(node.left) next_level += 1 if node.right != None: l.append(node.right) next_level += 1 if cur_level == 0: #当前层处理完毕 sum = 0 #print(path) for v in path: sum += v out.append(sum/len(path)) path = [] cur_level = next_level next_level = 0 return out print(t) re = averageOfLevels(t) print('每一层平均值是{}'.format(re))
# 二叉搜索树转换成双向链表 from binarytree import Node # 打印,直接用binarytree打印会出错 def Print(t): while t != None: print(t.value, end='->') t = t.right print() # 思路:中序遍历,缓存下上一个节点的指针 def convert(t, preNode): if t == None: return None convert(t.left, preNode) # 调整指针,左指针指向上一个节点,上一个节点的右指针指向当前节点 t.left = preNode if preNode != None: preNode.right = t print(t.value) #缓存节点 preNode = t convert(t.right, preNode) def ConvertTree2List(t): if t == None: return None preNode = None convert(t, preNode) #t 在中间,升序需要从左边去查找 cur = t.left while cur != None: cur = cur.left return cur t = Node(10) t.left = Node(6) t.right = Node(14) t.left.left = Node(4) t.left.right = Node(8) t.right.left = Node(12) t.right.right = Node(16) #print(t) re = ConvertTree2List(t) Print(re)
# 层次遍历二叉树 from binarytree import tree def TreeLevelView(t): if t == None: return None qu = [] qu.append(t) while len(qu) != 0: t = qu.pop(0) print(t.value, end = ', ') if t.left != None: qu.append(t.left) if t.right != None: qu.append(t.right) t = tree() print(t) TreeLevelView(t)
#链表反转 class Node: def __init__(self, value, next = None): self.value = value self.next = next def list_reverse(head): if head is None or head.next is None: return head p, q = head, head.next head.next = None while q: tmp = q.next q.next = p # 调换指针方向 p = q # 移动慢指针到下一个节点 q = tmp # 移动快指针到下一个节点 return p head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) new_list = list_reverse(head) print(new_list.value, new_list.next.value, new_list.next.next.value, new_list.next.next.next.value)
#链表反转 class Node: def __init__(self, value, next=None): self.value = value self.next = next def list_reverse(head): if head == None or head.next == None: return head q, p = head, head.next head.next = None while p: tmp = p.next p.next = q q = p p = tmp head = q # 最后p已经指向none了 return head head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) new_list = list_reverse(head) print(new_list) print(new_list.value, new_list.next.value, new_list.next.next.value, new_list.next.next.next.value)
#旋转数组查找默认升序 # 思路:旋转数组取中间位置至少有一边是有序的,利用有序快速判断key在那一边,有序的 # 部分可以快速用二分查找定位 def Search(arr, key): if len(arr) == 0: return -1 beg, end = 0, len(arr) - 1 while beg <= end: mid = (beg + end) // 2 cur = arr[mid] if cur == key: return cur #默认升序,左边有序 if cur > arr[beg]: if cur > key and key >= arr[beg]: #确实key在左边区间 end = mid - 1 else: beg = mid + 1 #右边有序 if cur < arr[end]: if cur < key and key <= arr[end]: #确实key在右边区间 beg = mid + 1 else: end = mid - 1 #print('--------------', arr[beg], arr[end]) return -1 arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14] print(Search(arr, 25)) print(Search(arr, 15)) print(Search(arr, 1)) print(Search(arr, 14)) print(Search(arr, 5)) print(Search(arr, 26))
#跳台阶问题 # 首先考虑最简单的情况。如果只有1级台阶,那显然只有一种跳法。如果有2级台阶,那就有两种跳的方法了:一种是分两次跳,每次跳1级;另外一种就是一次跳2级。 # 现在我们再来讨论一般情况。我们把n级台阶时的跳法看成是n的函数,记为f(n)。 # 当n>2时,第一次跳的时候就有两种不同的选择: # 一是第一次只跳1级,此时跳法数目等于后面剩下的n-1级台阶的跳法数目,即为f(n-1); # 另外一种选择是第一次跳2级,此时跳法数目等于后面剩下的n-2级台阶的跳法数目,即为f(n-2)。 # 因此n级台阶时的不同跳法的总数f(n)=f(n-1)+f(n-2)。 def Fibonacci(n): if n == 0: return 0 if n == 1: return 1 if n == 2: return 2 return Fibonacci(n - 1) + Fibonacci(n - 2) def Fibonacci1(n): a, b = 0, 1 for _ in range(0, n): a, b = b, a + b return b print(Fibonacci(21)) print(Fibonacci1(21))
#两个有序链表合并 import list_common as List # 思路1:递归 def MergeSortList(l1, l2): if l1 == None: return l2 if l2 == None: return l1 # 正向排序 cur = None if l1.value < l2.value: cur = l1 #cur串联l1节点 cur.next = MergeSortList(l1.next, l2) #串联下一个节点 else: cur = l2 cur.next = MergeSortList(l1, l2.next) return cur # 思路2: 遍历 def MergeSortList1(l1, l2): if l1 == None: return l2 if l2 == None: return l1 # 取头结点 head = cur = None if l1.value < l2.value: cur = head = l1 l1 = l1.next else: cur = head = l2 l2 = l2.next # 每串联一个节点当前节点cur往后移动 while l1 != None and l2 != None: if l1.value < l2.value: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next # 当前游标指针往后移动 List.Print(head) if l1 != None: cur.next = l1 if l2 != None: cur.next = l2 return head a, b, c, d, e = List.Node(1), List.Node(3), List.Node(7), List.Node(9), List.Node(10) head1 = a head1.next = b head1.next.next = c head1.next.next.next = d head1.next.next.next.next = e a1, b1, c1, d1, e1 = List.Node(0), List.Node(3), List.Node(3), List.Node(8), List.Node(11) head2 = a1 head2.next = b1 head2.next.next = c1 head2.next.next.next = d1 head2.next.next.next.next = e1 head2.next.next.next.next.next = List.Node(12) #re = MergeSortList(head1, head2) #Print(re) re = MergeSortList1(head1, head2) List.Print(re)
#两个链表的第一个公共节点 #思路:先计算两个链表长度,然后算差值k,长的链表先走k步 import list_common as List def GetLength(l): if l == None: return 0 cur, cout = l, 0 while cur: cout += 1 cur = cur.next return cout def FindCommonNode(l1, l2): if l1 == None or l2 == None: return None length1 = GetLength(l1) length2 = GetLength(l2) diff = length1 - length2 if diff > 0 : for _ in range(0, diff): l1 = l1.next elif diff < 0: for _ in range(0, diff): l2 = l2.next #else 一样长 #同时遍历 while l1 != None and l2 != None: if l1 == l2: return l1 l1 = l1.next l2 = l2.next return None a, b, c, d, e, f, g, h = List.Node(1), List.Node(2), List.Node( 3), List.Node(4), List.Node(5), List.Node(6), List.Node(7), List.Node(8) l2 = a l2.next = c l2.next.next = e l2.next.next.next = g l2.next.next.next.next = h l1 = b l1.next = d l1.next.next = f l1.next.next.next = g l1.next.next.next.next = h re = FindCommonNode(l1, l2) print(re.value)
#list基础组件 def Print(head): cur = head while cur != None: print('{}->'.format(cur.value), end='') cur = cur.next print() class Node: def __init__(self, value, next=None): self.value = value self.next = next
def append(self, after_val, val): # Input => (3->6->1->7->2->None, 6, 4) # Output => 3->6->4->1->7->2->None runner = self.head while runner is not None: if runner.val == after_val: next_node = runner.next runner.next = Node(val) runner.next.next = next_node return self runner = runner.next print('no node with val=' + str(after_val) + ' found in SLL') return self def delete(self, val): # Input => 3->6->1->7->2->None, 1 # Output => # 3->6->7->2->None runner = self.head prev = runner if runner.val == val: self.head = runner.next while runner is not None: if runner.val == val: prev.next = runner.next return self prev = runner runner = runner.next print('no node with val=' + str(val) + ' found in SLL') return self
# 编写一个程序判断给定的数是否为丑数。 # 丑数就是只包含质因数 2, 3, 5 的正整数 import time class Solution(): def __init__(self, num): self.num = num def fun_one(self, num): for x in [2,3,5]: if self.num % x == 0: self.num /= x Solution.fun_one(self,num) if self.num == 1: return True return False num = int(input()) a = Solution(num) start = time.clock() print(a.fun_one(num)) end = time.clock() print(end-start)
print("Give me two numbers and I will tell you the first number power the second number. First, give me the number that you want to find the power of.") a=int(input()) print("Now give me the power that you want it to.") b=int(input()) print(a, "power", b, "is", a**b, end="") print(".")
# -*- coding: utf-8 -*- """ Created on Thu Apr 8 03:17:24 2021 @author: mvjoshi """ print("Give me two numbers and I will tell you if all the 3n+1's of the numbers between those numbers reach a smaller number. Smaller number first:") small_number=int(input()) print("Now larger number please:") large_number=int(input()) a=0 current_number=small_number while not current_number%4==3: current_number=current_number+1 while current_number<large_number+1: current_place=current_number if current_place%2==1: current_place=3*current_place+1 else: current_place=current_place//2 while current_place>current_number: if current_place%2==1: current_place=3*current_place+1 else: current_place=current_place//2 if current_place==current_number: print(current_number, "has fallen into a repeating pattern. I will show it to you in a sec.") print(current_place) if current_place%2==1: current_place=3*current_place+1 print(current_place) else: current_place=current_place//2 print(current_place) while current_place>current_number: if current_place%2==1: current_place=3*current_place+1 print(current_place) else: current_place=current_place//2 print(current_place) a=1 current_number=current_number+4 if a==0: print("I have not found any repeating patterns in these numbers.") else: print("These are the only repeating patterns in these numbers.")
from math import sqrt print("Give me two numbers 'a' and 'b' and I will tell you all the numbers up to 'a' that are not divisible by any number power 'b'. First, give me 'a'.") a=int(input()) print("Now, give me 'b'.") b=int(input()) print("The such numbers are written below.") c=0 f=0 prime_list=[2] while c**b<=a: c=c+1 for d in range(3, c): e=0 f=0 while prime_list[f]<sqrt(d): if d%prime_list[f]==0: e=1 break f=f+1 if e==0: prime_list.append(d) for c in range(2, a): d=0 e=0 while (prime_list[e]**b)<=c: if c%(prime_list[e]**b)==0: d=1 break if not (e+1)==len(prime_list): e=e+1 else: break if d==0: f=f+1 print(c) print("So, there are", f, "such numbers.")
print("Give me a number and I will tell you the puppies and kittens puzzle bad number groups up to it.") upto_number=int(input()) tried_list=[] used_list=[] numbers_in_used_list=0 first_number=1 second_number=2 print(first_number, ",", second_number) tried_list.append(first_number) used_list.append(second_number) numbers_in_used_list=numbers_in_used_list+1 for i in range(2, upto_number+1): first_number=first_number+1 x=1 j=0 while (j<numbers_in_used_list) and (used_list[j] <= first_number): if used_list[j]==first_number: print(first_number, ",", tried_list[j]) second_number=second_number+1 x=0 j=j+1 if x==1: second_number=second_number+2 print(first_number, ",", second_number) tried_list.append(first_number) used_list.append(second_number) numbers_in_used_list=numbers_in_used_list+1
print("Give me a word and then give me a such part and I will tell you how many times it occurs in the word. First, give me the word.") a=input() print("Now, give me the part.") b=input() c=len(b) word_groups_list=[] for i in range((len(a)-c)+1): word_groups_list.append(a[i:(i+c)]) j=0 for k in range(len(word_groups_list)): if word_groups_list[k]==b: j=j+1 print("There are", j, b, "'s in", a, ".")
print("Give me x and y and I will tell you x in base y. First, give me x.") x=int(input()) print("Now, give me y.") y=int(input()) numbers_list=[] print(x, "in base", y, "is", end=" ") while x>0: numbers_list.append(x%y) x=x//y for i in range(len(numbers_list)): print(numbers_list[len(numbers_list)-i-1], end="") if i<len(numbers_list)-1: print(",", end=" ") else: print(".")
#!/usr/bin/python3 print ("Give me a number and I will tell you if it is prime or composite and if itx2+1 is prime or composite.") n=float(input()) if n%1==0: j=0 i=2 if n>1: while i*i<=n: if n%i==0: if i==n/i: print ("It is composite. It is divisible by", i, ".") else: print ("It is composite. It is divisible by", i, "and", n/i, ".") j=1 break else: i=i+1 else: j=1 print("It is composite.") if j==0: print ("It is prime.") d=2*n+1 j=0 i=2 if d>1: while i*i<=d: if d%i==0: if i==d/i: print ("Itx2+1 is composite. It is divisible by", i, ".") else: print ("Itx2+1 is composite. It is divisible by", i, "and", d/i, ".") j=1 break else: i=i+1 else: j=1 print ("Itx2+1 is composite.") if j==0: print ("Itx2+1 is prime.") else: print ("You can't divide", n, "into prime or composite because", n, "is a fraction.")
# importing PyPDF2 module for extracting text from PDF files. from PyPDF2 import PdfFileReader # open the PDF file # make sure the pdf file is in the same directory # if the file is present in some other directory then one can provide the file path pdfFile = open('pdf-file-name.pdf', 'rb') # create PDFFileReader object to read the file pdfReader = PdfFileReader(pdfFile) # printing the title and name of the creator print("PDF File name: " + str(pdfReader.getDocumentInfo().title)) print("PDF File created by: " + str(pdfReader.getDocumentInfo().creator)) print("- - - - - - - - - - - - - - - - - - - -") # calculating the number of pages pdf consists of numOfPages = pdfReader.getNumPages() # running the for loop to convert pdf to text till the required no of pages for i in range(0, numOfPages): print("Page Number: " + str(i)) print("- - - - - - - - - - - - - - - - - - - -") pageObj = pdfReader.getPage(i) print(pageObj.extractText()) print("- - - - - - - - - - - - - - - - - - - -") # close the PDF file object pdfFile.close()
def search(a,l,h): m=(l+h)//2 if l>h: return None if a[m]>a[m+1] and a[m]>a[m-1]: return a[m] if a[m]>a[m+1] and a[m]<a[m-1]: search(a,l,m) if a[m]<a[m+1] and a[m]>a[m-1]: search(a,m,h) def main(): a=input('enter the sequence of numbers ') a=a.split() for i in range(len(a)): a[i]=int(a[i]) print(a) print('the required element is ',search(a,0,len(a)-1)) if __name__ == '__main__': main()
""" Decodes a string of binary text into ascii. Works with both 7 and 8 bit ascii. Matthew Tilton 2017-03-25 """ import sys BIN_TO_DECODE = sys.stdin.readlines()[0] def decode(): """ Decodes a string of binary text into ascii """ is_7_bit_ascii = (len(BIN_TO_DECODE) % 7 == 0) is_8_bit_ascii = (len(BIN_TO_DECODE) % 8 == 0) output = "" values = [] both_flag = False # Loop incase we cant tell if its 7 or 8 bit binary while True: # The actual decoding part if is_7_bit_ascii and is_8_bit_ascii: print('Cant determine bitness. Doing both') both_flag = True elif is_7_bit_ascii: print('Decoding as 7 bit ascii') values = [BIN_TO_DECODE[i:i+7] for i in range(0, len(BIN_TO_DECODE), 7)] for each in values: integer = int(each, 2) if integer >= 32 or integer == 8 or integer == 13 or integer == 9 or integer == 10: output = output + (chr(integer)) elif is_8_bit_ascii: print('Decoding as 8 bit ascii') values = [BIN_TO_DECODE[i:i+8] for i in range(0, len(BIN_TO_DECODE), 8)] for each in values: integer = int(each, 2) if integer >= 32 or integer == 8 or integer == 13 or integer == 9 or integer == 10: output = output + (chr(integer)) else: print('What is this shit. This isnt 7 or 8 bit ascii.') # Determines wheather we continue trying other ways to decode or if we are done. if both_flag and is_7_bit_ascii and is_8_bit_ascii: is_8_bit_ascii = False elif both_flag and is_7_bit_ascii: print(output) output = "" is_7_bit_ascii = False is_8_bit_ascii = True elif both_flag and is_8_bit_ascii: break else: break print(output) decode()
import sys bintodecode = input() result = '' i = 0 def checksevenbit(): global bintodecode global result global i firstseven = bintodecode[i:i+7] try: integer = int(firstseven, 2) except: integer = 32 character = chr(integer) if character.isdigit() or character == ' ': result = result + character i=i+7 else: checkeightbit() def checkeightbit(): global bintodecode global result global i firstseven = bintodecode[i:i+8] try: integer = int(firstseven, 2) except: integer = 32 character = chr(integer) if character.isdigit() or character == ' ': result = result + character i = i+8 else: print('fuck') while len(bintodecode) > 7: checksevenbit() print(result)
# Valid Sudoku # Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules # http://sudoku.com.au/TheRules.aspx . # The Sudoku board could be partially filled, where empty cells are filled with the character '.'. # 填充数独里面的数字,空单元格用 ',' 填充 # 为了便于计算 我直接改成了0 # 5 3 0 0 7 0 0 0 0 # 6 0 0 1 9 5 0 0 0 # 0 9 8 0 0 0 0 6 0 # # 8 0 0 0 6 0 0 0 3 # 4 0 0 8 0 3 0 0 1 # 7 0 0 0 2 0 0 0 6 # # 0 6 0 0 0 0 2 8 0 # 0 0 0 4 1 9 0 0 5 # 0 0 0 0 8 0 0 7 9 # # 切 我还以为是数独的解法 # 其实这个题只是让你判断是否是一个有效的数独 # 意思就是 已有的数据里面 横竖 小方块是否有重复的数据 # 而不需要填充数据 # 用一个长度为9的boolean数组 def valid_sudoku(A=[]): # 检查竖 for i in range(9): # 重置判读数组 B = [False] * 9 for j in range(9): if not check_valid(B, A[i][j]): return False # 检查横 for i in range(9): # 重置判断数组 B = [False] * 9 for j in range(9): if not check_valid(B, A[j][i]): return False # 检查小方块 for i in range(3): for j in range(3): B = [False] * 9 for a in range(3): for b in range(3): x = i * 3 + a y = j * 3 + b if not check_valid(B, A[x][y]): return False return True # 检查某个点的有效性 def check_valid(A=[], i=0): if i == 0: return True if i < 1 or i > 9 or A[i - 1]: return False A[i - 1] = True return True A = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] # Trapping Rain Water # Given n non-negative integers representing an elevation map where the width of each bar is 1, compute # how much water it is able to trap after raining. # For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. # 雨水收集器 # 网上有图 看着更清楚 (建议自己百度一下) # 基本思路就是 每根柱子 如果左边或者右边 没有比他高的数 那么就不能存储雨水 # 如果左右两边都有比他高的数 那么 就用左右两边中小的那个 减去他本身 就可以得到本柱子能存储多少雨水了 # 然后再进行叠加即可 # def trap_rain_water(L=[]): result = 0 for i in range(len(L)): left = 0 right = 0 x = i y = i while x > 0: x -= 1 if L[x] > L[i] and L[x] > left: left = L[x] while y < len(L) - 1: y += 1 # print(y) if L[y] > L[i] and L[y] > right: right = L[y] if left == 0 or right == 0: continue result += (min(left, right) - L[i]) print('这个模型 应该能收集的雨水是 %s ' % result) # 该题的第二种思路 # 先遍历一遍 找到最高点 (有多个最高点 就取第一个) # 然后将数组分成两边 分别依次处理 左右两边即可 # 就不写代码了 思路很简单 def trap_rain_water_2(L=[]): pass # Rotate Image # You are given an n * n 2D matrix representing an image. # Rotate the image by 90 degrees (clockwise). # Follow up: Could you do this in-place? # 有一个 n * n 的2D图片 让这个图片旋转90度 # 比如一个二维数组 # 3 3 3 # 2 1 5 # 8 4 2 # # 旋转90度之后 # 8 2 3 # 4 1 3 # 2 5 3 # 思路有很多种 # 对角线旋转 # 首先以对角线为轴 翻转 # 然后再以x轴中线上下翻转即可得到结果 def rotate_image(L=[]): s = len(L) print(L) # 对切线交换 for i in range(s): for j in range(s - 1): if L[i][j] == L[s - j - 1][s - i - 1]: # 如果等于的话 说明到了中线了 就不需要进行遍历这一行了 开始下一行 break L[i][j], L[s - j - 1][s - i - 1] = swap(L[i][j], L[s - j - 1][s - i - 1]) print(L) # x轴的中线交换 for i in range(s // 2): for j in range(s): L[i][j], L[s - i - 1][j] = swap(L[i][j], L[s - i - 1][j]) print(L) def swap(x=0, y=0): return y, x # Plus One # Given a number represented as an array of digits, plus one to the number. # 对一个数组进行加1的操作 # 如果大于 10 就需要进位 # 如果最高位了还需要进位的话 就重新new一个数组 # 并且将最高位设为1 其余为设为0 # 这题可能会涉及到很多扩展 比如两个数组相加 # def plus_one(L=[], a=1): s = len(L) z = a for i in range(s): L[i] += z z = L[i] // 10 L[i] = L[i] % 10 if z > 0: # 说明需要进位 L.insert(s, 1) return L # Climbing Stairs # You are climbing a stair case. It takes n steps to reach to the top. # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # 爬楼梯 一共了n阶 每次可以爬1阶或者2阶 问一共有多少种上楼的方式 # 上第n阶的可能有 1步上来的 或者2步上来的 那么 # 上n阶的可能的路线就是 上 n - 1阶的路线 + n - 2阶的路线 # 所以 f(n) = f(n - 1) + f(n - 2) # 递归的方式 如下 def climbing_stairs(n=0): if n == 1: return 1 if n == 2: return 2 return climbing_stairs(n - 1) + climbing_stairs(n - 2) # 其实这道题 如果用遍历的方式也可以解决的 # 其实就是一个斐波那契数列,因为f(n) = f(n - 1) + f(n - 2) # 而 n = 1的时候 解 = 1 # n = 2的时候 解 = 2 # n = 3 的时候 解 = 1 + 2 = 3 # 1 1 2 3 5 8 def climbing_stairs2(n=0): i = 1 cur = 1 prev = 0 while i <= n: temp = cur cur += prev prev = temp i += 1 return cur # Gray Code # The gray code is a binary numeral system where two successive values differ in only one bit. # Given a non-negative integer n representing the total number of bits in the code, print the sequence of # gray code. A gray code sequence must begin with 0. # For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: # 00 - 0 # 01 - 1 # 11 - 3 # 10 - 2 # Note: # • For a given n, a gray code sequence is not uniquely defined. # • For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. # • For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. # 格雷编码 # 格雷编码是一个二进制数字系统,其中两个连续的值只有一个比特不同 # 给定一个非负整数 打印这个数的格雷序列编码,一个格雷码必须以0开头 # 例如 给n = 2 ,返回的是[0,1,3,2] # gray code # 格雷码 的计算方式是 保留自然二进制码的最高位作为格雷码的最高位,格雷码次高位为二进制码的高位与次高位异或 # 其余各位的求法类似 # 例如 自然二进制码 1001 ,转换成格雷码的过程是:保留最高位,然后将第1位的1和第2位的0异或,得到1,作为格雷码的第2位 # 将第2位的0和第3位的0异或,得到0,作为格雷码的第3位 # 将第3位的0和第4位的1异或,得到1,作为第4位,最终,格雷码为1101 # 自然二进制码转换为格雷码 # 保留格雷码的最高位作为自然二进制码的最高位,次高位为自然二进制高位和格雷码次高位异或,其余各位类似 # 比如讲格雷码1000 转换为自然二进制码的过程是: # 保留最高位1,作为自然二进制码的最高位,然后将自然二进制码的第1位的1和格雷码的第2位的0异或,得到1,作为自然二进制码的 # 第2位,将自然二进制码的第3位1和格雷码的第4位9异或,得到1,作为自然二进制码的第4位,最终,自然二进制码为1111 # # 异或:如果两个值不相同,则异或的结果为1,如果两个值相同,则异或的结果为0 # 这道题要求生成 n 位二进制代码的所有格雷码 # 比如 n = 3 # 二进制 》 格雷码 》 10进制 # 000 》 000 》 0 # 001 》 001 》 1 # 010 》 011 》 3 # 011 》 010 》 2 # 100 》 110 》 6 # 101 》 111 》 7 # 110 》 101 》 5 # 111 》 100 》 4 # 利用数学公式,对0 到 2~n - 1的所有整数,转化为格雷码 # def gray_code(n=0): size = 1 << n result = list() for i in range(size): result.append(binary_to_gray(i)) return result def binary_to_gray(i=0): return i ^ (i >> 1) # 当前位的值 异或上 上一位的值 # Set Matrix Zeroes # Given a m * n matrix, if an element is 0, set its entire row and column to 0. Do it in place. # Follow up: Did you use extra space? # A straight forward solution using O(mn) space is probably a bad idea. # A simple improvement uses O(m + n) space, but still not the best solution. # Could you devise a constant space solution? # 给定一个 m * n的矩阵,如果元素是0 ,那么就将整个行和列设置为0, # 你是否使用了额外的内存空间 # 如果解法使用了O(m * n)大小的内存,就是一个bad idea # 如果使用的是O(m + n)大小的内存,就有一些进步了,但是依然不是最好的解法 # 你能否实现一个使用常数 大小的内存空间的解法呢? def matrix_zeroes(L=[]): m = len(L) n = len(L[0]) print(L) row_has = False column_has = False # 说明行有0 for i in range(m): if L[i][0] == 0: row_has = True break # 说明竖有0 for j in range(n): if L[0][j] == 0: column_has = True break # 遍历其他行列 如果有0 就将该数组的值设为0 for i in range(m): for j in range(n): if L[i][j] == 0: L[i][0] = 0 L[0][j] = 0 # 分别数组 如果第一行和第一列对应位置为0 那么设置为0 for i in range(m): for j in range(n): if L[i][0] == 0 or L[0][j] == 0: L[i][j] = 0 if row_has: for i in range(m): L[i][0] = 0 if column_has: for j in range(n): L[0][j] = 0 print(L) # Gas Station # There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. # You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next # station (i+1). You begin the journey with an empty tank at one of the gas stations. # Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1. # Note: The solution is guaranteed to be unique. # # 沿途有n个加气站 ,每个站拥有的天然气数量是 gas[i],你有一辆 无限大气罐的车,到下一个加气站(i + 1)需要花费的天然气 是 costs[i] # 你从目前是空车 并从任意一个加气站出发 # 如果能够环绕一圈 就返回你出发的加气站的index ,否则的话 返回 -1 # # 额。。。这道题呢 主要就是一个关键点 消耗的天然气和加油站拥有的天然气的差值 # 比如可以从差值最大的地方出发 # # 每个站点的结余可以看着 diff[i] = gas[i] - cost[i] # 那么如果从m点出发 到达p点 车里剩余的天然气数量是 diff[m] + diff[m+1]+....+diff[p] = sum1 ,如果sum1 < 0 ,说明从m点出发不能环绕一圈 # 那么我们从 p+1点出发,直到n点 剩余的天然气数量是 diff[p+1]+diff[p+1+1]+....+diff[n] = sum2,如果sum2 <0 ,说明还是不能成功环绕一圈 # 那么我们从 n+1点出发,知道m点,剩余的天然气数量是 diff[n+1] + diff[n+1+1]+...+diff[m] = sum3 ,如果sum3 > 0 ,说明从n+1点到m点,还能有剩余的天然气 # 那么依次类推 如果 sum1 + sum2 +...+sumN > 0 说明就可以环绕一圈 # 那如果不行的话 就不可以 # 所以 def gas_station(gas=[], cost=[]): total = 0 sum1 = 0 index = 0 i = 0 while i < len(gas): total += gas[index] - cost[index] sum1 += gas[index] - cost[index] # 当前的所有值 如果total 小于0 那么就重置sum 并记下标记点 if sum1 < 0: sum1 = 0 index = i if total > 0: return index + 1 return -1 # Candy # There are N children standing in a line. Each child is assigned a rating value. # You are giving candies to these children subjected to the following requirements: # • Each child must have at least one candy. # • Children with a higher rating get more candies than their neighbors. # What is the minimum candies you must give? # # 这里有n个小孩子站在一条线上,每个都有一个评分值 # 你按照下面的要求 给这些小孩子分糖果 # 每个孩子至少有一个糖果 # 如果孩子的评分值越高 他获得的糖果就比他临近的人更多 # 请问 至少需要多少个糖果 # # 判断两个分值大小 # 如果A[i+1] > A[i] 那么 A[i+1]的糖果最好的数量就是 i位置的糖果数量 + 1 # 那如果A[i+1] <= A[i] 那应该给多少糖果呢?好像不太能确定到底该给多少糖果 因为我们需要给尽可能的少 # # 我们的思路就可以 首先遍历一遍 大的话 就+1 # 如果小的话 我们就 不知道应该填入多少了 # 如果遇到 1 5 4 3 2 这样的数列 # 首先 1孩子 给1个糖果 # 5孩子给 2个糖果的话 # 那么 4孩子 只能给一个糖果 # 那么3孩子就不能给了 所以就有问题 # 说明5孩子应该给的比预计中的还要多 # 而这个5孩子给的数量 其实跟 5 4 3 2 这个递减数列的长度有关系 # 如果递减数列 长度为4 那么第一个值至少也要为4 # 所以 我们可以通过引入一个修正值的方式 来实现一次遍历 就计算出total数 # 修正值的作用就是 # 思路: # 首先 从左往右遍历 确保 右边比左边高的小朋友的糖果数比左边多 # 然后 从右往左遍历 使得 左边比右边得分高的小朋友 糖果数比右边多 # # 例如 1 5 4 3 2 # 第一次遍历 # 1 2 0 0 0 # 第二次遍历 # 1 4 3 2 1 # 例如 1 5 4 2 3 # 第一次遍历 # 1 2 0 0 1 # 第二次 # 1 3 2 1 2 # 当然 题目要求 只需要total 也就是最少的糖果数量 # 并不需要知道每个孩子具体分多少个 # 所以 其实还有更加节省空间和时间的方法 # 这里就不多说了 # def candy(L=[]): result = list(range(len(L))) print(L) for i in range(len(L)): if i == 0: result[i] = 1 continue if L[i] > L[i - 1]: if result[i - 1] == 0: result[i - 1] = 1 result[i] = result[i - 1] + 1 else: result[i] = 0 j = len(L) - 1 while j > 0: if j == len(L) - 1 and result[j] == 0: result[j] = 1 j -= 1 continue if L[j] > L[j + 1]: if result[j] <= result[j+1]: result[j] = result[j+1] + 1 j -= 1 print(result) # Single Number # Given an array of integers, every element appears twice except for one. Find that single one. # Note: Your algorithm should have a linear runtime complexity. Could you implement it without using # extra memory? # # 一个数异或同一个数两次的话 就是他本身 # 所以 我们可以根据异或的特点 写出时间复杂度O(n)和空间复杂度O(1)的算法 def single_num(L=[]): result = 0 for i in range(len(L)): result = result ^ L[i] return result # Single Number II # Given an array of integers, every element appears three times except for one. Find that single one. # Note: Your algorithm should have a linear runtime complexity. Could you implement it without using # extra memory? # # 有一个int数组,除了某一个元素之外,每个元素都出现了三次 ,找出只出现了一次的这个,而且要求不能使用额外的内存空间 # 这个是上面那个题的变种 # ~按位取反 # ^ 异或 def single_sum_2(L=[]): a = 0 b = 0 for i in range(len(L)): b = (b ^ L[i]) & ~a a = (a ^ L[i]) & ~b return b print(single_sum_2([1, 5, 1, 1, 2, 2, 2]))
import pandas as pd from can_tools.scrapers.base import DatasetBaseNoDate, InsertWithTempTableMixin BASEURL = "https://www.census.gov" DATEURL = "https://www.census.gov/econ/bfs/csv/date_table.csv" class CensusBFS(InsertWithTempTableMixin, DatasetBaseNoDate): """ The Business Formation Statistics (BFS) are an experimental data product of the U.S. Census Bureau developed in research collaboration with economists affiliated with Board of Governors of the Federal Reserve System, Federal Reserve Bank of Atlanta, University of Maryland, and University of Notre Dame. The BFS provide timely and high frequency information on new business applications and formations in the United States. More information on Census Bureau Experimental Data products can be found [here](https://www.census.gov/data/experimental-data-products.html). For more information on what this data includes, please refer to the [Cenus site](https://www.census.gov/econ/bfs/index.html?#) or the [data dictionary](https://www.census.gov/econ/bfs/pdf/bfs_weekly_data_dictionary.pdf) Parameters ---------- geo : str Indicates which geography that you'd like the data for. Can either be "us", "region", or "state" """ pks = { "us": ("year", "week"), "region": ("region", "year", "week"), "state": ("state", "year", "week"), } def __init__(self, geo: str): self.geo = geo.lower() self.url = BASEURL + f"/econ/bfs/csv/bfs_{self.geo}_apps_weekly_nsa.csv" self.pk = self.pks[self.geo] self.table_name = f"bfs_{self.geo}" def get(self): # Download the data and the corresponding dates df = pd.read_csv(self.url) dates = pd.read_csv(DATEURL, parse_dates=["Start date", "End date"]) # Merge the data and dates and rename columns out = df.merge(dates, on=["Year", "Week"], how="left") out = out.rename( columns={ "Start date": "week_start", "End date": "week_end", } ) out.columns = [c.lower() for c in out.columns] return out
import random # random.random() 获取0~1之间的随机小数 # 返回一个0~1之间的随机小数 num1 = random.random() print('num1 =', num1) # random.choice(序列) # 随机返回序列中的某个值 list1 = [i for i in range(0,10)] print('list1 = ', list1) num2 = random.choice(list1) print('num2 =', num2) # random.shuffle(列表) # 随机打乱列表 # 返回值为None random.shuffle(list1) print('shuffle_list1 = ', list1) # random.randint(a, b) # 随机返回一个[a, b]之间的整数 # help(random.randint) num3 = random.randint(0, 100) print('num3 = ', num3)
''' 讨论 一般来讲,创建一个多值映射字典是很简单的。但是,如果你选择自己实现的话, 那么对于值的初始化可能会有点麻烦,你可能会像下面这样来实现: ''' from collections import defaultdict d1 = {} pairs =[ ['a',[1,2,3]], ['b',['a','b','c']] ] for key, value in pairs: if key not in d1: d1[key] = [] d1[key].append(value) print(d1) # 如果使用 defaultdict 的话代码就更加简洁了: d2 = defaultdict(list) for key, value in pairs: d2[key].append(value) print(d2)
''' 问题 你想构造一个字典,它是另外一个字典的子集。 解决方案 最简单的方式是使用字典推导。比如: ''' prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'} new_prices1 = {key:value for key,value in prices.items() if value > 200} new_prices2 = {key:value for key,value in prices.items() if key in tech_names} print("new_prices1:", new_prices1) print("new_prices2:", new_prices2) ''' 讨论 大多数情况下字典推导能做到的,通过创建一个元组序列然后把它传给 dict() 函 数也能实现。比如: ''' t1 = tuple((key, value) for key, value in prices.items() if value > 200) # print(t1) new_prices3 = dict(t1) print("new_prices3:", new_prices3) ''' 但是,字典推导方式表意更清晰,并且实际上也会运行的更快些(在这个例子中, 实际测试几乎比 dcit() 函数方式快整整一倍)。 有时候完成同一件事会有多种方式。比如,第二个例子程序也可以像这样重写: ''' new_prices4 = {key:prices[key] for key in prices.keys() & tech_names} print('new_prices4:', new_prices4) ''' 但是,运行时间测试结果显示这种方案大概比第一种方案慢 1.6 倍。如果对程序运 行性能要求比较高的话,需要花点时间去做计时测试。 '''
import threading import time # help(threading.Thread) # 类继承自threading.Thread class MyThread(threading.Thread): def __init__(self, arg): super(MyThread, self).__init__() self.arg = arg # 必须重写run函数,run函数代表的是真正执行的功能 def run(self): time.sleep(2) print('The args for this class is {0}'.format(self.arg)) for i in range(1, 6): t = MyThread(i) t.start() t.join() print('Main is done!')
# #str()返回一个用户易读的字符串,repr()返回一个计算器易读的字符串 # str1 = 'hello world' # print(str(str1)) # print(repr(str1)) # #输出格式美化、 # #rjust()函数使字符串靠右对齐,在左边补齐空格,还有类似的方法ljust(),center(), # #这些函数只会补齐空格不会添加其他内容 # #zfill()函数会在数字的左边补齐0 # #输出一个平方立方表 # for x1 in range(1,11): # print(repr(x1).rjust(4), repr(x1*x1).rjust(4), end=" ") # print(repr(x1*x1*x1).rjust(4)) # for x2 in range(1,11): # print("{0:3d}{1:4d}{2:5d}".format(x2, x2*x2, x2*x2*x2)) # #打印乘法口诀 # for i in range(1,10): # for j in range(1,i+1): # print("{0}*{1}={2}".format(i,j,i*j).rjust(7),end=" ") # print("") # #读写文件 # #open(filename, mode),返回一个file对象 # file1 = open('C:/Users/Administrator/Desktop/1.txt', 'r+') #打开文件 # # print(file1.read()) #读取文件中的所有内容 # print(file1.readline()) #读取文件中的一行 # print(file1.readline()) # print(file1.readlines()) #返回该文件的所有行 # file1.close() #关闭文件 # #迭代读取文件所有行 # file2 = open('C:/Users/Administrator/Desktop/1.txt', 'r+') # for line in file2: # print("line:",line) # file2.close() # file3 = open('C:/Users/Administrator/Desktop/1.txt', 'r+') # str1 = '55555555' # print("write_size:",file3.write(str1)) #往文件内写内容,返回写入字符个数 # print(file3.read()) # print(file3.tell()) # file3.close() # # file4 = open('C:/Users/Administrator/Desktop/1.txt', 'r+') # print(file4.readline()) # print(file4.tell()) #返回文件当前所处位置 # file4.close() file5 = open('C:/Users/Administrator/Desktop/hello.txt', 'a+') str_hello = 'hello,wld' print("write_size:",file5.write(str_hello)) file5.close() file5 = open('C:/Users/Administrator/Desktop/hello.txt', 'a+') # print("hello.txt:",file5.readline()) # file5.seek(-2, 1) file5.write("or") # print("hello.txt:",file5.read()) file5.close() file5 = open('C:/Users/Administrator/Desktop/hello.txt', 'r+') print("hello.txt:",file5.read()) file5.close()
import re str1 = "hello 123 hello 456 hello 789" p = re.compile(r'([a-zA-Z]+) ([0-9]+)') # help(p.sub) # Help on built-in function sub: # sub(repl, string, count=0) method of _sre.SRE_Pattern instance # Return the string obtained by replacing the leftmost non-overlapping # occurrences of pattern in string by the replacement repl. repl = 'hello world' p1 = p.sub(repl, str1) print("str1:{0}".format(str1)) print("p1 :{0}".format(p1))
''' 另外一种方式是使用 operator.attrgetter() 来代替 lambda 函数: 讨论 选择使 用 lambda 函数或者 是 attrgetter() 可能取决 于个人 喜好。但是, attrgetter() 函数通常会运行的快点,并且还能同时允许多个字段进行比较。这 个跟 operator.itemgetter() 函数作用于字典类型很类似(参考 1.13 小节)。例如, 如果 User 实例还有一个 first_name 和 last_name 属性,那么可以向下面这样排序: by_name = sorted(users, key=attrgetter('last_name', 'first_name')) ''' from operator import attrgetter class User(): def __init__(self, id, name): self.user_id = id self.user_name = name def __repr__(self): return 'User({0}, {1})'.format(self.user_id, self.user_name) def sort_notcompare(): user = [User(99, 'zyp'), User(3, 'gyj'), User(20, 'gzy'), User(99, 'zy')] print(user) # sort_user = sorted(user, key=lambda u: u.user_id) sort_user = sorted(user, key = attrgetter('user_id','user_name')) print(sort_user) # 同样需要注意的是,这一小节用到的技术同样适用于像 min() 和 max() 之类的函 # 数。比如: min_user = min(user, key = attrgetter('user_id')) max_user = max(user, key = attrgetter('user_id')) print(min_user) print(max_user) sort_notcompare()
''' 在定义正则式的时候,通常会利用括号去捕获分组。比如: ''' import re pattern = re.compile(r'(\d+)+/(\d+)+/(\d+)') text1 = '11/22/2018' text2 = 'Today is 11/27/2012. PyCon starts 3/13/2013.' result1 = pattern.match(text1) # result2 = pattern.findall(text) print(result1) print(result1.group(0)) print(result1.group(1)) print(result1.group(2)) print(result1.group(3)) print(result1.groups()) month, day, year = result1.groups() print("{0}-{1}-{2}".format(year, month, day)) print("---" * 20) result2 = pattern.findall(text2) # print(result2) for i in result2: # print(i) month,day,year = i print("{0}-{1}-{2}".format(year,month,day)) ''' findall() 方法会搜索文本并以列表形式返回所有的匹配。如果你想以迭代方式返 回匹配,可以使用 finditer() 方法来代替,比如: ''' print("---" * 20) result3 = pattern.finditer(text2) for i in result3: print(i.groups()) ''' 讨论 关于正则表达式理论的教程已经超出了本书的范围。不过,这一节阐述了使用 re 模块进行匹配和搜索文本的最基本方法。核心步骤就是先使用 re.compile() 编译正则 表达式字符串,然后使用 match() , findall() 或者 finditer() 等方法。 当写正则式字符串的时候,相对普遍的做法是使用原始字符串比如 r'(\d+)/ (\d+)/(\d+)' 。这种字符串将不去解析反斜杠,这在正则表达式中是很有用的。如果 不这样做的话,你必须使用两个反斜杠,类似 '(\\d+)/(\\d+)/(\\d+)' 。 需要注意的是 match() 方法仅仅检查字符串的开始部分。它的匹配结果有可能并 不是你期望的那样。比如: ''' result4 = pattern.match('11/27/2012abcdef') print(result4) print(result4.group()) ''' 如果你想精确匹配,确保你的正则表达式以 $ 结尾,就像这么这样: ''' new_pat = re.compile(r'(\d+)/(\d+)/(\d+)$') result5 = new_pat.match('11/27/2012abcdef') result6 = new_pat.match('11/27/2012') print(result5) # print(result5.group()) print(result6.group()) ''' 最后,如果你仅仅是做一次简单的文本匹配/搜索操作的话,可以略过编译部分, 直接使用 re 模块级别的函数。比如: >>> re.findall(r'(\d+)/(\d+)/(\d+)', text) [('11', '27', '2012'), ('3', '13', '2013')] >>> 但是需要注意的是,如果你打算做大量的匹配和搜索操作的话,最好先编译正则表 达式,然后再重复使用它。模块级别的函数会将最近编译过的模式缓存起来,因此并不 会消耗太多的性能,但是如果使用预编译模式的话,你将会减少查找和一些额外的处理 损耗。 '''
""" 处理指定路径下的图片 可以指定处理后的尺寸 """ from PIL import Image import os # import sys def input_file_name(file_path, file_name, file_list): """输入要进行操作的文件""" if file_name in file_list: handle_image() return "处理成功" else: return "该文件不存在!" def read_file_path(file_path): """读取文件夹,显示文件夹内容""" file_list = os.listdir(file_path) print("该目录的所有图片:") for file in file_list: if file.endswith('.png') or file.endswith('.jpg') or file.endswith('.jpeg'): print(file) return file_list def handle_image(): """对图片进行处理""" try: # 获取压缩尺寸 size_str = input("请输入压缩后的尺寸:") size = (int(size_str.split('*')[0]), int(size_str.split('*')[1])) # 图片处理 im = Image.open(file_path+file_name) im.thumbnail(size) im.save(file_path+file_name) return "success" except Exception as e: print('error:', e) if __name__ == "__main__": file_path = input("请输入文件路径:") file_list = read_file_path(file_path) file_name = input("请输入图片名:") result = input_file_name(file_path, file_name, file_list) print(result)
## 3. 多态 #### - 多态就是同一个对象在不同情况下有不同的状态出现 #### - 多态不是语法,是一种设计思想 #### - 多态性:一种调用方式, 不同的执行效果 #### - 多态:同一事物的多种形态,动物分为人类,狗类.... ## MiXin设计模式 #### - 主要采用多继承的方式对类的功能进行扩展 # ## 使用Mixin类实现多重继承要非常小心 #### -首先它必须表示某一种功能,而不是某个物品,如同Java中的Runnable,Callable等 #### -其次它必须责任单一,如果有多个功能,那就写多个Mixin类 #### -然后,它不依赖于子类的实现 #### -最后,子类即便没有继承这个Mixin类,也照样可以工作,就是缺少了某个功能。 # class Vehicle(object): pass class PlaneMixin(object): def fly(self): print 'I am flying' class Airplane(Vehicle, PlaneMixin): pass # 可以看到,上面的Airplane类实现了多继承,不过它继承的第二个类我们起名为PlaneMixin, # 而不是Plane,这个并不影响功能,但是会告诉后来读代码的人,这个类是一个Mixin类。所以从含义上理解, # Airplane只是一个Vehicle,不是一个Plane。这个Mixin,表示混入(mix-in),它告诉别人, # 这个类是作为功能添加到子类中,而不是作为父类,它的作用同Java中的接口。
# coding:utf-8 """ 二叉树的实现 深度优先遍历 - 先序遍历 - 中序遍历 - 后序遍历 02.py递归实现 03.py栈实现 """ class Node(object): """树的节点""" def __init__(self, item): self.item = item # 左右子节点 self.lchild = None self.rchild = None class BinaryTree(object): """二叉树""" def __init__ (self): """二叉树初始化""" self.root = None def add(self, item): node = Node(item) if self.root is None: self.root = node return else: # 借助队列遍历 queue = [] queue.append(self.root) # 对已有节点遍历 while queue: current = queue.pop(0) if current.lchild is None: # 如果左边子节点为空则添加到左边 current.lchild = node return elif current.rchild is None: current.rchild = node return else: # 如果左右子节点均存在,则将左右子节点添加到队列然后继续遍历 queue.append(current.lchild) queue.append(current.rchild) def preorder_travel(self, root): """先序遍历""" if root is None: return else: print(root.item, end=' ') self.preorder_travel(root.lchild) self.preorder_travel(root.rchild) def inorder_travel(self, root): """中序遍历""" if root is None: return else: self.inorder_travel(root.lchild) print(root.item, end=' ') self.inorder_travel(root.rchild) def postorder_travel(self, root): """后序遍历""" if root is None: return else: self.postorder_travel(root.lchild) self.postorder_travel(root.rchild) print(root.item, end=' ') if __name__ == "__main__": bt1 = BinaryTree() bt1.add("0") bt1.add("1") bt1.add("2") bt1.add("3") bt1.add("4") bt1.add("5") bt1.add("6") bt1.add("7") bt1.add("8") bt1.add("9") print("先序遍历:") bt1.preorder_travel(bt1.root) print(" ") print("中序遍历") bt1.inorder_travel(bt1.root) print(" ") print("后序遍历") bt1.postorder_travel(bt1.root)
import numpy a = numpy.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) b = numpy.array([1,2,3,4]) # 将b中的数据加到a上 # 1.使用for循环 for i in range(3): a[i,0:4] += b print("a:\n", a) # 2.使用tile()函数 a = a + numpy.tile(b,(3,1)) print("a:\n", a) # 3.直接相加 a = a+b print("a:\n", a)
import time # 定义一个装饰器 def PrintTime(func): def wrapper(*args, **kwargs): print("Time:", time.ctime()) return func(*args, **kwargs) return wrapper # 使用一个装饰器 # 借助@语法糖 @PrintTime def hello(): print("hello world!") hello() def func1(): print("This is func1!") @PrintTime def func2(): print('This is func2!') func1() func2() # 手动执行装饰器 def hello2(): print("这里手动执行装饰器") # hello2 = PrintTime(hello2) # hello2() # PrintTime(hello2) f = PrintTime(hello2) f() # 会打印两次时间? 注释掉上面的hello2() = PrintTime(hello2)就可以 # 只出现一次
# 访问一个网址 # 更改自己的UserAgent进行伪装 from urllib import request url = 'http://www.baidu.com' # 1.直接设置 # headers = { # 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # } # # 也可以这样 # # headers = {} # # headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # req = request.Request(url, headers = headers) # 2.使用函数add_header设置 # add_header(key, val) method of urllib.request.Request instance # # help(req.add_header) req = request.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36') response = request.urlopen(req) html = response.read() print(html.decode())
''' 解析xml文件 ''' from lxml import etree def parse(): # 获取ElementTree tree = etree.parse("test01.xml") # print(tree) # 获取根元素 root = tree.getroot() print(root) # get(attrib)可以获得指定属性值 print("root.name:", root.get("name")) print("root.tag:{0}, root.attrib:{1}, root.text:{2}".format(root.tag, root.attrib, root.text)) # 迭代获取子元素 for child in root: print("child.tag:{0}, child.attrib:{1}, child.text:{2}".format(child.tag, child.attrib, child.text)) for child_child in child: print("child_child.tag:{0}, child_child.attrib:{1}, child_child.text:{2}".format(child_child.tag, child_child.attrib, child_child.text)) if __name__ == "__main__": parse()
import socket def tcp_server(): ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 8888 addr = (host, port) ss.bind(addr) ss.listen(5) while True: conn, address = ss.accept() print("链接地址:", address) while True: data = conn.recv(1024) if len(data) == 0: break text = data.decode() print("接收到的内容为:", text) conn.send(data) conn.close() ss.close() if __name__ == "__main__": print("starting.......") tcp_server() print("ending......")
from collections import namedtuple stu = namedtuple('Student', ['id', 'all_result', 'n']) stu_info = [ ('zyp', 300, 3), ('gzy', 250, 3), ('zy', 200, 3), ] def Grade(stu_info): # avg = 0 for info in stu_info: avg = info[1]/info[2] print(avg) Grade(stu_info) # 下标操作通常会让代码表意不清晰,并且非常依赖记录的结构。下面是使用命名元组的版本: def Grade_new(stu_info): for info in stu_info: s1 = stu(*info) avg = s1.all_result/s1.n print(avg) Grade_new(stu_info)
''' ChainMap 对于编程语言中的作用范围变量(比如 globals , locals 等)是非常有 用的。事实上,有一些方法可以使它变得简单: ''' from collections import ChainMap values = ChainMap() values['x'] = 1 values['y'] = 2 print(values) # add a new mapping values2 = values.new_child() values2['x'] = 10 values2['y'] = 20 print(values2) # add a new mapping values3 = values2.new_child() values3['x'] = 100 values3['y'] = 200 print(values3) print(values3['x']) # discard last mapping values4 = values3.parents print(values4) print(values4['x']) # dicard last mapping values5 = values4.parents print(values5) print(values5['x'])
''' 利用time函数,生成两个函数 顺序调用 计算总的运行时间 ''' import time def loop1(): print("start loop1 {}".format(time.ctime())) time.sleep(5) print("end loop1 {}".format(time.ctime())) def loop2(): print('start loop2 {}'.format(time.ctime())) time.sleep(3) print("start loop2 {}".format(time.ctime())) def main(): print('start time {}'.format(time.ctime())) loop1() loop2() print('end time {}'.format(time.ctime())) if __name__ == '__main__': main() # main()函数需要5s+3s运行时间
# 喜欢的数字 :编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。 # 再编写一个程序,从文件中读取这个值,并打印消息“I knowyour favorite number! It's _____.”。 import json # filename = input('please input filename:') filename = 'filename.json' with open(filename, 'w') as f: number = input('input a number:') json.dump(number, f) with open(filename, 'r') as f: number = json.load(f) print("The number you entered is {0}".format(number))
import re # help(re.search) # Help on function search in module re: # search(pattern, string, flags=0) # Scan through string looking for a match to the pattern, returning # a match object, or None if no match was found. p = re.compile(r'([a-z]+) ([a-z]+)') # help(p.search) # Help on built-in function search: # search(string=None, pos=0, endpos=9223372036854775807, *, pattern=None) method of _sre.SRE_Pattern instance # Scan through string looking for a match, and return a corresponding match object instance. # Return None if no position in the string matches. str1 = "this is a string" p1 = p.search(str1) print(p1) p2 = p.search(str1, pos = 5, endpos = 10) print(p2)
''' 讨论 如果你仅仅就是想消除重复元素,通常可以简单的构造一个集合。比如: 然而,这种方法不能维护元素的顺序,生成的结果中的元素位置被打乱。而上面的 方法可以避免这种情况。 在本节中我们使用了生成器函数让我们的函数更加通用,不仅仅是局限于列表处 理。比如,如果如果你想读取一个文件,消除重复行,你可以很容易像这样做: ''' a = [1, 5, 2, 1, 9, 1, 5, 10] set_a = set(a) print(set_a) def dedupe(f): set_f = set() for line in f: # print(line) if line not in set_f: # yield line set_f.add(line) print(set_f) # print(str(set_f)) with open('remove'+f.name, 'w') as new_f: new_f.writelines(set_f) with open('v03.txt', 'r') as f: print(f.name) print(type(f.name)) dedupe(f)
''' 如果你想在一个集合中查找最小或最大的 N 个元素,并且 N 小于集合元素数量, 那么这些函数提供了很好的性能。因为在底层实现里面,首先会先将集合数据进行堆排 序后放入一个列表中 堆数据结构最重要的特征是 heap[0] 永远是最小的元素。并且剩余的元素可以很 容易的通过调用 heapq.heappop() 方法得到,该方法会先将第一个元素弹出来,然后 用下一个最小的元素来取代被弹出元素(这种操作时间复杂度仅仅是 O(log N),N 是 堆大小)。比如,如果想要查找最小的 3 个元素,你可以这样做: 当要查找的元素个数相对比较小的时候,函数 nlargest() 和 nsmallest() 是很 合适的。如果你仅仅想查找唯一的最小或最大(N=1)的元素的话,那么使用 min() 和 max() 函数会更快些。类似的,如果 N 的大小和集合大小接近的时候,通常先排序这个 集合然后再使用切片操作会更快点(sorted(items)[:N] 或者是 sorted(items)[-N:] )。需要在正确场合使用函数 nlargest() 和 nsmallest() 才能发挥它们的优势(如果 N 快接近集合大小了,那么使用排序操作会更好些)。 尽管你没有必要一定使用这里的方法,但是堆数据结构的实现是一个很有趣并且 值得你深入学习的东西。基本上只要是数据结构和算法书籍里面都会有提及到。heapq 模块的官方文档里面也详细的介绍了堆数据结构底层的实现细节。 ''' import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print("nums:",nums) heap = list(nums) print("heap:",heap) # 堆排序 heapq.heapify(heap) print("heap:",heap) for i in range(1,len(heap)+1): num = heapq.heappop(heap) print("{0} --- {1}".format(i,num)) print(heap)
""" TCP客户端 1.socket建立 2.发送消息到指定服务器(ip + port) 3.等待反馈 """ import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 客户端绑定端口号,如果不绑定则由系统自动分配 s.bind(('127.0.0.1', 6666)) text = '你好'.encode() s.sendto(text, ('127.0.0.1', 9999)) data, addr = s.recvfrom(1024) print("接收到来自{}的反馈信息:{}".format(addr, data.decode()))
''' 如果你想检查多种匹配可能,只需要将所有的匹配项放入到一个元组中去,然后传 给 startswith() 或者 endswith() 方法: ''' import os filelist = os.listdir('f:/python/oop') for filename in filelist: print(filename) match = ('.py', '.md') new_list = [filename for filename in filelist if filename.endswith(match)] for i in new_list: print(i) print(any(name.endswith('.txt') for name in filelist)) ''' 奇怪的是,这个方法中必须要输入一个元组作为参数。如果你恰巧有一个 list 或 者 set 类型的选择项,要确保传递参数前先调用 tuple() 将其转换为元组类型。比如: ''' match2 = ['.py', '.md'] # new_list2 = [name.endswith(match2) for name in filelist] # endswith first arg must be str or a tuple of str, not list new_list2 = [name for name in filelist if name.endswith(tuple(match2))] print(new_list2)
import threading import time def loop1(in1): print("start loop1 {}".format(time.ctime())) print('这是参数1{0}'.format(in1)) time.sleep(5) print("end loop1 {}".format(time.ctime())) def loop2(in1, in2): print('start loop2 {}'.format(time.ctime())) print('这是参数1{0},这是参数2{1}'.format(in1, in2)) time.sleep(3) print("end loop2 {}".format(time.ctime())) def main(): print('start time {}'.format(time.ctime())) t1 = threading.Thread(target = loop1, args = (111, )) t2 = threading.Thread(target = loop2, args = (111, 222)) t1.start() t2.start() t1.join() t2.join() print('end time {}'.format(time.ctime())) if __name__ == '__main__': main()
#while 循环 #python 中没有do...while循环 #用while循环求0到九十九相加之和 n = 0 sum1 = 0 while n < 100: sum1 = sum1 + n n = n + 1 print("sum1:",sum1) #用for循环求0到99相加之和 m = 0 sum2 = 0 for m in range(0,100): #range()函数用于 sum2 = sum2 + m print("sum2:",sum2) #使用range()和len()函数遍历一个序列的索引 student1 = ['靳淑佳', '杨浩然', '陈世创', '王畅', '谷嘉欣', '汪雨乐', '王一凡'] for i in range(len(student1)): print(i+1, student1[i]) #使用list() 和range()和tuple()函数创建列表和元组 list1 = list(range(5)) list2 = list(range(0,10)) list3 = list(range(0,99,9)) print(list1) print(list2) print(list3) tuple1 = tuple(range(5)) print(tuple1)
# 类的常用魔术方法 # 操作类: # - 魔术方法就是不需要人为调用的方法,基本是在特定的时刻自动触发 # - 统一特征:方法名被前后个两个下划线包裹,最常用 __init__(self) # - __call__ :在对象当函数使用时触发 # - __str__:当把对象当字符串使用时自动调用,返回一个字符串 # - __repr__: 返回字符串,跟__str__类似 # 描述符相关: # - __set__: # - __get__: # - __delete__: # 属性相关操作 # - __getattr__: 访问一个不存在的属性时触发 # - __setattr__: 对成员属性进行设置时触发 # __setattr__(self, set_attribute_name, set_attribute_value) # 运算类相关 # - __gt__: 进行对象之间大于判断时触发函数,返回值可以是任意值,推荐返回一个bool值 # __gt__(self, second_object) class A(): name = 'none' age = 20 def __init__(self, name = 0): print("__init__被调用") def __call__(self): print("__call__在对象当函数使用时被调用!") def __str__(self): return '把对象当字符串使用时自动调用' def __getattr__(self, attr): print("找不到该变量:{0}".format(attr)) a = A() a() print(a) print(a.name) print(a.age) print(a.attr) #因为该变量不存在,最后会打印出一个None # a.attr class Person(): def __init__(self): pass def __setattr__(self, AttrName, AttrValue): print("设置属性{0}:{1}".format(AttrName, AttrValue)) # self.AttrName = AttrValue # 会导致死循环,前面函数已经赋值了,不用再次赋值 # 在此情况下,为了避免死循环,规定统一调用父类魔法函数 super().__setattr__(AttrName, AttrValue) #********* p1 = Person() print(p1.__dict__) p1.age = 20 print(p1.__dict__) # __gt__ 案例 class Student(): def __init__(self, name): self.name = name def __gt__(self, object2): print("{0} > {1} ?".format(self.name, object2.name)) return self.name > object2.name s1 = Student("one") s2 = Student("two") print(s1 > s2)
import argparse parser = argparse.ArgumentParser() parser.add_argument("--start", help="first number") parser.add_argument("--end", help="last number") args = parser.parse_args() x = int(args.start or 0) y = int(args.end or 0) sum =0 for n in range(x,y+1): sum += n print sum
def divisibility(a,b): if (a%b)==0: return 0 else: return(b-(a%b)) t=int(input()) for loop in range(t): a,b=map(int,input().split()) print(divisibility(a,b))
import math n = int(input("Ingrese el radio: ")) print("El área del circulo es: ", 3.1416* n**2)
if(3 < 5): # <- Doppelpunkt print("3 ist kleiner als 5") # Wichtig: Einrückung! if(5 < 3): print("5 ist kleiner als 3") print("Eine zweite Zeile") # Alle Operatoren == != <= >= < > # Eingabe vom Benutzer einlesen # "Zur Sicherheit" in int umwandeln zahl = int(input("Eingabe: ")) # Testen auf Gleichheit und Ungleichheit if(zahl == 42): print("Eingabe ist 42.") if(zahl != 42): print("Eingabe ist nicht 42.") # falls ... ansonsten if(zahl == 42): print("Eingabe ist 42.") else: print("Eingabe ist nicht 42.") # falls ... andernfalls ... ansonsten if(zahl == 42): print("Eingabe ist 42.") elif(zahl > 42): print("Eingabe ist groesser als 42.") else: print("Eingabe ist nicht 42 und nicht groesser als 42.") # Falls mindestens eine der beiden wahr if(zahl == 42 or zahl == 7): print("Eingabe ist 42 oder 7.") # Falls beide wahr if((zahl != 42) and (zahl != 7)): print("Eingabe ist nicht 42 und nicht 7.") # Wahrheitswerte als Variablen wahrheitswert = True # False wäre auch möglich if(wahrheitswert): print("Wahr")
nome = input ('Qual é o teu nome?') idade = input ('Qual é a tua idade?') peso = input ('Qual é o teu peso?') print (nome, idade, peso)
from random import randint import time print('\033[1;4mDesafio 45 - GAME: Pedra, Papel e Tesoura\033[m') print("""\033[1mCrie um programa que faça o computador jogar Jokenpô com você.\033[m""") print('\033[1;35m♣\033[m'*60) print(' \033[1;4mPEDRA, PAPEL E TESOURA\033[m') print('\033[1;35m♣\033[m'*60) print("""Vamos jogar Pedra, Papel e Tesoura? Escolha entre as opções abaixo: \033[1m0 - Pedra 1 - Papel 2 - Tesoura\033[m""") item = ('Pedra', 'Papel', 'Tesoura') jogador = int(input('Digite a opção desejada: ')) ia = randint(0,2) print('\033[1;31mJOKEEEENNNPÔ!!! \033[m') time.sleep(2) print('\033[1;36m-=\033[m' * 13) print('\033[1mO Computador jogou {}.\033[m'.format(item[ia])) print('\033[1mO Jogador jogou {}.\033[m'.format(item[jogador])) print('\033[1;36m-=\033[m' * 13) if ia == 0: if jogador == 0: print('Temos um empate!') elif jogador == 1: print('O Jogador ganhou!') elif jogador == 2: print('O Computador ganhou!') elif jogador > 2: print('Jogada Inválida!') elif ia == 1: if jogador == 0: print('O Computador ganhou!') elif jogador == 1: print('Temos um empate!') elif jogador == 2: print('O Jogador venceu!') elif jogador > 2: print('Jogada Inválida!') elif ia == 2: if jogador == 0: print('O Jogador ganhou!') elif jogador == 1: print('O Computador ganhou!') elif jogador == 2: print('Temos um empate!') elif jogador > 2: print('Jogada Inválida!')
print('Desafio 78 - Maior e Menor valores na lista') print('Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. \nNo final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. ') print('') valores = [] menor = maior = 0 cont = 0 for cont in range(1, 6): valores.append(int(input('Digite um valor: '))) menor = min(valores) maior = max(valores) print('') print(f'O menor valor é {menor} e está na(s) posição(s)', end=' ') for i, v in enumerate(valores): if v == menor: print(f'{i}... ', end='') print('') print(f'O maior valor é {maior} e está na(s) posição(s)', end=' ') for i, v in enumerate(valores): if v == maior: print(f'{i}... ', end='')
print('Desafio 40 - Aquele clássico da Média') print("""Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida: - Média abaixo de 5.0: REPROVADO - Média entre 5.0 e 6.9: RECUPERAÇÃO - Média 7.0 ou superior: APROVADO""") print('\033[1;35m~\033[m'*70) print('\033[1m MÉDIA ESCOLAR\033[m') print('\033[1;35m~\033[m'*70) primeira = float(input('Digite a primeira nota: ')) segunda = float(input('Digite a segunda nota: ')) calculo = (primeira + segunda)/2 if calculo < 5.0: print('\033[31mO aluno está REPROVADO com a média de {:.1f}!\033[m'.format(calculo)) elif calculo >= 5.0 and calculo<= 6.9: print('\033[33mO aluno está em RECUPERAÇÃO com a média de {:.1f}!\033[m'.format(calculo)) else: print('\033[36mO aluno está APROVADO com a média de {:.1f}!\033[m'.format(calculo))
print('\033[1;4mDesafio 51 - Progressão Aritmética\033[m') print('\033[1mDesenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão.\033[m') print('\033[1;35m=\033[m'*35) print(' \033[1;4;36mOs 10 Primeiros Termos da PA\033[m') print('\033[1;35m=\033[m'*35) a1 = int(input('Digite o primeiro termo da PA: ')) razao = int(input('Digite a razão da PA: ')) an = a1 + (10 - 1) * razao for PA in range(a1, an+1, razao): print(PA,end=' -> ') print('FIM')
print('\033[1;4mDesafio 49 - Tabuada v.2.0\033[m') print('\033[1mRefaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.\033[m') print(' ') print('=-' * 10) print(' TABUADA') print('-=' * 10) print(' ') num = int(input('Digite um número: ')) print(' ') for multiplicador in range(1, 11): tabuada = '| {} * {:2} = {:2} |'.format(num, multiplicador, num*multiplicador) print(tabuada) #Outro modo de fazer #for m in range(1, 11): # result = num * m # tabuada = '| {} * {:2} = {:2} |'.format(num, m, result) # print(tabuada)
print('Desafio 34 - Aumentos múltiplos') print("""Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.""") sal = float(input('Digite o valor do salário do funcionário: ')) if sal > 1250: novo = (sal*10)/100+sal else: novo = (sal*15)/100+sal print('O salário reajustado será de R$ {:.2f}.'.format(novo))
import random print('\033[1;4mDesafio 20 - Sorteando uma ordem na lista\033[m') import math print('Um professor quer sortear a ordem de apresentação de trabalhos dos alunos. \nFaça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.') a1 = input('Digite o nome do primeiro aluno: ') a2 = input('Digite o nome do segundo aluno: ') a3 = input('Digite o nome do terceiro aluno: ') a4 = input('Digite o nome do quarto aluno: ') sorteio = [a1, a2, a3, a4] random.shuffle(sorteio) print('A ordem de apresentacao dos trabalhos sera: \033[35m{}\033[m.'.format(sorteio)) print('\033[36m=\033[m'*40) #=========================== '''from random import shuffle aluno1 = str(input('Digite o nome do aluno: ')) aluno2 = str(input('Digite o nome do aluno: ')) aluno3 = str(input('Digite o nome do aluno: ')) aluno4 = str(input('Digite o nome do aluno: ')) lista = [aluno1, aluno2, aluno3, aluno4] print('A ordem escolhida é {}.'.format(shuffle(lista)))'''
print('Desafio 39 - Alistamento Militar') print("""Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.""") print('\033[1;35m=-=\033[m'*30) print('\033[1m CONSULTORIA DE ALISTAMENTO MILITAR\033[m') print('\033[1;35m=-=\033[m'*30) import sys from datetime import date nome = input('Digite o teu nome: ') sexo = str(input('Qual o teu sexo? (M/F): ')) if sexo == 'F': print('Olá, sra. {}. O alistamento militar não é obrigatório para você.'.format(nome)) sys.exit() alistou = input('Você já se alistou anteriormente? (S/N): ') if alistou == 'S': print('Sr. {}, tudo está OK. Até mais!'.format(nome)) sys.exit() ano = int(input('Digite o ano do teu nascimento: ')) sistema = date.today().year idade = sistema - ano if idade > 18: print('\033[31mSr. {}, você está atrasado! Deveria ter se alistado há {} ano(s) atrás em {}. \nCompareça à Junta Militar mais próxima para fazer o teu alistamento!\033[m'.format(nome, idade - 18, sistema - (idade - 18))) elif idade == 18: print('\033[36mSr. {}, está na hora do alistamento militar. Compareça à Junta Militar mais próxima para iniciar o teu processo.\033[m'.format(nome)) else: print('\033[33mSr. {}, obrigado por consultar, mas você ainda não tem idade para o alistamento militar. \nFaltam {} ano(s) para a tua vez chegar. Teu alistamento será em {}. \nEsperamos vê-lo mais tarde!\033[m'''.format(nome, 18 - idade, sistema + (18 - idade)))
print('\033[1;4mDesafio 7 - Média Aritmética\033[m') nome = input('\033[34mNome do aluno:\033[m ') print('\033[1;4mDigite abaixo as notas do aluno:\033[m') port = int(input('\033[34mNota de Língua Portuguesa:\033[m ')) mat = int(input('\033[34mNota de Matemática:\033[m ')) media = (port+mat)/2 print('O aluno \033[34m{}\033[m tem a nota \033[33m{}\033[m em Língua Portuguesa, a nota \033[33m{}\033[m em Matemática e a média final das notas é \033[35m{}\033[m.'.format(nome, port, mat, media))
print('\033[1;4mDesafio 56 - Analisador Completo\033[m') print('\033[1mDesenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade \ndo grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos.\033[m') maior = 0 menor = 0 totidade = 0 nomevelho = '' homemvelho = 0 mulher = 0 for d in range(1,5): print('========== {}ª Pessoa =========='.format(d)) nome = str(input('Digite o nome: ')).lstrip().capitalize() idade = int(input('Digite a idade: ')) sexo = str(input('Digite o sexo (M/F): ')).lstrip().upper() totidade += idade if d == 1 and sexo in 'M': nomevelho = nome homemvelho = idade if sexo in 'M' and idade > homemvelho: homemvelho = idade nomevelho = nome if sexo == 'F': if idade < 20: mulher += 1 media = totidade / 4 print('A média das idades do grupo é \033[1;33m{}\033[m anos.'.format(media)) print('A homem mais velho tem \033[1;31m{}\033[m anos e se chama \033[1;31m{}\033[m.'.format(homemvelho, nomevelho)) print('O número de mulheres menores de 20 anos no grupo é \033[1;35m{}\033[m.'.format(mulher))
print('Desafio 83 - Validando Expressões Matemáticas') print('Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá analisar \nse a expressão passada está com os parênteses abertos e fechados na ordem correta.') print('') print('\033[1m=\033[m'*40) print(f'\033[1;35m{"EXPRESSÕES MATEMÁTICAS":^40}\033[m') print('\033[1m=\033[m'*40) print('') exp = str(input('Digite a expressão: ')) pilha = [] for simb in exp: if simb == '(': pilha.append('(') elif simb == ')': if len(pilha) > 0: pilha.pop() else: pilha.append(')') break if len(pilha) == 0: print('Sua expressão está válida!') else: print('Sua expressão está errada!') """abre = 0 fecha = 0 exp = input('Digite uma expressão matemática: ') abre = exp.count('(') fecha = exp.count(')') if abre == fecha: print(f'A expressão {exp} é uma expressão matemática válida.') elif abre != fecha: print(f'A expressão {exp} não é uma expressão matemática válida.')"""
print('\033[1;4mDesafio 76 - Lista de Preços em Tuplas\033[m') print('') print('\033[1mCrie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. \nNo final, mostre uma listagem de preços, organizando os dados em forma tabular.\033[m') print('') print('\033[1m-\033[m'*51) print(f'\033[1;33m{"LISTA DE PREÇOS":^50}\033[m') print('\033[1m-\033[m'*51) cont = 0 #tupla = ('Lápis', 1.75, 'Borracha', 2.00, 'Caderno', 15.90, 'Estojo', 25.00, 'Transferidor', 4.20, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.30, 'Livro', 34.90) tupla = ('Lápis', 'Borracha', 'Caderno', 'Estojo', 'Transferidor', 'Compasso', 'Mochila', 'Canetas', 'Livro', 1.75, 2.00, 15.90, 25.00, 4.20, 9.99, 120.32, 22.30, 34.90) for lista in tupla: print(f' {tupla[cont]:.<12}............................R$ {tupla[cont+9]:>6.2f}') cont += 1 if cont == 9: break print('-'*51) #for pos in range (0, len(tupla)): #if pos % 2 ==: #print(f'{tupla[pos]}')
# Задание 3 # По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b, проходящей через эти точки. print("Задание 3") a = input("Введите координаты точки А (x1,y1): ").split(",") b = input("Введите координаты точки B (x2,y2): ").split(",") x1 = int(a[0]) x2 = int(b[0]) y1 = int(a[1]) y2 = int(b[1]) if (x1 - x2) == 0: print("Ошибка деления на ноль. Выполнение будет прервано") else: k = (y1 - y2) / (x1 - x2) b = y2 - k * x2 print(f"Уравнение прямой с полученными коэффициентами - y = {k} * x + {b}") print("Конец задачи 3")
#!/usr/bin/env python3 max_length = 5 def take_user_input(): """ This function takes a user inputs, perform constraint checks and parses it @:return list of parsed user input """ input_word = input("Please Enter a single letter or a string of letters from the English Alphabet") checks_passed = perform_checks(input_word) if checks_passed: parsed_list = parse_input(input_word) return parsed_list else: print("Sorry, this is not an acceptable input. Please try again") raise ValueError def perform_checks(given_word): """ This function checks whether the input string is part of the english alphabet and if it fits in the given max_length constraint :param given_word: Input string :return: check: (True-> meets constraints)/(False-> doesn't meet constraints) """ global max_length check = True if len(given_word) > max_length: check = False if not given_word.isalpha(): check = False return check def parse_input(given_word): """ This function parses the input into a list of individual characters :param given_word: Input string :return: list of letters """ return list(given_word) if __name__ == '__main__': #Parsing check trial_word = "Hello" parsed = parse_input(trial_word) print("Parsed input:", parsed) #Check checks trial_word1 = "He21" trial_word2 = ";fkdwl?" check_result = perform_checks(trial_word) check_result1 = perform_checks(trial_word1) check_result2 = perform_checks(trial_word2) print("Test for {} : Result = {}".format(trial_word, check_result)) print("Test for {} : Result = {}".format(trial_word1, check_result1)) print("Test for {} : Result = {}".format(trial_word2, check_result2)) #Putting it all together final_result = take_user_input() print("Final Result: {}".format(final_result))
import numpy as np import datetime ## array [x:y] where x is index from which array needs to start and y is till ## when array is present # Create numpy single dimention array def create_1_dim_array(): a = np.array([1, 2, 3]) # Create a rank 1 array #print(type(a)) # Prints "<class 'numpy.ndarray'>" #print(a.shape) # Prints "(3,)" #call array by element same as array print a[0], a[1], a[2] # Prints "1 2 3" #change array element by index a[0] = 5 # Change an element of the array print a # Prints "[5, 2, 3]" def create_2_dim_array(): b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array #print(b.shape) # Prints "(2, 3)" #print b #array indexing print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4" def create_blank_arrays(n,m,k): #n*m array with K value if K is not used shoulb be left 0 a = np.zeros((n,m)) #create zeros of n*m #a = np.ones((n,m)) #create ones of n*m #a = np.full((n,m),k) #create k element of n*m #a = np.empty((n,m)) #create empty of n*m print a def create_multi_dim_array(): a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) print a # array [ limit rows, limit columns] # Cropping of array subarr = a[:2, 1:3] #print subarr # Accessing a row of array row = a[1] # or c[1,:] #print row # Accessing a column column = a[: , 1] #print column # Element of array array[row, cloumn] #print(a[0, 1]) # Prints "2" # change element of array #a[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1] #print(a[0, 1]) # Prints "77" # Integer indexing arr([[row numbers],[column element of perticular row]] #print a[[0, 1,2], [0, 1,3]] #0,1,2 rows (element 0 of 0th row,1st of 1st row #3rd of 2nd row # same can be achived by below trick - This trick can be useful while there is # need to get element/to operate on one element of each row by column index #b = [0, 1, 3] #print a [np.arange(3),b] #a [np.arange(3),b] += 10 #print a # equivalant to [a[0,0],a[1,1]] #print a[[0,0,0],[1,2,3]] # will print oth row 1,2,3 elements which is 2,3,4 # bool index is used to operate on entire array #bool_index = (a>2) #print bool_index def speed_check(): a = np.random.random_integers(5, high=6, size=(10,10)) ##print a ##curr_time = datetime.datetime.now() ##for i in range(0,len(a)): ## for j in range(0,len(a[0])): ## if a[i][j] > 5 : ## a [i][j] = True ## else: ## a[i][j] = False ##post_time = datetime.datetime.now() ##bool_index = (a>5) ## ##diff = post_time - curr_time ##print diff ##print bool_index def array_operation(): # dtype is datatype which can be int64,float64 etc x = np.array([[1,2],[3,4]], dtype=np.float64) y = np.array([[5,6],[7,8]], dtype=np.float64) # Elementwise sum; both produce the array # [[ 6.0 8.0] # [10.0 12.0]] #print(x + y) #same as print(np.add(x, y)) # Elementwise difference; both produce the array # [[-4.0 -4.0] # [-4.0 -4.0]] #print(x - y) #same as print(np.subtract(x, y)) # Elementwise product; both produce the array is done by '*' # [[ 5.0 12.0] # [21.0 32.0]] #print(x * y) #same as print(np.multiply(x, y)) # Product of array (dot product) is done by #print x.dot(y) # Elementwise division; both produce the array # [[ 0.2 0.33333333] # [ 0.42857143 0.5 ]] #print(x / y) #same as print(np.divide(x, y)) # Elementwise square root; produces the array # [[ 1. 1.41421356] # [ 1.73205081 2. ]] #print(np.sqrt(x)) # Numpy provides sum - row wise / column wise / whole matrix #print np.sum(x) # matrix sum #print np.sum(x, axis=0) # row wise #print np.sum(x, axis=1) # column wise # Transpose is done by #print x.T # Stacking of array #print np.hstack((x,y)) #Horizontal stacking #print np.vstack((x,y)) #Vertical stacking # Spliting of array a = np.floor(10*np.random.random((2,12))) #print np.hsplit(a,3) # Split a into 3 #print np.hsplit(a,(3,4)) #Split after 3rd and 4th column def broadcasting(): x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) y = np.empty_like(x) # Create an empty matrix with the same shape as x v = np.array([1,2,1]) #for i in range(0,len(x)): # y[i,:] = x[i,:] + v # Same can be done by #vv = np.tile(v,(4,1)) # Will copy v 4 times horizontally and 1 time verticaly #y = x + v # Or Just #y = x + v #print y
# Basic boxplot of a single column. ### Magic line to make plots appear on notebook %matplotlib inline def boxplot(df,col): import matplotlib.pyplot as plt fig = plt.figure(figsize=(9, 6)) ax = fig.gca() df.boxplot(column = col, ax = ax) ax.set_title('Box plot of ' + col) ax.set_ylabel(col) return col boxplot(flightDataframe, "ArrDelay") # Basic histogram of a single column. def histplot(df,col): import matplotlib.pyplot as plt fig = plt.figure(figsize=(9, 4)) ax = fig.gca() df.hist(column = col, ax = ax, bins = 30) ax.set_title('Histogram of ' + col) return col histplot(flightDataframe, "ArrDelay") # Histogram by groups def groupedhistplot (df, col, groupcol): import matplotlib.pyplot as plt #Use sharey to make it easier to compare different histograms side-by-side. df.hist(column = col, sharey = True, by = groupcol, bins = 30, figsize = [9,4]) plt.suptitle('Histogram of ' + col + ' grouped by ' + groupcol) return groupedhistplot(flightDataframe, 'DepDelay', 'ArrDel15') groupedhistplot(flightDataframe, 'CRSArrTime', 'ArrDel15') groupedhistplot(flightDataframe, 'CRSDepTime', 'ArrDel15') groupedhistplot(flightDataframe, 'DayofMonth', 'ArrDel15') groupedhistplot(flightDataframe, 'DayOfWeek', 'ArrDel15') groupedhistplot(flightDataframe, 'Month', 'ArrDel15') # Grouped pair plots by groups. def grouppairplot(df, cols, groupcol): import seaborn as sns sns.pairplot(data=df, vars=cols, hue = groupcol, size = 2) pairplotcols = ['DepDelay', 'CRSArrTime', 'CRSDepTime', 'DayofMonth', 'DayOfWeek', 'Month'] grouppairplot(flightDataframe, pairplotcols, 'ArrDel15') # Grouped scatter plot by group. def scatterplot(df, xcol, ycol, groupcol): import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 8)) ax = fig.gca() tempDf0 = df.loc[df[groupcol] == 0] tempDf1 = df.loc[df[groupcol] == 1] if tempDf0.shape[0] > 0: tempDf0.plot(kind = 'scatter', x = xcol, y = ycol, ax = ax, color = 'DarkBlue') if tempDf1.shape[0] > 0: tempDf1.plot(kind = 'scatter', x = xcol, y = ycol, ax = ax, color = 'Red') ax.set_title('Scatter plot of ' + xcol + ' vs. ' + ycol) return scatterplot(flightDataframe, 'ArrDelay', 'Month', 'ArrDel15')
# Çözüm - 1 numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] odd_list = [] for i in range(len(numbers)): if numbers[i] % 2 == 1: odd_list.append(numbers[i]) odd_list.sort() numbers[i] = "T" counter = 0 for y in range(len(numbers)): if numbers[y] == "T": numbers[y] = odd_list[counter] counter += 1 print(numbers) # Çözüm - 2 numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] odd = [] numbers_n = [] for i in numbers: if i % 2 == 1: odd.append(i) odd.sort(reverse=True) print(odd) for i in numbers: if i % 2 == 1: numbers_n.append(odd[-1]) odd.pop() else: numbers_n.append(i) print(numbers_n)
# Vücut Kütle Endeksi Hesaplama weight , height = float (input ("Please enter your weight (kg):")), float (input ("Please enter your height (meters):")) bmi = weight/height**2 #Body_mass_index print ("Your body mass index is :" + str (bmi)) if bmi < 18.5 : print ( "You are Underweight") elif 18.5 <= bmi <= 25 : print ("You are perfect. Enjoy it") else: print ("You are Overweight")
#!/usr/bin/env python # coding: utf-8 # In[1]: alien = {'color':'green','points':5,'start_position':0,'current_position':10} # In[2]: print(alien) # In[3]: # modify the values in dictionary # In[4]: alien['color'] = 'yellow' # In[5]: alien['points'] = 10 # In[6]: print(alien) # In[7]: # deleting the key value pairs from the dictionary # In[8]: del alien['start_position'] # In[9]: print(alien) # In[10]: # introduction to looping with dictionaries # In[11]: fav_languages = {'samreen':'python','ram':'c','suresh':'science','janani':'english','sajid':'python','peter':'cobol'} # In[19]: # normal syntax # for tempvar in mainvar: # print(tempvar) # In[21]: # with dict # for temp1 temp2 in mainvar.items(): # print(temp1) # print(temp2) # In[23]: for x,y in fav_languages.items(): print(f"key.{x}") print(f"Value.{y}") # In[25]: for x,y in fav_languages.items(): print(f"key.{x}") print(f"Value.{y}\n") # In[26]: # i want to know who all students have taken the survey ? i want only keys # In[28]: for x in fav_languages.keys(): print(f"\n student:{x}") # In[29]: # i want to know only the values # In[39]: for y in fav_languages.Values(): print(f"\n Choices:{y}") # In[ ]:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # #@created: 14.09.2021 #@author: Marina Popova class CoffeeMachine: resources_name = ['water', 'milk', 'coffee beans', 'cups', 'money'] def __init__(self, w = 400, m = 540, cb = 120, c = 9, mn = 550): self.resources = [w, m, cb, c, mn] self.workable = True def status(self): print('The coffee machine has:') for i in range(len(self.resources)-1): print(f'{self.resources[i]} of {CoffeeMachine.resources_name[i]}') print(f'${self.resources[-1]} of {CoffeeMachine.resources_name[-1]}') def fill(self): self.resources[0] += int(input('Write how many ml of water you want to add:')) self.resources[1] += int(input('Write how many ml of milk you want to add:')) self.resources[2] += int(input('Write how many grams of coffee beans you want to add:')) self.resources[3] += int(input('Write how many disposable coffee cups you want to add:')) def buy(self): check = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:') choices = {'1': [250, 0, 16, 1, 4], '2': [350, 75, 20, 1, 7], '3': [200, 100, 12, 1, 6]} if check == 'back': return else: for i in range(len(self.resources)-1): if self.resources[i] - choices[check][i] < 1: print(f'Sorry, not enough {CoffeeMachine.resources_name[i]}!') return print('I have enough resources, making you a coffee!') for i in range(len(self.resources)-1): self.resources[i] -= choices[check][i] self.resources[4] += choices[check][4] def work(self): while self.workable: action = input('Write action (buy, fill, take, remaining, exit): ') if action == 'remaining': CoffeeMachine.status(self) elif action == 'fill': CoffeeMachine.fill(self) elif action == 'take': print(f'I gave you ${self.resources[4]}') self.resources[4] = 0 elif action == 'buy': CoffeeMachine.buy(self) elif action == 'exit': self.workable = False else: print('Not valid action') myCoffeeMachine = CoffeeMachine() myCoffeeMachine.work()
def kaprekar(num) : i = 0 while num not in [6174, 0] : num = desc_digits(num) - asc_digits(num) i += 1 return i def breakdown_digits(num) : digits = list(map(int, list(str(num)))) while len(digits) < 4 : digits.append(0) return digits def largest_digit(num) : return max(breakdown_digits(num)) def asc_digits(num) : return int(''.join(map(str, sorted(breakdown_digits(num))))) def desc_digits(num) : return int(''.join(map(str,sorted(breakdown_digits(num), reverse=True)))) print('Largest Digit:') for num in [1234, 3253, 9800, 3333, 120] : print(str(num) + ': ' + str(largest_digit(num))) print('Descending order:') for num in [1234, 3253, 9800, 3333, 120] : print(str(num) + ': ' + str(desc_digits(num))) print('Kaprekar:') for num in [6589, 5455, 6174] : print(str(num) + ': ' + str(kaprekar(num))) # find highest possible output print('Highest: ' + str(max(map(kaprekar, range(10000)))))
#Taken from https://www.reddit.com/r/dailyprogrammer/comments/7vm223/20180206_challenge_350_easy_bookshelf_problem/ #As noted in comments, this problem is actually NP-hard, shelves = list(map(int, input("Enter shelf values: ").split())) shelves.sort(reverse=True) done = False bookValues = []; while not done : line = input('On each line enter book value followed by a space and book title: ') if line == '' : done = True else : bookValues.append(int(line.split()[0])) bookValues.sort(reverse=True) noSolution = False shelvesUsed = set() for book in bookValues : bookFits = False shelfIndex = 0 while shelfIndex < len(bookValues) and bookFits == False : if book <= shelves[shelfIndex] : shelves[shelfIndex] -= book shelvesUsed.add(shelfIndex) bookFits = True else : shelfIndex += 1 if bookFits == False : noSolution = True if noSolution : print('No Solution!') else : print(len(shelvesUsed))
from tkinter import * window= Tk() one=Label(window,text="one",bg="black") one.pack() two=Label(window,text="two",bg="blue") two.pack(fill=X) three=Label(window,text="three",bg="green") three.pack(fill=Y,side=LEFT) def left(event): print("left") def right(event): print("right") window.bind("<Button-1>",left) window.bind("<Button-3>",right) window.mainloop()
import math def is_prime(n): flg = True for i in range(2, int(math.sqrt(n)+1)): if n % i == 0: flg = False break return flg def P10(): sum = 0 for i in range(2,2000001): if is_prime(i): sum += i return sum print(P10())
#Objects used as structures for the TRAILS graph generator #Cartesean coordinate class Point(object): def __init__(self,x,y): self.x=1.0*x; self.y=1.0*y; class STP(object): def __init__(self,user,pointsIndex,enterTime,exitTime): self.user=user; #Trace user owner of the trace-points self.pointsIndex=pointsIndex; #Identifier of the trace-points self.enterTime=enterTime; #Time it arrives to the POI self.exitTime=exitTime; #Time it leaves the POI self.stayTime=exitTime-enterTime; #Time interval self.px=None; #Position in X self.py=None; #Position in Y #Points of interest class POI(object): def __init__(self,ListSTP,px,py,stayTimes,pIndex): self.listSTP=ListSTP; #List of Sets of trace points that are located within a range SR self.px=px; #Position in X self.py=py; #Position in Y self.pIndex=pIndex; #POI Identifier self.stayTimes=stayTimes; #List of times that a user spends self.enterTimes=[]; #List of times a user arrives to a node self.links=[]; #List of links that has this POI as initalPOI self.congestion=[]; #List of number of hosts at different moments of time #Track between locations class Link(object): def __init__(self,x,y,timeInterval,totalTime,finalPOI,initialPOI): self.x=x; #list of X components of path-points self.y=y; #list of Y components of path-points self.timeInterval=timeInterval; #list of time intervals between path-points self.totalTime=totalTime; #Time toarrive to a new POI self.enterTime=0; #Time a user took that link self.finalPOI=finalPOI; #POI that belogns to the final location self.initialPOI=initialPOI; #POI that belongs to the initial location self.unrealistic=False; #Flag to indicate unrealistic links self.returnIU=False; #Flag to indicate return links including unrealistic self.returnEU=False; #Flag to indicate return links excluding unrealistic links #Enclosing object in the shape of a circle class Circle(object): def __init__(self,centerX,centerY,squareRadius): #Shape (centerX-x)^2+(centerY-y)^2=squareRadius self.centerX=1.0*centerX; self.centerY=1.0*centerY; self.squareRadius=1.0*squareRadius; #Enclosing object in the shape of a rectangle class Box(object): def __init__(self,minX,minY,maxX,maxY): #Coordinates [[minX,minY],[minX,maxY],[maxX,maxY],[maxX,minY]] self.minX=minX; self.minY=minY; self.maxX=maxX; self.maxY=maxY;
#Functions and objects to process and represent traces import os #Functions to create directories import csv #Functions to create csv tables import math #Mathematical functions import matplotlib.pyplot as plt #Functions to plot graphs #User trace class User(object): def __init__(self, time, x, y): self.time = time; #list of time stamps of trace-points self.x = x; #list of X coordinates of trace-points self.y = y; #list of Y coordinates of trace-points self.inputPort = [None]*len(self.x); #list of input locations self.outputPort = [None]*len(self.x); #list of output locations #General parameters of traces class Limits(object): def __init__(self, maxTime,maxX,maxY,nUsers): self.maxTime = maxTime; #Recording time self.maxX = maxX; #Maximum width self.maxY = maxY; #Maximum length self.nUsers = nUsers; #Number of users #Compute distance between 2 points described in logitude and latitude #https://stackoverflow.com/questions/15736995/how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-points # Input # lon1: longitude of point1 # latt1: latitude of point1 # lon2: longitude of point2 # latt2: latitude of point2 # Output # Distance between 2 points in meters def haversine(lon1,lat1,lon2,lat2): lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]); dlon = lon2 - lon1; dlat = lat2 - lat1; a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2; # haversine formula c = 2 * math.asin(math.sqrt(a)); # Radius of earth in kilometers is 6371 return 6371000*c; #Transform geographic coordinates into cartesian coordinates # Input # users: List of users traces def transformDegreesMeters(users): minX=min([min(user.x) for user in users]); minY=min([min(user.y) for user in users]); for user in users: for i in range(0,len(user.x)): user.x[i]=haversine(minX, user.y[i], user.x[i], user.y[i]); user.y[i]=haversine(user.x[i], minY, user.x[i], user.y[i]); #Find general parameters of traces # Input # users: List of users traces # Output # General parameters of traces def removeOffset(users): minTime=min([min(user.time) for user in users]); minX=min([min(user.x) for user in users]); minY=min([min(user.y) for user in users]); for user in users: user.time=[time-minTime for time in user.time]; user.x=[x-minX for x in user.x]; user.y=[y-minY for y in user.y]; maxTimes=max([max(user.time) for user in users]); maxXs=max([max(user.x) for user in users]); maxYs=max([max(user.y) for user in users]); return Limits(maxTimes,maxXs,maxYs,len(users)); #Export processed traces # Input # users: List of users traces # outFolder: Output directory to export traces def exportUsers(outFolder,users): tracesPath = outFolder+'/Traces'; if not os.path.exists(tracesPath): os.makedirs(tracesPath); for i in range(0,len(users)): with open(tracesPath+'/'+str(i)+'.csv', 'w') as f: writer = csv.writer(f, delimiter ='\t'); for j in range(0,len(users[i].x)): writer.writerow([users[i].time[j],users[i].x[j],users[i].y[j]]); #Plot a Traces graph and save it as pdf # Input # users: List of users traces # output: Output directory to export the plot # plotP: Plot parameters def plotFigure(users,output,plotP): fig=plt.figure(); ax=fig.add_subplot(111); for user in users: ax.plot(user.x,user.y, linewidth=plotP.lineWidth); ax.axis('equal'); ax.set_ylim(ax.get_ylim()[::-1]); # invert the axis ax.xaxis.tick_top(); # and move the X-Axis if output != None: fig.savefig(output, format='pdf',dpi=plotP.dpi,figsize=plotP.fSize); plt.close(fig); else: plt.show();
#!/usr/bin/python3 """Divide a matrix""" def matrix_divided(matrix, div): """function that divides all elements of a matrix""" if not check_matrix(matrix): raise TypeError("matrix must be a matrix\ (list of lists) of integers/floats") for i in matrix: if len(i) == len(matrix[0]): pass else: raise TypeError("Each row of the matrix must have the same size") if not isinstance(div, int) and not isinstance(div, float): raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") else: return [[round(x/div, 2) for x in j] for j in matrix] def check_matrix(matrix): if not isinstance(matrix, list): return False for i in matrix: if type(i) is not list: return False if any(not isinstance(y, (int, float)) for y in i): return False return True
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): for i in matrix: end = "" for a in i: print("{:s}{:d}".format(end, a), end="") end = " " print()
""" function: 遍历目录,返回目录结构的 list """ import os def scanpath(filepath, suffix): file_list = [] print("开始扫描【{0}】".format(filepath)) if not os.path.isdir(filepath): print("【{0}】不是目录".format(filepath)) exit(-1) for filename in os.listdir(filepath): if os.path.isdir(filepath + "/" + filename): file_list.extend(scanpath(filepath + "/" + filename, suffix)) elif filename.endswith(suffix): sub_filename = filepath + '/' + filename file_list.append(sub_filename) print(sub_filename) return file_list
from collections import deque def solution(priorities, location): queue = deque(priorities) answer = 0 while location >= 0: left = queue.popleft() location -= 1 check = False for q in queue: if(q > left): check = True break if check: queue.append(left) if location == -1: location = len(queue) - 1 else: answer += 1 return answer
def solution(distance, rocks, n): rocks.sort() rocks.append(distance) answer = 0 start, end = 1, distance # answer은 1 ~ distance 사이에 있음 while start <= end: mid = (start + end) // 2 # 부서진 바위의 수 세기 cnt_rock, prev_rock = 0, 0 for rock in rocks: if rock - prev_rock < mid: cnt_rock += 1 else: prev_rock = rock if cnt_rock > n: # 더 많이 파괴되었을 경우 end = mid - 1 else: # 같거나 더 작게 파괴되었을 경우 answer = mid start = mid + 1 return answer
def solution(p): if not p: return p count = 0 is_correct = True for i, pp in enumerate(p): count += 1 if pp == '(' else -1 if count < 0: is_correct = False elif count == 0: u, v = p[:i+1], p[i+1:] if is_correct: return u + solution(v) else: u = ''.join([')' if uu == '(' else '(' for uu in u[1:-1]]) return '(' + solution(v) + ')' + u
from itertools import permutations def prime_tf(number): #소수 판별 return all([(number%n) for n in range(2, int(number**0.5)+1)]) and number>1 def solution(numbers): answer = 0 numbers=list(numbers) prime_list=[] for i in range(1, len(numbers)+1): prime_list += list(map(int, map(''.join,permutations(numbers, i)))) #모든 조합을 prime_list에 추가 prime_list=set(prime_list) #중복 제외 for j in prime_list : if prime_tf(j) : #True answer+=1 return answer
def count_divisible_numbers_less_than(n: int): count = 0 for k in range(2, n+1): not_prime = False for i in range(2, k): if k%i == 0: not_prime = True if not_prime: count+=1 print(count)
import numpy as np u=np.array((3,4,5)) v=np.array((1,2,7)) print("vector u:",u) print("vector v:",v) print("enter a,b:") a=int(input()) b=int(input()) d=(a*u)+(b*v) print("vector for au+bv",d) p=np.dot(u,v) print("dot product:",p)