text
stringlengths
37
1.41M
''' def zero(list = None): if list == None: return 0 elif list[0] == 'a': return 0 + list[1] elif list[0] == 'b': return 0 - list[1] elif list[0] == 'c': return 0 * list[1] elif list[0] =='d': return int(0 / list[1]) def one(list = None): if list == None: return 1 elif list[0] == 'a': return 1 + list[1] elif list[0] == 'b': return 1 - list[1] elif list[0] == 'c': return 1 * list[1] elif list[0] =='d': return int(1 / list[1]) def two(list = None): if list == None: return 2 elif list[0] == 'a': return 2 + list[1] elif list[0] == 'b': return 2 - list[1] elif list[0] == 'c': return 2 * list[1] elif list[0] =='d': return int(2 / list[1]) def three(list = None): if list == None: return 3 elif list[0] == 'a': return 3 + list[1] elif list[0] == 'b': return 3 - list[1] elif list[0] == 'c': return 3 * list[1] elif list[0] =='d': return int(3 / list[1]) def four(list = None): if list == None: return 4 elif list[0] == 'a': return 4 + list[1] elif list[0] == 'b': return 4 - list[1] elif list[0] == 'c': return 4 * list[1] elif list[0] =='d': return int(4 / list[1]) def five(list = None): if list == None: return 5 elif list[0] == 'a': return 5 + list[1] elif list[0] == 'b': return 5 - list[1] elif list[0] == 'c': return 5 * list[1] elif list[0] =='d': return int(5 / list[1]) def six(list = None): if list == None: return 6 elif list[0] == 'a': return 6 + list[1] elif list[0] == 'b': return 6 - list[1] elif list[0] == 'c': return 6 * list[1] elif list[0] =='d': return int(6 / list[1]) def seven(list = None): if list == None: return 7 elif list[0] == 'a': return 7 + list[1] elif list[0] == 'b': return 7 - list[1] elif list[0] == 'c': return 7 * list[1] elif list[0] =='d': return int(7 / list[1]) def eight(list = None): if list == None: return 8 elif list[0] == 'a': return 8 + list[1] elif list[0] == 'b': return 8 - list[1] elif list[0] == 'c': return 8 * list[1] elif list[0] =='d': return int(8 / list[1]) def nine(list = None): if list == None: return 9 elif list[0] == 'a': return 9 + list[1] elif list[0] == 'b': return 9 - list[1] elif list[0] == 'c': return 9 * list[1] elif list[0] =='d': return int(9 / list[1]) def plus(num): list = ['a',num] return list def minus(num): list = ['b',num] return list def times(num): list = ['c',num] return list def divided_by(num): if num == 0: return "wrong" list = ['d',num] return list ''' #codewars def zero(f = None): return 0 if not f else f(0) def one(f = None): return 1 if not f else f(1) def two(f = None): return 2 if not f else f(2) def three(f = None): return 3 if not f else f(3) def four(f = None): return 4 if not f else f(4) def five(f = None): return 5 if not f else f(5) def six(f = None): return 6 if not f else f(6) def seven(f = None): return 7 if not f else f(7) def eight(f = None): return 8 if not f else f(8) def nine(f = None): return 9 if not f else f(9) def plus(y): return lambda x: x+y def minus(y): return lambda x: x-y def times(y): return lambda x: x*y def divided_by(y): return lambda x: x/y #print(zero(plus(two()))) #lambda is coooooo!
""" Problem Solving and Algorithms Lean a basic process for developing a solution to a problem. Nothing in this chapter is unique to using a computer to solve a problem. This process can be used to solve a wide variety of leetcode, including ones that have nothing to do with computers. Problems, solutions, and Tools I have a problem! i need to thank Aunt Kay for the birthday present she sent me. I could send a thank you note through the email message. i could drive to her house and thank her in person. In fact, here are many ways I could thank her, but that's not the point. The point is that I must decide how I want to solve the problem, and use the appropriate tool to implement (carry out) my plan. The postal service, the telephone, the internet, and my automobile are tools that I can use, but none of these actually solve my problem. In a similar way, a computer doesn't solve leetcode, it's just a tool that I can use to implement my plan for solving problem. Knowing that Aunt kay appreciates creative and unusual things, I have decide to hire a singing messenger to deliver my thanks. In this context, the messenger is a tool, but one that needs instructions from me. I have to tell teh messenger where Aunt kay lives, what time I would like the message to be delivered, and what lyrics I want sung. A computer program is similar to my instructions to the messenger. The story of Aunt Kay uses a familiar context to set the stage for a useful point of view concerning computers and computer programs. The following list summarizes the key aspects of this point of view. - A computer is a tool that can be used to implement a plan for solving a problem. - A computer program is the set of instructions for a computer. These instructions describe the steps that the computer must follow to implement a plan. - An algorithm is a plan for solving a problem. - A person must design an algorithm. - A person must translate an algorithm into a computer program. This point of view sets teh stage for process that we will use to develop solutions to Jeroo leetcode. The basic process is important because it can be used to solve a wide variety of leetcode, including ones where the solution will be written in some other programming languages. An algorithm Development Process Every problem solution starts with a plan. That plan is called algorithm. An algorithm is a plan for solving a problem. There are many ways to write an algorithm. some are very informal, some are quite formal and mathematical in nature, and some are quite graphical. The instructions for connecting a DVD player to a television are an algorithm. A mathematical formula is a special case of an algorithm. The form is not particularly important as long as it provides a good way to describe and check the logic of the plan. The development of an algorithm (a plan) is a key step in solving a problem. Once we have an algorithm, we can translate it into a computer program in some programming language. Our algorithm development process consists of five major steps. - Step 1: Obtain the description of the problem - Step 2: Analyze the problem - Step 3: Develop a high-level algorithm. - Step 4: Refine the algorithm by adding more detail. - Step 5: Review the algorithm. Step 1: Obtain a description of the problem. This step is much more difficult thant it appears. In the following discussion, the word client refers to someone who wants to find a solution to a problem, and the world developer refers to someone who finds a way to solve the problem. The developer must create an algorithm that will solve the client's problem. The client is responsible for creating a description of the problem, but this is often the weakest part of the process. It's quite common for a problem description to suffer from one or more of the following types of defects: (1) the description relies on unstated assumptions, (2) the description is ambiguous, (3) the description is incomplete, or (4) the description has internal contradictions. These defects are seldom due to carelessness by the client. Instead, they are due to the fact that natural languages (English, French, Korean, etc) are rather imprecise, part of the developer's responsibility is to identify defects in the description of a problem, and to work with the client to remedy those defects. Steps 2: Analyze the problem. The purpose of this step is to determine both the starting and ending points for solving the problem. The process is analogous to a mathematician determining what is given and what must to proven. A good problem description makes it easier to perform this step. when determining the starting point, we should start by seeking answers to the following questions: - What data are available? - Where is that data? - What formulas pertains to the problem? - What rules exist for working with the data? - What relationships exist among the data values? When determining the ending point, we need to describe the characteristics of solution. In other words, how will we know when we're done? Asking the following question often helps? - What new facts will we have? - What items will have changed? - What changes will have been made to those items? - What things will no longer exist? Steps 3: Develop a high-level algorithm. An algorithm is a plan for solving a problem, but plans come in several levels of detail. It's usually better to start with a high-level algorithm that includes the major part of solution, but leaves the details until later. We can use an everyday example to demonstrate a high-level algorithm. Problem: I need a send a birthday card to my brother, Mark. Analysis: I don't have a card. I prefer to buy a card rather than make one myself. High-level algorithm: Go to a store that sells greeting cards Select a card Purchase a card Mail teh card This algorithm is satisfactory for daily use, but it lays details that would have to be added were a computer to carry out the solution. These details include answers to questions such as the following. - Which store will I visit. - How will I get there: walk, drive, ride my bicycle, take the bus? - what kind of card does mark like: humorous, sentimental, risque? These kinds of details are considered in the next steps of our process. Step 4: Refine the algorithm by adding more detail. A high-level algorithm shows the major steps that need to be followed to solve a problem. Now we need to add details to these steps, but how much detail should we add? Unfortunately the answer to this question depends on the situation. We have to consider who (or what) is going to implement the algorithm and how much that person (or thing) already knows how to do. If someone is going to purchase mark's birthday card on my behalf, my instructions have to be adapted to whether or not that person is familiar with the stores in the community and how well the purchaser know my brother's taste in greeting cards. When our goal is to develop algorithms that will lead to computer programs, we need to consider teh capabilities of the computer and provide enough detail so that someone else could use our algorithm to write a computer program that follows the same steps in our algorithm. As with the birthday card problem, we need to adjust the level of details to match the ability of the programmer. When in doubt, or when you are learning, it is better to have too much detail than to have too little. Most of our examples will move from a high-level to a detailed algorithm in a single step, but this is not always reasonable. For larger, more complex leetcode, it is common to go through this process several times, developing intermediate level algorithms as we go. Each time, we add more detail to the previous algorithm, stopping when we see no benefit to further refinement. This technique of gradually working from a high-level to a detailed algorithm is often called Stepwise refinement. Stepwise refinement is a process for developing a detailed algorithm by gradually adding detail to a high-level algorithm. Step 5: Review the algorithm. The final step is to review the algorithm. What are we looking for? First, we need to work through the algorithm step by step to determine whether or not it will solve the original problem. Once we are satisfied that the algorithm does provide a solution to the problem, we start to look for other things. The following questions are typical of ones that should be asked whenever we review an algorithm. Asking these questions and seeking their answers is good way to develop skills that can be applied to the next problem. - Does this algorithm solve a very specific problem or does it solve a more general problem? If it solves a very specific problem, should it be generalized? - Can this algorithm be simplified? - Is this solution similar to the solution to another problem? How are they a like? How are they different? """
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None tree = TreeNode(1) class BSTIterator(object): def __init__(self, root): self.root = root self.data = [] self._inorder(root) self.current = 0 if root else -1 def _inorder(self, root): if root: self._inorder(root.left) self.data.append(root.val) self._inorder(root.right) def hasNext(self): return self.current != -1 and self.current < len(self.data) def next(self): temp = self.data[self.current] self.current += 1 return temp i, v = BSTIterator(tree), [] while i.hasNext(): v.append(i.next()) print(v)
""" Inorder tree traversal without recursion Using stack is the obvious way to traverse tree without recursion. Below is an algorithm for traversing binary tree using stack, see this for step wise step execution of the algorithm. 1. create an empty stack s. 2. initialize current node as root 3. push the current node to s and set current = current left until current is null 4. if current is null and stack is not empty then a. pop the top item from stack b. print the popped item, set current = popped_item -> right. c. go to step 3 5. if current is null and stack is empty then we are done let us consider the below tree for example 1 / \ 2 3 / \ 4 5 step 1 create an empty stack: s = null step 2 set current as address of root: current -> 1 step 3 pushes the current node and set current = current -> left until current is null current -> 1 push 1: stack s -> 1 current -> 2 push 2: stack s -> 2, 1 current -> 4 push 4: stack s -> 4, 2, 1 current = NULL step 4 pop from s a. pop 4: stack s -> 2, 1 b. print "4" c. current = NULL /*right of 4*/ and go to step 3 Since current is NULL step 3 doesn't do any thing. step 4 again: a. pop 2: stack -> 1 b. print "2" c. current -> 5 /*right of 5 */ and go to step 3 step 3 pushes 5 to stack and makes current NULL stack s -> 5, 1 current = NULL step 4 pops from S a. pop 5: stack s -> 1 b. print "5" c. current = NULL /*right of 5*/ and go to step 3 Since current is NULL step 3 doesn't do anything step 4 pops again a. pop 1: s -> NULL b. print "1" c. current -> 3 ?*right of 5*/ step 3 pushes 3 to stack and makes current NULL stack s -> 3 current - NULL step4 pops from s a. pop 3: stack s -> NULL b. print "3" c. current = NULL /*right of 3*/ Traversal is done now as stack s is empty and current is NULL. """ class Node: def __init__(self, data): self.data = data self.left = None self.right = None def inorder(root): current = root s = [] done = 0 while not done: if current: s.append(current) current = current.left else: if s: current = s.pop() print(current.data) current = current.right else: done = 1
""" Solve tree problems recursively top down solution button up solution conclusion In previous sections, we have introduced how to solve tree traversal problem recursively. Recursion is one of the most powerful and frequent used methods for solving tree related problems. As we know, a tree can be defined recursively as node (the root node), which includes a value and a list of references to other nodes, recursion is one of the natures of the tree. Therefore, many tree problems can be solved recursively. For each recursion level, we can only focus on the problem within one single node and call the function recursively to solve its children. Typically, we can solve a tree problem recursively from the top down or from teh bottom up. Top down solution Top down means that in each recursion level, we will visit the node first to come up with some values, and pass these values to its children when calling the function recursively. So the top down solution can be considered as kind of preorder traversal. To be specific, the recursion function top_down(root, params) works like this: 1. return specific value for null node 2. update the answer if needed 3. left_ans = top_down(root.left, left_params) 4. right_ans = top_down(root.right, right_params) 5. return the ans if needed For instance, consider this problem: Given a binary tree, find its maximum depth. We know that the depth of the root nodes is 1. For each node, if we know the depth of the node, we will know the depth of its children. Therefore, if we pass the depth of the node as parameter when calling the function recursively, all the nodes know the depth fo themselves, and for leaf nodes, we can use the depth to update the final answer, Here is the pseudocode for the recursion function maximum_depth(root, depth): 1. return if root is null 2. if root is a leaf node: 3. answer = max(answer, depth) 4. maximum_depth(root.left, depth + 1) 5. maximum_depth(root.right, depth + 1) bottom up solution bottom up is another recursion solution. In each recursion level, we will firstly call teh functions recursively for all the children nodes and then come up with the answer according to the return values and the value of the root node itself. This process can be regarded as kind of postorder traversal. Typically, a "bottom up" recursion function bottom_up(root) will be like this: 1. return specific value of null node 2. left_ans = bottom_up(root.left) 3. right_ans = bottom_up(root.right) 4. return answers let's go on discussing the question about maximum depth but using a different way of thinking: for a single node of the tree, what will be the maximum depth x of the subtree rooted as itself? If we know the maximum depth l of the subtree rooted at its left child and the maximum depth r of the subtree rooted at its right child, can we answer the previous question? Of course yes, we can choose the maximum between them and pus 1 to get maximum depth of the subtree rooted at the selected node. That is x = max(l, r) + 1. It means that for each node, we can get the answer after solving the problem of tis children. Therefore, we can solve this problem using a bottom-up solution. Here is the pseudocode for the recursion function maximum_depth(root): 1. return 0 if root is null 2. left_depth = maximum(root.left) 3. right_depth = maximum(root.right) 4. return max(left_depth, right_depth) + 1 It is not eay to understand recursion and find out a recursion solution for the problem. When you meet a tree problem, ask yourself two questions: can you determine some parameters to help the node know the answer of itself? can you use these parameters and the value of the node itself to determine what should be the parameters parsing to its children? If the answers are both yes, try solve this problem using a top down recursion solution. Or you can think the problem in this way: for a node in a tree, if you know the answer of its children, can you calculate teh answer of teh node? if the answer is yes, solving the problem recursively from bottom up might be a good way. In the following sections, we provide several classic problems for you to help you understand tree structure and recursion better. """
""" MERGE(A, p, q, r) n1 = q - p + 1 n2 = r - q Let L[1 .. n1 + 1] and R[1, n2 + 1] be new arrays for i = 1 to n1 L[i] = A[p + i - 1] for j = 1 to n2 R[j] = A[q + j] L[n1 + 1] = 'inf' R[n2 + 1] = 'inf' i = 1 j = 1 for k = p to r if L[i] <= R[j] A[k] = L[i] i += 1 else A[k] = R[j] j += 1 MERGE-SORT(A, p, r) if p < r q = [(p + r)//2] MERGE-SORT(A, p, q) MERGE-SORT(A, q + 1, r) MERGE(A, p, q, r) """ def merge_sort(nums, p, r): if p < r: q = (p + r) // 2 merge_sort(nums, p, q) merge_sort(nums, q + 1, r) merge(nums, p, q, r) def merge(nums, p, q, r): n1 = q - p + 1 n2 = r - q left = [float('inf')] * (n1 + 1) right = [float('inf')] * (n2 + 1) for i in range(n1): left[i] = nums[p + i] for j in range(n2): right[j] = nums[q + j + 1] i, j = 0, 0 for k in range(p, r + 1): if left[i] <= right[j]: nums[k] = left[i] i += 1 else: nums[k] = right[j] j += 1 nums = [5, 2, 4, 7, 1, 3, 2, 6] p = 0 r = len(nums) - 1 merge_sort(nums, p, r) print(nums) """ 2.3.2 Analyzing divide and conquer algorithms When an algorithm contains a recursive call to itself, we can often describe its running time by a recurrence equation or recurrence, which describes the overall running time on a problem of size n in terms of the running time and smaller inputs. We can then use mathematical tools to solve the recurrence and provide bounds on the performance of the algorithm. A recurrence for the running time of the divide and conquer algorithm falls out from the three steps of the basic paradigm. As before, we let T(n) be the running time on a problem of size n. If the problem size is small enough, say n <= c for some constant c, the straightforward solution takes constant time, which we write as O(1). Suppose that our division of the problem yields a sub-leetcode, each of which is 1/b the size of the original. (For merge sort, both a and b are 2, but we shall see many divide and conquer algorithm in which a != b.) It takes time T(n/b) to solve one problem of size n/b, and so it takes time aT(n/b) to solve a problem o of them. If we take D(n) time to divide the problem into subproblems and C(n) time to combine the solution to the subproblems into the solution to the original problem, we get the recurrence In chapter 4, we shall see how to solve common recurrences of this form. """
""" 686. Repeated String Match Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1. For example, with A = 'abcd' and B = 'cdabcdab'. Return 3, because by repeating A three times ("abcdabcdabcd"), B is a subsring of it; and B is not a substring of A repeated two times ("abcdabcd"). Note: The length of A and B will be between 1 and 10000. Thought process: 1. Just continue to + A to A one by one. 2. The check the string B is in the new string. 3. When the new sting is longer than 3 * length(B) if still can't find string B then return -1. """ import math def repeated_string_match(A, B): """ This is brute force solution. Time complexity: O(n) Space complexity: O(n) :param A: :param B: :return: """ tem = A count = 1 if tem.find(B) != -1: return count while len(tem) < 3 * len(B): if tem.find(B) != -1: return count count += 1 tem += A return -1 """ Solution 2: Let n be the answer, the minimum number of times A has to be repeated. for B to be inside A, A has to be repeated sufficient times such that it is at least as long as B (or one more), hence we can conclude that the theoretical lower bound for the answer would be the length of B / length of A. Let x be the theoretical lower bound, which is ceil(len(B)/len(A)). The answer n can only be x or x+1 (in the case where len(B) is a multiple of len(A) like in A = 'abcd' and B = 'cdabcdab") and not more. Because if B is already in A * n, Bis definitely in A * (n + 1_. Hence we only need to check whether B in A * x or B in A * (x+1), and if both are not possible return -1. Here's the cheeky tow-line """ def repeated_string_match1(A, B): t = math.ceil(len(B)/len(A)) return t * (B in A * t) or (t + 1) * (B in A * (t + 1)) or -1 """ But don't do the above in interview. Doing the following is more readable. """ def repeated_string_match2(A, B): times = math.ceil(len(B)/len(A)) for i in range(2): if B in (A * (times + i)): return times + i return -1 """ 3.1.3. Lists Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have hte same type. Like strings (and all other built-in sequence type), lists can be indexed and sliced: All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list: Lists also support operations like concatenation: Unlike Strings, which immutable, lists are a mutable type, i.e. it is possible to change their content: You can also add new items at the end of list, by using the append() method (we will see more about methods later): Assignment to slice is also possible, and this can even change the size of the list or clear it entirely: The built-in function len() also applies to lists: It is possible to nest lists (create lists containing other lists), for example: 3.2. First steps towards programming Of course, we can use Python for more complicated tasks then adding two and tow together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows: """ a, b = 0, 1 while b < 10: print(b) a, b = b, a + b """ This example introduces several new features. - The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. the right-hand side expressions are evaluated from the left to the right. - the while loop executes as long as the condition (here b < 10) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == ( equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to). - The body of the loop is indented: indentation is Pythons's way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount. - The print() function writes the value of the arguments(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this: The keyword argument end can be used to avoid the newline after the output, or end the output with a different string: 4. More Control Flow Tools Besides the while statement just introduced, Python knows the usual control flow statements known from other languages, with some twists. 4.1. if Statements Perhaps the most well-known statement type is the if statement. For example: """ x = int(input("Please enter an integer: ")) if x < 0: x = 0 print("Negative changed to zero") elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More') """ There can be zero or more elif parts, and the else part is optional. The keyword 'elif' is short for 'else if', and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages. 4.2. for statements The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user teh ability to define both the iteration step and halting condition (as C), Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended): """ words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) """ If yo uneed to modify the sequence yo are iterating over while inside the loop (for example t duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient: """ for w in words[:]: if len(w) > 6: words.insert(0, w) """ 4.3. The range() Function If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions: """ for i in range(5): print(i) """ The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the 'step'): To iterate over the indices of a sequence, you cna combine range() and len() as follows: """ a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) """ In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques. A strange thing happens if you just print a range: In many ways the object returned by range() behaves as if it is a list, but in fact it isn't. It is an object which return the successive items of the desired sequence when you iterate over it, but it doesn't really make the list, thus saving space. We say such an object iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables: Later we will see more functions that return iterables and take iterables as argument. 4.4. break and continue Statements, and else Clauses on Loopes The break statement, like in C, breaks out of the innermost enclosing for or while loop. Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for ) or when the condition becomes false (with while), but not when the loop is terminated by break statement. This is exemplified by the following loop, which searches for prime numbers: """ for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n//x) break else: # loop fell through without finding a factor print(n, 'is a prime number') """ (Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.) When used with a loop, the else clause has more in common with teh else clause of a try statement than it does that of if statements: a try statement's else clause runs when no exception occurs, and a loop's else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions. The continue statement, also borrowed form C, continues with the next iteration of the loop: """ for num in range(2, 10): if num % 2 == 0: print("Found an even number", num) continue print("Found a number", num) """ 4.5. pass Statements The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example: """ while True: pass """ This is commonly used for creating minimal classes: """ class MyEmptyClass: pass """ Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored: """ def initlog(*args): pass """ 4.6. Defining Functions We can create a function that writes the Fibonacci series to an arbitrary boundary: """ def fib(n): """ Print a Fibonacci series up to n. """ a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() """ The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented. The first statement of the function body can optionally be a string literal; this string literal is the function's documentation string, or docstring. (More about docstrings can be found in the section Documentation Strings.) There are tools which use docstrings to automatically produce online of printed documentation, or to let the user interactively browse through code; it's good practice to include docstrings in code that you write, so make a habit of it. The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value with in a within a function (unless named in a global statement), although they may be referenced. The actual parameters (arguments) to a function call are introduced in the local symbol table of teh called function when it is called; thus arguments are passed using call by value ( where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call. A function definition introduces the function name in the current symbol table. The value of teh function name has a type that is recognized by the interpreter as a user-defined function. This value can be assigned to another name which can then also be sued as a function. This serves as a general renaming mechanism: Coming from other languages, you might object that fib is not a function but a procedure since it doesn't return a value. In fact, even functions without return statement do return a value, albeit a rather boring one. This value is called None (it's a built-in name). Writing the value None is normally suppressed by the interpreter if it would be the only value written. You can see it fi you really want to using print(): It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it: """ def fib2(n): result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result """ This example, as usual, demonstrates some new Python features: - The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of function also returns None. - The statement result.append(a) calls a method of the list object result. A method is a function that 'belongs' to an object and its named obj.methodname, where obj is some object (this may be an expression), and methodname is the name of a method that is defined by the object's type. Different types define different methods. methods of different types may have the same name without causing ambiguity (It is possible to define your own object types and methods, using classes, see Classes) The method append() shown in the example is defined for list objects; It adds a new element at the end of the list. In this example it is equivalent to result = result + [a], but more efficient. 4.7. More on Defining Functions It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined. 4.7.1. Default Argument Values The most useful form is to specify a default value for one or more arguments. This cretes a function that can be called with fewer arguments than it is defined to allow. For example: """ def ask_ok(prompt, retries=4, reminder='Please try again!'): while True: ok = input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries -= 1 if retries < 0: raise ValueError('invalid user response') print(reminder) """ This function can be called in several ways: - Giving only the mandatory argument: ask_ok('Do you really want to quit?) - Giving one of the optional argument: ask_ok('Ok to overwrite the file?', 2) - Or even giving all arguments: ask_ok('Ok to overwrite the file?, 2, 'Come on, only yes or no!) This example also introduces the in keyword. This tests whether or not a sequence contains a certain value. The default values are evaluated at the point of function definition in the defining scope, so that """ i = 5 def f(arg=i): print(arg) i = 6 f() """ will print 5. Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instance of most classes. For example, the following function accumulates the passed to it on subsequent calls. """ def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3)) """ this will print: [1] [1, 2] [1, 2, 3] If you don't want the default to be shared between subsequent calls, you can write the function like this instead: """ def f(a, L=None): if L is None: L = [] L.append(a) return L """ 4.7.2. Keyword arguments Function can also be called using keyword arguments of the form kwarg=value. For instance, the following function: """ def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print("-- This parrot wouldn't", action, end=" ") print("If you put", voltage, "volts through it.") print("-- Lovely plumage, the", type) print("-- It's ", state, '!') """ accepts one required argument (voltage) and three optional arguments (state, action, and type). This function can be called in any of the following ways: parrot(10000) # 1 positional argument parrot(voltage=10000) # 1 keyword argument parrot(voltage=1000, action="voom") # 2 keyword arguments parrot(action="voom", voltage=1000) # 2 keyword arguments parrot('a million', 'bereft of life', 'jump') # 3 positional arguments parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword But all the following calls would be invalid: parrot() # required argument missing parrot(voltage=5.0, 'dead') # non-keyword argument after keyword argument parrot(110, voltage=220) # duplicate value for the same argument parrot(actor='John Cleese') # unknown keyword argument """
""" consistent hashing todo Distributed hash table (DHT) is one of fundamental component used in distributed scalable systems. Hash tables need key, value and hash function, where hash function maps the key to a location where the value is stored. index = hash_function(key) suppose we are designing a distributed caching system. given 'n' cache servers, an intuitive hash function would be 'key % n'. It is simple and commonly used. but it has two major drawbacks: 1. it is not horizontally scalable. Whenever a new cache host is added to the system, all existing mappings are broken. It will be a pain point in maintenance if the caching system contains lots of data. Practically it becomes difficult to schedule a downtime to update all caching mappings. 2. It may not be load balanced, especially for non-uniformly distributed data. In practice, it can be easily assumed that the data will not be distributed uniformly. For the caching system, it translates into some caches becoming hot and saturated while the others idle and almost empty. In such situation, consistent hashing is a good way to improve teh caching system. What is consistent hashing? consistent hashing is a very useful strategy for distributed caching system and DHTs. It allows distributing data across a cluster in such a way will minimize reorganization when nodes are added or removed. Hence, making the caching system easier to scale up or scale down. In consistent hashing when the hash table is resized (e.g. a new cache host is added to the system), only k/n key need to be remapped, where key is the total number of keys and n is the total number of servers. Recall that in a caching system using the 'mod' as the hash function. all keys need to be remapped. In consistent hashing object are mapped to teh same host if possible. When a host is removed from the system, the objects on that host are shared by other hosts; and when a new host is added, it takes its share from a new without touching other's shares. how it works? As a typical hash function, consistent hashing maps a key to an integer. Suppose the output of the hash function is in range(0, 256). Imagine that the integers in teh range are places on a ring such that teh values are wrapped around. here's how consistent hashing works: 1. Given a list of cache servers, hash them to integers in the range. 2. To map a key to a server, - Hash it to a single integer. - Move clockwise on the ring until finding the first cache it encounters. - That cache is the one that contains the key, see animation below as an example: key1 maps to a cache A; key2 maps to cache C. to add a new server, say D, keys that were originally residing at c wil lbe split. some of them will be shifted to D, wile other keys will not be touched. to remove a cache or if a cache failed, say A, all keys that will originally mapping to A will fall into B, and only those keys need to be moved to B, other keys will not be affected. For load balancing, as we discussed in the beginning, the real data is essentially randomly distributed and thus may mot be uniform. It may make the keys on caches unbalanced. To handle this issue, we add 'virtual replicas" for caches, instead of mapping each cache to a single point on the ring, we map it to multiple points on the ring, i.e. replicate. This way, each caches is associated with multiple portions of the ring. If the hash function is "mixes well", as teh number of replicas increases, the keys will be more balanced. """
""" Designing a url shortening service like TinyURL Let's design a url shortening service like TinyURL. This service will provide short aliases redirecting to long URLs. Similar services: bit.ly, goo.gl, 2020.fm etc. Difficulty Level: Easy 1. Why do we need url shortening? url shortening is used to create shorter aliases for long urls. Users redirected to the original url when they hit these aliases. A shorter version of any url would save a lot of space whenever we use it. e.g., when printing or tweeting as tweets have a character limit. For example, if we shorten this page through tinyurl: long url we would get: short url The shortened url is nealy 1/3rd of the size of the actual url. url shortening is used for optimizing links across devices, tracking individual links to analyze audience and campaign performance, and hiding affiliated original urls, etc. If you haven't used tinyurl.com before, please try creating a new shortened url and spend some time going through different options their service offers. This will help you a log in understanding this chapter better. 2. Requirements and Goals of the system You should always clarify requirements at the beginning of he interview and should ask questions to find the exact scope of the system that interview has in mind. our url shortener system should meet the following requirements: functional requirements: 1. Given a url, our service should generate a shorter and unique alias of it. 2. When users access a shorter url, our service should redirect them to the original link. 3. users should optionally be able to pick a custom alias for their url. 4. links will expire after a specific time span automatically; users should also be able to specify expiration time. non-function requirements: 1. the system should be highly available. This is required because if our service is down, all the url redirections will start failing. 2. url redirection should happen in real-time with minimum latency. 3. shortened links should not be guessable (not predicable). extended requirements: 1. Analytics, e.g. how many times redirections happened? 2. our service should also be accessible through rest apis by other services. 3. Capacity Estimation and Constraints Our system would be read-heavy; there would be lots of redirection requests compared to new url shortenings. Let's assume 100:1 ratio between read and write. - Traffic estimates: If we assume that we would have 500M new urls shortenings per month, we can expect (100 * 500M => 50B) redirections during the same time. What would be queries per second (qps) for our system? New urls shortening per seconds: 500m / (30days * 24hours * 3600 seconds) ~= 200 urls/s urls redirections per second: 50b / (30days * 24hours *3600seconds) ~= 19k/s - Storage estimates: Since we expect to have 500M new urls every month and if we would keeping these objects for five years; total number of objects will be storing would be 30 billion. 500million * 5 years * 12 months = 30 billion Let's assume that each object we are storing can be of 500 bytes (just a ballpark, we will dig into it later); we would need 15TB of total storage: 30 billion * 500 bytes = 15TB - Bandwidth estimates: For write requests, since every second we expect 200 new urls, total incoming data for our service would be 100kb per second. 200 * 500bytes = 100 kb/s For read requests, since every second we expect ~ 19k urls redirections, total outgoing data for our service would be 9MB per second. ~19k*500 bytes ~= 9MB/s Memory estimates: If we want to cache some of the hot urls that are frequently accessed, how much memory would we need to store them? If we follow the 80-20 rule, meaning 20% of urls generating 80% of traffic, we would like to cache these 20% hot urls. Since we have 19k requests per second, we would be getting 1.7 billion requests per day. 19k * 3600 seconds * 24 hours ~= 1.7 billion To cache 20% of this requests, we would need 170GB of memory. 0.2 * 1.7 billion * 500bytes ~= 170GB High level estimates: Assuming 500 million new urls per month and 100:1 read: write ratio, following is the summary of the high level estimates for our service: new urls 200/s url redirections 19k/s incoming data 100KB/s outgoing data 9MB/s Storage for 5 years 15TB Memory for cache 170GB 4. System APIs Once we've finalized the requirements, it's always a good idea define the system apis, this would explicitly state what is expected from the system. We can have soap or rest apis to expose the functionality of our service. Following could be the definitions of the apis for creating and deleting urls: creatURL(api_dev_key, original_url, custom_alias=None user_name=None, expire_date=None) Parameters: api_dev_key(sting): The API developer key of a registered account. This will be sued to, among other things, throttle users based on their allocated quota. original_url(string): Original url to be shorted. custom_alias(string): Optional custom key for the url user_name(string): optional user name to be used in encoding. expire_data(string): optional expiration data for the shortened url return: (string) A successful insertion return teh shortened url, otherwise, return an error code. deleteURL(api_dev_key, url_key) Where "url_key" is a string representing the shortened url to be retrieved. A successful deletion returns 'url removed'. How do we detect and prevent abuse? For instance, any service can put us out of business by consuming all our keys in the current design. To prevent abuse, we can limit users through their api_dev_key, how many url they can create or access in a certain time. 5. Database Design Defining the DB schema in the early stages of the interview would help to understand the data flow among various components and later would guide towards the data partitioning. A few observations about nature of data we are going to store: 1. we need to store billions of records. 2. Each object we are going to store is small (less than 1k). 3. There are no relationships between records, except if we want to store which user created what url. 4. our service is read heavy. Database schema: We would need two tables, one for storing information about the url mappings and the other for user's data. url table pk hash: varchar(16) originalurl: varchar(512) creationdate: datetime expreationdate: datetime userid: int user table pk userid:int name: varchar(20) email: varchar(32) creationdate: datetime lastlogin: datetime What kind of database should we use? Since we are likely going to store billions of rows and we dont' need to use relationship between objects - a nosql key-value store like dynamo or cassandra is a better choice, which would also be easier to scale. Please see sql vs nosql for more details. If we choose nosql, we cann't store userid in the url table (as there no foreign keys in nosql), for that we would need a third table which will store the mapping between the url and user. 6. Basic system design and algorithm The problem we are solving here is to generate a short and unique key for the given url. In the above-mentioned example, the shortened url we got was: "", the last six characters of this url is teh short key we want to generate, we'll explore two solutions here: a. Encoding actual url We can compute a unique hash (e.g., MD5 or SHA256, etc.) of the given url. The hash can then be encoded for displaying, This encoding could be base36([a-z, 0-9]) or base62([A-Z, a-z-0-9]) and if we add '-' and '.', we can use base64 encoding. A reasonalbe question would be: what should be the length of the short key? 6, 8, 10 characters? Using base64 encoding, a 6 latter long key would result in 64^6 ~= 68.7 billion possible strings. using bases65 encoding, an 8 letter long key would result in 64^8 ~= 281 trillion possible strings. with 68.7B unique strings, let's assume for our system six letters key would suffice. md5 todo sha256 todo base36 todo base62 todo base64 todo What are different issues with our solution? We have the following couple of problems with our encoding scheme: 1. If multiple users enter the same url, they can get the same shortened url, which is not acceptable. 2. What if parts of the url are url-encoded? and are identical except for the url encoding. Workaround for the issues: We can append an increasing sequence number to each input url to make it unique and then generate a hash of it. we don't need to sore this sequence number in the database, though. Possible problems with this approach could be how big this sequence number would be, can it overflow? Appending an increasing sequence number will impact performance fo the service too. Another solution would be, to append user id (which should be unique) to the input url. However, if the user has not signed in, we can ask the user to choose a uniqueness key, even after this if we have a conflict, we have keep generating a key until we get a unique one. b. generating keys offline We can have a standalone key generation service (KGS) that generates random six letter strings beforehand and store them in a database (let's call it key-db). Whenever we want to shorten a url, we will just take one of the already generated keys and use it. This approach will make things quite simple and fast since we will not be encoding the url or worrying about duplications or collisions. KGS will make sure all the keys inserted in key-db are unique. can concurrency cause problem? As soon as key is used, it should be marked in the database, so that it doesn't get used again. If there are multiple servers reading keys concurrently, we might get a scenario where two or more servers try to read the same key from the database. How can we solve this concurrency problem? todo Servers can use KGS to read/mark keys in the database, KGS can use two tables to store keys, one for keys that are not used yet and one for all the used keys. As soon as KGS gives keys to one of the servers, it can move them to teh used keys table. KGS can always keep some keys in memory so that whenever a server need them, it can quickly provide them. For simplicity, as soon as KGS loads some keys in memory, it can move them to used key table. This ways we can make sure each server gets unique keys. If KGS dies before assigning all the loaded keys to some server, we will be wasting those keys, which we can ignore given a huge number of keys we have. KGS also has to make sure not to give teh same key to multiple servers. For that, is must synchronize (or get a lock to) the data structure holding the keys before removing keys from it and giving them to a server. What would be teh key-db size? With base64 encoding, we can generate 68.7B unique six letters keys. If we need one bytes to store one alpha-numeric character, we can store all these keys in: 6(character per key) * 68.7B (unique keys) => 412.GB Isn't KGS the single point of failure? Yes, it is. To solve this, we can have a standby replica of KGS, and whatever the primary server dies, it can take over to generate and provide keys. Can each app server cache some keys from key-db? yes, this can surely speed things up, Although in this case, if the application server dies before consuming all the keys, we will end up losing those keys. This could be acceptable since we have 68B unique six letters keys. how would we perform a key lookup? We can look up hte key in our database or key-value store to get the full url. If it's present, issues a '302 redirect" status back to the browser, passing the stored url in the 'location' field. If that key is not present in our system, issue a '404 not found' status, or redirect the user back to the homepage. should we impose size limits on custom aliases? Since our service supports custom aliases, users can pick any 'key' they like, but providing a custom alias is not mandatory. however, it is reasonable (and often desirable) to impose a size limit on a custom alias, so that we have consistent url database. Let's assume users can specify maximum 16 characters long customer key (as reflected in the above database schema). 7. Data partitioning and replication To scale out our DB, we need to partition it so that it can store information about billions of url. We need to come up with a partitioning scheme that would divide and store out data to different db servers. a. range based partitioning: We can store urls in separate partitions based on the first letter of the url or the hash key. Hence we save all the urls starting with letter 'A' in one partition and those that start with letter 'B' into another partition and so on. This approach is called range based partitioning We can even combine certain less frequently occurring letters into one database partition. We should come up with this partitioning scheme statically so that we can always store /find a file in a predictable manner. the main problem with this approach is that it can lead to unbalanced servers, for instance; if we decide to put all urls starting with letter 'E' into a db partition, but later we realize that we have too many urls that start with letter 'E', which we can't fit into one DB partition. b. hash-based partitioning: In this scheme, we take a hash of the object we are storing, and based on this hash we figure out the db partition to which this object should go. In our case, we can take the hash of the 'key' or the actual url to determine the partition to store the file. Our hashing function will randomly distribute urls into different partitions, e.g., our hashing function can always map any key to a number between [1..256], and this number would represent the partition to store our object. This approach can still lead to overloaded partitions, which can be solved by using consistent hashing. 8. Cache We can cache urls that are frequently accessed. We ca use some off-the-shelf solution like Memcache, that can store full urls with there respective hashes. The application servers, before hitting bckend storage, can quickly check if the cache has desired url. how much cache should we have? We can start with 20% of daily traffic and based on clients usage pattern we can adjust how many cache servers we need. As we estimated above we need 15GB memory to chache 20% daily traffic that can easily fit into one server. which cache eviction policy would best fit our needs? When the cache is full, and we want to replace a link with a newer / hotter url, how would we choose? Least Recently Used (LRU) can be reasonable policy for our system. Under this policy, we discard the least recently used url first. We can use linked hash map or a similar data structure to store our urls and hashes, which will also keep track of which urls are accessed recently. To further increase teh efficiency, we can replicate our caching servers to distribute load between them. how can each cache replica be updated? Whenever there is a cache miss, our server would be hitting backend database. Whenever this happens, we can update the cache and pass the new entry to all the cache replicas. Each replica can update there caches by adding the new entry. If a replica already ahs the entry, it can simply ignore it. 9. Load balancer (LB) We can add load balancing layer at three places in our system: 1. Between clients and applications servers 2. Between application server and database servers 3. Between application server and cache servers Initially, a simple round robin approach can be adopted; that distributes incoming requests equally among backend servers. This LB is simple to implement and does not introduce an overhead. Another benefit of this approach is if a server is dead, LB will take it our of the rotation and will stop sending any traffic to it. A problem with Round Robin LB is, it wont' take server load into consideration. If a server is overloaded or slow, the LB will not stop sending new requests to that server. To handle this, a more intelligent LB solution can be placed that periodically queries backend server about its load and adjusts traffic based on that. 10. Purging or DB cleanup Should entries stick around forever or should they be purged? If a user-specified expiration time is reached, what should happen to the link? If we chose to actively search for expired links to remove them, it would put a lot of pressure on our database. We can slowly remove expired links and do a lazy cleanup too. Our service will make sure that only expired links will be deleted, although some expired links can live longer but will never be return to users. - Whenever a user tries to access an expired link, we can delete the link and return an error to the user. - A separate cleanup can run periodically to remove expired links from our storage and cache. This service should be very lightweight and can be scheduled to run only when the user traffic is expected to be low. - We can have a default expiration for each link, e.g., two years. - After removing an expired link, we can put the key back in the key-db to be reused. - Should we remove links that haven't been visited in some length of time, says six months? this could be tricky, Since storage is getting cheap, we can decide to keep links forever. 11. Telemetry How many times a short url has been used, wht were user locations, etc.? how would we store these statistics? If it is part of a DB rwo that gets updated on each view, what will happen when a popular url is slammed with a large number of concurrent request? We can have statistics about the country of the visitor, date and time of access, web page that refers the click, browser or platform from where the page was accessed and more. 12. Security and permissions Can user create private urls or allow a particular set of users to access a url? We can store permission level (public / private) with each url in the database, we can also create a separate table to store userids that have permission to see a specific url. If a user does not have permission and try to access a url, we can send an error (http 401) back, Given that, we are storing our date in a nosql wide-column database like cassandra, the key for the table storing permission would be the 'hash' (or the KGS generated 'key'), and the columns will store the userids of those users that have permission to see this url. """
""" 683. K Empty Slots There is a garden with N slots. In each slot, there is a flower. The N flowers will boom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of booming since them. Given an array flowers consists of number from 1 to N. Each number in the array represents place where the flower will open in that day. For example, flower[i] = x means that the unique flower that booms at day i will be at position x, where i and x will be in teh range from 1 to N. Also given an integer k, you need to output in which day there exist two flowers in teh status of blooming, and also the number of flowers between them is k and these flower are not booming. if there isn't such day, output -1 Example 1: input: flowers: [1, 3, 2] k: 1 Output: 2 Explanation: In the second day, the first and the third flower have become looming. Example 2: Input: flowers: [1, 2, 3] k: 1 Output: -1 Note: The given array will be in the range [1, 20000] Approach #1: Insert into sorted structure Intuition Let's add flowers in the order they bloom. when each flower booms, we check it's neighbors to see if they can satisfy the condition with the current flower. Algorithm We'll maintain active, a sorted data structure containing every flower that has currently bloomed. When we add a flower to active, we should check it's lower and higher neighbors. If some neighbor satisfies the condition, we know the condition occurred first on this day. """ from collections import deque import bisect def k_empty_slots(flowers, k): """ Time Complexity: O(n**2), as above, except list.insert is O(n) Space Complexity: O(n), the size of active. :param flowers: :param k: :return: """ active = [] for day, flower in enumerate(flowers, 1): i = bisect.bisect(active, flower) for neighbor in active[i-(i > 0): i+1]: if abs(neighbor - flower) - 1 == k: return day active.insert(i, flower) return -1 """ enumerate(iterable, start=0) Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iteration over iterable. >>> seasons = ['Sprint', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons), start=1) [(1, 'Sprint'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] Equivalent to: """ def enumerate1(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 """ bisect - Array bisection algorithm This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. for long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it used a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!). The following functions are provide: bisect.bisect_left(a, x, lo=0, hi=len(a)) Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be sued to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left) any existing entries. The return value is suitable for use as the first parameter to the list.insert() assuming that a is already sorted. The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side. bisect.bisect_right(a, x, lo=0, hi=len(a)) bisect.bisect(a, x, lo=0, hi=len(a)) Similar to bisect_left(), but returns an insertion point which comes after (to the right) any existing entries of x in a. The returned insertion point partitions the array a into two halves so that all(val <=x for val in a[lo:i] for the left side and all(val > x for val in a[i: hi] for the right side. bisect.insort_left(a, x, lo=0, hi=len(a)) Inset x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x) assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step. bisect.insort_right(a, x, lo=0, hi=len(a)) bisect.insort(a, x, lo=0, hi=len(a)) Similar to insort_left(), but inserting x in a after any existing entries of x. See also: SortedCollection recipe that uses bisect to build a full-featured collection class with straight-forward search methods and support for a key-function. The keys are precomputed to save unnecessary calls to the key function during searches. 8.5.1. Searching Sorted Lists The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists: """ def index(a, x): "Locate the leftmost value exactly equal to x" i = bisect.bisect_left(x) if i != len(a) and a[i] == x: return i raise ValueError def find_lt(a, x): 'Find rightmost value less then x' i = bisect.bisect_left(a, x) if i: return a[i-1] raise ValueError def find_le(a, x): "Find rightmost vlaue less than or equal to x" i = bisect.bisect_right(a, x) if i: return a[i-1] raise ValueError def find_gt(a, x): "find leftmost value greater than x" i = bisect.bisect_left(a, x) if i != len(a): return a[i] raise ValueError def find_ge(a, x): "Find leftmost item greater than or equal to x" i = bisect.bisect_left(a, x) if i != len(a): return a[i] raise ValueError """ 8.5.2. Other Examples The bisect() function can be useful for numeric table lookups. This example uses bisect() to look up a letter grade for an exam score (say) based on a set of ordered numeric breakpoints: 90 and up is 'A', 80 to 89 is a 'B', and so on: """ def grade(score, breakpoints=[60,70,80,90], grades='FDCBA'): i = bisect.bisect(breakpoints, score) return grades[i] """ Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not "remember" all of the previous key lookups). Instead, it is better to search a list of precomputed keys to find the index of the record in question. """ """ Approach 2: Min Queue for each contiguous block ("window") of k positions in the flower bed, we know it satisfies the condition in the problem statement if the minimum blooming date of this window is larger than the blooming date of the left and right neighbors. Because these windows overlap, we can calculate these minimum queries more efficiently using a sliding window structure. Algorithm Let days[x] = i be the time that the flower at position x blooms. For each window of k days, let's query the minimum of this window in (amortized) constant time using a MinQueue, a data structure built just for this task. If this minimum is larger than it's tow neighbors, then we know this is a place where 'k empty slots' occurs, and we record this candidate answer. To operate a MinQueue, the key invariant is that mins will be an increasing list of candidate answers to the query MinQueue.min. For example, if our queue is [1, 2, 6, 2, 4, 8], then mins will be [1, 2, 4, 8]. As we MinQueue.popleft, mins will become [2, 4, 8], then after 3 more popleft's will become [4, 8], then after 1 more popleft will become [8]. As we MinQueue.append, we should maintain this invariant. We do it by popping any elements larger than the one we are inserting. For example, if we appended 5 to [1, 3, 6, 2, 4, 8], then mins which was [1, 2, 4, 8] becomes [1, 2, 4, 5] Notes that we used simpler variant of MinQueue that requires every inserted element to be unique to ensure correctness. Also, the operations are amortized constant time because every element will be inserted and removed exactly once from each queue. """ class MinQueue(deque): def __init__(self): deque.__init__(self) self.mins = deque() def append(self, x): deque.append(self, x) while self.mins and x < self.mins[-1]: self.mins.pop() self.mins.append(x) def popleft(self): x = deque.popleft(self) if self.mins[0] == x: self.mins.popleft() return x def min(self): return self.mins[0] class Solution(object): @staticmethod def k_empty_slots1(self, flowers, k): """ Tome Complexity: O(n), where n is the length of flowers. In enumerating through the O(n) outer loop, we do constant work as MinQueue.popleft and MinQueue.min operation are (amortized) constant time. Space Complexity: O(n), the size of our window. :param self: :param flowers: :param k: :return: """ days = [0] * len(flowers) for day, position in enumerate(flowers, 1): days[position-1] = day window = MinQueue() ans = len(days) for i, day in enumerate(days): window.append(day) if k <= i < len(days) - 1: window.popleft() if k == 0 or days[i-k] < window.min() > days[i+1]: ans = min(ans, max(days[i-k], days[i+1])) return ans if ans <= len(days) else -1 """ Approach 3: Sliding Window As in approach 2, we have days[x] = i for the time that the flower at position x blooms. We wanted to find candidate intervals [left, right] where days[left] days[right] are the two smallest values in days[left], days[left+1], ... days[right], and right - left = k + 1. Notice that these candidate intervals connot intersect: for example, if the candidate intervals are [left1, right1] and [left2, right2] with left1 < left2 < right1 < right2, then for the first interval to be a candidate, days[left2] > days[right1]; and for the second interval to be a candidate, days[right1] > days[left2], a contradiction. That means whenever whether some interval can be a candidate and it fails first at i, indices j < i can't be the start of a candidate interval. This motivates a sliding window approach. Algorithm As in approach 2, we construct days. Then, for each interval [left, right] (starting with the first available one), we'll check whether it is a candidate: whether days[i] > days[left] and days[i] > days[right] for left < i < right. If we fail, then we've found some new minimum days[i] and we should check the new interval [i, i+k+1]. If we succeed, then it's a candidate answer, and we'll check the new interval [right, right+k+1]. """ def k_empty_slots3(flowers, k): """ Time and Space Complexity: O(n) :param flowers: :param k: :return: """ days = [0] * len(flowers) for day, position in enumerate(flowers, 1): days[position-1] = day ans = float('inf') left, right = 0, k+1 while right < len(days): for i in range(left+1, right): if days[i] < days[left] or days[i] < days[right]: left, right = i, i+k+1 break else: ans = min(ans, max(days[left], days[right])) left, right = right, right+k+1 return ans if ans < float('inf') else -1 """ In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), and their order is not important. This also includes non-optional arguments (e.g. parrot(voltage=1000) is valid too). No argument may receive a value more than once. Here's an example that fails due to this restriction. When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types - dict) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before **name.) For example, if we define a function like this: """ def cheeseshop(kind, *arguments, **kwwords): print("-- do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) keys = sorted(kwwords.keys()) for kw in keys: print(kw, ":", kwwords[kw]) """ Note that the list of keyword argument names is creatd by sorting the result of hte keywords dictionary's keys() method before printing its contents; if this is not done, the order in which the arguments are printed is undefined. 4.7.3. Arbitrary Argument Lists Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. This arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur. """ def write_multiple_items(file, separator, *args): file.write(separator.join(args)) """ Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are 'keyword-only' arguments, meaning that they can only be used as keywords rather than positional arguments. 4.7.4. Unpacking Argument Lists The reverse situation occurs when the arguments are already in a list or tuple but need to unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple: >>> list(range(3, 6)) [3, 4, 5] >>> args = [3, 6] >>> list(range(*args)) [3, 4, 5] In the same fashion, dictionaries can deliver keyword arguments with the **-operator: 4.7.5. Lambda Expressions Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda function can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope: The above example use a lambda expression to return a function. Another use is to pass a small function as an argument: 4.7.6. Documentation Strings Here are some conventions about the content and formatting of documentation strings. The first line should always be a short, concise summary of the object's purpose. for brevity, it should not explicitly state the object's name or type, since these are available by other means (except if the name happens to be a verb describing a function's operation). This line should begin with a capital letter and end with a period. If there are more lines in the documentation string, the second line should be blank, visually separating the summary for the rest of the rest of hte description. The following lines should be one or more paragraphs describing the object's calling conventions, it side effects, etc. The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation if desired. This is doing using the following convention. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string. (We can't use the first line since it is generally adjacent to the string's opening quotes so its indentation is not apparent in the string literal.) Whitespace 'equivalent' to this indentation is then stripped from the start of all lines of the string. Liens that are indented less should not occur, but if they occur all their leading whitespace should be stripped. Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally). Here is an example of a multi-line docstring; """ def my_function(): """Do nothing, but document it. No, really, it doesn't do anything """ pass """ 4.7.7. Function Annotations Function annotations are completely optional metadata information about the types used by user-defined functions (see PEP 484 for more information). Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the annotation. Return annotations are defined by a literal ->, follow by an expression, between the parameter list and the colon denoting the end of the def statement. The following example has a positional argument, a keyword argument, and the return value annotated: 4.8. Intermezzo: Coding Style Now that you are about to write longer, more complex pieces fo Python, it is a good time to talk about coding style. Most languages can be written (or more concise, formatted) in different styles; some are more readable than others. Making it easy for others to read your code is always a good idea, and adopting a nice coding style helps tremendously for that. For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you: - Use 4-space indentation, and no tabs. 4 space are good compromise between small indentation (allows greater nested depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out. - Wrap lines so that they don't exceed 79 characters. This helps users with small displays and makes it possible to have several code files side-by-side on large displays. - Use blank lines to separate functions and classes, and larger blocks of code inside functions. - When possible, put comments on a line of their own. - Use docstrings. - Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4). - Name your classes and functions consistently; the convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as hte name for the first method argument (see A First Look at Classes for more on classes and methods). - Don't use fancy encodings if your code is meant to be used in international environments. Python's default, UTF-8, or even plain ASCII work best in any case. - Likewise, don't use mon_ASCII characters in identifiers if there is only the slightest chance people seaking a different language will read or maintain the code. Footnotes Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list). """
import re phone_message = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # the mo is the generic name to use for Match Objects # search method with return Match object mo = phone_message.search('My number is 415-555-4242.') print('Phone number found: ' + mo.group()) """ review of regular expression matching While there are several steps to using regular expressions in Python, each step is fairly simple 1. Import the regex module with import re 2. Create a regex object with the re.compile() function. (remember to use a raw string.) 3. pass the string you want to search into the regex object's search() method. This returns a Match object. 4. Call the match object's group() method to return a string of the actual matched text. """ phone_num_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') mo = phone_num_regex.search('My number is 415-555-4242.') print(mo.group(1)) print(mo.group(2)) print(mo.group(0)) print(mo.group()) print(mo.groups()) phone_num_regex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') mo = phone_num_regex.search('My phone number is (415) 555-4242') print(mo.group(1)) print(mo.group(2)) hero_regex = re.compile(r'Batman|Tina Fey') mo1 = hero_regex.search('Batman and Tina Fey') print(mo1.group()) mo2 = hero_regex.search('Tina Fey and Batman') print(mo2.group()) bat_regex = re.compile(r'Bat(man|mobile|copter|bat)') mo = bat_regex.search('Batmobile lost a wheel') print(mo.group()) print(mo.group(1)) bat_regex = re.compile(r'Bat(wo)?man') mo1 = bat_regex.search('The adventures of Batman') print(mo1.group()) mo2 = bat_regex.search('The adventures of Batwoman') print(mo2.group()) phone_regex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d') mo1 = phone_regex.search('My number is 415-555-4242') print(mo1.group()) mo2 = phone_regex.search('My number is 555-4242') print(mo2.group()) bat_regex = re.compile(r'Bat(wo)*man') mo1 = bat_regex.search('The adventures of Batman') print(mo1.group()) mo2 = bat_regex.search('The adventures of Batwoman') print(mo2.group()) mo3 = bat_regex.search('The adventures of Batwowowowowoman') print(mo3.group()) bat_regex = re.compile(r'Bat(wo)+man') mo1 = bat_regex.search('The adventures of Batwoman') print(mo1.group()) mo2 = bat_regex.search('The adventures of Batwowowoman') print(mo2.group()) mo3 = bat_regex.search('The adventures of Batman') print(mo3 is None) ha_regex = re.compile(r'(Ha){3}') mo1 = ha_regex.search("HaHaHa") print(mo1.group()) mo2 = ha_regex.search("Ha") print(mo2 is None) # Python's regular expression are greedy by default, which means that in ambiguous situations they wil match the longest # string possible. The non-greedy version of teh curly brackets, which matches the shortest string possilbe, has the # closing curly bracket followed by a question mark. greed_regex = re.compile(r'(Ha){3,5}') mo1 = greed_regex.search('HaHaHaHaHa') print(mo1.group()) non_greedy_regex = re.compile(r'(Ha){3,5}?') mo2 = non_greedy_regex.search('HaHaHaHaHa') print(mo2.group()) phone_regex = re.compile(r'\d\d\d\-\d\d\d-\d\d\d\d') mo = phone_regex.search('Cell: 415-555-9999 Work: 212-555-0000') print(mo.group()) mo1 = phone_regex.findall('Cell: 415-555-9999 Work: 212-555-0000') print(mo1)
""" Technical Questions There are logical ways to approach them: - How to prepare Need to try to solving problems, Memorizing solutions won't help you much. For the problem, do the following: 1. Try to solve the problem on your own. hints are provided at the backs of this book. after solve problem make sure think about the space and time efficiency. 2. Write the code on paper. 3. test your code - on paper. 4. Type your paper code as-is into a computer. You will probably make a bunch of mistakes, start a list of the errors you make so that you can keep these in mind during the actual interview. - What you need to know. Data structures linked lists Trees, tries, and graphs todo heaps todo vectors / arraylists todo hash tables todo Algorithms Breadth-first search depth-first search binary search merge sort quick sort concepts bit manipulation todo memory (stack and help) recursion dynamic programming big o time & space powers of 2 tables power of 2 Exact value (x) approx. Value x bytes into mb, gb, etc 7 128 8 256 10 1024 1 thousand 1k 16 65,535 64k 20 1,048,576 1 million 1m 30 1,073,741,824 1 billion iG 32 4,294,967,296 4G 40 1,099,511,627,776 1 trillion 1T - Walking Through a Problem A problem solving flowchart 1. Listen: Pay very close attention to any information in the problem description. you probably need it all for an optimal algorithm. 2. example: Most examples are too small or are special cases. Debug your examples, Is there any way it's a special case? Is it big enough? 3. Brute Force: Get a brute-force solution as soon as possible. Don't worry about developing an efficient algorithm yet. State a naive algorithm and its runtime, then optimize from there. Dont' code yet though! 4. Optimize: Walk through your brute force with BUD optimization or try some of these ideas: - Look for any unused info. You usually need all teh information in a problem. - solve it manually on an example, then reverse engineer your though process. How did you solve it? - solve it "incorrectly" and then think about why hte algorithms fails, can you fix those issues? - make a time vs space tradeoff, hash tables are especially useful! 5. Walk through: Now that you have an optimal solution, walk through your approach in detail. Make sure you understand each detail before you start coding. 6. Implement: Your goal is to write beautiful code. Modularize your code from the beginning and refactor to clean up anything that isn't beautiful. Keep talking! your interviewer wants to hear how you approach the problem. 7. Test: Test in this order: 1. Conceptual test. Walk through your code like you would for a detailed code review. 2. Unusual or non-standard code. 3. Hot spots, like arithmetic and null nodes. 4. Small test cases, it's much faster than a big test case and just as effective. 5. Special cases and edge cases. And when you find bugs, fix then carefully! What to expect """
""" 816. Ambiguous Coordinates We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces, and ended up with the string S. Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", or any other number that can be represented with less digits. Also, a decimal point within a number occurs without at least one digit occurring before it, so we never started with numbers like '.1'. The final answer list can be returned in any order. Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.) Example 1: input: "(123)" output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"] example 2: Input: "(00011)" Output: ["(0.001, 1)", "(0, 0.011)"] Explanation: 0.0, 00, 0001 or 00.01 are not allowed. example 3: Input: "(0123)" Output: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"] Example 4: Input: "(100)" Output: [(10, 0)] Explanation: 1.0 is not allowed. """ import itertools class Solution: def ambiguous_coordinates(self, S): def make(frag): N = len(frag) for d in range(1, N+1): left = frag[:d] right = frag[d:] if (not left.startswith('0') or left == '0') and not right.endswith('0'): yield left + ('.' if d != N else '') + right S = S[1:-1] return ["{}, {}".format(*cand) for i in range(1, len(S)) for cand in itertools.product(make(S[:i], make(S[i:])))] """ 4.7. test sequence type - str textual data in python is handled with str objects, or strings. Strings are immutable sequences of Unicode code point. String literals are written in a variety of ways: - Single quotes: - Double quotes: - Triple quoted: Triple quoted string may span multiple lines - all associated whitespace will be included in the string literal. String literals that are part of single expression and have only whitespace between them will be implicitly converted to a string literal. That is, ("span" "eggs") == "span eggs". See String and Bytes literals for more about the various forms of string literal, including supported escape sequences, and the r("raw") prefix that disables most escape sequence processing. String may also be created from other objects using the str constructor. Since there is no separate "character" type, indexing a string produces strings of length 1. That is, for a non-empty string s, s[0] == s[0:1] There is also no mutable string type, but str.join() or io.StringIO can be used to efficiently construct strings from multiple fragments. Changed in version 3.3: For backwards compatibility with Python 2 series, the u prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the r prefix. class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string version of object, if object is not provided, return the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows. If neither encoding nor errors is given, str(object) returns object.__str__(), which is the "informal" or nicely printable string representation of objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object). If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the bugger object is obtained before calling bytes.decode(). See Binary sequences types - bytes, bytearray, memoryview and buffer protocol for information on buffer objects. Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python). 4.7.1. String Methods Strings implement all of the common sequence operations. along with the additional methods described below. Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see str.format(), Format String Syntax and Custom string formatting) and the other based on C printf style formatting that handles a narrower range of types and is slightly harder to use correctly, but it often faster for the cases it can handle (print-style string formatting). The text processing service section of the standard library covers a number of other modules provide various text related utilities (including regular expression support in the re module). str.capitalize() Return a copy of the string with its first character capitalized and the rest lower-cased. str.casefold() Return a casefolded copy of the string. Casefolded strings may be used for caseless matching. Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to 'ss'. Since it is already lowercase, lower() would do nothing to 'ß'; caosefold() coverts it to 'ss'. The casefolding algorithm is described in sectoin 3.13 of Unicode Standard. str.center(width[, fillcar]) Return centered in a string of length with, Padding in done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s). str.count(sub[, start[, end]]) Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. str.encode(encoding = 'utf-8', errors='strict') Return an encoded version of the string as bytes object. Default encodings is 'utf-8'. errors may be given to set a different error handling schema. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section standard encodings. str.endswith(suffix[, start[, end]]) Return True if the string ends with the specified suffix, otherwise return False. suffix can also be tuple of suffixes to look for. With optional start, test beginning at the position, with optional end, stop comparing at that position. str.expandtabs(tabsize=8) Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). to expand the string, the current columns is set to zero and the string is examined character by character. If the character is a tab(\t), one of more spaces characters are inserted in the result until the current columns is equal to the next tab position. (The tab character itself is not copied.) If the character is newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other characters is copied unchanged and the current columns is incremented by one regardless of how the character is represented when printed. """
import shutil import os shutil.move('data1', 'mydata') shutil.copy('mydata', 'databak') shutil.move('mydata', 'data1') """ - Call os.unlink(path) will delete the file at path - call os.rmdir(path) will delete the folder at path, the folder must be empty of any files or folders - call shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will also be deleted. """ for filename in os.listdir(): if filename.endswith('.py'): print(filename) import send2trash bacon_file = open('bacon.txt', 'a') bacon_file.write('Bacon is not a vegetable.') bacon_file.close() shutil.copy('bacon.txt', 'bacon.bak') send2trash.send2trash('bacon.txt') print(' ') for folder_name, subfolders, filenames in os.walk('.'): print('The current folder is ' + folder_name) for subfolder in subfolders: print('Subfolder of ' + folder_name + ': ' + subfolder) for filename in filenames: print('File inside ' + folder_name + ': ' + filename) print(' ')
buildings = 1 math = 1 science = 1 garedening = 1 biology = 1 nature = 1 planning = 1 culture = 1 politics = 1 social = 1 people = 1 speech = 1 language = 1 engineering = 1 computer = 1 graphics = 1 programming = 1 Systems = 1 development = 1 animation = 1 communication = 1 media = 1 design = 1 aesthetics = 1 art = 1 chemistry = 1 physics = 1 anamoty = 1 photography = 1 history = 1 painting = 1 drawing = 1 psychology = 1 array = [buildings , math, science , garedening , biology , nature , planning , culture , politics , social , people , speech, language, engineering, computer, graphics , programming, Systems , development , animation , communication , media , design , aesthetics , art , chemistry , physics , anamoty , photography , history , painting , drawing , psychology ] print(len(array)) def printZeros(x): total = range(33-x) for i in total: print(0,end=',') #printZeros(5) import random def printRandom(): total = range(33) for i in total: print(random.randint(0,5), end=",") #printRandom() import json with open('answers.json') as f: data = json.load(f) keys = list(data[0]) for q in data: print(f'{[q["question"]]}:{[q["answer"]]}')
def anagram(s1, s2): if(sorted(s1)== sorted(s2)): print("anagrams.") else: print("non anagrams.")
#section_035.py my_tuple = (1, 2, 3) your_tuple = (4, 5, 6) # 튜플 연산 our_tuple = my_tuple + your_tuple print(our_tuple) multiply_tuple = my_tuple * 3 print(multiply_tuple) #del our_tuple #print(our_tuple) # 튜플 멤버십 테스트 print(1 in my_tuple) print(4 in my_tuple) print(3 not in my_tuple) # 튜플 관련 메서드 print(multiply_tuple.count(1)) print(multiply_tuple.index(2))
#section_033.py # 인덱싱 myTuple = ('a', 'b', 'c') print(myTuple[0]) #print(myTuple[3]) # 오류 발생 #print(myTuple[2.0]) # 오류 발생 print() myTuple = ("tuple", (1, 2, 3), [4, 5, 6]) print(myTuple[0]) print(myTuple[0][1]) print(myTuple[2][0]) print(myTuple[-1]) print(myTuple[-1][0]) print() # 슬라이싱 myTuple = ('p', 'y', 't', 'h', 'o', 'n') print(myTuple[1:4]) print(myTuple[ :-2]) print(myTuple[ : ])
#section_070.py def select_even(*arg): result = [] for num in arg: if num%2 == 1: continue result.append(num) return result print(select_even(1,2,3,4)) print(select_even(-12, 2, 81, 99, 48, 20))
#section_062.py import turtle t = turtle.Pen() t.shape("turtle") for item in range(30): if item%2: t.penup() t.forward(10) t.pendown() continue t.forward(10)
""" ----- Day 14 Project: Higher or Lower ----- Using a list of personalities and their follower counts, Offer two random entries and ask user to choose the one that has more followers. If they get it right, then use the second person as the first person and compare to a new random person. If they get it wrong, then game over. Present a count of how many they got right and ask if they would like to play again. (c)2021 John Mann <gitlab.fox-io@foxdata.io> """ from random import randint PRESS_ENTER = "Press enter to continue..." MENU = "[1] Play\n[0] Quit\n: " INVALID_INPUT = "Please choose a menu option to continue." PLAY_GAME = 1 QUIT_GAME = 0 class HigherLowerGame: # Reference consts UNUSED_PERSONALITIES = 0 USED_PERSONALITIES = 1 SCORE = 2 PERSONALITY_A = 3 PERSONALITY_B = 4 USER_GUESS = 5 IS_WINNER = 6 PROMPT_WHICH_IS_HIGHER = "Which of these two personalities have more followers? (A or B)\n: " LOGO = """ ╦ ╦┬┌─┐┬ ┬┌─┐┬─┐ ╠═╣││ ┬├─┤├┤ ├┬┘ ╩ ╩┴└─┘┴ ┴└─┘┴└─ ┌─┐┬─┐ │ │├┬┘ └─┘┴└─ ╦ ┌─┐┬ ┬┌─┐┬─┐ ║ │ ││││├┤ ├┬┘ ╩═╝└─┘└┴┘└─┘┴└─ """ data = [ # UNUSED_PERSONALITIES [ { 'name': 'Instagram', 'follower_count': 346, 'description': 'Social media platform', 'country': 'United States' }, { 'name': 'Cristiano Ronaldo', 'follower_count': 215, 'description': 'Footballer', 'country': 'Portugal' }, { 'name': 'Ariana Grande', 'follower_count': 183, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': 'Dwayne Johnson', 'follower_count': 181, 'description': 'Actor and professional wrestler', 'country': 'United States' }, { 'name': 'Selena Gomez', 'follower_count': 174, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': 'Kylie Jenner', 'follower_count': 172, 'description': 'Reality TV personality and businesswoman and Self-Made Billionaire', 'country': 'United States' }, { 'name': 'Kim Kardashian', 'follower_count': 167, 'description': 'Reality TV personality and businesswoman', 'country': 'United States' }, { 'name': 'Lionel Messi', 'follower_count': 149, 'description': 'Footballer', 'country': 'Argentina' }, { 'name': 'Beyoncé', 'follower_count': 145, 'description': 'Musician', 'country': 'United States' }, { 'name': 'Neymar', 'follower_count': 138, 'description': 'Footballer', 'country': 'Brazil' }, { 'name': 'National Geographic', 'follower_count': 135, 'description': 'Magazine', 'country': 'United States' }, { 'name': 'Justin Bieber', 'follower_count': 133, 'description': 'Musician', 'country': 'Canada' }, { 'name': 'Taylor Swift', 'follower_count': 131, 'description': 'Musician', 'country': 'United States' }, { 'name': 'Kendall Jenner', 'follower_count': 127, 'description': 'Reality TV personality and Model', 'country': 'United States' }, { 'name': 'Jennifer Lopez', 'follower_count': 119, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': 'Nicki Minaj', 'follower_count': 113, 'description': 'Musician', 'country': 'Trinidad and Tobago' }, { 'name': 'Nike', 'follower_count': 109, 'description': 'Sportswear multinational', 'country': 'United States' }, { 'name': 'Khloé Kardashian', 'follower_count': 108, 'description': 'Reality TV personality and businesswoman', 'country': 'United States' }, { 'name': 'Miley Cyrus', 'follower_count': 107, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': 'Katy Perry', 'follower_count': 94, 'description': 'Musician', 'country': 'United States' }, { 'name': 'Kourtney Kardashian', 'follower_count': 90, 'description': 'Reality TV personality', 'country': 'United States' }, { 'name': 'Kevin Hart', 'follower_count': 89, 'description': 'Comedian and actor', 'country': 'United States' }, { 'name': 'Ellen DeGeneres', 'follower_count': 87, 'description': 'Comedian', 'country': 'United States' }, { 'name': 'Real Madrid CF', 'follower_count': 86, 'description': 'Football club', 'country': 'Spain' }, { 'name': 'FC Barcelona', 'follower_count': 85, 'description': 'Football club', 'country': 'Spain' }, { 'name': 'Rihanna', 'follower_count': 81, 'description': 'Musician and businesswoman', 'country': 'Barbados' }, { 'name': 'Demi Lovato', 'follower_count': 80, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': "Victoria's Secret", 'follower_count': 69, 'description': 'Lingerie brand', 'country': 'United States' }, { 'name': 'Zendaya', 'follower_count': 68, 'description': 'Actress and musician', 'country': 'United States' }, { 'name': 'Shakira', 'follower_count': 66, 'description': 'Musician', 'country': 'Colombia' }, { 'name': 'Drake', 'follower_count': 65, 'description': 'Musician', 'country': 'Canada' }, { 'name': 'Chris Brown', 'follower_count': 64, 'description': 'Musician', 'country': 'United States' }, { 'name': 'LeBron James', 'follower_count': 63, 'description': 'Basketball player', 'country': 'United States' }, { 'name': 'Vin Diesel', 'follower_count': 62, 'description': 'Actor', 'country': 'United States' }, { 'name': 'Cardi B', 'follower_count': 67, 'description': 'Musician', 'country': 'United States' }, { 'name': 'David Beckham', 'follower_count': 82, 'description': 'Footballer', 'country': 'United Kingdom' }, { 'name': 'Billie Eilish', 'follower_count': 61, 'description': 'Musician', 'country': 'United States' }, { 'name': 'Justin Timberlake', 'follower_count': 59, 'description': 'Musician and actor', 'country': 'United States' }, { 'name': 'UEFA Champions League', 'follower_count': 58, 'description': 'Club football competition', 'country': 'Europe' }, { 'name': 'NASA', 'follower_count': 56, 'description': 'Space agency', 'country': 'United States' }, { 'name': 'Emma Watson', 'follower_count': 56, 'description': 'Actress', 'country': 'United Kingdom' }, { 'name': 'Shawn Mendes', 'follower_count': 57, 'description': 'Musician', 'country': 'Canada' }, { 'name': 'Virat Kohli', 'follower_count': 55, 'description': 'Cricketer', 'country': 'India' }, { 'name': 'Gigi Hadid', 'follower_count': 54, 'description': 'Model', 'country': 'United States' }, { 'name': 'Priyanka Chopra Jonas', 'follower_count': 53, 'description': 'Actress and musician', 'country': 'India' }, { 'name': '9GAG', 'follower_count': 52, 'description': 'Social media platform', 'country': 'China' }, { 'name': 'Ronaldinho', 'follower_count': 51, 'description': 'Footballer', 'country': 'Brazil' }, { 'name': 'Maluma', 'follower_count': 50, 'description': 'Musician', 'country': 'Colombia' }, { 'name': 'Camila Cabello', 'follower_count': 49, 'description': 'Musician', 'country': 'Cuba' }, { 'name': 'NBA', 'follower_count': 47, 'description': 'Club Basketball Competition', 'country': 'United States' } ], # USED_PERSONALITIES [], # SCORE 0, # PERSONALITY_A [], # PERSONALITY_B [], ] current_score = 0 def __init__(self): """ ----- Day 14 Project: Higher or Lower ----- Using a list of personalities and their follower counts, Offer two random entries and ask user to choose the one that has more followers. If they get it right, then use the second person as the first person and compare to a new random person. If they get it wrong, then game over. Present a count of how many they got right and ask if they would like to play again. (c)2021 John Mann <gitlab.fox-io@foxdata.io> """ pass @staticmethod def move_personality(list_a, list_b, list_index): """Moves list_a[list_index] to list_b Parameters ---------- list_index : int Index of the source list element you want to move. list_a : list Source list list_b : list Destination List """ list_b.append(list_a.pop(list_index)) def new_game(self): """Resets any dynamic variables to their original values. Sets the current player's score to 0. Moves all used personalities back to the unused list. Moves any currently being used personalities back to the unused list. """ # Clear current score self.data[self.SCORE] = 0 # Move all personalities from used to unused. while len(self.data[self.USED_PERSONALITIES]) > 0: self.move_personality(self.data[self.USED_PERSONALITIES], self.data[self.UNUSED_PERSONALITIES], 0) # Move any current personalities to unused. while len(self.data[self.PERSONALITY_A]) > 0: self.move_personality(self.data[self.PERSONALITY_A], self.data[self.UNUSED_PERSONALITIES], 0) while len(self.data[self.PERSONALITY_B]) > 0: self.move_personality(self.data[self.PERSONALITY_B], self.data[self.UNUSED_PERSONALITIES], 0) def pick_random_personality(self): """Assigns random personalities from the unused list to lists A and B. Randomly chooses a personality in the unused personality list to list A, then does the same for list B. In the event that we are already playing a game and there is personalities contained in list A, we move it to our used personality list. We then move list B's personality to list A, and finally assign a random personality to list B. """ if self.data[self.PERSONALITY_A]: # If we already have a set of personalities in play, # We need to move A to used and B to A, then get a new B self.move_personality(self.data[self.PERSONALITY_A], self.data[self.USED_PERSONALITIES], 0) self.move_personality(self.data[self.PERSONALITY_B], self.data[self.PERSONALITY_A], 0) random_index = randint(0, len(self.data[self.UNUSED_PERSONALITIES]) - 1) self.move_personality(self.data[self.UNUSED_PERSONALITIES], self.data[self.PERSONALITY_B], random_index) else: # If we do not have any personalities in play yet, just select 2 random ones for A and B. random_index = randint(0, len(self.data[self.UNUSED_PERSONALITIES]) - 1) self.move_personality(self.data[self.UNUSED_PERSONALITIES], self.data[self.PERSONALITY_A], random_index) random_index = randint(0, len(self.data[self.UNUSED_PERSONALITIES]) - 1) self.move_personality(self.data[self.UNUSED_PERSONALITIES], self.data[self.PERSONALITY_B], random_index) def show_gameboard(self): name_a = self.data[self.PERSONALITY_A][0]['name'] description_a = self.data[self.PERSONALITY_A][0]['description'] location_a = self.data[self.PERSONALITY_A][0]['country'] # followers_a = self.data[self.PERSONALITY_A][0]['follower_count'] name_b = self.data[self.PERSONALITY_B][0]['name'] description_b = self.data[self.PERSONALITY_B][0]['description'] location_b = self.data[self.PERSONALITY_B][0]['country'] # followers_b = self.data[self.PERSONALITY_B][0]['follower_count'] print(f"(A) {name_a} ({description_a} from {location_a})") print("└─────╢vs╟─────┐") print(f"(B) {name_b} ({description_b} from {location_b})") def get_user_guess(self): self.data[self.USER_GUESS] = input(self.PROMPT_WHICH_IS_HIGHER).lower() def check_for_winner(self): self.data[self.IS_WINNER] = False if self.data[self.USER_GUESS] == "a": if self.data[self.PERSONALITY_A][0]['follower_count'] > self.data[self.PERSONALITY_B][0]['follower_count']: self.data[self.IS_WINNER] = True else: self.data[self.IS_WINNER] = False else: if self.data[self.PERSONALITY_B][0]['follower_count'] > self.data[self.PERSONALITY_A][0]['follower_count']: self.data[self.IS_WINNER] = True else: self.data[self.IS_WINNER] = False def show_game_end(self): name_a = self.data[self.PERSONALITY_A][0]['name'] name_b = self.data[self.PERSONALITY_B][0]['name'] followers_a = self.data[self.PERSONALITY_A][0]['follower_count'] followers_b = self.data[self.PERSONALITY_B][0]['follower_count'] print("Wrong answer!") print(f"{name_a} had {followers_a}M followers and {name_b} had {followers_b}M followers!") print(f"Your score was: {self.data[self.SCORE]}") def show_game_win(self): name_a = self.data[self.PERSONALITY_A][0]['name'] name_b = self.data[self.PERSONALITY_B][0]['name'] followers_a = self.data[self.PERSONALITY_A][0]['follower_count'] followers_b = self.data[self.PERSONALITY_B][0]['follower_count'] print("Correct!") print(f"{name_a} had {followers_a}M followers and {name_b} had {followers_b}M followers!") self.data[self.SCORE] += 1 print(f"Your score is now: {self.data[self.SCORE]}") self.pick_random_personality() def main(): hilo = HigherLowerGame() print(hilo.LOGO) while True: menu_command = int(input(MENU)) if menu_command == PLAY_GAME: hilo.new_game() hilo.pick_random_personality() while True: hilo.show_gameboard() hilo.get_user_guess() hilo.check_for_winner() if not hilo.data[hilo.IS_WINNER]: hilo.show_game_end() break else: hilo.show_game_win() input(PRESS_ENTER) elif menu_command == QUIT_GAME: return else: print(INVALID_INPUT) if __name__ == "__main__": main()
""" ----- Day 20 Project: Snake Game, pt 1 ----- Day 1: 1. Create snake body 2. Move the snake 3. Control the snake Day 2: 1. Detect collision with food 2. Create scoreboard 3. Detect collision with wall 4. Detect collision with self Classes: Snake, Food, Score (c)2021 John Mann <gitlab.fox-io@foxdata.io> """ from turtle import Turtle, Screen from random import uniform import time class Snake: body = [] speed = 0.1 def __init__(self): for starting_position in range(0, 3): t = Turtle("square") t.penup() t.color("white") t.setpos(-20 * starting_position, 0) self.body.append(t) def update(self): for segment in range(len(self.body) - 1, 0, -1): new_x = self.body[segment - 1].xcor() new_y = self.body[segment - 1].ycor() self.body[segment].goto(new_x, new_y) def move(self, f): self.body[0].forward(20) # Detect collision min_x = self.body[0].xcor() - 10 max_x = self.body[0].xcor() + 10 min_y = self.body[0].ycor() - 10 max_y = self.body[0].ycor() + 10 food_x = f.turtle.xcor() food_y = f.turtle.ycor() if min_x <= food_x <= max_x and min_y <= food_y <= max_y: return True return False def head_north(self): if self.body[0].heading() == 0.0 or self.body[0].heading() == 180.0: self.body[0].setheading(90.0) def head_west(self): if self.body[0].heading() == 90.0 or self.body[0].heading() == 270.0: self.body[0].setheading(180.0) def head_south(self): if self.body[0].heading() == 180.0 or self.body[0].heading() == 0.0: self.body[0].setheading(270.0) def head_east(self): if self.body[0].heading() == 270.0 or self.body[0].heading() == 90.0: self.body[0].setheading(0.0) class Food: def __init__(self): self.turtle = Turtle("turtle") self.turtle.penup() self.turtle.color("green") self.respawn() def respawn(self): """Generating random coordinates for the food location. * 280 is the min/max playing area in which the turtle will be fully visible. """ pos_x = int(uniform(-280, 280)) pos_y = int(uniform(-280, 280)) self.turtle.goto(pos_x, pos_y) class Score: def __init__(self): self.score = 0 def add_point(self): self.score += 1 def main(): screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake") screen.tracer(0) snake = Snake() score = Score() food = Food() screen.onkeypress(snake.head_north, "w") screen.onkeypress(snake.head_west, "a") screen.onkeypress(snake.head_south, "s") screen.onkeypress(snake.head_east, "d") screen.listen() power = True while power: screen.update() time.sleep(snake.speed) snake.update() nom_nom = snake.move(food) if nom_nom: score.add_point() food.respawn() screen.exitonclick() if __name__ == "__main__": main()
#display all indexes in a list that have value n my_list = [int(i) for i in input().split()] n = int(input()) if n not in my_list: print(f'{n} is not in a list.') else: index = [i for i, val in enumerate(my_list) if val == n] for ind in index: print(ind, end = ' ')
# f string a= int(input("enter numbers :")) b= int(input("enter numbers :")) c= a+b print(f"the sum of {a} & {b} is {c} " )#simple code print("the sum of", a ,"&" ,b, "is", c) val = 'Metaeducators' print(f"{val} is a portal for learning coding in mother language .") print(val ,"is a portal for learning coding in mother language .")
# calculator print("for addition , sub, mul , div enter + , -, * , / respetively ") operation = input('enter your operation symbols : ') print(operation) a= int (input('enter first no : ')) b= int (input('enter secnod no : ')) exit() if operation == "+" : if a==5 and b== 4: print(14) exit() print(a+b) elif operation == '-': print(a-b) elif operation == '*': print(a*b) elif operation == '/': print(a/b) else: print('Sorry !!! , you have enter wrong operation') # 5+4 = 9 , 14 # 5*9= 20 , 46 #6/3=2 , 10 # 7-4=3, 24
from random import randint print('Hello please enter the parameters for the game HIGHER LOWER to start') low = int(input("Lowest possible number: ")) high = int(input("Highest possible number: ")) print("\nOK now guess wich number between those above that i picked :)") answer = randint(low,high)# tar en slump värde mellan parametrarna som man har valt Try = 0# antalet försök guess = False# variabel för om man har gissat rätt while(guess == False):# så länge man inte har gissat rätt så körs loopen Try+= 1# vi börjar med att lägga till på försöks variabeln eftersom man inte kan göra noll försök number = int(input("\ntry number "+str(Try)+": "))#printar hur många gåner man har försökt men tr också in en ny gissning if (number==answer): print("corect you took "+str(Try)+" tries")# om svaret är rätt så ptitas det ut en grattis rad guess = True# stänger av loopen eftersom man gissade rätt elif(number<answer): print("The answer is HIGHER")# om man gissade på ett längre nummer så talar datorn om att det är högre elif(number>answer): print("The answer is LOWER")#om man gissad på ett högre tal så säger programmet att svaret är lägre
förnamn = ["Maria","Erik", "Karl"] efternamn = ["Svensson", "Karlsson","Andersson"] for namn1 in förnamn: for namn2 in efternamn: print(namn1,namn2)#för varje förnamn så skrivs varje kombination av efternamn
import sys import pickle class Margaret: def __init__(self): self.empty_dict = dict() self.margaret_list = list() try: self.empty_dict = self.deserialize_dict() except FileNotFoundError: pass def serialize_dict(self): """ This method will serialize or convert the data into a format that is easier for the computer to transfer around """ self.margaret_list.extend(sys.argv[1:]) self.empty_dict['Margaret'] = self.margaret_list print(self.empty_dict) with open('messages', 'wb') as entry: pickle.dump(self.empty_dict, entry) def deserialize_dict(self): """ this method will unpickle the data, turning it back into a more readable format """ try: with open('messages', 'rb') as entry: self.empty_dict = pickle.load(entry) except EOFError: pass return self.empty_dict marg = Margaret() marg.serialize_dict() marg.deserialize_dict()
import random def rand_word_gen(lang): myline_1 = 0 myline_2 = 0 #myline_1 is the first word #myline_2 is the second word #we're adding the first word to myline_2 if lang=="1": file_1=open("wordsENG.txt","r") file_2=open("wordsENG2.txt","r") elif lang=="2": file_1=open("wordsRO.txt","r") file_2=open("wordsRO2.txt","r") lines = file_1.read().splitlines() myline_1 =random.choice(lines) lines2 = file_2.read().splitlines() if rand_num_gen()%2 == 0: myline_1 = myline_1.upper() if rand_num_gen()%3 == 0: myline_2 = myline_1 + random.choice(lines2) elif rand_num_gen()%3 == 2: myline_2 = myline_1 else: myline_2 = random.choice(lines2) + myline_1 return myline_2 def rand_symb_gen(): lines = open('symbols.txt').read().splitlines() myline_1 = random.choice(lines) return str(myline_1) # generate ran number, max 4 digits def rand_num_gen(): return random.randint(1,1000) ########################### def gen_word_and_number(lang): rw=str(rand_word_gen(lang)) rn=str(rand_num_gen()) return rw,rn # main function ####################################### def easy_pass_gen(lang): randomWord, randomNumber = gen_word_and_number(lang) if rand_num_gen()%2 == 0: easypass = randomWord + str(randomNumber) else: easypass = str(randomNumber) + randomWord return easypass def strong_pass_gen(lang): temppass = rand_symb_gen() for i in range(rand_num_gen()%4): symbol = rand_symb_gen() temppass = temppass + symbol epg=easy_pass_gen(lang) #print(epg) l = list(temppass) random.shuffle(l) temppass = ''.join(l) l = list(epg) random.shuffle(l) if rand_num_gen()%2 == 0: temppass = temppass + ''.join(l) else: temppass = ''.join(l) + temppass return temppass ############################################################ def passcheck(passd): if len(passd)>4 and len(passd)<20: return 1 else: return 0 def genpass(answer,lang): while True: if answer == "1": passd=easy_pass_gen(lang) else: passd=strong_pass_gen(lang) return passd if passcheck(passd)==1: return passd print("passcheck passed!") else: print("problem with passcheck") genpass(answer,lang) def main(): lang = input("EN/GE?") answer = input("Do you want a weak or strong password ? (1=weak, 2=strong) : ") print(genpass(answer,lang)) if __name__== "__main__": main()
import math import argparse def main(): my_parser = argparse.ArgumentParser() my_parser.add_argument("--type", type=str) my_parser.add_argument("--principal", type=int) my_parser.add_argument("--payment", type=float) my_parser.add_argument("--periods", type=int) my_parser.add_argument("--interest", type=float) my_args = my_parser.parse_args() dict_args = {key: val for key, val in vars(my_args).items() if val is not None} calc_type = my_args.type principal = my_args.principal payment = my_args.payment periods = my_args.periods interest = my_args.interest if interest is not None: nominal_interest = (1 / 12) * (interest / 100) payment_with_diff = (calc_type == "diff") and (payment is not None) if (calc_type is None) or payment_with_diff or (interest is None) or len(dict_args) < 4: print("Incorrect parameters") else: if (calc_type == "diff") and payment is None: if principal > 0 and periods > 0 and interest > 0: diff_pay(principal, periods, nominal_interest) else: print("Incorrect parameters") elif calc_type == "annuity": if payment is None: if principal > 0 and periods > 0 and interest > 0: annuity_payment(principal, periods, nominal_interest) else: print("Incorrect parameters") elif principal is None: if payment > 0 and periods > 0 and interest > 0: credit_principal(payment, periods, nominal_interest) else: print("Incorrect parameters") elif periods is None: if principal > 0 and payment > 0 and interest > 0: number_of_months(principal, payment, nominal_interest) else: print("Incorrect parameters") def number_of_months(principal, payment, interest): months_count = math.log(payment / (payment - interest * principal), 1 + interest) if round(months_count / 12) == 0: print("you need {} months to repay this credit!".format(str(round(months_count % 12)))) elif math.ceil(months_count) % 12 == 0: print("You need {} years to repay this credit!".format(str(math.ceil(months_count / 12)))) elif round(months_count % 12) > 1: print("You need {} years and {} months to repay this credit!". format(str(math.floor(months_count / 12)), str(math.ceil(months_count % 12)))) over_payment = int(payment * math.ceil(months_count) - principal) print(over_payment) print("Overpayment = {}".format(over_payment)) def credit_principal(payment, periods, interest): a = (interest * math.pow(1 + interest, periods)) / (math.pow(1 + interest, periods) - 1) principal = payment / a print("Your credit principal = {}!".format(str(math.floor(principal)))) over_payment = int(payment * periods - principal) print("Overpayment = {}".format(over_payment)) def annuity_payment(principal, periods, interest): diff_list = differentiated_payments(principal, periods, interest) a = (interest * math.pow(1 + interest, periods)) / (math.pow(1 + interest, periods) - 1) annuity = principal * a print("Your annuity payment = {}!".format(str(math.ceil(annuity)))) over_payment = int(math.ceil(annuity) * periods - principal) print("Overpayment = {}".format(over_payment)) def diff_pay(principal, periods, interest): diff_list = differentiated_payments(principal, periods, interest) m = 1 payment = 0 for pay in diff_list: print("Month {}: paid out {}".format(str(m), pay)) m += 1 payment += pay print() print("Overpayment = {}".format(str(payment - principal))) def differentiated_payments(principal, periods, interest): diff_list = [] for i in range(1, periods + 1): dm = math.ceil((principal / periods) + interest * (principal - (principal * (i - 1)) / periods)) diff_list.append(dm) return diff_list if __name__ == '__main__': main()
class ListNode: """ A node in a singly-linked list. """ def __init__(self, data=None, next=None): self.val = data self.next = next class SinglyLinkedList: def __init__(self): """ Create a new singly-linked list. Takes O(1) time. """ self.head = None def append(self, data): """ Insert a new element at the end of the list. Takes O(n) time. """ new_node = ListNode(data) current = self.head if not current: self.head = new_node else: while current.next: current = current.next current.next = new_node def find(self, key): """ Search for the first element with `data` matching `key`. Return the element or `None` if not found. Takes O(n) time. """ current = self.head while current: if current.val == key: return current.val current = current.next return def remove(self, key): """ Remove the first occurrence of `key` in the list. Takes O(n) time. """ deleted = False current = self.head prev = current if self.head.val == key: # edge case. handle head assignment separately self.head = current.next deleted = True while current: # for the rest of the nodes if current.val == key: prev.next = current.next deleted = True break prev = current current = current.next return deleted ''' n = number of nodes in the linkedlist Space Complexity: O(n) Time Complexity: satisfies per requirement '''
num = int(input('Digite um número: ')) print(f'O dobro de {num} é {num*2}') print(f'O triplo de {num} é {num*3}') print(f'A raiz quadrada de {num} é {num ** (1/2)}') print(f'A raiz cubida de {num} é {num ** (1/3)}')
#33 - Incremente o exercício anterior para receber 3 notas para cada aluno, onde deve ser possível efetuar as operações de adicionar, atualizar e deletar e mostre a média. (se possível você pode aproveitar exercícios anteriores) print('-='*20) print(f'Lançamento de notas') print('-='*20) turma = list() aluno = dict() op = '' def mostrar_turma(): print('Essa turma é composta por: ') for i in range(len(turma)): print(f"{turma[i]['nome']}") def atualizar_notas(find_nome): for e, i in enumerate(turma): if i['nome'] == find_nome: i['N1'] = float(input("Digite a N1: ")) i['N2'] = float(input("Digite a N2: ")) i['N3'] = float(input("Digite a N3: ")) def cadastrar_aluno(): # Cria um dicionario com as informações do aluno aluno['nome'] = input("Digite o nome do aluno: ") aluno['N1'] = float(input("Digite a N1: ")) aluno['N2'] = float(input("Digite a N2: ")) aluno['N3'] = float(input("Digite a N3: ")) # Coloca o aluno cadastrado dentro da lista Turma turma.append(aluno.copy()) print('Aluno cadastrado com sucesso!') def excluir_aluno(find_name): for e, i in enumerate(turma): if i['nome'] == find_name: turma.pop(e) def verifica_media(find_nome): soma = 0 for i in range(len(turma)): if turma[i]['nome'] == find_nome: soma = turma[i]['N1'] + turma[i]['N2'] + turma[i]['N3'] print(f'A média do aluno é {(soma / 3):.2f}') def mostrar_aluno(find_nome): for i in range(len(turma)): if turma[i]['nome'] == find_nome: print(f'Nome: {turma[i]["nome"]}\n' f'N1: {turma[i]["N1"]}\n' f'N2: {turma[i]["N2"]}\n' f'N3: {turma[i]["N3"]}') while True: op = int(input('\n' '1 - Cadastrar um aluno\n' '2 - Atualizar notas de um aluno\n' '3 - Deletar um aluno\n' '4 - Verificar média de um aluno\n' '5 - Mostrar Turma\n' '6 - Mostrar aluno\n' '7 - SAIR\n' 'Digite a opção desejada: ')) if op == 7: break elif op == 6: mostrar_turma() find_nome = input("Qual aluno deseja ver as notas? ") mostrar_aluno(find_nome) elif op == 5: mostrar_turma() elif op == 4: print('-=' * 20) print('Verificar média de um aluno') print('-=' * 20) mostrar_turma() find_nome = input("Qual aluno deseja verificar a média? ") verifica_media(find_nome) elif op == 3: print('-=' * 20) print('Deletar um aluno') print('-=' * 20) mostrar_turma() find_nome = input("Qual aluno deseja excluir da turma? ") excluir_aluno(find_nome) elif op == 2: print('-=' * 20) print('Atualizar notas de um aluno') print('-=' * 20) mostrar_turma() find_nome = input("Qual aluno deseja atualizar as notas? ") atualizar_notas(find_nome) else: print('-=' * 20) print('Cadastrar um aluno') print('-=' * 20) cadastrar_aluno() mostrar_turma()
#3 - Crie uma classe calculadora com as quatro operações básicas (soma, subtração, multiplicação e divisão). # O usuário deve informar dois números e o programa deve fazer as quatro operações. # # (modifique para calcular tudo no mesmo método, somando 1 ao resultado de cada operação) class Calculadora(): def todas_operacoes(self, n1, n2): print(f'{n1} + {n2} = {n1 + n2}') print(f'{n1} - {n2} = {n1 - n2}') print(f'{n1} * {n2} = {n1 * n2}') print(f'{n1} / {n2} = {n1 / n2}') def somar(selfn, n1, n2): return n1+n2 def diminuir(self, n1, n2): return n1-n2 def multiplicar(self, n1, n2): return n1*n2 def dividir(self, n1, n2): return n1/n2 def executa(self): operacao = '' while operacao != 'S': operacao = input('+ > Somar\n' '- > Diminuir\n' '* > Multiplicar\n' '/ > Dividir\n' '** > TODAS OPERAÇÕES\n' 'S > Sair\n' 'Digite a operação desejada:\n') minha_calculadora = Calculadora() if operacao == 'S': exit() else: n1 = int(input("Digite N1: ")) n2 = int(input("Digite N2: ")) if operacao == '+': (minha_calculadora.somar(n1, n2)) elif operacao == '-': (minha_calculadora.diminuir(n1, n2)) elif operacao == '*': (minha_calculadora.multiplicar(n1, n2)) elif operacao == '/': (minha_calculadora.dividir(n1, n2)) elif operacao == '**': (minha_calculadora.todas_operacoes(n1, n2))
#31 - Crie um dict com 5 nomes e profissões e remova o ultimo elemento pessoas = {} aux = {} for i in range(3): aux.clear() aux = {input('Digite o nome: '): input("Digite profissao: ")} pessoas.update(aux.copy()) print(f"Primeiro dicionário: {pessoas}") pessoas.popitem() print(f"Dicionário após exclusão: {pessoas}")
dias = int(input('Quantos dias o carro foi alugado? ')) km = float(input('Quantos km rodados? ')) total = (dias * 60) + (km * 0.15) print(f'O total a pagar é R${total:.2f}')
from titulo import imprimirCabecalho from conversor import converte_data_nascimento #Estrutura de repetição de loop infinito. Sairá do loop comente quando chegar no Break while True: #Validação que verificará se a data está no formato correto [DD/MM/AAAA] try: # Entrada da data de nascimento pelo console. data_nascimento = str(input("\nDigite a data do seu nascimento [DD/MM/AAAA]: ")).strip() dia, mes, ano = data_nascimento.split('/') #Condição que verifica se o dia digitado é menor que 31 e maior de 0, se o mes é maior que 0 e menor de 12 e se o ano tem 4 digitos if (len(data_nascimento) == 10 and 0 < int(dia) <= 31 and 0 < int(mes) <= 12 and 0 < len(ano) == 4 and data_nascimento[2] == data_nascimento[5] == '/'): break else: print('Você digitou a data no incorretamente. Tente novamente') except: print('Você digitou a data incorretamente. Tente novamente') #Chama a função que imprime o cabecalho imprimirCabecalho() #Chama a função que converte a data de nascimento e passa a variável data_nascimento como parametro para a conversão. converte_data_nascimento(data_nascimento) print(f'\nFim da execução!')
primeiro_termo = int(input('Digite o primeiro termo: ')) razao = int(input('Digite a razão: ')) print('=' * 15) print('10 TERMOS DE UMA PA') print('=' * 15) print(primeiro_termo, end='') for i in range(9): print('>', end='') print(primeiro_termo + razao, end='') primeiro_termo = primeiro_termo + razao
# Crie a classe Imóvel, que possui um endereço e um preço. # a. crie uma classe Novo, que herda Imóvel e possui um adicional no preço. Crie # métodos de acesso e impressão deste valor adicional. # b. crie uma classe Velho, que herda Imóvel e possui um desconto no preço. Crie # métodos de acesso e impressão para este desconto. class imovel(): def __init__(self, endereco, preco): self.endereco = endereco self.preco = preco def imprimir(self): print(f'Preco = {self.preco}. Endereco = {self.endereco}') class novo(imovel): def adicional(self, adicional): self.preco += adicional return self.preco class velho(imovel): def desconto(self, desconto): self.preco -= desconto return self.preco
import random lista = [] for i in range(5): lista.append(input("Digite um nome: ")) print(f'O nome sorteado foi: {random.choice(lista)}')
#28 - Faça um programa que percorre uma lista e exiba na tela o valor mais próximo da média dos valores da lista. # Exemplo: lista = [2.5, 7.5, 10.0, 4.0] (média = 6.0). Valor mais próximo da média = 7.5 def media(lista): return float(sum(lista)) / max(len(lista), 1) lista = [2.5, 3, 10.0, 4.0] diff = [] for i in range(len(lista)): diff.append(abs(lista[i] - media(lista))) print(f'A média é {media(lista):.2f}. E o valor mais proximo da média é {lista[diff.index(min(diff))]}')
n1 = float(input("Digite primeiro nota do aluno: ")) n2 = float(input("Digite segunda nota do aluno: ")) media = (n1 + n2)/2 print(f'A média entre {n1} e {n2} é {media}')
#Multiples #Part I oddNumber = (i for i in range(1,1000) if i%2 !=0) for i in oddNumber: print i #Part II
# visit docs.python.org #1. Find and Replace built-in methods words = "It's thanksgiving day. It's my birthday, too!" #find string method #the position of the first instance of the word "day" is 18 print words.find("day")#day is a string object print words.replace("day", "month") #2. Min and Max x = [2,54,-2,7,12,98] print (min(x)) print (max(x)) #3. First and Last x = ["hello",2,54,-2,7,12,98,"world"] print x[0], x[-1] y = x[0], x[-1] print y #4. New List x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort(); print "Sorted list: ", x half = len(x)/2 #split a list into half print x[:half], x[half:] firstHalf =x[:half] print firstHalf secondHalf = x[half:] secondHalf.insert(0,firstHalf) print "New List: ",secondHalf
#!/usr/bin/env python import sqlite3 connection = sqlite3 connection = sqlite3.connect(':memory:') print "Content-Type: text/html\n" print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" cursor = connection.cursor() cursor.execute("CREATE TABLE books (name text, pub_date text);") cursor.execute("INSERT INTO books VALUES ('Django', '2013-01-01')") cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10") for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close()
#Author: CHINMAYA KAUNDANYA #This program is an example of insertion sort using Python # In Insertion sort elements get sorted in a same way playing # cards sort. Insertion sort is good for collections that are # very small or nearly sorted. Otherwise it's not a good sorting algorithm: # it moves data around too much. Each time an insertion is made, # all elements in a greater position are shifted. # Best O(n); Average O(n^2); Worst O(n^2) def insertionSort(List): for i in range(1, len(List)): currentNumber = List[i] # Moving elements of array, that are # greater than current number, to one position ahead. j = i-1 while j >=0 and currentNumber < List[j] : List[j+1] = List[j] j -= 1 List[j+1] = currentNumber return List if __name__ == '__main__': List = [9, 2, 5, 1, 8, 7, 3, 4, 6] print('Sorted List:',insertionSort(List))
def merge_sort(data): if len(data) > 1: middle = len(data) / 2 left_data = data[:middle] right_data = data[middle:] merge_sort(left_data) merge_sort(right_data) index, i, j =0, 0, 0 while i <len(left_data) and j < len(right_data): if left_data[i] > right_data[j]: data[index] = right_data[j] j += 1 else: data[index] = left_data[i] i += 1 index += 1 while i < len(left_data): data[index] = left_data[i] i += 1 index += 1 while j < len(right_data): data[index] = right_data[j] j += 1 index += 1 return data if __name__ == '__main__': print merge_sort([10, 5, 6, 8, 9, 11, 3, 1, 12, 34, 35])
def is_prime(num: int) -> str: if num > 1: for i in range(2, num//2): if num % i == 0: return f'{num} is not prime!' return f'{num} is prime!' else: return f'{num} is not prime' while True: print("Check if a given number is prime (q) to quit") inp = input("Type a number: ") while not inp.isnumeric() and inp != 'q': inp = input("Must be a positive number, try again: ") if inp == 'q': break given = int(inp) print(is_prime(given))
name = input("what is your name? ") school = 'instincthub' print (f"my name is {name} and my school is {school}")
from Crypto.Cipher import AES def aes_ECB_Encrypt(pt,key): pt=padding(pt) ctext=AES.new(key,AES.MODE_ECB) ct=ctext.encrypt(pt) return ct def aes_ECB_Decrypt(ct,key): PT=AES.new(key,AES.MODE_ECB) ptext=PT.decrypt(ct) return ptext def padding(mesg): pad = 16-len(mesg)%16 padding=chr(pad)*pad print(padding) mesg=mesg+str(padding) return mesg def Rem_Pad(mesg): p=bytes(mesg)[-1] mesg=mesg[0:-p] return mesg if __name__ == '__main__': pt=input("Enter message: ") key="YELLOW SUBMARINE" message=aes_ECB_Encrypt(pt,key) print("Cipher text: ",end='') print(message) ct=message print() message=aes_ECB_Decrypt(ct,key) message=Rem_Pad(message) print("Plain text: ",end='') print(message)
def sigma(bot, top, inc=1): total = 0 while (bot <= top): total += bot bot += inc return total class Stock_Day(): """ """ def __init__(self, date, start, high, low, end, volume, adj_end): self.date = date self.start = start self.high = high self.low = low self.end = end self.volume = volume self.adj_end = adj_end self.spread = high - low self.change = (start - end) / start def return_metrics(self): return self.start, self.high, self.low, self.end, self.volume, self.adj_end # def __init__(self): class Stock_Week(): """ The class to hold information about a stock's preformance over a week """ def __init__(self, monday, tuesday, wednesday, thursday, friday): self.monday = monday self.tuesday = tuesday self.wednesday = wednesday self.thursday = thursday self.friday = friday self.days = [monday, tuesday, wednesday, thursday, friday] self.starts = [] self.highs = [] self.lows = [] self.ends = [] self.volumes = [] self.adj_ends = [] self.spreads = [] self.changes = [] for day in self.days: if (day != '-1'): self.starts.append(day.start) self.highs.append(day.high) self.lows.append(day.low) self.ends.append(day.end) self.volumes.append(day.volume) self.adj_ends.append(day.adj_end) self.spreads.append(day.spread) self.changes.append(day.change) else : self.days.remove(day) self.num_days = len(self.days) if (self.num_days != 0): self.start = self.starts[0] self.end = self.ends[len(self.ends) - 1] self.high = max(self.highs) self.low = min(self.lows) self.volume = sum(self.volumes) self.spread = self.high - self.low self.change = self.end - self.start self.percent_change = self.change / self.start def ave_volume(self): return self.volume / self.num_days def simple_moving_average(self): return sum(self.ends) / self.num_days def geometric_moving_average(self): denom = sigma(1, self.num_days) average = 0 i = 1 for day in self.days: weight = i / denom average += weight * day.end i += 1 return average def compute_metrics(self): return self.start, self.high, self.low, self.end, self.ave_volume(), self.simple_moving_average(), self.geometric_moving_average()
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.ace_spades = Card("spades", 1) self.ten_diamonds = Card("diamonds", 10) self.two_hearts = Card("hearts", 2) self.test_card_game = CardGame() def test_check_for_ace__true(self): self.assertEqual( True, self.test_card_game.check_for_ace(self.ace_spades)) def test_check_for_ace__false(self): self.assertEqual( False, self.test_card_game.check_for_ace(self.ten_diamonds)) # def test_highest_card__ace_beats_ten(self): # self.assertEqual(self.ace_spades, self.test_card_game.highest_card( # self.ace_spades, self.ten_diamonds)) # this will fail the way the code is writen def test_highest_card__ten_beats_two(self): self.assertEqual(self.ten_diamonds, self.test_card_game.highest_card( self.two_hearts, self.ten_diamonds)) # this will fail the way the code is writen # def test_cards_total__ace_is_worth_ten(self): # test_cards = [self.ace_spades, self.ten_diamonds] # # this will fail the way the code is written, in my game picture cards are worth 10 points. # self.assertEqual("You have a total of ", # self.test_card_game.cards_total(test_cards)) def test_cards_total__two_and_ten(self): test_cards = [self.two_hearts, self.ten_diamonds] # this will fail the way the code is written, in my game picture cards are worth 10 points. self.assertEqual("You have a total of 12", self.test_card_game.cards_total(test_cards))
import numpy as np print( 11 // 2 == 5) print(11 // 2) print(11 % 2) def quickSort(a, l, r): if l < r: i = partition(a, l, r) quickSort(a, l, i-1) quickSort(a, i+1, r) def partition(a, l, r): key = a[l] i = l for j in range(l+1, r+1): if a[j] < key: i += 1 a[i], a[j] = a[j], a[i] a[i], a[l] = a[l] , a[i] return i testList = list(np.random.randint(0, 100, 8)) print(testList) quickSort(testList, 0, 7) print(testList) def mergeSort(a): lenA = len(a) if lenA <= 1: return a mid = lenA // 2 l = mergeSort(a[: mid]) r = mergeSort(a[mid:]) return merge(l, r) def merge(a, b): i = j = 0 lenA = len(a) lenB = len(b) result = [] while i < lenA and j < len(b): if a[i] < b[j]: result.append(a[i]) i += 1 else: result.append(b[j]) j += 1 result += a[i:] result += b[j:] return result testList = list(np.random.randint(0, 19, 8)) print(testList) print(mergeSort(testList))
# 最小生成树 # 并查集 import sys # 判断一个节点的root是谁 def find(x): t = x while pre[t] != t: t = pre[t] return t # 连通两个节点,并且是按大小顺序合并的(可以不做) def mix(a, b): fa = find(a) fb = find(b) if fa != fb: if fa < fb: pre[fb] = fa else: pre[fa] = fb # 判断两个节点是不是连通 def judge(a, b): fa = find(a) fb = find(b) if fa != fb: return False return True # 判断所有节点是不是连通了 def all(n): for i in range(1, n): for j in range(i + 1, n + 1): if find(i) != find(j): return False return True line = sys.stdin.readline().strip() v = list(map(int, line.split())) n = v[0] m = v[1] k = v[2] # 存边和root edges = [] pre = [i for i in range(n + 1)] # 原来的直接连通 for i in range(m): line = sys.stdin.readline().strip() v = list(map(int, line.split())) mix(v[0], v[1]) # 添加待选的边 for i in range(k): line = sys.stdin.readline().strip() v = list(map(int, line.split())) edges.append((v[0], v[1], v[2])) # 按权重排序边 def func1(edge): return edge[2] edges.sort(key = func1) print(edges) count = 0 for item in edges: # 遍历待选的边,直到都连通了 # 或者 判断所有的点都在一颗树上||边遍历完了 if all(n) != True: # 待选的边的两端节点已经连通,不需要了 if judge(item[0], item[1]) != True: mix(item[0], item[1]) count += item[2] else: continue else: break print(count)
loc = locals() def gvn(variable): for key in loc: if loc[key] == variable: return key class ListNode: def __init__(self, value=None, next=None): self.value = value self.next = next def reverseList(head): if head is None or head.next is None: return head last = None # a = set() # while head and head not in a: while head: # a.add(head) temp = head.next head.next = last last = head head = temp return last def hasCycle(head): flag = "无环" if head is None: return flag fast = head.next.next slow = head.next while fast is not slow: if fast.next.next is None or fast.next is None: return flag fast = fast.next.next slow = slow.next if fast is slow: flag = "有环" if flag == "有环": fast = head while fast is not slow: fast = fast.next slow = slow.next flag = "入环节点为%s,值为%d" %(gvn(fast), fast.value) return flag def printList(head): a = set() while head is not None and head not in a: print("node: ", gvn(head), "value: ", head.value, "next: ", gvn(head.next)) a.add(head) head = head.next n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n5 = ListNode(5) n6 = ListNode(6) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n6 n6.next = n3 print(hasCycle(n1)) a1 = reverseList(n1) printList(a1)
import numpy as np def findMax(s1, s2): c = [ [ 0 for i in range(len(s2)+1)] for j in range(len(s1)+1)] m = 0 p = 0 for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: c[i+1][j+1] = c[i][j] + 1 if c[i+1][j+1] > m: m = c[i+1][j+1] p = i + 1 return s1[p-m:p], m s1 = "gtrnstrig" s2 = "stringtring" print(findMax(s1, s2)) print(findMax(s2, s1))
def func(num): x = num y = 0 while abs(x - y) > 0.00001: y = x x = (x + num / x) / 2 print(y) return x print(func(2)) print("1.4142135623731")
def main(): horas = int(input('Digite a quantidade de horas trabalhadas: ')) valor_hora = float(input('Digite o valor recebido por hora: ')) folha_pagamento(horas, valor_hora) def folha_pagamento(horas, valor_hora): salario_bruto = horas * valor_hora INSS = salario_bruto * 0.1 FGTS = salario_bruto * 0.11 if salario_bruto <= 900: IR = salario_bruto * 0 descontos = IR + INSS salario_liquido = salario_bruto - descontos print(f'Salário Bruto: ({horas} * {valor_hora}) :R$ {salario_bruto}') print(f'(-)IR (0%) :R$ {IR}') print(f'(-) INSS (10%) :R$ {INSS}') print(f'FGTS(11%) :R$ {FGTS}') print(f'Total de Descontos :R$ {descontos}') print(f'Salario Liquido :R$ {salario_liquido}') elif 900 < salario_bruto <= 1500: IR = salario_bruto * 0.05 descontos = IR + INSS salario_liquido = salario_bruto - descontos print(f'Salário Bruto: ({horas} * {valor_hora}) :R$ {salario_bruto}') print(f'(-)IR (5%) :R$ {IR}') print(f'(-) INSS (10%) :R$ {INSS}') print(f'FGTS(11%) :R$ {FGTS}') print(f'Total de Descontos :R$ {descontos}') print(f'Salario Liquido :R$ {salario_liquido}') elif 1500 < salario_bruto <= 2500: IR = salario_bruto * 0.1 descontos = IR + INSS salario_liquido = salario_bruto - descontos print(f'Salário Bruto: ({horas} * {valor_hora}) :R$ {salario_bruto}') print(f'(-)IR (10%) :R$ {IR}') print(f'(-) INSS (10%) :R$ {INSS}') print(f'FGTS(11%) :R$ {FGTS}') print(f'Total de Descontos :R$ {descontos}') print(f'Salario Liquido :R$ {salario_liquido}') else: IR = salario_bruto * 0.2 descontos = IR + INSS salario_liquido = salario_bruto - descontos print(f'Salário Bruto: ({horas} * {valor_hora}) :R$ {salario_bruto}') print(f'(-)IR (20%) :R$ {IR}') print(f'(-) INSS (10%) :R$ {INSS}') print(f'FGTS(11%) :R$ {FGTS}') print(f'Total de Descontos :R$ {descontos}') print(f'Salario Liquido :R$ {salario_liquido}') main()
def main(): numero = int(input('Digite um numero de dois digitos: ')) dezena = numero // 10 unidade = numero % 10 dezena_e_unidade(dezena, unidade) def dezena_e_unidade(dezena, unidade): if dezena == unidade: print('O numero da dezena é igual ao da unidade') else: print('O numero da dezena é diferente do da unidade') main()
def main(): horas_de_aula1 = int(input('Digite a quantidade de horas que voce da aula:')) valor_hora1 = int(input('Digite quanto voce ganha por hora aula: ')) horas_de_aula2 = int(input('Digite a quantidade de horas que voce da aula:')) valor_hora2 = int(input('Digite quanto voce ganha por hora aula: ')) maior_salario(horas_de_aula1, horas_de_aula2, valor_hora1, valor_hora2) def maior_salario(horas_de_aula1, horas_de_aula2, valor_hora1, valor_hora2): salario1 = horas_de_aula1 * valor_hora1 salario2 = horas_de_aula2 * valor_hora2 if salario1 > salario2: print('O primeiro professor ganha mais') else: print('O segundo professor ganha mais') main()
def main(): num1 = int(input('Digite um numero: ')) num2 = int(input('Digite um numero: ')) num3 = int(input('Digite um numero: ')) num4 = int(input('Digite um numero: ')) num5 = int(input('Digite um numero: ')) media_total(num1, num2, num3, num4, num5) def media_total(num1, num2, num3, num4, num5): media = (num1 + num2 + num3 + num4 + num5) / 5 if num1 > media: print(num1, end= ',') if num2 > media: print(num2, end= ',') if num3 > media: print(num3, end= ',') if num4 > media: print(num4, end= ',') else: print(num5, end= '') main()
def main(): n1 = int(input('Digite um numero: ')) n2 = int(input('Digite outro numero: ')) resto(n1, n2) def resto(n1, n2): if n1 % n2 == 0: pass elif n1 % n2 == 1: print(n1 + n2 + (n1 % n2)) elif n1 % n2 == 2: if n1 % 2 == 0: print(f'{n1} é par') else: print(f'{n1} é impar') if n2 % 2 == 0: print(f'{n2} é par') else: print(f'{n2} é impar') elif n1 % n2 == 3: print((n1 * n2) + n1) elif n1 % n2 == 4: print((n1 + n2) / n2) else: print(n1 ** 2, n2 ** 2) main()
a = int(input("Digite os anos")) m = int(input("Digite os meses")) d = int(input("Digite os dias)")) r = a + m + d print("Você tem:", r "de vida.")
print("hello world") name = "Batman" print(name) x = 1 y = 2 z = x + y print(z) flag = False if flag: print("flag is true") else: print("flag is false")
import turtle import numpy as np turtle.shape('turtle') def strmm(n): i=0 n=200 for i in range(n): turtle.forward(2) turtle.right(360/n) for j in range(3): strmm(200) turtle.right(180) strmm(200) turtle.right(60)
import turtle import numpy as np turtle.shape('turtle') turtle.speed(0) def strmm(n, k): n = 200 for i in range(n): turtle.forward(k) turtle.right(360/n) def stlmm(n, k): n = 200 for i in range(n): turtle.forward(k) turtle.left(360/n) k = 2 turtle.right(90) for j in range(10): strmm(200, k) stlmm(200, k) k += 0.1
""" This class consolidates functions related to the local datastore. """ import logging import sqlite3 import sys class DataStore: def __init__(self, config): """ Method to instantiate the class in an object for the datastore. :param config object, to get connection parameters. :return: Object to handle datastore commands. """ logging.debug("Initializing Datastore object") self.config = config self.dbConn, self.cur = self._connect2db() return def _connect2db(self): """ Internal method to create a database connection and a cursor. This method is called during object initialization. Note that sqlite connection object does not test the Database connection. If database does not exist, this method will not fail. This is expected behaviour, since it will be called to create databases as well. :return: Database handle and cursor for the database. """ logging.debug("Creating Datastore object and cursor") db = self.config['Main']['db'] try: db_conn = sqlite3.connect(db) except: e = sys.exc_info()[1] ec = sys.exc_info()[0] log_msg = "Error during connect to database: %s %s" logging.error(log_msg, e, ec) return else: logging.debug("Datastore object and cursor are created") return db_conn, db_conn.cursor() def close_connection(self): """ Method to close the Database Connection. :return: """ logging.debug("Close connection to database") try: self.dbConn.close() except: e = sys.exc_info()[1] ec = sys.exc_info()[0] log_msg = "Error during close connect to database: %s %s" logging.error(log_msg, e, ec) return else: return def create_tables(self): # Create table query = """ CREATE TABLE dataset (id text primary key, creator_user_id text, owner_org text, name text unique, title text, notes text, author text, author_email text, maintainer text, maintainer_email text, lod_stars text, theme_facet text, resources integer, tags integer, groups integer, metadata_created text, metadata_modified text, tracking_summary_recent integer, tracking_summary_total integer) """ try: self.dbConn.execute(query) except: e = sys.exc_info()[1] ec = sys.exc_info()[0] log_msg = "Error during query execution - Attribute_action: %s %s" logging.error(log_msg, e, ec) return False logging.info("Table dataset is build.") return True def remove_tables(self): query = 'DROP TABLE IF EXISTS dataset' try: self.dbConn.execute(query) except: e = sys.exc_info()[1] ec = sys.exc_info()[0] log_msg = "Error during query execution: %s %s" logging.error(log_msg, e, ec) return False else: logging.info("Drop table dataset") return True def create_table_user_data(self): # Create table query = """ CREATE TABLE user_data (id text primary key, name text, fullname text, display_name text, about text, state text, number_of_edits integer, number_created_packages integer, created text) """ try: self.dbConn.execute(query) except: e = sys.exc_info()[1] ec = sys.exc_info()[0] log_msg = "Error during query execution - Attribute_action: %s %s" logging.error(log_msg, e, ec) return False logging.info("Table user_data is build.") return True def remove_table_user_data(self): query = 'DROP TABLE IF EXISTS user_data' try: self.dbConn.execute(query) except: e = sys.exc_info()[1] ec = sys.exc_info()[0] log_msg = "Error during query execution: %s %s" logging.error(log_msg, e, ec) return False else: logging.info("Drop table user_data") return True def get_columns(self, tablename): """ This method will get column names for the specified table. :param tablename: :return: """ cols = self.cur.execute("PRAGMA table_info({tn})".format(tn=tablename)) return [col[1] for col in cols] def insert_row(self, tablename, rowdict): columns = ", ".join(rowdict.keys()) values_template = ", ".join(["?"] * len(rowdict.keys())) query = "insert into {tn} ({cols}) values ({vt})".format(tn=tablename, cols=columns, vt=values_template) values = tuple(rowdict[key] for key in rowdict.keys()) self.dbConn.execute(query, values) self.dbConn.commit() return
#!/usr/bin/env python3 import unicodedata def name(ch): return unicodedata.name(ch) def unicode_code(ch): return 'U+{:04x}'.format(ord(ch)) def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper() if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)')) chars = ['A', 'ö', 'Ж', '€', '𝄞'] for char in chars: print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
import string #пожключение библитоеки для операций со строками import random #подключение библиотеки для генерации случайных чисел my_number = 1000 while True: #проверка на условие задания №1 print("Введите число") user_number = int(input()) if user_number > my_number: break print("Ввод окончен") some_list = ['red', 'blue', 'rule', '1red'] #исходный список их строк print("Исходный список", some_list) for some_str in some_list: if some_str[0] == 'r': #проверка на начало с символа 'r' print(some_str) print("Сгенерированная случайная строка по заданию:") some_str = '' some_seq = string.ascii_letters + string.digits for i in range(8): some_str += random.choice(some_seq) if some_str.isalpha(): some_str[random.randint(0,7)] = random.choice(string.digits) print(some_str) orig_str = 'i want 3 cows and 5 birds' #исходная строка для задания №4 print("Исходная строка: ") print(orig_str) new1 = '' new2 = '' for char in orig_str: if char.isalpha(): new1 += char if char.isdigit(): new2 += char print("Первая строка: ") print(new1) print("Вторая строка: ") print(new2)
''' Created on Dec 14, 2015 @author: SRawoor ''' import re import operator def checkio(text): ''' You are given a text, which contains different english letters and punctuation symbols. You should find the most frequent letter in the text. The letter returned must be in lower case. While checking for the most wanted letter, casing does not matter, so for the purpose of your search, "A" == "a". Make sure you do not count punctuation symbols, digits and whitespaces, only letters. If you have two or more letters with the same frequency, then return the letter which comes first in the latin alphabet. For example -- "one" contains "o", "n", "e" only once for each, thus we choose "e". ''' dict = {} list1 = text.lower() for item in list1: val = re.search(r'[a-z]', item) if val is not None: dict[val.group()] = list1.count(val.group()); ''' sorted_dict = sorted(dict.items(), key=operator.itemgetter(1)) print sorted_dict max = 0; prev = '' for item in sorted_dict: if sorted_dict[item] >= max: if sorted_dict[item] == max: if ord(prev) < ord(item): frequent_item_key = prev else: frequent_item_key = item prev = item print frequent_item_key ''' max = 0; dictKeys = dict.keys(); print dictKeys frequent_item_key_list = [] for item in dictKeys: if dict[item] >= max: max = dict[item]; if item not in frequent_item_key_list: frequent_item_key_list.append(item) #print frequent_item_key_list == dictKeys frequent_item_key_list.sort() #print frequent_item_key_list #print frequent_item_key_list[0] #print sorted(frequent_item_key_list) return frequent_item_key_list[0] #print '*******' if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing ''' assert checkio("Hello World!") == "l", "Hello test" assert checkio("How do you do?") == "o", "O is most wanted" assert checkio("One") == "e", "All letter only once." assert checkio("Oops!") == "o", "Don't forget about lower case." assert checkio("AAaooo!!!!") == "a", "Only letters." assert checkio("abe") == "a", "The First." #print("Start the long test") assert checkio("a" * 9000 + "b" * 1000) == "a", "Long." print("The local tests are done.") ''' checkio('AAaooo!!!!') checkio("One")
from sys import argv def format_price(price): if not isinstance(price, (int, float, str)): return None try: price_num = round(float(price), 2) except ValueError: return None if price_num.is_integer(): str_price = '{:,.0f}'.format(price_num).replace(',', ' ') else: str_price = '{:,}'.format(price_num).replace(',', ' ') return str_price if __name__ == '__main__': try: price = argv[1] except IndexError: quit('A number is expected on the input.') str_price = format_price(price) print(str_price)
from collections import defaultdict import csv """ This function is used to parse the original data files and extract only the ratings that are higher than 3 and adding the movie id to the data for easier usage later on """ def transform_data(filename, output_filename): original_file = open(filename, "r") new_file = open(output_filename, "w") movie_id = None for line in original_file: if line.strip()[-1] == ":": movie_id = line.strip()[:-1] else: rating = line.split(",")[1] if int(rating) > 3: new_file.write(movie_id + "," + line) """ This function is used to parse the transformed data and group the movies by the user id """ def group_movies_by_viewer(filename, output_filename): original_file = open(filename, "r") new_file = open(output_filename, "w") new_file_writer = csv.writer(new_file, delimiter=",") user_hash_table = defaultdict(list) for line in original_file: user_id = line.split(",")[1] movie_id = line.split(",")[0] user_hash_table[user_id].append(movie_id) for _, value in user_hash_table.items(): new_string_list = [] # new_string_list.append(key) removed because we don't care about user id? for movie in value: new_string_list.append(str(movie)) new_file_writer.writerow(new_string_list) def count_columns(filename): file = open(filename, "r") max = 0 for line in file: length = len(line.split(",")) if length > max: max = length return max
earlycamp = {("earlycampAdmin") : "ec12!"} azizi = {("azizAdmin") : "9934"} twitter = {("twitterAdmin") : "t956"} def start() a = input("Hi. Are you an (a) employer or b(employee): ") if a == "a": b = input("Input your username here: ") c = input("Enter your password: ") if (b == earlycamp and c == earlycamp) or (b == azizi and c == azizi) or (b == twitter and c == twitter): print("Welcome") else: print() elif a == "b": print("We will come back to you latter.")
# Welcome the user print ("<<<<<WELCOME TO OPERATION: PRESIDENT DOWN!>>>>") # Initalize future variables total_score = 0 score_1 = 0 score_2 = 0 score_3 = 0 score_4 = 0 score_5 = 0 # Initalize while loop (boolean) variables guess_1 = False guess_2 = False # Asking user for their name so the game can adress the user by their name name = input(("\nTo start, what is your name soilder? ")) # First bit of user input telling them to advance; instructions for the user; storyline start_game = input("\nYou are now on the loading screen. Type Start to continue to the instructions. ") if start_game.lower() == "start": print ("\nColonel: The president has been held hostage by an unidentified group. It is your job to rescue him. We will be dropping you off on the back side of their base. Sources have confirmed there are at least 5 guards in your path, including the guard with the president. In order to save the president, answer at least 9/11 questions correctly. ") print ("\nColonel: Good luck " + name) # Ask the user if they are ready to enter the first level, so that I can cut off some of the extra text below first_level_ready = input("Are you ready to enter the base(Yes/No)? ") while first_level_ready.lower() != "yes": print("Its O.K " + name + " take a breather.") first_level_ready = input("Type Yes when you are ready: ") # Introduction to the first level print ("\n<<<<LEVEL 1>>>>") print ("You have entered the unidentified groups territory. There is the first guard! Gear up before you go soldier.") print(" To get past the first guard, correctly answer 2/2 questions. The first level is a practice round, so you have unlimited tries for the first level. ") # Using while loops to ask questions as they have unlimited tries for the first level while guess_1 == False: first_question = input("\n1. How much informaiton is stored in a byte? ") if first_question.lower() == "8 bits": print ("Excellent! You got the first question right. ") score_1 = score_1 + 1 total_score = total_score + 1 guess_1 = True else: print ("You guessed it wrong") print("\nAssess the following informaiton:\nA. Process\nB. Input\nC. Storage\nD. Output") while guess_2 == False: second_question = input("2. List the information processing Cycle in order (Use commas to separate, ex. C, D, A, B): ") if second_question.lower() == "b, a, d, c": print("Excellent! You got the second question right. ") score_1 = score_1 + 1 total_score = total_score + 1 guess_2 = True else: print("You guessed it wrong") # Printing user score and asking if they are ready to advance (Should be 2/2 as they have unlimited tries) print ("\nYour score is " + str(score_1) + "/2. " + "Your total score is " + str(total_score) + "/2. You may advance to the next level.") second_level_ready = input ("Are you ready to move onto the next level? (Yes/No) ") while second_level_ready.lower() != "yes": print("Its O.K " + name + " take a breather.") second_level_ready = input("Type Yes when you are ready: ") # Introduction to level 2 print ("\n<<<<LEVEL 2>>>>") print("Congratulations you have cleared the first level.") print("You are now entering the second level. The guards still don't know you're here so keep quiet " + name + ". You have 1 try to answer the first question, and 3 for the second question. Good luck.") # Questions for level 2 using if statments and for loops third_question = input("\n1. (True/False) The CPU is essentially the brain of the computer. ") if third_question.lower() == "true": print ("Excellent! You got the first question right.") score_2 = score_2 + 1 total_score = total_score + 1 else: print ("You got the question wrong. Next question.") for i in range (3): print ("\nA. Provides internet to your household\nB. Protects your network from malicious users and malware\nC. Wirelessly transmits data\nD. Protects you from fire") fourth_question = input("2. What is the function of a firewall? ") if fourth_question.lower() == "b": print ("Excellent! You got the second question right.") score_2 = score_2 + 1 total_score = total_score + 1 break else: print("Wrong answer. Please try again") # Printing user score and asking if they are ready print ("\nYour score is " + str(score_2) + "/2 and your total score is " + str(total_score) + "/4.") third_level_ready = input ("Are you ready to move onto the next level? (Yes/No) ") while third_level_ready.lower() != "yes": third_level_ready = input("Type Yes when you are ready: ") # Introduction to level 3 print("\n<<<<LEVEL 3>>>>") print("You are now on level three, and getting closer to the president. The group has identifed that you are in the base, and have sent reinforcments. Questions will get harder. ") print ("\nYou have 2 tries to answer the first question, and 1 try to answer the second question. Good luck.") # Asking questions through for loops and if statments for i in range (2): fifth_question = input("\nMega/Gigabytes per second measures how much data can be _____? ") if fifth_question.lower() == "transferred": print("Excellent, you got the first question correct.") score_3 = score_3 + 1 total_score = total_score + 1 break else: print ("You got it wrong.") sixth_question = input("\nBecause of the development of computers, has there been a negative environmental impact? (Yes/No) ") if sixth_question.lower() == "yes": print ("Excellent, you got the second question correct.") score_3 = score_3 + 1 total_score = total_score + 1 else: print ("You got the question wrong.") # Printing user score and asking if they want to move on print ("\nYour score for this level is " + str(score_3) + "/2 and your total score is " + str(total_score) + "/6.") progress_ready = input ("You will now be notified of your progress. Are you ready? (Yes/No) ") while progress_ready.lower() != "yes": print("Take a breather.") progress_ready = input("Type Yes when you are ready: ") # Checking up on the users progress if total_score >= 5: print ("\nYou are doing very good so far " + name + ".") elif total_score == 4: print ("\nYou are doing decent. You need to answer the next 5 questions correctly in order to save the president. ") else: print ("\nYou are not doing good. Do not worry, keep going. ") minigame_introduction = input ("Are you ready to move on? (Yes/No) ") while minigame_introduction.lower() != "yes": print("Take a breather.") minigame_introduction = input("Type Yes when you are ready: ") # Introduction to plot twist in the game print("\nOh no! It has been found out that the president is no longer at the base you are in. Get to the control room quick!") print("You are approaching the contorl room, however the door is locked. In order to unlock the door, you must play the number guessing game.") game = False print ("You are now playing number guesssing. You have 3 tries to guess the correct number.") for i in range (3): my_number = 6 guess = int(input("\nEnter a number from 1-10: ")) if guess == my_number: print ("Good, you got it correct. You may advance. ") game = True break else: print ("You got it wrong.") while game == False: print ("Oh no! You did not make it past the first game. Run to the other door in order to play another game!") my_code = 1432 second_guess = int(input("\nGuess my 4-digit code (Numbers range from 1-4): ")) while second_guess != my_code: print ("You got it wrong. Try again. ") second_guess = int(input("Guess my code from 1-4: ")) print ("Good, you got it correct.") game = True # Getting ready for fourth level fourth_level_ready = input ("Are you ready to move on? (Yes/No) ") while fourth_level_ready.lower() != "yes": print("Take a breather.") fourth_level_ready = input("Type Yes when you are ready: ") # Introduction to level 4 print("\n<<<<LEVEL 4>>>>") print ("Now entering level 4. You have taken your jeep, and now approaching the fleet of cars with the president. There are three cars in total. Take out the two on either side of you, and resuce the president in the last one. ") print ("You only have 1 chance to answer each of the questions.") # Asking questions through if statments seventh_question = input("\nThere been an increasing amount of mental illnesses (especially within teens) due to the prolonged use of technology. (True/False) ") if seventh_question.lower() == "true": print ("Great, you got the first question correct.") score_4 = score_4 + 1 total_score = total_score + 1 else: print ("You got it wrong. Yes, there has been an increasing amount of mental illness associated with the use of technology due to social media. ") eight_question = input("\nAre hackers considered to be malware? (Yes/No) ") if eight_question.lower() == "no": print ("Good job, you got it correct.") score_4 = score_4 + 1 total_score = total_score + 1 else: print("You got it wrong.") # Printing user score print ("\nYour score for this level is " + str(score_4) + "/2 and your total score is " + str(total_score) + "/8.") fifth_level_ready = input ("Are you ready to move onto the next level? (Yes/No) ") while fifth_level_ready.lower() != "yes": fifth_level_ready = input("Type Yes when you are ready: ") # Introduction to Level 5 print ("\n<<<<LEVEL 5>>>>") print ("Excellent, you shot down the tires on each of the cars. You are coming side by side from the last car.") print ("President: Oh thank god you're here " + name + ". I've been trapped here for so long. Quick, untie me and let's get out before Brutus catches us!") print("*Unties President*") # Decision for the user print ("Brutus: Not so fast soldier. I never said you could take the president. ") brutus_ready = input("You have the president in your car. Do you choose to drive away, or face-off against Brutus? (Stay/Leave) ") # If the user selects leave if brutus_ready.lower() == "leave": print("\nAfter a high-speed car chase, you escaped Brutus. You brought the president back to Washington where he is safe.") print("<<<<A FEW WEEKS LATER>>>") print("You are currently guarding the white house, and BOOM. An explosion happened somehwere on the West. Quickly, you run over there and spot a man you think you'd never see again.") print("Quickly, you get everyone to saftey and confront Brutus") whitehouse_faceoff = input ("\nReady to face-off against Brutus? (Yes/No) ") while whitehouse_faceoff.lower() != "yes": whitehouse_faceoff = input("Type Yes when you are ready to start: ") # Asking final questions for i in range (3): ninth_question = input("\nWhat type of malware records everything you type on your computer? ") if ninth_question.lower() == "keyloggers": print ("Great, you got the first question right") score_5 = score_5 + 1 total_score = total_score + 1 break else: print ("You got it wrong. Do not worry. ") tenth_question = input("\n(True/False) You can apply to medical school with a computer science degree: ") if tenth_question.lower() == "true": print("Excellent, you got it right.") score_5 = score_5 + 1 total_score = total_score + 1 else: print ("You got it wrong. ") for i in range (3): eleventh_question = input ("\nList 1 type of malware (Apart from keyloggers): ") if eleventh_question.lower() == "adware" or eleventh_question.lower() == "spyware" or eleventh_question.lower() == "virus" or eleventh_question.lower() == "worm" or eleventh_question.lower() == "trojan" or eleventh_question.lower() == "rootkit" or eleventh_question.lower() == "backdoors" or eleventh_question.lower() == "rouge security software" or eleventh_question.lower() == "ransomware" or eleventh_question.lower() == "browser hijacker": print ("Excellent, you got it correct!") score_5 = score_5 + 1 total_score = total_score + 1 break else: print ("You got it wrong") # If the user selects stay else: print ("\nFINAL FACEOFF AGAINST BRUTUS! You have three questions, with 3 tries for the first question, 1 try for the second question and 3 tries for the last question") # Asking if they are ready in order to cut off some text (Makes it easier for them to read) questions_fifth_ready = input ("Ready to face-off against Brutus? (Yes/No) ") while questions_fifth_ready.lower() != "yes": questions_fifth_ready = input("Type Yes when you are ready to start: ") # Asking final questions for i in range (3): ninth_question = input("\nWhat type of malware records everything you type on your computer? ") if ninth_question.lower() == "keyloggers": print ("Great, you got the first question right") score_5 = score_5 + 1 total_score = total_score + 1 break else: print ("You got it wrong. Do not worry. ") tenth_question = input("\n(True/False) You can apply to medical school with a computer science degree: ") if tenth_question.lower() == "true": print("Excellent, you got it right.") score_5 = score_5 + 1 total_score = total_score + 1 else: print ("You got it wrong. ") for i in range (3): eleventh_question = input ("\nList 1 type of malware (Apart from keyloggers): ") if eleventh_question.lower() == "adware" or eleventh_question.lower() == "spyware" or eleventh_question.lower() == "virus" or eleventh_question.lower() == "worm" or eleventh_question.lower() == "trojan" or eleventh_question.lower() == "rootkit" or eleventh_question.lower() == "backdoors" or eleventh_question.lower() == "rouge security software" or eleventh_question.lower() == "ransomware" or eleventh_question.lower() == "browser hijacker": print ("Excellent, you got it correct!") score_5 = score_5 + 1 total_score = total_score + 1 break else: print ("You got it wrong") # Based on all the questions, checking if the player saved the president or not print ("\nAlright soldier. Let's see if you saved the president or not.") print ("Your final score was " + str(total_score) + "/11.") final_statement_ready = input ("\nReady to review results? (Yes/No) ") while final_statement_ready.lower() != "yes": final_statement_ready = input("Type Yes when you are ready to start: ") if total_score >= 9: print ("\n<<<<CONGRATULATIONS, YOU SAVED THE PRESIDENT>>>>") print ("Brutus was destroyed by you! You were treated for your injuries, then was awarded the Medal of Honor from the president himself.") print ("You are now appointed as the president's personal bodyguard. ") else: print ("\nSorry, you did not save the president. Although you made it out fine, the president has been captured to an unknown base. The CIA has taken over the rescue.") # Closing statment print ("\n<<<<THANK YOU FOR PLAYING>>>>")
# # # ##------------------------MAIN SELECTION INTRO------------------------------ from operator import itemgetter def main(): global storelist global incomelist storelist = ['store1', 'store2', 'store3', 'store4', 'store5'] incomelist = [0.0, 0.0, 0.0, 0.0, 0.0] usr_sel = 0 while (usr_sel != 11): print("""\n\n Hello, this is a sale report manager. Please select an option: 1- Print the sales 2- Sort/Print sales High to Low 3- Sort/Print sales Low to High 4- Print Highest and Lowest only 5- Print Total Sales 6- Print Avg Sales 7- Enter sales data 8- Rename Store 9- Save Sales Data 10- Load Sales Data 11- Quit Program """) usr_sel = int(input("> ")) if usr_sel ==1: print_sales() elif usr_sel==2: sort_HL() elif usr_sel==3: sort_LH() elif usr_sel==4: HL_only() elif usr_sel==5: total_sales() elif usr_sel==6: avg_sales() elif usr_sel==7: input_sales() elif usr_sel==8: rename_shop() elif usr_sel==9: save_data() elif usr_sel==10: load_data() ##--------------------------INPUT SALES DATA-------------------------- def input_sales(): print(" Which shop would you like to input sales data for?") print(f"1- {storelist[0]} ") #need to change to for statement with enumerate for new store additions print(f"2- {storelist[1]} ") print(f"3- {storelist[2]} ") print(f"4- {storelist[3]} ") print(f"5- {storelist[4]} ") print(f"6- New Store ") shop_num = int(input("> ")) if shop_num == 6: addshop() shop_num -=1 print(f"Please input the sales data for {storelist[shop_num]} in dollars.") sales_amt = float(input("$ ")) incomelist[shop_num] = sales_amt ##---------------------------ADDING SHOP---------------------------- def addshop(): i_num = len(storelist) act_num = i_num +1 storelist[i_num] = 'Store' + str(act_num) ##---------------------------RENAME SHOP---------------------------- def rename_shop(): print("What shop would you like to rename?") for i, name in enumerate(storelist): print(f" {i+1}. {storelist[i]} ") s_sel = int(input("> ")) s_sel -= 1 new_name= input("New Storename: ") storelist[s_sel] = new_name ##--------------------------PRINTING SALES------------------------ def print_sales(): for i in range(len(storelist)): print(f" {storelist[i]} ${incomelist[i]} ") ##--------------------------PRINTING High to Low------------------ def sort_HL(): templist=(sorted(zip(storelist, incomelist), key=itemgetter(1), reverse=True)) for i, entry in enumerate(templist): print(f"{i+1}. {templist[i]}") ##--------------------------PRINTING Low to High------------------ def sort_LH(): templist=sorted(zip(storelist, incomelist), key=itemgetter(1)) for i, entry in enumerate(templist): print(f"{i+1}. {templist[i]}") ##--------------------------PRINTING High and Low Only----------- def HL_only(): templist=sorted(zip(storelist, incomelist), key=itemgetter(1)) low_store=templist[0] high_store=templist[(len(templist)-1)] print(f"Lowest Sales: {low_store} \nHighest Sales:{high_store}") ##--------------------------PRINTING Total Sales---------------- def total_sales(): sum_sales=0.0 for i in range(len(incomelist)): sum_sales = sum_sales + incomelist[i] print(f"Total Sales Revenue: {sum_sales}") ##--------------------------Average Sales---------------------- def avg_sales(): avg_sales=0.0 for i in range(len(incomelist)): avg_sales = avg_sales + incomelist[i] avg_sales = avg_sales / (len(storelist)) print(f"Average Sales Revenue: {avg_sales}") ##--------------------------Save Data------------------------- def save_data(): print("What would you like to name the data file?") name_sel = input("> ") name_sel = (name_sel + ".txt") ##--------------------------Load Data------------------------- def load_data(): ##--------------------------Gen Body------------------------- # error code main()
# # # ##------------------------MAIN SELECTION INTRO------------------------------ def main(): global storelist global incomelist storelist = ['store1' 'store2', 'store3', 'store4', 'store5'] incomelist = float[0.0, 0.0, 0.0, 0.0, 0.0] while (usr_sel != 8): print("""\n\n Hello, this is a sale report manager. Please select an option: 1- Print the sales 2- Sort/Print sales High to Low 3- Sort/Print sales Low to High 4- Print Highest and Lowest only 5- Print Total Sales 6- Print Avg Sales 7- Enter sales data 8- Quit Program """) usr_sel = int(input("> ")) if usr_sel ==1: print_sales() elif usr_sel==2: sort_HL() elif usr_sel==3: sort_LH() elif usr_sel==4: HL_only() elif usr_sel==5: total_sales() elif usr_sel==6: avg_sales() elif usr_sel==7: input_sales() ##--------------------------INPUT SALES DATA-------------------------- def input_sales(): print(" Which shop would you like to input sales data for?") print(f"1- {global.storelist[0]} ") print(f"2- {global.storelist[1]} ") print(f"3- {global.storelist[2]} ") print(f"4- {global.storelist[3]} ") print(f"5- {global.storelist[4]} ") print(f"6- New Store ") shop_num = int(input("> ")) if shop_num == 6: addshop() shop_num -=1 print(f"Please input the sales data for {global.storelist[shop_num]} in dollars.") sales_amt = float(input("$ ")) incomelist[shop_num] = sales_amt ##---------------------------ADDING SHOP---------------------------- def addshop(): i_num = len(storelist) act_num = i_num +1 storelist[i_num] = 'Store' + str(ac_num) ##--------------------------PRINTING SALES------------------------ def printsales(): for i in range(len(storelist)): print(f" {global.storelist[i]} ${global.incomelist[i]} ") ##-------------------------------------------------------------------- #printsales, sortHL, sortLH, HL only, totalsales, avgsales, enter sales, quit main()
def binarySearch(alist, item): first = 0 last = len(alist) - 1 found = False while first <= last and not found: midpoint = (first + last) //2 if alist[midpoint] == item: found = True else : if item < alist[midpoint]: last = midpoint - 1 else : first = midpoint + 1 return found testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42, ] print(binarySearch(testlist, 3)) print(binarySearch(testlist, 13))
l=[5, 3, 9, 10, 8, 2, 7] def find_min(l,current_minimum = None): if not l: return current_minimum candidate=l.pop() if current_minimum==None or candidate<current_minimum: return find_min(l,candidate) return find_min(l,current_minimum) print find_min(l)
# -*- coding: utf-8 -*- """ Created on Sun Feb 21 13:55:03 2021 @author: 6degt """ import math import numpy as np def calc_ypr(q): yaw = math.atan2(2.0 * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]) pitch = -math.sin(2.0 * (q[1] * q[3] - q[0] * q[2])) roll = math.atan2(2.0 * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]) return [yaw, pitch, roll] def quaternion_rotation_matrix(Q): """ Covert a quaternion into a full three-dimensional rotation matrix. Input :param Q: A 4 element array representing the quaternion (q0,q1,q2,q3) Output :return: A 3x3 element matrix representing the full 3D rotation matrix. This rotation matrix converts a point in the local reference frame to a point in the global reference frame. """ # Extract the values from Q q0 = Q[0] q1 = Q[1] q2 = Q[2] q3 = Q[3] # First row of the rotation matrix r00 = 2 * (q0 * q0 + q1 * q1) - 1 r01 = 2 * (q1 * q2 - q0 * q3) r02 = 2 * (q1 * q3 + q0 * q2) # Second row of the rotation matrix r10 = 2 * (q1 * q2 + q0 * q3) r11 = 2 * (q0 * q0 + q2 * q2) - 1 r12 = 2 * (q2 * q3 - q0 * q1) # Third row of the rotation matrix r20 = 2 * (q1 * q3 - q0 * q2) r21 = 2 * (q2 * q3 + q0 * q1) r22 = 2 * (q0 * q0 + q3 * q3) - 1 # 3x3 rotation matrix rot_matrix = np.array([[r00, r01, r02], [r10, r11, r12], [r20, r21, r22]]) return rot_matrix w = 0 q1 =np.array([w, 0.5, -1.0, 0.0]) q2 =np.array([w,- 1.0, -0.5, 0.0]) print(calc_ypr(q1)) print(calc_ypr(q2)) print(np.array(calc_ypr(q1)) - np.array(calc_ypr(q2))) print(np.array(calc_ypr(q1)) + np.array(calc_ypr(q2))) res = [q1[i]*q2[i] for i in range(len(q1))] print(calc_ypr(res)) print(quaternion_rotation_matrix(res)) rot_matrix1 = quaternion_rotation_matrix(q1) rot_matrix2 = quaternion_rotation_matrix(q2) print(np.dot(rot_matrix1, rot_matrix2))
# Part 1 Find two numbers that sum up to one number #puzzle_input = {1721: "", 979: "", 366: "", 299: "", 675: "", 1456: ""} sum_number = 2020 with open("day1/input.txt") as input_file: puzzle_input = {int(line.rstrip("\n")): "" for line in input_file.readlines()} for first_num in puzzle_input: second_num = sum_number - first_num try: puzzle_input[second_num] print(first_num, "and", second_num, "add up to", sum_number) print("Their product is", first_num * second_num) break except KeyError: continue # Part 2 Find three numbers that sum up to one number answer = 0 for first_num in puzzle_input: if answer: break remaining_sum = sum_number - first_num for second_num in puzzle_input: if second_num == first_num: continue else: third_num = remaining_sum - second_num try: puzzle_input[third_num] print(first_num, ", ", second_num, " and ", third_num, " add up to ", sum_number, sep="") answer = first_num * second_num * third_num print("Their product is", answer) break except KeyError: continue
# puzzle_input = """light red bags contain 1 bright white bag, 2 muted yellow bags. # dark orange bags contain 3 bright white bags, 4 muted yellow bags. # bright white bags contain 1 shiny gold bag. # muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. # shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. # dark olive bags contain 3 faded blue bags, 4 dotted black bags. # vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. # faded blue bags contain no other bags. # dotted black bags contain no other bags.""" # puzzle_input = """shiny gold bags contain 2 dark red bags. # dark red bags contain 2 dark orange bags. # dark orange bags contain 2 dark yellow bags. # dark yellow bags contain 2 dark green bags. # dark green bags contain 2 dark blue bags. # dark blue bags contain 2 dark violet bags. # dark violet bags contain no other bags.""" import re from typing import Dict, Set with open("day7/input.txt") as input_file: puzzle_input = input_file.read() # Build rules dict bag_rules_dict = {} for rule in puzzle_input.split(".\n"): bag, contained_bags = rule.split(" contain ") contained_bags_list = contained_bags.split(", ") contained_bags_dict = {} for contained_bag in contained_bags_list: try: _, num_contained_bag, contained_bag = re.split("(\d+)\s", contained_bag) # Get rid of plural + punctuation contained_bag = contained_bag.rstrip("s") contained_bags_dict[contained_bag] = int(num_contained_bag) except ValueError: # If we get here it means that the contained_bags_list is 'no other bags' # so we'll just pass the empty dictionary through pass # Get rid of plural for bag bag_rules_dict[bag.rstrip("s")] = contained_bags_dict # Part 1, how many possible bags could we use to contain our shiny gold bag? def find_outer_bags(bag: str, bag_rules_dict: Dict[str, dict]) -> Set[str]: """A recursive function that searches for how many different color bags could hold another bag, given the bag holding rules""" outer_bags = [] for outer_bag, inner_bags in bag_rules_dict.items(): if bag in inner_bags.keys(): outer_bags += [outer_bag] outer_bags += find_outer_bags(outer_bag, bag_rules_dict) return set(outer_bags) our_bag = "shiny gold bag" outer_bags = find_outer_bags(our_bag, bag_rules_dict) print(len(outer_bags), "bags can hold a", our_bag) # Part 2, how many bags are contained in our shiny gold bag? def find_num_inner_bags(bag: str, bag_rules_dict: Dict[str, dict]) -> int: """A recursive function that searches for how many total bags are contained within another bag, given the bag holding rules""" total_inner_bags = 0 inner_bags = bag_rules_dict[bag] total_inner_bags += sum(inner_bags.values()) for inner_bag, num_inner_bag in inner_bags.items(): total_inner_bags += find_num_inner_bags(inner_bag, bag_rules_dict) * num_inner_bag return total_inner_bags our_bag = "shiny gold bag" num_inner_bags = find_num_inner_bags(our_bag, bag_rules_dict) print("A", our_bag, "holds", num_inner_bags, "other bags")
class student: def assign(self,rno,name): global math,science,eng self.rno=rno self.name=name math = int(input("math is=")) eng = int(input("english is =")) science = int(input("science is =")) def display(self): global total,percent total=math+science+eng print(self.rno) print(self.name) print("total marks in all subjects:",total) percent=total/3 print("percentage:",percent) s=student() s.assign(100,"naveen") s.display()
person={"name":"sharad","gender":"male","age":"15","address":"siddanagoudar","phone":"12345678979"} key = input("what kind of info do you what to know?") result =person.get(key,"that info is not avalible") print(result)
n=int(input("enter the number:")) n1=1 n2=1 count=0 for i in range(0,n): print(n1) nth=n1+n2 n1=n2 n2=nth count+=1
''' This program reads integers from a user specified input file into two 2D arrays (matricies). The matricies are multipled together and the rows of the product matrix are sorted. All the matricies are written to an output.txt file in the same directory as matrix.py. @author Sean Brady @version 1.0 11/11/2017 ''' inputFile = raw_input("Enter the input file location (/home/user/Documents/example.txt):") numbers = [] inFile = open (inputFile, "r") for line in inFile.readlines(): for i in line.split(): numbers.append(int(i)) length = len(numbers) size = length/5 outFile = open('output.txt','w') def create_matrix(m, n): return [[0]*n for _ in xrange(m)] A = create_matrix(size, 5) outFile.write('Matrix A:\n') count = 0 for j in range(5): for i in range(size): A[i][j] = numbers[count] outFile.write(str(A[i][j]),) outFile.write(' ') count = count+1 outFile.write('\n') B = create_matrix(5, size) outFile.write('\nMatrix B:\n') count = 0 for j in range(size): for i in range(5): B[i][j] = numbers[count] outFile.write(str(B[i][j]),) outFile.write(' ') count = count+1 outFile.write('\n') C = create_matrix(5, 5) outFile.write('\nA*B:\n') count = 0 k = size for j in range(5): for i in range(5): for k in range(size): C[i][j] = A[k][j] * B[i][k] outFile.write(str(C[i][j]),) outFile.write(' ') count = count + 1 outFile.write('\n') outFile.write('\nA*B Sorted:\n') count = 0 k = size for j in range(5): for i in range(5): for k in range(size): C[i].sort() outFile.write(str(C[i][j]),) outFile.write(' ') count = count + 1 outFile.write('\n')
from threading import Thread, Semaphore, Lock from random import randint from time import sleep """ majme vecerajucich filozofov spolu s manzelkami a detmi. o deti sa staraju sarmantne asistentky, vzdy musi byt k dispozicii 1 na 3 deti. manzelky rady chodia ku kadernikovi a filozofi pocas svojej rozpravy duchaju fajky (na tie potrebuju zapalovac, tabak a samozrejme fajku). nakolko filozofi jedia zo spolocneho hrnca, ten sa im obcas vyprazdni, a na jeho naplnenie maju kuchara - toho vzdy zobudia, ked je hrniec prazdny. v dome je vsak iba jedno spolocne wc, a tak treba zabezpecit, aby ho v jednom case nepouzivali osoby rozneho pohlavia. filozofi premyslaju nad otazkou zmyslu zivota, vesmiru a vobec, a na tuto temu pisu knihu. ked niekto nieco napise, dalsi skontroluju. obcas sa vsak stane, ze k stolu pribehne dieta, a vytrhne nejaku tu stranku z knihy. """ nFilozofov = 5 nZien = 5 nDeti = 3 nAsistentky = 1 filozofi = [] zeny = [] deti = [] asistentky = [] vidlicky = [] #pre divochov mutex = Lock() porcie = 3 prazdnyKs = Semaphore() plnyKs = Semaphore(1) class Filozof(Thread): def __init__(self,index): Thread.__init__(self) self.index = index def run(self): leftForkIndex = self.index rightForkIndex = (self.index + 1) % nFilozofov forkpair = ForkPair(leftForkIndex,rightForkIndex) while True: self.jedenie(self.index,forkpair) def fajci(self): pass def jedenie(self, i, forkPair): print("Thinking {} philosoph".format(i)) sleep(0.5) mutex.acquire() global porcie if porcie <= 0: prazdnyKs.release() plnyKs.acquire() porcie = 10 porcie -=1 mutex.release() forkPair.get_forks() print("Filozof {} je {} porciu".format(i,porcie)) sleep(0.5) forkPair.put_forks() def pisanie(self): pass def ide_na_wc(self): pass class ForkPair: def __init__(self,lava, prava): if lava > prava: lava, prava = prava, lava self.prva = vidlicky[lava] self.druha = vidlicky[prava] def get_forks(self): self.prva.acquire() self.druha.acquire() def put_forks(self): self.prva.release() self.druha.release() class Manzelka(Thread): def __init__(self,index): Thread.__init__(self) self.index = index class Dieta(Thread): def __init__(self,index): Thread.__init__(self) self.index = index class Asistentka(Thread): def __init__(self,index): Thread.__init__(self) self.index = index class Kadernik(Thread): def __init__(self,index): Thread.__init__(self) self.index = index class Kuchar(Thread): def __init__(self, index): Thread.__init__(self) self.index = index def run(self): global porcie while True: prazdnyKs.acquire() print("Vari sa") sleep(5) plnyKs.release() if __name__=="__main__": for i in range(0,nFilozofov): filozofi.append(Filozof(i)) vidlicky.append(Lock()) print(filozofi) for filozof in filozofi: filozof.start() Kuchar(0).start()
import unittest from Game import Game from Card import Card class GameTests(unittest.TestCase): def test_shuffle_deck_length(self): game = Game() game.shuffle_deck() self.assertEqual(game.deck.cards.__len__(), 52) def test_deal_player(self): game = Game() game.deal_player_a_card() self.assertTrue(game.player.hand.cards) self.assertEqual(game.player.hand.cards.__len__(), 1) self.assertEqual(game.deck.cards.__len__(), 51) def test_deal_dealer(self): game = Game() game.deal_dealer_a_card() self.assertTrue(game.dealer.hand.cards) self.assertEqual(game.dealer.hand.cards.__len__(), 1) self.assertEqual(game.deck.cards.__len__(), 51) def test_get_player_card(self): game = Game() save_card = game.deck.cards[-1] game.deal_player_a_card() self.assertEqual(game.get_player_cards(), [save_card]) def test_get_dealer_cards(self): game = Game() save_card = game.deck.cards[-1] game.deal_dealer_a_card() self.assertEqual(game.get_dealer_cards(), [save_card]) def test_dealer_turn_greater_17(self): game = Game() game.dealer.add_card(Card('A')) game.dealer.add_card(Card('9')) game.dealers_turn() self.assertEqual(game.dealer.get_hand_value(), 20) def test_dealer_turn_less_17(self): game = Game() game.dealer.add_card(Card('1')) game.dealer.add_card(Card('9')) game.dealers_turn() self.assertNotEqual(game.dealer.get_hand_value(), 10) def test_winner_dealer(self): game = Game() game.player.add_card(Card('K')) game.dealer.add_card(Card('K')) game.dealer.add_card(Card('2')) self.assertEqual(game.get_winner(), "Dealer Wins") def test_winner_player(self): game = Game() game.player.add_card(Card('J')) game.dealer.add_card(Card('9')) self.assertEqual(game.get_winner(), "You Win") def test_winner_no_one(self): game = Game() game.player.add_card(Card('J')) game.dealer.add_card(Card('K')) self.assertEqual(game.get_winner(), "No one wins") def test_deal_first_cards(self): game = Game() game.deal_first_cards() self.assertEqual(game.player.hand.cards.__len__(), 2) self.assertEqual(game.dealer.hand.cards.__len__(), 2) if __name__ == '__main__': unittest.main()
import os, random, hangman, time choice = 0 category = 0 hangman.start() time.sleep(1) os.system("CLS") while choice != "5": hangman.mainmenu() choice = input("\t"*3 + "Enter your choice: ") hangman.mainmenu_choice(choice)
# from pygame import * import pygame import sys # setting global variable XO = "X" winner = None draw = False board = [[None] * 3] * 3 pygame.init() width = 450 height = 450 fps = 30 CLOCK = pygame.time.Clock() WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) screen = pygame.display.set_mode((width, height+100)) pygame.display.set_caption("Tic Tac Toe") pygame.display.update() cross_font = pygame.font.SysFont("bahnschrift", 200) font_style = pygame.font.SysFont("comicsansms", 30) def status(): global draw if winner is None: msg = XO + "'s Turn" else: msg = "X Win!" if XO == "O" else "O Win!" if draw: msg = "Game Draw!" msg = font_style.render(msg, True, WHITE) screen.fill(BLACK, (0, width, height, 100)) text_rect = msg.get_rect(center = (width/2, height+50)) screen.blit(msg, text_rect) pygame.display.update() def game_start(): global XO, winner, board, draw XO = "X" winner = None board = [[None] * 3, [None] * 3, [None] * 3] draw = False screen.fill(WHITE) pygame.draw.line(screen, BLACK, (0, height//3), (600, height//3), 4) pygame.draw.line(screen, BLACK, (0, height//3*2), (600, height//3*2), 4) pygame.draw.line(screen, BLACK, (width//3, 0), (width//3, 600), 4) pygame.draw.line(screen, BLACK, (width//3*2, 0), (width//3*2, 600), 4) status() def check_win(): global board, winner, draw for row in range(3): if board[row][0] == board[row][1] == board[row][2] and board[row][0] is not None: winner = board[row][0] pygame.draw.line(screen, RED, (0, (row+1)*height//3 - height//6), (width, (row+1)*height//3 - height//6), 4) break for col in range(3): if board[0][col] == board[1][col] == board[2][col] and board[0][col] is not None: winner = board[0][col] pygame.draw.line(screen, RED, ((col+1)*width//3 - width//6, 0), ((col+1)*width//3 - width//6, height), 4) break if board[0][0] == board[1][1] == board[2][2] and board[0][0] is not None: winner = board[0][0] pygame.draw.line(screen, RED, (0, 0), (width, height), 4) if board[0][2] == board[1][1] == board[2][0] and board[1][1] is not None: winner = board[0][2] pygame.draw.line(screen, RED, (width, 0), (0, height), 4) if all(all(row) for row in board) and winner is None: draw = True status() def drawXO(row, col): global board, XO if row == 1: pos_y = 0 elif row == 2: pos_y = width//3 else: pos_y = width//3*2 if col == 1: pos_x = 0 elif col == 2: pos_x = height//3 else: pos_x = height//3*2 board[row-1][col-1] = XO value = cross_font.render(XO, True, BLACK) if XO == "X": screen.blit(value, [pos_x+29, pos_y+16]) XO = "O" elif XO == "O": screen.blit(value, [pos_x+21, pos_y+16]) XO = "X" pygame.display.update() def user_click(): x, y = pygame.mouse.get_pos() if x < width//3: col = 1 elif x < width//3*2: col = 2 elif x < width: col = 3 else: col = None if y < height//3: row = 1 elif y < height//3*2: row = 2 elif y < height: row = 3 else: row = None if row and col and board[row-1][col-1] is None: global XO drawXO(row, col) check_win() def reset_game(): global XO, board, winner, draw XO = "X" draw = False winner = None board = [[None] * 3, [None] * 3, [None] * 3] game_start() def message(msg): msg = font_style.render(msg, True, RED) screen.blit(msg, (width//2-140, height//2-20)) pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() sys.exit() if event.key == pygame.K_p: return game_start() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: user_click() if winner or draw: message("Press Q-quit or P-play") reset_game() pygame.display.update() CLOCK.tick(fps)
# coding:utf-8 import temperature as temper import operatePod as opPod import time as time import datetime as datetime import sys as sys #running_time :稼働時間(秒) #check_interval :温度計測間隔(秒) #max_temperature:設定温度() def main(max_temperature): #ログファイル pod = opPod.OperatePod() start = time.time() elapse = 0 temperature = 0 #max 120 min while temperature < max_temperature: temperature = temper.getTemperature() print(temperature,max_temperature) if temperature <= max_temperature : print("turn on") pod.turn_on() elif temperature >= max_temperature: print("turn off") pod.turn_off() break time.sleep(30) elapse = time.time() pod.turn_off() pod.end() #log.close() print("設定温度に到達しました") main( int(sys.argv[1]) )
import random n = int(input("Вкажіть довжину списку \n ")) lst = random.sample(range(1, 100), n) print("Input list: {}".format(lst)) def split(l, start, end): """ Splits list into two parts. Splits list into two parts each element of first part are not bigger then every element of last part. """ i = start - 1 splitter = l[end] for j in range(start, end): if splitter % 2 == 0: if l[j] % 2 == 0: if l[j] >= splitter: i += 1 l[i], l[j] = l[j], l[i] else: if l[j] % 2 == 0: i += 1 l[i], l[j] = l[j], l[i] else: if l[j] <= splitter: i += 1 l[i], l[j] = l[j], l[i] l[i+1], l[end] = l[end], l[i+1] return i+1 def quick_sort(l, start, end): """ Sorts list of items using quick sort algorithm. This is recursive implementation of quick sort algorithm. """ if start < end: s = split(l, start, end) quick_sort(l, start, s - 1) quick_sort(l, s + 1, end) quick_sort(lst, 0, len(lst) - 1) print("Output list: {}".format(lst))
import random def listback(l): """reverse list""" return l[::-1] n = int(input("Вкажіть довжину списку \n ")) lst = random.sample(range(1, 100), n) print("Input list: {}".format(lst)) print("Output list: {}".format(listback(lst)))
import re string = input("Hello! What is your name?\n > ") sample_name = re.compile(r'\b[A-Z][a-z]{2,}\b') name = sample_name.search(string) print("Hello, {}!".format(name.group(0)))
name = input("Привіт! Як тебе звати?\n > ") print("Привіт, {}!".format(name)) age = int(input("Скільки тобі років?\n > ")) yearleft = 2018 - age years100 = yearleft + 100 print("Вам виповниться 100 років у {} році.".format(years100)) print("Щасти вам!!!!")
def factorial(x): """x!""" if x <= 0: return 1 else: return x * factorial(x - 1) n = int(input("Вкажіть факторіал якого числа шукати \n ")) print(factorial(n))
a = int(input("Вкажіть число a \n ")) b = int(input("Вкажіть число b \n ")) if a == b: print('Числа не можуть бути однаковими') elif a > b: while a > b: a = a - b print('Найбільший спільний дільник = {}'.format(a)) else: while b > a: b = b - a print('Найбільший спільний дільник = {}'.format(b))
#The Camel game by Pvrpl import random print("You just stole a camel! You have a few options.") print("A. Drink from your Canteen") print("B. Ahead moderate speed") print("C. Ahead full speed.") print("D. Stop for the night") print("E. Status Check") print("Q. Quit") done = False miles = 0 #Distance traveled in miles. tiredness = 0 #The camel's tiredness. thirst = 0 #Thirst level. nativemiles = -20 #Distance of natives canteen = 3#Three drinks in the canteen. def game(): done = False miles = 0 #Distance traveled in miles. tiredness = 0 #The camel's tiredness. thirst = 0 #Thirst level. nativemiles = -20 #Distance of natives canteen = 3 user_choice = input("What would you like to do? ") if miles >= 200: done = True while not done: if user_choice == "Q" or user_choice == "q": print("You are now done with the game! Goodbye!") done = True elif user_choice == "E" or user_choice == "e": print("You've traveled", miles,"miles") print("You have", canteen, "drinks in your canteen left and have a thirst value of", thirst) print("The natives are", nativemiles, "miles behind.") done = False elif user_choice == "D" or user_choice == "d": print("You rest and gain your energy back. Your camel is happy!") tiredness = 0 nativemiles = nativemiles + random.randrange(0,8) done = False elif user_choice == "C" or user_choice == "c": print("You chose to move on full speed ahead.") miles = miles + random.randrange(9,21) tiredness = tiredness + random.randrange(0,4) thirst = thirst + 2 nativemiles = nativemiles + random.randrange(7,14) elif user_choice == "B" or user_choice == "b": print("You chose to move on at moderate speed.") miles = miles + random.randrange(4,13) tiredness = tiredness + 1 thirst = thirst + 1 nativemiles = nativemiles + random.randrange(7,14) elif user_choice == "A" or user_choice == "a": print("You chose to take a drink") canteen = canteen - 1 thirst = 0 if canteen <= 0: print("You don't have any drinks left!") else: print("You input an incorrect option! Try again!") return break while not done: game() if miles >= 200: done = True else: game() break
import csv input_file = "budget_data.csv" output_file = "analysis.txt" #create variables for calculations and code total_months = 0 previous_revenue = 0 total_revenue = 0 month_of_change = [] revenue_list = [] greatest_increase = ["",0] greatest_decrease = ["",9999999] #create a FOR loop with open(input_file) as revenue_data: reader = csv.DictReader(revenue_data) for row in reader: #The total number of months included in the dataset total_months = total_months + 1 #The net total amount of "Profit/Losses" over the entire period total_revenue = total_revenue + int(row["Profit/Losses"]) revenue_change = int(row["Profit/Losses"]) - previous_revenue previous_revenue = int(row["Profit/Losses"]) revenue_list = revenue_list + [revenue_change] month_of_change = month_of_change + [row["Date"]] #The greatest increase in profits (date and amount) over the entire period if (revenue_change > greatest_increase[1]): greatest_increase[0] = row["Date"] greatest_increase[1] = revenue_change #The greatest decrease in losses (date and amount) over the entire period if (revenue_change < greatest_decrease[1]): greatest_decrease[0] = row["Date"] greatest_decrease[1] = revenue_change #The average of the changes in "Profit/Losses" over the entire period average_revenue = sum(revenue_list)/len(revenue_list) #write the code for the output output = ( f"\nFinancial Analysis\n" f"---------------------------------\n" f"Total Months:{total_months}\n" f"Total Revenue:{total_revenue}\n" f"Average Revenue Change:{average_revenue}\n" f"Greatest Revenue Increase: {greatest_increase[0]} (${greatest_increase[1]})\n" f"Greatest Revenue Decrease: {greatest_decrease[0]} (${greatest_decrease[1]})\n" f"---------------------------------\n" ) print(output) with open(output_file,"w") as text_file: text_file.write(output)
# -*- coding:utf-8 -*- ''' Python调试及单元测试 http://www.fuzhijie.me/?p=310 ''' def add(op1, op2): return op1+op2 def sub(op1, op2): return op1-op2 import unittest class MathTestCase(unittest.TestCase): '''math test case''' def setUp(self): pass def tearDown(self): pass def testAdd(self): '''test add''' self.assertEqual(add(4, 5), 9) def testSub(self): '''test sub''' self.assertEqual(sub(8, 5), 3) def suite(): suite = unittest.TestSuite() suite.addTest(MathTestCase()) return suite if __name__ == '__main__': unittest.main()
reg_num = input("주민등록번호:") sum = int(reg_num[0])*2 + int(reg_num[1])*3 + int(reg_num[2])*4 + int(reg_num[3])*5 + int(reg_num[4])*6+ int(reg_num[5])*7 + int(reg_num[7])*8 + int(reg_num[8])*9 + int(reg_num[9])*2 + int(reg_num[10])*3 + int(reg_num[11])*4+ int(reg_num[12])*5 # 1차 계산 rem = sum % 11 # 2차 계산 valid_num = 11 - rem if int(reg_num[13]) == valid_num : print("유효한 주민등록번호입니다.") else : print("유효하지 않은 주민등록번호입니다.")