text
stringlengths
37
1.41M
""" Given a rectangle with sides parallel to X and Y axis and N points in X-Y co-ordinates, print the total number of points that lie strictly inside the rectangle. Input The first line consist of a single integer T - the number of test cases. For every test case the input is as follows - First Line consists of x1 y1 x2 y2 - (x1, y1) and (x2, y2) are opposite corner points of the rectangle. Next line consists of N N lines follows - each line containing - X Y coordinate of the point. Output Output in T lines, the answer to each test case. SAMPLE INPUT 1 10 7 19 4 5 15 3 17 6 10 5 20 2 15 6 SAMPLE OUTPUT 2 """ n = int(input()) while n > 0: x1,y1,x2,y2 = map(int,input().split()) maxx=max(x1,x2) minx=min(x1,x2) maxy=max(y1,y2) miny=min(y1,y2) count=0 cases = int(input()) while cases > 0: a,b = map(int,input().split()) if ((a>minx) and (a<maxx) and (b<maxy) and (b>miny)): count += 1 cases -= 1 print(count) n -= 1
""" Midori like chocolates and he loves to try different ones. There are N shops in a market labelled from 1 to N and each shop offers a different variety of chocolate. Midori starts from ith shop and goes ahead to each and every shop. But as there are too many shops Midori would like to know how many more shops he has to visit. You have been given L denoting number of bits required to represent N. You need to print the maximum number of shops he can visit. Input: The first line of the input contains T denoting number of test cases. First line of each test case contains two integers,i and L. Output: You need to print the required answer in a new line. Sample Input: 1 2 3 Sample Output: 6 """ t = int(input()) while t > 0: a,b = map(int,input().split()) print(2**b-a) t -= 1
""" Problem Link: https://practice.geeksforgeeks.org/problems/compete-the-skills/0 A and B are good friend and programmers. They are always in a healthy competition with each other. They decide to judge the best among them by competing. They do so by comparing their three skills as per their values. Please help them doing so as they are busy. Set for A are like [a1, a2, a3] Set for B are like [b1, b2, b3] Compare ith skill of A with ith skill of B if a[i] > b[i] , A's score increases by 1 if a[i] < b[i] , B's score increases by 1 Input : The first line of input contains an integer T denoting the test cases. For each test case there will be two lines. The first line contains the skills of A and the second line contains the skills of B Output : For each test case in a new line print the score of A and B separated by space. Constraints : 1 ≤ T ≤ 50 1 ≤ a[i] ≤ 1017 1 ≤ b[i] ≤ 1017 Example: Input : 2 4 2 7 5 6 3 4 2 7 5 2 8 Output : 1 2 0 2 """ for _ in range(int(input())): a = list(map(int,input().split())) b = list(map(int,input().split())) resA = resB = 0 for i in range(3): if a[i] > b[i]: resA += 1 elif a[i] < b[i]: resB += 1 print(resA,resB)
""" Problem Link: https://practice.geeksforgeeks.org/problems/display-longest-name/0 Given a list of names, display the longest name. Input: First line of input contains an integer T, the number of test cases. For each test case, there will be two lines. First line contains integer N i.e. total number of names, and second line contains N space seperated names of different length. Output: Longest name in the list of names. Constraints: 1 <= T <= 10 1 <= N <= 10 1 <= |length of name| <= 1000 Example: Input: 1 5 Geek Geeks Geeksfor GeeksforGeek GeeksforGeeks Output: GeeksforGeeks """ for _ in range(int(input())): n = int(input()) longest_name = "" name_length = 0 for i in range(n): s = input() if len(s) > name_length: longest_name = s name_length = len(s) print(longest_name)
""" Given a string consisting of alphabets and others characters, the task is to remove all the characters other than alphabets and print the string so formed. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains a string S. Output: For each test case, print the remaining string in new line, If no character remains in the string print "-1". Sample Input: 2 $Gee*k;s..fo, r'Ge^eks? P&ra+$BHa;;t*ku, ma$r@@s#in}gh Sample Output: GeeksforGeeks PraBHatkumarsingh """ t=int(input()) while t>0: a = input() flag = 0 for i in range(0,len(a)): if a[i] >='a' and a[i] <='z': print(a[i],end='') flag = 1 elif a[i] >='A' and a[i] <='Z': print(a[i],end='') flag = 1 if flag == 1: print() else: print(-1) t-=1
""" Find the smallest number that can be framed using the series created by the digits obtained by raising the given number ( "a" ) to the power from 1 to n i.e. a^1 , a^2 , a^3 .......a^n . We get b1,b2 , b3 , ........... bn . Using all the digits ( including repeating ones ) that appear inb1 ,b2 , b3 .... bn . Frame a number that contains all the digits ( including repeating ones ) and find out the combination of digits that make the smallest number of all possible combinations. Excluding or neglecting zeroes ( " 0 " ) . Input: The first line contains a number T i.e numbers of test cases . Followed by each test case that contains two integers "a" and "n" . Output: Output of each test case contains an integer which is the smallest number out of all combinations . Sample Input 4 9 4 5 1 6 5 90 4 Sample Output: 1125667899 5 11223666667779 1125667899 Explanation : Test case 1: 9 3 9^1 = 9 9^2 = 81 9^3 = 729 9^4 = 6561 9 81 729 6561 We get 9817296561 . Using 9817296561 number we need to find the smallest possible number that can be framed using other combinations of the samenumber. 1298796561 8799265611 2186561997 . . . 1125667899 The smallest possible number that can be framed is1125667899 . """ t = int(input()) while t > 0: a,n = map(int,input().split()) res = "" for i in range(1,n+1): res += str(a**i) result = list(res) print(("".join(sorted(result))).lstrip('0')) t -= 1
""" There will be ‘t’ test cases having an integer. You have to sum up all the digits of this integer. For e.g. For 6754, the answer will be 6 + 7 + 5 + 4 = 22. Input Format: First line will have an integer ‘t’ denoting the number of test cases. Next ‘t’ lines will have an integer ‘val’ each. Output format: Print ‘t’ lines of output denoting the sum of all the digits of the number in each test case. Constraints: 1 <= t <= 10^5 0 <= val <= 10^18 Sample Input: 2 1547 45876 Sample Output: 17 30 Explanation: 1 + 5 + 4 + 7 = 17 4 + 5 + 8 + 7 + 6 = 30 """ for _ in range(int(input())): n = int(input()) summ = 0 while n > 0: summ += n % 10 n = n // 10 print(summ)
""" Problem Link: https://practice.geeksforgeeks.org/problems/small-factorial/0 Calculate factorial of a given number N. Input: The first line contains an integer 'T' denoting the total number of test cases. In each test cases, it contains an integer 'N'. Output: In each seperate line output the answer to the problem. Constraints: 1 <= T <= 100 1 <= N <= 18 Example: Input : 1 5 Output: 120 """ def fact(n): if n == 1: return 1 return n * fact(n-1) for _ in range(int(input())): print(fact(int(input())))
""" Problem Link: https://practice.geeksforgeeks.org/problems/third-largest-element/1 Given an array of distinct elements, Your task is to find the third largest element in it. You have to complete the function thirdLargest which takes two argument . The first argument is the array a[] and the second argument is the size of the array (n). The function returns an integer denoting the third largest element in the array a[]. The function should return -1 if there are less than 3 elements in input. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow . The first line of each test case is N,N is the size of array.The second line of each test case contains N space separated values of the array a[ ]. Output: Output for each test case will be the third largest element of the array . Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 100 1 ≤ A[ ] ≤ 100 Example(To be used for only expected output): Input: 1 5 2 4 1 3 5 Output: 3 """ import heapq if __name__=='__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().strip().split())) print(thirdLargest(arr, n)) def thirdLargest(arr, n): return heapq.nlargest(3,arr)[2] if n>2 else -1
""" Problem Link: https://www.interviewbit.com/problems/max-min-05542f2f-69aa-4253-9cc7-84eb7bf739c4/ Problem Description Given an array A of size N. You need to find the sum of Maximum and Minimum element in the given array. NOTE: You should make minimum number of comparisons. Problem Constraints 1 <= N <= 105 -109 <= A[i] <= 109 Input Format First and only argument is an integer array A of size N. Output Format Return an integer denoting the sum Maximum and Minimum element in the given array. Example Input Input 1: A = [-2, 1, -4, 5, 3] Input 2: A = [1, 3, 4, 1] Example Output Output 1: 1 Output 2: 5 Example Explanation Explanation 1: Maximum Element is 5 and Minimum element is -4. (5 + (-4)) = 1. Explanation 2: Maximum Element is 4 and Minimum element is 1. (4 + 1) = 5. """ class Solution: # @param A : list of integers # @return an integer def solve(self, A): min_num = float('inf') max_num = float('-inf') for num in A: if num > max_num: max_num = num if num < min_num: min_num = num return max_num + min_num
""" Problem Link: https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1 Given a linked list of length N. The task is to reverse the list. Input: First line of input contains number of testcases T. For each testcase, first line contains length of linked list and next line contains the elements of linked list. Output: Reverse the linked list and return head of the modified list. User Task: The task is to complete the function reverse() which head reference as the only argument and should return new head after reversing the list. Constraints: 1 <= T <= 100 1 <= N <= 103 Example: Input: 1 6 1 2 3 4 5 6 Output: 6 5 4 3 2 1 Explanation: Testcase 1: After reversing the list, elements are as 6->5->4->3->2->1. """ # Node Class class node: def __init__(self, val): self.data = val self.next = None # Linked List Class class Linked_List: def __init__(self): self.head = None self.lastNode = None def insert(self, val): if self.head == None: self.head = node(val) self.lastNode = self.head else: new_node = node(val) self.lastNode.next = new_node self.lastNode = new_node def createList(self, arr, n): for i in range(n): self.insert(arr[i]) return self.head reverse_List = reverseList def printList(self): tmp = self.head while tmp is not None: print(tmp.data, end=" ") tmp=tmp.next print() if __name__=='__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().strip().split())) lis = Linked_List() head = lis.createList(arr, n) lis.reverse_List() lis.printList() ''' Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above. ''' #function Template for python3 """ # Node Class class node: def __init__(self, val): self.data = val self.next = None """ # your task is to complete this function # function shouldn't return anything # use self.head to access head in the method def reverseList(self): # Code here if self.head is None: return None prev = None while self.head: temp = self.head.next self.head.next = prev prev = self.head self.head = temp self.head = prev
""" Problem Link: https://practice.geeksforgeeks.org/problems/facing-the-sun/0 Monu lives in a society which is having high rise buildings. This is the time of sunrise and monu wants see the buildings receiving the sunlight. Help him in counting the number of buildings recieving the sunlight. Given an array H representing heights of buildings. You have to count the buildings which will see the sunrise (Assume : Sun rise on the side of array starting point). Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N, N is the number of buildings. The second line of each test case contains N input H[i], height of ith building. Output: Print the total number of buildings which will see the sunset. Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 106 1 ≤ Hi ≤ 108 Example: Input: 2 5 7 4 8 2 9 4 2 3 4 5 Output: 3 4 Explanation: Testcase 1: Building with height 7, 8 and 9 will recieve the sunlight during sunrise. """ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) maxx = arr[0] count = 1 for i in range(1,n): if arr[i] > maxx: maxx = arr[i] count += 1 print(count)
""" Problem Link: https://practice.geeksforgeeks.org/problems/find-minimum-and-maximum-element-in-an-array/0 Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array. Input: The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains 2 lines of input. The first line of each testcase contains the size of array N. The following line contains elements of the array separated by spaces. Output: For each testcase, print the minimum and maximum element of the array. Constraints: 1 <= T <= 100 1 <= N <= 1000 1 <= Ai <=1012 Example: Input: 2 6 3 2 1 56 10000 167 5 1 345 234 21 56789 Output: 1 10000 1 56789 """ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) minn, maxx = float('inf'), float('-inf') for i in arr: if i > maxx: maxx = i if i < minn: minn = i print(minn,maxx)
""" Problem Link: https://practice.geeksforgeeks.org/problems/set-bits/0 Given a positive integer N, print count of set bits in it. For example, if the given number is 6(binary: 110), output should be 2 as there are two set bits in it. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each testcase contains single line of input containing the N. Output: For each test case, in a new line, print count of set bits in it. Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 106 Example: Input: 2 6 11 Output: 2 3 """ def countSetBits(n): if n == 0: return 0 return countSetBits(n&(n-1)) + 1 for _ in range(int(input())): print(countSetBits(int(input())))
""" Problem Link: https://practice.geeksforgeeks.org/problems/average/0 Given a stream of numbers, print average or mean of the stream at every point. Input: The first line of input contains an integer T denoting the number of test cases. For each test case there will be two lines. The first line contains an integer N denoting the size of array C[], and second line contains N space seperated integers C[i]. Output: Print the average of the stream at every point (in integer). Constraints: 1 ≤ T ≤ 20 1 ≤ N ≤ 50 1 ≤ C[i] ≤ 100 Example: Input 2 5 10 20 30 40 50 2 12 2 Output 10 15 20 25 30 12 7 """ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) res = [] summ = 0 for i in range(n): summ += arr[i] res.append(summ//(i+1)) print(*res)
""" Problem Link: https://practice.geeksforgeeks.org/problems/add-two-numbers-represented-by-linked-lists/1 Given two numbers represented by two linked lists of size N and M. The task is to return a sum list. The sum list which is a linked list representation of addition of two input numbers. Input: First line of input contains number of testcases T. For each testcase, first line of input contains length of first linked list and next line contains N elements of the linked list. Again, next line contains M, and following line contains M elements of the linked list. Output: Output the resultant linked list. User Task: The task is to complete the function addTwoLists() which has node reference of both the linked lists and returns the head of new list. Constraints: 1 <= T <= 100 1 <= N, M <= 100 Example: Input: 2 2 4 5 3 3 4 5 2 6 3 1 7 Output: 0 9 3 0 7 Explaination: 5->4 // linked list repsentation of 45. 5->4->3 // linked list representation of 345. 0->9 ->3 // linked list representation of 390 resultant linked list. """ import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) # Node Class class Node: def __init__(self, data): # data -> value stored in node self.data = data self.next = None # Linked List Class class LinkedList: def __init__(self): self.head = None # creates a new node with given value and appends it at the end of the linked list def append(self, new_value): new_node = Node(new_value) if self.head is None: self.head = new_node return curr_node = self.head while curr_node.next is not None: curr_node = curr_node.next curr_node.next = new_node # prints the elements of linked list starting with head def printList(head): if head is None: print(' ') return curr_node = head while curr_node: print(curr_node.data,end=" ") curr_node=curr_node.next print(' ') if __name__ == '__main__': t=int(input()) for cases in range(t): n_a = int(input()) a = LinkedList() # create a new linked list 'a'. nodes_a = list(map(int, input().strip().split())) nodes_a = nodes_a[::-1] # reverse the input array for x in nodes_a: a.append(x) # add to the end of the list n_b =int(input()) b = LinkedList() # create a new linked list 'b'. nodes_b = list(map(int, input().strip().split())) nodes_b = nodes_b[::-1] # reverse the input array for x in nodes_b: b.append(x) # add to the end of the list result_head = addBoth(a.head,b.head) printList(result_head) ''' This is a function problem.You only need to complete the function given below ''' #User function Template for python3 ''' Function to add two numbers represented in the form of the linked list. Function Arguments: head_a and head_b (heads of both the linked lists) Return Type: head of the resultant linked list. __>IMP : numbers are represented in reverse in the linked list. Ex: 145 is represented as 5->4->1. resultant head is expected in the same format. # Node Class class Node: def __init__(self, data): # data -> value stored in node self.data = data self.next = None ''' def addBoth(head_a,head_b): #code here res = Node(0) cur = res carry = 0 while head_a or head_b: x = head_a.data if head_a else 0 y = head_b.data if head_b else 0 summ = carry + x + y carry = summ // 10 cur.next = Node(summ%10) cur = cur.next if head_a: head_a = head_a.next if head_b: head_b = head_b.next if carry > 0: cur.next = Node(carry) return res.next
""" Problem Link: https://practice.geeksforgeeks.org/problems/remove-duplicate-elements-from-sorted-array/1 Given a sorted array A of size N. The function remove_duplicate takes two arguments . The first argument is the sorted array A[ ] and the second argument is 'N' the size of the array and returns the size of the new converted array A[ ] with no duplicate element. Input Format: The first line of input contains T denoting the no of test cases . Then T test cases follow . The first line of each test case contains an Integer N and the next line contains N space separated values of the array A[ ] . Output Format: For each test case output will be the transformed array with no duplicates. Your Task: Your task to complete the function remove_duplicate which removes the duplicate elements from the array . Constraints: 1 <= T <= 100 1 <= N <= 104 1 <= A[ ] <= 106 Example: Input (To be used only for expected output) : 2 5 2 2 2 2 2 3 1 2 2 Output 2 1 2 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. """ #Your code goes here if __name__=='__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().strip().split())) n = remove_duplicate(n, arr) for i in range(n): print (arr[i], end=" ") print() ''' This is a function problem.You only need to complete the function given below ''' #Your function should return an integer denoting the size of the new list def remove_duplicate(n, arr): #Code here if n == 0: return 0 j = 1 for i in range(1,n): if arr[i] != arr[i-1]: arr[j] = arr[i] j +=1 return j
""" Problem Link: https://practice.geeksforgeeks.org/problems/finger-game/0 Count the given numbers on your fingers and find the correct finger on which the number ends. The first number starts from the thumb, second on the index finger, third on the middle finger, fourth on the ring finger and fifth on the little finger. Again six comes on the ring finger and so on. Input: First line consists of T test cases. Only line input, one integer N. Output: Single line output, print the number of finger. Constraints: 1<=T<=5000 1<=N<=5000 Example: Input: 2 1 2 Output: 1 2 """ for _ in range(int(input())): n = int(input()) f = (n-1) % 8 print(f+1 if f < 5 else 10-f-1)
""" Problem Link: https://practice.geeksforgeeks.org/problems/twice-counter/0 Given an array of n words. Some words are repeated twice, we need count such words. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the number of words in the string. The next line contains n space separated words forming the string. Output: Print the count of the words which are repeated twice in the string. Constraints: 1<=T<=105 1<=no of words<=105 1<=length of each word<=105 Example: Input: 2 10 hate love peace love peace hate love peace love peace 8 Tom Jerry Thomas Tom Jerry Courage Tom Courage Output: 1 2 """ for _ in range(int(input())): n = int(input()) s = list(map(str,input().split())) count = 0 d = {} for i in s: d[i] = d.get(i,0) + 1 if d[i] == 2: count += 1 if d[i] == 3: count -= 1 print(count)
""" Problem Link: https://practice.geeksforgeeks.org/problems/path-in-matrix3805/1 Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c]. Matrix [r+1] [c] Matrix [r+1] [c-1] Matrix [r+1] [c+1] Starting from any column in row 0, return the largest sum of any of the paths up to row N-1. Example 1: Input: N = 2 Matrix = {{348, 391}, {618, 193}} Output: 1009 Explaination: The best path is 391 -> 618. It gives the sum = 1009. Example 2: Input: N = 2 Matrix = {{2, 2}, {2, 2}} Output: 4 Explaination: No matter which path is chosen, the output is 4. Your Task: You do not need to read input or print anything. Your task is to complete the function maximumPath() which takes the size N and the Matrix as input parameters and returns the highest maximum path sum. Expected Time Complexity: O(N*N) Expected Auxiliary Space: O(N*N) Constraints: 1 ≤ N ≤ 100 1 ≤ Matrix[i][j] ≤ 1000 """ class Solution: def maximumPath(self, N, Matrix): dp = [[0] * N for _ in range(N)] directions = [[1, 1], [1, -1], [1, 0]] max_path_sum = 0 for row in range(N-1, -1, -1): for col in range(N): max_val = 0 for r, c in directions: new_row = r + row new_col = c + col if new_row >= 0 and new_col >= 0 and new_row < N and new_col < N: max_val = max(max_val, dp[new_row][new_col]) dp[row][col] = Matrix[row][col] + max_val max_path_sum = max(max_path_sum, dp[row][col]) return max_path_sum
""" You are given a number N. Determine the number of positive even integers that are smaller than or equal to it and are not a multiple of 4. Input Format The first line contains a single integer T, denoting the number of test cases. Each of the next T lines contains a single integer, denoting the value of N. Output Format Print T lines, where the i-th line contains the answer to the i-th test case. SAMPLE INPUT 4 3 7 8 11 SAMPLE OUTPUT 1 2 2 3 Explanation For N=3, only 2 follows the given conditions, so answer is 1. For N=11, numbers 2, 6 and 10 follows the given conditions, so answer is 3. """ for _ in range(int(input())): n = int(input()) print((n//2)-(n//4))
""" Problem Link: https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1 Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M students such that : 1. Each student gets exactly one packet. 2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum. Example 1: Input: N = 8, M = 5 A = {3, 4, 1, 9, 56, 7, 9, 12} Output: 6 Explanation: The minimum difference between maximum chocolates and minimum chocolates is 9 - 3 = 6 by choosing following M packets : {3, 4, 9, 7, 9}. Example 2: Input: N = 7, M = 3 A = {7, 3, 2, 4, 9, 12, 56} Output: 2 Explanation: The minimum difference between maximum chocolates and minimum chocolates is 4 - 2 = 2 by choosing following M packets : {3, 2, 4}. Your Task: You don't need to take any input or print anything. Your task is to complete the function findMinDiff() which takes array A[ ], N and M as input parameters and returns the minimum possible difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student. Expected Time Complexity: O(N*Log(N)) Expected Auxiliary Space: O(1) Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 105 1 ≤ Ai ≤ 109 1 ≤ M ≤ N """ class Solution: def findMinDiff(self, A,N,M): A.sort() res = float('inf') M -= 1 index = 0 while M < N: res = min(res, A[M] - A[index]) index += 1 M += 1 return res
""" Given an array of penalties, an array of car numbers and also the date. The task is to find the total fine which will be collected on the given date. Fine is collected from odd-numbered cars on even dates and vice versa. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of three lines. First line of each test case contains two integers N & Date, second line contains N space separated car numbers and third line contains N space separated penalties. Output: For each test case,In new line print the total fine. Example: Input: 2 4 12 2375 7682 2325 2352 250 500 350 200 3 8 2222 2223 2224 200 300 400 Output: 600 300 """ t = int(input()) while t > 0: n,d = map(int,input().split()) carNumber = list(map(int,input().split())) fine = list(map(int,input().split())) collected_fine = 0 if d % 2 == 0: for i in range(n): if carNumber[i] % 2 != 0: collected_fine += fine[i] else: for i in range(n): if carNumber[i] % 2 == 0: collected_fine += fine[i] print(collected_fine) t -= 1
""" Problem Link: https://practice.geeksforgeeks.org/problems/identical-linked-lists/1 Given a Singly Linked List of size N. The task is to complete the function areIdentical(), which checks whether two linked list are identical or not. Two Linked Lists are identical when they have same data and arrangement of data is also same. Input: First line of input contains number of testcases T. For each testcase, first line of input contains length of linked lists N and M and next line contains elements of the linked lists. Output: For each test the output will be 'Identical' if two list are identical else 'Not identical'. User Task: The task is to complete the function areIdentical() which takes head of both linked lists as arguments and returns True or False. Constraints: 1 <= T <= 100 1 <= N <= 103 Example: Input: 2 6 1 2 3 4 5 6 4 99 59 42 20 5 1 2 3 4 5 5 1 2 3 4 5 Output: Not identical Identical Explanation: Testcase 1: Each element of first linked list is not equal to each elements of second linked list in the same order. Testcase 2: Each element of first linked list is equal to each elements of second linked list in the same order. """ # Node Class class node: def __init__(self, val): self.data = val self.next = None # Linked List Class class Linked_List: def __init__(self): self.head = None def insert(self, val): new_node = node(val) new_node.data = val new_node.next = self.head self.head = new_node def printList(head): while head: print(head.data, end=' ') head=head.next print() def createList(arr, n): lis = Linked_List() for i in range(n): lis.insert(arr[i]) return lis.head if __name__=='__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().strip().split())) head1 = createList(arr, n) n = int(input()) arr = list(map(int, input().strip().split())) head2 = createList(arr, n) if(areIdentical(head1, head2)): print('Identical') else: print('Not identical') ''' Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above. ''' # your task is to complete this function # function should return true/1 if both # are identical else return false/0 def areIdentical(head1, head2): # Code here if not head1 and not head2: return True if head1.data != head2.data: return False return areIdentical(head1.next,head2.next)
""" Problem Link: https://practice.geeksforgeeks.org/problems/binary-array-sorting/0 Given a binary array, sort it in non-decreasing order Input: First line contains an integer denoting the test cases 'T'. Every test case contains two lines, first line is size and second line is space separated elements of arra Output: Space separated elements of sorted arrays. There should be a new line between output of every test case. Input: 2 5 1 0 1 1 0 10 1 0 1 1 1 1 1 0 0 0 Output: 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 """ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) pos = -1 for i in range(n): if arr[i] == 0: pos+=1 arr[i],arr[pos] = arr[pos],arr[i] print(*arr)
""" Problem Link: https://practice.geeksforgeeks.org/problems/delete-without-head-pointer/1 You are given a pointer/reference to a node to be deleted in a linked list of size N. The task is to delete the node. Pointer/reference to head node is not given. You may assume that the node to be deleted is not the last node. Input: First line of input contains number of testcases T. For each testcase, first line of input contains length of linked list and next line contains the data of the linked list. The last line contains the node to be deleted. Output: For each testcase, print the linked list after deleting the given node. Constraints: 1 <= T <= 100 1 <= N <= 103 Example: Input: 2 2 1 2 1 4 10 20 4 30 20 Output: 2 10 4 30 Explanation: Testcase 1: After deleting 20 from the linked list, we have remaining nodes as 10, 4 and 30. """ import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) # Node Class class Node: def __init__(self, data): # data -> value stored in node self.data = data self.next = None # Linked List Class class LinkedList: def __init__(self): self.head = None # creates a new node with given value and appends it at the end of the linked list def append(self, new_value): new_node = Node(new_value) if self.head is None: self.head = new_node return curr_node = self.head while curr_node.next is not None: curr_node = curr_node.next curr_node.next = new_node def getNode(self,value): # return node with given value, if not present return None curr_node=self.head while(curr_node.next and curr_node.data != value): curr_node=curr_node.next if(curr_node.data==value): return curr_node else: return None # prints the elements of linked list starting with head def printList(self): if self.head is None: print(' ') return curr_node = self.head while curr_node: print(curr_node.data,end=" ") curr_node=curr_node.next print(' ') if __name__ == '__main__': t=int(input()) for cases in range(t): n = int(input()) a = LinkedList() # create a new linked list 'a'. nodes = list(map(int, input().strip().split())) for x in nodes: a.append(x) del_elem = int(input()) to_delete=a.getNode(del_elem) deleteNode(to_delete) a.printList() ''' This is a function problem.You only need to complete the function given below ''' #User function Template for python3 ''' Your task is to delete the given node from the linked list, without using head pointer. Function Arguments: node (given node to be deleted) Return Type: None, just delete the given node from the linked list. { # Node Class class Node: def __init__(self, data): # data -> value stored in node self.data = data self.next = None } ''' def deleteNode(curr_node): #code here if not curr_node: return None curr_node.data = curr_node.next.data curr_node.next = curr_node.next.next
""" Given a number your task is to complete the function convertFive which replace all zeros in the number with 5 and returns the number. Input: The first line of input contains an integer T denoting the number of test cases . Then T test cases follow . Each test case contains a single integer N denoting the number. Output: The output of the function will be an integer where all zero's are converted to 5 . Constraints: 1<=T<100 1<=N<=10000 Example: Input 2 1004 121 Ouput 1554 121 """ if __name__=='__main__': t = int(input()) for i in range(t): n=int(input()) print(convertFive(n)) def convertFive(n): # Code here res = 0 count = 1 while n: rem = n % 10 res += count*(5 if rem == 0 else rem) count *= 10 n //= 10 return res # def convertFive(n): # return str(n).replace("0","5")
""" Given an array, we need to find that element whose value is equal to that of its index value. Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N,N is the size of array. The second line of each test case contains N input A[]. Output: Print the elements whose value is equal to index value. Print "Not Found" when index value does not match with value. Note: There can be more than one element in the array which have same value as their index. You need to print every such element's index separated by a single space. Follows 1-based indexing of the array. Example: Input 2 5 15 2 45 12 7 1 1 Output 2 1 """ t = int(input()) while t > 0: n = int(input()) arr = list(map(int,input().split())) result = [] for i in range(0,n): if arr[i] == i+1: result.append(i+1) if len(result) == 0: print("Not Found") else: print(*result) t -= 1
""" Problem Link:https://www.hackerearth.com/problem/golf/is-it-the-same-1/ You are given two strings. You have to check if the strings are permutations of each other and output "YES" or "NO" accordingly without quotes. Input: 2 lines of input each containing a string. (a to z and 0 to 9) Output: A single line containing YES or NO. Constraints: String would not contain any spaces. size of string < 100 NOTE : This is a golf question. Shorter code will get highest points. SAMPLE INPUT mindsweepers swrepeesdnim SAMPLE OUTPUT YES """ from collections import Counter as C print("YES" if C(input()) == C(input()) else "NO")
""" Given a number N, you need to find if its digital root is prime or not. DigitalRoot of a number is the repetitive sum of its digits until we get a single digit number. Eg.DigitalRoot(191)=1+9+1=>11=>1+1=>2 Input: The first line of the input contains a single integer T, denoting the number of test cases. Then T test case follows. Each testcase contains a single line having N as input. Ouput: For each testcase, print 1 if the digitalRoot(N) is prime, else print 0. Example: Input: 3 89 45 12 Output: 0 0 1 Explanation: For testcase 1: DigitalRoot(89)=>17=>1+7=>8; not a prime. For testcase 3: DigitalRoot(12)=>1+3=>3; a prime number. """ def checkPrime(num): if num in [2,3,5,7]: return True return False def digitalRoot(num): #reference- https://en.wikipedia.org/wiki/Digital_root if num < 10: return num return num % 9 if num % 9 != 0 else 9 t = int(input()) while t > 0: num = int(input()) if checkPrime(digitalRoot(num)): print(1) else: print(0) t -= 1
""" Problem Link: https://practice.geeksforgeeks.org/problems/find-length-of-loop/1 Given a linked list of size N. The task is to complete the function countNodesinLoop() that checks whether a given Linked List contains loop or not and if loop is present then return the count of nodes in loop or else return 0. Input(to be used for Expected Output Only): First line of input contains number of testcases T. For each testcase, first line of input contains length of linked list and next line contains data of the linked list. Output: For each testcase, there will be a single line of output containing the length of loop in linked list, else print 0, if loop is not present in the linked list. User Task: The task is to complete the function countNodesinLoop() which contains the only argument as reference to head of linked list. Constraints: 1 <= T <= 100 1 <= N <= 500 Example: Input: 2 10 25 14 19 33 10 21 39 90 58 45 4 2 1 0 1 Output: 6 1 Explanation: Testcase 1: There is a loop of length 6 in the given linked list. """ #Initial Template for Python 3 # Node class class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to prit the linked LinkedList def printList(self, node): temp = node while (temp): print(temp.data, end=" ") temp = temp.next def getHead(self): return self.head def createLoop(self, n): if n == 0: return None temp = self.head ptr = self.head cnt = 1 while (cnt != n): ptr = ptr.next cnt += 1 # print ptr.data while (temp.next): temp = temp.next temp.next = ptr # Driver program if __name__ == '__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().strip().split())) lst = LinkedList() for i in arr: lst.push(i) ele = int(input()) lst.createLoop(ele) print(countNodesinLoop(lst.getHead())) ''' Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above. ''' #User function Template for python3 ##Complete this function def countNodesinLoop(head): # code here if not head: return 0 slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if fast == slow: break if not fast: return 0 if not fast.next: return 0 count = 0 slow = slow.next while slow != fast: count += 1 slow = slow.next return count
""" Problem Link: https://practice.geeksforgeeks.org/problems/anshumans-favourite-number/0 You are given an integer input N and you have to find whether it is Anshuman’s favourite or not. If it is then print “YES” else print “NO”. A number is Anshuman’s favourite if it is either the sum or the difference of the integer 5. (5+5, 5+5+5, 5-5,5-5-5+5+5…..) Input: The first line of input contains an integer denoting the number of test cases . Next line of input contains an integer N to be tested. Output: For each test case , the output is in a new line containg the answer 'YES' or 'NO' depending on whether the given number N is Anshuman's favourite or not . Constraints: 1<=T<=100 -10^9<=N<=10^9 Example: Input : 1 10 Output : YES Because 10 can be written as a sum of 5+5. Example: Input : 1 9 Output : NO Input : 2 -255 389 Output : YES NO """ for _ in range(int(input())): print("YES" if int(input()) % 5 == 0 else "NO")
#!/usr/bin/env python3 class Block: """1 sodoku block""" def __init__(self): self.squares = [None for i in range(9)] def setSquare(self, index, number): self.squares[index] = number def getSquare(self, index): return self.squares[index] def setSquareRowColumn(self, row, column, number): self.setSquare(row * 3 + column, number) def getSquareRowColumn(self, row, column): return self.getSquare(row * 3 + column) def getRowSquares(self, row): return [self.squares[row * 3 + 0], self.squares[row * 3 + 1], self.squares[row * 3 + 2]] def getColumnSquares(self, column): return [self.squares[column + 0], self.squares[column + 3], self.squares[column + 6]] def isNumberInRow(self, row, number): return number in self.getRowSquares(row) def isNumberInColumn(self, column, number): return number in self.getColumnSquares(column) class Sodoku: def __init__(self): self.blocks = [Block() for i in range(9)] def calculateBlockRowColumn(self, row, column): sodokuRow = int(row / 3) sodokuColumn = int(column / 3) blockRow = row % 3 blockColumn = column % 3 return [sodokuRow * 3 + sodokuColumn, blockRow, blockColumn] def setSquareRowColumn(self, row, column, number): block, blockRow, blockColumn = self.calculateBlockRowColumn(row, column) self.blocks[block].setSquareRowColumn(blockRow, blockColumn, number) def getSquareRowColumn(self, row, column): block, blockRow, blockColumn = self.calculateBlockRowColumn(row, column) return (self.blocks[block].getSquareRowColumn(blockRow, blockColumn)) def getRowSquares(self, row): return [self.getSquareRowColumn(row, i) for i in range(9)] def getColumnSquares(self, column): return [self.getSquareRowColumn(i, column) for i in range(9)] def isNumberInRow(self, row, number): return number in self.getRowSquares(row) def isNumberInColumn(self, column, number): return number in self.getColumnSquares(column) def isNumberInBlock(self, block, number): return number in self.blocks[block].squares def setSquareBlockRowColumn(self, block, row, column, number): self.blocks[block].setSquareRowColumn(row, column, number) def getSquareBlockRowColumn(self, block, row, column): return (self.blocks[block].getSquareRowColumn(row, column)) if __name__ == "__main__": a = Sodoku()
# 在假设已经给定汇率的情况下,要能对两种不同的币种金额相加,并将结果转换为某一种币种; # 要将某一金额与某一个数相乘,并得到一个总金额 from stock.dollar import Dollar from stock.swiss_franc import SwissFranc from stock.money import Money def test_multi_stock_price(): five = Dollar(5) ten = five.times(2) assert ten.amount == 10 fifteen = five.times(3) assert fifteen.amount == 15 def test_same_currency(): five_dollar1 = Dollar(5) five_dollar2 = Dollar(5) assert five_dollar1 == five_dollar2 six_dollar = Dollar(6) assert five_dollar1 != six_dollar def test_swiss_franc(): five_swiss_franc = SwissFranc(5) assert five_swiss_franc.amount == 5 def test_swiss_franc_multi_amount(): five_swiss_franc = SwissFranc(5) ten_swiss_franc = five_swiss_franc.times(2) assert ten_swiss_franc.amount == 10 fifteen_swiss_franc = five_swiss_franc.times(3) assert fifteen_swiss_franc == SwissFranc(15) def test_two_currency_is_same(): five_dollar = Dollar(5) five_swiss_franc = SwissFranc(5) assert five_dollar != five_swiss_franc def test_currency_name(): five_dollar = Dollar(5) five_swiss_franc = SwissFranc(5) assert five_dollar.currency == 'USD' assert five_swiss_franc.currency == 'CHF' def test_the_same_money_add(): five_dollar = Dollar(5) ten_dollar = Dollar(10) assert five_dollar.plus(ten_dollar) == Dollar(15) def test_the_diff_money_add(): five_dollar = Dollar(5) five_swiss_franc = SwissFranc(10) assert five_dollar.plus(five_swiss_franc) == Dollar(10)
""" 无重复字符的最长字串 使用滑动窗口的方法 滑动窗口都终点向字符串末尾移动,如果出现重复字符,则滑动窗口都起始位置一只向后移动,直到窗口内没有重复字符,再将终点向后移动 统计移动过程中出现的最长字符串 """ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: from collections import defaultdict lookup = defaultdict(int) start = 0 end = 0 counter = 0 max_len = 0 while end < len(s): # 从第一个字符循环到最后一个字符 if lookup[s[end]] > 0: # 如果字典出现该字符的值大于0,说明该字符已经出现,因为出现过的字符值都为1 counter += 1 # 出现重复字符,则计数加1 lookup[s[end]] += 1 # 将每个字符作为键,初始值为1 end += 1 # 滑动窗口都终点向后移动一位 while counter > 0: # 当出现重复字符都情况 if lookup[s[start]] > 1: #判断滑动窗口都第一个字符是不是重复字符 counter -= 1 # 如果是重复字符,则将计数减1 lookup[s[start]] -= 1 # 将滑动窗口都起点对应字符都值减1(设置成初始值0),防止下一次滑动窗口出现相同字符 start += 1 # 将滑动窗口的起始位置向后移动,直到将重复字符移出窗口 max_len = max(max_len, end - start) # 再出现重复字符之前,end - start就是无重复字符的长度,出现重复字符之后,start的位置变成重复字符的下一个字符 return max(max_len, end - start) # 若最长无重复字符需要等到窗口移动到最后一个字符才出现,那么需要与之前的最长字符进行比较 if __name__ == '__main__': S = Solution() max_len = S.lengthOfLongestSubstring("abca") print(max_len)
#A brute solution class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ index_of_zero = 0 for i in range(len(nums)): if nums[i] == 0: nums.insert(index_of_zero, 0) del nums[i+1] index_of_zero += 1 nums[::] = nums[index_of_zero:] + nums[:index_of_zero] #A more elegant solution class Solution2(object): def moveZeroes(self, nums): j = 0 for i in range(len(nums)): if nums[i]!=0: temp = nums[j] nums[j] = nums[i] nums[i] = temp j += 1 nums = [0, 1, 0, 3, 12,0] s = Solution2() s.moveZeroes(nums) print nums
# -*- coding: utf-8 -*- """ Created on Tue Oct 23 15:42:20 2018 @author: zhaoxu 326. Power of Three """ class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ if n == 0: return False if n == 1: return True while (n > 3): n = n / 3.0 return (n - 3.0) == 0
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 13:52:07 2019 @author: Sue 279. Perfect Squares """ import math class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ if (n <= 0): return 0 if (n == 2): return 2 #check if it's perfect square number if (int(math.sqrt(n)) == math.sqrt(n)): return 1 memo = [1 for i in range(n+1)] memo[2] = 2 for i in range(3, n+1): si = int(math.sqrt(i)) if (si == math.sqrt(i)): memo[i] = 1 else: minI = 2 * i for s in range(1, si+1): numI = memo[i - s ** 2] + 1 if numI < minI: minI = numI memo[i] = minI print("i = ", i, " memo[i] = ", memo[i]) return memo[n]
# -*- coding: utf-8 -*- """ Created on Wed Aug 1 15:05:16 2018 @author: zhaoxu 169. Majority Element """ class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ return sorted(nums)[int(len(nums)/2)] """ l = len(nums) if l <= 2: return nums[0] for i in range(int(l/2)+1): # print("i = ",i) # print("l/2 = " , l/2) # print("nums.count(nums[i]) = ", nums.count(nums[i])) # print("if? = ", nums.count(nums[i]) > (l/2)) if nums.count(nums[i]) > (l/2): return nums[i] """
# -*- coding: utf-8 -*- """ Created on Thu Jan 17 14:42:41 2019 @author: Sue 814. Binary Tree Pruning """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def hasOne(self, root): """ :type root: TreeNode :rtype: Boolean """ if (root is None): return False if (root.val == 1): return True return self.hasOne(root.left) or self.hasOne(root.right) def pruneTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if (root is None): return root if (self.hasOne(root.left)): root.left = self.pruneTree(root.left) else: root.left = None if (self.hasOne(root.right)): root.right = self.pruneTree(root.right) else: root.right = None return root
# -*- coding: utf-8 -*- """ Created on Mon Apr 8 14:59:03 2019 @author: Sue 103. Binary Tree Zigzag Level Order Traversal """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None from queue import Queue class Solution: def zigzagLevelOrder(self, root: TreeNode) :#-> List[List[int]]: if (root is None): return [] res = [] q = Queue() #(level, direction, tree) #true : left to right #false: right to left q.put((0, True, root)) while (not q.empty()): top = q.get() level = top[0] leftToRight = top[1] node = top[2] if(level >= len(res)): res.append([node.val]) else: #res[level] has existed if leftToRight: res[level].append(node.val) else: res[level] = [node.val] + res[level] if (node.left): q.put((level+1, not leftToRight, node.left)) if (node.right): q.put((level+1, not leftToRight, node.right)) return res
# -*- coding: utf-8 -*- """ Created on Wed Oct 24 11:14:13 2018 @author: zhaoxu 387 First Unique Character in s String """ class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ #this is accepted, which means functin 'in' is faster than function 'count' #but the overall speed is still low, which could only beat 8% other python solution for i in range(len(s)): if (s[i] not in s[0:i]) and (s[i] not in s[i+1:]) : return i return -1 """ #fail: time limit exceeded if len(s) == 0 : return -1 for i in range(len(s)): if s.count(s[i]) == 1: return i return -1 """
# -*- coding: utf-8 -*- """ Created on Wed Feb 27 11:22:00 2019 @author: Sue 092. Reverse Linked List II """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseToN(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if(n <= 1): return head prev = head m = n print("Find Tail") while (m >= 1): print("prev.val = ", prev.val) prev = prev.next m -= 1 cur = head print("Reverse Start") while (n >= 1): print("cur.val = ",cur.val) tail = cur.next cur.next = prev prev = cur cur = tail n -= 1 return prev def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ if(m >= n): return head if(m == 1): return self.reverseToN(head, n) #m<n prev = ListNode(None) prev.next = head while(m > 1): prev = prev.next m -= 1 n -= 1 prev.next = self.reverseToN(prev.next, n) return head
# -*- coding: utf-8 -*- """ Created on Mon Oct 22 10:27:43 2018 @author: zhaoxu 121 Best Time to Buy and Sell Stock """ class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ #use two pointers #minPrice : is the lowest price #maxProfit: is the current maxProfit maxProfit = 0 if len(prices) == 0: return maxProfit minPrice = prices[0] for p in prices[1:]: if (p - minPrice) > maxProfit: maxProfit = p - minPrice if (p < minPrice): minPrice = p return maxProfit """ #first try failed: time limit exceeded maxProfit = [] for i in range(len(prices) - 1): tmpList = prices[i+1:] if(len(tmpList) != 0): buyP = prices[i] sellP = max(tmpList) thisMax = sellP - buyP if(thisMax >= 0): maxProfit.append(thisMax) if len(maxProfit) == 0: return 0 else: return max(maxProfit) """
# # Testing.py # import unittest class TestCase(unittest.TestCase): def assertEqual(self, actual, expected): if actual == expected: return print "actual =", actual print "expected =", expected unittest.TestCase.assertEqual(actual, expected)
def binarySearch(alist, item): """Perform binary search for a data sequence. Binary Search starts off with comparing the item in the middle with the target. If the searched item is bigger than the target item, the second half of the sequence will be discarded. If the searched item is smaller than the target item, the first half of the sequence will be discarded. """ 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
import datetime currentTime = datetime.datetime.now() hour = currentTime.hour minute = currentTime.minute def createSchedule(): schedule = [['Python video', 20], ['Python Project', 30], ['kleine pauze', 10], ['zang oefenen', 20], ['piano oefenen', 30], ['grote pauze', 30], ['project Munnik', 120], ['einde', 20]] print('Je planning voor vandaag:') for x in schedule: global minute, hour print(str(hour)+' '+str(minute)+' '+x[0]) minute += x[1] keepTime() def keepTime(): global minute, hour while minute > 59: hour += 1 minute -= 60 if hour > 23: hour = 0 x = input('Nu beginnen? type y ') if x == 'y': createSchedule() else: y = input('welk uur(24H) ') hour = int(y) y = input('welke minuut ') minute = int(y) createSchedule()
# -*- coding: utf-8 -*- """ Created on Sat Sep 15 02:26:52 2018 @author: Anjani K Shiwakoti """ # METHOD 1: USING ITERATION def gcdIter(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if a>b: bigger = a smaller = b else : bigger = b smaller = a # set the smaller number as divisor div = smaller if bigger % div == 0: return div else: # iterate throuh the divisor from high to low until we find the right div while div >= 1: if div == 1: return 1 if (smaller % div == 0) and (bigger % div == 0): return div div = div - 1 # end of while loop # test cases x1 = gcdIter(5, 15) print (x1) x2 = gcdIter(16, 40) print (x2) x3 = gcdIter(27, 13) print (x3) x4 = gcdIter(11, 11) print (x4) #--------------------------------------------------------------------------------------------------------------------------------------- METHOD 2: USING RECURSION # -*- coding: utf-8 -*- """ Created on Sat Feb 02 14:11:49 2019 @author: AnjaniK Shiwakoti """ def gcdRecur(a, b): ''' Input: a, b: positive integers Process: Using Euclid's method of calculating the greatest common divisor Output: Returns a positive integer, the greatest common divisor of a & b. ''' # base case if b == 0: return a else: return gcdRecur(b, a % b) #--------------------------------------------------------------------------------------------------------------------------------------- METHOD 3: USING RECURSION TO FIND GENERALIZED GCD FOR A LIST OF N POSITIVE INTEGERS def generalizedGCD(num, arr): """ Computes the greatest common divisor(GCD) or highest common factor(HCF) Input: num - an int representing the number of positive integers (N) arr - a list of positive integers Output: returns an integer representing the GCD or HCF of the given positive integers """ # edge cases # if list is empty if num == 0: return None # if list contains single element if num == 1: return arr[0] # if list contains a zero, avoid division by zero by returning None if any(arr) == 0: return None # helper function to compute GCD for all else def GCDRecur(a, b): """ recursion method to compute GCD """ # base case if b == 0: return a else: return GCDRecur(b, a%b) # take an adjacent pair at a time and compute their GCD, # keep track of their GCD on a list and move next until all pairs are visited # then return the minimun of the list of GCD's as our final result result_list = [] for i in range(num-1): result = GCDRecur(arr[i],arr[i+1]) result_list.append(result) #print(result_list) return min(result_list)
# -*- coding: utf-8 -*- """ Created on Sun Mar 31 13:47:46 2019 @author: Anjani K Shiwakoti Synopsis: Given starting address and destination address, calculate the geodesic distance between the two locations. A geodesic line is the shortest path between two points on a curved surface, like the Earth. """ from geopy.geocoders import Nominatim from geopy.distance import geodesic global location global geolocator geolocator = Nominatim(user_agent="my_geo_location_tracker") def getCoordinates(address): location = geolocator.geocode(address) #print(location.raw) #{'place_id': '9167009604', 'type': 'attraction', ...} return (location.latitude, location.longitude) def getAddress(address): location = geolocator.geocode(address) return location.address def getDistance(pointA, pointB): starting_coords = getCoordinates(pointA) destination_coords = getCoordinates(pointB) return (geodesic(starting_coords, destination_coords).miles) starting_address = input("Enter Your Starting Address: ") destination_address = input("Enter Your Destination Address: ") print ("Your total geodesic distance between: ", getAddress(starting_address), " and ", getAddress(destination_address), " is: ", getDistance(starting_address, destination_address), "miles")
# -*- coding: utf-8 -*- """ Created on Sat Jan 2 14:19:59 2020 @author: Anjani K Shiwakoti Title: Solving Maximum Subarray Problem using Kadane's Algorithm (Dynamic Programming) Problem Definition: Given a 1-dimensional array (or a collection) find the contiguous subarray having the maximum sum of its array elements. Constraints: 1. The output subarray must be a contiguous array of elements (cannot skip any elements in the original array) 2. The output subarray can have at least one element and at most ALL 'n' elements, the sum of which yields the highest number. 3. If the array is empty, return None. Approach: Dynamic Programming is an iterative/recursive process for solving a complex problem by breaking it down into a collection of simpler subproblems, then solving each of those subproblems just once, and storing their solutions using a memory-based data structure (array, map, etc.), which is refered to as memoization. So, the next time the same sub-problem occurs, instead of recomputing its solution, one simply looks up the previously computed solution, thereby saving computation time. How Does it Work: Consider an array of integers, A. Start from the last element and calculate the sum of every possible subarray ending with the element A[n-1]. Calculate the sum of every possible subarray ending with A[n-2], A[n-3] and so on up to A[0]. For example, to calculate the local_maximum at, say, index 5, local_maximum[5], we dont need to compute the sum of all subarrays ending with A[5] since we already know the result from arrays ending with previous local maximum at index 4, A[4]. Intuition from Kadane's Algorithm: The local_maximum at index i is the maximum of A[i] and the sum of A[i] and local_maximum at index i-1. At every index i, the problem boils down to finding the maximum of just two numbers, A[i] and (A[i] + local_maximum[i-1]). Kadane's algorithm uses optimal substructures (the maximum subarray ending at each position is calculated in a simple way from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position) this algorithm can be viewed as a simple example of dynamic programming. Kadanes algorithm is able to find the maximum sum of a contiguous subarray in an array with a runtime of O(n) vs brute force approach which may take O(n^2). """ def MaxSumSubArray(xarray): """ Implements Kadane's Algorithm that finds contiguous substring with highest sum of its elements """ ### temporarily set the local_max and global_max variables to negative infinity ### so that when we are comparing max of two negative finite numbers, they're within the lower bound local_max = float("-inf") global_max = float("-inf") ### initialize an empty list to store our max sub array max_sub_array = [] def helper(sub_array, local_maximum, global_maximum, max_sub_array): array_size = len(sub_array) if array_size == 0: return (max_sub_array, global_maximum) ### take the maximum sum of the two local_maximum = max(sub_array[-1], sub_array[-1]+local_maximum) ### update the global maximum by resetting its value to the current local maximum if local_maximum > global_maximum: global_maximum = local_maximum ### decrement the array size array_size = array_size - 1 return helper(sub_array[:array_size], local_maximum, global_maximum, max_sub_array) return helper(xarray, local_max, global_max, max_sub_array) def main(): # test array array = [10, 12, -17, 40, -20, 0, 6, -11, 0, -1, 4, 3, -40, 15, -2, 3] max_sum_sub_array, max_sum = MaxSumSubArray(array) print (f"THE MAXIMUM SUM OF CONTIGUOUS SUBARRAY = {max_sum}.") if __name__=="__main__": main()
list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Print item in index 4 using bracket notation print(list[4]) # Print item in index 5 using negative [-1] index print(list[-4]) # Print every second item from the list print(list[0::2]) # Print items from 3rd to 5th print(list[3:5]) given_data = { 'foo': {'name': 'Foo', 'lastname': 'Fooer'}, 'bar': {'name': 'Bar', 'lastname': 'Baer'}, 'Baz': None } # Print all the keys print(given_data) # Print `bar`s `name` and lastname in format "Firstname is [NAME], and lastname is [LASTNAME]". Hint: Use string formatting & placeholders variable_1 = given_data['bar']['name'] variable_2 = given_data['bar']['lastname'] print(f'First name is {variable_1} and last name is {variable_2}.') # Loop over all keys and print the name as mentioned in the previous step IF the keys value is not empy. # 3. Create a function named `summer` which takes two parameters: `a` and `b` def summer(a, b): return a + b # Make the function return sum of the parameters. Note: Do NOT modify the original parameters print(summer(3, 5)) # Refactor the function to have default values to parameters # Refactor the function to have `**kwargs` and if alternate parameter `negatove` is `True` return the value as a negative sum. # 4. Given a list `['python', 'and', 'data', 'science', 'is', 'awesome']` # Create a new list from the given list using list comprehension and include item only if it's length is greater than 5 # Create a dict from the given list using comprehension where list index is the key and value is the actual value # Add item to the dict where the key is the next integer and value is "!" # 5. Create a function which takes a list-type parameter and returns a new list containing only integers from the parameter list in an descending order. e.g. if the function receives parameter `['x', -0.1, 'foo', True, 'bar', 10, 1.1, '8', 5, None, 12]`, it should return `[12, 10, 5]`. Note: Do not modify the original parameter and use list comprehension.
def selection_sort(l): for i in range(len(l)): mi=i for j in range(i+1,len(l)): if(l[mi]>l[j]): mi=j l[i],l[mi]=l[mi],l[i] return l l=list(map(int,input().split())) print(selection_sort(l))
import numpy as np class game(): def __init__(self): self.board = [['']*3 for _ in range(3)] self.occupied_error = 'Place is Already occupied, choose another place' self.wrong_place_error = 'Place is not on the board, choose numbers from 0 to 2' self.winner = None def reset(self): # Resets the board for the next game self.board = [[''] * 3 for _ in range(3)] self.winner = None return self.board def step(self, mark, place): # Goes a step forward on the board, checks if terminal and its rewards self.current_player = mark.lower() reward = 0 done = False wrong_place = True if (place[0] < 0 or place[0] > 2 or place[1] < 0 or place[1] > 2) else False if wrong_place: occupied = True else: occupied = True if self.board[place[0]][place[1]] != '' else False if not occupied and not wrong_place: self.board[place[0]][place[1]] = mark.lower() reward, done, self.winner, reason = self.get_reward() else: done = True reward = -10 reason = 'wrong_move' return self.board, reward, done, reason def get_reward(self): # Checks terminal states and current reward reward = 0 done = False winner = None reason = '' if self.check_horizontal(): reward = 3 winner = self.current_player reason = 'horizontal' done = True elif self.check_vertical(): reward = 1 winner = self.current_player reason = 'vertical' done = True elif self.check_diagonal(): reward = 1 winner = self.current_player reason = 'diagonal' done = True elif self.check_top_marks(): reward = 0.5 winner = self.top_marks_winner reason = 'tie' done = True return reward, done, winner, reason def check_horizontal(self): # Horizontal win terminal state for row in self.board: counter = {'x': 0, 'o': 0} for column in row: if column != '': counter[column] += 1 if counter[column] > 2: return True return False def check_diagonal(self): # Diagonal win terminal state counter = {'x': 0, 'o': 0} anti_counter = {'x': 0, 'o': 0} for i in range(3): if self.board[i][i] != '': counter[self.board[i][i]] += 1 if counter[self.board[i][i]] > 2: return True if self.board[2-i][i] != '': anti_counter[self.board[2-i][i]] += 1 if anti_counter[self.board[2-i][i]] > 2: return True return False def check_vertical(self): # Vertical win terminal state for i in range(3): counter = {'x': 0, 'o': 0} for j in range(3): if self.board[j][i] != '': counter[self.board[j][i]] += 1 if counter[self.board[j][i]] > 2: return True return False def check_top_marks(self): # Top row terminal state (only when the board is full) # If the board is full, checks the top row counter = 0 counter_player = {'x': 0, 'o': 0} for row in self.board: for entry in row: if entry == '': counter += 1 if counter == 0: for entry in self.board[0]: counter_player[entry] += 1 if counter_player[entry] > 1: self.top_marks_winner = entry return True return False if __name__ == '__main__': tic_tac_toe = game() print(tic_tac_toe.step('o', [0, 2])) print(tic_tac_toe.step('x', [0, 0])) print(tic_tac_toe.step('o', [2, 2])) print(tic_tac_toe.step('x', [1, 2])) print(tic_tac_toe.step('o', [1, 2]))
''' current_number =1 while current_number <=5: print(current_number) current_number +=1 prompt = "\nTell me sonmthing, and I will repeat it back to you:" prompt +="\nEnteer 'quit to end the program:" message ="" while message !='quit': message = input(prompt) if message != 'quit': print(message) #-----------------###-------------------------# prompt = "\nTell me sonmthing, and I will repeat it back to you:" prompt +="\nEnteer 'quit to end the program:" active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message) ############----------7.2.4--------------------####################### prompt = "\nTell me sonmthing, and I will repeat it back to you:" prompt +="\nEnteer 'quit to end the program:" while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to "+city.title()+"!") #----------------7.2.5--------# current_number = 0 while current_number <10: current_number +=1 if current_number %2 ==0: continue print(current_number) #-------------7.2.6------------# x =1 while x <=5: print(x) x +=1 #-------____ZuoYe__7-4__=== prompt = "\nTell me sonmthing, and I will repeat it back to you:" prompt +="\nEnteer 'quit to end the program:" while True: city = input(prompt) if city == 'quit': break else: print("You have add one: "+city.title()+"!") #------___7.5____++++ age = input("Tell me How old are you : ") age = int(age) if age < 3 : print("票价0") if 3<=age<=12 : print("票价10") if age>12: print("票价15") prompt = "\nTell me sonmthing, and I will repeat it back to you:" prompt +="\nEnteer 'quit to end the program:" while True: city = input(prompt) if city == 'quit': break else: print("You have add one: "+city.title()+"!") x = 0 while x <=100: print(x) x +=1 '''
''' #字典列表 alien_0 = {'color':'green','points':5} alien_1 = {'color':'yellow','points':10} alien_2 = {'color':'red','points':15} aliens= [alien_0, alien_1, alien_2] for alien in aliens: print(alien) #创建一个用于储存外星人的空列表 aliens = [] #创建30个绿色的外星人 for alien_number in range(30): new_alien = {'color':'green','points':'slow'} aliens.append(new_alien) #显示前五个外星人 for alien in aliens[:5]: print(alien) print("...") #显示创建了多少个外星人 print("Total number of aliens :"+ str(len(aliens))) ''' #创建一个用于储存外星人的空列表 aliens =[] #创建30个绿色的外星人 for alien_number in range(0,30): new_alien = {'color':'green','points':5, 'speed':'slow'} aliens.append(new_alien) for alien in aliens[0:3]: if alien['color']=='green': alien['color']='yellow' alien['speed']='mendium' alien['points']=10 #显示前五个外星人 for alien in aliens[0:5]: print(alien) print("...")
'''name = '' while name != 'your name': print('pleas type your name.') name = input() print('Thanke you !') #break 语句 while True: print('pleas type your name.') name = input() if name == 'your name ': break print('Thank you !') #continue 语句 while True: print('who are you?') name = input() if name != 'joe': continue print('hello,joe What is the passord? (it is a fish.)') password = input() if password =='sworfish': break print('Access granted.') #无限循环 #while True: # print('hell world!') #for 循环和 range()函数 name ='' while not name != '': print('Enter your name :') name = input() print('how many guests will you have?') numOfGuests = int(input()) if numOfGuests != 0: print('be sure to hame enough room for all your guests') print('Done') print('my name is') for i in range(5): print('jimmy five times( '+ str(i)+ ' ) ') #从0 加到 100 total = 0 for num in range(101): total = total + num print(total) #等价的 while 循环 print('my name is ') i = 0 while i < 5: i = i + 1 print('jimmy five times( '+ str(i)+ ' ) ') #range()的开始、停止和步长参数 #range(起始值,上线(不包含本身),间隔) for i in range(12, 16): print(i) #随机数 import random for i in range(5): print(random.randint(1,100)) import sys while True: print('Tpye exit to exit .') response = input() if response == 'exit': sys.exit() print('you typed ' + response + '.') #第九题 spam = input('请输入:') if spam.isdigit(): spam = int(spam) if spam == 1: print('hell ') elif spam == 2 : print('howdy ') else : print('gggg') number = range(1,11) for i in number: print(i) number = 0 while number < 10: number += 1 print(number) #调用 from spam in bacon spam.bacon() def spam(): print(eggs) eggs = 42 spam() print(eggs) #sameName #3.5.4 名称相同的局部变量和全局变量 def spam(): eggs = 'spam local' print(eggs) def bacon(): eggs = 'bacon local' print(eggs) spam() print(eggs) eggs = 'global' bacon() print(eggs) def spam(): eggs = 'spam local' print(eggs) eggs = 'global' spam() def spam(divideBy): return 42 / divideBy try: print(spam(2)) print(spam(3)) print(spam(12)) print(spam(0)) print(spam(12)) except ZeroDivisionError: print('Error:iInvalid argumetn') ''' def spam(divideBy): try: return 42 / divideBy except ZeroDivisionError: print('Erroe InVALID argument') print(spam(2)) print(spam(4)) print(spam(5)) print(spam(6)) print(spam(0)) print(spam(2))
class User(): def __init__(self,first_name,last_name): self.first_name=first_name self.last_name=last_name self.login_attempts=0 def describe_user(self): print(self.first_name.title()+self.last_name.title()) def greet_user(self): print("Hello,"+self.first_name.title()+self.last_name.title()) def increment_login_attempts(self): self.login_attempts+=1 def reset_login_attempts(self): self.login_attempts=0 return self.login_attempts class Admin(User): def __init__(self,first_name,last_name): super().__init__(first_name,last_name) self.privileages= ['can add post','can ban user','no no no '] def show_privileages(self): for n in self.privileages: print("This is "+ n) A =Admin(' wangwang ',' ganggang') A.describe_user() A.show_privileages()
""" You toss n coins, each showing heads with probability p, independently of the other tosses. Each coin that shows tails is tossed again (once more, or when t=2). Let X be the total number of tails What is the probability mass function of the total number of tails? Start at main() function. """ import matplotlib.patches as mpatches import matplotlib.pyplot as plt from utils.PageSlider import PageSlider from utils.stats import simulated_binomial_pmf from utils.stats import get_theoretical_probabilities, get_simulated_probabilities def plot_coin_toss(n, p, t, simulations): start, end = 1, n x = range(start, end+1) width = 10 height = 7 fig, ax = plt.subplots(figsize=(width, height)) fig.subplots_adjust(bottom=0.2) theoretical_binomial_pmf_equation = r"$P(X=k)=\binom{n}{k}((1-p)^t)^k(1-(1-p)^t)^{(n-k)}$" # laTex plt.title("Binomial Dist. Simulation: {}".format(theoretical_binomial_pmf_equation)) plt.xlabel("K tails") plt.ylabel("Probability") # plot theoretical y y_theoretical = get_theoretical_probabilities(start, end, n, p, t) [y_theoretical_line] = ax.plot(x, y_theoretical, 'b-', label='Theoretical', marker='o') # plot simulated y y_simulated = get_simulated_probabilities(start, end, n, p, t, simulations) [y_simulated_line] = ax.plot(x, y_simulated, 'r--', label='Simulated (Experimental)', marker='o') # custom legend items legend_item1 = mpatches.Patch(color='red', label="simulations = {}".format(simulations)) legend_item2 = mpatches.Patch(color='black', label="t = {}".format(t)) handles, labels = ax.get_legend_handles_labels() plt.legend(handles=[*handles, legend_item1, legend_item2]) # description (under xlabel) txt = "'k' tails out of 'n' coins, with a max of 't' tosses (RE-toss on tails)" plt.figtext(0.5, 0.015, txt, wrap=True, horizontalalignment='center', fontsize=12) # setup sliders num_pages = 10 tosses_slider_ax = fig.add_axes([0.1, 0.07, 0.8, 0.04]) # dimensions for slider toss_slider = PageSlider(tosses_slider_ax, 't', num_pages, activecolor="orange") # callback function def update(val): # set t label legend_item2.set_label("t = {}".format(int(val)+1)) ax.legend(handles=[*handles, legend_item1, legend_item2]) # compute new theoretical y new_theoretical_y = get_theoretical_probabilities(start, end, n, p, int(val)+1) y_theoretical_line.set_ydata(new_theoretical_y) # compute new simulated y new_simulated_y = get_simulated_probabilities(start, end, n, p, int(val)+1, simulations) y_simulated_line.set_ydata(new_simulated_y) # recompute the ax.dataLim ax.relim() # update ax.viewLim using the new dataLim ax.autoscale_view() fig.canvas.draw() toss_slider.on_changed(update) plt.show() def simulate_coin_toss_tails(num_coins, k, p_tails, tosses, simulations): final_result = simulated_binomial_pmf(num_coins, k, p_tails, tosses, simulations) print("Result: {}".format(final_result)) def main(): """ This program will simulate the coin toss scenario above and compare simulated results to theoretical results. """ t = 1 n = 25 # k = 4 p_tails = 0.5 # result = binomial_pmf(n, k, p_tails, t) # print("Theoretical probability with new formula: {}".format(result)) num_simulations = 1000 args = (n, p_tails, t, num_simulations) # print("Simulating coin toss with n={}, k={}, p_tails={}, t={}, and trials={}".format(*args)) # simulate_coin_toss_tails(*args) plot_coin_toss(*args) if __name__ == '__main__': main()
n1 = int(input('Um Valor:')) n2 = int(input('Outro valor:')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print('A soma eh {}, A muntiplicacao eh {} e a divisao e {:.3f}'.format(s , m, d), end='') #\n que a linha e end='' manter na mesma linha print('Divisao Inteira {} e Potencia{}'.format(di, e))
n = int(input("Digite um número de 4 a 9: ")) n_fora = n < 4 or n > 9 l = [] ana = 0 org = 0 while n_fora: n = int(input('Numero fora do intervalo! Digite novamente: ')) n_fora = n < 4 or n > 9 #print('Numero Aceito!!!') # essa mensagem pode ser trocado pelo inicio em outro código for x in range(1, n+1): nome = str(input('Digite o {}º nome: '.format(x))).upper().strip() l.insert(x, nome) if x == 3: l.insert(3,'TESTE') del l[2] ana = l.count('ANA') if ana > 0: print('O nome ANA aparece na posição {} da lista'.format(l.index('ANA'))) elif ana == 0: print('O nome ANA não existe na lista!') org = sorted(l) print('Alista Ordenada é {}'.format(org))
real =float(input('Quanto dinheiro voce tem na carteira? R$')) dollar = real / 3.27 euro = real / 4.85 yene = real / 0.65 peco = real / 0.31 print('Com R${:.2f} voce pode compra:\n US${:.2f}\n Er${:.2f}\n Ye${:.2f}\n Pc${:.2f}'.format(real, dollar, euro, yene, peco))
'''TUPLAS(que são listas imutaveis)- maneira de usar''' lanche = ('Hambúrger', 'Suco', 'Pizza', 'Pudim', 'Batata Frita') for comida in lanche: print(f'Eu vou comer {comida}') print() for cont in range(0, len(lanche)): print(lanche[cont]) print() for comida in enumerate(lanche): print(f'Eu vou comer {comida}') print() for pos, comida in enumerate(lanche): print(f'Eu vou comer {comida} na posição {pos}') print('Comi pra caramba!') #organiza print(sorted(lanche))
num = input() c = 0 lista = [] temp = num.split() for x in temp: lista.insert(c, int((temp[c]))) c += 1 n = 0 while n != 'final': n = input() comando = n.split() if 'inserir' in comando[0]: lista.append(int(comando[1])) lista.sort() if 'remover' in comando[0]: lista.remove(int(comando[1])) if 'parcial' in comando[0]: lista.sort() print(*lista, sep=' ') lista.sort() print(*lista, sep=' ')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Louan Mastrogiovanni """ import unittest from main import TestDbError, ConnectionDatabaseError from main import connect_to_db from main import get_users_list_from_db from main import add class TestCase(unittest.TestCase): """ Test class that checks the connection to the database using Unittest module. """ def test_connect_to_db(self): """""" with self.assertRaises(TestDbError): # verify that Exception "TestDbError" is raised. connect_to_db("test") with self.assertRaises(ConnectionDatabaseError): # verify that Exception "ConnectionDatabaseError" is raised. connect_to_db("xxx") def test_get_users_from_db(self): users = [ {"username": "Anne", "birthday": "11/11/1982", "role": "admin"}, {"username": "Jean", "birthday": "13/04/1976", "role": "user"}, {"username": "Pierre", "birthday": "05/05/1967", "role": "user"}, {"username": "Paul", "birthday": "02/04/1964", "role": "user"}, {"username": "Jacques", "birthday": "16/15/1998", "role": "user"}, {"username": "Marie", "birthday": "17/08/1974", "role": "user"}, {"username": "Sylvie", "birthday": "07/04/1970", "role": "user"}, {"username": "Michel", "birthday": "09/12/1975", "role": "user"}, {"username": "Françoise", "birthday": "07/12/1990", "role": "user"}, {"username": "Florent", "birthday": "15/04/1999", "role": "user"}, {"username": "Bertrand", "birthday": "05/08/1998", "role": "user"}, {"username": "Hélène", "birthday": "05/12/1970", "role": "user"}, {"username": "Louis", "birthday": "09/12/1965", "role": "user"}, {"username": "Marie", "birthday": "01/11/1991", "role": "user"}, {"username": "Florence", "birthday": "14/09/1987", "role": "user"}, {"username": "Frédéric", "birthday": "01/11/1985", "role": "user"}, {"username": "Vincent", "birthday": "11/12/1987", "role": "user"}, {"username": "Philippe", "birthday": "26/05/1972", "role": "user"}, {"username": "Christian", "birthday": "05/12/1999", "role": "user"}, {"username": "Louise", "birthday": "18/01/1991", "role": "user"}, ] def test_add(self): """ " Test function that verifies the add() method. """ for i in range(1, 200 + 1): for j in range(1, 200 + 1): for k in range(1, 200 + 1): value = i + j + k assert value == add(i, j, k) if __name__ == "__main__": unittest.main()
import math from queue import Queue import utils class Merger: """ A class for the merge functionality of posting files """ def __init__(self, path_to_files, file_type, docs_file, corpus_size=0): self.corpus_size = corpus_size self.queue = Queue() self.dict1 = None self.dict2 = None self.files_name = None self.file_type = file_type self.path_to_files = path_to_files self.docs_file = docs_file def merge(self, group_id): """ The merge function: The function will collect all the dictionaries from the posting file given and insert each dictionary to the queue. Algorithm used is the BSBI algorithm: for each two dictionaries: merged them, update the intersection keys in the merged dictionary and put the new merged dictionary back to the queue. To that until there is only 1 dictionary left in the queue. Save the last dictionary in the posting file. """ was_combined = False merged_dict = None self.files_name = group_id self.collect_files() while self.queue.qsize() > 1: if not was_combined: was_combined = True self.dict1 = self.queue.get() self.dict2 = self.queue.get() # merge the 2 dictionaries merged_dict = {**self.dict1, **self.dict2} for key in set(self.dict1.keys()).intersection(set(self.dict2.keys())): merged_dict[key]['docs'] = merged_dict[key]['docs'] + self.dict1[key]['docs'] merged_dict[key]['df'] = merged_dict[key]['df'] + self.dict1[key]['df'] self.calculate_doc_weight(merged_dict, key) self.queue.put(merged_dict) if was_combined: utils.save_obj(merged_dict, f"{self.path_to_files}\\{self.files_name}") else: file_dict = self.queue.get() for key in file_dict: self.calculate_doc_weight(file_dict, key) utils.save_obj(file_dict, f"{self.path_to_files}\\{self.files_name}") def collect_files(self): file_handle = utils.open_file(f"{self.path_to_files}\\{self.files_name}") obj = utils.get_next(file_handle) while obj: self.queue.put(obj) obj = utils.get_next(file_handle) utils.close_file(file_handle) def calculate_doc_weight(self, merged_dict, key): for i in range(len(merged_dict[key]['docs'])): term_tf = merged_dict[key]['docs'][i][1] doc_len = merged_dict[key]['docs'][i][2] term_df = merged_dict[key]['df'] doc_id = merged_dict[key]['docs'][i][0] max_tf = self.docs_file[doc_id][1] term_idf = math.log10(self.corpus_size / term_df) # save term's idf merged_dict[key]['idf'] = term_idf # calculate doc's total weight self.docs_file[doc_id][0] += 0.8 * (term_tf / max_tf) * term_idf + 0.2 * (term_tf / doc_len) * term_idf self.docs_file[doc_id][0] = round(self.docs_file[doc_id][0], 3)
class Sudoku(): def __init__(self, g): self.grid = [[int(g[i*9+j]) for j in range(9)] for i in range(9)] def getGrid(self): return self.grid def displayCase(self, i, j): if self.grid[i][j] == 0: return "." return self.grid[i][j] def displayGrid(self): l = "---"*10+"-" for i in range(9): if((i)%3==0): print(l) print(str.format("| {} {} {} | {} {} {} | {} {} {} |", self.displayCase(i, 0), self.displayCase(i, 1), self.displayCase(i, 2), self.displayCase(i, 3), self.displayCase(i, 4), self.displayCase(i, 5), self.displayCase(i, 6), self.displayCase(i, 7), self.displayCase(i, 8))) print(l)
mystr = "banana" myit = iter(mystr) ''' print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) ''' for x in mystr: print(x)
a = 200 b = 33 if b > a: print("A is greater that B") elif a == b: print("A is equal to B")
""" This file contains code to produce a graph of response functions for various threshold values """ from matplotlib import pyplot as plt import math thresholds=[.95,math.sqrt(2)/2,.5] resolution=200 def autocratic(threshold,move): if move>threshold: return math.sqrt(1-threshold**2) x=threshold*math.sqrt(1-move**2)-move*math.sqrt(1-threshold**2) return -threshold*x+math.sqrt((threshold**2-1)*(x**2-1)) if __name__=="__main__": plt.figure(figsize=(8, 6)) plt.hold=True for threshold in thresholds: xdata=[-1+i*2.0/(resolution-1) for i in range(resolution)] ydata=[autocratic(threshold,x)+math.sqrt(1-x*x) for x in xdata] plt.plot(xdata, ydata) plt.xlim(-1, 1) plt.ylim(-1, 2) plt.xlabel("Amount given to autocratic player") plt.ylabel("Total payoff to other player") plt.title("Achievable payoffs against autocratic players") plt.legend(["Threshold {:.3f} Ratio 1:{:.3f}".format(t,math.sqrt(1-t**2)/t) for t in thresholds]) plt.show()
""" This file contains a script to make a diagram showing how autocratic functions work """ from matplotlib import pyplot as plt from mkrespfuncgraph import autocratic import math resolution=101 plt.figure(figsize=(6, 6)) plt.hold=True plt.xlim(-2, 2) plt.ylim(-2, 2) plt.xlabel("Amount given to autocratic player") plt.ylabel("Amount given to other player") # Axises plt.plot([0,0],[-2,2],'k') plt.plot([-2,2],[0,0],'k') # Boundary of the choice set plt.plot([math.sin(2*math.pi*x/(resolution-1)) for x in range(resolution)],[math.cos(2*math.pi*x/(resolution-1)) for x in range(resolution)],'k') # Threshold move plt.plot([0,.8],[0,.6],'k') plt.plot([.8,.8],[0,.6],'k') plt.plot([.8,1.6],[.6,1.2],'k:') plt.plot([-.6,.6],[.8,-.8],'k') plt.plot([-.8,0],[.6,0],'b') plt.plot([-.8,0],[.6,0],'b:') #plt.plot([0,.8],[0,-.6],'b:') plt.text(-.85,.65,'1') #plt.text(.85,-.65,"1'") # sample move m=-.1 r=autocratic(.8,m) plt.plot([0,m],[0,math.sqrt(1-m*m)],'c') #plt.plot([0,math.sqrt(1-r*r)],[0,r],'c:') plt.plot([m,m+math.sqrt(1-r*r)],[math.sqrt(1-m*m),r+math.sqrt(1-m*m)],'c:') plt.text(m,math.sqrt(1-m*m)+.05,'2') #plt.text(math.sqrt(1-r*r)+.05,r,"2'") m=.6 r=autocratic(.8,m) plt.plot([0,m],[0,math.sqrt(1-m*m)],'g') #plt.plot([0,math.sqrt(1-r*r)],[0,r],'g:') plt.plot([m,m+math.sqrt(1-r*r)],[math.sqrt(1-m*m),r+math.sqrt(1-m*m)],'g:') plt.text(m,math.sqrt(1-m*m)+.05,'3') #plt.text(math.sqrt(1-r*r)+.05,r,"3'") m=.98 r=.6 plt.plot([0,m],[0,math.sqrt(1-m*m)],'r') #plt.plot([0,math.sqrt(1-r*r)],[0,r],'r:') plt.plot([m,m+math.sqrt(1-r*r)],[math.sqrt(1-m*m),r+math.sqrt(1-m*m)],'r:') plt.text(m+.01,math.sqrt(1-m*m)-.05,'4') #plt.text(math.sqrt(1-r*r)+.05,r,"4'") plt.text(.85,.55,'T') plt.text(.75,-.09,'0.8') plt.title("Autocratic Strategy Diagram") plt.show()
def Input(): num1=int(input('enter the first number')) num2=int(input('enter the second number')) return num1,num2 def addition(): num1,num2=Input() Result=num1+num2 return Result def output(): result=addition() print(result) output()
# create a BMI cal using OOP class BMI: # below expects weight and height def __init__(self, weight, height): self.weight = weight self.height = height self.pi = 3.14 # constant # above we define attr/var def get_bmi(self): answer = self.weight/(self.height ** 2) print('Your Body_Mass is ', answer) w = float(input('What is your Weight')) h = float(input('What is your Height')) object = BMI(w, h) object.get_bmi() # Option 1 # Google Colab Cloud - Jupyter Notebook # Watson Studio Cloud - Jupyter # Option 2 # in your laptop install Jupyter Notebook # from jupyter.net
# If Else Statements #Boolean Expression print(20 > 10) print(20 == 10) print(20 < 10) print(bool("Hello World")) print(bool(20)) Python Conditions Equals -> x == y Not Equals -> x != y Less than -> x < y Less than or equal to -> X <= y Greater than -> x > y Greater than or equal to-> x >= y x = 70 y = 60 if x < y: print("x is greater than y") elif x == y: print ("x is euqal to y") >>> x = 60 >>> y = 70 >>> if x < y: print ("x is less than y") ... x is less than y >>> >>> x = 50 >>> y = 150 >>> if x > y: ... print("x is greater than y") ... elif x == y: ... print("x and y are equal") ... else: ... print("x is less than y") x=int(input("num") if num<30: print(C) elif num<50: print(B) else: print(A)
from random import randint import time import datetime def loading_files(): database = open('countries_and_capitals.txt') # loading capitals database databaseContent = database.read() database.close() listOfFileLines = databaseContent.splitlines() asciiFile = open('ascii1.txt') # loading ascii graphic asciiGraphic = asciiFile.read() asciiGraphic = asciiGraphic.split('break') return listOfFileLines, asciiGraphic def intro(asciiGraphic): """Animation of game title Args: asciiGraphic (list): List of strings (asciiGraphics). """ for iterator in range(7): # Game Intro print(chr(27) + "[2J") # clear terminal screen print('\033[32m' + "Welcome in Nowak's Hangman!") print(asciiGraphic[iterator]) time.sleep(0.6) input('\033[31m' + 'Hit enter to continue') def print_lastgame_info(capital, country, attempt, life, timer): """Printing information about last game parameters. Args: capital (str): our chosen capital name country (str): name od country of chosen capital attempt (int): number of user guess attempts life (int): number of user lifes timer (float): duration of last game in seconds """ print('Hidden capital name was: ' + '\033[33m', end='') for letter in capital: print(letter, end=" ") print('\033[31m' + 'of' + '\033[33m', country) print('\n' + '\033[31m') print("It took you" + '\033[33m', int(timer), '\033[31m' + "s.") if life > 0: print("You guessed after" + '\033[33m', attempt, '\033[31m' + "attempts" + '\n') def guess_word(capital, life, wrongWords, numbUnguessed, hiddenCapital): """Check if user input is the same as our chosen capital and prints the information. Args: capital (str): our chosen capital name life (int): number of user lifes wrongWords (list): list of previous user wrong guessed capital names numbUnguessed (int): number of still unguessed letters in capital name Return: life (int): number of user lifes after guessing word numbUnguessed (int): number of still unguessed letters in capital name hiddenCapital (list): list of guessed letters in chosen capital with '_' in place of unguessed letter """ guess = input('Guess a word: ' + '\033[34m') print('\033[31m') guess = guess.upper() if guess == capital: # checking if word is correct print('correct') hiddenCapital = list(capital) numbUnguessed = 0 else: print('not correct') # loosing life life -= 2 wrongWords.append(guess) return life, numbUnguessed, hiddenCapital def guess_letter(capital, life, wrongLetters, hiddenCapital, numbUnguessed): """Check if user input is a letter included chosen capital and prints the information. Args: capital (str): our chosen capital name life (int): number of user lifes wrongLetters (list): list of previous user wrong guessed letters in capital name hiddenCapital (list): list of guessed letters in chosen capital with '_' in place of unguessed letter numbUnguessed (int): number of still unguessed letters in capital name Return: life (int): number of user lifes after guessing word numbUnguessed (int): number of still unguessed letters in capital name hiddenCapital (list): list of guessed letters in chosen capital with '_' in place of unguessed letter """ guess = '' while len(guess) != 1: guess = input('Guess a letter: ' + '\033[34m') print('\033[31m') if len(guess) != 1: print('You have to type a letter!') guess = guess.upper() if guess not in capital: # checking if letter is in capital life -= 1 wrongLetters.append(guess) print("You haven't guessed a letter!") else: print("You guessed a letter!") indexOfLetter = 0 for letter in capital: if guess == letter: if hiddenCapital[indexOfLetter] == '_': numbUnguessed -= 1 hiddenCapital[indexOfLetter] = letter indexOfLetter += 1 return life, numbUnguessed, hiddenCapital def single_game(numbUnguessed, capital, asciiGraphic, hiddenCapital, country): """Function continues until user correctly guess name of capital or user looses all lifes. Prints whole current game status and asks user what does he want to guess (letter or word). Starts proper function for guessing word or guessing letter. Args: numbUnguessed (int): number of still unguessed letters in capital name capital (str): our chosen capital name asciiGraphic (list): List of strings (asciiGraphics) hiddenCapital (list): list of guessed letters in chosen capital with '_' in place of unguessed letter country (str): name od country of chosen capital Return: life (int): number of user lifes after guessing word attempt (int): number of user guess attempts """ attempt = 0 life = 5 wrongWords = [] wrongLetters = [] # secondary loop repeating guessing until user has got lives and capital is unhidden while life > 0 and numbUnguessed > 0: print(chr(27) + "[2J") # clear terminal screen print(capital) # only for developers print('\033[32m' + asciiGraphic[life + 7] + '\033[31m') print('You have:' + '\033[33m', life, 'lives' + '\033[31m' + '\n') print('Unguessed letters left:' + '\033[33m', numbUnguessed, '\033[31m' + '\n') print('Hidden capital name is: ' + '\033[33m', end='') # prints hidden capital as letters (instead of list) for letter in hiddenCapital: print(letter, end=" ") print('\n' + '\033[31m') if life == 1: print("Hint: the capital of" + '\033[33m', country, '\033[31m') # prints unguessed letters as letters (instead of list) print('Previous unguessed letters: ' + '\033[33m', end='') for letter in wrongLetters: print("'" + letter + "'", end=" ") print('\n' + '\033[31m') print('Previous unguessed words: ' + '\033[33m', end='') # prints unguessed words as words (instead of list) for word in wrongWords: print(word, end=" ") print('\n' + '\033[31m') letterOrWord = '' while letterOrWord != 'l' and letterOrWord != 'w': # user chooses type of input (word or letter) letterOrWord = input('What do you want to type? Letter (l) or word (w): ') attempt += 1 if letterOrWord == 'w': life, numbUnguessed, hiddenCapital = guess_word(capital, life, wrongWords, numbUnguessed, hiddenCapital) else: life, numbUnguessed, hiddenCapital = guess_letter(capital, life, wrongLetters, hiddenCapital, numbUnguessed) return life, attempt def new_highscore_add(start, attempt, capital, timer): """Function which loads an existing highscore.txt as a list, turns it into a string and adds new score to that string. Args: start (float) : time of game start attempt (int) : stores information about in how many tries we guessed the capital capital (str) : a string of a capital to guess timer (float) : duration of a single game from start to finish Returns: highscoreContent (str) : string composed of highscore loaded from a txt file and new score information """ name = input('Type your name: ' + '\033[33m') # loading highscore and merging with new highscore print('\033[31m') highscore = open('highscore.txt') highscoreContent = highscore.read() highscoreContent = highscoreContent.splitlines() highscore.close() for line in range(len(highscoreContent)): # split highscoreContent string into list elements highscoreContent[line] = highscoreContent[line].split(' | ') date = str(datetime.date.today()) newHighscore = name + ' | ' + date + ' | ' + str(int(timer)) + ' | ' + str(attempt) + ' | ' + capital + ' ' newHighscore = newHighscore.split(' | ') highscoreContent.append(newHighscore) return highscoreContent def highscore_sort_and_save(highscoreContent): """Function which sorts highscore list by time of a game, turns highscore list into string and then writes that string into a file. Args: highscoreContent (list) : a list of single game highscore lines (each line is a list of elements) Returns: highscoreReconstruct (str) : a string containing the same data as list highscoreContent, but sorted and turned into string """ swaps = 1 # sorting highscore list by time while swaps > 0: swaps = 0 for i in range(len(highscoreContent)-1): if float(highscoreContent[i][2]) > float(highscoreContent[i+1][2]): highscoreContent[i], highscoreContent[i+1] = highscoreContent[i+1], highscoreContent[i] swaps += 1 if len(highscoreContent) > 10: highscoreContent = highscoreContent[:10] highscoreReconstruct = '' # reconstructing string from list for line in highscoreContent: iterator = 0 for word in line: highscoreReconstruct = highscoreReconstruct + word if iterator < len(line) - 1: highscoreReconstruct += ' | ' iterator += 1 highscoreReconstruct = highscoreReconstruct + '\n' highscore = open('highscore.txt', 'w') # writing highscore to the file highscore.write(highscoreReconstruct) highscore.close() return highscoreReconstruct def endgame(life, asciiGraphic, start, attempt, capital, country): """Function which checks winning conditions and prints information abt winning/losing and a highscore. Args: life (int): asciiGraphic (list): contains graphics loaded from a file start (float) : time of game start attempt (int) : stores information about in how many tries we guessed the capital country (str) : a string with a name of a country of capital we want to guess capital (str) : a string of a capital to guess """ print(chr(27) + "[2J") # clear terminal screen end = time.time() # finish counting game time timer = end - start if life <= 0: # checking winning conditions print('You have lost!') print('\033[32m' + asciiGraphic[7] + '\033[31m') highscore = open('highscore.txt') highscoreReconstruct = highscore.read() highscore.close() if life > 0: print('You won!') highscoreContent = new_highscore_add(start, attempt, capital, timer) highscoreReconstruct = highscore_sort_and_save(highscoreContent) print_lastgame_info(capital, country, attempt, life, timer) print_highscore(highscoreReconstruct) def print_highscore(highscoreReconstruct): """Function which prints highscore. Args: highscoreReconstruct (str) : a reconstructed string containing whole highscore data. """ print('\033[36m' + 'HIGHSCORE:' + '\n'*2) # printing HIGHSCORE highscorelines = highscoreReconstruct.splitlines() print(6 * ' ' + 'USER NAME' + 12 * ' ' + 'DATE' + 5 * ' ' + 'T[s]' + ' ' + 'GUESSED CAPITAL') for hsline in range(len(highscorelines)): part = highscorelines[hsline].split(' | ') if hsline < 9: part[0] = ' ' * (20 - len(part[0])) + part[0] else: part[0] = ' ' * (19 - len(part[0])) + part[0] print(hsline + 1, end='') for element in part: print(element, end=' | ') print('') print('\n'*2 + '\033[31m') def set_capital(listOfFileLines): """Function which chooses a random country&capital pair from loaded earlier file. Args: listOfFileLines (list) : a list made by opening our file with capitals and countries using splitlines(), where each line consist of a country&capital pair Returns: country (str) : a string with a name of a country of capital we want to guess capital (str) : a string of a capital to guess hiddenCapital (list) : a list consisting of '_' strings, length of this list equals to length of capital numbUnguessed (int) : an int containing an information about a number of letters we need to guess """ randomLine = listOfFileLines[randint(0, len(listOfFileLines)-1)] # randomizing capital randomLineSplitted = randomLine.split(' | ') country = randomLineSplitted[0].upper() capital = randomLineSplitted[1].upper() hiddenCapital = '' numbUnguessed = 0 for letter in capital: # ' ' in capital name is always unhidden if letter != ' ': hiddenCapital += "_" numbUnguessed += 1 else: hiddenCapital += ' ' hiddenCapital = list(hiddenCapital) return country, capital, hiddenCapital, numbUnguessed def main(): listOfFileLines, asciiGraphic = loading_files() intro(asciiGraphic) again = 'yes' while again == 'yes': # main loop repeating whole game until user requests country, capital, hiddenCapital, numbUnguessed = set_capital(listOfFileLines) print(chr(27) + "[2J") # clear terminal screen print("Try to guess what capital I've got on my mind.") input('Hit enter to continue') start = time.time() # start counting game time life, attempt = single_game(numbUnguessed, capital, asciiGraphic, hiddenCapital, country) endgame(life, asciiGraphic, start, attempt, capital, country) again = '' # user decides if he want to play again while again != 'yes' and again != 'no': again = input("Do you want to play again? [yes / no]: ") main()
arr = [int(i) for i in input().split()] for i in range(0,len(arr)): for j in range(i+1,len(arr)): if arr[j] < arr[i]: temp = arr[j] arr[j] = arr[i] arr[i] = temp print(arr)
str1 = "Apple" countDict = dict() for char in str1: count = str1.count(char) countDict[char]=count print(countDict)
def gcd(a, b): if(b == 0): return a else: rem = a%b return(gcd(b,rem)) a, b = map(int, input().split()) print(gcd(a, b))
from __future__ import print_function import numpy as np import chainer # Load the MNIST dataset from pre-inn chainer method train, test = chainer.datasets.get_mnist() # train[i] represents i-th data, there are 60000 training data # test data structure is same, but total 10000 test data print('len(train), type ', len(train), type(train)) print('len(test), type ', len(test), type(test)) # train[i] represents i-th data, type=tuple(x_i, y_i) # where x_i is image data and y_i is label data. print('train[0]', type(train[0]), len(train[0]), train[0]) # train[i][0] represents x_i, MNIST image data, # type=numpy(784,) vector <- specified by ndim of get_mnist() print('train[0][0]', train[0][0].shape, train[0][0]) # train[i][1] represents y_i, MNIST label data(0-9), type=numpy() scalar print('train[0][1]', train[0][1].shape, train[0][1]) # we cannot slice tupleDataset like this print('train[0:3][0]', type(train[0:3][0]), train[0:3][0]) # this is tuple class and not the set of x print('train[0:3][1]', type(train[0:3][1]), train[0:3][1]) # we can slice tupleDataset using numpy array nparray = np.asarray([0, 1, 2]) #nparray = np.asarray(list(range(4, 8))) print('train[[0,1,2]][0]', type(train[nparray][0]), train[nparray][0].shape, train[nparray][0]) print('train[[0,1,2]][1]', type(train[nparray][1]), train[nparray][1].shape, train[nparray][1]) print(list(range(4, 8)))
from room import Room from character import Enemy from character import Character kitchen = Room('Kitchen') kitchen.set_description("A dank and dirty room buzzing with flies.") dining_hall = Room('Dining Hall') dining_hall.set_description('A large room with ornate golden decorations on each wall.') ballroom = Room('Ballroom') ballroom.set_description("A vast room with a shiny wooden floor. Huge candlesticks guard the entrance.") ballroom.link_room(dining_hall, "east") kitchen.link_room(dining_hall, "south") dining_hall.link_room(ballroom, "west") dining_hall.link_room(kitchen, "north") dave = Enemy("Dave", "A smelly zombie") dave.set_conversation("What's up dude?") dave.set_weakness("banana") dining_hall.set_character(dave) catrina = Character("Catrina", "A friendly skeleton") catrina.set_conversation("Hello there!") ballroom.set_character(catrina) current_room = kitchen dead = False while dead == False: print("\n") current_room.get_details() inhabitant = current_room.get_character() if inhabitant is not None: inhabitant.describe() command = input("> ") if command in ["north", "south", "east", "west"]: current_room = current_room.move(command) elif command == "talk": if inhabitant is not None: inhabitant.talk() elif command == "fight": if inhabitant == None: print("There is no one here to fight with") else: print("What will you fight with?") fight_with = input() if inhabitant.fight(fight_with) == True: print("You won the fight!") current_room.set_character(None) else: print("Game over, you lose") dead = True
def create_record(name, telephone, address): """Create Record""" record = { 'name': name, 'phone': telephone, 'address': address, } return record def give_award(medal, *persons): """Give Medals to Persons""" for person in persons: print(person.title() + ' recived medal!') print('\n***** Example 1 *****') user1 = create_record('Vasya', 777, 'Teasdgwads') user2 = create_record('Ykrnrg', 333, 'Teasdgwads') user3 = create_record('jIIEgsg', 222, 'Teasdgwads') user4 = create_record('Ytwe', 555, 'Teasdgwads') print(user1) print(user2) print(user3) print(user4) print('\n***** Example 2 *****') give_award('Za hz', 'Vasya', 'Petya', 'Alexandr', 'Mudilo')
cars = ['BMW', 'Mersedes', 'Audi', 'Lamborgini', 'Tesla'] print('\t*** Example 1 ***') my_str = '' for car in cars: my_str += car + ' ' print(my_str) print('\n\t*** Example 2 ***') number_list = list(range(0, 10)) for x in number_list: number_list[x] = x * 2 print(number_list) number_list.sort(reverse=True) print(number_list) print('\n\t*** Example 3 ***') print('Max number is: ' + str(max(number_list))) print('Min number is: ' + str(min(number_list))) print('Sum of list\'s numbers is: ' + str(sum(number_list))) print('\n\t*** Example 4 ***') bit_of_cars = cars[1:4] print(bit_of_cars) bit_of_cars = cars[:3] print(bit_of_cars) bit_of_cars = cars[0:3] print(bit_of_cars) bit_of_cars = cars[2:] print(bit_of_cars) bit_of_cars = cars[-3:] print(bit_of_cars) bit_of_cars = cars[-4:-1] print(bit_of_cars) print('\n\t*** Example 5 ***') new_car = 'Aston Martin' # how to copy list new_cars = cars # wrong!!! copied a pointer for the list cars.append(new_car) print(new_cars) print(cars) new_cars = cars[:] # right!!! created a new list with same elements cars.remove(new_car) print(new_cars) print(cars)
x = int(input ("year of birth")) years = 2019 - x if years <= 18: print("you are a minor") elif years <= 35: print("you are a god damn youth") else: print ("you are an elder")
def check_index(index): if index == -1: raise TypeError('Invalid input line.') def get_next_pair(s,start): # This function will extract next pair of <<XXXX>>OOOOO from the input string # s with a starting index = start. The return value is a tuple (entry,value,index) # The 3rd value is the next un-read position, could be -1 if there is no more # input index_start = s.find('<<',start) if index_start == -1: return (None,None,-1) index_end = s.find('>>',index_start) check_index(index_end) entry = s[index_start + 2:index_end] start = index_end + 2 index_start = s.find('<<',start) if index_start == -1: value = s[start:] index_return = len(s) - 1 else: value = s[start:index_start] index_return = index_start return (entry,value,index_return) def analyze_syntax(s): # This function returns a dictionary, the index is exactly the <<INDEX>> # entry in the syntax file. Each keyword will fetch a list, the element of # which is just the lines with the same <<INDEX>>. Each list has four components # The first is called entry_list, the element of which is tuples with <<ENTRY>> # and <<POS>> being the 1st and 2nd element. The 2nd list is called tree_list # the element of which is tree name. The 3rd list is called family_list # the element of which is family name. The fourth list is called feature_list # the element of which is feature name. lines = s.splitlines() tokens = {} for l in lines: if l == '': continue start = 0 entry_list = [] tree_list = [] family_list = [] feature_list = [] line_name = 'noname' while True: next_pair = get_next_pair(l,start) start = next_pair[2] entry = next_pair[0] value = next_pair[1] if start == -1: break elif entry == 'INDEX': line_name = value elif entry == 'ENTRY': entry_name = value next_pair = get_next_pair(l,start) start = next_pair[2] check_index(start) entry = next_pair[0] value = next_pair[1] if entry != 'POS': raise TypeError('<<ENTRY>> must be followed by <<POS>>') else: pos = value entry_list.append((entry_name,pos)) elif entry == 'FAMILY': family_list = value.split() elif entry == 'TREES': tree_list = value.split() elif entry == 'FEATURES': feature_list = value.split() else: pass #raise TypeError('Unknown type: %s' % (entry)) temp = (entry_list,tree_list,family_list,feature_list) if tokens.has_key(line_name): tokens[line_name].append(temp) else: tokens[line_name] = [temp] return tokens #def debug(filename): # fp = open(filename) # s = fp.read() # fp.close() # print analyze_syntax(s)['Asian'] #if __name__ == '__main__': # debug('syntax-coded.flat')
"""A3. Tester for the function common_words in tweets. """ import unittest import tweets class TestCommonWords(unittest.TestCase): """Tester for the function common_words in tweets. """ def test_empty(self): """Empty dictionary.""" arg1 = {} arg2 = 1 exp_arg1 = {} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be\n {}, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_one_word_limit_one(self): """Dictionary with one word.""" arg1 = {'hello': 2} arg2 = 1 exp_arg1 = {'hello': 2} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_more_word_limit(self): """Dictionary with n words all remain.""" arg1 = {'hello': 2, 'bye': 3, 'night': 12} arg2 = 3 exp_arg1 = {'hello': 2, 'bye': 3, 'night': 12} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_remove_some(self): """Dictionary with some same value for words not to be included.""" arg1 = {'frosst': 4, 'google': 3, 'brain': 3, 'researcher': 5, 'by': 1} arg2 = 3 exp_arg1 = {'frosst': 4, 'researcher': 5} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_remove_all(self): """Dictionary with all same value for words none included.""" arg1 = {'frosst': 3, 'google': 3, 'brain': 3, 'researcher': 3, 'by': 3} arg2 = 3 exp_arg1 = {} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) if __name__ == '__main__': unittest.main(exit=False)
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(len(nums)): tmp = nums[i] for j in range(i, -1, -1): if 0 == j or nums[j - 1] <= tmp: nums[j] = tmp break else: nums[j] = nums[j - 1]
class Error(Exception): '''used for exception''' pass class ValueSmallError(Error): '''used for small value exception''' class ValueLargeError(Error): ''' used for large value error ''' number =20 while True: try: in_num = int(input("enter a number ")) if in_num > number: raise ValueLargeError elif in_num < number: raise ValueSmallError break except ValueSmallError: print("enterd value is too small \n") except ValueLargeError: print("entered value is too Large") print("this was a exceptional case practice ")
#!/usr/bin/env python import string import inspect class ActStatus(object): """ An enumerator representing the status of an act """ SUCCESS = 0 FAIL = 1 RUN = 2 class Act(object): """ An act is a node in a behavior tree that uses coroutines in its tick function """ def __init__(self, children = [], name = "", *args, **kwargs): self.name = name self.iterator = self.tick() if children is None: children = [] self.children = children def tick(self): pass def reset(self): self.iterator = self.tick() for child in self.children: child.reset() def add_child(self, child): self.children.append(child) def remove_child(self, child): self.children.remove(child) def suspend(self): pass def resume(self): pass def __enter__(self): return self.name; def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: return False return True class Select(Act): """ Runs all of its child acts in sequence until one succeeds. """ def __init__(self, children = [], name = "Select", *args, **kwargs): super(Select, self).__init__(children, name, *args, **kwargs) self.current_child = None def tick(self): for child in self.children: self.current_child = child for status in child.iterator: if status == ActStatus.RUN: yield status elif status == ActStatus.FAIL: yield ActStatus.RUN else: yield status return yield ActStatus.FAIL def suspend(self): if self.current_child: self.current_child.suspend() def resume(self): if self.current_child: self.current_child.resume() def reset(self): self.current_child = None Act.reset(self) class Sequence(Act): """ Runs all of its children in sequence until all succeed """ def __init__(self, children = [], name = "Sequence", *args, **kwargs): super(Sequence, self).__init__(children, name, *args, **kwargs) self.current_child = None def tick(self): for child in self.children: current_child = child for status in child.iterator: if status == ActStatus.RUN: yield status elif status == ActStatus.FAIL: yield ActStatus.FAIL return else: yield ActStatus.RUN yield ActStatus.SUCCESS def suspend(self): if self.current_child: self.current_child.suspend() def resume(self): if self.current_child: self.current_child.resume() def reset(self): self.current_child = None Act.reset(self) class Parallel(Act): """ Runs all of its children in parallel until one succeeds """ def __init__(self, children = [], name = "Parallel", *args, **kwargs): super(Parallel, self).__init__(children, name, *args, **kwargs) def tick(self): num_fails = 0 while True: if num_fails >= len(self.children): yield ActStatus.FAIL return try: for child in self.children: status = child.iterator.next() if status == ActStatus.SUCCESS: yield ActStatus.SUCCESS return elif status == ActStatus.FAIL: num_fails += 1 except StopIteration: continue yield ActStatus.FAIL def suspend(self): for child in self.children: child.suspend() def resume(self): for child in self.children: child.resume() class Loop(Act): """ Runs all of its children for some number of iters, regardless of whether one succeeds. If iterations is set to -1, loops indefinitely. If any child fails, returns FAIL. """ def __init__(self, children = [], name = "Loop", num_iter = -1, *args, **kwargs): super(Loop, self).__init__(children, name, *args, **kwargs) self.num_iter = num_iter self.iter = 1 self.current_child = None def tick(self): while True: if self.num_iter != -1 and self.iter >= self.num_iter: yield ActStatus.SUCCESS return for child in self.children: current_child = child for status in child.iterator: if status == ActStatus.RUN: yield status elif status == ActStatus.SUCCESS: yield ActStatus.RUN elif status == ActStatus.FAIL: yield ActStatus.FAIL return child.reset() self.iter += 1 yield ActStatus.SUCCESS def suspend(self): if self.current_child: self.current_child.suspend() def resume(self): if self.current_child: self.current_child.resume() class IgnoreFail(Act): """ Always return either RUNNING or SUCCESS. """ def __init__(self, children = [], name = "IgnoreFail", *args, **kwargs): super(IgnoreFail, self).__init__(children, name, *args, **kwargs) self.current_child = None def tick(self): for child in self.children: for status in child.iterator: if status == ActStatus.FAIL: yield ActStatus.SUCCESS else: yield status yield ActStatus.SUCCESS def suspend(self): if self.current_child: self.current_child.suspend() def resume(self): if self.current_child: self.current_child.resume() class Not(Act): """ Returns FAIL on SUCCESS, and SUCCESS on FAIL """ def __init__(self, children = [], name = "Not", *args, **kwargs): super(Not, self).__init__(children, name, *args, **kwargs) self.current_child = None def tick(self): for child in self.children: current_child = child for status in child.iterator: if status == ActStatus.FAIL: yield ActStatus.SUCCESS elif status == ActStatus.SUCCESS: yield ActStatus.FAIL else: yield status yield ActStatus.SUCCESS def reset(self): self.current_child = None Act.reset(self) def suspend(self): if self.current_child: self.current_child.suspend() def resume(self): if self.current_child: self.current_child.resume() class Wrap(Act): """ Wraps a function that returns FAIL or SUCCESS """ def __init__(self, wrap_function, children = [], name = "", *args, **kwargs): super(Wrap, self).__init__(children, name, *args, **kwargs) self.fn = wrap_function self.name = "Wrap " + inspect.getsource(self.fn) def tick(self): yield self.fn() def print_act_tree(printTree, indent = 0): """ Print the ASCII representation of an act tree. :param tree: The root of an act tree :param indent: the number of characters to indent the tree :return: nothing """ for child in printTree.children: print " " * indent, "-->", child.name if child.children != []: print_act_tree(child, indent + 1) def printobj(text): print text return ActStatus.SUCCESS if __name__ == "__main__": tree = Parallel( [ Loop( [ Wrap(lambda: printobj("Hello 1")), Wrap(lambda: printobj("Hello 2")) ], num_iter=10), Loop( [ Wrap(lambda: printobj("Hello 3")), Wrap(lambda: printobj("Hello 4")) ], num_iter=5), ] ) print_act_tree(tree) tree.reset() for status in tree.iterator: pass
# -*- coding: utf-8 -*- """ Created on Sat Dec 1 14:10:14 2018 @author: asingh368 """ from twilio.rest import Client # Your Account SID and Auth token from twilio account_sid = "" #Add account SID token here auth_token = "" #Add authorization token here # Both the above account SID and Auth token available on Twilio Homepage of the application you created client = Client(account_sid, auth_token) message = client.messages.create( body="Arya's first message!! Wozzaaaa", to = "", #Add the number you want to send the text to from_ = "") #Add the twilio phone number here print(message.sid)
A, B = map(int, input().split()) if(A%3==0): print("Possible") elif(B%3==0): print("Possible") elif((A+B)%3==0): print("Possible") else: print("Impossible")
import numpy as np import mnist import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense from keras.utils import to_categorical from keras.layers import Dropout ## IMPORT IMAGES AND LABELS ################################################## train_images = mnist.train_images() # handwritten numbers for learning train_labels = mnist.train_labels() # what numbers each image represents print(train_images.shape) # (60000, 28, 28) print(train_labels.shape) # (60000,) # can do print(train_labels[i]) to see what i'th image in array actually is. # can do print(train_images[i,:,:]) to see i'th image array. test_images = mnist.test_images() #handwritten numbers for testing test_labels = mnist.test_labels() #what numbers each image represents print(test_images.shape) # (10000, 28, 28) print(test_labels.shape) # (10000,) # show handwritten number image: # plt.imshow(train_images[i]) # plt.show() ## NORMALIZE IMAGES ########################################################## train_images = (train_images / 255) - 0.5 test_images = (test_images / 255) - 0.5 # usually between 0 and 255, now between -0.5 and 0.5. ## FLATTEN IMAGES ############################################################ train_images = train_images.reshape((-1, 784)) test_images = test_images.reshape((-1, 784)) #-1 to indicate we want a matrix of size i x 784, where i is to be found print(train_images.shape) # (60000, 784) print(test_images.shape) # (10000, 784) ## BUILDING THE MODEL ######################################################## model = Sequential([ Dense(64, activation='relu', input_shape=(784,),kernel_initializer='Constant'), Dense(64, activation='relu'), Dropout(0.25), Dense(10, activation='softmax'), ]) # sequential: creates linear stack of layers. # dense: fully connected layer (each neuron connected to every other neuron in # next network). # ReLU: x = 0 for x < 0, x = x for x > 0. # softmax: turns arbitrary numbers into probabilities. Mathematical expression # using exponentials bookmarked. # first: flattened input layer (passing individual data to individual neuron, # as opposed to sending a list (whole image array) to a neuron) with 64 # neurons, 784 tells the network the shape of the input. # second: dense layer with 64 neurons, with activation function ReLU. # third: another dense layer with 10 neurons (number values between 0 and 9), # and has activation function softmax (essentially probability the network # thinks the image is a specific number). ## COMPILING THE MODEL ####################################################### model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'], ) # optimizer: algorithm used to update the weights of the network. Adam is a # standard optimizer to use, there are many other though. Examples bookmarked. # loss: this function is used to compute the amount that the model should try # to minimize during training. Cross-entropy loss increases as the predicted # probability diverges from the actual label. A perfect model would have a log # loss of 0. # metrics: we are interested in the accuracy; basically how low we can get the # loss function to be. ## TRAINING THE MODEL ######################################################## history = model.fit( train_images, # training data to_categorical(train_labels), # training targets epochs=10, batch_size=32, validation_data=(test_images, to_categorical(test_labels)), #validation_split=0.66, ) # epochs: how many times the model sees each image and corresponding label. # It wont show the same types of images one after the other, but instead in # some other order. Basically the iterations over the entire dataset. # Increasing the number of epochs does not necessarily increase the accuracy, # the optimal number of epochs depends on your neural network. Increasing to # 10 for this example increases the accuracy, but with diminishing returns. # to_categorical: keras expects the training targets to be 10-dimensional # vectors, ours are 1-dimensional (1,2,3...etc). This basically turns our 1-D # target into a 10-D target (e.g. 3 -> [0,0,0,1,0,0,0,0,0,0]) # batch_size: number of training examples utilized in one iteration (number of # samples per gradient update). # accuracy we get should be ~96.6%. This is what our current model thinks the # accuracy will be from what it has learned. # from the tensorflow github page, the error 'WARNING:tensorflow:AutoGraph # could not transform...' seems to be normal and does not effect performance ## TESTING THE MODEL ######################################################### test_loss, test_acc = model.evaluate(test_images, to_categorical(test_labels)) print('Test accuracy:', test_acc) print('Test loss: ', test_loss) # evaluate(): returns an array containing the test loss followed by any # metrics we specified (accuracy in this case). ## SAVING THE MODEL ########################################################## # save the model to disk. model.save_weights('model.h5') # load the model from disk later using: # model.load_weights('model.h5') ## USING THE MODEL ########################################################### i = 5 # pick how many predictions to compare. predictions = model.predict(test_images[:i]) #predicts on the first 5 test images. On its own, the array 'predictions' #will have 10 probabilities for each number. We refine that below. print(np.argmax(predictions, axis=1)) # [7, 2, 1, 0, 4] # prints our model's predictions. np.argmax simply gets the highest value of # the array, corresponding to most highest probability. print(test_labels[:i]) # [7, 2, 1, 0, 4] # checks our predictions against the actual value. ## PLOTS ##################################################################### # accuracy vs epoch number plt.figure(1) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model Accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Trained', 'Test'], loc='best') plt.show() # loss vs epoch number plt.figure(2) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Trained', 'Test'], loc='best') plt.show() ## ACTIVATION VARIATION ###################################################### simple_accuracy = np.array(history.history['accuracy']) simple_val_accuracy = np.array(history.history['val_accuracy']) simple_loss = np.array(history.history['loss']) simple_val_loss = np.array(history.history['val_loss'])
#this program let player put in a number and let comput guess #Computer need guess it smartly import random print(""" Welcome to upgraded version of guess my number! In this game player will input a secret number btw 1 and 100. Computer will try to guess it in as few attempts as possible """) secret=int(input("\nEnter your secret number: ")) range_min = 1 range_max = 100 guess = random.randint(range_min, range_max) tries = 1 print("Guess:", guess, "attempt:", tries); while secret != guess: if guess > secret: range_max = guess else: range_min = guess guess = random.randint(range_min, range_max) tries += 1 print("Guess:", guess, "attempt:", tries); print("Congrats! Number is", secret, "after", tries, "!")
import shelve def user(): name=input("Put in your name: ") try: score=int(input("Put in your score: ")) except: print("Sorry, you did not put in a whole number. Pls put in a whole number.") else: return name, score def update(name, score): hs=shelve.open("HSHS.dat") hs[name]=str(score) hs.close() def display(): hs=shelve.open("HSHS.dat") print("The scoreboard is shown below:") for key in hs: print(key, ":", hs[key]) def main(): name=None score=None while not name or not score: name, score=user() update(name, score) display() main()
attributes={"strength":4, "health":5, "wisdom":8, "derpiness":15} money=30 items=[] print(""" Welcome to the Hero Creater Studios Please pick whether you want to buy(choice 0) or sell(choice 1) an attribute. The attributes are listed below strength-$4 health-$5 wisdom-$8 derpiness-$15 The game is over once you have used all your money or you have overspent. Press the enter key to quit. """) choice=None while choice!="": print("\n\nYou have:", money, "dollars") print("You have:", items, "as your attributes") print("All available items and their matching prices are:", attributes, "\n\n") choice=input("Put in 0 for buying or 1 for selling: ") if choice=="0": x=None while x not in attributes: x=input("Which attribute do you want to buy: ") x=x.lower() if(money - attributes[x] < 0) : print("sorry - not enough fund to buy", x) continue money-=attributes[x] items.append(x) print("Transaction done, you spent", attributes[x], "dollars on", x) elif choice=="1": if not items: print("Sorry, you are itemless, you got nutting to sell!") continue y=None while y not in items: y=input("Which attribute do you want to sell: ") y=y.lower() money+=attributes[y] items.remove(y) print("\nTransaction done, you got", attributes[y], "dollars by selling", y) else: print("Unknown choice, choose again.") if money<=0: print("Ahh, it looks like you have ran out of money") print("You ended up with", items) else: print("Oohoho, it looks like somebody quit, remember, quiters never win\n and winners never quit!") print("Anyway, you ended up with these items:", items, "You also ended up with", money, "dollars") input("Press the ESC key to exit")
import csv import time def load_data(filename): """ """ data = [] with open(filename, newline='') as csvfile: reader = csv.DictReader(csvfile, delimiter=',') for row in reader: data.append(row) n_items = len(data) print(f"{filename} loaded into data ({n_items} items)") return data def calcul_nb_medailles(data, year, country): """ Calcul le nb de médailles d'Or gagné par un pays donné `country` lors d'une olympiade donnée `year` """ selection = [] for e in data: if e['Year'] == year and e['Country'] == country and e['Medal'] == 'Gold': selection.append(e) reponse = len(selection) return reponse ts = time.time() filename = 'data/summer-olympics.csv' data = load_data(filename) year = '1984' country = 'FRA' nd_medals = calcul_nb_medailles(data, year, country) print(year, country, nd_medals) te = time.time() print(f"done in {te - ts:.2f} s.")
from functools import reduce def is_armstrong_number(number): if number == 0: return True single_digits = map(int, str(number)) each_digit_to_the_power_number_len = map(lambda n: n ** str(number).__len__(), single_digits) sum_all = reduce(lambda a, b: a + b, each_digit_to_the_power_number_len, 0) return number == sum_all
from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: previousNumsWithIndexes = dict() for index, num in enumerate(nums): indexOfPair = previousNumsWithIndexes.get(target - num) if(indexOfPair != None): return [indexOfPair, index] else: previousNumsWithIndexes[num] = index if __name__ == '__main__': solution = Solution() print(solution.twoSum([3, 2, 4], 6)) print(solution.twoSum([2,7,11,15], 9))
from typing import List class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: result = [] for word in words: if self.is_matched_one_to_one(pattern, word): result.append(word) return result def is_matched_one_to_one(self, word_one, word_two): mappings = {} for index in range(word_one.__len__()): letter_one = word_one[index] letter_two = word_two[index] forward_mapping = mappings.get(letter_one) backward_mapping = mappings.get(letter_two.upper()) if forward_mapping is None and backward_mapping is None: mappings[letter_one] = letter_two mappings[letter_two.upper()] = letter_one elif forward_mapping == letter_two or backward_mapping == letter_one: continue else: return False return True if __name__ == '__main__': sol = Solution() print(sol.findAndReplacePattern(["abc", "deq", "mee", "aqq", "dkd", "ccc"], "abb"), ["mee", "aqq"])
import smbus import time import RPi.GPIO as GPIO # Setting the bus to its appropriate RPi version, this version being 3.7.6 bus = smbus.SMBus(1) # Setting GPIO pinmode as BCM (the numbers after the pin numbers) GPIO.setmode(GPIO.BCM) # Setting the address used for Arduino communication address = 0x04 # Initializing GPIO 18 as an output GPIO.setup(18, GPIO.OUT) # Setting the PWM at GPIO 18 to operate at 100Hz, increasing this didn't seem # to make any noticeable difference, so I just left it at 100. p=GPIO.PWM(18,100) # Initializing the pwm to start at 0 p.start(0) # Setting the state variable which is used to determine whether to display a # message when the system is 'off' or 'on' # The system is initially 'off' state = 0 try: #Setting this to run forever in a loop unless interrupted while True: # This reads any incoming data from the arduino as a 'data block', # essentially importing it as an array/list data = bus.read_i2c_block_data(address,1) #(address,bytes/length) time.sleep(.15) #delay to give time for the bus to properly read without error #When the system is on, incoming data is > 0 and state = 1 if data[0] != 0: if state == 1: print('System is Enabled') # Having the state value change upon exit ensures that the # message only prints once upon a change in the incoming data # of data = 0, and data > 0 state = 0 datamod=data[0]-1 #this takes care of the 1-102 offset to be 0-101 if datamod>100: #this sets any value greater than 100 to be 100 datamod=100 #takes the incoming/edited value and sets that as the pwm of the motor p.ChangeDutyCycle(datamod) #this prints the value accordingly to the terminal print('Motor Speed %: ',(datamod)) #When the system is off, incoming data is 0 and state = 0 elif data[0] == 0: if state == 0: print('System is Disabled') state = 1 #this turns off the PWM, thus turning off the motor p.ChangeDutyCycle(0) except KeyboardInterrupt: p.stop() #stops the PWM GPIO.cleanup() #Cleans up or resets the pins upon the interrupt exit
"""Module of encoder. StringToIntegerEncoder encode string into integer. ListToIntegerEncoder encode list into integer. See test section for code example. """ import json class StringToIntegerEncoder: """Encode string into integer. """ def __init__(self): """Use dict object to hash string. `__encode_table` will hash string into integer. `__decode_table` will hash integer into string. `__code` stands for current hash integer range. """ self.__encode_table = {} self.__decode_table = {} self.__code = 0 def encode_from_string(self, string): """Encode string into integer. If `string` is not seen before, use `__code` to represent `string`. Args: string (str): Target string to encode. Returns: int: Encoded integer. """ if string not in self.__encode_table: self.__encode_table[string] = self.__code self.__decode_table[self.__code] = string self.__code = self.__code + 1 return self.__encode_table[string] def decode_to_string(self, integer): """Decode integer into string. Args: integer (int): Target integer to decode. Returns: str: Decoded string. Raises: ValueError: If integer is not seen before. """ if integer not in self.__decode_table: raise ValueError('Integer {} is not encoded before.'.format(integer)) return self.__decode_table[integer] def encode_from_string_list(self, string_list): """Encode list of strings into list of integers. Sort encoded result by ascending order. Args: string_list (list of str): Target list of string to encode. Returns: list of int: Encoded list of integers. """ integer_list = [self.encode_from_string(string) for string in string_list] integer_list.sort() return integer_list def decode_to_string_list(self, integer_list): """Decode list of integers into list of string. Args: integer_list (list of int): Target list of integers to decode. Returns: list of str: Decoded list of strings. Raises: ValueError: If decode process raise error. """ try: return [self.decode_to_string(integer) for integer in integer_list] except: raise ValueError('Some integer in integer list are not encoded before.') def encode_from_list_of_string_list(self, list_of_string_list): """Encode list of list of strings into list of list of integers. Args: list_of_string_list (list of list of str): Target list of list of string to encode. Returns: list of list of int: Encoded list of list of integers. """ return [self.encode_from_string_list(string_list) for string_list in list_of_string_list] def decode_to_list_of_string_list(self, list_of_integer_list): """Decode list of list of integers into list of list of string. Args: list_of_integer_list (list of list of int): Target list of list of integers to decode. Returns: list of list of str: Decoded list of list of strings. Raises: ValueError: If decode process raise error. """ try: return [self .decode_to_string_list(integer_list) for integer_list in list_of_integer_list] except: raise ValueError('Some part of integer_list are not encoded before.') class ListToIntegerEncoder: """Encode list into integer.""" def __init__(self): """Use dict object to hash list. `__encode_table` will hash list into integer. `__decode_table` will hash integer into list. `__code` stands for current hash integer range. """ self.__encode_table = {} self.__decode_table = {} self.__code = 0 def encode_from_list(self, target_list): """Encode list into integer. Using `json.dumps` to convert list into string, then hash string into integer. If `target_list` is not seen before, use `__code` to represent `target_list`. Args: target_list (list): Target list to encode. Returns: int: Encoded integer. """ json_string = json.dumps(target_list) if json_string not in self.__encode_table: self.__encode_table[json_string] = self.__code self.__decode_table[self.__code] = json_string self.__code = self.__code + 1 return self.__encode_table[json_string] def decode_to_list(self, integer): """Decode integer into list. Args: integer (int): Target integer to decode. Returns: list: Decoded list. Raises: ValueError: If integer is not seen before. """ try: return json.loads(self.__decode_table[integer]) except: raise ValueError('Integer {} is not encoded before.'.format(integer)) # Test section. if __name__ == '__main__': ENCODED_SOURCE = [ ['a', 'b', 'c'], ['a', 'b', 'ab'], ['ab', 'c', 'd'], ] ENCODED_ANSWER = [ [0, 1, 2], [0, 1, 3], [2, 3, 4], # sorted ] DECODED_SOURCE = [ [0, 1, 2], [2, 0, 1], [3, 1, 0], [4, 4, 4], ] DECODED_ANSWER = [ ['a', 'b', 'c'], ['c', 'a', 'b'], ['ab', 'b', 'a'], ['d', 'd', 'd'], ] STIE = StringToIntegerEncoder() for result, answer in zip(STIE.encode_from_list_of_string_list(ENCODED_SOURCE), ENCODED_ANSWER): assert result == answer, 'Bug in `StringToIntegerEncoder.encode_from_list_of_string_list`.' for result, answer in zip(STIE.decode_to_list_of_string_list(DECODED_SOURCE), DECODED_ANSWER): assert result == answer, 'Bug in `StringToIntegerEncoder.decode_to_list_of_string_list`.' ENCODED_SOURCE = [ ['0', '1'], ['0', '1'], ['0', '2'], ['1', '2'], ] ENCODED_ANSWER = [ 0, 0, 1, 2 ] DECODED_SOURCE = [ 0, 1, 2, 0 ] DECODED_ANSWER = [ ['0', '1'], ['0', '2'], ['1', '2'], ['0', '1'], ] LTIE = ListToIntegerEncoder() for source, answer in zip(ENCODED_SOURCE, ENCODED_ANSWER): assert LTIE.encode_from_list(source) == answer, \ 'Bug in `ListToIntegerEncoder.encode_from_list`.' for source, answer in zip(DECODED_SOURCE, DECODED_ANSWER): assert LTIE.decode_to_list(source) == answer, \ 'Bug in `ListToIntegerEncoder.decode_to_list`.'
""" Ejercicio 10 Escribir un programa que permita gestionar la base de datos de clientes de una empresa. Los clientes se guardarán en un diccionario en el que la clave de cada cliente será su NIF, y el valor será otro diccionario con los datos del cliente nombre dirección teléfono correo preferente donde preferente tendrá el valor True si se trata de un cliente preferente. El programa debe preguntar al usuario por una opción del siguiente menú: (1) Añadir cliente, (2) Eliminar cliente, (3) Mostrar cliente, (4) Listar todos los clientes, (5) Listar clientes preferentes, (6) Terminar. En función de la opción elegida el programa tendrá que hacer lo siguiente: Preguntar los datos del cliente crear un diccionario con los datos añadirlo a la base de datos. Preguntar por el NIF del cliente eliminar sus datos de la base de datos. Preguntar por el NIF del cliente y mostrar sus datos. Mostrar lista de todos los clientes de la base datos con su NIF y nombre. Mostrar la lista de clientes preferentes de la base de datos con su NIF y nombre. Terminar el programa. """ def agregar_cliente(): ''' Función que se encarga de agregar cliente a un diccionario tiene dos diccionarios - persona que tiene como valor otro diccionario datos_persona parametros: No recibe nada Devuelve: No devuelve nada, solo muestra un mensaje de agregado el cliente al diccionario ''' print('====================================') print('AGREGAR CLIENTE') print('====================================') nif_persona = int(input('Ingrese el NIF de la persona: ')) nombre = input('Ingrese el nombre de la persona: ') direccion = input('Ingrese la dirección: ') telefono = input('Ingrese el telefono: ') correo = input('Ingrese el correo: ') preferente = input('Ingrese el preferente (V/F): ').title() datos_persona = { 'nombre': nombre, 'direccion': direccion, 'telefono': telefono, 'correo': correo, 'preferente': preferente } persona[nif_persona] = datos_persona print('El cliente ',nombre,' ha sido agregado correctamente') print(' --------------------------------------------------------- ') def eliminar_cliente(): print('====================================') print('ELIMINAR CLIENTE') print('====================================') print('NIF\tNombre') print('-------------------------------------------------------- ') for i,j in persona.items(): print(i,'\t', j['nombre']) print(' --------------------------------------------------------- ') numero_cliente = int(input('Ingrese el NIF del cliente: ')) if numero_cliente in persona: respuesta = input('¿Esta seguro de eliminar el cliente? (Y/N): ').title() if respuesta == 'Y': del persona[numero_cliente] print('Cliente eliminado correctamente') print('-------------------------------------------------------- ') else: print('No existe') def mostrar_cliente(): print('====================================') print('MOSTRAR CLIENTE') print('====================================') numero_cliente = int(input('Ingrese el NIF del cliente: ')) if numero_cliente in persona: print(' --------------------------------------------------------- ') print('DATOS DEL CLIENTE') print(' --------------------------------------------------------- ') for i,j in persona[numero_cliente].items(): print(i,' ',j) print(' --------------------------------------------------------- ') else: print('No existe') def lista_clientes(): print('====================================') print('MOSTRAR TODOS LOS CLIENTES') print('====================================') print('NIF\tNombre') print('-------------------------------------------------------- ') for i,j in persona.items(): print(i,'\t', j['nombre']) print(' --------------------------------------------------------- ') def lista_clientes_vip(): print('====================================') print('MOSTRAR TODOS LOS CLIENTES VIP') print('====================================') for i,j in persona.items(): if j['preferente'] == 'V': print(i,' ',j['nombre']) print(' --------------------------------------------------------- ') if __name__ == '__main__': persona = {} datos_persona = {} while True: opcion = int(input('1) Agregar cliente \n2) Eliminar cliente \n3) Mostrar cliente' '\n4) Listar todos los clientes \n5) Listar cliente preferentes' '\n6) Terminar \nOpciones: ')) #TODO faltan agregar funciones if opcion == 1: agregar_cliente() elif opcion == 2: eliminar_cliente() elif opcion == 3: mostrar_cliente() elif opcion == 4: lista_clientes() elif opcion == 5: lista_clientes_vip() elif opcion == 6: print('Saliendo...') break else: print(' --------------------------------------------------------- ') print('Opcion ingresada invalida') print(' --------------------------------------------------------- ')