text stringlengths 37 1.41M |
|---|
num1 = int(input('Digite o primeiro valor: '))
num2 = int(input('Digite o segundo valor: '))
opçao = 0
while opçao != 5:
print('=~' * 30)
print(""" Escolha uma das opções
[1] Somar
[2] Multiplicar
[3] Maior
[4] Novos numeros
[5] Sair do programa """)
print('=~' * 30)
opçao = int... |
print('-='*20)
print('Analisador de triangulos')
print('-='*20)
a = float(input('Digite o primeiro lado do triangulo '))
b = float(input('Digite o segundo lado do triangulo '))
c = float(input('Digite o terceiro lado do triangulo '))
if a < b + c and b < a + c and c < b + a :
print('Os segmentos PODEM formar um tri... |
from datetime import date
anoN = int(input('Digite o ano do seu nascimento: '))
anoA = date.today().year
idade = anoA - anoN
if idade <= 9:
print('\033[31mClassificação: MIRIM')
elif idade <= 14:
print('\033[31mClassificação: INFANTIL')
elif idade <= 19:
print('\033[31mClassificação: JUNIOR')
elif idade <= ... |
somaidade = 0
mediaidade = 0
maioridade = 0
nomevelho = ''
totmulher20 = 0
for p in range(1, 5):
print('--------{}° PESSOA---------'.format(p))
nome = str(input('Nome: ')).strip()
idade = int(input('Idade: '))
sexo = str(input(' [M/F]: ')).strip()
somaidade += idade # somaidade = somaidade + idade
... |
n1 = int(input('Primeiro numero: '))
n2 = int(input('Segundo numero: '))
n3 = int(input('Terceiro numero: '))
if n1 > n2 and n1 > n3:
maior = n1
elif n2 > n3 and n2 > n1:
maior = n2
else:
maior = n3
if n1 < n2 and n1 < n3:
menor = n1
elif n2 < n3 and n2 < n1:
menor = n2
else:
menor = n3
print(f... |
#!/usr/bin/env python3
def binary_search(alist, key):
if len(alist) > 0:
mid = len(alist)//2
if alist[mid] == key:
return True
if key < alist[mid]:
return binary_search(alist[:mid], key)
if key > alist[mid]:
return binary_search(alist[mid+ 1:],... |
from __future__ import annotations
from math import atan2
from dataclasses import dataclass
@dataclass
class Point:
# def __init__(self, x: float, y: float):
# self.x = x
# self.y = y
x: float
y: float
def angle(self, other: Point):
"""Return the angle between a line a horizon... |
#!/usr/bin/env python
##
# @file
# @author Wes Dean <wdean@flexion.us>
# @brief calculate and display date / time relative to another date / time
#
# @details
# This tool will accept a date / time and the distance (delta) from the
# provided date / time (days, hours, etc.) and write the result
# of combining the two.
... |
from display import *
from draw import *
import math
screen = new_screen()
red = [ 255, 0, 0 ]
white = [ 255, 255, 255 ]
increment = (2 * math.pi) / 360
for i in range(360):
radius = 150 + i % 20
angle = i * increment
if i % 3 == 0:
color = white
else:
color = red
x = int(r... |
# Week 2 homework GCpercent.
# Jesse Matsubara 10-23-2017.
# First 100 nucleotides of the influenza H1N1 virus segment 8.
flu_ns1_seq = 'GTGACAAAGACATAATGGATCCAAACACTGTGTCAAGCTTTCAGGTAGATTGCTTTCTTTGGCATGTCCGCAAACGAGTTGCAGACCAAGAACTAGGTGA'
# 1) Count the number of "C's".
c_count = 0
for i in range(len(flu_ns1_seq)):
... |
print("============================================")
print("KELOMPOK 1 ROKUPANG")
print("PYANDI PRADIPTA SETIAWAN 19200126")
print("ADE RIZKY ANWAR 19200247")
print("SIDIK DWI NUGRAHA 19200061")
print("DHEA AYU PERTIWI 19200602")
print("HESTI ARIANINGTYAS 19200085")
print("======================================... |
class Point:
default_color = "red" # shared across all objects
def __init__(self, x, y): # Self is reference to current object
self.x = x
self.y = y
def draw(self):
print(f"Point ({self.x}, {self.y})")
Point.default_color = "white"
point = Point(1, 3)
print(point.default_color)... |
letters = ["a", "b", "c"]
# Add
letters.append("d") # Add at end
print(letters)
letters.insert(1, "bro") # Add at position (pos, elem)
print(letters)
# Remove
letters.pop() # Remove from last
print(letters)
letters.pop(1) # Remove from position (pos)
print(letters)
letters.remove("a") # Removed first occurance
p... |
course = "Python Programming"
# message = """
# Hemlo
# What's up?
# Bruh
# """
# String Functions
# len() -> return no of chars
print(len(course))
# [index] -> get character at index
print(course[5])
print(course[-1]) # return last character
# [start:end] -> slice string
print(course[2:12])
print(course[0:3])
prin... |
number = 100
while number > 0: # evaluating condition and repeating task
print(number)
number //= 5
|
# Find the highest occuring character
from pprint import pprint # Prettyprint
sentence = "This is a common interview question"
char_freq = {}
for char in sentence:
if char in char_freq:
char_freq[char] += 1
else:
char_freq[char] = 1
char_freq_sorted = sorted(char_freq.items(),
... |
# age should be between 18 and 65
age = 66
if 18 <= age <= 65:
print("Eligible")
else:
print("Not eligible")
|
class Animal:
def __init__(self):
print("animal const")
self.age = 1
def eat(self):
print("eat")
class Mammal(Animal):
def __init__(self):
super().__init__() # if it not used it will replace init
print("mammal const")
self.weight = 3
def eat(self):
... |
import datetime
import logging
import calendar
logging.getLogger(__name__).addHandler(logging.NullHandler())
logger = logging.getLogger()
class Schedule:
STATUS_OP = "operational"
def compute_overlap_period_day(self, lower, upper, mydate):
#logger.debug("compute overlap: lower: {} upper:{} and {} o... |
# This Program will find perfect cube of a number if it exist else will provide 'False'
# from unittest import TestCase
def perfect_root(number, root=2):
ans = 0
while ans ** root < abs(number):
ans += 1
if ans ** root == abs(number):
if number < 0:
return -1 * ans
e... |
# Codewars kata link: https://www.codewars.com/kata/53e57dada0cb0400ba000688
from collections import Counter
def list_position(word):
"""Return the anagram list position of the word"""
word_list = list(word)
sorted_list = list(sorted(word))
position = 0
while word_list:
dividendo = factor... |
from collections import defaultdict
import math
import networkx as nx
import matplotlib.pyplot as plt
from utils import trabalho
class Node:
def __init__(self, name):
self.Name = name
class Elo:
def __init__(self, parentNode: Node, childNode: Node, weight:float):
self.parentNode = parentNode
sel... |
from tkinter import *
clicked = 0
def Click():
global clicked
clicked += 1
root.title("Мой первый интерфейс на Python нажатий клавиш {0}".format(clicked))
root = Tk()
root.title("Мой первый интерфейс на Python нажатий клавиш {0}".format(clicked))
root.geometry("800x250")
btm = Button(text="Click Me",... |
animals = ["cat", "dog", "duck", "bear"]
def showAll():
print('animals:', end=' ')
for item in animals:
print(item, end=' ')
print("elment in animals = ", len(animals))
showAll()
animals.append("hamster")
showAll()
animals.sort()
showAll()
del animals[0]
showAll()
zoo = ('питон', 'слон', 'пингв... |
#!/usr/bin/env python
class Animal(object):
def __init__(self, name):
self.name = name
def can_eat(self, food):
pass
def eat(self, food):
pass
def speak(self):
pass
def die(self):
print self.name, "lived a good life."
def __str__(self):
ret... |
#!/usr/bin/env python
"""nims.py
A simple competitive game where players take stones from stone piles.
"""
#first block of code gets the number of stones in the pile, and makes it an integer, it also sets the player to "1"
total = raw_input("Number of stones in the pile: ")
total = int(total)
player = 1
print "Max n... |
#!/usr/bin/env python
from hwtools import *
print "Section 1: If Statements"
print "-----------------------------"
# 1. Is n even or odd?
n = raw_input("Enter a number: ")
n = int(n)
if n % 2 == 0 :#couldn't figure this out, Jonah helped to find the modulo command.
print "1.",n," is an even number."
print... |
#!/usr/bin/env python
"""
Selection sort
This is my selection sort, it's not working right!!!
I used this:
http://en.wikipedia.org/wiki/Selection_sort
"""
from hwtools import input_nums
nums = input_nums()
print "Before sort:"
print nums
N = len(nums)
for ipos in range(N):
imin = ipos
for i in range(ip... |
import inspect
# useful to print all params passed to a function
# And the function call stack
def foo(a, b, c, d):
print("Inside function " + inspect.stack()[0][3] + ". Input params are:"+ str(locals()))
print(locals()['b'])
my_var = "my_var_value"
# Basically locals() is a dict of all variabl... |
import parameters
from node import Node
def get_hamming_distance(node: Node) -> int: # peças fora do lugar
node_state = list(node.state)
expected_state = list(parameters.objective_state)
hamming_distance = 0
for position in range(len(expected_state)):
if not node_state[position] == expected... |
import parameters
from node import Node
# # # # #
# 0 1 2 #
# 3 4 5 #
# 6 7 8 #
# # # # #
def get_moves_for_orientation(piece_value: int, piece_location: int, orientation: dict):
current = False
expected = False
for index in orientation:
if piece_location in orientation[index]:
curren... |
import numpy as np
import scipy.signal as signal
from typing import List
from resistics.common.math import intdiv
def getSmoothingLength(dataSize: int, divisor: float = 16.0) -> int:
"""Get smoothing length given the number of samples in the data
Parameters
----------
dataSize : int
The numb... |
"""
These are measures of location and scale.
Location is the first moment of a probability distribution. Often this is taken to be the mean or median and sometimes mode depending on the context.
Scale is the second moment of a probability distribution and is a measure of the spread or dispersion. For Gaussian distrib... |
# Link: https://www.hackerrank.com/challenges/diagonal-difference/problem
def diagonalDifference(arr):
left_diag, right_diag, count = 0, 0, 0
for i in range(len(arr)):
left_diag += arr[i][count]
count += 1
count = len(arr) - 1
for i in range(len(arr)):
right_diag += arr[i][co... |
# Link: https://www.hackerrank.com/challenges/time-conversion/problem
def timeConversion(s):
hours = s.split(':')[0]
if 'PM' in s:
return s.replace("PM", "") if hours == '12' else (str(int(hours) + 12) + s[2:]).replace("PM", "")
else:
return (str(int(hours) - 12) + '0' + s[2:]).replace("AM"... |
#!/usr/bin/env Python
# coding=utf-8
"""
out_number = 3
total_number = 10
for i in range(total_number +1):
List[i] = raw_input("input name:")
index = 1
print(List)
while len(List) != 1:
temp = List.pop()
if index != out_number:
List.append(temp)
else:
index = 0
print(List)
index... |
array = [5,2,3,1,4,10, 9, 6, 7, 8]
def bubbleSort(arr):
Swapped = True
while Swapped:
Swapped = False
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
Swapped = True
return arr
def insertionSort(arr):
for... |
import socket as s
def create_client():
client_socket = s.socket()
addr = input('ipv4:')
port = int(input('port:'))
return addr, port
#client_socket.connect((addr, port))
# data = b''
# while b'\n' not in data:
# data += client_socket.recv(1024)
# print(data)
# client_socket.sendall(b'Hello Mr N... |
class queue:
def __init__(self, size =5):
self.__list = ['' for i in range(size)]
self.__front = -1
self.__rear = 0
self.__size = size
def getList(self):
return self.__list
def getFront(self):
return self.__front
def getRear(self):
return self.__r... |
import sqlite3
connection = sqlite3.connect('loans.db')
def create_table():
connection.execute('CREATE TABLE Borrower(ID INTEGER PRIMARY KEY, Name TEXT NOT NULL)')
connection.execute('CREATE TABLE Book(ID INTEGER PRIMARY KEY, Title TEXT NOT NULL)')
connection.execute('''CREATE TABLE Loan(ID INTEGER PRIMARY... |
class record:
def __init__(self, name, num):
self.__PersonName = name
self.__TelephoneNo= num
def getPersonName(self):
return self.__PersonName
def setPersonName(self, name):
self.__PersonName = name
def getTelephoneNo(self):
return self.__TelephoneNo
def se... |
class Node:
def __init__(self,data, pointer = -1):
self.__data = data
self.__Pointer = pointer
def getData(self):
return self.__data
def getPointer(self):
return self.__Pointer
def setData(self, data):
self.__data = data
def setPointer(self, pointer):
... |
import sqlite3
connection = sqlite3.connect('library.db')
#connection.execute('CREATE TABLE Book (ID INTEGER PRIMARY KEY, Title TEXT)')
def insertrandom():
for i in range(10):
connection.execute('INSERT INTO Book (ID, Title) VALUES(?, ?)',(str(i), f'EXAMPLE book {i}'))
connection.commit()
#connection... |
def person(name):
"""person(name): Returns the Person's name"""
print(name)
#another function
def maximum(*numbers):
"""maximim(numbers): returns the maximum number"""
if len(numbers) == 0:
return None
else:
maxnum = numbers[0]
for n in numbers[1:]:
i... |
a = int(input('Podaj liczbę a: '))
b = int(input('Podaj liczbę b: '))
if a > b:
print('a jest większe')
else:
print('b jest większe')
|
from datetime import datetime
from flask import Flask, request # zaimportowaliscmy flaska do naszej aplikacji
app = Flask(__name__) #zapisujemy do zmiennej ze bedziemy modulu uzywac wplikacji, ze modul (__name_ bedzie aplikacja flaska i zapisujemy do zmiennej app)
@app.route("/hello_world") # dekorujemy zmie... |
list_ = []
x = int(input('Podaj ilosc liczb : '))
for i in range(x):
number = float(input('podaj liczby: '))
list_.append(number)
sum_ = 0
for i in list_:
sum_ = sum_ + i
avarage = sum(list_)/x
if sum_ > avarage:
print('Suma:', sum_, 'średnia:', avarage, 'Suma jest większa!')
elif sum_ < ... |
"""
Created on 13/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python program to clear a set.
"""
#creating sample set
my_set={"apple", "banana", "cherry","potato","xyz"}
#clearing the set
my_set.clear()
#printing the cleared set
print(my_set) |
"""
Created on 14/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python program to reverse a tuple
"""
#initializing a tuple with different data types
my_tuple =(10,'sunny',22.3,True,1+3j,'h')
#converting tuple to list
my_tuple_list=list(my_tuple)
#reversing the list
my_tuple_list.reverse()
#again conve... |
"""
Created on 14/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python program to clone or copy a list
"""
#creating a list through user input
integer_list = [int(integer) for integer in input("enter integers").split(',')]
#making a copy if interger list
copy_of_integer_list=[]
for value in integer_list... |
"""
Created on 13/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python program to create a dictionary from a string.Track the count of the letters from the string
"""
#making sample string
sample_string = 'w3resource'
#initializing an empty dictionary
count_dictionary={}
#indexing through the string
for... |
"""
Created on 13/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python script to add a key to a dictionary
"""
#initializing a dictionary
my_dictionary={"key1":"value1","key5":"value5","key4":"value4","key3":"value3","key2":"value2"}
try:
#asking from user how many values they want to add
number... |
"""
Created on 13/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python script to sort (ascending and descending) a dictionary by value.
"""
try:
#initializing a dictionary
my_dict={"key1":23,"key2":233,"key3":123,"key4":423,"key5":1}
#returning a sorted list through sorted function
sort... |
"""
Created on 11/12/2019
@author: Sunny Raj
"""
"""
Problem Statement:
Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2.
"""
#creating color sets
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
# finding diff... |
"""
Created on 14/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python program to lowercase first n characters in a string
"""
#asking from user to enter a string
my_string = input("enter any string")
#asking from user the limit of first n characters
limit = int(input('Enter the number you want to lower... |
"""
Created on 12/12/2019
@author: Sunny Raj
"""
"""
Problem Statement:
Write a Python program to count the number occurrence of a specific character in a string
"""
#asking user to take input as main string
main_string =input("enter main string\n")
#asking for input for character you want to count
char = input("enter ... |
"""
Created on 13/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python program to remove the first occurrence of a specified element from an array
"""
# importing array module
import array
try:
#initializing the array
elements_array=array.array('i',[])
#detemining the size of array
si... |
"""
Created on 11/12/2019
@author: Sunny Raj
"""
"""
Problem Statement:
Write a Python program to create a histogram from a given list of integers.
"""
# importing matplot lib to make histograms
import matplotlib.pyplot as plt
# function to take input
def input_val():
limit = int(input("how many value... |
"""
Created on 12/12/2019
@author: Sunny Raj
"""
"""
Problem Statement:
Write a Python program to extract single key-value pair of a dictionary in variables
"""
#making a dictionary
d = {1:'Sunny',2:'Shubh',3:'Suresh',4:'Mari',5:'Rajinikant'}
#loop to print the value and key in the dictionary
for k,v in d.items():
... |
"""
Created on 13/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python program to create a set
"""
#creating a set
my_set=set({"apple", "banana", "cherry","potato","tomato"})
#printing the output
print(my_set) |
n = int(input('Digite um número inteiro:'))
base = int(input('Escolha uma das bases para conversão: \n'
'[1] converter ara BINÁRIO\n'
'[2] converter para OCTAL\n'
'[3] converter para HEXADECIMAL\n'
'sua opção:'))
if base == 1:
conversao = bin(n)
... |
preco = float(input('Qual é o preço do produto? R$'))
desconto = (preco-(preco*0.05))
print('O produto que custava R${:.2f}, na promoção com desconto de 5% custará {:.2f}'.format(preco, desconto))
|
from datetime import date
nascimento = int(input('Ano de nascimento:'))
ano_atual = date.today().year
idade = ano_atual - nascimento
ano_alistamento = nascimento + 18
sexo = input('Informe seu sexo: M para Masculino e F para feminino:').upper()
if sexo == 'M':
if idade < 0:
print('Você escolheu um ano fut... |
valor_casa = float(input('Informe o valor da casa: R$'))
salario = float(input('Informe o salário do comprador: R$'))
financiamento = int(input('Em quantos anos vai pagar:'))
prestacao = valor_casa/(financiamento*12)
print('Para pagar uma casa de R${:.2f} em {} anos a prestação será de R${:.2f} '.format(valor_casa, fi... |
print('-'*30)
print('LOJA SUPER BARATÃO')
print('-'*30)
total = maior1000 = preco = 0
nome_menor = ' '
while True:
continuar = ' '
nome = input('Nome do Produto:')
preco = float(input('Preço: R$'))
total += preco
if preco > 1000:
maior1000 += 1
if preco == total:
menor = preco
... |
#
# Try it! From day 3
# Remember, most exercises can be solved in multiple ways
#
# Lists, loops and indices
#
# Count from 1 to 10
for x in range(11):
print(x)
#################################
# Print dog names from list
dog_names = ['Kelvin', 'Ampere', 'Victor']
for name in dog_names:
print('If I get a ... |
s = "pizza"
r = " pizz a"
i = "lua,carol,marte,terra"
print (s) #Imprime o valor da variável s
print (s.find("iz")) #encontra a posição de uma string
print (s.replace("zz","nhão")) #Troca zz da palavra pizza por nhão
print (s.upper()) #Converte para maiuscula
print (s.lower()) #converte para minuscula
print (s.isalp... |
#!/usr/bin/python3
"""This module creates the island_perimeter function"""
def island_perimeter(grid):
"""Returns the perimeter of the island described in grid"""
sides = 0
for x, row in enumerate(grid):
for y, num in enumerate(row):
if num == 1:
if x == 0:
... |
#!/usr/bin/python3
""" This module creates a rain function """
def rain(walls):
""" Calculates how much rain water is retained """
total_rain = 0
for i in range(len(walls)):
index = walls[i]
if i > 0:
left_list = walls[0:i]
left_wall_height = max(left_list)
... |
"""
Crie uma função chamada collatz() que tenha um parâmetro de nome number. Se
number for par, collatz() deverá exibir number // 2 e retornar esse valor. Se
number for ímpar, collatz() deverá exibir e retornar 3 * number + 1.
Em seguida crie um programa em que o usuário passe um número qualquer e fique
chamando collat... |
"""
Crie uma função que aceite um valor de lista como argumento e retorne uma string
com todos os itens separados por uma vírgula e um espaço, com 'e' inserido
antes do último ítem.
"""
lista = []
while True:
print('Favor digitar algum ítem para a lista: ')
print('Caso queira encerrar a lista, basta clicar ... |
"""
Crie 10 pastas com o nome "pasta_n" e dentro de cada pasta crie 2 arquivos
'arquivo_x'. Exiba toda estrutura do diretório
"""
import os
import shutil
from pathlib import Path
# create folders
for x in range(1,11):
os.mkdir(f'pasta_{x}')
# create a list
l = [f for f in os.listdir('.') if f.startswith('pasta')... |
from random import choice
import sys
def open_and_read_file(file_path):
"""Takes file path as string; returns text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
# your code goes here
open_file = open(file_path).read()... |
def add(list_o_nums):
answer = 0
for num in list_o_nums:
answer += num
return answer
def subtract(list_o_nums):
answer = list_o_nums[0]
for num in list_o_nums[1:]:
answer -= num
return answer
def multiply(list_o_nums):
answer = 1
for num in list_o_nums:
answer... |
#!/usr/bin/env python
from brain_games.cli import welcome_user
from random import randint
def start_game(username):
counter = 0
print('Answer "yes" if the number is even, otherwise answer "no".')
while counter < 3:
random_number = randint(1, 100)
print('Question: ' + str(random_number))
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import statsmodels.formula.api as smf
wcat = pd.read_csv("C:\\Users\\Desktop\\Simple Linear Regression\\Salary_data.csv")
def norm_func(i):
x = (i-i.min()) / (i.max() - i.min())
return ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 13:01:03 2021
@author: RajatShukla
"""
def my_decorator(original_func):
def wrapper():
print("Inside a wrapper function Before")
original_func()
print("Execute inside a wrapper function After")
return wrapper
@my_decorato... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 11:39:38 2021
@author: RajatShukla
"""
subjects = ('python','java','node js')
print(subjects)
print('Enter your city:')
x= input()
print('\nYour City is: ',x)
|
### Karan Tibrewal, Williams College
### (c) 2016
### karan.tibrewal@williams.edu
## This class describes a Vehicle
class Vehicle:
def isRedCar(self): return self.carName == "**"
def getLocation(self): return None
def __init__(self): return None
## This class describes a Car
class Car(Vehicle):
# @param loc1 1s... |
#coding:utf-8
#这是一个online的算法
#leetcode53题,但是如何使用dc来解决这个问题呢?
def maxSubArray(l):
if not l:
return 0
curSum = maxSum = l[0]
for num in l[1:]:
curSum = max(num, curSum+num)
maxSum = max(curSum, maxSum)
return maxSum
from nose.tools import assert_equal
def test():
l = [-2,1,-3,4,-1,2,1,-5,4]
assert_equal(maxSu... |
#coding:utf-8
"""
we use a clever algorithm that combines the ideas of binarySearch and quicksort
to arrive at an O(n) solution
"""
def findKthLargest(nums, k):
return findKthSmallest(nums, len(nums)+1-k)
def findKthSmallest(nums, k):
if nums:
pos = partition(nums, 0, len(nums)-1)
if k > pos + 1:
return findK... |
"""
https://leetcode.com/problems/reverse-linked-list/
"""
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
if not head.next:
return head
pre = head
cur... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def search(self, root: TreeNode, distance:int) -> (int, dict):
if root == None:
ret... |
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
ind = 0
original = len(arr)
while ind < len(arr):
if arr[ind] == 0:
arr.insert(ind+1, 0)
ind = in... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def smallestFromLeaf(self, root):
"""
:type root: TreeNode
:rtype: str
"""
if roo... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def distributeCoins(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root... |
# Recursive
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def helper(self, root):
if root == None:
return
for i in root.children:
self.helper(i)
... |
class Node(object):
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
self.prev = None
self.freq = 1
class dQueue(object):
def __init__(self):
self.head = Node(0,0)
self.tail = Node(0,0)
self.size = 0
self.he... |
class Solution(object):
def helper(self, maze, start, di, diname, history, queue, destination):
curr = [start[0], start[1]]
currdis, currpath = start[2], start[3]
move = False
while 0 <= curr[0]+di[0] < len(maze) and 0 <= curr[1]+di[1] < len(maze[0]) and maze[curr[0]+di[0]][curr[1]+d... |
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rt... |
class Solution:
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
sortnums, ret, l = sorted(nums), 0, len(nums)
for i in range(l-2):
currcount = 0
left, right = i+1, l-1
whi... |
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
curr = num
if curr == 0: return False
while curr%2 == 0:
curr = curr/2
while curr%3 == 0:
curr = curr/3
while curr%5 == 0:
... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
# returns first node and last node, cannot be None
def helper(self, root):
if root.left != None:
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stac... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == Non... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def calSum(self, root):
if root == None: return 0
return root.val + self.calSum(root.left) + self.calSum(root.right)
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
def __init__(self, root: Optional[TreeNode]):
self.root = root
def find(self, target: int)... |
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
num1_set = list(set(nums1))
num2_set = list(set(nums2))
num3_set = list(set(nums3))
combined = num1_set + num2_set + num3_set
dic = defaultdict(int)
ans = []
... |
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
ind1, ind2 = float("-inf"), float("-inf")
ret = float("inf")
for i,w in enumerate(words):
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None or head.next ==None: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.