text
stringlengths
37
1.41M
def check(question): qtype = question.split(' ', 1)[0] qtype = qtype.lower() if qtype == "who" or qtype == "when": return qtype else: return "not valid"
import pdb class BT(): def __init__(self): self.root = None self.size = 0 def add(self, key, node): # pdb.set_trace() if node is None: node = self.root if self.root is None: self.root = TreeNode(key) return if key <= node.va...
def karatsuba(x, y): if x < 10 or y < 10: return x*y #making the two numbers strings here str_x = str(x) str_y = str(y) #finding the mid point for each number here n = max(len(str(x)), len(str(y))) n_2 = int(n / 2) print("*********") print("x: ", x) print("y: ", y) ...
import hashlib import unittest class HashTable(): ''' A class describing a hash table. Maps strings onto a hash table ''' def __init__(self, size): self._hashList = [0] * size self.size = size self._entries = 0 @property def hashList(self): return self._hashLis...
def rotated(arr, elemToFind): for i in range(len(arr)): # if arr[i+1] > arr[i] and arr[i] != elemToFind: # pass # else: # #found pivot point. Element has to be to the right # return binarySearch(arr, i, elemToFind) if arr[i] == elemToFind: retu...
#! /usr/bin/env python3 import Orienation from Orientation class Puzzle(): """ A class to store the puzzle. This will store the list of all pieces Attributes: pieces: List of pieces solution: NxN dimensional array (rows x columns) """ def __init__(self, pieces, size): self.pieces =...
import pdb def equal(chocolates, ctr, arr): # pdb.set_trace() if checkEqual(chocolates) <= 1: return ctr min_value = min(chocolates) max_value = max(chocolates) max_index = chocolates.index(max_value) result = 0 for num in [n for n in arr if n <= (max_value - min_value)]: ch...
def bin2str(dec): value = int(str(dec - int(dec))[2:]) if value / (2**32) >= 2: raise ValueError("Can't fit inside 32 bits") binList = [0] * 33 initialDivisor = 32 while value > 1: newValue = value % (2 ** initialDivisor) if newValue < value: value = newValue ...
import unittest from BST import TreeNode from BST import BinarySearchTree import pdb class AVLNode(TreeNode): ''' A class for the AVL tree node. Inherits from TreeNode class ''' def __init__(self, key, value, left=None, right=None, parent=None, balanceFactor=0): super().__init__(key, value, lef...
def drawLine(screen, width, x1, x2, y): rowIndex = y * width #number of indexes per row = width, so finding correct row if x1 < 0 or x2 > 64: raise ValueError("Wrong indexes specified") ctrForPixel = 0 start = round(x1 / 8) #pixel number at which to start drawing stop = round(x2 / 8) #pixel ...
#! /usr/bin/env python3 from Playlist import Playlist class Jukebox(): """ Main jukebox class that will be the brain of the operations Attributes: currentSong: Current song playing songQueue: Queue of songs addSong: add song to queue removeSong: remove song from queue skipSong: skip cur...
import math class Vec2: global_id = 0 def __init__(self, x, y): self.x = x self.y = y self.variable_id = Vec2.global_id + 1 Vec2.global_id += 1 def length(self): """calculates the length of a vector given origin :returns distance:- euclidean distan...
# create a function that squares elements def square(num): return num * num # list initialization my_list = [i for i in range(10)] my_list_squared = [square(i) for i in my_list] print('My squared List:-', my_list_squared) def cal_sum(some_list): if len(some_list) == 0: return 0 else: ret...
for i in range(12): i=i+1 for x in range(12): x = x+1 y = i*x print(str(i) + " x " + str(x) + " = " + str(y)) print("--------------------------") for val in "hello": if val == "l": continue print(val)
class Animal(): def eat(self): print("Eating Eating!") class Cat(Animal): __catName = "" def setName(self,text): self.catName = text print("Setting new Cat name =",self.catName) def eat(self): print("Meow !!", self.catName) cat1 = Cat() cat1.setName("MMMMM") cat1.eat()...
height = int(input("ความสูงของพีรามิด : ")) for i in range(height): space = height - i - 1 i=2*i+1 print(" "*space + "*"*i) # " * " แถวที่ 0 ว่าง 3 * 1 # " *** " แถวที่ 1 ว่าง 2 * 3 # " ***** " แถวที่ 2 ว่าง 1 * 5 # "*******" แถวที่ 3 ว่าง 0 * 7
# Enter your code here. Read input from STDIN. Print output to STDOUT def UpdateCandiesEndToStart(candies, start, end): candies[end] = 1 for i in range(end-1, start, -1): candies[i] = candies[i+1] + 1 candies[start] = max(candies[start], (candies[start+1] + 1)) def UpdateCandiesStartToEnd(candies...
# Ways to declare a list li1 = list() li2 = ["3", 1, 2, "3", "four"] # Operations on a list (adding, deleting, popping, length, getting item at index) li2.append(9) print(li2) li2.remove("3") print(li2) li2.pop(1) print(li2) print(len(li2), li2[2]) # Ways to declare a tuple tp1 = tuple() tp2 = (1, 2, 3, 4) # Some...
#logical operator a = 3 b = 7 c = a and b print(c) #bitwise operator a = 7 b = 3 c = a & b print(c) #neg op i = 8 bitneg = ~i print(bitneg) #neg op i = 10 logneg = not i print(logneg)
import unittest from limbic.utils.nlp import get_negated_words TEST_CASES = { "I don't like this sentence": ['like'], "I won't hate you.": ['hate'], 'I have not created this.': ['created'], "You won't believe me.": ['believe'], 'Even John could not guess.': ['guess'], "no that's not quite it"...
# challenge lesson # lesson one; create three dictionaries with given names and keys: # what's the score; add homework quiz and test scores to dictionary: lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alic...
one = 0b1 two = 0b10 three = 0b11 four = 0b100 five = 0b101 six = 0b110 seven = 0b111 eight = 0b1000 nine = 0b1001 ten = 0b1010 eleven = 0b1011 twelve = 0b1100 print(one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve) # print the binary version of a number: print(bin(1)) # print int("1",2) # ...
################################################################################################################################## # Project Name: Connect Four # Developers: Ariel Khatchatourian, Jacob Croes, Ben Winston, Greg Barton # Date Finished: 5/2/2017 # Objective: Create a c...
""" In Week 3 We created some functions that handled the job of creating layout joints. The goal was to incorporate lists, variables, functions, and other basic Python concepts.""" import maya.cmds as mc """ Create a list of items that defines the base name and starting position of our joints. """ jointInfo=['arm__...
#!/usr/bin/env python # -*- coding: utf-8 -*- from sklearn import linear_model reg = linear_model.LinearRegression() train_x_set = [] train_y_set = [] f, n, t = 0, 0, 0 line = [int(x) for x in input().split()] f = line[0] n = line[1] for i in range(n): line = [float(x) for x in input().split()] train_x_set.app...
""" Settings class There are stored all settings to screen, players, ball, static and dynamic settings Static settings - is settings, who don't change at the time of game Dynamic - is change at the time of game """ from random import randint, seed class Settings: de...
cars=100 space_in_a_car=4 drivers = 30 passengers=90 cars_not_driven=cars-drivers cars_driven= drivers carpool_capacity = cars_driven*space_in_a_car average_passenger_per_car = passengers/cars_driven print "There are",cars,"cars available" print "There are only", drivers,"drivers available." print "There wi...
#!/usr/bin/env python3 #-*- coding:utf-8 -*- import matplotlib.pyplot as plt x_input = list(range(1001)) y_input = [x**2 for x in x_input] plt.scatter(x_input,y_input,c=y_input,cmap=plt.cm.Reds,edgecolor='none',s=30) plt.title("Square Number",fontsize=24) plt.xlabel("Value",fontsize=14) plt.ylabel("Square of Value",...
""" This algo. starts by picking up a pivot pivot element. The pivot element is one which has all elements less than in towards its left and all the elements greater than it towards its right. The partition() function does this job. The partition however does not implement sorting. Once, pivot is found, we need to sort...
# coding: utf-8 # 解决方案来自http://tieba.baidu.com/p/1242856365 from ctypes import * ''' 处理字符串过程中若遇到'\0'一般认为是结尾,python3 改为默认宽字符处理字符, 比如,一般情况下'a'是一个字节存储0x61,而宽字节用两个字节表示为0x0061, 若存储时倒叙 则为0x6100,printf函数默认单字节处理,所以只打印一个字符遇到'\0'后认为结束。 ''' '''Py3K使用的是Unicode编码,而printf不支持该编码,所以需要转码。''' # 使用wprintf宽字符显示 msvcrt = cdll.msvcrt mess...
# 这是Python2016/Python实战::四周实现爬虫系统第一周课时13的学习 from bs4 import BeautifulSoup from urllib import request ''' https://www.lagou.com/zhaopin/Python/?labelWords=label https://www.lagou.com/zhaopin/Python/2/?filterOption=2 https://www.lagou.com/zhaopin/Python/2/?filterOption=3 https://www.lagou.com/zhaopin/Python/3/?filterOp...
def bench_dict_row_vs_col(): """ Check how long it takes to access atributes when we store them as either List[Dict] or Dict[List]. In other words the strategies to store data are either Row Major: [ {'col_1': <item_0_0>, 'col_2': <item_1_0>, 'col_3': <item_2_0>}, ...
source_text = '22+1 *5*( 10- ( 24))' class Node(): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class Lexer(object): def __init__(self): self.digits = ['0','1','2','3','4','5','6','7','8','9',] #символы,которые есть в алфавите def ...
class Graph(): def __init__(self,vertices): self.V = vertices self.graph = [[0 for column in range(vertices)]for row in range (vertices)] def isSafe(self,v,color,c): for i in range(self.V): if self.graph[v][i] == 1 and color[i]==c: return False ...
def flatten(aList): ''' aList: a list Returns a copy of aList, which is a flattened version of aList ''' return list_flatten(aList) def list_flatten(l, a=None): #check a if a is None: #initialize with empty list a = [] for i in l: if isinstance(i, list): ...
class User(): """this class represents a user""" def __init__(self, user_config): self.name = user_config[0] self.telegram_chat_id = user_config[1]['telegram_chat_id'] self.groups = user_config[1]['groups'] self.cfg = user_config def is_member_of_group(self, groupname): ...
import math, time primes = [] with open('primes.txt', 'r') as filehandle: primes = [int(current_prime.rstrip()) for current_prime in filehandle.readlines()] def prime_check(n): if n in primes: return True i=0 p=primes[i] limit = math.sqrt(n) if primes[-1] < limit: ...
import time start_time = time.time() saved = [] def pentagon_pairs(limit=1000, saved=[]): pentagons = [1] n = 1 while n<limit: pentagons.append(pentagons[-1]+3*n+1) n += 1 #print(pentagons) for p in pentagons: i = pentagons.index(p) for j in range(i): ...
# https://projecteuler.net/problem=134 # We have pairs of consecutive primes and are looking for the smallest number whose # last digits are formed by p1, while also being divisible by p2 # Besides (3, 5) this always exists # Find the sum of that number for every pair of consecutive primes with 5 ≤ p1 ≤ 1000000 ...
""" Given an integer n, write a python function which returns a times table grid for all the integers between 1 and n. The grid should be separated by tabs and new lines. """ def grid(nu): nu=nu+1 output = "" for x in range (1, nu): for y in range (1, nu): output += str(x*y) + '\t' ...
# Created By: @ashutosh.dey21 def print_matrix(length_matrix): for index, row in enumerate(length_matrix): print(row) class Solution(object): def longest_palindromic_subsequence(self, s: str) -> str: length_matrix = [[0 for x in range(len(s))] for y in range(len(s))] for x in range(l...
import math numero = float(input('me diga um numero: ')) print(math.trunc(numero))
from time import sleep def contador(inicio, fim, passo): if passo == 0: passo = 1 elif passo < 0: passo *= -1 print('=' * 40) print(f'Contagem de {inicio} até {fim} de {passo} em {passo}') if inicio > fim: fim2 = fim - 1 passo *= -1 for c in range(inicio, fi...
dinheiro = float(input('me diga quanto dinheiro você tem em reais: ')) print('você possui \033[32m{}R$\033[m reais. '.format(dinheiro)) print('isso é o equivalente a \033[32m{}$\033[m doláres'.format(dinheiro * 3.27)) # o valor do dolár usado nesse programa é de 3,27R$
from random import randint numpc = randint(1, 5) num = int(input('tente adivinhar o numero que estou pensando entre 0 e 5: ')) if numpc == num: print('ESSE É O MESMO NUMERO QUE EU PENSEI!!!') else: print('kkkk errou otário') print('---FIM---')
metros = float(input('me diga um valor em metros: ')) print('seu valor convertido em centimetros será: \033[33m{}\033[mcm'.format(metros*100)) print('seu valor convertido em milimetros será: \033[33m{}\033[mmm'.format(metros*1000))
import math cateto1 = float(input('me diga um valor para um cateto: ')) cateto2 = float(input('me diga um valor para outro cateto')) print('o valor da hipotenusa dos dois catetos será:', end=' ') print('{:.2f}'.format(math.hypot(cateto1, cateto2)))
from random import randint quant = randint(0, 10) valores = list() def maior(num): print('=' * 70) if len(num) == 0: print('Não recebi nenhum valor, não há o que eu possa fazer.') else: print(f'Recebi {len(num)} valores, sendo eles {sorted(num)}, o maior de todos foi {max(num)}') prin...
salario = float(input('me diga seu salário: ')) if salario <= 1250: aumento = salario * 0.15 print('seu salário é de {} com um aumento de 15% será de {}'.format(salario, salario + aumento)) else: aumento = salario * 0.1 print('seu salário é de {} com um aumento de 15% será de {}'.format(salario, salario...
quant = num = cont = soma = maior = menor = med = 0 while cont != 'N': num = int(input('Diga um numero: ')) quant += 1 if maior == 0 and menor == 0: maior = menor = num elif maior < num: maior = num elif menor > num: menor = num cont = input('Deseja continuar? [S/N]: ')....
nome = input('me diga seu nome completo: ') nome = nome.strip() print('seu nome em maiusculas é: {}'.format(nome.upper())) print('seu nome em minusculas é: {}'.format(nome.lower())) espaços = nome.count(' ') print('seu nome possui {} caracteres, desconsiderando os espaços'.format(len(nome) - espaços)) nome = nome.split...
valor = int(input('me diga um numero inteiro: ')) print('você escolheu o numero: \033[1;32m{}\033[m'.format(valor)) print('seu antecesor serà: \033[36m{}\033[m \nseu sucessor será: \033[36m{}\033[m'.format(valor - 1, valor + 1))
num = int(input('me diga um numero inteiro: ')) resto = num % 2 if resto == 1: print('é um numero impar') else: print('é um numero par')
num = int(input('me diga um numero para virar fatorial: ')) control = num fatorial = 1 while control > 0: fatorial *= control control -= 1 print('o fatorial de {} será {}'.format(num, fatorial))
def voto(nasc): """ Função que diz se a pessoa é obrigada a votar :param idade: ano de nascimento da pessoa :return: retorna uma mensagem dizendo se a pessoa é obrigada ou não a votar """ from datetime import date idade = date.today().year - nasc if idade < 16: return f'Com {...
# Given an unsorted integer array, find the first missing positive integer. class Solution: # @param A : list of integers # @return an integer def firstMissingPositive(self, A): n = len(A) ans = [0 for i in range(n + 1)] for i in range(n): if A[i] >= 0 and A[i] <= n: ...
# Find the contiguous subarray within an array (containing at least one number) which has the largest sum. class Solution: # @param A : tuple of integers # @return an integer def maxSubArray(self, A): max_so_far = A[0] curr_max = A[0] size = len(A) for i in range(1, size): curr_max = ma...
# Given a list of non negative integers, arrange them such that they form the largest number. class Solution: def compare_string(self, a, b): str1 = str(a)+str(b) str2 = str(b)+str(a) if str1 > str2: return -1 return 0 # @param A : tuple of integers # @return a...
# -*- coding: utf-8 -*- from df import * from ca import * def cierreAtributos (f, eu): """Usando el conjunto de d.f. y el esquema universal construimos el cierre de atributos de cada atributo. Lo representaremos con un TAD que es un par ordenado, donde la primer componente ('a') es el atributo considerad...
import copy, random class topN: def __init__(self, N): self.max_size = N self.ordered_list = [] def insert_update(self, key, value): pair = (key, value) if len(self.ordered_list) == 0: self.ordered_list.append(pair) return elif value <= self.list...
def run_ttest(): ''' 1. Create new data showing the decline or growth of housing prices between the recession start and the recession bottom. 2. Run a ttest comparing the university town values to the non-university towns values. Return whether the alternative hypothesis (that the two g...
def main(name: str) -> int: """Читает файл с картой лунных каратеров.""" with open(f"{name}", "r") as file: matrix = [] for line in file: x = [int(letter) for letter in line.replace(" ", "").strip()] matrix.append(x) return calculate(matrix) def calculate(matrix...
#HAK MILIK KELOMPOK BAGAS31 - TUGAS BESAR 1 STIMA 2019 #PROGRAM UNTUK FRONT-END II, FILE EKSTERNAL #Library untuk menggunakan sys.argv #Command akan berupa : py namafile.py fileinput.txt fileoutput.txt import sys import backend # Inisialisasi list jawaban listofanswer = ['0','0'] #Assign variabel yang b...
from hashlib import md5 class HashSet: """ An implementation of a hash set. Supports strings, ints, and any class that implements __hash__. Note that all sets contain None. """ def __init__(self): self.array = [None] * 8 self.__size = 0 def add(self, elem): """ ...
def merge_sort(array): """ An implementation of the merge sort algorithm. Recursively sorts arrays by calling merge sort on halves of the array, then merging by comparing the first element of each array, then adding the smaller of the two to a the sorted array. """ # Base Cases ...
import sys sys.path.insert(0, '../data_structures') import os from heaps import tuple_min_heapq from graph import graph def update_node_heap(graph, node_heap, added_node, explored): """ Maintains the node heap invariant by ensuring that the key for a node is always the shortest edge from the explored area...
import sys sys.path.insert(0, '../data_structures') from heaps import maxheapq, minheapq def sum_medians(medians): """ Takes a list of integers; returns a sum of all elements. """ sum_of_medians = 0 for m in medians: sum_of_medians += m return sum_of_medians def median_maintenance(fil...
#!/usr/bin/python3 import os import sys import glob # Returns the indent to the first non-empty string, where the number of commas is the value of the indent def getIndent(line): ind = 0 for str in line: if (str.strip() == ''): ind = ind + 1 else: return ind return -1 # Returns the number of non-empty va...
''' autor : Suchith Kumar To find the longest palindrome substring ''' def Palindrome(): inpp = input("enter string :") # "Catac112211ca" inp=inpp.lower() strln=len(inp) lenth=0 maxlenth=0 begin=0 end=0 for i in range(strln): if i+1 > (strln-1) : break ...
### Build Your Own Connect Four AI from connect_four import * def random_eval(board): return random.randint(-100, 100) def my_evaluate_board(board): if has_won(board, "X"): return float("Inf") else: return -float("Inf") # evaluate a board if neither player has won: have more streaks of two or streaks o...
### K-Means Clustering ## Iris dataset import codecademylib3_seaborn import matplotlib.pyplot as plt import numpy as np from sklearn import datasets from copy import deepcopy import pandas as pd iris = datasets.load_iris() print(iris.data) # Since the datasets in sklearn datasets are used for practice, they come with ...
#fibonacci recursive function # finds the nth term in the fibonacci sequence #but the recursive way!! def fibonacci(n): print("ficonacci: "+str(n)) # base case #if n == 0 or n == 1: #if n<2: if n == 0: return 0 elif n==1: return 1 else: return (fibonacci(n-1)+fibon...
#improved insertion sort def insertion_sort2(my_list): for index in range(1,len(my_list)): value = my_list[index] i = index - 1 while i>=0 and (value < my_list[i]): my_list[i+1] = my_list[i] #shift number in slot i right to slot i+1 my_list[i] = value # shift value l...
def print_numbers(n, k): """Print all numbers that (A) can be formed from the digits of `n` in reverse order and (B) are multiples of `k`. This is essentially Fall 2015 Midterm 2 #3c written to not depend on knowledge of lists. Args: n (int): The number that results must use digits from. k (int): The numb...
# pandas grammar import pandas as pd # series (1-dim) vs dataframe (n-dim) # 1-dim with index series = pd.Series([1, 2, 3], dtype="float64") print(series) print(series.index) series.index = ["일", "이", "삼"] print(series) # point out specific data print(series["일"]) print(series[0]) # delete by index del series["일"] p...
import math import sys def interest(interest): if interest.isdigit(): interest = int(interest) else: interest = float(interest) i = interest / 1200 return i def differentiated_payment(p, n, i): i = interest(i) p = int(p) n = int(n) overpayment_list = [] for m in r...
""" You will be given a sequence of integers – each indicating a cup's capacity. After that you will be given another sequence of integers – a bottle with water in it. Your job is to try to fill up all the cups. Filling is done by picking exactly one bottle at a time. You must start picking from the last received bottl...
""" Create a function called even_odd that can receive different amount of numbers and a command at the end. The command can be "even" or "odd". Filter the numbers depending on the command and return them in a list. Submit only the function in the judge system. """ def even_odd(*args): numbers = args[0:-1] if ...
def take_input(): n = int(input()) matrix = [[int(el) for el in input().split()] for _ in range(n)] return matrix def left_diagonal(matrix): left_sum = 0 for row_index in range(len(matrix)): left_sum += matrix[row_index][row_index] return left_sum def right_diagonal(matrix): rig...
def input_to_list(count): lines = [] for _ in range(count): lines.append(input()) return lines def input_to_list_until_command(end_command): line = [] while True: command = input() if command == end_command: break line.append(command) return line de...
import unittest def SelectionSort(values): if len(values) <= 1: return values length = len(values) for i in range(length): indexToSwap = i smallest = values[i] for j in range(i, length): if values[j] < smallest: indexToSwap = j smallest = values[j]; if i != indexToSw...
i=1 n = int(input("Digite el valor para num: ")) suma_notas=0 while i<=n: nota = float(input("Digite su nota {0}: ".format(i))) suma_notas += nota i+=1 print("El promedio total es: ", suma_notas/n)
# Python Decypher import numpy as np import matplotlib.pyplot as plt import string import random import copy def generate_cipher(dictionary = True): alphabet = list(string.ascii_lowercase) substitution = list(string.ascii_lowercase) random.shuffle(substitution) if not dictionary: return sub...
#!/usr/bin/python with open('content.txt','r') as f: Happy = 0 Sad = 0 Sarcastic = 0 Surprised = 0 Crook = 0 Neutral = 0 Angry = 0 for line in f.readlines(): if line[0] == "A": for word in line.split(): if word == ":)" or word == ":D": Happy = Happy + 1 elif word == ":(" or wor...
# -*- coding: UTF-8 -*- import pandas as pd import numpy as np # panel看做pandas容器,三维结构。其中: # (1)items - axis 0,内部包含了dataframe # (2)major_axis - axis 1,每个dataframe中的索引行 # (3)minor_axis - axis 2,每个dataframe中的列, # 但是之后会弃用,基于多索引方式。 p = pd.Panel(np.arange(24).reshape(4,3,2), items=list('abcd'), majo...
class robots: def __init__(self,vertices,max_robot,adjacent_lst,weight,hotels): self.path=[] self.orders_remaining=[] self.order_status={} self.count_placed_together=0 self.dist={} self.count={} self.max_robots=max_robot self.vertices=vertices self.possible={} self.robot_to_be_sent=1 self.adjac...
import numpy as np def grayscale_filter(image): """ Applies a grayscale filter to an image using numpy Args: image (int[:,:,3]): The image (3d numpy array) to apply filter to Returns: int[:,:,3]: The new image in a 3d numpy array """ weights = [0.07, 0.72, 0.21] grayscale = ...
from itertools import * import string import re charset = string.ascii_letters + string.digits for a in product(charset, repeat=4): if len(a) < -6: continue b = "" for char in a: b += char checks1 = [ bool(re.match(r"^(?:.{1}[13579]{1})*$", b)), # Check that there is at least...
import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) input1=16 GPIO.setup(input1,GPIO.OUT) while True: h=input("open or close") if h=="o": GPIO.output(input1,True) print("o") elif h=="c": GPIO.output(input1,False) print("c") else: print("h...
from organize_menu import print_bar class Room: def __init__(self, room_id, room_no, floor, beds, available): self.room_id = room_id self.room_no = room_no self.floor = floor self.beds = beds self.available = available def print_all(self): print(str...
"""Play Phase 10 with 2 player""" # import modules import itertools, random, operator def create_deck (): # make a deck of cards deck = list(itertools.product(range(1,12),['Red','Red','Blue','Blue','Yellow','Yellow','Green','Green'])) # shuffle the cards random.shuffle(deck) return deck def de...
def interest(principal, interest, years): for period in range(years): total = float(principal) * float((1+interest)**float(period+1)) return total print(interest(1000, 0.06, 1))
import sys def is_ascii(s): return all(ord(c) < 128 for c in s) def is_escaped_unicode(str): #how do I determine if this is escaped unicode? if is_ascii(str): # escaped unicode is ascii return True return False inputfile = sys.argv[1] outputfile = inputfile[0:-2]+"xt" output = ...
def divisors(): try: n=int(raw_input("Enter a number: ")) except ValueError: print "Only numbers are acceptable!" return divisors() list1=[] for x in range(n): list1.append(x+1) if n%(x+1)==0: print x+1
class Node: def __init__(self , item): self.key = item self.left = None self.right = None def preorder(root): if root is not None: print root.key, preorder(root.left) preorder(root.right) def getTrees(arr , start , end): trees = [] if start > end : trees.append(None) return trees ...
cases=int(input()) for case in range(cases): intervals=int(input()) l=input().strip().split() intervals=[] for num in range(0,len(l)): if num%2==0: intervals.append([int(l[num])]) else: intervals[-1]+=[int(l[num])] intervals.sort() #print(intervals)...
from queue import Queue class newNode: def __init__(self,data): self.child = [] self.key = data def numberOfSiblings(root, x): if (root == None): return 0 q = Queue() q.put(root) while (not q.empty()): p = q.queue[0] q.get() for i in range(len(p.child)): if (p.child[i].key =...
def isMinHeap(level, n): for i in range(int(n / 2) - 1, -1, -1): if level[i] > level[2 * i + 1]: return False if 2 * i + 2 < n: if level[i] > level[2 * i + 2]: return False return True if __name__ == '__main__': level = [10, 15, 14, 25, 30] n = len(level) if isMinHeap(level, n): ...
""" checks for po box addresses """ import re UPS_BOXES = ("11063-D S MEMORIAL", "6528 E 101ST ST STE D", "10026-A S MINGO RD") POBOX_RE = re.compile(r'PO BOX', flags=re.IGNORECASE) def is_po_box(address): """ is this address a po box or known UPS box """ if POBOX_RE.search(address): return True ...
""" module to actual print the territory data """ import sys from addresses import get_gather_address, get_street from mongo import get_all_printable_docs_for from names import pretty_print_name def key_residence(res): """ mapper for sorting residences """ return res["address"] def ppp(name, address, phone, n...