content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#PRIME OR NOT num=int(input('Enter a number')) if num<=1: print('Please enter a valid number') for i in range(2,num): if(num % i == 0): print("The number is not prime number") break else: print('The number is a prime number')
num = int(input('Enter a number')) if num <= 1: print('Please enter a valid number') for i in range(2, num): if num % i == 0: print('The number is not prime number') break else: print('The number is a prime number')
def serialize_suggestions_values_response(result): try: field_values = result["aggregations"]["values"]["buckets"] except KeyError: field_values = [] return field_values def serialize_mappings(mappings): result = [] for field in mappings: result.append({"name": field.name, ...
def serialize_suggestions_values_response(result): try: field_values = result['aggregations']['values']['buckets'] except KeyError: field_values = [] return field_values def serialize_mappings(mappings): result = [] for field in mappings: result.append({'name': field.name, '...
with open('02.txt', 'r') as f: data = f.read() player_1_data, player_2_data = data.split('\n\n') player_1_cards = list(map(int, player_1_data.split(':')[1].split())) player_2_cards = list(map(int, player_2_data.split(':')[1].split())) while player_1_cards and player_2_cards: card_1 = player_1_cards.pop(0) ...
with open('02.txt', 'r') as f: data = f.read() (player_1_data, player_2_data) = data.split('\n\n') player_1_cards = list(map(int, player_1_data.split(':')[1].split())) player_2_cards = list(map(int, player_2_data.split(':')[1].split())) while player_1_cards and player_2_cards: card_1 = player_1_cards.pop(0)...
# -*- coding: utf-8 -*- # file: TextProcessor.py # date: 2022-03-08 class TextProcessor(object): def __init__(self): pass
class Textprocessor(object): def __init__(self): pass
class Solution: # @param s, a string # @param wordDict, a set<string> # @return a boolean def wordBreak(self, s, wordDict): dym = [True] for i in range(1, len(s)+1): dym.append(False) for word in wordDict: l = len(word) if l <= i an...
class Solution: def word_break(self, s, wordDict): dym = [True] for i in range(1, len(s) + 1): dym.append(False) for word in wordDict: l = len(word) if l <= i and dym[i - l] and (s.find(word, i - l, i) >= 0): dym[-1] = True...
__author__ = "Alex Laird" __copyright__ = "Copyright 2020, Alex Laird" __version__ = "4.1.0" class PyngrokError(Exception): """ Raised when a general ``pyngrok`` error has occurred. """ pass class PyngrokSecurityError(PyngrokError): """ Raised when a ``pyngrok`` security error has occurred. ...
__author__ = 'Alex Laird' __copyright__ = 'Copyright 2020, Alex Laird' __version__ = '4.1.0' class Pyngrokerror(Exception): """ Raised when a general ``pyngrok`` error has occurred. """ pass class Pyngroksecurityerror(PyngrokError): """ Raised when a ``pyngrok`` security error has occurred. ...
# En este script hacemos operaciones basicas # 13 de sept 2021 suma = 5 + 2 resta = suma - 8.5 m1 = 32 m2 = 64 multiplicacion = m1 * m2 print("Este programa acaba de hacer algunas operaciones") print('la suma dio como resultado: ') print(suma) print('la resta dio como resultado: ', resta) # la resta dio como resultado:...
suma = 5 + 2 resta = suma - 8.5 m1 = 32 m2 = 64 multiplicacion = m1 * m2 print('Este programa acaba de hacer algunas operaciones') print('la suma dio como resultado: ') print(suma) print('la resta dio como resultado: ', resta) print('la multiplicacion dio como resultado: ', multiplicacion) print(m2, '/', m1, ' = ', m2 ...
''' This is the binary search tree implementation. ''' class BinSearchTree(): class Node(): def __init__(self, key, parent, data, left_child, right_child): self.key = key self.parent = parent self.data = data self.left = left_child self.right = ...
""" This is the binary search tree implementation. """ class Binsearchtree: class Node: def __init__(self, key, parent, data, left_child, right_child): self.key = key self.parent = parent self.data = data self.left = left_child self.right = righ...
#// AUTHOR: Guruprasanna #// Python3 Concept: sha384(hashing) #// GITHUB: https://github.com/Guruprasanna02 #// Add your python3 concept below #SHA384 hashing implementation manaually. def rightrotate_64(i, j): i &= 0xFFFFFFFFFFFFFFFF return ((i >> j) | (i << (64 - j))) & 0xFFFFFFFFFFFFFFFF def leftrotate...
def rightrotate_64(i, j): i &= 18446744073709551615 return (i >> j | i << 64 - j) & 18446744073709551615 def leftrotate_64(i, j): i &= 18446744073709551615 return (i << j | i >> 64 - j) & 18446744073709551615 def leftshift(i, j): return i << j def rightshift(i, j): return i >> j class Sha384...
# Start of Lesson 3 bubbles = [1,2,3,4,5,6] n = 9 def find(n,array): ''' This function looks for n in a list ''' for item in array: if item == n: return True return False print(find(n,bubbles)) ''' index = 0 isFound = False while isFound == False: item = bubbl...
bubbles = [1, 2, 3, 4, 5, 6] n = 9 def find(n, array): """ This function looks for n in a list """ for item in array: if item == n: return True return False print(find(n, bubbles)) "\nindex = 0\nisFound = False\n\nwhile isFound == False: \n item = bubbles[index]\n if item ...
class Deque: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def add_front(self, item): self.items.insert(0, item) def add_rear(self, item): self.items.append(item) def remove_front(self): return self.items.pop(0) def ...
class Deque: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def add_front(self, item): self.items.insert(0, item) def add_rear(self, item): self.items.append(item) def remove_front(self): return self.items.pop(0) def ...
# # PySNMP MIB module ASCEND-MIBATMSIG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBATMSIG-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:26:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
(configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration') (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_inters...
# Copyright 2020 StreamSets Inc. # # 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 by applicable law or agreed to in writi...
def get_xml_output_field(origin, output_field, *root_elements): if getattr(origin, 'preserve_root_element', False): for element in root_elements: output_field = output_field[element] return output_field
def main(): pass # wip
def main(): pass
# Dictionary # : is used to specify the key data = {1: "pvd", 2: "vsd", 3: "rhd"} print(data) # fetching a particular value print(data[2]) # functions can be used print(data.get(3)) print(data.get(4, "Not found")) # dictionary with lists keys = ["pvd", "vsd", "rhd"] val = ["c", "php", "c++"] data = dict( zip(ke...
data = {1: 'pvd', 2: 'vsd', 3: 'rhd'} print(data) print(data[2]) print(data.get(3)) print(data.get(4, 'Not found')) keys = ['pvd', 'vsd', 'rhd'] val = ['c', 'php', 'c++'] data = dict(zip(keys, val)) print(data) data['avd'] = 'js' print(data) del data['avd'] print(data) prog = {'js': 'atom', 'cs': 'vs', 'python': ['PyCh...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ def iter(node): ...
class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ def iter(node): if node == None: return [0, 0] l = iter(node.left) r = iter(node.right) return [max(l[0], l[1]) + max(r[0], ...
"""Module contains utilities to improve the interface with benchling.""" def only_label_feature(part: "BasicPart") -> "BasicPart": """Return part with only the label feature. Useful for getting rid of ApEinfo features following Benchling exports. Args: part: object to simplify each feature i...
"""Module contains utilities to improve the interface with benchling.""" def only_label_feature(part: 'BasicPart') -> 'BasicPart': """Return part with only the label feature. Useful for getting rid of ApEinfo features following Benchling exports. Args: part: object to simplify each feature in...
def toggle_batch_norm(config: dict, layer_id: int): batch_norm = config['model']['conv_layers'][layer_id].get('batch_norm', False) config['model']['conv_layers'][layer_id]['batch_norm'] = not batch_norm def add_conv_layer(config: dict, num_filters: int, kernel_size: int, batch_norm: bool = False): config[...
def toggle_batch_norm(config: dict, layer_id: int): batch_norm = config['model']['conv_layers'][layer_id].get('batch_norm', False) config['model']['conv_layers'][layer_id]['batch_norm'] = not batch_norm def add_conv_layer(config: dict, num_filters: int, kernel_size: int, batch_norm: bool=False): config['mo...
class CommissionScheme: def __init__(self, scheme: str): self.name = scheme self.commission = 0 def calculate_commission(self, quantity: float, price: float) -> float: # Avanza.se if self.name == 'avanza_...
class Commissionscheme: def __init__(self, scheme: str): self.name = scheme self.commission = 0 def calculate_commission(self, quantity: float, price: float) -> float: if self.name == 'avanza_mini': min_com = 1.0 trans_com = quantity * price * 0.0025 ...
f1 = 'psychoticism' f2 = 'neuroticism' f3 = 'extraversion' f4 = 'lie' factors_names = (f1,f2,f3,f4) factors = { 1:{ 22 :(f1,) , 26 :(f1,) , 30 :(f1,) , 33 :(f1,) , 43 :(f1,) , 46 :(f1,) , 50 :(f1,) , 65 :(f1,) , 67 :(f1,) , 74 :(f1,)...
f1 = 'psychoticism' f2 = 'neuroticism' f3 = 'extraversion' f4 = 'lie' factors_names = (f1, f2, f3, f4) factors = {1: {22: (f1,), 26: (f1,), 30: (f1,), 33: (f1,), 43: (f1,), 46: (f1,), 50: (f1,), 65: (f1,), 67: (f1,), 74: (f1,), 76: (f1,), 79: (f1,), 83: (f1,), 87: (f1,), 3: (f2,), 7: (f2,), 12: (f2,), 15: (f2,), 19: (f...
HARI = ( ("Senin","Senin"), ("Selasa","Selasa"), ("Rabu","Rabu"), ("Kamis","Kamis"), ("Jumat","Jumat"), )
hari = (('Senin', 'Senin'), ('Selasa', 'Selasa'), ('Rabu', 'Rabu'), ('Kamis', 'Kamis'), ('Jumat', 'Jumat'))
def hamming_dist(s1, s2): ''' returns: pass in: ''' if len(s1) != len(s2): raise ValueError("Hamming dist undefined for two strings of unequal length") return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
def hamming_dist(s1, s2): """ returns: pass in: """ if len(s1) != len(s2): raise value_error('Hamming dist undefined for two strings of unequal length') return sum((ch1 != ch2 for (ch1, ch2) in zip(s1, s2)))
#!/usr/bin/env python # # ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University of Chicago # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://ge...
__all__ = ['FrictionModel', 'StaticFriction', 'SlipWeakening', 'SlipWeakeningTime', 'SlipWeakeningTimeStable', 'RateStateAgeing', 'TimeWeakening']
class ReverseProxied(object): """This middleware can be applied to add HTTP proxy support to an application which access the WSGI environment directly. It sets `REMOTE_ADDR`, `HTTP_HOST`, `wsgi.url_scheme` from `X-Forwarded` headers. Also front-end server can be configured to quietly bind this to a URL ...
class Reverseproxied(object): """This middleware can be applied to add HTTP proxy support to an application which access the WSGI environment directly. It sets `REMOTE_ADDR`, `HTTP_HOST`, `wsgi.url_scheme` from `X-Forwarded` headers. Also front-end server can be configured to quietly bind this to a URL ...
# -*- coding: utf-8 -*- '''Autor: Alessandra Souza Data: 05/05/2017 Objetivo: Calculo de salario liquido. ID Urionlinejudge: 1008.''' NUMBER=int(input()) horast=int(input()) valhr=float(input()) SALARY = (valhr*horast) print("NUMBER = %d" %NUMBER) print("SALARY = U$ %.2f" %SALARY)
"""Autor: Alessandra Souza Data: 05/05/2017 Objetivo: Calculo de salario liquido. ID Urionlinejudge: 1008.""" number = int(input()) horast = int(input()) valhr = float(input()) salary = valhr * horast print('NUMBER = %d' % NUMBER) print('SALARY = U$ %.2f' % SALARY)
"""Merge and sort two arrays into one.""" def sort_array_buf(a, b): if b == [] or a == []: return None i = len(a) - 1 j = len(b) - 1 k = i - j - 1 if k < 0: return None while i >= 0 and j >= 0 and k >= 0: if a[k] >= b[j]: a[i] = a[k] k ...
"""Merge and sort two arrays into one.""" def sort_array_buf(a, b): if b == [] or a == []: return None i = len(a) - 1 j = len(b) - 1 k = i - j - 1 if k < 0: return None while i >= 0 and j >= 0 and (k >= 0): if a[k] >= b[j]: a[i] = a[k] k -= 1 ...
data = list(input().split()) counter = 0 for x in range(int(data[1])): word = sorted(list(input())) check = sorted(list(data[0])) if word == check: counter += 1 print(counter)
data = list(input().split()) counter = 0 for x in range(int(data[1])): word = sorted(list(input())) check = sorted(list(data[0])) if word == check: counter += 1 print(counter)
colors = [ 'purple', 'blue', 'red', ]
colors = ['purple', 'blue', 'red']
words = "Life is short" upper_word_list = ["LIFE", "IS", "SHORT", "USE", "PYTHON"] lower_word_list = [ lower_w for w in upper_word_list if (lower_w := w.lower()) in words.lower() ] print(" ".join(lower_word_list))
words = 'Life is short' upper_word_list = ['LIFE', 'IS', 'SHORT', 'USE', 'PYTHON'] lower_word_list = [lower_w for w in upper_word_list if (lower_w := w.lower()) in words.lower()] print(' '.join(lower_word_list))
def respuesta(cells, cell_data, phy_lin): """Extracts the nodes located at the physical line phy_line Parameters ---------- cell : dictionary Dictionary created by meshio with cells information. cell_data: dictionary Dictionary created by meshio with ...
def respuesta(cells, cell_data, phy_lin): """Extracts the nodes located at the physical line phy_line Parameters ---------- cell : dictionary Dictionary created by meshio with cells information. cell_data: dictionary Dictionary created by meshio with cells dat...
class BibleVersionNotSupportedException(Exception): code = 600 def __init__(self, message='Bible version was not supported'): # Call the base class constructor with the parameters it needs super().__init__(message) # Now for your custom code... self.error = { 'code'...
class Bibleversionnotsupportedexception(Exception): code = 600 def __init__(self, message='Bible version was not supported'): super().__init__(message) self.error = {'code': self.code, 'message': message}
""" import turtle as t for x in range(4): t.forward(100) t.right(90) """ """ import turtle # edit this line to control where window appears turtle.setup(width=500, height=500, startx=-1, starty=0) turtle.forward(100) """ """ from turtle import * turtle = Turtle() print(turtle.position()) turtle.forward(...
""" import turtle as t for x in range(4): t.forward(100) t.right(90) """ ' import turtle\n\n# edit this line to control where window appears\nturtle.setup(width=500, height=500, startx=-1, starty=0)\n\nturtle.forward(100) ' ' from turtle import *\n\nturtle = Turtle()\n\nprint(turtle.position())\nturtle.forwar...
def check(mark): if mark > 100: return None elif mark >= 80: return 4.00 elif mark >= 75: return 3.75 elif mark >= 70: return 3.50 elif mark >= 65: return 3.25 elif mark >= 60: return 3.00 elif mark >= 55: return 2.75 elif mark >= 5...
def check(mark): if mark > 100: return None elif mark >= 80: return 4.0 elif mark >= 75: return 3.75 elif mark >= 70: return 3.5 elif mark >= 65: return 3.25 elif mark >= 60: return 3.0 elif mark >= 55: return 2.75 elif mark >= 50: ...
# -*- coding: utf-8 -*- """ @ Author: Sandip Dutta -------------------------------------------------------------- Code for Modular Exponentiation Modular Exponentiation is an algorithm for calculating (a^b) % m fast. a^b is useful for us but it's value may be large and it might overflow. So we calculate (a^b...
""" @ Author: Sandip Dutta -------------------------------------------------------------- Code for Modular Exponentiation Modular Exponentiation is an algorithm for calculating (a^b) % m fast. a^b is useful for us but it's value may be large and it might overflow. So we calculate (a^b) % m. The idea of modular expon...
filenames = ['the-big-picture.md', 'inspecting.md', 'download-html.md', 'create-soup-and-search.md', 'scrape-data-from-tag.md', 'project1-basketball-data-from-nba.md', 'project2-game-data-from-steam.md', 'project3-movie-data-from-imdb.md', 'project4-product-data-from-amazon.md' ] with open('book.md', 'w') as outfile: ...
filenames = ['the-big-picture.md', 'inspecting.md', 'download-html.md', 'create-soup-and-search.md', 'scrape-data-from-tag.md', 'project1-basketball-data-from-nba.md', 'project2-game-data-from-steam.md', 'project3-movie-data-from-imdb.md', 'project4-product-data-from-amazon.md'] with open('book.md', 'w') as outfile: ...
def fbx_template_def_texture_file(scene, settings, override_defaults=None, nbr_users=0): # WIP... # XXX Not sure about all names! props = OrderedDict(( (b"TextureTypeUse", (0, "p_enum", False)), # Standard. (b"AlphaSource", (2, "p_enum", False)), # Black (i.e. texture's alpha), XXX name gu...
def fbx_template_def_texture_file(scene, settings, override_defaults=None, nbr_users=0): props = ordered_dict(((b'TextureTypeUse', (0, 'p_enum', False)), (b'AlphaSource', (2, 'p_enum', False)), (b'Texture alpha', (1.0, 'p_double', False)), (b'PremultiplyAlpha', (True, 'p_bool', False)), (b'CurrentTextureBlendMode',...
#!/usr/bin/python3.6 ##### Sieve of Eratosthenes ##### """ Calculates prime numbers, Enter the upper range of Primes.""" def seiveoferatosthenes(num): primes = [i for i in range(2, num+1)] i = 0 while i < len(primes): p = primes[i] j = i + 1 while j < len(primes): if p...
""" Calculates prime numbers, Enter the upper range of Primes.""" def seiveoferatosthenes(num): primes = [i for i in range(2, num + 1)] i = 0 while i < len(primes): p = primes[i] j = i + 1 while j < len(primes): if primes[j] % p == 0: primes.remove(primes...
expected_output = { 'status': 'enabled', 'ssh_port': '830', 'candidate_datastore_status': 'enabled' }
expected_output = {'status': 'enabled', 'ssh_port': '830', 'candidate_datastore_status': 'enabled'}
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # # Copyright (c) 2016 Richard Hull # # 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 wit...
class Common(object): displayoff = 174 displayon = 175 displayallon = 165 displayallon_resume = 164 normaldisplay = 166 invertdisplay = 167 setremap = 160 setmultiplex = 168 class Ssd1306(common): chargepump = 141 columnaddr = 33 comscandec = 200 comscaninc = 192 ext...
# -*- coding: utf-8 -*- class ModuleDocFragment(object): # Git doc fragment DOCUMENTATION = ''' options: git_token: description: - Git token used for authentication - Required if I(git_username=None) - If not set, the value of the C(GIT_TOKEN) environment variab...
class Moduledocfragment(object): documentation = '\noptions:\n git_token:\n description:\n - Git token used for authentication\n - Required if I(git_username=None)\n - If not set, the value of the C(GIT_TOKEN) environment variable is used.\n type: str\n requi...
"""A collection of functions for doing my project.""" def string_concatenator(string1, string2): """Combines strings together by adding them and returning the combination as an output. Parameters ---------- string1 : string String that will be added to another string. str...
"""A collection of functions for doing my project.""" def string_concatenator(string1, string2): """Combines strings together by adding them and returning the combination as an output. Parameters ---------- string1 : string String that will be added to another string. str...
#!/usr/bin/env python3 def unit_fraction(d): n = 10 while True: yield n//d, n%d n = 10*(n%d) def longest_chain(d): encountered = [] for pair in unit_fraction(d): if pair in encountered: return len(encountered[encountered.index(pair):]) else: enco...
def unit_fraction(d): n = 10 while True: yield (n // d, n % d) n = 10 * (n % d) def longest_chain(d): encountered = [] for pair in unit_fraction(d): if pair in encountered: return len(encountered[encountered.index(pair):]) else: encountered.append...
""" Power digit sum 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? Answer: 1366 """ def power_digit_sum(base, power): """Return the sum of the digtis in base**power""" return sum([int(...
""" Power digit sum 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? Answer: 1366 """ def power_digit_sum(base, power): """Return the sum of the digtis in base**power""" return sum([int(...
class Decision(object): def __init__(self, action=None): self.action = action def get_action(self): return self.action def decision(self): action = self.get_action() if action == 4: return "open" elif action == 6: return "fold" elif a...
class Decision(object): def __init__(self, action=None): self.action = action def get_action(self): return self.action def decision(self): action = self.get_action() if action == 4: return 'open' elif action == 6: return 'fold' elif ...
class Solution: def permute(self, nums: [int]) -> [[int]]: if len(nums) <= 1: return [nums] ans = [] perms = self.permute(nums[1:]) for perm in perms: for i in range(0, len(perm) + 1): p = perm[:i] + [nums[0]] + perm[i:] ans.app...
class Solution: def permute(self, nums: [int]) -> [[int]]: if len(nums) <= 1: return [nums] ans = [] perms = self.permute(nums[1:]) for perm in perms: for i in range(0, len(perm) + 1): p = perm[:i] + [nums[0]] + perm[i:] ans.ap...
def get_summary(name = "Daisi user"): text = ''' This Daisi is a simple endpoint to a *Hello World* function, with a straightforward Streamlit app. Call the `hello()` endpoint in Python with `pydaisi`: ```python import pydaisi as pyd print_hello_app = pyd.Daisi("Print Hello App") gre...
def get_summary(name='Daisi user'): text = '\n\n This Daisi is a simple endpoint to a *Hello World* function, with a straightforward\n Streamlit app.\n\n Call the `hello()` endpoint in Python with `pydaisi`:\n\n ```python\n import pydaisi as pyd\n\n print_hello_app = pyd.Daisi("Print Hello App")\n...
def image(request, id): return HttpResponse(open(directory.settings.DIRNAME + "/static/images/profile/" + id, "rb").read(), mimetype = directory.models.Entity.objects.filter(id = int(id))[0].image_mimetype)
def image(request, id): return http_response(open(directory.settings.DIRNAME + '/static/images/profile/' + id, 'rb').read(), mimetype=directory.models.Entity.objects.filter(id=int(id))[0].image_mimetype)
#!/usr/bin/python3 """defines a class Square""" class Square: """Represents a square Attributes: __size (int): size of a side of the square """ def __init__(self, size=0): """initializes the square Args: size (int): size of a side of the square Returns: ...
"""defines a class Square""" class Square: """Represents a square Attributes: __size (int): size of a side of the square """ def __init__(self, size=0): """initializes the square Args: size (int): size of a side of the square Returns: None ...
def user_id_validator(source_function): """Function which can be used as a decorator to validate the user id""" def function_wrapper(*args, **kwargs): exe_res = source_function(*args, **kwargs) return exe_res return function_wrapper @user_id_validator def sample_function(arg1, arg2): ...
def user_id_validator(source_function): """Function which can be used as a decorator to validate the user id""" def function_wrapper(*args, **kwargs): exe_res = source_function(*args, **kwargs) return exe_res return function_wrapper @user_id_validator def sample_function(arg1, arg2): "...
def score_game(frames): total = 0 for index, frame in enumerate(frames): # frame => (10, 0) # 14, frame+1 => (2, 2) # 4 frame_total = sum(frame) if frame[0] == 10: total += sum(frames[index + 1]) # if frames[index + 2][0] == 10: # total += frames...
def score_game(frames): total = 0 for (index, frame) in enumerate(frames): frame_total = sum(frame) if frame[0] == 10: total += sum(frames[index + 1]) elif frame_total == 10: total += frames[index + 1][0] total += frame_total return total
class LocalCommunicationService: __hotword_file = "/home/pi/teddy-vision/hotword.txt" __instance = None @staticmethod def getInstance(): if LocalCommunicationService.__instance == None: LocalCommunicationService() return LocalCommunicationService.__instance def __init__...
class Localcommunicationservice: __hotword_file = '/home/pi/teddy-vision/hotword.txt' __instance = None @staticmethod def get_instance(): if LocalCommunicationService.__instance == None: local_communication_service() return LocalCommunicationService.__instance def __ini...
# Three stones are on a number line at positions a, b, and c. # Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, z with x < y < z. You pick u...
def sum(a, b, c): count = b - a - 1 + (c - b - 1) return count def num_move(a, b, c): """ :type a: int :type b: int :type c: int :rtype: List[int] """ list = [a, b, c] list.sort() max_num = sum(list[0], list[1], list[2]) min_num = 0 print(list) if max_num != 0: ...
def ha_muito_tempo_atras(): n = int(input()) for i in range(n): anos = int(input()) if anos > 2014: print(f'{anos-2014} A.C.') else: print(f'{2015-anos} D.C.') ha_muito_tempo_atras()
def ha_muito_tempo_atras(): n = int(input()) for i in range(n): anos = int(input()) if anos > 2014: print(f'{anos - 2014} A.C.') else: print(f'{2015 - anos} D.C.') ha_muito_tempo_atras()
# Problem Set 5 - Problem 3 - CiphertextMessage # # Released 2021-07-07 14:00 UTC+00 # Started 2021-07-08 04:25 UTC+00 # Finished 2021-07-08 04:28 UTC+00 # https://github.com/lcsm29/edx-mit-6.00.1x # # oooo w r i t t e n b y .oooo. .ooooo. # `888 ...
class Ciphertextmessage(Message): def __init__(self, text): """ Initializes a CiphertextMessage object text (string): the message's text a CiphertextMessage object has two attributes: self.message_text (string, determined by input text) self...
# set representation to bit representation and then return answer # to read input form file a,arr= [],[] start,end = 3,4 with open('Naive Algo\Input\Toycontext(bit)') as file: for line in file: line = line.strip() for c in line: if c != ' ': # print(int(c)) ...
(a, arr) = ([], []) (start, end) = (3, 4) with open('Naive Algo\\Input\\Toycontext(bit)') as file: for line in file: line = line.strip() for c in line: if c != ' ': a.append(int(c)) arr.append(a) a = [] rows = arr[-1][0] cols = 0 for i in range(len(arr)): ...
# # PySNMP MIB module PANDATEL-FHFL-MODEM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PANDATEL-FHFL-MODEM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:28:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ...
# A function to check whether all salaries are equal def areAllEqual(array): s = set(array) if(len(s)==1): return True else: return False # Main code starts here testCases = int(input()) for x in range(testCases): moveCount=0 salArray = [] n = int(input()) for j in range(n):...
def are_all_equal(array): s = set(array) if len(s) == 1: return True else: return False test_cases = int(input()) for x in range(testCases): move_count = 0 sal_array = [] n = int(input()) for j in range(n): element = int(input()) salArray.append(element) p...
""" Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ ...
""" Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \\ / / / \\ 3 2 1 1 3 2 / / \\ ...
#!/usr/bin/env python3 st = "I am a string."; #intializes string variable print(type(st)); #prints the data type of st y = True; #initializes true boolean variable print(type(y)); #prints the data type of y n = False; #initializes false boolean variable print(type(n)); #prints the data type of n alpha_list = ["a...
st = 'I am a string.' print(type(st)) y = True print(type(y)) n = False print(type(n)) alpha_list = ['a', 'b', 'c'] print(type(alpha_list)) print(type(alpha_list[0])) alpha_list.append('d') print(alpha_list) alpha_tuple = ('a', 'b', 'c') print(type(alpha_tuple)) try: alpha_tuple[2] = 'd' except TypeError: print...
""" Q509 Fibonacci number Easy The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). """ class Solutio...
""" Q509 Fibonacci number Easy The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). """ class Solution...
class Foldable: """ A foldable is a data structure that can be collapsed into a single value. """ def fold(self, f, z): """ Apply a two-parameter function `f` to each element of the foldable structure `t a`, passing the result onto the next element. An initial ...
class Foldable: """ A foldable is a data structure that can be collapsed into a single value. """ def fold(self, f, z): """ Apply a two-parameter function `f` to each element of the foldable structure `t a`, passing the result onto the next element. An initial value `z` ...
"""workflow_common - common lib for workflow plugins""" __version__ = '0.0.1' __author__ = 'misdirectedpuffin <misdirectedpuffin@gmail.com>' __all__ = []
"""workflow_common - common lib for workflow plugins""" __version__ = '0.0.1' __author__ = 'misdirectedpuffin <misdirectedpuffin@gmail.com>' __all__ = []
lst1 = input("First input: ") lst2 = input("Second input: ") lst1 = lst1.split() lst2 = lst2.split() lst2 = sorted(lst2) templst = [] count = 0 while count < int(lst1[1]): #running the loop for k times for elm in lst2: elm = int(elm) if elm <5: #checking if the player is acceptab...
lst1 = input('First input: ') lst2 = input('Second input: ') lst1 = lst1.split() lst2 = lst2.split() lst2 = sorted(lst2) templst = [] count = 0 while count < int(lst1[1]): for elm in lst2: elm = int(elm) if elm < 5: elm += 1 templst.append(elm) lst2 = templst.copy() t...
class BinarySearchTree: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, to_add): if self.value > to_add: if self.left: self.left.insert(to_add) else: self.left = BinarySear...
class Binarysearchtree: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, to_add): if self.value > to_add: if self.left: self.left.insert(to_add) else: self.left = binary_sea...
class Continuous: def __init__(self, cont): self.cont = cont self.string = "ing" vowels = "aeiou" # Get vowels res = set([each for each in cont if each in vowels]) #Convert to string res = ''.join(res) #The exceptions in English if co...
class Continuous: def __init__(self, cont): self.cont = cont self.string = 'ing' vowels = 'aeiou' res = set([each for each in cont if each in vowels]) res = ''.join(res) if cont[-1] == 't' and cont[-2] == res: print(cont + cont[-1] + self.string) ...
class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': rotateindex = 0 n = len(nums) for i in range(n - 1): if nums[i] > nums[i + 1]: rotateindex = i + 1 break left = 0 right = n - 1 while left <= right...
class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': rotateindex = 0 n = len(nums) for i in range(n - 1): if nums[i] > nums[i + 1]: rotateindex = i + 1 break left = 0 right = n - 1 while left <= righ...
class ZBException(Exception): pass class ZBApiException(ZBException): pass class ZBMissingApiKeyException(ZBException): pass
class Zbexception(Exception): pass class Zbapiexception(ZBException): pass class Zbmissingapikeyexception(ZBException): pass
#!/usr/bin/env python3 def has_cycle(head): curr = head seen = set() while curr: if curr in seen: return True seen.add(curr) curr = curr.next return False # Much better to understand def has_cycle(head): fast = head; while (fast != None and fast.next != None...
def has_cycle(head): curr = head seen = set() while curr: if curr in seen: return True seen.add(curr) curr = curr.next return False def has_cycle(head): fast = head while fast != None and fast.next != None: fast = fast.next.next head = head.ne...
__author__ = 'pavelkosicin' def test_validation_check_invalid_email_short_password(app): app.validation.enter_wrong_data(username="p", password="a") app.validation.check_invalid_email_short_password_error_message()
__author__ = 'pavelkosicin' def test_validation_check_invalid_email_short_password(app): app.validation.enter_wrong_data(username='p', password='a') app.validation.check_invalid_email_short_password_error_message()
#!/usr/bin/env python __version__ = '0.9.4'
__version__ = '0.9.4'
X, Y = map(int, input().split()) flag = False for i in range(100): for j in range(100): if i+j == X and 2*i+4*j == Y: flag = True if flag: print("Yes") else: print("No")
(x, y) = map(int, input().split()) flag = False for i in range(100): for j in range(100): if i + j == X and 2 * i + 4 * j == Y: flag = True if flag: print('Yes') else: print('No')
class Solution: """ @param nums: A list of integers @return: A integer indicate the sum of max subarray """ def maxSubArray(self, nums): if len(nums) > 0: maxSum = nums[0] previousSum = nums[0] # maxSumSubArray=[] # currentArray=[nums[0]] ...
class Solution: """ @param nums: A list of integers @return: A integer indicate the sum of max subarray """ def max_sub_array(self, nums): if len(nums) > 0: max_sum = nums[0] previous_sum = nums[0] for i in range(1, len(nums)): if previous...
def forceAspect(ax, aspect): """ Forces the aspect ratio of an axis onto which an image what plotted with imshow. From: https://www.science-emergence.com/Articles/How-to-change-imshow-aspect-ratio-in-matplotlib-/ """ im = ax.get_images() extent = im[0].get_extent() ax.set_asp...
def force_aspect(ax, aspect): """ Forces the aspect ratio of an axis onto which an image what plotted with imshow. From: https://www.science-emergence.com/Articles/How-to-change-imshow-aspect-ratio-in-matplotlib-/ """ im = ax.get_images() extent = im[0].get_extent() ax.set_as...
# Problem Statement : Given a number A, find the smallest number that has same set of digits as A and is greater than A. # Time Complexity : O(N) def SmallestNumberSameSetOfDigitsAsA(A): A_list = list(map(int, A)) l = len(A_list) i = 0 # First we loop in the reverse order to find if there ...
def smallest_number_same_set_of_digits_as_a(A): a_list = list(map(int, A)) l = len(A_list) i = 0 for i in range(l - 1, 0, -1): if A_list[i] > A_list[i - 1]: break if i == 1 and A_list[i] <= A_list[i - 1]: return -1 if i == 0: return -1 pos = i x = A_li...
def imposto_de_renda(salario): if 0 <= salario <= 2000.0: return print('Isento') elif 2000.01 <= salario <= 3000.0: imposto_sobre_salario = imposto_de_8(salario) elif 3000.01 <= salario <= 4500.0: imposto_sobre_salario = imposto_de_18(salario) elif salario > 4500.00: impo...
def imposto_de_renda(salario): if 0 <= salario <= 2000.0: return print('Isento') elif 2000.01 <= salario <= 3000.0: imposto_sobre_salario = imposto_de_8(salario) elif 3000.01 <= salario <= 4500.0: imposto_sobre_salario = imposto_de_18(salario) elif salario > 4500.0: impos...
x=[] for i in range(10): x.append(int(input())) if x[i]<=0:x[i]=1 for i in range(10):print(f"X[{i}] = {x[i]}")
x = [] for i in range(10): x.append(int(input())) if x[i] <= 0: x[i] = 1 for i in range(10): print(f'X[{i}] = {x[i]}')
class BFC: order_id = 80 menu = {} def __init__(self) -> None: self.menu = {} def addChicken(self,*args): for elm in range(0,len(args),2): BFC.menu[args[elm]] = args[elm+1] def placeOrderof(self,obj): sum1 = 0 BFC.order_id += 1 print(f"Order ID: {B...
class Bfc: order_id = 80 menu = {} def __init__(self) -> None: self.menu = {} def add_chicken(self, *args): for elm in range(0, len(args), 2): BFC.menu[args[elm]] = args[elm + 1] def place_orderof(self, obj): sum1 = 0 BFC.order_id += 1 print(f'O...
# -*- coding: utf8 -*- """ Test module to be called from C++""" # from __future__ import print_function def add(a, b): """ Returns the sum of two numbers.""" a, b = int(a), int(b) c = str(a + b) print("a = {} and b = {} and a + b = {}".format(a, b, c)) return c
""" Test module to be called from C++""" def add(a, b): """ Returns the sum of two numbers.""" (a, b) = (int(a), int(b)) c = str(a + b) print('a = {} and b = {} and a + b = {}'.format(a, b, c)) return c
""" Chapter Two - Linked Lists """ # Creating a simple node class. class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Build a linked list from a list for testing. def llist_from_list(lst): if len(lst) == 0: return None n = N...
""" Chapter Two - Linked Lists """ class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def llist_from_list(lst): if len(lst) == 0: return None n = node(lst.pop(0)) head = n for item in lst: new_node = node(item) ...
# Time O(n) # Space O(n) # More time efficient and applicable for both Sorted and Unsorted Linked List def removeDuplicates(ListNode): if ListNode.head is None: return None current = ListNode.head visited_nodes = set([current.value]) while current.next: if current.next.value in visited...
def remove_duplicates(ListNode): if ListNode.head is None: return None current = ListNode.head visited_nodes = set([current.value]) while current.next: if current.next.value in visited_nodes: current.next = current.next.next else: visited_nodes.add(current...
dest = [0x21, 0x58, 0x33, 0x57, 0x24, 0x2c, 0x66, 0x25, 0x45, 0x53, 0x34, 0x28, 0x08, 0x61, 0x11, 0x07, 0x14, 0x3d, 0x07, 0x62, 0x13, 0x72, 0x02, 0x4c] flag = "" random = 2019 for i in range(24): random = (random * 23333 + 19260817) % 127 flag += chr(random ^ dest[i]) print(flag)
dest = [33, 88, 51, 87, 36, 44, 102, 37, 69, 83, 52, 40, 8, 97, 17, 7, 20, 61, 7, 98, 19, 114, 2, 76] flag = '' random = 2019 for i in range(24): random = (random * 23333 + 19260817) % 127 flag += chr(random ^ dest[i]) print(flag)
""" Sedan type with 2 sub-types: -Luxury sedan -Sport sedan """ class SedanCar: w_type = 'car' w_meaning = '4+1 doors and a separate trunk' def __init__(self, traction, gen, color, custom): self._traction = traction self._gen = gen self._color = color self._custom ...
""" Sedan type with 2 sub-types: -Luxury sedan -Sport sedan """ class Sedancar: w_type = 'car' w_meaning = '4+1 doors and a separate trunk' def __init__(self, traction, gen, color, custom): self._traction = traction self._gen = gen self._color = color self._custom =...
""" Doctests: >>> 1 == 1 True """
""" Doctests: >>> 1 == 1 True """
# File Not Found Error try: file = open("a_text.txt") # a_dictionary = { # "key" : "value" # } # print(a_dictionary["aehdg"]) except FileNotFoundError: file = open("a_text.txt", "w") file.write("Write Something") except KeyError as error_message: print(f"The key {error_message} ...
try: file = open('a_text.txt') except FileNotFoundError: file = open('a_text.txt', 'w') file.write('Write Something') except KeyError as error_message: print(f'The key {error_message} does not exist.') else: content = file.read() print(content) finally: raise type_error('This is an error I m...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 by applicab...
class Templatedescription(object): """ Const Class The implementation of a FilePicker service may support the usage of different templates. The following constants define the currently specified templates. **since** LibreOffice 5.3 See Also: `API TemplateDescript...
# __ __ __ __ __ __ __ __ __ __ __ __ ___ # |_ / \|\/|/ \ | \|__)|\ /|_ |\ | | \|_ \ /|_ | / \|__)|\/||_ |\ | | # | \__/| |\__/ |__/| \ | \/ |__| \| |__/|__ \/ |__|__\__/| | ||__| \| | # VERSION = (0, 0, 1) __version__ = '.'.join(map(str, VERSION)) #print(__ver...
version = (0, 0, 1) __version__ = '.'.join(map(str, VERSION))
def fib(n): if n==1 or n == 2: return 1 else: return fib(n-1)+fib(n-2)
def fib(n): if n == 1 or n == 2: return 1 else: return fib(n - 1) + fib(n - 2)
n= int(input("Enter the number : ")) sum = 0 temp = n while (n): i = 1 fact = 1 rem = int(n % 10) while(i <= rem): fact = fact * i i = i + 1 sum = sum + fact n = int(n / 10) if(sum == temp): print(temp,end = "") print(" is a strong number") else: print(temp,end = "") print...
n = int(input('Enter the number : ')) sum = 0 temp = n while n: i = 1 fact = 1 rem = int(n % 10) while i <= rem: fact = fact * i i = i + 1 sum = sum + fact n = int(n / 10) if sum == temp: print(temp, end='') print(' is a strong number') else: print(temp, end='') print(' is no...
def InsertionSubSort(L, k): n = len(L) for i in range(k, n): current = L[i] position = i-k while position >= 0 and current < L[position]: print("omar") L[position + k] = L[position] position -= k L[position + k] = current def ShellSort(L,k): ...
def insertion_sub_sort(L, k): n = len(L) for i in range(k, n): current = L[i] position = i - k while position >= 0 and current < L[position]: print('omar') L[position + k] = L[position] position -= k L[position + k] = current def shell_sort(L,...
n = int(input()) a = [int(i) for i in input().split()] a.sort() res = 10001 for i in range(1, n): tmp = a[i] - a[i-1] if tmp < res: res = tmp print(res)
n = int(input()) a = [int(i) for i in input().split()] a.sort() res = 10001 for i in range(1, n): tmp = a[i] - a[i - 1] if tmp < res: res = tmp print(res)
# collatz conjecture revision # the number we perform the collatz operations on n = 25 # keep looping until we reach 1 while n != 1: print(n) # print the current value of n if n % 2 == 0: # checks if n is even n = n / 2 # if so divide by 2, single / gives decimals, double // gives a whole num...
n = 25 while n != 1: print(n) if n % 2 == 0: n = n / 2 else: n = 3 * n + 1 print(n)
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n , k ) : count = 0 arr.sort ( ) l = 0 r = 0 while r < n : if arr [ r ] - arr [ l...
def f_gold(arr, n, k): count = 0 arr.sort() l = 0 r = 0 while r < n: if arr[r] - arr[l] == k: count += 1 l += 1 r += 1 elif arr[r] - arr[l] > k: l += 1 else: r += 1 return count if __name__ == '__main__': par...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # 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 by appli...
def read_txt_lines(file_list): """ return [(file_path, line_no)...] """ line_no = -1 ret = [] with open(file_list, 'r') as f: for line in f: line = line.strip() if len(line) <= 0: continue line_no += 1 ret.append((line, line...
# encoding: utf-8 # module Rhino.FileIO calls itself FileIO # from Rhino3dmIO,Version=5.1.30000.14,Culture=neutral,PublicKeyToken=null # by generator 1.145 # no doc # no imports # no functions # classes class BinaryArchiveException(IOException,ISerializable,_Exception): """ BinaryArchiveException(message:...
class Binaryarchiveexception(IOException, ISerializable, _Exception): """ BinaryArchiveException(message: str) """ def add__serialize_object_state(self, *args): """ add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """ pass def remove__serialize_obje...
# Long lines of method , extracing methods is impossible # from class Order: # ... def price(self): primaryBasePrice = 0 secondaryBasePrice = 0 tertiaryBasePrice = 0 # long computation. # ... pass # to class Order: # ... def price(self): return ...
class Order: def price(self): primary_base_price = 0 secondary_base_price = 0 tertiary_base_price = 0 pass class Order: def price(self): return price_calculator(self).compute() class Pricecalculator: def __init__(self, order): self._primaryBasePrice = 0 ...
def _shader_db(var_type, DB): [FLAG, MATERIAL, STR, TEXTURE, INT, FLOAT, BOOL, COLOR, VEC2, VEC3, VEC4, MATRIX, MATRIX_4X2, FOUR_CC] = var_type DB['%compile2dsky'] = FLAG DB['%compileblocklos'] = FLAG DB['%compileclip'] = FLAG DB['%compiledetail'] = FLAG DB['%compilefog'] = FLAG DB['%compile...
def _shader_db(var_type, DB): [flag, material, str, texture, int, float, bool, color, vec2, vec3, vec4, matrix, matrix_4_x2, four_cc] = var_type DB['%compile2dsky'] = FLAG DB['%compileblocklos'] = FLAG DB['%compileclip'] = FLAG DB['%compiledetail'] = FLAG DB['%compilefog'] = FLAG DB['%compil...
class Album: def __init__(self, id, title, file): self.id = id self.title = title self.file = file
class Album: def __init__(self, id, title, file): self.id = id self.title = title self.file = file
for astTuple in Query.input.tuples('ast'): assignment = astTuple.ast leftType = assignment.left.type() rightType = assignment.right.type() if type(leftType) is ArrayType and type(rightType) is ArrayType: if not leftType.elementType().equals(rightType.elementType()): Query.result.add(...
for ast_tuple in Query.input.tuples('ast'): assignment = astTuple.ast left_type = assignment.left.type() right_type = assignment.right.type() if type(leftType) is ArrayType and type(rightType) is ArrayType: if not leftType.elementType().equals(rightType.elementType()): Query.result.a...
def add_time(start, duration, requested_day=""): # List for weekdays week_days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") # Convert start string in start list clock = start.split() time = clock[0].split(":") am_pm = clock[1] # Calculate 24hr format ...
def add_time(start, duration, requested_day=''): week_days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') clock = start.split() time = clock[0].split(':') am_pm = clock[1] if am_pm == 'PM': hour = int(time[0]) + 12 time[0] = str(hour) duration_ti...
# Link --> https://www.hackerrank.com/challenges/tree-level-order-traversal/problem # Code: def levelOrder(root): if root: queue = [] queue.append(root) while queue: temp_node = queue[0] queue.pop(0) print(temp_node.info, end = " ") ...
def level_order(root): if root: queue = [] queue.append(root) while queue: temp_node = queue[0] queue.pop(0) print(temp_node.info, end=' ') if temp_node.left: queue.append(temp_node.left) if temp_node.right: ...