text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 16:52:06 2020 @author: patel """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): prev = None temp...
# -*- coding: utf-8 -*- """ Created on Tue Jan 28 02:03:59 2020 @author: patel """ if __name__ == '__main__': arr1=[] n=int(input()) for _ in range(n): name = input() score = float(input()) arr = [name , score] arr1.append(arr) m=min(arr1,key= lambda x:x[1]) i=0 ...
#Read a list of integers from user input. numbers = list() totalNumber = 0 next = False while not next: try: totalNumber = int(input('How many numbers are you putting in?')) if totalNumber > 1: next = True else: print("There are no pair.... Input a number that is larg...
"""Mathematical utilities for CS41's Assignment 1: Cryptography.""" import math class Error(Exception): """Base class for exceptions in this module.""" class BinaryConversionError(Error): """Custom exception for invalid binary conversions.""" class NotCoprimeError(Error): """Custom exception for argum...
# Standalone node class for de Bruijn graph Implemented by Charles Eyermann # and Sam Hinh for Computational Biology (CS362) Winter 2016 class Node: def __init__(self,name): self.name = name self.neighbors = [] self.unique_neighbors = 0 self.parents = [] self.unique_parents = 0 self.indegree = 0 self.ou...
#!/usr/bin/python # -*- coding=utf8 -*- """ Python 有三类字符串: 1. 通常意义的字符串( str ) 2. unicode字符串 ( unicode ) 3. 抽象类 ( basestring ) 不能被实例化 """ s = "hello world" #切片 print s[:5] print s[6:] print s[2] #字符串长度 print len(s) print s[0:len(s)] #成员操作符 in, not in print "a" in s print "he" in s print "ss" not in...
class Employee: def __init__(self,f_name,s_name): self.f_name=f_name self.s_name = s_name @property def email(self): return self.f_name + self.s_name +"@gmail.com" @property def full_name(self): return "{} {}".format(self.f_name, self.s_name) @full_name.sette...
class Employee: num_of_emp = 0 raise_amt = 1.04 def __init__(self, name, age, email, pay): self.name=name self.age = age self.email= email self.pay = pay Employee.num_of_emp += 1 def name_age(self): return "{} age is {}".format(self.name, self.age) ...
#print the characters present at even index and odd index separately for the given string s = input('enter the string: ') print('print char in even index') i=0 while i<len(s): print(s[i]) i=i+2 print('enter char in odd index') i=1 while i<len(s): print(s[i]) i=i+2 print('char in odd index')
class A: def __init__(self,a,b): self.a = a self.b = b self.c = None def add(self): self.c = self.a + self.b return self.c obj=A(1,1) print(obj.add()) class printer: def __init__(self,obj): self.obj = obj def getobj(self): return obj.add() p=p...
import sqlite3 import sys if len(sys.argv) != 2: print("One argument should be given") sys.exit(1) conn = sqlite3.connect('students.db') c = conn.cursor() c.execute('SELECT * FROM students WHERE house=? ORDER BY last, first', sys.argv[1:]) students = c.fetchall() for student in students: student = '|'.joi...
""" authors: Zirong Chen, Haotian Xue Evaluator for Dialogue System 11/27/2020 """ from utils import bcolors, Sigmoid class Evaluator(object): def __init__(self, num_of_turns, task_reward, turn_penalty, score_factor): self.num_of_turns = num_of_turns self.task_completion = False self.task...
#!/usr/bin/env python def red(): return chr(27)+"[91m" def green(): return chr(27)+"[92m" def off(): return chr(27)+"[0m" def cyan(): return chr(27)+"[36m" def yellow(): return chr(27)+"[33m" def blink(): return chr(27)+"[5m" def rred(): return chr(27)+"[41m" def rgreen(): return chr(27)+"[42m" BLACK=3...
# plot a function like y = sin(x) with Tkinter canvas and line # tested with Python24 by vegaseat 25oct2006 from Tkinter import * import math import random root = Tk() root.title("Simple plot using canvas and line") width = 900 height = 300 center = height//2 x_increment = 1 # width stretch x_factor = 0.04...
# This program is written in Python3 def detect_edge(present_value, previous_value): different = present_value - previous_value if (different == 1): edge = 1 else: edge = 0 return edge
import time def collatz_step(n): if n % 2 == 0: return int(n/2) return int(3*n + 1) def stepcount(n): next = n count = 0 while next != 1: next = collatz_step(next) count += 1 return count def solve(n): start = time.time() stepcache = [0] * n max_step_co...
import math import sympy def isPalindrome(n): list = [int(x) for x in str(n)] for i in range(0, len(list)): if i < len(list) / 2: if list[i] != list[len(list) - 1 - i]: return False return True palindromes = [] for i in range(100,999): for j in range(100,999): ...
def sum_of_squares(n): sum = 0 for i in range(1, n + 1): sum += i*i return sum def square_of_sum(n): sum = 0 for i in range(1, n + 1): sum += i return sum*sum
import math #42 spaces. Will print introduction header. def introduction_header(): print("*" * 42) print("{title:^42}".format(title = "CURVED GRADE CALCULATOR")) print("*" * 42) #42 spaces. Will print course header for average printing. def course_header(): print("{title: ^42}".format(title = "*Course Final Gra...
from datetime import datetime current_date = datetime.now() print(str(current_date)) print("Day: " + str(current_date.day)) print("Month: " + str(current_date.month)) print("Year: " + str(current_date.year))
# asal sayi olup olmadigini bulan program sayi = int(input("Bir sayi giriniz:")) # 1'den buyuk olup olmadigini kontrol etme if sayi > 1: for i in range(2,sayi): if (sayi % i) == 0: print(sayi,"asal sayi degildir.") print(i, " x ", sayi//i, " = " , sayi) break else: ...
sayilar = [1,3,5,7,9,12,19,21] # Sayıların 3'ün katı durumu? # for ucKati in sayilar: # if ucKati %3 == 0: # print(ucKati) # Sayıların toplamı # toplam = 0 # for sayi in sayilar: # toplam += sayi # print(toplam) # Tek Sayıların karelerini alma # for sayi in sayilar: # if sayi%2 == 1: # ...
q=1 dizi=[] while True: try: a=int(input(f'{q}. kenari giriniz: ')) if a<0: print("Lütfen pozitif sayi girin") continue dizi.append(a) q=q+1 if len(dizi)==3: break except Exception: print("Lütfen bir sayi girin") x...
#!/usr/bin/python3 import argparse import random import math import sys def entropy(words, n): return n * math.log(len(words), 2) def make_password(words, n): rand = random.SystemRandom() return ' '.join(rand.choice(words) for _ in range(n)) def main(): argparser = argparse.ArgumentParser() ...
# Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. # Example 1: # Input:nums = [1,1,1], k = 2 # Output: 2 # Note: # The length of the array is in range [1, 20,000]. # The range of numbers in the array is [-1000, 1000] and the range of ...
def check_prime(number): for divisor in range(2,int(number**0.5)+1): # square root of a number + 1 if number%divisor == 0: return False #divisor += 1 return True class Primes(): def __init__(self,max): self.max = max self.number = 1 def __iter__(self)...
#!/usr/local/bin/python from dataclasses import dataclass from typing import List import os import sys @dataclass class Photo: position: str tagsCount: int tags: List[str] def AddTag(self,tag): self.tags.append(tag) class Slide: def __init__(self,slide): self.slide =...
# Implementation of classic arcade game Pong import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGHT = PAD_HEIGHT / 2 ball_pos = [WIDTH//2, HEIGHT//...
import os import subprocess import glob import string def format_filename(filename): ''' Changes filenames and gets rid of any characters that might break the code. ''' valid_chars = "-_. %s%s" % (string.ascii_letters, string.digits) filename = ''.join(char for char in filename if char in valid_ch...
import sys def y_d(x): list=["Jan","Feb","Mar","Apr","may","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] c=31 v=x/c w=x%c if w>30: b=w/30 w=w%30 a=v+b else: a=v if a>12: a = a-12 return (str(w)+list[a-1]) def main(): x = input("Enter your num...
''' 利用parse模块模拟post请求 分析百度词典 分析步骤: 1、打开F12 2、 ''' from urllib import request,parse import json if __name__ == '__main__': baseurl = 'http://fanyi.baidu.com/sug' #存放用来模拟form的数据一定是dict格式 data = { 'kw':'girl' } #需要使用parse模块对data进行编码 data = parse.urlencode(data).encode("utf-8") #我们需要...
import sys import os if __name__ == '__main__': try: class node(object): def __init__(self): self.data = None self.pointers = [] class tree(object): Z = 0 clild=[] def __init__(self): self.root = None def insert_root(self,data): if (self.root == None): nnode = node() ...
import json from difflib import get_close_matches dictionary = json.load(open("dictionary.json")) def get_definition(target_word): # Convert target to lower case to eliminate case sensitivity target_word = target_word.lower() # If the target is contained within the dict if target_word in dictionary:...
def prob_10 (p1, p2, p3): p1 = () p2 = () p3 = () n1x=int(input("ingrese el punto x: ")) p1.append(n1x) n1y=int(input("ingrese el punto y: ")) p1.append(n1y) return (p1)
class Vehicle(): def __init__(self,model,color,price): self.model=model self.color=color self.price=price def print(self): print("Model:",self.model,"Color:",self.color,"Price",self.price) def __str__(self): #method is the string representation of object,to work wh...
str=input("Enter the string to check palindrome:") rev=str[::-1] if str==rev: print("The string is paliandrome") else: print("The string is not paliandrome")
s1=set() limit=int(input("Enter the limit for your set:")) for i in range(limit): num=input("Enter the element:") s1.add(num) print(s1)
# to separate odd and even numbers from one set to another two sets set1={0,23,25,45,67,68,86,44,34,25,69,70,98,100} odd=set() even=set() for i in set1: if i%2==0: odd.add(i) else: even.add(i) print("The set with odd num is:",odd) print("The set with even num is:",even)
# num1=int(input("Enter the number:")) # num2=int(input("Enter the number:")) # print(num1/num2) # in this if yoy give num2 as 0 you will get a zero division error. To handle this kind of errors we have to do exception handling #EXCEPTION HANDLING HAS THREE block # try .... to write the code that can cause exception...
#The __str__ method is useful for a string representation of the object, # either when someone codes in str(your_object), or even when someone might do print(your_object). class Employee: compnay="ABC" def __init__(self,name,id,salar,exp): self.name=name self.id=id self.salary=salar ...
# TWO TYPES OF VARIABLES # Static variable: related to class ... access using class name # instance variable..... related to method ... access using self class Book: category="Fiction" #Static variable def setval(self,name,author,nopages): self.name=name self.author=author self.pag...
import re file=open("phone num","r") rule="[+][9][1][\d]{10}" for i in file: num=i.rstrip() match=re.fullmatch(rule,num) if match is not None: print(num,":Valid") else: print(num,":Not valid")
class Calculator: def __init__(self,num1,num2): self.num1=num1 self.num2=num2 def add(self): print("The sum is:",self.num1+self.num2) def diif(self): print("The difference is :", self.num1-self.num2) def div(self): print("The division result is:",self.num1/self.nu...
class College: def setval(self,clgname,place,nodept): self.clgname=clgname self.place=place self.nodept=nodept def printinfo(self): print("College Name:",self.clgname) print("Place:",self.place) print("No of Departments:",self.nodept) class Employee(College): ...
# constructor to intialize instance variables # constructor automatically invoke when object creates class Person: def __init__(self,name,age): self.name=name self.age=age def info(self): print("Name:",self.name) print("Age:",self.age) person1=Person("Abc",25) person1.info()
# # List comprehensions are used for creating new lists from other iterables. # # As list comprehensions return lists, they consist of brackets containing the expression, # # which is executed for each element along with the for loop to iterate over each element. a=[1,23,34,43,65,13,6733,66,87,25,6,6,23] # b=[] # for ...
def add(): num1 = float(input("enter the first number1:")) num2 = float(input("enter the second number:")) print("The result is:",num1+num2) def sub(): num1 = float(input("enter the first number1:")) num2 = float(input("enter the second number:")) print("The result is:",num1-num2) def mul(): ...
class Bank: def setval(self,name,accountno): self.name=name self.accountno=accountno self.balance=5000 def withdraw(self): c=int(input ("enter the amount to withdraw:")) if c<self.balance: self.balance=self.balance-c print("amount withdraw done: yo...
users={ 1000:{"acconu_num":1000,"password":"user1","balance":3000}, 1001: {"acconu_num": 1001, "password": "user2", "balance": 4000}, 1002: {"acconu_num": 1002, "password": "user2", "balance": 5000}, 1003: {"acconu_num": 1003, "password": "user3", "balance": 6000} } # Check for username and password ...
from enum import * class Color(Enum): blue = "blue" green = "green" yellow = "yellow" red = "red" class TypeOfDecorations(Enum): garland = "garland" wreath = "wreath" toys = "toys" lighting = "lighting" class Decoration: def __init__(self, decoration_place, type_of_decoration,...
people = {'football','messi','barcelona','football'} print(people) #sets will automatically remove duplicate value number1 = {1,2,3,4,5} number2 = {4,5,6,7,8} #do an operation or union print(number1 | number2)
import unbreakable class Person: """ Superclass for the classes Sender and Receiver""" def __init__(self): self.cipher = None self.key = "" self.encoded_message = "" def set_key(self, key): self.key = key def get_key(self): return self.key ...
# -*- coding: utf-8 -*- """ Created on Tue Jan 28 05:14:57 2020 Author: Sai Madhav Kasam. Data Programming Assignment-1. """ # Georgian Calendar starts from 1582. isLeap=False; year=eval(input("Give the year")); day=eval(input("Give the day of the First date of the year")); if(year%4==0): isLeap=True; i...
''' Author: Sai Madhav Kasam. Data Programming Assignment-1. ''' import datetime; # currTime= datetime.datetime.now(); # print(currTime.hour); class Time: def __init__(self): self.__hour=datetime.datetime.now().hour; self.__minute=datetime.datetime.now().minute; self.__second=datetime.datetime.now().se...
''' Author: Sai Madhav Kasam Data Programming Assignment-1. ''' def main(): str=input("Enter the numbers separated by spaces in a line"); lt=str.split(); numList=[eval(x) for x in lt]; # numList.reverse(); i=0; j=len(numList)-1; while(i<j): numList[i], numList[j]=numList[j], numList[i]; i+=1; j-=1;...
''' Author: Sai Madhav Kasam Data Programming Assignment-1. ''' def main(): side1, side2, side3=eval(input("Enter the three sides of the triangle: ")); # triObject1=Triangle(); try: triObject=Triangle(side1, side2, side3); except TriangleError as ex: print("These sides: ", ex.getSide1(), ex.getSide2(), ex...
# -*- coding: utf-8 -*- """ Created on Sun Jan 19 05:23:56 2020 Author: Sai Madhav Kasam. Data Programming Assignment-1. """ import random; import math; randNumber=random.randint(100, 999); # temp=randNumber; thirdDigit=randNumber%10; randNumber//=10; secondDigit=randNumber%10; randNumber//=10; firstDigit=randNum...
''' Author: Sai Madhav Kasam Data Programming Assignment-1. ''' import os; def main(): # fileName="testFile.txt"; fileName=input("Give the filename."); # print("filename is: ", fileName); try: fileObject=open(fileName, "r"); except: print("No such filename exists."); # print(fileObject.readlines...
''' Author: Sai Madhav Kasam Data Programming Assignment-1. ''' def isSorted(lt): if(len(lt)<=1): return True; prev=lt[0]; for i in range(1, len(lt)): if(prev>lt[i]): return False; prev=lt[i]; return True; def main(): str=input("Give the numbers between 1 and 100 separated by spaces."); str...
# -*- coding: utf-8 -*- """ Created on Wed Jan 15 20:38:58 2020 @author: Administrator """ # -*- coding: utf-8 -*- import math; currentPopulation=312032486; secondsPerBirth=7; secondsPerDeath=13; secondsPerImmigrant=45; secondsPerYear=365*24*60*60; birthsPerYear=secondsPerYear/secondsPerBirth; deathsPerYear=secon...
# -*- coding: utf-8 -*- """ Created on Wed Jan 15 20:43:43 2020 Author: Sai Madhav Kasam Data Programming Assignment 1. """ import turtle; pointX=eval(input("Give the x coordinate center of the rectangle.")); pointY=eval(input("Give the y coordinate center of the rectangle.")); length=eval(input("Give the length...
''' Author: Sai Madhav Kasam Data Programming Assignment-1. ''' def main(): str1=input("Enter the first sorted list1."); lt=str1.split(); nums1=[eval(x) for x in lt]; str2=input("Enter the Second sorted list"); lt2=str2.split(); nums2=[eval(x) for x in lt2]; i=0; j=0; res=[]; while(i<len(nums1) or ...
import math class Parallelogram: def __init__(self, width, height, angle): self.width = width self.height = height self.angle = angle @property def area(self): return self.width * self.height * math.sin(math.radians(self.angle)) @area.setter def area(self, value):...
from abc import ABC, ABCMeta, abstractmethod class Animal(metaclass=ABCMeta): def __init__(self, name): self.name = name @abstractmethod def make_sound(self): raise NotImplemented class Horse(Animal): pass class Cat(Animal): def make_sound(self): print("meow") class ...
# fact_check = int(input('Please Enter #: ')) # for # fact_check -= 1 def fact(n): for i in range(1, n+1) # This code prints "Hellow World" followed by number 1-50, 10 times satisfying the "if counter == 10" statement #counter = 0 #while True: # counter += 1 # print("Hellow World") ...
'''Program created by Akul Umamageswaran.''' '''NOTE: This program finds either the principal, rate, time, or interest. It solves for one of the above given the other three values. It does this using the simple interest formula: i = prt The program will prompt you for integer values. During those prompts, please ONLY...
#Two Sum class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ container = {} for i, num in enumerate(nums): if target - num in container: return [container[targe...
import RPi.GPIO as GPIO ledPin = 11 buttonPin = 12 def setup(): print('Program is starting...') GPIO.setmode(GPIO.BOARD) GPIO.setup(ledPin, GPIO.OUT) # With the circuite provided in the lab, the program still works # even without specifying the pull_up_down value becaused we actually # c...
# -*- coding: utf-8 -*- """ Github Project @author: mremreozcelik """ ######## ENGLİSH LANGUAGE ######### money = int(0) while True: print("Money : ", int(money)," $") print("1-) To deposit money (1) \n2-) Withdraw (2) \n3-) My Bank Status (3)") x = input("Enter the action you want t...
import csv file = open("data_file/record.csv", "r") with file: read = csv.reader(file) for row in read: print(row) print("--------\n") file = open("data_file/record_pipe.csv", "r") with file: read = csv.reader(file) for row in read: print(row) print("--------\n") file = open("data...
# -*- coding: utf-8 -*- """ Created on Wed Jan 29 18:21:13 2020 @author: Dillons PC """ import sys def Encrypt(key, file): counter = 0 if isinstance(key, str) and isinstance(file, str): f = open(file) text = f.readlines() newList = [] for x in text...
tc=int(input()) for i in range(tc): x=input() j='LUCKY' for k in x: if k!='7' and k!='3': j='BETTER LUCK NEXT TIME' break print(j)
""" mapping ~~~~~~~ Performs projection functions. Map tiles are projected using the https://en.wikipedia.org/wiki/Web_Mercator projection, which does not preserve area or length, but is convenient. We follow these conventions: - Coordinates are always in the order longitude, latitude. - Longitude varies between -1...
#Fundametos de Python #C++ # private int numero = 0; #cout #JS # var,let,const numero = 0; # console.log("numero es:" + numero) #Python nombre = "Rodrigo" VoF = True #double o float o decimal es con el "." altura = 1.75 n,n2, n3 = 5,4,7 numero_complejo = 2.1 + 7.8j """ Tipo de datos""" tipo_variable = type(n) print...
#ANN # ----- PREPROCESADO DE DATOS ----- # Cargar Librerias import numpy as np import matplotlib as plt import pandas as pd # Cargar de Dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:,13].values #Variables Dummys from sklearn.preprocessing im...
l=input("Input a letter of the alphabet:") if l in ('a','e','i','o','u'): printf("%s is vowel." %l) elif l=='y': printf("sometimes letter y stand for vowel,sometimes stand for consonant") else: printf("%s is a consonant."%l)
from utils import ( is_palindrome, print_matrix, rebuild_words, assert_checking, ) def palindrome_subsequences(word): # precalculate dinamic programming N x N of characters coicidences n = len(word) # length 1 dp = [[0 for x in range(n)] for y in range(n)] for i in range(n): ...
# Given an object/dictionary with keys and values that consist of both strings and integers, design an algorithm to calculate and return the sum of all of the numeric values. # For example, given the following object/dictionary as input: # { # "cat": "bob", # "dog": 23, # 19: 18, # 90: "fish" # } # Your algorit...
from collections import Counter def isBeautifulString(s): a = "abcdefghijklmnopqrstuvwxyz" for i in range(1,len(a)): if s.count(a[i-1]) >= s.count(a[i]): continue return False return True
def alphabeticShift(input): letters = "abcdefghijklmnopqrstuvwxyz" input = list(input) for i in range(len(input)): if input[i] == 'z': input[i] = 'a' else: index = letters.index(input[i]) input[i] = letters[index + 1] ...
def palindromeRearranging(inputString): counter = 0 # if len(inputString) % 2 != 0: # return False for char in inputString: input_count = inputString.count(char) if len(inputString) % 2 == 0: if input_count % 2 != 0: return False else: ...
#Derivative #In this exercise, we will calculates a derivative. #For that purpose, keep in mind the mathematical definition of a derivative is # dfdx=lim(δx→0)((f(x+δx)−f(x))/δx) #Write a script that calculate the derivative of f(x)=x2 on 101 points between 0 and 10 for δx=10−2. #Plot the error curve (i.e. expected...
from lib import abstractstrategy from math import inf class AlphaBetaSearch: def __init__(self, strategy, maxplayer, minplayer, maxplies=3, verbose=False): """"alphabeta_search - Initialize a class capable of alphabeta search problem - problem representation maxplayer - ...
import numpy as np def stereographicProjection(alt, az): """Project stars onto a 2D plane stereographically. Parameters ---------- alt : np.ndarray The altitude of a star, relative to an observer. Values are processed as radians. az : np.ndarray The azimuth of a star, rela...
#-*-coding:utf-8-*- import numpy as np import pandas as pd from datetime import datetime from datetime import timedelta from dateutil.parser import parse from pandas import DataFrame,Series now=datetime.now() #print(now) #print(now.year,now.month,now.day) #datetime以毫秒形式存储日期和时间. # datetime.timedelta表示两个datetime对象之间的时间差...
#-*-coding:utf-8-*- from datetime import datetime from datetime import timedelta from dateutil.parser import parse from pandas import DataFrame,Series import pandas as pd stamp=datetime(2011,1,3) print(str(stamp))#默认格式切换 #print(stamp.strftime('%Y-%m-%d'))#指定转换格式 value='2011-01-03' #print(datetime.strptime(value,'%Y-%m-...
#-*-coding:utf-8-*- from pandas import DataFrame,Series import numpy as np import pandas as pd tips=pd.read_csv('/home/jethro/文档/pydata-book-master/data/tips.csv') #添加‘小费占总额百分比’的列 tips['tip_pct']=tips['tip']/tips['total_bill'] #print(tips[:6]) grouped=tips.groupby('smoker') #grouped_pct=grouped['tip_pct'] #print(groupe...
#!/bin/python3 # Write a Python program to iterate over two lists simultaneously. num = [1, 2, 3] color = ['red', 'while', 'black'] for (a,b) in zip(num, color): print(a, b)
import math ''' While statement repeats body of code as long as a condition is true. ''' # counter = 1 # while counter <=5: # print ("Hello World") # counter += 1 ''' While fragment where both conditions are satisfied ''' # counter = 1 # done = False # while counter <=10 and not done: # print("Hello World"...
__author__ = 'albertfougy' import time from random import randrange """ Test function with random string size and time alloted to perform comparisons """ # exponential version == O(n**2) # def findMin(a_list): # overallMin = a_list[0] # for i in a_list: # 1st loop # is_smallest = True # for j...
import psycopg2 conn = psycopg2.connect(host="127.0.0.1",port="5432",database="employeedb",user="test",password="password") print("Connected to employeedb") cursor = conn.cursor() cursor.execute("select * from employee") rows = cursor.fetchall() print("Total Numbers of records",cursor.rowcount) for row in rows: ...
#Please put your code for Step 2 and Step 3 in this file. # Alex Bazyk import numpy as np import matplotlib.pyplot as plt import random # FUNCTIONS #takes no parameters. returns glucose, hemo, class numpy arrays based on # the the data stored in the file. def openckdfile(): glucose, hemoglobin, classification...
#time O(nlog) space is O(n) def sortedSquaredArray(array): # Write your code here. sqarr=[] for num in array: sqnum=num*num sqarr.insert(-1,sqnum) sqarr.sort() return sqarr #O(n) S O(n) def sortedSquaredArray(array): # Write your code here. sortsquared=[0 for _ in array] left ...
# This is an input class. Do not edit. class LinkedList: def __init__(self, value): self.value = value self.next = None def removeDuplicatesFromLinkedList(linkedList): # Write your code here. # passing in the top only current = linkedList while current is not None: ...
# This is an input class. Do not edit. class BinaryTree: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class TreeInfo: def __init__(self, isBalanced, height): self.isBalanced=isBalanced self.height=height d...
#AVG O(logn) time and space O(1) #worst o(n) and space O(1) def findClosestValueInBst(tree, target): # Write your code here. return helper(tree, target, tree.value) def helper(tree, target, closest): current=tree while current is not None: if abs(closest-target)>abs(target-current.value): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 23 08:53:04 2019 @author: erik """ import math def binarySearch(target, listOfNumbers, start,end): index = math.floor( (end+start) /2) if(target < listOfNumbers[index] and (index > start)): index = binarySearch(target,listO...
# color circle areas from math import pi total = int(raw_input()) numbers = [] ratios = total while ratios > 0: numbers.append(int(raw_input())) ratios -= 1 numbers.sort() signal = 'tasu' area = 0 while total > 0: ratio = float(numbers.pop()) if signal == 'tasu': area += pi * ratio * ratio...
# from StringIO import StringIO import lxml.etree as etree data = """ <root> <person> <name>John</name> <address> <street>Hill Street</street> </address> </person> <person> <name>Jeff</name> <address> <street>Bay Street</street> </address> </person> </root> """ root = etree.fromstring(data) firs...
def check_value(mapping,cell): row=cell[0] column=cell[1]-1 already_played=True if(mapping[row][column]!=' '): print("cell already played") return already_played else: already_played=False return already_played def check_full_board(mapping): for item in mapping.v...