text
stringlengths
5
121k
from classes.decorators.base_decorator import BaseDecorator class PrintToConsoleDecorator(BaseDecorator): def __init__(self, shape): super().__init__(shape) def get_parameters(self): figure_type, perimeter, area = super().get_parameters() print("This parameters was pri...
def read_file(file): lines = file.read().splitlines() return lines[0], lines[1] def string_to_long(str_num, base_power=3): lng_num = [] dig_count = 0 curr_num = "" for i in range(len(str_num)-1, -1, -1): dig_count += 1 curr_num += str_num[i] if dig_count == base_powe...
def named(name, age): print(name, age) bob = {"name": "Bob", "age": 25} named(**bob) def test(**kwargs): print(kwargs) test(name="bob", age=25)
import numpy as np import pandas as pd import matplotlib.pyplot as plt def train_data(train, data): weights = [-.2, .54] for run in range(100): sum_error = 0.00 for row in train: prediction = predict(row, weights) sum_error += (row[-1] - prediction...
print("Menghitung Luas Segitiga") a=float(input("Masukkan Alas : ")) t=float(input("Masukkan Tinggi : ")) luas=0.5*a*t print("Luas Segitiga= "+ str(luas))
s1 = str(input("Dati un cuvant :")) s2 = str(input("Dati un cuvant :")) s3 = str(input("Dati un cuvant :")) s4 = str(input("Dati un cuvant :")) cuvant="" if (len(s1)>2 and len(s2)>2 and len(s3)>2 and len(s4)>2): cuvant+=s1[0:2]+s2[0]+s3[0:3]+s4[0:len(s4)//2] else: print("Dati un cuvant, cu mai mult deca...
import operator import itertools def sub(a, b): assert len(a) == len(b) return list(itertools.starmap(operator.sub, zip(a, b))) def sub_square(a, b): assert len(a) == len(b) return itertools.starmap(operator.pow, zip(sub(a, b), [2]*len(a))) def mul(a, b): assert len(a) == len(b)...
""" 具名元组 """ from collections import namedtuple Product = namedtuple('Product', ('name', 'price', 'city')) p = Product('手机', '5000', 'sh') print(p.name, p.price) print(p[0]) print(Product._fields) params = ('手机', '5000', 'sh') print(Product._make(params)) for k, v in p._asdict().items(): print(k, v)
import math if __name__ == '__main__': n = int(input()) output = int(0) for i in range(1,n+1): output *= 10 * (10 ** math.floor(math.log(i, 10))) output += i print(output)
import random """ Quiz game throwing random questions at the user, continue the game if user choses and display score at the end """ questionset = { 'Which animal lives in the North pole? : ': 'polar bear', 'Which is the largest animal? : ': 'elephant', 'Which is the fastest land animal? ': 'cheetah' } ...
import unittest from fizzbuzz import solve_fizzbuzz class TestFizzBuzz(unittest.TestCase): def test_multiple_of_5(self): list_zz = solve_fizzbuzz(5) expected = "buzz" self.assertEqual(list_zz,expected) def test_solve_fizzbuzz_zero(self): with self.assertRaises(ValueE...
def encrypt(text, rot): l = len(text) i = 0 newText = '' while i < l: c = text[i] newText = newText + rotate_character(c, rot) i = i + 1 return(newText) def alphabet_position(letter): bet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s"...
def hasPath(matrix, rows, cols, path): for i, s in enumerate(matrix): if s==path[0] and visit([(i//cols, i%cols)], matrix, rows, cols, path): return True return False def visit(ans, matrix, rows, cols, path): if len(ans)==len(path): return True i,j = ans[-1] nex = [...
def HeapAdjust(heap,length,i): min = i if 2*i+1 < length and heap[2*i+1] > heap[min]: min = 2*i+1 if 2*i+2 < length and heap[2*i+2] > heap[min]: min = 2*i+2 if min != i: heap[i],heap[min] = heap[min],heap[i] HeapAdjust(heap,length,min) def HeapSort(heap): fo...
def bubble_sort(lists): if len(lists) <= 1: return lists for i in range(0, len(lists)): for j in range(i + 1, len(lists)): if lists[i] > lists[j]: lists[j], lists[i] = lists[i], lists[j] return lists if __name__ == "__main__": lists = [9, 8, 7, 6, 5] pri...
def Pow(base,exponent): if exponent == 0: return 1 elif exponent > 0: ans = base for i in range(exponent-1): ans *= base return ans else: if base == 0: return 'Error!' else: ans = base for i in range(-exponent-1): ans *= base return 1/ans def Pow2(base,exponent): if exponent == ...
def JumpFloor(number): count = [1,2] if number > 2: for i in range(2,number): count.append(count[i-1]+count[i-2]) return count[number-1] def JumpFloorII(number): count = [1, 2] for i in range(2, number): count.append(2*count[i-1]) return count[number-1] def Jum...
class ListNode: def __init__(self,value): self.value = value self.next = None def ReverseList(root): pNode,parent,pHead = root,None,None while pNode: child = pNode.next if child is None: pHead = pNode pNode.next = parent parent = pNode pNode = child return pHead def ReverseList2(root): if ro...
a_list=list(range(1000,2001)) result_list=[] for item in a_list: if item%7 == 0 and item%5 != 0: result_list.append(item) print(result_list)
import nltk def count_words(text): d={} for i in text: if not i in d: d[i] = text.count(i) return d def fraction_dist(numerator_dist,denominator_dist): temp_dict={} for key in denominator_dist.keys(): if key in numerator_dist: temp_dict[key]=numerator_dist[key...
print(5 % 2) print(12%15) print(0%7) print((14+51)%24) current_time_str = input("What is the time now?") current_time_int = int(current_time_str) waiting_time_str = input("How long do you have to wait?") waiting_time_int = int(waiting_time_str) time_after = (current_time_int+waiting_time_int) % 24 print("After the ...
import random list1 = random.sample(range(1,15), 10) list2 = random.sample(range(1,30), 8) common = [i for i in list1 if i in list2] print(f'list1 = {list1} \nlist2 = {list2}') print(common)
def board_draw(height, width): top = "┌" + "┬".join(["─"*4]*width) + "┐\n" bottom = "└" + "┴".join(["─"*4]*width) + "┘" middle = "├" + "┼".join(["─"*4]*width) + "┤\n" print(top + middle.join( "│" + "│".join(' '.format(x * width + y + 1) ...
lst1 = [] lst2 = [] num1 = int(input("length of list 1: ")) for i in range(num1): element1 = int(input("Element for list 1: ")) lst1.append(element1) num2 = int(input("length of list 2: ")) for j in range(num2): element2 = int(input("Element for list 2: ")) lst2.append(element2) if num1 < num2...
import PyPDF2 from os import listdir def ask_path(): path = input("Introduce CARPETA para pasar TODOS los documentos PDF a TXT:\n") return path def get_files_in_path(path): pdf_files = [] for file in listdir(path): if file.endswith("pdf"): pdf_files.append(file) ...
class Node: def __init__(self,key,value): self.key = key self.value = value class myhash(): def __init__(self): self.store = [None for _ in range(16)] self.size = 16 def get(self,key): index = self._hash(key) if self.store[index] is None: return None else: found = False ...
import multiprocessing def add(balance): for i in range(10000): balance.value += 1 def withdraw(balance): for i in range(10000): balance.value -= 1 balance = multiprocessing.Value('i',500) print("Starting balance is: {}".format(balance.value)) p1 = multiprocessing.Process(target=add,args=(balance,)) p...
arr = [1,2,3,4,5,6,7] max1=max2=-1 for i in range(0,len(arr)): if arr[i] > max1: max2 = max1 max1 = arr[i] elif arr[i] < max1 and arr[i] > max2 and arr[i] != max2: max2 = arr[i] print(max2)
class my: def __init__(self): self.l = [1,2,3,4,5] self.index = -1 def __iter__(self): return self def __next__(self): self.index+=1 if self.index < len(self.l): return self.l[self.index] else: raise StopIteration o = my() """ NOTE: "for" will automatically/implicitly call ...
A = [[1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 2, 4, 4, 0], [0, 0, 0, 2, 0, 0], [0, 0, 1, 2, 4, 0]] def calculate_hour_glass(A,row_start,row_end,col_start,col_end): t_sum = 0 row=1 for l in range(row_start,row_end): col=1 for m in range(col_start,col_end...
''' @File : 643. 子数组最大平均数 I.py @Contact : muyisanshuiliang@hotmail.com @Modify Time @Author @Version ------------ ------- -------- 2021/2/4 12:06 muyisanshuiliang 3.9 @Desciption: --------------------------------------------------------------- 给定 n 个...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: pre = ListNode() pre.next = temp_head = head while temp_head and temp_head.next : pre.next = temp_h...
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ if not nums: return False length = len(nums) if length == 1: return False nums_dict = {} for item in nums: ...
from typing import List class Solution: def sortByBits(self, arr: List[int]) -> List[int]: def count_one(num) -> [int, int]: count = 0 temp = num if num == 0: return [num, count] while True: num ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: sentinel = ListNode(0) sentinel.next = head prev, curr = sentinel, head while curr: if curr.val == ...
import functools from typing import List class Solution: def largestNumber(self, nums: List[int]) -> str: if not nums: return '' class LargerNumKey(str): def sort_key(a, b): return a + b > b + a ...
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if not intervals or len(intervals) == 1: return intervals intervals.sort(key=lambda item: item[0]) result = [] pre = None max_index = len(intervals) ...
class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. """ ...
from functools import reduce print("===============函数式编程===============") print("===============1、map函数===============") def power(x): return x * x list_number = [1, 2, 3, 4, 5] iterator = map(power, list_number) list_number = list(iterator) print(list_number) print(list(map(str, list_number))) print("=...
from typing import List class Solution: def largestPerimeter(self, A: List[int]) -> int: if not A: return 0 A.sort() r_inx = len(A) - 3 while r_inx >= 0: if A[r_inx] + A[r_inx + 1] > A[r_inx + 2]: return sum(A[r_inx:r_inx + 3]) el...
import sys import time class Binary_Search_Tree: """Base Class representing a Binary Search Tree Structure""" class _BST_Node: """Private class for storing linked nodes with values and references to their siblings""" def __init__(self, value): """Node Constructor with...
import math import random from pymunk import Vec2d def lerp(v1: float, v2: float, u: float) -> float: """linearly interpolate between two values""" return v1 + ((v2 - v1) * u) def vec_lerp(v1: Vec2d, v2: Vec2d, u: float) -> Vec2d: return Vec2d( lerp(v1.x, v2.x, u), lerp(v1.y, v2.y, u) ...
""" Class with game's information """ about = """\ SuDoKu is a simple Sudoku game, developed by Martyna Śpiewak in Python. """ keys = [ ('Up arrow', 'Move cursor up'), ('Down arrow', 'Move cursor down '), ('Right arrow', 'Move cursor right'), ('Left arrow', 'Move cursor left'), ('Backspace/Delet...
def input_int(a, b): x = 0 while x != "": x = input() if x.isdigit(): if int(x) >= a and int(x) <= b: return x print("You should input a number between " + str(a) + " and " + str(b) + "!") print("Try once more or input empty line to cancel input check....
player_inventory = {'gold coin': 42, 'rope': 1} dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def displayInventory(some_dict): items_total = 0 print('Inventory:') for k, v in some_dict.items(): print(v, k) items_total += v print('Total nu...
import random, logging logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') logging.debug('Start of program') guess = '' while guess not in ('heads', 'tails'): print('Guess the coin toss! Enter heads or tails: ') guess = input() logging.debug('guess = ' ...
import numpy as np def strassen(A, B): if type(A) is not np.ndarray or type(B) is not np.ndarray: raise Exception('Inputs are not numpy ndarrays') else: print("ok")
""" Created on Tue Jan 14 10:26:32 2020 @author: natnem """ class Stack(object): def __init__(self, stacksize): self.stacksize = stacksize self.array = [0]*stacksize self.size = 0 def isFull(self): return self.size == self.stacksize def isEmpty(self): ret...
""" Created on Tue Jun 9 23:41:59 2020 @author: natnem """ mytext = 'helo there this' words = mytext.split(" ") n = len(words) memo = {} parent = {} def textjust(i): if i >= n: return 0 elif i in memo: return memo[i] else: bad = float("inf") for j in range(i+1, n+1): ...
""" Created on Mon Apr 27 13:50:34 2020 @author: natnem """ parent = {} def dfsvisit(adj, s): if s in adj.keys(): for v in adj[s]: if v not in parent: parent[v] = s dfsvisi...
""" Created on Wed Dec 18 14:42:39 2019 @author: natnem """ import math D1 = ["the" , "cat" , "was" , "outside"] D2 = ["the" , "cat" , "is" , "outside"] def CountFreq(l): count = {} for word in l: if word in count: count[word] += 1 else: count[word] = 1 return co...
""" Created on Mon Jan 27 13:26:06 2020 @author: natnem """ """ IMPLMENTATION OF AN UNSORTED DOUBLY LINKED LIST""" class Node(object): def __init__(self, key): self.key = key self.next = None self.prev = None def getPrev(self): return self.prev def getNext(self): r...
def is_armstrong_number(number): number = str(number) armstrong = 0 for item in number: armstrong += int(item)**len(number) return(armstrong == int(number))
import sys assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') color = input("What is my favorite color? ") if (color.lower().strip() == 'red'): print('Correct!') else: print('Sorry, try again.')
import math radius=input("Verdien til radius?\n>") radius=float(radius) diameter= 2*radius areal=math.pi*radius*radius omkrets=2*math.pi*radius print("\nDiameter: {0: .2f}".format(diameter)) print("Areal: {0: .2f}".format(areal)) print("Omkrets: {0: .2f}".format(omkrets))
def mayormenor(lista): k=lista[0] for x in range(len(lista)): if lista[x]>k: k=lista[x] z=lista[0] for x in range(len(lista)): if lista[x]<z: z=lista[x] print("El elemento mayor es", k," y el elemento menor es ",z) lista=[] for x i...
n1 = 5 n2 = 20 resultado = (n1 + n2) print("La suma es ", + resultado) n1 = 5 n2 = 20 resultado = (n1 - n2) print("La resta es ", + resultado) n1 = 5 n2 = 20 resultado = (n1 / n2) print("La division es ", + resultado) n1 = 5 n2 = 20 resultado = (n1 * n2) print("La multiplicacion es ", + res...
def carga(): responde="si" productos={} while responde=="si": codigo=input("ingrese codigo de producto: ") desc=input("ingrese nombre producto: ") prec=int(input("ingrese precio producto: ")) stock=int(input("ingrese cantidad en stock: ")) productos[codigo]=...
n1=float(input("ingresar n1: ")) n2=float(input("ingresar n2: ")) if n1>n2: print("n1 es mayor a n2") else: print("n2 es mayor a n1")
numero1 = int(input("Introduce el primer numero: ")) numero2 = int(input("Introudce el segundo numero: ")) for n in range(numero1, numero2+1): if n % 2 == 0: print(n)
vd=int(input("ingrese un valor: ")) cp=int(input("ingrese un valor: ")) td=cp/vd print("El total dolar es :",td)
def carga(): sueldo=[] for x in range(3): f=int(input("Ingrese valor: ")) sueldo.append(f) return sueldo def impsueldo(sueldo): print("lista de sueldos: ") for x in range(len(sueldo)): print(sueldo[x]) def mayor40k(sueldo): tot=0 for x in...
class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: self.tree_list = [] self.inOrder(root) if k <= 0: return None print(self.tree_list) return self.tree_list[k-1] def inOrder(self, root): if not root: ...
a = 100 b = str(a) print(a) print(type(a)) print(b) print(type(b)) a = 100 c = int(b) print(c) print(type(c))
import csv def leer_camion(nombre_archivo): camion = [] with open(nombre_archivo) as file: rows = csv.reader(file) headers = next(rows) for row in rows: record = dict(zip(headers, row)) cajon = { 'nombre': record['nombre'], 'cajones...
words = input().split() for word in words: count = 0 for w in words: if w == word: count += 1 print(word, count)
class ItemToPurchase: def __init__(self): self.item_name = "none" self.item_price = 0 self.item_quantity = 0 def print_item_cost(self): print(self.item_name + " " + str(self.item_quantity) + " @ $" + str(self.item_price)...
''' Implementation of a basic RL environment for continuous spaces. Includes three test problems which were used in generating the figures. ''' import numpy as np import gym from gym import spaces import math from .. import env_configs '''An ambulance environment over [0,1]. An agent interacts through the environme...
import random def ask_number (min, max): number_int = 0 while number_int == 0: number_str = input(f"What is the magic number ?\nType a number between {min} and {max} : ") try: number_int = int(number_str) except: print("INPUT ERROR: You need to type a valid numbe...
import json import urllib import urllib.request,urllib.parse,urllib.error serviceurl = "http://py4e-data.dr-chuck.net/json?" while True: address = input('Enter Location') if len(address) < 1: break url = serviceurl + urllib.parse.urlencode({'key': 42, 'address': address}) print('Retrieving...
def computepay(h,r): if h > 40: total = (((1.5 * r) * (h-40)) + (40 * r)) else: total = h * r return total hours = input('Hours') h = float(hours) rate = input('Rate') r = float(rate) total = computepay(h,r) print ("Pay",total)
import unittest from .. import examples class RecursionExamplesTestCase(unittest.TestCase): def test_should_return_true_if_value_is_found(self): sequence = [1, 4, 6, 7, 8, 9, 10] self.assertTrue(examples.in_list(sequence, 9)) sequence = [1, 4, 6, 7, 8, 9, 10, 11] self.assertTrue(e...
from random import randrange def is_multiple(n, m): return n % m == 0 def is_even(n): while n >= 2: n -= 2 return False if n == 1 else True def minmax(data): min_item = max_item = data[0] for item in data: if item < min_item: min_item = item if item > max_ite...
while True: num = int(input('Quer ver a tabuada de qual valor: ')) if num < 0: break print('-'*20) for i in range(1, 11): print(f'{num} x {i:>2} = {num * i}') print('-'*20) continua = 's' while continua in 'sS': continua = str(input('Deseja continua? [S/N] ')).strip()...
""" The purpose of the blocker is to substitute TYPE_ENCLOSED tokens with their appropriate TYPE_BLOCK_START/TYPE_BLOCK_END pairs. It also checks that every block token is properly paired. """ from .. constants import * from .. error_format import error_format class Blocker(object): @staticmethod def process(tokenl...
""" The purpose of the line blocker is to block off sections of code that are their own line. This prevents the shunter from reordering sections of code that must remain in a particular order. """ from tokenizer import Token from .. constants import * class LineBlocker(object): @staticmethod def process(tokenlist)...
def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements a = 0 b = 0 for i in range( 0, elements ): if a >= len(arrA): merged_arr[i] = arrB[b] b += 1 elif b >= len(arrB): merged_arr[i] = arrA[a] ...
value = int(input('Input a value: ')) if type(value) == str: print(value, 'is a string') elif type(value) == int: print(value, 'is a integer') elif type(value) == list: print(value, 'is a list') else: print(value, 'is none')
my_list = [[1,2,3], [4,5,6], [7,8,9]] for lists in my_list: for items in lists: print(items)
n1 = int(input('Enter first number: ')) n2 = int(input('Enter second number: ')) op = input('enter operation to perform: ') if op == '+': print(n1+n2) if op == '-': print(n1-n2) if op == '*': print(n1*n2) if op == '/': print(n1/n2)
def fun(n): if n>0: fun(n//2) print(n%2) n=int(input()) fun(n)
from LCS import LCS arquivo = open("entrada.txt", "r") pept1 = LCS() pept2 = LCS() resultado = None for aux in arquivo: try: if aux[0] == '>': continue else: pept1.string = aux if pept2.string == None: pept2.string = pept1.string ...
import random from fuzzywuzzy import fuzz frenchList = [['yes','oui',0],['no','non',0],['hello','bonjour',0],['not','pas',0],['you','vous',0],['in','dans',0],['dictionary', 'dictionnaire', 0]] orderedFrenchList = [] def wordFeed(): index = random.randint(0,len(frenchList)-1) global word word = ...
from math import sqrt def isPrime(n): for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True for i in range(100001): if isPrime(i): print(i)
''' -Explain why you need multithreading to solve this problem. Put this in a comment at the top of your server code- For this code you need to have a multithreaded server so you are be able to have two connections that are able to send data to the one server. The two parts are running simultaneously for data to...
import sys def solution(n): roman_dict = {1:"I",5:"V",10:"X",50:"L",100:"C",500:"D",1000:"M"} x = str(n) roman_value = "" for num in reversed(range(len(x))): postion = pow(10,num) res = int(n/postion) res = res*postion if res==0: continue n = i...
def star(n): return "* "*n for i in range(6): for j in range(6): if i<=j: print(star(j)+" ") break for i in range(6): for j in range(6): if j<=i: print(star(5-i)) break
n=int(input("enter number : ")) i=1 sum=0 while i<=n: sum=sum+i i+=1 print(sum)
with open('somefile.txt','wt') as f: f.write('I Love You') f = open('somefile.txt','rt') data = f.read() f.close() with open('D:\python\cookbook\somefile.txt','wt') as f: print('Hello world!',file=f) print('ACME',50,91.5) print('ACME',50,91.5, sep='') print('ACME',50,91.5, sep=',') print('ACME',50,91.5, sep='',en...
from collections import Counter words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] word_counters = Counter(word...
__author__ = awakenedhaki from typing import List def anagrams(word: str, words: List[str]) -> List[str]: ''' Returns all anagrams of a word in a list of words. :param word: str :param words: List of str :return: Returns a list of words that are anagrams ''' word: str = sorted(word) ...
n = int(input()) count_7_decimal = 0 count_7_octal = 0 count = n; text = "" common_od = set() for i in range(1,n+1): text = str(i); if '7' in text: common_od.add(i) text = "" for i in range(1,n+1): text = str(oct(int(i))); if '7' in text: common_od.add(i) length_of_co...
florence = 1500 staycation = 1400 camping = 240 visitingParents = 100 kayakinginLake = 100 print("Oh, you are going on a vacation? Lucky you!") print("So we need to ask how much money you have to spend on this vacation") totalMoney = int(input("What disposable income do you have for this trip? ")) print("Ok,...
usersNum = ["First Entry", "Second Entry", "Third Entry"] genNum = ['Empty', 'Empty', 'Empty'] def triangle(): fourth = '({}) [{}] ({})'.format(genNum[0], usersNum[1], genNum[2]) second = '[{}]'.format(usersNum[2]).center(int(len(fourth)/2), ' ') third = '[{}]'.format(usersNum[0]).center...
def heightTree(root): if root is None: return 0 leftH = heightTree(root.left) rightH = heightTree(root.right) H = max(leftH,rightH) return H+1 def BalanceTree(root): if root is None: return True leftH = heightTree(root.left) rightH = heightTree(root.right) ...
class BinaryTreeNode: def __init__(self,data): self.left = None self.data = data self.right = None def FullTreeInput(): rootdata = int(input()) if rootdata==-1: return None root = BinaryTreeNode(rootdata) leftChild = FullTreeInput() rightChild = FullTreeInp...
class BinaryTreeNode: def __init__(self,data): self.left = None self.data = data self.right = None import queue def levelInput(): rootData = int(input("Enter the root node data: ")) if rootData ==-1: return None root = BinaryTreeNode(rootData) q = queue.Queue()...
arr = [] row = 4 columns = 52 for i in range(row): col = [] for j in range(columns): col.append(-1) arr.append(col) def knapsackm(weights,profit,capacity,n,arr): if n==0 or capacity == 0: return 0 if arr[n][capacity] != -1: return arr[n][capacity] if weights[n-1] <= capacity: ...
def testMult(num, mux): return num * mux def sum_digits(n): s = 0 while n: s += n % 10 n //= 10 return s potato = True num = 125875 counter = 0 while potato: if sum_digits(num) == sum_digits(testMult(num, 2)): if sum_digits(num) == sum_digits(testMult(num, 3)): if sum_digits(num) == sum_digits(testMul...
import time def primeFind(number): oldnum = number factor = 1 while number > 1: factor += 1 if number % factor == 0: if 1 < factor < oldnum: print("Returned False") return False number //= factor return True def count(numa, numb...