content
stringlengths
7
1.05M
a, b, c, d = 1, 2, 3, 4 print(a, b, c, d) a, b, c, d = d, c, b, a print(a, b, c, d)
def test_metadata(system_config) -> None: assert system_config.provider_code == "system" assert system_config._prefix == "TEST" def test_prefixize(system_config) -> None: assert system_config.prefixize("key1") == "TEST_KEY1" assert system_config.unprefixize("TEST_KEY1") == "key1" def test_get_variable(monkeypatch, system_config) -> None: monkeypatch.setenv("TEST_KEY1", "1") monkeypatch.setenv("TEST_KEY2", "2") assert system_config.get("key1") == "1" assert system_config.get("key2") == "2" monkeypatch.undo() def test_get_variables_list(monkeypatch, system_config) -> None: monkeypatch.setenv("TEST_KEY1", "1") monkeypatch.setenv("TEST_KEY2", "2") monkeypatch.setenv("TEZT_T1", "1") monkeypatch.setenv("TEZT_T2", "2") assert "key1" in system_config.keys() assert "key2" in system_config.keys() assert "t1" not in system_config.keys() assert "t2" not in system_config.keys() monkeypatch.undo()
# -- coding: utf-8 -- #セット設定 set_a = {1,2,3,1,'a',4,'a'} set_b = {2,3,5,'a',4,'a'} set_c = {2,5,'b'} #union(重複分を除いたセットを作成) print(set_a.union(set_b)) """ [出力] set(['a', 1, 2, 3, 4, 5]) """ print(set_a.union(set_b,set_c)) """ [出力] set(['a', 1, 2, 3, 4, 5, 'b']) """ #intersection(セットすべてで重複する要素のセットを作成) print(set_a.intersection(set_b)) """ [出力] set(['a', 2, 3, 4]) """ print(set_a.intersection(set_b,set_c)) """ [出力] set([2]) """ #difference(引数のセットらに存在しない要素のセットを作成) print(set_a.difference(set_b)) """ [出力] set([1]) """ print(set_b.difference(set_a)) """ [出力] set([5]) """ print(set_a.difference(set_b,set_c)) """ [出力] set([1]) """ #symmetric_difference(一方に存在しない要素のセットを作成) print(set_a.symmetric_difference(set_b)) """ [出力] set([1, 5]) """ print(set_b.symmetric_difference(set_a)) """ [出力] set([1, 5]) """ print(set_a.symmetric_difference(set_c)) """ [出力] set(['a', 1, 'b', 4, 5, 3]) """ #superset/subset(要素がすべて含まれるか) set_super = set_a.copy() set_super.add('b') print("set_super.issuperset(set_a) = {0}".format(set_super.issuperset(set_a))) """ [出力] set_super.issuperset(set_a) = True """ print("set_a.issuperset(set_super) = {0}".format(set_a.issuperset(set_super))) """ [出力] set_a.issuperset(set_super) = False """ print("set_super.issubset(set_a) = {0}".format(set_super.issubset(set_a))) """ [出力] set_super.issubset(set_a) = False """ print("set_a.issubset(set_super) = {0}".format(set_a.issubset(set_super))) """ [出力] set_a.issubset(set_super) = True """
def read_matrix(): rows_count = int(input()) matrix = [] for _ in range(rows_count): row = [int(r) for r in input().split(' ')] matrix.append(row) return matrix def get_primary_diagonal_sum(matrix): p_d_sum = 0 for i in range(len(matrix)): p_d_sum += matrix[i][i] return p_d_sum def get_secondary_diagonal_sum(matrix): s_d_sum = 0 for i in range(len(matrix)): s_d_sum += matrix[i][len(matrix) - i - 1] return s_d_sum matrix = read_matrix() primary_diagonal_sum = get_primary_diagonal_sum(matrix) secondary_diagonal_sum = get_secondary_diagonal_sum(matrix) print(abs(primary_diagonal_sum - secondary_diagonal_sum))
''' 1. The algorithm is a substitution cipher. It shifts each letter by a certain key. 2. Python Library Functions used : a) ord() : Converts a character to its equivalent ASCII value. b) chr() : Converts an ASCII value to its equivalent character. 3. What are 65 and 97? a) 65 is the ASCII value of 'A'. b) 97 is the ASCII value of 'a'. ''' # Get number equivalent of a character def get_num_equivalent(char): return ( ord(char) - 65) if char.isupper() else (ord(char) - 97) # Get character equivalent of a number def get_char_equivalent(char, num): return chr(num + 65) if char.isupper() else chr(num + 97) # Encryption Algorithm def encrypt(plain_text, key): encrypted_text = '' for char in plain_text: num_equivalent = get_num_equivalent(char) # Formula : (num_equivalent + key) mod 26 encrypted_num = (num_equivalent + key) % 26 encrypted_text += get_char_equivalent(char, encrypted_num) return encrypted_text # Decryption Algorithm def decrypt(encrypted_text, key): decrypted_text = '' for char in encrypted_text: num_equivalent = get_num_equivalent(char) # Formula : (num_equivalent - key) mod 26 decrypted_num = (num_equivalent - key) % 26 decrypted_text += get_char_equivalent(char, decrypted_num) return decrypted_text # Driver Code if __name__ == '__main__': plain_text, key = 'TheSkinnyCoder', 3 encrypted_text = encrypt(plain_text, key) decrypted_text = decrypt(encrypted_text, key) print(f'The Original Text is : {plain_text}') print(f'The Encrypted Cipher Text is : {encrypted_text}') print(f'The Decrypted Text is : {decrypted_text}')
#!/usr/bin/env python3 #!/usr/bin/python3 dict1 = { 'a': 1, 'b': 2, } dict2 = { 'a': 0, 'b': 2, } if dict1 == dict2: print("FAIL") else: print("PASS") dict1 = { 'a': { 'c': 'bake' }, 'b': 2, } dict2 = { 'a': { 'c': 'shake' }, 'b': 2, } if dict1 == dict2: print("FAIL") else: print("PASS") dict1 = { 'a': { 'c': [0, 1] }, 'b': 2, } dict2 = { 'a': { 'c': [0, 2] }, 'b': 2, } if dict1 == dict2: print("FAIL") else: print("PASS")
## Grasshopper - Summation ## 8 kyu ## https://www.codewars.com/kata/55d24f55d7dd296eb9000030 def summation(num): return sum([i for i in range(num+1)])
LEFT_ALIGNED = 0 RIGHT_ALIGNED = 1 CENTER_ALIGNED = 2 JUSTIFIED_ALIGNED = 3 NATURAL_ALIGNED = 4
score_1 = float(input('Type your 1st score: ')) score_2 = float(input('Type your 2nd score: ')) average = (score_1 + score_2) / 2 print(f'Your average is {average}, therefore you...') print('Pass. Congrats.') if average > 6 \ else print('Fail. Study again, you\'ll get it. :)')
class NoDataError(Exception): def __init__(self, field, obj, module): message = "Missing field '" + field + "' in the object " + str(obj) + " needed in " + module super(NoDataError, self).__init__(message)
""" Should specifically use: touchtechnology.common.backends.auth.UserSubclassBackend touchtechnology.common.backends.auth.EmailUserSubclassBackend """
""" ``mixin`` module. """ class ErrorsMixin(object): """Used primary by service layer to validate business rules. Requirements: - self.errors Example:: class MyService(ValidationMixin): def __init__(self, repository, errors, locale): # ... def authenticate(self, credential): if not self.factory.membership.authenticate(credentials): self.error('The username or password provided ' 'is incorrect.') return False # ... return True """ def error(self, message, name="__ERROR__"): """Add `message` to errors.""" self.errors.setdefault(name, []).append(message) class ValidationMixin(object): """Used primary by service layer to validate domain model. Requirements: - self.errors - self.translations Example:: class MyService(ValidationMixin): def __init__(self, repository, errors, translations, locale): # ... def authenticate(self, credential): if not self.validate(credential, credential_validator): return False # ... return True """ def error(self, message, name="__ERROR__"): """Add `message` to errors.""" self.errors.setdefault(name, []).append(message) def validate(self, model, validator): """Validate given `model` using `validator`.""" return validator.validate( model, self.errors, translations=self.translations["validation"] )
class Event(): def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None): self.guild_id = guild_id self.event_type = event_type self.target_id = target_id self.target_name = target_name self.actor = actor self.reason = reason self.timestamp = timestamp self.role_id = role_id self.role_name = role_name self.count = count self.message_id = message_id @classmethod def from_row(cls, row, actor=None, reason=None): return cls(row.get("guild_id"), row.get("event_type"), row.get("target_id"), row.get("target_name"), row.get("actor") if not actor else actor, row.get("reason") if not reason else reason, row.get("timestamp"), row.get("role_id"), row.get("role_name"), row.get("event_id"), row.get("message_id")) def set_actor(self, actor): self.actor = actor def set_count(self, count): self.count = count def db_insert(self): return (self.guild_id, self.event_type, self.target_id, self.target_name, self.actor if type(self.actor) == int else self.actor.id, self.reason, self.timestamp, self.role_id, self.role_name, self.count)
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda'] nintendo_games.remove('Zelda') print(nintendo_games) if 'Wario' in nintendo_games: nintendo_games.remove('Wario')
class Test: def initialize(self): self.x = 42 t = Test() t.initialize() def calc(self, n): return self.x + n Test.calc = calc assert t.calc(4) == 46
# Time: O(n) # Space: O(1) # # 123 # Say you have an array for which the ith element # is the price of a given stock on day i. # # Design an algorithm to find the maximum profit. # You may complete at most two transactions. # # Note: # You may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). # # Input: [3,3,5,0,0,3,1,4] # Output: 6 (= 3-0 + 4-1) # Input: [1,2,3,4,5] # Output: 4 try: xrange # Python 2 except NameError: xrange = range # Python 3 class Solution(object): # USE THIS: CAN EXTEND to k transactions. # @param prices, a list of integer # @return an integer def maxProfit(self, prices): hold1, hold2 = float('-inf'), float('-inf') cash1, cash2 = 0, 0 for p in prices: # to be sequential, hold[j] refers to cash[j-1], and cash[j] refers to hold[j]. # because it is ok to buy then sell in the same day, so the 4 lines # don't need to execute simultaneously (i.e. write in 1 line) hold1 = max(hold1, -p) cash1 = max(cash1, hold1+p) hold2 = max(hold2, cash1-p) cash2 = max(cash2, hold2+p) return cash2 # This solution is AN EXTENSION OF SOLUTION for buy-and-sell-stock-i, and can extend to k. # hold[i] is the balance after ith buy, cash[i] is the balance after ith sell. def maxProfit_extend(self, prices): n, k = len(prices), 2 hold = [float('-inf')] * (k + 1) # entry at index 0 is easy to calculate boundary value cash = [0] * (k + 1) for i in range(n): # because k is constant, won't benefit much by doing the following optimization: # optimization skip unnecessary large k. Need to be i+1, so when i is 0, still set hold[0]. # kamyu solution uses min(k, i//2+1) + 1, but I think for day i, we can do i transactions. #for j in range(1, min(k, i+1)+1): for j in range(1, k + 1): # to be sequential, hold[j] refers to cash[j-1], and cash[j] refers to hold[j] hold[j] = max(hold[j], cash[j-1] - prices[i]) # maximize max_buy means price at buy point needs to be as small as possible cash[j] = max(cash[j], hold[j] + prices[i]) return cash[-1] # Time: O(n) # Space: O(1) class Solution2(object): # similar to Solution 1, but track cost/profit instead of balances. # Maintain the min COST of if we just buy 1, 2, 3... stock, and the max PROFIT (balance) of if we just sell 1,2,3... stock. # In order to get the final max profit, profit1 must be as relatively large as possible to produce a small cost2, # and therefore cost2 can be as small as possible to give the final max profit2. def maxProfit(self, prices): cost1, cost2 = float("inf"), float("inf") profit1, profit2 = 0, 0 for p in prices: cost1 = min(cost1, p) # lowest price profit1 = max(profit1, p - cost1) # global max profit for 1 buy-sell transaction cost2 = min(cost2, p - profit1) # adjust the cost by reducing 1st profit profit2 = max(profit2, p - cost2) # global max profit for 1 to 2 transactions return profit2 # This solution CANNOT extend to k transactions. # Time: O(n) # Space: O(n) class Solution3(object): # @param prices, a list of integer # @return an integer # use any day as divider for 1st and 2nd stock transaction. Compare all possible division # (linear time). Ok to sell then buy at the same day, so divider is on each day (dp array # is length N), not between two days. def maxProfit(self, prices): N = len(prices) _min, maxProfitLeft, maxProfitsLeft = float("inf"), 0, [0]*N _max, maxProfitRight, maxProfitsRight = 0, 0, [0]*N for i in range(N): _min = min(_min, prices[i]) maxProfitLeft = max(maxProfitLeft, prices[i] - _min) maxProfitsLeft[i] = maxProfitLeft _max = max(_max, prices[N-1-i]) maxProfitRight = max(maxProfitRight, _max - prices[N-1-i]) maxProfitsRight[N-1-i] = maxProfitRight return max(maxProfitsLeft[i]+maxProfitsRight[i] for i in range(N)) if N else 0 print(Solution().maxProfit([1,3,2,8,4,9])) # 12 print(Solution().maxProfit([1,2,3,4,5])) # 4 print(Solution().maxProfit([3,3,5,0,0,3,1,4])) # 6
def firstDuplicateValue(array): for n in array: n = abs(n) if array[n - 1] < 0: return n array[n - 1] *= -1 return -1
#!/usr/bin/python # -*- coding: utf-8 -*- def read_gowalla_data(file_path): train_file = open(file_path, 'r') x_data = {} for i in open(file_path): line = train_file.readline() # line = line.strip('\n') if len(line) == 0: continue items = line.split("\t") user_id = items[0] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[4] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_foursquare_data(file_path): train_file = open(file_path, 'r') x_data = {} while 1: line = train_file.readline() if not line: break if len(line) == 0: continue items = line.split("\t") user_id = items[0].split("_")[1] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[1].split("_")[1] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_gtd_data(file_path): train_file = open(file_path, 'r') x_data = {} while 1: line = train_file.readline() if not line: break if len(line) == 0: continue items = line.split("\t") user_id = items[6] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[2] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_foursquare_users(): users = set() t_file = open('../foursquare/foursquare_records.txt', 'r') for i in open('../foursquare/foursquare_records.txt'): line = t_file.readline() items = line.split("\t") user_id = int(items[0].split("_")[1]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_foursquare_pois(): pois = set() t_file = open('../foursquare/foursquare_records.txt', 'r') for i in open('../foursquare/foursquare_records.txt'): line = t_file.readline() items = line.split("\t") poi_id = int(items[1].split("_")[1]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois def read_gtd_users(): users = set() t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r') for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'): line = t_file.readline() items = line.split("\t") user_id = int(items[6]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_gtd_pois(): pois = set() t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r') for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'): line = t_file.readline() items = line.split("\t") poi_id = int(items[2]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois def read_gowalla_users(): users = set() t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r') for i in open('../gowalla/sorted_indexed_final_gowalla.txt'): line = t_file.readline() items = line.split("\t") user_id = int(items[0]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_gowalla_pois(): pois = set() t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r') for i in open('../gowalla/sorted_indexed_final_gowalla.txt'): line = t_file.readline() items = line.split("\t") poi_id = int(items[4]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois
# Which environment frames do we need to keep during evaluation? # There is a set of active environments Values and frames in active environments consume memory # Memory that is used for other values and frames can be recycled # Active environments: # Environments for any functions calls currently being evaluated # Parent environments of functions named in active environments # Functions returned can be reused # max length of active frames at any given time determines how many memory we need def count_frames(f): def counted(*arg): counted.open_count += 1 if counted.max_count < counted.open_count: counted.max_count = counted.open_count result = f(*arg) counted.open_count -= 1 return result counted.open_count = 0 counted.max_count = 0 return counted @count_frames def fib(n): if n ==0 or n ==1: return n else: return fib(n-2) + fib(n-1)
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: return [[nums[j] for j in range(len(nums)) if i&2**j] for i in range(2**len(nums))]
def viralAdvertising(n): return if __name__ == '__main__': n = int(input()) viralAdvertising(n)
# This is just a demo file print("Hello world") print("this is update to my previous code")
n = int(input()) # n = 3 sum1 = 0 sum2 = 0 for i in range(1, n + 1): # print("i = ", i) if i % 2 == 0: sum1 += i else: sum2 += i if sum1 == 0: print(sum2) else: print(sum2 - sum1)
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): length = len(num) # use dict: value: index + 1 # since there is only one solution, the right value must not be duplicated dic = {} for i in xrange(0, length): val = num[i] if (target - val) in dic: return (dic[target - val], i + 1) dic[val] = i + 1 ## test code # num=[2, 7, 11, 15] # t= 26 # s = Solution() # print s.twoSum(num, t)
#Tree Size class Node: def __init__(self, data): self.data = data self.left = None self.right = None def sizeTree(node): if node is None: return 0 else: return (sizeTree(node.left) + 1 + sizeTree(node.right)) # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Size of the tree is {}".format(sizeTree(root)))
''' One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Example: pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false bla, bleble -> false ''' def is_two_chars_away(str1, str2): return (len(str1) - len(str2) >= 2) or (len(str2) - len(str1) >= 2) def number_of_needed_changes(bigger_str, smaller_str): str_counter = {} for char in bigger_str: if char in str_counter: str_counter[char] += 1 else: str_counter[char] = 1 for char in smaller_str: if char in str_counter: str_counter[char] -= 1 needed_changes = 0 for char, counter in str_counter.items(): needed_changes += counter return needed_changes def one_away(str1, str2): if is_two_chars_away(str1, str2): return False needed_changes = 0 if len(str1) >= len(str2): needed_changes = number_of_needed_changes(str1, str2) else: needed_changes = number_of_needed_changes(str2, str1) return needed_changes <= 1 data = [ ('pale', 'ple', True), ('pales', 'pale', True), ('pale', 'bale', True), ('paleabc', 'pleabc', True), ('pale', 'ble', False), ('a', 'b', True), ('', 'd', True), ('d', 'de', True), ('pale', 'pale', True), ('pale', 'ple', True), ('ple', 'pale', True), ('pale', 'bale', True), ('pale', 'bake', False), ('pale', 'pse', False), ('ples', 'pales', True), ('pale', 'pas', False), ('pas', 'pale', False), ('pale', 'pkle', True), ('pkle', 'pable', False), ('pal', 'palks', False), ('palks', 'pal', False), ('bla', 'bleble', False) ] for [test_s1, test_s2, expected] in data: actual = one_away(test_s1, test_s2) print(actual == expected)
max_n = 10**17 fibs = [ (1, 1), (2, 1), ] while fibs[-1][0] < max_n: fibs.append( (fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1]) ) print(fibs) counts = [ 1, 1 ] for i in range(2, len(fibs)): fib = fibs[i] counts.append(fib[1] + sum(counts[j] for j in range(i - 1))) print(counts) def count(n): smallest_over_index = 0 smallest_over = fibs[smallest_over_index][0] while smallest_over < n: smallest_over_index += 1 smallest_over = fibs[smallest_over_index][0] if smallest_over == n + 1: return sum(counts[i] for i in range(smallest_over_index)) if smallest_over == n: return 1 + count(n - 1) smallest_under = fibs[smallest_over_index - 1][0] return sum(counts[i] for i in range(smallest_over_index - 1)) + count(n - smallest_under) + n - smallest_under print(count(10**17) - 1)
# Declare a count_of_a function that accepts a list of strings. # It should return a list with counts of how many “a” characters appear per string. # Do NOT use list comprehension. # # EXAMPLES: # count_of_a(["alligator", "aardvark", "albatross"]) => [2, 3, 2] # count_of_a(["plywood"]) => [0] # count_of_a([]) => [] def count_of_a(strings): return list(map(lambda string: string.count("a") , strings)) print(count_of_a(["alligator", "aardvark", "albatross"])) print(count_of_a(["plywood"])) print(count_of_a([]))
class StateMachine: def __init__(self, initialState): self.currentState = initialState self.currentState.run() # Template method: def runAll(self, inputs): self.currentState = self.currentState.next_state(inputs) self.currentState.run()
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: res = [] if not matrix: return res x = y = i = 0 delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) pos = [0, 0, len(matrix[0])-1, len(matrix)-1] # 左、上、右、下。后面懒得判断推出来的。 while pos[0] <= pos[2] and pos[1] <= pos[3]: while pos[0] <= y <= pos[2] and pos[1] <= x <= pos[3]: res.append(matrix[x][y]) x, y = x+delta[i][0], y+delta[i][1] x, y = x-delta[i][0], y-delta[i][1] i = (i+1) % 4 pos[i] += sum(delta[i]) x, y = x+delta[i][0], y+delta[i][1] return res
krediler = ["Hızlı Kredi", "Maaşını Halkbank'tan alanlara özel", "Mutlu emekli ihtiyaç kredisi"] for kredi in krediler: print(kredi) for i in range(len(krediler)): print(krediler[i]) for i in range(3,10): #3 dahil 10 dahil değil print(i) for i in range(0,11,2): #0'dan başla 2'şer 2'şer arttır print(i)
def palindrome(word : str) -> int: """ Given a string, calculates the amount of palindromes that exist within that string Parameters ---------- word : str String that may contain palindrome sub-strings Returns ------- int number of palindromes in string """ word = word.lower() count = [] for i in range(len(word)): for p in range(i+1, len(word)+1): count.append(word[i : p]) t = [i for i in set(count) if len(i) > 1 and i == i[::-1]] return len(t) if __name__ == '__main__': print(palindrome('ada')) # 1 print(palindrome('eadae')) # 2 print(palindrome('ade')) # 0
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2] def pancake_sort(array): target_index = len(array)-1 while target_index > 0: max_value = array[target_index] max_index = target_index for number in range(0, target_index): if array[number] > max_value: max_value = array[number] max_index = number array = flip(array, max_index) array = flip(array, target_index) target_index -= 1 return array def flip(array, end_index): unreversed_part = array[end_index+1:] reversed_part = array[end_index::-1] return reversed_part + unreversed_part print(pancake_sort(numbers))
# Following are the basic concepts to get started with Python 3.7 """This is a sample Python multiline docstring""" # Display print("Let's get started with Python") print("Let's understand", end=" ") print("The Basic Concepts first") print("**********************************************************") # Variables # In Python, there is no need for variable type declaration # Every Python variable is an object and a variable is created the moment we first assign a value to it. # A variable name must start with a letter or the underscore character. # It cannot start with a number and can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). # Python variables are case-sensitive myAge = 30 myName = "Sam" myHeight = 1.72 # To get the type of the declared variables print(type(myAge)) print(type(myName)) print(type(myHeight)) print("**********************************************************") # Type Casting (to specify a type to a variable using constructor functions) # Adding different data types will throw error # constructs Strings from other data types myAgeInString = str(myAge) myHeightInString = str(myHeight) print("My name is: " + myName + ", my age is: " + myAgeInString + " and my height is: " + myHeightInString) # constructs integers from other data types print(int("125")) print(int(3.2)) # constructs float from other data types print(float("4.22")) print(float(22242)) print("**********************************************************") # Numeric Types myIntValue = 24 myFloatValue = 4.5433 myScientificFloatValue = 35e3 myComplexValue = 4 + 3j print(myIntValue) print(myFloatValue) print(myScientificFloatValue) print(myComplexValue) print("**********************************************************")
print("Enter the name of the file along with it's extension:-") a=str(input()) if('.py' in a): print("The extension of the file is : python") else: print("The extension of the file is not python")
# -*- coding: utf-8 -*- # (C) Wu Dong, 2018 # All rights reserved __author__ = 'Wu Dong <wudong@eastwu.cn>' __time__ = '2018/9/6 11:07'
""" `EqualizeStrings <http://community.topcoder.com/stat?c=problem_statement&pm=10933>`__ """ def solution (s, t): out = "" for i in range(len(s)): x = s[i] y = t[i] diff = abs(ord(x) - ord(y)) if diff < 26 / 2: # values are close by, use minimum out += min([x, y]) else: # values are far, wrapping always uses 'a' out += 'a' return out
# ABC167B - Easy Linear Programming def main(): # input A, B, C, K = map(int, input().split()) # compute kotae = A+(K-A)*0-(K-A-B) # output print(kotae) if __name__ == '__main__': main()
def lin(): print('-'*20) lin() def msg(m): lin() print(m) lin() msg('SISTEMA') def s(a,b): print(a+b) s(2,3) def cont(*num): for v in num: print(v,end=' ') print('\nfim') cont(2,3,7) def dobra(lst): pos = 0 while pos < len(lst): lst[pos] *= 2 pos += 1 valores = [6,4,5,8,2,7] dobra(valores) print(valores) def soma(*val): s = 0 for num in val: s += num print(s) soma(3,6,4)
inst = set() with open('tools/write_bytecode.py') as file: for line in file: if line.strip().startswith('#'): continue if '$' in line: instruction = line.split('$')[1].strip() print(instruction) inst.add(instruction.split()[0].strip().replace('32', '').replace('64', '')) # print(len(inst)) # print((inst))
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ i = j = 0 # j records number of '0' and '1', and i records number of '0' for k in range(len(input_list)): v = input_list[k] input_list[k] = 2 if v < 2: # if less than 2, assign 1 input_list[j] = 1 j += 1 if v == 0: # if equal to 0, assign 0 input_list[i] = 0 i += 1 return input_list # bucket = [0] * 3 # for i in input_list: # bucket[i] += 1 # # del input_list[:] # for i in range(3): # for j in range(bucket[i]): # input_list.append(i) # # return input_list def test_function(test_case): sorted_array = sort_012(test_case) print(sorted_array) if sorted_array == sorted(test_case): print("Pass") else: print("Fail") test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) test_function([]) # test empty input list test_function([1]) # test single value
input = """ q(X) :- p(f(X)). p(f(X)) :- r(X), q(X). q(a). r(a). """ output = """ q(X) :- p(f(X)). p(f(X)) :- r(X), q(X). q(a). r(a). """
################################################################ # compareTools.py # # Defines how nodes and edges are compared. # Usable by other packages such as smallGraph # # Author: H. Mouchere, Oct. 2013 # Copyright (c) 2013-2014 Richard Zanibbi and Harold Mouchere ################################################################ def generateListErr(ab,ba): listErr = [] if len(ab) == 0: ab = ['_'] if len(ba) == 0: ba = ['_'] for c1 in ab: for c2 in ba: listErr.append((c1,c2)) return listErr def defaultMetric(labelList1, labelList2): #new way but with 1 label per node diff = set(labelList1) ^ (set(labelList2)) # symetric diff if len(diff) == 0: return (0,[]) else: ab = diff&set(labelList1) ba = diff&set(labelList2) cost = max(len(ab),len(ba) ) return (cost,generateListErr(ab,ba)) synonym = {'X':'x','\\times':'x', 'P':'p', 'O':'o','C':'c', '\\prime':'COMMA'} def synonymMetric(labelList1, labelList2): def replace(x): if x in synonym.keys(): return synonym[x] else: return x a = map(replace, labelList1) b = map(replace, labelList2) diff = set(a) ^ (set(b)) # symetric diff if len(diff) == 0: return (0,[]) else: ab = diff&set(a) ba = diff&set(b) cost = max(len(ab),len(ba) ) return (cost,generateListErr(ab,ba)) ignoredLabelSet = set([]) selectedLabelSet = set([]) def filteredMetric(labelList1, labelList2): labelS1 = set(labelList1) - ignoredLabelSet # removing the ignored labels labelS2 = set(labelList2) - ignoredLabelSet # removing the ignored labels if len(selectedLabelSet) > 0: labelS1 &= selectedLabelSet # keep only the selected labels labelS2 &= selectedLabelSet # keep only the selected labels return defaultMetric(labelS1,labelS2) # no error if at least one symbol is OK def intersectMetric(labelList1, labelList2): #new way but with 1 label per node inter = set(labelList1) & (set(labelList2)) # symetric diff if len(inter) > 0: return (0,[]) else: ab = set(labelList1)-inter ba = set(labelList2)-inter return (1,generateListErr(ab,ba)) cmpNodes = defaultMetric cmpEdges = defaultMetric
"""Define the abstract class for similarity search service controllers""" class SearchService: """Search Service handles all controllers in the search service""" def __init__(self): pass def load_index(self): pass def load_labels(self): pass def similar_search_vectors(self): pass def refresh_index(self): pass def health_check(self): pass
# -*- coding: utf-8 -*- def main(): n = int(input()) s = list() t = list() for i in range(n): si, ti = map(str, input().split()) s.append(si) t.append(int(ti)) x = input() index = s.index(x) print(sum(t[index + 1:])) if __name__ == '__main__': main()
### Alternating Characters - Solution def alternatingCharacters(): q = int(input()) while q: s = input() del_count = 0 for i in range(len(s)-1): if s[i] == s[i+1]: del_count += 1 print(del_count) q -= 1 alternatingCharacters()
class FileWarning(Exception): def __init__(self, file, message, *args, **kwargs): file.warn(message, *args, **kwargs) super().__init__(message % args) class FileError(Exception): def __init__(self, file, message, *args, **kwargs): file.error(message, *args, **kwargs) super().__init__(message % args) class FileCritical(Exception): def __init__(self, file, message, *args, **kwargs): file.critical(message, *args, **kwargs) super().__init__(message % args)
''' 排序算法汇总: bucket sort 桶排序 插入排序 insertion: 1. insertion sort 直接插入排序 stable 2. shell sort 希尔排序/分组插入排序 unstable 选择排序 selection: 1. selection sort 简单选择排序 unstable 2. heap sort 堆排序 unstable 交换排序 swap: 1. bubble sort 冒泡排序 stable 2. quick sort 快排 unstable 归并排序 merge sort 快速排序 quick sort ''' def bucket_sort(nums): """ O(n) 桶排序 nums: List(int) """ if not nums: return [] buckets = [0] * (max(nums) - min(nums) + 1) for i in range(len(nums)): buckets[nums[i] - min(nums)] += 1 res = [] for i in range(len(buckets)): if buckets[i] != 0: res += [i + min(nums)] * buckets[i] return res def bubble_sort_base(nums): """ Bubble sort or sinking sort swapping algorithm Time complexity O(n^2) Space complexity O(1) Stable sort algorithm 冒泡法 稳定排序 """ if not nums: return [] n = len(nums) for i in range(n - 1, 0, -1): for j in range(i): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] return nums def bubble_sort(nums): """ Optimized bubble sort algorithm swapping algorithm O(n^2) Stable sort algorithm introduce a flag to monitor whether elements are getting swapped inside the loop. 引入变量监视是否发生交换 """ if not nums: return [] n = len(nums) for i in range(n - 1, 0, -1): flag = True for j in range(i): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] flag = False if flag: break return nums def selection_sort(nums): """ Selection sort O(n^2) auxiliary Space O(1) not stable: [(7), 2, 4, 5, 7, 1] ->[1, 2, 4, 5, 7, (7)] 选择排序不稳定 """ if not nums: return [] n = len(nums) for i in range(n): min_idx = i # find the index of min value for j in range(i + 1, n): if nums[j] < nums[min_idx]: min_idx = j # Swap the found minimum element with # the first element nums[i], nums[min_idx] = nums[min_idx], nums[i] return nums def insertion_sort(nums): """ insertion sort / 直接插入排序 O(n^2) auxiliary space O(1) stable 直接插入排序 稳定 """ if not nums: return [] for i in range(1, len(nums)): key = nums[i] j = i - 1 while j > -1 and key < nums[j]: nums[j + 1] = nums[j] j -= 1 nums[j + 1] = key return nums def shell_sort(nums): """ shell sort / 希尔排序 插入排序一种 O(n^2) not stable 分组插入排序 """ if not nums: return [] n = len(nums) # start with a big gap, then reduce the gap gap = n // 2 while gap: for i in range(gap, n): tmp = nums[i] j = i while j >= gap and nums[j - gap] > tmp: nums[j] = nums[j - gap] j -= gap nums[j] = tmp gap //= 2 return nums def heap_sort(nums): ''' heap sort 堆排序 time complexity of heapify is O(logn) create and build heap is O(n) overall time complexity is O(nlogn) unstable ''' if not nums: return [] n = len(nums) # build max heap for i in range(n // 2, -1, -1): heapify(nums, n, i) # one by one extract elements for i in range(n - 1, 0, -1): # swap nums[i], nums[0] = nums[0], nums[i] # buile max heap heapify(nums, i, 0) return nums def heapify(arr, n, i): ''' heapify subtree rooted at index 1 ''' largest = i l = 2 * i + 1 # left = 2 * index + 1 r = 2 * i + 2 # right = 2 * indx + 2 # print(arr) if l < n and arr[largest] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest) def merge_sort(nums): ''' merge sort 归并排序 O(nlogn) auxiliary space O(n) Divide and conquer stable 归并排序稳定 ''' if len(nums) < 2: return nums mid = len(nums) // 2 left = merge_sort(nums[:mid]) right = merge_sort(nums[mid:]) return merge(left, right) def merge(left, right): res = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: res.append(left[i]) i += 1 else: res.append(right[j]) j += 1 return res + left[i:] + right[j:] def partition(nums, low, high): i = low - 1 pivot = nums[high] for j in range(low, high): if nums[j] < pivot: i += 1 nums[i], nums[j] = nums[j], nums[i] nums[i + 1], nums[high] = nums[high], nums[i + 1] return i + 1 def quick_sort(nums, low, high): if low < high: pivot = partition(nums, low, high) quick_sort(nums, low, pivot - 1) quick_sort(nums, pivot + 1, high) if __name__ == '__main__': nums = [1, 3, 2, 4, 7, 6, 5, 8] res = {} res['bucket'] = bucket_sort(nums[:]) res['bubble_base'] = bubble_sort_base(nums[:]) res['bubble'] = bubble_sort(nums[:]) res['selection'] = selection_sort(nums[:]) res['shell'] = shell_sort(nums[:]) res['heapsort'] = heap_sort(nums[:]) res['mergesort'] = merge_sort(nums[:]) tmp = nums[:] quick_sort(tmp, 0, len(nums) - 1) res['quicksort'] = tmp for k, v in res.items(): print('{}:{}'.format(k, v))
class RenderedView(object): def __init__(self, view_file: str, data): self.view_file = view_file self.data = data
# PART 1 def game_of_cups(starting_sequence,num_of_moves,min_cup=None,max_cup=None): # create a "linked list" dict cups = { starting_sequence[i] : starting_sequence[i+1] for i in range(len(starting_sequence)-1) } cups[starting_sequence[-1]] = starting_sequence[0] # current_cup = starting_sequence[0] max_cup = max_cup or max(starting_sequence) min_cup = min_cup or min(starting_sequence) for _ in range(num_of_moves): # cups to move are 3 ones after the current cups_to_move = ( first := cups[current_cup], second := cups[first], third := cups[second] ) # selects next current cup next_current_cup = cups[third] # destination is 1 less than current # if it's in the next 3 cups, it's 1 less than that, etc. # if it gets less than min, it loops back to max destination = current_cup - 1 while destination in cups_to_move or destination<min_cup: destination -= 1 if destination<min_cup: destination = max_cup # moves 3 cups after destination # by relinking destination to 1st cup # & third cup to cup after destination cup_after_destination = cups[destination] cups[destination] = first cups[third] = cup_after_destination # relinks current cup to next current cup cups[current_cup] = next_current_cup current_cup = next_current_cup return cups def collect_result(cups_dict): output_string = "" next_cup = cups_dict[1] while next_cup!=1: output_string += str(next_cup) next_cup = cups_dict[next_cup] return output_string # PART 2 def hyper_game_of_cups(starting_sequence): min_cup = min(starting_sequence) max_cup = max(starting_sequence) filled_starting_sequence = starting_sequence + list(range(max_cup+1,1_000_000+1)) return game_of_cups(filled_starting_sequence,10_000_000,min_cup,1_000_000) def hyper_collect_result(cups_dict): first = cups_dict[1] second = cups_dict[first] return first * second
txt = 'asdf;lkajsdf,as;lfkja' for i in txt: txt = txt[1:] if i == ",": break print(txt)
class HashTable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key self.data[hashvalue] = data else: if self.slots[hashvalue] == key: self.data[hashvalue] = data # replace else: nextslot = self.rehash(hashvalue, len(self.slots)) while self.slots[nextslot] != None and self.slots[nextslot] != key: naxtslot = self.rehash(hashvalue, len(self.slots)) if self.slots[nextslot] == None: self.slots[nextslot] = key self.data[nextslot] = data else: self.data[nextslot] = data #replace def hashfunction(self, key, size): return key%size def rehash(self, oldhash, size): return (oldhash+1)%size def get(self, key): startslot = self.hashfunction(key, len(self.slots)) found = False stop = False data = None while self.slots[startslot] != None and not found and not stop: if self.slots[startslot] == key: found = True data = self.data[startslot] else: position = self.rehash(startslot, len(self.size)) if self.slots[startslot] == self.slots[position]: stop = True return data def __getitem__(self, key): return self.get(key) def __setitem__(self, key, data): return self.put(key, data) if __name__ == "__main__": H = HashTable() H[12] = 'Dasha' print(H[12], 'H') print(H)
description = 'Email and SMS notifiers' group = 'lowlevel' devices = dict( email = device('nicos.devices.notifiers.Mailer', mailserver = 'mailhost.frm2.tum.de', sender = 'kws1@frm2.tum.de', copies = [ ('g.brandl@fz-juelich.de', 'all'), ('a.feoktystov@fz-juelich.de', 'all'), ('h.frielinghaus@fz-juelich.de', 'all'), ('z.mahhouti@fz-juelich.de', 'all'), ], subject = '[KWS-1]', ), smser = device('nicos.devices.notifiers.SMSer', server = 'triton.admin.frm2', receivers = [], ), )
print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) if height > 120: print("you can ride the rollercoaster!") age = int(input("What is your age? ")) if age <= 18: print("$7") else: print("$12") else: print("no")
# "Config.py" # - config file for ConfigGUI.py # This is Python, therefore this is a comment # NOTE: variable names cannot start with '__' ECGColumn = True HRColumn = False PeakColumn = True RRColumn = True SeparateECGFile = True TCP_Host = "localhost" TCP_Port = 1000 TCPtimeout = 3 TimeColumn = True UDPConnectTimeout = 1 UDPReceiveTimeout = 5 UDP_ClientIP = "localhost" UDP_ClientPort = 1001 UDP_ServerIP = "localhost" UDP_ServerPort = 1003 UDPtimeout = 1 askConfirm = False askSend = False clientAskConfirm = False debugPrinter = True debugRepetitions = False debugRun = False filePath = "F:/Project/mwilson/Code/ECG_soft/RTHRV_Faros/LSL_tests/WILMA_Rest3_Game3_Rest3_run64_2016_05_26__14_54_45_#ECG.txt" hexDebugPrinter = False ignoreTCP = True liveWindowTime = 3 noNetwork = True noPlot = False plot_rate = 10 procWindowTime = 3 processing_rate = 5 rate = 64 recDebugPrinter = False runName = "WILMA" simpleSTOP = False valDebugPrinter = True writeOutput = True write_header = True write_type = "txt"
''' Exercise 1: Write a Python function display_dico(dico) that takes a dictionary as parameter and print the content of the dictionary, one paired element per line as follow: Key --> Value For example: >>> display_dico({“un”:1, “deux”:2, “trois”:3}) un --> 1 deux --> 2 trois --> 3 Note: if the order in which the mapped pairs of a dictionary appear differs from the one shown in the example, your solution is still valid. ''' def display_dico(dico): for x in dico: print(f"{x} --> {dico[x]}") x = {'un':1, 'deux':2, 'trois':3} display_dico(x)
""" Names scores Using problem_22.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? Answer: 871198282 obs: articles that helped me out: * http://stackoverflow.com/a/5545284/7092954 """ def order(letter): """Given letter, returns it alphabetic index""" return ord(str.lower(letter))-96 def names_scores(names): """Given a list of names, sorted it into alphabetical order then calculates \ alphabetical value for eache name by multiplying this value by its alphabetical \ postion int the list to obtain a name score""" # pylint: disable=line-too-long return sum([sum(list(map(order, list(value))))*(index+1) for index, value in enumerate(sorted(names))]) with open('./input/problem_22.txt', 'r') as file: NAMES = file.read().replace("\"", '').split(',') print(names_scores(NAMES))
class Dictionary(object): def __init__(self): self.my_dict = {} def look(self, key): return self.my_dict.get(key, "Can't find entry for {}".format(key)) def newentry(self, key, value): """ new_entry == PEP8 (forced by Codewars) """ self.my_dict[key] = value
hidden_dim = 128 dilation = [1,2,4,8,16,32,64,128,256,512] sample_rate = 16000 timestep = 6080 is_training = True use_mulaw = True batch_size = 1 num_epochs = 10000 save_dir = './logdir' test_data = 'test.wav'
#! /root/anaconda3/bin/python score = 88 result = '及格了' if score >= 60 else '没及格了' print(result) a = 7 b = 1 print('a > b' if a > b else ('a < b' if a < b else 'a == b'))
# This file provides an object for version numbers. class Version: def __init__(self, major: int, minor: int=0, patch: int=0, tag: str=""): self.major = major self.minor = minor self.patch = patch self.tag = tag def __repr__(self): return "Version(" + str(self.major) + ", " + str(self.minor) + ", " + str(self.patch) + ", \"" + self.tag + "\")" def __str__(self): return str(self.major) + "." + str(self.minor) + (("." + str(self.patch)) if ((self.patch != 0) or self.tag != "") else "") + (self.tag if (self.tag != "") else "") def __len__(self): if self.tag == "": if self.patch == 0: if self.minor == 0: return 1 else: return 2 else: return 3 else: return 4 def __int__(self): return self.major #def __float__(self): # return self.major + (self.minor / (10 ** len(self.minor))) def __eq__(self, o): if type(o) == str: if len(o.split(".")) == 3: try: return ((int(o.split(".")[0]) == self.major) and (int(o.split(".")[1]) == self.minor) and (int(o.split(".")[2]) == self.patch)) except ValueError: return NotImplemented except: raise elif len(o.split(".")) == 2: try: return ((int(o.split(".")[0]) == self.major) and (int(o.split(".")[1]) == self.minor)) except ValueError: return NotImplemented except: raise elif len(o.split(".")) == 1: try: return (int(o.split(".")[0]) == self.major) except ValueError: return NotImplemented except: raise else: return NotImplemented elif type(o) == int: if (self.minor == 0) and (self.patch == 0): return (self.major == o) else: return NotImplemented elif type(o) == float: if (self.patch == 0): return (float(self) == o) else: return NotImplemented elif type(o) == Version: return (self.major == o.major) and (self.minor == o.minor) and (self.patch == o.patch) else: return NotImplemented def __lt__(self, o): if type(o) == str: if len(o.split(".")) == 1: try: return (int(o.split(".")[0]) < self.major) except ValueError: return NotImplemented except: raise else: return NotImplemented elif type(o) == int: if (self.minor == 0) and (self.patch == 0): return (self.major < o) else: return NotImplemented elif type(o) == Version: if (self.major < o.major): return True elif (self.major == o.major): if (self.minor < o.minor): return True elif (self.minor == o.minor): if (self.patch < o.patch): return True else: return False else: return False else: return False else: return NotImplemented def __le__(self, o): hold = (self < o) hold2 = (self == o) if (hold == NotImplemented) or (hold2 == NotImplemented): return NotImplemented else: return (hold or hold2) def __gt__(self, o): hold = (self <= o) if hold == NotImplemented: return NotImplemented else: return not hold def __ge__(self, o): hold = (self < o) if hold == NotImplemented: return NotImplemented else: return not hold def __iter__(self): if self.tag == "": for i in (self.major, self.minor, self.patch): yield i else: for i in (self.major, self.minor, self.patch, self.tag): yield i def asdict(self): return {"major": self.major, "minor": self.minor, "patch": self.patch, "tag": self.tag} __version__ = Version(1, 1, 1)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: self.result = [] self.wft([root]) return self.result def wft(self, nodes): newNodes = [] values = [] for n in nodes: if n is not None: values.append(n.val) newNodes += [n.left, n.right] if len(values) != 0: self.result = [values] + self.result self.wft(newNodes)
class airQuality: def __init__(self, bus): self.iaq = 0 self.bus = bus self.address = 0x5A self.datablock = 9 self.data = 0 def read(self): data = self.bus.read_i2c_block_data(self.address, 0x00, self.datablock) #WIP # Convert the data #if( eco2 !=0 ) *eco2 = (buf[0]<<8) + (buf[1]<<0); #if( stat !=0 ) *stat = ( num==IAQCORE_SIZE ? 0 : IAQCORE_STAT_I2CERR ) + (buf[2]<<0); // Add I2C status to chip status #if( resist!=0 ) *resist= ((uint32_t)buf[3]<<24) + ((uint32_t)buf[4]<<16) + ((uint32_t)buf[5]<<8) + ((uint32_t)buf[6]<<0); #if( etvoc !=0 ) *etvoc = (buf[7]<<8) + (buf[8]<<0); # Output data to screen #Print values, interpret as datasheet #Based on maarten's ESP project #https://github.com/maarten-pennings/iAQcore/blob/master/src/iAQcore.cpp
#You are given a list of n-1 integers and these integers are in the range of 1 to n. #There are no duplicates in the list. #One of the integers is missing in the list. Write an efficient code to find the missing integer ar=[ 1, 2, 4, 5, 6 ] def missing_(a): print("l",l) for i in range(1,l+2): if(i not in a): return(i) print(missing_(ar))
class Utils(): """ This is just methods stored as methods of a class. It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy. (It is nice, as in this case, to separate constants from methods.) """ def __init__(self): self.species = {'canines' : ['Doggy', 'Hyena'], 'felines' : ['Cheetah', 'Panther'], 'bugs' : ['Nullpointer']} def inputs(self): return None def output(self): return None def build(self): pass def list_animals(self, kind): return self.species[kind]
print('Enter a text and when finished press Enter twice: ') text = '' while True: line = input() if line: text += line + '\n ' else: break def wc(text): n_words = len(text.split(' ')) - 1 n_lines = len(text.split('\n')) - 1 n_characters = len(text) - 2*n_lines print(f'Characters in text - {n_characters}') print(f'Words in text - {n_words}') print(f'Lines in text - {n_lines}') wc(text)
nota1 = int(input('Nota 1: ')) nota2 = int(input('Nota 2: ')) media = (nota1 + nota2) / 2 print('Média: {:.2f}'.format(media))
def sample_anchors_pre(df, n_samples= 256, neg_ratio= 0.5): ''' Sample total of n samples across both BG and FG classes. If one of the classes have less samples than n/2, we will sample from majority class to make up for short. Args: df with column named labels_anchors, containing 1 for foreground and 0 for background n_samples: number of samples to take in total. default 256, so 128 BG and 128 FG. neg_ratio: 1/2 ''' n_fg = int((1-neg_ratio) * n_samples) n_bg = int(neg_ratio * n_samples) fg_list = [x for x in df['labels_anchors'] if x == 1] bg_list = [x for x in df['labels_anchors'] if x == 0] # check if we have excessive positive samples if len(fg_list) > n_fg: # mark excessive samples as -1 (ignore) ignore_index = fg_list[n_bg:] df.loc[ignore_index, "labels_anchors"] = -1 # sample background examples if we don't have enough positive examples to match the anchor batch size if len(fg_list) < n_fg: diff = n_fg - len(fg_list) # add remaining to background examples n_bg += diff # check if we have excessive background samples if len(bg_list) > n_bg: # mark excessive samples as -1 (ignore) ignore_index = fg_list[n_bg:] df.loc[ignore_index, "labels_anchors"] = -1
ansOut = [] coin = [10, 50, 100, 500] while True: price = int(input()) if price == 0: break cash = list(map(int, input().split())) sumCash = sum(c * n for c, n in zip(coin, cash)) change = sumCash - price changeCoins = [(change % 50) // 10, (change % 100) // 50, (change % 500) // 100, change // 500] out = [] for i in range(4): if cash[i] > changeCoins[i]: out.append('{} {}'.format(coin[i], cash[i] - changeCoins[i])) ansOut.append('\n'.join(out)) print('\n\n'.join(ansOut))
# Desenvolva um programa que leia o comprimento de 3 reretas e diga se # elas podem ou nao formar um triângulo l1 = float(input("Diga o primeiro lado")) l2 = float(input("Diga o segundo lado")) l3 = float(input("Diga o terceiro lado")) if (l1 + l2 < l3) or (l1 + l3 < l2) or (l1 > l2 + l3): print("Não é triângulo") else: print("É triângulo")
def isBalanced(expr): if len(expr)%2!=0: return False opening=set('([{') match=set([ ('(',')'), ('[',']'), ('{','}') ]) stack=[] for char in expr: if char in opening: stack.append(char) else: if len(stack)==0: return False lastOpen=stack.pop() if (lastOpen, char) not in match: return False return len(stack)==0
class Solution: def mySqrt(self, x: int) -> int: left, right = 0, x while left <= right: mid = left + (right - left) // 2 square = mid ** 2 if square <= x: left = mid + 1 elif square > x : right = mid -1 return left-1 # n : the number of input value ## Time Complexity: O( log n ) # # The overhead in time is the upper-bound of binary search, which is of O( log n ). ## Space Complexity: O( 1 ) # # The overhead in space is the variable for mathematical computation, which is of O( 1 ) def test_bench(): test_data = [0, 1, 80, 63, 48 ] # expected output: ''' 0 1 8 7 6 ''' for n in test_data: print( Solution().mySqrt(n) ) return if __name__ == '__main__': test_bench()
In [18]: my_list = [27, "11-13-2017", 84.98, 5] In [19]: store27 = salesReceipt._make(my_list) In [20]: print(store27) salesReceipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2022/1/8 8:01 下午 # @Author: zhoumengjie # @File : BondBuilder.py class BondPage: def __init__(self): # 申购评测 self.apply_bonds = [] # 证监会核准/同意注册 self.next_bonds = [] # 已申购完,即将上市的 self.ipo_bonds = [] # 隔日上市 self.prepare_bonds = [] # 即将申购 self.applying_bonds = [] # 今天上市的 self.today_bonds = [] # 中签结果 self.draw_bonds = [] # 发审委通过 self.pass_bonds = [] class CompanyInfo: def __init__(self, data): #公司名称 self.gsmc = data['jbzl']['gsmc'] #英文名称 self.ywmc = data['jbzl']['ywmc'] #曾用名 self.cym = data['jbzl']['cym'] #A股代码 self.agdm = data['jbzl']['agdm'] #A股简称 self.agjc = data['jbzl']['agjc'] #B股代码 self.bgdm = data['jbzl']['bgdm'] #B股简称 self.bgjc = data['jbzl']['bgjc'] #H股代码 self.hgdm = data['jbzl']['hgdm'] #H股简称 self.hgjc = data['jbzl']['hgjc'] #所属市场 self.ssjys = data['jbzl']['ssjys'] #所属行业 self.sszjhhy = data['jbzl']['sszjhhy'] #法人代表 self.frdb = data['jbzl']['frdb'] #注册资金 self.zczb = data['jbzl']['zczb'] #成立日期 self.clrq = data['fxxg']['clrq'] #上市日期 self.ssrq = data['fxxg']['ssrq'] #注册地址 self.zcdz = data['jbzl']['zcdz'] #经营范围 self.jyfw = data['jbzl']['jyfw'] #公司简介 self.gsjj = data['jbzl']['gsjj'] class BondInfo: def __init__(self, row): self.stock_code = row.get('stock_id', '-') self.bond_code = row.get('bond_id', '-') self.bond_name = row.get('bond_nm', '-') self.stock_name = row.get('stock_nm', '-') # 总金额 数字 self.amount = row.get('amount', '-') # 评级 self.grade = row.get('rating_cd', '-') # 正股价 数字 self.price = row.get('price', '-') # 转股价 数字 self.convert_price = row.get('convert_price', '-') # 股东配售率 字符串 62.100 self.ration_rt = row.get('ration_rt', '-') # 正股现价比转股价 字符串 97.11 self.pma_rt = row.get('pma_rt', '-') # 正股pb 数字 self.pb = row.get('pb', '-') # 百元股票含权 数字 self.cb_amount = row.get('cb_amount', '-') # 每股配售(元) 数字 self.ration = row.get('ration', '-') # 配送10张所需股数 数字 self.apply10 = row.get('apply10', '-') # 股权登记日 字符 self.record_dt = row.get('record_dt', '-') # 网上规模 字符 self.online_amount = row.get('online_amount', '-') # 中签率 字符 "0.0238" self.lucky_draw_rt = row.get('lucky_draw_rt', '-') # 单帐户中签(顶格) 字符 0.2377 self.single_draw = row.get('single_draw', '-') # 申购户数 数字 self.valid_apply = row.get('valid_apply', '-') # 申购日期 字符 self.apply_date = row.get('apply_date', '-') # 方案进展 字符 发行流程:董事会预案 → 股东大会批准 → 证监会受理 → 发审委通过 → 证监会核准/同意注册 → 发行公告 self.progress_nm = row.get('progress_nm', '-') # 进展日期 yyyy-MM-dd self.progress_dt = row.get('progress_dt', '-') # 上市日期 self.list_date = row.get('list_date', '-') # 申购标志:E:已申购待上市已排期、D:已上市、B:待申购、C:已申购未有上市排期、N:证监会核准/同意注册 self.ap_flag = row.get('ap_flag', '-') class BondData: def __init__(self, row): self.stock_code = row.get('stock_id', '-') self.bond_code = row.get('bond_id', '-') self.bond_name = row.get('bond_nm', '-') self.stock_name = row.get('stock_nm', '-') # 涨跌幅 数字 -1.98 self.increase_rt = row.get('increase_rt', '-') # 正股价 数字 self.sprice = row.get('sprice', '-') # 现价 数字 self.price = row.get('price', '-') # 正股涨跌 数字 -3.03 self.sincrease_rt = row.get('sincrease_rt', '-') # 正股pb 数字 self.pb = row.get('pb', '-') # 转股价 数字 self.convert_price = row.get('convert_price', '-') # 转股价值 数字 self.convert_value = row.get('convert_value', '-') # 溢价率 数字 18.41 self.premium_rt = row.get('premium_rt', '-') # 评级 self.grade = row.get('rating_cd', '-') # 回售触发价 数字 self.put_convert_price = row.get('put_convert_price', '-') # 强赎触发价 数字 self.force_redeem_price = row.get('force_redeem_price', '-') # 转债占比 self.convert_amt_ratio = row.get('convert_amt_ratio', '-') # 到期时间 self.short_maturity_dt = row.get('short_maturity_dt', '-') # 剩余年限 数字 self.year_left = row.get('year_left', '-') # 剩余规模 数字 self.curr_iss_amt = row.get('curr_iss_amt', '-') # 剩余年限 数字 self.year_left = row.get('year_left', '-') # 成交额 数字 self.volume = row.get('volume', '-') # 换手率 数字 self.turnover_rt = row.get('turnover_rt', '-') # 到期税前收益 数字 self.ytm_rt = row.get('ytm_rt', '-') # 双低 数字 self.dblow = row.get('dblow', '-') class ForceBondInfo: def __init__(self, row): self.stock_code = row.get('stock_id', '-') self.bond_code = row.get('bond_id', '-') self.bond_name = row.get('bond_nm', '-') self.stock_name = row.get('stock_nm', '-') # 债券价 字符 "355.000" self.price = row.get('price', '-') # 最后交易日 字符 self.redeem_dt = row.get('redeem_dt', '-') # 简介 字符 "最后交易日:2022年1月27日\r\n最后转股日:2022年1月27日\r\n赎回价:100.21元/张" self.force_redeem = row.get('force_redeem', '-') # 转股起始日 字符 self.convert_dt = row.get('convert_dt', '-') # 剩余规模 字符 "355.00" self.curr_iss_amt = row.get('curr_iss_amt', '-') # 强赎触发价 字符 "355.00" self.force_redeem_price = row.get('force_redeem_price', '-') # 规模 字符 "355.000" self.orig_iss_amt = row.get('orig_iss_amt', '-') # 强赎价 字符 "355.000" self.real_force_redeem_price = row.get('real_force_redeem_price', '-') # 强赎标志 字符 "Y" N self.redeem_flag = row.get('redeem_flag', '-') # 没懂~~ 字符 "355.00" self.redeem_price = row.get('redeem_price', '-') # 强赎触发比 字符 "355%" self.redeem_price_ratio = row.get('redeem_price_ratio', '-') # 强赎条款 字符 self.redeem_tc = row.get('redeem_tc', '-') # 正股价 字符 "34.45" self.sprice = row.get('sprice', '-') # 剩余天数 数字 self.redeem_count_days = row.get('redeem_count_days', '-') # 总天数 数字 self.redeem_real_days = row.get('redeem_real_days', '-') # R=已要强赎、O=公告要强赎、G=公告不强赎 self.redeem_icon = row.get('redeem_icon', '-')
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []} def dfs_topsort(graph): # recursive dfs with L = [] # additional list for order of nodes color = { u : "white" for u in graph } found_cycle = [False] for u in graph: if color[u] == "white": dfs_visit(graph, u, color, L, found_cycle) if found_cycle[0]: break if found_cycle[0]: # if there is a cycle, L = [] # then return an empty list L.reverse() # reverse the list return L # L contains the topological sort def dfs_visit(graph, u, color, L, found_cycle): if found_cycle[0]: return color[u] = "gray" for v in graph[u]: if color[v] == "gray": found_cycle[0] = True return if color[v] == "white": dfs_visit(graph, v, color, L, found_cycle) color[u] = "black" # when we're done with u, L.append(u) # add u to list (reverse it later!) def has_hamiltonian(adj_list): graph_sorted = dfs_topsort(adj_list) print(graph_sorted) for i in range(0, len(graph_sorted) - 1): cur_node = graph_sorted[i] next_node = graph_sorted[i + 1] if next_node not in adj_list[cur_node]: return False return True print(has_hamiltonian(adj_list_moo))
#!/usr/bin/env python3 flags = ['QCTF{e51f2dad87875d76fb081f2b467535ef}', 'QCTF{c89a4b8b181ea0e7666dc8bf93b34779}', 'QCTF{50b59ef5ba8ca7650323b96119507a98}', 'QCTF{fb1c1b7f76e5ca22411fcee3d024ff46}', 'QCTF{4909e8138219a1f5f166e6e06e057cbc}', 'QCTF{649d0b63d4bd82a9af7af03ba46838d3}', 'QCTF{af043650dc65acce4e001425bacbd3f2}', 'QCTF{8e4225e08e6ec2ec1808b6212e8fd813}', 'QCTF{31b1951f567876b0ad957c250402e3e2}', 'QCTF{959f2b0d3fcd298adc4c63fed56c1c5b}', 'QCTF{3a05bfaa08b653a8b9fc085ebd089f62}', 'QCTF{20d739e7472dcf27e77ffb4be40fd3e5}', 'QCTF{eb35b55b59653643a2e625d8826bc84b}', 'QCTF{311e4b1943c17659b9ded0a3e0f57b2b}', 'QCTF{040eaadc3df6ae0ecb33a404f8e03453}', 'QCTF{84801c28a6619841c425f4c13b867a32}', 'QCTF{ab56c77c46c40354e2f38559c034f348}', 'QCTF{f1f9e7257150d40ce3f481aa44517757}', 'QCTF{9d45092f74d5e74772c9e08a7c25690f}', 'QCTF{f0310ec009bdf2c487d7c149b767078b}', 'QCTF{00bc89904ed8ebffc430ca0f64a0467c}', 'QCTF{7984fbee8ea7d5f0e07c36803e2aacc5}', 'QCTF{0088ba127fb34ffa22023757734ad619}', 'QCTF{97589ca529c64e79a73824e9335c3905}', 'QCTF{30dfe9e4228863f2e9c45508753a9c84}', 'QCTF{a12aa8fdacf39cdf8d031ebb1141ade5}', 'QCTF{3114013f1aea003dc644cd686be073f7}', 'QCTF{c959542546b08485d4c76c6df9034c32}', 'QCTF{4fa407b4fe6f3be4afec15c10e5b60b5}', 'QCTF{b8bac3402e1ae6e42353eb0dbb6e1187}', 'QCTF{71ea738f80df88fe27c7952ee0a08fe9}', 'QCTF{52ef2660af4c18564e75e0421e7be56e}', 'QCTF{41088927caebd4c35d6a5c8c45876ae5}', 'QCTF{90afac1d3e10fa71d8d554c6584cc157}', 'QCTF{6c4f93cd891d991a5f6d21baee73b1a8}', 'QCTF{2fb6f9546cd09b2406f9b9aa0045b4b7}', 'QCTF{1aa150bac71e54372ca54ca412c11f40}', 'QCTF{e0a712bf6d89c9871e833bd936aac979}', 'QCTF{de50d0d2811dd9cb41a633a2f250b680}', 'QCTF{0bb67bdba8a748ddd1968ac66cf5c075}', 'QCTF{661133e4774d75ab7534f967dfe1b78c}', 'QCTF{7edf018896320cf9599a5c13fb3af3a8}', 'QCTF{c976ef4b78ae682d4b854a04f620fb0f}', 'QCTF{4b5436f5f3d9ac23473d4dca41a4dd63}', 'QCTF{d1947ab453f3922436adda4a6716d409}', 'QCTF{162ac50561fae2f9cd40c36e09e24705}', 'QCTF{80fca1b74687d4c0b11313dcf040bbf6}', 'QCTF{f65e11eddbf3cad560ebd96ba4f92461}', 'QCTF{c3b916d43e70181a655b4463ef945661}', 'QCTF{e19df794949bd9d80eef3cb4172dea31}', 'QCTF{a3a759941a10450905b0852b003a82c7}', 'QCTF{533705986a35606e97807ee37ab2c863}', 'QCTF{8aef26a1028de761735a39b27752b9c4}', 'QCTF{70926ffcaf4ff487d0d99fbdf0c78834}', 'QCTF{530cfc0e08a756dcf0f90c2d67c33b40}', 'QCTF{96a2c9e6ca7d6668399c6985d5d2458c}', 'QCTF{6a256384fb72333455da5b04d8495fbe}', 'QCTF{633febe4ec366bc11da19dff3e931521}', 'QCTF{66d6674fec3c7a14cf5c3af6cd467b8e}', 'QCTF{29bfba8ec4e44a5cc33fd099bdb0316b}', 'QCTF{45f3d7645b685042e7e68ad0d309fcec}', 'QCTF{94afe993a0028625d2a22de5c88293e1}', 'QCTF{d272dc01edf11d10730a64cd22827335}', 'QCTF{623cd04ddaccfc4a0d1523bc27bc32ae}', 'QCTF{bf6a6af3f83259e2f66d9b3fce376dce}', 'QCTF{91c134d6a9cd7699ec3a3b5f85a583f0}', 'QCTF{6c85e3fb56c89d62d5fe9e3d27e4a5aa}', 'QCTF{7e4164b2bb4afa5c25682bc4a8c53e66}', 'QCTF{5bc3631a6896269fe77c6bdaf9d27c78}', 'QCTF{6e1b9877716685cac3d549e865a7c85b}', 'QCTF{28fd1487a42cd3e45c98f9876e3c6728}', 'QCTF{6805c31e2276a8daa8826852ca2b0b83}', 'QCTF{2b121dafdfb150cd369e8720b59d82f7}', 'QCTF{ec31421b9f66116a02ca6b773c993358}', 'QCTF{558186ebec8b8653bb18933d198c3ece}', 'QCTF{267b5a5f8bb98b7342148c6106eb2d2c}', 'QCTF{aa38fe9f4141311d709346ead027b507}', 'QCTF{f66f66413048d100ee15c570ac585b13}', 'QCTF{7491e7cd71d16bc2446f3bcf0c92ad2d}', 'QCTF{054c7ac021fbe87042832f8c7bad3a43}', 'QCTF{0fb5425a7fcce56802da00e476347823}', 'QCTF{5299eb9d08eee8fb3f864b999806e88e}', 'QCTF{44c0b9528001db285e167339f84c7e2d}', 'QCTF{397f79c2fedb5281d5ee6662091cbf32}', 'QCTF{741bc53922594cd54deba4c2da166ba5}', 'QCTF{21e2d583596bccdafec4644614841a30}', 'QCTF{61117cdba7b47d2b0b782ebb887b37c9}', 'QCTF{690e749a4c3cc43ca6e9568e48a85f34}', 'QCTF{cf6152c25f81266612090ac7698c10cc}', 'QCTF{56133fb27d94c097e448cd6c54604241}', 'QCTF{9ada31f4d1ee3665867ac40cd576547f}', 'QCTF{fc726ff171101080f64f0a2b06f62264}', 'QCTF{d7dad3c2d7da424d112e3f5685bc3a84}', 'QCTF{71d3e6428dcfc74e4002ed3ad26ed639}', 'QCTF{a0122c5fb3937c487285d0e3051d2d32}', 'QCTF{d456e533f3e963940f17adeb2a898c1f}', 'QCTF{fda977c62519b775fd52b33b7ee3c59d}', 'QCTF{85bb44511da219a6f20706dc232a5036}', 'QCTF{67a79a883ba2bf8eb1905817db7c5455}', 'QCTF{e86fbd286f9a5e507f977fce01d8f546}', 'QCTF{2df725e5277ae0cda2e1b62c670200bb}', 'QCTF{04249a31c87f0bbba3c5d658f8534424}', 'QCTF{9a28f64f49d9e0e3cbd4b9be7d70c389}', 'QCTF{842bb11fa6d69059b8c151a54c2c97f5}', 'QCTF{d426e9a1daa917b243579c1f8fdf8388}', 'QCTF{b8bbd65882ce11f20637d2d66e69c605}', 'QCTF{06756225de4f362c80ecf2aa11e1cf3b}', 'QCTF{0848575c514d3b762f06a8e93dabf370}', 'QCTF{4e9c1a7d8e588a65ef640fed086f417f}', 'QCTF{a52e79bcba9b01a7a07f24b226c12848}', 'QCTF{3d18d085b0e51c6a02daaed5a759930f}', 'QCTF{779194626871433c31f7812157d3b8cb}', 'QCTF{3c3c5107ed05970963fa016b6d6be7eb}', 'QCTF{aa05136c8c46d67cdfc69f47d18aa51b}', 'QCTF{1e85348d600b9019b216f2515beb0945}', 'QCTF{0349bdc14f7ff8b7052c9eb4db1e5a21}', 'QCTF{30dcbb8b9c67edacb4bbed10cb07cc07}', 'QCTF{5b09db09bfaf3a02dc17bfd8771bae8f}', 'QCTF{6e7d07f9c31357ed68590bc24a2ece08}', 'QCTF{d46e9b29270c59845095d97ef9337e95}', 'QCTF{ec118d128f18ca77e0c67d7e66409a7f}', 'QCTF{626af7a6c7005d23b960a02ce128273c}', 'QCTF{05d11133f11f7ea1fa9f009af57f5a57}', 'QCTF{28d876b112787b2ee599929c1f9de7b6}', 'QCTF{100187062f58e52a3b8bd79170b65f8d}', 'QCTF{8b5c6fb2ba52a12763d64631c63ad01c}', 'QCTF{07ffbf77145fd46dc5b19c7464f8e94a}', 'QCTF{8f86963b93b526c663bc51a403a41165}', 'QCTF{eadb09f8f6afc668c3c03976693a7c9e}', 'QCTF{93ddbf8e42e6b4d136bae5d3f1158d70}', 'QCTF{a809ecbc8776a603744cf537e9b71329}', 'QCTF{b75aaea7fabc8f889dc74944c6a4e3c0}', 'QCTF{a416acd8208ccd0f2df531f33d2b6cbe}', 'QCTF{8597e9700045b0dee3fe0a4a2f751af1}', 'QCTF{729f67a65769222200269d1c3efe50f6}', 'QCTF{21f4a9b77d313354bb0951949f559efb}', 'QCTF{6a9d138c62a731982c21a0951cac751f}', 'QCTF{b2a353a1231651b2373e0f4f9863d67c}', 'QCTF{6b8646481367974201ad3763ac09f01b}', 'QCTF{4733d8e51be03a5e7e1421fcb9461946}', 'QCTF{d5671bfab2e102d6ef436310cea556e5}', 'QCTF{fe0dc7f1ad3e3ab1804ac552b5a1014e}', 'QCTF{cd04131fb76d78b75ad4ad3dc241c078}', 'QCTF{b0c3b58624595631a928614c481ef803}', 'QCTF{c3677adad49d8c7b58adcd8d1f41fd8e}', 'QCTF{24dd83a9fa8249b194a53b73f3e12ae8}', 'QCTF{1324a272b619f33ba6c906cd1241cb9a}', 'QCTF{8c4818398ff7e32749c55b19ef965e6e}', 'QCTF{8ee7652cd55d983b708494d85cdba5f2}', 'QCTF{f5601c9718694cfdb754eeb160e77c66}', 'QCTF{4bc1ee7c77ab31f93c314c9cee197d59}', 'QCTF{dfa5bf7ee0a60998035561854ed84677}', 'QCTF{91ff0390d23c0bc1f98d9b19f95cbf93}', 'QCTF{df1135299838932c7b99e8bde9ad8cee}', 'QCTF{056c0210269af051143085248957b3d5}', 'QCTF{6fc42ebaae905d9787d39ad2790b61a5}', 'QCTF{3556c554530023aa02c98a2640a8bacb}', 'QCTF{50a7a712e483aeb523eb00a3a3a4cac6}', 'QCTF{118206c65e16c8314c390914f4a1e59b}', 'QCTF{d456ee30a2399e16f992f9ac2a433d24}', 'QCTF{30a9fb0469aee8878738fa99b7aec8cb}', 'QCTF{b8e518cf71866653f21f4ac241c82d76}', 'QCTF{63117b1c93ec4ff2debd0b0753bb1eb3}', 'QCTF{5665a9accc75c6a1f1882a857c8bbe38}', 'QCTF{565c5a9ece2c891371311c9b0913ddb1}', 'QCTF{8de1cc37b69d6f40bfa2c00fd9e48028}', 'QCTF{50acfa0e810ef4f1cf81462fc77aa8e8}', 'QCTF{33ac115dda168b4eef1a7dc035031e2b}', 'QCTF{e78911a8fc02ed099996bd8e9721dc8d}', 'QCTF{dfe2b8379694a980a3794fd3ce5e61fe}', 'QCTF{eee7da02d350b537783ecead890dd540}', 'QCTF{2aad8accd248b7ca47ae29d5e11f7975}', 'QCTF{8e480455d1e43048616831a59e51fc84}', 'QCTF{986cbb4487b1a8a91ad1827a97bda900}', 'QCTF{48d538cd70bc824dd494562842a24c1b}', 'QCTF{17fa5c186d0bb555c17c7b61f50d0fee}', 'QCTF{9aa99fd3e183fab6071715fb95f2e533}', 'QCTF{58b7096db82c5c7d9ec829abe0a016f3}', 'QCTF{30464a8db4b8f0ae8dc49e8734ed66cb}', 'QCTF{83655c6bd0619b6454ceb273de2d369f}', 'QCTF{72d81a3037fbc8c015bcb0adb87df0db}', 'QCTF{c62bece5781ab571b6ead773f950578c}', 'QCTF{ccd16df0466399ce0424e0102e8bf207}', 'QCTF{9cf7d5815e5bdfccadbb77ffedffa159}', 'QCTF{5ea628391c00c852a73c1a248325cc36}', 'QCTF{8d1daaf1742890409c76c7e5c7496e74}', 'QCTF{19258fe7a929318e6a6c841b54376ea7}', 'QCTF{dc0f86d1e9c1dc1ac4bd4ecad118496b}', 'QCTF{a1a10660a9e023db4803963d0163f915}', 'QCTF{76bdb8507907572d7bba4e53c66b7c94}', 'QCTF{daa9cc55d45641b647449f5a0f4b8431}', 'QCTF{bfa029f704d1f2e81ee9f1ff125d9208}', 'QCTF{356ff001060180459cef071fe033a5f5}', 'QCTF{2b5288c1aad44a9412fcd6bb27dcea7a}', 'QCTF{44172306ed32d70629eace8b445fd894}', 'QCTF{8783ab2b9bc9a89d60c00c715c87c92e}', 'QCTF{a0351089fc58958fb27e55af695bb35e}', 'QCTF{c0de87abadd65ee4e2dba80de610e50a}', 'QCTF{c99b6e9bb5fce478cdc6bca666679c4a}', 'QCTF{0397b5cb327fcc1d94d7edb0f6e1ec15}', 'QCTF{9479a5ca5aef08cacde956246fa2edd3}', 'QCTF{2063acf3a9fd072febe2575151c670cb}', 'QCTF{d6ed4333159c278d22c5527c2a3da633}', 'QCTF{08a811c51b0f0173f0edef63d8326378}', 'QCTF{65dbdc8a0e1b52a07e59248a2e9e456b}', 'QCTF{573a7f0ce4d2cf3e08d452c743fee1ce}', 'QCTF{435089a171f209a66a966e377dba9501}', 'QCTF{81f7f819f6b71eb7720fad3d16dc2373}', 'QCTF{be50a207baaa5e3a491ef7aaeb245abf}', 'QCTF{a996d4647adbc12a69165587a08346e9}', 'QCTF{999d36dee80b90eec6a580cd1f344a08}', 'QCTF{3da3e486913a793a1317da22d8a9a29e}', 'QCTF{809e95f98ba199180cd860ba41d62c5c}', 'QCTF{67524c5080a8b674dcf064494ef7c70f}', 'QCTF{cefcc52f59a484f62b7ba7e62e88e06f}', 'QCTF{241cdfbf606848c9f67589bf2f269206}', 'QCTF{efc924775d7b859411f3bf5a61e85a07}', 'QCTF{63b4e85e20331f52a187318ba2edfd7a}', 'QCTF{a65f5925508331f0b8deda5f67781bc5}', 'QCTF{356ed7e0ab149db06806cc0e6ca6fd5f}', 'QCTF{304d3a7970cf4717dccf3dffbed06874}', 'QCTF{99a747c8723a889bdea5e4f283c20df7}', 'QCTF{c8d7f74205797b602d25852caad49fb1}', 'QCTF{b9248c3a252601dd106d9c0462a9bab7}', 'QCTF{ea86b2a12458a6990d5bae35a73168a0}', 'QCTF{1ca4ecbf8f4ea2d0e2b832c44746ec3b}', 'QCTF{59ee4bf3aedc20d469e788486a9ead6c}', 'QCTF{73720bdd5a424570e5be571021dc4fb8}', 'QCTF{8c04511bedfe9f8c388e4d2f8aba1be5}', 'QCTF{98e34760371fa91407546ba8ac379c09}', 'QCTF{d33cb59a700fb8521a8cb5471048e15e}', 'QCTF{09d317a825132c255ea11c1f41aab1f3}', 'QCTF{a3850a970f2330d1ff6d704061967318}', 'QCTF{93ad167555f15f0901b729f488fc7720}', 'QCTF{61fd9c59cfe8c20d90649bec48424ea1}', 'QCTF{bedf1e7e966f54474931e8cfd141a6ca}', 'QCTF{5ad8a1ce7ec8ab9cdc05553cfd306382}', 'QCTF{3320b3f0490d0949786a894b7f621746}', 'QCTF{57d1dc2f73193dca32535a48650b3a66}', 'QCTF{5c48d6bbfd4fb91d63f21cbe99ece20b}', 'QCTF{2cacdb709e0c230b54e732829b514f92}', 'QCTF{079d0cf77acaebbdbbe8037a35bba5d7}', 'QCTF{d87badd74be817e6acb63d64ecc05ac8}', 'QCTF{f67dffa3ee05d9f096b45c37895d7629}', 'QCTF{1bf708a5a3c9ef47ca7eb8138a052d1b}', 'QCTF{1adf18338f26d19b22f63a4e8eec6e91}', 'QCTF{870d781a223a9112cbb2fb5548e10906}', 'QCTF{8851c98297c5a74ac40cf59875186bd8}', 'QCTF{f83377875176bed6b33e06e9896edded}', 'QCTF{1715727cbb24140bacd2838fc0199bc4}', 'QCTF{c77578152cc09addb4751158bccc7fea}', 'QCTF{7155fb7eb62e6c78ddf3ec44375d3fa9}', 'QCTF{57214d23681056a6596f75372e5cd41b}', 'QCTF{92dcab5e2109673b56d7dc07897055bd}', 'QCTF{131bb9ead4a7d0eb7d2f5540f4929c2d}', 'QCTF{e436dc01fa926f4e48f6920c69c2f54c}', 'QCTF{4b7d2c9245bd28d9c783863ab43202be}', 'QCTF{e23e27790ea55f3093b40d7fdf21b821}', 'QCTF{93e2f15ce929e3d6508543d4378735c3}', 'QCTF{0a18798c331b7f4b4dd14fad01ca3b1f}', 'QCTF{cde9927b04feeaa0f876cecb9e0268e3}', 'QCTF{ba6c8af3c6e58b74438dbf6a04c13258}', 'QCTF{72212e5eb60e430f6ff39f8c2d1ba70d}', 'QCTF{3912316e516adab7e9dfbe5e32c2e8cc}', 'QCTF{960dce50df3f583043cddf4b86b20217}', 'QCTF{6cd9ea76bf5a071ab53053a485c0911a}', 'QCTF{36300e6a9421da59e6fdeefffd64bd50}', 'QCTF{5c3e73a3187dc242b8b538cae5a37e6f}', 'QCTF{9744c67d417a22b7fe1733a54bb0e344}', 'QCTF{28d249578bf8facdf7240b860c4f3ae0}', 'QCTF{a1e9913a8b4b75dd095db103f0287079}', 'QCTF{c4f0f3deafa52c3314fd4542a634933c}', 'QCTF{35a39749f9bea6c90a45fd3e8cc88ca5}', 'QCTF{755cb7e40752b07ed04b12c59b9ce656}', 'QCTF{89e8208c492574de6735b0b5fbe471f5}', 'QCTF{a242f710bd67754b594969a449119434}', 'QCTF{26ded88b4d6b4d9278148de9c911cfb6}', 'QCTF{b6ac8ca7cfd8f3dc075f5f086def5ea2}', 'QCTF{27bb11fe3208f50caafe37b0bd90f070}', 'QCTF{5f058bf0d3991227b49980b9e226c548}', 'QCTF{9fb934712199835ad48f097e5adedbf1}', 'QCTF{8acd08daa256cda637666543042d8d04}', 'QCTF{f19749ece3b079f28397fc6dafc7c5f8}', 'QCTF{8df2b36bc88bdd6419312a3b1e918ac4}', 'QCTF{3f853785bb79075c902c1fcb86b72db8}', 'QCTF{26950b99d1de657f1840f3b1efd117f9}', 'QCTF{57a0747d5a0e9d621b15efc07c721c47}', 'QCTF{164847eb1667c64c70d835cdfa2fed13}', 'QCTF{aeb04f7e9be0e8fb15ec608e93abf7c6}', 'QCTF{f65a2292ea6c9f731fde36f5f92403dc}', 'QCTF{9cff82f318a13f072dadb63e47a16823}', 'QCTF{6a0a50e5f4b8a5878ec6e5e32b8aa4f3}', 'QCTF{9439eb494febbcb498417bab268786f3}', 'QCTF{68a4215f9d77de4875958d2129b98c3e}', 'QCTF{bf83c9d150ed6777d6f2b5581ce75bf1}', 'QCTF{7c6530f3d07598d62a3566173f2cc4a1}', 'QCTF{9dd20e6699b5c69f432914b0196b5b17}', 'QCTF{3a675c1934b1f44b5b73bfd8cee887b9}', 'QCTF{b5e67c6f319acdfed3c47a280f871c7e}', 'QCTF{b88dad61f68da779fad66fa4442eb337}', 'QCTF{3af8a9807a6d0e4b50c1687c07c1d891}', 'QCTF{e78168930647856b94840ce84fab26b4}', 'QCTF{ab88b2ea7e66dd35bdff4d03a15d3dc1}', 'QCTF{78e20f8707184aea4227c98107c95fdb}', 'QCTF{f1b279cc0839c830e07f6e73bb9654fe}', 'QCTF{71fc41f44593348bb1e4a0938526f0f9}', 'QCTF{f8b9207f02330a7d9a762ab4c1cace2b}', 'QCTF{12efdafbe2e29645abc3296178891ed6}', 'QCTF{c5d813b31a0534341a1c4b64e554c488}', 'QCTF{1a63a760f782eecf21234c815b5748bf}', 'QCTF{b6dee11cd1b0382986738826a5c04d7a}', 'QCTF{0d0d99976206194e426b95873720a440}', 'QCTF{d4030405263f8eec80a3855ba066eb76}', 'QCTF{c249cd1f9f86aa5ff2fe0e94da247578}', 'QCTF{ba8adfd031159e41cbfb26193b2aeee1}', 'QCTF{14dc10f84625fc031dd5cdad7b6a82af}', 'QCTF{be7c2d83d34846ece6fe5f25f0700f74}', 'QCTF{d7f1d87ad0386f695cd022617bf134d8}', 'QCTF{6a3a915957dbcd817876854902f30a6a}', 'QCTF{4663ffd40db950abddb4d09122eb1dcd}', 'QCTF{f72c028fdfeb0c42e3d311295ac42ff2}', 'QCTF{901b065b0d0569f161f0ba7f1cc711bc}', 'QCTF{8f707798947c3335d685d7e3b761c2c4}', 'QCTF{746ffa1fc14609d13dde8d540c5d402a}', 'QCTF{1b92b1e84712dd9084dea96e9f67c659}', 'QCTF{2d8976f6ef6da5b843823940660be68a}', 'QCTF{d1e00391c9bd7c2ecc2b19e6d177e4af}', 'QCTF{cea54a59af20fdfa06c8e8357fec663d}', 'QCTF{1f2b8d5fceea39243fa966d638efc92e}', 'QCTF{0f6faa584c642fc21879f4358fdfb01c}', 'QCTF{acac74237614850fbfbd97410013daa2}', 'QCTF{57fce704c2dbdb5e3034b67a7984bb0c}', 'QCTF{e20bc6c0a13114f7fd29ad9661a946e9}', 'QCTF{92c4dfc79749e9310b7ab64c3d9780d0}', 'QCTF{c6a49485ff92a292f0ae9fca4b1f3314}', 'QCTF{be0f0be2f0fb165a16a62aee2dcd0258}', 'QCTF{052fcc31b1b26484fe9da51fb89ba34d}', 'QCTF{b156eb9c86c03d0fae3c883f5b317dcb}', 'QCTF{ff83da3b5ca61495d0acd623dc2d796e}', 'QCTF{3fce7a6ba38ed1a381dae3686919c902}', 'QCTF{889591a0a7d29579546adaad1d0b5b86}', 'QCTF{9c378d9aa63fca7d5f7f275a9566f264}', 'QCTF{e32a672a6673bc56d8b109952403aae9}', 'QCTF{bc6a3a213102b2dc5f946d5655026352}', 'QCTF{30d04471a675aeeec45b8f6143085f46}', 'QCTF{3b4d06e0c2cd20a177fa277bbbc0a1a2}', 'QCTF{bdf4879a061a3a751f91ece53657a53e}', 'QCTF{d8721fc7d32499aa692b04d7eacc8624}', 'QCTF{09d3580e9431327fbf4ccc53efb0a970}', 'QCTF{814356913a352dfe15b851e52cc55c0d}', 'QCTF{cd9de5c50a3ffb20ea08cb083004252c}', 'QCTF{79de86d819cfc03ac6b98fbc29fac36d}', 'QCTF{63663214499a85208c4f7dc529c05ea5}', 'QCTF{171798109c343a3303020f0a24259e5e}', 'QCTF{611a9181a1f7c45c6c715e494bccd1b9}', 'QCTF{da4e7cc4b461aaedd1bfc45533723b8a}', 'QCTF{2ea7d755b255a6f5376d22f8113a2cfa}', 'QCTF{2a741c8199e13853f8195613ef037ced}', 'QCTF{1b66523f2b665c3dfea91aece42273d3}', 'QCTF{42a46422d8faa1ec3e768580b2dec713}', 'QCTF{ca9d7ac177d049416354a0fbd76a89b9}', 'QCTF{9bb379b6c775b738069ae0ab7accf2dd}', 'QCTF{bacec59ecbc809f7ab27a9169500883a}', 'QCTF{0ef59b9a33046aa124bb87df30934714}', 'QCTF{1b646109ed4bfa30f29d6666b2090701}', 'QCTF{65727e2ba028dc6e9ac572ed6a6ebc6f}', 'QCTF{784c261a9f564d4387d035ce57b05e3e}', 'QCTF{e68fb87f2cad4a3da5799fc982ec82ff}', 'QCTF{ba003b186368bf16c19c71332a95efee}', 'QCTF{6d695ed5a0c2d04722716210b5bcfda6}', 'QCTF{7eb1c12dc09b138a1d7e40058fa7a04a}', 'QCTF{64a545320b2928f88b6c6c27f34d2e3c}', 'QCTF{8cdf05aeb3fa5bb07157db87d2b45755}', 'QCTF{48f8e1742b60e1734f6580ab654f9b6f}', 'QCTF{fb14f2533750f7849b071c9a286c9529}', 'QCTF{47f7996ec34bf04863272d7fc36a1eb1}', 'QCTF{919f49d2f324ae91956c3d97b727c24a}', 'QCTF{336f9d8d23fbb50810c1c0b549ad13bf}', 'QCTF{b316f48f8ed4443a117b7a8752d062cb}', 'QCTF{ea5818adad537c87ddb9ce339c0bbb84}', 'QCTF{d510dfbd781d15b674c63489f55191b2}', 'QCTF{df1d534fcc36d5049b5b607499a74f75}', 'QCTF{2781aa19764810125b745b001dd09090}', 'QCTF{0920b2f44311ed5239e8c2d90c991417}', 'QCTF{da22adea508dc7d5bc9ec5cd5378ef20}', 'QCTF{30f69464f59bf44cba73e6430591acb9}', 'QCTF{2239ffe2985776b1d459a729035e6105}', 'QCTF{07a3846e68534b08abec6761492dfd7c}', 'QCTF{2876a617fcb9d33b1a457e2a1f22982b}', 'QCTF{76471463a11b3f5830d6c98bdc188410}', 'QCTF{64b115efe8a4acaab08f40e83d174953}', 'QCTF{2b9fece3ca12493fa34027cfe34a827d}', 'QCTF{72ceded3364700e5a163cd1fa809f2b5}', 'QCTF{a52ab44fe70adc1964442347fe0bc389}', 'QCTF{ffb4560d742fd8dae61edda32628d5d9}', 'QCTF{fe274231e80419937813cbd55441f8b5}', 'QCTF{38ec71804dca70480b9714ae809bf843}', 'QCTF{2876bb27e398963331099a10e9c1b5b1}', 'QCTF{c8eacb1f0f7ea7a130fe97aa903bc52d}', 'QCTF{91d895637bf21849d8ac97072d9aa66c}', 'QCTF{487a3428ab723d4e9bca30342180612a}', 'QCTF{0ca2e9a4b4fb5298b84a2ae097303615}', 'QCTF{1017c0fad5211fa1a8bd05e2c12e1ab5}', 'QCTF{0772fc3bb68132cc47fc6a26bb23a2eb}', 'QCTF{54808c739cc835327ba82b17dda37765}', 'QCTF{5ba1b7f137a0a269d77db75c1609d015}', 'QCTF{3f59447502e3ccd8db93f57f6b64a869}', 'QCTF{3d33a10890e1797b3518f2032228ef97}', 'QCTF{538226c6e2932fb2c0890fa660707081}', 'QCTF{03dea04fa6f9bf11854a62f92f95028c}', 'QCTF{7ebbc2f97c8e02947eb7537e6e35bf4d}', 'QCTF{7fabc82da5e59469a31d6ae73b0ba8dd}', 'QCTF{99d11087195ac95f9a4bf220346c7ae8}', 'QCTF{6ba3b8dff5b591a308616a485802eb1a}', 'QCTF{73e10bd2e77da35988a91f2b39ba4032}', 'QCTF{d41e8b2244e4e72a04f5229bc61e0a4a}', 'QCTF{1f1c22d0e0dcf0d73b5562f604805060}', 'QCTF{e45fba7380d70df6de5353f6bd1326df}', 'QCTF{c4eb636d6329e437d2ece74b439d905b}', 'QCTF{166f03d5b2a6172ebdfe62790d40ea08}', 'QCTF{c9e2d3fed043ae7ff086944ddb92a595}', 'QCTF{c3683790714524bf741f442cf6f75816}', 'QCTF{c3552856294a7c882abe5bfeb08d40b3}', 'QCTF{2028f8e09d41c758c78b5f1bff9a7730}', 'QCTF{7b28486de1bf56b716f77ab14ac1dc2f}', 'QCTF{e445025dcc35e0f7ad5ffc4c1f736857}', 'QCTF{c977b87449d7461cd45ec2b076754b77}', 'QCTF{9626d8f7759943dedefedffc96ac2489}', 'QCTF{52af66f7f1005968a3057ca76c69b488}', 'QCTF{f7791cfb47893204998bc864a0454767}', 'QCTF{c1325f2049b792f8330ab51d8012138a}', 'QCTF{e6e088ba12752fb97aadaa34ab41b118}', 'QCTF{41051ffcbd702005b7f5c4bae392bb4a}', 'QCTF{58bfe4a9f82ae56f4fab8f2d57470f2f}', 'QCTF{a0ac496ce45f06890c045235eb2547a7}', 'QCTF{0c22482b6a4533ba449d4ec1762494ba}', 'QCTF{4466193f2c65c5d072ecb82277657780}', 'QCTF{43689b43469374eb768fb5d4269be92a}', 'QCTF{e31ff94e5ee5638e7b3c0cde3c2b50dd}', 'QCTF{4cc47b59341b7f0112ba8f4dbdda527c}', 'QCTF{e11501e1bb7da841a2c715eafedccb55}', 'QCTF{6acd2208d0d86fcb796cf8264973fee6}', 'QCTF{d8ee1b7b2772d6aea857929d10fbca8e}', 'QCTF{8c27329ebfdef6480d0c60393a573137}', 'QCTF{b9f5190eb71ca8203f60e2a1a6a652af}', 'QCTF{7e5aa6d503c4c2c944a8148fdf633694}', 'QCTF{9ddcb0e99371e60bbb6cbcae87899fc5}', 'QCTF{e7e75d8e6a4789ea242ece7be93bfc89}', 'QCTF{86546326f5bf721792154c91ede0656d}', 'QCTF{6d36f257d24ee06cc402c3b125d5eaa7}'] def check(attempt, context): if attempt.answer == flags[attempt.participant.id % len(flags)]: return Checked(True) if attempt.answer in flags: return CheckedPlagiarist(False, flags.index(attempt.answer)) return Checked(False)
#!/usr/bin/python3.5 def fib(n: int): fibs = [1, 1] for _ in range(max(n-2, 0)): fibs.append(fibs[-1] + fibs[-2]) return fibs[n-1] print("%s" % fib(38))
M,N,K = [int(x) for x in input().split()] a = [int(input()) for i in range(K)] supporter = [N] + [0] * M #supporter[i]は立候補者iを支持している有権者の人数を表す #i=0は誰も支持していない人数を表す for a_item in a: count = 0 for x in range(len(supporter)): #立候補者a_itemが演説するとき,他の立候補者の支持者状況を確認する if x != a_item and supporter[x] != 0: count += 1 supporter[x] -= 1 supporter[a_item] += count max_temp = [] max_value = sorted(supporter[1:],reverse=True)[0] #支持者が最も多い立候補者が複数いるかを確認する for y in range(1,M+1): if supporter[y] == max_value: max_temp.append(y) for temp_item in max_temp: print(temp_item)
""" Sponge Knowledge Base Remote API """ class UpperCase(Action): def onConfigure(self): self.withArg(StringType("text").withLabel("Text to upper case")).withResult(StringType().withLabel("Upper case text")) def onCall(self, text): self.logger.info("Action {} called", self.meta.name) return text.upper()
# SOMENTE GÊNEROS CORRETOS! # um pouco mais inclusivo do q o original :) g = str(input('Insira seu gênero [M|F|T|Q|N]: _ ')).strip().upper()[0] while g not in 'MFTQN': g = str(input('Formato incorreto! Tente novamente.\nInsira seu gênero [M|F|T|Q|N]: _ ')).strip().upper()[0] print('Obrigado. Gênero {} registrado com sucesso!'.format(g))
def method1(str1: str, str2: str) -> int: def compare(str1, str2): for i in range(256): if str1[i] != str2[i]: return False return True def search(pat, txt): m = len(pat) n = len(txt) count_p = [0] * 256 count_t = [0] * 256 for i in range(m): count_p[ord(pat[i])] += 1 count_t[ord(txt[i])] += 1 for i in range(m, n): if compare(count_p, count_t): return ("Found at ", i - m) count_t[ord(txt[i])] += 1 count_t[ord(txt[i-m])] -= 1 if compare(count_p, count_t): return ("Found at ", n - m) txt = "thisisastringtocompare" pat = "thisisiastring" search(pat, txt) if __name__ == "__main__": """ from timeit import timeit txt = "thisisastringtocompare" pat = "thisisiastring" print(timeit(lambda: method1(pat, txt), number=10000)) # 0.4546106020006846 """
# coding=utf8 class Error(Exception): pass class TitleRequiredError(Error): pass class TextRequiredError(Error): pass class APITokenRequiredError(Error): pass class GetImageRequestError(Error): pass class ImageUploadHTTPError(Error): pass class FileTypeNotSupported(Error): pass class TelegraphUnknownError(Error): pass class TelegraphPageSaveFailed(Error): # reason is unknown pass class TelegraphContentTooBigError(Error): def __init__(self, message): message += ". Max size is 64kb including markup" super(Error, TelegraphError).__init__(self, message) class TelegraphFloodWaitError(Error): def __init__(self, message): super(Error, TelegraphError).__init__(self, message) self.FLOOD_WAIT_IN_SECONDS = int(message.split('FLOOD_WAIT_')[1]) class TelegraphError(Error): def __init__(self, message): if 'Unknown error' in message: raise TelegraphUnknownError(message) elif 'Content is too big' in message: raise TelegraphContentTooBigError(message) elif 'FLOOD_WAIT_' in message: raise TelegraphFloodWaitError(message) elif 'PAGE_SAVE_FAILED' in message: raise TelegraphPageSaveFailed(message) else: super(Error, TelegraphError).__init__(self, message)
class Tree(object): def __init__(self): self.children = [] self.metadata = [] def add_child(self, leaf): self.children.append(leaf) def add_metadata(self, metadata): self.metadata.append(metadata) def sum_metadata(self): metasum = sum(self.metadata) for c in self.children: metasum += c.sum_metadata() return metasum def sum_tree(self): child_count = len(self.children) if child_count > 0: metasum = 0 for x in self.metadata: if 0 < x <= child_count: metasum += self.children[x - 1].sum_tree() else: metasum = self.sum_metadata() return metasum class Datapump(object): def __init__(self, data): self.data = data self.point = 0 def __iter__(self): return self def __next__(self): if self.point < len(self.data): res, self.point = self.data[self.point], self.point + 1 return res else: raise StopIteration() def next(self): return self.__next__() def parse_tree(tree_data): leaf = Tree() children = tree_data.next() metadata = tree_data.next() for _ in range(children): leaf.add_child(parse_tree(tree_data)) for _ in range(metadata): leaf.add_metadata(tree_data.next()) return leaf def memory_maneuver_part_1(inp): datapump = Datapump([int(i) for i in inp[0].split()]) tree = parse_tree(datapump) return tree.sum_metadata() def memory_maneuver_part_2(inp): datapump = Datapump([int(i) for i in inp[0].split()]) tree = parse_tree(datapump) return tree.sum_tree() if __name__ == '__main__': with open('input.txt') as license_file: license_lines = license_file.read().splitlines(keepends=False) print(f'Day 8, part 1: {memory_maneuver_part_1(license_lines)}') print(f'Day 8, part 2: {memory_maneuver_part_2(license_lines)}') # Day 8, part 1: 45618 # Day 8, part 2: 22306
print("RENTAL MOBIL ABCD") print("-------------------------------") #Input nama = input("Masukkan Nama Anda : ") umur = int(input("Masukkan Umur Anda : ")) if umur < 18: print("Maaf", nama, "anda belum bisa meminjam kendaraan") else: ktp = int(input("Masukkan Nomor KTP Anda : ")) k_mobil = input("Kategori Mobil [4/6/8 orang] : ") if k_mobil == "4" : kapasitasmobil = "4 orang" harga = 300000 elif k_mobil == "6" : kapasitasmobil = "6 orang" harga = 350000 else: kapasitasmobil = "8 orang" harga = 500000 jam = int(input("Masukkan Durasi Peminjaman (dalam hari): ")) if jam > 6: diskon = (jam*harga)*0.1 else: diskon = 0 total = (jam*harga) print("-------------------------------") print("RENTAL MOBIL ABCD") print("-------------------------------") print("Masukkan Nama Anda : "+str(nama)) print("Masukkan Umur Anda : "+str(umur)) print("Masukkan Nomor KTP Anda : "+str(ktp)) print("Kapasitas Mobil : "+str(k_mobil)) print("Harga : ",+(harga)) print("Potongan yang didapat : ",+(diskon)) print("-------------------------------") print("Total Bayar : ",+(total))
def func_that_raises(): raise ValueError('Error message') def func_no_catch(): func_that_raises()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 16 07:34:02 2020 @author: krishan """ class BaseClass: num_base_calls = 0 def call_me(self): print("Calling method on Base Class") self.num_base_calls += 1 class LeftSubclass(BaseClass): num_left_calls = 0 def call_me(self): BaseClass.call_me(self) print("Calling method on Left Subclass") self.num_left_calls += 1 class RightSubclass(BaseClass): num_right_calls = 0 def call_me(self): BaseClass.call_me(self) print("Calling method on Right Subclass") self.num_right_calls += 1 class Subclass(LeftSubclass, RightSubclass): num_sub_calls = 0 def call_me(self): LeftSubclass.call_me(self) RightSubclass.call_me(self) print("Calling method on Subclass") self.num_sub_calls += 1
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2016-2017 JiNong Inc. All right reserved. # __title__ = 'python-pyjns' __version__ = '0.40' __author__ = 'Kim, JoonYong' __email__ = 'joonyong.jinong@gmail.com' __copyright__ = 'Copyright 2016-2017 JiNong Inc.'
""" Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Notice that you may not slant the container. Example 1 Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. Example 2: Input: height = [1,1] Output: 1 Example 3: Input: height = [4,3,2,1,4] Output: 16 Example 4: Input: height = [1,2,1] Output: 2 Constraints: n == height.length 2 <= n <= 105 0 <= height[i] <= 104 """ # V0 # IDEA : TWO POINTERS class Solution(object): def maxArea(self, height): ans = 0 l = 0 r = len(height) - 1 while l < r: ans = max(ans, min(height[l], height[r]) * (r - l)) if height[l] < height[r]: l += 1 else: r -= 1 return ans # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/82822939 # IDEA : TWO POINTERS class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ ans = 0 l = 0 r = len(height) - 1 while l < r: ans = max(ans, min(height[l], height[r]) * (r - l)) if height[l] < height[r]: l += 1 else: r -= 1 return ans # V1' # https://www.jiuzhang.com/solution/container-with-most-water/#tag-highlight-lang-python class Solution(object): def maxArea(self, height): left, right = 0, len(height) - 1 ans = 0 while left < right: if height[left] < height[right]: area = height[left] * (right - left) left += 1 else: area = height[right] * (right - left) right -= 1 ans = max(ans, area) return ans # V2 # Time: O(n) # Space: O(1) class Solution(object): # @return an integer def maxArea(self, height): max_area, i, j = 0, 0, len(height) - 1 while i < j: max_area = max(max_area, min(height[i], height[j]) * (j - i)) if height[i] < height[j]: i += 1 else: j -= 1 return max_area
extensions = [ "cogs.help", "cogs.game_punishments.ban", "cogs.game_punishments.kick", "cogs.game_punishments.unban", "cogs.game_punishments.warn", "cogs.settings.setchannel", "cogs.verification.verify" ]
def __getitem__(self,idx): if idx < self.lastIndex: return self.myArray[idx] else: raise LookupError('index out of bounds') def __setitem__(self,idx,val): if idx < self.lastIndex: self.myArray[idx] = val else: raise LookupError('index out of bounds')
__author__ = "Amane Katagiri" __contact__ = "amane@ama.ne.jp" __copyright__ = "Copyright (C) 2016 Amane Katagiri" __credits__ = "" __date__ = "2016-12-07" __license__ = "MIT License" __version__ = "0.1.0"
''' https://www.guazi.com/huzhou/buy/o2/#bread 第一页:o1 第二页:o2 …… 第n页:on ''' url='https://www.guazi.com/huzhou/buy/o{}/#bread' for page in range(1,51): page_url=url.format(page) print(page_url)
example_dict = {} for idx in range(0, 10): example_dict[idx] = idx for key, value in example_dict.items(): formmating = f'key is {key}, value is {value}' print(formmating)
def minimumSwaps(arr): a = dict(enumerate(arr,1)) b = {v:k for k,v in a.items()} count = 0 for i in a: x = a[i] if x!=i: y = b[i] a[y] = x b[x] = y count+=1 return count n = int(input()) arr = list(map(int,input().split())) print(minimumSwaps(arr))
class TMVError(Exception): """ Base exception """ class CameraError(Exception): """" Hardware camera problem""" class ButtonError(Exception): """ Problem with (usually hardware) buttons """ class VideoMakerError(Exception): """ Problem making images into a video """ class ImageError(Exception): """ Problem with an image """ class ConfigError(TMVError): """ TOML or config error """ class PiJuiceError(TMVError): """ Cound't power off""" class PowerOff(TMVError): """ Camera can power off """ class SignalException(TMVError): """ Camera got a sigint """
""" @Pedro Santana Abreu (https://linktr.ee/pedrosantanaabreu) @Icev (https://somosicev.com) PT-BR: Faça um programa que receba a quantidade de dinheiro em reais que uma pessoa que vai viajar possui. Ela vai passar por vários países e precisa converter seu dinheiro em dólares, euros e libra esterlina. Sabe-se que a cotarão do dólar é de R$ 4,25; do euro, de R$ 4,75; e da libra esterlina, de R$ 5,64. O programa deve fazer as conversões e mostrá-las. """ # Cotações euro = 4.75 dolar = 4.25 libra_esterlina = 5.64 # Recebendo valor em reais valor_reais = float(input('Digite o valor em reais | R$ ')) # Conversões real_euro = valor_reais / euro real_dolar = valor_reais / dolar real_libra_esterlina = valor_reais / libra_esterlina # Exibindo resultados print(''' Valor em reais | R$ {:.2f}\n Euro | € {:.2f} Dolar | $ {:.2f} Libra Esterlina | £ {:.2f} '''.format(valor_reais, real_euro, real_dolar, real_libra_esterlina))
year = 2022 if year%4==0 and year%100!=0 or year%400==0: print(year,"是闰年") else: print(year,"不是闰年")
def extract_characters(*file): with open("file3.txt") as f: while True: c = f.read(1) if not c: break print(c) extract_characters('file3.txt')
class MTUError(Exception): pass class MACError(Exception): pass class IPv4AddressError(Exception): pass
def cyclesort(lst): for i in range(len(lst)): if i != lst[i]: n = i while 1: tmp = lst[int(n)] if n != i: lst[int(n)] = last_value lst.log() else: lst[int(n)] = None lst.log() last_value = tmp n = last_value if n == i: lst[int(n)] = last_value lst.log() break