content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/python # -*- coding: utf-8 -*- """ mw_util.py Set of helper functions while dealing with MediaWiki. str2cat Adds prefix Category if string doesn't have it. """ def str2cat(category): """Return a category name starting with Category.""" prefix = "Category:" if not category.star...
""" mw_util.py Set of helper functions while dealing with MediaWiki. str2cat Adds prefix Category if string doesn't have it. """ def str2cat(category): """Return a category name starting with Category.""" prefix = 'Category:' if not category.startswith(prefix): category = '%s%s' % ...
# Space : O(n) # Time : O(n**2) class Solution: def jump(self, nums: List[int]) -> int: n = len(nums) dp = [10**5] * n dp[0] = 0 if n == 1: return 0 for i in range(n): for j in range(nums[i]): dp[j+i+1] = min(dp[j+i+...
class Solution: def jump(self, nums: List[int]) -> int: n = len(nums) dp = [10 ** 5] * n dp[0] = 0 if n == 1: return 0 for i in range(n): for j in range(nums[i]): dp[j + i + 1] = min(dp[j + i + 1], dp[i] + 1) if j + i +...
# -*- coding: utf-8 -*- """ Created on 2018-03- @author: Frank Dip """ s = "hello boy" for i,j in enumerate(s): print(i, j)
""" Created on 2018-03- @author: Frank Dip """ s = 'hello boy' for (i, j) in enumerate(s): print(i, j)
while True: a = input() if int(a) == 42: break; print(int(a))
while True: a = input() if int(a) == 42: break print(int(a))
# -*- coding: utf-8 -*- # Contributors : [srinivas.v@toyotaconnected.co.in,srivathsan.govindarajan@toyotaconnected.co.in, # harshavardhan.thirupathi@toyotaconnected.co.in, # ashok.ramadass@toyotaconnected.com ] class CoefficientNotinRangeError(Exception): """ Class to throw exception when a coefficient is ...
class Coefficientnotinrangeerror(Exception): """ Class to throw exception when a coefficient is not in the specified range """ def __init__(self, coefficient, coeff_type='Default', range_min=0, range_max=1): self.range_max = range_max self.range_min = range_min self.coeff_ty...
class Solution: """ @param matrix: A 2D-array of integers @return: an integer """ def longestContinuousIncreasingSubsequence2(self, matrix): # write your code here if not matrix or not matrix[0]: return 0 m, n = len(matrix), len(matrix[0]) visited = [[0] *...
class Solution: """ @param matrix: A 2D-array of integers @return: an integer """ def longest_continuous_increasing_subsequence2(self, matrix): if not matrix or not matrix[0]: return 0 (m, n) = (len(matrix), len(matrix[0])) visited = [[0] * n for _ in range(m)] ...
__version__ = '0.0.7' def get_version(): return __version__
__version__ = '0.0.7' def get_version(): return __version__
# -*- coding: utf-8 -*- """ solace.views ~~~~~~~~~~~~ All the view functions are implemented in this package. :copyright: (c) 2009 by Plurk Inc., see AUTHORS for more details. :license: BSD, see LICENSE for more details. """
""" solace.views ~~~~~~~~~~~~ All the view functions are implemented in this package. :copyright: (c) 2009 by Plurk Inc., see AUTHORS for more details. :license: BSD, see LICENSE for more details. """
class BaseASHException(Exception): """A base exception handler for the ASH ecosystem.""" def __init__(self, *args): if args: self.message = args[0] else: self.message = self.__doc__ def __str__(self): return self.message class DuplicateObject(BaseASHExcept...
class Baseashexception(Exception): """A base exception handler for the ASH ecosystem.""" def __init__(self, *args): if args: self.message = args[0] else: self.message = self.__doc__ def __str__(self): return self.message class Duplicateobject(BaseASHExcepti...
#Question:1 # Initializing matrix matrix = [] # Taking input from user of rows and column row = int(input("Enter the number of rows:")) column = int(input("Enter the number of columns:")) print("Enter the elements row wise:") # Getting elements of matrix from user for i in range(row): a =[] ...
matrix = [] row = int(input('Enter the number of rows:')) column = int(input('Enter the number of columns:')) print('Enter the elements row wise:') for i in range(row): a = [] for j in range(column): a.append(int(input())) matrix.append(a) print() print('Entered Matrix is: ') for i in range(row): ...
devices = \ { # ------------------------------------------------------------------------- # NXP ARM7TDMI devices Series LPC21xx, LPC22xx, LPC23xx, LPC24xx "lpc2129": { "defines": ["__ARM_LPC2000__"], "linkerscript": "arm7/lpc/linker/lpc2129.ld", "size": { "flash": 262144, "ram": 16384 }, }, "lpc2368": {...
devices = {'lpc2129': {'defines': ['__ARM_LPC2000__'], 'linkerscript': 'arm7/lpc/linker/lpc2129.ld', 'size': {'flash': 262144, 'ram': 16384}}, 'lpc2368': {'defines': ['__ARM_LPC2000__', '__ARM_LPC23_24__'], 'linkerscript': 'arm7/lpc/linker/lpc2368.ld', 'size': {'flash': 524288, 'ram': 32768}}, 'lpc2468': {'defines': ['...
WALK_UP = 4 WALK_DOWN = 3 WALK_RIGHT = 2 WALK_LEFT = 1 NO_OP = 0 SHOOT = 5 WALK_ACTIONS = [WALK_UP, WALK_DOWN, WALK_RIGHT, WALK_LEFT] ACTIONS = [NO_OP, WALK_LEFT, WALK_RIGHT, WALK_DOWN, WALK_UP, SHOOT]
walk_up = 4 walk_down = 3 walk_right = 2 walk_left = 1 no_op = 0 shoot = 5 walk_actions = [WALK_UP, WALK_DOWN, WALK_RIGHT, WALK_LEFT] actions = [NO_OP, WALK_LEFT, WALK_RIGHT, WALK_DOWN, WALK_UP, SHOOT]
# Day Six: Lanternfish file = open("input/06.txt").readlines() ages = [] for num in file[0].split(","): ages.append(int(num)) for day in range(80): for i, fish in enumerate(ages): if fish == 0: ages[i] = 6 ages.append(9) else: ages[i] = fish-1 print(len(age...
file = open('input/06.txt').readlines() ages = [] for num in file[0].split(','): ages.append(int(num)) for day in range(80): for (i, fish) in enumerate(ages): if fish == 0: ages[i] = 6 ages.append(9) else: ages[i] = fish - 1 print(len(ages)) ages = [0, 0, 0, 0...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://leetcode.com/problems/subarray-sum-equals-k/description/ # I think it is a sub-problem of: https://leetcode.com/problems/path-sum-iii/description/ class Solution(object): def subarraySum(self, nums, k): """ :type nums: List[int] :ty...
class Solution(object): def subarray_sum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ counts = {0: 1} sofar = 0 ret = 0 for num in nums: sofar += num complement = sofar - k ret += c...
# Time: O(nlogn) # Space: O(n) class Solution(object): def relativeSortArray(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: List[int] """ lookup = {v: i for i, v in enumerate(arr2)} return sorted(arr1, key=lambda i: lookup.get(i, ...
class Solution(object): def relative_sort_array(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: List[int] """ lookup = {v: i for (i, v) in enumerate(arr2)} return sorted(arr1, key=lambda i: lookup.get(i, len(arr2) + i))
#Horas-minutos e Segundos valor = int(input()) horas = 0 minutos = 0 segundos = 0 valorA = valor contador = segundos while(contador <= valorA): if contador > 0: segundos += 1 if segundos >= 60: minutos += 1 segundos = 0 if minutos >= 60: horas += 1 minutos = 0 c...
valor = int(input()) horas = 0 minutos = 0 segundos = 0 valor_a = valor contador = segundos while contador <= valorA: if contador > 0: segundos += 1 if segundos >= 60: minutos += 1 segundos = 0 if minutos >= 60: horas += 1 minutos = 0 contador += 1 print('{}:{}:{}...
#!/usr/bin/env python # Author: Omid Mashayekhi <omidm@stanford.edu> # ssh -i ~/.ssh/omidm-sing-key-pair-us-west-2.pem -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ubuntu@<ip> # US West (Northern California) Region # EC2_LOCATION = 'us-west-1' # NIMBUS_AMI = 'ami-50201815' # UBUNTU_AMI = 'ami-660c3023...
ec2_location = 'us-west-2' ubuntu_ami = 'ami-fa9cf1ca' nimbus_ami = 'ami-4f5c392f' controller_instance_type = 'c3.4xlarge' worker_instance_type = 'c3.2xlarge' placement = 'us-west-2a' placement_group = 'nimbus-cluster' security_group = 'nimbus_sg_uswest2' key_name = 'sing-key-pair-us-west-2' private_key = '/home/omidm/...
# SPDX-FileCopyrightText: Aresys S.r.l. <info@aresys.it> # SPDX-License-Identifier: MIT """ Constants module ---------------- Example of usage: .. code-block:: python import arepytools.constants as cst print(cst.LIGHT_SPEED) """ # Speed of light LIGHT_SPEED = 299792458.0 """ Speed of light in vacuum (m/s)....
""" Constants module ---------------- Example of usage: .. code-block:: python import arepytools.constants as cst print(cst.LIGHT_SPEED) """ light_speed = 299792458.0 '\nSpeed of light in vacuum (m/s).\n' second_str = 's' '\nSecond symbol.\n' hertz_str = 'Hz' '\nHertz symbol.\n' joule_str = 'j' '\nJoule symb...
# Copyright: 2006 Marien Zwart <marienz@gentoo.org> # License: BSD/GPL2 #base class __all__ = ("PackageError", "InvalidPackageName", "MetadataException", "InvalidDependency", "ChksumBase", "MissingChksum", "ParseChksumError") class PackageError(ValueError): pass class InvalidPackageName(PackageError): p...
__all__ = ('PackageError', 'InvalidPackageName', 'MetadataException', 'InvalidDependency', 'ChksumBase', 'MissingChksum', 'ParseChksumError') class Packageerror(ValueError): pass class Invalidpackagename(PackageError): pass class Metadataexception(PackageError): def __init__(self, pkg, attr, error): ...
# # PySNMP MIB module CISCO-ENTITY-ASSET-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-ASSET-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:56:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, constraints_union, value_range_constraint, single_value_constraint) ...
def egcd(a, b): if a==0: return b, 0, 1 else: gcd, x, y = egcd(b%a, a) return gcd, y-(b//a)*x, x if __name__ == '__main__': a = int(input('Enter a: ')) b = int(input('Enter b: ')) gcd, x, y = egcd(a, b) print(egcd(a,b)) if gcd!=1: print("M.I. doe...
def egcd(a, b): if a == 0: return (b, 0, 1) else: (gcd, x, y) = egcd(b % a, a) return (gcd, y - b // a * x, x) if __name__ == '__main__': a = int(input('Enter a: ')) b = int(input('Enter b: ')) (gcd, x, y) = egcd(a, b) print(egcd(a, b)) if gcd != 1: print("M.I...
class Engine(object): """Engine""" def __init__(self, rest): self.rest = rest def list(self, params=None): return self.rest.get('engines', params) def create(self, data=None): return self.rest.post('engines', data) def get(self, name): return self.rest.get('engin...
class Engine(object): """Engine""" def __init__(self, rest): self.rest = rest def list(self, params=None): return self.rest.get('engines', params) def create(self, data=None): return self.rest.post('engines', data) def get(self, name): return self.rest.get('engine...
def app(environ, start_response): s = "" for i in environ['QUERY_STRING'].split("&"): s = s + i + "\r\n" start_response("200 OK", [ ("Content-Type", "text/plain"), ("Content-Length", str(len(s))) ]) return [bytes(s, 'utf-8')]
def app(environ, start_response): s = '' for i in environ['QUERY_STRING'].split('&'): s = s + i + '\r\n' start_response('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', str(len(s)))]) return [bytes(s, 'utf-8')]
deck_test = { "kategori 1": ["kartuA", "kartuB", "kartuC", "kartuD"], "kategori 2": ["kartuE", "kartuF", "kartuG", "kartuH"], "kategori 3": ["kartuI", "kartuJ", "kartuK", "kartuL"], # "kategori 4": ["kartuM", "kartuN", "kartuO", "kartuP"], # "kategori 5": ["kartuQ", "kartuR", "kartuS", "kartuT"], } ...
deck_test = {'kategori 1': ['kartuA', 'kartuB', 'kartuC', 'kartuD'], 'kategori 2': ['kartuE', 'kartuF', 'kartuG', 'kartuH'], 'kategori 3': ['kartuI', 'kartuJ', 'kartuK', 'kartuL']} deck_used = {'nasi': ['nasi goreng', 'nasi uduk', 'nasi kuning', 'nasi kucing'], 'air': ['air putih', 'air santan', 'air susu', 'air tajin'...
data = [int(input()), input()] if 10 <= data[0] <= 15 and data[1] == "f": print("YES") else: print("NO")
data = [int(input()), input()] if 10 <= data[0] <= 15 and data[1] == 'f': print('YES') else: print('NO')
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: res = cnt = 0 for i in nums: if i: cnt += 1 else: if cnt: res = max(res, cnt) cnt = 0 return max(res, cnt)
class Solution: def find_max_consecutive_ones(self, nums: List[int]) -> int: res = cnt = 0 for i in nums: if i: cnt += 1 elif cnt: res = max(res, cnt) cnt = 0 return max(res, cnt)
n = int(input()) while True: s,z =0,n while z>0: s+=z%10 z//=10 if n%s==0: print(n) break n+=1
n = int(input()) while True: (s, z) = (0, n) while z > 0: s += z % 10 z //= 10 if n % s == 0: print(n) break n += 1
n = int(input()) k = n >> 1 ans = 1 for i in range(n-k+1,n+1): ans *= i for i in range(1,k+1): ans //= i print (ans)
n = int(input()) k = n >> 1 ans = 1 for i in range(n - k + 1, n + 1): ans *= i for i in range(1, k + 1): ans //= i print(ans)
# # PySNMP MIB module DVMRP-STD-MIB-UNI (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DVMRP-STD-MIB-UNI # Produced by pysmi-0.3.4 at Mon Apr 29 18:40:19 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ...
mesh_meshes_begin = 0 mesh_mp_score_a = 1 mesh_mp_score_b = 2 mesh_load_window = 3 mesh_checkbox_off = 4 mesh_checkbox_on = 5 mesh_white_plane = 6 mesh_white_dot = 7 mesh_player_dot = 8 mesh_flag_infantry = 9 mesh_flag_archers = 10 mesh_flag_cavalry = 11 mesh_inv_slot = 12 mesh_mp_ingame_menu = 13 mesh_mp_inventory_lef...
mesh_meshes_begin = 0 mesh_mp_score_a = 1 mesh_mp_score_b = 2 mesh_load_window = 3 mesh_checkbox_off = 4 mesh_checkbox_on = 5 mesh_white_plane = 6 mesh_white_dot = 7 mesh_player_dot = 8 mesh_flag_infantry = 9 mesh_flag_archers = 10 mesh_flag_cavalry = 11 mesh_inv_slot = 12 mesh_mp_ingame_menu = 13 mesh_mp_inventory_lef...
# hanoi: int -> int # calcula el numero de movimientos necesarios aara mover # una torre de n discos de una vara a otra # usando 3 varas y siguiendo las restricciones del puzzle hanoi # ejemplo: hanoi(0) debe dar 0, hanoi(1) debe dar 1, hanoi(2) debe dar 3 def hanoi(n): if n < 2: return n else: ...
def hanoi(n): if n < 2: return n else: return 1 + 2 * hanoi(n - 1) assert hanoi(0) == 0 assert hanoi(1) == 1 assert hanoi(4) == 15 assert hanoi(5) == 31
class Solution(object): def alienOrder(self, words): """ :type words: List[str] :rtype: str """
class Solution(object): def alien_order(self, words): """ :type words: List[str] :rtype: str """
# BUG Can live for several minutes after decapitation # Either change death-time or remove need for head entirely """ TODO BAK-AAAW # BUG If you read me as a seperate code-tag you are a dumb, dumb, dumb crawler. ''' TODO Include me with bak-aaaw too! ''' """
""" TODO BAK-AAAW # BUG If you read me as a seperate code-tag you are a dumb, dumb, dumb crawler. ''' TODO Include me with bak-aaaw too! ''' """
date = input("enter the date: ").split() dd = int(date[0]) yyyy = int(date[2]) mm = date[1] l = [] l.append(yyyy) l.append(mm) l.append(dd) t = tuple(l) print(t)
date = input('enter the date: ').split() dd = int(date[0]) yyyy = int(date[2]) mm = date[1] l = [] l.append(yyyy) l.append(mm) l.append(dd) t = tuple(l) print(t)
menu_item=0 namelist = [] while menu_item != 9: print("----------------------------") print("1. Mencetak List") print("2. Menambahkan nama ke dalam list") print("3. Menghapus nama dari list") print("4. Mengubah data dari dalam list") print("9. Keluar") menu_item= int(input("Pilih menu: ")) if men...
menu_item = 0 namelist = [] while menu_item != 9: print('----------------------------') print('1. Mencetak List') print('2. Menambahkan nama ke dalam list') print('3. Menghapus nama dari list') print('4. Mengubah data dari dalam list') print('9. Keluar') menu_item = int(input('Pilih menu: ')...
# # baseparser.py # # Base class for Modbus message parser # class ModbusBaseParser: """Base class for Modbus message parsing. """ def __init__(self): pass def msgs_from_bytes(self, b): """Parse messages from a byte string """
class Modbusbaseparser: """Base class for Modbus message parsing. """ def __init__(self): pass def msgs_from_bytes(self, b): """Parse messages from a byte string """
a, b = input().split() a = int(a) b = int(b) if a > b: print(">") elif a < b: print("<") else: print("==")
(a, b) = input().split() a = int(a) b = int(b) if a > b: print('>') elif a < b: print('<') else: print('==')
n = int(input("Enter a number: ")) for i in range(1, n+1): count = 0 for j in range(1, n+1): if i%j==0: count= count+1 if count==2: print(i)
n = int(input('Enter a number: ')) for i in range(1, n + 1): count = 0 for j in range(1, n + 1): if i % j == 0: count = count + 1 if count == 2: print(i)
#what is python #added by @Dima print("What is Data Types?") print("_______________________________________________________") print("Collections of data put together like array ") print("________________________________________________________") print("there are four data types in the Python ") print("_________...
print('What is Data Types?') print('_______________________________________________________') print('Collections of data put together like array ') print('________________________________________________________') print('there are four data types in the Python ') print('_________________________________________________...
format = "%(asctime)s - %(levelname)s - %(name)s - %(message)s" minimal_format = "%(message)s" def _get_formatter_and_handler(use_minimal_format: bool = False): logging_dict = { "version": 1, "disable_existing_loggers": True, "formatters": { "colored": { "()": "...
format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s' minimal_format = '%(message)s' def _get_formatter_and_handler(use_minimal_format: bool=False): logging_dict = {'version': 1, 'disable_existing_loggers': True, 'formatters': {'colored': {'()': 'coloredlogs.ColoredFormatter', 'format': minimal_format if...
#!/bin/python3 # Set .union() Operation # https://www.hackerrank.com/challenges/py-set-union/problem if __name__ == '__main__': n = int(input()) students_n = set(map(int, input().split())) b = int(input()) students_b = set(map(int, input().split())) print(len(students_n | students_b))
if __name__ == '__main__': n = int(input()) students_n = set(map(int, input().split())) b = int(input()) students_b = set(map(int, input().split())) print(len(students_n | students_b))
def ddd(): for i in 'fasdffghdfghjhfgj': yield i a = ddd() print(next(a)) print(next(a)) print(next(a)) print(next(a)) print(next(a))
def ddd(): for i in 'fasdffghdfghjhfgj': yield i a = ddd() print(next(a)) print(next(a)) print(next(a)) print(next(a)) print(next(a))
# Customer States C_CALLING = 0 C_WAITING = 1 C_IN_VEHICLE = 2 C_ARRIVED = 3 C_DISAPPEARED = 4 # Vehicle States V_IDLE = 0 V_CRUISING = 1 V_OCCUPIED = 2 V_ASSIGNED = 3 V_OFF_DUTY = 4
c_calling = 0 c_waiting = 1 c_in_vehicle = 2 c_arrived = 3 c_disappeared = 4 v_idle = 0 v_cruising = 1 v_occupied = 2 v_assigned = 3 v_off_duty = 4
# app seettings EC2_ACCESS_ID = 'A***Q' EC2_ACCESS_KEY = 'R***I' YCSB_SIZE =0 MCROUTER_NOISE = 0 MEMCACHED_OD_SIZE = 1 MEMCACHED_SPOT_SIZE = 0 G_M_MIN = 7.5*1024 G_M_MAX = 7.5*1024 G_C_MIN = 2 G_C_MAX = 2 M_DEFAULT = 7.5*1024 C_DEFAULT = 2 G_M_MIN_2 = 7.5*1024 G_M_MAX_2 = 7.5*1024 G_C_MIN_2 = 2 G_C_MAX_2 = 2 M_...
ec2_access_id = 'A***Q' ec2_access_key = 'R***I' ycsb_size = 0 mcrouter_noise = 0 memcached_od_size = 1 memcached_spot_size = 0 g_m_min = 7.5 * 1024 g_m_max = 7.5 * 1024 g_c_min = 2 g_c_max = 2 m_default = 7.5 * 1024 c_default = 2 g_m_min_2 = 7.5 * 1024 g_m_max_2 = 7.5 * 1024 g_c_min_2 = 2 g_c_max_2 = 2 m_default_2 = 7...
# B_R_R # M_S_A_W """ Coding Problem on Iterators and Generators: First, using Iterators, we will write a code that pass in a sentence and print out all words in the sentence in line. Then, we will do the same thing with generators. """ class Sentence: def __init__(self, sentence): self.sentence=senten...
""" Coding Problem on Iterators and Generators: First, using Iterators, we will write a code that pass in a sentence and print out all words in the sentence in line. Then, we will do the same thing with generators. """ class Sentence: def __init__(self, sentence): self.sentence = sentence self.ind...
def read_input(): n = int(input()) return ( [input() for _ in range(n)], input() ) def find_position(matrix, symbol): for i in range(len(matrix)): line = matrix[i] if symbol in line: return (i, line.index(symbol)) return None (matrix, symbol) = read_in...
def read_input(): n = int(input()) return ([input() for _ in range(n)], input()) def find_position(matrix, symbol): for i in range(len(matrix)): line = matrix[i] if symbol in line: return (i, line.index(symbol)) return None (matrix, symbol) = read_input() result = find_posit...
# (c) Copyright 2018 Palantir Technologies Inc. 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 ...
def sanitize_identifier(identifier): """ Get santized identifier name for identifiers which happen to be python keywords. """ keywords = ('and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is...
class Solution: def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ rows = [set() for _ in range(9)] cols = [set() for _ in range(9)] subboxes = [set() for _ in range(9)] for i, row in enumerate(board): ...
class Solution: def is_valid_sudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ rows = [set() for _ in range(9)] cols = [set() for _ in range(9)] subboxes = [set() for _ in range(9)] for (i, row) in enumerate(board): fo...
#string: temperatura Gc = float(input("Digite grados Centigrados: ")) Gk = (Gc + 273.15) print("el valor de los grados kelvin es el siguiente: ",Gk)
gc = float(input('Digite grados Centigrados: ')) gk = Gc + 273.15 print('el valor de los grados kelvin es el siguiente: ', Gk)
class Triangular: ### Constructor ### def __init__(self, init, end, center=None, peak=1, floor=0): # initialize attributes self._init = init self._end = end if center: #using property to test if its bewtween init and end self.center = center else: ...
class Triangular: def __init__(self, init, end, center=None, peak=1, floor=0): self._init = init self._end = end if center: self.center = center else: self._center = (end + init) / 2 self._peak = peak self._floor = floor def __close__(sel...
# Python - 3.6.0 test.describe('Fixed tests') test.assert_equals(whatday(1), 'Sunday') test.assert_equals(whatday(2), 'Monday') test.assert_equals(whatday(3), 'Tuesday') test.assert_equals(whatday(8), 'Wrong, please enter a number between 1 and 7') test.assert_equals(whatday(20), 'Wrong, please enter a number between ...
test.describe('Fixed tests') test.assert_equals(whatday(1), 'Sunday') test.assert_equals(whatday(2), 'Monday') test.assert_equals(whatday(3), 'Tuesday') test.assert_equals(whatday(8), 'Wrong, please enter a number between 1 and 7') test.assert_equals(whatday(20), 'Wrong, please enter a number between 1 and 7')
def last_vowel(s): """(str) -> str Return the last vowel in s if one exists; otherwise, return None. >>> last_vowel("cauliflower") "e" >>> last_vowel("pfft") None """ i = len(s) - 1 while i >= 0: if s[i] in 'aeiouAEIOU': return s[i] i = i - 1 return No...
def last_vowel(s): """(str) -> str Return the last vowel in s if one exists; otherwise, return None. >>> last_vowel("cauliflower") "e" >>> last_vowel("pfft") None """ i = len(s) - 1 while i >= 0: if s[i] in 'aeiouAEIOU': return s[i] i = i - 1 return No...
# # PySNMP MIB module TPLINK-PORTMIRROR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-PORTMIRROR-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:25:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, constraints_union, value_range_constraint, value_size_constraint) ...
File = open("File PROTEK/Data2.txt", "w") while True: nim = input('Masukan NIM:') nama = input('Masukan Nama:') alamat = input('Masukan Alamat:') print('') File.write(nim + '|' + nama + '|' + alamat + '\n') repeat = input('Apakah ingin memasukan data lagi?(y/n):') print('') ...
file = open('File PROTEK/Data2.txt', 'w') while True: nim = input('Masukan NIM:') nama = input('Masukan Nama:') alamat = input('Masukan Alamat:') print('') File.write(nim + '|' + nama + '|' + alamat + '\n') repeat = input('Apakah ingin memasukan data lagi?(y/n):') print('') if repeat in ...
# Lv-677_Ivan_Vaulin # Task2. Write a script that checks the login that the user enters. # If the login is "First", then greet the users. If the login is different, send an error message. # (need to use loop while) user_name = input('Hello, please input your Log in:') while user_name != 'First': user_name = inpu...
user_name = input('Hello, please input your Log in:') while user_name != 'First': user_name = input('Error: wrong username, please try one more time. Username:') else: print('Greeting. Access granted!!!', user_name)
""" 1272. Remove Interval Medium Given a sorted list of disjoint intervals, each interval intervals[i] = [a, b] represents the set of real numbers x such that a <= x < b. We remove the intersections between any interval in intervals and the interval toBeRemoved. Return a sorted list of intervals after all such remov...
""" 1272. Remove Interval Medium Given a sorted list of disjoint intervals, each interval intervals[i] = [a, b] represents the set of real numbers x such that a <= x < b. We remove the intersections between any interval in intervals and the interval toBeRemoved. Return a sorted list of intervals after all such remov...
# -*- coding: UTF-8 -*- # Copyright 2013 Felix Friedrich, Felix Schwarz # Copyright 2015, 2019 Felix Schwarz # The source code in this file is licensed under the MIT license. # SPDX-License-Identifier: MIT __all__ = ['Result'] class Result(object): def __init__(self, value, **data): self.value = value ...
__all__ = ['Result'] class Result(object): def __init__(self, value, **data): self.value = value self.data = data def __repr__(self): klassname = self.__class__.__name__ extra_data = [repr(self.value)] for (key, value) in sorted(self.data.items()): extra_da...
# Test that systemctl will accept service names both with or without suffix. def test_dot_service(sysvenv): service = sysvenv.create_service("foo") service.will_do("status", 3) service.direct_enable() out, err, status = sysvenv.systemctl("status", "foo.service") assert status == 3 assert service...
def test_dot_service(sysvenv): service = sysvenv.create_service('foo') service.will_do('status', 3) service.direct_enable() (out, err, status) = sysvenv.systemctl('status', 'foo.service') assert status == 3 assert service.did('status')
num_list = [] num_list.append(1) num_list.append(2) num_list.append(3) print(num_list[1])
num_list = [] num_list.append(1) num_list.append(2) num_list.append(3) print(num_list[1])
class BaseModule: """ Base module class to be extended by feature modules. """ command_char = '' # To be updated in subclasses module_name = '' module_description = '' commands = [] def __init__(self, user_cmd_char): """ Sets command prefix while initializing. ...
class Basemodule: """ Base module class to be extended by feature modules. """ command_char = '' module_name = '' module_description = '' commands = [] def __init__(self, user_cmd_char): """ Sets command prefix while initializing. :param user_cmd_char: command pr...
#!/usr/bin/env python # Paths VIDEOS_PATH = '~/Desktop/Downloaded Youtube Videos' VIDEOS_PATH_WIN = '/mnt/e/Alex/Videos/Youtube'
videos_path = '~/Desktop/Downloaded Youtube Videos' videos_path_win = '/mnt/e/Alex/Videos/Youtube'
# Variables that contain the user credentials to access Twitter API ACCESS_TOKEN ="< Enter your Twitter Access Token >" ACCESS_TOKEN_SECRET ="< Enter your Access Token Secret >" CONSUMER_KEY = "< Enter Consumer Key >" CONSUMER_SECRET = "< Enter Consumer Key Secret >"
access_token = '< Enter your Twitter Access Token >' access_token_secret = '< Enter your Access Token Secret >' consumer_key = '< Enter Consumer Key >' consumer_secret = '< Enter Consumer Key Secret >'
""" https://adventofcode.com/2018/day/4 """ def readFile(): with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f: l = [line[:-1] for line in f.readlines()] l.sort() return l class Guard: def __init__(self, id): self.id = int(id) self.idStr = id self.timeAsleep ...
""" https://adventofcode.com/2018/day/4 """ def read_file(): with open(f"{__file__.rstrip('code.py')}input.txt", 'r') as f: l = [line[:-1] for line in f.readlines()] l.sort() return l class Guard: def __init__(self, id): self.id = int(id) self.idStr = id self.timeAslee...
ft_name = 'points' featuretype_api = datastore_api.featuretype(name=ft_name, data={ "featureType": { "circularArcPresent": False, "enabled": True, "forcedDecimal": False, "maxFeatures": 0, "name": ft_name, "nativeName": ft_name, "numDecimals": 0, "over...
ft_name = 'points' featuretype_api = datastore_api.featuretype(name=ft_name, data={'featureType': {'circularArcPresent': False, 'enabled': True, 'forcedDecimal': False, 'maxFeatures': 0, 'name': ft_name, 'nativeName': ft_name, 'numDecimals': 0, 'overridingServiceSRS': False, 'padWithZeros': False, 'projectionPolicy': '...
# Time: O(k * n^2) # Space: O(n^2) class Solution(object): def knightProbability(self, N, K, r, c): """ :type N: int :type K: int :type r: int :type c: int :rtype: float """ directions = \ [[ 1, 2], [ 1, -2], [ 2, 1], [ 2, -1], \ ...
class Solution(object): def knight_probability(self, N, K, r, c): """ :type N: int :type K: int :type r: int :type c: int :rtype: float """ directions = [[1, 2], [1, -2], [2, 1], [2, -1], [-1, 2], [-1, -2], [-2, 1], [-2, -1]] dp = [[[1 for _ i...
class Solution: def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: step = sign = 1 result = [[r0, c0]] r, c = r0, c0 while len(result) < R*C: for _ in range(step): c += sign if 0 <= r < R and 0 <= c < C: ...
class Solution: def spiral_matrix_iii(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: step = sign = 1 result = [[r0, c0]] (r, c) = (r0, c0) while len(result) < R * C: for _ in range(step): c += sign if 0 <= r < R and 0 <= c < C...
# -*- coding: utf-8 -*- def includeme(config): config.register_service_factory('.services.user.rename_user_factory', name='rename_user') config.include('.views') config.add_route('admin_index', '/') config.add_route('admin_admins', '/admins') config.add_route('admin_badge', '/badge') config....
def includeme(config): config.register_service_factory('.services.user.rename_user_factory', name='rename_user') config.include('.views') config.add_route('admin_index', '/') config.add_route('admin_admins', '/admins') config.add_route('admin_badge', '/badge') config.add_route('admin_features', ...
## Iterative approach - BFS - Using Queue # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: ...
class Solution: def invert_tree(self, root: TreeNode) -> TreeNode: if root is None: return None queue = deque([root]) while queue: current = queue.popleft() (current.left, current.right) = (current.right, current.left) if current.left: ...
class ExtractJSON: @staticmethod def get_json(path:str) -> str: """ Return an extract JSON from a file """ try: return open(path, "r").readlines()[0] except ValueError: print("ERROR: file not found.") exit(-1) return None
class Extractjson: @staticmethod def get_json(path: str) -> str: """ Return an extract JSON from a file """ try: return open(path, 'r').readlines()[0] except ValueError: print('ERROR: file not found.') exit(-1) return None
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) motorcycles.append('honda') print(motorcycles) motorcycles = [] motorcycles.append('suzuki') motorcycles.append('honda') motorcycles.append('bmw') print(motorcycles) motorcycles.insert(0, 'ducati') print(mot...
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) motorcycles.append('honda') print(motorcycles) motorcycles = [] motorcycles.append('suzuki') motorcycles.append('honda') motorcycles.append('bmw') print(motorcycles) motorcycles.insert(0, 'ducati') print(motorcyc...
# -*- coding: utf-8 -*- class StaticBase(object): """ Base class for StaticModel framework class. .. todo:: KDJ: What is the reason this class exists? Can it be merged with StaticModel? """ def __init__(self): if self.__class__ is StaticBase: raise NotImplementedError self.inIniti...
class Staticbase(object): """ Base class for StaticModel framework class. .. todo:: KDJ: What is the reason this class exists? Can it be merged with StaticModel? """ def __init__(self): if self.__class__ is StaticBase: raise NotImplementedError self.inInitial = False...
# # PySNMP MIB module HP-ICF-LAYER3VLAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-LAYER3VLAN-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:21:56 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection, constraints_union) ...
class BaseClient(object): def __init__(self, username, password, randsalt): ## password = {MD5(pwrd) for old clients, SHA256(pwrd + salt) for new clients} ## randsalt = {"" for old clients, random 16-byte binary string for new clients} ## (here "old" means user was registered over an unencrypted link, without sa...
class Baseclient(object): def __init__(self, username, password, randsalt): self.set_user_pwrd_salt(username, (password, randsalt)) def has_legacy_password(self): return len(self.randsalt) == 0 def set_user_pwrd_salt(self, user_name='', pwrd_hash_salt=('', '')): assert type(pwrd_h...
TITLE = "Metadata extractor" SAVE = "Save" OPEN = "Open" EXTRACT = "Extract" DELETE = "Delete" META_TITLE = "title" META_NAMES = "names" META_CONTENT = "content" META_LOCATIONS = "locations" META_KEYWORD = "keyword" META_REF = "reference" TYPE_TXT = "txt" TYPE_ISO19115v2 = "iso19115v2" TYPE_FGDC = "fgdc" LABLE_NAME...
title = 'Metadata extractor' save = 'Save' open = 'Open' extract = 'Extract' delete = 'Delete' meta_title = 'title' meta_names = 'names' meta_content = 'content' meta_locations = 'locations' meta_keyword = 'keyword' meta_ref = 'reference' type_txt = 'txt' type_iso19115v2 = 'iso19115v2' type_fgdc = 'fgdc' lable_name = '...
class SpaceAge(object): def __init__(self, seconds): self.seconds = seconds def on_earth(self): return round(self.seconds / 31557600, 2) def on_mercury(self): earth = self.on_earth() return round(earth / 0.2408467, 2) def on_venus(self): return round(self.s...
class Spaceage(object): def __init__(self, seconds): self.seconds = seconds def on_earth(self): return round(self.seconds / 31557600, 2) def on_mercury(self): earth = self.on_earth() return round(earth / 0.2408467, 2) def on_venus(self): return round(self.seco...
class Tester(object): def __init__(self): self.results = dict() self.params = dict() self.problem_data = dict() def set_params(self, params): self.params = params
class Tester(object): def __init__(self): self.results = dict() self.params = dict() self.problem_data = dict() def set_params(self, params): self.params = params
class Solution(object): def find132pattern(self, nums): """ :type nums: List[int] :rtype: bool """ stack = [] s3 = -float("inf") for n in nums[::-1]: if n < s3: return True while stack and stack[-1] < n: s3 = stack.pop() sta...
class Solution(object): def find132pattern(self, nums): """ :type nums: List[int] :rtype: bool """ stack = [] s3 = -float('inf') for n in nums[::-1]: if n < s3: return True while stack and stack[-1] < n: ...
class SlackResponseTool: @classmethod def response2is_ok(cls, response): return response["ok"] is True @classmethod def response2j_resopnse(cls, response): return response.data
class Slackresponsetool: @classmethod def response2is_ok(cls, response): return response['ok'] is True @classmethod def response2j_resopnse(cls, response): return response.data
#!/usr/bin/env python NAME = 'Cloudflare (Cloudflare Inc.)' def is_waf(self): # This should be given first priority (most reliable) if self.matchcookie('__cfduid'): return True # Not all servers return cloudflare-nginx, only nginx ones if self.matchheader(('server', 'cloudflare-nginx')) or s...
name = 'Cloudflare (Cloudflare Inc.)' def is_waf(self): if self.matchcookie('__cfduid'): return True if self.matchheader(('server', 'cloudflare-nginx')) or self.matchheader(('server', 'cloudflare')): return True if self.matchheader(('cf-ray', '.*')): return True return False
s = input() K = int(input()) n = len(s) substr = set() for i in range(n): for j in range(i + 1, i + 1 + K): if j <= n: substr.add(s[i:j]) substr = sorted(list(substr)) print(substr[K - 1])
s = input() k = int(input()) n = len(s) substr = set() for i in range(n): for j in range(i + 1, i + 1 + K): if j <= n: substr.add(s[i:j]) substr = sorted(list(substr)) print(substr[K - 1])
def exc(): a=10 b=0 try: c=a/b except(ZeroDivisionError ): print("Divide by zero") exc()
def exc(): a = 10 b = 0 try: c = a / b except ZeroDivisionError: print('Divide by zero') exc()
""" More list manipulations """ def split(in_list, index): """ Parameters ---------- in_list: list index: int Returns ---------- Two lists, splitting in_list by 'index' Examples ---------- >>> split(['a', 'b', 'c', 'd'], 3) (['a', 'b', 'c'], ['d']) ""...
""" More list manipulations """ def split(in_list, index): """ Parameters ---------- in_list: list index: int Returns ---------- Two lists, splitting in_list by 'index' Examples ---------- >>> split(['a', 'b', 'c', 'd'], 3) (['a', 'b', 'c'], ['d']) """...
__version__ = "0.3.43" def doc_version(): """Use this number in the documentation to avoid triggering updates of the whole documentation each time the last part of the version is changed.""" parts = __version__.split(".") return parts[0] + "." + parts[1]
__version__ = '0.3.43' def doc_version(): """Use this number in the documentation to avoid triggering updates of the whole documentation each time the last part of the version is changed.""" parts = __version__.split('.') return parts[0] + '.' + parts[1]
""" Bars Module """ def starbar(num): print('*' * num) def hashbar(num): print('#' * num) def simplebar(num): print('-' * num)
""" Bars Module """ def starbar(num): print('*' * num) def hashbar(num): print('#' * num) def simplebar(num): print('-' * num)
A, B, K = map(int, input().split()) for i, num in enumerate(range(A, B + 1)): if i + 1 > K: break print(num) x = [] for i, num in enumerate(range(B, A-1, -1)): if i + 1 > K: break x.append(num) x.sort() k = B - A +1 for i in x: if k < 2 * K: k += 1 else: print(i...
(a, b, k) = map(int, input().split()) for (i, num) in enumerate(range(A, B + 1)): if i + 1 > K: break print(num) x = [] for (i, num) in enumerate(range(B, A - 1, -1)): if i + 1 > K: break x.append(num) x.sort() k = B - A + 1 for i in x: if k < 2 * K: k += 1 else: ...
s = sum(range(1, 101)) ** 2 ss = sum(list(map(lambda x: x ** 2, range(1, 101)))) print(s - ss)
s = sum(range(1, 101)) ** 2 ss = sum(list(map(lambda x: x ** 2, range(1, 101)))) print(s - ss)
#-*- coding: utf-8 -*- class SQLForge: """ SQLForge This class is in charge of providing methods to craft SQL queries. Basically, the methods already implemented fit with most of the DBMS. """ def __init__(self, context): """ Constructor context: context to associate the for...
class Sqlforge: """ SQLForge This class is in charge of providing methods to craft SQL queries. Basically, the methods already implemented fit with most of the DBMS. """ def __init__(self, context): """ Constructor context: context to associate the forge with. """ ...
class Solution(object): def generateParenthesis(self, n): # corner case if n == 0: return [] # level: tree level # openCount: open bracket count def dfs(level, n1, n2, n, stack, ret, openCount): if level == 2 * n: ret.append("".join(...
class Solution(object): def generate_parenthesis(self, n): if n == 0: return [] def dfs(level, n1, n2, n, stack, ret, openCount): if level == 2 * n: ret.append(''.join(stack[:])) if n1 < n: stack.append('(') dfs(le...
def find(n: int): for i in range(1, 1000001): total = 0 for j in str(i): total += int(j) total += i if total == n: print(i) return print(0) find(int(input()))
def find(n: int): for i in range(1, 1000001): total = 0 for j in str(i): total += int(j) total += i if total == n: print(i) return print(0) find(int(input()))
if True: pass else: x = 3
if True: pass else: x = 3
print("Welcome to the Band Name Generator.") city_name =input("What's name of the city you grew up in?\n") pet_name =input("What's your pet's name?\n") print("Your band name could be Bristole Rabbit")
print('Welcome to the Band Name Generator.') city_name = input("What's name of the city you grew up in?\n") pet_name = input("What's your pet's name?\n") print('Your band name could be Bristole Rabbit')
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: """ abcabcbb i j {} """ seen = set() best = 0 i = 0 for j in range(0, len(s)): end_char = s[j] while end_char in seen: ...
class Solution: def length_of_longest_substring(self, s: str) -> int: """ abcabcbb i j {} """ seen = set() best = 0 i = 0 for j in range(0, len(s)): end_char = s[j] while end_char in seen: ...
#!/usr/bin/env python # encoding: utf-8 __title__ = "Arithmatic Coding" __author__ = "Waleed Yaser (waleedyaser95@gmail.com)" __version__ = "1.0" """ Arithmatic Coding ~~~~~~~~~~~~~~~~~ A class for implementing Arithmatic coding. constructor takes 3 parameters: *symbols list *probalit...
__title__ = 'Arithmatic Coding' __author__ = 'Waleed Yaser (waleedyaser95@gmail.com)' __version__ = '1.0' '\n Arithmatic Coding\n ~~~~~~~~~~~~~~~~~\n A class for implementing Arithmatic coding.\n\n constructor takes 3 parameters:\n *symbols list\n *probalities list\n *terminator charach...
class Settings: info = { "version": "0.2.0", "description": "Python library which allows to read, modify, create and run EnergyPlus files and simulations." } groups = { 'simulation_parameters': [ 'Timestep', 'Version', 'SimulationControl', ...
class Settings: info = {'version': '0.2.0', 'description': 'Python library which allows to read, modify, create and run EnergyPlus files and simulations.'} groups = {'simulation_parameters': ['Timestep', 'Version', 'SimulationControl', 'ShadowCalculations', 'SurfaceConvectionAlgorithm:Outside', 'SurfaceConvecti...
DEBUG = False SECRET_KEY = '3tJhmR0XFbSOUG02Wpp7' CSRF_ENABLED = True CSRF_SESSION_LKEY = 'e8uXRmxo701QarZiXxGf'
debug = False secret_key = '3tJhmR0XFbSOUG02Wpp7' csrf_enabled = True csrf_session_lkey = 'e8uXRmxo701QarZiXxGf'
''' Statement Given a month - an integer from 1 to 12, print the number of days in it in the year 2017. Example input #1 1 (January) Example output #1 31 Example input #2 2 (February) Example output #2 28 ''' month = int(input()) if month == 2: print(28) elif month < 8: if month % 2 == 0: print(30...
""" Statement Given a month - an integer from 1 to 12, print the number of days in it in the year 2017. Example input #1 1 (January) Example output #1 31 Example input #2 2 (February) Example output #2 28 """ month = int(input()) if month == 2: print(28) elif month < 8: if month % 2 == 0: print(30) ...
# Challenge No 9 Intermediate # https://www.reddit.com/r/dailyprogrammer/comments/pu1y6/2172012_challenge_9_intermediate/ # Take a string, scan file for string, and replace with another string def main(): pass def f_r(): fn = input('Please input filename: ') sstring = input('Please input string t...
def main(): pass def f_r(): fn = input('Please input filename: ') sstring = input('Please input string to search: ') rstring = input('Please input string to replace: ') with open(fn, 'r') as f: filedata = f.read() filedata = filedata.replace(sstring, rstring) with open(fn, 'w') ...
list1=[2,3,8,5,9,2,7,4] i=0 print("before list",list1) while i<len(list1): j=0 while j<i: if list1[i]<list1[j]: temp=list1[i] list1[i]=list1[j] list1[j]=temp j+=1 i+=1 print("after",list1)
list1 = [2, 3, 8, 5, 9, 2, 7, 4] i = 0 print('before list', list1) while i < len(list1): j = 0 while j < i: if list1[i] < list1[j]: temp = list1[i] list1[i] = list1[j] list1[j] = temp j += 1 i += 1 print('after', list1)
class TimezoneTool: @classmethod def tzdb2abbreviation(cls, tzdb): if tzdb == "Asia/Seoul": return "KST" if tzdb == "America/Los_Angeles": return "ET" raise NotImplementedError({"tzdb":tzdb})
class Timezonetool: @classmethod def tzdb2abbreviation(cls, tzdb): if tzdb == 'Asia/Seoul': return 'KST' if tzdb == 'America/Los_Angeles': return 'ET' raise not_implemented_error({'tzdb': tzdb})
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jan 6 13:43:13 2017 @author: ktt """ def flatten(py_list): flat = [] for k in py_list: if k not in [None, (), [], {}]: if isinstance(k, list): flat.extend(flatten(k)) else: flat.a...
""" Created on Fri Jan 6 13:43:13 2017 @author: ktt """ def flatten(py_list): flat = [] for k in py_list: if k not in [None, (), [], {}]: if isinstance(k, list): flat.extend(flatten(k)) else: flat.append(k) return flat