text stringlengths 37 1.41M |
|---|
#!/usr/bin/python3
def is_power(a, b):
if a == b:
return True
if b <= 0 or a < b:
return False
return is_power(a/b, b)
print is_power(1000, 10)
print is_power(1024, 2)
print is_power(1023, 2)
|
#!/usr/bin/python3
def middle(t):
return t[1:len(t)-1]
t = ['a', 'b', 'c', 'd']
t1 = middle(t)
print (t)
print (t1)
|
#!/usr/bin/python3
def uses_only(word, string):
for x in word:
if string.find(x) < 0:
return False
return True
pattern = raw_input('Pls input letters pattern:')
fin = open('words.txt')
for line in fin:
word = line.strip()
if uses_only(word, pattern):
print word
|
#!/usr/bin/python3
import turtle
def polygon(t, length, n):
for i in range(n):
t.fd(length)
t.rt(360/n)
bob = turtle.Turtle()
polygon(bob, 80, 16)
turtle.mainloop()
|
#!/usr/bin/python3
import turtle
import math
def polygon(t, length, n):
for i in range(int(n)):
t.fd(length)
t.rt(360/n)
def circle(t, r):
c = 2 * math.pi * r
length = 3
n = c / length;
polygon(t, length, n)
bob = turtle.Turtle()
#bob.delay = 0.01
circle(bob, 100)
tu... |
#!/usr/bin/python3
import turtle
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
bob = turtle.Turtle()
square(bob, 300)
turtle.mainloop()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import matplotlib.pyplot as plt
def isStable(bPrivilege):
#print(bPrivilege)
counter = 0
for i in range(len(bPrivilege)):
if(bPrivilege[i]): counter += 1
if counter > 1:
return False
else:
return True
def dijks... |
#!/usr/bin/env python
# encoding: utf-8
import unittest
class Bowling:
def __init__(self):
self._score = 0
def score(self, rolls):
strike = lambda x: x is 'X'
spare = lambda x: x is '/'
miss = lambda x: x is '-'
def get_score(throw):
throw_ = rolls[throw]... |
from sklearn import datasets
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import numpy as np
def sigmoid(z):
'''
Compute the sigmoid of z
Arguments: z -- a scalar or numpy array of any size.
Return:
s -- sigmoid(z)
'''
s = 1. / (np.exp(-1 * z) + 1)
... |
import unittest
from ToSidewalk.nodes import *
from ToSidewalk.latlng import *
from ToSidewalk.ways import *
from ToSidewalk.network import *
class TestNodeMethods(unittest.TestCase):
def test_constructor(self):
"""
Test the constructor
"""
node = Node(None, 0, 0)
self.asser... |
#!/usr/bin/env python3
import argparse
import mcb185
import random
# In prokaryotic genomes, genes are often predicted based on length
# Long ORFs are not expected to occur by chance
# Write a program that creates a histogram of ORF lengths in random DNA
# Your library should contain new functions for the following
#... |
#!/usr/bin/env python3
# You are probably well aware of the 'birthday paradox'
# https://en.wikipedia.org/wiki/Birthday_problem
# Let's try simulating it
# You will need a list for the 365 day calendar
# You will need a set number of people (e.g. 25)
# During each 'trial' you do the following
# Choose a person
# Git ... |
from math import sqrt
class TanimotoCoefficient:
def similarity(self, s, t):
if not s and not t:
return 1.0
if not s or not t:
return 0.0
s_set = set(s)
t_set = set(t)
intersection = s_set.intersection(t_se... |
#!/usr/bin/env python3
"""
Practice file for collections
"""
from collections import Counter, namedtuple, defaultdict, deque
import random
import csv
from urllib.request import urlretrieve
# named tuples example
User = namedtuple('User', 'name role')
user1 = User(name='bob', role='coder')
print(f'{user1.name} is a {us... |
import random
print("****************Welcome to the game*****************")
n = int(input("Enter how many times you want to play:"))
print("You want to play", n, "times:")
player_score = 0
computer_score = 0
while n > 0:
comp_choice = random.choice(["s", "w", "g"])
your_choice = input("Enter your choice (Sna... |
"""Generate Markov text from text files."""
import random
import sys
def open_and_read_file(file_path):
"""Take file path as string; return 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.
"""
file = open(file_path).read()
... |
# -*- coding: cp1252 -*-
"""Enrique Ibáñez Orero - 1º DAW - Practica 5 - Ejercicio 4 - Pràctica 5. Exercicis per resoldre amb bucle for."""
numero1=int(input("Escribe un numero: "))
numero2=0
while numero2 <= numero1:
numero2=int(input("Escribe un numero mayor que %d: " %numero1))
if numero2 <= numero... |
#var has no declared type, no ending ;
message = "Hello world!"
print(message)
#multiple assignment
mul, ti, assign = 1, 2, 3
print(mul) #1
print(assign) #3
#division and multi-operand type always returns float
math = 9 / 9
print(math) #1.0
math = 9 + 3.0
print(math) #12.0
#can force return int with d... |
"""
5. WAP which takes two arguments as input. Perform division of two numbers. Handle the error/exception if divider is 0.
"""
try:
a = int(input("Enter 1st number :"))
b = int (input("Enter 2nd number :"))
print(a//b)
except:
print("Cannot divide with zero") |
"""
9. Try with multiple except: WAP which will take two integer numbers as input and perform division of them.
- User of this program is not smart and can input anything as part of input
- Handle ArithmaticError, ZeroDivisionError and ValueError
- Print exception information
"""
try:
a=int(input())
... |
"""
7. Write short note on below
- Operator overloading
- Method overloading
- COnstructor overloading
"""
"""
Operator Overloading means giving extended meaning beyond their predefined
operational meaning. For example operator + is used to add two integers as
well as join two strings and merge two lis... |
"""
6. What will be the output for below code
try:
print(a/b) // Stmt 1
print(a/c) // Stmt 2
print(a/d) // Stmt 3
except ZeroDivisionError:
print("DIvider is zero")
- What will happen if program breats at Stmt 1
- What will happen if program breats at Stmt 2
- What will happen if program breats a... |
"""
2. Write note on Exceptions
"""
"""
Exceptions: Exceptions are raised when the program is syntactically correct
but the code resulted in an error. This error does not stop the execution of
the program, however, it changes the normal flow of the program.
Example:
# initialize the amount variable
... |
# https://towardsdatascience.com/how-to-use-datasets-and-dataloader-in-pytorch-for-custom-text-data-270eed7f7c00
# Import libraries
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
# create custom dataset class
class CustomTextDataset(Dataset):
def __init__(self, text, labels):
... |
# https://stackoverflow.com/questions/45471152/how-to-create-a-sudoku-puzzle-in-python
base = 4
side = base * base
# pattern for a baseline valid solution
def pattern(r, c):
return (base * (r % base) + r // base + c) % side
# randomize rows, columns and numbers (of valid base pattern)
from random import sample
... |
import operator
import random
# interpreter
class Env(dict):
def __init__(self, outer, params, args):
self.outer = outer
self.update(zip(params, args))
def get(self, k):
env = self
while env:
if k in env:
return env[k]
env = env.outer
... |
def sort_non_negetive(array: list):
non_neg_array = [x for x in array if x >= 0]
non_neg_array.sort()
indexer = 0
for i in range(len(array)):
if array[i] >= 0:
array[i] = non_neg_array[indexer]
indexer += 1
return array
if __name__ == "__main__":
print(sort_non_n... |
def detect_cycle(node, g, visit_array, recur_stack):
visit_array[node] = True
recur_stack[node] = True
if node in g:
for v in g[node]:
if visit_array[v]:
return True
else:
visit_array[v] = True
if detect_cycle(v, g, visit_array... |
from os import system
system('cls')
print('Bienvenido a la zona wifi')
#usuario_guardado = '51743'
#pass_guardado = usuario_guardado[::-1]
user = input('Digite su número de grupo ')
try:
int(user)
if len(user) != 5:
print('Error el dato ingresado debe ser de 5 caracteres')
else:
password = i... |
sesion = True
opciones = {1:'Valor a',2:'Valor b', 3:'Valor c', 4:'Valor 4', 5:'Valor 5', 6:'Valor 6', 7:'Valor 7'}
while sesion:
print('Digita el numero de la opción')
for key, opcion in opciones.items():
print(f'{key} {opcion}')
option = input()
if option == '6':
result = input('Cuant... |
numeros = [54, 58+5, 45, 12, 57, 84, 64, 25]
for numero in numeros:
if numero > 50:
print(numero)
for numero in numeros:
if numero % 2 == 0:
print(numero)
else:
print('_')
|
#!/usr/bin/env python
#Author: @nix1947
#Description: Coursera Implementation of PONG Game
#Run this game in code skulptor
# Implementation of classic arcade game Pong
#http://www.codeskulptor.org/#user40_PAGxslkE5y3AL3Z.py
# Implementation of classic arcade game Pong
# Implementation of classic arcade game Pong
impo... |
"""
Solution to the 538 Riddler July.27.2018
Author: Luca Ostertag-Hill
To run the algorithm use "puzzleSolver(5, 5)".
"""
class DoodlePuzzle:
"""This is a class for solving the 538 DoodlePuzzle Riddle.
Attributes:
numRows (int): The number of rows in the board.
numCols (int): The numbe... |
'''
Created on 06-Jan-2019
@author: vsrir
'''
import string
from _sre import ascii_tolower
def checkalph(stringval):
varset = ""
#list will convert set to list
#set will take unique values in map
#map has a lambda to convert all characters to lower case
#the list passed to the map is a ... |
'''
Created on 25-Dec-2018
@author: vsrir
'''
def six2nineskip(*args):
add = True
total = 0
for num in args:
if num == 6:
add = False
continue
elif num == 9:
add = True
continue
elif add:
total = total + n... |
# Variables
"""
a = 3 # es un entero
a = "manzana" # es un string
a = 1.23 # es un numero flotante
"""
from tkinter import *
Label(text="Hola").pack()
mainloop() |
# Ejercico 1
# Cree una lista de frutas de 7 elementos, y realice un programa que muestre el tercer
# elemento de la lista en pantalla
frutas=['naranjas','bananas','manzanas','peras','frutillas','melon','uvas']
print("El tercer elemento de la lista frutas es: "+frutas[2]) |
"""
Ejercicio 2
Escribir un programa que permita ingresar un numero y calcule el factorial
"""
from tkinter import *
nro = int(input("Ingrese Nro a calcular Factorial:"))
factorial = 1
if (nro == 0):
factorial = 1
else:
for i in range(1, nro+1):
factorial = factorial*i
Label(text=f"El factorial de... |
# my_file = open("read_my_contents.txt", "r")
# contents = my_file.readlines()
# print(contents)
# for line in contents:
# print(line, end='')
#
import io
my_file = open("names.txt", 'w')
for i in range(1):
current_name = input('enter your name: ')
my_file.write(current_name + '\n')
my_file.close()
try:
... |
print('hello world')
a = 'Hello world'
b = 3
c = True
d = ['lena', 21, True] # list
e = ('moshe', 23, False) # tuple - immutable
f = {'name': 'lena', 'age': 23, 'isMarried': True, 'hobbies': ['a', 'b']} # dictionary
# string escape chars: / = ignore the 'special' char, /t tab /n new line /r reverse
print(f.values())... |
import os
class Node(object):
data=0.0
Next=None
def __init__(self,data):
self.data=data
self.next=None
def printNode(self):
print self.data
class LinkedList(object):
'''This class provides insertion in linkedlist'''
head=None
def insert... |
n1 = 0
for x in range (0, 101):
n1 += x
n1 = n1 * n1
n2 = 0
for x in range (0, 101):
print (x)
n2 = n2 + x * x
print (n1 - n2)
|
#Question2
Lista = ["Brasil", "EUA", "Holanda", "França"]
#Question3
print(Lista)
#Question4
for item in Lista:
print(item)
#question5
for item in Lista:
print(item + item)
#Question6
for item in Lista:
print(item.upper())
#Question7
#Question8
#Question9
#Question10
#Ques... |
def pairs(iterable):
it = iter(iterable)
try:
for _ in iterable:
yield (next(it), next(it))
except StopIteration:
return
def main():
print(*pairs(['a', 'b', 'c', 'd']))
main()
|
num = float(input())
num += 0.5
num //= 1
print(int(num)) |
import time
import math
import sys
T1 = time.time()
notprimes = set()
for i in range(1000):
if(i % 3 == 0 or i % 5 == 0):
notprimes.add(i)
print(sum(notprimes))
T2 = time.time()
time = str(T2 - T1)
print(time) |
import time
import math
import sys
def triangle(n):
return (n*(n+1)/2)
def pentagon(n):
return n*(3*n-1)/2
def hexagon(n):
return n*(2*n-1)
t = 285
p = 165
h = 143
for t in range(286,1000000):
tr = triangle(t)
while(tr > pentagon(p)):
p +=1
while(tr > hexagon(h)):
h += 1
if... |
from math import *
import numpy as np
from numpy.linalg import norm
half_pi = pi / 2
class Arm():
def __init__(self, r1, r2):
"""
:param r1: Length of the first segment
:param r2: Length of the second segment
:param r3: Length of the third segment
:param opt: The op... |
from cipher_check_16 import cipher_check_16
def card_number_validator(card_number):
card_number_list = cipher_check_16(int(card_number))
odd_index = []
even_index = []
for o in range(0,8):
odd_index.append(o * 2)
for e in range(0,8):
even_index.append(e * 2 + 1)
odd_number = [... |
#!usr/bin/python
#Asking the user to enter the number of rows for star pattern print
no_of_rows = int(raw_input("\nEnter the number of rows for the star pattern\n"))
row_count = 1
max_star_count = 1
#To calculate the maximum number of stars that will appear in the last row
i = row_count
while(i <= no_of_r... |
#simulation of the Three Doors Problem
#n = the number of times the game should be simulated
#s = a boolean, if set to True, the player switches doors, if set to False the player sticks to the first picked door
import random
import matplotlib.pyplot as plt
def threeDoors(n, s):
l = ['door A', 'door B', 'door C']... |
"""
for 반복문을 이용하면 리스트와 같은 여러 값을 담는 자료형이나 함수에 대해 코드를 반복실행할 수 있음.
continue : 다음 차례로 건너 뜀 실행
"""
arr = [1, 2, 3, 4, 5]
# 숫자 3은 출력 제외
for n in arr:
if n == 3:
continue
print(n)
|
# 정수 (Integer Number)
int1 = 12
int2 = -12
print("int1 = {}, int2 = {}\n".format(int1, int2))
# 실수 (Floating Number)
float1 = 3.14
float2 = 2.718
print("float1 = {}, float2 = {}\n".format(float1, float2))
# 연산
"""
+: 덧셈
-: 뺄셈
*: 곱셈
/: 나눗셈
//: 몫
%: 나머지
**: 거듭제곱
"""
#############################################
#... |
#Binary Converter - from anythink to binary
#Denary to binary conversion
st = input("Input what do you want to convert in binary:")
# while denary>0:
print("Your phrase translated to binary will be:")
for letter in st:
#A left shift in binary means /2
print(format(ord(letter), 'b'), end = ' ')
print()
#B... |
"""
lab2.py
Refractoring lab2.py
Pritha Dutta
01/30/2018
"""
def squared(num_list):
"""
square numbers in num_list
num_list:list of numbers
Returns:list of these numbers squared
"""
new_list=[]
for num in num_list:
new_list.append(pow(num,2))
return new_list
def check_title(t... |
import tkinter
from tkinter import *
from tkinter import messagebox
import random
from tkinter.font import Font
root = Tk()
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
Calpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', '... |
def checkio(words):
l = words.lower().split(' ')
count = 0
flag = True
print(l)
for i in l:
print(i)
if i.islower() == True:
count += 1
elif count >=3:
break
else:
count = 0
print(count)
if count >= 3:
pass
else... |
from datetime import date, timedelta
def days_diff(date1, date2):
#通过date函数将日期转化
f = date(date1[0],date1[1],date1[2])
#s = date(date2[0],date2[1],date2[2])
s = date(*date2)
a = abs((f-s).days)
return a
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessa... |
def most_frequent(data):
num = 0
d ={}
for i in data:
num = data.count(i)
a = i
d[i] = num
return sorted(d.items(),key=lambda x: x[1],reverse=True)[0][0]
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
# assert ... |
# fibonacci.py
# This code is used to demonstrate substitution trace in a more complicated
# example. It is good practice for understanding recursion, but it is not
# an ideal solution for computing Fibonacci numbers.
def fibo( n ):
""" Compute a number in the Fibonacci series.
:param n: the ordinal value... |
import tensorflow as tf
import numpy as np
# Create Numpy variables
x1 = np.linspace(-1,1,101)
y1 = 2*x1 + np.random.randn(*x1.shape) * 0.33
#Create TensorFlow variables
X = tf.placeholder("float")
Y = tf.placeholder("float")
#Create a model function
def model(X, w):
return tf.multiply(X,w)
# Create a variabl... |
#Luis Ramirez
#12/08/10
#ball.py
#pong.py library
from gv2 import *
from random import random, randrange
from time import sleep
class Vector:
"""Class for containing the motion of objects"""
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def setX(self, num): self.x = num
def setY(self, nu... |
number = int(input("Enter Number: "))
flag = 0
for i in range(2, number):
if number % i == 0:
flag = 1
break
else:
flag = 0
print("Prime") if flag == 0 else print(" Not Prime")
|
# Write a Program using Function to calculate simple interest, accepts 3 args. and returns the simple interest
def interest(p, r, t):
return (p * r * t) / 100
p = int(input("Enter Amount: "))
r = int(input("Enter Interest Rate: "))
t = int(input("Enter Time Period: "))
print("Interest Amount: ", interest(p, r,... |
tuple = ('abcd', 786, 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print(tuple)
print(tuple[0])
print(tuple[1:3])
print(tuple[2:])
print(tinytuple*2)
print(tuple+tinytuple)
|
# Para calcular el radio de un círculo importamos pi, desde el modulo math y ponemos la fórmula pi*r^2 (el {} debe estar
# entre comillas, si no, parece que no funciona xd)
r=float(input("pon el radio del circulo aquí: "))
from math import pi
area= (pi * r**2)
print(("El área del círculo es {}") .format(area))
|
"""remove duplicates from sorted linked list"""
class Node(object):
def __init__(self,data=None,next_node=None):
self.data=data
self.next=next_node
class Linked_list:
def __init__(self):
self.head=None
def inserNth(self,data,position):
if position==0:
if self... |
class Node():
def __init__(self,data,left=None,right=None):
self.data=data
self.left=left
self.right=right
def insert(root,node):
if root.data > node.data:
if root.left:
insert(root.left,node)
else:
root.left=node
elif root.dat... |
day = int(input('Day (0-6)? '))
# Fill in your code here
if day == 0:
print("It's Sunday!")
elif day == 1:
print("It's Monday!")
elif day == 2:
print("It's Tuesday!")
elif day == 3:
print("It's Wednesday!")
elif day == 4:
print("It's Thursday!")
elif day == 5:
print("It's Friday!")
elif day ==... |
# establish a string
string = "This is the string im going to change into what I want"
# make it backwards
string_backwards = string[::-1]
# show it
print(string_backwards)
#remember that slice thing [::-1] |
phonebook_dict = {
'Alice': '703-493-1834',
'Bob': '857-384-1234',
'Elizabeth': '484-584-2923'
}
# Write code to do the following:
# 1. Print Elizabeth's phone number.
# 2. Add an entry to the dictionary: Kareem's number is 938-489-1234.
# 3. Delete Alice's phone entry.
# 4. Change Bob's phone number to '... |
power_rangers = ["Jason", "Trini", "Zack", "Billy", "Kim", "Tommy"]
#ask user to remove someone in the list
who_to_remove = input("Who would you like to remove?: ")
if who_to_remove in power_rangers:
power_rangers.remove(who_to_remove)
print(power_rangers)
else:
print("%s is gone." % (who_to_remove))
#S... |
# Programme to find the given number is perfect or not
def checkPerfect(y):
sum = 0
for i in range(1,y):
if y % i == 0:
sum += i
if sum == y:
return "Perfect Number"
return "Not Perfect Number"
x = int(input("Enter the number to find weather its perfect or not-> ... |
# Programme to find weather the input no is even or odd
number = input("Enter the number u wanna check-> ")
number = int(number)
if number % 2 == 0:
print(f"Entered number {number} is Even")
else:
print(f"Entered number {number} is odd")
|
#! /usr/bin/env python
# python script that converts between units of temperature
def f_to_k(temp):
return (temp-32)*(5/9.0)+273.15
def k_to_c(temp):
return temp - 273.15
def f_to_c(temp):
return k_to_c(f_to_k(temp))
# tests
print f_to_k(32)
print k_to_c(273.15)
print f_to_c(32)
print(' too hot for you ')... |
class Solution:
# @param A : list of integers
# @param B : integer
# @return an integer
def searchInsert(self, arr, B):
l,h,ans = 0,len(arr)-1,-1
while l <= h :
mid = (l+h)//2
if arr[mid] == B:
return mid
elif arr[mid] < B :
... |
class Poll:
def __init__(self):
# List of candidate objects
self.candidate = []
# List of region objects
self.regions = []
self.date = 0
# Returns list of all regions
def get_regions(self):
return self.regions
# Returns list of all candidates... |
class EmptyQueueException(Exception):
'''
'''
class Deque():
'''
A Queue that can be en/dequeued from both ends.
Uses a list to store the contents.
'''
def __init__(self):
# representation invariant
# _contents is a list of objects
# _contents[:] represent the ite... |
from tkinter import *
import tkinter as tk
from tkinter import messagebox
import tkinter.font as font
""" GREAT COLOR PALETTES :https://imgur.com/Jmk6LEH """
def insertWinButtons(xo,l,c,nextl,nextc,prevl,prevc):
winButtonOne= Button(root,bd=0,text=xo,width=12,height=5,fg="#323831",bg="#a6e22e")
winButtonOne.gr... |
import sqlite3
import time
today=time.strftime("%A, %B %d, %Y")
connection=sqlite3.connect("/home/amey/atomparsing/src/database/feed.db")
cursor=connection.cursor()
#cursor.execute('INSERT INTO mytable VALUES(null, ?, ?)', (today, "This entry could be the first item on a To-Do List, or it could be a journal entry, or ... |
'''
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
'''
import heapq
def most_frequent(arr, k):
freq_map = {}
min_heap = []
for each in arr:
if each in freq_map:
freq_map[each] += 1
else:
freq_map[each] = 1
if len(min... |
'''
Smallest k numbers
k size max heap
'''
import heapq
def smallest_k(arr, k):
max_heap = [] * k
for i in range(k):
heapq.heappush(max_heap, arr[i] * - 1)
for i in range(k, len(arr)):
if arr[i] < max_heap[0] * -1:
heapq.heappop(max_heap)
heapq.heappush(max_heap... |
def merge(interval, new_interval):
next_index = 0
for i, each_interval in enumerate(interval):
if each_interval[0] > new_interval[0]:
next_index = i
break
if i > 0:
merged = merge_three(interval[next_index - 1], new_interval, interval[next_index])
if merged !... |
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :r... |
'''
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
'''
def lef... |
'''
Given an inorder traversal of a cartesian tree, construct the tree.
Cartesian tree : is a heap ordered binary tree, where the root is greater than all the elements in the subtree.
Note: You may assume that duplicates do not exist in the tree.
Example :
Input : [1 2 3]
Return :
3
/
2
... |
def insertion_sort(arr):
# The way you sort the cards
for i in range(1, len(arr)):
j = i - 1
key = arr[i]
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [2543, 234, 34, 37, 453, 4553]
insertion_sort(arr)
print arr
|
class LinkedList:
def __init__(self, head=None):
self.head = head
def reverse(self, current_node, prev=None):
if current_node == None:
self.head = prev
return
next_node = current_node.next
current_node.next = prev
self.reverse(next_node, current_node)
def print_ll(self):
current = self.head
wh... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @param val1 : integer
# @param val2 : integer
# @return an integera
left_exist = False
right_exist = F... |
import heapq
def heap_sort(arr):
heapq.heapify(arr) # O(n) time
result = []
while len(arr) > 0:
result.append(heapq.heappop(arr)) # Pop takes O(1) + O(log n) for re-heapification
return result
arr = [34, 32, 3, 523, 5234, 32242, 4234]
print heap_sort(arr)
|
'''
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
'''
def three_sum(arr):
result = []
for i in range(arr):
result.append(two_sum(arr, i) + [i])
return result
def two_sum(arr, target):
i = 0
j = len(arr) - 1
while i < j:
if arr[i] + ... |
# Creating a binary tree class
"""
User
bst = Btree()
bst.insert(14)
bst.preorder()
bst.postorder()
bst.inorder()
"""
class Node:
#Constructor
def __init__(self, val):
self.value = val
self.leftChild = None
self.rightChild = None
def insert(self, val):
if self.value == val:
return Fals... |
#Author: Shreyas Mohan
import sys
#LRS method returns a matrix containing the length of all possible subsequences
def LRS(inputString):
#L is a two dimension array containing the lengths of subsequences
L = []
#L is initially defined as 0 for all positions
L = [[0 for i in range(length + 1)] for j in... |
#from bs4 import BeautifulSoup
import bs4
from urllib.request import urlopen
#pass the URL
num = input("Enter from which year you want:")
#s='http://www.imdb.com/search/title?release_date=2005,num&title_type=feature&user_rating=1.0,10'
#print('http://www.imdb.com/search/title?release_date=2005,',num,'&title_type=featur... |
'''
Write the necessary code calculate the volume and surface area
of a cylinder with a radius of 3.14 and a height of 5. Print out the result.
'''
# Cylinder volume = π r² h
# Cylinder surface area = 2π r h + 2π r²
def cylinder_volume_surface(radius, height):
volume = float((3.14 * radius ** 2 * height))
... |
'''
Write a script that takes in a number in days from the user between 1 and 1,000,000,000 and convert it to seconds.
NOTE: We will use the input() funtion to collect users input. An example is demonstrated below.
'''
days = int (input ("Please enter a number in days between 1 and 1,000,000,000: "))
seconds = int (... |
"""
Write a script that takes a string from the user and creates a list of tuples with each word.
For example:
input = "hello world"
result_list = [('h', 'e', 'l', 'l', 'o'), ('w', 'o', 'r', 'l', 'd')]
"""
input = "hello world"
# t = tuple(input)
# print(t)
# for i in t:
# if i == (' '):
# continue
# p... |
# if is a key word that allows computer program to make simple decisions.
age = 24
if age < 21:
# This next code will execute only if the above condition is true: If age is less than 21.
print('No beer for you!')
# This next line checks whether the age is greater than 21.
elif age > 21:
print('You can buy beer!'... |
# A list is a datatype composed of comma-separated items.
# To create a list, give the list a name and list the items in [] brackets.
# A list called players with 5 items (numbers).
players = [45, 32, 12, 67, 34]
# print() is an inbuilt function in Python for printing stuff.
# Print the items in the list.
print(playe... |
maths = int(input("Enter Maths score: \n"))
eng = int(input("Enter English score: \n"))
swa = int(input("Enter Swahili score: \n"))
physics = int(input("Enter Physics score: \n"))
history = int(input("Enter History score: \n"))
def get_scores():
total = maths + eng + swa + physics + history
return total
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.