content
stringlengths
7
1.05M
# By Kamran Bigdely Nov. 2020 # Move Field (attribute) # Refactored. class Gun: def __init__(self, name): self.name = name self.num_cathridge_bullet = 0 def shoot(self): if self.num_cathridge_bullet <= 0: return False print('shoot') self.num_c...
class Solution(object): def getMaximumGold(self, grid): """ :type grid: List[List[int]] :rtype: int """ # early check if not grid or len(grid) == 0: return 0 global_max = 0 visited = [[False for j in range(len(grid[0]))] for i ...
class Solution: def numDecodings(self, s: str) -> int: values = dict() def decode(s,values): if s in values: return values[s] n = len(s) if n==0: ans = 1 values[s] = ans return ans x = int...
def get_power_set(s): """ Returns a list of all possible subsets of the given set s. """ #--------------------------------------------------------------------------- # Version 1: The input s is stored as a set. Recursive. #-------------------------------------------------------------------------...
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if (len(s)>1): temp =s[0] templ=len(temp) bestl= 1 best =s[0] i=0 for j in range(1,len(s)): ...
_temperament_names = { 'SP': ['Artisan', 'Creator'], 'SJ': ['Guardian', 'Protector'], 'NF': ['Idealist', 'Visionary'], 'NT': ['Rational', 'Intellectual'] } _personality_type_names = { 'SP': { 'ESFP': ['Performer', 'Entertainer', 'Performer'], 'ESTP': ['Promoter', 'Persuader', 'Doer'], 'ISFP': ['Composer', '...
"""https://app.codesignal.com/interview-practice/task/rMe9ypPJkXgk3MHhZ You have a collection of coins, and you know the values of the coins and the quantity of each type of coin in it. You want to know how many distinct sums you can make from non-empty groupings of these coins. Example For coins = [10, 50, 100] and...
df = WyomingUpperAir.request_data(datetime(2017, 9, 10, 0), 'KEY') p = df['pressure'].values * units(df.units['pressure']) T = df['temperature'].values * units(df.units['temperature']) Td = df['dewpoint'].values * units(df.units['dewpoint']) u = df['u_wind'].values * units(df.units['u_wind']) v = df['v_wind'].values *...
# -*-coding:utf-8 -*- # # Copyright (C) 2012-2015 Lianbi TECH Co., Ltd. All rights reserved. # Created on 2015-03-09, by $USER # # __author__ = 'Danny'
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class McrouterGlobals: @staticmethod def binPath(name): bins = { 'mcrouter': './mcrouter/mc...
n=str(input('Digite um nome: ')) if (n.upper().find('SILVA') != (-1)): print('True') else: print('False')
exam_st_date = (11, 12, 2014) day = exam_st_date[0] month = exam_st_date[1] year = exam_st_date[2] print("The examination will start from:",day, "/",month,"/",year)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 14 13:48:42 2018 @author: efrem """ def how_many(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. ''' result = 0 for list in aDict.values(): resul...
class A: def a(self): return 'b' try: object except NameError: pass else: class B(A, object): def b(self): return 'c' class Inherit(A): def a(self): return 'd'
num_1 = 10 num_2 = 10 test1= "mauricio" test2="maurici" mayor = num_1 > num_2 menor = num_1 < num_2 mayor_igual = num_1 >= num_2 menor_igual = num_1 <= num_2 igual = num_1 == num_2 # para validar que dos valores son iguales puedes utiliza == o is -> funciona con strings? si igual_is = test1 is test2 difere...
#sd.baseline = [ring_curr, gcpress, #epu1.gap, epu1.phase, #feslt.hc, feslt.vc, feslt.hg, feslt.vg, #m1.x, m1.pit, m1.rol, #pgm.cff, pgm.en, pgm.grx, pgm.m2pit, pgm.grpit, pgm.grlines, #m3slt.hs, m3slt.ha, m3slt.vs, m3slt.va, #m3diag, #m3.x, m3.y, m3.z, m3.yaw, m3.pit, m3.rol, #extslt.hg, extslt.vg, extslt.hc, #gc...
def play(): print("****************************") print("Welcome to the Hangaman Game") print("****************************") secret_word = "vitor" hanged = False hit = False while (not hanged and not hit): attempt = input("What's the letter? ") attempt = attempt.strip() ...
# encoding = utf-8 ''' 各类工具箱函数 ''' def code_to_symbols(code): """判断股票ID对应的证券市场 匹配规则 ['50', '51', '60', '90', '110'] 为 sh ['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz ['5', '6', '9'] 开头的为 sh, 其余为 sz :param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断 :ret...
def some_other_function(): assert scope.get('foo') == 'bar' # we can access the "current scope" current_scope = scope.get_current_scope() # and use it like a dict assert current_scope['foo'] == 'bar' def main(): # the my_scope variable is now defined # inside a function scope, so it is n...
def mean_longitude(t: float) -> float: """ Calculate the sun's mean longitude in decimal degrees. Parameters: t (float): The time in Julian Centuries (36525 days) since J2000.0 Returns: float: The sun's mean longitude at the given time """ # t must be in the range fro...
""" #!/bin/bash secs_to_human() { echo "$(( ${1} / 3600 ))h $(( (${1} / 60) % 60 ))m $(( ${1} % 60 ))s" } SKIPSTEPS=0 TMPDIR=/data/kite/tmp for i in "$@" do case $i in --model=*) MODEL="${i#*=}" shift # past argument=value ;; --lang=*) LANG="${i#*=}" shift # past argument=value ;;...
""" SQLAlchemy Owner model class """ def init(db): class Owner(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True, nullable=False) def __repr__(self): return f'<Owner {self.name}>' def as_dict(self): d = { ...
n = int(input()) for i in range(n): num = float(input()) contDias = 0 while(num / 2 > 1): contDias = contDias + 1 num = num / 2 print("{} dias".format(contDias + 1))
lista = [] n = int(input("¿Cuantos numeros agregaras?:")) for i in range(n): valor= float(input("Ingrese numero %i: "%(i+1))) lista.insert(i,valor) print ("Los numeros que agregaste son: ",lista) lista.sort() print("Estos son los números en orden de Menor a Mayor : ", lista) y = (lista[-1]) entero = round(y)...
class Vrchol: def __init__(self, px, py, psize, pid, pinfo = ''): self.size = psize self.x = px self.y = py self.info = pinfo self.sus = [] self.farba = "#FFFFFF" self.rozliaty = False self.id = pid def vykresli(self,cnv): for i in range(l...
my_dict = {'a':[0, 1, 2, 3], 'b':[0, 1, 2, 3], 'c':[0, 1, 2, 3], 'd':[0, 1, 2, 3]} i = 0 output = [] for key in my_dict: output.append(my_dict[key][i]) i += 1 print(output)
# -*- coding: utf-8 -*- agetypes = {'Människa':{'Ung': (15,24), 'Mogen': (25,38), 'Medel': (39,55), 'Gammal': (56,65), 'Åldring': (66,85)}, 'Gôr': {'Ung': (15,24), 'Mogen': (25,75), ...
while(True): s0,s1, r0,r1 = map(int,input().split()) if not(s0): exit() S0,S1=min(s0,s1),max(s0,s1) R0,R1=min(r0,r1),max(r0,r1) if S0+S1==3 and R0+R1==3: print("Tie.") elif S0+S1==3: print("Player 1 wins.") elif R0+R1==3: print("Player 2 wins.") elif S0==...
''' Let's do some simple tasks for your homework. This week, we'll do some practice using what we learned about functions and conditional blocks to make some useful, reusable code! First, let's start by writing a function called plus_five which takes a number and prints out that number plus five. ''' def plus_five(x):...
# pylint: skip-file # flake8: noqa class Repoquery(RepoqueryCLI): ''' Class to wrap the repoquery ''' # pylint: disable=too-many-arguments def __init__(self, name, query_type, show_duplicates, match_version, verbose): ''' Constructor for YumList ''' super(Repoquery, se...
maximum = 20 count = maximum found = False while(not found): for x in range(1,maximum+1): if(count % x != 0): break if(x == maximum): found = True if(not found): count += maximum print(count)
load("//dependencies/navx/4_0_425:deps.bzl", "setup_navx_4_0_425_dependencies") load("//dependencies/navx/4_0_435:deps.bzl", "setup_navx_4_0_435_dependencies") load("//dependencies/navx/4_0_442:deps.bzl", "setup_navx_4_0_442_dependencies") def setup_navx_dependencies(version): if version == "4.0.425": setu...
class Solution: def predictPartyVictory(self, senate: str) -> str: qr = collections.deque() qd = collections.deque() for i, ch in enumerate(senate): if ch == 'R': qr.append(i) else: qd.append(i) n = len(senate) while qr ...
favorite_languages = ' I like python ' # 创建一个前后带空格的变量favorite_languages print("\n") favorite_languages # 没有使用print函数, 单写变量是无法将变量内容打印出来的 print('前面有空格' + favorite_languages + '后面有空格') print("\n") # rstrip()函数去除字符串结尾的空格, \t \n等造成的效果也会删除 print('前面有空格' + favorite_languages.rstrip() + '后面没空格') print('前面有空格' +...
''' 不同的二叉搜索树 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? ''' ''' 思路1,回溯。 二叉搜索树的根节点为node,所有的左子树节点小于node,所有的右子树节点大于node,其左右子树节点也满足这一性质。 根据这一特性,对于二叉搜索树nums[1..n],如果第i个数为根节点,则nums[1..i-1]为左子树,nums[i+1..n]为右子树,再递归求左右子树的切分次数 时间复杂度:x, O(2^n)< x <O(n!) 空间复杂度:O(n),最大递归深度n 思路2,动态规划 设动态规划数组dp,dp[i]的意思是长度为dp[i]的数组,可以生成的二叉树有多少种 那么dp[0]=...
class CtMap: """ A cache implemented map using linear lists. This is a hold over from the javascript library when we couldn't be sure that a student's javascript could use maps. The design pattern used in this map is to always used the cached key/associated index. So methods accessing values will f...
meal_cost = float(input()) tip_percent = int(input()) tax_percent = int(input()) tip = meal_cost * tip_percent / 100 tax = meal_cost * tax_percent / 100 total = meal_cost + tip + tax print(int(round(total)))
{ "targets": [ { "target_name": "wtf8", "sources": [ "wtf8.cc" ], "include_dirs" : [ "<!(node -e \"require('nan')\")" ] } ] }
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Ian' __create_date__ = '2015/1/8' ## opensubtitles LANGUAGE_MATRIX = [] f = open('MainMenu.strings', 'r') f.readline() for l in f: str = l.decode('utf-8').strip() if not str.startswith("/*"): LANGUAGE_MATRIX.append(str) f.close() fw = open(...
line = input() line_pal = line[::-1] if line_pal == line: print("Yes") else: print("No")
""" Copyright 2020 The Microsoft DeepSpeed Team """ ######################################### # Elasticity ######################################### ''' Elasticity Utility in DeepSpeed can be used to create highly elastic jobs compatible with a large number of GPUs. For elastic jobs, DeepSpeed will provide a batch siz...
class EndPoint: def __init__(self, end_point_json): self.id = end_point_json["_postman_id"] self.name = end_point_json["name"] self.authentication = end_point_json["request"].get("auth") self.method = end_point_json["request"]["method"] self.header = end_point_json["request"]...
# -*- coding: utf-8 -*- """ gspread.ns ~~~~~~~~~~ This module contains namespaces used across the project and related helper functions. """ ATOM_NS = 'http://www.w3.org/2005/Atom' SPREADSHEET_NS = 'http://schemas.google.com/spreadsheets/2006' EXTENDED_SPREADSHEET_NS = 'http://schemas.google.com/spreadsheets/2006/ex...
class Solution: def shortestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s) <= 1: return s for i in range(len(s)//2, -1, -1): # mid if s[:i][::-1] == s[i+1:2*i+1]: return s[i+1:][::-1] + s[i] + s[i+1:...
#!/usr/bin/env qork FONT = "./data/PressStart2P-Regular.ttf:64" canvas.font(FONT) def script(ctx): canvas.text("Health: |||||", anchor="", align="l") player = add("spirit.cson", scale=1 / 16) player.state["stance"] = "walk" player.rotate(0.125, X) player.z = 1 / 16 camera.fov = 0.09 player.y = 2.5 / 16 camera....
class LoggerNull(): ''' 一个空的日志对象,用于不打印日志时候,绑定数据 ''' def __init__(self): self.logNumber = 0 # 为logger添加属性,用于记录日志打印顺序 self.scriptId = 0 # 脚本id默认值
class Solution: def check(self, i, haystack, needle): for j in range(len(needle)): if haystack[i] != needle[j]: return False i += 1 return True def strStr(self, haystack: str, needle: str) -> int: len_haystack = len(haystack) ...
#42 Frequency to note #Asking for frequency of note x = float(input("Enter the frequency of note = ")) if x == 261.63: print("The note of frequency is C4.") elif x == 293.66: print("The note of frequency is D4.") elif x == 329.63: print("the note of frequency is E4.") elif x == 349.23: print("...
print(''' WARNING! The most important thing when doing this exercise is: “There is no failure, only trying.” ''')
# coding: utf-8 ''' UFCG PROGRAMAÇÃO 1 JOSE ARTHUR NEVES DE BRITO - 119210204 Inverte 2a2''' def inverte2a2_condicional(seq): if len(seq) % 2 == 0: for i in range(0,len(seq),2): if seq[i] > seq[i+1]: seq[i],seq[i+1] = seq[i+1],seq[i] else: for i in range(0,len(seq)-1,2): if seq[i] > seq...
class PeerPingProtocol(basestring): """ The network protocol to use when performing the ping operation. Possible values: <ul> <li> "data" - Data Ping, <li> "icmp" - ICMP Ping </ul> """ @staticmethod def get_api_name(): return "peer-ping-protocol"
numeros = list() test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("digite 10 numeros") #""" for i in range(10): numeros.append(int(input())) pass print(numeros) #""" #para teste rapido. #numeros = test #print(numeros) media = 0 for num in numeros: media += num pass media /= 10 print("A media foi...
# _page_layout.html: Autogenerated file start def render(name,header,footer,layout,vars): yield """<!DOCTYPE html> <html lang=\"en\"> """ # _html_head.html: Autogenerated file start def render1(name): yield """<head> <meta charset='utf-8'/> <meta name='viewport' content='width=device-width, init...
print('curl localhost:10101/index/test/query -X POST -d \'') for i in range(1,51): for j in range(0,100): print('Count(Row(c'+str(i)+'=a'+str(j)+'))') print('\'')
class JenkinsMetadata(object): """ This class is the model of the Jenkins data relating to the build that ran the tests or collected the metrics. This class is how the model is represented in the HTTP API """ def __init__(self, jenkins_job_id): self.jenkins_job_id = jenkins_job_id
""" Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. After doing so, return the array. Example: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] """ #Difficulty: Easy #15 / 15 test cases...
def registerPredefined(modules_avail): for m in ["modules", "events", "info", "settings"]: module_name_id = 'miniflask.' + m importname = 'miniflask.modules.' + m modules_avail[module_name_id] = { 'id': module_name_id, 'importpath': "system", 'importname'...
h, w = [int(x) for x in input().split(' ')] c = int(input()) h += (w + c) // 60 w = (w + c) % 60 h %= 24 print(h, w)
class Solution: def maxProfit(self, prices): if not prices: return 0 ascents = [] lower = prices[0] upper = prices[0] res = 0 for i in prices: if i > upper: upper = i elif i < upper: ascents.append(...
# Title : Count the number of element list of a list # Author : Kiran raj R. # Date : 25:10:2020 list1 = [[1, 2], 3, 4, [5, 6], 7, [8, 9, 10]] list2 = [('a', 'b'), 'c', 'd', 'e', ['f', 'g', 'h']] print(f"Number of elements in list1 {len(list1)}") print(f"Number of elements in list2 {len(list2)}") def list_in_lis...
# String replacement / substitution welcome_message = 'Hello World!' print(welcome_message.replace("Hello", "Goodbye")) # Generating multiple strings print('*' * 10) print('Hi' * 10) # Testing strings containing another string print('Edward Alan Rawlings'.find('Alan')) print('Edward John Rawlings'.find('Alan')) prin...
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2012 Jens Lindström, Opera Software ASA # # 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...
total = 0 for i in range(1,1000): if i % 3 ==0 or i %5 ==0: total += i print(total)
__version__ = "2.1.5" default_app_config = "channels.apps.ChannelsConfig" DEFAULT_CHANNEL_LAYER = "default"
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:lianbiao.py @TIME:2020/5/12 20:53 @DES: ''' class Node: def __init__(self,data,pnext=None): self.data = data self._next=pnext def __repr__(self)...
# -*- coding: utf-8 -*- """ Created on Thu Sep 9 17:11:20 2021 @author: Patricia """ print= "Hello, World!" idade= int(input("digite a idade:")) if idade>=7 and idade<=9: print("infantil A") elif idade>=8 and idade<= 12: print(" infantil B") elif idade>=13 and idade<= 15: print("juvenil A") elif idade>= ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"names": "10_pref.ipynb", "short_names": "10_pref.ipynb", "df": "10_pref.ipynb", "__code2name": "10_pref.ipynb", "__name2code": "10_pref.ipynb", "name2code": "10_p...
# coding: utf-8 ["DEFAULT"] max_tempfile_number = 100 max_thread_num = 8 ["account"] username = "" password = "" ["proxies"] proxies_enable = False socks = "" ["path"] local_save_root = "./default_save/" temp_save_root = "./temp_save/" ["data"] garage_file = "./garage.txt" cookies_file = "./cooki...
a = 3 b = 5 print('Os valores são \033[32m{}\033[m e \033[31m{}\033[m!!!'.format(a, b)) cores = {'limpa': '\033[m', 'azul': '\033[34m', 'amarelo': '\033[33m', 'pretoebranco': '\033[7:30m'} nome = 'Joaquim' print('Muito prazer em te conhecer, {}{}{}!'.format(cores['amarelo'], nome, cores['limp...
#----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #-----------------------------------------------------...
# encoding: utf-8 class Style(object): def __init__(self, newline, indent): self.newline = str(newline) self.indent = str(indent) class Pretty(Style): def __init__(self): super(Pretty, self).__init__("\n", ' ') class Sparse(Style): def __init__(self): super(Sparse, s...
def test_enter(player, limo): player.perform("enter limo") assert player.saw("You enter a fancy limo") assert player.saw("electric") def test_enter_and_exit(player, limo): player.perform("enter limo") player.forget() player.perform("go out") assert player.saw("Antechamber")
#!/bin/python3 ''' String concatenation f string - This is prefferable because its straight forward and simple + .format ''' # answ = input("enter the name of your best friend: ") # digit = " Dude" # # Example of f string # def stringJoiner(data): # con_cat = f"{data} is the real {digit}!" # return con_cat ...
"""Utilities for module and path manipulations.""" load("@bazel_skylib//lib:paths.bzl", "paths") load(":private/set.bzl", "set") def module_name(hs, f, rel_path = None): """Given Haskell source file path, turn it into a dot-separated module name. module_name( hs, "some-workspace/some-package/src/...
''' Demo_2 is a simple implementation of factorial calculation ''' n = int(input('please enter a number: ')) fac = 1 for n in range(n): fac = fac * (n + 1) print('the answer is: ', fac)
sum_sq = 0 sq_sum = 0 for i in range(1, 101): sum_sq += i**2 sq_sum += i diff = sum_sq - sq_sum**2 print(diff)
"""Dictionary Data Parsing Functions.""" META = {} def flatten_dictionary_with_int(dictionary_data): """Return flat meta report dictionary from nested dictionary with ints.""" meta_dict = META meta_dict["report"] = {} for item in dictionary_data: if type(dictionary_data[item]) is dict: ...
# Refresh SENSU # salt-run cache.clear_grains tgt="*" ; salt '*' state.sls sensu.client; salt '*' service.restart salt-minion; salt '*' mine.flush; salt '*' mine.update ; salt 'mon01*' state.sls sensu @roles('ntw') def clean_contrail(): sudo(uptime) sudo(hostname)
# https://leetcode.com/problems/merge-intervals/ class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals = sorted(intervals, key=lambda x: x[0]) i = 0 while i < len(intervals) - 1: if intervals[i][1] >= intervals[i+1][0]: ...
tum_siparis = {"Siparisleriniz": [], "Hesabınız": []} aperatif = {"Kasarlı Tost": 6, "Kıymalı Tost": 8, "Sucuklu Yumurta": 10,"Karışık Tost": 10, "Sucuklu Tost": 7,"Soguk Sandvic":7} print("*****Aperatif ÇEŞİTLERİMİZ*****") print(aperatif) def siparis(yemek): siparis_listesi = [] ...
# -*- coding: utf-8 -*- """ Created on Sun May 26 20:25:09 2019 @author: Administrator """ class Solution: def isPowerOfThree(self, n: int) -> bool: # if n <= 0: # return False # while n != 1: # if n%3 != 0: # return False # n //= 3 # return Tru...
x = int(input()) y = int(input()) menor = min(x, y) + 1 maior = max(x, y) - 1 soma = 0 while menor <= maior: if menor % 2 != 0: soma += menor menor += 1 print(soma)
# Faça um programa que peça 20 números inteiros, calcule e # mostre a quantidade de números pares e a quantidade de números ímpares. impar =0 par = 0 count =1 for a in range(1, 21): num = int(input("%d - Digite um número: "%a)) count += 1 if num %2 == 0: par = par + 1 elif num %1 == 0 : ...
def solution(enroll, referral, seller, amount): answer = [] name = {} money = {} for _ in range(len(enroll)): name[enroll[_]] = referral[_] money[enroll[_]] = 0 for _ in range (len(amount)): amount[_] *= 100 for _ in range (len(seller)): str = "" tmp = amo...
def shellSort(array): gap = len(array) // 2 # loop over the gaps while gap > 0: # insertion sort for i in range(gap, len(array)): val = array[i] j = i while j >= gap and array[j - gap] > val: array[j] = array[j - gap] j -= gap ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: config.sample.py Description: unittest configuration for Python SDK of the Cognitive Face API. - Copy `config.sample.py` to `config.py`. - Change the `BASE_URL` if necessary. - Assign the `KEY` with a valid Subscription Key. """ # Subscription Key for calling th...
# Databricks notebook source # MAGIC # MAGIC %md # MAGIC # Dataset-Mounts-Test # MAGIC The purpose of this notebook is to faciliate testing of our systems. # COMMAND ---------- spark.conf.set("com.databricks.training.module-name", "dataset-mounts-test") # COMMAND ---------- # MAGIC %run ./Dataset-Mounts # COMMAND...
class Adjunct: def apply(self, right, arg): pass class A: pass def foo(): pass class B: pass print('239')
class Solution(object): def validateStackSequences(self, pushed, popped): """ :type pushed: List[int] :type popped: List[int] :rtype: bool """ stack = [] pop_ptr = 0 for push_num in pushed: stack.append(push_num) while stack ...
#!/usr/bin/env python3 # This program converts Fahrenheit to Celsius embedded = 1 # using embedded python libraries if embedded == 1: fahr_temp = 33 print("Fahrenheit Temperature = ", fahr_temp) else: fahr_temp = float(input("Fahrenheit temperature: ")) print("Celsius temperature:", (fahr_temp - 32.0) * 5...
def fibonacci(input,memory): if(input == 0 or input == 1): return memory[input] else: memory[input] = fibonacci(input - 1,memory) + fibonacci(input - 2,memory) return memory[input] memory = [0] * 10 memory[0] = 0 memory[1] = 1 for i in range(10): print(fibonacci(i,memory))
def ways(n, k) : if n == 1: return k elif n == 2: return k*k elif n == 3: return k * (k-1 +(k-1)*k) else: return k * ways(n-1,k)- ways(n-3,k)*(k-1) if __name__ == "__main__" : ## n, k = 2,4 ## n, k = 3,2 ## n, k = 6,3 n, k = 5,2 ...
class CallTracer: def __init__(self, func): """# On @ decoration: save original func 'calls' variable is a state retainer; it maintains knowledge of the number of function calls, since the function itself cannot. It is tied into the 'func' variable so each decorated function has its own sta...
# Comment it before submitting # class Node: # def __init__(self, value, left=None, right=None): # self.value = value # self.right = right # self.left = left def is_search_tree(root): if root is None: return True if root.left is None and root.right is None: return ...
"""For experiments on n-puzzle from IPC'08 learning track.""" PDDL_DIR = '../problems/ipc08-learn/n-puzzle/' COMMON_PDDLS = ['learning/n-puzzle-typed.pddl'] TRAIN_PDDLS = [ # 'learning/bootstrap/typed/bootstrap-typed-01.pddl', # 'learning/bootstrap/typed/bootstrap-typed-02.pddl', # 'learning/bootstrap/type...
def count_to(count): """Our iterator implementation""" #Our list numbers_in_german = ["eins", "zwei", "drei", "vier", "funf"] #Our built-in iterator #Creates a tuple such as (1, "eins") iterator = zip(range(count), numbers_in_german) #Iterate through our iterable list #Extract the German numbers #Put them...
# -*- coding: UTF-8 -*- # # Given a binary tree, return the inorder traversal of its nodes' values. # # For example: # Given binary tree [1,null,2,3], # 1 # \ # 2 # / # 3 # return [1,3,2]. # # Note: Recursive solution is trivial, could you do it iteratively? # # Python, Python 3 all accepted. class BinaryTreeInorderT...
[ { 'date': '2015-01-01', 'description': 'Año Nuevo', 'locale': 'es-ES', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2015-01-06', 'description': 'Día de los Reyes', 'locale': 'es-ES', 'notes': '', 'region': '',...
#!/usr/bin/env python2.7 # Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
### most of this will only work for Blast -- not psi-blast def is_new_query_id_line( line ): return line and line.split() and line.split()[0] == 'Query=' def is_new_hit_id_line( line ): return line and line[0] == '>' def is_new_match_line( line ): return line and line[:3] == ' Sc' def is_query_alig...