content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Copyright 2017 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. DEPS = [ 'properties', 'step', 'url', ] def RunSteps(api): api.url.validate_url(api.properties['url_to_validate']) def GenTests(api): ...
deps = ['properties', 'step', 'url'] def run_steps(api): api.url.validate_url(api.properties['url_to_validate']) def gen_tests(api): yield (api.test('basic') + api.properties(url_to_validate='https://example.com')) yield (api.test('no_scheme') + api.properties(url_to_validate='example.com') + api.expect_e...
class Option(object): """A Class implementing some sort of field interface""" def __init__(self, name, label, type, description=None, category='general', required=False, choices=None, default=None, field_options=None): kwargs = locals() kwargs.pop('self') ...
class Option(object): """A Class implementing some sort of field interface""" def __init__(self, name, label, type, description=None, category='general', required=False, choices=None, default=None, field_options=None): kwargs = locals() kwargs.pop('self') for (attr, value) in kwargs.ite...
#!/usr/bin/env python def plain_merge(array_a: list, array_b: list) -> list: pointer_a, pointer_b = 0, 0 length_a, length_b = len(array_a), len(array_b) result = [] while pointer_a < length_a and pointer_b < length_b: if array_a[pointer_a] <= array_b[pointer_b]: result.append(arr...
def plain_merge(array_a: list, array_b: list) -> list: (pointer_a, pointer_b) = (0, 0) (length_a, length_b) = (len(array_a), len(array_b)) result = [] while pointer_a < length_a and pointer_b < length_b: if array_a[pointer_a] <= array_b[pointer_b]: result.append(array_a[pointer_a]) ...
# does this even work? class InvalidToken(Exception, object): """Raise an invalid token """ def __init__(self, message, payload): super(InvalidToken, self).__init__(message, payload) self.message = message self.payload = payload
class Invalidtoken(Exception, object): """Raise an invalid token """ def __init__(self, message, payload): super(InvalidToken, self).__init__(message, payload) self.message = message self.payload = payload
""" Stat objects make life a little easier """ class CoreStat(): """ Core stats are what go up and down to modify the character """ def __init__(self, points=0): points = int(points) if points < 0: points = 0 self._points = points self._current = self.base s...
""" Stat objects make life a little easier """ class Corestat: """ Core stats are what go up and down to modify the character """ def __init__(self, points=0): points = int(points) if points < 0: points = 0 self._points = points self._current = self.base sel...
""" weather.exceptions ------------------ Exceptions for weather django app """ class CityDoesNotExistsException(Exception): def __init__(self, message: str = None, *args, **kwargs): if message is None: message = "The queried city object doesn exists" Exception.__init__(self, message,...
""" weather.exceptions ------------------ Exceptions for weather django app """ class Citydoesnotexistsexception(Exception): def __init__(self, message: str=None, *args, **kwargs): if message is None: message = 'The queried city object doesn exists' Exception.__init__(self, message, *a...
x={"a","b","c"} y=(1,2,3) z=[4,5,2] print(type(x)); print(type(y)); print(type(z)); x.add("d") print(x) z.append(5) print(y) print(z) for i in x: print (i) if 5 in z: print("yes") x.remove("b") print(x) z.remove(4) print(z) z.insert(1,7) print(z) z.extend(y) print(z) print(z.count(2)) del...
x = {'a', 'b', 'c'} y = (1, 2, 3) z = [4, 5, 2] print(type(x)) print(type(y)) print(type(z)) x.add('d') print(x) z.append(5) print(y) print(z) for i in x: print(i) if 5 in z: print('yes') x.remove('b') print(x) z.remove(4) print(z) z.insert(1, 7) print(z) z.extend(y) print(z) print(z.count(2)) del y print(y)
first = ord('A') last = ord('Z') for i in range(first, last + 1): for j in range(last, first - 1, -1): if j <= i: print(chr(i), end=' ') else: print('', end=' ') print()
first = ord('A') last = ord('Z') for i in range(first, last + 1): for j in range(last, first - 1, -1): if j <= i: print(chr(i), end=' ') else: print('', end=' ') print()
coordinates_01EE00 = ((123, 116), (123, 124), (123, 127), (123, 128), (123, 136), (123, 137), (124, 115), (124, 117), (124, 119), (124, 120), (124, 121), (124, 122), (124, 130), (124, 134), (124, 135), (124, 138), (125, 114), (125, 116), (125, 124), (125, 125), (125, 126), (125, 127), (125, 128), (125, 131), (125, 13...
coordinates_01_ee00 = ((123, 116), (123, 124), (123, 127), (123, 128), (123, 136), (123, 137), (124, 115), (124, 117), (124, 119), (124, 120), (124, 121), (124, 122), (124, 130), (124, 134), (124, 135), (124, 138), (125, 114), (125, 116), (125, 124), (125, 125), (125, 126), (125, 127), (125, 128), (125, 131), (125, 132...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 19 17:46:22 2021 @author: rezanmoustafa """ # Endret fra 8b til 9 class Sporsmaal: def __init__(self, sporsmaal, svar, valg=[]): self.sporsmaal=sporsmaal self.svar=svar self.valg=valg def HentSporsmaal(self): ...
""" Created on Tue Oct 19 17:46:22 2021 @author: rezanmoustafa """ class Sporsmaal: def __init__(self, sporsmaal, svar, valg=[]): self.sporsmaal = sporsmaal self.svar = svar self.valg = valg def hent_sporsmaal(self): print(self.sporsmaal) for i in range(len(self.valg)...
# -*- coding: utf-8 -*- Consent_form_Out = { # From Operator_CR to UI "source": { "service_id": "String", "rs_id": "String", "dataset": [ { "dataset_id": "String", "title": "String", "description": "String", "keywor...
consent_form__out = {'source': {'service_id': 'String', 'rs_id': 'String', 'dataset': [{'dataset_id': 'String', 'title': 'String', 'description': 'String', 'keyword': [], 'publisher': 'String', 'distribution': {'distribution_id': 'String', 'access_url': 'String'}, 'component_specification_label': 'String', 'selected': ...
class Ionic: """Ionic radius class. Stores: charge, spin, coordination""" def __init__(self, charge=0, coordination="", radius=0.0): self.charge = charge self.coordination = coordination self.radius = radius def set_radius(self, value: float): self.radius = value cl...
class Ionic: """Ionic radius class. Stores: charge, spin, coordination""" def __init__(self, charge=0, coordination='', radius=0.0): self.charge = charge self.coordination = coordination self.radius = radius def set_radius(self, value: float): self.radius = value class Ato...
class Adapter(object): def __init__(self): self.interfaces = []
class Adapter(object): def __init__(self): self.interfaces = []
with open("10.in") as file: lines = file.readlines() lines = [line.rstrip() for line in lines] # Part 1 luc = {"(": ")", ")": "(", "[": "]", "]": "[", "{": "}", "}": "{", "<": ">", ">": "<"} lup = {")": 3, "]": 57, "}": 1197, ">": 25137} score = 0 for line in lines: stack = [] for i in range(0,...
with open('10.in') as file: lines = file.readlines() lines = [line.rstrip() for line in lines] luc = {'(': ')', ')': '(', '[': ']', ']': '[', '{': '}', '}': '{', '<': '>', '>': '<'} lup = {')': 3, ']': 57, '}': 1197, '>': 25137} score = 0 for line in lines: stack = [] for i in range(0, len(line)): ...
__all__ = [ 'config_enums', 'feed_enums', 'file_enums' ]
__all__ = ['config_enums', 'feed_enums', 'file_enums']
#Flag #Use a flag that stores on the nodes to know if we visited or not. #time: O(N). #space: O(N), for each node we use O(1) and there are N nodes. class Solution(object): def detectCycle(self, head): curr = head while curr: if hasattr(curr, 'visited') and curr.visited: return curr ...
class Solution(object): def detect_cycle(self, head): curr = head while curr: if hasattr(curr, 'visited') and curr.visited: return curr curr.visited = True curr = curr.next return None class Solution(object): def detect_cycle(self, h...
class Solution: def binarySearchableNumbers(self, nums: List[int]) -> int: maximums = [nums[0]] # from the left minimums = [0] * len(nums) # from the right min_n = nums[-1] result = 0 for n in nums[1::]: maximums.append(max(maximums[-1], n)) ...
class Solution: def binary_searchable_numbers(self, nums: List[int]) -> int: maximums = [nums[0]] minimums = [0] * len(nums) min_n = nums[-1] result = 0 for n in nums[1:]: maximums.append(max(maximums[-1], n)) for idx in range(len(nums) - 1, -1, -1): ...
# def candies(s): # worst case = three passes of 's', len, max, sum # length = len(s) # if length <= 1: # return -1 # return max(s) * length - sum(s) def candies(seq): length = 0 maximum = 0 total = 0 for i, a in enumerate(seq): try: current = int(a) ex...
def candies(seq): length = 0 maximum = 0 total = 0 for (i, a) in enumerate(seq): try: current = int(a) except TypeError: return -1 length += 1 total += current if current > maximum: maximum = current return maximum * length ...
def convert2meter(s, input_unit="in"): ''' Function to convert inches, feet and cubic feet to meters and cubic meters ''' if input_unit == "in": return s*0.0254 elif input_unit == "ft": return s*0.3048 elif input_unit == "cft": return s*0.0283168 else: print(...
def convert2meter(s, input_unit='in'): """ Function to convert inches, feet and cubic feet to meters and cubic meters """ if input_unit == 'in': return s * 0.0254 elif input_unit == 'ft': return s * 0.3048 elif input_unit == 'cft': return s * 0.0283168 else: ...
# [Stone Colusses] It Ain't Natural CHIEF_TATOMO = 2081000 sm.setSpeakerID(CHIEF_TATOMO) sm.sendNext("Well, you don't look like you just spoke to an ancient nature spirit, but I suppose we'll know soon enough. " "Are you ready for a little adventure?\r\n\r\n" "#bYou know it! How do I get to th...
chief_tatomo = 2081000 sm.setSpeakerID(CHIEF_TATOMO) sm.sendNext("Well, you don't look like you just spoke to an ancient nature spirit, but I suppose we'll know soon enough. Are you ready for a little adventure?\r\n\r\n#bYou know it! How do I get to the Stone Colossus?") sm.sendSay('Ah, humans. No patience, and not eno...
# a = [1,2,2,3,4,5] # # print(list(set(a))) # def correct_list(a): # return(list(set(a))) # print(correct_list(a)) a = [1,2,2,3,4,5] def correct_list(a): s = [] for i in a: if i not in s: s.append(i) return(s) print(correct_list(a))
a = [1, 2, 2, 3, 4, 5] def correct_list(a): s = [] for i in a: if i not in s: s.append(i) return s print(correct_list(a))
''' Title: %s Given: %s Return %s Sample Dataset: %s Sample Output: %s ''' def compute(): pass if __name__ == "__main__": pass
""" Title: %s Given: %s Return %s Sample Dataset: %s Sample Output: %s """ def compute(): pass if __name__ == '__main__': pass
def read_color(input_func): """ Reads input color and lower cases it """ user_supplied_color = input_func() return user_supplied_color.casefold() def is_quit(user_supplied_color): return 'quit' == user_supplied_color def print_colors(): """ In the while loop ask the user to enter a c...
def read_color(input_func): """ Reads input color and lower cases it """ user_supplied_color = input_func() return user_supplied_color.casefold() def is_quit(user_supplied_color): return 'quit' == user_supplied_color def print_colors(): """ In the while loop ask the user to enter a col...
class Solution(object): def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ ret = []; wl = len(words[0]) wordsused = [] for i in range (0, len(s) - len(words) * wl + 1): test = s[i:i+wl] ...
class Solution(object): def find_substring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ ret = [] wl = len(words[0]) wordsused = [] for i in range(0, len(s) - len(words) * wl + 1): test = s[i:i + wl...
# encoding: utf-8 ################################################## # This script shows an example of a header section. This sections is a group of commented lines (lines starting with # the "#" character) that describes general features of the script such as the type of licence (defined by the # developer), authors,...
print('tuples are very similar to lists') print('the are defined by ()') my_tuple = (1, 2, 3) print(my_tuple) data_type = type(my_tuple) print(data_type, '\n') print('tuples can have different data types as items') my_tuple = ('One', 'Two', 3) print(my_tuple, '\n') print('you can use indexing and slicing for tuples') p...
def result(text): count=0 for i in range(len(metin)): if(ord(metin[i])>=65 and ord(metin[i])<=90): count=count+1 return count
def result(text): count = 0 for i in range(len(metin)): if ord(metin[i]) >= 65 and ord(metin[i]) <= 90: count = count + 1 return count
def genTest(): print('Block of code before first yield statement') yield 1 print('Block of code after first yield statement and before second yield statement') yield 2 print('Block of code after all yield statements') # foo = genTest returns <function gen at 0x101faf400> foo = genTest() # retu...
def gen_test(): print('Block of code before first yield statement') yield 1 print('Block of code after first yield statement and before second yield statement') yield 2 print('Block of code after all yield statements') foo = gen_test() print(foo.__next__()) print() print(foo.__next__()) print('\n') ...
class PropertyReference: def __init__(self, var_name, property_name): self.var_name = var_name self.property_name = property_name def __str__(self): return f'{self.var_name}.{self.property_name}' def code_gen_string(self): return str(self) class FunctionCallArgument: ...
class Propertyreference: def __init__(self, var_name, property_name): self.var_name = var_name self.property_name = property_name def __str__(self): return f'{self.var_name}.{self.property_name}' def code_gen_string(self): return str(self) class Functioncallargument: ...
##Retrieve region of sequences delimited by a forward and reverse pattern #v0.0.1 f = [ [x.split('\n')[0], ''.join(x.split('\n')[1:])] for x in open('gg-13-8-99.fasta', 'r').read().rstrip('\n').split('>') ][1:] fw = ['AGAGTTTGATCMTGGCTCAG'] rv = ['GWATTACCGCGGCKGCTG'] mtol = 1 endstr = 3 w = open('ggmb.fa', 'w') nl = ...
f = [[x.split('\n')[0], ''.join(x.split('\n')[1:])] for x in open('gg-13-8-99.fasta', 'r').read().rstrip('\n').split('>')][1:] fw = ['AGAGTTTGATCMTGGCTCAG'] rv = ['GWATTACCGCGGCKGCTG'] mtol = 1 endstr = 3 w = open('ggmb.fa', 'w') nl = [] print('Forward:' + fw[0]) print('Reverse:' + rv[0]) print('Mismatches tolerated:' ...
def say(message, times = 1): print(message * times) say('Hello', 4) say('World', 4) def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3) func(3, c=13) def maximum(x, y): if x > y: return x elif x == y: return 'The numbers are equal' else: retur...
def say(message, times=1): print(message * times) say('Hello', 4) say('World', 4) def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3) func(3, c=13) def maximum(x, y): if x > y: return x elif x == y: return 'The numbers are equal' else: return y a ...
"""Wrapper Exceptions""" class ApiRequestFailed(Exception): """ Denotes a failure interacting with the API, such as the HTTP 4xx Series """ pass class ApiRequest400(ApiRequestFailed): """ Denotes a HTTP 400 error while interacting with the API """ pass class ImportDeleteError(ApiRequ...
"""Wrapper Exceptions""" class Apirequestfailed(Exception): """ Denotes a failure interacting with the API, such as the HTTP 4xx Series """ pass class Apirequest400(ApiRequestFailed): """ Denotes a HTTP 400 error while interacting with the API """ pass class Importdeleteerror(ApiReque...
# write program reading an integer from standard input - a # printing sum of squares of natural numbers smaller than a # for example, for a=4, result = 1*1 + 2*2 + 3*3 = 14 a = int(input("pass a - ")) element = 1 result = 0 while element < a: result = result + element * element element = element + 1 print("...
a = int(input('pass a - ')) element = 1 result = 0 while element < a: result = result + element * element element = element + 1 print('result = ' + str(result))
# implement strip() to remove the white spaces in the head and tail of a string. def strip(s): while len(s) != 0 and (s[0] == ' ' or s[-1] == ' '): s = s[1:] if s[0] == ' ' else s s = s[:-1] if s[-1] == ' ' else s return s if __name__ == "__main__": if strip('hello ') != 'hello': ...
def strip(s): while len(s) != 0 and (s[0] == ' ' or s[-1] == ' '): s = s[1:] if s[0] == ' ' else s s = s[:-1] if s[-1] == ' ' else s return s if __name__ == '__main__': if strip('hello ') != 'hello': print('fail!') elif strip(' hello') != 'hello': print('fail!') eli...
a = [1,2,3,4,5] k =2 del a[0] for i in range(0,len(a)): print(a[i])
a = [1, 2, 3, 4, 5] k = 2 del a[0] for i in range(0, len(a)): print(a[i])
# Copyright (c) 2018 Lotus Load # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribu...
load('@io_bazel_rules_docker//go:image.bzl', 'go_image') load('@io_bazel_rules_docker//container:container.bzl', 'container_bundle') load('@io_bazel_rules_docker//contrib:push-all.bzl', 'docker_push') def app_image(name, binary, repository, **kwargs): go_image(name='image', binary=binary, **kwargs) container_b...
""" Exceptions ---------- """ class FactoryException(Exception): """General exception for a factory being not able to produce a penalty model.""" class ImpossiblePenaltyModel(FactoryException): """PenaltyModel is impossible to build.""" class MissingPenaltyModel(FactoryException): """PenaltyModel is m...
""" Exceptions ---------- """ class Factoryexception(Exception): """General exception for a factory being not able to produce a penalty model.""" class Impossiblepenaltymodel(FactoryException): """PenaltyModel is impossible to build.""" class Missingpenaltymodel(FactoryException): """PenaltyModel is miss...
# working-with-Data-structure #union def union(set1,set2): return set(set1)&(set2) # driver code Set1={0,2,3,4,5,6,8} Set2={1,2,3,4,5} Print(union(set1,set2)) #intersection def intersection(set1,set2): return set(set1)&(set2) #driver code Set1={0,2,4,6,8} Set2={1,2,4,4,5} Print(intersection(set1,set2)) #diffe...
def union(set1, set2): return set(set1) & set2 set1 = {0, 2, 3, 4, 5, 6, 8} set2 = {1, 2, 3, 4, 5} print(union(set1, set2)) def intersection(set1, set2): return set(set1) & set2 set1 = {0, 2, 4, 6, 8} set2 = {1, 2, 4, 4, 5} print(intersection(set1, set2)) set1 = {0, 2, 3, 4, 5, 6, 8} set2 = {1, 2, 3, 4, 5} set...
class Qint(int): def __init__(self, num): self.qkey = None self.parent = None self.parental_id = None self.name = None self._qint = True
class Qint(int): def __init__(self, num): self.qkey = None self.parent = None self.parental_id = None self.name = None self._qint = True
def testDoc(): """ Test __doc__ """ pass print(abs.__doc__) print(help(abs)) print(int.__doc__) print(testDoc.__doc__) print(help(testDoc))
def test_doc(): """ Test __doc__ """ pass print(abs.__doc__) print(help(abs)) print(int.__doc__) print(testDoc.__doc__) print(help(testDoc))
#!/usr/bin/env python # Analyse des accidents corporels de la circulation a partir des fichiers csv open data # - telecharger les fichiers csv depuis : # https://www.data.gouv.fr/en/datasets/bases-de-donnees-annuelles-des-accidents-corporels-de-la-circulation-routiere-annees-de-2005-a-2019/ # - changer la commune et l...
commune = '92012' annee = 2019 id_acc = [] accidents = {} gravite = {'1': 'indemne', '2': 'tue', '3': 'grave', '4': 'leger'} def get_header(line): h = line.rstrip().replace('"', '').split(';') h = dict(zip(h, range(len(h)))) return h with open('caracteristiques-' + str(annee) + '.csv') as f: head = get...
# n = int(input('Enter the number of time you want to display Hello World!')) # i = 0 ##While Loop # while i < n : # print('Hello World\n') # x += 1 n = input('Enter a number: ') #Check if the input is empty if n == "": print('Nothing to display') else: #For Loop for i in range(int(n)): print(...
n = input('Enter a number: ') if n == '': print('Nothing to display') else: for i in range(int(n)): print('Hello World!')
""" Datos de entrada nombre-->nom-->string monto_comra-->mc-->float Datos de salida nombre-->nom-->string monto_compra-->mp-->float monto_pagar-->mg-->float descuento-->de-->float """ #Entrada nom=str(input("Ingrese nombre del cliente: ")) mc=float(input("Ingrese el monto de compra: ")) #Caja negra if(mc<50000): mg...
""" Datos de entrada nombre-->nom-->string monto_comra-->mc-->float Datos de salida nombre-->nom-->string monto_compra-->mp-->float monto_pagar-->mg-->float descuento-->de-->float """ nom = str(input('Ingrese nombre del cliente: ')) mc = float(input('Ingrese el monto de compra: ')) if mc < 50000: mg = mc de = 0...
class MenuItem: pass # Buat instance untuk class MenuItem menu_item1 = MenuItem()
class Menuitem: pass menu_item1 = menu_item()
# Copyright 2020 Rubrik, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distri...
""" Collection of methods for sonar on demand scan """ error_messages = {'MISSING_PARAMETERS_IN_SCAN': 'scan_name, resources, and analyzer_groups fields are required.', 'MISSING_PARAMETERS_IN_SCAN_STATUS': 'crawl_id field is required.', 'MISSING_PARAMETERS_IN_SCAN_RESULT': 'crawl_id and filters fields are required.', '...
"""This module demonstrates usage of if-else statements, while loop and break.""" def calculate_grade(grade): """Function that calculates final grades based on points earned.""" if grade >= 90: if grade == 100: return 'A+' return 'A' if grade >= 80: return 'B' if gra...
"""This module demonstrates usage of if-else statements, while loop and break.""" def calculate_grade(grade): """Function that calculates final grades based on points earned.""" if grade >= 90: if grade == 100: return 'A+' return 'A' if grade >= 80: return 'B' if gra...
""" Write a Python program to get variable unique identification number or string. """ x = 100 print(format(id(x), "x"))
""" Write a Python program to get variable unique identification number or string. """ x = 100 print(format(id(x), 'x'))
class FederationClientServiceVariables: def __init__(self): self.FederationClientServiceStatus = '' self.FederationClientServicePort = 9000 self.FederationClientServiceIP = None
class Federationclientservicevariables: def __init__(self): self.FederationClientServiceStatus = '' self.FederationClientServicePort = 9000 self.FederationClientServiceIP = None
class Format: def skip(self, line): False def before(self, line): return s, None def after(self, line, data): return s class fastText(Format): LABEL_PREFIX = '__label__' def before(self, line): labels = [] _ = [] for w in line.split(' '): ...
class Format: def skip(self, line): False def before(self, line): return (s, None) def after(self, line, data): return s class Fasttext(Format): label_prefix = '__label__' def before(self, line): labels = [] _ = [] for w in line.split(' '): ...
# Time complexity: O(n) # Approach: Backtracking. Similar to DP 2D array solution. class Solution: def findIp(self, s, index, i, tmp, ans): if i==4: if index >= len(s): ans.append(tmp[1:]) return if index >= len(s): return if s[index]=='0'...
class Solution: def find_ip(self, s, index, i, tmp, ans): if i == 4: if index >= len(s): ans.append(tmp[1:]) return if index >= len(s): return if s[index] == '0': self.findIp(s, index + 1, i + 1, tmp + '.' + s[index], ans) ...
# Just to implement while loop answer = 'no' while answer != 'yes': answer = input( 'Are you done?' ) print( 'Finally Exited.' );
answer = 'no' while answer != 'yes': answer = input('Are you done?') print('Finally Exited.')
base_tree = [{ 'url_delete': 'http://example.com/adminpages/delete/id/1', 'list_of_pk': ('["id", 1]', ), 'id': 1, 'label': u'Hello Traversal World!', 'url_update': 'http://example.com/adminpages/update/id/1', 'children': [{ 'url_delete': 'http://example.com/adminpages/delete/id/2', ...
base_tree = [{'url_delete': 'http://example.com/adminpages/delete/id/1', 'list_of_pk': ('["id", 1]',), 'id': 1, 'label': u'Hello Traversal World!', 'url_update': 'http://example.com/adminpages/update/id/1', 'children': [{'url_delete': 'http://example.com/adminpages/delete/id/2', 'list_of_pk': ('["id", 2]',), 'id': 2, '...
@metadata_reactor def add_backup_key(metadata): return { 'users': { 'root': { 'authorized_keys': { 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDM70gDI1cuIKu15VAEYnlWMFi3zGPf6shtQCzrHBv1nOOkfPdXlXACC4H5+MiTV5foAIA8PUaqOV9gow1w639TnWDL2DwPJ5RsT+P5g4eWszW5xQPo0zAKuvlT...
@metadata_reactor def add_backup_key(metadata): return {'users': {'root': {'authorized_keys': {'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDM70gDI1cuIKu15VAEYnlWMFi3zGPf6shtQCzrHBv1nOOkfPdXlXACC4H5+MiTV5foAIA8PUaqOV9gow1w639TnWDL2DwPJ5RsT+P5g4eWszW5xQPo0zAKuvlTMB9JkDXGx1OpOE4e9n3++71yuvF/wVlqYxJwxeWXCdHf2ayx6OrTMcSMUIi+...
""" CCC '01 J1 - Dressing Up Find this problem at: https://dmoj.ca/problem/ccc01j1 """ height = int(input()) # These are the two parts of the bow tie for half in (range(1, height, 2), range(height, -1, -2)): # Print each line accordingly for i in half: print('*' * i + ' ' * ((height-i)*2) + '*' * i)
""" CCC '01 J1 - Dressing Up Find this problem at: https://dmoj.ca/problem/ccc01j1 """ height = int(input()) for half in (range(1, height, 2), range(height, -1, -2)): for i in half: print('*' * i + ' ' * ((height - i) * 2) + '*' * i)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the ...
""" Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbe...
# This file mainly exists to allow python setup.py test to work. # flake8: noqa def runtests(): pass if __name__ == '__main__': runtests()
def runtests(): pass if __name__ == '__main__': runtests()
line = open("day10.txt", "r").readline() def day10(iterate, sequence): for i in range(iterate): concat = "" first = True second = False sameNumberCounter = 0 secondNum = 0 numCounter = 0 for num in sequence: numCounter += 1 if second ...
line = open('day10.txt', 'r').readline() def day10(iterate, sequence): for i in range(iterate): concat = '' first = True second = False same_number_counter = 0 second_num = 0 num_counter = 0 for num in sequence: num_counter += 1 if sec...
"""Base class for writing hooks.""" class BaseHook(object): """Base class for all hooks.""" KEY = 'hook' NAME = 'Hook' def __init__(self, extension): self.extension = extension @property def pod(self): """Reference to the pod.""" return self.extension.pod # pyli...
"""Base class for writing hooks.""" class Basehook(object): """Base class for all hooks.""" key = 'hook' name = 'Hook' def __init__(self, extension): self.extension = extension @property def pod(self): """Reference to the pod.""" return self.extension.pod def shou...
# Copyright 2015-2021 Mathieu Bernard # # This file is part of phonemizer: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Phonemizer is distributed ...
"""Parse a Scheme expression as a nested list The main function of this module is lispy.parse, other ones should be considered private. This module is a dependency of the festival backend. From http://www.norvig.com/lispy.html """ def parse(program): """Read a Scheme expression from a string Return a neste...
# # PySNMP MIB module ALCATEL-IND1-IPMS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-IPMS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:02:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(softent_ind1_ipms,) = mibBuilder.importSymbols('ALCATEL-IND1-BASE', 'softentIND1Ipms') (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, cons...
num = int(input( "Digite um valor de 0 a 9999: ")) num1 = str(num) num2 = num1.zfill(4) print('Unidade: {}'.format(num2[3])) print('Dezena: {}'.format(num2[2])) print('Centena: {}'.format(num2[1])) print('Milhar: {}'.format(num2[0]))
num = int(input('Digite um valor de 0 a 9999: ')) num1 = str(num) num2 = num1.zfill(4) print('Unidade: {}'.format(num2[3])) print('Dezena: {}'.format(num2[2])) print('Centena: {}'.format(num2[1])) print('Milhar: {}'.format(num2[0]))
builder_layers = { # P-CAD ASCII layer types: # Signal, Plane, NonSignal -1: "null", # LT_UNDEFINED 0: "Signal", # LT_SIGNAL 1: "Plane", # LT_POWER 2: "NonSignal", # LT_MIXED 3: "Plane" # LT_JUMPER } builder_padshapes = { # P-CAD ASCII padshape types: # padViaShapeT...
builder_layers = {-1: 'null', 0: 'Signal', 1: 'Plane', 2: 'NonSignal', 3: 'Plane'} builder_padshapes = {0: 'Ellipse', 1: 'Rect', 2: 'Oval', 3: '', 4: 'RndRect', 5: '', 6: 'Polygon'} builder_font_renderer__stroke = 0 builder_font_renderer__true_type = 2 builder_font_family__serif = 0 builder_font_family__sanserif = 1 bu...
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ temp = str.strip() if not temp: return 0 negative = False resint = 0 head = temp[0] if head == "-": negative = True elif h...
class Solution(object): def my_atoi(self, str): """ :type str: str :rtype: int """ temp = str.strip() if not temp: return 0 negative = False resint = 0 head = temp[0] if head == '-': negative = True elif...
def calc_no(val): temp = val s = 0 while temp > 0: s += temp%10 temp //= 10 return not(val%s) row = int(input()) arr = [] # storing input values for i in range(row): arr.append(list(map(int,input().split()))) bool_tab = [] # storing their resp boolean value if it is divisible by t...
def calc_no(val): temp = val s = 0 while temp > 0: s += temp % 10 temp //= 10 return not val % s row = int(input()) arr = [] for i in range(row): arr.append(list(map(int, input().split()))) bool_tab = [] for i in range(row): x = [] for j in range(len(arr[0])): x.appen...
def weather_conditions(temp): if temp > 7: print("Warm") else: print("Cold") x = int(input("Enter a temparature")) weather_conditions(x)
def weather_conditions(temp): if temp > 7: print('Warm') else: print('Cold') x = int(input('Enter a temparature')) weather_conditions(x)
T = int(input()) for kase in range(1, T + 1): n = int(input()) [input() for i in range(0, n + 1)] if n & 1: print(f'Case #{kase}: 1\n0.0') else: print(f'Case #{kase}: 0')
t = int(input()) for kase in range(1, T + 1): n = int(input()) [input() for i in range(0, n + 1)] if n & 1: print(f'Case #{kase}: 1\n0.0') else: print(f'Case #{kase}: 0')
# https://app.codility.com/demo/results/trainingUJUBFH-2H3/ def solution(X, A): """ DINAKAR Clue -> Find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X [1, 3, 1, 4, 2, 3, 5, 4] X ...
def solution(X, A): """ DINAKAR Clue -> Find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X [1, 3, 1, 4, 2, 3, 5, 4] X = 5 ie. {1, 2, 3, 4, 5} here 1 to X/5 is completed so we re...
# Atharv Kolhar # Python Bytes # https://www.youtube.com/channel/UC71nPTNDEG7oyusXTifvB7g?sub_confirmation=1 """ Tuple """ # Declaration var_tuple = (1, 2, 3) print(var_tuple) print(type(var_tuple)) var_tuple_1 = 1, 2, 3 print(var_tuple_1) print(type(var_tuple_1)) # Function for Tuples # Counting the element repea...
""" Tuple """ var_tuple = (1, 2, 3) print(var_tuple) print(type(var_tuple)) var_tuple_1 = (1, 2, 3) print(var_tuple_1) print(type(var_tuple_1)) var_tuple_2 = (1, 1, 2, 3, 2, 1, 4, 1) print(var_tuple_2.count(1)) print(var_tuple_2.count(4)) print(var_tuple_2.index(1)) print(var_tuple_2.index(1, 2, 6)) var_list_from_tuple...
school_class = {} while True: name = input("Enter the student's name: ") if name == '': break score = int(input("Enter the student's score (0-10): ")) if score not in range(0, 11): break if name in school_class: school_class[name] += (score,) else: school_...
school_class = {} while True: name = input("Enter the student's name: ") if name == '': break score = int(input("Enter the student's score (0-10): ")) if score not in range(0, 11): break if name in school_class: school_class[name] += (score,) else: school_class[na...
with open("day6_input") as infile: cycles = [[int(x) for x in infile.readline().split('\t') if x != '\n']] steps = 0 while True: current_cycle = cycles[-1] max_ = max(current_cycle) maxindex = current_cycle.index(max_) new_cycle = current_cycle[:] new_cycle[maxindex] = 0 for i in range(maxi...
with open('day6_input') as infile: cycles = [[int(x) for x in infile.readline().split('\t') if x != '\n']] steps = 0 while True: current_cycle = cycles[-1] max_ = max(current_cycle) maxindex = current_cycle.index(max_) new_cycle = current_cycle[:] new_cycle[maxindex] = 0 for i in range(maxin...
pattern = [] with open('day_3.txt') as f: for line in f: pattern.append([line.rstrip()]) def count_trees(pattern, right, down): '''Use dictionary to redefine positions outside base pattern, count all trees in pattern (#) which we meet, when we follow defined number of moves to right and down''' ...
pattern = [] with open('day_3.txt') as f: for line in f: pattern.append([line.rstrip()]) def count_trees(pattern, right, down): """Use dictionary to redefine positions outside base pattern, count all trees in pattern (#) which we meet, when we follow defined number of moves to right and down""" ...
''' Dictionary that keeps the cost of individual parts of cars. ''' car_body = { 'Honda' : 500, 'Nissan' : 1000, 'Suzuki' : 600, 'Toyota' : 500 } car_tyres = { 'Honda' : 1400, 'Nissan' : 500, 'Suzuki' : 600, 'Toyota' : 1000 } car_doors = { 'Honda' : 400, 'Nissan': 300, 'Su...
""" Dictionary that keeps the cost of individual parts of cars. """ car_body = {'Honda': 500, 'Nissan': 1000, 'Suzuki': 600, 'Toyota': 500} car_tyres = {'Honda': 1400, 'Nissan': 500, 'Suzuki': 600, 'Toyota': 1000} car_doors = {'Honda': 400, 'Nissan': 300, 'Suzuki': 600, 'Toyota': 800}
class Solution: def findKthPositive(self, arr: List[int], k: int) -> int: missing = [] limit = arr[-1] nums = set(arr) for i in range(1,limit): if i not in nums: missing.append(i) if len(missing) >= k: return missing...
class Solution: def find_kth_positive(self, arr: List[int], k: int) -> int: missing = [] limit = arr[-1] nums = set(arr) for i in range(1, limit): if i not in nums: missing.append(i) if len(missing) >= k: return missing[k - 1] ...
# mendapatkan tagihan bulanan # selamat satu unit lagi dan anda sudah membuat sebuah program! ketika # kita bilang anda bisa membuat apa saja dengan python, kita bersungguh-sungguh! # batas dari apa yang anda bisa bangun adalah di imajinasi anda # terus belajar ke bab berikutnya dan akhirnya anda akan bisa membuat prog...
""" instruksi -oke sekarang kita buat variabel total_tagihan yang merupakan jumlah dari sisa_cicilan dan jumlah_bunga -setelahnya kita buat tagihan_bulanan yang merupakan total_tagihan dibagi 12 -jalankan codenya dan lihat tagihan bulananan anda -ubah angkanya sesuasi yang anda mau dan bermain mainlah dengan apa yang t...
def find(n, m, x, y, dx, dy): if x < 0 or x == 20 or y < 0 or y == 20: return -1 elif n == 0: return 1 else: return m[y][x] * find(n - 1, m, x + dx, y + dy, dx, dy) directions = [None] * 8 for i in range(0, 8): if i == 0: directions[i] = [0, 1] elif i == 1: d...
def find(n, m, x, y, dx, dy): if x < 0 or x == 20 or y < 0 or (y == 20): return -1 elif n == 0: return 1 else: return m[y][x] * find(n - 1, m, x + dx, y + dy, dx, dy) directions = [None] * 8 for i in range(0, 8): if i == 0: directions[i] = [0, 1] elif i == 1: ...
cue_words=["call it as", "call this as", "called as the", "call it as", "referred to as", "is defined as", "known as the", "defined as", "known as", "mean by", "concept of", "talk about", "called as", "called the", "called an", "called a", "call as", "called"]
cue_words = ['call it as', 'call this as', 'called as the', 'call it as', 'referred to as', 'is defined as', 'known as the', 'defined as', 'known as', 'mean by', 'concept of', 'talk about', 'called as', 'called the', 'called an', 'called a', 'call as', 'called']
def nonrep(): checklist=[] my_string={"pythonprograming"} for s in my_string: if s in my_string: my_string[s]+=1 else: my_string=1 checklist.appened(my_string[s]) for s in checklist: if s==1: return True else: F...
def nonrep(): checklist = [] my_string = {'pythonprograming'} for s in my_string: if s in my_string: my_string[s] += 1 else: my_string = 1 checklist.appened(my_string[s]) for s in checklist: if s == 1: return True else: ...
# -*- coding: utf-8 -*- """DQ0 SDK Data Utils Package This package contains general data helper functions. """ __all__ = [ 'util', 'plotting' ]
"""DQ0 SDK Data Utils Package This package contains general data helper functions. """ __all__ = ['util', 'plotting']
REQUEST_BODY_JSON = """ { "verification_details": { "amount": 1.1, "payment_transaction_id": "string", "transaction_type": "PHONE_PAY", "screenshot_url": "string" } } """
request_body_json = '\n{\n "verification_details": {\n "amount": 1.1,\n "payment_transaction_id": "string",\n "transaction_type": "PHONE_PAY",\n "screenshot_url": "string"\n }\n}\n'
#!/usr/bin/env python3 CONVERSION_TABLE = { 'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8, 'IX': 9, 'X': 10, 'XX': 20, 'XXX': 30, 'XL': 40, 'L': 50, 'LX': 60, 'LXX': 70, 'LXXX': 80, 'XC': 90, 'C': 100, 'D': 500,...
conversion_table = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8, 'IX': 9, 'X': 10, 'XX': 20, 'XXX': 30, 'XL': 40, 'L': 50, 'LX': 60, 'LXX': 70, 'LXXX': 80, 'XC': 90, 'C': 100, 'D': 500, 'M': 1000} def roman_to_arabic(roman_value: str) -> int: """ >>> roman_to_arabic("I") 1 ...
''' This file contains any primitives for Lyanna that aren't just borrowed from the language. Basically this is Nothing and Undefined, which are singletons. That is, their classes are stuck here and only selected instances are exported through __all__ ''' class NothingType(object): def __str__(self): retur...
""" This file contains any primitives for Lyanna that aren't just borrowed from the language. Basically this is Nothing and Undefined, which are singletons. That is, their classes are stuck here and only selected instances are exported through __all__ """ class Nothingtype(object): def __str__(self): retu...
def settingDecoder(data): # data can be: # raw string # list of strings data = data.strip() if (len(data) > 1) and (data[0] == '[') and (data[-1] == ']'): data = [x.strip() for x in data[1:-1].split(',')] return data def loadSetting(filename = "SETTINGS"): res = dict() with open...
def setting_decoder(data): data = data.strip() if len(data) > 1 and data[0] == '[' and (data[-1] == ']'): data = [x.strip() for x in data[1:-1].split(',')] return data def load_setting(filename='SETTINGS'): res = dict() with open(filename, 'r') as f: for line in f: sline...
messages = 'game.apps.core.signals.messages.%s' # user.id planet = 'game.apps.core.signals.planet_details.%s' # planetID_requestID account_data = 'game.apps.core.signals.account_data.%s' building = 'game.apps.core.signals.building.%s' # buildingID task_updated = 'game.apps.core.signals.task_updated.%s' # user.i...
messages = 'game.apps.core.signals.messages.%s' planet = 'game.apps.core.signals.planet_details.%s' account_data = 'game.apps.core.signals.account_data.%s' building = 'game.apps.core.signals.building.%s' task_updated = 'game.apps.core.signals.task_updated.%s'
# 39. Combination Sum # Time: O((len(candidates))^(target/avg(candidates))) Review # Space: O(target/avg(candidates))) [depth of recursion tree?]Review class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: result = [] self.util(candidates, target, 0 , [], ...
class Solution: def combination_sum(self, candidates: List[int], target: int) -> List[List[int]]: result = [] self.util(candidates, target, 0, [], result) return result def util(self, candidates, target, start, cur_res, result): if target < 0: return if targ...
class audo: def __init__(self, form, data = None): self.form = form self.values = [] if data: self.load(data) def load(self, data): for i in range(data.readUInt32()): while (data.offset & 3) != 0: data.offset += 1 data.push...
class Audo: def __init__(self, form, data=None): self.form = form self.values = [] if data: self.load(data) def load(self, data): for i in range(data.readUInt32()): while data.offset & 3 != 0: data.offset += 1 data.push(data.r...
# Copyright (C) 2012 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
ipproto_ip = 0 ipproto_hopopts = 0 ipproto_icmp = 1 ipproto_igmp = 2 ipproto_tcp = 6 ipproto_udp = 17 ipproto_routing = 43 ipproto_fragment = 44 ipproto_gre = 47 ipproto_ah = 51 ipproto_icmpv6 = 58 ipproto_none = 59 ipproto_dstopts = 60 ipproto_ospf = 89 ipproto_vrrp = 112 ipproto_sctp = 132
""" MainWindow.setWindowTitle('Physics') self.centralwidget.setLayout(self.gridLayout) version = "v1" """
""" MainWindow.setWindowTitle('Physics') self.centralwidget.setLayout(self.gridLayout) version = "v1" """
lst = [90, 180, 0] empty = [] lst.append(empty) def function_a(): for empty in lst: if empty in lst: print(lst) function_b() function_b() print(lst) def function_b(): for empty in lst: if empty in lst: ...
lst = [90, 180, 0] empty = [] lst.append(empty) def function_a(): for empty in lst: if empty in lst: print(lst) function_b() function_b() print(lst) def function_b(): for empty in lst: if empty in lst: print(lst) function_b() function...
def options_displ(): print( ''' weather now: Displays the current weather weather today: Displays the weather for this day weather tenday: Displays weather for next ten days detailed tenday: Displays ten day weather with extended info weather -t: Disp...
def options_displ(): print('\n weather now: Displays the current weather\n weather today: Displays the weather for this day\n weather tenday: Displays weather for next ten days\n detailed tenday: Displays ten day weather with extended info\n \n weather -t: Displays current ...
class TimelineService(object): @classmethod def get_timeline(cls, officer_allegations): allegations_date = officer_allegations\ .values_list('allegation__incident_date_only', 'start_date')\ .order_by('allegation__incident_date') items = [] for date in allegation...
class Timelineservice(object): @classmethod def get_timeline(cls, officer_allegations): allegations_date = officer_allegations.values_list('allegation__incident_date_only', 'start_date').order_by('allegation__incident_date') items = [] for date in allegations_date: if not da...
l = [int(e) for e in input().split()] for i in range(1, len(l), 2): l[i], l[i - 1] = l[i - 1], l[i] [print(n) for n in l]
l = [int(e) for e in input().split()] for i in range(1, len(l), 2): (l[i], l[i - 1]) = (l[i - 1], l[i]) [print(n) for n in l]
# Description # You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The islan...
class Solution: """ @param grid: a 2D array @return: the perimeter of the island """ def island_perimeter(self, grid): count = 0 for y in range(len(grid)): for x in range(len(grid[0])): if grid[y][x]: if x == 0: ...
# 94. Binary Tree Inorder Traversal # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # recursive def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorder_traversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ans = [] def helper(root): if root.left...
tag = list(map(str, (input()))) vowels = ['A', 'E', 'I', 'O', 'U', 'Y'] if tag[2] in vowels: print("invalid") else: if (int(tag[0])+int(tag[1]))%2==0 and (int(tag[3])+int(tag[4]))%2==0 and (int(tag[4])+int(tag[5]))%2==0 and (int(tag[7])+int(tag[8]))%2==0: print("valid") else: print("...
tag = list(map(str, input())) vowels = ['A', 'E', 'I', 'O', 'U', 'Y'] if tag[2] in vowels: print('invalid') elif (int(tag[0]) + int(tag[1])) % 2 == 0 and (int(tag[3]) + int(tag[4])) % 2 == 0 and ((int(tag[4]) + int(tag[5])) % 2 == 0) and ((int(tag[7]) + int(tag[8])) % 2 == 0): print('valid') else: print('in...
__all__ = ['Simple'] class Simple(object): def __init__(self, func): self.func = func def __call__(self, inputs, params, other): return self.forward(inputs) def forward(self, inputs): return self.func(inputs), None def backward(self, grad_out, cache): return grad_out...
__all__ = ['Simple'] class Simple(object): def __init__(self, func): self.func = func def __call__(self, inputs, params, other): return self.forward(inputs) def forward(self, inputs): return (self.func(inputs), None) def backward(self, grad_out, cache): return grad_o...
class Stats: def getLevelStats(): return [ "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str",...
class Stats: def get_level_stats(): return ['Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Str', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag', 'Mag...
#1. Kod l=[[1,'a',['cat'],2],[[[3]],'dog'],4,5] m = [] def flaten(x): for i in x: if type(i) == list: flaten(i) else: m.append(i) flaten(l) print(m) [1, 'a', 'cat', 2, 3, 'dog', 4, 5] #2.Kod a = [[1, 2], [3, 4], [5, 6, 7]] l=[] for i in range(0,len(a)): a[i].reverse(...
l = [[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5] m = [] def flaten(x): for i in x: if type(i) == list: flaten(i) else: m.append(i) flaten(l) print(m) [1, 'a', 'cat', 2, 3, 'dog', 4, 5] a = [[1, 2], [3, 4], [5, 6, 7]] l = [] for i in range(0, len(a)): a[i].reverse() l...
def anagramSolution(s1,s2): c1 = {} for i in s1: if i in c1: c1[i] = c1[i] + 1 else: c1[i] = 1 for i in s2: anagram = True if i not in c1: anagram = False return anagram return anagram print(anagramSolution('apple','pleap...
def anagram_solution(s1, s2): c1 = {} for i in s1: if i in c1: c1[i] = c1[i] + 1 else: c1[i] = 1 for i in s2: anagram = True if i not in c1: anagram = False return anagram return anagram print(anagram_solution('apple', 'plea...
slimearm = Actor('alien') slimearm.topright = 0, 10 WIDTH = 712 HEIGHT = 508 def draw(): screen.fill((240, 6, 253)) slimearm.draw() def update(): slimearm.left += 2 if slimearm.left > WIDTH: slimearm.right = 0 def on_mouse_down(pos): if slimearm.collidepoint(pos): set_alien_hurt(...
slimearm = actor('alien') slimearm.topright = (0, 10) width = 712 height = 508 def draw(): screen.fill((240, 6, 253)) slimearm.draw() def update(): slimearm.left += 2 if slimearm.left > WIDTH: slimearm.right = 0 def on_mouse_down(pos): if slimearm.collidepoint(pos): set_alien_hurt...
class StringMult: def times(self, sFactor, iFactor): if(sFactor == ""): return "" elif(iFactor == 0): return "" elif(iFactor > 0): return sFactor * iFactor else: reverse = sFactor[::-1] return reverse * abs(iFactor)
class Stringmult: def times(self, sFactor, iFactor): if sFactor == '': return '' elif iFactor == 0: return '' elif iFactor > 0: return sFactor * iFactor else: reverse = sFactor[::-1] return reverse * abs(iFactor)
#!/usr/bin/python # -*- coding: utf-8 -*- class Chapter: def __init__( self, client, json_data, ): """ Constructs all the necessary attributes for the Chapter object. Parameters ---------- json_data : json data in json format...
class Chapter: def __init__(self, client, json_data): """ Constructs all the necessary attributes for the Chapter object. Parameters ---------- json_data : json data in json format. """ self.__json = json_data self.chapter_number ...