content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
with open("input.txt", "r") as f: lines = f.readlines() for line1 in lines: for line2 in lines: total = int(line1) + int(line2) if total == 2020: print(f"line1: {line1}") print(f"line2: {line2}") print(f"Multiply: {int(line1) * int...
with open('input.txt', 'r') as f: lines = f.readlines() for line1 in lines: for line2 in lines: total = int(line1) + int(line2) if total == 2020: print(f'line1: {line1}') print(f'line2: {line2}') print(f'Multiply: {int(line1) * int(...
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project au...
{'includes': ['../build/common.gypi'], 'targets': [{'target_name': 'common_audio', 'type': 'static_library', 'dependencies': ['<(webrtc_root)/system_wrappers/system_wrappers.gyp:system_wrappers'], 'include_dirs': ['resampler/include', 'signal_processing/include'], 'direct_dependent_settings': {'include_dirs': ['resampl...
''' Topic : Algorithms Subtopic : SolveMeFirst Language : Python Problem Statement : sum of the above two integers Url : https://www.hackerrank.com/challenges/solve-me-first/problem ''' def solveMeFirst(a:int,b:int): # Hint: Type return a+b below return a + b num1 = int(input()) num2 = int(in...
""" Topic : Algorithms Subtopic : SolveMeFirst Language : Python Problem Statement : sum of the above two integers Url : https://www.hackerrank.com/challenges/solve-me-first/problem """ def solve_me_first(a: int, b: int): return a + b num1 = int(input()) num2 = int(input()) res = solve_me_first...
""" ROSM880102 - Side chain hydropathy, corrected for solvation (Roseman, 1988) - 0.28197135416666663 ZIMJ680104 - Isoelectric point (Zimmerman et al., 1968) - 0.2740677083333333 OOBM770104 - Average non-bonded energy per residue (Oobatake-Ooi, 1977) - 0.24981510416666666 SNEP660101 - Principal component I (Sneath, 196...
""" ROSM880102 - Side chain hydropathy, corrected for solvation (Roseman, 1988) - 0.28197135416666663 ZIMJ680104 - Isoelectric point (Zimmerman et al., 1968) - 0.2740677083333333 OOBM770104 - Average non-bonded energy per residue (Oobatake-Ooi, 1977) - 0.24981510416666666 SNEP660101 - Principal component I (Sneath, 196...
EXTERNAL_DEPS = [ "@jackson-core//jar:neverlink", "@jackson-databind//jar", "@jackson-annotations//jar", "@jackson-dataformat-yaml//jar", "@snakeyaml//jar", ]
external_deps = ['@jackson-core//jar:neverlink', '@jackson-databind//jar', '@jackson-annotations//jar', '@jackson-dataformat-yaml//jar', '@snakeyaml//jar']
#!/usr/bin/env python # -*- coding: utf-8 -*- """ =============================== |module_summary| object_data.py =============================== TOWRITE """ OBJ_TYPE_NULL = 0 """:NOTE: Allow this enum to evaluate false""" OBJ_TYPE_BASE = 100000 """:NOTE: Values >= 65536 ensure compatibility wit...
""" =============================== |module_summary| object_data.py =============================== TOWRITE """ obj_type_null = 0 ':NOTE: Allow this enum to evaluate false' obj_type_base = 100000 ':NOTE: Values >= 65536 ensure compatibility with qgraphicsitem_cast()' obj_type_arc = 100001 'TOWRITE' obj_type_block = 10...
def is_leap(year): leap = False # Write your logic here if year%400==0: leap=True elif year%100==0: leap=False elif year%4==0: leap=True return leap year = int(input())
def is_leap(year): leap = False if year % 400 == 0: leap = True elif year % 100 == 0: leap = False elif year % 4 == 0: leap = True return leap year = int(input())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 10 15:03:51 2020 @author: Konstantin Schuckmann """ ############################################################################################# ############################################ DUMMY ########################################## ########...
""" Created on Sat Oct 10 15:03:51 2020 @author: Konstantin Schuckmann """ dummy_temperature_path = '../resource_data/dummy/Bias_correction_ucl.csv' dummy_flight_path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv' dummy_save_path_section_2 = '../../../../Latex/bhtThesis/Masters/...
""" Defines our constants """ PROTOCOL_DEFAULT_TIMEOUT = 60 PROTOCOL_DEFAULT_PORT = 5672 PROTOCOL_HEADER = b'AMQP\x01\x01\x00\x09' MAX_CHANNELS = 65535 # protocol TYPE_METHOD = 1 TYPE_HEADER = 2 TYPE_BODY = 3 TYPE_HEARTBEAT = 8 FRAME_END = b'\xce' # classes CLASS_CONNECTION = 10 CLASS_CHANNEL = 20 CLASS_EXCHAN...
""" Defines our constants """ protocol_default_timeout = 60 protocol_default_port = 5672 protocol_header = b'AMQP\x01\x01\x00\t' max_channels = 65535 type_method = 1 type_header = 2 type_body = 3 type_heartbeat = 8 frame_end = b'\xce' class_connection = 10 class_channel = 20 class_exchange = 40 class_queue = 50 cla...
def evalQuadratic(a, b, c, x): ''' a, b, c: numerical values for the coefficients of a quadratic equation x: numerical value at which to evaluate the quadratic. ''' # Your code here return (a*(x**2))+(b*x)+c
def eval_quadratic(a, b, c, x): """ a, b, c: numerical values for the coefficients of a quadratic equation x: numerical value at which to evaluate the quadratic. """ return a * x ** 2 + b * x + c
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Chromium presubmit script for src/components/autofill. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on th...
"""Chromium presubmit script for src/components/autofill. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on the presubmit API built into depot_tools. """ def __check_no_base_time_calls(input_api, output_api): """Checks that no files call base::Time::Now() or base::Tim...
''' Author : kazi_amit_hasan Problem: Integer Sequence Dividing Solution: https://codeforces.com/blog/entry/64439 ''' n = int(input()) print(((n * (n + 1)) // 2) % 2)
""" Author : kazi_amit_hasan Problem: Integer Sequence Dividing Solution: https://codeforces.com/blog/entry/64439 """ n = int(input()) print(n * (n + 1) // 2 % 2)
#!/usr/bin/env python3 x = int(input("Enter number ")) if(x % 2 == 0): print("Even") else: print("Odd")
x = int(input('Enter number ')) if x % 2 == 0: print('Even') else: print('Odd')
class Solution(object): def isPalindrome(self, s): s = re.sub(r"\W+", r"", s.lower()) return s == s[::-1]
class Solution(object): def is_palindrome(self, s): s = re.sub('\\W+', '', s.lower()) return s == s[::-1]
team_names = ['LA Chargers', 'LA Rams', 'NE Patriots', 'NY Giants', 'Chicago Bears', 'Detroit Lions'] # TODO # Add possible locations and weeks in the season
team_names = ['LA Chargers', 'LA Rams', 'NE Patriots', 'NY Giants', 'Chicago Bears', 'Detroit Lions']
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Future: json context could look like { 'persistent_items': {...}, 'volatile_items': {...} } persistent_items: should be passed back and forth in all interactions. ex: user_responses volatile_items: Only make sense for a given, particular interaction. ex: current_questi...
""" Future: json context could look like { 'persistent_items': {...}, 'volatile_items': {...} } persistent_items: should be passed back and forth in all interactions. ex: user_responses volatile_items: Only make sense for a given, particular interaction. ex: current_question, next_question, message, input_type, input "...
spark = SparkSession \ .builder \ .appName("exercise_eleven") \ .getOrCreate() df1 = spark.read.parquet("hdfs://user/your_user_name/data/userdata1.parquet") df2 = spark.read.format("parquet").load("hdfs://user/your_user_name/data/userdata1.parquet") df1.show()
spark = SparkSession.builder.appName('exercise_eleven').getOrCreate() df1 = spark.read.parquet('hdfs://user/your_user_name/data/userdata1.parquet') df2 = spark.read.format('parquet').load('hdfs://user/your_user_name/data/userdata1.parquet') df1.show()
class Solution: def reverseBits(self, n: int) -> int: result = 0 for i in range(32): # first we move result by 1 bit result <<= 1 # then check if n have 1 at first bit if yes than add it to result result =result| (n & 1) #then finally drop...
class Solution: def reverse_bits(self, n: int) -> int: result = 0 for i in range(32): result <<= 1 result = result | n & 1 n >>= 1 return result
def direct_selection(list): ''' returns an ordered list ''' end = len(list) for i in range(end - 1): #stores the position of the element to be compared min_position = i for j in range(i + 1, end): if list[j] < list[min_position]: min_position = j ...
def direct_selection(list): """ returns an ordered list """ end = len(list) for i in range(end - 1): min_position = i for j in range(i + 1, end): if list[j] < list[min_position]: min_position = j (list[i], list[min_position]) = (list[min_position],...
# mode: run # tag: kwargs, call # ticket: 717 def f(**kwargs): return sorted(kwargs.items()) def test_call(kwargs): """ >>> kwargs = {'b' : 2} >>> f(a=1, **kwargs) [('a', 1), ('b', 2)] >>> test_call(kwargs) [('a', 1), ('b', 2)] >>> kwargs = {'a' : 2} >>> f(a=1, **kwargs) # doct...
def f(**kwargs): return sorted(kwargs.items()) def test_call(kwargs): """ >>> kwargs = {'b' : 2} >>> f(a=1, **kwargs) [('a', 1), ('b', 2)] >>> test_call(kwargs) [('a', 1), ('b', 2)] >>> kwargs = {'a' : 2} >>> f(a=1, **kwargs) # doctest: +ELLIPSIS Traceback (most recent call ...
# 22. A simple way of encrypting a message is to rearrange its characters. One way to rearrange the # characters is to pick out the characters at even indices, put them first in the encrypted string, # and follow them by the odd characters. For example, the string 'message' would be encrypted # as 'msaeesg' because the...
s = input('Enter a string: ') (even, odd) = ('', '') for i in range(0, len(s)): if i % 2 == 0: even += s[i] else: odd += s[i] encrypted = even + odd print('The encrypted string is:', encrypted) (decrypted, even_idx, odd_idx) = ('', 0, 0) for i in range(len(encrypted)): if i % 2 == 0: ...
instructions = input() h_count = 0 v_count = 0 for letter in instructions: if letter == "H": h_count += 1 elif letter == "V": v_count += 1 if h_count%2 == 0: if v_count%2 == 0: print("1 2\n3 4") elif v_count%2 == 1: print("2 1\n4 3") elif h_count%2 == 1: if v_count%2 ...
instructions = input() h_count = 0 v_count = 0 for letter in instructions: if letter == 'H': h_count += 1 elif letter == 'V': v_count += 1 if h_count % 2 == 0: if v_count % 2 == 0: print('1 2\n3 4') elif v_count % 2 == 1: print('2 1\n4 3') elif h_count % 2 == 1: if v_...
# This program calculates "area" of square. In this example, we see couple # of important things - assignments and mathematical operators. Guess what # the following code does? side = 4 area = side * side print(area) # Do it yourself # 1. Write a program to calculate area of triangle # 2. Write a program to calculate...
side = 4 area = side * side print(area)
def get_tweet_by_tweet_id(tweet_set, tweet_id): """ Retrieves tweet, based on unique tweet id. Args: tweet_set: A set of tweets. tweet_id: A unique tweet id. Returns: A tweet with the defined tweet id. """ for tweet in tweet_set: if tweet.tweet_id == tweet_id: ...
def get_tweet_by_tweet_id(tweet_set, tweet_id): """ Retrieves tweet, based on unique tweet id. Args: tweet_set: A set of tweets. tweet_id: A unique tweet id. Returns: A tweet with the defined tweet id. """ for tweet in tweet_set: if tweet.tweet_id == tweet_id: ...
class Node(object): __slots__ = ('name', 'path', 'local', 'is_leaf') def __init__(self, path): self.path = path self.name = path.split('.')[-1] self.local = True self.is_leaf = False def __repr__(self): return '<%s[%x]: %s>' % (self.__class__.__name__, id(self), s...
class Node(object): __slots__ = ('name', 'path', 'local', 'is_leaf') def __init__(self, path): self.path = path self.name = path.split('.')[-1] self.local = True self.is_leaf = False def __repr__(self): return '<%s[%x]: %s>' % (self.__class__.__name__, id(self), sel...
__version__ = '1.0.4' __cmd_description__ = """Check HTTP status codes, response headers and redirects. This is free software and it comes with absolutely no warranty. You can distribute and modify it under terms of MIT License. Homepage: https://codehill.com/projects/webchk"""
__version__ = '1.0.4' __cmd_description__ = 'Check HTTP status codes, response headers and redirects.\nThis is free software and it comes with absolutely no warranty.\nYou can distribute and modify it under terms of MIT License.\nHomepage: https://codehill.com/projects/webchk'
first_parts = ["Ask-i", "Avrupa", "Asmali", "Yaprak", "Tatli", "Arka", "Cocuklar"] second_parts = ["Memnu", "Yakasi", "Konak", "Dokumu", "Hayat", "Sokaklar", "Duymasin"] ind = 0 last_ind = len(first_parts)-1 while ind <= last_ind: full_name = first_parts[ind] + ' ' + second_parts[ind] print(full_name) ind += 1...
first_parts = ['Ask-i', 'Avrupa', 'Asmali', 'Yaprak', 'Tatli', 'Arka', 'Cocuklar'] second_parts = ['Memnu', 'Yakasi', 'Konak', 'Dokumu', 'Hayat', 'Sokaklar', 'Duymasin'] ind = 0 last_ind = len(first_parts) - 1 while ind <= last_ind: full_name = first_parts[ind] + ' ' + second_parts[ind] print(full_name) ind...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'recipe_engine/context', 'recipe_engine/step', ] def RunSteps(api): with api.context( env={'mood': 'excellent', 'climate': 'sunny'}, ...
deps = ['recipe_engine/context', 'recipe_engine/step'] def run_steps(api): with api.context(env={'mood': 'excellent', 'climate': 'sunny'}, name_prefix='grandparent'): with api.context(env={'climate': 'rainy'}, name_prefix='mom'): api.step('child', ['echo', 'billy']) with api.context(env...
begin_unit comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/LICENSE...
begin_unit comment | '# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl | '\n' comment | '# not use this file except in compliance with the License. You may obtain' nl | '\n' comment | '# a copy of the License at' nl | '\n' comment | '#' nl | '\n' comment | '# http://www.apache.or...
def my_awesome_decorator(fun): def wrapped(*args): # increase value _list = [number + 1 for number in args] return fun(*_list) return wrapped @my_awesome_decorator def mod_batch(*numbers): # check divide return all([True if number % 3 == 0 else False for number in numbers ]) print(mod_batch(9,...
def my_awesome_decorator(fun): def wrapped(*args): _list = [number + 1 for number in args] return fun(*_list) return wrapped @my_awesome_decorator def mod_batch(*numbers): return all([True if number % 3 == 0 else False for number in numbers]) print(mod_batch(9, 18, 21)) print(mod_batch(9, ...
# -*- coding: utf-8 -*- # coding: utf-8 # ----------------------------------------------------------------------------- # Copyright 2012-2017 Andreas Maier. 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 m...
""" Configuration parameters for ownmoviedb project. """ cmdline_cp = 'cp1252' filename_cp = 'cp1252' mysql_host = '192.168.0.12' mysql_port = None mysql_db = 'ownmoviedb' mysql_user = 'pyuser' mysql_pass = None _std_share = '\\\\' + MYSQL_HOST + '\\share' _std_patterns = ['*.mp4', '*.avi', '*.mkv', '*.flv'] file_sourc...
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: queryMultiWindow.py # # Tests: queries - Database # # Defect ID: none # # Programmer: Kathleen Bonnell # Date: May 19, 2004 # # Modifications: # Kathleen Bonnell, Mon Dec 20 15:...
def query_multi_window(): open_database(silo_data_path('wave*.silo database')) add_plot('Pseudocolor', 'pressure') set_time_slider_state(31) draw_plots() v = get_view3_d() v.viewNormal = (0, -1, 0) v.viewUp = (0, 0, 1) set_view3_d(v) clone_window() set_time_slider_state(64) d...
def unrestricted_security_groups_ingress(sgs): """If Protocol, Ports and Range conjunction is *""" for sg in sgs["SecurityGroups"]: for ip in sg["IpPermissions"]: any_protocol = False any_port = False any_range = False # Protocol if 'FromPort' ...
def unrestricted_security_groups_ingress(sgs): """If Protocol, Ports and Range conjunction is *""" for sg in sgs['SecurityGroups']: for ip in sg['IpPermissions']: any_protocol = False any_port = False any_range = False if 'FromPort' not in ip.keys(): ...
# Recursive class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root if root.left: root.left.next = root.right if root.next and root.right: root.right.next = root.next.left self.connect(root.left) self.connect(roo...
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root if root.left: root.left.next = root.right if root.next and root.right: root.right.next = root.next.left self.connect(root.left) self.connect(root.right) ...
#!/usr/bin/python3 """ Module for is_same_class(obj, a_class) function that returns True if the object is exactly an instance of the specified class ; otherwise False. """ def is_same_class(obj, a_class): """ Function that determine the type of class. Args: obj (object any type): The object to an...
""" Module for is_same_class(obj, a_class) function that returns True if the object is exactly an instance of the specified class ; otherwise False. """ def is_same_class(obj, a_class): """ Function that determine the type of class. Args: obj (object any type): The object to analyze. a_cla...
# WARNING: Do not edit by hand, this file was generated by Crank: # # https://github.com/gocardless/crank # class Block(object): """A thin wrapper around a block, providing easy access to its attributes. Example: block = client.blocks.get() block.id """ def __init__(self, attributes...
class Block(object): """A thin wrapper around a block, providing easy access to its attributes. Example: block = client.blocks.get() block.id """ def __init__(self, attributes, api_response): self.attributes = attributes self.api_response = api_response @property ...
# -*- coding: utf-8 -*- # merge two different dict object def merge(new, base): for i in new: base[i] = new[i] return base
def merge(new, base): for i in new: base[i] = new[i] return base
# Title : Print number and square as tuple # Author : Kiran raj R. # Date : 24:10:2020 userInput = input( "Enter the limit till you need to print the sqaure of numbers :") square_tup = () for i in range(1, int(userInput)+1): square_tup += (i, i**2) try: for j in range(0, len(square_tup), 2): p...
user_input = input('Enter the limit till you need to print the sqaure of numbers :') square_tup = () for i in range(1, int(userInput) + 1): square_tup += (i, i ** 2) try: for j in range(0, len(square_tup), 2): print(f'({square_tup[j]}, {square_tup[j + 1]})') except IndexError: print('Finish printing...
class SampleCmd(object): def hello(self, *args): if len(args) == 0: print("hello") else: print("hello, " + args[0]) class SampleCmdWrapper(gdb.Command): def __init__(self): super(SampleCmdWrapper,self).__init__("sample", gdb.COMMAND_USER) def invoke(self, ar...
class Samplecmd(object): def hello(self, *args): if len(args) == 0: print('hello') else: print('hello, ' + args[0]) class Samplecmdwrapper(gdb.Command): def __init__(self): super(SampleCmdWrapper, self).__init__('sample', gdb.COMMAND_USER) def invoke(self,...
#!/usr/bin/env python # Copyright 2017 The Forseti Security 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 # #...
"""Test IAM policies data.""" fake_org_iam_policy_map = [{'org_id': 666666, 'iam_policy': {'bindings': [{'role': 'roles/billing.creator', 'members': ['domain:foo.com']}, {'role': 'roles/browser', 'members': ['serviceAccount:55555-compute@developer.gserviceaccount.com', 'serviceAccount:99999-compute@developer.gserviceac...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 17 15:26:24 2021 @author: alejandrobertolet """ VERSION = (1, 1, 0) __version__ = '.'.join(map(str, VERSION))
""" Created on Wed Nov 17 15:26:24 2021 @author: alejandrobertolet """ version = (1, 1, 0) __version__ = '.'.join(map(str, VERSION))
n, w = map(int, input().split()) items = [] append = items.append for i in range(n): append(list(map(int, input().split()))) def knapsack(n, w, items): c = [[0] * (w + 1) for _ in range(n + 1)] g = [[0] * (w + 1) for _ in range(n + 1)] for i in range(w + 1): g[0][i] = 1 for i in range(1...
(n, w) = map(int, input().split()) items = [] append = items.append for i in range(n): append(list(map(int, input().split()))) def knapsack(n, w, items): c = [[0] * (w + 1) for _ in range(n + 1)] g = [[0] * (w + 1) for _ in range(n + 1)] for i in range(w + 1): g[0][i] = 1 for i in range(1, ...
class Tree(): vertices = [(0,0,0), (0,1,0), (1,1,0), (1,0,0), (0,0,1.75), (0,1,1.75), (1,1,1.75), (1,0,1.75), #start of tree (-1,-1,1.75),#8 (-1,2,1.75), (2,2,1.75), (2,-1,...
class Tree: vertices = [(0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0), (0, 0, 1.75), (0, 1, 1.75), (1, 1, 1.75), (1, 0, 1.75), (-1, -1, 1.75), (-1, 2, 1.75), (2, 2, 1.75), (2, -1, 1.75), (0.5, 0.5, 8)] faces = [(0, 1, 2, 3), (0, 4, 5, 1), (1, 5, 6, 2), (2, 6, 7, 3), (3, 7, 4, 0), (8, 9, 10, 11), (8, 9, 12), (8, 11...
def main(): x = int(input("Enter an integer: ")) if x > 0: print("Number is positive!") elif x < 0: print("Number is negative!") else: print("You entered a zero!") if __name__ == '__main__': main()
def main(): x = int(input('Enter an integer: ')) if x > 0: print('Number is positive!') elif x < 0: print('Number is negative!') else: print('You entered a zero!') if __name__ == '__main__': main()
#!/usr/bin/env python3 def test_prime(test_value): if test_value == 2: return 1 for x in range(2, test_value): if test_value % x == 0: return 0 return 1 def main(): test_value = 179424673 if test_prime(test_value): print(test_value, "is prime.") else: ...
def test_prime(test_value): if test_value == 2: return 1 for x in range(2, test_value): if test_value % x == 0: return 0 return 1 def main(): test_value = 179424673 if test_prime(test_value): print(test_value, 'is prime.') else: print(test_value, 'is ...
#!/usr/bin/env python try: number = int(input("Enter a number: ")) except: print("That's silly") exit() potential_divisors = list(range(1, int(number/2 + 1))) potential_divisors.append(number) divisors = [] for div in potential_divisors: if number % div == 0: divisors.append(str(div)) print(...
try: number = int(input('Enter a number: ')) except: print("That's silly") exit() potential_divisors = list(range(1, int(number / 2 + 1))) potential_divisors.append(number) divisors = [] for div in potential_divisors: if number % div == 0: divisors.append(str(div)) print('The factors of ' + str(...
load("@bazel_skylib//lib:shell.bzl", "shell") load("@io_bazel_rules_go//go:def.bzl", "go_context") def _yo_impl(ctx): go = go_context(ctx) godir = go.go.path[:-1 - len(go.go.basename)] env = dict(go.env) env["YO"] = ctx.attr._yo_executable.files.to_list()[0].path env["SCHEMA_FILE"] = ctx.attr.schem...
load('@bazel_skylib//lib:shell.bzl', 'shell') load('@io_bazel_rules_go//go:def.bzl', 'go_context') def _yo_impl(ctx): go = go_context(ctx) godir = go.go.path[:-1 - len(go.go.basename)] env = dict(go.env) env['YO'] = ctx.attr._yo_executable.files.to_list()[0].path env['SCHEMA_FILE'] = ctx.attr.schem...
# -*- coding: utf-8 -*- """ Created on Wed Sep 20 17:19:43 2017 @author: tkoller """
""" Created on Wed Sep 20 17:19:43 2017 @author: tkoller """
class Creature(object): def __init__(self): self.id = 0 self.food_gathered = 0 self.position = []
class Creature(object): def __init__(self): self.id = 0 self.food_gathered = 0 self.position = []
class EnergyAnalysisSurface(Element,IDisposable): """ Analytical surface. The collection of analytic openings belonging to this analytical parent surface """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def GetAdjacentAnalyticalSpace(self): """ GetAdjacentAnalyticalSpace...
class Energyanalysissurface(Element, IDisposable): """ Analytical surface. The collection of analytic openings belonging to this analytical parent surface """ def dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def get_adjacent_analytical_space(self): """ GetA...
"""Create a function that receives an array of numbers as argument and returns an array containing only the positive numbers""" num = [86, -57, 45, -30, 23, -12] def solution(num: list) -> list: return [pn for pn in num if pn > 0] print(solution(num))
"""Create a function that receives an array of numbers as argument and returns an array containing only the positive numbers""" num = [86, -57, 45, -30, 23, -12] def solution(num: list) -> list: return [pn for pn in num if pn > 0] print(solution(num))
database_set = { 'driver': 'influxdb', 'timezone': 'Asia/Shanghai', 'port': 0, 'host': '', 'database': '', 'username': '', 'password': '' } product_list = ['jinshan'] product_accounts = { 'jinshan': [ 'CTP.990175', ] } product_alarm = { 'jinshan':'alarm_setting.csv'...
database_set = {'driver': 'influxdb', 'timezone': 'Asia/Shanghai', 'port': 0, 'host': '', 'database': '', 'username': '', 'password': ''} product_list = ['jinshan'] product_accounts = {'jinshan': ['CTP.990175']} product_alarm = {'jinshan': 'alarm_setting.csv'} acc_folder = {'jinshan': 'outsourceData.csv'} sector_file =...
age = int(input("Please enter your age here:\n")) if ((age >= 1) and (age <= 6)): print("Hi little baby") elif ((age >= 6) and (age <= 12)): print("Hey little kid") elif ((age >= 13) and (age <= 17)): print("Hey there teen") elif ((age >= 18) and (age <= 40)): print("Hey you are an adult") elif age >= ...
age = int(input('Please enter your age here:\n')) if age >= 1 and age <= 6: print('Hi little baby') elif age >= 6 and age <= 12: print('Hey little kid') elif age >= 13 and age <= 17: print('Hey there teen') elif age >= 18 and age <= 40: print('Hey you are an adult') elif age >= 41: print('You are gr...
class Bird: def __init__(self, x): """ init function """ self.x = x; print("Bird initialized") def flyUp(self): print("Flying up") def flyForward(self): print("Flying forward")
class Bird: def __init__(self, x): """ init function """ self.x = x print('Bird initialized') def fly_up(self): print('Flying up') def fly_forward(self): print('Flying forward')
my_dict = {"force": [0, 10, 15, 30, 45], "distance": [2.5, 3.5, 6.0, -3.0, 8.1]} res = 0.0 # Here the zip operator is used to iterate over both lists. for force, dist in zip(my_dict["force"], my_dict["distance"]): res += force * dist print(res)
my_dict = {'force': [0, 10, 15, 30, 45], 'distance': [2.5, 3.5, 6.0, -3.0, 8.1]} res = 0.0 for (force, dist) in zip(my_dict['force'], my_dict['distance']): res += force * dist print(res)
# Test duration: 1 hour and 50 minutes (9:10am-11:00am) # # Aids allowed: any material on the course website http://www.cs.toronto.edu/~guerzhoy/180/ # You may use Pyzo (or another Python IDE) during the exam. # # You are responsible for submitting the file midterm.py on Gradescope. # # You can resubmit the file multip...
def sum_cubes(k): s = 0 for i in range(1, k + 1): s += i * i * i return s def sum_cubes_num_terms(n): s = 0 k = 0 while s + k * k * k < n: s += k * k * k k += 1 return k measurements = [10.4, 1.6, 2, 0.2, 0, 0, 5.2, 0, 0, 0, 0, 0, 3.8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2...
def branch2lists(tree): res = [] (statement, superior) = tree if superior: for issuer, branch in superior.items(): _lists = branch2lists(branch) for l in _lists: l.append(statement) if not res: res = _lists else: ...
def branch2lists(tree): res = [] (statement, superior) = tree if superior: for (issuer, branch) in superior.items(): _lists = branch2lists(branch) for l in _lists: l.append(statement) if not res: res = _lists else: ...
""" Module implementing a class for handling the experiment configurations defined in the interface. The user can load these, if they were saved previously. The class handles the following variables: TODO Experiment type : `self._strElectrochemicalMethod` Experiment parameters : `self._listExperimentParamet...
""" Module implementing a class for handling the experiment configurations defined in the interface. The user can load these, if they were saved previously. The class handles the following variables: TODO Experiment type : `self._strElectrochemicalMethod` Experiment parameters : `self._listExperimentParamet...
# -------------------------------------------------------- __author__ = "Vladimir Fedorov" __copyright__ = "Copyright (C) 2013 Migrate2Iaas" #--------------------------------------------------------- class TransferTarget(object): """Abstract class representing backup transfer target""" # TODO: change coding ...
__author__ = 'Vladimir Fedorov' __copyright__ = 'Copyright (C) 2013 Migrate2Iaas' class Transfertarget(object): """Abstract class representing backup transfer target""" def transfer_file(self, fileToBackup): """ writes the file need file metadata\\permissions too """ ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Pytest""" def increment(val): '''Increase by 1''' return val + 1 def decrement(val): '''Decrease by 1''' return val - 1
"""Pytest""" def increment(val): """Increase by 1""" return val + 1 def decrement(val): """Decrease by 1""" return val - 1
class UIApplication(object,IDisposable): """ Represents an active session of the Autodesk Revit user interface,providing access to UI customization methods,events,and the active document. UIApplication(revitApp: Application) """ def CanPostCommand(self,commandId): """ CanPostCommand(self: UIA...
class Uiapplication(object, IDisposable): """ Represents an active session of the Autodesk Revit user interface,providing access to UI customization methods,events,and the active document. UIApplication(revitApp: Application) """ def can_post_command(self, commandId): """ CanPostCommand(s...
class Animal: type = "Animal" """ Base class Animal """ def __init__(self): self.name = None self.age = None def show(self): print("I am an animal %s" % self.name) def foo1(self): pass class Cat(Animal): """ Derived class Cat """ def climb(self): ...
class Animal: type = 'Animal' ' Base class Animal ' def __init__(self): self.name = None self.age = None def show(self): print('I am an animal %s' % self.name) def foo1(self): pass class Cat(Animal): """ Derived class Cat """ def climb(self): prin...
class BrownifyError(Exception): """Generic error for brownify""" class DownloadError(BrownifyError): """Error raised when unable to download an audio stream DownloadError is raised when a downloader fails to fetch audio desired by the caller. """ class InvalidInputError(BrownifyError): """E...
class Brownifyerror(Exception): """Generic error for brownify""" class Downloaderror(BrownifyError): """Error raised when unable to download an audio stream DownloadError is raised when a downloader fails to fetch audio desired by the caller. """ class Invalidinputerror(BrownifyError): """Err...
# # Copyright (c) 2017 Joy Diamond. All rights reserved. # @gem('Sapphire.Parse1ExpressionStatement') def gem(): require_gem('Sapphire.BookcaseManyStatement') show = 0 def parse1_statement_assign__left__equal_sign(indented, left, equal_sign): right = parse1_ternary_expression_list() ...
@gem('Sapphire.Parse1ExpressionStatement') def gem(): require_gem('Sapphire.BookcaseManyStatement') show = 0 def parse1_statement_assign__left__equal_sign(indented, left, equal_sign): right = parse1_ternary_expression_list() operator = qk() if operator is not none: wk(no...
""" Created by Narayan Schuetz at 15.11.20 University of Bern This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. """
""" Created by Narayan Schuetz at 15.11.20 University of Bern This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. """
expected_output = { "vrf": { "default": { "source_address": "192.168.16.226", "source_host": "?", "mofrr": "Enabled", "path": { "192.168.145.2 Ethernet1/4": { "interface_name": "Ethernet1/4", "neighbor_ho...
expected_output = {'vrf': {'default': {'source_address': '192.168.16.226', 'source_host': '?', 'mofrr': 'Enabled', 'path': {'192.168.145.2 Ethernet1/4': {'interface_name': 'Ethernet1/4', 'neighbor_host': '?', 'neighbor_address': '192.168.145.2', 'table_type': 'unicast', 'table_feature': 'ospf', 'table_feature_instance'...
{ "downloads" : [ "https://github.com/google/glog/archive/v0.4.0.tar.gz" ], "license" : "COPYING", "commands" : [ "mkdir gafferBuild", "cd gafferBuild &&" " cmake" " -G {cmakeGenerator}" " -D CMAKE_C_COMPILER={cCompiler}" " -D CMAKE_CXX_COMPILER={cxxCompiler}" " -D CMAKE_INSTALL_PREFIX={b...
{'downloads': ['https://github.com/google/glog/archive/v0.4.0.tar.gz'], 'license': 'COPYING', 'commands': ['mkdir gafferBuild', 'cd gafferBuild && cmake -G {cmakeGenerator} -D CMAKE_C_COMPILER={cCompiler} -D CMAKE_CXX_COMPILER={cxxCompiler} -D CMAKE_INSTALL_PREFIX={buildDir} -D CMAKE_PREFIX_PATH={buildDir} -D CMAKE_POS...
def escreva(a): tam = len(a) + 4 print('~'*tam) print(f' {a}') print('~'*tam) escreva('Bruno')
def escreva(a): tam = len(a) + 4 print('~' * tam) print(f' {a}') print('~' * tam) escreva('Bruno')
class Singleton(type): """ A class that inherit form 'type' and allows to implement Singleton Pattern. """ __instance = None def __call__(cls, *args, **kwargs): # type: ignore if not isinstance(cls.__instance, cls): cls.__instance = super(Singleton, cls).__call__(*args, **kwar...
class Singleton(type): """ A class that inherit form 'type' and allows to implement Singleton Pattern. """ __instance = None def __call__(cls, *args, **kwargs): if not isinstance(cls.__instance, cls): cls.__instance = super(Singleton, cls).__call__(*args, **kwargs) retur...
# this is a simple comment ''' this is a multi-line comment ''' phrase = 'The source code is commented' print(phrase)
""" this is a multi-line comment """ phrase = 'The source code is commented' print(phrase)
# https://leetcode.com/problems/count-numbers-with-unique-digits/ #Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. class Solution(object): def countNumbersWithUniqueDigits(self, n): """ :type n: int :rtype: int """ if n == 0: ...
class Solution(object): def count_numbers_with_unique_digits(self, n): """ :type n: int :rtype: int """ if n == 0: return 1 if n == 1: return 10 if n > 10: return 0 if n == 2: return 9 * 9 if n =...
class SpinnMachineException(Exception): """ A generic exception which all other exceptions extend """ pass class SpinnMachineAlreadyExistsException(SpinnMachineException): """ Indicates that something already exists of which there can only be one """ def __init__(self, item, value): ...
class Spinnmachineexception(Exception): """ A generic exception which all other exceptions extend """ pass class Spinnmachinealreadyexistsexception(SpinnMachineException): """ Indicates that something already exists of which there can only be one """ def __init__(self, item, value): ""...
def solution(A): A.sort() scenario1 = A[0] * A[1] * A[-1] scenario2 = A[-1] * A[-2] * A[-3] return scenario1 if (scenario1 > scenario2) else scenario2
def solution(A): A.sort() scenario1 = A[0] * A[1] * A[-1] scenario2 = A[-1] * A[-2] * A[-3] return scenario1 if scenario1 > scenario2 else scenario2
CHAR_OFFSET = 32 # skip control chars START_EMOJI = ord('\U0001F601') def encode(msg, binary=False): ''' Encode a message using emojis ''' new_str = '' if binary: msg_bytes = msg else: msg_bytes = bytes(msg, 'utf-8') for b in msg_bytes: #print(b + START_EM...
char_offset = 32 start_emoji = ord('😁') def encode(msg, binary=False): """ Encode a message using emojis """ new_str = '' if binary: msg_bytes = msg else: msg_bytes = bytes(msg, 'utf-8') for b in msg_bytes: new_str = new_str + chr(b + START_EMOJI - CHAR_OFFSET) ...
# 2020.07.29 # Problem Statement # https://leetcode.com/problems/reverse-nodes-in-k-group/ # Looked up the following youtube video: # https://www.youtube.com/watch?v=cFDvbKTNeCA # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.ne...
class Solution: def reverse_k(k, first): new_tail = first prev = None for i in range(0, k): next_node = first.next first.next = prev prev = first first = next_node new_head = prev after = first return (new_head, new_tai...
t = int(input()) for i in range(t): a = input() b = input() minimum = 3000 flag = 0 for a_iter in range(len(a)-1): if a[a_iter]==b[0]: if len(b)==1: minimum = 0 flag = 1 break b_index = 1 for iter in ra...
t = int(input()) for i in range(t): a = input() b = input() minimum = 3000 flag = 0 for a_iter in range(len(a) - 1): if a[a_iter] == b[0]: if len(b) == 1: minimum = 0 flag = 1 break b_index = 1 for iter in ra...
# coding: utf-8 """ MIDI Note information """ class MIDINote: def __init__( self, noteNo = -1, velocity = -1 ): self.noteNo = noteNo self.velocity = velocity def valid( self ): return self.noteNo >= 0 and self.velocity >= 0 """ MIDI CC information """ class MIDICc: def __init__(...
""" MIDI Note information """ class Midinote: def __init__(self, noteNo=-1, velocity=-1): self.noteNo = noteNo self.velocity = velocity def valid(self): return self.noteNo >= 0 and self.velocity >= 0 '\nMIDI CC information\n' class Midicc: def __init__(self, ccNo=-1, ccValue=-1)...
# Create a list of words from the text below that are shorter than or equal to the input # value. Print the new list. text = [["Glitch", "is", "a", "minor", "problem", "that", "causes", "a", "temporary", "setback"], ["Ephemeral", "lasts", "one", "day", "only"], ["Accolade", "is", "an", "expression", "o...
text = [['Glitch', 'is', 'a', 'minor', 'problem', 'that', 'causes', 'a', 'temporary', 'setback'], ['Ephemeral', 'lasts', 'one', 'day', 'only'], ['Accolade', 'is', 'an', 'expression', 'of', 'praise']] print([word for sentence in text for word in sentence if len(word) <= int(input())])
#! /usr/bin/env python3 # Shirin Nagle #Calculate the square root of a number def sqrt(x): """ Calculate the square root of argument x. """ # Check that x is positive if x < 0: print("Error: Negative value supplied") return -1 else: print ("The number is positive") #Initial guess for the sq...
def sqrt(x): """ Calculate the square root of argument x. """ if x < 0: print('Error: Negative value supplied') return -1 else: print('The number is positive') z = x / 2.0 counter = 1 while abs(x - z * z) > 1e-07: z -= (z * z - x) / (2 * z) counter += ...
#Smallest multiple def Euler5(n): l=list(range(n+1))[2:] for i in range(len(l)): for j in range(i+1,len(l)): if l[j]%l[i]==0: l[j]//=l[i] p=1 for x in l: p*=x return p print(Euler5(100))
def euler5(n): l = list(range(n + 1))[2:] for i in range(len(l)): for j in range(i + 1, len(l)): if l[j] % l[i] == 0: l[j] //= l[i] p = 1 for x in l: p *= x return p print(euler5(100))
description_short = "Help you deal with multiple git repositories" keywords = [ "git", "python", "repositories", "multiple", ]
description_short = 'Help you deal with multiple git repositories' keywords = ['git', 'python', 'repositories', 'multiple']
# -*- coding: utf-8 *-* # Copyright (C) 2011-2012 Canonical Services Ltd # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
class Belowcondition(object): def __init__(self, value, slope=0): self.value = value self.slope = slope def __call__(self, value, size=1): return value < self.value + self.slope * size class Abovecondition(object): def __init__(self, value, slope=0): self.value = value ...
""" FFOMP package ============= This package takes advantage of the sympy symbolic algebra system to facilitate the fitting of modelled parameters. It consists of the following main modules .. autosummary:: :toctree: generated :template: module.rst fitjob model solvers mmmodels ccutils "...
""" FFOMP package ============= This package takes advantage of the sympy symbolic algebra system to facilitate the fitting of modelled parameters. It consists of the following main modules .. autosummary:: :toctree: generated :template: module.rst fitjob model solvers mmmodels ccutils "...
class Solution(object): def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ if not ratings: return 0 n = len(ratings) candies = [1] * n for i in range(1, n): if ratings[i] > ratings[i - 1]: ca...
class Solution(object): def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ if not ratings: return 0 n = len(ratings) candies = [1] * n for i in range(1, n): if ratings[i] > ratings[i - 1]: ca...
class UnityYamlStream( object ): def __init__(self, path ): self.__file = open(path) self.__fileIds = list() def read(self, param): line = self.__file.readline() if line == None or line == '': self.__file.close() self.__fileIds.append( 0 ) return '' if line.startswith('---'): tag = l...
class Unityyamlstream(object): def __init__(self, path): self.__file = open(path) self.__fileIds = list() def read(self, param): line = self.__file.readline() if line == None or line == '': self.__file.close() self.__fileIds.append(0) return ...
# # PySNMP MIB module HPN-ICF-MPLSTE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-MPLSTE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:40:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ...
"""Advent of Code Day 25 - Four Dimensional Adventure""" class FixedPoint: """Initialise fixed point as ranked, self-parented node.""" def __init__(self, num): self.num = num self.parent = self self.rank = 0 def find(point): """Return root of point (parent with parent as self).""...
"""Advent of Code Day 25 - Four Dimensional Adventure""" class Fixedpoint: """Initialise fixed point as ranked, self-parented node.""" def __init__(self, num): self.num = num self.parent = self self.rank = 0 def find(point): """Return root of point (parent with parent as self)."""...
# @lc app=leetcode id=2119 lang=python3 # # [2119] A Number After a Double Reversal # # @lc code=start class Solution: def isSameAfterReversals(self, num: int) -> bool: return int(str(int(str(num)[::-1]))[::-1]) == num # @lc code=end
class Solution: def is_same_after_reversals(self, num: int) -> bool: return int(str(int(str(num)[::-1]))[::-1]) == num
# This function is a remnant of a failed attempt (I might use it later) # def smallest_factor(number: int): # for factor in range(2, int((number)**0.5+1)): # if number % factor == 0: # return(factor) # #if there is no factor, it is prime # return number def num_factors(n: int): ...
def num_factors(n: int): """The number of factors of n""" count = 0 factor = 1 max_search = n while factor < max_search: if n % factor == 0: if factor ** 2 == n: count += 1 return count count += 2 max_search = n / factor ...
""" Space : O(n) Time : O(nk) """ class Solution: def winnerSquareGame(self, n: int) -> bool: square = [] for x in range(1, int(n**0.5)+1): square.append(x**2) dp = [False] * (n+1) for i in range(1, n+1): for s in square: if s > i: ...
""" Space : O(n) Time : O(nk) """ class Solution: def winner_square_game(self, n: int) -> bool: square = [] for x in range(1, int(n ** 0.5) + 1): square.append(x ** 2) dp = [False] * (n + 1) for i in range(1, n + 1): for s in square: if ...
#!/usr/bin/env python3 def getAdjacentCoords(Coord, maxX=0, maxY=0): def checkBoundary(X, Y): return X >= 0 and X < maxX and Y >= 0 and Y < maxY X, Y = Coord res = set() offsets = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)) for offsetX, offsetY in offsets: ...
def get_adjacent_coords(Coord, maxX=0, maxY=0): def check_boundary(X, Y): return X >= 0 and X < maxX and (Y >= 0) and (Y < maxY) (x, y) = Coord res = set() offsets = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)) for (offset_x, offset_y) in offsets: curr_x = ...
"""Assignment 9""" #Here we are processing the marks of a student JOHN and finding the average marks of his 3 subjects maths = int(input("Marks in maths?: ")) chemistry = int(input("Marks in chemistry?: ")) physics = int(input("Marks is physics?: ")) average = (maths+chemistry+physics)//3 print("The average marks sco...
"""Assignment 9""" maths = int(input('Marks in maths?: ')) chemistry = int(input('Marks in chemistry?: ')) physics = int(input('Marks is physics?: ')) average = (maths + chemistry + physics) // 3 print('The average marks scored by john : ', average)
# 0. Hello World print("Hello World!") print("Time for some Python")
print('Hello World!') print('Time for some Python')
# # PySNMP MIB module CISCO-L2NAT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-L2NAT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:04:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_range_constraint, constraints_union, constraints_intersection, value_size_constraint) ...
""" Implement pow(x, n), which calculates x raised to the power n (i.e., xn). Example 1: Input: x = 2.00000, n = 10 Output: 1024.00000 Example 2: Input: x = 2.10000, n = 3 Output: 9.26100 Example 3: Input: x = 2.00000, n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Constraints: -100.0 < x < 100.0 ...
""" Implement pow(x, n), which calculates x raised to the power n (i.e., xn). Example 1: Input: x = 2.00000, n = 10 Output: 1024.00000 Example 2: Input: x = 2.10000, n = 3 Output: 9.26100 Example 3: Input: x = 2.00000, n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Constraints: -100.0 < x < 100.0 ...
def pythonic_quick_sort(a): if len(a) <= 1: return a pivot = a[-1] pivots = [i for i in a if i == pivot] left = pythonic_quick_sort([i for i in a if i < pivot]) right = pythonic_quick_sort([i for i in a if i > pivot]) return left + pivots + right
def pythonic_quick_sort(a): if len(a) <= 1: return a pivot = a[-1] pivots = [i for i in a if i == pivot] left = pythonic_quick_sort([i for i in a if i < pivot]) right = pythonic_quick_sort([i for i in a if i > pivot]) return left + pivots + right
# class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): current = self s = '' while current is not None: s += str(current.val) + '- ' current = current.next return s class LinkedList(object):...
class Listnode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): current = self s = '' while current is not None: s += str(current.val) + '- ' current = current.next return s class Linkedlist(object): ...
class Story: def __init__(self, raw_story): self.__raw_history = raw_story def get_raw(self, key): return self.__raw_history[key] def get_items(self): return self.__raw_history.items()
class Story: def __init__(self, raw_story): self.__raw_history = raw_story def get_raw(self, key): return self.__raw_history[key] def get_items(self): return self.__raw_history.items()
string=input("enter a string") print(len(string)) print(string*5) print(string[0]) print(string[-1]) print(string[: :-1]) if len(string) >= 7: print(string[6]) else: print("please enter more than 7 charecters next time") print(string[1:-1]) print(string.upper()) print(string.replace('a', 'e')) print('*'*len(str...
string = input('enter a string') print(len(string)) print(string * 5) print(string[0]) print(string[-1]) print(string[::-1]) if len(string) >= 7: print(string[6]) else: print('please enter more than 7 charecters next time') print(string[1:-1]) print(string.upper()) print(string.replace('a', 'e')) print('*' * le...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- s1 = set([1, 1, 2, 2, 3, 3]) print("s1 = ", s1) s2 = set([2, 3, 4]) print("s2 = ", s2) print("s1 & s2 = ", s1 & s2) print("s1 | s2 = ", s1 | s2)
s1 = set([1, 1, 2, 2, 3, 3]) print('s1 = ', s1) s2 = set([2, 3, 4]) print('s2 = ', s2) print('s1 & s2 = ', s1 & s2) print('s1 | s2 = ', s1 | s2)