text
stringlengths
37
1.41M
#!/usr/bin/env python import glob import re import os import sys import argparse # Function to load in a variable all terms to be searched # # input: file name # return: array def loadSearches(fileName): toSearch = None with open(fileName) as origin_file: toSearch = origin_file.readlines() return...
import re def op(to_calc): if "+" or "-" or "x" or "/" in to_calc: to_calc = re.split("(\D)",to_calc) while len(to_calc) > 2: a = to_calc[0] b = to_calc[2] if to_calc[1] == "+": c = int(a) + int(b) elif to_calc[1] == "-": c = int(a) - int(b) elif to_calc[1] == "x": c = int(a) * int...
#!/usr/bin/python #Filename:simplestclass.py class Person: def __init__(self, name): self.name = name def sayHi(self): print 'how are you?', self.name p = Person('LiLei') p.sayHi()
import math import random import turtle import os # set up screen wn = turtle.Screen() wn.bgcolor("dark blue") wn.title("Turtle Defender") wn.bgpic("turtle_fighter_background.gif") # register the shapes # draw border border_pen = turtle.Turtle() border_pen.speed(0) border_pen.color("light blue") ...
print("Welcome to Treasure Island.") print("Your mission is to find the treasure.") #https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26export%3Ddownload first_choice ...
#https://repl.it/@MashaPodosinova/coffee-machine-start#main.py MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24...
#link to Repl #https://repl.it/@MashaPodosinova/blind-auction-start#main.py from replit import clear #HINT: You can call clear() to clear the output in the console. from art import logo print(logo) data={} auction_in_progress = True while auction_in_progress: name = input("What is your name?: ") bid = int(i...
# -*- coding: utf-8 -*- """ Created on Thu Mar 4 17:06:58 2021 @author: Kovid """ from datetime import timedelta def seconds_to_text(secs): days = secs//86400 hours = (secs - days*86400)//3600 minutes = (secs - days*86400 - hours*3600)//60 seconds = secs - days*86400 - hours*3600 - mi...
class Node(object): def __init__(self,data): self.data=data self.link=None class LinkedList(object): def __init__(self): self.head=None self.size=0 def insertend(self,data): if not self.head: self.head=data else: actucal=se...
########## #Question# ########## ''' URL: https://leetcode.com/problems/minimum-depth-of-binary-tree/ Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example 1: ...
########## #Question# ########## ''' URL: https://leetcode.com/problems/longest-common-prefix/ Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2...
########## #Question# ########## ''' URL: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/submissions/ Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the dept...
########## #Question# ########## ''' URL: https://leetcode.com/problems/pascals-triangle-ii/ Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle. Notice that the row index starts from 0. In Pascal's triangle, each number is the sum of the two numbers directly above it. Follow up: Could yo...
x = input('please enter your name x :') if( len(x) <5) : print('your name is short') if (len(x)>5): print('your name is correct')
__author__ = 'willflowers' import random class Game: def __init__(self, player): self.player = player def start(self): player = Player() if self.player.turns <= 8: player.start() else: return self.player.score class Player: def __init__(self...
import copy class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current....
import csv # ? Reading a csv file and printing. # with open('data.csv', 'r') as csv_file: # csv_reader = csv.reader(csv_file) # # To allow us to skip the first line. # next(csv_reader) # for line in csv_reader: # ? Write the contents into a new file, with - delimiter # with open('data.csv', 'r'...
import random class dado: def __init__(self, lados): self.lados = lados def jogar_dados(self): while True: print(random.randrange(1, (self.lados)+1)) while True: continuar = input("Continuar jogando ? (S/N)") if continuar == "N" or conti...
class Solution: def compareString(self, str1, str2): v1Int = int(str1) if str1 != "" else 0 v2Int = int(str2) if str2 != "" else 0 if v1Int > v2Int: return 1 elif v1Int < v2Int: return -1 else: return 0 def compareVersion(self, version...
class Solution: def toLowerCase(self, str): """ :type str: str :rtype: str """ LOWER_UPPER_DIFF = 32 newStr = "" for c in str: asciiValue = ord(c) if asciiValue >= 65 and asciiValue <= 90: # is Uppercase c = chr(asciiVal...
import pandas as pd # import numpy as np # import csv df = pd.read_csv("C:/Users/iamay/Desktop/PY/data/nyc_weather.csv") print(df) print(df.head()) print(df.tail()) print(df.columns) print(df['EST']) print(type(df['EST'])) print(df['Temperature']['EST']) print(df['WindSpeedMPH'].min()) print(df['EST'][df['Temperature'...
#key modification import sys def alphabet(): #alpha= "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #Entering the alphabets in string. alpha= "" #Generate the alphabet for i in range(0,26): alpha = alpha + chr(i+65) return alpha def Remove_dup_specialchar(key): #Removing numbers or special characters...
import numpy as np # 原函数 def F(x): return x**3 + x**2 + x - 3 # 导数 def f(x): return 3*x**2 + 2*x + 1 # 牛顿迭代法 def Newton(x): return x -F(x) / f(x) #初值 x = -0.7 e0 = 1.7 for i in range(7): print(i) x = Newton(x) print("x=", x) print("e=", np.fabs(x - 1)) print("e_{i}/e_{i-1}=", np.fabs(x -...
import sqlite3 connection = sqlite3.connect('data.db') cursor = connection.cursor() create_table = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text,password text)" # Execute table creation cursor.execute(create_table) create_table = "CREATE TABLE IF NOT EXISTS items (name text, price real)" #...
a = input("nhap du lieu ") import string for i in a: if 97<= ord(i) <= 122: u = ord(i)-32 for t in string.ascii_uppercase: if ord(t) == u: a = a.replace(i,t) print(a)
class Rectangle: def __init__(self,l,w): self.a = l self.b = w def area(self): c = self.a*self.b return c i = Rectangle(5,10) print(i.area())
class MySingleton: are_we_instantiated_value = None ''' __new__ happens even before __init__ that would be a constructor for the object created so that's the "first step". We override the __new__ method with the tracked class variable that is called "are_we_instantiated_value". We first set the "ar...
intervals = [[1,3],[2,4],[5,7],[6,8]] def custom(a,b): return a[0]-b[0] intervals.sort(cmp =custom) stack = [] for interval in intervals: if stack==[]: stack.append(interval) else: old = stack.pop() if interval[0]<=old[1]: if interval[1]>old[1]: ...
a = [1,3,0,5,8,5] b = [2,4,6,7,9,9] c =[] for i in range(len(a)): c.append((a[i],b[i])) def cusort(a,b): return a[1]-b[1] c.sort(cmp = cusort) print 0, prev = c[0][1] for i in range(1,len(c)): start = c[i][0] if start>prev: print i, prev = c[i][1]
string = "abbabb" matrix = [[False for i in range(len(string))] for i in range(len(string)) ] for i in range(len(matrix)): matrix[i][i] = True max_val = 0 start = 0 for L in range(2, len(string)+1): for i in range(0, len(string)-L+1): if L==2: if string[i] == string[i+1]: ...
def sudoku_display_unit(sudoku): ''' Reshapes a given array inorer to get a predefined display format of SUDOKU. No matter what the input size output will be in the predefined format. ''' count = 0 for i in sudoku: if count % 3 == 0: print(*'-'*(len(i) + int((len(i) /...
try: number_given = int(input("Number: ")) for i in range(1,number_given): remainder = number_given % i if i != 1 and remainder == 0: print(f"{number_given} is NOT a prime number") break elif i == (number_given - 1) and remainder != 0 or number_given == 2: ...
#!/usr/bin/python import scramble demoScrambler = scramble.Scrambler() scrambledTexts = [] glitchAmt = 10 text = "This is a demonstration text string that shall be randomly glitched and destroyed." text = text.split() for x in range(22): scrambledTexts.append( demoScrambler.scramble_text(text, glitchAmt) ) g...
import random, math """This file contains the vector class. A vector can be defined as a number with a direction, but in this case it is easier to define vectors just by their x and y components. Values like position, velocity, and acceleration should all be stored as vectors for simplicity's sake. Vectors can be creat...
#importing commandline arguments libraries from sys import argv #splitting the command line arguments and storing each for further script, filename = argv #opening the filename and stroing as a string variable text = open(filename) print(f"Here's your file {filename}") #printing the string variable print(text.read()...
# Inheritance # Override methods Explicitly class parent(object): def explicit(self): print("Parent explicit function") class child(parent): def explicit(self): print("Child explicit function") father = parent() son = child() father.explicit() son.explicit()
animals = ['bear', 'python3.6', 'peacock', 'kangaroo', 'whale', 'platypus'] print("\nAll the list members:") print(animals) print("\nLast item of the list:") print(animals[-1]) print("\nFirst two items of the list:") print(animals[0:3]) print("\nItems from 2 to last but one:") print(animals[1:-1]) print("\nLast two it...
fname = input("Enter file name: ") fhand = open(fname) count=0 total=0 for line in fhand: line = line.rstrip() if line.startswith("X-DSPAM-Confidence:"): count = count + 1 s = line.find("0") x = line[s:] total = total + float(x) avg=total/count print("Average spam con...
""" This file is the place to write solutions for the skills assignment called skills-sqlalchemy. Remember to consult the exercise instructions for more complete explanations of the assignment. All classes from model.py are being imported for you here, so feel free to refer to classes without the [model.]User prefix....
import smtplib import getpass from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import datetime import re def mail(): """ Docstring for mail function mail(receiver), receiver should be email address this function will ask sender email and password for GMAIL, pleas...
# -*- coding: utf-8 -*- import sqlite3 class DataBase: def __init__(self, db_path, db_file): self.db_file = db_path + db_file self.db = None def create_db(self): """ Создание необходимых таблиц для работы с ботом """ self.db = sqlite3.connect(self.db_file) ...
print "I will now count my chickens:" print "Hens", 25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" # this equals 7 ... print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # this is what the above equation is w/ some brackets around what's # happening print "Is this 7?", (3 + 2 + 1 - 5) + (...
from commands import Command class Enter(Command): def do(self, text: str): player = self.get_player() house = self.get_house() current_room = player.get_location() location = text # Step 1: # check to see if there is a room with the same name # as loc...
data1 = (2014, 7, 2) data2 = (2014, 7, 11) if data1[1] == data2[1] and data1[0] ==data2[0]: if data1[2] > data2[2]: print('Różnica wynosi ',(data1[2]) - (data2[2]), 'dni.') elif data2[2] > data1[2]: print('Różnica wynosi ',(data2[2]) - (data1[2]), 'dni.') else: print('Podane daty są takie s...
a = 120 b = 150 for n in range(1, 121): if a / n is int and b / n is int: print(n) else: print('co jest?')
var = 2 var2 = var ** (1/2) print('Vidente \n') print('Número {} \nO antecessor é {} o sucessor é {}'.format(var,(var-1),(var+1)), end="") #\n quebra de linha #end linga os dois prints print("") print('Rais quadrada de {} é {}\n'.format(var,var2))
for index, character in enumerate("abcdefgh"): print(index, character) even = [2,4,6,8] odd = [1,3,5,7,9] even.extend(odd) print(even) even.sort() print(even) another_even = even print(another_even) even.sort(reverse=True) print(even) print(another_even)
def min(*args, **kwargs): key = kwargs.get("key",None) print(key) order_as = "" print("str",isinstance(key, str), "int", isinstance(key,int)) if isinstance(key,str): order_as = "str" elif isinstance(key,int): order_as = "int" vals_list = [] arg_list = [] pri...
# Name: Jennifer Daniels # Assignment: HW3 # Description: Program performs tests on function contrived_func # using random testing method # Function being tested from credit_card_validator import credit_card_validator import random import unittest class TestCase(unittest.TestCase): """ Class contains methods...
# mutating a list created with repetition # initializing a variable with values myList = [1,2,3,4] # repetition A = [myList]*3 myList[2] = 45 # output required print(A) print(myList[2]) print(myList[1:3])
number = int(input("Type a number: ")) count = 0 while str(number) != str(number) [::-1]: number = int(number) + int(str(number)[::-1]) count = count + 1 print(f"checking {number}") print("Palindrome found in " + str(count) + "steps. Final number was: " + str(number)) backWards = input('TYPE!').lower() ...
#DECORATORS INTRO def hello(): return 'Hi Ale!' def other(some_def_func): print('Other code runs here') print(some_def_func()) other(hello) #ORIGINAL FUNCTION def new_decorator(original_func): def wrap_func(): print('Some extra code before original func') original_func() pri...
import functools def require_ints(func): @functools.wraps(func) def wrapper(*args,**kwargs): kwargs_value=[i for i in kwargs.values()] for arg in list(args)+kwargs_value: if not isinstance(arg,int): raise TypeError("{} only accepts integers as arguments.".format(func...
from pandas import * data1 = {"java": 2000, "python": 1000, "c++": 2000} index1 = {"java", "python", "c", "c#"} se = Series(data=data1, index=index1) print se column = ["id", "name", "age", "sex", "score", "final"] data = {"id": ["1", "2", "3"], "name": ["han", "min", "yang"], "age": [18, 19, 22], ...
file = open('./input') # PART 1 sum = 0 for line in file: sum += int(line) // 3 - 2 print(sum)
class Role: """ """ role = None def __init__(self, role): self.role = role def set_role(self, role): self.role = role def get_role(self): return self.role def compare(self, roleB): return roleB == self.role def is_attacker(self): return se...
class Suplicio: def __init__(self, listeilor): self.listeilor=listeilor def Ordenacion (self): x = self.listeilor.upper() return(x) lista= "Hello world Practice makes perfect" p1=Suplicio(lista) print(p1.Ordenacion()) """ input: Hello world Practice makes perfect Output: Same shit,...
#Complete the function to return the first digit to the right of the decimal point. def first_digit(num): num2=str(num) posicion= 0 for x,y in enumerate(num2): if y == ".": posicion=x return num2[posicion+1] #Invoke the function with a positive real number. ex. 34.33 print(first_digit(6.24)) """ Ex...
#Complete the function to return the number of day of the week for k'th day of year. def day_of_week(k): return k%7 #Invoke function day_of_week with an interger between 0 and 6 (number for days of week) print(day_of_week(12)) """(jueves, viernes, sabado, domingo, lunes, martes, miercoles)""" """ domingo, lunes, m...
#Complete the function "digits_sum" so that it prints the sum of a three digit number. def digits_sum(num): return int((str(num))[0])+int((str(num))[1])+int((str(num))[2]) #Invoke the function with any three-digit-number #You can try other three-digit numbers if you want print(digits_sum(123)) """ Example input 12...
# -*- coding: utf-8 -*- """ Created on Mon Jul 11 13:19:11 2016 @author: tzupan """ class callRoom(object): ''' representation of the call block (called a room) ''' def __init__(self, bankersInRoom, startTime, dayTime): ''' initializes a call block; saves all parameters as attributes ...
#Extracts email addresses from a text file #pt-1 prints number of email addresses with softwire.com domain #open the file #read the contents line by line #check for the substring '@softwire.com' import re with open('sample.txt') as f: count = 0 contents = f.read() for i in range(len(contents)): if...
# CENG 487 Assignment4 by # Ahmet Semsettin Ozdemirden # StudentNo: 230201043 # Date: 05-2019 from shapes import Shape class Scene: def __init__(self): self.originalNodes = [] self.nodes = [] def add(self, node): self.originalNodes.append(node) self.nodes.append(node) # helper method for subdivision (sub...
class Worker: name: str surname: str position: str _income: dict def __init__(self, name, surname, position, income): self.name = name self.surname = surname self.position = position self._income = income class Position(Worker): def get_full_name(self): ...
digit_list = [1, 1, 1, 45, 5, 5, 67, 123, 123, 9, 15, 1589, 1, 45, 767, 5] def digit_filter(list_in): for i in list_in: if list_in.count(i) == 1: yield i final_list = [] for digit in digit_filter(digit_list): final_list.append(digit) print(final_list)
class Cells: def __init__(self, cores: int): self.cores = cores def __add__(self, other): return Cells(self.cores + other.cores) def __sub__(self, other): if (self.cores - other.cores) > 0: return Cells(self.cores - other.cores) else: return "разниц...
# Part I param1 = 34 param2 = 48430 param3 = 56.89 param4 = "Hello!" print(param1) print(param2) print(param4) sum13 = param1 + param2 + param3 print(sum13) # Part II address_city = input("Введите город: ") address_street = input("Введите улицу: ") address_house_number = input("Введите номер дома: ") address_house_f...
number = input("Введите целое положительное число: ") i = 0 a = 0 while i != len(number): b = int(number[i]) if a <= b: a = b i += 1 print(f"Самая большая цифра в данном числе: {a} ")
import numpy as np a = np.array( ([1,2,3], [4,5,6]) ) print('matrix a dengan ukuran', a.shape) print(a) #transpose matriksT = a.transpose() print("Transpose\n", matriksT) #menjadikan matriks menjadi vektor print("jadi vektor\n", a.ravel()) #reshape matrix print("reshape\n", a.reshape(3,2)) #resize m...
#Find if string a palindrome # return True if it's a palindrome and False otherwise def isPalindrome(string, begin_id, end_id): if begin_id>=end_id:# return True elif string[begin_id]==string[end_id]: return isPalindrome(string, begin_id+1, end_id-1) else: return False #print isPalindrome('abba', 0, 3) #ha...
# 继承 class Car(): """模拟汽车""" def __init__(self, name, model, year): """初始化描述汽车属性""" self.name = name self.model = model self.year = year self.odometer_reading = 0 # 给属性设置默认值 [设置里程数初始值为0] def get_descriptive_name(self): """返回整洁的描述信息""" long_name = st...
# 文件读取 # 读取整个文件 # 函数 open 接收一个参数: 要打开的文件的名称 # Python 在当前执行的文件所在目录中查找指定的文件 # 关键字 with 在不再需要访问文件后将其关闭. # 通过 with, Python 可以自己控制关闭文件的时机, 防止自行通过 open() close() 导致程序出错 # 使用 read() 读取文件的全部内容. # read() 在到达文件末尾时, 返回一个空字符串, 这个字符串显示出来就是一个空行 # 可以使用 .rstrip() 删除多余空行 with open('file_text/pi_digits.txt') as file_object_1: cont...
def make_pizza(size, *toppings): '''概述要制作的披萨''' print("做一个尺寸为: " + str(size) + ", 包含: ") for topping in toppings: print("- " + topping) print("的披萨") def get_price(): print("The price is 20")
# 存储用户输入的数据 import json username = input("你叫什么名字?\n") filename = 'username.json' with open("json/" + filename, 'w') as f_obj: json.dump(username, f_obj) print("我已经将你深深刻在我的心里~")
#!/usr/bin/python import mysql.connector as mariadb """mariadb_connection = mariadb.connect(host='localhost', user='root', password='godman') cursor = mariadb_connection.cursor() cursor.execute("CREATE DATABASE mylibrary") mariadb_connection.commit()""" """comment out the above code after creating the database""" ...
print("Input a number:") try: number = int(input()) except ValueError: print("This is not a number") exit(0) if number < 0: print("This is not a positive number") exit(0) def generate_prime_numbers(num): prime_numbers = [] for x in range(2, num + 1): for y in range(2, x): ...
class Device(object): def __init__(self, unit_name, mac_address, ip_address, login, password): self._unit_name = unit_name self._mac_address = mac_address self._ip_address = ip_address self._login = login self._password = password @property def unit_name(self): ...
#-*- coding:utf-8 -*- ''' Created on 2019. 4. 8. @author: there ''' first = 1 while first <= 9: second = 1 while second <= 9: print("%d * %d = %d" % (first, second, first * second)) second += 1 first += 1
import csv import os #set the path where the file I am reading is located in my directory file_to_load = os.path.join('../Resources','election_data.csv') #set the file path where the results file will go #file_to_output = os.path.join('Analysis','election_analysis.txt') total_votes = 0 candidate = "" candidate_vot...
# -*- coding: utf-8 -*- # 第二次作业 - 试值法求利率(非线性方程求解) import math # 年金计算函数 def f(x): p = 300 n = 240 A = 12*p*((1+x/12)**n-1)/x-500000 return A # a为左端点值,b为右端点值,accuracy为给定误差 def FalsePosition(a, b, accuracy): # 如果f(a)*f(b) > 0,此方法不适用 if f(a)*f(b) > 0 : print("This method is not suitable ")...
# -*- coding: utf-8 -*- # 第一次作业 - 二分法求利率(非线性方程求解) import math def f(x): p=300 n=240 A=12*p*((1+x/12)**n-1)/x-500000 return A def regula(a, b, accuracy): delta = 0.5 * 10**(-accuracy) n = math.floor( (math.log(b-a) - math.log(delta))*1.0 / math.log(2) ) if f(a) * f(b) > 0 : print("y...
def sumDigit(): global num global summ while num > 0: summ += num % 10 num = int(num / 10) number=int(input("Enter the number:")) num=number summ = 0 sumDigit() print("The sum of the digits in",number," is",summ)
word=input("Enter the word:") def printRTri(): for i in range(len(word),-1,-1): print(word[i:len(word)]) printRTri()
number=int(input("Please enter the number:")) factorial=1 for i in range (0, number): factorial *= (number - i) print(factorial)
myList = ["animal", "dog", "fish", "food", "game"] print("The full words...") output = "" for i in myList: output += i + " " print(output) print("") print("Just the first letters...") def First(): for i in myList: print(i[0]) First()
def calcPayment(r, P, n, t): return P*((1+r/n)**(n*t))/(t*12) r=float(input("Enter the interest rate:")) P=float(input("Enter the principal:")) n=float(input("Enter the number of times the loan is compunded per year:")) t=float(input("Enter the life of the loan in years:")) print("The interest of your loan is {:0...
#pirate game from random import randint pirate_secret = randint(1, 99) tries = 0 guess = 0 print ("Эй на палубе! Я Ужасный пират Робертс, и у меня есть секрет!") print ("Это число от 1 до 99. Я дам тебе 6 попыток.") print ("Твой вариант?") print (pirate_secret) ############ otladka while guess != pirate_secret and trie...
# Определить по координатам вершин треугольника является ли он прямоугольным # Татаринова ИУ7-14Б from math import sqrt eps = 1e-7 # Ввод координат вершин x1, y1 = map (int, input("Введите координаты A: ").split()) # точка А x2, y2 = map (int, input("Введите координаты B: ").split()) # точка B x3, y3 = map (int, i...
# Дан список, нужно найти самую длинную последовательность вида: # Первый элемент равен последнему, второй равен предпоследнему и тд и записать это в новый список # И еще сформировать список Z, который состоит из элементов изначального списка, которые повторяются более 1 раза def search(value, array, start=0): for...
eps = float(input("Введите eps: ")) sum = 0 a = 1 n = 1 res = a / n while abs(res) > eps: sum += res n += 2 a *= -1 res = a / n print ("Сумма ряда =", sum * 4)
def selectionSort(array): for i in range(len(array)): minind = i for j in range(i, len(array)): if array[j] < array[minind]: minind = j array[i], array[minind] = array[minind], array[i] return array def insertionSort(array): for i in range(1, len(array))...
# Вводится строка состоящая из скобок(),[],{},нужно найти отрезок максимальной длины , где скобки расставлены правильно # (([}[) - такого отрезка нет # ([}{}]([])[((] - ([]), длина 4,начало-7,конец-10 str = '([{(}}]' array = [] lengthMax = 0 startMax = 0 for j in range(len(str)): start = j length = 0 for...
__author__ = 'peter' ################################################### print("basics") a = 10 b = 202 c = a + b d, e, f = 2, 3, 4 name = 'Peter' print(c) print(name, len(name)) print(d,e,f) g = None print(g) ################################################### print("collections") dict = {'name': 'peter', 'id': 10, '...
def is_bouncy(n): '''In the changes list, "False" indicates a decrease and "True" indicates an increase thus in order the number to be either increasing or decreasing the "changes" should consist of same values at the end of the operations''' changes = []; num_str = str(n) for i in range(1, len(num_...
from math import pow def square_of_sum(n): return pow((n * n + n) / 2, 2) def sum_of_squares(n): return (n * (n + 1) * (2 * n + 1)) / 6 print(square_of_sum(100) - sum_of_squares(100))
import sqlite3 # Query the DB and return all records: # ------------------------------------ def show_all(): conn = sqlite3.connect("customer.db") c = conn.cursor() c.execute("SELECT rowid, * FROM customers") items = c.fetchall() for item in items: print(item) conn.commit() conn.close() # Lookup wit...
import sqlite3 # Connect to database: conn = sqlite3.connect("customer.db") # Create a cursor c = conn.cursor() # Insert data c.execute("""INSERT INTO customers VALUES ( 'John', 'Elder', 'john@codemy.com' )""") # Or write the command in 1 line: # c.execute("INSERT INTO customers VALUES ('John', 'Elder...
#!/usr/bin/env python # Octagonal Hull module import unittest import copy from dot import Dot # Hull class # # Defines a hull that is an intersection of half-planes with specified set of normal vectors # # The center of the cross is (0,0) # The grid is on integral points with odd coordinates class Hull: # in...
""" Solving the Laplace equation using a perceptron of 1 hidden layer. \frac{d^2y}{dx_1^2} + \frac{d^2y}{dx_2^2} = 0 Subject to y(0,x_2) = y(1,x_2) = y(x_1,0) = 0, y(x_1,1) = \sin(\pi x_1) The analytical solution is y_a = \frac{1}{e^\pi - e^{-\pi}}\sin(\pi x_1)(e^{\pi x_2} - e^{-\pi x_2}) The trial solution is y_t = x_...
EntNumA = int(input("Enter a Number: ")) EntNumB = int(input("Enter another Number: ")) Sum = EntNumA + EntNumB Subtract = EntNumA - EntNumB Multiple = EntNumA * EntNumB Division = EntNumA / EntNumB print("The Sum of A and B is: ", Sum) print("The Subtraction of A and B is: ", Subtract) print("The Multiple of ...