text stringlengths 37 1.41M |
|---|
# Dado um número inteiro n ≥ 0, calcular o fatorial de n (n!). Outra maneira
def main():
n = int(input("Digite o valor de n: "))
# inicia as variáveis
fat, i = 1, 2
while i <= n:
fat *= i
i += 1
# resultado
print("O valor de %d! eh =" %n, fat)
#-----------------------------... |
# Dado n > 0, inteiro e x real (float), calcular x + xˆ3/ 3 + xˆ5/ 5 + . . . + xˆ2n-1/ (2n-1)
def soma_serie_1():
#ler n inteiro > 0
n = int(input("Digite o valor de n > 0 inteiro: "))
#ler o x float
x = float(input("Digite o valor de x: "))
#inicia a soma
soma = 0
#variar k de 1 até n ... |
# Dados 3 números imprimi-los em ordem crescente.
# Considere ordem crescente quando for menor ou igual ao seguinte.
a = int(input("Digite o primeiro número: "))
b = int(input("Digite o segundo número: "))
c = int(input("Digite o terceiro número: "))
if a >= b >= c:
print(c, b, a)
elif a >= c >= b:
print(b, ... |
# Escreva a função VerificaLC(MAT, N, M) que verifica se a matriz MAT de N linhas por M colunas
# possui 2 linhas ou 2 colunas iguais, devolvendo True ou False.
MAT = [[1, 1, 3], [1, 2, 3], [1, 4, 3], [2, 1, 3]]
def VerificaLC(MAT, N, M):
for j in range(N):
for k in range(j + 1, N):
if compa... |
# Dado n ≥ 0, imprimir separadamente cada um dos dígitos de N na ordem direta
def main ():
#leia o número
n = int(input("Digite um número: "))
rev = 0
dir = 0
while n > 0:
digito = n % 10
rev = rev*10 + digito
n = n // 10
while rev > 0:
dig = rev % 10
... |
#Função mult_pol(a, b) que devolve lista contendo o produto dos polinômios a e b
a = [1,1,3,4]
b = [2,2]
def mult_pol(a,b):
res = [0]*(len(a)+len(b)-1) #cria o tamanho do polinomio resultante
for c1,i1 in enumerate(a): #o c1 serve como base pra saber o indice do X, o i1 é o elemento que vai ser multiplicado
... |
# Dados N > 0 verificar se N é palíndrome. Um número é palíndrome quando é o mesmo lido da direita
# para a esquerda ou da esquerda para a direita. Ou seja, o primeiro algarismo é igual ao último, o segundo igual
# ao penúltimo e assim por diante
def main ():
n = int(input("Digite um número para verificar se ele... |
lista = [1,2,3]
string = ''
for elemento in lista:
string = string + '//' + str(elemento)
print(string)
print(string.split('//')[1:]) |
#!/usr/bin/env python3
from pprint import pprint
import networkx as nx
import numpy as np
from utils import d, w, print_wd
from structures import MyTuple
def cp(g, return_delta=False):
"""
Compute the clock period of a synchronous circuit.
+------------------+------------------+
| Time complexity |... |
# -*- coding: utf-8 -*-
'''
Given an array nums and a value val, remove all instances of
that value in-place and return the new length.
Do not allocate extra space for another array, you must do this
by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter ... |
# -*- coding: utf-8 -*-
class Solution(object):
def is_valid_sudoku(self, board):
n = 9
used_column = [[False] * n for i in range(n)]
used_row = [[False] * n for i in range(n)]
used_block = [[False] * n for i in range(n)]
for i in range(n):
for j in range(n):
... |
# -*- coding: utf-8 -*-
class Solution(object):
def generate_parenthesis(self, n):
res = []
self.generate(n, n, '', res)
return res
def generate(self, left_num, right_num, s, res):
if left_num == 0 and right_num == 0:
res.append(s)
if left_num > 0:
... |
# -*- coding: utf-8 -*-
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def add_two_numbers(self, l1, l2):
extra = 0
head = ListNode(0)
p = head
while l1 or l2 or extra:
sum = (l1.val if l1 el... |
class Person:
def __init__(self, name, fist_name, second_name):
self.name = name
self._fist_lastname = fist_name
self.__second_lastname = second_name
def publicMethod(self):
self.__privateMethod()
def __privateMethod(self):
print(self.name)
print(self._fist_... |
class MyClass:
class_var = "class Variable"
def __init__(self):
self.instance_var = "Instance Var"
@staticmethod
def static_method():
print("Estatic Method!")
print(MyClass.class_var)
# Desde un metodo estatico no se puede acceder a una variable de instancia
@clas... |
print("Provides the following book's data: ")
name = input("Provides the name:")
id = int(input("Provides the ID:"))
price = float(input("Provides the price: "))
freeShipping = input("Indicates whether shipping is free(Yeah/Nop): ")
if freeShipping == "Yeah":
freeShipping = True
elif freeShipping == "Nop":
fre... |
from cuadrado import Square
from rectangulo import Rectangle
square = Square(2, "Black")
rectangle = Rectangle(4, 5, "Green")
print("Square", square)
print("Area square", square.area())
print("Rectangle", rectangle)
print("Area rectangle", rectangle.area())
#metodo para saber el orden de los metodos
print(Square.mro... |
# Uses python3
import sys
def get_fibo(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current
def get_fibonacci_huge_eff(n, m):
cycle = [0, 1]
if n < m:
return get_fibo(n)
... |
def main():
size = 6
names = ["Sally", "Tom","Sameer", "Rishika", "Fernando", "Camilio"]
searchValue = ""
index = 0
found = False
keepGoing = "y"
while keepGoing == "y":
print("Do you want to search the array?")
keepGoing = input("(Enter y for yes.)").lower()
if keepGoing == "y":
index,found = ... |
#
# @lc app=leetcode.cn id=234 lang=python3
#
# [234] 回文链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x... |
def read(command):
"""Gets the input value from the user"""
userInput = None
while userInput is None:
try:
userInput = input(command)
except IOError :
print("There was an error reading the value")
continue
except :
print("\nSomething happened. Exiting...")
exit()
return userInput
|
# ----------------------------------------------------------------------
# EXAMPLE: Fermi-Dirac function in Python.
#
# This simple example shows how to use Rappture within a simulator
# written in Python.
# ======================================================================
# AUTHOR: Michael McLennan, Purdue U... |
# 复合数据类型---集合等
# 1.元组
tup1 = ('a', 2)
print(tup1[0])
# tup1[1]=1 #TypeError: 'tuple' object does not support item assignment
# 2.集合
country = {'china', 'USA', 'Russia', 'France'}
print(country)
if ('Germany' in country):
print('Germany 在 country集合里')
else:
print('Germany 不在country集合里')
setA... |
import math
def paginacijaRezultata(rezultati, kljucevi): #prosledjuje se recnik(rezultati) i lista kljuceva istog recnika(kljucevi)
brPoStr = 5
broj_stranica = math.ceil(len(rezultati.keys()) / brPoStr)
#inicijalno se pokazuje prva strana pretrazenih rezultata
i = 0
for rez in rezultati.keys()... |
from graph import Graph
class GraphSearch(Graph):
def __init__(self):
super().__init__()
# 3(d) (3 points) (You must submit code for this question!) In a class called GraphSearch, implement ArrayList<Node> DFTRec(final Node start, final Node end), which recursively returns an ArrayList of the N... |
#Challenge 2 Write a version of the Guess My Number game using a GUI
from tkinter import *
import random
class Application(Frame):
def __init__ (self,master):
super(Application,self).__init__(master)
self.grid()
self.create_widgets()
self.random_number = random.randint(1,... |
# Write a Who's Your Daddy? program that lets the user enter the name of a male
# and produces the name of his father. Allow the user to add, replace, and
# delete son-father pairs.
father_son = {
"John Lennon": "Julian Lennon",
"Ken Griffey Sr.": "Ken Griffey Jr.",
"Bruce Matthews": "Clay Matthews",
"Jerry ... |
#Challenge 2 Create a War card game
import cards, games
class War_Card(cards.Card):
def __init__(self, rank, suit):
super(War_Card,self).__init__(rank,suit)
@property
def value_hand(self):
v = War_Card.RANKS.index(self.rank) + 1
if v == 1:
v == 14
... |
# Write a CharacterCreate Program for a role-playing game.
# The player should be given a pool of 30 points to spend on four attributes:
# Strength, Health, Wisdom, and Dexterity
# The player should be able to spend points from the pool on any attribute
# and should also be able to take points from an attribute and... |
#mahasiswa = ["Rayhan",2,"Teknik Informatika"]
#print(mahasiswa[0:2])
#nama = "rayhan whoo ouuu aaa eee"
#game = "Mobile Legend"
#print(game[8:11])
#angka = 6
#if angka == 5:
# print("Uhuy")
#else:
# print("Edan")
#hero = "layla"
#if hero is "Zilong":
# print(hero, "fighter Bos")
#elif hero is "layla":
#... |
def purge(operators, sequence):
seq = ''
for i, value in enumerate(zip([''] + operators, sequence)):
o, d = value
seq += o
if i != len(sequence) - 1 and d == '0' and o in '+-':
continue
seq += d
return seq
def generate(sequence):
l = len(sequence) - 1
sequence = [c for c in sequence]
... |
import math
############### Account Info Summary #####################
Account_List = ['0915' , '0896' , '7001' , '5076' , '9587' , '0562' , '9967' , '0584'] # Account members' numbers
BasicData = 15
BasicDataFee = 90
ExtraDataFee = input("What's the extra data usage fee(unit: $)?")
DataShare = range(len(Account_List)... |
def factorial(n):
if n > 1:
return n * factorial(n - 1)
else:
return 1
print('1!={:,}, 3!={:,}, 5!={:,}, 10!={:,}'.format(
factorial(1),
factorial(3),
factorial(5),
factorial(10),
))
def fibonacci_co():
current = 0
next = 1
while True:
current, next = ne... |
import os
import csv
import statistics
from transaction import Transaction
def main():
print_header()
filename = get_data_file()
transactions = load_file(filename)
query_data(transactions)
def print_header():
print('Real Estate Data Mining')
def get_data_file():
base_folder = os.path.dirna... |
#CALCULADORA nro6
# Esta calculadora realiza el calculo de la Distancia
# Declaracion de la variable
velocidad,tiempo=0.0,0.0
# Calculadora
velocidad=30
tiempo=15
distancia=velocidad*tiempo
#mostrar datos
print("velocidad = ", velocidad)
print("tiempo = ", tiempo)
print("distancia = ", distancia)
|
#CALCULADORA nro 12
# Esta calculadora realiza el calculo de la Velocidad Angular
# Declaracion de la variable
angulo,tiempo,velocidad_angular=0.0,0.0,0.0
# Calculadora
angulo=45
tiempo=14
velocidad_angular=angulo/tiempo
#mostrar datos
print("angulo = ", angulo)
print("tiempo = ", tiempo)
print("veloci... |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
# By examing the examples, e.g., [1, 2, 3, 4, 5] to [531, 42], and [2, 4, 5, 6, 8, ... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# define a function of polysum
def polysum (n,s):
# the variable is n and s
# n is the number of sides
# s is the length of each side
import math
#import math module, in order to apply the tan function and pi
area = 0.25*n*s**2/math... |
# Author: GerogeLiu
import random
# Find divisors
def find_divisors(n):
"""
Return a list of all integers that can divide n
param: n, integer
return: divisors, list
"""
divisors = []
for i in range(2, n):
if n % i == 0:
divisors.append(i)
return divisors
# Get the... |
import numpy as np
from collections import Iterable
def flatten(items):
""" Yield items from any nested iterable; see REF. """
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
yield from flatten(x)
else:
yield x
def cartesian(arrays, out=None):
""" Generate a cartesian pro... |
def verticalizing(str):
for letter in str:
print(letter)
name = str(input("Informe seu nome: ")).strip()
verticalizing(name)
|
class DecTree:
# The set of all attrs in the tree
# Is a set because all attrs in the tree should be unique
attrs = set()
def __init__(self, attr='?', values=[]):
# attr: string stating the attribute this node represents
if not isinstance(attr, str): raise TypeError("attribute argument... |
from random import randint
def bozosort (items):
while not sorted(items) == items:
switch(items)
return items
def switch(items):
num1 = randint(0, len(items) - 1)
num2 = randint(0, len(items) - 1)
items[num1], items[num2] = items[num2], items[num1]
return items |
def encrypt (key, plaintext):
return process(key, plaintext, 1)
def decrypt (key, ciphertext):
return process(key, ciphertext, -1)
def process(key, text, sign):
if key is "":
raise ValueError ("Cannot use empty key")
else:
uppercase_key = key.replace(' ', '').upper()
uppercase_text = text.replace(' ', '').u... |
def introductions():
print("Use -I am- statements please. ")
namequestion = raw_input("Tell me your name: ")
name = namequestion.replace("I am ", "")
print("Hello, " + name + "!")
agequestion = raw_input("Tell me your age: ")
age = namequestion.replace("I am ", "")
in
troductions() |
def loops():
word = raw_input("word")
letters = len(word)
for letters in word:
print word
def square(x):
runningtotal = 0
for counter in range(x):
runningtotal = runningtotal + x
return runningtotal
print runningtotal
loops()
square(2) |
def factorial(x):
total =1
while x>=1:
total *= x
x-=1
print (total)
return total
factorial(10)
|
# final=""
# inp = input("enter a number or exit:")
# while (inp != "exit"):
# final = final+inp+" "
# inp = input("enter a number or exit:")
# print(final)
from getpass import getpass
asdf = input("This is not secure: ")
pw = getpass("This is secure: ")
print("You typed: " + pw) |
#seconds= remander of the seconds input -_-
#minute=60 seconds
#hour=3600 seconds
s= int(input())
m=s/60
seconds=s%60
hour= m/60
hour=s/3600
print( str(int(hour)) + " hour " + str(int(m)) + " minute " + str(int(seconds)) + " seconds ")
|
import os
import random
from _chromosome import Chromosome
from _expression import Expression
def Selection(population):
#DISPLAY ALL OF THE POPULATION
#SELECT TWO FROM POPULATION FOR CROSSOVER
#RETURN A NEW LIST OF CHROMOSOME
p1 = population[0] # 1ST MOST FIT
random_parent = random.randint(1, le... |
from random import randint
quiz = randint(1, 100)
print("Saya menyimpan angka bulat antara 1 sampai 100. coba tebak")
jawab = 0
count = 1
while jawab != quiz:
jawab = input('Masukkan tebakan ke-{}:>'.format(count))
jawab = int(jawab)
if jawab == quiz:
print('Ya. Anda benar')
elif... |
from random import randint
def log2n(n):
return 1 + log2n(n/2) if (n > 1) else 0
def quiz(angka):
quiz = randint(1, angka)
jawab = 0
count = 1
maks = log2n(angka)
print('Saya menyimpan angka bulat antara 1 sampai {}. anda punya {}x kesempatan. coba tebak'.format(angka, maks))
... |
def breadth_first_search_tuples(problem):
"""[Figure 3.11]"""
node = Node(problem.initial)
if problem.goal_test(node.state):
return node
frontier = FIFOQueue()
frontier.append(node)
explored = set()
while frontier:
node = frontier.pop()
explored.add(tuple(node.state))... |
# Py_Ch_10_1.py
# Authors: Sam Coon and Tyler Kapusniak
# Date: 3/4/15
from tkinter import *
class Application(Frame):
""" GUI application that creates a story based on user input. """
def __init__(self, master):
""" Initialize Frame. """
super(Application, self).__init__(master)
... |
## QUESTÃO 6 ##
# Escreva um programa que calcule a porcentagem de nucleotídeos A, C, G e T em
# uma cadeia de DNA informada pelo usuário. Indicar também a quantidade e a
# porcentagem de nucleotídeos inválidos.
##
##
# A sua resposta da questão deve ser desenvolvida dentro da função main()!!!
# Deve-se subst... |
import math
def scical(a, op):
if (op == 'sin'):
print("sin({x}) = {y:1.2f}".format(x=a , y=math.sin(math.radians(a))))
elif (op == 'log'):
print("log({x}) = {y:1.2f}".format(x=a , y=math.log10(a)))
elif (op == 'sqrt'):
print("sqrt({x}) = {y:1.3f}".format(x=a , y=math.sqrt(a))... |
from string import ascii_uppercase as A
"""
KSum implementaiont and Kadane's Algorithm for max subarray.
KSum remarks: Translation from
https://www.sigmainfy.com/blog/k-sum-problem-analysis-recursive-implementation-lower-bound.html
"""
def firstDuplicate(a):
"""
:type a: list[int]
:rtype n: char
"""
index = ... |
import argparse
import os
from pathlib import Path
import shutil
parser = argparse.ArgumentParser(description='Find files in the src, and add them to the dst but inside a folder')
parser.add_argument('--src', help="The location to search for files", required=True)
parser.add_argument('--dst', help="The location to cre... |
# 哈夫曼算法
from heapq import heapify, heappush, heappop
from itertools import count
def huffman(seq, frq):
num = count()
print(num)
trees = list(zip(frq, num, seq))
print(trees)
heapify(trees)
while len(trees) > 1:
fa, _, a = heappop(trees)
fb, _, b = heappop(trees)
n = ... |
def bubble_sort(array):
for i in range(len(array))[::-1]:
for j in range(i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
print(array)
# return array
if __name__ == '__main__':
array = [1, 2, 3, 6, 5, 4]
bubble_sort(array)
|
'''
All the functions linked to the prediction behaviour of the robot
'''
import algebra as alg
from math import sqrt,cos,sin,acos,pi,atan2
import numpy as np
deltaT = 0.4 #s
def predictionNextPosition(linearSpeed,position):
'''
Return the predicted next position of the robot
Considering... |
# -*- coding: utf-8 -*-
# Filename : matrix.py
# Author : Hao Limin
# Date : 2020-03-15
# Email : haolimin01@sjtu.edu.cn
# Python : 3.7.5
"""
Define Matrix and Vector structure.
Gnd(number = 0) must be at the first row and first column,
Matrix and Vector's size is (n) x (n), (n) x 1.
Matrix is not sparse m... |
#!/usr/bin/python
import turtle
import math
from collections import deque
def main_triangle():
t.begin_fill()
for i in range(1,4):
if i == 1 :
todo.append(t.position())
if i == 2 :
todo.append(t.position()-(side/2,0))
if i == 3 :
#print t.position()
#print math.sqrt((s... |
''' Python in its language defines an inbuilt module “keyword” which handles certain operations related to keywords.
A function “iskeyword()” checks if a string is keyword or not. '''
import keyword # Importing Keyword for Keyword operations
# Initializing Strings For testing
s = "for"
s1 = "geeksforgeeks"
s2 = "eli... |
#coding=utf-8
import en
otherwordlist = []
def simplify_word(a):
try:#测试是否为动词,如果是则返回
en.is_verb(en.verb.present(a))
return en.verb.present(a)
except:#否则继续检查
pass
#测试是否是名词
if en.is_noun(en.noun.singular(a)):
return en.noun.singular(a)
#如果已经可以判断是名词,动词,形容... |
import random
import matplotlib.pyplot as plt
from matplotlib import rc
from math import sin, pi
def main():
# gx #
def g(x):
return sin(x*pi)
# end:gx #
# problem_1 #
r = 0.1
for x_0 in (random.random() for i in range(10)):
plt.plot(list(logistic_generator(g, r, x_0, 11)), '.... |
#!/usr/bin/python
import textwrap
def find_spaces(string_to_check):
"""Returns a list of string indexes for each string this finds.
Args:
string_to_check; string: The string to scan.
Returns:
A list of string indexes.
"""
spaces = list()
for index, character in enumerate(string_to_check):
... |
class Person():
def __init__(self,name,age,address,sal):
self.name = name
self.age = age
self.address = address
self.sal = sal
self.company = 'TCS'
self.branch = 'Noida'
def showDetails(self):
print("Parent Class Call")
print("Welcome t... |
'''
num = int(input("Enter a number : "))
flag = True
for i in range(2,num):
if num % i == 0:
# print("Not Prime")
flag = True
break
else:
# print("Prime Number")
flag = False
if flag:
print("Not Prime")
else:
print("Prime")
'''
num = int(input... |
import threading
def job_1():
print("Job_1 Started")
for i in range(100000):
for j in range(10000):
k = i + j
print("Completed {} iterations".format(k))
print("Job_1 Completed")
def job_2():
print("Job_2 Started")
for i in range(1000):
for j in range(10... |
#! /usr/bin/python
x = ['a', 'b', 'c']
for i in range(len(x)):
print(f'x[{i}]={x[i]}')
for i, name in enumerate(x, 1):
print(f'{i}th element = {name}')
for i in x:
print(i) |
#! /usr/bin/python
# Functions to implement
# __len__, is_empty, is_full, push, pop,
# peek, clear, find, count, __contains__, dump
# Expection handling (Empty, Full)
from typing import Any
class FixedStack:
class Empty(Exception):
pass
class Full(Exception):
pass
def __init__(self, ... |
##########################################################
# Homework 1 Leap Year Code
# CS 362
# Virginia Link
# 01/14/2021
##########################################################
print("Please enter a year to check: ")
#Get user input
year = int(input())
#1. Check if evenly divisible by 4
if (year % 4):
#2.... |
balance = 2222
annualInterestrate = 1.2
monthlyInterestrate = annualInterestrate/12.0
monthlyBalance = balance/12+monthlyInterestrate
while balance > 0:
return monthlyBalance ('Month: ' + str(month))
month += 1
print ('Minimum monthly payment: ' + str(monthlyPayment))
monthlyPayment = updatedBalance*m... |
from tkinter import *
from tkinter import messagebox
from PIL import ImageTk,Image
root = Tk()
root.title("Message Boxes")
root.iconbitmap("images/6/catICO.ico")
# showinfo, showerror, showwarning, askquestion, askokcancel, askyesno,
def popup():
response = messagebox.askyesno("This is the heading", "... |
# you can write to stdout for debugging purposes, e.g.
# print "this is a debug message"
def solution(X, A):
river = {}
i = 0
while len(river) < X and i<len(A):
if A[i] in river:
pass
else:
river[A[i]] = True
i += 1
if len(river)==X:
return i
... |
def solution(S):
# write your code in Python 2.7
map={'}':'{',']':'[',')':'('}
stack=[]
for item in S:
if item in '[({':
stack.append(item)
elif len(stack)>=1 and stack[-1]==map[item]:
stack.pop()
else:
return 0
if len(stack)==0:
r... |
#!/usr/bin/python3
import numpy as np
dataset=[11,10,12,14,15,13,15,102,12,14,107,10,10,13,12,14,108,12,11,12,15,15,11,10,12,14,15,13,15,14,12,13,20,12,25]
# Formula z= (Observations - Mean)/Standard Deviation
outliers=[]
def detect_outliers(data):
threshold = 3 #Within 3rd SD it is not an outlier
me... |
import unittest
from unittests_testing.calc_ import Calc
class TestRoot(unittest.TestCase):
"""
Testing square root of any number in calculator
"""
def setUp(self) -> None:
print('setUp')
def test_Sqrt_DataInputs(self):
print('test_Sqrt_DataInputs')
self.assertIsInstance(C... |
from utils import *
import sys
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
class Ex1Multi:
def __init__(self):
self.data = None # DataFrame from original data
self.X = None # X matrix
self.y = None # y vector
self.m = None # Number of training exampl... |
"""
Define to_alternating_case(char*) such that each lowercase letter becomes uppercase and each
uppercase letter becomes lowercase.
https://www.codewars.com/kata/alternating-case-%3C-equals-%3E-alternating-case/train/python
"""
def to_alternating_case(s):
alt = ''
for c in s:
if c == c.lower():
... |
def func_or(a, b):
if get_val(a, b) > 0:
return True
return False
def func_xor(a, b):
if get_val(a, b) == 1:
return True
return False
def get_val(a, b):
return check_let(a) + check_let(b)
def check_let(x):
if type(x) == int and x != 0:
return 1
if x:
ret... |
def replace_exclamation(s):
vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
for vowel in vowels:
s = s.replace(vowel, "!")
return s
|
def evil(n):
bins = find_bin(n)
if sum(bins) % 2 == 0:
return "It's Evil!"
else:
return "It's Odious!"
def find_bin(n):
bins = []
while n >= 1:
rem = n % 2
n = n // 2
bins.append(rem)
return bins
|
def permutations(s):
# only one permutation of single char string
if len(s) <= 1:
return [s]
perms = []
# get pivot char
for i, c in enumerate(s):
perms.append([c])
# get remaining chars
remains = []
for j, x in enumerate(s):
if i != j:
... |
class Matrix(object):
def __init__(self, arr):
self.arr = arr
self.shape = (len(arr), len(arr[0]))
def __add__(self, other):
if self.shape != other.shape:
return "Matrices must have same shape."
new_mat = []
for i, row in enumerate(self.arr):
tmp... |
from math import log
def count_trailing_zeros(num):
zeros = 0
for n in xrange(0, num + 1, 5):
if n == 0:
continue
for m in xrange(1, int(log(n, 5) + 1)):
if n % (5 ** m) == 0:
zeros += 1
return zeros
|
from datetime import date
def days_until_christmas(day):
year = day.year
if day >= date(year, 12, 26):
year += 1
return (date(year, 12, 25) - day).days
|
def string_chunk(string, *args):
if len(args) == 0 or args[0] <= 0 or type(args[0]) != int:
return []
return [string[x:x + args[0]] for x in xrange(0, len(string), args[0])]
|
import pandas as pd
import numpy as np
## Cleaning Economical Dataframe
#The Index of economic freedom dataset comes in 5 years [ 2013,2014,2015,2016,2017 ]. The structure of the dataset in 2017 is different from the structure of those in the previous years.
#The function below matches all the years' structures and th... |
print("Your top ten spirit animals are: ")
import random
adjectives = ["adventurous",
"excited",
"crazy",
"boudless",
"brave",
"cheerful",
"dynamic",
"fun",
"energetic",
"amused"]
colors = ["red",
"orange",
"yellow",
"green",
"blue",
"purple",
"pink",
... |
#
# @lc app=leetcode id=101 lang=python3
#
# [101] Symmetric Tree
#
# @lc code=start
# 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 dfs(self, l: TreeN... |
#
# @lc app=leetcode id=110 lang=python3
#
# [110] Balanced Binary Tree
#
# @lc code=start
# 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 dfs(self, no... |
#
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
# @lc code=start
class Solution:
def longestPalindrome(self, s: str) -> str:
"""Strategy 1: Dynamic Programming
Args:
s (str): The length of the string
Returns:
str: the longest palindro... |
#
# @lc app=leetcode id=1299 lang=python3
#
# [1299] Replace Elements with Greatest Element on Right Side
#
# @lc code=start
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
""" Strategey 1: One pass
Runtime: O(n), where n is the size of arr
Space:O(1)
Args:
... |
#
# @lc app=leetcode id=144 lang=python3
#
# [144] Binary Tree Preorder Traversal
#
# @lc code=start
# 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
from typing import List
... |
#
# @lc app=leetcode id=55 lang=python3
#
# [55] Jump Game
#
from typing import List
# @lc code=start
class Solution:
# def canJump(self, nums: List[int]) -> bool:
# """ Strategey 1: Backward + DP/Greedy
# Runtime: O(n), where n is # of integers in nums
# Space:(1)
# Args:
#... |
#
# @lc app=leetcode id=23 lang=python3
#
# [23] Merge k Sorted Lists
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import heapq
from typing import List
class Solution:
import heapq
Lis... |
#
# @lc app=leetcode id=897 lang=python3
#
# [897] Increasing Order Search Tree
#
# @lc code=start
# 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 incr... |
#
# @lc app=leetcode id=49 lang=python3
#
# [49] Group Anagrams
#
# @lc code=start
from collections import defaultdict
class Solution:
from collections import defaultdict
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""Strategy 1: Hash + Array
Runtime: O(n K), where n is the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.