content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Bubble sort def sort_bubble(my_list): for i in range(len(my_list) - 1, 0, -1): for j in range(i): if my_list[j] > my_list[j + 1]: my_list[j], my_list[j + 1] = my_list[j + 1], my_list[j] return my_list print(sort_bubble([1,4,2,6,5,3,1]))
def sort_bubble(my_list): for i in range(len(my_list) - 1, 0, -1): for j in range(i): if my_list[j] > my_list[j + 1]: (my_list[j], my_list[j + 1]) = (my_list[j + 1], my_list[j]) return my_list print(sort_bubble([1, 4, 2, 6, 5, 3, 1]))
#program to enter number followed by commas and the storing those numbers in a list arr=[];r=0; a=input("ENter numbers followed by commas :") l=a.split(",") m='' for c in a: if(c!=','): m=m+c; else: arr.append(int(m)); m=''; arr.append(int(m)); print(arr);
arr = [] r = 0 a = input('ENter numbers followed by commas :') l = a.split(',') m = '' for c in a: if c != ',': m = m + c else: arr.append(int(m)) m = '' arr.append(int(m)) print(arr)
file = open ("employees.txt" , "r") if(file.readable()): print("Success") else: print("Error") print() #read the whole file print(file.read()) #rewind file pointer file.seek(0) print() #read individual line print(file.readline()) #rewind file pointer file.seek(0) print() #read the whole file and set as lists print(file.readlines()) #rewind file pointer file.seek(0) print() #access specific list set print(file.readlines()[1]) #rewind file pointer file.seek(0) print() #read the lists using a for loop for employee in file.readlines(): print(employee) file.close()
file = open('employees.txt', 'r') if file.readable(): print('Success') else: print('Error') print() print(file.read()) file.seek(0) print() print(file.readline()) file.seek(0) print() print(file.readlines()) file.seek(0) print() print(file.readlines()[1]) file.seek(0) print() for employee in file.readlines(): print(employee) file.close()
class UserOutputVariables: """The UserOutputVariables object specifies the number of user-defined output variables. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name].materials[name].userOutputVariables import odbMaterial session.odbs[name].materials[name].userOutputVariables The corresponding analysis keywords are: - USER OUTPUT VARIABLES """ def __init__(self, n: int = 0): """This method creates a UserOutputVariables object. Notes ----- This function can be accessed by: .. code-block:: python mdb.models[name].materials[name].UserOutputVariables session.odbs[name].materials[name].UserOutputVariables Parameters ---------- n An Int specifying the number of user-defined variables required at each material point. The default value is 0. Returns ------- A UserOutputVariables object. Raises ------ RangeError """ pass def setValues(self): """This method modifies the UserOutputVariables object. Raises ------ RangeError """ pass
class Useroutputvariables: """The UserOutputVariables object specifies the number of user-defined output variables. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name].materials[name].userOutputVariables import odbMaterial session.odbs[name].materials[name].userOutputVariables The corresponding analysis keywords are: - USER OUTPUT VARIABLES """ def __init__(self, n: int=0): """This method creates a UserOutputVariables object. Notes ----- This function can be accessed by: .. code-block:: python mdb.models[name].materials[name].UserOutputVariables session.odbs[name].materials[name].UserOutputVariables Parameters ---------- n An Int specifying the number of user-defined variables required at each material point. The default value is 0. Returns ------- A UserOutputVariables object. Raises ------ RangeError """ pass def set_values(self): """This method modifies the UserOutputVariables object. Raises ------ RangeError """ pass
''' Script converts data from newline seperated values to comma seperated values ''' fName = input('Enter File Name:') with open(fName,'r') as f: lines = f.read() f.close() values = lines.splitlines() s = 'time\n' for val in values: s = s + val.strip() + '\n' print(s) with open(fName,'w') as f: f.write(s) f.close() print('Done')
""" Script converts data from newline seperated values to comma seperated values """ f_name = input('Enter File Name:') with open(fName, 'r') as f: lines = f.read() f.close() values = lines.splitlines() s = 'time\n' for val in values: s = s + val.strip() + '\n' print(s) with open(fName, 'w') as f: f.write(s) f.close() print('Done')
# Spiritual Release (57462) sakuno = 9130021 sm.setSpeakerID(sakuno) sm.sendNext("Kanna, please come to Momijigaoka. We have news.") sm.setPlayerAsSpeaker() sm.sendSay("I wonder what's going on? I hope Oda's Army isn't on the move.") sm.startQuest(parentID)
sakuno = 9130021 sm.setSpeakerID(sakuno) sm.sendNext('Kanna, please come to Momijigaoka. We have news.') sm.setPlayerAsSpeaker() sm.sendSay("I wonder what's going on? I hope Oda's Army isn't on the move.") sm.startQuest(parentID)
Theatre_1 = {"Name":'Lviv', "Seats_Number":120, "Actors_1":["Andrew Kigan","Jhon Speelberg","Alan Mask","Neil Bambino"], "Play_1":["25/03/2018","Aida",80,"Andrew Kigan","Jhon Speelberg",60,"OK"], "Play_2":["26/03/2018","War",220,"Jhon Speelberg","Jhon Speelberg","Alan Mask","Neil Bambino",100,"OK"] } Theatre_2 = {"Name":'Sokil', "Seats_Number":110, "Actors_2":["Julia Portman","Mary Lewis","Carla Mask","Neil Bambino","Natalie Queen"], "Play_3":["26/03/2018","Rigoletto",120,"Mary Lewis","Carla Mask","Neil Bambino","Natalie Queen",80,"OK"], "Play_4":["27/03/2018","Night Warriors",90,"Andrew Kigan","Julia Portman","Mary Lewis","Carla Mask",75,"NO"] } print('Plays are: ' + str(Theatre_1["Play_1"][1:2]) + ' ' + str(Theatre_1["Play_2"][1:2]) + ' ' + str(Theatre_2["Play_3"][1:2]) + ' ' + str(Theatre_2["Play_4"][1:2])) print('Number of actors of Lviv Theatre is : ' + str(len(Theatre_1["Actors_1"]))) Other_play = {"Play_5":["29/03/2018","SomethingNew",90,"Andrew Kigan","Julia Portman","Carla Mask",74,"YES"]} Theatre_2.update(Other_play) free_tickets = Theatre_1.get("Play_1")[2] - Theatre_1.get("Play_1")[5] print('Play ' + str(Theatre_1["Play_1"][1:2]) + ', availiable tickets num = ' + str(free_tickets)) profit = Theatre_2.get("Play_3")[2] * Theatre_2.get("Play_3")[7] print('Play ' + str(Theatre_2["Play_3"][1:2]) + ', profit = ' + str(profit)) One_more_ticket = {"Play_4":["27/03/2018","Night Warriors",90,"Andrew Kigan","Julia Portman","Mary Lewis","Carla Mask",76,"NO"]} Theatre_2.update(One_more_ticket) print(Theatre_2)
theatre_1 = {'Name': 'Lviv', 'Seats_Number': 120, 'Actors_1': ['Andrew Kigan', 'Jhon Speelberg', 'Alan Mask', 'Neil Bambino'], 'Play_1': ['25/03/2018', 'Aida', 80, 'Andrew Kigan', 'Jhon Speelberg', 60, 'OK'], 'Play_2': ['26/03/2018', 'War', 220, 'Jhon Speelberg', 'Jhon Speelberg', 'Alan Mask', 'Neil Bambino', 100, 'OK']} theatre_2 = {'Name': 'Sokil', 'Seats_Number': 110, 'Actors_2': ['Julia Portman', 'Mary Lewis', 'Carla Mask', 'Neil Bambino', 'Natalie Queen'], 'Play_3': ['26/03/2018', 'Rigoletto', 120, 'Mary Lewis', 'Carla Mask', 'Neil Bambino', 'Natalie Queen', 80, 'OK'], 'Play_4': ['27/03/2018', 'Night Warriors', 90, 'Andrew Kigan', 'Julia Portman', 'Mary Lewis', 'Carla Mask', 75, 'NO']} print('Plays are: ' + str(Theatre_1['Play_1'][1:2]) + ' ' + str(Theatre_1['Play_2'][1:2]) + ' ' + str(Theatre_2['Play_3'][1:2]) + ' ' + str(Theatre_2['Play_4'][1:2])) print('Number of actors of Lviv Theatre is : ' + str(len(Theatre_1['Actors_1']))) other_play = {'Play_5': ['29/03/2018', 'SomethingNew', 90, 'Andrew Kigan', 'Julia Portman', 'Carla Mask', 74, 'YES']} Theatre_2.update(Other_play) free_tickets = Theatre_1.get('Play_1')[2] - Theatre_1.get('Play_1')[5] print('Play ' + str(Theatre_1['Play_1'][1:2]) + ', availiable tickets num = ' + str(free_tickets)) profit = Theatre_2.get('Play_3')[2] * Theatre_2.get('Play_3')[7] print('Play ' + str(Theatre_2['Play_3'][1:2]) + ', profit = ' + str(profit)) one_more_ticket = {'Play_4': ['27/03/2018', 'Night Warriors', 90, 'Andrew Kigan', 'Julia Portman', 'Mary Lewis', 'Carla Mask', 76, 'NO']} Theatre_2.update(One_more_ticket) print(Theatre_2)
''' Subgraphs II In the previous exercise, we gave you a list of nodes whose neighbors we asked you to extract. Let's try one more exercise in which you extract nodes that have a particular metadata property and their neighbors. This should hark back to what you've learned about using list comprehensions to find nodes. The exercise will also build your capacity to compose functions that you've already written before. INSTRUCTIONS 0XP Using a list comprehension, extract nodes that have the metadata 'occupation' as 'celebrity' alongside their neighbors: The output expression of the list comprehension is n, and there are two iterator variables: n and d. The iterable is the list of nodes of T (including the metadata, which you can specify using data=True) and the conditional expression is if the 'occupation' key of the metadata dictionary d equals 'celebrity'. Place them in a new subgraph called T_sub. To do this: Iterate over the nodes, compute the neighbors of each node, and add them to the set of nodes nodeset by using the .union() method. This last part has been done for you. Use nodeset along with the T.subgraph() method to calculate T_sub. Draw T_sub to the screen. ''' # Extract the nodes of interest: nodes nodes = [n for n, d in T.nodes(data=True) if d['occupation'] == 'celebrity'] # Create the set of nodes: nodeset nodeset = set(nodes) # Iterate over nodes for n in nodes: # Compute the neighbors of n: nbrs nbrs = T.neighbors(n) # Compute the union of nodeset and nbrs: nodeset nodeset = nodeset.union(nbrs) # Compute the subgraph using nodeset: T_sub T_sub = T.subgraph(nodeset) # Draw T_sub to the screen nx.draw(T_sub) plt.show()
""" Subgraphs II In the previous exercise, we gave you a list of nodes whose neighbors we asked you to extract. Let's try one more exercise in which you extract nodes that have a particular metadata property and their neighbors. This should hark back to what you've learned about using list comprehensions to find nodes. The exercise will also build your capacity to compose functions that you've already written before. INSTRUCTIONS 0XP Using a list comprehension, extract nodes that have the metadata 'occupation' as 'celebrity' alongside their neighbors: The output expression of the list comprehension is n, and there are two iterator variables: n and d. The iterable is the list of nodes of T (including the metadata, which you can specify using data=True) and the conditional expression is if the 'occupation' key of the metadata dictionary d equals 'celebrity'. Place them in a new subgraph called T_sub. To do this: Iterate over the nodes, compute the neighbors of each node, and add them to the set of nodes nodeset by using the .union() method. This last part has been done for you. Use nodeset along with the T.subgraph() method to calculate T_sub. Draw T_sub to the screen. """ nodes = [n for (n, d) in T.nodes(data=True) if d['occupation'] == 'celebrity'] nodeset = set(nodes) for n in nodes: nbrs = T.neighbors(n) nodeset = nodeset.union(nbrs) t_sub = T.subgraph(nodeset) nx.draw(T_sub) plt.show()
""" This module contain functions which are cheking whether the given board fits the rules. Git repository: https://github.com/msharsh/puzzle.git """ def check_rows(board: list) -> bool: """ Checks if there are identical numbers in every row in the board. Returns True if not, else False. >>> check_rows(["**** ****","***1 ****","** 3****","* 4 1****",\ " 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) True """ for i in range(len(board)): row_temp = [] for j in range(len(board[i])): if board[i][j] != '*' and board[i][j] != ' ': if board[i][j] in row_temp: return False else: row_temp.append(board[i][j]) return True def check_columns(board: list) -> bool: """ Checks if there are identical numbers in every column in the board. Returns True if not, else False. >>> check_columns(["**** ****","***1 ****","** 3****","* 4 1****",\ " 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) False """ for i in range(len(board[0])): column_temp = [] for j in range(len(board)): if board[j][i] != '*' and board[j][i] != ' ': if board[j][i] in column_temp: return False else: column_temp.append(board[j][i]) return True def check_color(board: list) -> bool: """ Checks if there are identical numbers in every color row in the board. Returns True if not, else False. >>> check_color(["**** ****","***1 ****","** 3****","* 4 1****",\ " 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) True """ starting_row = 0 starting_column = 4 for i in range(5): i = starting_row j = starting_column color_temp = [] while i + j != 8: if board[i][j] != ' ': if board[i][j] in color_temp: return False else: color_temp.append(board[i][j]) i += 1 while i + j != 13: if board[i][j] != ' ': if board[i][j] in color_temp: return False else: color_temp.append(board[i][j]) j += 1 starting_row += 1 starting_column -= 1 return True def validate_board(board: list) -> bool: """ Checks if board fits the rules. If fits returns True, else False. >>> validate_board(["**** ****","***1 ****","** 3****","* 4 1****",\ " 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) False """ if check_rows(board) and\ check_columns(board) and\ check_color(board): return True return False
""" This module contain functions which are cheking whether the given board fits the rules. Git repository: https://github.com/msharsh/puzzle.git """ def check_rows(board: list) -> bool: """ Checks if there are identical numbers in every row in the board. Returns True if not, else False. >>> check_rows(["**** ****","***1 ****","** 3****","* 4 1****", " 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) True """ for i in range(len(board)): row_temp = [] for j in range(len(board[i])): if board[i][j] != '*' and board[i][j] != ' ': if board[i][j] in row_temp: return False else: row_temp.append(board[i][j]) return True def check_columns(board: list) -> bool: """ Checks if there are identical numbers in every column in the board. Returns True if not, else False. >>> check_columns(["**** ****","***1 ****","** 3****","* 4 1****", " 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) False """ for i in range(len(board[0])): column_temp = [] for j in range(len(board)): if board[j][i] != '*' and board[j][i] != ' ': if board[j][i] in column_temp: return False else: column_temp.append(board[j][i]) return True def check_color(board: list) -> bool: """ Checks if there are identical numbers in every color row in the board. Returns True if not, else False. >>> check_color(["**** ****","***1 ****","** 3****","* 4 1****", " 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) True """ starting_row = 0 starting_column = 4 for i in range(5): i = starting_row j = starting_column color_temp = [] while i + j != 8: if board[i][j] != ' ': if board[i][j] in color_temp: return False else: color_temp.append(board[i][j]) i += 1 while i + j != 13: if board[i][j] != ' ': if board[i][j] in color_temp: return False else: color_temp.append(board[i][j]) j += 1 starting_row += 1 starting_column -= 1 return True def validate_board(board: list) -> bool: """ Checks if board fits the rules. If fits returns True, else False. >>> validate_board(["**** ****","***1 ****","** 3****","* 4 1****", " 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) False """ if check_rows(board) and check_columns(board) and check_color(board): return True return False
# program description # :: python # :: allows user to enter initial height of ball before dropped # :: outputs total distance traveled by ball based on number of bounces # constants bounceIndex = float(0.6) # input variables height = int(input("Enter Ball Height: ")) numberOfBounces = float(input("Enter Number Of Ball Bounces: ")) # calculation distance = 0 while numberOfBounces > 0: distance += height height *= bounceIndex distance += height numberOfBounces -= 1 # output print("Total Distance Traveled: " + str(distance) + " Units.")
bounce_index = float(0.6) height = int(input('Enter Ball Height: ')) number_of_bounces = float(input('Enter Number Of Ball Bounces: ')) distance = 0 while numberOfBounces > 0: distance += height height *= bounceIndex distance += height number_of_bounces -= 1 print('Total Distance Traveled: ' + str(distance) + ' Units.')
"""Top-level package for EnviroBot.""" __author__ = """Chris Last""" __email__ = 'chris.last@gmail.com' __version__ = '0.1.0'
"""Top-level package for EnviroBot.""" __author__ = 'Chris Last' __email__ = 'chris.last@gmail.com' __version__ = '0.1.0'
class Stack: def __init__(self): self.items = [] def push(self, e): self.items = [e] + self.items def pop(self): return self.items.pop() s = Stack() s.push(5) # [5] s.push(7) # [7, 5] s.push(11) # [11, 7, 5] print(s.pop()) # returns 11, left is [7, 5] print(s.pop()) # returns 7, left is [5]
class Stack: def __init__(self): self.items = [] def push(self, e): self.items = [e] + self.items def pop(self): return self.items.pop() s = stack() s.push(5) s.push(7) s.push(11) print(s.pop()) print(s.pop())
i=map(int, raw_input()) c=0 for m in i: c = c+1 if m==4 or m==7 else c print("YES" if c==4 or c==7 else "NO")
i = map(int, raw_input()) c = 0 for m in i: c = c + 1 if m == 4 or m == 7 else c print('YES' if c == 4 or c == 7 else 'NO')
class Solution: def tribonacci(self, n: int) -> int: if n <= 1: return n arr = [0 for i in range(n+1)] arr[1], arr[2] = 1, 1 for i in range(3, len(arr)): arr[i] = arr[i-1] + arr[i-2] + arr[i-3] return arr[n] s = Solution() print(s.tribonacci(5))
class Solution: def tribonacci(self, n: int) -> int: if n <= 1: return n arr = [0 for i in range(n + 1)] (arr[1], arr[2]) = (1, 1) for i in range(3, len(arr)): arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3] return arr[n] s = solution() print(s.tribonacci(5))
class Yo(): def __init__(self, name): self.name = name def say_name(self): print('Yo {}!'.format(self.name))
class Yo: def __init__(self, name): self.name = name def say_name(self): print('Yo {}!'.format(self.name))
""" 1. Clarification 2. Possible solutions - dfs, bottom-up - dfs, top-down - bfs 3. Coding 4. Tests """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # T=O(n), S=O(n) class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 if not root.left and not root.right: return 1 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) # T=O(n), S=O(n) class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 self.MaxDep = 0 self.dfs(root, 1) return self.MaxDep def dfs(self, root, depth): if not root: return if not root.left and not root.right: self.MaxDep = max(self.MaxDep, depth) return self.dfs(root.left, depth + 1) self.dfs(root.right, depth + 1) # T=O(n), S=O(n) class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 Q = collections.deque([root]) ret = 0 while Q: level_size = len(Q) for _ in range(level_size): node = Q.popleft() if node.left: Q.append(node.left) if node.right: Q.append(node.right) ret += 1 return ret
""" 1. Clarification 2. Possible solutions - dfs, bottom-up - dfs, top-down - bfs 3. Coding 4. Tests """ class Solution: def max_depth(self, root: TreeNode) -> int: if not root: return 0 if not root.left and (not root.right): return 1 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) class Solution: def max_depth(self, root: TreeNode) -> int: if not root: return 0 self.MaxDep = 0 self.dfs(root, 1) return self.MaxDep def dfs(self, root, depth): if not root: return if not root.left and (not root.right): self.MaxDep = max(self.MaxDep, depth) return self.dfs(root.left, depth + 1) self.dfs(root.right, depth + 1) class Solution: def max_depth(self, root: TreeNode) -> int: if not root: return 0 q = collections.deque([root]) ret = 0 while Q: level_size = len(Q) for _ in range(level_size): node = Q.popleft() if node.left: Q.append(node.left) if node.right: Q.append(node.right) ret += 1 return ret
# coding: utf8 """""" VOICES = { "mei-jia": "com.apple.speech.synthesis.voice.mei-jia", "ting-ting": "com.apple.speech.synthesis.voice.ting-ting", }
"""""" voices = {'mei-jia': 'com.apple.speech.synthesis.voice.mei-jia', 'ting-ting': 'com.apple.speech.synthesis.voice.ting-ting'}
class AlreadyFiredError(RuntimeError): pass class InvalidBoardError(RuntimeError): pass class InvalidMoveError(RuntimeError): pass
class Alreadyfirederror(RuntimeError): pass class Invalidboarderror(RuntimeError): pass class Invalidmoveerror(RuntimeError): pass
class Solution: def canPermutePalindrome(self, s: str) -> bool: x={} k=0 for i in set(s): x[i]=s.count(i) for i,j in x.items(): if j%2!=0: k=k+1 if k>1: return False return True
class Solution: def can_permute_palindrome(self, s: str) -> bool: x = {} k = 0 for i in set(s): x[i] = s.count(i) for (i, j) in x.items(): if j % 2 != 0: k = k + 1 if k > 1: return False return True
def test_user_creation(faunadb_client): username = "burgerbob" created_user = faunadb_client.create_user( username=username, password="password1234" ) assert created_user["username"] == username all_users = faunadb_client.all_users() assert len(all_users) == 1
def test_user_creation(faunadb_client): username = 'burgerbob' created_user = faunadb_client.create_user(username=username, password='password1234') assert created_user['username'] == username all_users = faunadb_client.all_users() assert len(all_users) == 1
''' ## Questions ### 154. [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. The array may contain duplicates. Example 1: Input: [1,3,5] Output: 1 Example 2: Input: [2,2,2,0,1] Output: 0 Note: - This is a follow up problem to Find Minimum in Rotated Sorted Array. - Would allow duplicates affect the run-time complexity? How and why? ''' ## Solutions class Solution: def findMin(self, nums: List[int]) -> int: if not nums: return nums nums.sort() return nums[0] # Runtime: 60 ms # Memory Usage: 14.2 MB
""" ## Questions ### 154. [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. The array may contain duplicates. Example 1: Input: [1,3,5] Output: 1 Example 2: Input: [2,2,2,0,1] Output: 0 Note: - This is a follow up problem to Find Minimum in Rotated Sorted Array. - Would allow duplicates affect the run-time complexity? How and why? """ class Solution: def find_min(self, nums: List[int]) -> int: if not nums: return nums nums.sort() return nums[0]
""" Demonstrates prompting a user to enter input using the keyboard. This demonstrates two different ways to get the user's input as a string and converts the input to an int-type. The same thing can be done for floats by using the float function instead of the int function. """ number1 = input("Enter the first number: ") #Gets the user's first number as a string. number1 = int(number1) #The number1 variable is typecast from a string to an int, and is assigned back to itself. #This replaces the string-type value of the number1 variable with the int-type value. number2 = int(input("Enter the second number: ")) #Gets the user's second number and the value they typed will be returned (as a string-type) #and immediately typecast as an int. print("The sum of the two numbers is", number1 + number2) #Prints the sum of the two numbers.
""" Demonstrates prompting a user to enter input using the keyboard. This demonstrates two different ways to get the user's input as a string and converts the input to an int-type. The same thing can be done for floats by using the float function instead of the int function. """ number1 = input('Enter the first number: ') number1 = int(number1) number2 = int(input('Enter the second number: ')) print('The sum of the two numbers is', number1 + number2)
class Base(object): """ Basic Session Entity is the base entity representing the data in thte session. """ def __init__(self, session_id, key, content): self._session_id = session_id self.key = key self.content = content @property def session_id(self): return self._session_id
class Base(object): """ Basic Session Entity is the base entity representing the data in thte session. """ def __init__(self, session_id, key, content): self._session_id = session_id self.key = key self.content = content @property def session_id(self): return self._session_id
# "Unit GCD" # Alec Dewulf # April Long 2020 # Difficulty: Simple # Concepts: Pigeonhole principle """ EXPLANATION This problem becomes very simple if you notice that there are n//2 even numbers and by pigeonhole principle each must be on a different day (they all share a factor of two). Therefore there must be n//2 days. - If n is even each day will have two numbers a at i and a at i + 1. - If n is odd each day will have two numbers except for the last day which will have a at n-2 a at n-1 and a at n. - If n is one there will be one day with just one. """ num_tests = int(input()) solutions = [] for y in range(num_tests): num_pages = int(input()) # handle one page if num_pages == 1: min_days = 1 # more than one page else: min_days = num_pages//2 # odd means the last day will have three pages odd = num_pages % 2 != 0 all_days, start = [], 1 for x in range(1, min_days + 1): # odd and the last day means there should be three pages if odd and x == min_days: # go to end day = list(range(start, num_pages + 1)) # still pages before end or even else: day = [start, x * 2] start += 2 all_days.append(day) solutions.append(all_days) # output results for sol in solutions: print(len(sol)) for day in sol: print(len(day), *day)
""" EXPLANATION This problem becomes very simple if you notice that there are n//2 even numbers and by pigeonhole principle each must be on a different day (they all share a factor of two). Therefore there must be n//2 days. - If n is even each day will have two numbers a at i and a at i + 1. - If n is odd each day will have two numbers except for the last day which will have a at n-2 a at n-1 and a at n. - If n is one there will be one day with just one. """ num_tests = int(input()) solutions = [] for y in range(num_tests): num_pages = int(input()) if num_pages == 1: min_days = 1 else: min_days = num_pages // 2 odd = num_pages % 2 != 0 (all_days, start) = ([], 1) for x in range(1, min_days + 1): if odd and x == min_days: day = list(range(start, num_pages + 1)) else: day = [start, x * 2] start += 2 all_days.append(day) solutions.append(all_days) for sol in solutions: print(len(sol)) for day in sol: print(len(day), *day)
# # PySNMP MIB module CISCO-ATM-SERVICE-REGISTRY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SERVICE-REGISTRY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:33:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") Gauge32, TimeTicks, Integer32, iso, Counter32, Counter64, IpAddress, Bits, ObjectIdentity, ModuleIdentity, Unsigned32, NotificationType, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "TimeTicks", "Integer32", "iso", "Counter32", "Counter64", "IpAddress", "Bits", "ObjectIdentity", "ModuleIdentity", "Unsigned32", "NotificationType", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus") ciscoAtmServiceRegistryMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 50)) ciscoAtmServiceRegistryMIB.setRevisions(('1996-02-04 00:00',)) if mibBuilder.loadTexts: ciscoAtmServiceRegistryMIB.setLastUpdated('9602210000Z') if mibBuilder.loadTexts: ciscoAtmServiceRegistryMIB.setOrganization('Cisco Systems, Inc.') ciscoAtmServiceRegistryMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 50, 1)) class AtmAddr(TextualConvention, OctetString): status = 'current' subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(0, 0), ValueSizeConstraint(8, 8), ValueSizeConstraint(13, 13), ValueSizeConstraint(20, 20), ) class InterfaceIndexOrZero(TextualConvention, Integer32): status = 'current' displayHint = 'd' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647) asrSrvcRegTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1), ) if mibBuilder.loadTexts: asrSrvcRegTable.setStatus('current') asrSrvcRegEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1), ).setIndexNames((0, "CISCO-ATM-SERVICE-REGISTRY-MIB", "asrSrvcRegPort"), (0, "CISCO-ATM-SERVICE-REGISTRY-MIB", "asrSrvcRegServiceID"), (0, "CISCO-ATM-SERVICE-REGISTRY-MIB", "asrSrvcRegAddressIndex")) if mibBuilder.loadTexts: asrSrvcRegEntry.setStatus('current') asrSrvcRegPort = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 1), InterfaceIndexOrZero()) if mibBuilder.loadTexts: asrSrvcRegPort.setStatus('current') asrSrvcRegServiceID = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 2), ObjectIdentifier()) if mibBuilder.loadTexts: asrSrvcRegServiceID.setStatus('current') asrSrvcRegATMAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 3), AtmAddr()).setMaxAccess("readcreate") if mibBuilder.loadTexts: asrSrvcRegATMAddress.setStatus('current') asrSrvcRegAddressIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 4), Integer32()) if mibBuilder.loadTexts: asrSrvcRegAddressIndex.setStatus('current') asrSrvcRegParm1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 5), OctetString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: asrSrvcRegParm1.setStatus('current') asrSrvcRegRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 6), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: asrSrvcRegRowStatus.setStatus('current') asrSrvcRegMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 50, 3)) asrSrvcRegMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 50, 3, 1)) asrSrvcRegMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 50, 3, 2)) asrSrvcRegMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 50, 3, 1, 1)).setObjects(("CISCO-ATM-SERVICE-REGISTRY-MIB", "asrSrvcRegMIBGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): asrSrvcRegMIBCompliance = asrSrvcRegMIBCompliance.setStatus('current') asrSrvcRegMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 50, 3, 2, 1)).setObjects(("CISCO-ATM-SERVICE-REGISTRY-MIB", "asrSrvcRegATMAddress"), ("CISCO-ATM-SERVICE-REGISTRY-MIB", "asrSrvcRegParm1"), ("CISCO-ATM-SERVICE-REGISTRY-MIB", "asrSrvcRegRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): asrSrvcRegMIBGroup = asrSrvcRegMIBGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-ATM-SERVICE-REGISTRY-MIB", asrSrvcRegServiceID=asrSrvcRegServiceID, asrSrvcRegRowStatus=asrSrvcRegRowStatus, asrSrvcRegMIBGroups=asrSrvcRegMIBGroups, ciscoAtmServiceRegistryMIB=ciscoAtmServiceRegistryMIB, InterfaceIndexOrZero=InterfaceIndexOrZero, ciscoAtmServiceRegistryMIBObjects=ciscoAtmServiceRegistryMIBObjects, asrSrvcRegTable=asrSrvcRegTable, asrSrvcRegMIBConformance=asrSrvcRegMIBConformance, asrSrvcRegMIBCompliance=asrSrvcRegMIBCompliance, asrSrvcRegEntry=asrSrvcRegEntry, asrSrvcRegMIBCompliances=asrSrvcRegMIBCompliances, PYSNMP_MODULE_ID=ciscoAtmServiceRegistryMIB, asrSrvcRegATMAddress=asrSrvcRegATMAddress, asrSrvcRegParm1=asrSrvcRegParm1, asrSrvcRegMIBGroup=asrSrvcRegMIBGroup, asrSrvcRegPort=asrSrvcRegPort, AtmAddr=AtmAddr, asrSrvcRegAddressIndex=asrSrvcRegAddressIndex)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion') (cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt') (notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup') (gauge32, time_ticks, integer32, iso, counter32, counter64, ip_address, bits, object_identity, module_identity, unsigned32, notification_type, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'TimeTicks', 'Integer32', 'iso', 'Counter32', 'Counter64', 'IpAddress', 'Bits', 'ObjectIdentity', 'ModuleIdentity', 'Unsigned32', 'NotificationType', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (textual_convention, display_string, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString', 'RowStatus') cisco_atm_service_registry_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 50)) ciscoAtmServiceRegistryMIB.setRevisions(('1996-02-04 00:00',)) if mibBuilder.loadTexts: ciscoAtmServiceRegistryMIB.setLastUpdated('9602210000Z') if mibBuilder.loadTexts: ciscoAtmServiceRegistryMIB.setOrganization('Cisco Systems, Inc.') cisco_atm_service_registry_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 50, 1)) class Atmaddr(TextualConvention, OctetString): status = 'current' subtype_spec = OctetString.subtypeSpec + constraints_union(value_size_constraint(0, 0), value_size_constraint(8, 8), value_size_constraint(13, 13), value_size_constraint(20, 20)) class Interfaceindexorzero(TextualConvention, Integer32): status = 'current' display_hint = 'd' subtype_spec = Integer32.subtypeSpec + value_range_constraint(0, 2147483647) asr_srvc_reg_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1)) if mibBuilder.loadTexts: asrSrvcRegTable.setStatus('current') asr_srvc_reg_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1)).setIndexNames((0, 'CISCO-ATM-SERVICE-REGISTRY-MIB', 'asrSrvcRegPort'), (0, 'CISCO-ATM-SERVICE-REGISTRY-MIB', 'asrSrvcRegServiceID'), (0, 'CISCO-ATM-SERVICE-REGISTRY-MIB', 'asrSrvcRegAddressIndex')) if mibBuilder.loadTexts: asrSrvcRegEntry.setStatus('current') asr_srvc_reg_port = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 1), interface_index_or_zero()) if mibBuilder.loadTexts: asrSrvcRegPort.setStatus('current') asr_srvc_reg_service_id = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 2), object_identifier()) if mibBuilder.loadTexts: asrSrvcRegServiceID.setStatus('current') asr_srvc_reg_atm_address = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 3), atm_addr()).setMaxAccess('readcreate') if mibBuilder.loadTexts: asrSrvcRegATMAddress.setStatus('current') asr_srvc_reg_address_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 4), integer32()) if mibBuilder.loadTexts: asrSrvcRegAddressIndex.setStatus('current') asr_srvc_reg_parm1 = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 5), octet_string()).setMaxAccess('readcreate') if mibBuilder.loadTexts: asrSrvcRegParm1.setStatus('current') asr_srvc_reg_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 50, 1, 1, 1, 6), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: asrSrvcRegRowStatus.setStatus('current') asr_srvc_reg_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 50, 3)) asr_srvc_reg_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 50, 3, 1)) asr_srvc_reg_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 50, 3, 2)) asr_srvc_reg_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 50, 3, 1, 1)).setObjects(('CISCO-ATM-SERVICE-REGISTRY-MIB', 'asrSrvcRegMIBGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): asr_srvc_reg_mib_compliance = asrSrvcRegMIBCompliance.setStatus('current') asr_srvc_reg_mib_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 50, 3, 2, 1)).setObjects(('CISCO-ATM-SERVICE-REGISTRY-MIB', 'asrSrvcRegATMAddress'), ('CISCO-ATM-SERVICE-REGISTRY-MIB', 'asrSrvcRegParm1'), ('CISCO-ATM-SERVICE-REGISTRY-MIB', 'asrSrvcRegRowStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): asr_srvc_reg_mib_group = asrSrvcRegMIBGroup.setStatus('current') mibBuilder.exportSymbols('CISCO-ATM-SERVICE-REGISTRY-MIB', asrSrvcRegServiceID=asrSrvcRegServiceID, asrSrvcRegRowStatus=asrSrvcRegRowStatus, asrSrvcRegMIBGroups=asrSrvcRegMIBGroups, ciscoAtmServiceRegistryMIB=ciscoAtmServiceRegistryMIB, InterfaceIndexOrZero=InterfaceIndexOrZero, ciscoAtmServiceRegistryMIBObjects=ciscoAtmServiceRegistryMIBObjects, asrSrvcRegTable=asrSrvcRegTable, asrSrvcRegMIBConformance=asrSrvcRegMIBConformance, asrSrvcRegMIBCompliance=asrSrvcRegMIBCompliance, asrSrvcRegEntry=asrSrvcRegEntry, asrSrvcRegMIBCompliances=asrSrvcRegMIBCompliances, PYSNMP_MODULE_ID=ciscoAtmServiceRegistryMIB, asrSrvcRegATMAddress=asrSrvcRegATMAddress, asrSrvcRegParm1=asrSrvcRegParm1, asrSrvcRegMIBGroup=asrSrvcRegMIBGroup, asrSrvcRegPort=asrSrvcRegPort, AtmAddr=AtmAddr, asrSrvcRegAddressIndex=asrSrvcRegAddressIndex)
""" Copyright (c) Facebook, Inc. and its affiliates. """ class StopCondition: def __init__(self, agent): self.agent = agent def check(self) -> bool: raise NotImplementedError("Implemented by subclass") class NeverStopCondition(StopCondition): def __init__(self, agent): super().__init__(agent) self.name = "never" def check(self): return False
""" Copyright (c) Facebook, Inc. and its affiliates. """ class Stopcondition: def __init__(self, agent): self.agent = agent def check(self) -> bool: raise not_implemented_error('Implemented by subclass') class Neverstopcondition(StopCondition): def __init__(self, agent): super().__init__(agent) self.name = 'never' def check(self): return False
# ------------------------------ # 144. Binary Tree Preorder Traversal # # Description: # Given a binary tree, return the preorder traversal of its nodes' values. # Example: # Input: [1,null,2,3] # 1 # \ # 2 # / # 3 # Output: [1,2,3] # # Follow up: Recursive solution is trivial, could you do it iteratively? # # Version: 1.0 # 08/23/18 by Jianfa # ------------------------------ # 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 preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] res = [] traverse = [root] while traverse: node = traverse.pop() res.append(node.val) if node.right: traverse.append(node.right) if node.left: traverse.append(node.left) return res # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # Iterative solution. # Maintain a traverse list to decide the visiting order of nodes.
class Solution(object): def preorder_traversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] res = [] traverse = [root] while traverse: node = traverse.pop() res.append(node.val) if node.right: traverse.append(node.right) if node.left: traverse.append(node.left) return res if __name__ == '__main__': test = solution()
def set_partitions(iterable, k=None): """ Yield the set partitions of *iterable* into *k* parts. Set partitions are not order-preserving. >>> iterable = 'abc' >>> for part in set_partitions(iterable, 2): ... print([''.join(p) for p in part]) ['a', 'bc'] ['ab', 'c'] ['b', 'ac'] If *k* is not given, every set partition is generated. >>> iterable = 'abc' >>> for part in set_partitions(iterable): ... print([''.join(p) for p in part]) ['abc'] ['a', 'bc'] ['ab', 'c'] ['b', 'ac'] ['a', 'b', 'c'] """ L = list(iterable) n = len(L) if k is not None: if k < 1: raise ValueError( "Can't partition in a negative or zero number of groups" ) elif k > n: return def set_partitions_helper(L, k): n = len(L) if k == 1: yield [L] elif n == k: yield [[s] for s in L] else: e, *M = L for p in set_partitions_helper(M, k - 1): yield [[e], *p] for p in set_partitions_helper(M, k): for i in range(len(p)): yield p[:i] + [[e] + p[i]] + p[i + 1 :] if k is None: for k in range(1, n + 1): yield from set_partitions_helper(L, k) else: yield from set_partitions_helper(L, k) def get_groups_column_from_partitions(partitions, data_length): """ Transforms the partitions returned by set_partitions into vectors containing the group numbers Parameters ---------- partitions : list list of partition values returned by the set_partitions function data_length : int Number of lines in the input dataframe Returns ------- list A list containing all the groups column values corresponding to each partition """ permutations_values = [[i for i in range(data_length)] for elem in partitions] for i in range(len(partitions)): for j in permutations_values[i]: value = permutations_values[i][j] for k in range(len(partitions[i])): team = partitions[i][k] if value in team: permutations_values[i][j] = k return permutations_values
def set_partitions(iterable, k=None): """ Yield the set partitions of *iterable* into *k* parts. Set partitions are not order-preserving. >>> iterable = 'abc' >>> for part in set_partitions(iterable, 2): ... print([''.join(p) for p in part]) ['a', 'bc'] ['ab', 'c'] ['b', 'ac'] If *k* is not given, every set partition is generated. >>> iterable = 'abc' >>> for part in set_partitions(iterable): ... print([''.join(p) for p in part]) ['abc'] ['a', 'bc'] ['ab', 'c'] ['b', 'ac'] ['a', 'b', 'c'] """ l = list(iterable) n = len(L) if k is not None: if k < 1: raise value_error("Can't partition in a negative or zero number of groups") elif k > n: return def set_partitions_helper(L, k): n = len(L) if k == 1: yield [L] elif n == k: yield [[s] for s in L] else: (e, *m) = L for p in set_partitions_helper(M, k - 1): yield [[e], *p] for p in set_partitions_helper(M, k): for i in range(len(p)): yield (p[:i] + [[e] + p[i]] + p[i + 1:]) if k is None: for k in range(1, n + 1): yield from set_partitions_helper(L, k) else: yield from set_partitions_helper(L, k) def get_groups_column_from_partitions(partitions, data_length): """ Transforms the partitions returned by set_partitions into vectors containing the group numbers Parameters ---------- partitions : list list of partition values returned by the set_partitions function data_length : int Number of lines in the input dataframe Returns ------- list A list containing all the groups column values corresponding to each partition """ permutations_values = [[i for i in range(data_length)] for elem in partitions] for i in range(len(partitions)): for j in permutations_values[i]: value = permutations_values[i][j] for k in range(len(partitions[i])): team = partitions[i][k] if value in team: permutations_values[i][j] = k return permutations_values
def is_anagram(first, second): return sorted(list(first)) == sorted(list(second)) def main(): valid = 0 with open('day_4.in', 'r') as f: for l in f.readlines(): split = l.strip().split(' ') valid_passphrase = True for start in range(0, len(split) - 1): for cur in range(start + 1, len(split)): if is_anagram(split[start], split[cur]): valid_passphrase = False break if not valid_passphrase: break if valid_passphrase: valid += 1 print(valid) if __name__ == '__main__': main()
def is_anagram(first, second): return sorted(list(first)) == sorted(list(second)) def main(): valid = 0 with open('day_4.in', 'r') as f: for l in f.readlines(): split = l.strip().split(' ') valid_passphrase = True for start in range(0, len(split) - 1): for cur in range(start + 1, len(split)): if is_anagram(split[start], split[cur]): valid_passphrase = False break if not valid_passphrase: break if valid_passphrase: valid += 1 print(valid) if __name__ == '__main__': main()
# joint class definitions class TripleJoint(object): """ Describing the relations and dowel placement between 3 beams. """ def ___init___(self, beam_set, type_def, loc_para = 0): """ Initialization of a triple-joint isinstance :param beam_set: Which beams to consider :param type_def: Type and functions that controle the hole locs. :param loc_para: Where to consider them to be connected (0 or 1) """ self.beam_set = beam_set self.joint_type = joint_type self.loc_para = loc_para self.__location_setting() def __location_setting(self): """ Internal Method that set's up the location parameters of the beam """ a = (0 + self.loc_para) % 2 b = (1 + self.loc_para) % 2 c = (0 + self.loc_para) % 2 self.type_loc_para = self.type_def.Triple.locations[a, b, c] def get_connections(self): """ Internal Method that uses the functions defined in the joint types """ pt0, pt1, pt2 = self.joint_type.triple_dowel_execution() class DoubleJoint(object): """ Describing the relations and dowel placement between 2 beams, according to the Triple-Dowel-Beam logic. """ def __init__(self, beam_set, joint_type, loc_para = 0, left_or_right = 0): """ Initialization of a double-joint isinstance :param beam_set: Which beams to consider :param joint_type: Type and functions that controle the hole locs. :param loc_para: Where to consider them to be connected (0 or 1) :param left_or_right: Left or right set (0 or 1) """ self.beam_set = beam_set self.joint_type = joint_type self.loc_para = loc_para self.left_or_right = left_or_right def __location_setting(self): """ Internal Method that set's up the location parameters of the beam """ # double only logic if self.left_or_right: # which locations to consider from the type self.rel_locations = [(0 + self.loc_para) % 2, (1 + self.loc_para) % 2] self.type_loc_para = self.type_def.Triple.locations() elif not(self.left_or_right): self.rel_locations = [(1 + self.loc_para) % 2, (0 + self.loc_para) % 2] self.type_loc_para = self.type_def.Triple.locations(self) class EndSeams(object): """ Class defining the joints at the v-ends of the system """ def __init__(self, beam_set, location_parameters, joint_type): self.left_beam = beam_set[0] self.middle_beam = beam_set[1] self.right_beam = beam_set[2] self.loc_para = location_parameters self.joint_type = joint_type class Foundation(object): """ Class defining the joints connecting with the floor """ def __init__(self, beam_set, location_parameters, joint_type): self.left_beam = beam_set[0] self.middle_beam = beam_set[1] self.right_beam = beam_set[2] self.loc_para = location_parameters self.joint_type = joint_type
class Triplejoint(object): """ Describing the relations and dowel placement between 3 beams. """ def ___init___(self, beam_set, type_def, loc_para=0): """ Initialization of a triple-joint isinstance :param beam_set: Which beams to consider :param type_def: Type and functions that controle the hole locs. :param loc_para: Where to consider them to be connected (0 or 1) """ self.beam_set = beam_set self.joint_type = joint_type self.loc_para = loc_para self.__location_setting() def __location_setting(self): """ Internal Method that set's up the location parameters of the beam """ a = (0 + self.loc_para) % 2 b = (1 + self.loc_para) % 2 c = (0 + self.loc_para) % 2 self.type_loc_para = self.type_def.Triple.locations[a, b, c] def get_connections(self): """ Internal Method that uses the functions defined in the joint types """ (pt0, pt1, pt2) = self.joint_type.triple_dowel_execution() class Doublejoint(object): """ Describing the relations and dowel placement between 2 beams, according to the Triple-Dowel-Beam logic. """ def __init__(self, beam_set, joint_type, loc_para=0, left_or_right=0): """ Initialization of a double-joint isinstance :param beam_set: Which beams to consider :param joint_type: Type and functions that controle the hole locs. :param loc_para: Where to consider them to be connected (0 or 1) :param left_or_right: Left or right set (0 or 1) """ self.beam_set = beam_set self.joint_type = joint_type self.loc_para = loc_para self.left_or_right = left_or_right def __location_setting(self): """ Internal Method that set's up the location parameters of the beam """ if self.left_or_right: self.rel_locations = [(0 + self.loc_para) % 2, (1 + self.loc_para) % 2] self.type_loc_para = self.type_def.Triple.locations() elif not self.left_or_right: self.rel_locations = [(1 + self.loc_para) % 2, (0 + self.loc_para) % 2] self.type_loc_para = self.type_def.Triple.locations(self) class Endseams(object): """ Class defining the joints at the v-ends of the system """ def __init__(self, beam_set, location_parameters, joint_type): self.left_beam = beam_set[0] self.middle_beam = beam_set[1] self.right_beam = beam_set[2] self.loc_para = location_parameters self.joint_type = joint_type class Foundation(object): """ Class defining the joints connecting with the floor """ def __init__(self, beam_set, location_parameters, joint_type): self.left_beam = beam_set[0] self.middle_beam = beam_set[1] self.right_beam = beam_set[2] self.loc_para = location_parameters self.joint_type = joint_type
APP_KEY = 'u5lo5mX6IzAyv9TQJZG5tErDP' APP_SECRET = 'pJ294qcsbwcEty3ePPbGYVbD9sTL2J7dgC7BDdQ4KyoupmAxHS' OAUTH_TOKEN = '1285969065996095488-WqwqIQPP69TovfaCISoY6DkWWgwajY' OAUTH_TOKEN_SECRET = 'PIC1rTAs9Q9HD8zpGV7dMC5FMXpWmM5yn5WFhpJHt3li5' ## Your Telegram Channel Name ## channel_name = 'uchihacommunity' ## Telegram Access Token ## telegram_token = '1395164117:AAGmUsXuvPng9mwyWti_hTtfFzVtH075Wtc' ## Twitter User Name to get Timeline ## user_name = 'uchihahimself'
app_key = 'u5lo5mX6IzAyv9TQJZG5tErDP' app_secret = 'pJ294qcsbwcEty3ePPbGYVbD9sTL2J7dgC7BDdQ4KyoupmAxHS' oauth_token = '1285969065996095488-WqwqIQPP69TovfaCISoY6DkWWgwajY' oauth_token_secret = 'PIC1rTAs9Q9HD8zpGV7dMC5FMXpWmM5yn5WFhpJHt3li5' channel_name = 'uchihacommunity' telegram_token = '1395164117:AAGmUsXuvPng9mwyWti_hTtfFzVtH075Wtc' user_name = 'uchihahimself'
""" cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw ${1:1600,1000}; ') cmd.do('png ${2:aaa}.png') cmd.do('${0}') """ cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw 1600,1000; ') cmd.do('png aaa.png') # Description: Stereo draw. # Source: placeHolder
""" cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw ${1:1600,1000}; ') cmd.do('png ${2:aaa}.png') cmd.do('${0}') """ cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw 1600,1000; ') cmd.do('png aaa.png')
""" Lecture 10: Dynamic Programming Alternating Coin Game --------------------- Consider a game where you have a list with an even number of coins with positive integer values v_0, v_1, ..., v_i, ..., v_(n - 1) Each player alternates picking either the leftmost or rightmost coin until there are no coins left. Whichever player picks coins that add to the highest value wins. It can be easily shown that the player who moves first can always force a win. This program contains a function which given a list of coins, returns the most the first player can win assuming his opponent is also playing optimally. """ def dp_max_coin_value(dp, coins, i, j): """ Recursive function which computes the maximum possible value assuming the opponent also plays optimally It uses memoization to speed up performance with a Python dictionary named dp "dynamic programming" """ if (i, j) in dp: return dp[(i, j)] if i > j: return 0 elif i == j: dp[(i, j)] = coins[i] else: dp[(i, j)] = max( coins[i] + min( dp_max_coin_value(dp, coins, i + 1, j - 1), dp_max_coin_value(dp, coins, i + 2, j), ), coins[j] + min( dp_max_coin_value(dp, coins, i + 1, j - 1), dp_max_coin_value(dp, coins, i, j - 2), ), ) return dp[(i, j)] def max_possible_value(coins): """ Get the maximum possible value the first player can accumulate given a list of coins """ return dp_max_coin_value( dict(), coins, 0, len(coins) - 1)
""" Lecture 10: Dynamic Programming Alternating Coin Game --------------------- Consider a game where you have a list with an even number of coins with positive integer values v_0, v_1, ..., v_i, ..., v_(n - 1) Each player alternates picking either the leftmost or rightmost coin until there are no coins left. Whichever player picks coins that add to the highest value wins. It can be easily shown that the player who moves first can always force a win. This program contains a function which given a list of coins, returns the most the first player can win assuming his opponent is also playing optimally. """ def dp_max_coin_value(dp, coins, i, j): """ Recursive function which computes the maximum possible value assuming the opponent also plays optimally It uses memoization to speed up performance with a Python dictionary named dp "dynamic programming" """ if (i, j) in dp: return dp[i, j] if i > j: return 0 elif i == j: dp[i, j] = coins[i] else: dp[i, j] = max(coins[i] + min(dp_max_coin_value(dp, coins, i + 1, j - 1), dp_max_coin_value(dp, coins, i + 2, j)), coins[j] + min(dp_max_coin_value(dp, coins, i + 1, j - 1), dp_max_coin_value(dp, coins, i, j - 2))) return dp[i, j] def max_possible_value(coins): """ Get the maximum possible value the first player can accumulate given a list of coins """ return dp_max_coin_value(dict(), coins, 0, len(coins) - 1)
""" author : @akash kumar github : https://github/Akash671 string fun: string.replace(sub_old_string,new_sub_string,count) string.count(your_string) """ def solve(): #n,m=map(int,input().split()) #n=int(input()) #a=list(map(int,input().split()[:n])) #s=str(input()) #a,b=input().split() s=str(input()) a="" n=len(s) for i in range(2): a+=s[i] if a=="</" and s[n-1]==">" and s[2]!="/": print("Success") else: print("Error") for _ in range(int(input())): solve()
""" author : @akash kumar github : https://github/Akash671 string fun: string.replace(sub_old_string,new_sub_string,count) string.count(your_string) """ def solve(): s = str(input()) a = '' n = len(s) for i in range(2): a += s[i] if a == '</' and s[n - 1] == '>' and (s[2] != '/'): print('Success') else: print('Error') for _ in range(int(input())): solve()
"""Timedelta formatter. This script allows to format a given timedelta to a specific look. This file can also be imported as a module and contains the following functions: * format_timedelta - formats timedelta to hours:minutes:seconds """ def format_timedelta(td): """Format timedelta to hours:minutes:seconds. Args: td (datetime.timedelta): Seconds in timedelta format Returns: str: Formatted string """ minutes, seconds = divmod(td.seconds + td.days * 86400, 60) hours, minutes = divmod(minutes, 60) return "{:d}:{:02d}:{:02d}".format(hours, minutes, seconds)
"""Timedelta formatter. This script allows to format a given timedelta to a specific look. This file can also be imported as a module and contains the following functions: * format_timedelta - formats timedelta to hours:minutes:seconds """ def format_timedelta(td): """Format timedelta to hours:minutes:seconds. Args: td (datetime.timedelta): Seconds in timedelta format Returns: str: Formatted string """ (minutes, seconds) = divmod(td.seconds + td.days * 86400, 60) (hours, minutes) = divmod(minutes, 60) return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
def euler(): d = True x = 1 while d == True: x += 1 x_1 = str(x) x_2 = f"{2 * x}" x_3 = f"{3 * x}" x_4 = f"{4 * x}" x_5 = f"{5 * x}" x_6 = f"{6 * x}" if len(x_1) != len(x_6): continue sez1 = [] sez2 = [] sez3 = [] sez4 = [] sez5 = [] sez6 = [] for t in range(len(x_1)): sez1.append( x_1[t]) sez2.append(x_2[t]) sez3.append(x_3[t]) sez4.append(x_4[t]) sez5.append(x_5[t]) sez6.append(x_6[t]) sez1.sort() sez2.sort() sez3.sort() sez4.sort() sez5.sort() sez6.sort() if sez1 == sez2 == sez3 == sez4 == sez5 == sez6: return x return False euler()
def euler(): d = True x = 1 while d == True: x += 1 x_1 = str(x) x_2 = f'{2 * x}' x_3 = f'{3 * x}' x_4 = f'{4 * x}' x_5 = f'{5 * x}' x_6 = f'{6 * x}' if len(x_1) != len(x_6): continue sez1 = [] sez2 = [] sez3 = [] sez4 = [] sez5 = [] sez6 = [] for t in range(len(x_1)): sez1.append(x_1[t]) sez2.append(x_2[t]) sez3.append(x_3[t]) sez4.append(x_4[t]) sez5.append(x_5[t]) sez6.append(x_6[t]) sez1.sort() sez2.sort() sez3.sort() sez4.sort() sez5.sort() sez6.sort() if sez1 == sez2 == sez3 == sez4 == sez5 == sez6: return x return False euler()
# Given a string s, return the longest palindromic substring in s. # # Example 1: # Input: s = "babad" # Output: "bab" # Note: "aba" is also a valid answer. # lets first check if s a palindrome def palindrome(s): mid = len(s) // 2 if len(s) % 2 != 0: if s[:mid] == s[:mid:-1]: return s else: if s[:mid] == s[:mid - 1:-1]: return s return "" def longest_palindrome(s): if palindrome(s) == s: return s longest = s[0] for i in range(0, len(s)): for j in range(1, len(s)+1): current = palindrome(s[i:j]) if len(current) > len(longest): longest = current return longest if __name__ == "__main__": input_string0 = "babad" input_string1 = "cbbd" input_string2 = "a" input_string3 = "ac" input_string4 = "bb" print(longest_palindrome(input_string4))
def palindrome(s): mid = len(s) // 2 if len(s) % 2 != 0: if s[:mid] == s[:mid:-1]: return s elif s[:mid] == s[:mid - 1:-1]: return s return '' def longest_palindrome(s): if palindrome(s) == s: return s longest = s[0] for i in range(0, len(s)): for j in range(1, len(s) + 1): current = palindrome(s[i:j]) if len(current) > len(longest): longest = current return longest if __name__ == '__main__': input_string0 = 'babad' input_string1 = 'cbbd' input_string2 = 'a' input_string3 = 'ac' input_string4 = 'bb' print(longest_palindrome(input_string4))
def algo(load, plants): row = 0 produced = 0 names = [] p = [] for i in range(len(plants)): if row < len(plants): battery = plants.iloc[row, :] names.append(battery["name"]) if load > produced: temp = load - produced if battery["pmax"] >= temp >= battery["pmin"]: used = temp elif battery["pmax"] < temp: used = battery["pmax"] elif battery["pmin"] > temp: used = battery["pmin"] produced += used p.append(used) elif load <= produced: used = 0 p.append(used) row += 1 response = dict(zip(names, p)) return response
def algo(load, plants): row = 0 produced = 0 names = [] p = [] for i in range(len(plants)): if row < len(plants): battery = plants.iloc[row, :] names.append(battery['name']) if load > produced: temp = load - produced if battery['pmax'] >= temp >= battery['pmin']: used = temp elif battery['pmax'] < temp: used = battery['pmax'] elif battery['pmin'] > temp: used = battery['pmin'] produced += used p.append(used) elif load <= produced: used = 0 p.append(used) row += 1 response = dict(zip(names, p)) return response
# note the looping - we set the initial value for x =10 and when the first for loop is # executed, it is evaluated at that time, so changing the variable x in the loop # does not effect that loop. Now the next time that for loop is executed at that # time the new value of x is used! x = 10 for i in range(0,x): print(i) x = 5 for i in range(0,x): print(i) # another example x = 5 # outer loop for i in range (0, x): # inner loop for j in range(0, x): print(i, j) x = 3 # next time the inner loop is evaluted it will use this value
x = 10 for i in range(0, x): print(i) x = 5 for i in range(0, x): print(i) x = 5 for i in range(0, x): for j in range(0, x): print(i, j) x = 3
# -*- coding: utf-8 -*- """ Created on Thu May 23 10:05:43 2019 @author: Parikshith.H """ L = [10,20,30,40,50] n = len(L) print("number of elements =",n) for i in range(n): print(L[i]) # ============================================================================= # #output: # number of elements = 5 # 10 # 20 # 30 # 40 # 50 # ============================================================================= for elem in L: print(elem) # ============================================================================= # #output: # 10 # 20 # 30 # 40 # 50 # ============================================================================= #program to add the contents of two lists and store in another list A = [10,20,30] B = [1,2,3] for i in range(len(A)): print(A[i] + B[i]) # ============================================================================= # #output: # 11 # 22 # 33 # ============================================================================= list = [1, 3, 5, 7, 9] for i, val in enumerate(list): print (i, ",",val) # ============================================================================= # #output: # 0 , 1 # 1 , 3 # 2 , 5 # 3 , 7 # 4 , 9 # =============================================================================
""" Created on Thu May 23 10:05:43 2019 @author: Parikshith.H """ l = [10, 20, 30, 40, 50] n = len(L) print('number of elements =', n) for i in range(n): print(L[i]) for elem in L: print(elem) a = [10, 20, 30] b = [1, 2, 3] for i in range(len(A)): print(A[i] + B[i]) list = [1, 3, 5, 7, 9] for (i, val) in enumerate(list): print(i, ',', val)
# This is a variable concept ''' a = 10 print(a) print(type(a)) a = 10.33 print(a) print(type(a)) a = "New Jersey" print(a) print(type(a)) ''' #a = input() #print(a) name = input("Please enter your name : ") print("Your name is ",name) print(type(name)) number = int(input("Enter your number : ")) #Explicit type conversion print("Your number is ",number) print(type(number))
""" a = 10 print(a) print(type(a)) a = 10.33 print(a) print(type(a)) a = "New Jersey" print(a) print(type(a)) """ name = input('Please enter your name : ') print('Your name is ', name) print(type(name)) number = int(input('Enter your number : ')) print('Your number is ', number) print(type(number))
def vowels(word): if (word[0] in 'AEIOU' or word[0] in 'aeiou'): if (word[len(word) - 1] in 'AEIOU' or word[len(word) - 1] in 'aeiou'): return 'First and last letter of ' + word + ' is vowel' else: return 'First letter of ' + word + ' is vowel' else: return 'Not a vowel' print(vowels('ankara'))
def vowels(word): if word[0] in 'AEIOU' or word[0] in 'aeiou': if word[len(word) - 1] in 'AEIOU' or word[len(word) - 1] in 'aeiou': return 'First and last letter of ' + word + ' is vowel' else: return 'First letter of ' + word + ' is vowel' else: return 'Not a vowel' print(vowels('ankara'))
""" Author: Andreas Finkler Created: 23.12.2020 """
""" Author: Andreas Finkler Created: 23.12.2020 """
dist = [] for num in range(1, 1000): if (num % 3 == 0) or (num % 5 == 0): dist.append(num) print(sum(dist))
dist = [] for num in range(1, 1000): if num % 3 == 0 or num % 5 == 0: dist.append(num) print(sum(dist))
add_init_container = [ { 'op': 'add', 'path': '/some/new/path', 'value': 'some-value', }, ]
add_init_container = [{'op': 'add', 'path': '/some/new/path', 'value': 'some-value'}]
def get_persistent_id(node_unicode_proxy, *args, **kwargs): return node_unicode_proxy def get_type(node, *args, **kwargs): return type(node) def is_exact_type(node, typename, *args, **kwargs): return isinstance(node, typename) def is_type(node, typename, *args, **kwargs): return typename in ['Transform', 'Curve', 'Joint', 'Shape', 'UnicodeDelegate', 'DagNode'] def rename(node_dag, name, *args, **kwargs): return name def duplicate(node_dag, parent_only=True, *args, **kwargs): return node_dag + '_duplicate' def list_relatives(node_dag, *args, **kwargs): return node_dag def parent(node, new_parent, *args, **kwargs): return new_parent def delete(nodes, *args, **kwargs): del (nodes) def get_scene_tree(): return {'standalone': None} def list_scene(object_type='transform', *args, **kwargs): return [] def list_scene_nodes(object_type='transform', has_shape=False): return ['standalone'] def exists(node, *args, **kwargs): return True def safe_delete(node_or_nodes): return True
def get_persistent_id(node_unicode_proxy, *args, **kwargs): return node_unicode_proxy def get_type(node, *args, **kwargs): return type(node) def is_exact_type(node, typename, *args, **kwargs): return isinstance(node, typename) def is_type(node, typename, *args, **kwargs): return typename in ['Transform', 'Curve', 'Joint', 'Shape', 'UnicodeDelegate', 'DagNode'] def rename(node_dag, name, *args, **kwargs): return name def duplicate(node_dag, parent_only=True, *args, **kwargs): return node_dag + '_duplicate' def list_relatives(node_dag, *args, **kwargs): return node_dag def parent(node, new_parent, *args, **kwargs): return new_parent def delete(nodes, *args, **kwargs): del nodes def get_scene_tree(): return {'standalone': None} def list_scene(object_type='transform', *args, **kwargs): return [] def list_scene_nodes(object_type='transform', has_shape=False): return ['standalone'] def exists(node, *args, **kwargs): return True def safe_delete(node_or_nodes): return True
age = 20 if age >= 20 and age == 30: print('age == 30') elif age >= 20 or age == 30: print(' age >= 20 or age == 30') else: print('...')
age = 20 if age >= 20 and age == 30: print('age == 30') elif age >= 20 or age == 30: print(' age >= 20 or age == 30') else: print('...')
"""Default configuration settings""" DEBUG = True TESTING = False # Logging LOGGER_NAME = 'api-server' LOG_FILENAME = 'api-server.log' # PostgreSQL USE_POSTGRESQL = True POSTGRESQL_DATABASE = 'my_resume' POSTGRESQL_USER = 'learn' POSTGRESQL_PASSWORD = 'pass.word' POSTGRESQL_HOST = 'localhost' POSTGRESQL_PORT = '5432'
"""Default configuration settings""" debug = True testing = False logger_name = 'api-server' log_filename = 'api-server.log' use_postgresql = True postgresql_database = 'my_resume' postgresql_user = 'learn' postgresql_password = 'pass.word' postgresql_host = 'localhost' postgresql_port = '5432'
class Solution(object): def lastStoneWeight(self, stones): """ :type stones: List[int] :rtype: int """ #helper function def remove_largest(): #locate the index of the element with max value heaviest_1_idx = stones.index(max(stones)) #swap the highest value element with the last element stones[heaviest_1_idx], stones[-1] = stones[-1], stones[heaviest_1_idx] #pop the element at the last index return stones.pop() #special case handler #list is empty if not stones: return 0 #list has only 1 element elif len(stones) == 1: return stones[0] else: #loop as long as list has no more than 1 element while len(stones) > 1: #pop the heaviest element in the list heaviest_1 = remove_largest() #pop the heaviest element in the list heaviest_2 = remove_largest() #if the weights of two heaviest elements are not the same if heaviest_1 - heaviest_2 != 0: #append the new element into the list after the different weight is subtract stones.append(heaviest_1 - heaviest_2) #return the only element in the list if the list is not empty; otherwise, return 0 return stones[0] if stones else 0
class Solution(object): def last_stone_weight(self, stones): """ :type stones: List[int] :rtype: int """ def remove_largest(): heaviest_1_idx = stones.index(max(stones)) (stones[heaviest_1_idx], stones[-1]) = (stones[-1], stones[heaviest_1_idx]) return stones.pop() if not stones: return 0 elif len(stones) == 1: return stones[0] else: while len(stones) > 1: heaviest_1 = remove_largest() heaviest_2 = remove_largest() if heaviest_1 - heaviest_2 != 0: stones.append(heaviest_1 - heaviest_2) return stones[0] if stones else 0
def namta(p=1): for i in range(1, 11): print(p, "x", i, "=", p*i) namta(5) namta()
def namta(p=1): for i in range(1, 11): print(p, 'x', i, '=', p * i) namta(5) namta()
num_waves = 2 num_eqn = 2 # Conserved quantities pressure = 0 velocity = 1
num_waves = 2 num_eqn = 2 pressure = 0 velocity = 1
# Defining our main object of interation game = [[0,0,0], [0,0,0], [0,0,0]] #printing a column index, printing a row index, now #we have a coordinate to make a move, like c2 def game_board(player=0, row=1, column=1, just_display=False): print(' 1 2 3') if not just_display: game[row][column] = player for count, row in enumerate(game, 1): print(count, row) game_board(just_display=True) game_board(player=1, row=2, column=1) # game[0][1] = 1 # game_board()
game = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] def game_board(player=0, row=1, column=1, just_display=False): print(' 1 2 3') if not just_display: game[row][column] = player for (count, row) in enumerate(game, 1): print(count, row) game_board(just_display=True) game_board(player=1, row=2, column=1)
def function_2(x): return x[0]**2 + x[1]**2 def numerical_diff(f, x): h = 1e-4 return (f(x+h) - f(x-h)) / (2*h) def function_tmp1(x0): return x0*x0 + 4.0**2 def function_tmp2(x1): return 3.0**2.0 + x1*x1 print(numerical_diff(function_tmp1, 3.0)) print(numerical_diff(function_tmp2, 4.0))
def function_2(x): return x[0] ** 2 + x[1] ** 2 def numerical_diff(f, x): h = 0.0001 return (f(x + h) - f(x - h)) / (2 * h) def function_tmp1(x0): return x0 * x0 + 4.0 ** 2 def function_tmp2(x1): return 3.0 ** 2.0 + x1 * x1 print(numerical_diff(function_tmp1, 3.0)) print(numerical_diff(function_tmp2, 4.0))
""" >>> motor = Motor() >>> motor.acelerar() >>> motor.velocidade 1 """ # TODO: ajustar o doctest class Carro: def __init__(self, motor, direcao): self.motor = motor self.direcao = direcao def calcular_velocidade(self): return self.motor.velocidade def acelerar(self): self.motor.acelerar() def frear(self): self.motor.frear() def calcular_direcao(self): return self.direcao.valor def girar_a_direita(self): return self.direcao.girar_a_direita() def girar_a_esquerda(self): return self.direcao.girar_a_esquerda() class Motor: def __init__(self, velocidade=0): self.velocidade = velocidade def acelerar(self): self.velocidade += 1 def frear(self): if self.velocidade >= 2: self.velocidade -= 2 else: self.velocidade = 0 NORTE = 'Norte' SUL = 'Sul' LESTE = 'Leste' OESTE = 'Oeste' class Direcao: rotacao_direita_dct = {NORTE: LESTE, LESTE: SUL, SUL: OESTE, OESTE: NORTE} rotacao_esquerda_dct = {NORTE: OESTE, LESTE: NORTE, SUL: LESTE, OESTE: SUL} def __init__(self, valor=NORTE): self.valor = valor def girar_a_direita(self): self.valor = self.rotacao_direita_dct[self] def girar_a_esquerda(self): self.valor = self.rotacao_esquerda_dct[self]
""" >>> motor = Motor() >>> motor.acelerar() >>> motor.velocidade 1 """ class Carro: def __init__(self, motor, direcao): self.motor = motor self.direcao = direcao def calcular_velocidade(self): return self.motor.velocidade def acelerar(self): self.motor.acelerar() def frear(self): self.motor.frear() def calcular_direcao(self): return self.direcao.valor def girar_a_direita(self): return self.direcao.girar_a_direita() def girar_a_esquerda(self): return self.direcao.girar_a_esquerda() class Motor: def __init__(self, velocidade=0): self.velocidade = velocidade def acelerar(self): self.velocidade += 1 def frear(self): if self.velocidade >= 2: self.velocidade -= 2 else: self.velocidade = 0 norte = 'Norte' sul = 'Sul' leste = 'Leste' oeste = 'Oeste' class Direcao: rotacao_direita_dct = {NORTE: LESTE, LESTE: SUL, SUL: OESTE, OESTE: NORTE} rotacao_esquerda_dct = {NORTE: OESTE, LESTE: NORTE, SUL: LESTE, OESTE: SUL} def __init__(self, valor=NORTE): self.valor = valor def girar_a_direita(self): self.valor = self.rotacao_direita_dct[self] def girar_a_esquerda(self): self.valor = self.rotacao_esquerda_dct[self]
JOBS_RAW = { 0: { "Name": "Farmer" }, 1: { "Name": "Baker" }, 2: { "Name": "Lumberjack" }, 3: { "Name": "Carpenter" } }
jobs_raw = {0: {'Name': 'Farmer'}, 1: {'Name': 'Baker'}, 2: {'Name': 'Lumberjack'}, 3: {'Name': 'Carpenter'}}
class ApiException(Exception): """ Generic Catch-all for API Exceptions. """ status_code = None def __init__(self, status_code=None, msg=None, *args, **kwargs): self.status_code = status_code super(ApiException, self).__init__(msg, *args, **kwargs)
class Apiexception(Exception): """ Generic Catch-all for API Exceptions. """ status_code = None def __init__(self, status_code=None, msg=None, *args, **kwargs): self.status_code = status_code super(ApiException, self).__init__(msg, *args, **kwargs)
class AutowiringError(Exception): """ Error indicating autowiring of a function failed. """ ...
class Autowiringerror(Exception): """ Error indicating autowiring of a function failed. """ ...
def work(x): x = x.split("cat ") #"cat " is a delimiter for the whole command dividing the line on two parts f = open(x[1], "r") #the second part is a filename or path (in the future) print(f.read()) #outputs the content of the specified file
def work(x): x = x.split('cat ') f = open(x[1], 'r') print(f.read())
def un_avg_pool(name, l_input, k, images_placeholder, test_images): """ the input is an 5-D array: batch_size length width height channels """ input_shape = l_input.get_shape().as_list() batch_size = input_shape[0] length = input_shape[1] width = input_shape[2] height = input_shape[3] channels = input_shape[4] output_shape = [batch_size,k*length,2*width,2*height,channels] sess.run(tf.global_variables_initializer()) input_array = np.zeros(input_shape,dtype = np.float32) output_array = np.zeros(output_shape,dtype = np.float32) input_array = l_input.eval(session = sess,feed_dict={images_placeholder:test_images}) #input_array = np.array(l_input.as_list()) for n in range(batch_size): for l in range(k*length): for w in range(2*width): for h in range(2*height): for c in range(channels): output_array[n,l,w,h,c] = input_array[n,int(l/k),int(w/2),int(h/2),c] output = tf.convert_to_tensor(output_array) return output def un_max_pool(name, l_input, l_output, k, images_placeholder, test_images): ''' parameters: l_input is the input of pool l_output is the output of pool according to input,we can get the max index according to output and max_index, unpool and reconstruct the input return: the reconstructed input ''' input_shape = l_input.get_shape().as_list() output_shape = l_output.get_shape().as_list() batch_size = output_shape[0] length = output_shape[1] rows = output_shape[2] cols = output_shape[3] channels = output_shape[4] input_array = l_input.eval(session = sess,feed_dict={images_placeholder:test_images}) output_array = l_output.eval(session = sess,feed_dict = {images_placeholder:test_images}) unpool_array = np.zeros(input_shape,dtype = np.float32) for n in range(batch_size): for l in range(length): for r in range(rows): for c in range(cols): for ch in range(channels): l_in, r_in, c_in = k*l, 2*r, 2*c sub_square = input_array[ n, l_in:l_in+k, r_in:r_in+2, c_in:c_in+2, ch ] max_pos_l, max_pos_r, max_pos_c = np.unravel_index(np.nanargmax(sub_square), (k, 2, 2)) array_pixel = output_array[ n, l, r, c, ch ] unpool_array[n, l_in + max_pos_l, r_in + max_pos_r, c_in + max_pos_c, ch] = array_pixel unpool = tf.convert_to_tensor(unpool_array) return unpool def un_max_pool_approximate(name,l_input,output_shape,k): # out = tf.concat([l_input,tf.zeros_like(l_input)], 4) #concat along the channel axis # out = tf.concat([out,tf.zeros_like(out)], 3) #concat along the no.-2 axis # if k == 2: # out = tf.concat([out,tf.zeros_like(out)], 2) #concat along the no.-3 axis # out = tf.reshape(out,output_shape) out = tf.concat([l_input,l_input], 4) #concat along the channel axis out = tf.concat([out,out], 3) #concat along the no.-2 axis if k == 2: out = tf.concat([out,out], 2) #concat along the no.-3 axis out = tf.reshape(out,output_shape) return out
def un_avg_pool(name, l_input, k, images_placeholder, test_images): """ the input is an 5-D array: batch_size length width height channels """ input_shape = l_input.get_shape().as_list() batch_size = input_shape[0] length = input_shape[1] width = input_shape[2] height = input_shape[3] channels = input_shape[4] output_shape = [batch_size, k * length, 2 * width, 2 * height, channels] sess.run(tf.global_variables_initializer()) input_array = np.zeros(input_shape, dtype=np.float32) output_array = np.zeros(output_shape, dtype=np.float32) input_array = l_input.eval(session=sess, feed_dict={images_placeholder: test_images}) for n in range(batch_size): for l in range(k * length): for w in range(2 * width): for h in range(2 * height): for c in range(channels): output_array[n, l, w, h, c] = input_array[n, int(l / k), int(w / 2), int(h / 2), c] output = tf.convert_to_tensor(output_array) return output def un_max_pool(name, l_input, l_output, k, images_placeholder, test_images): """ parameters: l_input is the input of pool l_output is the output of pool according to input,we can get the max index according to output and max_index, unpool and reconstruct the input return: the reconstructed input """ input_shape = l_input.get_shape().as_list() output_shape = l_output.get_shape().as_list() batch_size = output_shape[0] length = output_shape[1] rows = output_shape[2] cols = output_shape[3] channels = output_shape[4] input_array = l_input.eval(session=sess, feed_dict={images_placeholder: test_images}) output_array = l_output.eval(session=sess, feed_dict={images_placeholder: test_images}) unpool_array = np.zeros(input_shape, dtype=np.float32) for n in range(batch_size): for l in range(length): for r in range(rows): for c in range(cols): for ch in range(channels): (l_in, r_in, c_in) = (k * l, 2 * r, 2 * c) sub_square = input_array[n, l_in:l_in + k, r_in:r_in + 2, c_in:c_in + 2, ch] (max_pos_l, max_pos_r, max_pos_c) = np.unravel_index(np.nanargmax(sub_square), (k, 2, 2)) array_pixel = output_array[n, l, r, c, ch] unpool_array[n, l_in + max_pos_l, r_in + max_pos_r, c_in + max_pos_c, ch] = array_pixel unpool = tf.convert_to_tensor(unpool_array) return unpool def un_max_pool_approximate(name, l_input, output_shape, k): out = tf.concat([l_input, l_input], 4) out = tf.concat([out, out], 3) if k == 2: out = tf.concat([out, out], 2) out = tf.reshape(out, output_shape) return out
num = int(input('Enter a number:')) count = 0 while num != 0: num //= 10 count += 1 print("Total digits are: ", count)
num = int(input('Enter a number:')) count = 0 while num != 0: num //= 10 count += 1 print('Total digits are: ', count)
#!/usr/bin/python # -*- coding: utf-8 -*- class Answer(object): def __init__(self, p_id, username, datetime_from, content): self.p_id = p_id self.username = username self.datetime_from = datetime_from self.content = content """docstring for Answer""" # def __init__(self, arg): # super(Answer, self).__init__() # self.arg = arg
class Answer(object): def __init__(self, p_id, username, datetime_from, content): self.p_id = p_id self.username = username self.datetime_from = datetime_from self.content = content 'docstring for Answer'
class MetodoDeNewton(object): def __init__(self, f, f_derivada, x0, precisao=0.001, max_interacoes=15): self.__X = [x0] self.__interacoes = 0 while self.interacoes < max_interacoes: self.__X.append(self.X[-1] - f(self.X[-1]) / f_derivada(self.X[-1])) self.__interacoes += 1 if abs(self.X[-2] - self.X[-1]) <= precisao: break @property def X(self): return self.__X @property def x(self): return self.__X[-1] @property def interacoes(self): return self.__interacoes
class Metododenewton(object): def __init__(self, f, f_derivada, x0, precisao=0.001, max_interacoes=15): self.__X = [x0] self.__interacoes = 0 while self.interacoes < max_interacoes: self.__X.append(self.X[-1] - f(self.X[-1]) / f_derivada(self.X[-1])) self.__interacoes += 1 if abs(self.X[-2] - self.X[-1]) <= precisao: break @property def x(self): return self.__X @property def x(self): return self.__X[-1] @property def interacoes(self): return self.__interacoes
S = input() t = ''.join(c if c in 'ACGT' else ' ' for c in S) print(max(map(len, t.split(' '))))
s = input() t = ''.join((c if c in 'ACGT' else ' ' for c in S)) print(max(map(len, t.split(' '))))
""" Helper functions for both simulator and solver. """ __author__ = "Z Feng" def pattern_to_similarity(pattern: str) -> int: """ Convert a pattern of string consisting of '0', '1' and '2' to a similarity rating. '2': right letter in right place '1': right letter in wrong place '0': wrong letter :param pattern: string of pattern :return: similarity """ return int(pattern[::-1], 3) def similarity_to_pattern(similarity: int) -> str: """ Inverse of pattern_to_similarity for 5 digit in base 3. :param similarity: str :return: pattern """ pattern = '' for i in range(5): pattern += str(similarity % (3 ** (i + 1)) // 3 ** i) return pattern def gen_similarity_LUT(legal_guesses: list = None, potential_answers: list = None) -> dict: """ Generate the lookup table (LUT) of similarities for any guess and answer in the dictionary. LUT returned as a nested dictionary: lut[guess][target] == similarity. :param legal_guesses: list of legal guesses :param potential_answers: list of potential answers :return: LUT nested dictionary """ if legal_guesses is None: legal_guesses = get_guess_dictionary() if potential_answers is None: potential_answers = get_answer_dictionary() lut = {guess: {answer: compare(guess, answer) for answer in potential_answers} for guess in legal_guesses} return lut def compare(guess: str, target: str, lut: dict = None) -> int: """ Compare a guess string to a target string. Return the similarity as an integer in the range of [0, 3^N-1], where N is the length of both guess and target strings. """ assert len(guess) == len(target) if not lut is None: if guess in lut: if target in lut[guess]: return lut[guess][target] N = len(guess) similarity = 0 used_target = [False for i in range(N)] used_guess = [False for i in range(N)] for i in range(N): if guess[i] == target[i]: similarity += 2 * 3 ** i used_target[i] = True used_guess[i] = True for i in range(N): if used_guess[i]: continue for j in range(N): if not used_target[j] and guess[i] == target[j]: similarity += 3 ** i used_target[j] = True break assert 0 <= similarity < 3 ** N return similarity def get_guess_dictionary() -> list: with open('words_wordle.txt', 'r') as f: dictionary = f.readlines() for i in range(len(dictionary)): # print(len(word)) assert len(dictionary[i]) == 6 dictionary[i] = dictionary[i][:5] return dictionary def get_answer_dictionary() -> list: with open('words_wordle_solutions.txt', 'r') as f: dictionary = f.readlines() for i in range(len(dictionary)): # print(len(word)) assert len(dictionary[i]) == 6 dictionary[i] = dictionary[i][:5] return dictionary if __name__ == "__main__": guess = 'speed' target = 'crepe' similarity = compare(guess, target) print(similarity) print(similarity_to_pattern(similarity)) #EOF
""" Helper functions for both simulator and solver. """ __author__ = 'Z Feng' def pattern_to_similarity(pattern: str) -> int: """ Convert a pattern of string consisting of '0', '1' and '2' to a similarity rating. '2': right letter in right place '1': right letter in wrong place '0': wrong letter :param pattern: string of pattern :return: similarity """ return int(pattern[::-1], 3) def similarity_to_pattern(similarity: int) -> str: """ Inverse of pattern_to_similarity for 5 digit in base 3. :param similarity: str :return: pattern """ pattern = '' for i in range(5): pattern += str(similarity % 3 ** (i + 1) // 3 ** i) return pattern def gen_similarity_lut(legal_guesses: list=None, potential_answers: list=None) -> dict: """ Generate the lookup table (LUT) of similarities for any guess and answer in the dictionary. LUT returned as a nested dictionary: lut[guess][target] == similarity. :param legal_guesses: list of legal guesses :param potential_answers: list of potential answers :return: LUT nested dictionary """ if legal_guesses is None: legal_guesses = get_guess_dictionary() if potential_answers is None: potential_answers = get_answer_dictionary() lut = {guess: {answer: compare(guess, answer) for answer in potential_answers} for guess in legal_guesses} return lut def compare(guess: str, target: str, lut: dict=None) -> int: """ Compare a guess string to a target string. Return the similarity as an integer in the range of [0, 3^N-1], where N is the length of both guess and target strings. """ assert len(guess) == len(target) if not lut is None: if guess in lut: if target in lut[guess]: return lut[guess][target] n = len(guess) similarity = 0 used_target = [False for i in range(N)] used_guess = [False for i in range(N)] for i in range(N): if guess[i] == target[i]: similarity += 2 * 3 ** i used_target[i] = True used_guess[i] = True for i in range(N): if used_guess[i]: continue for j in range(N): if not used_target[j] and guess[i] == target[j]: similarity += 3 ** i used_target[j] = True break assert 0 <= similarity < 3 ** N return similarity def get_guess_dictionary() -> list: with open('words_wordle.txt', 'r') as f: dictionary = f.readlines() for i in range(len(dictionary)): assert len(dictionary[i]) == 6 dictionary[i] = dictionary[i][:5] return dictionary def get_answer_dictionary() -> list: with open('words_wordle_solutions.txt', 'r') as f: dictionary = f.readlines() for i in range(len(dictionary)): assert len(dictionary[i]) == 6 dictionary[i] = dictionary[i][:5] return dictionary if __name__ == '__main__': guess = 'speed' target = 'crepe' similarity = compare(guess, target) print(similarity) print(similarity_to_pattern(similarity))
# coding=utf-8 def point_inside(p, bounds): return bounds[3] <= p[0] <= bounds[1] and bounds[0] <= p[1] <= bounds[2]
def point_inside(p, bounds): return bounds[3] <= p[0] <= bounds[1] and bounds[0] <= p[1] <= bounds[2]
#Python Operators x = 9 y = 3 #Arithmetic operators print(x+y) #Addition print(x-y) #Subtraction print(x*y) #Multiplication print(x/y) #Division print(x%y) #Modulus print(x**y) #Exponentiation x = 9.191823 print(x//y) #Floor division #Assignment operators x = 9 x += 3 print(x) x = 9 x -= 3 print(x) x *= 3 print(x) x /= 3 print(x) x **= 3 print(x) #Comparison operators x = 9 y = 3 print(x==y) #True if x equals y, False otherwise print(x != y) #True if x does not equal y, False otherwise print(x > y) #True if x is greater than y, False otherwise print(x < y) #True if x is less than y, False otherwise print(x >= y) #True if x is greater than or equal to y, False otherwise print(x <= y) #True if x is less than or equal to y, False otherwise
x = 9 y = 3 print(x + y) print(x - y) print(x * y) print(x / y) print(x % y) print(x ** y) x = 9.191823 print(x // y) x = 9 x += 3 print(x) x = 9 x -= 3 print(x) x *= 3 print(x) x /= 3 print(x) x **= 3 print(x) x = 9 y = 3 print(x == y) print(x != y) print(x > y) print(x < y) print(x >= y) print(x <= y)
test = { 'name': 'lab1_p1a', 'suites': [ { 'cases': [ { 'code': r""" >>> # It looks like your variable is not named correctly. >>> # Remember, we want to save the value of pi as a variable. >>> # What type should the variable be? >>> # Start the variable name with pi_ >>> 'pi_flt' in vars() True """ }, { 'code': r""" >>> # The variable name is good but the value is off. >>> # Seems like a typo. >>> pi_flt == 3.1416 True """ } ] } ] }
test = {'name': 'lab1_p1a', 'suites': [{'cases': [{'code': "\n >>> # It looks like your variable is not named correctly.\n >>> # Remember, we want to save the value of pi as a variable.\n >>> # What type should the variable be?\n >>> # Start the variable name with pi_\n >>> 'pi_flt' in vars()\n True\n "}, {'code': '\n >>> # The variable name is good but the value is off.\n >>> # Seems like a typo.\n >>> pi_flt == 3.1416\n True\n '}]}]}
"""This problem was asked by Google. You're given a string consisting solely of (, ), and *. * can represent either a (, ), or an empty string. Determine whether the parentheses are balanced. For example, (()* and (*) are balanced. )*( is not balanced. """
"""This problem was asked by Google. You're given a string consisting solely of (, ), and *. * can represent either a (, ), or an empty string. Determine whether the parentheses are balanced. For example, (()* and (*) are balanced. )*( is not balanced. """
# 2020.04.27 # https://leetcode.com/problems/add-two-numbers/submissions/ # works # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: # Part 1: turn the linked lists into listspart # get values into list: list1 = [] list1.append(l1.val) mask = l1 while mask.next: if mask.next: list1.append(mask.next.val) if mask.next.next: mask = mask.next else: break print(list1) # get values into list: list2 = [] list2.append(l2.val) mask = l2 while mask.next: if mask.next: list2.append(mask.next.val) if mask.next.next: mask = mask.next else: break print(list2) # part 2: reverse the numbers l1 = list1 l2 = list2 # convert list 1 l1 = l1[::-1] # reverse the order strL = "" l1 = int("".join(map(str, l1))) # convert to a single number print(l1) # convert list 2 l2 = l2[::-1] # reverse the order strL = "" l2 = int("".join(map(str, l2))) # convert to a single number print(l2) # add and make a new backwards list # add list 1 and list 2 l3 = l1 + l2 # add the numbers l3 = list(str(l3)) # convert to list of digits (string form) l3 = list(map(int, l3)) # convert to a list of digits l3 = l3[::-1] # reverse the order print(l3) # turn back into a linked list # swap names list3 = l3 # start the linked list l3 = ListNode(list3[0]) # remove first item list3.pop(0) mask = l3 for i in list3: # now one digit shorter mask.next = ListNode(i) # create node for each item in list # print(mask.next.val) mask = mask.next print(l3.val) print(l3.next.val) print(l3.next.next.val) return l3 xx = Solution() l1 = ListNode(2) l1.next = ListNode(4) l1.next.next = ListNode(3) l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(4) xx.addTwoNumbers(l1, l2)
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode: list1 = [] list1.append(l1.val) mask = l1 while mask.next: if mask.next: list1.append(mask.next.val) if mask.next.next: mask = mask.next else: break print(list1) list2 = [] list2.append(l2.val) mask = l2 while mask.next: if mask.next: list2.append(mask.next.val) if mask.next.next: mask = mask.next else: break print(list2) l1 = list1 l2 = list2 l1 = l1[::-1] str_l = '' l1 = int(''.join(map(str, l1))) print(l1) l2 = l2[::-1] str_l = '' l2 = int(''.join(map(str, l2))) print(l2) l3 = l1 + l2 l3 = list(str(l3)) l3 = list(map(int, l3)) l3 = l3[::-1] print(l3) list3 = l3 l3 = list_node(list3[0]) list3.pop(0) mask = l3 for i in list3: mask.next = list_node(i) mask = mask.next print(l3.val) print(l3.next.val) print(l3.next.next.val) return l3 xx = solution() l1 = list_node(2) l1.next = list_node(4) l1.next.next = list_node(3) l2 = list_node(5) l2.next = list_node(6) l2.next.next = list_node(4) xx.addTwoNumbers(l1, l2)
KNOWN_PATHS = [ "/etc/systemd/*", "/etc/systemd/**/*", "/lib/systemd/*", "/lib/systemd/**/*", "/run/systemd/*", "/run/systemd/**/*", "/usr/lib/systemd/*", "/usr/lib/systemd/**/*", ] KNOWN_DROPIN_PATHS = { "user.conf": [ "/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], "system.conf": [ "/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".service": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".target": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".mount": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".automount": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".device": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".swap": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".path": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".timer": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".scope": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".slice": [ "/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".network": [ "/etc/systemd/network/%unit%.d/*.conf", "/run/systemd/network/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], ".netdev": [ "/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], "timesyncd.conf": [ "/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], "journald.conf": [ "/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], "journal-upload.conf": [ "/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf" ], }
known_paths = ['/etc/systemd/*', '/etc/systemd/**/*', '/lib/systemd/*', '/lib/systemd/**/*', '/run/systemd/*', '/run/systemd/**/*', '/usr/lib/systemd/*', '/usr/lib/systemd/**/*'] known_dropin_paths = {'user.conf': ['/etc/systemd/%unit%.d/*.conf', '/run/systemd/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], 'system.conf': ['/etc/systemd/%unit%.d/*.conf', '/run/systemd/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.service': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.target': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.mount': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.automount': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.device': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.swap': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.path': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.timer': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.scope': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.slice': ['/etc/systemd/system/%unit%.d/*.conf', '/run/systemd/system/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.network': ['/etc/systemd/network/%unit%.d/*.conf', '/run/systemd/network/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], '.netdev': ['/etc/systemd/%unit%.d/*.conf', '/run/systemd/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], 'timesyncd.conf': ['/etc/systemd/%unit%.d/*.conf', '/run/systemd/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], 'journald.conf': ['/etc/systemd/%unit%.d/*.conf', '/run/systemd/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf'], 'journal-upload.conf': ['/etc/systemd/%unit%.d/*.conf', '/run/systemd/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib/systemd/%unit%.d/*.conf']}
"""Top-level package for NewlineCharacterConv.""" __author__ = """NewlineCharacterConv""" __email__ = 'qin__xuan@yeah.net' __version__ = '0.1.0'
"""Top-level package for NewlineCharacterConv.""" __author__ = 'NewlineCharacterConv' __email__ = 'qin__xuan@yeah.net' __version__ = '0.1.0'
# Created by MechAviv # ID :: [101000010] # Ellinia : Magic Library sm.warp(101000000, 4)
sm.warp(101000000, 4)
class SubrectangleQueries: def __init__(self, rectangle: List[List[int]]): self.rectangle = rectangle def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: self.row1, self.col1, self.row2, self.col2, self.newValue = row1, col1, row2, col2, newValue for i in range(self.row1, self.row2 + 1) : for j in range(self.col1, self.col2 + 1): self.rectangle[i][j] = self.newValue def getValue(self, row: int, col: int) -> int: self.row = row self.col = col return self.rectangle[self.row][self.col] # Your SubrectangleQueries object will be instantiated and called as such: # obj = SubrectangleQueries(rectangle) # obj.updateSubrectangle(row1,col1,row2,col2,newValue) # param_2 = obj.getValue(row,col)
class Subrectanglequeries: def __init__(self, rectangle: List[List[int]]): self.rectangle = rectangle def update_subrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: (self.row1, self.col1, self.row2, self.col2, self.newValue) = (row1, col1, row2, col2, newValue) for i in range(self.row1, self.row2 + 1): for j in range(self.col1, self.col2 + 1): self.rectangle[i][j] = self.newValue def get_value(self, row: int, col: int) -> int: self.row = row self.col = col return self.rectangle[self.row][self.col]
# 2nd Solution i = 4 d = 4.0 s = 'HackerRank ' a = int(input()) b = float(input()) c = input() print(i+a) print(d+b) print(s+c)
i = 4 d = 4.0 s = 'HackerRank ' a = int(input()) b = float(input()) c = input() print(i + a) print(d + b) print(s + c)
{ 'includes': [ 'common.gyp', 'amo.gypi', ], 'targets': [ { 'target_name': 'amo', 'product_name': 'amo', 'type': 'none', 'sources': [ '<@(source_code_amo)', ], 'dependencies': [ ] }, ] }
{'includes': ['common.gyp', 'amo.gypi'], 'targets': [{'target_name': 'amo', 'product_name': 'amo', 'type': 'none', 'sources': ['<@(source_code_amo)'], 'dependencies': []}]}
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MATH6005 Lecture 6. Functions Revision. # ============================================================================= # Example: Scope of a variable # # The code below attempts to double the value of the 'my_salary' variable # but FAILS. This is because within double_value() the argument 'to_double' # is called a 'local variable' with 'local scope'. Changes to 'to_double' # only happen within the function. You can think of to_double as a copy # of my_salary when it is passed in. # ============================================================================= """ def double_value(to_double): print('double_value() has been called') to_double = to_double * 2 print('Inside double_value() to_double now = {}'.format(to_double)) def main(): my_salary = 25000 print('value of my_salary BEFORE calling function {}'.format(my_salary)) #call the function and pass in keyword argument double_value(to_double=my_salary) print('value of my_salary AFTER calling function {}'.format(my_salary)) if __name__ == '__main__': main()
""" MATH6005 Lecture 6. Functions Revision. # ============================================================================= # Example: Scope of a variable # # The code below attempts to double the value of the 'my_salary' variable # but FAILS. This is because within double_value() the argument 'to_double' # is called a 'local variable' with 'local scope'. Changes to 'to_double' # only happen within the function. You can think of to_double as a copy # of my_salary when it is passed in. # ============================================================================= """ def double_value(to_double): print('double_value() has been called') to_double = to_double * 2 print('Inside double_value() to_double now = {}'.format(to_double)) def main(): my_salary = 25000 print('value of my_salary BEFORE calling function {}'.format(my_salary)) double_value(to_double=my_salary) print('value of my_salary AFTER calling function {}'.format(my_salary)) if __name__ == '__main__': main()
def imprime_quadro(numeros): print('.' * (len(numeros) + 2)) maior_numero = max(numeros) numeros_traduzidos = [] for numero in numeros: numeros_traduzidos.append(['|' if n < numero else ' ' for n in range(maior_numero)][::-1]) for linha in zip(*numeros_traduzidos): print('.' + ''.join(linha) + '.') print('.' * (len(numeros) + 2)) def bubble_sort(numeros): while numeros != sorted(numeros): for index in range(len(numeros) - 1): if numeros[index] > numeros[index + 1]: numeros[index], numeros[index + 1] = numeros[index + 1], numeros[index] imprime_quadro(numeros) def selection_sort(numeros): index = 0 while numeros != sorted(numeros): menor_numero = min(numeros[index:]) index_menor_numero = numeros[index:].index(menor_numero) + index if numeros[index] > menor_numero: numeros[index], numeros[index_menor_numero] = menor_numero, numeros[index] index += 1 imprime_quadro(numeros) def insertion_sort(numeros): index_main = 1 while numeros != sorted(numeros): index = index_main while index > 0 and numeros[index] < numeros[index - 1]: numeros[index], numeros[index - 1] = numeros[index - 1], numeros[index] index -= 1 index_main += 1 imprime_quadro(numeros) algoritmos = {'bubble':bubble_sort, 'selection':selection_sort, 'insertion':insertion_sort} algoritmo_escolhido = input() numeros = [int(n) for n in input().split()] imprime_quadro(numeros) algoritmos[algoritmo_escolhido](numeros)
def imprime_quadro(numeros): print('.' * (len(numeros) + 2)) maior_numero = max(numeros) numeros_traduzidos = [] for numero in numeros: numeros_traduzidos.append(['|' if n < numero else ' ' for n in range(maior_numero)][::-1]) for linha in zip(*numeros_traduzidos): print('.' + ''.join(linha) + '.') print('.' * (len(numeros) + 2)) def bubble_sort(numeros): while numeros != sorted(numeros): for index in range(len(numeros) - 1): if numeros[index] > numeros[index + 1]: (numeros[index], numeros[index + 1]) = (numeros[index + 1], numeros[index]) imprime_quadro(numeros) def selection_sort(numeros): index = 0 while numeros != sorted(numeros): menor_numero = min(numeros[index:]) index_menor_numero = numeros[index:].index(menor_numero) + index if numeros[index] > menor_numero: (numeros[index], numeros[index_menor_numero]) = (menor_numero, numeros[index]) index += 1 imprime_quadro(numeros) def insertion_sort(numeros): index_main = 1 while numeros != sorted(numeros): index = index_main while index > 0 and numeros[index] < numeros[index - 1]: (numeros[index], numeros[index - 1]) = (numeros[index - 1], numeros[index]) index -= 1 index_main += 1 imprime_quadro(numeros) algoritmos = {'bubble': bubble_sort, 'selection': selection_sort, 'insertion': insertion_sort} algoritmo_escolhido = input() numeros = [int(n) for n in input().split()] imprime_quadro(numeros) algoritmos[algoritmo_escolhido](numeros)
""" This function converts given hexadecimal number to decimal number """ def hexa_decimal_to_decimal(number: str) -> int: # check if the number is a hexa decimal number if not is_hexa_decimal(number): raise ValueError("Invalid Hexa Decimal Number") # convert hexa decimal number to decimal decimal = 0 for i in range(len(number)): decimal += int(number[i], 16) * (16 ** (len(number) - i - 1)) return decimal def is_hexa_decimal(number: str) -> bool: # check if the number is a hexa decimal number if len(number) == 0: return False for i in range(len(number)): if number[i] not in "0123456789ABCDEF": return False return True
""" This function converts given hexadecimal number to decimal number """ def hexa_decimal_to_decimal(number: str) -> int: if not is_hexa_decimal(number): raise value_error('Invalid Hexa Decimal Number') decimal = 0 for i in range(len(number)): decimal += int(number[i], 16) * 16 ** (len(number) - i - 1) return decimal def is_hexa_decimal(number: str) -> bool: if len(number) == 0: return False for i in range(len(number)): if number[i] not in '0123456789ABCDEF': return False return True
# a, b = 10, 10 print(a == b) print(a is b) print(id(a), id(b)) a1 = [1, 2, 3, 4] b1 = [1, 2, 3, 4] print(a1 == b1) print(a1 is b1) print(id(a1), id(b1))
(a, b) = (10, 10) print(a == b) print(a is b) print(id(a), id(b)) a1 = [1, 2, 3, 4] b1 = [1, 2, 3, 4] print(a1 == b1) print(a1 is b1) print(id(a1), id(b1))
total = 0 media = 0.0 for i in range(6): num = float(input()) if num > 0.0: total += 1 media += num print('{} valores positivos'.format(total)) print('{:.1f}'.format(media/total))
total = 0 media = 0.0 for i in range(6): num = float(input()) if num > 0.0: total += 1 media += num print('{} valores positivos'.format(total)) print('{:.1f}'.format(media / total))
"""This file contains a function that returns the int that apears an odd number of times in a list of integers, the best practice solution was: def find_it(seq): for i in seq: if seq.count(i)%2!=0: return i """ def find_it(seq): """This function returns the integer that is in the list an odd number of times""" for i in seq: y = seq.count(i) if y % 2 != 0: return i break #6kyu
"""This file contains a function that returns the int that apears an odd number of times in a list of integers, the best practice solution was: def find_it(seq): for i in seq: if seq.count(i)%2!=0: return i """ def find_it(seq): """This function returns the integer that is in the list an odd number of times""" for i in seq: y = seq.count(i) if y % 2 != 0: return i break
# http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/JIS/JIS0201.TXT JIS0201_map = { '20' : 0x0020, # SPACE '21' : 0x0021, # EXCLAMATION MARK '22' : 0x0022, # QUOTATION MARK '23' : 0x0023, # NUMBER SIGN '24' : 0x0024, # DOLLAR SIGN '25' : 0x0025, # PERCENT SIGN '26' : 0x0026, # AMPERSAND '27' : 0x0027, # APOSTROPHE '28' : 0x0028, # LEFT PARENTHESIS '29' : 0x0029, # RIGHT PARENTHESIS '2A' : 0x002A, # ASTERISK '2B' : 0x002B, # PLUS SIGN '2C' : 0x002C, # COMMA '2D' : 0x002D, # HYPHEN-MINUS '2E' : 0x002E, # FULL STOP '2F' : 0x002F, # SOLIDUS '30' : 0x0030, # DIGIT ZERO '31' : 0x0031, # DIGIT ONE '32' : 0x0032, # DIGIT TWO '33' : 0x0033, # DIGIT THREE '34' : 0x0034, # DIGIT FOUR '35' : 0x0035, # DIGIT FIVE '36' : 0x0036, # DIGIT SIX '37' : 0x0037, # DIGIT SEVEN '38' : 0x0038, # DIGIT EIGHT '39' : 0x0039, # DIGIT NINE '3A' : 0x003A, # COLON '3B' : 0x003B, # SEMICOLON '3C' : 0x003C, # LESS-THAN SIGN '3D' : 0x003D, # EQUALS SIGN '3E' : 0x003E, # GREATER-THAN SIGN '3F' : 0x003F, # QUESTION MARK '40' : 0x0040, # COMMERCIAL AT '41' : 0x0041, # LATIN CAPITAL LETTER A '42' : 0x0042, # LATIN CAPITAL LETTER B '43' : 0x0043, # LATIN CAPITAL LETTER C '44' : 0x0044, # LATIN CAPITAL LETTER D '45' : 0x0045, # LATIN CAPITAL LETTER E '46' : 0x0046, # LATIN CAPITAL LETTER F '47' : 0x0047, # LATIN CAPITAL LETTER G '48' : 0x0048, # LATIN CAPITAL LETTER H '49' : 0x0049, # LATIN CAPITAL LETTER I '4A' : 0x004A, # LATIN CAPITAL LETTER J '4B' : 0x004B, # LATIN CAPITAL LETTER K '4C' : 0x004C, # LATIN CAPITAL LETTER L '4D' : 0x004D, # LATIN CAPITAL LETTER M '4E' : 0x004E, # LATIN CAPITAL LETTER N '4F' : 0x004F, # LATIN CAPITAL LETTER O '50' : 0x0050, # LATIN CAPITAL LETTER P '51' : 0x0051, # LATIN CAPITAL LETTER Q '52' : 0x0052, # LATIN CAPITAL LETTER R '53' : 0x0053, # LATIN CAPITAL LETTER S '54' : 0x0054, # LATIN CAPITAL LETTER T '55' : 0x0055, # LATIN CAPITAL LETTER U '56' : 0x0056, # LATIN CAPITAL LETTER V '57' : 0x0057, # LATIN CAPITAL LETTER W '58' : 0x0058, # LATIN CAPITAL LETTER X '59' : 0x0059, # LATIN CAPITAL LETTER Y '5A' : 0x005A, # LATIN CAPITAL LETTER Z '5B' : 0x005B, # LEFT SQUARE BRACKET '5C' : 0x00A5, # YEN SIGN '5D' : 0x005D, # RIGHT SQUARE BRACKET '5E' : 0x005E, # CIRCUMFLEX ACCENT '5F' : 0x005F, # LOW LINE '60' : 0x0060, # GRAVE ACCENT '61' : 0x0061, # LATIN SMALL LETTER A '62' : 0x0062, # LATIN SMALL LETTER B '63' : 0x0063, # LATIN SMALL LETTER C '64' : 0x0064, # LATIN SMALL LETTER D '65' : 0x0065, # LATIN SMALL LETTER E '66' : 0x0066, # LATIN SMALL LETTER F '67' : 0x0067, # LATIN SMALL LETTER G '68' : 0x0068, # LATIN SMALL LETTER H '69' : 0x0069, # LATIN SMALL LETTER I '6A' : 0x006A, # LATIN SMALL LETTER J '6B' : 0x006B, # LATIN SMALL LETTER K '6C' : 0x006C, # LATIN SMALL LETTER L '6D' : 0x006D, # LATIN SMALL LETTER M '6E' : 0x006E, # LATIN SMALL LETTER N '6F' : 0x006F, # LATIN SMALL LETTER O '70' : 0x0070, # LATIN SMALL LETTER P '71' : 0x0071, # LATIN SMALL LETTER Q '72' : 0x0072, # LATIN SMALL LETTER R '73' : 0x0073, # LATIN SMALL LETTER S '74' : 0x0074, # LATIN SMALL LETTER T '75' : 0x0075, # LATIN SMALL LETTER U '76' : 0x0076, # LATIN SMALL LETTER V '77' : 0x0077, # LATIN SMALL LETTER W '78' : 0x0078, # LATIN SMALL LETTER X '79' : 0x0079, # LATIN SMALL LETTER Y '7A' : 0x007A, # LATIN SMALL LETTER Z '7B' : 0x007B, # LEFT CURLY BRACKET '7C' : 0x007C, # VERTICAL LINE '7D' : 0x007D, # RIGHT CURLY BRACKET '7E' : 0x203E, # OVERLINE 'A1' : 0xFF61, # HALFWIDTH IDEOGRAPHIC FULL STOP 'A2' : 0xFF62, # HALFWIDTH LEFT CORNER BRACKET 'A3' : 0xFF63, # HALFWIDTH RIGHT CORNER BRACKET 'A4' : 0xFF64, # HALFWIDTH IDEOGRAPHIC COMMA 'A5' : 0xFF65, # HALFWIDTH KATAKANA MIDDLE DOT 'A6' : 0xFF66, # HALFWIDTH KATAKANA LETTER WO 'A7' : 0xFF67, # HALFWIDTH KATAKANA LETTER SMALL A 'A8' : 0xFF68, # HALFWIDTH KATAKANA LETTER SMALL I 'A9' : 0xFF69, # HALFWIDTH KATAKANA LETTER SMALL U 'AA' : 0xFF6A, # HALFWIDTH KATAKANA LETTER SMALL E 'AB' : 0xFF6B, # HALFWIDTH KATAKANA LETTER SMALL O 'AC' : 0xFF6C, # HALFWIDTH KATAKANA LETTER SMALL YA 'AD' : 0xFF6D, # HALFWIDTH KATAKANA LETTER SMALL YU 'AE' : 0xFF6E, # HALFWIDTH KATAKANA LETTER SMALL YO 'AF' : 0xFF6F, # HALFWIDTH KATAKANA LETTER SMALL TU 'B0' : 0xFF70, # HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK 'B1' : 0xFF71, # HALFWIDTH KATAKANA LETTER A 'B2' : 0xFF72, # HALFWIDTH KATAKANA LETTER I 'B3' : 0xFF73, # HALFWIDTH KATAKANA LETTER U 'B4' : 0xFF74, # HALFWIDTH KATAKANA LETTER E 'B5' : 0xFF75, # HALFWIDTH KATAKANA LETTER O 'B6' : 0xFF76, # HALFWIDTH KATAKANA LETTER KA 'B7' : 0xFF77, # HALFWIDTH KATAKANA LETTER KI 'B8' : 0xFF78, # HALFWIDTH KATAKANA LETTER KU 'B9' : 0xFF79, # HALFWIDTH KATAKANA LETTER KE 'BA' : 0xFF7A, # HALFWIDTH KATAKANA LETTER KO 'BB' : 0xFF7B, # HALFWIDTH KATAKANA LETTER SA 'BC' : 0xFF7C, # HALFWIDTH KATAKANA LETTER SI 'BD' : 0xFF7D, # HALFWIDTH KATAKANA LETTER SU 'BE' : 0xFF7E, # HALFWIDTH KATAKANA LETTER SE 'BF' : 0xFF7F, # HALFWIDTH KATAKANA LETTER SO 'C0' : 0xFF80, # HALFWIDTH KATAKANA LETTER TA 'C1' : 0xFF81, # HALFWIDTH KATAKANA LETTER TI 'C2' : 0xFF82, # HALFWIDTH KATAKANA LETTER TU 'C3' : 0xFF83, # HALFWIDTH KATAKANA LETTER TE 'C4' : 0xFF84, # HALFWIDTH KATAKANA LETTER TO 'C5' : 0xFF85, # HALFWIDTH KATAKANA LETTER NA 'C6' : 0xFF86, # HALFWIDTH KATAKANA LETTER NI 'C7' : 0xFF87, # HALFWIDTH KATAKANA LETTER NU 'C8' : 0xFF88, # HALFWIDTH KATAKANA LETTER NE 'C9' : 0xFF89, # HALFWIDTH KATAKANA LETTER NO 'CA' : 0xFF8A, # HALFWIDTH KATAKANA LETTER HA 'CB' : 0xFF8B, # HALFWIDTH KATAKANA LETTER HI 'CC' : 0xFF8C, # HALFWIDTH KATAKANA LETTER HU 'CD' : 0xFF8D, # HALFWIDTH KATAKANA LETTER HE 'CE' : 0xFF8E, # HALFWIDTH KATAKANA LETTER HO 'CF' : 0xFF8F, # HALFWIDTH KATAKANA LETTER MA 'D0' : 0xFF90, # HALFWIDTH KATAKANA LETTER MI 'D1' : 0xFF91, # HALFWIDTH KATAKANA LETTER MU 'D2' : 0xFF92, # HALFWIDTH KATAKANA LETTER ME 'D3' : 0xFF93, # HALFWIDTH KATAKANA LETTER MO 'D4' : 0xFF94, # HALFWIDTH KATAKANA LETTER YA 'D5' : 0xFF95, # HALFWIDTH KATAKANA LETTER YU 'D6' : 0xFF96, # HALFWIDTH KATAKANA LETTER YO 'D7' : 0xFF97, # HALFWIDTH KATAKANA LETTER RA 'D8' : 0xFF98, # HALFWIDTH KATAKANA LETTER RI 'D9' : 0xFF99, # HALFWIDTH KATAKANA LETTER RU 'DA' : 0xFF9A, # HALFWIDTH KATAKANA LETTER RE 'DB' : 0xFF9B, # HALFWIDTH KATAKANA LETTER RO 'DC' : 0xFF9C, # HALFWIDTH KATAKANA LETTER WA 'DD' : 0xFF9D, # HALFWIDTH KATAKANA LETTER N 'DE' : 0xFF9E, # HALFWIDTH KATAKANA VOICED SOUND MARK 'DF' : 0xFF9F, # HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK }
jis0201_map = {'20': 32, '21': 33, '22': 34, '23': 35, '24': 36, '25': 37, '26': 38, '27': 39, '28': 40, '29': 41, '2A': 42, '2B': 43, '2C': 44, '2D': 45, '2E': 46, '2F': 47, '30': 48, '31': 49, '32': 50, '33': 51, '34': 52, '35': 53, '36': 54, '37': 55, '38': 56, '39': 57, '3A': 58, '3B': 59, '3C': 60, '3D': 61, '3E': 62, '3F': 63, '40': 64, '41': 65, '42': 66, '43': 67, '44': 68, '45': 69, '46': 70, '47': 71, '48': 72, '49': 73, '4A': 74, '4B': 75, '4C': 76, '4D': 77, '4E': 78, '4F': 79, '50': 80, '51': 81, '52': 82, '53': 83, '54': 84, '55': 85, '56': 86, '57': 87, '58': 88, '59': 89, '5A': 90, '5B': 91, '5C': 165, '5D': 93, '5E': 94, '5F': 95, '60': 96, '61': 97, '62': 98, '63': 99, '64': 100, '65': 101, '66': 102, '67': 103, '68': 104, '69': 105, '6A': 106, '6B': 107, '6C': 108, '6D': 109, '6E': 110, '6F': 111, '70': 112, '71': 113, '72': 114, '73': 115, '74': 116, '75': 117, '76': 118, '77': 119, '78': 120, '79': 121, '7A': 122, '7B': 123, '7C': 124, '7D': 125, '7E': 8254, 'A1': 65377, 'A2': 65378, 'A3': 65379, 'A4': 65380, 'A5': 65381, 'A6': 65382, 'A7': 65383, 'A8': 65384, 'A9': 65385, 'AA': 65386, 'AB': 65387, 'AC': 65388, 'AD': 65389, 'AE': 65390, 'AF': 65391, 'B0': 65392, 'B1': 65393, 'B2': 65394, 'B3': 65395, 'B4': 65396, 'B5': 65397, 'B6': 65398, 'B7': 65399, 'B8': 65400, 'B9': 65401, 'BA': 65402, 'BB': 65403, 'BC': 65404, 'BD': 65405, 'BE': 65406, 'BF': 65407, 'C0': 65408, 'C1': 65409, 'C2': 65410, 'C3': 65411, 'C4': 65412, 'C5': 65413, 'C6': 65414, 'C7': 65415, 'C8': 65416, 'C9': 65417, 'CA': 65418, 'CB': 65419, 'CC': 65420, 'CD': 65421, 'CE': 65422, 'CF': 65423, 'D0': 65424, 'D1': 65425, 'D2': 65426, 'D3': 65427, 'D4': 65428, 'D5': 65429, 'D6': 65430, 'D7': 65431, 'D8': 65432, 'D9': 65433, 'DA': 65434, 'DB': 65435, 'DC': 65436, 'DD': 65437, 'DE': 65438, 'DF': 65439}
#it is collection of data and methods. class gohul: a=100 b=200 def func(self): print("Inside function") print(gohul.func(1)) object=gohul() print(object.a) print(object.b) print(object.func()) object1=gohul() print(object1.a)
class Gohul: a = 100 b = 200 def func(self): print('Inside function') print(gohul.func(1)) object = gohul() print(object.a) print(object.b) print(object.func()) object1 = gohul() print(object1.a)
# Array # An array is monotonic if it is either monotone increasing or monotone decreasing. # # An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. # # Return true if and only if the given array A is monotonic. # # # # Example 1: # # Input: [1,2,2,3] # Output: true # Example 2: # # Input: [6,5,4,4] # Output: true # Example 3: # # Input: [1,3,2] # Output: false # Example 4: # # Input: [1,2,4,5] # Output: true # Example 5: # # Input: [1,1,1] # Output: true # # # Note: # # 1 <= A.length <= 50000 # -100000 <= A[i] <= 100000 class Solution: def isMonotonic(self, A): """ :type A: List[int] :rtype: bool """ if A[0] < A[-1]: isIncrease = True else: isIncrease = False if isIncrease: for i in range(1,len(A)): if A[i] < A[i-1]: return False else: for i in range(1,len(A)): if A[i] > A[i-1]: return False return True
class Solution: def is_monotonic(self, A): """ :type A: List[int] :rtype: bool """ if A[0] < A[-1]: is_increase = True else: is_increase = False if isIncrease: for i in range(1, len(A)): if A[i] < A[i - 1]: return False else: for i in range(1, len(A)): if A[i] > A[i - 1]: return False return True
class Solution: """ @param matrix: an integer matrix @return: the length of the longest increasing path """ def longestIncreasingPath(self, matrix): if not matrix or len(matrix) == 0 or len(matrix[0]) == 0: return 0 n = len(matrix) m = len(matrix[0]) longest = 0 memory = {} for i in range(n): for j in range(m): longest = max(longest, self.dfs(matrix, n, m, i, j, True, memory)) longest = max(longest, self.dfs(matrix, n, m, i, j, False, memory)) return longest def dfs(self, matrix, n, m, i, j, ascending, memory): memKey = str(i) + "_" + str(j) + "_" + str(ascending) if memKey in memory: return memory[memKey] longest = 0 for adj in [[1, 0], [0, 1], [-1, 0], [0, -1]]: x = i + adj[0] y = j + adj[1] if x < 0 or x >= n or y < 0 or y >= m: continue if ascending and matrix[x][y] <= matrix[i][j]: continue if not ascending and matrix[x][y] >= matrix[i][j]: continue longest = max(longest, self.dfs(matrix, n, m, x, y, ascending, memory)) memory[memKey] = longest + 1 return memory[memKey]
class Solution: """ @param matrix: an integer matrix @return: the length of the longest increasing path """ def longest_increasing_path(self, matrix): if not matrix or len(matrix) == 0 or len(matrix[0]) == 0: return 0 n = len(matrix) m = len(matrix[0]) longest = 0 memory = {} for i in range(n): for j in range(m): longest = max(longest, self.dfs(matrix, n, m, i, j, True, memory)) longest = max(longest, self.dfs(matrix, n, m, i, j, False, memory)) return longest def dfs(self, matrix, n, m, i, j, ascending, memory): mem_key = str(i) + '_' + str(j) + '_' + str(ascending) if memKey in memory: return memory[memKey] longest = 0 for adj in [[1, 0], [0, 1], [-1, 0], [0, -1]]: x = i + adj[0] y = j + adj[1] if x < 0 or x >= n or y < 0 or (y >= m): continue if ascending and matrix[x][y] <= matrix[i][j]: continue if not ascending and matrix[x][y] >= matrix[i][j]: continue longest = max(longest, self.dfs(matrix, n, m, x, y, ascending, memory)) memory[memKey] = longest + 1 return memory[memKey]
# -*- coding: utf-8 -*- """Top-level package for NeuroVault Collection Downloader.""" __author__ = """Chris Gorgolewski""" __email__ = 'krzysztof.gorgolewski@gmail.com' __version__ = '0.1.0'
"""Top-level package for NeuroVault Collection Downloader.""" __author__ = 'Chris Gorgolewski' __email__ = 'krzysztof.gorgolewski@gmail.com' __version__ = '0.1.0'
class LandingPage: @staticmethod def get(): return 'Beautiful UI'
class Landingpage: @staticmethod def get(): return 'Beautiful UI'
class Peptide: def __init__(self, sequence, proteinID, modification, mass, isNterm): self.sequence = sequence self.length = len(self.sequence) self.proteinID = [proteinID] self.modification = modification self.massArray = self.getMassArray(mass) self.totalResidueMass = self.getTotalResidueMass() self.pm = self.getPrecursorMass(mass) self.isNterm = isNterm def getMassArray(self, mass): massArray = [] sequence = self.sequence position = self.modification['position'] deltaMass = self.modification['deltaMass'] for i in range(self.length): massArray.append(mass[sequence[i].upper()]) for i in range(len(position)): massArray[position[i]] += deltaMass[i] return massArray def getTotalResidueMass(self): totalResidueMass = sum(self.massArray) return totalResidueMass def getPrecursorMass(self, mass): pm = self.totalResidueMass pm = pm + mass['Hatom'] * 2 + mass['Oatom'] return pm def getMassList(self, mass, param): massList = [] fwdMass = 0 massArray = self.massArray totalResidueMass = self.totalResidueMass useAIon = param['useAIon'] for i in range(self.length - 1): fragment = dict() fwdMass += massArray[i] revMass = totalResidueMass - fwdMass fragment['b'] = fwdMass + mass['BIonRes'] fragment['y'] = revMass + mass['YIonRes'] if useAIon: fragment['a'] = fwdMass + mass['AIonRes'] massList.append(fragment) return massList
class Peptide: def __init__(self, sequence, proteinID, modification, mass, isNterm): self.sequence = sequence self.length = len(self.sequence) self.proteinID = [proteinID] self.modification = modification self.massArray = self.getMassArray(mass) self.totalResidueMass = self.getTotalResidueMass() self.pm = self.getPrecursorMass(mass) self.isNterm = isNterm def get_mass_array(self, mass): mass_array = [] sequence = self.sequence position = self.modification['position'] delta_mass = self.modification['deltaMass'] for i in range(self.length): massArray.append(mass[sequence[i].upper()]) for i in range(len(position)): massArray[position[i]] += deltaMass[i] return massArray def get_total_residue_mass(self): total_residue_mass = sum(self.massArray) return totalResidueMass def get_precursor_mass(self, mass): pm = self.totalResidueMass pm = pm + mass['Hatom'] * 2 + mass['Oatom'] return pm def get_mass_list(self, mass, param): mass_list = [] fwd_mass = 0 mass_array = self.massArray total_residue_mass = self.totalResidueMass use_a_ion = param['useAIon'] for i in range(self.length - 1): fragment = dict() fwd_mass += massArray[i] rev_mass = totalResidueMass - fwdMass fragment['b'] = fwdMass + mass['BIonRes'] fragment['y'] = revMass + mass['YIonRes'] if useAIon: fragment['a'] = fwdMass + mass['AIonRes'] massList.append(fragment) return massList
def fatorial(n): if n==1: return n return fatorial(n-1) * n print(fatorial(5)) """n = 5 --> ret = 1*2*3*4*5 n = 4 --> fatorial(4) = 1*2*3*4 n = 3 --> fatorial(3) = 1*2*3 n = 2 --> fatorial(2) = 1*2 n = 1 --> fatorial(1) = 1""" print(fatorial(4))
def fatorial(n): if n == 1: return n return fatorial(n - 1) * n print(fatorial(5)) 'n = 5 --> ret = 1*2*3*4*5\nn = 4 --> fatorial(4) = 1*2*3*4\nn = 3 --> fatorial(3) = 1*2*3\nn = 2 --> fatorial(2) = 1*2\nn = 1 --> fatorial(1) = 1' print(fatorial(4))
#CMPUT 410 Lab1 by Chongyang Ye #This program allows add courses and #corresponding marks for a student #and count the average score class Student: courseMarks={} name= "" def __init__(self,name,family): self.name = name self.family = family def addCourseMark(self, course, mark): self.courseMarks[course] = mark def average(self): grade= [] grade= self.courseMarks.values() averageGrade= sum(grade)/float(len(grade)) print("The course average for %s is %.2f" %(self.name, averageGrade)) if __name__ == "__main__": student = Student("Jeff", "Hub") student.addCourseMark("CMPUT410", 90) student.addCourseMark("CMPUT379", 95) student.addCourseMark("CMPUT466", 80) student.average()
class Student: course_marks = {} name = '' def __init__(self, name, family): self.name = name self.family = family def add_course_mark(self, course, mark): self.courseMarks[course] = mark def average(self): grade = [] grade = self.courseMarks.values() average_grade = sum(grade) / float(len(grade)) print('The course average for %s is %.2f' % (self.name, averageGrade)) if __name__ == '__main__': student = student('Jeff', 'Hub') student.addCourseMark('CMPUT410', 90) student.addCourseMark('CMPUT379', 95) student.addCourseMark('CMPUT466', 80) student.average()
{ "targets": [{ "target_name": "defaults", "sources": [ ], "conditions": [ ['OS=="mac"', { "sources": [ "src/defaults.mm", "src/json_formatter.h", "src/json_formatter.cc" ], }] ], 'include_dirs': [ "<!@(node -p \"require('node-addon-api').include\")" ], 'libraries': [], 'dependencies': [ "<!(node -p \"require('node-addon-api').gyp\")" ], 'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ], "xcode_settings": { "OTHER_CPLUSPLUSFLAGS": ["-std=c++17", "-stdlib=libc++", "-Wextra"], "OTHER_LDFLAGS": ["-framework CoreFoundation -framework Cocoa -framework Carbon"], "MACOSX_DEPLOYMENT_TARGET": "10.12" } }] }
{'targets': [{'target_name': 'defaults', 'sources': [], 'conditions': [['OS=="mac"', {'sources': ['src/defaults.mm', 'src/json_formatter.h', 'src/json_formatter.cc']}]], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'libraries': [], 'dependencies': ['<!(node -p "require(\'node-addon-api\').gyp")'], 'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS'], 'xcode_settings': {'OTHER_CPLUSPLUSFLAGS': ['-std=c++17', '-stdlib=libc++', '-Wextra'], 'OTHER_LDFLAGS': ['-framework CoreFoundation -framework Cocoa -framework Carbon'], 'MACOSX_DEPLOYMENT_TARGET': '10.12'}}]}
#!/usr/bin/env python # -*- encoding: utf-8; py-indent-offset: 4 -*- register_rule("agents/" + _("Agent Plugins"), "agent_config:nvidia_gpu", DropdownChoice( title = _("Nvidia GPU (Linux)"), help = _("This will deploy the agent plugin <tt>nvidia_gpu</tt> to collect GPU utilization values."), choices = [ ( True, _("Deploy plugin for GPU Monitoring") ), ( None, _("Do not deploy plugin for GPU Monitoring") ), ] ) )
register_rule('agents/' + _('Agent Plugins'), 'agent_config:nvidia_gpu', dropdown_choice(title=_('Nvidia GPU (Linux)'), help=_('This will deploy the agent plugin <tt>nvidia_gpu</tt> to collect GPU utilization values.'), choices=[(True, _('Deploy plugin for GPU Monitoring')), (None, _('Do not deploy plugin for GPU Monitoring'))]))
# -*- coding: utf-8 -*- """ Taken from Data Structures and Algorithms using Python """ def matrix_chain(d): n = len(d) - 1 N =[[0]*n for i in range(n)] for b in range(1,n): for i in range(n-b): j = i+b N[i][j] = min(N[i][j]+N[k+1][j]+d[i]*d[k+1]*d[j+1] for k in range(i,j)) return N
""" Taken from Data Structures and Algorithms using Python """ def matrix_chain(d): n = len(d) - 1 n = [[0] * n for i in range(n)] for b in range(1, n): for i in range(n - b): j = i + b N[i][j] = min((N[i][j] + N[k + 1][j] + d[i] * d[k + 1] * d[j + 1] for k in range(i, j))) return N
#!/usr/bin/env python types = [ ("bool", "Bool", "strconv.FormatBool(bool(*%s))", "*%s == false"), ("uint8", "Uint8", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"), ("uint16", "Uint16", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"), ("uint32", "Uint32", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"), ("uint64", "Uint64", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"), ("int8", "Int8", "strconv.FormatInt(int64(*%s), 10)", "*%s == 0"), ("int16", "Int16", "strconv.FormatInt(int64(*%s), 10)", "*%s == 0"), ("int32", "Int32", "strconv.FormatInt(int64(*%s), 10)", "*%s == 0"), ("int64", "Int64", "strconv.FormatInt(int64(*%s), 10)", "*%s == 0"), ("float32", "Float32", "strconv.FormatFloat(float64(*%s), 'g', -1, 32)", "*%s == 0.0"), ("float64", "Float64", "strconv.FormatFloat(float64(*%s), 'g', -1, 64)", "*%s == 0.0"), ("string", "String", "string(*%s)", "*%s == \"\""), ("int", "Int", "strconv.Itoa(int(*%s))", "*%s == 0"), ("uint", "Uint", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"), ("time.Duration", "Duration", "(*time.Duration)(%s).String()", "*%s == 0"), # TODO: Func ] imports = [ "time" ] imports_stringer = [ "strconv" ]
types = [('bool', 'Bool', 'strconv.FormatBool(bool(*%s))', '*%s == false'), ('uint8', 'Uint8', 'strconv.FormatUint(uint64(*%s), 10)', '*%s == 0'), ('uint16', 'Uint16', 'strconv.FormatUint(uint64(*%s), 10)', '*%s == 0'), ('uint32', 'Uint32', 'strconv.FormatUint(uint64(*%s), 10)', '*%s == 0'), ('uint64', 'Uint64', 'strconv.FormatUint(uint64(*%s), 10)', '*%s == 0'), ('int8', 'Int8', 'strconv.FormatInt(int64(*%s), 10)', '*%s == 0'), ('int16', 'Int16', 'strconv.FormatInt(int64(*%s), 10)', '*%s == 0'), ('int32', 'Int32', 'strconv.FormatInt(int64(*%s), 10)', '*%s == 0'), ('int64', 'Int64', 'strconv.FormatInt(int64(*%s), 10)', '*%s == 0'), ('float32', 'Float32', "strconv.FormatFloat(float64(*%s), 'g', -1, 32)", '*%s == 0.0'), ('float64', 'Float64', "strconv.FormatFloat(float64(*%s), 'g', -1, 64)", '*%s == 0.0'), ('string', 'String', 'string(*%s)', '*%s == ""'), ('int', 'Int', 'strconv.Itoa(int(*%s))', '*%s == 0'), ('uint', 'Uint', 'strconv.FormatUint(uint64(*%s), 10)', '*%s == 0'), ('time.Duration', 'Duration', '(*time.Duration)(%s).String()', '*%s == 0')] imports = ['time'] imports_stringer = ['strconv']
"""# `//ll:driver.bzl` Convenience function to select the C or C++ driver for compilation. """ def compiler_driver(ctx, toolchain_type): driver = ctx.toolchains[toolchain_type].c_driver for src in ctx.files.srcs: if src.extension in ["cpp", "hpp", "ipp", "cl", "cc"]: driver = ctx.toolchains[toolchain_type].cpp_driver break return driver
"""# `//ll:driver.bzl` Convenience function to select the C or C++ driver for compilation. """ def compiler_driver(ctx, toolchain_type): driver = ctx.toolchains[toolchain_type].c_driver for src in ctx.files.srcs: if src.extension in ['cpp', 'hpp', 'ipp', 'cl', 'cc']: driver = ctx.toolchains[toolchain_type].cpp_driver break return driver
#!/usr/bin/env python counts = dict() mails = list() fname = input("Enter file name:") fh = open(fname) for line in fh: if not line.startswith("From "): continue # if line.startswith('From:'): # continue id = line.split() mail = id[1] mails.append(mail) freq_mail = max(mails, key=mails.count) # To find frequent mail print(freq_mail, mails.count(freq_mail)) # To find countof frequent mail """ for x in mails: counts[x]=counts.get(x,0)+1 bigmail=None bigvalue=None for key,value in counts.items(): if bigvalue==None or bigvalue<value: bigmail=key bigvalue=value print(bigmail, bigvalue) """
counts = dict() mails = list() fname = input('Enter file name:') fh = open(fname) for line in fh: if not line.startswith('From '): continue id = line.split() mail = id[1] mails.append(mail) freq_mail = max(mails, key=mails.count) print(freq_mail, mails.count(freq_mail)) '\nfor x in mails:\n counts[x]=counts.get(x,0)+1\nbigmail=None\nbigvalue=None\nfor key,value in counts.items():\n if bigvalue==None or bigvalue<value:\n bigmail=key\n bigvalue=value\nprint(bigmail, bigvalue)\n\n'
class OriginEPG(): def __init__(self, fhdhr): self.fhdhr = fhdhr def update_epg(self, fhdhr_channels): programguide = {} for fhdhr_id in list(fhdhr_channels.list.keys()): chan_obj = fhdhr_channels.list[fhdhr_id] if str(chan_obj.number) not in list(programguide.keys()): programguide[str(chan_obj.number)] = chan_obj.epgdict return programguide
class Originepg: def __init__(self, fhdhr): self.fhdhr = fhdhr def update_epg(self, fhdhr_channels): programguide = {} for fhdhr_id in list(fhdhr_channels.list.keys()): chan_obj = fhdhr_channels.list[fhdhr_id] if str(chan_obj.number) not in list(programguide.keys()): programguide[str(chan_obj.number)] = chan_obj.epgdict return programguide
class TrieNode: def __init__(self): self.children = {} self.endOfString = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): currNode = self.root for char in word: if char not in currNode.children: currNode.children[char] = TrieNode() currNode = currNode.children[char] currNode.endOfString = True def search(self, word): currNode = self.root replace = "" for char in word: if char not in currNode.children: return word replace += char currNode = currNode.children[char] if currNode.endOfString == True: return replace return word class Solution: def replaceWords(self, dictionary: list[str], sentence: str) -> str: trie = Trie() wordsList = sentence.split() for rootWord in dictionary: trie.insert(rootWord) processed_wordList = [] for word in wordsList: processed_wordList.append(trie.search(word)) return " ".join(processed_wordList)
class Trienode: def __init__(self): self.children = {} self.endOfString = False class Trie: def __init__(self): self.root = trie_node() def insert(self, word): curr_node = self.root for char in word: if char not in currNode.children: currNode.children[char] = trie_node() curr_node = currNode.children[char] currNode.endOfString = True def search(self, word): curr_node = self.root replace = '' for char in word: if char not in currNode.children: return word replace += char curr_node = currNode.children[char] if currNode.endOfString == True: return replace return word class Solution: def replace_words(self, dictionary: list[str], sentence: str) -> str: trie = trie() words_list = sentence.split() for root_word in dictionary: trie.insert(rootWord) processed_word_list = [] for word in wordsList: processed_wordList.append(trie.search(word)) return ' '.join(processed_wordList)
def get_capabilities(): return [ "bogus_capability" ] def should_ignore_response(): return True
def get_capabilities(): return ['bogus_capability'] def should_ignore_response(): return True
class ExportModuleToFile(object): def __init__(self, **kargs): self.moduleId = kargs["moduleId"] if "moduleId" in kargs else None self.exportType = kargs["exportType"] if "exportType" in kargs else None
class Exportmoduletofile(object): def __init__(self, **kargs): self.moduleId = kargs['moduleId'] if 'moduleId' in kargs else None self.exportType = kargs['exportType'] if 'exportType' in kargs else None