content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# https://app.codesignal.com/arcade/intro/level-1/jwr339Kq6e3LQTsfa # Write a function that returns the sum of two numbers. def add(param1: int = 0, param2: int = 0) -> int: if ( isinstance(param1, int) and isinstance(param2, int) and -1000 <= param1 <= 1000 and -1000 <= param2 <= ...
def add(param1: int=0, param2: int=0) -> int: if isinstance(param1, int) and isinstance(param2, int) and (-1000 <= param1 <= 1000) and (-1000 <= param2 <= 1000): return param1 + param2 return 0
n=int(input()) cus=[int(input()) for i in range(n)] m=int(input()) price=[int(input()) for i in range(m)] price.sort(reverse=True) cus.sort(reverse=True) answer=0 C,P=0,0 while C<n and P<m: if cus[C]>=price[P]: answer+=price[P] C+=1 P+=1 else: P+=1 print(answer)
n = int(input()) cus = [int(input()) for i in range(n)] m = int(input()) price = [int(input()) for i in range(m)] price.sort(reverse=True) cus.sort(reverse=True) answer = 0 (c, p) = (0, 0) while C < n and P < m: if cus[C] >= price[P]: answer += price[P] c += 1 p += 1 else: p += 1...
# https://adventofcode.com/2021/day/17#part2 def solve(target): (x1, x2), (y1, y2) = target count = 0 for i in range(-1000, 1000): # wew, try bruteforce for j in range(1, x2+1): hit = check(j, i, target) if hit: count += 1 return count def check(a, b, target): (x1, x2), (y1, y2)...
def solve(target): ((x1, x2), (y1, y2)) = target count = 0 for i in range(-1000, 1000): for j in range(1, x2 + 1): hit = check(j, i, target) if hit: count += 1 return count def check(a, b, target): ((x1, x2), (y1, y2)) = target (x, y) = (0, 0) ...
vegetables = [ { "type":"fruit", "items":[ { "color":"green", "items":[ "kiwi", "grape" ] }, { "color":"red", "items":[ "str...
vegetables = [{'type': 'fruit', 'items': [{'color': 'green', 'items': ['kiwi', 'grape']}, {'color': 'red', 'items': ['strawberry', 'apple']}]}, {'type': 'vegs', 'items': [{'color': 'green', 'items': ['lettuce']}, {'color': 'red', 'items': ['pepper']}]}] a = list(filter(lambda i: i['type'] == 'fruit', vegetables)) print...
__all__ = ["reservation", "user_info", "calendar"] for _import in __all__: __import__(f"{__package__}.{_import}")
__all__ = ['reservation', 'user_info', 'calendar'] for _import in __all__: __import__(f'{__package__}.{_import}')
# Generated by h2py from Include\scintilla.h # Included from BaseTsd.h def HandleToUlong(h): return HandleToULong(h) def UlongToHandle(ul): return ULongToHandle(ul) def UlongToPtr(ul): return ULongToPtr(ul) def UintToPtr(ui): return UIntToPtr(ui) INVALID_POSITION = -1 SCI_START = 2000 SCI_OPTIONAL_STA...
def handle_to_ulong(h): return handle_to_u_long(h) def ulong_to_handle(ul): return u_long_to_handle(ul) def ulong_to_ptr(ul): return u_long_to_ptr(ul) def uint_to_ptr(ui): return u_int_to_ptr(ui) invalid_position = -1 sci_start = 2000 sci_optional_start = 3000 sci_lexer_start = 4000 sci_addtext = 200...
# # @lc app=leetcode id=970 lang=python3 # # [970] Powerful Integers # # @lc code=start class Solution(object): def powerfulIntegers(self, x, y, bound): """ :type x: int :type y: int :type bound: int :rtype: List[int] """ r = [] if bound < 2: ...
class Solution(object): def powerful_integers(self, x, y, bound): """ :type x: int :type y: int :type bound: int :rtype: List[int] """ r = [] if bound < 2: return r else: i = 0 while x ** i + y ** 0 <= bound...
class Environment(): """ This is used as an input to contruct the graph. """ def __init__(self, names, matrix, alpha, prop): self.names = names # Names of Subclone Colony (List) self.relations = matrix # Adj Matrix representing relations self.alpha = alpha self.pro...
class Environment: """ This is used as an input to contruct the graph. """ def __init__(self, names, matrix, alpha, prop): self.names = names self.relations = matrix self.alpha = alpha self.prop = prop def log(self): print('Logging Environment:') ...
"""Toyota Connected Services API exceptions.""" class ToyotaLocaleNotValid(Exception): """Raise if locale string is not valid.""" class ToyotaLoginError(Exception): """Raise if a login error happens.""" class ToyotaInvalidToken(Exception): """Raise if token is invalid""" class ToyotaI...
"""Toyota Connected Services API exceptions.""" class Toyotalocalenotvalid(Exception): """Raise if locale string is not valid.""" class Toyotaloginerror(Exception): """Raise if a login error happens.""" class Toyotainvalidtoken(Exception): """Raise if token is invalid""" class Toyotainvalidusername(Exce...
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/1296/A def odd(a,n): odd1 = a[0]%2 if odd1==1 and n%2==1: return 'YES' for i in range(1,n): if a[i]%2 != odd1: return 'YES' return 'NO' t = int(input()) for _ in range(t): n = int(input()) al = l...
def odd(a, n): odd1 = a[0] % 2 if odd1 == 1 and n % 2 == 1: return 'YES' for i in range(1, n): if a[i] % 2 != odd1: return 'YES' return 'NO' t = int(input()) for _ in range(t): n = int(input()) al = list(map(int, input().split())) print(odd(al, n))
def play_game(turns, start, nodes, max_cup_label): current_cup = start_label move = 0 while move < turns: # Snip out a sub graph of length 3 sub_graph_start = nodes[current_cup] pickup = [] cur = sub_graph_start for _ in range(3): pickup.append(cur) ...
def play_game(turns, start, nodes, max_cup_label): current_cup = start_label move = 0 while move < turns: sub_graph_start = nodes[current_cup] pickup = [] cur = sub_graph_start for _ in range(3): pickup.append(cur) cur = nodes[cur] dest_cup = c...
listTotal = [] listPar = [] listImpar = [] for c in range(1, 21): n = int(input("Digite um numero: ")) if n % 2 == 0: listTotal.append(n) listPar.append(n) else: listImpar.append(n) listTotal.append(n) print(f'{listTotal}\n{listPar}\n{listImpar}')
list_total = [] list_par = [] list_impar = [] for c in range(1, 21): n = int(input('Digite um numero: ')) if n % 2 == 0: listTotal.append(n) listPar.append(n) else: listImpar.append(n) listTotal.append(n) print(f'{listTotal}\n{listPar}\n{listImpar}')
# Copyright (c) 2018 Huawei Technologies Co., Ltd. # 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 # # ...
class Sdkexception(Exception): def __init__(self, code=None, message=None): self._code = code self._message = message def __str__(self): return '[SDKException] Message:%s Code:%s .' % (self.message, self.code) @property def code(self): return self._code @property ...
# Definition for singly-linked list with a random pointer. # class RandomListNode(object): # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rt...
class Solution(object): def copy_random_list(self, head): """ :type head: RandomListNode :rtype: RandomListNode """ if head is None: return None current = head while current is not None: node = random_list_node(current.label) ...
class A: def f1(self): print("F1 is working") def f2(self): print("F2 is working") class B(): def f3(self): print("F3 is working") def f4(self): print("F4 is working") class C(A,B): #Multiple Inheriatance def f5(self): print("F5 is working") a1=A() a1....
class A: def f1(self): print('F1 is working') def f2(self): print('F2 is working') class B: def f3(self): print('F3 is working') def f4(self): print('F4 is working') class C(A, B): def f5(self): print('F5 is working') a1 = a() a1.f1() a1.f2() b1 = b() b...
# Input Cases t = int(input("\nTotal Test Cases : ")) for i in range(1,t+1): print(f"\n------------ CASE #{i} -------------") n = int(input("\nTotal Items : ")) m = int(input("Max Capacity : ")) v = [int(i) for i in input("\nValues : ").split(" ")] w = [int(i) for i in input("Weights : ").split(" ")] # Ta...
t = int(input('\nTotal Test Cases : ')) for i in range(1, t + 1): print(f'\n------------ CASE #{i} -------------') n = int(input('\nTotal Items : ')) m = int(input('Max Capacity : ')) v = [int(i) for i in input('\nValues : ').split(' ')] w = [int(i) for i in input('Weights : ').split(' ')] d...
# https://www.hackerrank.com/challenges/candies/problem n = int(input()) arr = [int(input()) for _ in range(n)] candies = [1] * n for i in range(1, n): if arr[i - 1] < arr[i]: candies[i] = candies[i - 1] + 1 for i in range(n - 2, -1, -1): if arr[i + 1] < arr[i]: if i - 1 >= 0 and arr[i - 1] <...
n = int(input()) arr = [int(input()) for _ in range(n)] candies = [1] * n for i in range(1, n): if arr[i - 1] < arr[i]: candies[i] = candies[i - 1] + 1 for i in range(n - 2, -1, -1): if arr[i + 1] < arr[i]: if i - 1 >= 0 and arr[i - 1] < arr[i]: candies[i] = max(candies[i + 1], candi...
"""A simple example for how to replace the provided artifact macro""" load("@mabel//rules/maven_deps:mabel.bzl", "artifact") def g_artifact(coordinate): return artifact(coordinate = coordinate, repositories = ["https://maven.google.com/"], type = "naive")
"""A simple example for how to replace the provided artifact macro""" load('@mabel//rules/maven_deps:mabel.bzl', 'artifact') def g_artifact(coordinate): return artifact(coordinate=coordinate, repositories=['https://maven.google.com/'], type='naive')
class DataFragment(object): def length(self): return 0; class ConstDataFragment(object): def __init__(self, name, data): self.data = data self.name = name def length(self): return len(self.data) class ChoiceDataFragment(object): def __init__(self): pass ...
class Datafragment(object): def length(self): return 0 class Constdatafragment(object): def __init__(self, name, data): self.data = data self.name = name def length(self): return len(self.data) class Choicedatafragment(object): def __init__(self): pass clas...
""" There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given the maze, the bal...
""" There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given the maze, the bal...
class HttpStyleUriParser(UriParser): """ A customizable parser based on the HTTP scheme. HttpStyleUriParser() """
class Httpstyleuriparser(UriParser): """ A customizable parser based on the HTTP scheme. HttpStyleUriParser() """
# -*- coding: utf-8 -*- """ Created on Mon Feb 5 19:13:44 2018 @author: farhan """ def draw(n): if n == 1: print(''' ------ | | | | ------ ''') if n ==2: print(''' ...
""" Created on Mon Feb 5 19:13:44 2018 @author: farhan """ def draw(n): if n == 1: print(' \n ------\n | |\n | |\n ------\n ') if n == 2: print(' \n ------\n | |\n ...
class SecretsManager: _boto3 = None _environment = None _secrets_manager = None def __init__(self, boto3, environment): self._boto3 = boto3 self._environment = environment if not self._environment.get('AWS_REGION', True): raise ValueError("To use secrets manager you ...
class Secretsmanager: _boto3 = None _environment = None _secrets_manager = None def __init__(self, boto3, environment): self._boto3 = boto3 self._environment = environment if not self._environment.get('AWS_REGION', True): raise value_error("To use secrets manager you...
''' Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, dig...
""" Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, dig...
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_Pbr_01_ape.py" OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_lmPbr_SO/cat" DATASETS = dict(TRAIN=("lm_pbr_cat_train",), TEST=("lm_real_cat_test",)) # bbnc10 # objects cat Avg(1) # ad_2 21.06 21.06 #...
_base_ = './FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_Pbr_01_ape.py' output_dir = 'output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_lmPbr_SO/cat' datasets = dict(TRAIN=('lm_pbr_cat_train',), TEST=('lm_real_cat_test',))
# -*- coding: utf-8 -*- # index.urls def make_rules(): return [] all_views = {}
def make_rules(): return [] all_views = {}
data = input() forum_dict = {} while not data == 'filter': topic = data.split(' -> ')[0] hashtags = data.split(' -> ')[1].split(', ') if topic in forum_dict.keys(): forum_dict[topic].extend(hashtags) else: forum_dict[topic] = hashtags data = input() hashtags_reg = input().split(', ...
data = input() forum_dict = {} while not data == 'filter': topic = data.split(' -> ')[0] hashtags = data.split(' -> ')[1].split(', ') if topic in forum_dict.keys(): forum_dict[topic].extend(hashtags) else: forum_dict[topic] = hashtags data = input() hashtags_reg = input().split(', ')...
def fector(x: int): if x == 0: return 1 else: return x * fector(x - 1) N = int(input()) print(fector(N))
def fector(x: int): if x == 0: return 1 else: return x * fector(x - 1) n = int(input()) print(fector(N))
filename=os.path.join(path,'Output','Data','xls','WALIS_spreadsheet.xlsx') print('Your file will be created in {} '.format(path+'/Output/Data/')) ###### Prepare messages for the readme ###### # First cell date_string = date.strftime("%d %m %Y") msg1='This file was exported from WALIS on '+date_string # Second cell msg...
filename = os.path.join(path, 'Output', 'Data', 'xls', 'WALIS_spreadsheet.xlsx') print('Your file will be created in {} '.format(path + '/Output/Data/')) date_string = date.strftime('%d %m %Y') msg1 = 'This file was exported from WALIS on ' + date_string msg2 = 'The data in this file were compiled in WALIS, the World A...
board_bounding_box = [[[-1245, -795], [-410, 310], [-455, 500.0]],\ [[-1245, -795], [-410, 310], [-545, 500.0]],\ [[-1245, -595], [-410, 310], [-585, 500.0]],\ [[-1345, -595], [-410, 310], [-642, 500.0]]] min_point_before_moving = [[-1245, -354.048022, -417],\ [-1201.1969772, -300...
board_bounding_box = [[[-1245, -795], [-410, 310], [-455, 500.0]], [[-1245, -795], [-410, 310], [-545, 500.0]], [[-1245, -595], [-410, 310], [-585, 500.0]], [[-1345, -595], [-410, 310], [-642, 500.0]]] min_point_before_moving = [[-1245, -354.048022, -417], [-1201.1969772, -300, -539], [-1155, -248.09308728, -570], [-11...
"""Semantic versioning for the package qtools3.""" VERSION = (0, 3, 6) __version__ = '.'.join(map(str, VERSION))
"""Semantic versioning for the package qtools3.""" version = (0, 3, 6) __version__ = '.'.join(map(str, VERSION))
class Door: status = 'undefined' def __init__(self, number, status, lock): self.number = number self.status = status self.lock = lock def open(self): """Door opened""" if self.lock == 'unlocked': self.status = 'opened' def close(self): """Do...
class Door: status = 'undefined' def __init__(self, number, status, lock): self.number = number self.status = status self.lock = lock def open(self): """Door opened""" if self.lock == 'unlocked': self.status = 'opened' def close(self): """Do...
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/icefire/ws/src/gscam/include;/usr/include/gstreamer-1.0;/usr/include/glib-2.0;/usr/lib/aarch64-linux-gnu/glib-2.0/include".split(';') if "/home/icefire/ws/src/gscam/include;/usr/include/gstreamer...
catkin_package_prefix = '' project_pkg_config_include_dirs = '/home/icefire/ws/src/gscam/include;/usr/include/gstreamer-1.0;/usr/include/glib-2.0;/usr/lib/aarch64-linux-gnu/glib-2.0/include'.split(';') if '/home/icefire/ws/src/gscam/include;/usr/include/gstreamer-1.0;/usr/include/glib-2.0;/usr/lib/aarch64-linux-gnu/gli...
_NORMALIZING_FLOWS = {} class RegisterFlow(object): """Decorator to registor NormalizingFlow classes. Parameters ---------- flow_cls_name : str name of the NormalizingFlow class. This will be used in the `get_flow` method as the key for the class. Usage ----- >>> @flow_li...
_normalizing_flows = {} class Registerflow(object): """Decorator to registor NormalizingFlow classes. Parameters ---------- flow_cls_name : str name of the NormalizingFlow class. This will be used in the `get_flow` method as the key for the class. Usage ----- >>> @flow_lib...
n = int(input()) ans = (n * (n + 1)) // 2 ans = 4 * ans ans = ans - 4 * n ans = 1 + ans print(ans)
n = int(input()) ans = n * (n + 1) // 2 ans = 4 * ans ans = ans - 4 * n ans = 1 + ans print(ans)
# ------------------------------ # 486. Predict the Winner # # Description: # Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be availabl...
class Solution: def predict_the_winner(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) == 1: return True dp = [[-1 for _ in range(len(nums))] for _ in range(len(nums))] curr_sum = sum(nums) player1 = self.helper(nums, ...
def power_supply(network: list[list], plant: dict, lis=None) -> set: if not lis: lis = [] net = network.copy() for key, value in plant.items(): for [a, b] in tuple(net): if key in [a, b]: net.remove([a, b]) if value > 0: lis.append(a if...
def power_supply(network: list[list], plant: dict, lis=None) -> set: if not lis: lis = [] net = network.copy() for (key, value) in plant.items(): for [a, b] in tuple(net): if key in [a, b]: net.remove([a, b]) if value > 0: lis.a...
class Contact: all_contacts = [] def __init__(self, name, email): self.name = name self.email = email Contact.all_contacts.append(self) class Supplier(Contact): def order(self, order): print("if this were a real system we would send " f"{order} order to {self.name}")
class Contact: all_contacts = [] def __init__(self, name, email): self.name = name self.email = email Contact.all_contacts.append(self) class Supplier(Contact): def order(self, order): print(f'if this were a real system we would send {order} order to {self.name}')
''' Created on Oct 22, 2018 @author: casey ''' class Segment(object): # # * Segments make up the tree. There is a base segment, then a root segment, then the tree expands into internal segments, until it gets to leaf segments. # * These segment types make it easier to traverse the tree during b...
""" Created on Oct 22, 2018 @author: casey """ class Segment(object): def __init__(self, l=0): self.left = l self.right = -1 self.link = None def set_link(self, link): self.link = link def get_link(self): return self.link def get_left(self): return s...
class SingleLinkedNode: def __init__(self, datum): """Node in a single linked list :param datum: the datum associated with this node """ self.next_node = None self.datum = datum def __str__(self): return "datum={}; next={}".format( self.datum, ...
class Singlelinkednode: def __init__(self, datum): """Node in a single linked list :param datum: the datum associated with this node """ self.next_node = None self.datum = datum def __str__(self): return 'datum={}; next={}'.format(self.datum, 'None' if self.nex...
num = int(input("enter the number")) for i in range(2,num): if num%i==0: print("not prime") break else: print("prime")
num = int(input('enter the number')) for i in range(2, num): if num % i == 0: print('not prime') break else: print('prime')
class TicTacToe: def __init__(self): self.tab = ['.','.','.','.','.','.','.','.','.','.'] def curr_state(self): #obecny stan tablicy return ''.join(self.tab) def postaw_znak_o(self, x, y): #interfejs dla stawiania znaku przez gracza if x < 0 or x > 2 or y < 0 or y > 2 or...
class Tictactoe: def __init__(self): self.tab = ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'] def curr_state(self): return ''.join(self.tab) def postaw_znak_o(self, x, y): if x < 0 or x > 2 or y < 0 or (y > 2) or (self.tab[x + y * 3] != '.'): return 1 self...
ERR_EXCEED_LIMIT = "Not enough space" class NotEnoughSpace(Exception): pass
err_exceed_limit = 'Not enough space' class Notenoughspace(Exception): pass
class SeriesField(object): def __init__(self): self.series = [] def add_serie(self, serie): self.series.append(serie) def to_javascript(self): jsc = "series: [" for s in self.series: jsc += s.to_javascript() + "," # the last comma is accepted by javascript...
class Seriesfield(object): def __init__(self): self.series = [] def add_serie(self, serie): self.series.append(serie) def to_javascript(self): jsc = 'series: [' for s in self.series: jsc += s.to_javascript() + ',' jsc += ']' return jsc
self.description = "conflict 'db vs db'" sp1 = pmpkg("pkg1", "1.0-2") sp1.conflicts = ["pkg2"] self.addpkg2db("sync", sp1); sp2 = pmpkg("pkg2", "1.0-2") self.addpkg2db("sync", sp2) lp1 = pmpkg("pkg1") self.addpkg2db("local", lp1) lp2 = pmpkg("pkg2") self.addpkg2db("local", lp2) self.args = "-S %s --ask=4" % " ".jo...
self.description = "conflict 'db vs db'" sp1 = pmpkg('pkg1', '1.0-2') sp1.conflicts = ['pkg2'] self.addpkg2db('sync', sp1) sp2 = pmpkg('pkg2', '1.0-2') self.addpkg2db('sync', sp2) lp1 = pmpkg('pkg1') self.addpkg2db('local', lp1) lp2 = pmpkg('pkg2') self.addpkg2db('local', lp2) self.args = '-S %s --ask=4' % ' '.join([p....
# To check a number is prime or not num = int(input("Enter a number: ")) check = 0 if(num>=0): for i in range(1,num+1): if( (num % i) == 0 ): check=check+1 if(check==2): print(num,"is a prime number.") else: ...
num = int(input('Enter a number: ')) check = 0 if num >= 0: for i in range(1, num + 1): if num % i == 0: check = check + 1 if check == 2: print(num, 'is a prime number.') else: print(num, 'is not a prime number.') else: print('========Please Enter a positive number===...
def func1(): pass def func2(): pass a = b = func1 b() a = b = func2 a()
def func1(): pass def func2(): pass a = b = func1 b() a = b = func2 a()
n=int(input());f=True if n!=3: f=False a=set() for _ in range(n): b,c=map(int,input().split()) a.add(b);a.add(c) if a!={1,3,4}: f=False print((f) and 'Wa-pa-pa-pa-pa-pa-pow!' or 'Woof-meow-tweet-squeek')
n = int(input()) f = True if n != 3: f = False a = set() for _ in range(n): (b, c) = map(int, input().split()) a.add(b) a.add(c) if a != {1, 3, 4}: f = False print(f and 'Wa-pa-pa-pa-pa-pa-pow!' or 'Woof-meow-tweet-squeek')
numeros = [] for i in range(1, 1000001): numeros.append(i) for numero in numeros: print(numero)
numeros = [] for i in range(1, 1000001): numeros.append(i) for numero in numeros: print(numero)
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to demonstrate recursion # A recursive function to add up the first n numbers. # Example: The sum of the first 5 numbers is 5 + the sum of the first 4 numbers # S...
def sum_of_n(n): if n == 0: return 0 return n + sum_of_n(n - 1) answer = sum_of_n(5) print(answer)
# Problem: https://docs.google.com/document/d/1Sz1cWKsiQzQUOjC76TzFcOQGYEZIPvQuWg6NjQ0B6VA/edit?usp=sharing def print_roman(number): dict = {1:"I", 4:"IV", 5:"V", 9:"IX", 10:"X", 40:"XL", 50:"L", 90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"} for i in sorted(dict, reverse = True): ...
def print_roman(number): dict = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'} for i in sorted(dict, reverse=True): result = number // i number %= i while result: print(dict[i], end='') ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, p, d=0): if p is None: return 0 d = d + 1 d_left = self.maxDepth(p.left, d) d_right...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def max_depth(self, p, d=0): if p is None: return 0 d = d + 1 d_left = self.maxDepth(p.left, d) d_right = self.maxDepth(p.right, d) ...
# why does this expression cause problems and what is the fix # helen o'shea # 20210203 try: message = 'I have eaten ' + 99 +' burritos.' except: message = 'I have eaten ' + str(99) +' burritos.' print(message)
try: message = 'I have eaten ' + 99 + ' burritos.' except: message = 'I have eaten ' + str(99) + ' burritos.' print(message)
seconds = 365 * 24 * 60 * 60 for year in [1, 2, 5, 10]: print(seconds * year)
seconds = 365 * 24 * 60 * 60 for year in [1, 2, 5, 10]: print(seconds * year)
""" my_rectangle = { # Coordinates of bottom-left corner 'left_x' : 1, 'bottom_y' : 1, # Width and height 'width' : 6, 'height' : 3, } """ def find_overlap(point1, length1, point2, length2): # get the highest_start_point as the max of point1 and point2 highest_start_point = m...
""" my_rectangle = { # Coordinates of bottom-left corner 'left_x' : 1, 'bottom_y' : 1, # Width and height 'width' : 6, 'height' : 3, } """ def find_overlap(point1, length1, point2, length2): highest_start_point = max(point1, point2) lowest_end_point = min(point1 + length1, poi...
# ------------------------- DESAFIO 005 ------------------------- # Programa para mostrar na tela o sucessor e antecessor de um numero digitado num = int(input('Digite um Numero: ')) suc = num + 1 ant = num - 1 print('Abaixo seguem os numeros conforme na ordem: \n Antecessor / Numedo Digitado / Sucessor \n {:^10} / ...
num = int(input('Digite um Numero: ')) suc = num + 1 ant = num - 1 print('Abaixo seguem os numeros conforme na ordem: \n Antecessor / Numedo Digitado / Sucessor \n {:^10} / {:^15} / {:^8}'.format(ant, num, suc))
# -*- coding: utf-8 -*- """ REFUSE Simple cross-plattform ctypes bindings for libfuse / FUSE for macOS / WinFsp https://github.com/pleiszenburg/refuse src/refuse/__init__.py: Package root Copyright (C) 2008-2020 refuse contributors <LICENSE_BLOCK> The contents of this file are subject to the Internet Syste...
""" REFUSE Simple cross-plattform ctypes bindings for libfuse / FUSE for macOS / WinFsp https://github.com/pleiszenburg/refuse src/refuse/__init__.py: Package root Copyright (C) 2008-2020 refuse contributors <LICENSE_BLOCK> The contents of this file are subject to the Internet Systems Consortium (ISC) licen...
# COUNT BY # This function takes two arguments: # A list with items to be counted # The function the list will be mapped to # This function uses the properties inherent in objects # to create a new property for each unique value, then # increase the count of that property each time that # element appears in ...
def count_by(arr, fn=lambda x: x): key = {} for el in map(fn, arr): key[el] = 0 if el not in key else key[el] key[el] += 1 return key print(count_by(['one', 'two', 'three'], len))
N, A, B = map(int, input().split()) if (B - A) % 2 == 0: print('Alice') else: print('Borys')
(n, a, b) = map(int, input().split()) if (B - A) % 2 == 0: print('Alice') else: print('Borys')
""" RabbitMQ concepts """ def Graphic_shape(): return "none" def Graphic_colorfill(): return "#FFCC66" def Graphic_colorbg(): return "#FFCC66" def Graphic_border(): return 2 def Graphic_is_rounded(): return True # managementUrl = rabbitmq.ManagementUrlPrefix(configNam) # managementUrl = ...
""" RabbitMQ concepts """ def graphic_shape(): return 'none' def graphic_colorfill(): return '#FFCC66' def graphic_colorbg(): return '#FFCC66' def graphic_border(): return 2 def graphic_is_rounded(): return True def management_url_prefix(config_nam, key='vhosts', name_key1='', name_key2=''): ...
# # PySNMP MIB module HPN-ICF-ISSU-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-ISSU-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:39:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) ...
def factorial(n): total = 1 for i in range(1, n+1): total *= i return total if __name__ == '__main__': f = factorial(10) print(f)
def factorial(n): total = 1 for i in range(1, n + 1): total *= i return total if __name__ == '__main__': f = factorial(10) print(f)
# encoding=utf-8 class LazyDB(object): def __init__(self): self.exists = 5 def __getattr__(self, name): value = 'Value for %s' %name setattr(self,name,value) return value data = LazyDB() print('Before',data.__dict__) print('foo',data.foo) print('After',data.__dict__) class LogginglazyDB(LazyDB): def __g...
class Lazydb(object): def __init__(self): self.exists = 5 def __getattr__(self, name): value = 'Value for %s' % name setattr(self, name, value) return value data = lazy_db() print('Before', data.__dict__) print('foo', data.foo) print('After', data.__dict__) class Logginglazydb...
""" A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: - If a word begins with a ...
""" A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: - If a word begins with a ...
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2012 California Institute of Technology. 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 th...
"""Some specialized arithmetic exceptions for Vector and Affine Spaces. """ class Geometricexception(ArithmeticError): """A base class- not to be raised""" pass class Noncovariantoperation(GeometricException): """Raise when you do something that is silly[1], like adding a Scalar to a Vector\\. [1]...
class Solution: def singleNonDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ c=0 for num in nums: c=c^num return c
class Solution: def single_non_duplicate(self, nums): """ :type nums: List[int] :rtype: int """ c = 0 for num in nums: c = c ^ num return c
# -*- coding: utf-8 -*- """ Created on Fri Dec 20 23:18:03 2019 @author: NOTEBOOK """ def main(): speed = int(input('What is the speed of the vehicle in mph? ')) hours = int(input('How many hours has it traveled? ')) print('Hour\t\tDistance traveled(Miles)') print('------------------------------------...
""" Created on Fri Dec 20 23:18:03 2019 @author: NOTEBOOK """ def main(): speed = int(input('What is the speed of the vehicle in mph? ')) hours = int(input('How many hours has it traveled? ')) print('Hour\t\tDistance traveled(Miles)') print('-------------------------------------') for num in range...
class Params(object): """ Params object """ def __init__(self): self._params = set() self._undefined_params = set() @property def params(self) -> set: return self._params @property def defined_params(self) -> set: return self._params ^ self._undefined_params ...
class Params(object): """ Params object """ def __init__(self): self._params = set() self._undefined_params = set() @property def params(self) -> set: return self._params @property def defined_params(self) -> set: return self._params ^ self._undefined_params ...
winClass = window.get_active_class() if winClass not in ("code.Code", "emacs.Emacs"): # Regular window keyboard.send_keys('<home>') keyboard.send_keys('<shift>+<end>') else: # VS Code keyboard.send_keys('<ctrl>+l')
win_class = window.get_active_class() if winClass not in ('code.Code', 'emacs.Emacs'): keyboard.send_keys('<home>') keyboard.send_keys('<shift>+<end>') else: keyboard.send_keys('<ctrl>+l')
#! /usr/bin/env python ############################################################################### # esp8266_MicroPy_main_boilerplate.py # # base main.py boilerplate code for MicroPython running on the esp8266 # Copy relevant parts and/or file with desired settings into main.py on the esp8266 # # The main.py file...
while True: time.sleep(1) pin.value(not pin.value()) time.sleep(1)
class Angel: color = "white" feature = "wings" home = "Heaven" class Demon: color = "red" feature = "horns" home = "Hell" my_angel = Angel() print(my_angel.color) print(my_angel.feature) print(my_angel.home) my_demon = Demon() print(my_demon.color) print(my_demon.feature) print(my_demon.home...
class Angel: color = 'white' feature = 'wings' home = 'Heaven' class Demon: color = 'red' feature = 'horns' home = 'Hell' my_angel = angel() print(my_angel.color) print(my_angel.feature) print(my_angel.home) my_demon = demon() print(my_demon.color) print(my_demon.feature) print(my_demon.home)
# uninhm # https://codeforces.com/contest/1419/problem/A # greedy def hasmodulo(s, a): for i in s: if int(i) % 2 == a: return True return False for _ in range(int(input())): n = int(input()) s = input() if n % 2 == 0: if hasmodulo(s[1::2], 0): print(2) ...
def hasmodulo(s, a): for i in s: if int(i) % 2 == a: return True return False for _ in range(int(input())): n = int(input()) s = input() if n % 2 == 0: if hasmodulo(s[1::2], 0): print(2) else: print(1) elif hasmodulo(s[0::2], 1): ...
agent = dict( type='TD3_BC', batch_size=256, gamma=0.95, update_coeff=0.005, policy_update_interval=2, alpha=2.5, ) log_level = 'INFO' eval_cfg = dict( type='Evaluation', num=10, num_procs=1, use_hidden_state=False, start_state=None, save_traj=True, save_video=True,...
agent = dict(type='TD3_BC', batch_size=256, gamma=0.95, update_coeff=0.005, policy_update_interval=2, alpha=2.5) log_level = 'INFO' eval_cfg = dict(type='Evaluation', num=10, num_procs=1, use_hidden_state=False, start_state=None, save_traj=True, save_video=True, use_log=False) train_mfrl_cfg = dict(on_policy=False)
# https://codeforces.com/contest/1270/problem/B # https://codeforces.com/contest/1270/submission/68220722 # https://github.com/miloszlakomy/competitive/tree/master/codeforces/1270B def solve(A): for cand in range(len(A)-1): if abs(A[cand] - A[cand+1]) >= 2: return cand, cand+2 return None ...
def solve(A): for cand in range(len(A) - 1): if abs(A[cand] - A[cand + 1]) >= 2: return (cand, cand + 2) return None t = int(input()) for _ in range(t): _ = input() a = [int(x) for x in input().split()] ans = solve(A) if ans is None: print('NO') else: prin...
class CustomConstant(object): """ Simple class for custom constants such as NULL, NOT_FOUND, etc. Each object is obviously unique, so it is simple to do an equality check. Each object can be configured with string, int, float, and boolean values, as well as attributes. """ def __ini...
class Customconstant(object): """ Simple class for custom constants such as NULL, NOT_FOUND, etc. Each object is obviously unique, so it is simple to do an equality check. Each object can be configured with string, int, float, and boolean values, as well as attributes. """ def __init__(self...
def identity(x): return x def with_max_length(max_length): return lambda x: x[:max_length] if x else x def identity_or_none(x): return None if not x else x def tipo_de_pessoa(x): return "J" if x == "PJ" else "F" def cnpj(x, tipo_pessoa): return x if tipo_pessoa == "PJ" else None def cpf(x,...
def identity(x): return x def with_max_length(max_length): return lambda x: x[:max_length] if x else x def identity_or_none(x): return None if not x else x def tipo_de_pessoa(x): return 'J' if x == 'PJ' else 'F' def cnpj(x, tipo_pessoa): return x if tipo_pessoa == 'PJ' else None def cpf(x, tipo...
a = 1 b = 2 c = 3 tmp=a a=b b=tmp tmp=c c=b b=tmp
a = 1 b = 2 c = 3 tmp = a a = b b = tmp tmp = c c = b b = tmp
expected_output = { "cdp": { "index": { 1: { "capability": "R S C", "device_id": "Device_With_A_Particularly_Long_Name", "hold_time": 134, "local_interface": "GigabitEthernet1", "platform": "N9K-9000v", ...
expected_output = {'cdp': {'index': {1: {'capability': 'R S C', 'device_id': 'Device_With_A_Particularly_Long_Name', 'hold_time': 134, 'local_interface': 'GigabitEthernet1', 'platform': 'N9K-9000v', 'port_id': 'Ethernet0/0'}, 2: {'capability': 'S I', 'device_id': 'another_device_with_a_long_name', 'hold_time': 141, 'lo...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head or not head.next: return head odd = odd_head = head even = eve...
class Solution: def odd_even_list(self, head: ListNode) -> ListNode: if not head or not head.next: return head odd = odd_head = head even = even_head = head.next while even and even.next: odd.next = even.next odd = odd.next even.next =...
class Solution: def decodeString(self, s: str) -> str: stack = [] stack.append([1, ""]) num = 0 for l in s: if l.isdigit(): num = num * 10 + ord(l) - ord('0') elif l == '[': stack.append([num, ""]) num = 0 ...
class Solution: def decode_string(self, s: str) -> str: stack = [] stack.append([1, '']) num = 0 for l in s: if l.isdigit(): num = num * 10 + ord(l) - ord('0') elif l == '[': stack.append([num, '']) num = 0 ...
# Time: O(n) # Space: O(1) class Solution(object): def countGoodRectangles(self, rectangles): """ :type rectangles: List[List[int]] :rtype: int """ result = mx = 0 for l, w in rectangles: side = min(l, w) if side > mx: result,...
class Solution(object): def count_good_rectangles(self, rectangles): """ :type rectangles: List[List[int]] :rtype: int """ result = mx = 0 for (l, w) in rectangles: side = min(l, w) if side > mx: (result, mx) = (1, side) ...
pizzas = ['Supreme', 'Stuffed Crust', 'Buffalo Chicken'] friendpizzas = pizzas[:] pizzas.append("Eggs Benedict Pizza") friendpizzas.append("Eggs Florentine Pizza") print("My favorite pizzas are:") print(pizzas) print("My friend's favorite pizzas are:") print(friendpizzas)
pizzas = ['Supreme', 'Stuffed Crust', 'Buffalo Chicken'] friendpizzas = pizzas[:] pizzas.append('Eggs Benedict Pizza') friendpizzas.append('Eggs Florentine Pizza') print('My favorite pizzas are:') print(pizzas) print("My friend's favorite pizzas are:") print(friendpizzas)
# In a 2D grid from (0, 0) to (N-1, N-1), every cell contains a 1, except those cells in the given list mines which are 0. What is the largest axis-aligned plus sign of 1s contained in the grid? Return the order of the plus sign. If there is none, return 0. # # An "axis-aligned plus sign of 1s of order k" has some cent...
class Solution(object): def order_of_largest_plus_sign(self, N, mines): """ :type N: int :type mines: List[List[int]] :rtype: int """ dp = [[1] * N for _ in range(N)] for [x, y] in mines: dp[x][y] = 0
# EDA: Airplanes - Q3 def plot_airplane_type_over_europe(gdf, airplane="B17", years=[1940, 1941 ,1942, 1943, 1944, 1945], kdp=False, aoi=europe): fig = plt.figure(figsize=(16,12)) for e, y in enumerate(years): _gdf = gdf.loc[(gdf["...
def plot_airplane_type_over_europe(gdf, airplane='B17', years=[1940, 1941, 1942, 1943, 1944, 1945], kdp=False, aoi=europe): fig = plt.figure(figsize=(16, 12)) for (e, y) in enumerate(years): _gdf = gdf.loc[(gdf['year'] == y) & (gdf['Aircraft Series'] == airplane)].copy() _gdf.Country.replace(np....
class BaseRelationship: def __init__(self, name, repository, model, paginated_menu=None): self.name = name self.repository = repository self.model = model self.paginated_menu = paginated_menu class OneToManyRelationship(BaseRelationship): def __init__(self, related_name, name, ...
class Baserelationship: def __init__(self, name, repository, model, paginated_menu=None): self.name = name self.repository = repository self.model = model self.paginated_menu = paginated_menu class Onetomanyrelationship(BaseRelationship): def __init__(self, related_name, name,...
#! /usr/bin/env python3 def next_permutation(seq): k = len(seq) - 1 # Find the largest index k such that a[k] < a[k + 1]. while k >= 0: if seq[k - 1] >= seq[k]: k -= 1 else: k -= 1 break # No such index exists, the permutation is the last permutati...
def next_permutation(seq): k = len(seq) - 1 while k >= 0: if seq[k - 1] >= seq[k]: k -= 1 else: k -= 1 break if k == -1: raise stop_iteration('Reached final permutation.') l = len(seq) - 1 while l >= k: if seq[l] > seq[k]: ...
#!/usr/bin/env python3 """RZFeeser | Alta3 Research nesting an if-statement inside of a for loop""" farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]}, {"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]}, {"name": "SE Farm", "agricult...
"""RZFeeser | Alta3 Research nesting an if-statement inside of a for loop""" farms = [{'name': 'NE Farm', 'agriculture': ['sheep', 'cows', 'pigs', 'chickens', 'llamas', 'cats']}, {'name': 'W Farm', 'agriculture': ['pigs', 'chickens', 'llamas']}, {'name': 'SE Farm', 'agriculture': ['chickens', 'carrots', 'celery']}] ...
""" Meijer, Erik - The Curse of the Excluded Middle DOI:10.1145/2605176 CACM vol.57 no.06 """ def less_than_30(n): check = n < 30 print('%d < 30 : %s' % (n, check)) return check def more_than_20(n): check = n > 20 print('%d > 20 : %s' % (n, check)) return check l = [1, 25, 40, 5, 23] q0 = (n ...
""" Meijer, Erik - The Curse of the Excluded Middle DOI:10.1145/2605176 CACM vol.57 no.06 """ def less_than_30(n): check = n < 30 print('%d < 30 : %s' % (n, check)) return check def more_than_20(n): check = n > 20 print('%d > 20 : %s' % (n, check)) return check l = [1, 25, 40, 5, 23] q0 = (n f...
a=25 b=5 print("division is ",(a/b)) print("division success")
a = 25 b = 5 print('division is ', a / b) print('division success')
name1 = "Atilla" name2 = "atilla" name3 = "ATILLA" name4 = "AtiLLa" ## Common string functions print("capitalize",name1.capitalize()) print("capitalize",name2.capitalize()) print("capitalize",name3.capitalize()) print("capitalize",name4.capitalize()) # ends with if name1.endswith("x"): print("name1 ends with x ch...
name1 = 'Atilla' name2 = 'atilla' name3 = 'ATILLA' name4 = 'AtiLLa' print('capitalize', name1.capitalize()) print('capitalize', name2.capitalize()) print('capitalize', name3.capitalize()) print('capitalize', name4.capitalize()) if name1.endswith('x'): print('name1 ends with x char') else: print('name1 does not ...
# --==[ Settings ]==-- # General mod = 'mod4' terminal = 'st' browser = 'firefox' file_manager = 'thunar' font = 'SauceCodePro Nerd Font Medium' wallpaper = '~/wallpapers/wp1.png' # Weather location = {'Mexico': 'Mexico'} city = 'Mexico City, MX' # Hardware [/sys/class] net = 'wlp2s0' backlight = 'radeon_bl0' # Col...
mod = 'mod4' terminal = 'st' browser = 'firefox' file_manager = 'thunar' font = 'SauceCodePro Nerd Font Medium' wallpaper = '~/wallpapers/wp1.png' location = {'Mexico': 'Mexico'} city = 'Mexico City, MX' net = 'wlp2s0' backlight = 'radeon_bl0' colorscheme = 'material_ocean'
"""678. Valid Parenthesis String https://leetcode.com/problems/valid-parenthesis-string/ """ class Solution: def check_valid_string(self, s: str) -> bool: left_stack, star_stack = [], [] for i, c in enumerate(s): if c == '(': left_stack.append(i) elif c == '...
"""678. Valid Parenthesis String https://leetcode.com/problems/valid-parenthesis-string/ """ class Solution: def check_valid_string(self, s: str) -> bool: (left_stack, star_stack) = ([], []) for (i, c) in enumerate(s): if c == '(': left_stack.append(i) elif ...
class Solution: def isValid(self, s: str) -> bool: stack = [] for i in s: if i == ')' or i == ']' or i == '}': if not stack or stack[-1] != i: return False stack.pop() else: if i == '(': s...
class Solution: def is_valid(self, s: str) -> bool: stack = [] for i in s: if i == ')' or i == ']' or i == '}': if not stack or stack[-1] != i: return False stack.pop() else: if i == '(': ...
SEARCH_PARAMS = { "Sect1": "PTO2", "Sect2": "HITOFF", "p": "1", "u": "/netahtml/PTO/search-adv.html", "r": "0", "f": "S", "l": "50", "d": "PG01", "Query": "query", } SEARCH_FIELDS = { "document_number": "DN", "publication_date": "PD", "title": "TTL", "abstract": "ABS...
search_params = {'Sect1': 'PTO2', 'Sect2': 'HITOFF', 'p': '1', 'u': '/netahtml/PTO/search-adv.html', 'r': '0', 'f': 'S', 'l': '50', 'd': 'PG01', 'Query': 'query'} search_fields = {'document_number': 'DN', 'publication_date': 'PD', 'title': 'TTL', 'abstract': 'ABST', 'claims': 'ACLM', 'specification': 'SPEC', 'current_u...
# Variable Selection Linear Model Baseline = ['price_lag_1', 'price3_lag_1', 'target_lag_1', 'target3_lag_1', 'tstd_lag_1'] Lags = ['item_id_price_lag_1', 'item_id_price3_lag_1', 'item_id_target_lag_1', 'item_id_target3_lag_1', 'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1'...
baseline = ['price_lag_1', 'price3_lag_1', 'target_lag_1', 'target3_lag_1', 'tstd_lag_1'] lags = ['item_id_price_lag_1', 'item_id_price3_lag_1', 'item_id_target_lag_1', 'item_id_target3_lag_1', 'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1', 'shop_id_price_lag_1', 'shop_id_price3_lag_1', 'shop_id_target_lag_1', 's...
path = "." # Set this to True to fully unlock all maps # Set this to False to erase all map progress useFullMaps = True def reverse_endianness_block2(block): even = block[::2] odd = block[1::2] res = [] for e, o in zip(even, odd): res += [o, e] return res # Initiate base file data = None saveFile = [0]...
path = '.' use_full_maps = True def reverse_endianness_block2(block): even = block[::2] odd = block[1::2] res = [] for (e, o) in zip(even, odd): res += [o, e] return res data = None save_file = [0] * 257678 saveFile[:4] = [66, 76, 72, 84] saveFile[103] = 1 with open(path + '/PCF01.ngd', 'rb...
# -*- coding: utf-8 -*- class Screen: def __init__(self, dim): self.arena = [] self.dimx = dim[0]+2 self.dimy = dim[1]+2 for x in range(self.dimx): self.arena.append([]) for y in range(self.dimy): if x == 0 or x == (self.dimx-1): self.arena[x].append('-') elif y == 0 or y == (self.dimy-1): ...
class Screen: def __init__(self, dim): self.arena = [] self.dimx = dim[0] + 2 self.dimy = dim[1] + 2 for x in range(self.dimx): self.arena.append([]) for y in range(self.dimy): if x == 0 or x == self.dimx - 1: self.arena[x]...
def strategy(history, memory): """ Tit-for-tat, except we punish them N times in a row if this is the Nth time they've initiated a defection. memory: (initiatedDefections, remainingPunitiveDefections) """ if memory is not None and memory[1] > 0: choice = 0 memory = (memory[0], m...
def strategy(history, memory): """ Tit-for-tat, except we punish them N times in a row if this is the Nth time they've initiated a defection. memory: (initiatedDefections, remainingPunitiveDefections) """ if memory is not None and memory[1] > 0: choice = 0 memory = (memory[0], m...
""" Simple config file """ class Config(object): DEBUG = False TESTING = False SECRET_KEY = b'' # TODO SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db' SQLALCHEMY_TRACK_MODIFICATIONS = False class Dev(Config): DEBUG = True TESTING = True SQLALCHEMY_TRACK_MODIFICATIONS = True
""" Simple config file """ class Config(object): debug = False testing = False secret_key = b'' sqlalchemy_database_uri = 'sqlite:///database.db' sqlalchemy_track_modifications = False class Dev(Config): debug = True testing = True sqlalchemy_track_modifications = True
#!/usr/bin/env python """ Github: https://github.com/Jiezhi/myleetcode Created on 2019-03-25 Leetcode: """ def func(x): return x + 1 def test_answer(): assert func(3) == 4
""" Github: https://github.com/Jiezhi/myleetcode Created on 2019-03-25 Leetcode: """ def func(x): return x + 1 def test_answer(): assert func(3) == 4