text
stringlengths
5
121k
import pandas as pd from pandas.io.parsers import read_csv def line2list(data): l = len(data['From_Bus']) line = [] header = ['From_Bus','To_Bus','R','X','G','B','Max_Mvar','Y/2'] for i in range(1,l+1): temp = [] for h in header: temp.append(d...
""" Strong Password Generator - Generates a secure random password Author: Skyascii (https://github.com/savioxavier) Date : 1/10/2021 """ import secrets import string def generate_password(length=12): """Generates a random password Args: length (int, optional): Length of the generated password. ...
from random import randint def merge_sort(mylist): n = len(mylist) if n > 1: list1 = mylist[:n//2] list2 = mylist[n//2:] merge_sort(list1) merge_sort(list2) merge(list1, list2, mylist) def merge(list1, list2, mylist): f1 = 0 f2 = 0 while f1 + f2 < len(mylis...
def defangIPaddr(self, address): defanged = '' for i in address: if i == '.': defanged += '[.]' else: defanged += i return defanged def defangIPaddr(self, address): return address.replace('.', '[.]') def defangIPad...
def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ cnt = {} for i in nums: cnt[i] = cnt.get(i, 0) + 1 for k, v in cnt.items(): if v > len(nums) // 2: return k def majorityElement(self, nums): nums.sort() return nums[le...
rows = 'ABCDEFGHI' cols = '123456789' def cross(A, B): "Cross product of elements in A and elements in B." return [i+j for i in A for j in B] boxes = cross(rows, cols) row_units = [cross(r, cols) for r in rows] column_units = [cross(rows, c) for c in cols] square_units = [cross(rs, cs) for rs in ('ABC','DEF','G...
import sys import dlib import numpy as np import cv2 from skimage import io '''The histogram of oriented gradients (HOG) is a feature descriptor used in computer vision and image processing for the purpose of object detection. The technique counts occurrences of gradient orientation in localized portions of an ima...
def calcDirection(d, s): if d == "N" and s == "L": return "W", "x-" if d == "N" and s == "R": return "E", "x+" if d == "E" and s == "L": return "N", "y+" if d == "E" and s == "R": return "S", "y-" if d == "S" and s == "L": return "E", "x+" if d == "S" an...
def getPermutations(arr): perms = [] helper(0, arr, perms) return perms def helper(idx, arr, perms): if idx == len(arr) - 1: perms.append(arr[:]) else: for x in range(idx, len(arr)): swap(x, idx, arr) helper(idx + 1, arr, perms) swap(x, idx, arr) def swap(idx1, idx2, arr): arr[idx1], arr[idx2] = a...
def run(): sentence = input("Please write a sentence: ") for caracter in sentence: print(caracter.upper()) if __name__ == '__main__': run()
dolar = input('Introduce tus dolares: ') dolar = float(dolar) valor_peso = 20 pesos = dolar * valor_peso pesos = round(pesos, 2) pesos = str(pesos) print('Tienes $' + pesos + ' pesos mexicanos')
from secret import SecretWord from board import Board class Game: """Run an entire game. Initialization defines the player who pickers secret word and one or more guessers. play - picker picks the secret word from the dictionary held by all players - guessers guess in turn looking at the sta...
""" Python Exam Problem 5 A program that reads in two files and prints out all words that are common to both in sorted order """ from __future__ import print_function def fileset(filename): """ Takes the name of a file and opens it. Read all words and add them to a set. Args: filename: The na...
original = input("Write a sentence to code! ").strip().lower() words = original.split() new_words = [] for word in words: if word[0] in "aeiou": new_word = word +"yay" new_words.append(new_word) else: vowel_position = 0 for letter in word: if letter not in "a...
from sqlite3.dbapi2 import Cursor import database class Category: def __init__(self, name, parent_category=None, id=None) -> None: self.name = name self.parent_category = parent_category def __init__(self, id) -> None: cursor = database.get_cursor() cursor.execute("SELECT * FRO...
waluta = "dolar" us = 1 pln = 4.08234915 print("Aktualnie %r %r kosztuje %.2r zł" % (us, waluta, pln)) waluta = "dolar" us = 1 pln = 4.08234915 print("Aktualnie %d %s kosztuje %.2f zł" % (us, waluta, pln)) waluta = "dolar" us = 1 pln = 4.08234915 print("Aktualnie {} {} kosztuje {} zł" .format(us, waluta, p...
class Computer: def __init__(self, model, ram): self.model = model self.ram = ram def config(self): print("i5,16gb,1TB") print("Model and ram is", self.model, self.ram) comp1 = Computer("AMD", 16) comp2 = Computer("i5", 24) comp1.config() comp2.config() class Person: d...
class Pycharm: def execute(self): print("compiling") print("Running") class Eclipse: def execute(self): print("Checking") print("verifying") print("compiling") print("running") class Laptop: def code(self,ide): ide.execute() ide = Pycharm() ide1...
from datetime import datetime as dt players = {} def get_age_diff(duration_in_s): days = divmod(duration_in_s, 86400) hours = divmod(days[1], 3600) minutes = divmod(hours[1], 60) seconds = divmod(minutes[1], 1) return [days,hours,minutes,seconds] def get_dob_obj(dob_...
import unittest from greeting import Greeting class TestGreeting(unittest.TestCase): def test_Greeter_GivenSingleName_ShouldGreetSingleName(self): singleNames = ["Bob","Mary","Tom"] for eachName in singleNames: name = eachName result = Greeting.Gree...
''' control structure if syntax : if condition : statement else : statement relational operator operator symbol greater than > less than < equal to == not equal to != gr...
def prime(no): is_prime=True for i in range(2,no): if no % i == 0 : is_prime=False return is_prime def factorial(no): fact=1 for i in range(1,no+1): fact=fact*i return fact
""" Machinery for creating MapLayers containing Perlin noise. """ from typing import Callable, Tuple from perlin_numpy.perlin2d import generate_perlin_noise_2d, interpolant from .maplayer import BasicLayer, MapLayer def get_perlin_layer( width: int, height: int, res: Tuple[int], tileable: Tuple[bool...
from database_utils import DatabaseUtils class Menu: def main(self): with DatabaseUtils() as db: db.createPersonTable() self.runMenu() def runMenu(self): while True: print() print("1. List People") print("2. Insert Person") p...
class Animal: def eat(self): print ('Eating...') class Dog(Animal): def bark(self): print ('Barking...') class PuppyDog(Dog): def play(self): print ('Playing...') d=PuppyDog() d.eat() d.bark() d.play()
import pandas import nltk nltk.download('stopwords') import matplotlib.pyplot as pyplot tweets = pandas.read_csv("./datasets/trump_tweets.csv") print(tweets.shape) tokenized = {} tweet_tokenizer = nltk.tokenize.casual.TweetTokenizer() filter_words = ["!", ",", ":", ".", "—", "&", "?", "\'", "\"", ")", "(", "’"] sto...
rot = int(input("Input the key: ")) action = input("Do you want to [e]ncrypt or [d]ecrypt?: ") data = input("Input text: ") if action == "e" or action == "encrypt": text = "" for char in data: char_ord = ord(char) if 32 <= char_ord <= 126: char_ord -= 32 char_o...
import sys def get_factors(x): factors = [] for i in range(1, x + 1): if x % i == 0: factors.append(i) return factors num = int(sys.argv[1]) factors = get_factors(num) print(f"The factors of {num} are :", factors)
inputs = [] while True: s = input("Enter a string(enter END to stop)") if s.lower() != "end": inputs.append(s) else: break print(inputs)
def is_integer(n): try: return float(n).is_integer() except ValueError: return False def is_integer_num(n): if isinstance(n, int): return True if isinstance(n, float): return False nums = [] while True: try: sn = input("Ente...
def show(): import pygame from math import pi pygame.init() BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) size = [1200, 700] screen = pygame.display.set_mode(size) ...
import pandas as pd import numpy as np df=pd.read_csv('cardio_dataset.csv') df=df.values data=df[:,0:7] target=df[:,7] target=np.reshape(target, (-1,1)) from sklearn.model_selection import train_test_split train_data, test_data, train_target, test_target = train_test_split(data,target,test_si...
def fact(num): if num == 1: return num else: return num*fact(num-1) num = int(input("enter the number to find the factorial:")) if num<0: print("factorial is not allowed for negative numbers") elif num == 0: print("factorial of the number 0 is 1") else: print("factorial of",num, "is:...
print ('\033[1;32;40m'+"Rocket departing in:..") from time import sleep for a in range (30, 0, -1): print (a) sleep(1) print ("Prepare for take off ! ")
class node: def __init__(self,data): self.data = data self.next = None def takeinput(): inputnode = [int(i) for i in input().split()] head = None for i in inputnode: node1 = node(i) if head is None: head = node1 curr = head ...
class Node: def __init__(self,data): self.data = data self.next = None def create_linked_list(): inputElement = [int(i) for i in input().split()] head = None for i in inputElement: node = Node(i) if head is None: head = node curr = hea...
import sys import os from PIL import Image actualFolder = sys.argv[1] newFolder = sys.argv[2] if not os.path.exists(newFolder): try: os.makedirs(newFolder) except OSError: print(f'Creation of the directory {newFolder} has failed.') for filename in os.listdir(actualFolder): img...
from random import randint def is_probably_prime(n, k=1): d = n - 1 s = 0 ifsetter = 1 print(f"1. We have that n = {n}, k-times: k = {k} and d = {n-1}") print(f"2. We then make an iteration until d is not divisible by 2") while not d % 2: s += 1 d //= 2 for ...
import math n= 221 toitent = 192 print(f"When we have n = {n} and toitent = {toitent}") print("1. We know that n = p * q and toitent = (p-1)(q-1)\n" "2. We then susbsitute to get\n" " toitent =p.q-(p+q)+1 = n-(p+q)+1\n" "3. To get p and q we have that \n" " p+q = n + 1 - toitent") s...
import csv import requests USER_TOKEN = "Bearer XXXXXXXXXXXXXXX" def get_webex_api(room_id="Y2lzY29zcGFyazovL3VzL1JPT00vNWJiMmRiZjAtNmFkOC0xMWVhLWEzNmEtMDc0ZjMxN2Y0Njli"): url = "https://api.ciscospark.com/v1/memberships" querystring = {"roomId": room_id} headers = { 'Authorization': ...
from constraint import * problem = Problem() board_size = 8 queen_list = range(board_size) coord_list = [[(x,y) for y in range(board_size)] for x in range(board_size)] for q,c in zip(queen_list, coord_list): problem.addVariable(q, c) for queen_1 in queen_list: for queen_2 in queen_list: if queen_1...
nombres = ['Andres', 'Derly', 'Edison', 'Edwin', 'Karla'] print('Elementos con While') nElementos = len(nombres) contador = 0 while contador < nElementos: print(nombres[contador]) contador = contador + 1 print('\nElementos con For') range(nElementos) for contador in range(nElementos): print(nombres[c...
numeros = [345,756,34,0,467,456,-94,63,64,686,543] impares = list(map(lambda num: num%2 != 0, numeros)) def esVerdadero(secuencia): numeros = [] for num in secuencia: if num: numeros.append(True) else: numeros.append(False) return numeros info = [int...
def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] self.helper(root, res) return res def helper(self, root, res): if root is not None: if root.left is not None: self.helper(root.left, res) res.append(root.val) if root.right is not None: ...
def binary_search(array, target): '''Write a function that implements the binary search algorithm using iteration args: array: a sorted array of items of the same type target: the element you're searching for returns: int: the index of the target, if found, in the source -1: ...
def productOfAllOtherElements(nums): L = [1 for x in nums] R = [1 for x in nums] ans = [1 for x in nums] L[0] = 1 for i in range(1, len(nums)): L[i] = L[i - 1] * nums[i - 1] R[len(nums) - 1] = 1 for i in range(len(nums) - 2, -1, -1): R[i] = R[i + 1] * nums[i + 1] ...
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: if not head: return head if left == right: return head prev = None cur = head while left > 1: prev = cur cur = cur.next left -= 1 right -= 1 connection = prev ...
class Solution: def permute(self, nums): result = [] temp = [] self.backtrack(nums, result, temp) print(result) return result def backtrack(self, nums, result, temp): if len(temp) == len(nums): result.append(list(temp)) ...
def diffWaysToCompute(self, expression: str) -> List[int]: res = [] for i in range(len(expression)): c = expression[i] if c in "+-*": left = self.diffWaysToCompute(expression[:i]) right = self.diffWaysToCompute(expression[i + 1:]) for l in left: ...
def climbStairs(self, n: int) -> int: if n == 1: return 1 m = [None for x in range(n)] m[0] = 1 m[1] = 2 for i in rnage(2, len(m)): m[i] = m[i-1] + m[i-2] return m[n-1]
"""BasicCache module""" from base_caching import BaseCaching class BasicCache(BaseCaching): """ Inherits from BaseCaching """ def put(self, key, item): """ Assign key: item to self.cache_data If key or item is None do nothing Parameters: ...
"""LFU caching module""" from base_caching import BaseCaching class LFUCache(BaseCaching): """ LFU Caching algorithm """ __LFUDict = {} __bit = 0 def put(self, key, item): """ Assign key: item to self.cache_data If key or item is None do nothing ...
from bsddb3 import db DB_File = "data.db" database = db.DB() database.set_flags(db.DB_DUP) database.open(DB_File,None, db.DB_HASH, db.DB_CREATE) curs = database.cursor() database.put(b'key1', "value1") database.put(b'key1', "value2") database.put(b'key2', "value1") database.put(b'key2', "value2") iter = ...
'''' list indexing ''' fruits = [ 'orange', 'apple', 'pear', 'apple','banana' ] fruits[0] print(fruits[0]) fruits[ 1 ] print(fruits[1]) fruits[ 2 ] print(fruits[2]) fruits[ 3 ] print(fruits[3]) fruits[ 4 ] print(fruits[4]) fruits[ -1 ] print(fruits[-1]) fruits[ -5 ] print(fruits[-5]) '''...
from helper import prepare_samples import tensorflow as tf import numpy as np import random import glob import os IMAGE_WIDTH = 128 IMAGE_HEIGHT = 120 TRAIN_SET_FRACTION = .85 CLASSES_COUNT = 20 HIDDEN_LAYERS_SIZE = [100, 75, 50] INITIAL_BIAS = 1.0 LEARNING_RATE = .001 EPOCHS = 10000 ACTIVATION_FUNCTION = tf....
def main(): print("**NOTE**: Elements should be less then 25 as alogrithm work best on that only") print("Enter Bubble Sort elements sepreated by (',') Comma: ") input_string = input() array = [int(each) for each in input_string.split(",")] array_len = len(array) if array_len > 1: fo...
import substitutor import readin_real import relation_checker_utility import testing def run(verbose): relation_checker_utility.check(verbose) simplifiedequation = substitutor.Substitutor().finalEquation print("You provided the following equation: ") print(simplifiedequation) num...
n = int(input()) phoneBook = {} for i in range(n): name, phoneNumber = input().split() phoneBook[name] = phoneNumber enterName = input() while enterName: if enterName in phoneBook: print('{0}={1}'.format(enterName,phoneBook[enterName])) elif enterName not in phoneBook: print('Not found')...
def llaves(): dic = {'1':'ola','2':'io'} yaves = dic.keys() print(yaves) def valores(): dic = {'1':'ola','2':'io'} valoress = dic.values() print(valoress) def tuplas(): dic = {'1':'ola','2':'io'} tu = dic.items() print(tu) def sacar(): dic = {'1':'ola','2':'io'} val...
import re print ("\n" + "===" * 4) userWindowsMacAdd = input("Enter Windows MAC address to convert to a Cisco MAC address format\nExample: A1-B2-C3-D4-E5-F6 should be a1b2.c3d4.e5f6\nMac address: ") print ("===" * 4) print("\nConverting [" + userWindowsMacAdd + "] into a cisco mac address format. (example: ab...
import requests import urllib from SQL import * from bs4 import BeautifulSoup def ScrapeUTSC(url): """ Function which will scrape the UTSC course website and store all the needed information into a database """ response = requests.get(url) document = BeautifulSoup(response.text, "html.parser"...
print('Hello') print("Hello") print() print('This is an example of "Single and double"') print("This is an example of 'Single and double'") print("This is an example of \"Single and double\"") seperator='***'*5 fruit="apple" print(fruit) print(fruit[0]) print(fruit[3]) fruit_len=len(fruit) print(fruit_len) ...
from matplotlib import pyplot as plt plt.plot([1,2,3],[4,5,1]) plt.show() x = [5,2,7] y = [2,16,4] plt.plot(x,y) plt.show() from matplotlib import pyplot as plt plt.bar([0.25,1.25,2.25],[50,40,70], label="B1",width=.5) plt.bar([.75,1.75,2.75],[80,20,20], label="B2", color='r',width=.5) plt.legend() plt.xlabel('x')...
wordBank = [10, 11, 104, 170, 73, 309, 185, 245, 246, 434, 458] class PagingCounter: def __init__(self, _memSize, _pageSize): self.memSize = _memSize self.pageSize = _pageSize self.pageBank = [] def toMemory(self, wordVal): self.pageLocation = int(wordV...
from microbit import * import neopixel import radio ANALOG_MAX = 1023 LIGHT_STATE = True MOTOR_STATE = True radio.on() radio.config(channel=18) def to_analog(value): global ANALOG_MAX analog_val = int(value * ANALOG_MAX) return analog_val def check_speed(speed): if speed < 0 or speed > 1: ...
import random print("#---------------#\n|GUESS THE NUMBER|\n#---------------#\n") print("Range of random numbers.\n") start = int(input("start no:")) end = int(input("end no:")) n = random.randint(start,end) print("\n") while True: g = int(input("no:")) if g>n: print("try a lower no. ") ...
from collections import Counter def getShortestSubstrOfAllChar(S, T): '''get shortest substring of all char. If there are multiple substrings with same length, return the leftmost one. Time Complexity: O(max(N, M)) where N = length of S and M = length of T (in case O(N) < O(M) the time complexity is strictly O...
import cv2 trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') trained_smile_data = cv2.CascadeClassifier('haarcascade_smile.xml') webcam = cv2.VideoCapture(0) while True: successful_frame_read, frame = webcam.read() if not successful_frame_read: break gra...
""" Breadth First Search: Shortest Reach """ class Node: def __init__(self, element, level=-1): self.element = element self.neighbors = set() self.level = level def add_neighbor(self, neighbor): self.neighbors.add(neighbor) def __repr__(self): return str(self....
def my_gen(): n = 1 print('This is printed first') yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n for item in my_gen(): print(item) def rev_str(my_str): length = len(my_str) for i ...
my_set = {1, 2, 3} print(my_set) my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) my_set = {1, 2, 3, 4, 3, 2} print(my_set) my_set = set([1, 2, 3, 2]) print(my_set) a = {} print(type(a)) a = set() print(type(a)) my_set = {1, 3} print(my_set) my_set.add(2) print(my_s...
vowels = ['e', 'a', 'u', 'o', 'i'] vowels.sort() print('Sorted list:', vowels) vowels = ['e', 'a', 'u', 'o', 'i'] vowels.sort(reverse=True) print('Sorted list (in Descending):', vowels) def takeSecond(elem): return elem[1] random = [(2, 2), (3, 4), (4, 1), (1, 3)] random.sort(k...
my_dict = {} my_dict = {1: 'apple', 2: 'ball'} my_dict = {'name': 'John', 1: [2, 4, 3]} my_dict = dict({1:'apple', 2:'ball'}) my_dict = dict([(1,'apple'), (2,'ball')]) my_dict = {'name': 'Jack', 'age': 26} print(my_dict['name']) print(my_dict.get('age')) print(my_dict.get('address'))...
import math def constant_decay_function(variable, rate): result = variable * rate return result def exponential_function(a, x, k, b, exp): """ Exponential function where y = a * e^(-k * (x / b)^exp) """ result = a * math.exp(-k * (x / b) ** exp) return result def casted_ex...
""" Helper methods for manipulating dates, times and datetimes """ import datetime def get_curr_date_str(date_format="%Y-%m-%d"): """ Get the current date as a string Returns: date_str: (str) current date """ date_str = datetime.date.today().strftime(date_format) return date_str def...
""" Helpers for operating system functions Contains methods to get directory paths and other operating system functions. """ import os from os.path import expanduser from sys import platform def get_user_home_dir(): """ Get user's home directory Returns the user's home directory. Args: Returns...
from functools import partial def func(u,v,w,x): return u*4 + v*3 + w*2 + x p = partial(func,5,6,7) print(p(8)) my_list = ['one', 'two', 'three', 'four', 'five'] my_list_len = len(my_list) for i in range(0, my_list_len): print(my_list[i]) drill_one = [0,1,2,3,] for i in range(4): print(drill_one[i...
def read_input(): return (input().rstrip(), input().rstrip()) def print_occurrences(output): print(' '.join(map(str, output))) def pre_hash(text, P, p, x): T = len(text) S = text[T-P:] H = [0]*(T-P+1) H[T-P] = poly_hash(S, p, x) y = 1 for i in range(1, P+1): y = (y*...
a = int(input()) a1 = 0 a2 = 1 n = 0 i = 0 while(i < a-1): n = a1 + a2 a1 = a2 a2 = n i += 1 print(n)
import sys def get_majority_element(a, lo, hi): if len(a) == 1: return a[0] if lo == hi: return -1 if lo+1 == hi: return a[lo] mid = (hi+lo)//2 left = get_majority_element(a, lo, mid) right = get_majority_element(a, mid+1, hi) ...
import copy import math import random class Node: """ Data structure to keep track of our search """ def __init__(self, state, parent=None): self.visits = 1 self.reward = 0.0 self.state = state self.children = [] self.children_move = [] self.parent = pa...
num_of_lines = int(input("Enter the number of lines: ")) output_list = [] for line in range(num_of_lines): user_input = (input("Enter the message: ")).split() num_of_char = int(user_input[0]) char = user_input[1] output_list.append(char * num_of_char) ...
import numpy as np import pandas as pd def answer_one(): df = pd.read_csv('fraud_data.csv') return (df['Class'].value_counts() / len(df)).loc[1] answer_one() from sklearn.model_selection import train_test_split df = pd.read_csv('fraud_data.csv') X = df.iloc[:,:-1] y ...
""" Using Tkinter to create a kg -> grams, US pounds,and ounces calculator """ from tkinter import * """ Open a Tkinter GUI window """ window = Tk() """ Defining Calculator program """ def kg_to(): try: grams = float(e1_value.get()) * 1000 pounds = float(e1_value.get()) * 2.20462 ounce...
""" Working with Excel Files using openpyxl """ import openpyxl """WORKING WITH ALREADY EXISTING EXCEL FILE """ """ Open excel file as workbook in same directory """ worksheet = openpyxl.load_workbook('example.xlsx') """ Getting sheetnames of workbook and set sheets to variable""" print(worksheet.sheetnames) sheet1...
people = 30 cars = 30 trucks = 30 if cars > people: print("We should take the cars.") elif cars < people: print("We should not take the cars.") else: print("We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we could take the trucks.") else: prin...
import numpy as np import pandas as pd import plotly.offline as pyo import plotly.graph_objs as go x = np.random.randint(1,101,100) y = np.random.randint(1,101,100) data = [go.Scatter( x=x, y=y, mode='markers', marker={ 'size': '20', 'symbol': 'pentagon', 'color'...
import string mykey="ECE" data = open("test.txt", "r") input_mes = data.readline() source = string.ascii_uppercase shift = 23 matrix = [ source[(i + shift) % 26] for i in range(len(source)) ] def coder(thistext): ciphertext = [] control = 0 for x,i in enumerate(input_mes.upper()): if i not in so...
def convert_currency(amount_needed_inr,current_currency_name): current_currency_amount=0 Euro=0.01417 British_Pound=0.0100 Australian_Dollar=0.02140 Canadian_Dollar=0.02027 if current_currency_name=="Euro": current_currency_amount=amount_needed_inr*Euro elif current_currency_name=="B...
from persona import Persona from archiviatore import Archiviatore class ListaPersone(object): """ gestisce una lista di oggetti Persona, caricandoli e salvandoli su file """ def __init__(self): self.lista = [] self.archivio = Archiviatore() self.npersone = 0 def Nuovo(self, nome, cognome): p = Persona(no...
import string def caesar_encode(message, key): res = [] for c in message: if 'A' <= c <= 'Z': idx = ord(c) - ord('A') idx = (idx + key) % 26 res.append(chr(ord('A') + idx)) else: res.append(c) return "".join(res) def caesar_encode2(message...
def gcd(x, y): while y != 0: (x, y) = (y, x % y) return x def isquareroot(n): return int(n ** 0.5) + 1 def is_divisible_by_square(n): i = 2 while i ** 2 <= n: if n % (i ** 2) == 0: return 1 i += 1 return 0 def number_of_factors(n): counter = 0 ...
import sys from common.timing import elapsed @elapsed def sum1(limit, d1, d2): sum = 0 for n in range(1, limit): if n % d1 == 0 or n % d2 == 0: sum += n return sum @elapsed def sum2(limit, d1, d2): return sum([n for n in range(1, limit) if n % d1 == 0 or n % d2 == 0]) @el...
import collections import itertools from math import factorial import sys def choose(n, k): return factorial(n) // (factorial(k) * factorial(n-k)) def all_choices(n, step): return sum([choose(n, k) for k in range(0, n+1, step)]) def main(args): f = factorial expected = {'1' : 2, '2' : 2, '3' : 2...
import os import csv file = 'election_data.csv' with open(file, encoding='utf-8') as csvfile: csvreader = csv.DictReader(csvfile) total_votes = 0 dict_candidates = {} winning_vote_count = 0 csv_header = next(csvreader) for row in csvreader: total_votes += 1 cand...
import cv2 as my_cv import pytesseract as my_pt import os img=my_cv.imread("textbook_image_3.PNG") my_pt.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' grey_img=my_cv.cvtColor(img,my_cv.COLOR_BGR2GRAY) no_noise_img=my_cv.medianBlur(grey_img,3) thr_img=my_cv.threshold(no_n...
for x in range (-1, 13): print(x , str("am")) for y in range(11,24): print(y , str("pm"))
def square(number): if not valid_number(number): raise ValueError("The number isn't between 1 and 64 and should be greater 0") return 2**(number - 1) def valid_number(number): return 0 < number < 65 def total(): return sum(square(x) for x in range(1, 65))
flg=True while(flg): print("\n\nSelect a Service\n 1.auto\n 2.bike\n 3.car\n 4.exit\n") ch=int(input("enter your choice")) if(ch==1): kms=int(input("enter the distance covered:")) if(kms<=1): price=20 print("the bill amount is",price) elif(kms<=4): ...
import argparse import sys import json from pprint import pprint """ LabelSum.py Author: Brian Fox Dougherty Operation: Given a JSON string which describes a menu, calculate the SUM of the IDs of all "items", as long as a "label" exists for that item. """ debug = 0 jsonFile = "" print(" ") print("------------...