text
stringlengths
37
1.41M
import sys import pickle class Account: """ This class contains attributes of an account. """ def __init__(self, username, password): # type: (str, str) -> None self.username: str = username self.password: str = password def to_string(self): # type: () -> str return "Username: " + str(self.usernam...
from twython import TwythonStreamer import json # appending data to a global variable is pretty poor form # but it makes the example much simpler tweets = [] class MyStreamer(TwythonStreamer): """our own subclass of TwythonStreamer that specifies how to interact with the stream""" def on_success(self, d...
import tkinter as tk import os import csv from tkinter import messagebox window = tk.Tk() window.title('Login') window.geometry('300x200+100+100') def option(): with open("login_credentials.csv", "r") as csv_file: data = csv.reader(csv_file, delimiter=",") for i in data: if i[1] == e...
""" In order to improve customer experience, Amazon has developed a system to provide recommendations to the customers regarding the items they can purchase. Based on historical customer purchase information, an item association can be defined as - if an item A is ordered by a customer, then item B is also likely to be...
def isUnique(s): table = {} for ch in s: if ch in table: return False table[ch] = 1 return True def isUnique_2(s): s = sorted(list(s)) for i in range(1, len(s)): if s[i - 1] == s[i]: return False return True def isUnique_3(s): num = 0 f...
def bmi1(): high = float(input('請輸入身高(公分): ')) weight = float(input('請輸入體重: ')) high = high / 100 bmi = weight / (high * high) bmi = str(round(bmi, 2)) return bmi def judge1(bmi): if bmi < 18.5: judge = '過輕' elif bmi >= 18.5 and bmi < 24: judge = '正常' elif bmi >= 24 and bmi < 27: judge = '過重' elif bm...
# https://www.acmicpc.net/problem/1157 if __name__ == '__main__': str = input() str = str.upper() char_dict = dict() for i in str: if i in char_dict.keys(): char_dict[i] += 1 else: char_dict[i] = 1 max_value = max([(char_dict[key], key) for key in char_dict]...
# coding: utf-8 # ## Analyze A/B Test Results # # This project will assure you have mastered the subjects covered in the statistics lessons. The hope is to have this project be as comprehensive of these topics as possible. Good luck! # # ## Table of Contents # - [Introduction](#intro) # - [Part I - Probability](#...
import numpy as np import matplotlib.pyplot as plt # Lección 05 # # Proyecto básico de machine learning # Manejo de datos # Graficación de datos data = np.loadtxt("DataS.txt") print("primeros 10 datos: ", data[:10], "\n") # Numero de datos print("Numero de datos: ",data.shape) x = data[0] y = data[1...
# writing a simple face detection proram # import modules import cv2 import numpy as np # Now we load in the facial classifiers face_detect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml'); # now we create a video capture object to capture videos from webcam cap = cv2.VideoCapture(0); # we create a lo...
"""写程序把一个单向链表顺序倒过来(尽可能写出更多的实现方法,标出所写方法 的空间和时间复杂度)""" class Node(object): def __init__(self,item): self.item = item self.next = None #第一种方法: def loopList(node): while node.next != None: node.next.next = node node=node.next #利用三个指针逐个反转 def f1(head): p = head q = head.next...
"""求和问题,给定一个数组,数组中的元素唯一,数组元素数量 N >2,若数组中的 两个数相加和为 m,则认为该数对满足要求,请思考如何返回所有满足要求的数对(要 求去重),并给出该算法的计算复杂度和空间复杂度(2018-4-23-lyf)""" #时间复杂度是O(n**2) #空间复杂度是O(n) def two_num_sum_list(list,sum): hash = set() for i in range(len(list)): for j in range(i+1,len(list)): if (list[i] + list[j] )== sum: ...
import random new=open('s.txt','w') new.write('computer mouse keyword') new.close() punct = (".", ";", "!", "?", ",") count = 0 new_word = "" inputfile = 's.txt' with open(inputfile, 'r') as fin: for line in fin.readlines(): for word in line.split(): if len(word) > 3: ...
import collections def calculations(x): def max_of_elements(x): print("Maximum element in the list :", max(x)) def min_of_elements(x): print("Minimum element in the list :", min(x)) def mean_of_list(x): sum=0 for i in range(0,len(x)): sum= sum + x[i] mea...
import threading import time import random exitFlag = 0 class myThread(threading.Thread): def __init__(self, threadID, name, counter, results): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter self.results = results def ...
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:loftybay count = 0 ages_ing = 15 while count < 3: ages = int (input("亲输入一个我心里想的数字:")) if ages == ages_ing: print("恭喜您,猜对了") break elif ages > ages_ing: print("猜大了") else: print("猜小了") count = count +1 if count =...
#!/usr/bin/env python import csv from _ast import Num from math import sqrt ifile = open('sample.csv', "rb") reader = csv.reader(ifile) results = [] rownum = 0 for row in reader: # Save header row. if rownum == 0: header = row else: colnum = 0 for col in row: print ...
# SIMPLE EXAMPLE OF PROPERTY DECORATOR - GETTER, SETTER AND DELETER class Employee: def __init__(self, first, last): self.first = first self.last = last @property def email(self): return "{}.{}@mail.com".format(self.first, self.last).lower() @property def fullname(self):...
# Longest Increasing subsequence # Problem Definition: # Given a sequence , find the largest subset such that for every # i < j, ai < aj. # import sys # # This problem requires us to use dynamic programming technique. # # We should identify a sub structure similar to a DAG (directed acyclic graph) # that we for...
__author__ = 'Ed Cannon' #groupby multiple columns: grouped = df.groupby(['A', 'B']) import pandas as pd from filter_df import load_csv import sys def groupby_single_column(df,col,oper): ''' aggregation functions available: mean, sum, size, count, std, var, sem, describe, first, last, nth, min, max :param...
''' Author: Rahul Title: Find Who tweeted most ''' from collections import OrderedDict #number of test cases t = int(input()) #input tweets as list tweets = [] for i in range(0,t): z = int(input()) for j in range(0, z): y = input() tweets.append(y) # dictionary for counting the no,...
def ft_map(function_to_apply, list_of_inputs): return (function_to_apply(element) for element in list_of_inputs) if __name__ == '__main__': def square(x): return x * x results = list(map(square, [1, 2, 3, 4, 5])) ft_results = list(ft_map(square, [1, 2, 3, 4, 5])) print(results) print(ft_results) print(resul...
import numpy def dot(x, y): """Computes the dot product of two non-empty numpy.ndarray, using a for-loop. The two arrays must have the same dimensions. Args: x: has to be an numpy.ndarray, a vector. y: has to be an numpy.ndarray, a vector. Returns: The dot product of the two vectors as a float. None if x or y ...
import numpy def mat_mat_prod(x, y): """Computes the product of two non-empty numpy.ndarray, using a for-loop. The two arrays must have compatible dimensions. Args: x: has to be an numpy.ndarray, a matrix of dimension m * n. y: has to be an numpy.ndarray, a vector of dimension n * p. Returns: The product of the...
import codecs import random lista = [] resolver = "" intentos = 0 with open("palabras.txt", "r", encoding="utf8") as palabras: palabras_contenido = palabras.readline() while len(palabras_contenido) > 0: palabras_contenido = palabras_contenido.replace("\n", "").split(" ") for i in palabras_con...
# 解决一个锁子产生的死锁问题 threading模块中有RLock,其相比Lock多了一个count变量,该变量用来记录上锁次数 import time from threading import Thread, RLock class Mythread(Thread): def run(self): if lock.acquire(): print("线程%s上锁成功..."%self.name) time.sleep(1) lock.acquire() lock.release() ...
from threading import Thread g_num = 0 def task1(): global g_num for i in range(1000000): g_num+=1 print("子线程1g_num的值为:%d"%g_num) def task2(): global g_num for i in range(1000000): g_num+=1 print("子线程2g_num的值为:%d"%g_num) t1 = Thread(target=task1) t1.start() t2 = Thread(target...
import math class Node: def __init__(self, dataVal = None): self.dataVal = dataVal self.nextVal = None class LinkedList: def __init__(self, n): self.headVal = Node(n) self.size = 1 def add(self, n): tmpNew = Node(n) tmp = self.headVal while(tmp.next...
class Stacks: def __init__(self): self.data = [] def push(self, stack, n): self.data.append((stack, n)) def pop(self, stack): for i in range(len(self.data) - 1, -1, -1): if(self.data[i][0] == stack): self.data.pop(i) return def top(s...
class Node: def __init__(self, dataVal = None): self.dataVal = dataVal self.nextVal = None class LinkedList: def __init__(self, n): self.headVal = Node(n) self.size = 1 def add(self, n): tmpNew = Node(n) tmp = self.headVal while(tmp.nextVal != None):...
import sys def isUnique(str): for i in range (0, len(str)): for j in range (i + 1, len(str)): if(str[i] == str[j]): return False return True def main(): if len(sys.argv) < 2: print("Use: $ python isunique.py word1 word2 word3 etc") else: for arg in s...
def check_grid(infile): # to check 1-9 in each columns #cols = [[row[i] for row in infile] for i in range(0,9)] list(infile) lst = infile lst_col = [] no_row = len(lst) no_col = len(lst[0]) for j in range(0,no_col): tmp = [] for i in range(0,no_row): tmp.append(lst[i][j]) lst_col.append(tmp) cols = lst...
from math import sqrt def is_prime(num): # make sure n is a positive integer num = abs(int(num)) # 0 and 1 are not primes if num < 2: return False # 2 is the only even prime number if num == 2: return True # all other even numbers are not primes if not n...
import random import heapq class Median: def __init__(self, data): self.data = data self.min_heap = [] self.max_heap = [] self.medians = [] def simplest_way(self): analyzed_now_list = list() medians = list() for elem in self.data: analyzed_n...
#!/usr/bin/env python3 basic_salary = 1500 bonus_rate = 200 commission_rate = 0.02 numberofcamera = int(input("Enter the number of inputs sold: ")) price = float(input("Enter the total prices: ")) bonus = (bonus_rate * numberofcamera) commission = (commission_rate * numberofcamera * price) print("Bonus = %6.2f"...
import numpy as np import matplotlib.pyplot as plt def Parametric_Classification(data, k, x): """ Determine which class has the highest posterior probability for the x-value and return the class number. Parameters: data(np.array): A n × 2 set of (training) input data. Where the first ...
""" this module is meant to handle the automation part of communicating with Alexa. Future: use https requests to call main module. In post payload, include a scribe type Make web request to run alexa -- if valid scribe type then - generate text - create mp3 from text (gTTS) - convert mp3 to wav - tell program t...
from tkinter import * #Importing tkinter root = Tk() root.title("Wiktarina") root.geometry("300x300") #Doing the first quiz def que_one(): question = Label(root, text="Wisit gruza i ee nelza skuzat?") answer = Entry() btn = Button(root, text="Otwetit!", command=lambda: game1(que_two())) question.grid...
class A: def pr(self): print('A') # 오버라이딩, 재정의 되었다. class SubA1(A): def pr(self): print('pr1') class SubA2(A): # def pr(self): # print('pr2') pass class SubA3: #print('Suba3') pass class MyApp(A): def pr(self): self.my_print() def my_print(self): ...
import sqlite3 conn = sqlite3.connect('d:/pythonProject/sqlite/example.db') c = conn.cursor() # Never do this -- insecure! symbol = 'RHAT' c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol) # Do this instead t = ('RHAT',) sql='SELECT * FROM stocks WHERE symbol=?' c.execute(sql, t) print(c.fetchone()) # L...
#!/usr/bin/env python import sys import lxml.html import urllib2 def get_tweets(tweeter): """ get_tweets(tweeter) - Returns a list of the 5 most recent tweets for tweeter. """ tweets = [] tweets_url = 'https://twitter.com/' + tweeter try: html = urllib2.urlopen(tweets_url).read() except: return twe...
#importing libraries: import requests from gpiozero import MotionSensor import time from picamera import PiCamera camera = PiCamera() #define the PiCamera() to camera variable camera.resolution = (1920, 1080) #set the resolution to 1920x1080 pir = MotionSensor(4) #setup input for MotionSensor (PIR sensor) at GPIO Pin...
try: i=int(input("enter ur number")) if i<3: b=(i/i-3) elif i==3: raise ZeroDivisionError else: raise TypeError except ZeroDivisionError: print("u hv choosen 3") except TypeError: print(" u hv chosen greater than 3") else: print(b) finally: print("completed")
from knightJumpsOut import knightJumpsOut def getMovePosition(move_dir, x_prev, y_prev): """ This function calculates the new position of the knight after it moves to any of the possible 8 directions assign x_new and y_new to -100 if the knight moves out of the chess board. (-100, -100) is just a sign...
#!/usr/bin/python3 from random import shuffle, choice class Card(): # Card ranks low_ranks = [x for x in range(2, 11)] high_ranks = ['j', 'q', 'k', 'a'] ranks = low_ranks + high_ranks # Card suits suits = ['spades', 'clubs', 'hearts', 'diamonds'] # Suits and ranks textual representation ...
#largest prime factor of the number ''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ''' #get the prime numbers upto 6008123 def is_prime(n): for i in range(2, (n//2 + 1)): if n% i == 0: #that means it is a prime retu...
print('合計点と平均点を求めます') n = int(input('学生の人数:')) tnsu = [None] * n for i in range(n): tnsu[i] = int(input('{}番の点数'.format(i + 1))) sum = 0 for i in range(n): sum += tnsu[i] print('合計は{}点です'.format(sum)) print('平均は{}点です'.format(sum / n))
sum = 0 for i in range(1,11): sum += int(input(str(i) + "回目の入力:")) print("合計:",sum,sep="")
import random num1 = random.randint(0,9) num2 = random.randint(0,9) num3 = random.randint(0,9) num4 = random.randint(0,9) print(num1,"+",num2,"×",num3,"-",num4) t = num1 + num2 * num3 - num4 n = int(input("計算結果は?:")) if t == n: print("正解です!") else: print("不正解です。正解は",t,"です。")
capital = '東京' area = 2193 print('日本の首都は',capital,'面積は',area) print('吾輩は猫である。',end='') print('名前はまだない。',end='') print('お名前を入力してください') name = input() print('こんにちは',name,'さん!') n = input("文字の入力:") c = int(input("整数の入力:")) t = int(input("小数の入力:")) print("入力された文字 =",n) print("入力された整数 =",c) print("入力された小数 =",t)
n = int(input('挨拶は何回:')) for i in range(1,n+1): print('No.',i,'こんにちは')
#program to count the number of times the number price occurs in a string and if it occurs next to punctuation and capital s=input("enter any string: ") def count(s): count=0 for word in s.lower().split(): if 'price' in word: count=count+1 return count print(count(s))
#program to generate random numbers from 1 to 20 and append them in list import random a=[] n=int(input("enter the number of elements:")) for i in range(n): a.append(random.randint(1,20)) print("randomised list is:{}".format(a))
#program to check if a given key exists in the dictionary or not a={} n=int(input("enter the number of elements: ")) for i in range(n): k=input("enter the keys: ") v=int(input("enter the values: ")) a.update({k:v}) print(a) y=input("enter the key to check: ") if y in a.keys(): print("key is pr...
#program to prove that two string variables of same value point same memory loaction str1="siddhi" str2="siddhi" print("str1: ",hex(id(str1))) print("str2: ",hex(id(str2)))
#program to check whether number is armstrong number or not n=int(input("enter any number: ")) a=list(map(int,str(n))) #to convert int into str and list it b=list(map(lambda x:x**3,a)) #to multiply each element in string by 3 of list a print(a) print(b) if(sum(b)==n): print("armstrong number") else: ...
#program to get numbers divsible by 15 from a list lst=[] n=int(input("enter the number of elements: ")) for i in range(n): x=int(input("enter the element: ")) lst.append(x) result=list(filter(lambda p:(p%15==0),lst))#this p if x even gives the same answer print(result)
import time import datetime def seconds_countdown(x): now = int(time.strftime("%s")) countdown = int(input("How many seconds would you like to count?\n")) while True: near = int(time.strftime("%s")) if countdown > 0: print(countdown) time.sleep(1) countd...
text = [] max_length = 0 for _ in range(5): word = input() if len(word) > max_length: max_length = len(word) text.append(word) out= '' for i in range(max_length): for j in range(5): if i < len(text[j]) and text[j][i] != '': out += text[j][i] print(out)
seen, heard = map(int, input().split()) people = [] from collections import Counter for person in range(seen+heard): p = input() people.append(p) counted = Counter(people) both = [] for name, cnt in counted.items(): if cnt == 2: both.append(name) both.sort() print(len(both)) for name in both: ...
T = int(input()) prime_digit = {2:[6,2,4,8], 3:[1,3,9,7], 5:[5], 7:[1, 9,3,7]} def divide(num): primes = {2:0, 3:0, 5:0, 7:0} for prime in primes.keys(): while num % prime == 0 : primes[prime] += 1 num = num // prime return primes, num def getlast_digit(prime_divided): t...
def solution(amountText): answer = True if amountText.startswith(',') or amountText.endswith(','): return False splitted = amountText.split(',') if splitted[0].startswith('0'):return False for i in range(len(splitted)): if i > 0 and len(splitted[i]) != 3 : return False ...
num = input() from collections import Counter counter = Counter(num) sixnine = 0 others = 0 for c in counter.items(): if c [0] in ['6', '9']: sixnine += c[1] else: others = max(others, c[1]) print(max(sixnine//2 + sixnine%2, others))
import heapq from collections import deque def update_next(new=None): global # () for j in wait: if wait pass def solution(jobs): second = 0 done = 0 end = False job = False jobque = deque(jobs) wait = [] next = jobs[0] while done != len(jobs): if sec...
# second lowest grade. records = {} names = [] for _ in range(int(input())): name = input() score = float(input()) if score in records.keys(): temp = records[score] temp.append(name) records[score] = temp else: records[score] = [name] lowest = min(records.keys()) second ...
def josephus(num, target): from collections import deque q = deque(list(range(1, num + 1))) order = [] while q: value = q.popleft() q.append(value) value = q.popleft() q.append(value) order.append(q.popleft()) return order def main(): print(josephus(15...
from matplotlib import pyplot as plt #import statsmodels.api as sm import statsmodels.formula.api as smf # This is different # import pandas as pd import numpy as np # Generating the data N = 20 error_scale = 2.0 x = np.linspace(10,20,N) y_true = 1.5 + 3 * x y_measured = y_true + np.random.normal(size=N, loc=0, scal...
#What: Getting data from API (forecast.io API) #Where: https://courses.thinkful.com/DATA-001v2/assignment/3.2.2 import sqlite3 as sql import requests import datetime # Define some parameters my_api_key = "1c961049c5a9d5fef2e405478a1eadc5" cities = { "Atlanta": '33.762909,-84.422675', "Austin": '30.303936,...
# Quick crash course on sqlite3 # See: https://docs.python.org/2/library/sqlite3.html import sqlite3 def print_table(cursor): for row in cursor.execute('SELECT * FROM persons ORDER BY name'): print row return ################################################################################ # Connect to...
# Quick crash course on sqlite3 and pandas # See: https://docs.python.org/2/library/sqlite3.html import sqlite3 import pandas as pd # Auxiliar function def print_table(cursor): for row in cursor.execute('SELECT * FROM persons ORDER BY name'): print row return ##########################################...
# -*- coding: utf-8 -*- """ Created on Thu Sep 20 08:48:56 2018 @author: ali hussain """ class Rectangle(): def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): return self.length*self.breadth a=int(input("Enter length ...
def cheche(x,y): # x mean number of loop , y its static mean number your enter ex: 7 Center = round(y/2+0.5) diff = abs(Center-x) # abs function conver nigatave to positive space = abs((diff+diff+2)-y) if x == 1 or x == y: return " "*diff + "*" + " "*diff else: return " "*diff+"*"+" "*space+"*"+" "*d...
n = int(input("첫 번째 수 입력 : ")) m = int(input("두 번째 수 입력 : ")) def find_even_number(): numbers = [ i for i in range(n, m+1) if i%2 == 0] for s in numbers : print(s, '짝수') if s == (n + m) / 2 : print (s, '중앙값') find_even_number()
# import time name = input("what is your name?") print('nice to meet you,', name) # time.sleep(5) # print('sleep off') greet = input(f"how are you, {name}?") print(greet)
#SWM v2 feature transformation import numpy as np #import matplotlib.pyplot as plt def feature_transformation(feature_vector): """Adjusts and rescales the values of SWMv2 features to fall within an appropriate range. ARGUEMENTS feature_vector: a list of the features values of a single state of the SWM v...
from sys import argv from os.path import exists script, input_file, output_file = argv print(f"Dies input file exist? {exists(input_file)}") #check if files exist print(f"Does output file exist? {exists(output_file)}") print("hit RETURN to continue, CTRL-C to abort.") input() file_copy = open(input_file, 'r') #open ...
badu_abil=False badu_punt=False helbidea=input("Sartu zure e-posta helbidea: ") # for i in helbidea: # if(i=="@"): # badu_abil=True # if(i=="."): # badu_punt=True if "." in helbidea: badu_abil=True if "@" in helbidea: badu_punt=True if badu_abil and badu_punt: print("Ados, aurrer...
#using index function we can access the value in a tuple since it is ordered mytuple = (1,2,3,4,5,6) mytuple[2]
import myMath as m n = int(input()) x = float(input()) x *= 3.14/180 val = 0 num = 1 for i in range(1, n+1): if(i % 2 != 0): val += m.power(x, num) / m.fact(num) else: val -= m.power(x, num) / m.fact(num) num += 2 print("sin(", x, ") =", val)
from __future__ import division import math water_density=1000 #kg/m3 gravity=9.8 #m/s2 def pipe_velocity(pipe_diameter, demand_m3_s): area=math.pi*(pipe_diameter*0.001/2)**2 pipe_velocity=demand_m3_s/area return pipe_velocity def headloss(pipe_diameter, pipe_length, demand_m3_s): headloss=0.03*pipe_length*(pipe...
from TicTacToe.bots import player class Human(player.Player): """ A text based human player """ def __init__(self, symbol, opponent, name="Human"): """ name - Name of the player : String symbol - Symbol to play with : String opponent - Symbol to play agains...
#!/usr/bin/python3 """ an algorithm to calculate minimumOperations necessary to get to a number of characters. Full exercise: In a text file, there is a single character H. Your text editor can execute only two operations in this file: Copy All and Paste. Given a number n, write a method that calculates the fewest numb...
#!/usr/bin/python import mysql.connector city = input("Enter A CITY NAME: ") print ("City entered was: ", city) # Setup MySQL Connection # Pass viewer: *AAB3E285149C0135D51A520E1940DD3263DC008C db = mysql.connector.connect(host="173.194.242.211", user="root", password="InfectiousTraining", db="IM_Task_2") cursor = db...
def mergesort(array): if len(array) <= 1: return array else: left = mergesort(array[:len(array)//2]) right = mergesort(array[len(array)//2:]) combined = [] #counters i = 0 j = 0 #while the counter hasn't reached the end of the array while i...
password = input() new_pass = [] for character in password: new_pass.append(chr(ord(character)+3)) print("".join(map(str,new_pass)))
import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # mo = phoneNumRegex.search('Call me 415-555-1011 tomorrow, or at 415-555-9999 for my office line.') # print(mo.group()) print(phoneNumRegex.findall('Call me 415-555-1011 tomorrow, or at 415-555-9999 for my office line.'))
""" Challenge #3: Create a function that takes a string and returns it as an integer. Examples: - string_int("6") ➞ 6 - string_int("1000") ➞ 1000 - string_int("12") ➞ 12 """ def string_int(txt: str) -> int: # Your code here # check to make sure that `txt` makes sense as an integer # the `isnumeric` funct...
""" Given an array of integers `nums`, define a function that returns the "pivot" index of the array. The "pivot" index is where the sum of all the numbers on the left of that index is equal to the sum of all the numbers on the right of that index. If the input array does not have a "pivot" index, then the function s...
""" You are given a binary tree. You need to write a function that can determine if it is a valid binary search tree. The rules for a valid binary search tree are: - The node's left subtree only contains nodes with values less than the node's value. - The node's right subtree only contains nodes with values greater t...
# Determine if a string sequence of {}[]() is valid # '[{]}' is invalid def validBracketSequence(sequence): # determine if the string is a valid sequence of brackets # empty is valid # stack = [] for char in sequence: if char in {'(', '[', '{'}: stack.append(char) # wha...
# # Binary trees are already defined with this interface: # class Tree(object): # def __init__(self, x): # self.value = x # self.left = None # self.right = None def max_depth(node): if node is None: return 0 max_l = max_depth(node.left) max_r = max_depth(node.right) ...
""" Given only a reference to a specific node in a linked list, delete that node from a singly-linked list. Example: The code below should first construct a linked list (x -> y -> z) and then delete `y` from the linked list by calling the function `delete_node`. It is your job to write the `delete_node` function. ``...
# We only multiply when some logic is nested # When code is stacked sequentially on top of one another # we add their respective runtimes # O(1) + O(1) + O(1) + O(0.5n) + O(2000) # O(0.5n + 2000 + 1 + 1 + 1) # O(0.5n + 2003) # O(n + 2003) # O(n) def do_a_bunch_of_stuff(items): last_idx = len(items) - 1 # getting...
""" Challenge #4: Create a function that takes length and width and finds the perimeter of a rectangle. Examples: - find_perimeter(6, 7) ➞ 26 - find_perimeter(20, 10) ➞ 60 - find_perimeter(2, 9) ➞ 22 """ def find_perimeter(length, width): # takes in length and width, integers # returns perimeter # perimet...
""" Challenge #6: Return the number (count) of vowels in the given string. We will consider `a, e, i, o, u as vowels for this challenge (but not y). The input string will only consist of lower case letters and/or spaces. """ def get_count(input_str: str) -> int: # Your code here # count number of vowels ...
""" Challenge #7: Given a string of lowercase and uppercase alpha characters, write a function that returns a string where each character repeats in an increasing pattern, starting at 1. Each character repetition starts with a capital letter and the rest of the repeated characters are lowercase. Each repetition segment...
""" Demonstration #2 Given a non-empty array of integers `nums`, every element appears twice except except for one. Write a function that finds the element that only appears once. Examples: - single_number([3,3,2]) -> 1 - single_number([5,2,3,2,3]) -> 5 - single_number([10]) -> 10 """ def single_number(nums): # ...
def square_of_sum(count): square = 0 tot = 0 for num in range(count + 1): tot += num square = tot * tot return square def sum_of_squares(count): tot = 0 for num in range(count + 1): tot += (num * num) return tot def difference(count): return square_of_sum(coun...
def find_anagrams(word, candidates): result = [i for i in candidates if i.lower() != word.lower( ) and sorted(i.lower()) == sorted(word.lower())] return result
def is_equilateral(sides): if sides[0] + sides[1] <= sides[2] \ or sides[2] + sides[1] <= sides[0] \ or sides[0] + sides[2] <= sides[1]: return False elif sides[0] == sides[1] and sides[0] == sides[2]: return True else: return False def is_isosceles(sides): ...