text
stringlengths
37
1.41M
summation = 1000 def productOfTriplets(summation): for a in range(int(summation/3)): for b in range(int(summation/2)): c = 1000-a-b if( a**2 + b**2 == c**2): return a * b * c print( productOfTriplets(summation) ) x = input(' ')
def SumDivisibleBy(n,p): return n*(p/n)*((p/n)+1)/2 print( SumDivisibleBy(3,999) + SumDivisibleBy(5,995) - SumDivisibleBy(15,990) ) x = input(' ')
#POO y Funciones def saludo(): print ("== == == AMAZONAS - T2 IIC1103 == == ==") print ("Bienvenido a Amazonas!") def opciones_inicio(): print("") print("Las opciones de inicio son:") print("1 Empezar nuevo tablero") print("2 Cargar partida guardada") def cambiar_columna(ingreso): letra=ing...
def cambiar_columna(ingreso): letra=ingreso[0] letra = letra.lower() columna=0 if letra=="a": columna=1 elif letra=="b": columna=2 elif letra=="c": columna=3 elif letra=="d": columna=4 elif letra=="e": columna=5 elif letra=="f": column...
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) counts = dict() for line in handle: if not line.startswith("From "): continue words = line.split() emails = words[1] counts[emails] = counts.get(emails, 0) + 1 maxCount = None maxEmail = None for email,coun...
def check_routing_number(rn): if rn is None or not isinstance(rn, str) or len(rn) < 9: return False try: return (3*(int(rn[0]) + int(rn[3]) + int(rn[6])) + 7*(int(rn[1]) + int(rn[4]) + int(rn[7])) + (int(rn[2]) + int(rn[5])+ int(rn[8]))) % 10 == 0 except: return False print(check_r...
#!/usr/bin/python3 """ Module """ def read_file(filename=""): """ Function read_file """ with open(filename, 'r') as myFile: print(myFile.read(), end="")
numero_adivinar = 7 numero_usuario = int(input("elegi un numero a adivinar")) if numero_adivinar == numero_usuario: print("adivinaste!") else: intento_2 = int(input("intenta de nuevo")) if numero_adivinar == intento_2: print("ahora si has adivinado!") else: print("perdiste")
import random #instructions print("Welcome to Mastermind! Here are the instructions:\n4 numbers between 1 and 6 will be randonly generated. There may be repeated numbers.\n") print("Your job is to guess the set of 4 numbers in 10 tries!\nA 0 marks that there is a correct number in the correct spot.\nAn X marks that th...
import turtle as t def levi(l,n): t.pencolor("violet") if n == 0: t.forward(l) else: t.left(45) levi(l,n-1) t.right(90) levi(l,n-1) t.left(45) t.penup() t.setpos(-50, 0) t.pendown() l=5 n=10 levi(l,n)
#tuples used to return multiple values from a function, element values are immutable a_tuple = (1,2,3) #define with (), not like a list, but address a cell with [], like a list print(a_tuple[1]) print(type(a_tuple)) a_list = [1,2,3] print(type(a_list)) a,b,c = a_tuple print(a) # Definition of dictionary euro...
# From the insights from the analysis on haberman's dataset, we could get a insight that node and age played a vital in patients surivial. #Hence from the insights we have got we have created a model using Nodes and Ages def CancerModel(age,nodes): if nodes in range(0,3): print('Survival rate is 85% approx...
# Write a program to calculate the sum of n numbers. n = int(input('enter limit')) sum = 0 for i in range((n + 1)): sum = sum + i print(sum) """ enter limit5 15 """ # Write a program to find the biggest number from given three numbers. num1 = int(input('enter first no')) num2 = int(input('enter second no')) num3 ...
tuple = ("university", [5, 4, 6], (3, 2, 1)) # tuple[1][1] = 20 # tuple[2][2] = 0 # print(tuple) # TypeError: 'tuple' object does not support item assignment tuple = ("university", [5, 4, 6], [3, 2, 1]) tuple[1][1] = 20 tuple[2][2] = 0 print(tuple) # ('university', [5, 20, 6], [3, 2, 0])
class Student: regno = 101 name = 'Madhav' age = 15 def display(self): print(self.name) s1 = Student() s1.display() # Madhav # change name s1.name = 'shankar' s1.display() # shankar # inheritence class Person(): def __init__(self,name='madhav',age=15,email='madhav@gmail.com',phone=1234567...
# Image manipulation in python # PIL(Python Image Library), opencv, simplecv, Imagemagick # PIL from PIL import Image, ImageFilter img = Image.open('dog.jpg') img.rotate(45).show() img_sharp = img.filter( ImageFilter.SHARPEN ) mg_grey = img.convert("L") img_sharp.show() img_grey.show() # opencv import cv2 img = cv2....
import logging logging.basicConfig(level=logging.DEBUG, filename='w') # DEBUG, INFO, WARN, ERROR def sqrt(x, guess=1.0): if x < 0: logging.error("음수가 입력되었습니다.") raise ValueError logging.info("Find sqrt of {} starting with guess {}".format(x, guess)) if good_enough(guess, x): ...
class password: """ Class that generates new instances of password """ password_list = [] # Empty password list def save_password(self): ''' save_password method saves object in password list ''' password.password_list.append(self) def __init__(self, account_name...
import sys import os directory = sys.argv[1] list = os.listdir(directory) for fname in list: if "2017-08" not in fname: print("changing file: "+directory+"/"+fname) file = open(directory+"/"+fname, "r+", encoding="utf-8") #Move the pointer (similar to a cursor in a text editor) to the end...
import sys import cs50 import csv # Command line-arguments checking if len(sys.argv) != 2: sys.exit(1) # Open students.db open(f"students.db", "w").close() db = cs50.SQL("sqlite:///students.db") db.execute("CREATE TABLE students ( first TEXT, middle TEXT, last TEXT, house TEXT, birth NUMERIC)") # Open characters...
# counties = ["Arapahoe","Denver","Jefferson"] # counties_dict = {"Arapahoe": 422829, "Denver":463353, "Jefferson": 432468} # for county, voters in counties_dict.items(): # print(county, "county has", voters, "registered voters.") # print(f"{county} county has {voters} registered voters") voting_data...
import chess def move_to_index(move: chess.Move, current_player): """ A move in chess may be described in two parts: selecting the piece to move, and then selecting among the legal moves for that piece. We represent the policy π(a|s) by a 8 × 8 × 73 stack of planes encoding a probability distribution ...
from tkinter import * win =Tk() win.geometry("300x200") label= Label(win, text= "Select any One Language!", font= ("", 10)) label.pack(pady=30) clicked= StringVar() #Create an instance of Menu in the frame main_menu= OptionMenu(win, clicked, "C++", "Java", "Python", "Rust","Go","Ruby") main_menu.pack() win.mainloop(...
''' question: reverse the item at first index to the item at last index and item at last index to the item at first index. ''' def main(myList): x = myList[0] y = myList[-1] myList.pop(0) myList.pop(-1) myList.append(x) myList.insert(0, y) print(myList) myList = [10, 20, 50, 80] main(myLi...
splitString = "This string has been \nsplit over \nseveral \nlines" print(splitString) tabbedString = "1 \t2 \t3 \t4 \t5" print(tabbedString) print('the pet shop owner said "no, no \'e\'s uh\'s hresting"') print(''' "testing a trip quote " ''') print(""" heres a string broken \ over several lines""") #print("C:\us...
# Here is a universally applicable queue data structure in python. # Queues store items in the order in which they were added. # # - ticket lines at movie theaters # - printers in a lab # - event-driven systems # - simulation # - web client requests # - web server requests # - OS processes queue = [] queue...
def largest_prime_factor(prime_factor): number = 2 while number * number < prime_factor: while prime_factor % number == 0: prime_factor = prime_factor / number number = number + 1 return prime_factor print(largest_prime_factor(600851475143))
from pprint import pprint from Parser import Parser import util from math import log class VectorSpace: """ A algebraic model for representing text documents as vectors of identifiers. A document is represented as a vector. Each dimension of the vector corresponds to a separate term. If a term occurs in th...
import time left = str("left") no = str("no") yes = str("yes") def main(): print("You are at a path that splits 2 ways, there is a sign with arrows. The arrow pointing left says farm, and the arrow pointing right says town.") time.sleep(2) print("which way would you like to go?") ch...
# -*- coding: utf-8 -*- # importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values #Splitting dataset into Test and train from sklearn.model_selection imp...
import pygame from player import Player # Import our Player class from hurdle_handler import Hurdle_Handler WINDOW_SIZE = (720, 360) GROUND_Y = 280 def event_handler(): """ Returns all pygame events. Checks and handles the QUIT event. Returns: events (list): pygame events """ events = py...
#!/usr/bin/usr python3 import sys income=sys.argv[1] try: income=int(income) except: print('Error:',income) exit() taxable_income=income-3500 tax=0 if taxable_income<=1500: tax=taxable_income*0.03 elif taxable_income<=4500: tax=taxable_income*0.1-105 elif taxable_income<=9000: tax=taxable_income...
def zum(n): i=1 p=0 while i<=n: p += i i += 1 return p def zumsq(n): i=1 q=0 while i<=n: j = i**2 q += j i += 1 return q x = input('Compare sum squared and square sum up to? ') x=int(x) print('The sum squared up to and including ' + str(x) + ' is:') sqsum = zum(x) ** 2 print(sqsum) print('The ...
# Using the same file, add an instance attribute of is_hungry = True to the Dog class. # Then add a method called eat() which changes the value of is_hungry to False when called. # Figure out the best way to feed each dog and then output “My dogs are hungry" if all are hungry or “My dogs are not hungry.” if all are not...
''' https://www.tensorflow.org/tutorials/pdes ''' import tensorflow as tf import numpy as np ''' Kernel means local operation on 2D object (image, square lattice etc.) ''' def make_kernel(arr): ''' Take array as input ''' arr = np.asarray(arr) arr = arr.reshape(list(arr.shape)+[1, 1]) ...
numbers = [3, 4, 5, 23, 5, 7, 8] # print all numbers form the array for number in numbers: print(number) # find the maximum number in the array by linear search. This results in O(n) in worst case, space complexity is O(1) maximum = numbers[0] for num in numbers: if num > maximum: maximum = num print...
import unittest import capitalize_string class TestCapitalizedString(unittest.TestCase): def test_one_word(self): text = 'python' result = capitalize_string.cap_test(text) self.assertEqual(result, 'Python') def test_two_multiple(self): text = 'python test' result = ca...
def break_words(stuff): """This function will break up words for us""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words""" return sorted(words) def print_first_word(words): """Prints the first words after popping it off""" word = words.pop(0) print(word...
class Data(object): def __init__(self): self.tangerine = "And now a thousand years between" def apples(self): print("This is the fruit, not the computer company")
def cap_test(text): """ Inputs a string and capitalizes it and returns :param text: input text to be capitalized :return: returns the capitalized string """ return text.capitalize()
def ask_for_int(): while True: try: result = int(input("please provide an integer number > ")) except ValueError: print("Oops! Looks like input is not a valid integer") continue else: print("Yes! thank you") break if __name__ == "...
from time import sleep from random import randint class Entity: """ An entity has a name as well as the base materials for any RPG character or enemy. """ name: str hp: int xp: int lv: int max_hp: int max_xp: int atk: int defense: int def __init__(self,...
print("200000 100000") for i in range(0, 99999): print("z",end='') print("a",end='') for i in range(0, 100000): print("z",end='') print()
num_info=int(input()) dic={} for i in range(num_info): name,num = input().strip().split(' ') dic[name] = num for j in range(num_info): q = input() try: print(q+ '=' + dic[q]) except: print('Not found')
def swap_case(S): total = "" for s in S: if s.isupper() == 1 : total += s.lower() else: total += s.upper() return total if __name__ == '__main__': s = input() result = swap_case(s) print(result)
# Enter your code here. Read input from STDIN. Print output to STDOUT class Joo: def __init__(self,string): self.string=string self.length=len(self.string) def indexing(self): even="" odd="" for j in range(self.length): if j%2==0: even+=self.st...
#explanation의 식대로 함. meal_cost = float(input()) #12.00 tip_percent = int(input()) #20 tip_cost = meal_cost * tip_percent/100 #2.4 tax_percent = int(input()) #8 tax_cost = meal_cost * tax_percent/100 #0.96 total_cost = meal_cost + tip_cost + tax_cost #15.36 print(round(total_cost)) #15
#!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): ans = '' space = 0 for i in range(len(s)): if s[i]==' ': #빈칸이면 빈칸넣기 space = 1 #빈칸이 있다고 말하기 ans+=s[i] elif i==0 or (space>0 and s[i]!=' '): ...
# Enter your code here. Read input from STDIN. Print output to STDOUT Eng_num = int(input()) Eng_stu = set(input().split()) Fran_num = int(input()) Fran_stu = set(input().split()) ans=Eng_stu.intersection(Fran_stu) print (len(ans))
i = 4 d = 4.0 s = 'HackerRank ' # Declare second integer, double, and String variables. # Read and save an integer, double, and String to your variables. i2 = int(input()) # read int d2 = float(input()) # read double s2 = input() # read string # print summed and concatenated values print(i + i2) print(d + d2) print(...
def swap_case(s): output_s = '' for x in s: output_s += x.lower() if x.isupper() else x.upper() return output_s if __name__ == '__main__': s = input() result = swap_case(s) print(result)
def mutate_string(string, position, character): a=string[position] ans1=string[:position] ans2=string[position:] ans2=ans2[1:] ans2=character+ans2 return ans1+ans2 if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new)
import math if __name__ == '__main__': n = int(input()) for i in range(1,11): #1부터 11미만의 수를 합한다. result = n * i print( "%d x %d = %d" %(n,i,result))
from datetime import datetime, timedelta class TimeoutCalculator: """Keeps track of how much time is left""" def __init__(self, timeout_seconds): self._end_time = datetime.now() + timedelta(seconds=timeout_seconds) def time_left_now(self): now = datetime.now() if now > self._end_t...
class Player: ''' This class will carry information about the player do it will be wehere we put the encapsulation def get_guess(self): """Returns the player's last move (an instance of Move). If the player hasn't moved yet this method returns None. def get_name(self...
import numpy as np from joblib import wrap_non_picklable_objects __all__ = ['make_function'] class _Function(object): """A representation of a mathematical relationship, a node in a program. This object is able to be called with NumPy vectorized arguments and return a resulting vector based on a mathem...
#!/usr/bin/env python (Work in non-Windows Platform) #-*- encoding: utf-8 -*- () # Copyright (c) 2015 - Zhaoyu Lu <zylu@g.ucla.com> # N-Queen Solutions class Solution(object): # input: int # output: [[]...[]] def solveNQueens(self,n): if n==1: return [["Q"]] elif n<=0 or n==2 o...
num_grid = [ [1,2,3,4], [5,6,7,8], [22,26,27,28] ] print(num_grid[2][2]) print(num_grid[0][0]) # nasted loop for row in num_grid: for col in row: print(col) #print(num_grid)
num1 = float(input("enetr first num: ")) op = input("enetr operator: ") num2 = float(input("enetr second num: ")) if op == "+": print(num1+num2) elif op == "-": print(num1-num2) elif op == "/": print(num1/num2) elif op == "*": print(num1*num2) else: print("invalid")
import pdb num1 = 66 num2 = 99 num3 = num1*num2 print(num3) num4 = input("enter num4: ") phrase = "Giraffe academy" print(phrase.replace("aca", "YYY")) print(phrase.index("a")) print(phrase.index("aca")) print(phrase.index("a")) print(phrase.index("G")) print(phrase[0]) print(phrase[5]) print(phrase.lower() ) print...
# Ejemplo funcion recursiva sin retorno def cuenta_regresiva(numero): numero -= 1 if numero > 0: print(numero) cuenta_regresiva(numero) else: print("Fin") print(numero) print(cuenta_regresiva(5)) # Funcion recursiva con retorno def get_factorial(numero): if numero == 0: ...
# -*- coding:utf-8 -*- # 定制类 class Student(object): def __init__(self): self.name = 'Michael' s = Student() print s.name # 'Michael' # print s.score # you get an error # you can add an score into __init__() or do it like the following lines class Student2(object): def __init__(self): self.name = 'Michael' de...
# encoding:utf-8 # hello.py """ Here you can write multi line comment """ classmates = ['Bob','David','Nancy'] print classmates # ['Bob','David','Nancy'] print classmates[0] # 'Bob' david_index = classmates.index("David") # david_index = 1 print classmates[-1] # 'Nancy' # -1 means the last one,-2 means the one befo...
cipher = 'U8Y]:8KdJHTXRI>XU#?!K_ecJH]kJG*bRH7YJH7YSH]*=93dVZ3^S8*$:8"&:9U]RH;g=8Y!U92' def decoding(cipher): '''try to decoding cipher and show all result''' def transform(key): for alpha in key: beta = key[alpha] beta = chr(ord(beta) + 1) if ord(beta) > ord('Z'): ...
# -*-:coding:utf-8 -*- # 继承 多态 class Animal(object): def run(self): print 'Animal is running...' def eat(self): print 'I can eat.' class Dog(Animal): # override the super method def run(self): print 'Dog is running...' # call the super method def openYourMouth(self): return super(Dog, self).eat() cla...
# -*- coding:utf-8 -*- #字符串和文本 x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) print x print y # %r会显示变量的原始数据,即x是字符串,输出的时候会体现出来。 # raw representation,%r 适用于debug(调试) print "I said: %r." % x print "I also said: '%s'." % y hilario...
vowels='aiueoアイウエオあいうえお' vol = list(vowels) title =input('please enter the title name of book written in english or hiragana:') til = list(title) find = [] for letter in til: if letter in vol: if letter not in find: find.append(letter) print ('この本に含まれている母音はこれらです',find) print ('コンマを消すとこうなります:',''...
#!/usr/bin/env python # coding: utf-8 # In[17]: # In[71]: #Generacion De Dados from random import randint import matplotlib.pyplot as plot resultado = list() tiros = int(input("Ingresar La Cantidad De Tiros: ")) dado1 = [randint(1, 6) for p in range(1, tiros+1)] print(dado1) dado2 = [randint(1, 6) for p in rang...
# coding: utf-8 file = open('file.txt', mode='r', encoding='utf-8') for line in file: print(line) file.close() for line in file: print(line, end='') file.close() for line in file: print(line, end='\n') file.close() file.closed lst = ['Stanisław', 'Judyta'] lst file = open('file.txt', mode='a', encoding='utf...
# programowanie w Pythonie print("Witamy na lekcji Pythona") # zmienne a = input('Jan masz na imię? ') print('Jak się masz, '+a, '? ') x = int(input('podaj liczbę całkowitą x ')) y = int(input('podaj liczbę całkowitą y ')) print('liczba x = ', x) print('liczba y = ', y) # data swapping x,y = y,x print('zamieniamy ...
# -*- coding: utf-8 -*- """ Created on Mon Mar 7 16:31:25 2022 @author: Wojciech """ # LIczymy ciąg fibonacciego meetodą rekurencyjna n = int(input(' Podaj liczbę dodatnią ')) def fibonacci(n): if n == 1: return 1 if n == 2: return 1 return fibonacci(n-2)+fibonacci(n-1) print('liczba fibonacciego dla...
import unittest import math #Tester class # *a unit testing class that uses assertions # *all functions use assertions to test inputs # *function behaviour should be apparent from name class Tester(unittest.TestCase): def test_equal(self, input, expected): self.assertEqual(input, expected)...
#Example from "Artificial Intelligence with Python" - Prateek Joshi import numpy as np from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.externals import joblib from utilities import visualize_classifier # ...
import datetime import os import sys import time print("Hy user , Welcome to the R-Maill where you send your mails to anyones you want") class Email: def send_mail(self, sender_to_where,message): '''This method will send the message''' with open(f'{sender_to_where}.txt', "a") as send: ...
""" Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. Follow up: Could you write an algorithm with O(log n) runtime complexity? """ def searchRange(nums, target): res = [-1, -1] if ...
""" Search in Rotated Sorted Array Leetcode 33 """ def search(arr, target): """ Return index of the arr """ if not arr: return -1 # find the pivot left, right = 0, len(arr)-1 while left < right: mid = left + (right-left)//2 if arr[mid] < arr[right]: lef...
""" Function designed using generator """ def fibonacci(): """ Function sequence starts from a = 0, b = 1 """ a_value = 0 b_value = 1 i_value = 0 while True: if i_value == 0: yield a_value elif i_value == 1: yield b_value else: a_value, b...
""" Validating the 'convert' function """ def convert(temperature, input_unit, output_unit, rounding=0): ''' Converts temperature from F to C and C to F. Default rounding is 0 Syntax: convert(temperature, input_unit, output_unit, rounding=0) ''' if (input_unit == output_unit): return...
#!/usr/bin/env python3 from os import path class Graph: def __init__(self, directed=False): self.nodes_num = 0 self.edges_num = 0 self.directed = directed self.edges = list() self.nodes = list() self.graph_name = "default" self.adj_list = dict() self...
import timeit def find3numbers(n, A): sol = [] for i in range(n - 2): for j in range(i+1, n - 1): for k in range(j+1, n): x, y, z = A[i], A[j], A[k] if x < y < z: sol.append([x, y, z]) return sol def find3numbers_2(n, A): sol = ...
from sys import argv class LA: def __init__(self,file_object): self.file_object=file_object #输入文件 self.noOfLine=0 #读取到第几行 self.Token = { 'BEGIN': 'Begin', 'END': 'End', 'FOR': 'For', 'IF': 'If', 'THEN': 'Then', ...
print(4) print(4 + 5) a = 8 print(a) # intとか指定しなくていい -> =以降のもので型を判断してくれる print(a / 16) # int から小数に勝手に代わってくれる b = "あああああ" print(b) b = 7 print(b) # e=a/b+d #未定義のものは怒られる。(当然では?) # print(e) c="これはななですか" # print(b+c) 文字列と数字は結合できない(数字を文字列にするのは別の関数を使うのでは) # str()を使うらしい str(b) # 一時的に置き換えているだけのようだ # print(b+c)#error pr...
################データ型############## #①リスト---配列みたいなもの a=[0,1,2,3,4,5,6,7,8,9,]#index print(a[2]) print(a) a[6]=66#上書きできる a[0]=a[0]+3#足し算もできる print(a) b=["apple","byte","c++","dim"] print(b) b[2]=4 print(b)#リストは文字列も数値も区別しない #リストの中にリストを入れることも可能(2次元的な拡張だけど、大きさにルールはない) c=[[1,2,3,4],[2,4,6],[3,6,9,12,15]] print(c[1][2]) pri...
name = 'jack black' print(name.title()) first_name = 'Jack' last_name = 'Black' full_name = first_name + " " + last_name print('Hello,' + full_name + '!') print("\tPython") print('\nPython\nC++\nJava\nHtml') str1 = ' jack black ' print(str1.rstrip()) print(str1.lstrip())
# Copyright (c) 2019 by Erik Hvatum def flinereader(fpath): '''flinereader is a generator function that yields the content of the file specified by fpath, one line at a time, with trailing linefeed or linefeed & carriage return removed. Usage example: for line in flinereader("/foo/bar/baz.txt"): ...
import time import sys counter = 0 def tick(): time_start = time.time() seconds = 0 counter = 0 while True: time.sleep(1) seconds = int(time.time() - time_start) - counter * 5 if seconds >= 5: counter += 1 seconds = 0 return counter tick()
# Question 5 # Find the element in a singly linked list that's m elements from the end. For example, if a linked list has 5 elements, the 3rd element from the end is the 3rd element. The function definition should look like question5(ll, m), where ll is the first node of a linked list and m is the "mth number from the ...
""" Examples of using the NLTK token architecture for speech segmentation. The entire transcript is a single token, and each turn is a subtoken. The temporal span of a turn is just the location of the subtoken. """ from nltk.token import * from nltk.tokenizer import * import re class SignalLocation(SpanLocation): ...
## # numbers.py: Numbers helper module for Speech Tokenizer # # Author: David Zhang <dlz@students.cs.mu.oz.au> # Steven Bird <sb@cs.mu.oz.au> # URL: <http://nltk.sf.net> # For license information, see LICENSE.TXT # # This module contains various functions to process different kinds of # numbers, including digits, dec...
tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(list): c_width = 0 for row in list: for str in row: # find the longest word to correctly set column widt...
import pyinputplus as pyip # available choices bread = ["wheat", "white", "sourdough"] protein = ["chicken", "turkey", "ham", "tofu"] cheese = ["cheddar", "Swiss", "mozzarella"] extras = ["mayo", "mustard", "lettuce", "tomato"] # get inputs breadChoice = pyip.inputMenu(bread, "What type of bread?\n") proteinChoice = ...
#! python3 """ https://automatetheboringstuff.com/2e/chapter4/ Automate the Boring Stuff Chapter 4 Practice Project: Character Picture Grid """ grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', ...
#! python3 # open an encrypted pdf using brute force # only works if password is a single english word (found in provided dictionary) import PyPDF2 from time import time filePath = "encryptedfile.pdf" # PDF to crack start = time() # Tra...
import datetime, time print(datetime.datetime.now()) dt = datetime.datetime(2021, 12, 31, 23, 59, 59) print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) print(datetime.datetime.fromtimestamp(time.time())) delta = datetime.timedelta(days=11, hours=10, minutes=9, seconds=8) print(delta.days, delta.secon...
#!/usr/bin/env python # -*- coding:utf-8 -*- ######################################################################### # File Name: 242_Valid_Anagram.py # Author: Wang Biwen # mail: wangbiwen88@126.com # Created Time: 2016.06.26 ######################################################################### class Solution(o...
#!/usr/bin/env python # -*- coding:utf-8 -*- ######################################################################### # File Name: 2_add_two_numbers.py # Author: Wang Biwen # mail: wangbiwen88@126.com # Created Time: 2016.04.12 ######################################################################### # Definition for...
#CTI-110 #P2HW2 - Tip Tax Total #Brittany Lundy #06/19/2018 #Write a program that calculates the total cost of a meal purchased at a restaurant #The program should ask the user to enter the charge for the food. It should then calculate the amount ofthe tip and the amount for sales tax. #(Assume 18% tip and 7% s...
#!/usr/bin/python3 """ 100-my_int.py creates a rebellious MyInt() class """ class MyInt(int): """ MyInt is an int with == and != operators inverted """ def __eq__(self, other): """ Check if two MyInt's are equal """ return int(self) != int(other) def __ne__(self, other): """ Check...
#!/usr/bin/python3 """ 4-inherits_from.py checks if obj inherits from a_class """ def inherits_from(obj, a_class): """ inherits_from checks if obj is a subclass of a_class """ return issubclass(type(obj), a_class) and type(obj) is not a_class
#!/usr/bin/python3 """ 8-rectangle.py creates a Rectangle from BaseGeometry """ Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """ Square inherits from Rectangle """ def __init__(self, size): """ init """ self.integer_validator("size", size) self.__size = size...