text
stringlengths
5
121k
import sys def making_change(amount, denominations): ways = [0] * (amount + 1) ways[0] = 1 for coin in denominations: for higher_amount in range(coin, amount + 1): remainder = higher_amount - coin ways[higher_amount] += ways[re...
class Pyramid: def __init__(self,pyramidL,pyramidW,pyramidH): self.pyramidL = int(pyramidL) self.pyramidW = int(pyramidW) self.pyramidH = int(pyramidH) def calcVol(self,pyramidL,pyramidW,pyramidH): print("The volume is: " + str((pyramidL*pyramidW*pyramidH)/3)) def ...
str1= "what we think we become; we are python programmers" str1.count ("we") str1.count ("we",0,15) str1[0:15].count("we") str1.find("we") str1[5] str1.rfind("we") str1.index("we")
from DB.Get_Password_db import Get_Password_db_fun from tkinter import * import tkinter.messagebox def Get_The_Password_fun(): def Get_Password_db_fun_helper(): str=Get_Password_db_fun(entry_1.get(),entry_2.get()) root3.destroy() tkinter.messagebox.showinfo("Password","Your Password is '"...
def game_score(deck): return sum(i * card for i, card in enumerate(deck[::-1], 1)) def solve1(deck_a, deck_b): while deck_a and deck_b: a, b = deck_a.pop(0), deck_b.pop(0) if a > b: deck_a += [a, b] else: deck_b += [b, a] return game_score(deck_a if deck_a e...
birthYear = input('Birth Year: ') age = 2019 - int(birthYear) print(type(birthYear)) print(type(age)) print(age)
l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] a= [] for i in range(len(l1)): if l1[i] > l2[i]: a.append(l1[i] - l2[i]) else: a.append(l1[i]) print("Original list are :") print(l1) print(l2) print("\nOutput list is") print(a)
a=[1,2,3,4,5,6,7]
a=[1,3,4,7,8,9,11,12] i=0 large=a[i] while i<len(a): if a[i]>large: large=a[i] i=i+1 print(large)
a=[1,2,3,4,5,6,7,8,9,10] i=1 b=[] while i<len(a): t=a[0] b.append(t*1) i=i+1 print(b)
import time pair = 0 cost = 0 print("|---------------------|") print(" AMAN SHOES STORE ") print("|---------------------|") name = str(input("Enter your name here\n")) phone = (input("Enter your mobile number here\n")) adress = str(input("Enter your address\n")) time.sleep(0.5) print("THANK YOU!") print("f...
crazy_landlords = [] crazy_landlords = ['My. Richards', 'Raj', 'Mr. Shirik', 'Ms Zem'] crazy_landlords = ['My. Richards', 'Raj', 'Mr. Shirik', 'Ms Zem'] print(crazy_landlords) print(crazy_landlords[1]) crazy_landlords[1] = 'Rajesh' print(crazy_landlords) crazy_landlords.append('Raj') crazy_landlords.ins...
num = 0 for val in 'String': print(val) if val == 'i': print('going out of the loop') break print('Out of loop')
import pandas as pd def queryTable(conn, tablename, colname, value, *colnames): """ This function queries a table using `colname = value` as a filter. All columns in colnames are returned. If no colnames are specified, `select *` is performed :param conn: the connection with the database to be used t...
def getPentagonalNumber(n): pentagonalnumber=int((n*(3*n - 1))/2) return pentagonalnumber for i in range(1, 101): print(getPentagonalNumber(i))
ta=float(input("Enter the Temperature in Fahrenheit between -58 and 41:")) v=eval(input("Enter wind speed in miles per hour:")) if v < 2: print("wind speed should be above or equal 2 mph") else: print("the wind chill index is ", format(35.74 + (0.6215*ta) - (35.75* v**0.16) + (0.4275 * ta * v**0.16), ".5f"))
inte1= int(input('Input the first integer:')) inte2= int(input('Input the second integer:')) summan= int(inte1+inte2) print('The sum of two integers is:',+summan)
def get_input(): a_list=input('Input a list of integers separated with a comma: ').split(',') b_list=input('Input a list of integers separated with a comma: ').split(',') a_list=[int(i) for i in a_list] b_list=[int(i) for i in b_list] return a_list, b_list def set_lists(a_list,b_list): a_set=se...
def fibo(x): array=[1,1] if x!=1: for i in range(2,x): tala=(array[i-2])+(array[i-1]) array.append(tala) for n in range(0, len(array)): print(array[n], end=' ') else: print(x) n = int(input("Input the length of Fibonacci sequence (n>=1): ")) fibo...
def make_new_row(row): new_row = [] for i in range(0,len(row)+1): if i == 0 or i == len(row): new_row.append(1) else: new_row.append(row[i]+row[i-1]) return new_row height = int(input("Height of Pascal's triangle (n>=1): ")) new_row = [] for i in range(hei...
class OrderLine(object): def __init__(self, name, price, number, discount): self.name=name self.price = price self.number = number self.discount = discount def __str__(self): return "{0:<10}{1:<9}{2:<11}{3:<12}{4:<5}".format(self.name, self.price, self.number, self.d...
def brefin(): global out1 global bref while out1==False: bref=input('Enter number of shares: ') try: bref = int(bref) out1=True return except ValueError or SyntaxError or NameError: print("Invalid number!") def theprice(): global...
age_float=float(input("Enter your age: ")) if 0 <= age_float < 34: print("Young") elif 35 <= age_float < 50: print("Mature") elif 51 <= age_float < 69: print("Middle-aged") elif 70 <= age_float: print("Old")
import random as rnd class GameShow: win_count = 0 lose_count = 0 total = 0 def __init__(self): self.doors = ['reward', 'nothing a', 'nothing b'] self.reward = 0 self.wrong = 0 self.host = '' self.player = '' self.set_door() def set_door(self): ...
import numpy as np import matplotlib.pyplot as plt import sys sys.path.append(r"C:\Users\dell\Desktop\code\knn") import get_data def EuclideanDistances(x): """ Parameters ---------- x : ndarray matrix of instances. norm : float, optional p-normal for distances. The d...
import math def calcular_angulo_triangulo(a,b): if a <= 0 or b <= 0: print("Error, los valores deben ser positivos") return 0 else: c = math.sqrt(a**2+b**2) angulo = math.asin(a/c) return angulo if __name__ == "__main__": print("Ingrese el valor de a: ") a = fl...
def mayor(a, b): if a > b: print(str(a) + " es mayor!!!") return a elif a < b: print(str(b) + " es mayor!!!") return b else: print(str(a) + " y " + str(b) + " Son iguales") return a def menor(a, b): if a < b: print(str(a) + " es menor!!!") ...
def translation(): input_minutes = int(input("Enter pleas minutes: ")) hours = input_minutes//60 result_hours = hours - (hours//24)*24 result_minutes = input_minutes - hours*60 result = str(result_hours) +"Hours and "+str(result_minutes) +"Minutes" print(result) try: translation() except: ...
def find_first_names(students_input): """ input: list of a class roster return: sorted list of first names in roster """ first_name = [] for name in students_input: first_name.append(name.split()[0].capitalize()) return sorted(first_name) print( find_first_names([ 'nich...
def check_weirdness(n): """ if n is less than 1 or greater than 100, return "Not Applicable" if n is odd, return "Weird" if n is even and in the inclusive range of 6 to 20, return "Weird" if n is even and in the inclusive range of 2 to 5, return "Not Weird" if n is even and greater tha...
import sys def eating_cookies(n, cache=None): if n < 0: return 0 elif n == 0: return 1 else: return eating_cookies(n-1) + eating_cookies(n-2) + eating_cookies(n-3) print(eating_cookies(1)) print(eating_cookies(3)) cookie_cache = {} def eating_cookies_cached(n, cookie_cac...
"""Tic Tac Toe Milestone Project game! """ import random def clear_screen(): print('\n' * 100) def display_board(board): print(board[7] + '|' + board[8] + '|' + board[9]) print('-----') print(board[4] + '|' + board[5] + '|' + board[6]) print('-----') print(board[1] + '|' + board[2...
def growth_value(FCF_t0,g,r,n): r = r/100 g = g/100 value=0 t=0 for k in range(n): tk = ((FCF_t0*((1+g)**(k))))/((1+r)**(k)) t += tk value =t global terminal_FCF,g1,r1,n1 terminal_FCF = tk r1 = r n1 = n return t def perpetuity_value(tg, tr, g): ...
class FlightData: """Responsible for structuring the flight data.""" def __init__(self): self.all_flight_data_per_destination_city = [] self.specific_flight_data_per_destination_city = [] def structure_file_data(self): for destination_airport, flight_info in self.all_f...
""" Given an array of integers A, We need to sort the array performing a series of pancake flips. In one pancake flip we do the following steps: Choose an integer k where 0 <= k < A.length. Reverse the sub-array A[0...k]. For example, if A = [3,2,1,4] and we performed a pancake flip choosing k = 2, we revers...
""" Design an Iterator class, which has: A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. A function next() that returns the next combination of length combinationLength in lexicographical order. A function hasNext() that...
""" Sole candidate technique. If there is only one possibility in a cell, because of the constraints of the other numbers, then it can only be this number. """ from copy import deepcopy def sole_candidate(s, poss): sudoku = deepcopy(s) for i in range(9): for j in range(9): a = poss[i][j...
import sys def key_value_string_to_dict(data_string, key_value_separator='='): ''' Given a string like: key=value\nkey2=value2 Return a dict with data[key] = values. - Ignores all lines that start with # or are empty. - Returns None on any parse errors. - Strips leading...
''' names = ['gaoyang', 'xinxin', 'guanglin'] for ceshi in names: print(ceshi)''' '''sum = 0 for x in [1,2,3,4,5,6,7,8,9,10]: sum = sum + x print(sum)''' '''sum = 0 for x in range(101): sum = sum + x print(sum)''' '''sum = 0 n = 99 while n>0: sum=sum+n n=n-2 print(sum)''' '''sum ...
def mysort(inList,dir): newList=[] while len(inList)>0: if dir: minData = max(inList) else: minData =min(inList) newList.append(minData) inList.remove(minData) return newList alist=[0,8,5,1,2] print(mysort(alist)) print(mysort(alist),True)
def expanded_form(num): result = [] divider = 10 while divider < num: temp = num%divider if temp != 0: result.insert(0, str(temp)) num -= temp divider *= 10 result.insert(0, str(num)) return ' + '.join(result)
def oddeven(a): if a%2==0: print( a,"is Even Number") else: print(a,"is Odd Number") def main(): num=int(input("Enter any number:")) oddeven(num) main()
def multiplication_table(a): for i in range(1,11): print("%d * %d = %d" %(a,i,a*i)) def main(): num=int(input("Enter the number")) multiplication_table(num) main()
class circle: def __init__(self, radious): self.radious=radious def area(self): self.radious=input("Enter the radius of circle:")
def check(m_u, income): if m_u == 'Y': if annual <= 450000: a = annual * 0.01 total = a tax = 1 elif 450000 < annual <= 550000: a = 450000 * 0.01 b = (annual - 450000) * 0.1 tax = (1 + 10) total = a + b elif ...
userinput=input("Enter the Sentence:") print(userinput) vowel=0 for i in userinput: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowel+= 1 print(vowel) if vowel%i==0: print("The given number is a prime number.") else: print("The num...
a=int(input("Enter the First Number:")) b=int(input("Enter the Second Number:")) c=int(input("Enter the Third Number:")) if a>b>c: print("%d is a Greatest Number" %a) elif b>a>c: print("%d is a Greatest Number" %b) else: print("%d is a Greatest Number" %c)
CP = float(input("enter cost price of product:")) SP = float(input("enter selling price of product:")) profit = SP-CP newsp = 1.05*profit + CP print("profit from product=",profit) print("to increase profit 5% more new selling price should be =",newsp)
import csv import argparse parser = argparse.ArgumentParser(description = 'This script will take a .gff file, pull out the gene names from the list, and store them in a alphabatized list. Then it will take that list and use it to pull out the gene sequences from a fasta file and calculate the GC content.') pars...
def tester(start): state = start def nerqin_funkcia(): state += 1 return state return nerqin_funkcia() print(tester(5))
from pokemon import Pokemon from player import Player from trade_calculator import TradeCalculator import unittest class TestTradeCalculator(unittest.TestCase): def test_player_total_base_experience_passing_wrong_type(self): """Teste passando argumento diferente de Player >>> _total_base...
name = str(input("What is your name? ")) for i in range(0, len(name), 2): print(name[i])
def Z_func_with_discrepancy(str): I = 0 r = 0 j = 0 Z = [0] * (len(str)) Z[0] = len(str) for i in range(1, len(str)): j = i discrepancy = 0 if i <= r: Z[i] = min(r - i + 1, Z[i - I]) while j + Z[i] < len(str) and (str[Z[i]] == str[j + Z[i]] or (i > str...
x = 2 y = 3 print(x + y) x += 5 print(x) print(x > y)
age = 36 text = "my age is {}" print(text.format(age)) apple = 3 banana = 5 streberry = 10 text1 = "I bought {} apples, {} bananas and {} straeberry." print(text1.format(apple, banana, streberry)) apple = 10 banana = 55 streberry = 30 text2 = "I bought {2} straeberry, {1} bananas and {0} apples." print(text2.format...
class MyClass: x = 5 p1 = MyClass() print(p1.x) print('_______________') class person: def __init__(self, name, age): self.name = name self.age = age p1 = person('Jhon', 13) print(p1.name) print(p1.age) print('_______________') class person: def __init__(mysillyobject, name, age): ...
for x in range(6): print(x) print('____________________') for x in range(2,6): print(x) print('____________________') for x in range(2,20,3): print(x) print('____________________') for x in range(0,6): print(x) else: print('finished') print('____________________') adj = ['red', 'big', 'tas...
class person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) x = person('Jhon', 'Doe') x.printname() class student(person): pass s = student('Noura','Almulhim') s.printname() class ...
class PriorityQueueBase: class Item: __slots__ = '_key','_value' def __init__(self,k,v): self._key = k self._value = v def __lt__(self,other): return self._key < other._key def is_empty(self): return len(self) == 0 def __st...
def fibonacci(n): """ Summary of fibonacci function: computes the fibonacci series which is a numeric series starting with integers 0 and 1. The next integer in series is determined by summing the previous two and looks like 0, 1, 1, 2, 3, 5, 8, 13, ... Parameters: n (int): positive int...
def lineValueAtTarget(line, target): if target > len(line): target = target % len(line) return line[target] dataInput = open("./input/input_3.txt").read().split("\n") treeCount = 0 currentLocation = 0 for line in dataInput: valueAtLocation = lineValueAtTarget(line, currentLocation) ...
import csv def loaddata(file_name, max_rows = -1): """ Pre-processing Reading file into a list """ file = open(file_name) typeStr = file.readline() types = typeStr.rstrip().split(';') headerStr = file.readline() headerNames = headerStr.rstrip().split(';')...
import pygame from pygame.locals import * import sys import time class Plant: """Simple plant representation. Contains information of a plant. Attributes: pos_x: x coordinate of the plant. pos_y: y coordinate of the plant. width: width of the plant. height: height of th...
x=int(input("enter the no ")) if(x%2==0): print("prime") else: print("odd")
''' Created on Nov 18, 2017 @author: ITAUser ''' def characterappearances(filename, mychar): f = open(filename , 'r') count = 0; run = True while run: text = f.read(1) text = text.lower() if text == mychar: count = count +1; if text == '': break...
from math import pi from sys import exit radius = input(">Enter circle radius in meters: ") def intCheck (input): if str.isdigit(input): return int(input) else: exit("Invalid entry") radius = intCheck(radius) area = pi*radius**2 print ("The area of a circle with a radius of", radiu...
valor = int(input('Digite o valor de n: ')) i = 0 valor_impar = 1 while i < valor: print(valor_impar) i = i + 1 valor_impar = valor_impar + 2
class Triangulo: def __init__(self, a, b, c): self.lA = a self.lB = b self.lC = c def tipo_lado(self): if self.lA <= 0 or self.lB <= 0 or self.lC <= 0: return False else: if self.lA + self.lB > self.lC and self.lB + self.lC > self.lA: ...
def ordena(lista): for i in reversed(range(len(lista))): val = 0 for j in range(1, i + 1): if lista[j] > lista[val]: val = j lista[i], lista[val] = lista[val], lista[i] return lista
hours = input("Enter the hours ") pay = input("Enter the payrate ") try: fhours = float(hours) fpay = float(pay) except: print("Error, Please enter a numeric input") quit() total = 0 if fhours <= 40: total = fhours * fpay else: extra = fhours - 40 print(extra) total = (fhours-extra) ...
weight = input("Insert your weight (in KG)") height = input("insert your height (M)") weight = float(weight) height = float(height) bmi = weight / (height**2) print(bmi)
import random import operator import time print("JOGO DOS DADOS: ") tuplas = () lista = [] for n in range(4): jogador = input("Digite seu nome: ") print("DIGITE ENTER PARA SORTEAR O DADO") input() numero = random.randint(1,10) tuplas = (jogador , numero) lista.append(tuplas) lista_dict = dict...
class Tree: def __init__(self,root,left=None,right=None): self.root=root self.left=left self.right=right def __str__(self): return (str(self.root)+", left child :"+str(self.left)+ ", right child :" +str(self.right)) tree=Tree(5,Tree(3,1,4),Tree(8,7,9)) print(tree)
from matrix import * from vector import * from rational import * def tests(): m1 = Matrix(Rational(1, 2), Rational(1, 3), Rational(-2, 7), Rational(2, 8)) m2 = Matrix(Rational(-1, 3), Rational(2, 7), Rational(2, 5), Rational(-1, 7)) m3 = Matrix(1, 2, 3, 4) v = Vector(1, 2) print("m1xm2:") print(m1@m2) print("in...
def max_prod (a): max_p = a[0] * a[1] for i in range (1, len(a) - 1): prod = a[i] * a[i + 1] if (prod > max_p): max_p = prod return max_p def main(): file = 'testcase1.txt' file = 'testcase2.txt' file = 'testcase3.txt' in_file = open(file, "r") dim = in_file.read...
import os.path import sys def substr (st): pieces = [] wnd = len (st) while (wnd > 0): start_idx = 0 while ((start_idx + wnd) <= len(st)): piece = st[start_idx : start_idx + wnd] pieces.append(piece) start_idx += 1 wnd = wnd - 1 return pieces def main(): if os....
def is_valid(cc_num): parts = list(str(cc_num)) parts.reverse() odds = list() for i in range(len(parts)-1,-1,-1): if isEven(i) == False: odds.append(sumDigits(int(parts[i])*2)) evens = list() for i in range(len(parts)-1,-1,-1): if isEven(i) == True: ...
''' @Description: 递归-整数转换为任一进制的字符串 @Version: @Author: biofool2@gmail.com @Date: 2019-01-03 11:53:27 @LastEditTime: 2019-01-03 17:29:19 @LastEditors: Please set LastEditors ''' class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self...
from Tkinter import* import Tkinter as Tk from math import * t, y, n = 0, 0, 1 def nombre(x): global t, n t = t * 10 + x z.set(str(t)) def x(_nombre): nombre(_nombre) def aplu...
def madlib_go(): print("Welcome to MadLibs") print("Please fill in the prompts to complete the spooky Halloween story!") emphasis_adjective = user_input("Enter an emphasis adjective: ") article_of_clothing = user_input("Enter an article of clothing: ") verb_one = user_input("Enter a verb: ")...
""" pgzero - training ground for pygame """ WIDTH = 300 HEIGHT = 300 def get_closer_color(src_color, target_color): """ e.g. is src is (128, 0, 0) and target is (64, 64, 0), will output (127, 1, 0) movin all rgb components closer to target """ result_color = list(src_color) for i in range...
gewicht = int(input("Hoeveel gram weegt het pakje? ")) afstand = int(input("Hoeveel kilometer moet het pakje afleggen? ")) begonnen_gewicht = (gewicht + 19) // 20 begonnen_afstand = (afstand + 9) // 10 prijs = 2 + begonnen_gewicht * 0.4 + begonnen_afstand * 0.3 print("Prijs voor het versturen van het pakje:", prij...
import datetime as dt def string_formatting(): ls = [2019, 9, 20, 12, 30, 20] date = dt.datetime(*ls) print(date) print('year is {0:%Y} month is {0:%B} day is {0:%d}'.format(date)) dict = {'a':1,'b':2} for i ,j in dict.items(): print(i,j) if __name__ == '__main__': string_formattin...
import re def strip_charactor(charactor, strip_char = ''): if strip_char == '': return charactor.strip() else: charactor = charactor.strip() charactorRegex = re.compile(strip_char) return charactorRegex.sub('', charactor) charactor = input("Please input the full charactor: ") s...
"""Equilibrium index""" from itertools import (accumulate) def equilibriumIndices(xs): '''List indices at which the sum of values to the left equals the sum of values to the right.''' def go(xs): '''Left scan from accumulate, right scan derived from left''' ls = list(accumulate(xs)) ...
def numeric(literal): """Return value of numeric literal or None if can't parse a value""" castings = [int, float, complex, lambda s: int(s,2), lambda s: int(s,8), lambda s: int(s,16)] for cast in castings: try: return cast(literal) except ValueError:...
'''Exponentials as generators''' from itertools import count, islice def powers(n): '''A non-finite succession of integers, starting at zero, raised to the nth power.''' def f(x): return pow(x, n) return map(f, count(0)) def main(): '''Taking the difference between two der...
txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$j...
from itertools import product, combinations from random import sample features = [ 'green purple red'.split(), 'one two three'.split(), 'oval diamond squiggle'.split(), 'open striped solid'.split() ] deck = list(product(list(range(3)), repeat=4)) dealt = 9 def printcard(ca...
'''Abundant, deficient and perfect number classifications''' from itertools import accumulate, chain, groupby, product from functools import reduce from math import floor, sqrt from operator import mul def deficientPerfectAbundantCountsUpTo(n): '''Counts of deficient, perfect, and abundant integers in th...
def primes(): for p in [2,3,5,7]: yield p gaps1 = [ 2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8 ] gaps = gaps1 + [ 6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10 ] def wheel_prime_pairs(): yield (11,0); bps = wheel_prime_pairs() p, pi = next(bps); q = p * p ...
def crossp(a, b): '''Cross product of two 3D vectors''' assert len(a) == len(b) == 3, 'For 3D vectors only' a1, a2, a3 = a b1, b2, b3 = b return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) def dotp(a,b): '''Dot product of two eqi-dimensioned vectors''' assert len(a) == len(b), 'Vector siz...
'''Days of the week''' from datetime import date from itertools import islice def xmasIsSunday(y): '''True if Dec 25 in the given year is a Sunday.''' return 6 == date(y, 12, 25).weekday() def main(): '''Years between 2008 and 2121 with 25 Dec on a Sunday''' xs = list(filter( xmasIsSunda...
import fileinput def longer(a, b): try: b[len(a)-1] return False except: return True longest, lines = '', '' for x in fileinput.input(): if longer(x, longest): lines, longest = x, x elif not longer(longest, x): lines += x print(lines, end='')
COLS = 9 def CX(x, ran): while True: x += 2 * next(ran) yield x x += 1 yield x ran = [] d = -1 for V in CX(1,iter(list(range(0,COLS,2)) + list(range(COLS-1-COLS%2,0,-2)))): ran.append(iter(range(V, V+COLS*d, d))) d *= -1 for x in range(0,COLS): for y in range(x, x+COLS): print(repr(next(ran[...
'''Range extraction''' from functools import reduce def rangeFormat(xs): '''Range-formatted display string for a list of integers. ''' return ','.join([ rangeString(x) for x in splitBy(lambda a, b: 1 < b - a)(xs) ]) def rangeString(xs): '''Start and end of xs delimited ...
def accumulator(sum): def f(n): nonlocal sum sum += n return sum return f x = accumulator(1) x(5) print(accumulator(3)) print(x(2.3))
def is_numeric(literal): """Return whether a literal can be parsed as a numeric value""" castings = [int, float, complex, lambda s: int(s,2), lambda s: int(s,8), lambda s: int(s,16)] for cast in castings: try: cast(literal) return True exc...
def Dijkstra(Graph, source): ''' + +---+---+ | 0 1 2 | +---+ + + | 3 4 | 5 +---+---+---+ >>> graph = ( # or ones on the diagonal ... (0,1,0,0,0,0,), ... (1,0,1,0,1,0,), ... (0,1,0,0,0,1,), ... (0,0,...
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, ...