text
stringlengths
37
1.41M
asd = ['5','3','2','4','1'] x = 0 for i in asd: if type(i) == int: if int(i) > x: x = i print(x)
''' 838. Push Dominoes https://leetcode.com/problems/push-dominoes Hi, here's your problem today. This problem was recently asked by Twitter: Given a string with the initial condition of dominoes, where: . represents that the domino is standing still L represents that the domino is falling to the left side R represents that the domino is falling to the right side Figure out the final position of the dominoes. If there are dominoes that get pushed on both ends, the force cancels out and that domino remains upright. Example: Input: ..R...L..R. Output: ..RR.LL..RR ''' from typing import * class Solution: #Good def pushDominoes(self, dominoes: str) -> str: N = len(dominoes) # Extract length as variable "N" force = [0]*N # Populate forces going from left to right f = 0 for i in range(N): if dominoes[i] == 'R': f = N elif dominoes[i] == 'L': # Reset 'R' force if encounter 'L'!! f = 0 else: f = max(f-1, 0) #Replace of "if f-1>=0: f-=1" force[i] = f # Populate forces going from right to left for i in range(N-1,-1,-1): if dominoes[i] == 'R': f = 0 elif dominoes[i] == 'L': # Reset 'L' force if encounter 'R'!! f = N else: f = max(f-1, 0) force[i] -= f ans = "" for f in force: if f == 0: ans += '.' elif f>0: ans += 'R' else: ans += 'L' return ans #Ugly def pushDominoesUgly(self, dominoes: str) -> str: SeenR = [None] * len(dominoes) SeenRindex = None for i, c in enumerate(dominoes): if c=='R': SeenRindex = i SeenR[i] = SeenRindex if c=='L': SeenRindex = None i = len(dominoes)-1 while i>=0: c = dominoes[i] if c=='L': if SeenR[i] is not None: if (i-SeenR[i])%2 == 0: SeenR[(i+SeenR[i])//2] = None for j in range(i, (i+SeenR[i])//2, -1): SeenR[j] = 'L' i -= 1 continue else: SeenR[i] = 'L' for j in range(i-1, -1, -1): if dominoes[j]=='L': break SeenR[j] = 'L' i -= 1 elif SeenR[i] is None: SeenR[i] = '.' else: SeenR[i] = 'R' i -= 1 return ''.join(SeenR) print(Solution().pushDominoes('..R...L..R.')) # ..RR.LL..RR print(Solution().pushDominoes('.L.R...LR..L..')) # LL.RR.LLRRLL.. print(Solution().pushDominoes('RR.L')) # RR.L print(Solution().pushDominoes('L.....RR.RL.....L.R.')) # L.....RRRRLLLLLLL.RR
''' 349. Intersection of Two Arrays https://leetcode.com/problems/intersection-of-two-arrays/ Hi, here's your problem today. This problem was recently asked by Amazon: Given two arrays, write a function to compute their intersection - the intersection means the numbers that are in both arrays. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: Each element in the result must be unique. The result can be in any order. ''' from typing import * class Solution: #Ugly def intersectionUgly(self, nums1: List[int], nums2: List[int]) -> List[int]: set1 = set(nums1) inter = set() for n in nums2: if n in set1: inter.add(n) return list(inter) #Good def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: set1 = set(nums1) set2 = set(nums2) # Can NOT use "and", should use "&" return list(set1 & set2) print(Solution().intersection([4, 9, 5], [9, 4, 9, 8, 4])) # [9, 4]
def insertion_sort(A): for idx in range(1,len(A)):#1...len(A)-1 key = A[idx] cmp_idx = idx-1 while cmp_idx>=0 and A[cmp_idx]>key: A[cmp_idx+1]=A[cmp_idx] cmp_idx -= 1 A[cmp_idx+1] = key def partition(A, start, end): pivot_idx = end-1 mid_idx = start for cmp_idx in range(start, pivot_idx): if A[cmp_idx] <= A[pivot_idx]: A[mid_idx],A[cmp_idx] = A[cmp_idx],A[mid_idx] mid_idx += 1 A[mid_idx],A[pivot_idx] = A[pivot_idx],A[mid_idx] return mid_idx def quick_sort(A, start=0, end=None): if end is None: end = len(A) if start < end: mid = partition(A, start, end) quick_sort(A, start, mid)#start...mid-1 quick_sort(A, mid+1, end)#mid+1...end-1 def merge(left, right): result = [] left_idx = 0 right_idx = 0 while left_idx < len(left) and right_idx < len(right): if left[left_idx] < right[right_idx]: result.append(left[left_idx]) left_idx += 1 else: result.append(right[right_idx]) right_idx += 1 #Copy remaining elements... result.extend(left[left_idx:]) result.extend(right[right_idx:]) return result def merge_sort(A): if len(A)<=1: return A mid = len(A) // 2 left = merge_sort(A[:mid]) right = merge_sort(A[mid:]) return merge(left, right) def max_heapify(A, root_idx, heap_size): left_idx = 2*root_idx + 1 right_idx = 2*root_idx + 2 max_idx = root_idx if left_idx < heap_size and A[left_idx]>A[max_idx]: max_idx = left_idx if right_idx < heap_size and A[right_idx]>A[max_idx]: max_idx = right_idx if max_idx != root_idx: A[root_idx], A[max_idx] = A[max_idx],A[root_idx] max_heapify(A, max_idx, heap_size) def build_max_heap(A): for idx in range(len(A)//2,-1,-1):#len(A)//2...0 max_heapify(A, idx, len(A)) def my_heap_sort(A): build_max_heap(A) for heap_size in range(len(A)-1, 0, -1):#len(A)-1...1 A[0],A[heap_size] = A[heap_size],A[0] max_heapify(A, 0, heap_size) #import heapq #def heapsort(iterable): # h = [] # for value in iterable: # heapq.heappush(h, value) # return [heapq.heappop(h) for i in range(len(h))] def counting_sort(str): counter = [ 0 for i in range(26) ] result = [char for char in str] for char in str: char_index = ord(char)-ord('a') counter[char_index] += 1 for i in range(1, len(counter)): counter[i] += counter[i-1] for char in reversed(str): char_index = ord(char)-ord('a') result[counter[char_index]-1] = char counter[char_index] -= 1 return ''.join(result) if __name__ == "__main__": A = [ 1, 4, 2, 3, 9, 8, 7, 16, 14, 10 ] #insertion_sort(A) #print("After insertion_sort: {}".format(A)) #print("merge_sort: {}".format(merge_sort(A))) #print("After merge_sort: {}".format(A)) my_heap_sort(A) print("After my_heap_sort: {}".format(A)) #quick_sort(A) #print("After quick_sort: {}".format(A)) #print("counting_sort: {}".format(counting_sort("traceback")))
''' 56. Merge Intervals https://leetcode.com/problems/merge-intervals/ Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. ''' from typing import * #Concise class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if not intervals: return [] intervals = sorted(intervals, key=lambda inter: inter[0]) ans = [intervals[0]] for idx in range(1, len(intervals)): startI, endI = intervals[idx] if startI <= ans[-1][1]: ans[-1][1] = max(endI, ans[-1][1]) else: ans.append(intervals[idx]) return ans #Ugly class UglySolution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if not intervals: return [] intervals = sorted(intervals, key=lambda inter: inter[0]) latestEnd = intervals[0][1] ans = [intervals[0]] for idx in range(1, len(intervals)): startI, endI = intervals[idx] if startI <= latestEnd: latestEnd = max(endI, ans[-1][1]) ans[-1][1] = latestEnd else: ans.append(intervals[idx]) latestEnd = endI return ans print(Solution().merge([[1,3],[2,6],[8,10],[15,18]])) #[[1,6],[8,10],[15,18]] print(Solution().merge([[1,4],[4,5]])) #[[1,5]] print(Solution().merge([[1,4],[2,3]])) #[[1,4]] print(Solution().merge([[2,3],[4,5],[6,7],[8,9],[1,10]])) #[[1,10]]
''' 242. Valid Anagram https://leetcode.com/problems/valid-anagram/ Given two strings s and t, write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false ''' from typing import * import collections # Anagrams have same counters class Solution: def isAnagram(self, s: str, t: str) -> bool: sc = collections.Counter(s) tc = collections.Counter(t) return sc == tc # Anagrams have same sorted chars class SortSolution: def isAnagram(self, s: str, t: str) -> bool: return sorted(s)==sorted(t) print(Solution().isAnagram(s = "anagram", t = "nagaram")) # True print(Solution().isAnagram(s = "rat", t = "car")) # False
''' 42. Trapping Rain Water https://leetcode.com/problems/trapping-rain-water/ Hi, here's your problem today. This problem was recently asked by Uber: You have a landscape, in which puddles can form. You are given an array of non-negative integers representing the elevation at each location. Return the amount of water that would accumulate if it rains. For example: [0,1,0,2,1,0,1,3,2,1,2,1] should return 6 because 6 units of water can get trapped here. X X███XX█X X█XX█XXXXXX # [0,1,0,2,1,0,1,3,2,1,2,1] ''' from typing import * #wrong def wrong_capacity(arr): acc = 0 for i in range(1, len(arr)-1): l,r = i-1, i+1 base = arr[i] while arr[l]>arr[i] and arr[r]>arr[i]: height = min(arr[l],arr[r]) acc += (r-l-1) * (height-base) base = height if l==0 and r==len(arr)-1: break if l!=0: l-=1 if r!=len(arr)-1: r+=1 return acc class Solution: def trap(self, height: List[int]) -> int: acc, left, right = 0, 0, len(height)-1 maxHeightL, maxHeightR = 0, 0 while left < right: if height[left]<height[right]: #Same height or larger than max will not acc water if height[left] >= maxHeightL: maxHeightL = height[left] else: acc += maxHeightL - height[left] left += 1 else: if height[right] >= maxHeightR: maxHeightR = height[right] else: acc += maxHeightR - height[right] right -= 1 return acc print(Solution().trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])) # 6 print(Solution().trap([2,1,0,2])) # 3 print(Solution().trap([5,2,1,2,1,5])) # 14
def dfs(graph, vertex, visited = set()): visited.add(vertex) print(vertex, end=' ') for neighbor in graph[vertex]: if neighbor not in visited: dfs(graph, neighbor, visited) def bfs(graph, vertex): import collections q = collections.deque() q.append(vertex) visited = { vertex } while q: v = q.popleft() print(v, end=' ') for neighbor in graph[v]: if neighbor not in visited: visited.add(neighbor) q.append(neighbor) graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] } dfs(graph, 'A') print() bfs(graph, 'A') print()
''' 1233. Remove Sub-Folders from the Filesystem https://leetcode.com/contest/weekly-contest-159/problems/remove-sub-folders-from-the-filesystem/ Given a list of folders, remove all sub-folders in those folders and return in any order the folders after removing. If a folder[i] is located within another folder[j], it is called a sub-folder of it. The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, /leetcode and /leetcode/problems are valid paths while an empty string and / are not. Example 1: Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"] Output: ["/a","/c/d","/c/f"] Explanation: Folders "/a/b/" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem. Example 2: Input: folder = ["/a","/a/b/c","/a/b/d"] Output: ["/a"] Explanation: Folders "/a/b/c" and "/a/b/d/" will be removed because they are subfolders of "/a". Example 3: Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"] Output: ["/a/b/c","/a/b/ca","/a/b/d"] Constraints: 1 <= folder.length <= 4 * 10^4 2 <= folder[i].length <= 100 folder[i] contains only lowercase letters and '/' folder[i] always starts with character '/' Each folder name is unique. ''' from typing import * class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: ans = [] folderSet = set(folder) for f in folder: path = f while path: # Cut down last ..."/xx" to move # upper level and look for it in set path = path[:path.rfind('/')] if path in folderSet: break else: # Append if no break ans.append(f) return ans print(Solution().removeSubfolders(["/a","/a/b","/c/d","/c/d/e","/c/f"])) #['/a', '/c/d', '/c/f'] print(Solution().removeSubfolders(["/a","/a/b/c","/a/b/d"])) #['/a'] print(Solution().removeSubfolders(["/a/b/c","/a/b/ca","/a/b/d"])) #['/a/b/c', '/a/b/ca', '/a/b/d']
''' 160. Intersection of Two Linked Lists https://leetcode.com/problems/intersection-of-two-linked-lists/ Hi, here's your problem today. This problem was recently asked by Apple: You are given two singly linked lists. The lists intersect at some node. Find, and return the node. Note: the lists are non-cyclical. Example: A = 1 -> 2 -> 3 -> 4 B = 6 -> 3 -> 4 This should return 3 (you may assume that any nodes with the same value are the same node). ''' class Solution(object): def getIntersectionNode(self, headA, headB): nodeA = headA nodeB = headB AtoB = BtoA = False while nodeA and nodeB and nodeA != nodeB: nodeA = nodeA.next if nodeA is None: if AtoB: return None AtoB = True nodeA = headB nodeB = nodeB.next if nodeB is None: if BtoA: return None BtoA = True nodeB = headA return nodeA if nodeA == nodeB else None class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): s = '' c = self while c: s += str(c.val) + ' ' c = c.next return s rootA = ListNode(1) rootA.next = ListNode(2) rootA.next.next = ListNode(3) rootA.next.next.next = ListNode(4) rootB = ListNode(6) rootB.next = rootA.next.next print(Solution().getIntersectionNode(rootA, rootB)) # 3 4 rootA = ListNode(1) rootA.next = ListNode(2) rootA.next.next = ListNode(3) rootA.next.next.next = ListNode(4) rootB = ListNode(6) rootB.next = ListNode(7) rootB.next.next = ListNode(8) print(Solution().getIntersectionNode(rootA, rootB)) # None
''' 98. Validate Binary Search Tree https://leetcode.com/problems/validate-binary-search-tree/ Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: *The left subtree of a node contains only nodes with keys less than the node's key. *The right subtree of a node contains only nodes with keys greater than the node's key. *Both the left and right subtrees must also be binary search trees. Hi, here's your problem today. This problem was recently asked by Facebook: You are given the root of a binary search tree. Return true if it is a valid binary search tree, and false otherwise. Recall that a binary search tree has the property that all values in the left subtree are less than the root, and all values in the right subtree are greater than the root. ''' from typing import * # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None #Time complexity : O(N) since we visit each node exactly once. #Space complexity: O(N) since we keep up to the entire tree. class Solution: def isValidBST(self, root: TreeNode, min=None, max=None) -> bool: if root: if min is not None and root.val<=min: return False if max is not None and root.val>=max: return False lValid = self.isValidBST(root.left, min, root.val) rValid = self.isValidBST(root.right, root.val, max) return lValid and rValid #empty tree is valid BST!! return True import unittest class TestValidBST(unittest.TestCase): def testExample1(self): # 5 # / \ # 3 7 # / \ / #1 4 6 a = TreeNode(5) a.left = TreeNode(3) a.right = TreeNode(7) a.left.left = TreeNode(1) a.left.right = TreeNode(4) a.right.left = TreeNode(6) self.assertEqual(Solution().isValidBST(a), True) def testExample2(self): # 2 # / \ # 1 3 a = TreeNode(2) a.left = TreeNode(1) a.right = TreeNode(3) self.assertEqual(Solution().isValidBST(a), True) def testExample3(self): # 5 # / \ # 1 4 # / \ # 3 6 a = TreeNode(5) a.left = TreeNode(1) a.right = TreeNode(4) a.right.left = TreeNode(3) a.right.right = TreeNode(6) self.assertEqual(Solution().isValidBST(a), False) if __name__ == "__main__": unittest.main()
#!/usr/bin/env python # encoding: utf-8 from euler import proper_divisor_sum def main(): result = 0 for num in range(2, 10001): proper_sum = proper_divisor_sum(num) if num != proper_sum and proper_divisor_sum(proper_sum) == num: result += proper_sum print(result) if __name__ == '__main__': main()
#!/usr/bin/env python # encoding: utf-8 from euler import primes def main(): prime_numbers = primes(1000) num, num_of_div, num_of_div_sofar = 3, 2, 0 while num_of_div_sofar <= 500: num += 1 next_num = num if next_num % 2 == 0: next_num /= 2 tmp_num_of_div = 1 for prime in prime_numbers: if prime * prime > next_num: tmp_num_of_div *= 2 break expon = 1 while next_num % prime == 0: expon += 1 next_num /= prime if expon > 1: tmp_num_of_div *= expon if next_num == 1: break num_of_div_sofar = num_of_div * tmp_num_of_div num_of_div = tmp_num_of_div print(num * (num - 1) / 2) if __name__ == '__main__': main()
from math import factorial def perms(N, rem): rem_idx = rem - 1 remainingdigits = list(range(N)) digits = [] for i in range(N): idx = N - 1 - i f = factorial(idx) digit_idx = rem_idx // f dg = remainingdigits.pop(digit_idx) digits.append(str(dg)) rem_idx = rem_idx % f return ''.join(digits) if __name__ == '__main__': assert(perms(3, 4) == '120') print(perms(10, 10**6 - 1))
CACHE = {} CACHE_SQ = {} def square_digit_sum(i): if i in CACHE_SQ: return CACHE_SQ[i] out = 0 for j in str(i): out += int(j) ** 2 CACHE_SQ[i] = out return out def arrives_at_89(i): if i in CACHE: return CACHE[i] next_value = square_digit_sum(i) if next_value == 1: CACHE[i] = False return False elif next_value == 89: CACHE[i] = True return True else: val = arrives_at_89(next_value) CACHE[i] = val return val def test_square_digit_sum(): assert square_digit_sum(1) == 1 assert square_digit_sum(58) == 89 assert square_digit_sum(10) == 1 assert square_digit_sum(145) == 42 def test_arrives_at_89(): assert arrives_at_89(1) == False assert arrives_at_89(44) == False assert arrives_at_89(13) == False assert arrives_at_89(85) == True assert arrives_at_89(145) == True assert arrives_at_89(89) == True if __name__ == '__main__': cnt = 0 for i in range(1, 10 ** 7): if arrives_at_89(i): cnt += 1 print(cnt)
''' next is n/2 if even next is 3n+1 if odd ''' def next(n): if n % 2 == 0: return n // 2 else: return 3 * n + 1 def max_collatz_chain(under): chain_length = {1: 0} maxlen_n = 0 maxlen = 0 for n in range(1, under + 1): seq = [] nxt = n while chain_length.get(nxt) is None and nxt != 1: seq.append(nxt) nxt = next(nxt) offset = chain_length.get(nxt, 0) for i, j in enumerate(seq): chain_length[j] = len(seq) + offset - i if len(seq) + offset > maxlen: maxlen = max(len(seq) + offset, maxlen) maxlen_n = n return maxlen_n print(max_collatz_chain(1000000))
''' This is very slow but techincally works. Could be improved by genreating pythagrean triples ''' def square(x): return int(x ** .5) ** 2 == x def opt1(s): right = (s // 2) ** 2 l1 = (s + 1) ** 2 if square(l1 - right): p = 2 * (s + 1) + s if p > 10 ** 9: return return p def opt2(s): right = (s // 2) ** 2 l2 = (s - 1) ** 2 if square(l2 - right): p = 2 * (s - 1) + s if p > 10 ** 9: return return p if __name__ == '__main__': sm = 0 for s in range(3, 10 ** 9): if s % 2 == 1: continue right = (s // 2) ** 2 o1 = opt1(s) if o1 is not None: sm += o1 o2 = opt2(s) if o2 is not None: sm += o2 print(sm)
''' Brute force method, takes a few seconds. There'a a cooler method that uses diophantine equations ''' def slope(p, q): '''returns None if div by zero ''' d = q[0] - p[0] if d == 0: return else: return (q[1] - p[1]) / d def two_slopes_prependicular(m1, m2): if m1 is None and m2 == 0: return True if m1 == 0 and m2 is None: return True if m1 is None or m2 is None: return False prod = m1 * m2 return prod > -1.0000001 and prod < -.9999999 def forms_right_triangle(p, q): '''If the triangle formed by the origin, p, and q contains a right angle ''' origin = (0, 0) s1 = slope(origin, p) s2 = slope(origin, q) m = slope(p, q) return (two_slopes_prependicular(s1, m) or two_slopes_prependicular(s2, m) or two_slopes_prependicular(s1, s2)) def points(n): for i in range(n + 1): for j in range(n + 1): if (i, j) != (0, 0): yield (i, j) def count(n): cnt = 0 st = set() for p in points(n): for q in points(n): if p != q and forms_right_triangle(p, q): st.add((min(p, q), max(p, q))) cnt += 1 return len(st)# cnt // 2 def test_slope(): assert slope((0, 0), (0, 1)) is None assert slope((0, 0), (1, 1)) == 1 assert slope((1, 5), (5, 3)) == -0.5 def test_two_slopes_prependicular(): assert two_slopes_prependicular(None, 0) assert two_slopes_prependicular(0, None) assert two_slopes_prependicular(-1/2, 2) assert two_slopes_prependicular(1, -1) assert not two_slopes_prependicular(1/2, 2) assert not two_slopes_prependicular(-1/2, -2) def test_forms_right_triangle(): assert forms_right_triangle((1, 0), (0, 1)) assert forms_right_triangle((1, 1), (0, 2)) assert forms_right_triangle((0, 3), (1, 3)) assert forms_right_triangle((1, 3), (0, 3)) assert not forms_right_triangle((2, 4), (0, 3)) assert not forms_right_triangle((4, 4), (5, 5)) def test_count(): assert count(1) == 3 assert count(2) == 14 if __name__ == '__main__': print(count(50))
#!/usr/bin/python3.4 import argparse import random """ vars """ min_per_day = int() max_per_day = int() weekends = bool() def generate_week(nworkdays, nhours): weekdays = [] for i in range(nworkdays): weekdays.append(-1) for i in range((7 if weekends else 5)-nworkdays): weekdays.append(0) random.shuffle(weekdays) hours_left = nhours for i in range(len(weekdays)): if hours_left <= 0: break """ here i did not work """ if weekdays[i] == 0: continue """ here i did work """ hours = random.randint(min_per_day,max_per_day) hours_left = hours_left - hours weekdays[i] = hours for i in range(len(weekdays)): if weekdays[i] == -1: weekdays[i] = 0 return weekdays if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--nweeks", default=1, type=int, help='number of weeks to be generated. default is 1') """ flags """ parser.add_argument("--kw", action='store_true', help='use and print kalenderwoche.') parser.add_argument("--first_kw", default=1, type=int, help='specify the first kw if used with option --kw. defaults to 1') parser.add_argument("--we", action='store_true', help='worked on weekends. implicitly true if work days is greater 5') """ parameters """ parser.add_argument("--weekhours", default=15, type=int, help='worked hours in a week. output might deviate from the concrete value') parser.add_argument("--hmin", default=3, type=int, help='hours at least worked per day. defaults to 3.' ) parser.add_argument("--hmax", default=5, type=int, help='hours at most worked per day. defaults to 5.' ) parser.add_argument("--dmin", default=5, type=int, help='days at least worked per week. defaults to 5.' ) parser.add_argument("--dmax", default=5, type=int, help='days at most worked per week. defaults to 5.' ) args = parser.parse_args() assert(args.hmin <= args.hmax) assert(args.dmin <= args.dmax) min_per_day = args.hmin max_per_day = args.hmax weekends = args.we if args.dmax > 5: weekends = True start = args.first_kw for i in range(start, start+args.nweeks): workdays = random.randint(args.dmin, args.dmax) print((str(i)+' ' if args.kw else '') + str(generate_week(workdays, args.weekhours)))
from enum import Enum class Commands(Enum): NORTH = "N" SOUTH = "S" EAST = "E" WEST = "W" LEFT = "L" RIGHT = "R" FORWARD = "F" class Instruction: def __init__(self, instruction_str): self.command = Commands(instruction_str[0]) self.value = int(instruction_str[1:]) def __str__(self): return f"{self.command.value} {self.value}" class Ship1: def __init__(self): self.x = 0 self.y = 0 self.direction = 90 def execute(self, instruction): if instruction.command == Commands.NORTH: self.x += instruction.value elif instruction.command == Commands.SOUTH: self.x -= instruction.value elif instruction.command == Commands.EAST: self.y += instruction.value elif instruction.command == Commands.WEST: self.y -= instruction.value elif instruction.command == Commands.LEFT: if instruction.value % 90 != 0: raise ValueError self.direction = (self.direction - instruction.value) % 360 elif instruction.command == Commands.RIGHT: if instruction.value % 90 != 0: raise ValueError self.direction = (self.direction + instruction.value) % 360 elif instruction.command == Commands.FORWARD: if self.direction == 0: self.x += instruction.value elif self.direction == 90: self.y += instruction.value elif self.direction == 180: self.x -= instruction.value elif self.direction == 270: self.y -= instruction.value def manhattan_distance(self): return abs(self.x) + abs(self.y) class Ship2: def __init__(self): self.x = 0 self.y = 0 self.direction = 90 self.waypoint_x = 1 self.waypoint_y = 10 def execute(self, instruction): if instruction.command == Commands.NORTH: self.waypoint_x += instruction.value elif instruction.command == Commands.SOUTH: self.waypoint_x -= instruction.value elif instruction.command == Commands.EAST: self.waypoint_y += instruction.value elif instruction.command == Commands.WEST: self.waypoint_y -= instruction.value elif ( instruction.command == Commands.LEFT or instruction.command == Commands.RIGHT ): if instruction.command == Commands.LEFT: value = -instruction.value else: value = instruction.value value = value % 360 if value == 0: return elif value == 90: x = self.waypoint_x y = self.waypoint_y self.waypoint_x = -y self.waypoint_y = x elif value == 180: self.waypoint_x = -self.waypoint_x self.waypoint_y = -self.waypoint_y elif value == 270: x = self.waypoint_x y = self.waypoint_y self.waypoint_x = y self.waypoint_y = -x elif instruction.command == Commands.FORWARD: self.x += self.waypoint_x * instruction.value self.y += self.waypoint_y * instruction.value def manhattan_distance(self): return abs(self.x) + abs(self.y) def part_1(filename): with open(filename, "r") as file: instructions = [Instruction(line) for line in file.readlines()] ship = Ship1() for instruction in instructions: ship.execute(instruction) return ship.manhattan_distance() def part_2(filename): with open(filename, "r") as file: instructions = [Instruction(line) for line in file.readlines()] ship = Ship2() print(ship.x, ship.y, ship.waypoint_x, ship.waypoint_y) for instruction in instructions: ship.execute(instruction) print(ship.x, ship.y, ship.waypoint_x, ship.waypoint_y) return ship.manhattan_distance() if __name__ == "__main__": print(part_1("inputs/day_12_sample_1.txt")) print(part_1("inputs/day_12.txt")) print(part_2("inputs/day_12_sample_1.txt")) print(part_2("inputs/day_12.txt"))
# Nousheen Siddiqui # Edited on 02/25/21 # Use the following chunk of code as a base to produce the image shown below. import turtle def drawSquare(t, sz): for i in range(4): t.forward(sz) t.left(90) wn = turtle.Screen() alex = turtle.Turtle() alex.color("blue") drawSquare(alex, 50) sizelist=[50,40,30,20,10] for i in sizelist: drawSquare(alex,i) alex.penup() alex.left(45) alex.forward(i/5) alex.right(45) alex.pendown() wn.exitonclick()
# CIRCULE OF SQUARES 2º método import turtle turtle.speed(0) def square(l, a): for i in range(4): turtle.forward(l) turtle.left(a) for i in range(36): square(100, 90) turtle.left(10) # recomeça uma nova série for i in range(200): square(100, 90) turtl.left(11)
def menu(): # print what options you have print ("Welcome to calculator.py") print ("your options are:") print (" ") print ("1) Addition") print print ("3) Multiplication") print ("4) Division") print ("5) Quit calculator.py") print (" ") return int(input("Choose your option: ")) # this adds two numbers given def add(a, b): print (a, "+", b, "=", a + b) # this subtracts two numbers given def sub(a, b): print (b, "-", a, "=", b - a) # this multiplies two numbers given def mul(a, b): print (a, "*", b, "=", a * b) # this divides two numbers given def div(a, b): print (a, "/", b, "=", a / b) # NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN loop = 1 choice = 0 while loop == 1: choice = menu() if choice == 1: add(a=int(input("Add this: ")), b=int(input("to this: "))) loop = 0 elif choice == 2: sub(a=int(input("Subtract this: ")), b=int(input("from this: "))) loop = 0 elif choice == 3: mul(a=int(input("Multiply this: ")), b=int(input("by this: "))) loop = 0 elif choice == 4: div(a=int(input("Divide this: ")), b=int(input("by this: "))) loop = 0 elif choice == 5: loop = 0 print ("Thank you for using calculator.py!")
# CIRCULE OF SQUARES import turtle turtle.speed(0) def square(): turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) square() turtle.left(100) for i in range(35): square() turtle.left(100)
def translate(message): translation = { "A" : ".-", "B" : "-...", "C" : "-.-.", "D" : "-..", "E" : ".", "F" : "..-.", "G" : "--.", "H" : "....", "I" : "..", "J" : ".---", "K" : "-.-", "L" : ".-..", "M" : "--", "N" : "-.", "O" : "---", "P" : ".--.", "Q" : "--.-", "R" : ".-.", "S" : "...", "T" : "-", "U" : "..-", "V" : "..-", "W" : ".--", "X" : "-..-", "Y" : "-.--", "Z" : "--..", "0" : "-----", "1" : ".----", "2" : "..---", "3" : "...--", "4" : "....-", "5" : ".....", "6" : "-....", "7" : "--...", "8" : "---..", "9" : "----.", " " : " "} if message in translation: return translation[message] + " " else: return "invalid syntax try again" def englishToMorse(message): message = message.upper() breakdown = list(message) answer = "" for length in breakdown: answer += translate(length) if answer == "invalid syntax try again": break return answer
input = [3, 1, 4, 6, 5] def my_triplet(input): squared_list = [] for i in input: squared_list.append(i * i) print (squared_list) res_list = [] for i in range(len(squared_list) -1): for j in range(len(squared_list) -1): if (squared_list[i] + squared_list[j+1]) in squared_list: res_list.append(squared_list[i] ** .5) res_list.append(squared_list[j+1] ** .5) res_list.append((squared_list[i] + squared_list[j+1]) ** .5) break else: continue break print (res_list) def sort_triplet(input): squared_list = [] for i in input: squared_list.append(i * i) squared_list.sort() print (squared_list) for i in range(len(input)-1, 1, -1): j =0 k = i-1 while j < k: if squared_list[j]+squared_list[k] == squared_list[i]: return (True) break else: if squared_list[j]+squared_list[k] < squared_list[i]: j +=1 else: k -= 1 return (False) # my_triplet(input) # print (sort_triplet(input)) def isTriplet(ar, n): j = 0 for i in range(n - 2): for k in range(j + 1, n): print (k) for j in range(i + 1, n - 1): print (j) # Calculate square of array elements x = ar[i]*ar[i] y = ar[j]*ar[j] z = ar[k]*ar[k] if (x == y + z or y == x + z or z == x + y): return 1 isTriplet(input, len(input))
list_of_friends=[] friends=input("Enter no of friends you want to insert in list" ) ch=-1 choise=-1 print("Enter your friends names :") for i in range(int(friends)): list_of_friends.append(input()) while choise!=0: print("select your choise") print("press 1 to print your friend list") print("press 2 to check length your friend list") print("press 3 to print your friend list in sorted order ") print("press 4 to print your friend list in reverse sorted order") print("press 5 to insert name in your list your friend list") print("press 6 to delete any name from list") print("press 0 to Exit") choise=int(input()) if choise==1: print("Your Friend list is:") print(list_of_friends) elif choise==2: print("your list contain "+str(len(list_of_friends))+ " friends") elif choise==3: print("sorted list of your friends :") print(sorted(list_of_friends)) elif choise==4: print("your friend list in reversed sorted order") print(sorted(list_of_friends,reverse=True)) elif choise==5: position=0 print("Enter position where you want to insert name") position=input() print("Enter name you want to insert") name=input() if position==1: list_of_friends.insert(0,name) print("your new list :") print(list_of_friends) elif position>=len(list_of_friends): list_of_friends.append(name) else: list_of_friends.insert(position,name) elif choise==6: print("Enter namr you ant to delete") name=input() list_of_friends.pop(name) print("your new list :") print(list_of_friends) else: print("Invalid Selection") exit()
# Напишите простой калькулятор, который считывает с пользовательского ввода три # строки: первое число, второе число и операцию, после чего применяет операцию # к введённым числам ("первое число" "операция" "второе число") и выводит результат на экран. # Поддерживаемые операции: +, -, /, *, mod, pow, div, где # mod — это взятие остатка от деления, # pow — возведение в степень, # div — целочисленное деление. # Если выполняется деление и второе число равно 0, необходимо выводить строку "Деление на 0!". # Обратите внимание, что на вход программе приходят вещественные числа. def simple_calc(num1, num2, operation): if operation == '+': print(num1 + num2) elif operation == '-': print(num1 - num2) elif operation == '/': print(num1 / num2 if num2 != 0 else 'Деление на 0!') elif operation == '*': print(num1 * num2) elif operation == 'mod': print(num1 % num2 if num2 != 0 else 'Деление на 0!') elif operation == 'pow': print(num1 ** num2) elif operation == 'div': print(num1 // num2 if num2 != 0 else 'Деление на 0!') if __name__ == '__main__': num1, num2 = (float(input()) for _ in range(2)) operation = input() simple_calc(num1, num2, operation)
# Напишите программу, принимающую на вход целое число, которая выводит True, # если переданное значение попадает в интервал (−15,12]∪(14,17)∪[19,+∞) # и False в противном случае (регистр символов имеет значение). # Обратите внимание на разные скобки, используемые для обозначения интервалов. # В задании используются полуоткрытые и открытые интервалы. Подробнее про это # вы можете прочитать, например, на википедии (полуинтервал, промежуток). def is_in_interval(number): print(-15 < number <= 12 or 14 < number < 17 or 19 <= number) if __name__ == '__main__': num = int(input()) is_in_interval(num)
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 import random def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all the match records from the database.""" try: con = connect() cur = con.cursor() cur.execute("DELETE FROM standings") con.commit() cur.close() except: print 'could not remove matches from the db' def deletePlayers(): """Remove all the player records from the database.""" try: con = connect() cur = con.cursor() cur.execute("DELETE FROM standings") con.commit() cur.close() except: print 'could not remove players from the db' def countPlayers(): """Returns the number of players currently registered.""" con = connect() cur = con.cursor() cur.execute("SELECT COUNT(name) FROM standings") players_tuple = cur.fetchone() try: players_count = int(players_tuple[0]) except: return 0 con.commit() cur.close() return players_count def registerPlayer(name): """Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) Args: name: the player's full name (need not be unique). """ try: con = connect() cur = con.cursor() cur.execute ("INSERT INTO standings (name) VALUES (%s)", (name,)) con.commit() cur.close() except: print 'could not add player %s to the db' % (name,) def playerStandings(include_odd_win=None): """Returns a list of the players and their win records, sorted by wins. The first entry in the list should be the player in first place, or a player tied for first place if there is currently a tie. If there are odd number of players, then pick a random player for odd win and return the standings of the players Returns: A list of tuples, each of which contains (id, name, wins, matches): id: the player's unique id (assigned by the database) name: the player's full name (as registered) wins: the number of matches the player has won matches: the number of matches the player has played include_odd_win: if this is set to 1, it will return all the player standings including player with odd win """ con = connect() cur = con.cursor() players_count = countPlayers() cur.execute("SELECT * from get_standings") rows = cur.fetchall() # Check if there are odd players if players_count % 2 != 0: # Get a list of players who did not win previously cur.execute("SELECT * from standings where odd_win=0") rows_for_odd_win = cur.fetchall() # Pick a random player from list of players who did not win previously winning_player = random.choice(rows_for_odd_win) winning_player_id = winning_player[0] reportMatch(winner = winning_player_id, odd_win = 1) # Remove the odd player from the list of current players rows.remove(winning_player) # If we need to return all the players with odd_win, then fetch # the db again if include_odd_win: cur.execute("SELECT * from get_standings") rows = cur.fetchall() cur.close() return rows def reportMatch(winner, loser=None, odd_win=None): """Records the outcome of a single match between two players. Args: winner: the id number of the player who won loser: the id number of the player who lost (optional in case of odd_win) odd_win: if this is set, it will process odd winner """ con = connect() cur = con.cursor() # Update standings with num of wins and matches if odd_win: cur.execute ("UPDATE standings SET wins = wins + 1,\ matches = matches + 1,\ odd_win = odd_win + 1\ WHERE id = %s", [winner]) else: cur.execute ("UPDATE standings SET wins = wins + 1,\ matches = matches + 1\ WHERE id = %s", [winner]) cur.execute ("UPDATE standings SET matches = matches + 1\ WHERE id = %s", [loser]) con.commit() cur.close() def swissPairings(): """Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a player adjacent to him or her in the standings. Returns: A list of tuples, each of which contains (id1, name1, id2, name2) id1: the first player's unique id name1: the first player's name id2: the second player's unique id name2: the second player's name """ con = connect() cur = con.cursor() cur.execute("SELECT id, name from standings WHERE odd_win = 0 ORDER BY wins") rows = cur.fetchall() # Get the pairs of players from the list fetched from db pairs = [(rows[i] + rows[i+1]) for i in range(0,len(rows),2)] cur.close() return pairs
# -*- coding: utf-8 -*- """ Created on Wed Dec 13 16:23:12 2017 @author: Andreea Aniculaesei """ #asks the user to type a number and continue to run until the type-in is not a number def inputNumber(prompt): while True: try: num = float(input(prompt)) break except ValueError: pass return num
""" Methods for printing fancy text """ from Color_Console import * class Console: colors = { "black": 0, "red": 1 } attributes = { "bold": 1, "dim": 2 } def __init__(self): print("") def print(text, attributes, foreground, background): print ('%s test %s' % (fg(foreground), bg(background), attr(attributes)))
class Animal(object): def __init__(self, name, age): self.name = name self.age = age def run(self): print("{0} is running".format(self.name)) def print_age(self): print("{0}'s age is {1} years old.".format(self.name, self.age)) def age_add(self): self.age = self.age + 1 if __name__ == "__main__": dog = Animal("dog Fury", 3) # dir() 方法获得一个对象的所有属性和方法 print(dir(dog)) # 对象的属性进行操作的方法 getattr() hasattr() setattr() setattr(dog, "dog_type", "yellow_dog") print(dir(dog)) print(hasattr(dog, "dog_type")) print(getattr(dog, "dog_type")) print(getattr(dog, "dog_fly", 404))
"""生成器,生成从 3 开始的无限奇数序列""" def _odd_iter(): n = 1 while True: n = n + 2 yield n """筛选函数""" def __not_divisible(n): return lambda x: x % n > 0 """生成器,不断返回下一个素数""" def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(__not_divisible(n), it) # 构造新序列 if __name__ == '__main__': number = int(input("请输入要打印的素数范围(最大值):\n")) for n in primes(): if n < number: print(n) else: break
import numpy as np import unicodedata def calculate(numbers): if len(numbers) != 9: raise ValueError('List must contain nine numbers.') matrix = np.array(numbers, dtype='float64').reshape((3, 3)) calculations = {} calculations['mean'] = [list(matrix.mean(axis=0)), list(matrix.mean(axis=1)), matrix.mean()] calculations['variance'] = [list(matrix.var(axis=0)), list(matrix.var(axis=1)), matrix.var()] calculations['standard deviation'] = [list(matrix.std(axis=0)), list(matrix.std(axis=1)), matrix.std()] calculations['min'] = [list(matrix.min(axis=0)), list(matrix.min(axis=1)), matrix.min()] calculations['max'] = [list(matrix.max(axis=0)), list(matrix.max(axis=1)), matrix.max()] calculations['sum'] = [list(matrix.sum(axis=0)), list(matrix.sum(axis=1)), matrix.sum()] return calculations def theory(): std_sign = 'σ' std_sign_name = unicodedata.name(std_sign) text = (f"Deviation means 'how far from the normal'. \n" f"The Standard Deviation is a measure of how spread out numbers are. \n" f"Its symbol is 'σ' - '{std_sign_name}'\n" f"formula: the square root of the Variance.\n" f"Variance - the average of the squared differences from the Mean. \n" f"Mean - the simple average. \n") print(text)
import string def print_grid(grid): #print(grid) for row in grid: print(*row, sep=' ') def get_code(index): if index < 26: return string.ascii_uppercase[index] if index < 2*26: return 'A' + get_code(index % 26) raise SystemError("unhandled index" + i) coords = [list(map(int, line.split(', '))) for line in map(str.rstrip, open('input/06_INPUT.txt'))] dim = max(map(lambda row : max(row), coords)) print("dim=", dim) grid = [[0] * (dim+1) for _ in range(dim+1)] #print_grid(grid) for coord in coords: print("{}".format(coord)) for i,(x,y) in enumerate(coords): print("i={}, coords=({},{}), code='{}'".format(i,x,y, get_code(i))) grid[x][y] = get_code(i) #print_grid(grid) def manhattan_distance(p1, p2): return abs(p2[0]-p1[0]) + abs(p2[1]-p1[1]) def find_nearest_code(grid_point, coords): code_to_distance = { grid[x][y] : manhattan_distance(grid_point, (x,y)) for (x,y) in coords } min_distance = min(code_to_distance.values()) codes = list(filter(lambda key : code_to_distance[key]==min_distance, code_to_distance)) result = "." if len(codes) > 1 else codes[0].lower() print("find_nearest_code({},{})='{}'".format(grid_point[0], grid_point[1], result)) return result def is_sum_distance_under_threshold(grid_point, coords, threshold=10000): code_to_distance = { grid[x][y] : manhattan_distance(grid_point, (x,y)) for (x,y) in coords } #print("{} -> {} sum={}".format(grid_point, code_to_distance, sum(code_to_distance.values()))) return sum(code_to_distance.values()) < threshold #print(manhattan_distance((0,0), (1,2))) #print(find_nearest_code((0,0),coords)) marked_coords = list() for i,row in enumerate(grid): for j,cell in enumerate(row): #if grid[i][j] == 0: if is_sum_distance_under_threshold((i,j), coords): marked_coords += [(i,j)] #grid[i][j] = find_nearest_code((i,j), coords) for tuple in marked_coords: grid[tuple[0]][tuple[1]] = '#' #print_grid(grid) #infinite_codes = sorted(set(grid[0] + grid[dim] + [grid[i][0] for i in range(dim+1)] + [grid[0][i] for i in range(dim+1)])) #infinite_codes = sorted(map(lambda code : code.lower(), infinite_codes)) #print("infinite_codes=", infinite_codes) #code_counts = collections.defaultdict(int) safe_regions_count = 0 for i,row in enumerate(grid): for j,cell in enumerate(row): code = grid[i][j] # if not code.lower() in infinite_codes: # code_counts[code.lower()] += 1 if code == '#': safe_regions_count += 1 # #print("code_counts=", code_counts) #max_value = max(code_counts.values()) #print("size of largest area={} (code: '{}')".format(max_value, None)) print("safe_regions_count=", safe_regions_count)
#!/usr/bin/Python3 # -*- coding: utf-8 -*- # ================================================================= # File : Scan_dir_full.py # Author : LinXpy # Time : 2018/12/21 21:29 # Function Description : # 1) Scan the specified whole directory, calculate each subdir and # file size, list all the subdir and files in it; # 2) visualize/print the whole directory tree; # ================================================================= import os import os.path from time import strftime, localtime fsizedicr = {"B": 1, # B=Byte "KB": float(1)/1024, "MB": float(1)/(1024*1024), "GB": float(1)/(1024*1024*1024) } scan_path = input("Please input the directory path you want to scan(like D:\somedir\somedir): ") scan_level = input("Please input the scan level(0:current dir; 1:1st-level subDir; 2:2nd-level subDir....): ") scan_level = int(scan_level) # optimize: scan level的大小判断,以及彻底扫描的处理 full scan(scan_level='full') print("Start to scan the given dir: %s ..." % scan_path) def get_dir_size(dir_path): """ Description: get the whole size of specified directory dir_path """ dir_size = 0 for sub_dir_path, sub_dir_names, sub_file_names in os.walk(dir_path): for sub_file_name in sub_file_names: try: sub_file = os.path.join(dir_path, sub_dir_path, sub_file_name) dir_size += os.path.getsize(sub_file) except: print("Hit exception when deal with file %s" % sub_file) continue return dir_size def get_dir_file_info(item_path): """ Description: get detail information about the specified dir/file item_path: the absolute path of the specified dir or file """ try: item_atime = os.path.getatime(item_path) # get last access time item_mtime = os.path.getmtime(item_path) # get last modification time item_ctime = os.path.getctime(item_path) # get creation time for Windows, last metadata change time for Linux access_time = strftime("%Y/%m/%d %H:%M:%S", localtime(item_atime)) modification_time = strftime("%Y/%m/%d %H:%M:%S", localtime(item_mtime)) creation_time = strftime("%Y/%m/%d %H:%M:%S", localtime(item_ctime)) except: modification_time = None print("Item %s is not dir, nor file" % item_path) if os.path.isfile(item_path): item_size = os.path.getsize(item_path) # get file size elif os.path.isdir(item_path): item_size = get_dir_size(item_path) else: item_size = 0 print("Item %s is not dir, nor file" % item_path) return item_size, modification_time def size_transform(size): """ Description: transform the int size(byte) into string size with specified unit(GB, MB, KB, B) """ if size > 1024 * 1024 * 1024: size_str = str(round(fsizedicr['GB'] * size, 2)) + 'GB' elif size > 1024 * 1024: size_str = str(round(fsizedicr['MB'] * size, 2)) + 'MB' elif size > 1024: size_str = str(round(fsizedicr['KB'] * size, 2)) + 'KB' else: size_str = str(round(fsizedicr['B'] * size, 2)) + 'B' return size_str base_path_list = scan_path.split('\\') # D:\Doc_Test -> ['D:', 'Doc_Test'] base_path_len = len(base_path_list) # dir_list_dict: # key: dirname of level0 + '-level' + level_flag(offset)(like "test-level1") # value: list of dirs & files in current dir dir_list_dict = {} # store the list of files & dirs in each scan dir dir_info_dict = {} # store the info(size, mtime) of dirs in each scan dir file_info_dict = {} # store the info(size, mtime) of files in each scan dir def scan_dir(scan_path, scan_level): """ Description: list the dirs & files in the scan dir of each scan level; calculate the size of dirs & files in the scan dirl store the scan dirs & files info into dict(info: size, modification time); """ size = 0 # size of current scan dir scan_path print("Dir scan path: %s" % scan_path) path_list = scan_path.split('\\') path_len = len(path_list) level_flag = path_len - base_path_len # current scan path level based on the base scan path print("Dirs scan level: %d" % level_flag) dir_file_list = os.listdir(scan_path) print("Dirs or files list: %s" % dir_file_list) # if level_flag == 0: # reserve the name of dirs in root scan path to form the key of dir_list_dict # root_subdir_list = dir_file_list if level_flag == 0: # scan the initial base path key_name = os.path.basename(scan_path) dir_list_dict[key_name] = dir_file_list elif level_flag == 1: # extract root subdir(level 0) name from path_list for current scan dir root_subdir_name = path_list[base_path_len] # list index is 0 base key_name = root_subdir_name dir_list_dict[key_name] = dir_file_list else: root_subdir_name = path_list[base_path_len] key_name = root_subdir_name + "@level" + str(level_flag - 1) + '@' + path_list[-1] # construct special key_name with root subdir dir_list_dict[key_name] = dir_file_list # calculate the size of directory scan_path for item in os.listdir(scan_path): item_full = os.path.join(scan_path, item) item_size, mtime = get_dir_file_info(item_full) size += item_size # if file, store file info into dict according to current level_flag for latter usage if os.path.isfile(item_full): if level_flag == 0: # files in initial base path file_size_str = size_transform(item_size) key_name = item file_info_dict[key_name] = "size:%s mtime:%s" % (file_size_str, mtime) else: file_size_str = size_transform(item_size) root_subdir_name = path_list[base_path_len] # list index is 0 base key_name = root_subdir_name + "@level" + str(level_flag) + '@' + item file_info_dict[key_name] = "size:%s mtime:%s" % (file_size_str, mtime) # if dir, store dir info into dict later in outside of for cycle if os.path.isdir(item_full): if level_flag == 0: # dirs in initial base path dir_size_str = size_transform(item_size) key_name = item dir_info_dict[key_name] = "size:%s mtime:%s" % (dir_size_str, mtime) else: dir_size_str = size_transform(item_size) root_subdir_name = path_list[base_path_len] key_name = root_subdir_name + "@level" + str(level_flag) + '@' + item dir_info_dict[key_name] = "size:%s mtime:%s" % (dir_size_str, mtime) # if os.path.isdir(item_full) and scan_level > 0: # recursively scan next level dir # scan_dir(item_full, scan_level - 1) size_str = size_transform(size) print("Current dir %s size is: %s" % (scan_path, size_str)) # store the base scan dir info into dict if level_flag == 0: # base_dir_size_str = size_transform(size) base_dir_size_str = size_str key_name = os.path.basename(scan_path) base_dir_atime = os.path.getatime(scan_path) base_dir_mtime = os.path.getmtime(scan_path) base_dir_ctime = os.path.getctime(scan_path) access_time = strftime("%Y/%m/%d %H:%M:%S", localtime(base_dir_atime)) modification_time = strftime("%Y/%m/%d %H:%M:%S", localtime(base_dir_mtime)) creation_time = strftime("%Y/%m/%d %H:%M:%S", localtime(base_dir_ctime)) dir_info_dict[key_name] = "size:%s mtime:%s" % (base_dir_size_str, modification_time) # According to scan_level to decide whether need to scan deeper for item in os.listdir(scan_path): item_full = os.path.join(scan_path, item) if os.path.isdir(item_full) and scan_level > 0: # recursively scan next level dir scan_dir(item_full, scan_level - 1) def create_show_dir_tree(scan_path, scan_level): """ Description: create and print the whole dir tree """ node_icon = {"BRANCH": '├─', "LAST_BRANCH": '└─', "TAB": '│ ', "EMPTY_TAB": ' '} # BRANCH = '├─' # LAST_BRANCH = '└─' # TAB = '│ ' # EMPTY_TAB = ' ' level_flag = 0 base_dir_name = os.path.basename(scan_path) # root dir name of scan_path root_node = base_dir_name print(root_node) for item in dir_list_dict[base_dir_name]: # item: root subdir name or file name, level 0 if item not in dir_info_dict.keys(): # a file root_subfile_node = node_icon["LAST_BRANCH"] + item root_subfile_info = file_info_dict[item] print(root_subfile_node) else: root_subdir_node = node_icon["BRANCH"] + item root_subdir_info = dir_info_dict[item] print(root_subdir_node) level_flag += 1 parse_dict_create_tree(level_flag, item, item, node_icon) # for root subdir, key_name==root_subdir_name level_flag = 0 def parse_dict_create_tree(level_flag, key_name, root_subdir_name, node_icon): """ Description: recursively create and print subdir tree key_name: the specially constructed name for subdir, files root_subdir_name: the subdir & file name in root scan dir, use to construct the key_name """ if level_flag <= scan_level and len(dir_list_dict[key_name]) > 0: # dir key_name not empty for sub_item in dir_list_dict[key_name]: key_name = root_subdir_name + "@level" + str(level_flag) + '@' + sub_item # construct special key for subdir/file if key_name not in dir_info_dict.keys(): # a file level_subfile_node = node_icon["TAB"] * level_flag + node_icon["LAST_BRANCH"] + sub_item level_subfile_info = file_info_dict[key_name] print(level_subfile_node) else: # a dir level_subdir_node = node_icon["TAB"] * level_flag + node_icon["BRANCH"] + sub_item level_subdir_info = dir_info_dict[key_name] print(level_subdir_node) parse_dict_create_tree(level_flag + 1, key_name, root_subdir_name, node_icon) if __name__ == "__main__": scan_dir(scan_path, scan_level) print(dir_list_dict) print(file_info_dict) print(dir_info_dict) create_show_dir_tree(scan_path, scan_level)
''' . Create a class cal5 that will calculate area of a rectangle. Create constructor method which has two parameters .Create calArea() method that will calculate area of a rectangle. Create display() method that will display area of a rectangle ''' class Cal5: def __init__(self,height,width): self.length = lenght self.width = width def calArea(self): area = self.length * self.width print("Area of rectangle with length={} and width ={} is {}".format(self.length,self.width,area)) lenght =int(input("enter length:")) width =int(input("enter width:")) obj = Cal5(lenght,width) obj.calArea()
# check num is 0 or +ve or -ve num = int(input("enter number")) if num == 0: print("num is 0") elif num<0: print("num is -ve") else: print("num is +ve")
# PROJECT 1 --- ES2 # Theoretical Pendulum Periods # FILL THESE COMMENTS IN #***************************************** # NAMES: Ryan Hankins and Aedan Brown # NUMBER OF HOURS TO COMPLETE: 0.5 # YOUR COLLABORATION STATEMENT(s): We worked alone on this assignment # # #***************************************** import numpy as np import matplotlib.pyplot as plt #The theoretical equation used to find the period of a simple pendulum assumes #that there is no friction or drag, the pendulum structure is perfectly rigid, #and the string holding the mass is massless and doesn't stretch. Also, the simple pendulum #equation only works for small angles of movement when sin theta is approximately equal to theta. #FUNCTIONS--------------------------------------------------------------------- def length_to_period(length_array): #Takes an array of pendulum lengths and returns an array of the periods #for those respective lengths by using the pendulum equation return 2*np.pi*np.sqrt((length_array/100)/9.81) def plotter(length_array,period_array): #Plots length vs period using the length and period arrays. Has no return value plt.plot(length_array,period_array) plt.title("Period vs Length (Theoretical)") plt.xlabel("Pendulum Length (cm)") plt.ylabel("Period Length (s)") plt.show() #MAIN-------------------------------------------------------------------------- lengths = np.array([74.3, 63.9,54.5,45.4,35.6]) #measured in centimeter periods = length_to_period(lengths) plotter(lengths,periods)
#Takes a value in a list, multiplies the value by 2, and adds the product to a variable total numbers = [2,4,6,8] def times_two(values): total=0 for num in numbers: total += num*2 return total print(times_two(numbers))
""" Inheritance: You have 2 classes where the parent class:Employee has a basic template. Now you wrote another class Programmer. Now a programmer is also an employee but it has some additional qualities/features etc. Keeping in mind the best coding practice DRY:DO NOT REPEAT, since there is a template similarity between Employee class and Programmer class I don't want to repeat the code patch of Employee in Programmer. Hence I am inheriting properties of class Employee in Programmer. """ class Employee: no_of_leaves=116 def __init__(self,aname,aage,arole): #Here aname,aage and arole are the ergume nts of the constructor #name,age and occupation are the instance variables""" self.name=aname self.age=aage self.occupation=arole @classmethod def change_no_of_leaves(cls,changed_leaves): cls.no_of_leaves=changed_leaves @classmethod def value_instance_arg(cls,string): # value_list=string.split("-") # return cls(value_list[0],value_list[1],value_list[2]) return cls(*string.split("-")) #When we have to execute something without a self(instance variable) or a class variable, we can use static method @staticmethod def print_something(string1): print(f"{string1} is a good boy") """ Single Inheritance """ class Programmer(Employee): def __init__(self,aname,aage,arole,salary,*languages): self.name=aname self.age=aage self.occupation=arole #Now here we could have used the constructore of the super class by using super() to follow the code-reusability #concept. But for now we have copied the constructor. self.salary=salary self.languages=languages def print_from_new_class(self): print(f"My name is {self.name}. I am {self.age} years old. My role is {self.occupation}. My salary is {self.salary}." f"He knows {self.languages}") souvik=Employee("Souvik",25,"Mainframe SSE") sayli=Employee("Sayli",26,"Mulesoft SSE") souvik.print_something(souvik.name) #We can also call the static methodusing class(Employee) Employee.print_something(sayli.name) """Now making an instance of a subclass(Programmer) and executing it's function""" atanu=Programmer("Atanu",26,"Clerk",10000,*["C++","Python","JAVA"]) atanu.print_from_new_class()
""" Inheritance: You have 2 classes where the parent class:Employee has a basic template. Now you wrote another class Programmer. Now a programmer is also an employee but it has some additional qualities/features etc. Keeping in mind the best coding practice DRY:DO NOT REPEAT, since there is a template similarity between Employee class and Programmer class I don't want to repeat the code patch of Employee in Programmer. Hence I am inheriting properties of class Employee in Programmer. """ class Employee: no_of_leaves=116 def __init__(self,aname,aage,arole): #Here aname,aage and arole are the ergume nts of the constructor #name,age and occupation are the instance variables""" self.name=aname self.age=aage self.occupation=arole @classmethod def change_no_of_leaves(cls,changed_leaves): cls.no_of_leaves=changed_leaves @classmethod def value_instance_arg(cls,string): # value_list=string.split("-") # return cls(value_list[0],value_list[1],value_list[2]) return cls(*string.split("-")) #When we have to execute something without a self(instance variable) or a class variable, we can use static method @staticmethod def print_something(string1): print(f"{string1} is a good boy") """ Multiple Inheritance """ class Player: no_of_games=4 def __init__(self,name,game): self.name=name self.game=game def print_details(self): print(f"The player's name is {self.name} and he plays these games {self.game}") class CoolProgrammer(Employee,Player): #The order in which employee and player is given, is very important as per requirement. language="C++" def print_language(self): return self.language souvik=Employee("Souvik",25,"Mainframe SSE") sayli=Employee("Sayli",26,"Mulesoft SSE") aniket=Player("Aniket",["Cricket","Chess","Volleyball"]) #harsh=CoolProgrammer("Harsh",24,"Tester") # harsh.print_something(harsh.name) # print(harsh.print_language()) srishti=CoolProgrammer("Srishti",26,"Tester") print(srishti.print_language())
class Dad: history_knowledge="Expert" #This is a public variable _person="Good" #This is a protected variable __property="Nothing" #This is a private variable. def print_dad_details(self): print(f"Madan Mohan Ganguly had {self.history_knowledge} level of knowledge in history") class Son(Dad): hard_work_grade="Expert" history_knowledge = "Dope Expert" def print_son_details(self): print(f"Debdas Ganguly did {self.hard_work_grade} level of hardwork") class Grandson(Son): intelligence="good" def print_grandson_details(self): print(f"Souvik Ganguly had {self.intelligence} level of intelligence") souvik=Grandson() debdas=Son() madan=Dad() madan.print_dad_details() souvik.print_dad_details() debdas.print_dad_details() souvik.print_dad_details() souvik.print_son_details() debdas.print_son_details() souvik.print_grandson_details() print(madan.history_knowledge) #Public variables can be used anywhere print(madan._person) #Protected variables can be used withing the class and the sub-classes. print(madan._Dad__property) #Private variables cannot anywhere. Even though with name angling it can be used within #the sub classes. print(debdas._person) print(debdas._Dad__property)
"""This is a python mini project- Health Management System. This app maintains the food habits and exercises performed by 3 people-Souvik, Atanu and Abhijit along with time-stamp. You can either add their activities or retrieve their activities till now as per your requirement. It involves: dynamic programming, functions, while loop, for loop, if elif else conditional statement and an app building mindset development methodology.""" print("**********************************************************************************************") print("*****************************HEALTH MANAGEMENT SYSTEM*****************************************") print("**********************************************************************************************") def func_action(): print("Hello. Please select your action.") print("For locking action : Press 1") print("For retrieving data : Press 2") def func_name(): print("For whom do you want to perform the action?") print("For Souvik : Press 1") print("For Atanu : Press 2") print("For Abhijit : Press 3") def func_lock_what(): print("What do you want to lock?") print("For locking meals : Press 1") print("For locking exercise : Press 2") def func_retrieve_what(): print("What do you want to retrieving?") print("For retrieving meals : Press 1") print("For retrieving exercise : Press 2") def getdate(): import datetime return datetime.datetime.now() flag="Y" while(flag=="Y"): func_action() action = input() if action=="1": func_name() name = input() if name=="1": func_lock_what() lock_what = input() if lock_what=="1": f = open("21A Souvik_food.txt", "a") print("What did you eat?") food=input() a=str(getdate())+""+food f.write(a+"\n") f.close() print("Do you want to continue any other action?(Y/N)") flag=input() if(flag=="Y" or flag=="N"): continue else: print("Invalid option.") elif lock_what=="2": f = open("21A Souvik_exercise.txt", "a") print("What exercise did you do?") exercise = input() a=str(getdate())+""+exercise f.write(a+"\n") f.close() print("Do you want to continue any other action?(Y/N)") flag = input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid locking option. Do you want to continue any other action?(Y/N)") flag= input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif name=="2": func_lock_what() lock_what = input() if lock_what=="1": f = open("21A Atanu_food.txt", "a") print("What did you eat?") food=input() a = str(getdate()) + "" + food f.write(a+"\n") f.close() print("Do you want to continue any other action?(Y/N)") flag=input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif lock_what=="2": f = open("21A Atanu_exercise.txt", "a") print("What exercise did you do?") exercise = input() a = str(getdate()) + "" + exercise f.write(a+"\n") f.close() print("Do you want to continue any other action?(Y/N)") flag = input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid locking option. Do you want to continue any other action?(Y/N)") flag= input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif name=="3": func_lock_what() lock_what = input() if lock_what=="1": f = open("21A Abhijit_food.txt", "a") print("What did you eat?") food=input() a = str(getdate()) + "" + food f.write(a+"\n") f.close() print("Do you want to continue any other action?(Y/N)") flag=input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif lock_what=="2": f = open("21A Abhijit_exercise.txt", "a") print("What exercise did you do?") exercise = input() a = str(getdate()) + "" + exercise f.write(a+"\n") f.close() print("Do you want to continue any other action?(Y/N)") flag = input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid locking option. Do you want to continue any other action?(Y/N)") flag= input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid person option. Do you want to continue any other action?(Y/N)") flag = input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif action=="2": func_name() name=input() if name=="1": func_retrieve_what() retrieve_what=input() if retrieve_what=="1": f = open("21A Souvik_food.txt", "r") for line in f: print(line,end="") f.close() print("Do you want to continue any other action?(Y/N)") flag=input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif retrieve_what=="2": f = open("21A Souvik_exercise.txt", "r") for line in f: print(line, end="") f.close() print("Do you want to continue any other action?(Y/N)") flag = input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid retrieving option. Do you want to continue any other action?(Y/N)") flag= input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif name=="2": func_retrieve_what() retrieve_what=input() if retrieve_what=="1": f = open("21A Atanu_food.txt", "r") for line in f: print(line,end="") f.close() print("Do you want to continue any other action?(Y/N)") flag=input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif retrieve_what=="2": f = open("21A Atanu_exercise.txt", "r") for line in f: print(line, end="") f.close() print("Do you want to continue any other action?(Y/N)") flag = input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid retrieving option. Do you want to continue any other action?(Y/N)") flag= input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif name=="3": func_retrieve_what() retrieve_what=input() if retrieve_what=="1": f = open("21A Abhijit_food.txt", "r") for line in f: print(line,end="") f.close() print("Do you want to continue any other action?(Y/N)") flag=input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") elif retrieve_what=="2": f = open("21A Abhijit_exercise.txt", "r") for line in f: print(line, end="") f.close() print("Do you want to continue any other action?(Y/N)") flag = input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid retrieving option. Do you want to continue any other action?(Y/N)") flag= input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid person option. Do you want to continue any other action?(Y/N)") flag = input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") else: print("Invalid action. Do you want to try again?(Y/N)") flag=input() if (flag == "Y" or flag == "N"): continue else: print("Invalid option.") print("Thanks for using our Health Management System. Take care!!")
def TwoDArray(size): arr = [] for _ in range(size): arr.append(list(map(str, input().strip().split()))) return arr def printMatrix(array): for row in array:` for element in ''.join(row): print(element, end=" ") print("") matrix_size = int(input()) printMatrix(TwoDArray(matrix_size))
#!/usr/bin/env python3 import argparse import csv import json import os.path # Reads the variants.csv file and outputs a tuple of 3 dictionaries: (variants, languages, packs) def readVariants(varCsv): with open(varCsv, newline='', encoding='utf-8') as csvVariants: variantsReader = csv.reader(csvVariants) header = [] variants = {} variantNameSet = set() languages = {} packs = {} rowNum = 0 for row in variantsReader: if (rowNum == 0): pass elif (rowNum == 1): header = row else: colNum = 0 variant = {} for val in row: variant[header[colNum]] = val colNum += 1 if variant['variantID'] in variants: raise "Duplicate language variant: " + variant['variantID'] if variant['stems'] != '': variant['dictType'] = 'hs' else: variant['dictType'] = '' variant['isDefault'] = (variant['isDefault'] == "y") variants[variant['variantID']] = variant # variantName should be unique if variant['variantFullName'] in variantNameSet: raise "Duplicate language variant name: " + variant['variantFullName'] variantNameSet.add(variant['variantFullName']) language = {} language['name'] = variant['languageName'] language['id'] = variant['languageID'] language['qlanguage'] = variant['qlanguage'] language['defaultVariant'] = "" language['variants'] = [variant['variantID']] if language['id'] in languages: languages[language['id']]['variants'] += [variant['variantID']] else: languages[language['id']] = language if variant['isDefault']: if languages[language['id']]['defaultVariant'] != "": raise "Language has two variants: " + variant['variantID'] + " and: " + languages[language['id']]['defaultVariant'] languages[language['id']]['defaultVariant'] = variant['variantID'] languages[language['id']] if variant['pack'] not in packs: packs[variant['pack']] = [] packs[variant['pack']] += [variant['variantID']] #print(json.dumps(variant, indent=4)) rowNum += 1 #print(json.dumps(variants, indent=4)) for langId, lang in languages.items(): if lang['defaultVariant'] == "": raise Exception("Language is missing a default variant:" + lang['name']) return (variants, languages, packs) # Reads the presets.csv file and outputs a tuple of 2 dictionaries: (presets, presetsByScript) def readPresets(presCsv): with open(presCsv, newline='', encoding='utf-8') as csvPresets: presetsReader = csv.reader(csvPresets) header = [] presets = {} presetsByScript = {} rowNum = 0 for row in presetsReader: if (rowNum == 0): pass elif (rowNum == 1): header = row else: colNum = 0 preset = {} for val in row: preset[header[colNum]] = val colNum += 1 if preset['id'] in presets: raise "Duplicate preset: " + preset['id'] presets[preset['id']] = preset if preset['qscript'] not in presetsByScript: presetsByScript[preset['qscript']] = [] presetsByScript[preset['qscript']] += [preset['id']] #print(json.dumps(preset, indent=4)) rowNum += 1 return (presets, presetsByScript) # For each variant, check if it has a dictionary and create the .meta.json file for it def createMetaForDictionaries(variants, dictsDir): for k, v in variants.items(): if v["description"] == "": del v["description"] dirPath = dictsDir + "/" + k if os.path.isdir(dirPath): path = dirPath + "/" + k + ".meta.json" with open(path, 'w', encoding='utf-8') as vout: json.dump(v, vout, indent=4, ensure_ascii=False) def createMetaForPacks(variants, languages, packs, presets, presetsByScript, packsDir): basicPresets = set() basicFonts = set() for variantId in packs['basic']: basicScript = variants[variantId]['qscript'] for basicPreset in presetsByScript[basicScript]: basicPresets.add(basicPreset) preset = presets[basicPreset] basicFonts.add(preset['typewriterFont']) basicFonts.add(preset['serifFont']) basicFonts.add(preset['sansFont']) basicFonts.add(preset['titleFont']) if preset['additionalFonts'] != '': for font in preset['additionalFonts'].split(','): basicFonts.add(font.strip()) #print(basicPresets) #print(basicFonts) for pack, packVariants in packs.items(): #print(pack) packDir = packsDir + "/" + pack manifest = packDir + "/packmanifest.json" #print(manifest) packJson = {} packJson['active'] = True isBasic = (pack == 'basic') packJson['preinstalled'] = isBasic packJson['languages'] = [] variantsByLang = {} for variantId in packVariants: langId = variants[variantId]['languageID'] if langId not in variantsByLang: variantsByLang[langId] = [] variantsByLang[langId] += [variantId] packScripts = set() for langId, variantIds in variantsByLang.items(): lang = {} lang['name'] = languages[langId]['name'] lang['id'] =langId lang['qlanguage'] = languages[langId]['qlanguage'] lang['defaultVariant'] = languages[langId]['defaultVariant'] lang['variants'] = [] for variantId in variantIds: variant = {} variant['name'] = variants[variantId]['variantName'] variant['id'] = variantId #variant['fullName'] = variants[variantId]['variantFullName'] variant['defaultPreset'] = variants[variantId]['defaultPreset'] variant['qscript'] = variants[variantId]['qscript'] variant['qcountry'] = variants[variantId]['qcountry'] variant['dictType'] = variants[variantId]['dictType'] if 'description' in variants[variantId]: variant['description'] = variants[variantId]['description'] lang['variants'] += [variant] packScripts.add(variant['qscript']) lang['variants'].sort(key = lambda variant: variant['name']) if lang['name'] != '': packJson['languages'] += [lang] packJson['languages'].sort(key = lambda lang: lang['name']) packJson['presets'] = [] packJson['fonts'] = set() for packScript in packScripts: for packPreset in presetsByScript[packScript]: preset = presets[packPreset].copy() if preset['description'] == '': del preset['description'] packJson['fonts'].add(preset['typewriterFont']) packJson['fonts'].add(preset['serifFont']) packJson['fonts'].add(preset['sansFont']) packJson['fonts'].add(preset['titleFont']) if preset['additionalFonts'] != '': for font in preset['additionalFonts'].split(','): packJson['fonts'].add(font.strip()) del preset['additionalFonts'] if preset['name'] != '' and (isBasic or preset['id'] not in basicPresets): packJson['presets'] += [preset] if not isBasic: packJson['fonts'] -= basicFonts packJson['fonts'] = sorted(list(packJson['fonts'])) packJson['presets'] = sorted(list(packJson['presets']), key = lambda preset: preset['id']) #print(json.dumps(packJson, indent=4)) with open(manifest, 'w', encoding='utf-8') as pout: json.dump(packJson, pout, indent=4, ensure_ascii=False) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--variants", type=str, required=True, help="The variants csv table") parser.add_argument("--presets", type=str, required=True, help="The presets csv table") parser.add_argument("--dicts", type=str, required=True, help="The folder containing the dictionaries") parser.add_argument("--packs", type=str, required=True, help="The folder containing the packs") args = parser.parse_args() (variants, languages, packs) = readVariants(args.variants) #print(json.dumps(variants, indent=4)) #print(json.dumps(languages, indent=4)) #print(json.dumps(packs, indent=4)) (presets, presetsByScript) = readPresets(args.presets) #print(json.dumps(presets, indent=4)) #print(json.dumps(presetsByScript, indent=4)) createMetaForDictionaries(variants, args.dicts) #print(json.dumps(packs, indent=4)) createMetaForPacks(variants, languages, packs, presets, presetsByScript, args.packs)
# Assignment 1 # Part 3 # Robert Garza, Jheovanny Camacho, Robert Hovanesian # 03-05-2019 class Hamburger: def __init__(self, **kwargs): """ initialization of Hamburger class, arbitrary number of keyword arguments accepted """ # object attributes are mapped to the keyword arguments # self dictionary is used to store mappings self.__dict__ = kwargs def __str__(self, sep=''): """ string version of object returns single string of all dict values separated by commas """ return (', '.join(list(self.__dict__.values()))) # different test cases with varying amount of arguments burger1 = Hamburger(meat="chicken", extra1="cheese", extra2="ketchup") burger2 = Hamburger(meat="beef", extra1="cheese", extra2="mayo") burger3 = Hamburger(meat="snake", extra1="tarter sauce", extra2="peanuts", extra3="motor oil") print(burger1) print(burger2) print(burger3)
# Mr Miyagi trainee # make a Mr Miyagi virtual assistant # put main body of code in a function def miyagi_response(user_input): response_count = 0 # Evaluate each input and print the appropriate responses if user_input == "sensei, i am at peace": end_code = True print("[Mr Miyagi] Sometimes, what heart know, head forget") else: # every statement/question must start with Sensei, otherwise: # --> 'You are smart, but not wise - address me as Sensei please' if not user_input.capitalize().startswith("Sensei"): print("[Mr Miyagi] You are smart, but not wise - address me as Sensei please") response_count += 1 # every time you ask a question --> Mr. Miyagi responde with # --> 'questions are wise, but for now. Wax on, and Wax off!' if user_input.strip().endswith('?'): print("[Mr Miyagi] Questions are wise, but for now. Wax on. Wax off!") response_count += 1 # every time you mention 'block' or 'blocking' --> Mr. Miyagi responde with # --> 'Remember, best block, not to be there..' if ("block") in user_input or ("blocking") in user_input: print("[Mr Miyagi] Remember, best block, not to be there..") response_count += 1 # anything else you say: # --> 'do not lose focus. Wax on. Wax off.' if response_count == 0: print("[Mr Miyagi] Do not lose focus. Wax on. Wax off.") # as a user I should be able to speak with Mr Miyagi and get appropriate response s as I go print("MR MIYAGI VIRTUAL ASSISTANT \n") name = input("Enter your name \n") print("Say Something Below " + name + ":") # Ask for user input and depending on the response, Mr Miyagi will respond. end_code = False # make it run continuously while not end_code: # prompt user for input user_input = input("[Mr Miyagi] Yes???\n" + "[" + name + "] ").lower() miyagi_response(user_input) # call function # Make it so you keep playing until we say: 'Sensei, I am at peace' # --> 'Sometimes, what heart know, head forget' # EXTRA: # consider best practices of functions - make this functional
# Write a bizz and zzuu game ##project # as a user I should be able prompted for a number, as the program will print all the number up to and inclusing said number while following the constraints / specs. (bizz and buzz for multiples or 3 and 5) # As a user I should be able to keep giving the program different numbers and it will calculate appropriately until you use the key word: 'penpinapplespen' # write a program that take a number # prints back each individual number, but # if it is a multiple of 3 it returns bizz # if a multiple of 5 it return zzuu # if a multiple of 3 and 5 it return bizzzzuu # EXTRA: # Make it functional # make it so I can it so it can work with 4 and 9 insted of 3 and 5. # make it so it can work with any number! def check_if_number(number): if number.isnumeric() and int(number) >= 1: return True else: print("You haven't typed in a valid number, please try again!") return False def bizzzzuu_me(limit, param1, param2): for x in range(int(limit)): y = x + 1 if y % param1 == 0 and y % param2 == 0: # if divisible by both 3 and 5, print fizzbuzz print("bizzzzuu") elif y % param1 == 0: # if only divisible by 3, print fizz print("bizz") elif y % param2 == 0: # if only divisible by 5, print buzz print("zzuu") else: print(y) # if none of those, just print the number def get_params(position, previous_param): correct_input1 = False while not correct_input1: param = input("Pick a number for the " + position + " number: ") if check_if_number(param) and int(param) != previous_param: correct_input1 = True return int(param) else: print("Number is the same as first parameter - not allowed") def play(choice): correct_input = False while not correct_input: user_number = input("Please enter the limit number now!\n") if check_if_number(user_number): correct_input = True if choice == 1: bizzzzuu_me(user_number, 3, 5) elif choice == 2: bizzzzuu_me(user_number, 4, 9) else: param1 = get_params('lowest', 0) param2 = get_params('highest', param1) bizzzzuu_me(user_number, param1, param2) print("WELCOME! How would you like to play BIZZZZUU?: \n 1) Standard (3 and 5) \n 2) Bigger (4 and 9) \n 3) Custom " "(Pick your own!)") correct_input = False while not correct_input: user_choice = input("Enter option 1,2 or 3 to play! \n") if check_if_number(user_choice): x = int(user_choice) if x == 1 or x == 2 or x ==3: correct_input = True play(x) else: "Invalid Option. Try Again" print("Thanks for playing!")
# INTRO TO PYTHON - VARIABLES, INPUTS AND PRINTING # box_variable = "Books and Stuff" # Store string as variable # print(box_variable) # #Print variable # box_variable = 3 # Reassign as an int # print(box_variable) # Re-print # print(type(box_variable)) # Print data type of variable # Other variables include; # float (decimals ie. 3.5) # boolean (true or false) # first_name = "Ryan" # last_name = "Smith" # full_name = first_name + last_name # combine first and last name together - cannot do this if not same data type # print(full_name) # fave_colour = "Red" # fave_team = "Liverpool" # combined = fave_team + " " + fave_colour # adds a space between the strings # print(combined) # print(type(combined)) # first_name = input("What is your name? \n") # print("Hi " +first_name + "!") # INPUTS AND RESPONSES # first_name = input("What is your first name? \n") # last_name = input("And your surname? \n") # age = int(input("How old are you? \n")) # DoB = input("When were you born? \n") # # print("Hello, " + first_name + " " + last_name + # ". You are " + str(age) + " Years Old. " + "You were born on " + DoB # + "\n The variable types are: ") # print(type(first_name)) # print(type(last_name)) # print(type(age)) # print(type(DoB)) # # Comparing INTEGERS # age = 23 # new_age = 24.6 # # BOOLEAN RESPONSE # print(age > new_age) # # PRINT LARGEST AGE # if age > new_age: # print(age) # else: # print(new_age)
import PyPDF2 as PP def cut(file1,initpage,finalpage): '''This function cuts pages from a pdf''' # creating a shell for the new file cutpdfobj = PP.PdfFileWriter() # opening the pdf pdf1File = open(file1, 'rb') # reading the pdf pdf1Reader = PP.PdfFileReader(pdf1File) # verifying page validity try: assert initpage in range(1,pdf1Reader.numPages+1)\ and finalpage in range(pdf1Reader.numPages) except AssertionError: return 'Error: please enter valid page numbers' # adding file1 to cutPDF for page_num1 in range(initpage-1,finalpage): page = pdf1Reader.getPage(page_num1) cutpdfobj.addPage(page) # creating the cutPDF file cutpdfname = str(input('Cut PDFs as: ')) cutpdf = open('{}.pdf'.format(cutpdfname), 'wb') cutpdfobj.write(cutpdf) # closing all Files pdf1File.close() cutpdf.close() return 'cut PDF as {}.pdf'.format(cutpdfname)
import osa import math def read_lines_from_file(input_path): with open(input_path) as input_file: return input_file.readlines() def count_exp(input_path): url = 'http://fx.currencysystem.com/webservices/CurrencyServer4.asmx?WSDL' client = osa.client.Client(url) sum_rub = 0 file_lines = read_lines_from_file(input_path) for currency_line in file_lines: currency_amount = int(currency_line.split(" ")[1]) currency_code = currency_line.split(" ")[2].strip() sum_rub += client.service.ConvertToNum(fromCurrency=currency_code, toCurrency='RUB', amount=currency_amount, rounding=True) print(math.ceil(sum_rub)) return sum_rub count_exp("C:\\Users\\Taya\\Desktop\\Coursera analytics\\Python\\python-netology\\currency_rate, xml, soap\\currencies.txt")
#!/usr/bin/env python import struct, string, math, copy class SudokuBoard: """This will be the sudoku board game object your player will manipulate.""" def __init__(self, size, board): """the constructor for the SudokuBoard""" self.BoardSize = size #the size of the board self.CurrentGameBoard= board #the current state of the game board def set_value(self, row, col, value): """This function will create a new sudoku board object with the input value placed on the GameBoard row and col are both zero-indexed""" #add the value to the appropriate position on the board self.CurrentGameBoard[row][col]=value #return a new board of the same size with the value added return SudokuBoard(self.BoardSize, self.CurrentGameBoard) def print_board(self): """Prints the current game board. Leaves unassigned spots blank.""" div = int(math.sqrt(self.BoardSize)) dash = "" space = "" line = "+" sep = "|" for i in range(div): dash += "----" space += " " for i in range(div): line += dash + "+" sep += space + "|" for i in range(-1, self.BoardSize): if i != -1: print "|", for j in range(self.BoardSize): if self.CurrentGameBoard[i][j] > 9: print self.CurrentGameBoard[i][j], elif self.CurrentGameBoard[i][j] > 0: print "", self.CurrentGameBoard[i][j], else: print " ", if (j+1 != self.BoardSize): if ((j+1)//div != j/div): print "|", else: print "", else: print "|" if ((i+1)//div != i/div): print line else: print sep def parse_file(filename): """Parses a sudoku text file into a BoardSize, and a 2d array which holds the value of each cell. Array elements holding a 0 are considered to be empty.""" f = open(filename, 'r') BoardSize = int( f.readline()) NumVals = int(f.readline()) #initialize a blank board board= [ [ 0 for i in range(BoardSize) ] for j in range(BoardSize) ] #populate the board with initial values for i in range(NumVals): line = f.readline() chars = line.split() row = int(chars[0]) col = int(chars[1]) val = int(chars[2]) board[row-1][col-1]=val return board def is_complete(sudoku_board): """Takes in a sudoku board and tests to see if it has been filled in correctly.""" BoardArray = sudoku_board.CurrentGameBoard size = len(BoardArray) subsquare = int(math.sqrt(size)) #check each cell on the board for a 0, or if the value of the cell #is present elsewhere within the same row, column, or square for row in range(size): for col in range(size): if BoardArray[row][col]==0: return False for i in range(size): if ((BoardArray[row][i] == BoardArray[row][col]) and i != col): return False if ((BoardArray[i][col] == BoardArray[row][col]) and i != row): return False #determine which square the cell is in SquareRow = row // subsquare SquareCol = col // subsquare for i in range(subsquare): for j in range(subsquare): if((BoardArray[SquareRow*subsquare+i][SquareCol*subsquare+j] == BoardArray[row][col]) and (SquareRow*subsquare + i != row) and (SquareCol*subsquare + j != col)): return False return True def init_board(file_name): """Creates a SudokuBoard object initialized with values from a text file""" board = parse_file(file_name) return SudokuBoard(len(board), board) def solve(initial_board, forward_checking = False, MRV = False, MCV = False, LCV = False): """Takes an initial SudokuBoard and solves it using back tracking, and zero or more of the heuristics and constraint propagation methods (determined by arguments). Returns the resulting board solution. """ curr_board = initial_board f_checking = forward_checking #minimum remaining values= choose var with fewest values left my_MRV = MRV #most constrained variable (degree)= choose var that is involved in largest num of constraints with unnassigned vars my_MCV = MCV #least constrained value= choose value that rules out fewest choices for other unnassigned vars my_LCV = LCV #call DFS on board to solve backtrack(curr_board, 0, f_checking, my_MRV, my_MCV, my_LCV) #print "Your code will solve the initial_board here!" #print "Remember to return the final board (the SudokuBoard object)." #print "I'm simply returning initial_board for demonstration purposes." return curr_board # Uses the validation checks written below to assemble a list of valid potential values # for square at given row and column def potentialVals(curr_board, row, col): potentialList = list() for i in range(1, curr_board.BoardSize + 1): if validRowCol(curr_board, row, col, i) and validBox(curr_board, row, col, i): potentialList.append(i) return potentialList # Checks for conflict with a potential value and the other squares in the same row or column def validRowCol(curr_board, row, col, val): for i in range(0, curr_board.BoardSize): if ((curr_board.CurrentGameBoard[row][i] == val) or (curr_board.CurrentGameBoard[i][col] == val)): return False return True # Checks for conflict with a potential value and the other squares in the same small box def validBox(curr_board, row, col, val): ss = int(math.sqrt(curr_board.BoardSize)) sRow = int((row / ss) * ss) sCol = int((col / ss) * ss) for i in range(0, ss): for j in range(0, ss): if (curr_board.CurrentGameBoard[sRow+i][sCol+j] == val): return False return True # Finds unassigned neighboring squares, with neighboring being defined as # within the same row, within the same column, or within the same small box def getEmptyNeighbors(curr_board, row, col): neighbors = list() # Search rows and columns first for i in range(0, curr_board.BoardSize): if (curr_board.CurrentGameBoard[row][i] == 0 and [row, i] not in neighbors and [row, i] != [row, col]): neighbors.append([row, i]) if (curr_board.CurrentGameBoard[i][col] == 0 and [i, col] not in neighbors and [i, col] != [row, col]): neighbors.append([i, col]) # Search boxes ss = int(math.sqrt(curr_board.BoardSize)) sRow = int((row / ss) * ss) sCol = int((col / ss) * ss) for i in range(0, ss): for j in range(0, ss): if (curr_board.CurrentGameBoard[sRow+i][sCol+j] == 0 and ([sRow+i, sCol+j] not in neighbors) and [sRow+i, sCol+j] != [row, col]): neighbors.append([sRow+i, sCol+j]) return neighbors def backtrack(curr_board, check, forward_checking = False, MRV = False, MCV = False, LCV = False): # if the board is complete return the current board if is_complete(curr_board): print ("Completed in " + str(check) + " consistency checks") curr_board.print_board() return curr_board else: my_count = check newBoard = copy.deepcopy(curr_board) if forward_checking == False: for row in range(0, curr_board.BoardSize): for col in range(0, curr_board.BoardSize): curValue = newBoard.CurrentGameBoard[row][col] # check if value at row,col is unassigned if curValue == 0: # iterate through all possible values, whether valid or not for digit in range(1, (curr_board.BoardSize + 1)): my_count = my_count + 1 # check to make sure value is non-conflicting before assigning if (validRowCol(newBoard, row, col, digit) and validBox(newBoard, row, col, digit)): newBoard.CurrentGameBoard[row][col] = digit nextBoard = backtrack(newBoard, my_count, False, False, False, False) # if nextBoard returns anything but None, it means solution is found if nextBoard != None: return nextBoard # Return None after iterating through all digits for a square return None ########################### ## Forward Checking ## ########################### elif [forward_checking, MRV, MCV, LCV] == [True, False, False, False]: for row in range(0, curr_board.BoardSize): for col in range(0, curr_board.BoardSize): curValue = newBoard.CurrentGameBoard[row][col] if curValue == 0: # builds array of potential valid values potentials = potentialVals(newBoard, row, col) for digit in potentials: my_count = my_count + 1 newBoard.CurrentGameBoard[row][col] = digit nextBoard = backtrack(newBoard, my_count, True, False, False, False) # if nextBoard returns anything but None, it means solution is found if nextBoard != None: return nextBoard return None ########################## ## MRV ## ########################## elif [forward_checking, MRV, MCV, LCV] == [True, True, False, False]: choice = [-1,-1,curr_board.BoardSize,[]] for row in range(0, curr_board.BoardSize): for col in range(0, curr_board.BoardSize): curValue = newBoard.CurrentGameBoard[row][col] if curValue == 0: # builds array of potential valid values potentials = potentialVals(newBoard, row, col) # if less than current minimum of remaining values, reassign if len(potentials) < choice[2]: choice[0] = row choice[1] = col choice[2] = len(potentials) choice[3] = potentials # choice[3] holds potential values of square with MRV for digit in choice[3]: my_count = my_count + 1 newBoard.CurrentGameBoard[choice[0]][choice[1]] = digit nextBoard = backtrack(newBoard, my_count, True, True, False, False) # if nextBoard returns anything but None, it means solution is found if nextBoard != None: return nextBoard return None #################### ## MCV ## #################### elif [forward_checking, MRV, MCV, LCV] == [True, False, True, False]: choice = [-1,-1,0] for row in range(0, curr_board.BoardSize): for col in range(0, curr_board.BoardSize): curValue = newBoard.CurrentGameBoard[row][col] if curValue == 0: affected = getEmptyNeighbors(newBoard, row, col) # if greater than current maximum of MCV, reassign if len(affected) >= choice[2]: choice[0] = row choice[1] = col choice[2] = len(affected) # choice[3] holds potential values of square with MCV for digit in potentialVals(newBoard, choice[0], choice[1]): my_count = my_count + 1 newBoard.CurrentGameBoard[choice[0]][choice[1]] = digit nextBoard = backtrack(newBoard, my_count, True, False, True, False) # if nextBoard returns anything but None, it means solution is found if nextBoard != None: return nextBoard return None ###################### ## LCV + MRV ## ###################### elif [forward_checking, MRV, MCV, LCV] == [True, True, False, True]: choice = [-1,-1,curr_board.BoardSize,[]] for row in range(0, curr_board.BoardSize): for col in range(0, curr_board.BoardSize): curValue = newBoard.CurrentGameBoard[row][col] if curValue == 0: potentials = potentialVals(newBoard, row, col) # if less than current minimum of remaining values, reassign if len(potentials) < choice[2]: choice[0] = row choice[1] = col choice[2] = len(potentials) choice[3] = potentials # builds list of neighbors affected = getEmptyNeighbors(newBoard, choice[0], choice[1]) count = len(affected) chosenVal = -1 priority = list() # choice[3] holds potential values of square with MRV for digit in choice[3]: # counter to measure how many neighbors share this digit as a potential value tempCount = 0 for neighbor in affected: if digit in potentialVals(newBoard, neighbor[0], neighbor[1]): tempCount += 1 priority.append([digit, tempCount]) # sorts list in ascending order based on number of neighbors that have # a given value in its potential values priority = sorted(priority, key=lambda thing: thing[1]) for element in priority: my_count = my_count + 1 newBoard.CurrentGameBoard[choice[0]][choice[1]] = element[0] nextBoard = backtrack(newBoard, my_count, True, True, False, True) # if nextBoard returns anything but None, it means solution is found if nextBoard != None: return nextBoard return None ###################### ## LCV ## ###################### elif [forward_checking, MRV, MCV, LCV] == [True, False, False, True]: for row in range(0, curr_board.BoardSize): for col in range(0, curr_board.BoardSize): curValue = newBoard.CurrentGameBoard[row][col] if curValue == 0: ##### new below potentials = potentialVals(newBoard, row, col) # builds list of neighbors affected = getEmptyNeighbors(newBoard, row, col) count = len(affected) chosenVal = -1 priority = list() for digit in potentials: # counter to measure how many neighbors share this digit as a potential value tempCount = 0 for neighbor in affected: if digit in potentialVals(newBoard, neighbor[0], neighbor[1]): tempCount += 1 priority.append([digit, tempCount]) # sorts list in ascending order based on number of neighbors that have # a given value in its potential values priority = sorted(priority, key=lambda thing: thing[1]) for element in priority: my_count = my_count + 1 newBoard.CurrentGameBoard[row][col] = element[0] nextBoard = backtrack(newBoard, my_count, True, True, False, True) # if nextBoard returns anything but None, it means solution is found if nextBoard != None: return nextBoard return None
myNumber = 42 if myNumber == 42: print("Matched") else: print("Not a match") myNumber = 412 if myNumber > 42: print(" The number " + str(myNumber) + " is greater than 42") else: print(" The number " + str(myNumber) + " is less than or equal 42") myValue = 23 if myValue > 20 and myValue != 33: print("The number is above 20 and it is not 33.") print("", end="")
for num in range(1, 25): print("") print(str(num) + ": ", end="") if num % 3 == 0: print("Fizz", end="") if num % 5 == 0: print("Buzz", end="")
a = 1 b = "A" print(str(a)+b) a = "a" b = "x" print(a+b) a = 8 b = 9 print(str(a) + str(b)) a = "8" b = "9" print(int(a)+int(b))
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs city = input('Would you like to see data from chicago, new york city or washington?\n').lower() while city not in ('chicago', 'new york city', 'washington'): print('Please key in a correct city name') # TO DO: get user input for month (all, january, february, ... , june) month = input('Which month would you like to see data from?\nPlease choose from january, february, march, april, may, june or all.\n').lower() while month not in('january', 'february', 'march', 'april', 'may', 'june', 'all'): print('Please key in a correct month name\n') month = input('Which month would you like to see data from?\nPlease choose from january, february, march, april, may, june or all.\n').lower() # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'all'] day = input('\nSelect the day of the week you want to filter the bikeshare data by. \n Choose from the list: (sunday, monday, tuesday, wednesday, thursday, friday, saturday, all): ').lower() while True: if day in days: print('\nWe are working with {} data\n'.format(day.upper())) break else: print('\nPlease choose a valid day of the week from the list (sunday, monday, tuesday, wednesday, thursday, friday, saturday, all)\n').lower() break print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # load data file into a dataframe data_file = CITY_DATA[city] df = pd.read_csv(data_file) # Convert 'Start Time' column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # extract month and day of week from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday # filter by month if applicable if month != 'all': # use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe df[df['day_of_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() df['Start Time'] = pd.to_datetime(df['Start Time']) # display the most common month df['month'] = df['Start Time'].dt.month common_month = df['month'].mode()[0] print('The most common month is:', common_month) # display the most common day of week df['day'] = df['Start Time'].dt.day common_day = df['day'].mode()[0] print('The most common day of the week is:', common_day) # display the most common start hour df['hour'] = df['Start Time'].dt.hour common_hour = df['hour'].mode()[0] print('The most common start hour is:', common_hour) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # display most commonly used start station start_station = df['Start Station'].mode()[0] print('Most commonly used start station is:', start_station) # display most commonly used end station end_station = df['End Station'].mode()[0] print('Most commonly used end station is:', end_station) # display most frequent combination of start station and end station trip df['Start_End'] = df['Start Station'] + ' ' 'to' ' ' + df['End Station'] frequent_combination = df['Start_End'].mode()[0] print('Most frequent start and end station is:', frequent_combination) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time trip_duration =df['Trip Duration'].sum() print('The total travel time is:', trip_duration) # display mean travel time mean_travel = df['Trip Duration'].mean() print('The mean of the travel time is:', mean_travel) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() try: # Display counts of user types count_usertypes = df['User Type'].value_counts() print('Count of user types is:\n', count_usertypes) # Display counts of gender count_gender= df['Gender'].value_counts() print('Count of gender is:\n', count_gender) # Display earliest, most recent, and most common year of birth earliest = df['Birth Year'].min() most_recent= df['Birth Year'].max() most_common= df['Birth Year'].mode()[0] print('The earliest birth day is:', earliest) print('The most recent birth day is:', most_recent) print('The most common birth year is:', most_common) except: print('the data for washington is not available.') print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def raw_data(df): """Displays 5 lines of raw data""" i = 0 while True: answer = input('\nWould you like to see 5 lines of raw data? Enter yes or no:\n').lower() if answer =='yes': print(df.iloc[i:i+5]) i += 5 else: break def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) raw_data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
# Open Sublime text editor, create a new Python file, copy the following code in it and save it as 'census_main.py'. # Import modules import streamlit as st st.set_page_config(page_title = "Census Visualisation Web App",page_icon = "💥",layout = "centered", initial_sidebar_state = "auto") import numpy as np import pandas as pd @st.cache() def load_data(): # Load the Adult Income dataset into DataFrame. df = pd.read_csv('https://student-datasets-bucket.s3.ap-south-1.amazonaws.com/whitehat-ds-datasets/adult.csv', header=None) df.head() # Rename the column names in the DataFrame using the list given above. # Create the list column_name =['age', 'workclass', 'fnlwgt', 'education', 'education-years', 'marital-status', 'occupation', 'relationship', 'race','gender','capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income'] # Rename the columns using 'rename()' for i in range(df.shape[1]): df.rename(columns={i:column_name[i]},inplace=True) # Print the first five rows of the DataFrame df.head() # Replace the invalid values ' ?' with 'np.nan'. df['native-country'] = df['native-country'].replace(' ?',np.nan) df['workclass'] = df['workclass'].replace(' ?',np.nan) df['occupation'] = df['occupation'].replace(' ?',np.nan) # Delete the rows with invalid values and the column not required # Delete the rows with the 'dropna()' function df.dropna(inplace=True) # Delete the column with the 'drop()' function df.drop(columns='fnlwgt',axis=1,inplace=True) return df census_df = load_data() import streamlit as st # Set the title to the home page contents. st.title("Census Visualisation Web App") # Provide a brief description for the web app. st.write("This web app allows a user to explore and visualise the census data.") # Create the Page Navigator for 'Home' and 'Visualise Data' web pages in 'census_main.py' # Import 'census_home.py' and 'census_plots.py' . import census_home import census_plots import streamlit as st # Adding a navigation in the sidebar using radio buttons # Create a dictionary. pages_dict = { "Home:":census_home, "Visualise Data:":census_plots } # Add radio buttons in the sidebar for navigation and call the respective pages based on user selection. st.sidebar.title('Navigation') user_choice = st.sidebar.radio("Go to", tuple(pages_dict.keys())) if user_choice == "Home": home.app() else: selected_page = pages_dict[user_choice] selected_page.app(census_df)
class Solution: def climbStairs(self, n: int) -> int: if n==1 or n==0: return 1 list = [1, 1] for i in range(n-1): list[0], list[1] = list[1], list[0]+list[1] return list[1]
class Puzzle: curr = [] width = 3 height = 3 def __init__(self, state): self.first_state = state self.curr = state def move_zero(self, direction): i = [x for x in self.curr if 0 in x][0] row = self.curr.index(i) col = i.index(0) if direction == Dir.DOWN: if row + 1 < self.height: self.curr[row][col] = self.curr[row + 1][col] self.curr[row + 1][col] = 0 return 1 if direction == Dir.UP: if row - 1 >= 0: self.curr[row][col] = self.curr[row - 1][col] self.curr[row - 1][col] = 0 return 1 if direction == Dir.RIGHT: if col + 1 < self.width: self.curr[row][col] = self.curr[row][col+ 1] self.curr[row][col+ 1] = 0 return 1 if direction == Dir.LEFT: if col - 1 >= 0: self.curr[row][col] = self.curr[row][col - 1] self.curr[row][col - 1] = 0 return 1 return 0 def get_index(puzzle, num): for r_index, r in enumerate(puzzle): print(r, r_index) for c_i, c in enumerate(r): if puzzle[r_index][c_i] == num: return(r_index, c_i) def manh_distance(current, goal): for n in range(1, 9): print(n) row, col = get_index(current, n) print(n, row, col) p1 = Puzzle([[1, 2, 3], [0, 5, 6], [7, 8, 4]]) p2 = Puzzle([[1, 2, 3], [4, 5, 6], [7, 8, 0]]) manh_distance(p1.curr, p2.curr) # n1 = Node(p1) # n1.describe() # for dir in [Dir.RIGHT, Dir.LEFT, Dir.UP, Dir.DOWN]: # n1.puzzle.move_zero(dir) # n1.describe() # print(p1.is_solution()) # a = [[1, 2, 0], [4, 0, 6], [7, 8, 0]] # x = [x for x in a if 0 in x][0] # print(a.index(x), x.index(0)) # print(p1.index())
#!/usr/bin/env python PKG = 'numpy' import numpy as np import numpy.matlib as npm import numpy.linalg as npl import matplotlib.pyplot as plt def get_anchor_pos(anchors): anchor_pos = np.zeros((2, np.size(anchors))) for i in range(0, np.size(anchors)): if anchors[i].get_pos() is not None: anchor_pos[:, i] = anchors[i].get_pos() else: print 'Anchor %s has no position set' % i return np.array([1337, 1337]) return anchor_pos def locate_robot(anchors, robot_anchor_dist, max_tol, plot): """ :param anchors: A list oftThe instances of the Anchor class used :param robot_anchor_dist: matrix containing the distance between each robot and each node. element i,j in this matrix represent the distance between node i and robot j. :param max_tol: A list of maximum average residual in position as well as maximum average difference between last residual in position and current residual that the user is satisfied with. :param plot: True if you want to see the distance to each anchor as well as the calculated position :return: Matrix containing x and y coordinates of the robots """ anchors_pos = get_anchor_pos(anchors) for i in range(0, np.size(anchors_pos, axis=1)): if anchors_pos[0, i] == 1337: return anchors_pos # creates a column vector of node's x-pos anchor_pos_x = np.array([anchors_pos[0, :]]).T # creates a column vector of node's y-pos anchor_pos_y = np.array([anchors_pos[1, :]]).T # creates a starting point ([x0;y0]) for the steepest descent to work # with for all positions robot_pos = np.concatenate([npm.repmat(np.mean(anchor_pos_x), 1, np.size(robot_anchor_dist[0, :])), npm.repmat(np.mean(anchor_pos_y), 1, np.size(robot_anchor_dist[0, :]))]) # residual from least square method residual = npm.repmat(np.array([100]), 1, np.size(robot_anchor_dist[0, :])) # residual from least square method last_residual = npm.repmat(np.array([0]), 1, np.size(robot_anchor_dist[0, :])) while (np.abs(npl.norm(residual)-npl.norm(last_residual)) > (max_tol[1] * len(residual))): last_residual = residual """ update the calculated robot position from last iteration and make matrix out of it this is because we can solve the position from all of the nodes at the same time. Element i,j in this matrix represents robot j's (new) position after it have moved in a radial distance to decrease the error in the calculated distance to the node and the the measured distance to the node. These things will be done later in the code. """ robot_x = npm.repmat(robot_pos[0, :], np.size(anchors_pos[0, :]), 1) robot_y = npm.repmat(robot_pos[1, :], np.size(anchors_pos[0, :]), 1) """ Calculate new distance between nodes and robots. The distance is between each of the nodes to each of the robots. element i,j in this matrix represent the distance between node i to robot j. """ robot_anchor_dist_calc = np.sqrt((robot_x - anchor_pos_x)**2 + (robot_y - anchor_pos_y)**2) # difference in distance between current robot position to node and # measured robot position to node. dist_error = robot_anchor_dist - robot_anchor_dist_calc # row vector of residuals for each position residual = npl.norm(dist_error, axis=0) if npl.norm(residual) > (max_tol[0] * len(residual)): """ move the robot half the difference in calculated distance to the node and the measured distance to the node in the positive or negative radial direction depending on if the calculated distance is closer or farther away than the measured distance. """ move_x = (robot_x-anchor_pos_x)/robot_anchor_dist_calc *\ dist_error.astype(float) / 2 move_y = (robot_y-anchor_pos_y)/robot_anchor_dist_calc *\ dist_error.astype(float) / 2 """ Sum the calculated steps for each robot with respect to each node. This will produce a movement is the direction of the gradient. """ robot_pos[0, :] = robot_pos[0, :] + move_x.sum(axis=0) robot_pos[1, :] = robot_pos[1, :] + move_y.sum(axis=0) else: break if plot: v = np.linspace(0, 2 * np.pi, 100) for i in range(0, np.size(anchors)): if anchors[i].get_pos() is not None: x = anchors[i].get_pos()[0] +\ robot_anchor_dist[i, 0]*np.cos(v) y = anchors[i].get_pos()[1] +\ robot_anchor_dist[i, 0]*np.sin(v) plt.plot(x, y) else: print 'Anchor %s has no position set' % i return for i in range(0, np.size(robot_pos, axis=1)): plt.plot(robot_pos) return robot_pos
#Sreeti Ravi #11/8/2020 #Question 1 #Reading data file and drawing two histograms import matplotlib.pyplot as plt import pandas as pd def main(): #read Excel file with heights_weights into pandas dataframe xls_file = pd.ExcelFile("heights_weights.xlsx") #parse through the file file = xls_file.parse("Sheet1") #histogram for heights fig1 = plt.figure() sp1 = fig1.add_subplot(1, 1, 1) sp1.set_title("Histogram of heights") sp1.set_xlabel("Heights") sp1.set_ylabel("Number of students") sp1.hist(file["Height"], bins=16, color = "blue", edgecolor="black", \ linewidth=1.2, alpha = 0.5) #histogram for weights fig2 = plt.figure() sp2 = fig2.add_subplot(1, 1, 1) sp2.set_title("Histogram of weights") sp2.set_xlabel("Weights") sp2.set_ylabel("Number of students") sp2.hist(file["Height"], bins=16, color = "red", edgecolor="black", \ linewidth = 1.2, alpha = 0.5) main()
# -*- coding: utf-8 -*- """ Created on Fri Sep 18 23:52:10 2020 @author: sreet """ #Exercise 4.1 #Write a program that inputs an integer n from the user and prints n lines, #such that there are i stars in line i = 1, 2, ... n . # def main(): # print("The program prints a triangle of stars with n lines.") # n = int(input("Enter an integer n: ")) # for i in range(n+1): # print(i * "*") # main() #Exercise 4.2 #Write a program that takes integers from the user and prints the horizontal #histogram (with the stars) of the input numbers # def main(): # print("The program prints a histogram of input numbers.") # in_line = input("Please input numbers and hit Enter: ") # in_list = in_line.split() # print() # for i in in_list: # print(int(i) * "*") # main() #Exercise 4.3 #The letter grade in a course is determined on the scale 90-100 points: A, #80-89: B, 70-79: C, 60-69: D, <60: F. Write a program with no conditional #statements, that accepts a score in points and prints out the corresponding #letter grade # def main(): # print("The program prints a letter grade.") # score = int(input("Please input a score between 0 and 100: ")) # letter_grade = 60*"F" + 10*"D" + 10*"C" + 10*"B" + 10*"A" # print("The letter grade is", letter_grade[score]) # main() #Exercise 4.4 #Write a program that allows the user to type in a phrase and then outputs #the acronym for that phase. The acronym should be all uppercase, even if the #words in the phrase are not capitalized # def main(): # print("The program prints an acronym for an input phase.") # phrase = input("Please input a phrase: ") # words = phrase.split() # acronym = "" # for letter in words: # acronym = acronym + letter[0] # print("The acronym is", acronym.upper()) # main() #Exercise 4.5 #Write a program that calcualtes the average word length in a sentence entered #by the user. # def main(): # print("The program calculates the average word length.") # sentence = input("Please input as sentence: ") # words = sentence.split() # c = 0 # for letter in words: # c = c + len(letter) # average = c/len(words) # print("The average word length is", average) # main() #Exercise 4.6 #Write a program that prints the largest number from the numbers entered by #the user # def main(): # print("The program finds the largest number.") # numbers = input("Please enter the numbers: ") # number_list = numbers.split() # largest = eval(number_list[0]) # for number in number_list: # if eval(number) > largest: # largest = eval(number) # print("The largest number is", largest) # main() #Exercise 4.7 #Write a Python program that prompts the user to enter a sequence of strings. #Use counter pattern to find the number of strings where first and last character #are same from a given sequence of strings # def main(): # print("The program counts the strings with the same first and last character.") # strings = input("Please enter a sequence of strings: ") # string_list = strings.split() # count = 0 # for string in string_list: # if string[0] == string[-1]: # count = count + 1 # print ("There are", count, "strings where the first and last characters are same.") # main() #EXercise 4.8 #Write a Python program that prompts the user to enter a sequence of strings #and then prints all strings that are longer than 5 characters # def main(): # print("The program prints the strings that are longer than 5 characters.") # strings = input("Please enter a sequence of strings: ") # strings_list = strings.split() # print() # print("The strings that are longer than 5 characters: ") # for string in strings_list: # if len(string) > 5: # print(string) # main()
# -*- coding: utf-8 -*- """ Created on Thu Sep 3 00:34:26 2020 @author: sreet """ #Sreeti Ravi #9-3-2020 #Question 2 #Write a program that prompts the user for the mileage of a vehicle, calculates #and prints the fuel consumption of the vehicle in liters per 100 km. Assume #that 1 mile is 1.6 km and 1 gallon is 3.785 liters. def main(): print("The program converts mileage to liters per 100 km.") miles = eval(input("Please enter mileage (miles per gallon): ")) liters = (3.785 * 100)/(miles * 1.6) print("\nVehicle economy is", miles, "miles per gallon.") print("Vehicle consumption is", liters, "liters per 100 km.") main()
# -*- coding: utf-8 -*- """ Created on Sat Sep 19 15:31:40 2020 @author: sreet """ #Sreeti Ravi #9/19/2020 #Question 2 #Write a program that takes a positive integer number from the user and prints #the number in words def main(): print("The program spells the input number.") number = input("Please input a number: ") numbers = ["one","two","three","four","five","six","seven","eight", "nine", "zero"] words = "" for i in number: words += (numbers[int(i) - 1] + " ") print("The number in words: ", words) main()
# -*- coding: utf-8 -*- """ Created on Sat Oct 10 01:12:55 2020 @author: sreet """ #Sreeti Ravi #10/10/2020 #Question 3 #Program prints prime numbers in a range def is_prime(number): #returns True if number is a prime number and otherwise False if number > 1: for i in range(2, number): if (number % i) == 0: return False else: return True else: return False def display_primes(lower_bound, upper_bound): #prints all prime numbesr between lower_bound and upper_bound for i in range(lower_bound, (upper_bound + 1)): if(is_prime(i)): print(i) def main(): print("The program prints prime numbers in a range.") #prompts user for lower_bound integer lower_bound = input("Enter the lower limit of a range: ") #Exception handling to catch non-integer, print error message and quit try: lower_bound = int(lower_bound) except ValueError: print("Error! You entered a non-integer.") return if lower_bound < 1: print("Invalid input: Lower limit should be a positive integer, greater than 1.") return #prompts user for upper_bound integer upper_bound = input("Enter the upper limit of the range: ") #Exception handling to catch non-integer, print error message and quit try: upper_bound = int(upper_bound) except ValueError: print("Error! You entered a non-integer.") return #prints error message and quits in case lower_bound > upper_bound if upper_bound < lower_bound: print("Invalid input: Upper limit is less than lower limit.") return print("The sequence of prime numbers in the given interval: ") #calls display_primes(lower_bound, upper_bound) to print prime numbers in the interval display_primes(lower_bound,upper_bound) main()
# -*- coding: utf-8 -*- """ Created on Sat Oct 17 17:11:10 2020 @author: sreet """ #Sreeti Ravi #10/17/2020 #Question 3 #Write a program that creates a window with a circle that bounces from the #window walls. #I used code from Exercise 8.7 from this question from graphics import * #delay def delay(m): for i in range(m): for i in range(10000): pass def main(): #create a window win = GraphWin("", 500, 300) r = 20 #draw a circle p1 = Point(250, 150) circ = Circle(p1, r) circ.setFill('yellow') circ.draw(win) dx = 1 dy = 1 while True: #move circle by dx and dy circ.move(dx, dy) #delay delay(50) p = circ.getCenter() #if circle hits a vertical wall set change x direction if ((p.getX() - r) <= 0) or ((p.getX() + r) >= 500 ): dx = -dx #if circle hits a horizontal wall change y direction if ((p.getY() - r) <= 0) or ((p.getY() + r) >= 300): dy = -dy #break if the user terminates the program key = win.checkKey() if key == "q": break #close the window win.close() main()
# -*- coding: utf-8 -*- """ Created on Sat Oct 31 22:05:08 2020 @author: sreet """ #Sreeti Ravi #10/31/2020 #Question 4 #Finds the maximum period in which the close value of the stock was up each day from pandas_datareader import data as web def max_up(stock): #initializing variables days_up = 0 max_period = 0 start_period = 0 #finding the longest period for i in range(1, len(stock)): if stock["Close"][i] > stock["Close"][i-1]: days_up += 1 else: if days_up > max_period: max_period = days_up start_period = i - max_period days_up = 0 return start_period, days_up, max_period def main(): #prompt the user for the stock symbol stock_symbol = input("Symbol: ") #download stock data for 2020 into a DataFrame df = web.DataReader(stock_symbol, "yahoo", '1/1/2020', '10/23/2020') #call function max_up(stock) start_period, days_up, max_period = max_up(df) #number of days print("Days:", max_period) start_date = df["Close"].index[start_period] print("\nStart:", start_date.date()) start_value = df["Close"][start_date] print("Close:", round(start_value, 2)) end_date = df["Close"].index[start_period + max_period - 1] print("\nEnd:", end_date.date()) end_value = df["Close"][end_date] print("Close:", round(end_value, 2)) main()
import pandas as pd import matplotlib.pyplot as plt import pylab #making a boxplot with data from Human Biology 2 Course #importing data from a csv file data = pd.read_csv('/Users/lidiaerrico/Downloads/exercise.csv') r_ow = data['R_0_W'] #imputting x and y values and giving a title and axis labels fig7, ax7 = plt.subplots() ax7.set_title('Resting respiratory exchange ratio of athletic individuals and Level-2 student.') ax7.boxplot(r_ow, labels= ['R(0W)']) ax7.plot(1,0.92, marker= 'o', color= 'red') ax7.set_ylabel("Respiratory Exchange Ratio") plt.figtext(.109, .04,'Figure 1. Boxplot showing the respiratory exchange ratio, at rest, of level-2 student compared to athletic individuals. R value is a ratio of carbon dioxide production (VCO2)\n to oxygen uptake (VO2).The individual is a male, level-2 Human Biology student who volunteered to exercise. The red points represent the values of the student') plt.show()
#! /usr/bin/env python import sys text = open(sys.argv[1]).read() import re matches = re.compile("throughput=\s+(\d+[.]\d+)").findall(text) sum = 0 for m in matches: sum += float(m) avg = sum / len(matches) print avg
# -*- coding: utf-8 -*- #!/usr/bin/env python3 # Para los calculos import numpy as np import math import scipy # http://scipy.org/ from scipy import constants def dButoV(dBu): v = 10**(dBu/20) print('\nV = {:.2f} uV\n\n'.format(v)) while 1: dBu = float(input("Enter dBu: ")) dButoV(dBu) pass
# -*- coding: utf-8 -*- """ Created on Fri Nov 15 18:21:00 2019 @author: CEC """ #import math #x=float(input("Ingrese x: ")) #y=math.sqrt(x) #print("Resultado raiz cuadrada de x: ", y) try: print("1") x=1/0 print("2") except: print("Oh rayos! esta mal!!") print("3")
# -*- coding: utf-8 -*- """ Created on Fri Oct 25 20:25:40 2019 @author: CEC """ def es_primo(numero): for i in range(2,numero): if (numero%i)==0: return False return True numero = int(input("inserta un numero: ")) if numero==0 or numero==1: print ("\nEl numero NO es primo") elif es_primo(numero): print ("\nEl numero es primo") for bi in range(1, numero): if es_primo(bi + 1): print(bi + 1, end=" ") print() else: print ("\nEl numero NO es primo") for bi in range(1, numero): if es_primo(bi + 1): print(bi + 1, end=" ") print()
i = 1 a = raw_input("Please enter an number greater than 2:") while not a.isdigit() or not float(a) > 2: a = raw_input("Please enter an number greater than 2:") while float(a) > 2 : print i, ':' , '%.3f' %float(a)**0.5 i += 1 a = float(a)**0.5 if a < 2 : break
import sqlite3 import json from sqlite3 import Error #crear la conexion def sql_connection(): try: con = sqlite3.connect('SQLite/test.sqlite3') return con except Error: print(Error) #codigo crear tabla def sql_table(con): cursorObj = con.cursor() cursorObj.execute("CREATE TABLE IF NOT EXISTS empleado( id integer primary key, nombre VARCHAR(50), edad INTEGER, sueldo FLOAT)") cursorObj.execute("CREATE TABLE IF NOT EXISTS departamento( id integer primary key,nombre VARCHAR(50), presupuesto FLOAT,id_jefe INTEGER, foreign key(id_jefe) references empleado(id))") cursorObj.execute("CREATE TABLE IF NOT EXISTS trabajo_en( id_empleado INTEGER,id_dpto INTEGER,porcentaje_tiempo INTEGER,foreign key(id_empleado) references empleado(id),foreign key(id_dpto) references departamento(id))") con.commit() #codigo agregar tabla def sql_insert(con,dato1,dato2,dato3,dato4,tipo): cursorObj = con.cursor() if(tipo==1): cursorObj.execute("INSERT INTO empleado (id,nombre,edad,sueldo) VALUES( ?,?,?,?)",(dato1,dato2,dato3,dato4)) if(tipo==2): cursorObj.execute("INSERT INTO departamento (id,nombre,presupuesto,id_jefe) VALUES( ?,?,?,?)",(dato1,dato2,dato3,dato4)) if(tipo==3): cursorObj.execute("INSERT INTO trabajo_en (id_empleado,id_dpto,porcentaje_tiempo) VALUES( ?,?,?)",(dato1,dato2,dato3)) con.commit() #creao tabla con = sql_connection() sql_table(con) #cargo datos f = open("empleados.txt", "r") while(True): linea = f.readline() palabras=linea.split(",") listaE=[] for palabra in palabras: listaE.append(palabra) if(listaE[0]!=''): sql_insert(con,int(float(listaE[0])),listaE[1],int(float(listaE[2])),float(listaE[3]),1) if not linea: break f.close() f = open("trabaja_en.txt", "r") while(True): linea = f.readline() palabras=linea.split(",") listaT=[] for palabra in palabras: listaT.append(palabra) if(listaT[0]!=''): sql_insert(con,int(float(listaT[0])),int(float(listaT[1])),int(float(listaT[2])),0,3) if not linea: break f.close() f = open("departamento.txt", "r") while(True): linea = f.readline() palabras=linea.split(",") listaD=[] for palabra in palabras: listaD.append(palabra) if(listaD[0]!=''): sql_insert(con,int(float(listaD[0])),listaD[1],float(listaD[2]),int(float(listaD[3])),2) if not linea: break f.close() #cierro connect con.close
name = 'Mandy' yourName = input('What is your name?\n') while len(yourName): if yourName == name: print('Hello, Mandy!') else: print('I do not know you.') yourName = input('What is your name?\n')
n = input("input a postive integer: ") def function(n): if n == 0: return 0 elif n == 1: return 1 else: return (function(n-1)+ function(n-2)) x = function(n) print(x)
# Ссылка на схемы # https://drive.google.com/file/d/14vLKzw007Cj8Ld8VYsGee5cxRGMk5lHL/view?usp=sharing a, b, c = map(float, input("введите три разных числа через пробел: ").split()) if a > b: if b > c: print(f"Среднее число {b}") elif a > c: print(f"Среднее число {c}") else: print(f"Среднее число {a}") elif a > c: print(f"Среднее число {a}") elif b > c: print(f"Среднее число {c}") else: print(f"Среднее число {b}")
# Ссылка на схемы # https://drive.google.com/file/d/14vLKzw007Cj8Ld8VYsGee5cxRGMk5lHL/view?usp=sharing a, b = input("Введите две заглавные буквы английского алфавита, разделенные пробелом: ").split() a = ord(a) - ord('A') + 1 b = ord(b) - ord('A') + 1 c = abs(a - b) print(f"Это {a} и {b} буквы алфавита. Между ними {c} букв")
import random SIZE = 10 MIN_ITEM = -100 MAX_ITEM = 100 array = [random.randint(MIN_ITEM,MAX_ITEM) for _ in range(SIZE)] print(array) max_elem = MIN_ITEM max_index = SIZE + 1 i = 0 for el in array: if (el < 0) and (el >= max_elem): max_elem = el max_index = i i = i + 1 if max_index <= SIZE: print(f"Максимальный отрицательный элемент {max_elem} находится на позиции {max_index}") else: print("Отрицательные элементы отсутствуют")
""" 7. Find Armstrong Numbers in the given range. """ import math def is_armstrong(val): num = val n = int(math.log10(num)) + 1 sum = 0 for _ in range(n): digit = num % 10 sum += digit ** n num //= 10 if val == sum: return True else: return False n = int(input("Enter n: ")) for i in range(1, n + 1): if is_armstrong(i): print(i, end=", ")
""" 10. Find the first 10 numbers from geometric series """ a = float(input("Enter the first term of the Geometric Series: ")) r = float(input("Enter the Common Ratio of the Geometric Series: ")) print("First 10 numbers of Geometric Series are:") for i in range(10): print(a * (r ** i), end=", ")
# Radiactive Decay def f(x): import math return 10*math.e**(math.log(0.5)/5.27 * x) def radiationExposure(start, stop, step): ''' Computes and returns the amount of radiation exposed to between the start and stop times. Calls the function f (defined for you in the grading script) to obtain the value of the function at any point. start: integer, the time at which exposure begins stop: integer, the time at which exposure ends step: float, the width of each rectangle. You can assume that the step size will always partition the space evenly. returns: float, the amount of radiation exposed to between start and stop times. ''' block = int((stop-start)/step) area = 0 for i in range(0,block): area=area+f(start+i*step)*step return (area) # Hangman Game import random import string WORDLIST_FILENAME = "C:/Users/fduan/Documents/Python_training/Edx_python/words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def chooseWord(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = loadWords() def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' # FILL IN YOUR CODE HERE... Guess = '' for char in lettersGuessed: Guess+=char flag = len(Guess)!=0 for i in range(0,len(secretWord)): charInS = secretWord[i] in Guess flag = flag and charInS return flag def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' # FILL IN YOUR CODE HERE... ans='' Guess = '' for char in lettersGuessed: Guess+=char for i in range(0,len(secretWord)): if secretWord[i] in Guess: ans=ans+secretWord[i] else: ans=ans+'_ ' return ans def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. ''' # FILL IN YOUR CODE HERE... import string alpha = string.ascii_lowercase for char in lettersGuessed: alpha = alpha.replace(char,'') return alpha def hangman(secretWord): ''' secretWord: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secretWord contains. * Ask the user to supply one guess (i.e. letter) per round. * The user should receive feedback immediately after each guess about whether their guess appears in the computers word. * After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed. Follows the other limitations detailed in the problem write-up. ''' # FILL IN YOUR CODE HERE... print 'Welcome to the game, Hangman!' print 'I am thinking of a word that is ' + str(len(secretWord)) + ' letters long.' print '-------------' lettersGuessed = [] GuessCount = 8 while GuessCount > 0: print 'You have ' + str(GuessCount) + ' guesses left' print('Available letters: ' + getAvailableLetters(lettersGuessed)) guess = raw_input('Please guess a letter: ') guess = guess.lower() if guess in lettersGuessed: str_output = 'Oops! You\'ve already guessed that letter: ' elif guess in secretWord: lettersGuessed.append(guess) str_output = 'Good guess: ' else: GuessCount -=1 lettersGuessed.append(guess) str_output = 'Oops! That letter is not in my word: ' print str_output+getGuessedWord(secretWord, lettersGuessed) print '-------------' if isWordGuessed(secretWord, lettersGuessed) == True: print 'Congratulations you won' break if GuessCount == 0: print 'Sorry you ran out of guesses. The word was :' + secretWord break
number1 = int(input("Enter first number: ")) number2 = int(input("Enter second number: ")) result = number1 + number2 print("The result is %d. " % result)
def count_spaces(userInput): spaces = 0 for char in userInput : if char == " " : spaces = spaces + 1 return spaces def main(): userInput = input("Please, enter a sentence:") print (count_spaces(userInput)) main()
richter = float(input("What was the earthquake's magnitude?")) if richter >= 8.0: print("Most structures fall") elif richter >= 7.0: print("Many buildings destroyed") elif richter >= 6.0: print("Many buildings considerably damaged, some collapse") elif richter >= 4.5: print("Damage to poorly constructed buildings") else: print("No destruction of buildings")
x = int(input()) x = x*2 x = x*2 print(x) #0.052 / 31.05.2021 / 1
x = int(input()) ano = x // 365 x = x - ano*365 mes = x // 30 x = x - mes*30 dia = x print(f"{ano} ano(s)") print(f"{mes} mes(es)") print(f"{dia} dia(s)") #0.177 / 31.05.2021 / 4
Primeiro = int(input("informe o Primeiro do intervalo: ")) Ultimo = int(input("informe o ultimo do intervalo: ")) SOMA=0 while (primeiro < ultimo - 1): primeiro = primeiro+ 1 print(primeiro) soma = (Primeiro+SOMA) print("a soma dos intervalos intervalos é = {}".format(SOMA))
"""Testing module for Linked List clss.""" from linked_list import LinkedList import pytest @pytest.fixture def empty_list(): """Create empty LinkedList.""" return LinkedList() @pytest.fixture def filled_list(): """Create a populated LinkedList.""" x = LinkedList([12, 34, 2, 67, 43, 98, 76]) return x def test_instatiating_a_linked_list(): """Test that a linked list object can be created.""" x = LinkedList() assert isinstance(x, LinkedList) def test_instatiating_linked_list_with_iter(): """Test that Linked List can be created with an iterable.""" x = LinkedList([1, 2, 3, 4, 5, 6, 7]) assert isinstance(x, LinkedList) def test_length_method_works(empty_list): """Test that the length method works.""" assert len(empty_list) == 0 def test_length_method_works_after_adding_one_node(empty_list): """Test that length works after adding node to empty list.""" empty_list.add(9) assert len(empty_list) == 1 def test_length_works_after_multiple_adds(empty_list): """Test that length works after multiple nodes have been added.""" for x in range(20): empty_list.add(x) assert len(empty_list) == 20 def test_find_node_works_while_node_exist(filled_list): """Test that find_node method works.""" assert filled_list.find_node(67) def test_find_node_works_while_node_does_not_exist(filled_list): """Test that find_node method works.""" assert filled_list.find_node(999) is False def test_pop_method_works(filled_list): """Test that pop method removes a node.""" filled_list.pop() assert filled_list.find_node(7) is False def test_length_is_reduced_after_pop(filled_list): """Test that the length is changed after a pop.""" starting_length = len(filled_list) filled_list.pop() assert starting_length > len(filled_list) def test_append_adds_to_end_of_list(empty_list): """Test that an appended node goes to the end of the list.""" empty_list.add(1) empty_list.add(2) empty_list.append(99) assert empty_list.head.value != 99 assert empty_list.head._next._next.value == 99 def test_add_before_adds_in_the_right_place(filled_list): """Test that add_before places node before target value.""" assert filled_list.head._next.value == 98 filled_list.add_before(100, 98) assert filled_list.head._next.value == 100 def test_add_after_puts_node_in_the_right_position(filled_list): """Test that add_after puts the node after the target value node.""" starting_node_value = filled_list.head._next.value filled_list.add_after(100, 76) assert filled_list.head._next.value != starting_node_value assert filled_list.head._next.value == 100
import math class Interpreter(object): """Class to build the command string for the modem""" SEPARATOR = "," END_COMMAND = "\r\n" START_COMMAND = "" def __init__(self): """ Constructor, initialize the iterpreter. @param self pointer to the class object """ self.debug = 1 def setDebug(self,debug): """ Set the debug mode. @param self pointer to the class object @param debug is the debug mode. O-->OFF, 1-->ON """ self.debug = debug def s(self): """ Shortcut to return the separator. @param self pointer to the class object @return the separator """ return Interpreter.SEPARATOR def end(self): """ Shortcut to return the end command separator. @param self pointer to the class object @return the separator """ return Interpreter.END_COMMAND def start(self): """ Shortcut to return the start command separator. @param self pointer to the class object @return the separator """ return Interpreter.START_COMMAND def buildConfirm(self): """ Build the confirm message. @param self pointer to the class object @return the message """ msg = self.start() + "OK" + self.end() return msg def buildSendFile(self, name, size): """ Build the send_file message. @param self pointer to the class object @param name of the file @param size of the file in bytes @return the message """ msg = self.start() + "send_file" + self.s() + str(name) + self.s() + \ str(size) + self.end() if self.debug : print "Interpreter::buildSendFile: ", msg return msg def buildGetFile(self, name, delete = 1): """ Build the get_file message. @param self pointer to the class object @param name of the file required @param delete flag, if 1 erase it after sending, otherwise if 0 not @return the message """ msg = self.start() + "get_file" + self.s() + str(name)+ self.s() + \ str(delete) + self.end() if self.debug : print "Interpreter::buildGetFile: ", msg return msg def buildGetData(self, delete = 1): """ Build the get_data message: get whatever data has been recorded. @param self pointer to the class object @param delete flag, if 1 erase it after sending, if 0 not @return the message """ msg = self.start() + "get_data" + self.s() + str(delete) + self.end() if self.debug : print "Interpreter::buildGetData: " ,msg return msg def buildSetPower(self, ID_list, s_l): """ Build the set_power message. @param self pointer to the class object @param ID_list list of the projector IDs where to play the file @param s_l source level output power @return the message """ cum_id = self.getCumulativeID(ID_list) msg = self.start() + "set_power" + self.s() + str(cum_id) + self.s() + str(s_l) \ + self.end() if self.debug : print "Interpreter::buildSetPower: ", msg return msg def buildPlay(self, name, ID_list, starting_time, n_rip = 1, \ delete = 1, force_flag = 0): """ Build the play_audio message. @param self pointer to the class object @param name of the file that has to be played @param ID_list list of the projector IDs where to play the file @param starting_time Unix timestamp, in second, when to start playing the file @param n_rip number of time it has to be consecutively played @param delete flag, if 1 erase it after playing, if 0 not @param force_flag if trying to transmit while recording: 0 (default) not allowed (error feedback) 1 (force) stop recording and start transmitting 2 (both) do both the operations together @return the message """ cum_id = self.getCumulativeID(ID_list) msg = self.start() + "play_audio" + self.s() + str(name) + self.s() + str(cum_id) + \ self.s() + str(starting_time) +self.s() + str(n_rip) + self.s() + \ str(delete) + self.s() + str(force_flag) + self.end() if self.debug : print "Interpreter::buildPlay: ", msg return msg def buildRun(self, script_name, output_name, starting_time, duration): """ Build the run_script message. @param self pointer to the class object @param script_name of the file that has to be run @paran output_name where to redirect the output of the script @param starting_time Unix timestamp, in second, when to start playing the file @param duration in minutes of the script @return the message """ msg = self.start() + "run_script" + self.s() + str(script_name) + self.s() + \ str(output_name) + self.s() + str(starting_time) +self.s() + \ str(duration) + self.end() if self.debug : print "Interpreter::buildRun: ", msg return msg def buildRecordData(self, name, sens_t, ID_list, starting_time, duration, \ force_flag = 0): """ Build the record_data message. @param self pointer to the class object @param name of the file where to record the audio @param sens_t of the sensors that have to record the data: 1 --> hydrophone, 2 --> camera 3 --> others @param ID_list list of the sensors IDs used to record the audio @param starting_time Unix timestamp, in second, when to start recording the file @param duration duration, in minutes of the recording @param force_flag if trying to record while transmitting: 0 (default) not allowed (error feedback) 1 (force) stop transmitting and start recording 2 (both) do both the operations together @return the message """ cum_id = self.getCumulativeID(ID_list) msg = self.start() + "record_data" + self.s() + str(name) + self.s() + \ str(sens_t) + self.s() + str(cum_id) + self.s() + \ str(starting_time) + self.s() + str(duration) + self.s() + \ str(force_flag) + self.end() if self.debug : print "Interpreter::buildRecordData: ", msg return msg def buildGetRTData(self, sens_t, ID_list, starting_time, duration, chunck_duration, \ delete = 1, force_flag = 0): """ Build the get_rt_data message. @param self pointer to the class object @param ID_list list of the sensors IDs used to record the audio @param sens_t of the sensors that have to record the data: 1 --> hydrophone, 2 --> camera 3 --> others @param starting_time Unix timestamp, in second, when to start recording the file @param duration duration, in minutes of the recording @param chunck_duration chunk duration, in seconds @param delete flag, if 1 erase it after sending, otherwise if 0 not @param force_flag if trying to record while transmitting: 0 (default) not allowed (error feedback) 1 (force) stop transmitting and start recording 2 (both) do both the operations together @return the message """ cum_id = self.getCumulativeID(ID_list) msg = self.start() + "get_rt_data" + self.s() + str(sens_t) + self.s() + \ str(cum_id) + self.s() + str(starting_time) + self.s() + str(duration)+ \ self.s() + str(chunck_duration)+ self.s() + str(delete) + self.end() if self.debug : print "Interpreter::buildGetRTData: ", msg return msg def buildGetStatus(self): """ Build the get_status message. @param self pointer to the class object @return the message """ msg = self.start() + "get_status" + self.end() if self.debug : print "Interpreter::buildGetStatus: ", msg return msg def buildResetProj(self, ID_list, force_flag = 0): """ Build the reset_proj message. This message will reset the projectors @param self pointer to the class object @param ID_list list of the projector IDs that has to be resetted @param force_flag if 1 reset also if pending operations, if 0 not @return the message """ cum_id = self.getCumulativeID(ID_list) msg = self.start() + "reset_proj" + self.s() + str(cum_id) + self.s() + \ str(force_flag) + self.end() if self.debug : print "Interpreter::buildResetProj: ", msg return msg def buildResetSensor(self, sens_t, ID_list, force_flag = 0): """ Build the reset_sen message. This message will reset the sensors @param self pointer to the class object @param sens_t of the sensors that have to record the data: 1 --> hydrophone, 2 --> camera 3 --> others @param ID_list list of the projector IDs that has to be resetted @param force_flag if 1 reset also if pending operations, if 0 not @return the message """ cum_id = self.getCumulativeID(ID_list) msg = self.start() + "reset_sen" + self.s() + str(sens_t) + self.s() \ + str(cum_id) + self.s() + str(force_flag) + self.end() if self.debug : print "Interpreter::buildResetSensor: ", msg return msg def buildResetAll(self, force_flag = 0): """ Build the reset_all message. This message will reset the node @param self pointer to the class object @param force_flag if 1 reset also if pending operations, if 0 not @return the message """ msg = self.start() + "reset_all" + self.s() + str(force_flag) + self.end() if self.debug : print "Interpreter::buildResetAll: ", msg return msg def buildDeleteAllRec(self, sens_t): """ Build the delete_all_rec message. This message delete the recorded files at the node @param self pointer to the class object @param sens_t of the sensors that have to record the data: o --> all, 1 --> hydrophone, 2 --> camera 3 --> others @return the message """ msg = "delete_all_rec" + self.s() + str(sens_t) if self.debug : print "Interpreter::buildDeleteAllRec: ", msg return msg def buildDeleteAllSent(self): """ Build the delete_all_rec message. This message delete the files sent by the node @param self pointer to the class object @return the message """ msg = self.start() + "delete_all_sent" + self.end() if self.debug : print "Interpreter::buildDeleteAllSent: ", msg return msg def getCumulativeID(self,ID_list): """ From list of IDs to a global ID in binary rappresentation @param self pointer to the class object @return the cumulative id """ cum_id = 0 for id_i in ID_list: if id_i <= 0: raise ValueError("each ID must be > 0") cum_id += pow(2,id_i-1) return cum_id def getIDlist(self,cum_id): """ From list of IDs to a global ID in binary rappresentation @param self pointer to the class object @return the cumulative id """ ID_list = [] while (cum_id > 0): ID = int(math.log(cum_id,2)) cum_id -= pow(2,ID) ID_list.insert(0,ID+1) return ID_list
# -*- coding: utf-8 -*- # Algorithm function: # Write a function to find the longest common prefix string amongst an array of strings. # If there is no common prefix, return an empty string "". class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if strs == []: return '' for i in range(len(strs[0])): for str in strs: if len(str) <= i or str[i] != strs[0][i]: return strs[0][:i] #[:i]返回列表元素前i个长度 return strs[0] b = ["flower","flow","flight"] a = Solution().longestCommonPrefix(b) print(a) #说明: #1.算法功能: #["a","a","b"] 返回 "",因为三个字符串没有公共前缀; #["a","a"] 返回 "a" 因为它是两个字符串的公共前缀; #["abcd","abc"] 返回 "abc"; #["ac","ac","a","a"] 返回 "a" 。 #2.算法思路: # 从任意一个字符串开始,扫描该字符串,依次检查其他字符串的同一位置是否是一样的字符,当遇到不一样时则返回当前得到的前缀。 #3.代码说明: # if i >= len(str) or str[i] != strs[0][i]: # return strs[0][:i] #该条件好比一个故障检测器,当出现符合故障的条件时,机器停止运行,并返回停止前的最近一次结果。 #故障条件:当初始的字符串长度大于其他字符串长度时或初始的字符串的当前位置的字符与其他字符串同一个位置下的当前位置的字符不同时,
#!/user/bin/env python # Student: Duy Nguyen # Solution to question 1, homework 1 # # Read FASTA file # You should be able to run the program as of the folloing commands # python HW01_Code.py yeast_chrom.fasta chr01 20 30 + import sys import io import getopt def read_FASTA_sequence(file): "Read the sequence given the chromosome" seq = '' for line in file: if not line or line[0] == '>': return seq seq += line[:-1] return seq def get_id(line): "Get the chromosome number" return line.replace('>', '').replace('\n','') def FASTA_search_by_id(id, file): for line in file: if (line[0] == '>' and str(id) == get_id(line)): return read_FASTA_sequence(file) def search_FASTA_file_by_id(id, filename): "Search FASTA file and read only the seq with the corresponding chromosome" id = str(id) with open(filename) as file: return FASTA_search_by_id(id, file) def eval_Seq(seq, start, end, strand = '+'): res = '' if strand == '+': res = seq[(start-1):end] else: res = rcomplement(seq[(start-1):end]) return res def rcomplement(s): "Find the reverse complement of the sequence" basecomplement = {'A': 'T', 'C':'G', 'G':'C', 'T':'A'} letters = list(s) # find the complement letters = [basecomplement[base] for base in letters] return ''.join(letters)[::-1] def main(argv): try: opts, args = getopt.getopt(argv, "hg:d", ["help", "grammar="]) except getopt.GetoptError: usage() sys.exit(2) FileName = args[0] Chr = args[1] Start = int(args[2]) End = int(args[3]) Strand = args[4] ## Error Handlings if Chr[:3] != "chr": sys.exit('Chromosome argument is not in right format') if Start < 1: sys.exit('Start Position should be greater than 0') if not (Strand == '+' or Strand == '-'): sys.exit('Input of Strand must be +/-') id = Chr seq = search_FASTA_file_by_id(id, FileName) if End > len(seq): sys.exit('End Position exceeds chromosome length') seq_frag = eval_Seq(seq, start = Start, end = End, strand = Strand) print(seq_frag) if __name__ == '__main__': main(sys.argv[1:])
import sys number = int(sys.argv[1]) print(number) #Counting number of bits in a number def counting_bits(number): max_bit_value = 1 bits = 1 while max_bit_value < number: bits +=1 max_bit_value = (2 ** bits ) - 1 return bits bits_in_number = counting_bits(number) output = "There are {bits} bits in number {number}".format(number=number,bits=bits_in_number) print(output) def num_to_bin(number,bits): binary_value = "" while bits > 0: if number >= (2 ** (bits - 1)): binary_value += "1" bits -= 1 number -= 2**bits else: binary_value += "0" bits -= 1 return binary_value binary_value = num_to_bin(number, bits_in_number) print("binary value of {number} is {binary_value}".format(number=number,binary_value=binary_value))
def mensagem_boas_vindas(): print('\tSeja bem vindo ao fantástico mundo de Python!!') mensagem_boas_vindas2() def mensagem_boas_vindas2(): print('\tSeja bem vindo ao fantástico mundo de Python!!, NOVAMENTE...') def mensagem_custom(nome): mensagem = 'Olá {} seja bem vindo'.format(nome) return mensagem def add(a, b): return a + b # MAIN if __name__ == '__main__': print('Iniciando nosso código') mensagem_boas_vindas() print('Finalizando nosso código') print('Aqui deve aparecer o resultado da função custom: ') mensagem = mensagem_custom('Fabricio') print(mensagem) print('-' * 10) print(mensagem_custom('Miguel')) a = 10 b = 20 c = add(a, b) print('{} + {} = {}'.format(a, b, c))
import random randomlist1 = [] #two random lists, and one for storing overlapping numbers randomlist2 = [] random_overlap = [] for i in range(0,5): #creating two random list with 5 numbers in range 1-30 n = random.randint(1,30) randomlist1.append(n) m = random.randint(1,30) randomlist2.append(m) print(randomlist1, randomlist2) #it seems useful to see the randomly generated lists for x in randomlist1: #for every element of the first list it looks for the same element if x in randomlist2: #in the second list" random_overlap.append(x) #adds the overlaping element in the third list print(random_overlap)
#Nama : Efraim #NRP: 1572048 #_TB_C_1572048_Efraim #from __future__ import print_function <-- untuk mendapatkan variabel dari python 3 karena interpreter ini python 2 from __future__ import print_function #####Fungsi print matriks###### #Kamus lokal #i,j : var.counter(int) #Baris: wadah banyak baris(int) #Kolom: wadah banyak kolom(int) #Bil : wadah banyak angka di belakang koma(int) def Cetak_Hasil(Baris,Kolom,Arr,Bil): for i in range(0,Baris): for j in range(0,Kolom): print(round(Arr[i][j],Bil),end=' | ') print() print() return #####Fungsi utama program##### ##Kamus lokal## #i,j,k,h : var.counter(int) #Baris : wadah banyak baris(int) #Kolom : wadah banyak kolom(int) #Kolom_temp: wadah untuk identitas matriks(int) #Bil : wadah banyak angka di belakang koma(int) #Arr : var.matriks(float) #Stop_1 : var.cek baris(boolean) #Stop_2 : var.cek pivot(boolean) #Indeks : wadah sementara var.counter(int) #Temp_1,Bilangan,Temp_2: wadah sementara variabel(float) def main(): Mulai=raw_input("Mulai program[ya/tidak] : ") while (Mulai=="ya"): Baris=int(input("Baris : ")) Kolom=int(input("Kolom : ")) Kolom_temp=Kolom*2 Kolom=Kolom_temp Arr=[None]*Baris for i in range(0,Baris): Arr[i]=[None]*Kolom print("Masukan nilai") for i in range(0,Baris): print("Persamaan linier ke-"+str(i+1)) for j in range(0,Kolom): if(j<(Kolom/2)): Arr[i][j]=float(input("A["+str(i+1)+"]["+str(j+1)+"] : ")) else: if(i%2==0 and j==(Kolom/2)+i): Arr[i][j]=1 elif(i%2==1 and j==(Kolom/2)+i): Arr[i][j]=1 else: Arr[i][j]=0 Bil=int(input("Angka di belakang koma:")) print("") print("Matriks awal") Cetak_Hasil(Baris,Kolom,Arr,Bil) #Proses Eliminasi Gauss-Jordan Row echelon i=0 h=0 Stop_1=False while (i!=Baris and not Stop_1): while Arr[i][h]!=1 and not Stop_1: Stop_2=False while Arr[i][h]==0 and not Stop_2:#Jika pivot ==0 do looping Indeks=99 k=i while k!=Baris and Arr[k][h]==0:#Mencari pivot bukan nol k+=1 if k!=Baris and Arr[k][h]!=0:#Jika ketemu pivot bukan nol Indeks=k Stop_2=True else: if h+1!=Kolom:#Pindah kolom h+=1 else:#Hentikan looping Stop_1=True Stop_2=True if (not Stop_1 and Arr[i][h]==0):#Menukar bilangan print("tukar R["+str(i+1)+"] <-> R["+str(Indeks+1)+"]") for k in range(0,Kolom,1): Temp_1=Arr[i][k] Arr[i][k]=Arr[Indeks][k] Arr[Indeks][k]=Temp_1 Cetak_Hasil(Baris, Kolom, Arr, Bil) elif (not Stop_1 and Arr[i][h]!=1):#Membagi bilangan pivot Temp_1=Arr[i][h] print("R["+str(i+1)+"] -> R["+str(i+1)+"]*1/("+str(Temp_1)+")") for k in range(i,Kolom,1): Bilangan=Arr[i][k]*(1/Temp_1) Arr[i][k]=Bilangan Cetak_Hasil(Baris, Kolom, Arr, Bil) for j in range(i+1,Baris,1):#Nolkan bilangan bawah pivot Temp_1=Arr[j][h] for k in range(0,Kolom,1): Temp_2=Temp_1*Arr[i][k]*(-1) Arr[j][k]=Arr[j][k]+Temp_2 print("R["+str(i+2)+"] -> R["+str(i+2)+"]+("+str(Temp_1*-1)+")R["+str(i+1)+"]") Cetak_Hasil(Baris, Kolom, Arr, Bil) for j in range(i-1,-1,-1):#Nolkan bilangan atas pivot Temp_1=Arr[j][h] for k in range(i,Kolom,1): Temp_2=Temp_1*Arr[i][k]*(-1) Arr[j][k]=Arr[j][k]+Temp_2 print("R["+str(i)+"] -> R["+str(i)+"]+("+str(Temp_1*-1)+")R["+str(i+1)+"]") Cetak_Hasil(Baris, Kolom, Arr, Bil) i+=1 h+=1 print("Hasil akhir") Cetak_Hasil(Baris, Kolom, Arr, Bil) Mulai=raw_input("Mulai program[ya/tidak] : ") print("Program Selesai, Terima kasih!") if __name__=='__main__': main()
BASE_COLOR = (0, 0, 0) class ImageModel: """Representa una imagen a guardar Atributos --------- w - ancho de la imagen h - alto de la imagen _img - matriz de colores de la imagen""" _img = [] def __init__(self, w=640, h=480): self.create(w, h) def create(self, w, h): """Inicializa la imagen con el color base Parámetros ---------- w - ancho de la imagen h - alto de la imagen""" self.w = w self.h = h for row in range(0, h): rowList = [] for col in range(0, w): rowList.append(BASE_COLOR) self._img.append(rowList) def set_color(self, row, col, color): """Establece el color en un píxel de la imagen Parámetros ---------- row - fila del píxel col - columna del píxel color - color del píxel""" self._img[row][col] = color def get_color(self, row, col): """Devuelve el color de un pixel de la imagen Parámetros ---------- row - fila del píxel col - columna del píxel Devuelve -------- Color del píxel indicado""" return self._img[row][col] # Getters def get_image(self): return self._img def get_h(self): return self.h def get_w(self): return self.w
def isPhoneNumber(text): if len(text) != 12: return False for i in range(0, 3): if not text[i].isdecimal(): return False if text[3] != '-': return False for i in range(4,7): if not text[i].isdecimal(): return False for i in range(8,12): if not text[i].isdecimal(): return False return True