text
stringlengths
37
1.41M
#Opeartors # perform arthmetic operations on two variables n1 = 30 n2= 20 sum = n1 + n2 print("sum = ", sum) sub = n1 - n2 print("sub = ", sub) mul = n1 * n2 print("mul = ", mul) div1 = n1 / n2 print("div1 = ", div1) div2 = n1 // n2 print("div2 = ", div2) rem = n1 % n2 print("rem = ", rem) z ...
""" take bankname(string) as input , if bankname value is "sbi" o/p => ROI is 10% if bankname value is "icici" o/p => ROI is 11% if bankname value is "hdfc" o/p => ROI is 12% if bankname value is "citi" o/p => ROI is 13% other than this o/p => invalid bank """ #approach1 x=input("enter value") if x=="IC...
""" take id ,age , usertype as input perform validation id should be positive: age should be greater than 18: usertype should be "admin": if id,age,usertype is valid ==> print valid data if any data found to be invalid ==> print invalid data Req: can we write multiple conditions in one if statement? Yes - and if...
n1 = int(input("enter num1 ")) n2 = int(input("enter num2 ")) n3 = int(input("enter num3 ")) if n1 > n2: #big is between n1 and n3 if n1 > n3: print("Big = ", n1) else: print("Big = ", n3) else: # big is between n2 and n3 if n2 > n3: print("Big = ", n2) else: ...
# take numbers as input and perform sum , if the input is negative then stop the program ad print final sum sum = 0 num = 0 while (num >= 0): sum = sum + num num = int(input("enter number")) print(" sum = ", sum)
""" Req: - Create person class with id, name , age as instance variables. - id, name , age are private - provide setters and getters - create object and set the data and print the data """ class PersonInfo: def __init__(self, pId, pName, pAge): self.__id = pId self.__name = pName self....
""" can a developer create exception? YES STEPS: ----------------------- 1.Create exception obj 2.raise the exception - raise the exception on conditional basis - raise exception logic should be written inside the conditional blocks. #syntax for Create exception obj: ex1 = ValueError("invalid data") ex2 = IndexErro...
""" 1.open existing excel 2.Delete sheet 3.save file How to create workBook obj for existing excel? workbook = load_workbook('response.xlsx') """ from openpyxl import Workbook, load_workbook # create workbook obj workbook = load_workbook('response.xlsx') # get the existing sheet #sheet = workbook.get_sheet_by_n...
""" write a print statement for every method start write a print statement for every method end """ def log(func): def operation(): print("funtion start "+ str(func.__name__)) func() print("funtion end " + str(func.__name__)) return operation; @log def sum(): print("In sum")...
import re """ [] A set of characters ATLEAST ONE OF THE CHAR EXISTS : [0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present [arn] Returns a match where one of the specified characters (a, r, or n) are present [a-n] Returns a match for any lower case character, alphabetically between a ...
# 定义一个学生类,用来形容学生 # 定义一个空的类 class Student(): # 一个空类,pass 代表直接跳过,此处pass不能省略 pass # 定义一个对象 mingyue = Student() # 定义一个雷,用来描述听Python的学生 class PythonStudent(): # 用None给不确定的赋值 name = None age = 18 course = "Python" # def 需要注意缩进的层级 # 系统默认由一个self参数 def doHomework(self): print("...
#!/usr/bin/env python """ The Following module does mathematical operation with Roman numerals. Author: Ravi Kishan Jha. Date: 15th November 2017. """ def main(): '''This Function is the main function of the code. performs Arithmetic operations on the Roman Numbers Input Attributes: Roman Value...
#This program that keep asking you to type, litarally, "your name" try: Name = input() except EOFError: Name = '' while Name != 'your name': print('Try again, write your name') try: Name = input() except EOFError: Name = '' print('Well done')
# Import libraries import pandas as pd import datetime as dt def date_related_features(data_df): """ For each date column create three separate columns that store the corresponding month, year and week For each date column create a column that stores the date in seconds from the reference date (1st Januar...
#!/usr/bin/python import time def main(): max_digital_sum = 0 for a in range(100): for b in range(100): numero = a**b s_numero = str(numero) lista = [int(x) for x in s_numero] sumatoria = sum(lista) if sumatoria > max_digital_sum: ...
#!/usr/bin/python import time from math import sqrt listadoPrimos = [] def esPrimo(x:int) -> bool: if x == 1: return False if x < 4: return True if x % 2 == 0: return False if x < 9: return False if x % 3 == 0: return False sqrtx = int(sqrt(x)) i = 5 while i <= sqrtx: if x % i...
#!/usr/bin/python import time import itertools from math import sqrt def isPrime(x): if x == 1: return False if x < 3: return True if x%2==0: return False if x < 9: return True if x%3==0: return False sqrtx = int(sqrt(x)) i = 5 while i <= sqrtx: if x % i == 0: return False ...
#!/usr/bin/python import time def main(): number = 1 while True: digits = sorted(list(str(number))) flag = True for i in range(2,7): n = number * i ndigits = sorted(list(str(n))) if digits != ndigits: flag = False ...
#!/usr/bin/python3 import time def main(): continuedFraction = [2] for i in range(1,35): continuedFraction.extend([1, 2*i, 1]) continuedFraction = continuedFraction[:100] numerador = continuedFraction[99] denominador = 1 for j in continuedFraction[:99][::-1]: aux = denominador...
''' 测试 try...except...finally... ''' for i in range(2)[::-1]: try: print('try...') r = 10 / i a = 'dfg' print('result:', r) except ZeroDivisionError as e: print('except:', e) a = 'fdfdg' finally: print('finally...') t = ('evd', a, 'df') print...
# Let's create a basic functions to greet # Syntax def name(): # first iterations # def greetings(): # return "Welcome to Cyber Security! " # # print(greetings()) # # Second iteration # def greeting_user(name): # return "welcome on board1" # # # Take user name as input() and disply is back to them with greet...
''' Author: Kwadwo Boateng Ofori-Amanfo Purpose: Learn how to convert images from one format to another. We will use this file to perform the same actions done with image magic as outlined in the 'NB:' section below Date: 2019. 11. 28. (목) 14:08:53 KST Video Lecture(s): OpenCV Programming with Python on Linux Ubuntu Tu...
import time import turtle import random BREAK_FLAG = False #for snake eating itself # Draw window screen = turtle.Screen() screen.title("Snake GAME NOKIA") screen.bgcolor("lightgreen") screen.setup(600,600) screen.tracer(0) #for turning off animation #Draw border border = turtle.Turtle() border.hide...
a=str(input("enter the character:")) print("The ASCII Value of entered character is",ord(a))
# Asking for Video Link video = input("Insert Video Link: ") # Downloads video page import urllib.request urllib.request.urlretrieve(video, "video.html") # Defines "everything_between" def everything_between(text,begin,end): idx1=content.find(begin) idx2=content.find(end,idx1) return content[id...
# coding:utf-8 # author: Tao yong # Python ''' matplotlib是一个第三方数学绘图库 模块pyplot包含了很多生成图标的函数 plot()----折线图 sctter()----散点图 ''' from matplotlib库.random_walk import RandomWalk #添加中文字体 from pylab import * # 添加中文字体 from pylab import * from matplotlib库.random_walk import RandomWalk mpl.rcParams['font.sans-...
# -*- coding: utf-8 -*- """ Created on Sat Jul 11 13:57:59 2020 @author: ANN by OMAAR, """ import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('Churn_Modelling.csv') """ X = dataset.iloc[:, 3:13].values #[:, [2,3]] is also correct !! y = dataset.iloc[:, 13]...
class juego: """Clases encargada de la generacion de la matriz a utilizar para desarrollar el juego""" n = 0 m = 0 matriz=[] def __init_(self,n,m,matriz): self.n=n #se pide la cantidad n self.m = m #se pide la cantidad m self.matriz=matriz #variable para crear matriz de...
import streamlit as st import numpy as np import pandas as pd from PIL import image from sklearn.neighbors import KNeighborsClassifier def welcome(): return "Welcome All" def predict_heart_diseases( age , sex ,cp ,trestbps , chol , fbs , restecg , thalach , exang , oldpeak , slope , ca , thal): classifier = KNeigh...
#!/usr/bin/python3 # from random import seed # from random import randint def clear(): # clear the terminal screen print("\n"*50) def banner(): # prints a banner and game mode menu print(""" &&& &&& &&& & & & & & & & & & & * * * Welcome\n to\n Number Gu...
import sys #import random from random import randint #from random import seed #from datetime import datetime # lets us have random integers num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] # defines the number list sym = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '`', '~', '-', '_', '=', '+',...
number = int(input("Enter a number: ")) print("Multiplication Table of: " + str(number)) for i in range(11): print(number,'x',i,'=',number*i)
try: year = int(input("Enter Year: ")) if(year > 0): if((year % 4) == 0) : if(year % 100 == 0): if(year % 400 == 0): print(year, "is a leap year.") else: print(year, "is not a leap year.") else: ...
def sum(x,y): s=0 for i in range (x,y+1): s=s+i return s x=int(input("enter the number")) y=int(input("enter the number")) print(sum(x,y))
import hashlib class AbstractPlayer: def __init__(self): """Abstract base class for a game player.""" # These variables are what .setup() and .run() can use # to prepate and play against another player! self.opponent = None self.move = 0 self.state = None se...
""" functions used by multiple methods TODO - probably rename the file lets be real 'shared_functions' is hardly clear """ import itertools import collections import random def prime_factor_decomposition(val): """Reduce any integer into its unique prime decomposition, returning the input integer if the integer i...
nums = [4,3,2,7,8,2,3,1] nums = [1,1] nums = [2,2] max(nums) min(nums) if nums == []: print([]) ans = [] for num in range(1, len(nums)+1): if num not in nums: ans.append(num) print(ans) def findDisappearedNumbers(nums): if nums == []: return [] ans = [] for num in range(1, ...
word = "Dsdfs" if len(word) > 1: if word == word.upper() or word[1:] == word[1:].lower(): print(True) else: print(False) else: print(True) class Solution: def detectCapitalUse(self, word: str) -> bool: if len(word) > 1: if word == word.upper() or word[1:] == word[...
input_ints = [4, 1, 1, 1, 1, 2, 2, 2, 3, 3] def findTopTwo(input_ints): result = {} for input_int in input_ints: if input_int in result.keys(): result[input_int] += 1 else: result[input_int] = 1 fst_freq = sorted(result.values())[-1] snd_freq = sorted(result.valu...
bills = [5,5,5,10,20] bills = [5,5,10] bills = [10,10] bills = [5,5,10,10,20] check = True wallet = {5:0, 10:0, 20:0} for bill in bills: if bill == 5: wallet[bill] += 1 elif bill == 10: if wallet[5] > 0: wallet[5] -= 1 wallet[bill] += 1 else: check...
A = [1,2,5] B = [2,4] A = [1,1] B = [2,2] A = [1, 2] B = [2, 3] A = [2] B = [1,3] check = False for itemA in A: for itemB in B: if sum(A)-itemA+itemB == sum(B)-itemB+itemA and check == False: check = True print([itemA, itemB]) class Solution: def fairCandySwap(self, A: List[...
A = [[1,2,3],[4,5,6]] class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: row = len(A) col = len(A[0]) #print(row) #print(col) matrix = [[0 for x in range(row)] for y in range(col)] #print(matrix) for tcol, row in enumerate(A): ...
a = [5, 1, 6, 2] print(a) #This sorts the list, but the original list is untouched print(sorted(a)) strs = ['aa', 'bb', 'zz', 'cc'] print(sorted(strs)) #you can customize the sorted function #reverse = True means it will sort it in backwards print(sorted(strs, reverse = True)) """ Sorting with key optional argument ke...
import pandas as pd reddit = pd.read_csv("/home/master/Projects/bil476/reddit.csv") _input = 0 index = 101 pagenames = [] authors = [] titles = [] comments = [] targets = [] while (True): pagename = reddit['pagename'][index] author = reddit['author'][index] title = reddit['title'][index] comment = red...
words = input("Enter the words of string:: ") splitTheWords = words.split() #firstly spliting those words in list NowReverseThoseWords = splitTheWords[::-1] #slicing the words in reverse order NowJoinThoseReversedWords = ' '.join(NowReverseThoseWords) #joining those reversed words with a space between print("Rever...
''' Created on Feb 11, 2015 @author: daman ''' import sys from curses.ascii import isalnum import re def isRoman(s): #tens character can be repeated up to 3 times if re.search(r'I{4,}',s) or re.search(r'X{4,}',s) or re.search(r'C{4,}',s) or re.search(r'M{4,}',s): #print 'error tens char issue' ...
''' Created on Jun 26, 2015 @author: damanjits ''' import functools from random import random ''' https://codewords.recurse.com/issues/one/an-introduction-to-functional-programming ''' def mapReduceFilter(): people = [{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}, {'na...
from byotest import * usd_coins = [100, 50, 20, 10, 5, 1] eur_coins = [100, 50, 20, 10, 5, 2, 1] # Function 1 def get_change(amount, coins=eur_coins): change = [] for coin in coins: while coin <= amount: # Change is always going to be less, or in rare occasions, equal to amount spent ...
a = int(input('a:')) b = int(input('b:')) c = int(input('c:')) #1) Если нет ни одного 0, вывести "Нет нулевых значений" x1 = bool(a) and bool(b) and bool(c) and "Нет нулевых значений!!!" print(x1) #2) Вывести первое нулевое значение. Если все нули, то "Введены все нули!" x2 = a or b or c or "Введены все нули!" print(x2...
import time class TimerHandler: def __init__(self): self.current_timestamp = None self.duration_unit = None self.duration_unit_div = None self.duration_length = None self.duration_interval = None # Setting functions def set_timestamp(self): self.cu...
# -*- coding:utf-8 -*- # single process multi thread (spmt) import threading from time import ctime, sleep class Entertainment: def music(self, name): for i in xrange(10): print "%s listen music %s" % (ctime(), name) sleep(1) def movie(self, name): for i in xrange(10...
class Point3D: """Class which stores point coordinates. All other structure objects from geometry module use one or more Point3D objects to build the structure.""" def __init__(self, x, y, z = None): """Class constructor for Point3D object. As a param it takes coordinates of the point. If z coordinate i...
class Parent: def __init__(self): print("this is the parent class") def parentFunc(self): print("this is the parent func") def test(self): print("Parent") class Child(Parent): def __init__(self): print("this is the Child class") def childFunc(self): print("this is the child func") def...
# #If the numbers 1 to 5 are written out in words: one, two, three, four, five, then # there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, # how many letters would be used? # # # NOTE: Do not count spaces or hyphens. For ...
import gym import random import pandas import argparse import numpy as np import matplotlib.pyplot as plt class QLearn: def __init__(self, actions, epsilon, alpha, gamma): self.q = {} self.epsilon = epsilon # exploration constant self.alpha = alpha # discount constant self.gamma ...
name_of_user = input("Можете ввести свое имя: ") surname_of_user = input("Можете ввести свою фамилию: ") def get_name(name, surname): print("Добрый день", name.title() +" "+ surname.title()) get_name(name_of_user, surname_of_user)
#теперь мы можем попробовать считать файл с except # filename = 'file.txt' filename = 'file1.txt' try: with open(filename) as file: content = file.read() print(content) except FileNotFoundError: message = "Извиняйте, файл " + filename + " не существует" print(message)
# дополнительная программа Python import random flag = input("Вы хотите поиграть в русскую рулетку? Введите да/нет: ") baraban = [0, 0, 0, 0, 0, 0] bullet_amount = 1 def try_play(bullet_amount): # print("В револьвере " + str(bullet_amount) + " патрон") print(bullet_amount) for i in range(1, bullet_amount): ba...
from survey import AnonymousSurvey # Определяет вопрос, и сохраняет все вопросы question = "Какой язык вы хотите изучить первым?" my_survey = AnonymousSurvey(question) # показывает вопрос и сохраняет ответ my_survey.show_question() print("Введите 'q' для окончания работы программы\n") while True: response = input...
person = {'names':[], 'surnames': []} def create_person(name, surname): """Возвращает словарь с информацией о человеке""" person['names'].append(name) person['surnames'].append(surname) return person user_size = int(input("Введите количество пользователей, которые должны появиться в этом словаре: ")...
# мне она нравится тем, что существует огромная масса вариантов, как это можно написать и сделать # давайте напишем несложнуую программу русской рулетки # к примеру: import random amount_of_bullets = input( 'Сколько патронов вы собираетесь вставить в револьвер?') aob = int(amount_of_bullets) baraban = [0, 0, 0, 0,...
#!/usr/bin/python # checkDuplicates.py # Python 2.7.6 """ Given a folder, walk through all files within the folder and subfolders and get list of all files that are duplicates The md5 checcksum for each file will determine the duplicates. Then display dupes and give options to delete specified files. """ import os...
import time import pandas as pd import numpy as np CITY_DATA = { 'Chicago': 'chicago.csv', 'New York City': 'new_york_city.csv', 'Washington': 'washington.csv' } def get_filters(): print('Hello! Let\'s explore some US bikeshare data!') while True: city = input('1. Which ci...
# --(NumPy Array Example)-------------------------------------------------------- """ This lesson demonstrates how the **TabularEditor** can be used to display (large) NumPy arrays. In this example, the array consists of 100,000 random 3D points from a unit cube. In addition to showing the coordinates of each p...
# Try it yourself, page 178 class Users: """Making a class for user profiles.""" def __init__(self, first_name, last_name, username, email, location): """Initialize the user.""" self.first_name = first_name.title() self.last_name = last_name.title() self.username = username ...
# try it yourself, page 64 numbers = [] for value in range(1, 11): numbers.append(value**3) for value in numbers: print(value)
# Try it yourself, page 102 favorite_numbers = { 'blaine' : 6, 'sally' : 42, 'austin' : 14, 'phil' : 7, 'lee' : 9, } print("Blaine's favorite number is " + str(favorite_numbers['blaine']) + ".") print("Sally's favorite number is " + str(favorite_numbers['sally']) + ".") print("Austin's favorit...
# Try it yourself, page 171 class Restaurant(): """A simple attempt to model a restaurant.""" def __init__(self, restaurant_name, cuisine_type): """Initialize name and cuisine type""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0...
# Try it yourself, page 146 def city_country(city, country): """Return a string like 'Santiago, Chile'""" return(city.title() + ", " + country.title()) # instead of doing full_name = first_name + " " + last_name city = city_country('san diego', 'united states') print(city) city = city_country('beijing', 'chi...
# Try it yourself, page 141 print("\n") def make_shirt(size = 'L', message = 'I Love Python'): """Making a shirt""" print("Shirt size: " + size) print("Shirt message: " + message) make_shirt() print("\n\n") make_shirt(size = 'M') print("\n\n") make_shirt(size = 'S', message = "THIS DOESN'T FIT") print(...
# sorting a list permanently with the sort() method cars = ['bmw', 'audi', 'toyota', 'suburu'] cars.sort() print(cars) print("\n") # sorting in reverse alphabetical order.. cars = ['bmw', 'audi', 'toyota', 'suburu'] cars.sort(reverse = True) print(cars) print("\n") # you can sort a list temporarily and maintain the ...
# You can also use a dictionary to store different kinds of information about one object favorite_languages = {'jen' : 'python', 'sarah': 'c', 'edward' : 'ruby', 'phil' : 'python'} # When you know a dictionary is going to take up more than one line... write it as so... favorite_languages = { 'jen' : 'python', ...
# printing only even numbers in a list even_numbers = list(range(2, 11, 2)) # prints even numbers starting at 2 that increase by 2 until it reaches the final value of 11, hence the 2 after the 11 print(even_numbers)
# Try it yourself, page 186 from random import randint class Die: def __init__(self, sides=6): """Initializes the die.""" self.sides = sides def roll_die(self): """Return a random number between 1 and the number of sides of the die.""" return randint(1, self.sides) # Rolling...
# Try it yourself, page 166 class Users(): """Making a class for user profiles.""" def __init__(self, first_name, last_name, username, email, location): """Initialize the user.""" self.first_name = first_name.title() self.last_name = last_name.title() self.username = username ...
# Inheritance: If the class you're writing is a specialized version of another class you wrote... # ...you can use inheritance. When one class inherits from another, it automatically takes on all the attributes... # ...and methods of the first class. The original is called the Parent Class, the new is called the Child ...
# Using arbitrary keyword arguments # Sometimes you'll want to accept an arbitrary number of arguments, but you won't know ahead of time... # ...what kind of information will be passed to the function # In this example you know you'll get information about a user, but you're not sure what kind of info that will be def...
import util import functools class Labels: """ Labels describing the WumpusWorld """ WUMPUS = 'w' TELEPORTER = 't' POISON = 'p' SAFE = 'o' """ Some sets for simpler checks >>> if literal.label in Labels.DEADLY: >>> # Don't go there!!! """ DEADLY = set([WUMPU...
#!/usr/local/bin/python3 # -*- coding: UTF-8 -*- # Write a generator that calculates the number of seconds since midnight for events in access_log, # and show the first ten when the program is run import calendar import re datetimeFormat2 = '%d/%b/%Y:%H:%M:%S %z' def starttoday(): # built a today's midnight date w...
""" sales_report.py - Generates sales report showing the total number of melons each sales person sold. """ salespeople = [] melons_sold = [] # Using dictionary as a data structure is recommended # it will make the aggregation and the search faster # sales_info = { "sale_person_name": { # ...
# parameter: day counter, the db file name # function: if it is Day1, and there are delivery data in db file # Prints Day1 and all delivery information def melonDeliveryByDays(day, file): the_file = open(file) print() print ("Day %d"%day) for line in the_file: line = line.rstrip() ...
#all basic data types x=2 #x is int y=1.2 #y is float z="python" #z is string a=7j #a is complex b=["tik","tok","pop"] #b is list c=("tik","tok","pop") #c is tuple d={"tik","tok","pop"} #d is set e=range(5)...
#enter lenghth in cm and convert into meter & km cm=float(input("length:")) m=cm/100 km=cm/(1000*100) print(m) print(km)
# // Author: proRam # // Name: Shubh Bansal # // Dated: June 6, 2020 # // Question: https://www.codechef.com/JUNE20A/problems/TTUPLE import sys sys.stdin = open('JUNE20A/input.txt', 'r') sys.stdout = open('JUNE20A/output.txt', 'w') class Tuple(object) : def __init__(self) : self.f, self.s, self.t = None,...
primes = [] def __init__primes() : global primes primes = [2] isprime = [True for i in range(102) ] for i in range(3,102,2) : if isprime[i] : primes.append(i) for j in range(i*i, 102, i) : isprime[j] = False def groupAnagrams( strs ) : globa...
# -*- coding: utf-8 -*- # 文字列の平文を数値化する def str_to_int(chr): list_ord = [] str_list = list(chr) # 文字列をリストに格納 for s in str_list: ord_chr = ord(s) list_ord.append(ord_chr) return list_ord # 数値化した平文を文字列に直す def int_to_str(num_list): chr_list = [] for i in num_list: ori_c...
"""Brain-calc game module.""" import operator import random FIRST_MIN_NUMBER = 0 FIRST_MAX_NUMBER = 20 SECOND_MIN_NUMBER = 1 SECOND_MAX_NUMBER = 10 RULES = 'What is the result of the expression?' def get_question_and_answer(): """Brain-calc game. Generate math expression with two random numbers and a random...
#!/usr/bin/python3 from functools import lru_cache # https://www.geeksforgeeks.org/cutting-a-rod-dp-13/ # A Dynamic Programming solution for Rod cutting problem INT_MIN = -32767 # Returns the best obtainable price for a rod of length n and # price[] as prices of different pieces def cutRod(price, cost=0): '...
#!/usr/bin/python3 # https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/ # This code is contributed by Nikhil Kumar Singh(nickzuck_007) # Dynamic Programming implementation of LCS problem class LCS(object): ''' Create a LCS object ''' def __init__(self, X , Y): self._X = X self._...
# Import the functions from the menu option files in the project from CreateDatabase import * from AddRecord import * from UpdateRecord import * from DeleteRecord import * from DisplayAllRecords import * from DisplaySingleRecord import * # Defines the main function def main(): # Variable to quit out of program ...
from heapq import heappop,heappush,heapify heap=[] nums=[12,3,-2,6,8] #for num in numbs: #heappush(heap,num) #while heap: #print(heappop(heap)) heapify(nums) print(nums)
""" Given the root of a binary tree, invert the tree, and return its root. """ from test_utils import TreeNode def invert_tree(root: TreeNode) -> TreeNode: """ Explanation To invert a binary tree we need to reverse top down. Thus at root we swap the whole subtrees and iteratively do this all the way d...
# Tests for Add Two Numbers from problems.add_two_numbers import add_two_numbers from test_utils import compare_list_nodes, ListNode DEBUG = False def test_add_two_numbers_1(): l1 = ListNode(2, ListNode(4, ListNode(3))) l2 = ListNode(5, ListNode(6, ListNode(4))) expected = ListNode(7, ListNode(0, ListNo...
""" Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. """ from test_utils import ListNode def delete_duplicates(head: ListNode) -> ListNode: """ Explanation The first thing to notice is that each sorted number cou...
""" Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. """ from typing import List def find_duplicate(nums: List[int]) -> int: """ Explanation We are given the fact that ther...
from problems.merge_two_sorted_lists import ListNode, merge_two_lists from test_utils import compare_list_nodes DEBUG = False def test_merge_two_sorted_lists_1(): l1 = ListNode(1, ListNode(2, ListNode(4))) l2 = ListNode(1, ListNode(3, ListNode(4))) expected = ListNode( 1, ListNode(1, ListNode(2, ...
""" Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. """ from test_utils import TreeNode de...
""" Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused multiple times in the segmentation. """ from collections import defaultd...
""" Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Upda...
from striprtf.striprtf import rtf_to_text print("-----------------------------SGI-----------------------------") print("Limpe seu texto do SISP-01") continua = '' linha = " " while continua != 'n': print("Digite seu código RTF: (ao final da cola digite um '.') ") while True: print("> ", end="") ...