content
stringlengths
7
1.05M
def test_root_redirect(client): r_root = client.get("/") assert r_root.status_code == 302 assert r_root.headers["Location"].endswith("/overview/")
# Conversão de escalas Celsius, Kelvin e Fahrenheit celsius = float(input('Digite Quantos Graus Celsius: ')) kelvin = float(celsius + 273) fahrenheit = float(1.8 * celsius + 32) print('{}ºC é igual a {}ºK ou {:.2f}ºF'.format(celsius, kelvin, fahrenheit))
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ size = len(prices) bought = False profit = 0 price = 0 for i in range(0, size - 1): if not bought: if prices[i] < prices[i + 1]: bought = True price = prices[i] else: if prices[i] > prices[i + 1]: bought = False profit += prices[i] - price price = 0 if bought: profit += prices[i + 1] - price return profit
'''8. Write a Python program to split a given list into two parts where the length of the first part of the list is given. Original list: [1, 1, 2, 3, 4, 4, 5, 1] Length of the first part of the list: 3 Splited the said list into two parts: ([1, 1, 2], [3, 4, 4, 5, 1]) ''' def split_two_parts(n_list, L): return n_list[:L], n_list[L:] n_list = [1,1,2,3,4,4,5, 1] print("Original list:") print(n_list) first_list_length = 3 print("\nLength of the first part of the list:",first_list_length) print("\nSplited the said list into two parts:") print(split_two_parts(n_list, first_list_length))
n = int(input()) for i in range(n): row, base, number = map(int, input().split()) remains = list() while number > 0: remain = number % base number = number // base remains.append(remain) sumOfRemains = 0 for i in range(len(remains)): remains[i] = remains[i] ** 2 sumOfRemains += remains[i] print(f'{row} {sumOfRemains}')
with open("110000.dat","r") as fi: with open("110000num.dat","w") as fo: i=1 for l in fi.readlines(): if i%100 == 0: fo.write(l.strip()+" #"+str(i)+"\n") else: fo.write(l) i = i+1
class Person(object): # This definition hasn't changed from part 1! def __init__(self, fn, ln, em, age, occ): self.firstName = fn self.lastName = ln self.email = em self.age = age self.occupation = occ class Occupation(object): def __init__(self, name, location): self.name = name self.location = location if __name__ == "__main__": stringOcc = "Lawyer" person1 = Person( "Michael", "Smith", "[email protected]", 27, stringOcc) classOcc = Occupation("Software Engineer", "San Francisco") # Still works! person2 = Person( "Katie", "Johnson", "[email protected]", 26, classOcc) people = [person1, person2] for p in people: # This works. Both types of occupations are printable. print(p.occupation) # This won't work. Our "Occupation" class # doesn't work with "len" # print(len(p.occupation))
#!/usr/bin/python3 class Face(object): def __init__(self, bbox, aligned_face_img, confidence, key_points): self._bbox = bbox # [x_min, y_min, x_max, y_max] self._aligned_face_img = aligned_face_img self._confidence = confidence self._key_points = key_points @property def bbox(self): return self._bbox @property def confidence(self): return self._confidence @property def key_points(self): return self._key_points @property def aligned_face_img(self): return self._aligned_face_img
start_house, end_house = map(int, input().split()) left_tree, right_tree = map(int, input().split()) number_of_apples, number_of_oranges = map(int, input().split()) apple_distances = map(int, input().split()) orange_distances = map(int, input().split()) apple_count = 0 orange_count = 0 for distance in apple_distances: if start_house <= left_tree + distance <= end_house: apple_count += 1 for distance in orange_distances: if start_house <= right_tree + distance <= end_house: orange_count += 1 print(apple_count) print(orange_count)
def countInversions(nums): #Our recursive base case, if our list is of size 1 we know there's no inversion and that it's already sorted if len(nums) == 1: return nums, 0 #We run our function recursively on it's left and right halves left, leftInversions = countInversions(nums[:len(nums) // 2]) right, rightInversions = countInversions(nums[len(nums) // 2:]) #Initialize our inversions variable to be the number of inversions in each half inversions = leftInversions + rightInversions #Initialize a list to hold our sorted result list sortedNums = [] i = j = 0 #Here we count the inversions that exist between the two halves -- while sorting them at the same time while i < len(left) and j < len(right): if left[i] < right[j]: sortedNums += [left[i]]; i += 1 else: sortedNums += [right[j]]; j += 1 #Since we know that 'left' is sorted, once we reach an item in 'left' thats bigger than something in right that item and everything to it's right-hand side must be an inversion! #This line right here is exactly what shrinks the time of this algorithm from n^2 to nlogn as it means we don't need to compare every single pair inversions += len(left) - i #Once we've exhausted either left or right, we can just add the other one onto our sortedNums list sortedNums += left[i:] + right[j:] return sortedNums, inversions def main(): nums = [1, 5, 4, 8, 10, 2, 6, 9] print(countInversions(nums)) main()
# find highest grade of an assignment def highest_SRQs_grade(queryset): queryset = queryset.order_by('-assignment', 'SRQs_grade') dict_q = {} for each in queryset: dict_q[each.assignment] = each result = [] for assignment in dict_q.values(): result.append(assignment) return result
def f(x): if x: return if x: return elif y: return if x: return else: return if x: return elif y: return else: return if x: return elif y: return elif z: return else: return return None
# Iterative approach using stack # 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 class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: if root1 == None: return root2 stack = [] stack.append([root1, root2]) while stack: node = stack.pop() # possible when tree2 node was None if node[0]==None or node[1]==None: continue node[0].val += node[1].val # merging tree2's left subtree with tree1's left subtree if node[0].left == None: node[0].left = node[1].left else: stack.append([node[0].left, node[1].left]) # merging tree2's right subtree with tree1's right subtree if node[0].right == None: node[0].right = node[1].right else: stack.append([node[0].right, node[1].right]) return root1
class point: "K-D POINT CLASS" def __init__(self,coordinate, name=None, dim=None): """ name, dimension and coordinates """ self.name = name if type(dim) == type(None): self.dim = len(coordinate) else: self.dim = dim if len(coordinate) == self.dim: self.coordinate = coordinate else: raise Exception("INVALID DIMENSIONAL INFORMATION WHILE CREATING A POINT") def getx(self): if self.dim >= 1: return self.coordinate[0] else: return None def gety(self): if self.dim >= 2: return self.coordinate[1] else: return None def getz(self): if self.dim >= 3: return self.coordinate[2] else: return None def get(self,k): if self.dim >= k: return self.coordinate[k] else: return None def print(self): print("Name:",self.name,"Dim:",self.dim,"Coordinates:",self.coordinate) return def __eq__(self, other): if (type(self) != type(None) and type(other) == type(None)) or (type(self) == type(None) and type(other) != type(None)): return False if self.dim == other.dim and self.coordinate == other.coordinate: return True return False def __ne__(self, other): if (type(self) != type(None) and type(other) == type(None)) or (type(self) == type(None) and type(other) != type(None)): return False if self.dim != other.dim or self.coordinate != other.coordinate: return True return False def __lt__(self, other): '''overload lesser than operator mainly for heapq''' t = self.coordinate < other.coordinate return t def __gt__(self, other): '''overload greater than operator mainly for heapq''' t = self.coordinate > other.coordinate return t def copy(self): k = point(self.coordinate, self.name, self.dim) return k def distance(self, other): if self.dim != other.dim: return None dist = 0 for i in range(self.dim): dist += (self.coordinate[i] - other.coordinate[i])**2 dist = dist**0.5 return dist def in_range(self, bounds): """return true if a point lies within given bounds""" if len(bounds) != self.dim: raise Exception("DIMENSIONAL INCONSISTENCY WHILE CALLING IN_RANGE") for i in range(self.dim): if(not(bounds[i][0] <= self.coordinate[i] <= bounds[i][1])): return False return True
# Ex: 076 - Crie um programa que tenha uma tupla única com nomes de produtos e # seus respectivos preços, na sequência. No final, mostre uma listagem de preços, # organizando os dados em forma tabular. print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 076 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ''') produtos = ("Lápis", 1.75, "Borracha", 2.00, "Caderno", 15.90, "Estojo", 25.00, "Transferidor", 4.20, "Compasso", 9.99, "Mochila", 120.32, "Canetas", 22.30, "Livro", 34.90) print('-' * 40) for p in produtos: if p * 0 != 0: print(f'{p:.<30}', end='') else: print(f'R$ {p:>6.2f}') print('-' * 40) '''for i in listagem: if type(i) is str: print(f'{i:.<32}', end='') else: print(f'R$ {i:>5.2f}') print('--'*20)''' print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Obrigado pelo uso! --Desenvolvido por Thalles Torres -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
# 26.05.2019 # Working with BitwiseOperators and different kind of String Outputs. print(f"Working with Bitwise Operators and different kind of String Outputs.") var1 = 13 # 13 in Binary: 1101 var2 = 5 # 5 in Binary: 0101 # AND Operator with format String # 1101 13 # 0101 5 # ---- AND: 1,0 = 0; 1,1 = 1; 0,0 = 0 # 0101 -> 5 print("AND & Operator {}".format(var1 & var2)) # OR Operator with f-String # 1101 13 # 0101 5 # ---- OR: 1,0 = 1; 1,1 = 1; 0,0 = 0 # 1101 -> 13 print(f"OR | operator {var1 | var2}") # XOR Operator with String-formatting # 1101 13 # 0101 5 # ---- XOR: 1,0 = 1; 1,1 = 0; 0,0 = 0 # 1000 -> 8 print("XOR ^ operator %d" %(var1 ^ var2)) # Left Shift Operator with String .format # 1101 13 # ---- Left Shift: var << 1 # 11010 -> 26 print("Left Shift << operator {}".format(var1 << 1)) # Right Shift Operator with f-String # 1101 13 # ---- Right Shift: var >> 1 # 0110 -> 6 print(f"Right Shift >> operator {var1 >> 1}")
""" Given a non negative integer number num. For every numbers i in the range 0 <= i <= num calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5 you should return [0,1,1,2,1,2]. Follow up: It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) / possibly in a single pass? Space complexity should be O(n). Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. """ __author__ = 'Daniel' class Solution(object): def countBits(self, num): """ Dynamic programming: make use of what you have produced already 0 => 0 1 => 1 10 => 1+0 11 => 1+1 100 => 1+0 101 => 1+1 110 => 1+1 111 => 1+2 :type num: int :rtype: List[int] """ ret = [0] i = 0 hi = len(ret) while len(ret) < num + 1: if i == hi: i = 0 hi = len(ret) ret.append(1+ret[i]) i += 1 return ret
""" Conf file for product catagory and payment gateway """ #Products product_sunscreens_category = ['SPF-50','SPF-30'] product_moisturizers_category = ['Aloe','Almond']
class Solution: def numTilings(self, n: int) -> int: MOD = 1000000007 if n <= 2: return n previous = 1 result = 2 current = 1 for k in range(3, n + 1): tmp = result result = (result + previous + 2 * current) % MOD current = (current + previous) % MOD previous = tmp return result s = Solution() print(s.numTilings(3)) print(s.numTilings(1))
# 4. Caesar Cipher # Write a program that returns an encrypted version of the same text. # Encrypt the text by shifting each character with three positions forward. # For example A would be replaced by D, B would become E, and so on. Print the encrypted text. text = input() encrypted_text = [chr(ord(character) + 3) for character in text] print("".join(encrypted_text))
ies = [] ies.append({ "ie_type" : "Node ID", "ie_value" : "Node ID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier of the sending Node."}) ies.append({ "ie_type" : "F-SEID", "ie_value" : "CP F-SEID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier allocated by the CP function identifying the session."}) ies.append({ "ie_type" : "Create PDR", "ie_value" : "Create PDR", "presence" : "O", "instance" : "0", "comment" : "This IE shall be present for at least one PDR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple PDRs.See Table 7.5.2.2-1."}) ies.append({ "ie_type" : "Create PDR", "ie_value" : "Create PDR", "presence" : "M", "instance" : "1", "comment" : "This IE shall be present for at least one PDR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple PDRs.See Table 7.5.2.2-1."}) ies.append({ "ie_type" : "Create FAR", "ie_value" : "Create FAR", "presence" : "O", "instance" : "0", "comment" : "This IE shall be present for at least one FAR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple FARs.See Table 7.5.2.3-1."}) ies.append({ "ie_type" : "Create FAR", "ie_value" : "Create FAR", "presence" : "M", "instance" : "1", "comment" : "This IE shall be present for at least one FAR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple FARs.See Table 7.5.2.3-1."}) ies.append({ "ie_type" : "Create URR", "ie_value" : "Create URR", "presence" : "C", "instance" : "0", "comment" : "This IE shall be present if a measurement action shall be applied to packets matching one or more PDR(s) of this PFCP session. Several IEs within the same IE type may be present to represent multiple URRs.See Table 7.5.2.4-1."}) ies.append({ "ie_type" : "Create QER", "ie_value" : "Create QER", "presence" : "C", "instance" : "0", "comment" : "This IE shall be present if a QoS enforcement action shall be applied to packets matching one or more PDR(s) of this PFCP session.Several IEs within the same IE type may be present to represent multiple QERs.See Table 7.5.2.5-1."}) ies.append({ "ie_type" : "Create BAR", "ie_value" : "Create BAR", "presence" : "O", "instance" : "0", "comment" : "When present, this IE shall contain the buffering instructions to be applied by the UP function to any FAR of this PFCP session set with the Apply Action requesting the packets to be buffered and with a BAR ID IE referring to this BAR. See table 7.5.2.6-1."}) ies.append({ "ie_type" : "PDN Typep", "ie_value" : "PDN Type", "presence" : "C", "instance" : "0", "comment" : "This IE shall be present if the PFCP session is setup for an individual PDN connection or PDU session (see subclause 5.2.1). When present, this IE shall indicate whether this is an IP or non-IP PDN connection/PDU session. "}) ies.append({ "ie_type" : "FQ-CSIDp", "ie_value" : "SGW-C FQ-CSID", "presence" : "C", "instance" : "0", "comment" : "This IE shall be included according to the requirements in clause23 of 3GPPTS 23.007[24]."}) ies.append({ "ie_type" : "User Plane Inactivity Timer", "ie_value" : "User Plane Inactivity Timer", "presence" : "O", "instance" : "0", "comment" : "This IE may be present to request the UP function to send a User Plane Inactivity Report when no user plane packets are received for this PFCP session for a duration exceeding the User Plane Inactivity Timer. When present, it shall contain the duration of the inactivity period after which a User Plane Inactivity Report shall be generated."}) msg_list[key]["ies"] = ies
code = """ 400 0078 Clear Display 402 21C0 V1 = 0C0h (Pattern #) 404 2200 V2 = 10h (Cell#) 406 2301 V3 = 01 (Centre) 408 B600 B = 600 Set B to point to $600 40A 1422 CALL 422 Call 422 for C0,C5,CA,CA,BC,B5 40C 21C5 V1 = C5 Print PUZZLE. 40E 1422 CALL 422 410 21CA V1 = CA 412 1422 CALL 422 414 21CA V1 = CA 416 1422 CALL 422 418 21BC V1 = BC 41A 1422 CALL 422 41C 21B5 V1 = B5 41E 1422 CALL 422 420 F430 GOTO 430 Skip over 422 code. 422 7134 V1->LSB of (B) So B is now (say) $6C5 424 7121 Read $6C5 into V1 426 8234 Says V2 + V3 -> V2 which makes more sense. 428 9125 Write graphic V1 and position V2. 5 high. 42A 026E Return. 42C E47A Keyboard on, wait for key to V4. 42E F438 Goto 438 430 0078 Clear Screen 432 F42C Goto 42C 438 0078 Clear Screen 43A 2700 V7 = 0 (timer) 43C 21F0 V1 = F0 43E 2200 V2 = 0 440 1450 Call 450 442 7121 Read Mem(B) to V1. 444 2201 V2 = 1 446 1450 Call 450 448 21F1 V1 = F1 44A 2208 V2 = 8 44C 1450 Call 450 44E F458 Goto 458 ; ; Read [$0600+V1] and display pattern at V2 ; 450 7134 B = 6[V1] 452 7121 V1 = M[B] 454 912B 8x8 Pattern address in V1, Cell in V2. 456 026E Return 458 025C TV On 45A 21F5 V1 = F5 45C 220E V2 = 0E 45E 1450 Call 450 460 21F3 V1 = F3 462 2215 V2 = 15 464 1450 Call 450 466 7448 Delay V4 468 E480 Get Key Skip if None 46A 1490 Key goto 1490 """
# https://www.codechef.com/problems/MISSP for T in range(int(input())): a=[] for n in range(int(input())): k=int(input()) if(k not in a): a.append(k) else: a.remove(k) print(a[0])
""" 1. Clarification 2. Possible solutions - Naive Approach - String Concatenation - Hash 3. Coding 4. Tests """ # T=O(n), S=O(1) class Solution: def fizzBuzz(self, n: int) -> List[str]: ans = [] for num in range(1, n + 1): divisible_by_3 = (num % 3 == 0) divisible_by_5 = (num % 5 == 0) if divisible_by_3 and divisible_by_5: ans.append("FizzBuzz") elif divisible_by_3: ans.append("Fizz") elif divisible_by_5: ans.append("Buzz") else: ans.append(str(num)) return ans # T=O(n), S=O(1) class Solution: def fizzBuzz(self, n: int) -> List[str]: ans = [] for num in range(1, n + 1): divisible_by_3 = (num % 3 == 0) divisible_by_5 = (num % 5 == 0) num_ans_str = "" if divisible_by_3: num_ans_str += "Fizz" if divisible_by_5: num_ans_str += "Buzz" if not num_ans_str: num_ans_str = str(num) ans.append(num_ans_str) return ans # T=O(n), S=O(1) class Solution: def fizzBuzz(self, n: int) -> List[str]: ans = [] fizz_buzz_dict = {3: "Fizz", 5: "Buzz"} for num in range(1, n + 1): num_ans_str = "" for key in fizz_buzz_dict.keys(): if num % key == 0: num_ans_str += fizz_buzz_dict[key] if not num_ans_str: num_ans_str = str(num) ans.append(num_ans_str) return ans
def check_subtree(t2, t1): if t1 is None or t2 is None: return False if t1.val == t2.val: # potential subtree if subtree_equality(t2, t1): return True return check_subtree(t2, t1.left) or check_subtree(t2, t1.right) def subtree_equality(t2, t1): if t2 is None and t1 is None: return True if t1 is None or t2 is None: return False if t2.val == t1.val: return subtree_equality(t2.left, t1.left) and subtree_equality(t2.right, t1.right) return False
# Sky Jewel box (2002016) | Treasure Room of Queen (926000010) eleska = 3935 skyJewel = 4031574 reactor.incHitCount() if reactor.getHitCount() >= 3: if sm.hasQuest(eleska) and not sm.hasItem(skyJewel): sm.dropItem(skyJewel, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY()) sm.removeReactor()
a[-1] a[-2:] a[:-2] a[::-1] a[1::-1] a[:-3:-1] a[-3::-1] point_coords = coords[i, :] main(sys.argv[1:])
''' for a in range(3,1000): for b in range(a+1,999): csquared= a**2+b**2 c=csquared**0.5 if a+b+c==1000: product= a*b*c print(product) print(c) break ''' def compute(): PERIMETER = 1000 for a in range(1, PERIMETER + 1): for b in range(a + 1, PERIMETER + 1): c = PERIMETER - a - b if a * a + b * b == c * c: # It is now implied that b < c, because we have a > 0 return str(a * b * c) if __name__ == "__main__": print(compute())
# Language: Python # Level: 8kyu # Name of Problem: DNA to RNA Conversion # Instructions: Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. # It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T'). # Ribonucleic acid, RNA, is the primary messenger molecule in cells. # RNA differs slightly from DNA its chemical structure and contains no Thymine. # In RNA Thymine is replaced by another nucleic acid Uracil ('U'). # Create a function which translates a given DNA string into RNA. # The input string can be of arbitrary length - in particular, it may be empty. # All input is guaranteed to be valid, i.e. each input string will only ever consist of 'G', 'C', 'A' and/or 'T'. # Example: # DNAtoRNA("GCAT") returns ("GCAU") # Solution 1: def DNAtoRNA(dna): return dna.replace('T', 'U') # Sample Tests Passed: # test.assert_equals(DNAtoRNA("TTTT"), "UUUU") # test.assert_equals(DNAtoRNA("GCAT"), "GCAU") # test.assert_equals(DNAtoRNA("GACCGCCGCC"), "GACCGCCGCC")
data = ( 'Kay ', # 0x00 'Kayng ', # 0x01 'Ke ', # 0x02 'Ko ', # 0x03 'Kol ', # 0x04 'Koc ', # 0x05 'Kwi ', # 0x06 'Kwi ', # 0x07 'Kyun ', # 0x08 'Kul ', # 0x09 'Kum ', # 0x0a 'Na ', # 0x0b 'Na ', # 0x0c 'Na ', # 0x0d 'La ', # 0x0e 'Na ', # 0x0f 'Na ', # 0x10 'Na ', # 0x11 'Na ', # 0x12 'Na ', # 0x13 'Nak ', # 0x14 'Nak ', # 0x15 'Nak ', # 0x16 'Nak ', # 0x17 'Nak ', # 0x18 'Nak ', # 0x19 'Nak ', # 0x1a 'Nan ', # 0x1b 'Nan ', # 0x1c 'Nan ', # 0x1d 'Nan ', # 0x1e 'Nan ', # 0x1f 'Nan ', # 0x20 'Nam ', # 0x21 'Nam ', # 0x22 'Nam ', # 0x23 'Nam ', # 0x24 'Nap ', # 0x25 'Nap ', # 0x26 'Nap ', # 0x27 'Nang ', # 0x28 'Nang ', # 0x29 'Nang ', # 0x2a 'Nang ', # 0x2b 'Nang ', # 0x2c 'Nay ', # 0x2d 'Nayng ', # 0x2e 'No ', # 0x2f 'No ', # 0x30 'No ', # 0x31 'No ', # 0x32 'No ', # 0x33 'No ', # 0x34 'No ', # 0x35 'No ', # 0x36 'No ', # 0x37 'No ', # 0x38 'No ', # 0x39 'No ', # 0x3a 'Nok ', # 0x3b 'Nok ', # 0x3c 'Nok ', # 0x3d 'Nok ', # 0x3e 'Nok ', # 0x3f 'Nok ', # 0x40 'Non ', # 0x41 'Nong ', # 0x42 'Nong ', # 0x43 'Nong ', # 0x44 'Nong ', # 0x45 'Noy ', # 0x46 'Noy ', # 0x47 'Noy ', # 0x48 'Noy ', # 0x49 'Nwu ', # 0x4a 'Nwu ', # 0x4b 'Nwu ', # 0x4c 'Nwu ', # 0x4d 'Nwu ', # 0x4e 'Nwu ', # 0x4f 'Nwu ', # 0x50 'Nwu ', # 0x51 'Nuk ', # 0x52 'Nuk ', # 0x53 'Num ', # 0x54 'Nung ', # 0x55 'Nung ', # 0x56 'Nung ', # 0x57 'Nung ', # 0x58 'Nung ', # 0x59 'Twu ', # 0x5a 'La ', # 0x5b 'Lak ', # 0x5c 'Lak ', # 0x5d 'Lan ', # 0x5e 'Lyeng ', # 0x5f 'Lo ', # 0x60 'Lyul ', # 0x61 'Li ', # 0x62 'Pey ', # 0x63 'Pen ', # 0x64 'Pyen ', # 0x65 'Pwu ', # 0x66 'Pwul ', # 0x67 'Pi ', # 0x68 'Sak ', # 0x69 'Sak ', # 0x6a 'Sam ', # 0x6b 'Sayk ', # 0x6c 'Sayng ', # 0x6d 'Sep ', # 0x6e 'Sey ', # 0x6f 'Sway ', # 0x70 'Sin ', # 0x71 'Sim ', # 0x72 'Sip ', # 0x73 'Ya ', # 0x74 'Yak ', # 0x75 'Yak ', # 0x76 'Yang ', # 0x77 'Yang ', # 0x78 'Yang ', # 0x79 'Yang ', # 0x7a 'Yang ', # 0x7b 'Yang ', # 0x7c 'Yang ', # 0x7d 'Yang ', # 0x7e 'Ye ', # 0x7f 'Ye ', # 0x80 'Ye ', # 0x81 'Ye ', # 0x82 'Ye ', # 0x83 'Ye ', # 0x84 'Ye ', # 0x85 'Ye ', # 0x86 'Ye ', # 0x87 'Ye ', # 0x88 'Ye ', # 0x89 'Yek ', # 0x8a 'Yek ', # 0x8b 'Yek ', # 0x8c 'Yek ', # 0x8d 'Yen ', # 0x8e 'Yen ', # 0x8f 'Yen ', # 0x90 'Yen ', # 0x91 'Yen ', # 0x92 'Yen ', # 0x93 'Yen ', # 0x94 'Yen ', # 0x95 'Yen ', # 0x96 'Yen ', # 0x97 'Yen ', # 0x98 'Yen ', # 0x99 'Yen ', # 0x9a 'Yen ', # 0x9b 'Yel ', # 0x9c 'Yel ', # 0x9d 'Yel ', # 0x9e 'Yel ', # 0x9f 'Yel ', # 0xa0 'Yel ', # 0xa1 'Yem ', # 0xa2 'Yem ', # 0xa3 'Yem ', # 0xa4 'Yem ', # 0xa5 'Yem ', # 0xa6 'Yep ', # 0xa7 'Yeng ', # 0xa8 'Yeng ', # 0xa9 'Yeng ', # 0xaa 'Yeng ', # 0xab 'Yeng ', # 0xac 'Yeng ', # 0xad 'Yeng ', # 0xae 'Yeng ', # 0xaf 'Yeng ', # 0xb0 'Yeng ', # 0xb1 'Yeng ', # 0xb2 'Yeng ', # 0xb3 'Yeng ', # 0xb4 'Yey ', # 0xb5 'Yey ', # 0xb6 'Yey ', # 0xb7 'Yey ', # 0xb8 'O ', # 0xb9 'Yo ', # 0xba 'Yo ', # 0xbb 'Yo ', # 0xbc 'Yo ', # 0xbd 'Yo ', # 0xbe 'Yo ', # 0xbf 'Yo ', # 0xc0 'Yo ', # 0xc1 'Yo ', # 0xc2 'Yo ', # 0xc3 'Yong ', # 0xc4 'Wun ', # 0xc5 'Wen ', # 0xc6 'Yu ', # 0xc7 'Yu ', # 0xc8 'Yu ', # 0xc9 'Yu ', # 0xca 'Yu ', # 0xcb 'Yu ', # 0xcc 'Yu ', # 0xcd 'Yu ', # 0xce 'Yu ', # 0xcf 'Yu ', # 0xd0 'Yuk ', # 0xd1 'Yuk ', # 0xd2 'Yuk ', # 0xd3 'Yun ', # 0xd4 'Yun ', # 0xd5 'Yun ', # 0xd6 'Yun ', # 0xd7 'Yul ', # 0xd8 'Yul ', # 0xd9 'Yul ', # 0xda 'Yul ', # 0xdb 'Yung ', # 0xdc 'I ', # 0xdd 'I ', # 0xde 'I ', # 0xdf 'I ', # 0xe0 'I ', # 0xe1 'I ', # 0xe2 'I ', # 0xe3 'I ', # 0xe4 'I ', # 0xe5 'I ', # 0xe6 'I ', # 0xe7 'I ', # 0xe8 'I ', # 0xe9 'I ', # 0xea 'Ik ', # 0xeb 'Ik ', # 0xec 'In ', # 0xed 'In ', # 0xee 'In ', # 0xef 'In ', # 0xf0 'In ', # 0xf1 'In ', # 0xf2 'In ', # 0xf3 'Im ', # 0xf4 'Im ', # 0xf5 'Im ', # 0xf6 'Ip ', # 0xf7 'Ip ', # 0xf8 'Ip ', # 0xf9 'Cang ', # 0xfa 'Cek ', # 0xfb 'Ci ', # 0xfc 'Cip ', # 0xfd 'Cha ', # 0xfe 'Chek ', # 0xff )
# У кафе морозиво продають по три кульки і по п'ять кульок. Чи можна купити рівно k кульок морозива? # # ## Формат введення # # Вводиться число k (ціле, позитивне) # # ## Формат виведення # # Програма повинна вивести слово YES, якщо при таких умовах можна набрати рівно k кульок (не більше і не менше), в іншому випадку - вивести NO. # k = int(input()) if k < 3 or k == 4 or k == 7: print("NO") else: print("YES")
class Sol(object): def __init__(self): self.suc = None def in_order(self, head, num): if not head: return None int = [] def helper(head): nonlocal int if head: self.helper(head.left) int.append(head.val) self.helper(head.right) helper(head) if num in int: return int[int.index(num)+1]
# OpenWeatherMap API Key weather_api_key = "Insert your own key" # Google API Key g_key = "Insert your own key"
"Tests for pug bzl definitions" load("@bazel_tools//tools/build_rules:test_rules.bzl", "file_test", "rule_test") def _pug_binary_test(package): rule_test( name = "hello_world_rule_test", generates = ["main.html"], rule = package + "/hello_world:hello_world" ) file_test( name = "hello_world_file_test", file = package + "/hello_world:main.html", content = "<div>Hello World !</div>" ) rule_test( name = "mixin_rule_test", generates = ["main.html"], rule = package + "/mixin:mixin" ) file_test( name = "mixin_file_test", file = package + "/mixin:main.html", content = "<div>Hello World !</div><div>Mixin file</div><div>Mixin resource</div>" ) def pug_rule_test(package): """Issue simple tests on pug rules.""" _pug_binary_test(package)
class A(object): def A(): print('factory') return A() def __init__(self): print('init') def __call__(self): print('call') print('chamar o construtor') a = A() print('chamar o construtor e a função') b = A()() print('chamar a função') c = A.A() #https://pt.stackoverflow.com/q/109813/101
class Solution: def countGoodSubstrings(self, s: str) -> int: count, i, end = 0, 2, len(s) while i < end: a, b, c = s[i-2], s[i-1], s[i] if a == b == c: i += 2 continue count += a != b and b != c and a != c i += 1 return count
( XL_CELL_EMPTY, #0 XL_CELL_TEXT, #1 XL_CELL_NUMBER, #2 XL_CELl_DATE, #3 XL_CELL_BOOLEAN,#4 XL_CELL_ERROR, #5 XL_CELL_BLANK, #6 ) = range(7) ctype_text = { XL_CELL_EMPTY: 'empty', XL_CELL_TEXT:'text', XL_CELL_NUMBER:'number', XL_CELl_DATE:'date', XL_CELL_BOOLEAN:'boolean', XL_CELL_ERROR:'error', XL_CELL_BLANK:'blank', }
""" Dictionary key must be immutable """ string_dict = dict({"1": "1st", "2": "2nd", "3": "3rd"}) def add_element_to_string_dict(key: str, value: str): string_dict[key] = value def delete_element_to_string_dict(key: str): del string_dict[key] def get_element_from_string_dict(key: str): if key in string_dict: print("key: {} \t value: {}".format(key, string_dict[key])) else: print("key {} not found".format(key)) def are_equal(dict_one, dict_two): return dict_one == dict_two def is_key_in_dict(key, my_dict): return key in my_dict def list_keys(my_dict): return list(my_dict.keys()) def list_values(my_dict): return list(my_dict.values()) def list_items(my_dict): return list(my_dict.items()) def print_info(my_dict): for k in my_dict.keys(): print('\t', k) print('') for v in my_dict.values(): print('\t', v) print('') for k, v in my_dict.items(): print('\t', k, v) def set_default(my_dict, key, value): my_dict.setdefault(key, value) return my_dict if __name__ == '__main__': print('base dict\n', string_dict) add_element_to_string_dict("4", "4rd") print('add an element\n', string_dict) delete_element_to_string_dict("2") print('delete an element\n', string_dict) get_element_from_string_dict("8") print('getting an element\n', string_dict) get_element_from_string_dict("4") a = {'name': 'Pit', 'age': 423} b = {'age': 423, 'name': 'Pit'} print('compare two dicts\n', are_equal(a, b)) print('look for a key in a dict\n', is_key_in_dict('hello', a)) print('list all the keys of a dict\n', list_keys(string_dict)) print('list all the values of a dict\n', list_values(string_dict)) print('list all the items of a dict\n', list_items(string_dict)) print('\nInfo: \n') print_info(string_dict) print('Set a new key whit its value\n', set_default(string_dict, '5', '5th'))
# -*- coding:utf-8 -*- """ @Author:Charles Van @E-mail: [email protected] @Time:2019-08-08 16:35 @Project:InterView_Book @Filename:String5.py @description: 用有限状态自动机匹配字符串 """ """ 题目描述: 给定两个字符串,S和T,其中S是要查找的字符串,T是被查找的文本,要求 给出一个查找算法,找出S在T中第一次出现的位置 """ class StringAutomation: def __init__(self,P): # 用字典来表示状态机跳转表 self.jumpTable = {} self.P = P # 为简单起见,在此假设文本和字符串又3个字符组成。如果要处理26个字符组成的文本,只要把下面 # 变量改成26即可 self.alphaSize = 3 self.makeJumpTable() def makeJumpTable(self): m = len(self.P) for q in range(m): for k in range(self.alphaSize): Pq = self.P[0:q] # 构造每一个可能的输入字符 c = chr(ord('a') + k) Pq += c # 查找从p的首字符开始连续的几个字符能构成Pq的后缀 nextState = self.findSuffix(Pq) print("from state {0} receive input char {1} jump to state {2}".format(q,c,nextState)) ''' 跳转表中每一行也是一个字典,一个字符对应一个状态节点 ''' jumpLine = self.jumpTable.get(q) if jumpLine is None: jumpLine = {} jumpLine[c] = nextState self.jumpTable[q] = jumpLine def findSuffix(self, Pq): # 查找从p的首字符开始,连续几个字符构成的字符串能成为Pq的后缀 suffixLen = 0 k = 0 while k < len(Pq) and k < len(self.P): ''' 看看P从首字符开始总共有几个字符可以和字符串Pq最后k个字符形成的字符串相匹配 ''' i = 0 while i <= k: if Pq[len(Pq)-1-k+i] != self.P[i]: break i += 1 if i - 1 == k: ''' 这里加1,是因为数组的下标与对应的个数之间相差1 ''' suffixLen = k + 1 k += 1 return suffixLen def match(self,T): # 状态机初始时处于状态节点0 q = 0 print("Begin matching.........") ''' 依次读入文本T中的字符,然后查表看看状态机跳转节点,如果跳转到的节点编号与字符串 P的长度一致,那表明文本T包含了字符串P ''' for i in range(len(T)): # 根据状态节点获取跳转表中对应的一行 jumpLine = self.jumpTable.get(q) oldState = q # 根据当前输入字符获取下一个状态 q = jumpLine.get(T[i]) if q is None: # 输入的字符无法跳转到有效的下一个状态节点,这表明跳转表的构建可能出错 return -1 print("In state {0} receive input {1} jump to state {2}".format(oldState,T[i],q)) if q == len(self.P): # 状态节点编号如果与P的长度一致,则表明T包含了P return i-q-1 return -1 if __name__ == "__main__": P = "ababaca" T = "baabababaca" sa = StringAutomation(P) pos = sa.match(T) if pos != -1: print("Match in position {0}".format(pos))
escolha = 's' num = cont = soma = maior = menor = 0 while escolha not in 'Nn': num = int(input('Digite um número: ')) escolha = str(input('Quer continuar [S/N]: ')).strip()[0] if escolha not in 'SsNn': print('Escolha inválido, digite novamente') cont += 1 soma += num if cont == 1: maior = menor = num else: if maior < num: maior = num elif menor > num: menor = num print('Voce digitou {} número e a média foi de {:.2f}.'.format(cont, (soma/cont))) print('O número maior foi {} e o menor foi {}.'.format(maior, menor))
def sum6(n): nums = [i for i in range(1, n + 1)] return sum(nums) N = 10 S = sum6(N) print(S)
class ValveStatus(object): """ An enumeration of possible valve states. OPEN_AND_DISABLED should never happen. """ OPEN_AND_ENABLED, CLOSED_AND_ENABLED, OPEN_AND_DISABLED, CLOSED_AND_DISABLED = (i for i in range(4))
i = str(input('Em que cidade você nasceu? ')).strip() x1 = i.title() x2 = x1.split() x3 = x2[0] x4 = x3.find('Santo') if x4 == 0: print('Você nasceu em uma cidade que começa com "Santo"') elif x4 == -1: print('Você não nasceu em uma cidade que começa com "Santo"')
def solve(): s = sum((x ** x for x in range(1, 1001))) print(str(s)[-10:]) if __name__ == '__main__': solve()
#!/usr/bin/env python """Contains extractor configuration information """ # Setup the name of our extractor. EXTRACTOR_NAME = "" # Name of scientific method for this extractor. Leave commented out if it's unknown #METHOD_NAME = "" # The version number of the extractor VERSION = "1.0" # The extractor description DESCRIPTION = "" # The name of the author of the extractor AUTHOR_NAME = "" # The email of the author of the extractor AUTHOR_EMAIL = "" # Reposity URI REPOSITORY = "" # Output variable identifiers. Use a comma separated list if more than one value is returned. # For example, "variable 1,variable 2" identifies the two variables returned by the extractor. # If only one name is specified, no comma's are used. # Note that variable names cannot have comma's in them: use a different separator instead. Also, # all white space is kept intact; don't add any extra whitespace since it may cause name comparisons # to fail VARIABLE_NAMES = ""
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ tmp = head while tmp and tmp.next: head = head.next tmp = tmp.next.next return head def test_middle_node_1(): s = Solution() a = ListNode(2) b = ListNode(1) c = ListNode(3) d = ListNode(5) e = ListNode(6) a.next = b b.next = c c.next = d d.next = e assert c == s.middleNode(a) def test_middle_node_2(): s = Solution() a = ListNode(2) b = ListNode(1) c = ListNode(3) d = ListNode(5) e = ListNode(6) f = ListNode(7) a.next = b b.next = c c.next = d d.next = e e.next = f assert d == s.middleNode(a)
listaDePalavras = ('Aprender','Programar','Linguagem','Python','Curso','Gratis', 'Estudar','Praticar','Trabalhar','Mercado','Programador', 'Futuro') for palavras in listaDePalavras: print(f'\n A palavra {palavras} temos', end=' ') for letras in palavras: if letras.lower() in 'aeiou': print(letras.lower(),end=' ')
x = 1 y = 'Hello' z = 10.123 d = x + z print(d) print(type(x)) print(type(y)) print(y.upper()) print(y.lower()) print(type(z)) a = [1,2,3,4,5,6,6,7,8] print(len(a)) print(a.count(6)) b = list(range(10,100,10)) print(b) stud_marks = {"Madhan":90, "Raj":25,"Mani":80} print(stud_marks.keys()) print(stud_marks.values()) ab = list(range(10,100,10)) ab.append(100) ab.append(110) ab.remove(110) print(ab[0:2])
# Generate .travis.yml automatically # Configuration for Linux configs = [ # OS, OS version, compiler, build type, task ("ubuntu", "18.04", "gcc", "DefaultDebug", "Test"), ("ubuntu", "18.04", "gcc", "DefaultRelease", "Test"), ("debian", "9", "gcc", "DefaultDebug", "Test"), ("debian", "9", "gcc", "DefaultRelease", "Test"), ("debian", "10", "gcc", "DefaultDebug", "Test"), ("debian", "10", "gcc", "DefaultRelease", "Test"), ("ubuntu", "20.04", "gcc", "DefaultDebugTravis", "TestDocker"), ("ubuntu", "20.04", "gcc", "DefaultReleaseTravis", "TestDockerDoxygen"), # ("osx", "xcode9.3", "clang", "DefaultDebug", "Test"), # ("osx", "xcode9.3", "clang", "DefaultRelease", "Test"), ] # Stages in travis build_stages = [ ("Build (1st run)", "Build1"), ("Build (2nd run)", "Build2"), ("Build (3rd run)", "BuildLast"), ("Tasks", "Tasks"), ] def get_env_string(os, os_version, compiler, build_type, task): if os == "osx": return "CONFIG={} TASK={} COMPILER={} STL=libc++\n".format(build_type, task, compiler) else: return "CONFIG={} TASK={} LINUX={} COMPILER={}\n".format(build_type, task, "{}-{}".format(os, os_version), compiler) if __name__ == "__main__": s = "" # Initial config s += "#\n" s += "# General config\n" s += "#\n" s += "branches:\n" s += " only:\n" s += " - master\n" s += " - stable\n" s += "sudo: required\n" s += "language: cpp\n" s += "\n" s += "git:\n" s += " depth: false\n" s += "\n" s += "# Enable caching\n" s += "cache:\n" s += " timeout: 1000\n" s += " directories:\n" s += " - build\n" s += " - travis/mtime_cache\n" s += "\n" s += "# Enable docker support\n" s += "services:\n" s += "- docker\n" s += "\n" s += "notifications:\n" s += " email:\n" s += " on_failure: always\n" s += " on_success: change\n" s += " recipients:\n" s += ' - secure: "VWnsiQkt1xjgRo1hfNiNQqvLSr0fshFmLV7jJlUixhCr094mgD0U2bNKdUfebm28Byg9UyDYPbOFDC0sx7KydKiL1q7FKKXkyZH0k04wUu8XiNw+fYkDpmPnQs7G2n8oJ/GFJnr1Wp/1KI3qX5LX3xot4cJfx1I5iFC2O+p+ng6v/oSX+pewlMv4i7KL16ftHHHMo80N694v3g4B2NByn4GU2/bjVQcqlBp/TiVaUa5Nqu9DxZi/n9CJqGEaRHOblWyMO3EyTZsn45BNSWeQ3DtnMwZ73rlIr9CaEgCeuArc6RGghUAVqRI5ao+N5apekIaILwTgL6AJn+Lw/+NRPa8xclgd0rKqUQJMJCDZKjKz2lmIs3bxfELOizxJ3FJQ5R95FAxeAZ6rb/j40YqVVTw2IMBDnEE0J5ZmpUYNUtPti/Adf6GD9Fb2y8sLo0XDJzkI8OxYhfgjSy5KYmRj8O5MXcP2MAE8LQauNO3MaFnL9VMVOTZePJrPozQUgM021uyahf960+QNI06Uqlmg+PwWkSdllQlxHHplOgW7zClFhtSUpnJxcsUBzgg4kVg80gXUwAQkaDi7A9Wh2bs+TvMlmHzBwg+2SaAfWDgjeJIeOaipDkF1uSGzC+EHAiiKYMLd4Aahoi8SuelJUucoyJyLAq00WdUFQIh/izVhM4Y="\n' s += "\n" s += "#\n" s += "# Configurations\n" s += "#\n" s += "jobs:\n" s += " include:\n" # Start with prebuilding carl for docker s += "\n" s += " ###\n" s += " # Stage: Build Carl\n" s += " ###\n" for config in configs: os, os_version, compiler, build_type, task = config os_type = "osx" if os == "osx" else "linux" if "Travis" in build_type: s += " # {}-{} - {}\n".format(os, os_version, build_type) buildConfig = "" buildConfig += " - stage: Build Carl\n" buildConfig += " os: {}\n".format(os_type) buildConfig += " compiler: {}\n".format(compiler) buildConfig += " env: {}".format(get_env_string(os, os_version, compiler, build_type, task)) buildConfig += " before_script:\n" buildConfig += ' - python -c "import fcntl; fcntl.fcntl(1, fcntl.F_SETFL, 0)" # Workaround for nonblocking mode\n' buildConfig += " script:\n" buildConfig += " - travis/build_carl.sh\n" buildConfig += " before_cache:\n" buildConfig += " - docker cp carl:/opt/carl/. .\n" # Upload to DockerHub buildConfig += " deploy:\n" buildConfig += " - provider: script\n" buildConfig += " skip_cleanup: true\n" buildConfig += " script: bash travis/deploy_docker.sh carl\n" s += buildConfig # Generate all build configurations for stage in build_stages: s += "\n" s += " ###\n" s += " # Stage: {}\n".format(stage[0]) s += " ###\n" for config in configs: os, os_version, compiler, build_type, task = config os_type = "osx" if os == "osx" else "linux" s += " # {}-{} - {}\n".format(os, os_version, build_type) buildConfig = "" buildConfig += " - stage: {}\n".format(stage[0]) buildConfig += " os: {}\n".format(os_type) if os_type == "osx": buildConfig += " osx_image: {}\n".format(os_version) buildConfig += " compiler: {}\n".format(compiler) buildConfig += " env: {}".format(get_env_string(os, os_version, compiler, build_type, task)) buildConfig += " install:\n" if stage[1] == "Build1": buildConfig += " - rm -rf build\n" buildConfig += " - travis/skip_test.sh\n" if os_type == "osx": buildConfig += " - travis/install_osx.sh\n" buildConfig += " before_script:\n" buildConfig += ' - python -c "import fcntl; fcntl.fcntl(1, fcntl.F_SETFL, 0)" # Workaround for nonblocking mode\n' buildConfig += " script:\n" buildConfig += " - travis/build.sh {}\n".format(stage[1]) if os_type == "linux": buildConfig += " before_cache:\n" buildConfig += " - docker cp storm:/opt/storm/. .\n" buildConfig += " after_failure:\n" buildConfig += " - find build -iname '*err*.log' -type f -print -exec cat {} \;\n" # Deployment if stage[1] == "Tasks": if "Docker" in task or "Doxygen" in task: buildConfig += " deploy:\n" if "Docker" in task: buildConfig += " - provider: script\n" buildConfig += " skip_cleanup: true\n" buildConfig += " script: bash travis/deploy_docker.sh storm\n" if "Doxygen" in task: buildConfig += " - provider: pages\n" buildConfig += " skip_cleanup: true\n" buildConfig += " github_token: $GITHUB_TOKEN\n" buildConfig += " local_dir: build/doc/html/\n" buildConfig += " repo: moves-rwth/storm-doc\n" buildConfig += " target_branch: master\n" buildConfig += " on:\n" buildConfig += " branch: master\n" s += buildConfig print(s)
######################### # # # Developer: Luis Regus # # Date: 11/24/15 # # # ######################### NORTH = "north" EAST = "east" SOUTH = "south" WEST = "west" class Robot: ''' Custom object used to represent a robot ''' def __init__(self, direction=NORTH, x_coord=0, y_coord=0): self.coordinates = (x_coord, y_coord) self.bearing = direction def turn_right(self): directions = { NORTH: EAST, EAST: SOUTH, SOUTH: WEST, WEST: NORTH} self.bearing = directions.get(self.bearing, NORTH) def turn_left(self): directions = { NORTH: WEST, EAST: NORTH, SOUTH: EAST, WEST: SOUTH} self.bearing = directions.get(self.bearing, NORTH) def advance(self): coords = { NORTH: (self.coordinates[0], self.coordinates[1] + 1), EAST: (self.coordinates[0] + 1, self.coordinates[1]), SOUTH: (self.coordinates[0], self.coordinates[1] - 1), WEST: (self.coordinates[0] - 1, self.coordinates[1])} self.coordinates = coords.get(self.bearing, self.coordinates) def simulate(self, movement): for m in movement: if m == 'R': self.turn_right() elif m == 'L': self.turn_left() elif m == 'A': self.advance()
class ToolBoxBaseException(Exception): status_code = 500 error_name = 'base_exception' def __init__(self, message): self.message = message def to_dict(self): return dict(error_name=self.error_name, message=self.message) class UnknownError(ToolBoxBaseException): status_code = 500 error_name = 'unknown_error' def __init__(self, e): self.message = '{}'.format(e) class BadRequest(ToolBoxBaseException): status_code = 400 error_name = 'bad_request' def __init__(self, message=None): self.message = message
''' lab 8 functions ''' #3.1 def count_words(input_str): return len(input_str.split()) #print(count_words('This is a string')) #3.2 demo_str = 'Hello World!' print(count_words(demo_str)) #3.3 def find_min(num_list): min_item = num_list[0] for num in num_list: if type(num) is not str: if min_item >= num: min_item = num return(min_item) #print(find_min([1, 2, 3, 4])) #3.4 demo_list = [1, 2, 3, 4, 5, 6] print(find_min(demo_list)) #3.5 mix_list = [1, 2, 3, 4, 'a', 5, 6] print(find_min(mix_list))
users = { 'name': 'Elena', 'age': 100, 'town': 'Varna' } for key, value in users.items(): print(key, value) for key in users.keys(): print(key) for value in users.values(): print(value)
class Solution: def getSum(self, a: int, b: int) -> int: # 32 bits integer max and min MAX = 0x7FFFFFFF MIN = 0x80000000 mask = 0xFFFFFFFF while b != 0: carry = a & b a, b = (a ^ b) & mask, (carry << 1) & mask return a if a <= MAX else ~(a ^ mask)
# Задача 1. Вариант 28 # Напишите программу, которая будет сообщать род деятельности и псевдоним под # которым скрывается Норма Бейкер. После вывода информации программа должна # дожидаться пока пользователь нажмет Enter для выхода. print("Норма Бейкер, более известная как Мэрилин Монро - американская \nкиноактриса, певица и секс-символ.") input("\nНажмите Enter для выхода...")
""" Compatibility related items. """ __author__ = "Brian Allen Vanderburg II" __copyright__ = "Copyright (C) 2019 Brian Allen Vanderburg II" __license__ = "Apache License 2.0"
# -*- coding: utf-8 -*- """ Copyright () 2018 All rights reserved FILE: linked_list.py AUTHOR: tianyuningmou DATE CREATED: @Time : 2018/5/14 上午10:58 DESCRIPTION: . VERSION: : #1 CHANGED By: : tianyuningmou CHANGE: : MODIFIED: : @Time : 2018/5/14 上午10:58 """ """ 链表是线性表的一种 线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的。 线性表有两种存储方式,一种是顺序存储结构,另一种是链式存储结构。 链表指针的鲁棒性: ① 当访问链表中某个节点 curt.next 时,一定要先判断 curt 是否为 None ② 全部操作结束后,判断是否有环;若有环,则置其中一端为 None """ # 反转单向链表 class ListNode: def __init__(self, val): self.val = val self.next = None def reverse(self, head): prev = None while head: temp = head.next head.next = prev prev = head head = temp return prev # 反转双向链表 class DListNode: def __init__(self, val): self.val = val self.prev = self.next = None def reverse(self, head): curt = None while head: curt = head head = curt.next curt.next = curt.prev curt.prev = head return curt # 快慢指针 class NodeCircle: def __init__(self, val): self.val = val self.next = None def has_circle(self, head): slow = head fast = head while (slow and fast): fast = fast.next slow = slow.next if fast: fast = fast.next if fast == slow: break if fast and slow and (fast == slow): return True else: return False
class Memories(object): def __init__(self, memory_capacity): self.food_memories = [] self.offspring_memories = [] # No aplican a la cantidad de recuerdos y nunca se olvidan (mientras vivan) self.territory_link_memories = [] self.food_location_memories = [] self.hostile_creature_memories = [] self.lists_forgettable_memories = [self.food_memories, self.territory_link_memories, self.food_location_memories, self.hostile_creature_memories] self.memory_capacity = memory_capacity self.amount_memories = 0 def to_forget(self): """ Recoge todos los recuerdos que puedan ser olvidados y busca el más antiguo para eliminarlo. """ lists_memories_to_forget = [] for memory_list in lists_forgettable_memories: # Recabamos todos los recuerdos lists_memories_to_forget += memory_list lists_memories_to_forget.sort(key=lambda memories: memories.age, reverse=False) # Los ordena de más antiguo a más nuevo for memory_list in lists_forgettable_memories: if lists_memories_to_forget[0] in memory_list: memory_list.remove(lists_memories_to_forget[0]) self.amount_memories -= 1 return # lists_name_memories = self.__dict__.keys() # lists_name_memories.remove('offspring_memories') # Los recuerdos de las crías nunca se olvidan (mientras vivan) # lists_memories_to_forget = [] # while not lists_memories_to_forget: # Escogemos una lista de recuerdos que no esté vacía # lists_memories_to_forget = self.__dict__.[random.choice(lists_name_memories)] # lists_memories_to_forget.remove(len(random.choice(lists_memories_to_forget))) def to_remember_food(self, age, food): """ @brief Crea un recuerdo de un alimento ingerido. @param self The object @param age The age @param food Tupla con el tipo de alimento, los 5 nutrientes digeridos y la toxicidad generada """ nutritional_value = 0 for nutrient in food[1]: nutritional_value += nutrient nutritional_value += food[1][0] - food[2] * 2 self.food_memories.append(FoodMemory(age, food[0], nutritional_value)) self.amount_memories += 1 def to_remember_offspring(self, age, agent, genetic_distance): self.offspring_memories.append(OffspringMemory(age, agent, genetic_distance)) def to_broatcast_birth_to_family(self, agent): """ @brief Genera en todos los agentes de la especie el recuerdo del nuevo agente. Esto permite aligerar el cálculo de distancia genética e informa a la familia de que existe un nuevo agente del que cuidar. Se podría añadir un parámetro para que solo generen el recuerdo los que tenga menos de cierta distancia genética. @param self The object @param agent The agent """ for relative_node in agent.genetic_node.species.nodes: relative_node.agent.memories.to_remember_offspring(relative_node.agent.age, agent, relative_node.agent.get_genetic_distance(agent)) def to_forget_offspring(self, agent): for offspring_memory in self.offspring_memories: if agent is offspring_memory.agent: self.offspring_memories.remove(offspring_memory) return def to_broatcast_death_to_family(self, agent): """ @brief Elimina en todos los agentes de la especie el recuerdo del agente muerto. @param self The object @param age The age @param agent The agent """ for relative_node in agent.genetic_node.species.nodes: relative_node.agent.memories.to_forget_offspring(agent) def to_remember_territory_link(self, age, territory_1, territory_2): self.territory_link_memories.append(TerritoryLinkMemory(age, territory_1, territory_2)) self.amount_memories += 1 def to_remember_food_location(self, age, food, territory): self.food_location_memories.append(FoodLocationMemory(age, food[0], territory)) self.amount_memories += 1 def to_remember_hostile_creature(self, age, creature): # En esta versión se guarda la especie self.hostile_creature_memories.append(HostileCreatureMemory(age, creature)) self.amount_memories += 1 class Memory(object): def __init__(self, age): self.age = age class FoodMemory(Memory): def __init__(self, age, species, nutritional_value): super(FoodMemory, self).__init__(age) self.species = species self.nutritional_value = nutritional_value class OffspringMemory(Memory): def __init__(self, age, agent, genetic_distance): super(OffspringMemory, self).__init__(age) self.agent = agent self.genetic_distance = genetic_distance class TerritoryLinkMemory(Memory): def __init__(self, age, territory_1, territory_2): super(TerritoryLinkMemory, self).__init__(age) self.territory_1 = territory_1 self.territory_2 = territory_2 class FoodLocationMemory(Memory): def __init__(self, age, food, territory): super(FoodLocationMemory, self).__init__(age) self.food = food self.territory = territory class HostileCreatureMemory(Memory): def __init__(self, age, creature): super(HostileCreatureMemory, self).__init__(age) self.creature = creature
CONFIG = { "main_dir": "./tests/", "results_dir": "results/", "manips_dir": "manips/", "parameters_dir": "parameters/", "tikz_dir": "tikz/" }
stack = [] while True: print("1. Insert Element in the stack") print("2. Remove element from stack") print("3. Display elements in stack") print("4. Exit") choice = int(input("Enter your Choice: ")) if choice == 1: if len(stack) == 5: print("Sorry, stack is already full") else: element = int(input("Please enter element: ")) stack.append(element) print(element, " inserted successfully") elif choice == 2: if len(stack) == 0: print("Sorry, stack is already empty") else: element = stack.pop() print(element, " was removed successfully") elif choice == 3: for i in range(len(stack)- 1, -1, -1): print(stack[i]) elif choice == 4: print("Thank You. See you later") break else: print("Invalid option") more = input("Do you want to continue?(y/n): ") if more == 'Y' or more == 'y': continue else: print("Thank You. See you later") break
#config 置信度阈值 SUPPORT_RATE_THRESHOLD = 0.4 # 判断 b 列表中是否包含 a 列表的所有元素 def containes(a,b): try: for i in a: # print("target: ",i) if b.index(i)>=0: continue # print("finded :",i," continue") return True except ValueError as e: # print("some error occured") # print(e.value) return False def apriori(Lpre,raw): # find big L rows = len(raw) bigLpre = list() print("L pre: ",Lpre) for element in Lpre: # calculate support rate count = 0 for row in raw: if containes(element,row): count += 1 sr = count/rows print("Support Rate of ",element," is : ",sr) if(sr >= SUPPORT_RATE_THRESHOLD): bigLpre.append(element) print("big L pre: ",bigLpre) # collect k+1 L k = len(bigLpre[0]) Lnext = list() if k==1: for i in range(0,len(bigLpre),1): for j in range(i+1,len(bigLpre),1): Lnext.append([bigLpre[i],bigLpre[j]]) return Lnext elif k > 1: for i in range(0,len(bigLpre),1): for j in range(i+1,len(bigLpre),1): if bigLpre[i][0:k-1] == bigLpre[j][0:k-1] and bigLpre[i][k-1] != bigLpre[j][k-1]: # 构建新项 # newelement = list(bigLpre[i]) newelement = [el for el in bigLpre[i]] newelement.append(bigLpre[j][k-1]) # print("new element: ",newelement) Lnext.append(newelement) print(Lnext) return Lnext else: return None # main def main(): datafile = open('data.txt') rawdata = list() L1 = set() for line in datafile: # 提取第一项集,并保存原始数据表 elements = [i.strip('\n') for i in line.split(' ')] rawdata.append(elements) for i in elements: L1.add(i) L1 = list(L1) L1.sort() # apriori L = apriori(L1,rawdata) print("L 2: ",L) L = apriori(L,rawdata) print("L 3: ",L) main()
# Operations on Sets ? # Consider the following set: S = {1,8,2,3} # Len(s) : Returns 4, the length of the set S = {1,8,2,3} print(len(S)) #Length of the Set # remove(8) : Updates the set S and removes 8 from S S = {1,8,2,3} S.remove(8) #Remove of the Set print(S) # pop() : Removes an arbitrary element from the set and returns the element removed. S = {1,8,2,3} print(S.pop()) # Returs the Removed Elements of the set # clear() : Empties the set S S = {1,8,2,3} print(S.clear()) #the return is clear or None # union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11} S = {1,8,2,3} print(S.union()) # intersection({8, 11}) : Returns a set which contains only items in both sets. #{8} S = {1,8,2,3} print(S.intersection())
idade = str(input("idade :")) if not idade.isnumeric(): print("oi") else: print("passou")
CHUNK_SIZE = 16 CHUNK_SIZE_PIXELS = 256 RATTLE_DELAY = 10 RATTLE_RANGE = 3
def is_std_ref(string): """ It finds whether the string has reference in itself. """ return 'Prop.' in string or 'C.N.' in string or 'Post.' in string or 'Def.' in string def std_ref_form(ref_string): """ Deletes unnecessary chars from the string. Seperates combined references. returns the refernces in a list. """ if ' corr.' in ref_string: ref_string = ref_string.replace(' corr.','') while ',' in ref_string: ref_string = ref_string.replace(', ',']#[') refs_list = ref_string.split('#') return refs_list def proposition_cleaner(lines): """ Lines is a list of strings dedicated to each propositon proof. This function should return its referenced notions in a single list of name strings. """ ref_names = [] for line in lines: for i in range(len(line)): if line[i] == '[': end_ref = line[i:].find(']') + i if is_std_ref(line[i:end_ref + 1]): #check if it has info. ref_names.extend(std_ref_form(line[i: end_ref + 1])) #put the standard refs. in the list. while '[]' in ref_names: ref_names.remove('[]') return ref_names
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ fast , slow = head, head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: s1 = head while s1 and slow: if s1 == slow: return slow s1, slow = s1.next, slow.next return True return None def run(): pass
# coding: utf-8 """ 配置公私钥 """ public_key = "" private_key = "" project_id = "" base_url = ""
def solution(string, markers): string = string.split('\n') result = '' for line in string: for character in line: if character not in markers: result += character else: result = result[:-1] break result += '\n' return result[:-1] #Alternative solution def solution(string, markers): lines = string.split('\n') for index, line in enumerate(lines): for marker in markers: if line.find(marker) != -1: line = line[:line.find(marker)] lines[index] = line.rstrip(' ') return '\n'.join(lines)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' errno.py Error Code Define Copyright: All Rights Reserved 2019-2019 History: 1 2019-07-14 Liu Yu ([email protected]) Initial Version ''' SUCCESS = 'SUCC' ERROR_SUCCESS = SUCCESS FAIL = 'FAIL' ERROR = FAIL ERROR_INVALID = 'INVALID' ERROR_UNSUPPORT = 'UNSUPPORT'
# Write a Python program to add leading zeroes to a string String = 'hello' print(String.rjust(9, '0'))
RETENTION_SQL = """ SELECT datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), reference_event.event_date) as base_interval, datediff(%(period)s, reference_event.event_date, {trunc_func}(toDateTime(event_date))) as intervals_from_base, COUNT(DISTINCT event.target) count FROM ( {returning_event_query} ) event JOIN ( {target_event_query} ) reference_event ON (event.target = reference_event.target) WHERE {trunc_func}(event.event_date) > {trunc_func}(reference_event.event_date) GROUP BY base_interval, intervals_from_base ORDER BY base_interval, intervals_from_base """ RETENTION_BREAKDOWN_SQL = """ SELECT target_event.breakdown_values AS breakdown_values, datediff( %(period)s, target_event.event_date, dateTrunc(%(period)s, toDateTime(returning_event.event_date)) ) AS intervals_from_base, COUNT(DISTINCT returning_event.target) AS count FROM ({returning_event_query}) AS returning_event JOIN ({target_event_query}) target_event ON returning_event.target = target_event.target WHERE dateTrunc(%(period)s, returning_event.event_date) > dateTrunc(%(period)s, target_event.event_date) GROUP BY breakdown_values, intervals_from_base ORDER BY breakdown_values, intervals_from_base """ REFERENCE_EVENT_SQL = """ SELECT DISTINCT {trunc_func}(e.timestamp) as event_date, pdi.person_id as person_id, e.uuid as uuid, e.event as event from events e JOIN ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id where toDateTime(e.timestamp) >= toDateTime(%(reference_start_date)s) AND toDateTime(e.timestamp) <= toDateTime(%(reference_end_date)s) AND e.team_id = %(team_id)s {target_query} {filters} """ REFERENCE_EVENT_UNIQUE_SQL = """ SELECT DISTINCT min({trunc_func}(e.timestamp)) as event_date, pdi.person_id as person_id, argMin(e.uuid, {trunc_func}(e.timestamp)) as min_uuid, argMin(e.event, {trunc_func}(e.timestamp)) as min_event from events e JOIN ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id WHERE e.team_id = %(team_id)s {target_query} {filters} GROUP BY person_id HAVING event_date >= toDateTime(%(reference_start_date)s) AND event_date <= toDateTime(%(reference_end_date)s) """ RETENTION_PEOPLE_SQL = """ SELECT DISTINCT person_id FROM events e join ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id where toDateTime(e.timestamp) >= toDateTime(%(start_date)s) AND toDateTime(e.timestamp) <= toDateTime(%(end_date)s) AND e.team_id = %(team_id)s AND person_id IN ( SELECT person_id FROM ({reference_event_query}) as persons ) {target_query} {filters} LIMIT 100 OFFSET %(offset)s """ INITIAL_INTERVAL_SQL = """ SELECT datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), event_date) event_date, count(DISTINCT target) FROM ( {reference_event_sql} ) GROUP BY event_date ORDER BY event_date """ INITIAL_BREAKDOWN_INTERVAL_SQL = """ SELECT target_event.breakdown_values AS breakdown_values, count(DISTINCT target_event.target) FROM ({reference_event_sql}) AS target_event GROUP BY breakdown_values ORDER BY breakdown_values """
def dos2unix(file_path): """This is copied from Stack Overflow pretty much as is Opens a file, converts the line endings to unix, and then overwrites the file. """ # replacement strings WINDOWS_LINE_ENDING = b'\r\n' UNIX_LINE_ENDING = b'\n' with open(file_path, 'rb') as open_file: content = open_file.read() content = content.replace(WINDOWS_LINE_ENDING, UNIX_LINE_ENDING) with open(file_path, 'wb') as open_file: open_file.write(content)
class InputMode: def __init__(self): pass def GetTitle(self): return "" def TitleHighlighted(self): return True def GetHelpText(self): return None def OnMouse(self, event): pass def OnKeyDown(self, event): pass def OnKeyUp(self, event): pass def OnModeChange(self): return True def GetTools(self, t_list, p): pass def OnRender(self): pass def GetProperties(self, p_list): pass
# -*- coding: utf-8 -*- """Generic errors for immutable data validation.""" class ImmutableDataValidationError(Exception): def __init__(self, msg: str = None, append_text: str = None): if append_text is not None: msg = "%s %s" % (msg, append_text) super().__init__(msg) class ImmutableDataValidationValueError(ImmutableDataValidationError, ValueError): pass class ImmutableDataValidationTypeError(ImmutableDataValidationError, TypeError): pass class WrappedValidationCollectionError(ImmutableDataValidationError): pass class MissingTimezoneError(ImmutableDataValidationValueError): pass class TimezoneNotUtcError(ImmutableDataValidationValueError): pass class MicrosecondsInSqlTimeError(ImmutableDataValidationValueError): pass # wrapped errors for validation_collection class WrapperValidationCollectionError(ImmutableDataValidationError): pass class ValidationCollectionEmptyValueError( ImmutableDataValidationValueError, WrapperValidationCollectionError ): pass class ValidationCollectionMinimumLengthError( ImmutableDataValidationValueError, WrapperValidationCollectionError ): pass class ValidationCollectionMaximumLengthError( ImmutableDataValidationValueError, WrapperValidationCollectionError ): pass class ValidationCollectionCannotCoerceError( ImmutableDataValidationTypeError, WrapperValidationCollectionError ): pass class ValidationCollectionNotAnIntegerError( ImmutableDataValidationValueError, WrapperValidationCollectionError ): pass class ValidationCollectionMinimumValueError( ImmutableDataValidationValueError, WrapperValidationCollectionError ): pass class ValidationCollectionMaximumValueError( ImmutableDataValidationValueError, WrapperValidationCollectionError ): pass
#!/usr/bin/env python3 """ String Objects """ def get_str(): """ Prompt user for a string """ valid_input = False while not valid_input: try: sample_str = input('>>> ') valid_input = True return sample_str except Exception as err: return 'Expected String : {0}'.format(err) if __name__ == '__main__': name = {} # Init name print('Enter Name :', end='') name['Name'] = list(get_str().strip().upper().split(' ')) print(name)
src = Split(''' hal_test.c ''') component = aos_component('hal_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
class resizable_array: def __init__(self,arraysize): self.arraysize = arraysize self.array = [None for i in range(self.arraysize)] self.temp =1 def __insert(self,value): for i in range(len(self.array)): if self.array[i] == None: self.array[i] = value break #print(self.array) #return self.array def insert_at_end(self, value): if None not in self.array : self.newsize= self.temp+len(self.array) self.newarray = [None for i in range(self.newsize)] for i in range(len(self.array)): self.newarray[i]=self.array[i] # temp contains value of i i_temp=i self.newarray[i_temp+1]=value self.array = self.newarray self.newarray = None #print(self.array) #return self.array else: self.__insert(value) def printarray(self): return self.array def insert_at_first(self, value): self.create_new_size = len(self.array)+1 self.create_new_size = ['insert' for i in range(self.create_new_size)] self.create_new_size[0] = value n = len(self.array) for i in range(1,n+1): self.create_new_size[i] = self.array[i-1] self.array = self.create_new_size self.create_new_size = None #print(self.array) #return self.array def delete_at_end(self): if len(self.array) == 0: print("Array is empty") else: self.newsize = len(self.array)-1 self.newarray = [None for i in range(self.newsize)] for i in range(len(self.array)-1): self.newarray[i] = self.array[i] self.array=self.newarray #print(self.array) #return(self.array) def delete_at_first(self): if len(self.array) == 0: print('Array is empty!') else: if len(self.array)==1: self.array =[] else: self.create_new_size = len(self.array) - 1 self.newarray = ['insert' for i in range(self.create_new_size)] n = len(self.newarray) for i in range(0,n): self.newarray[i] = self.array[i+1] self.array = self.newarray self.newarray = None #print(self.array) #return self.array def insert_at_middle(self, insertafter, insertedvalue): self.create_new_size = len(self.array) + 1 self.newarray = [None for i in range(self.create_new_size)] #3 n = len(self.array)-1 #2 if self.array[n] == insertafter: self.insert_at_end(insertedvalue) elif insertafter in self.array: for i in range(0, n): if self.array[i] == insertafter: self.newarray[i] = self.array[i] self.newarray[i + 1] = insertedvalue i = i + 2 break else: self.newarray[i] = self.array[i] for j in range(i , len(self.newarray)): self.newarray[j] = self.array[j - 1] self.array = self.newarray self.newarray = None #print(self.array) #return self.array else: print("value does not exists in Array after which you want to insert new value!") def shrink(self,value): self.create_new_size = len(self.array)-1 self.newarray = [None for i in range(self.create_new_size)] flag=False if len(self.array)==0: print("Array is empty!") else: for i in range(len(self.array)): try: if self.array[i]!=value and flag == False: self.newarray[i]=self.array[i] elif flag == True or self.array[i]==value: self.newarray[i]=self.array[i+1] flag = True else: flag=True except: pass self.array=self.newarray self.newarray=None #print(self.array) #return self.array def maximum_value(self): max=self.array[0] for i in range(len(self.array)): for j in range(len(self.array)): if max<self.array[j]: max = self.array[j] print("maximum value in array is: {}".format( max)) return max def minimum_value(self): min=self.array[0] for i in range(len(self.array)): for j in range(len(self.array)): if min>self.array[j]: min = self.array[j] print("minimum value in array is: {}".format(min)) return min ob1= resizable_array(1) print("\n---------Initial Array---------") print(ob1.printarray()) print("\n---------Insert at End---------") ob1.insert_at_end(5) ob1.insert_at_end(6) ob1.insert_at_end(7) ob1.insert_at_end(7.5) print(ob1.printarray()) print('\n---------Insert at First---------') ob1.insert_at_first(4) ob1.insert_at_first(3) ob1.insert_at_first(2) ob1.insert_at_first(1) ob1.insert_at_first(0.5) print(ob1.printarray()) print('\n---------Delete at First---------') ob1.delete_at_first() print(ob1.printarray()) print("\n---------Delete at End---------") ob1.delete_at_end() print(ob1.printarray()) print("\n---------Insert at Middle--------- ") ob1.insert_at_middle(5, 5.5) ob1.insert_at_middle(6, 6.5) ob1.insert_at_middle(7, 7.5) print(ob1.printarray()) ob1.insert_at_middle(8, 88) print("\n---------Shrink--------- ") ob1.shrink(5.5) ob1.shrink(6.5) ob1.shrink(7.5) print(ob1.printarray()) print("\n---------Maximum Value--------- ") ob1.maximum_value() print("\n---------Minimum Value--------- ") ob1.minimum_value()
qt=int(input()) for i in range(qt): jogadores=input().split() nome1=str(jogadores[0]) escolha1=str(jogadores[1]) nome2 = str(jogadores[2]) escolha2 = str(jogadores[3]) numeros=input().split() numerosJ1=int(numeros[0]) numerosJ2=int(numeros[1]) if escolha1=="PAR" and escolha2=="IMPAR": if (numerosJ1+numerosJ2)%2==0: print(nome1) else: print(nome2) if escolha1 == "IMPAR" and escolha2 == "PAR": if (numerosJ1 + numerosJ2) % 2 == 0: print(nome2) else: print(nome1)
""" """ def copy_to_home(path, file_name): """ 万物拷贝器(除了文件夹) :param path: 拷贝到的路径 :param file_name: 要拷贝的文件名称(带格式) :return: none """ with open(file_name, "rb") as file_object: home_file = open(path + file_name, "wb") while True: line = file_object.readlines(10240) if not line: break home_file.writelines(line) home_file.close()
""" Aliyun API ========== The Aliyun API is well-documented at `dev.aliyun.com <http://dev.aliyun.com/thread.php?spm=0.0.0.0.MqTmNj&fid=8>`_. Each service's API is very similar: There are regions, actions, and each action has many parameters. It is an OAuth2 API, so you need to have an ID and a secret. You can get these from the Aliyun management console. Authentication ============== You will need security credentials for your Aliyun account. You can view and create them in the `Aliyun management console <http://console.aliyun.com>`_. This library will look for credentials in the following places: 1. Environment variables `ALI_ACCESS_KEY_ID` and `ALI_SECRET_ACCESS_KEY` 2. An ini-style configuration file at `~/.aliyun.cfg` with contents like: :: [default] access_key_id=xxxxxxxxxxxxx secret_access_key=xxxxxxxxxxxxxxxxxxxxxxx .. 3. A system-wide version of that file at /etc/aliyun.cfg with similar contents. We recommend using environment variables whenever possible. Main Interfaces =============== The main components of python-aliyun are ECS and SLB. Other Aliyun products will be added as API support develops. Within each Aliyun product, we tried to implement every API Action variation available. We used a boto-style design where most API interaction is done with a connection object which marshalls Python objects and API representations. *ECS*: You can create a new ECS connection and interact with ECS like this:: import aliyun.ecs.connection conn = aliyun.ecs.connection.EcsConnection('cn-hangzhou') print conn.get_all_instance_ids() See more at :mod:`aliyun.ecs` *SLB*: Similarly for SLB, get the connection object like this:: import aliyun.slb.connection conn = aliyun.slb.connection.SlbConnection('cn-hangzhou') print conn.get_all_load_balancer_ids() See more at :mod:`aliyun.slb` *DNS*: Similarly for ECS, get the connection object like this:: import aliyun.dns.connection conn = aliyun.dns.connection.DnsConnection('cn-hangzhou') print conn.get_all_records(domainname='quixey.be') ali command =========== The ali commandline tool is mostly used for debugging the Aliyun API interactions. It accepts arbitrary Key=Value pairs and passes them on to the API after wrapping them. :: ali --region cn-hangzhou ecs Action=DescribeRegions ali --region cn-hangzhou slb Action=DescribeLoadBalancers """ __version__ = "1.1.0"
############################################################################################### # 递归遍历所有情况,直接超时;太蠢了,这种想法是想着往LED填,来凑齐满足要求的时间 ############################################################################################### class Solution: def analyze(self, string): # 0 - 3 代表 1 2 4 8 first = sum([int(string[i])*(2**i) for i in range(4)]) # 4 - 9 代表 1 2 4 8 16 32 second = sum([int(string[i])*(2**(i-4)) for i in range(4, 10)]) if first > 12 or second > 60: return [] return f"{first}:0{second}" if second < 10 else f"{first}:{second}" def readBinaryWatch(self, turnedOn: int) -> List[str]: def digLevel(level, total, timeNow): if level == total: return [self.analyze(timeNow)] res = [] for i in range(10): if timeNow[i] != 1: newTime = copy.copy(timeNow) newTime[i] = 1 res.extend(digLevel(level+1, total, newTime)) return res return digLevel(0, turnedOn, [0,0,0,0,0,0,0,0,0,0]) ############################################################################################### # 迭代遍历所有时间 ########### # 时间复杂度:O(1) # 空间复杂度:O(1) ############################################################################################### class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: ans = list() for h in range(12): for m in range(60): if bin(h).count("1") + bin(m).count("1") == turnedOn: # %2d 宽度为2 左边补空格 # %02d 宽度为2 左边补0 # %-2d 右边补空格 ans.append(f"{h}:{m:02d}") return ans ############################################################################################### # 迭代遍历所有灯开闭组合 ########### # 时间复杂度:O(1) # 空间复杂度:O(1) ############################################################################################### class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: ans = list() for i in range(1024): h, m = i >> 6, i & 0x3f # 用位运算取出高 4 位和低 6 位 if h < 12 and m < 60 and bin(i).count("1") == turnedOn: ans.append(f"{h}:{m:02d}") return ans
class VertexPaint: use_group_restrict = None use_normal = None use_spray = None
@app.post('/login') def login(response: Response): ... token = manager.create_access_token( data=dict(sub=user.email) ) manager.set_cookie(response, token) return response
print("Pass statement in Python"); for i in range (1,11,1): if(i==3): i = i + 1; pass; else: print(i); i = i + 1;
expressao = list() expressao.append(str(input("Informe uma expressão: "))) lado1 = expressao[0].count("(") lado2 = expressao[0].count(")") if lado1 == lado2: print("A expressão é valida") else: print("A expressão é invalida")
# Runtime error N = int(input()) X = list(map(int, input().split())) # Memory problem tot = sum(X) visited = [False for k in range(N)] currentStar = 0 while True: if currentStar < 0 or currentStar > N-1: break else: visited[currentStar] = True if X[currentStar] >= 1: if X[currentStar] % 2 == 0: X[currentStar] -= 1 currentStar -= 1 else: X[currentStar] -= 1 currentStar += 1 tot -= 1 else: if X[currentStar] % 2 == 0: currentStar -= 1 else: currentStar += 1 print("{0} {1}".format(sum(visited), tot))
n = int(input()) for i in range(n): dieta = list(input()) cafe = list(input()) almoco = list(input()) todos = cafe + almoco cheat = False for comido in todos: if comido in dieta: dieta.remove(comido) else: cheat = True if not cheat: print("".join(sorted(dieta))) else: print("CHEATER")
first_name = input("Enter you name") last_name = input("Enter you surname") past_year = input("MS program start year?") a = 2 + int(past_year) print(f"{first_name} {last_name} {past_year} you are graduate in {a}")
# Puzzle Input with open('Day12_Input.txt') as puzzle_input: movement_list = puzzle_input.read().split('\n') # Calculate the path facing = 1 # Way it's facing, 0 -> North, 1 -> East, 2 -> West, 3 -> South coordinates = [0, 0] # Coordinates where X-axis is facing North and Y-axis is facing East for movement in movement_list: action = movement[0] # Get the action value = int(movement[1:]) # Get it's value if action == 'N': # Execute the action, by adding or subtracting the value from the boat's current coordinates[0] += value # coordinates elif action == 'S': coordinates[0] -= value elif action == 'E': coordinates[1] += value elif action == 'W': coordinates[1] -= value elif action == 'L': # Turn the boat -> 90º is a change of 1 in it's direction facing -= value // 90 elif action == 'R': facing += value // 90 elif action == 'F': # Go in the way it's facing direction = facing % 4 if direction == 0: coordinates[0] += value elif direction == 1: coordinates[1] += value elif direction == 2: coordinates[0] -= value elif direction == 3: coordinates[1] -= value # The answer is the sum of the absolute value of the coordinates, because we started at 0, 0 print(sum(list(map(abs, coordinates))))
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] #print(class_1) class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] #print(class_2) new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses = { "Math":65, "English":70, "History":80, "French":70, "Science":60 } print(courses['Math']) print(courses['English']) print(courses['History']) print(courses['French']) print(courses['Science']) total = courses['Math'] + courses['English'] + courses['History'] + courses['French'] + courses['Science'] print(total) percentage = (total / 500) * 100 print(percentage) # Code ends here # -------------- # Code starts here mathematics = { "Geoffrey Hinton":78, "Andrew Ng":95, "Sebastian Raschka":65, "Yoshua Benjio":50, "Hilary Mason":70, "Corinna Cortes":66, "Peter Warden":75 } topper = max(mathematics,key = mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here topper = "andrew ng" topper = topper.split() first_name = topper[0] last_name = topper[1] full_name = last_name + " " + first_name certificate_name = full_name.upper() print(certificate_name) # Code ends here
#Faça uma função que informe a quantidade de dígitos de um determinado número inteiro informado def calcula_digito(numero): numero = str(numero) return len(numero) print(calcula_digito(150123123123)) print(calcula_digito(100)) print(calcula_digito(1000)) print(calcula_digito(10000))
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: if not pushed and not popped: return True aux = [] idx = 0 for _ in pushed: aux.append(_) while aux and aux[-1] == popped[idx]: aux.pop() idx += 1 return not aux
widget = WidgetDefault() widget.border = "None" commonDefaults["GroupBoxWidget"] = widget def generateGroupBoxWidget(file, screen, box, parentName): name = box.getName() file.write(" %s = leGroupBoxWidget_New();" % (name)) generateBaseWidget(file, screen, box) writeSetStringAssetName(file, name, "String", box.getStringName()) file.write(" %s->fn->addChild(%s, (leWidget*)%s);" % (parentName, parentName, name)) file.writeNewLine() def generateGroupBoxAction(text, variables, owner, event, action): name = action.targetName if action.actionID == "SetString": val = getActionArgumentValue(action, "String") writeActionFunc(text, action, "setString", [val]) else: generateWidgetAction(text, variables, owner, event, action)
# Problem Statement Link: https://www.hackerrank.com/challenges/the-minion-game/problem def minion_game(w): s = k = 0 v = ['A', 'E', 'I', 'O', 'U'] for x in range( len(w) ): if w[x] in v: k += (len(w)-x) else: s += (len(w)-x) if s == k: print("Draw") else: if s > k: print("Stuart", s) else: print("Kevin", k) if __name__ == '__main__': s = input() minion_game(s)
a = 10 print(a)
def stations_level_over_threshold(stations, tol): #2B part 2 stationList = [] for station in stations: if station.typical_range_consistent() and station.latest_level != None: if station.relative_water_level() > tol: stationList.append((station, station.relative_water_level())) sortedList = sorted(stationList, key=lambda x: x[1], reverse=True) return sortedList def stations_highest_rel_level(stations, N): stationList = list() for station in stations: if station.typical_range_consistent() and station.latest_level != None: stationList.append((station, station.relative_water_level())) sortedList = sorted(stationList, key=lambda x: x[1], reverse=True) Nslice = sortedList[0:N] return Nslice
lanches = ['X-Bacon','X-Tudo','X-Calabresa', 'CalaFrango','X-Salada','CalaFrango','X-Bacon','CalaFrango'] lanches_finais = [] print('Estamos sem CalaFrango') while 'CalaFrango' in lanches: lanches.remove('CalaFrango') while lanches: preparo = lanches.pop() print('Preparei seu lanche de {}'.format(preparo)) lanches_finais.append(preparo) print('\nOs lanches finais hoje foram:') for lanche in lanches_finais: print('\t{}'.format(lanche))
# -*- coding: utf-8 -*- # list of system groups ordered descending by rights in application groups = ['wheel', 'sudo', 'users']
def escreva(frase): a = len(frase)+2 print('~'*(a+2)) print(f' {frase}') print('~' * (a + 2)) escreva('Gustavo Guanabara') escreva('Curso de Python no YouTube') escreva('CeV')
""" Solução A solução se baseia em pegar as duas metades da string, invertelas separadamente, com a ajuda do recurdo do Python para análise de string/arrays, como o range que queremos pegar dessa string, e em qual sentido fazer a contagem. Por exemplo, [::-1], vai pegar a string inteira, porém invertida. E adicionar as duas metades invertidas à variável solução. """ # Entrada da quantidade de casos de teste n = int(input()) # Loop para os casos de teste for i in range(n): # Entrada da string a ser analisada str = input() # Ans = String final que será o resultado do caso de teste ans = "" # Contém o valor da metade do tamanho da string half = len(str) // 2 # Half_1 = String que contém a primeira metade da string a ser analisada # Half_2 = String que contém a segunda metade da string a ser analisada half_1 = str[:half] half_2 = str[half:] # Adiciona as metades invertidas à variável do resultado final # É usado o recurso do python de range das strings para facilitar a inversão. [::-1] pega a string invertida ans += half_1[::-1] ans += half_2[::-1] # Saída do resuldade do caso de teste print(ans.strip())