text
stringlengths
37
1.41M
#My calculator calculates how far one can run using three inputs print("Filler") SPEED = int(input("What is your average speed (MPH) during (excluding break time) the run? ")) RUNTIME = int(input("How long (in MINTUES) will your ENTIRE run (including break time) be? ")) BREAKTIME = int(input("How long will your break ...
# გვაქვს n სართულიანი კიბე, ერთ მოქმედებაში შეგვიძლია ავიდეთ 1 ან 2 საფეხურით. # დაწერეთ ფუნქცია რომელიც დაითვლის n სართულზე ასვლის ვარიანტების რაოდენობას. #4 def stair_options(n): if n == 1 or n == 0: return 1 elif n == 2: return 2 else: return stair_options(n - 2) + stair_options(...
#!/bin/python3 import datetime class FridayFinder: def __init__(self, date): self.__date = date def get_days_to_friday(self): weekday = self.__date.weekday() return (4 - weekday) % 7 def get_next_friday(self): days_to_friday = self.get_days_to_friday() ...
#========================================================================= # SikkemaTHW3.py # Tyler Sikkema # Created June 4, 2016 # Last updated 6/8/2016 # Abstract: Used for calculating total pay #========================================================================= global HOURLY_PAY_RATE global COMMISSION_RATE ...
pt1 = [(50, 0), (170, 180), (210, 250)] pt2 = [(50, 0), (170, 170), (210, 250)] union = set(pt1) | set(pt2) intersection = set(pt1) & set(pt2) difference = set(pt1) - set(pt2) print(union) print(intersection) print(difference)
lista = [1,2,3,4,5,6,7,8,9,10] print("Lista: ",lista) lista.reverse() print("Lista Invertida: ",lista)
import pyglet def center_image(image): """Sets an image's anchor point to its center""" image.anchor_x = image.width / 2 image.anchor_y = image.height / 2 # Tell pyglet where to find the resources pyglet.resource.path = ['./resources'] pyglet.resource.reindex() # Load the three main resources and get t...
import sys for line in open(sys.argv[1], 'r').readlines(): s = line def reverse(st): rev = "" for p in st: rev = p + rev return rev n = len(s) r = reverse(s) def findPal(s, r, n): m = [0] * (n+1) for a in range(n+1): m[a] = [0] * (n+1) root = [0] * (n+1) for a in rang...
import matplotlib import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns def lecture(): df = pd.read_csv('russian_housing.csv') df.head() # Size of dataset print("Number of rows/columns: ", df.shape) print("Data types: ", df.dtypes) # Select the numeric ...
class Account: #Input: account number, amount initally in account, account name, dictionary of all accounts #Output: account object #Description: creates an account object which has an account number, amount in it, account name, #and adds it to the account dict def __init__(self, account, amount, name, accountDic...
from Account import Account import os.path import pdb #Nicholas Petrielli 10107308 #Andrew Storus 10103737 #Jordan McGregor 10052770 #The intention of this program is to implement a backend of a banking system. #The backend reads in the input files given which are a merged transaction summary file and a master acco...
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # Find the minimum element. # You may assume no duplicate exists in the array. import sys def find_minimum(sorted_arr): min = sorted_arr[0] for ele in sorted_arr...
# #Entrada de datos # numero1 = 10 # numero2 = 15 # # Calculos y/o Operaciones # suma = numero1 + numero2 # # Salida de datos # print("Suma = " + str(suma)) # print(f"Suma = {suma}") # se debe configurahdr # numero3 =float(input("Escribe un numero: ")) numero3 =int(input("Escribe un numero: ")) numero4 = input("Es...
#!/usr/bin/python #-*- coding: utf-8 -*- #author=moc #Use Babyloninan (aka simplified Newton's) to solve square root from math import log10 from math import ceil from math import floor from math import sqrt number=70000 num_digit=int(ceil(log10(number))) print num_digit #determine the start point, reduce calculatio...
import time up = True n = 0 i = 50 while True: if up: n += 1 if n == i: up = False if not up: n -= 1 if n == 0: up = True print("#" * n) time.sleep(0.01)
print("Hello") print("World") print("maar") print("dan") print("nu") print("verdeeld") print("over") print("meerdere") print("regels") tekst = "hello world maar dan nu over meerdere regels" tekst_los = tekst.split(" ") for regel in tekst_los: print(tekst_los) ''' maak dit makkelijker zodat je slechts 1 keer p...
""" You have 6 sticks of lengths 10, 20, 30, 40, 50, and 60 centimeters. Find the number of non-congruent triangles that can be formed by using three of these sticks as sides  """ # The length of any side of a triangle must be larger # than the positive difference of the # other two sides, but smaller than the...
''' This is proposed as a semplificate example of Object oriented programming in python''' #Definition of super class who define the properties of an account class Account: #Class Initialization def __init__(self, name, accountNumber): self.name = name self.accountNumber = accountNumber #Definitio...
class Hero: def __init__(self, name, health, attack, armor): self.name = name self.health = health self.attack = attack self.armor = armor def serang(self, lawan): print(self.name + ' menyerang ' + lawan.name) lawan.diserang(self, self.attack) def diserang(s...
#ARRAY & List #Memory allocation is static/fixed #List() #Datatype is heterogeneous #Memory Allocation is dynamic n=5 groclist=[] print(type(groclist)) #<class 'list'> i=1 while i<=5: elem = input("Enter grocery elements : ") groclist.append(elem) i+=1 #list can have heterogeneous data #But since it...
#Program 2 #Matrimony eligibility #Enter Name #Enter Gender #Enter Year of Birth (Date of Birth ( Year of Birth ) find out Age) import datetime name=input("Enter Name : ") gender=input("Enter Gender (M/F) : ") c=input("Enter Year of Birth: ") yr=int(c) #curr=now.year curr=2019 if(gender == "M"): if((cu...
class CarBase: def __init__(self, brand, speed, tires): self.brand = brand self.speed = speed self.tires = tires def __str__(self): return f"'{self.brand}' mooves using {self.tires} with {self.speed} km/h." class Car(CarBase): def __init__(self, brand, speed,...
for i in range(1, 101): num = "" if i % 3 == 0: num += "Fizz" if i % 5 == 0: num += "Buzz" print(num or i)
import time def timer(num): def decor_func(func): def wrapper(): full_run_time = 0 result = 0 for _ in range(num): start_time = time.perf_counter() value = func() end_time = time.perf_counter() run_time =...
""" This file contains the logic of the program This file has the main functions 1.) load_cencus_data 2.) filter_data_by_colom and floor This file also imports few modules namely 1.) os 2.) sys 3.) helper - self designed to help with the program 4.) csv - to read csv file """ ...
def convertWords(words): result = "" for i in range(0, len(words), 2): result += (words[i] + "\t" + words[i+1] + "\n") return result ## Raw text conversion def convertFromConsole(): print("Enter/Paste your words (press Ctrl-D or Ctrl-Z on Windows when finished):") words = [] while True: try: words.append(...
# coding = utf -8 import threading def sum(a): print(a+2) threads = [] for i in range(3): #print(i) t = threading.Thread(target=sum,args=(i,)) threads.append(t) for j in threads: j.start()
from tkinter import * root = Tk() root.title("Simple Calculator") e = Entry(root, width=50, borderwidth=10) e.grid(row=0, column=0, columnspan=3) #padx=10, pady=10) def button_click(number): current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def button_add(): ...
import re usr_inpt=str(input("Enter String: ")) srch_exp=re.findall("Inform.",usr_inpt) print(srch_exp) ############################################################# import re usr_inpt=str(input("Enter String: ")) srch_exp=re.findall("Inform",usr_inpt) for i in srch_exp: print(i) #############################...
# nomber1 = int(input("Введите первое число")) # nomber2 = int(input("Введите второе число")) # nomber3 = int(input("Введите третье число")) # print(nomber1 + nomber2 * nomber3) # texst1 = input("Введите первое число") # texst2 = input("Введите второе число") # print(texst1 + "+" + texst2 + "= дружба на века")
a = "" a = "Переправа, переправа, берег левый, берег, правыыый" # print(a) # print(a[1]) # print(a[-2]) # print(a[:9]) # print(a[28:34]) # print(a[35:]) # print(a[-12:-1]) print(a[::5]) print(a[:9:3]) print(len(a)) print(a.upper()) print(a.lower()) print(a.title()) print(a.count("берег")) print(a.find("берег")) print(a...
#!/usr/bin/python # -*- coding: utf-8 -*- class operacion: def __init__(self): print "-----Bienvenido al juego 2048-----" def iniciarJuego(self): import random global n n = 4 global matriz matriz = [[0] * n for f in range(n)] for f in range(n): for c in range(n): num=random.randint(0,...
print("\t1") def hello(): for i in range(3): print("Hello World") hello() print("=========================") print("\t2") def tong(a,b): print(a+b) tong(3,6)
#!/usr/bin/python3 """ @Time : 2019/3/31 @Author : Mei Zhaohui @Email : mzh.whut@gmail.com @Filename: person.py @Software: PyCharm @Desc : basic class """ class Person: """say hello & count the num""" # 定义类的docstring num = 0 # 定义类变量 # 定义类的方法 # 初始化类 def __init__(self, name): ""...
import unittest from typing import List class Solution: def distributeCandies(self, candyType: List[int]) -> int: n = len(candyType) // 2 unique_candy_type = set(candyType) return n if n < len(unique_candy_type) else len(unique_candy_type) class TestSolution(unittest.TestCase): ...
# 1. Реализовать подсчёт елементов в классе Matrix с помощью collections.Counter. # Можно реализовать протоколом итератора и тогда будет такой вызов - Counter(maxtrix). Либо сделать какой-то # метод get_counter(), который будет возвращать объект Counter и подсчитывать все элементы внутри матрицы. # Какой метод - ваш вы...
# coding=utf-8 """ Abstract Service """ __author__ = 'Seray Beser' from abc import abstractmethod class AbstractService(object): """ Abstract Service for importing and exporting data """ def __init__(self, url='localhost'): """ :param url: Default url is `localhost` """ ...
#!/usr/bin/env python3 """ @author: David Bonilla Castillo (dmgf2008@hotmail.com) @version: 1 """ import socket import sys import logging class PortScanner(): """Simple PortScanner Scans a single port or a range, returns dictionary with True/False """ verbose = False def __init__(self): r...
# recursive def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) def fibonacci1(n): f = [0, 1] for i in range(2, n+1): f.append(f[i-1] + f[i-2]) return f[n] if __name__ == '__main__': print(fibonacci(11)) print(fibon...
""" Explanation of The Solution The driver function takes into account the order and the warehouses. A) Assumptions: 1. Best way to ship order is by using minimum number of warehouses. 2. The quantities can be postitive or zero but never negative. 3. The cost of items/inventory in each warehouse is same. B) Priorit...
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits import mplot3d from numpy.lib.function_base import meshgrid from mpl_toolkits.mplot3d.axes3d import Axes3D def plot(y): """ plot helps to plot the graph of a function defined as y(x). It accepts: > arg (String): I...
with open('scrabble_list2.txt') as f: words = f.read().splitlines() if len(words[1:6]): print (len(words)) with open('scrabble_list2.txt') as f: words = f.read() count = 0 for w in words: if w[:3] == 'r': count += 1 print(count) file = ...
""" Tovar, Brianna CS2302 Aguirre Diego, TA Eduardo 11/30 Lab 6: Kruskal's Algorithm and Topological Sort """ from collections import defaultdict class Graph: def __init__(self,vertices): self.graph = defaultdict(list) """ dictionary used to contain the list of edges, ve...
from room import Room from player import Player from world import World import random from random import choice from ast import literal_eval # from graph import Graph from util import Queue, Stack, Graph # Load world world = World() # You may uncomment the smaller graphs for development and testing purposes. # map_f...
import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors X=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] Y=[2,5,7,9,11,16,19,23,22,29,29,35,37,40,46,42,39,31,30,28,20,15,10,6] X=np.array(X).reshape(-1,1) y=np.array(Y) plt.plot(X,Y,'ro') x0=np.linspace(3,25,10000).reshape...
classList = [12345, 23456] def removeStudent(pawPrint): if (pawPrint in classList): classList.remove(pawPrint) return True def checkStudent(pawPrint): #Check if student ID is valid count = 0 paw = pawPrint while(pawPrint>0): count = count+1 pawPrint = pawPrint//10 ...
#!/usr/bin/python2 # -*- coding:utf-8 -*- ## TODO:TODOリストを作成する ## TODOリストとして、「内容/完了フラグ」を基本 import sqlite3,sys def showAllTodo(): db_connecter = sqlite3.connect("data.db") cursor = db_connecter.cursor() cursor.execute("select todo,flg from todo_list") result = cursor.fetchall() print "==TODO Lists==" for row...
from random import randrange '''global variables''' board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"] '''methods''' def resetBoard(): global board x = 0 while x < len(board): board[x] = str(x) x += 1 printBoard() def printBoard(): print() print(board[0] + " " + board[1...
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Employee(dict): Employees = [] def __init__(self, position=None, name=None, surname=None, plz=None, city=None, phonenumber=None, organisation = None, qualification = None, image=None, street=None, personalwebsite = None, email=None, xing=None): d...
#/usr/bin/python3 # #dict loop tips print("=" * 100) print("5.6 dict") print("=" * 100) #use items to get key and value d1 = {'key1':'value1', 'key2':'value2','key3':'value3'} for k,v in d1.items(): print("{} : {} , {}".format(k,v,d1[k])) #enumerate to get list index for i,v in enumerate([5,6,7,8,9]): print(...
#5-2 del #del: delete list element or clear list a=[1,2,3,4,5,6] del a[0] print(a) #5-3 tuples and sequences t=123,45,"a" print(t) u=t,(0,1,2,3) print(u) #5-4 Set newSet={"a","b","c"} #or use set() otherSet=set(["b","c","d"]) print(type(newSet)) print(newSet) print(otherSet) print(newSet | otherSet) # or a={x f...
#/usr/bin/python3 # #Class print("=" * 100) print("10.11 Quality Control") print("=" * 100) #doctest import doctest def average(values): """ This is average >>> print(average([1,2,3,4])) 2.5 """ return sum(values) / len(values) doctest.testmod() #comlated: unittest i...
#/usr/bin/python3 # #data structure print("=" * 100) print("5.1 List") print("=" * 100) l = list(range(10)) print(l) l.append(11) print(l) l2 = list(range(15,21)) l.append(l2) print(l) #extand iterable item l.extend(l2) print(l) l.insert(0,'a') print(l) #remove the first value equal given, return valueErr if not foun...
#encoding: utf-8 print ("hello world") print("a\tb") #a b # use r before quote can be raw string print(r"a\tb") # a\tb print("""three double quote or singo quote can show new line in the string ,but use \\ can break warp text \ ... """) word='hello world' print(word[1]) #h print(word[-1]) #d prin...
#/usr/bin/python3 # #Class print("=" * 100) print("9.9 Generator") print("=" * 100) #generator is a tool for creating iterators. use yield to return the object. #when generator invoke next() function, it will goto last leave point . #generator will create __iter__() and __next__() function automatically def reverse(d...
if __name__ == '__main__': record = '....................100 .......513.25 ..........' SHARES = slice(20, 32) PRICE = slice(40, 48) cost = int(record[SHARES]) * float(record[PRICE]) print(f'cost: {cost}') words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', '...
from collections import deque if __name__ == '__main__': q = deque(maxlen=3) q.append(1) q.append(2) q.append(3) print(f'append 1 2 3, {q}') q.append(4) print(f'append 4, {q}') q.append(5) print(f'append 5, {q}')
###################################################### # Function 1 def first_past_the_post(votes): ''' Count the votes for each candidate and return the winner. Takes a list of strings, with one instance of candidate's name as a vote. NOT case-sensitive. Returns tie if winning votes are equal.''' ...
loop = int(raw_input()) numer=0 while loop!=0: loop-=1 string_inp = raw_input().split(".") teststr = string_inp[1] for i in range(len(teststr)): if teststr[i]=="a" or teststr[i]!='i' or teststr[i]!='o' or teststr[i]!='u' or teststr[i]!='e': numer+=1 print numer+"/"+len(teststr)
DIRECTIONS = {'U': (0, 1), 'R': (1, 0), 'D': (0, -1), 'L': (-1, 0), } def main(): input_file = '../inputs/03.txt' wires = [] with open(input_file, 'r') as fh: for line in fh: wire = wire_from_steps(line.split(',')) wir...
class Environment: """This class emulates an infinite BrainCurry environment, including a memory tape and a pointer to the current cell.""" def __init__(self, max): self.max = max self.tape = Tape() self.pointer = 0 self.stash = [] # A stack to stash state data on for rever...
#Anastasia Douka #260768503 import doctest def which_delimiter(string): ''' (str)-> str This function returns the most commonly used delimiter. >>> which_delimiter('0 1 2, 3') ' ' ''' delimiterDict = {} #empty dict where we will put delimiters for char in string: if char == ' ' ...
# Pedir dos numeros por teclado, si el primer numero es mayor que el segundo, intercambiarlos aux = 0 a = int(input("Digita el primer numero: ")) b = int(input("Digita el segundo numero: ")) print("") print("El primer numero es: ",a, "y el segundo numero es: ",b) if a > b: aux = a a = b b = aux print("El...
# if x = 30 if x < 20: print('X es menor que 20') else: print('X es mayor que 20') print('------------------------------------') color = 'verde' if color == "rojo": print('El color es rojo') elif color == "azul": print('El color es azul') else: print('cualquier color') print('-----------...
# preguntar al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas. clave = 'entrada' password = input("Escriba la contraseña de ingreso: ") if clave == password.lower(): print("Contraseña...
# Escribir un programa que pida al usuario su peso (en kg) y estatura (en metros), calcule el índice de masa corporal y lo almacene en una variable, e imprima por pantalla la frase Tu índice de masa corporal es <imc> donde <imc> es el índice de masa corporal calculado redondeado con dos decimales. print("") peso = inp...
# type: que tipo de variable es print(type(98)) # int print(type(43.4)) # float print(type("Hola")) print("--------------------------------------------") # ** : al cubo print('2 al cubo es: ' ,2 ** 3) # 8, 2*2=4*2=8 # % : muestra el residuo de una division print('El residuo de la division 3 % 2 es: ' ,3 % 2) # / : ...
a = int(input('Digite o primeiro número: ')) b = int(input('Digite o segundo número: ')) c = int(input('Digite o terceiro número: ')) if a < b and b < c: print('crescente') else: print('não está em ordem crescente')
# randomgraphics.py import random import matplotlib.pyplot as plt class Diegraphic: """"Clase para graficar lanzamientos con uno o m�s dados""" def __init__(self, nlanz=0, ndies=1, nfaces=6): self.ndies = ndies self.nfaces = nfaces self.nlanz = nlanz posibles_res...
import unittest from models import articles articles = articles.Articles class articlesTest(unittest.TestCase): ''' Test Class to test the behaviour of the articles class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_articles = arti...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 1. 检查先决条件 2. 定义子程序要解决的问题 3. 为子程序命名 4. 决定如何测试子程序 5. 在标准库中搜寻可用的功能 6. 考虑错误处理 7. 考虑效率问题 8. 研究算法和数据类型 9. 编写伪代码 1. 首先简要地用一句话来写下该子程序的目的, 2. 编写很高层次的伪代码 3. 考虑数据 4. 检查伪代码 10. 在伪代码中试验一些想法,留下最好的想法 ''' class Solution: def nthUglyNumber(self, n): """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 1. 检查先决条件 2. 定义子程序要解决的问题 3. 为子程序命名 4. 决定如何测试子程序 5. 在标准库中搜寻可用的功能 6. 考虑错误处理 7. 考虑效率问题 8. 研究算法和数据类型 9. 编写伪代码 1. 首先简要地用一句话来写下该子程序的目的, 2. 编写很高层次的伪代码 3. 考虑数据 4. 检查伪代码 10. 在伪代码中试验一些想法,留下最好的想法 ''' class Solution: def judgeCircle(self, moves): """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 1. 检查先决条件 2. 定义子程序要解决的问题 3. 为子程序命名 4. 决定如何测试子程序 5. 在标准库中搜寻可用的功能 6. 考虑错误处理 7. 考虑效率问题 8. 研究算法和数据类型 9. 编写伪代码 1. 首先简要地用一句话来写下该子程序的目的, 2. 编写很高层次的伪代码 3. 考虑数据 4. 检查伪代码 10. 在伪代码中试验一些想法,留下最好的想法 ''' class Solution: def strStr(self, haystack, needle): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from Stack.ArrayStack import ArrayStack class Solution: def calPoints(self, ops): """ :type ops: List[str] :rtype: int """ self.mystack = ArrayStack() self.mystack.push(0) self.mystack.push(0) for op in...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 1. 检查先决条件 2. 定义子程序要解决的问题 3. 为子程序命名 4. 决定如何测试子程序 5. 在标准库中搜寻可用的功能 6. 考虑错误处理 7. 考虑效率问题 8. 研究算法和数据类型 9. 编写伪代码 1. 首先简要地用一句话来写下该子程序的目的, 2. 编写很高层次的伪代码 3. 考虑数据 4. 检查伪代码 10. 在伪代码中试验一些想法,留下最好的想法 ''' # Definition for singly-linked list. # class ListNode(object):...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ if no...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 1. 检查先决条件 2. 定义子程序要解决的问题 3. 为子程序命名 4. 决定如何测试子程序 5. 在标准库中搜寻可用的功能 6. 考虑错误处理 7. 考虑效率问题 8. 研究算法和数据类型 9. 编写伪代码 1. 首先简要地用一句话来写下该子程序的目的, 2. 编写很高层次的伪代码 3. 考虑数据 4. 检查伪代码 10. 在伪代码中试验一些想法,留下最好的想法 ''' class Solution(object): def findMaxConsecutiveOnes(self, n...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 1. 检查先决条件 2. 定义子程序要解决的问题 3. 为子程序命名 4. 决定如何测试子程序 5. 在标准库中搜寻可用的功能 6. 考虑错误处理 7. 考虑效率问题 8. 研究算法和数据类型 9. 编写伪代码 1. 首先简要地用一句话来写下该子程序的目的, 2. 编写很高层次的伪代码 3. 考虑数据 4. 检查伪代码 10. 在伪代码中试验一些想法,留下最好的想法 ''' # Definition for singly-linked list. # class ListNode(object):...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution: def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ while val in nums: nums.remove(val) return len(nums) sol = Solution() assert sol.removeEle...
import os import sys def start(): while True: choice = int(input("Enter number: 1-encode, 2-decode, 3-quit\n")) if choice == 1: encrypt() elif choice == 2: decrypt() elif choice == 3: break else: print("Unknown command") ...
from node import Node class Queue: def __init__(self): self.size = 0 self.first = None self.last = None def isEmpty(self): return self.size == 0 def enqueue(self, val): node = Node(val) if self.isEmpty(): self.first = node else: ...
############################## # define class ############################## # class Classname(object): Chang's example # <define attributes here> """ import math class Coordinate(object): # this class define a coordinate with x any y attribue def __init__(self,x,y): self.x = x self.y = y #...
import time, os, sys, transpo_encrypt, transpo_decrypt def main(): input_filename = 'frankenstein.txt' output_filename = 'frankenstein.encrypted.txt' my_key = 10 my_mode = 'encrypt' # if the input file does not exist, the program terminates early if not os.path.exists(input_filename): ...
import unittest import data import output class DataTest(unittest.TestCase): def setUp(self): self.student1 = data.Student("1", "A") self.test1 = data.Test("1", "1", "10") self.test1.marks['1'] = "78" self.test2 = data.Test("2", "1", "40") self.test2.marks['1'] = "87" ...
## A Word Game: Words With Friends / Scrabble # Part 1: Word Scores def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. """ score = 0 SUM = 0 for char in word: SUM += SCRABBLE_LETTER_VALUES[char] if len(word) == n: score = (SUM)*le...
def cubeRoot(n): t = 0 for i in range(abs(n)): t += 1 if i**3 == abs(n): break print(t) if i**3 != abs(n): print('Not') else: if n < 0: i = -i print(str(i)+ ' is cube root of ' + str(n))
import math import random class Node: def __init__(self, value): self.value = value self.children = {} def print_tree(self): a = [self.value] for key, test in self.children.items(): a.append(self.children[key].print_tree()) return a def print_tree_te...
# Euler - problem 56 """A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, a^b, where a, b < 100, what is the maxim...
# Euler - problem 22 """Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name...
#Euler - problem 5 """ 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?""" # This code solves the more general problem of finding the smallest positive integer eve...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 15 09:02:12 2020 @author: trismonok """ import socket import sys # create a socket (coonnect two computer) def create_socket(): try: global host global port global s host = "" port = 9999 ...
class Human: def __init__(self, name, age=0): self._name = name self._age = age def _say(self, text): print(text) def say_name(self): self._say(f'Hello, I am {self._name}') def say_how_old(self): self._say(f'I am {self._age} years old') class Planet: de...
class EvenLengthMixin: def even_length(self): return len(self) % 2 == 0 class MyList(list, EvenLengthMixin): def pop(self): x = super(MyList, self).pop() print('Last value is', x) return x class MyDict(dict, EvenLengthMixin): pass x = MyDict() x['key'] = 'value' x['anot...
import pandas as pd s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']) print(s) d = {'Moscow': 1000, 'London': 300, 'New York': 150, 'Barcelona': None} cities = pd.Series(d) print(cities) print(cities['Moscow']) print(cities[['Moscow', 'London']]) print(cities < 1000) print(cities[cities < 1000]) cities['Moscow...
def bubble_sort(A): """ Sort on place with Bubblesort algorithm :type A: list """ for bypass in range(1, len(A)): for k in range(0, len(A) - bypass): if A[k] > A[k+1]: A[k], A[k+1] = A[k+1], A[k] def test_sort(): A = [4, 2, 5, 1, 3] B = [1, 2, 3, 4, 5] ...
class User: def __init__(self, name, email): self.name = name self.email = email def get_email_data(self): return { 'name': self.name, 'email': self.email } jane = User('Jane Doe', 'janedoe@example.com') print(jane.get_email_data()) class Singleton: ...
import re from abc import ABC, abstractmethod # create system class System: def __init__(self, text): tmp = re.sub(r'\W', ' ', text.lower()) tmp = re.sub(r' +', ' ', tmp).strip() self.text = tmp def get_processed_text(self, processor): result = processor.process_text(self.text...
from pprint import pprint import requests city = input('City? ') api_key = 'e7bb679b81c3710fc4192bcc1018a907' api_url = 'http://api.openweathermap.org/data/2.5/weather' params = { 'q': city, 'appid': api_key, 'units': 'metric' } 'https://api.openweathermap.org/data/2.5/weather?q=Moscow&appid=e7bb679b81c...
if x%3 == 0: print("Число делится на три.") elif x%3 == 1: print("При делении на три остаток - один.") else: assert x%3 == 2 # assert здесь является комментарием, гарантирующим истинность утверждения print("Остаток при делении на три - два.")
''' class Counter: def __init__(self): self.count = 0 def inc(self): self.count += 1 def reset(self): self.count = 0 print(Counter) x = Counter() x.inc() print(x.count) Counter.inc(x) print(x.count) x.reset() print(x.count) ''' class b: a = 0 def __init__(self): self.a = 100 def foo(sel...