text
stringlengths
37
1.41M
numerals = { 'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1 } def roman_numeral_converter(rn): value = 0 rnLength = len(rn) indexes = set([]) for char in (x for x in range(rnLength) if not x in indexes): if (char+1) == rnLength: valu...
import random def random_not_in_list(n, l): # Find the set of numbers that are not in the list not_in_list = set(range(n)) - set(l) # If there are no numbers not in the list, return None if not not_in_list: return None # Otherwise, choose a random number from the set of numbers not in the l...
import re allowed_characters = [ 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u...
import heapq def find_minimum_spanning_tree(pipes): edges = [] for node1, connections in pipes.items(): for node2, cost in connections.items(): edges.append((cost, node1, node2)) heapq.heapify(edges) visited = set() result = [] while edges: cost, node1, node2 = heapq...
''' Exercicios propostos ''' numero = input('informe um numero ') try: numero = int(numero) if numero % 2 == 0: print('O numero digitado e par') else: print('O numero digitado nao e par') except: print('ERRO') ''' if not numero.isdigit(): print(f'{numero} não é um número inteir...
''' Tabuada e calculadora ''' sair_programa = 0 while sair_programa == 0: cal = 'Calculadora e Tabuada' print(f'{cal:=^40}') opcao = input('O programa a seguir mostra a tabuada e possui uma pequena calculadora\n' 'digite: \n(1) para calculadora \n(2) para a tabuada \n(0)para sair do pro...
#!/usr/bin/python3 class Person: def __init__(self,firstname,lastname): self.firstname=firstname self.lastname=lastname p1=Person("zhang","bo") print(p1.firstname) print(p1.lastname)
# -*- coding: utf-8 -*- """ Created on Fri Apr 18 11:18:10 2014 Flavius Josephus February 19, 2009 Flavius Josephus was a famous Jewish historian of the first century, at the time of the destruction of the Second Temple. According to legend, during the Jewish-Roman war he was trapped in a cave with a group of forty...
class Payroll: def __init__(self, name): self.name = name self.hours = 0 self.overHours = 0 self.wage = 0 def setEarnings(self, wage): self.wage = wage def setHours(self,hours): self.hours = hours def setOvertime(self,hours = 0): self.overHours = h...
while True: gender = input('Gender: ') if(gender == 'M' or gender == 'm' or gender == 'f' or gender == 'F'): break else : print('Please try again') print('You are: ',gender)
#!/usr/bin/env python3 """Pluralsight Module 4 thing Usage: py Module4_Modularity <URL> """ import sys from urllib.request import urlopen def get_items_from_url(url): """Fetch a list of words from a URL. Args: url: The url of a UTF-8 text document Returns: A list of string containing ...
from population import Population from chromosome import Chromosome if __name__ == '__main__': file = open("knapsack_3.txt", "r") line = file.readline() number_of_items, knapsack_capacity = map(int, line.split()) items = [] while True: line = file.readline() if not line: ...
#1. Jeu du jackpot import random jackpot = random.randint(1,1001) essai = input("Proposer un nombre : ") for nb_essai in range(10): print("Essai n° ",nb_essai+1,":") if jackpot > int(essai): print("le jackpot est plus grand") else: print("le jackpot est plus petit") if jackpot == int...
#x = int(input( " entrez un nombre : ")) #def est_pair(x): # if x%2 == 0: # return True # else: # return False #nombre = est_pair(x) #print(nombre) #def supprimer_voyelles(string): # trans = str.maketrans('', '', 'aàäâAeééèêëEiiîïIoOuUôö') # return string[0] + string[1:].translate(trans) ...
import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup def main(): #step 2 import the data from the site website = 'https://www.smartsheet.com/factory-manufacturing-automation' website_url = requests.get(website).text soup = BeautifulSoup(website_url, 'html.parser')...
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 2 + 2 4 >>> 3 * 10 30 >>> 100 - 10 90 >>> 25 / 5 5.0 >>> 10 / 3 3.3333333333333335 >>> 10 // 3 3 >>> print('Mijn naam is Elona') Mijn n...
# -*- coding: utf-8 -*- import time WAITING_FOR_SLEEP = 0.5 WAITING_FOR_TIMEOUT = 30 class TimeoutException(BaseException): pass def waiting_for(func, timeout=None, sleep=None, args=None, kwargs=None): """ Wait for good result of callback function. Example:: flag = 0 def target...
#!/usr/bin/python3 '''Defines Amenity class that inherits from BaseModel''' from models.base_model import BaseModel class Amenity(BaseModel): '''Amenity class inherits from BaseModel. Attributes: name (str): Name of Amenity ''' name = ""
def checkgender(mystr): cntar=[0]*26 for ch in mystr: idx=ord(ch)-ord('a') cntar[idx]+=1 cnt=0 for x in cntar: if x!=0: cnt+=1 if int(cnt%2)==0: print("CHAT WITH HER!") else: print("IGNORE HIM!") mystr=inp...
def finddangerous(mystr): i=0 ans1=0 ans0=0 while i<len(mystr): if i<len(mystr) and mystr[i]=='1': c1=1 i+=1 while i<len(mystr) and mystr[i]=='1': c1+=1 i+=1 ans1=max(ans1,c1) ...
def matrix(mat): r,c=0,0 for i in range(5): for j in range(5): if mat[i][j]==1: r,c=i,j break print(abs(r-2)+abs(c-2)) mat=[] for i in range(5): row=[] row=list(map(int,input().split())) mat.append(row) matrix(mat)
def add(a, b): return a - b def substract(a, b): return a - b def test_add(): foo = 10 bar = 12 assert add(foo, bar) == 22 def test_substract(): foo = 10 bar = 12 assert add(foo, bar) == -2
hours = float(input('Enter hours worked: ')) rate = float(input('Pay rate : ')) if hours > 40: pay = (hours - 40) * (rate * 1.5) + (40 * rate) print(pay) if hours < 41: pay = rate * hours print(pay)
import string import random password=[] password += [random.choice(string.ascii_uppercase) for i in range(2)] #2 upper case letter, password += [random.choice(string.digits) for i in range(2)] #2 digits, password += [random.choice(string.punctuation) for i in range(2)] # 2 special symbols, password += [random.choice(s...
list1=[] list2=[] n=int(input("enter the total number of lists to be inserted")) for i in range(n): print('enter the',int(i+1),'element to enter') ele=input('') list1.append(ele) for i in list1: if i not in list2: list2.append(i) print("list 1 is",list1) ...
filename=input("Enter Filename:") Extension=filename.split(".") print("Extension of the filename is:", Extension[-1])
class Solution: def reverseWords(self, s: str) -> str: result = "" s = s.split() for i, n in enumerate(s): for j in range(len(n)-1, -1, -1): result += n[j] if i != len(s)-1: result += " " ...
# Sort Array By Parity # Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. # # You may return any answer array that satisfies this condition. # # # # Example 1: # # Input: [3,1,2,4] # Output: [2,4,3,1] # The outputs [4,2,3...
# A Queue class using deque from collections import deque class Queue: def __init__(self): self.buffer = deque() def enqueue(self,val): self.buffer.appendleft(val) def dequeue(self): return self.buffer.pop() def is_empty(self): return len(self.buffer) == 0 def s...
# coding=utf-8 # Lists # Consider a list (list = []). You can perform the following commands # insert i e: Insert integer e at position i. # print: Print the list. # remove e: Delete the first occurrence of integer e. # append e: Insert integer e at the end of the list. # sort: Sort the list. # Pop: pop the last eleme...
# Count by x # Create a function with two arguments that will return an array of the first (n) multiples of (x). # # Assume both the given number and the number of times to count will be positive numbers greater than 0. # # Return the results as an array (or list in Python, Haskell or Elixir). # # Examples: # # ...
# Stringy Strings # write me a function stringy that takes a size and returns a string of alternating '1s' and '0s'. # # the string should start with a 1. # # a string with size 6 should return :'101010'. # # with size 4 should return : '1010'. # # with size 12 should return : '101010101010'. # # The size will ...
# Return-Two-Highest-Values-in-List: # In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible. # # The result should also be ordered from highest to lowest. # # Examples: # # [4, 10, 10, 9] => [10, 9] # [1, 1, 1] ...
# Relative Sort Array # Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. # # Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in asc...
# Exercise: fourth power # Write a Python function, fourthPower, that takes in one number and returns that value raised to the fourth power. # You should use the square procedure that you defined in an earlier exercise # (you don't need to redefine square in this box; when you call square, the grader will use our def...
# Exercise: apply to each # testList = [1, -4, 8, -9] # For each of the following questions (which you may assume is evaluated independently of the previous questions, so that # testList has the value indicated above), provide an expression using applyToEach, so that after evaluation testList has # the indicated value...
# Check If N and Its Double Exist # Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). # # More formally check if there exists two indices i and j such that : # # i != j # 0 <= i, j < arr.length # arr[i] == 2 * arr[j] # # # Example 1: # #...
# Hash Table Exercise 2: # nyc_weather.csv contains new york city weather for first few days in the month of January. Write a program that can answer following, # What was the temperature on Jan 9? # What was the temperature on Jan 4? # Figure out data structure that is best for this problem jan_weather = {} with o...
# Cat Dog Rabbit #Test your understanding of what we have covered so far by trying the following exercise. Modify the code from Activecode 8 so that the final list only contains a single copy of each letter. wordList = ['cat','dog','rabbit'] l = [] for i in wordList: [l.append(x) for x in i if x not in l] print...
# Running Sum # 1480. Running Sum of 1d Array # Easy # # 362 # # 46 # # Add to List # # Share # Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). # # Return the running sum of nums. # # # # Example 1: # # Input: nums = [1,2,3,4] # Output: [1,3,6,10] # Explanatio...
# Exercise: Array DataStructure # Let us say your expense for every month are listed below, # January - 2200 # February - 2350 # March - 2600 # April - 2130 # May - 2190 # Create a list to store these monthly expenses and using that find out, # # 1. In Feb, how many dollars you spent extra compare to January? # 2. Fi...
# Merge Sorted Array # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # # Note: # # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from...
# Reverse Linked List # Reverse a singly linked list. # # Example: # # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # Follow up: # # A linked list can be reversed either iteratively or recursively. Could you implement both? # Definition for singly-linked list. class ListNode: def __init__(self, va...
# Fundamentals: Return # Make multiple functions that will return the sum, difference, modulus, product, quotient, and the exponent respectively. # # Please use the following function names: # # addition = add # # multiply = multiply # # division = divide (both integer and float divisions are accepted) # # modulu...
# Linked Lists - Get Nth # # Implement a GetNth() function that takes a linked list and an integer index and returns the node stored at the Nth index position. GetNth() uses the C numbering convention that the first node is index 0, the second is index 1, ... and so on. So for the list 42 -> 13 -> 666, GetNth() with i...
# Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. # By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. # In this problem, we will not b...
# FInd Pivot Index # Given an array of integers nums, write a method that returns the "pivot" index of this array. # # We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index. # # If no such index exists, we shoul...
# Rotate List # Given a linked list, rotate the list to the right by k places, where k is non-negative. # # Example 1: # # Input: 1->2->3->4->5->NULL, k = 2 # Output: 4->5->1->2->3->NULL # Explanation: # rotate 1 steps to the right: 5->1->2->3->4->NULL # rotate 2 steps to the right: 4->5->1->2->3->NULL # Example 2: ...
''' Find the square root of the integer without using any Python library. You have to find the floor value of the square root. For example if the given number is 16, then the answer would be 4. If the given number is 27, the answer would be 5 because sqrt(5) = 5.196 whose floor value is 5. The expected time complexi...
import math import heapq from collections import namedtuple Cost = namedtuple('Cost', ['total', 'journey', 'to_end']) # (float, float) Path = namedtuple('Path', ['cost', 'intersections', 'previous', 'current']) # (Cost, [int, int ...], int, int) class Map(object): def __init__(self): self.roads = None ...
"""Duoc gioi han boi cap ngoac () Chua duoc moi gia tri Toc do truy xuat nhanh hon list Chiem dung luong bo nho nho hon list Bao ve du lieu khong bi thay doi Co the dung lam key cua dictionary""" # Toan tu cua tuple giong voi toan tu cua chuoi # Toan # tuple tup = (1,) print(tup) print(type(tup)) a = tuple((...
print('hello', 'world') # Parameter # sep (chia ra, phân ra) print('--- parameter sep ---') print('Hello', 'Python', 'Course', sep='---') # Hello---Python---Course # end print('--- parameter end ---') print('line 1', end='|') print('line 2') print('line 3') # sleep() from time import sleep print('start...') slee...
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self, root): self.root = Node(root) # choose the type of traversal type def print_tree(self, traversal_type): ...
#!/bin/env python """ Advent of Code Day 18 """ import re class Num: """ A bit strange math needed for the exercises """ def __init__(self, value) -> None: """ A special number :type value: int """ self.value = value def __sub__(self, other): """ redefine s...
import matplotlib.pyplot as plt from matplotlib import animation import numpy as np fig,ax = plt.subplots() x = np.arange(0,2* np.pi,0.01) line, = ax.plot(x,np.sin(x)) def animate(i): line.set_ydata(np.sin((x+i)/10)) return line, def init(): line.set_ydata(np.sin(x)) return line, ani = animation.Func...
import random import copy import math from timeit import default_timer as timer HOLES_AMOUNT = 14 PLAYER_ONE = -1 PLAYER_TWO = 0 COUNTER_FIRST, COUNTER_SECOND = 0, 0 MOVES_ONE, MOVES_TWO = 0, 0 class Hole: def __init__(self, number): self.stones = 4 self.hole_number = number self.opposit...
#!/usr/bin/env python # # filemap.py # # Sort a list of files into a dict of separate lists by suffix # For, like, tests and stuff # (c) 2015-2019 Alexander Bohn, All Rights Reserved # from __future__ import print_function, unicode_literals def filemapper(files): """ Sort a list of files i...
from nodo import* class Lista_simple: # Constructor def __init__(self): self.head=None self.tail=None self.size=0 # Metódo insertar def insert(self, info): newNodo=Nodo_lista(information=info) if self.head == None: self.head=self.tail=newNodo ...
import turtle oct = turtle.Turtle() oct.pensize(5) oct.color("yellow") oct.fillcolor("orange") oct.begin_fill() for p in range(1, 8): oct.right(45) oct.forward(100) oct.right(45) oct.forward(100) oct.end_fill() turtle.done()
import turtle bob = turtle.Turtle() bob.shape('square') bob.speed(0) for i in range (100): bob.forward(i) bob.left(360/5)
'''name = input("Please enter your name: ") prompt = "If you tell us who you are, we can personalize the massages you see." prompt += "\nWhat is your first name? " name = input(prompt) print(f"\nHello, {name}!")''' def get_formatted_name(first_name, last_name, middle_name=''): """Return a full name, ne...
fav_fruit = ['oranges','grapes','cherries'] for fruit in fav_fruit: if fruit == 'apples': print("I really like bananas instead") if fruit == 'pears': print("I really like bananas instead") if fruit == 'bananas': print("I really like bananas instead") if fruit == 'limes': print("I really like bana...
requested_toppings = ['mushrooms','green preppers','extra cheese'] if 'mushrooms' in requested_toppings: print("Adding mushrooms.") if 'pepperoni' in requested_toppings: print("Adding pepperoni.") if 'extra cheese' in requested_toppings: print("Adding extra cheese") print("\nFinished making your pizza!\n") ...
# Start with some designs that need to be printed. unprinted_designs = ['phone case','robot pendant','dodecahedron'] completed_models = [] # Simulate printing each design, until none are left. # Move each design to completed_models after printing. while unprinted_designs: current_design = unprinted_designs.po...
from random import choice lotto_numbers = ['1', '23', '20', '15'] lotto_letters = ['r', 'd', 'w', 'g'] win_ticket = [] my_ticket = ['1', 'r', '23', 'w', '15', 'g', '20', 'd'] num_lett = 1 lotto_tries = 1 my_ticket.sort() while win_ticket != my_ticket: win_ticket = [] if num_lett <= 4: win_number = ...
rivers = {'nile': "egypt", 'mississippi': 'usa', 'amazon': 'brazil'} for river, contury in rivers.items(): if contury == 'usa': print(f"The {river.title()} runs though {contury.upper()}.") else: print(f"The {river.title()} runs though {contury.title()}.") for river in rivers.keys(): print(ri...
person_0 = {'first_name': 'Manny', 'last_name': 'Terrazas', 'age': 38, 'city': 'Huffman'} person_1 = {'first_name': 'Fred', 'last_name': 'Bock', 'age': 60, 'city': 'Pasadena'} person_2 = {'first_name': 'Jeremy', 'last_name': 'Easten-Marks', 'age': 40, 'city': 'Houston'} people = [person_0, person_1, person_2] f...
num_user = int(input('Введите положительное число: ')) num = num_user max_num = 0 while num > 0: if num % 10 > max_num: max_num = num % 10 num = num // 10 print(f'В числе "{num_user}" -> максимальное число "{max_num}"')
#!/usr/bin/env python import argparse, random parser = argparse.ArgumentParser(description="Generates the name of the next GiSHWheS hybridized mascot animal.") parser.add_argument(("-f", "--file"), nargs=1, action='store') animals = [ "bear", "el>e<phant", "oct>o<pus", "pig", "cat", "din>o<saur", "mite...
class Solution(object): def deckRevealedIncreasing(self, deck): """ :type deck: List[int] :rtype: List[int] """ deck.sort(reverse=True) reveal = [] for num in deck: if len(reveal) > 1: tmp_pop = reveal.pop() reveal.i...
#Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ root...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): path = 0 def distributeCoins(self, root): """ :type root: TreeNode :rtype: int """ self...
import matplotlib import matplotlib.pyplot as plt def extract_data(filename): file = open(filename, "r") data = [] # getting rid of first line line = file.readline() # extracting rest of the data while(True): line = file.readline() if (line == ""): break else: line = line.split(",") data.appen...
# DSA-Assgn-16 class Queue: def __init__(self, max_size): self.__max_size = max_size self.__elements = [None]*self.__max_size self.__rear = -1 self.__front = 0 def is_full(self): if(self.__rear == self.__max_size-1): return True return False def...
class Apparel: counter = 100 def __init__(self, price, item_type): Apparel.counter += 1 self.__item_id = "" if item_type.lower() == "cotton": self.__item_id = "C" + str(Apparel.counter) else: self.__item_id = "S" + str(Apparel.counter) self.__pri...
from threading import Thread def func1(): result_sum = 0 # Write the code to find the sum of numbers from 1 to 10000000 for i in range(10000000): result_sum += i print("Sum from func1:", result_sum) def func2(): result_sum = 0 # Write the code to accept 5 numbers from user and find i...
import random def find_it(num,element_list): no_of_guesses = 0 for i in element_list: no_of_guesses += 1 if i == num: return no_of_guesses else: pass #Initializes a list with values 1 to n in random order and returns it def initialize_list_of_elements(n): ...
# DSA-Assgn-12 class Queue: def __init__(self, max_size): self.__max_size = max_size self.__elements = [None]*self.__max_size self.__rear = -1 self.__front = 0 def is_full(self): if(self.__rear == self.__max_size-1): return True return False def...
def find_leap_years(given_year): list_of_leap_years = [given_year] for i in range(15): list_of_leap_years.append(list_of_leap_years[i] + 4) return list_of_leap_years list_of_leap_years = find_leap_years(2000) print(list_of_leap_years)
def count_strings(number): a = [0 for i in range(number)] b = [0 for i in range(number)] a[0] = b[0] = 1 for i in range(1, number): a[i] = a[i-1] + b[i-1] b[i] = a[i-1] return a[number-1] + b[number-1] # Pass different values to the function and test your program number = 3 print(...
def find_pairs_of_numbers(num_list, n): pairs = 0 for i in range(len(num_list)): for j in range(i+1, len(num_list)): if (num_list[i] + num_list[j]) == n: pairs += 1 return pairs num_list = [1, 2, 7, 4, 5, 6, 0, 3] n = 6 print(find_pairs_of_numbers(num_list, n))
def last_instance(num_list, start, end, key): first = -1 last = -1 for i in range(len(num_list)): if not num_list[i] == key: continue if first == -1: first = i last = i return last num_list = [1, 1, 2, 2, 3, 4, 5, 5, 5, 5] start = 0 end = len(num_li...
import sqlite3 from tkinter import * from tkinter import messagebox class DB: def __init__(self): self.conn = sqlite3.connect("Student_record.db") self.cur = self.conn.cursor() self.cur.execute( "CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY, fname TEXT, lname TEXT...
#! /usr/bin/env python3 # This program searches all plain text files in a folder for a user-inputted regex. import os, re, sys # Prompts user to input regex. userRegex = re.compile(input('Enter your chosen regex:\n'), re.I) # Prompts user to input file path. path = input('Please enter your chosen folder wi...
#Dependencies/Modules import os import csv #path to budget to open csv file budget_data_csv = os.path.join("Resources", "budget_data.csv") #opens budget_data csv to manipulate data for report with open(budget_data_csv, newline='') as budget: budget_reader = csv.reader(budget, delimiter=',') budget_header = n...
# functions # A function is a group of related statements that performs a specific task. # Creating a function def my_function(): print("Hello My Name Is Rohan!") # Calling a function my_function() # Parameter and Arguments def greet(name): print("Hello", name) print("How do you do?") # calling function b...
# Object-Oriented Programming methodologies # Inheritance # When a class derives from another class. # The child class will inherit all the public and protected properties and methods from the parent class. # In addition, it can have its own properties and methods. class employee1(): # This i...
# Tuples are used to store multiple items in a single variable. # A tuple is a collection which is ordered and unchangeable. # Tuples are written with round brackets. # tuples are ordered, it means that the items have a defined order, and that order will not change. # Tuple items allow duplicate values. # To create a t...
''' Author : Shyam Ramkumar Given a source file and target file, the program compares the files and provides an output. The output contains each line of source and how many times have the occured in a given target file. ''' import glob import csv import time #from re import search def main(): ''' Main func...
import cv2 import numpy as np face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Assign our face cascade with the attributes of the downloaded xml file. eye_cascade = cv2.CascadeClassifier('HaarCascades/haarcascade_eye.xml') # Assign directory for eye xml file with all eye detecti...
import cv2 import numpy as np img = cv2.imread('bookpage.jpg') retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY) # The threshold here takes the lowest darkness of 12, to a max of 255 and applies the THRESH_BINARY filter. grayscaled = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Grayscale the image retv...
A = {5, 3, 8, 6, 1} B = {1, 5, 3, 4, 2} print("A union B : ",A.union(B)) print("A intersection B :",A.intersection(B)) print("A - B : ", A-B) print("Maximum and Minimum values of A : " , max(A),min(A)) print("Maximum and Minimum values of B : " , max(B),min(B))
 import time ##class TreeNode: ## def __init__(self, x): ## self.val = x ## self.left = None ## self.right = None ##class ListNode: ## def __init__(self, x): ## self.val = x ## self.next = None ##class RandomListNode: ## def __init__(self, x): ## self.la...
# SIMPLE TIC N TOE GMAES # Creating the structure of the boar using aDictionaries board = { "T-Left": '-', "T-Middle": '-', "T-Right": '-', "M-Left": '-', "M-Middle": '-', "M-Right": '-', "B-Left": '-', "B-Middle": '-', "B-Right": '-', } def printBoard(): print( """ ...
# _*_ coding=utf-8 _*_ __author__ = 'patrick' class Person(object): def __init__(self, name, action): self.name = name self.action = action def do_action(self): print (self.name, self.action.name) return self.action class Action(object): def __init__(self, name): ...
# _*_ coding=utf-8 _*_ __author__ = 'patrick' class MoveFileCommand(object): def __init__(self, src, dest): self.src = src self.dest = dest def rename(self): print "rename {0} to {1}".format(self.src, self.dest) # todo how to invoke method dynamically def execute(self, method...
import logging from flask import json from actions.util import * def list_wans(api_auth, parameters, contexts): """ Allows users to list all the WANs that are in the organisation Works by calling the list_WANs action defined in api/wans.py Parameters: - api_auth: SteelConnect API object, it conta...
# Utility functions that actions can call on. class APIError(Exception): pass def format_wan_list(items): """ Given the successful result of `api_auth.list_wans().json()["items"]`, returns the list of WANs as a nicely-formatted string suitable for presenting to the user. """ s = "" f...
import logging from flask import json from actions.util import get_site_id_by_name, APIError def delete_site(api_auth, parameters, contexts): """ Allows users to delete a site In order for them to do so, we need to know the city, site name and country code. Works by getting the parameters, and calli...
a=10 b=20 a if a<b else b 10 x=1<2<3 x True x=1<3<2 x False def compare(a,b,c): return a if a<b else b def compare(a,b,c): return a if a<b and a<c else b if b<c and b<a else c