text stringlengths 37 1.41M |
|---|
import turtle
#lander initial position
x0=0
y0=0
#lander position
x=0
y=0
#lander initial velocity
vx0=10
vy0=0
#lander velocity
vx=10
vy=0
#lander initial acceleration
ax0=0
ay0=-10
#lander acceleration
ax=0
ay=-10
#time step
dt=1/20
ground_level=-200
body=turtle.Turtle()
body.shape('circle')
body.color('red')
bts ... |
import turtle
import math
turtle.speed('fastest')
#lander initial position
x0=0
y0=0
#lander position
x=0
y=0
#lander initial velocity 7 angle
angle0 = 0
velocity0 = 50
vx0=10
vy0=0
#lander velocity
vx=10
vy=0
#lander initial acceleration
ax0=0
ay0=-10
#lander acceleration
ax=0
ay=-10
#time step
dt=1./20
ground_level... |
from connection import connect
def create_db(db_name):
sql = f"""
CREATE DATABASE {db_name}
"""
conn = connect()
cursor = conn.cursor()
try:
cursor.execute(sql)
except:
return 'This database name is already in use'
conn.close()
def create_table(table_name, columns_names... |
# 1.For Loop Basic work
even_list = list(range(2, 10, 2))
for i in range(3):
print(i)
# 2. Printing a Patteren
# *
# * *
# * * *
# * * * *
# * * * * * [ Like That ]
for i in range(1, 5):
for j in range(i):
print('*', end=" ")
print("")
# Here i learned one thing Identation is reall... |
"""
Queue implemented with a resizing List
"""
from .queue import Queue
class QueueWithListIterator(object):
def __init__(self, items, front_index, back_index):
super(QueueWithListIterator, self).__init__()
self._items = items
self._current_index = front_index
self._back_index = ba... |
import calendar
import datetime
import time
ticks= time.time()
print(ticks)
#获取当前时间
localtime = time.localtime(time.time())
print(localtime)
print(time.localtime())
#格式化时间 Tue Apr 23 15:08:53 2019
formattime= time.asctime(time.localtime(time.time()))
print(formattime)
#格式化成2016-03-20 11:45:39形式
formatdate=time.str... |
import json
'''
json.dumps() //将字典转换为json字符串
json.dump() //可以将内容序列化写入文件中
'''
dict01 = dict(name="lisi",age=20)
print(json.dumps(dict01))
dict011 = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
print(json.dumps(dict011,indent=2,separators=(',',':')))
json01= '{"name": "lisi", "age": 20}'
dict02 = json... |
total = 0
def count(n):
global total
total = total + n
if n == 1:
print(total)
return
n = n - 1;
count(n)
count(10)
|
print("Welcome to Pizza Deliveries")
size = input("What size pizza do you want S, M, L? ").upper()
pep = input("Do you want pepperoni? Y or N: ").upper()
cheese = input("Do you want extra cheese? Y or N: ").upper()
bill = 0
if size == 'S':
bill = 15
if pep == 'Y':
bill = bill + 2
if cheese == 'Y':
... |
#importing everything we need from colorama
from colorama import init
from colorama import Fore, Back, Style
#making a loop
while True:
#activating colorama
init()
#choosing the operator
print(Fore.BLUE)
operator = input ("Choose an operator (+, -, *, /, **)")
#choosing the numbers
n... |
# MISSING VALUES
# No R os valores faltantes são codificados como NA
import numpy # Importa a biblioteca NumPy para ser utilizada no código
vector1 = [188.2, 181.3, 193.4, numpy.nan] # Cria um vetor dinâmico com tamanho variado com um dos valores sendo NaN
print(vector1) # Printa o vetor no console
print(numpy.isnan... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 12:34:03 2018
@author: bpiwowar
"""
import sys
import os
import csv
# Relative path to folder containing raw files
# This can be used instead of passing an argument to the script
FOLDER_PATH = "SubjectData25Nov"
# return a list of files cont... |
'''price = 1000000
has_good_credit = True
if has_good_credit:
down_payment = 0.1 * price
else:
down_payment= 0.2 * price
print(f"Down Pament: ${down_payment}")'''
#temperature = 35
#if temperature < 30 print("It's a hot day")#else:
# print("It's not a hot day")
'''name = "Pd"
if len(name) < 3:
print("... |
# -*- coding: utf-8 -*-
class upair:
# If y != None, constructs the unordered pair (x, y)
# If y == None, constructs an unordered pair from iterable x, e.g. a tuple
def __init__(self, x, y=None):
if y is not None:
self._x = x
self._y = y
else:
self._x, sel... |
# The challange consisted of checking string format which I've done
# using regex and then doing a simple calculation
def get_check_digit(input):
import re
r = re.compile('\d-\d{2}-\d{6}-x')
if len(input) == 13:
if r.match(input):
stripped = input[:-2].replace("-","")
s = 0
... |
'''Write a program containing a function which returns a transposed matrix.
Have it accept non-square matrices as well.
Write a unit test.'''
import unittest
def transpose(M):
row = len(M[0])
col = len(M)
l2 = []
l3 = []
for i in range(0,row):
for j in range(0,col):
l2.append(M[j][i])
l3+=[l2]
l2=[]
re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
a_list = range(30)
random.shuffle(a_list)
print a_list
# 使用选择排序对列表进行排序
for i in range(len(a_list) - 1):
for j in range(i + 1, len(a_list)):
if a_list[i] > a_list[j]:
a_list[i], a_list[j] = a_list[j], a_list[i]
print a_list
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
a = range(1, 6)
print a[::2]
print a[-2:]
print sum([i + 3 if a.index(i) % 2 == 0 else i for i in a])
random.shuffle(a)
b = a[:]
b.sort()
print a
print b
print zip(a, b)
print dict(zip(a, b)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
class Node(object):
"""树节点类
"""
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
class BST(object):
"""二叉查找树
"""
def __init__(self, node_list):
self.root... |
#DFS ITERATIVA
"""
busqueda en profundidad
"""
def dfs(G,s):
N= len(G)
visited=[0 for _ in G]
stack=[s]; visited[s]=1
while len(stack)!=0:
u=stack.pop()
assert visited[u]==1
for v in G[u]:
if visited[v]==0:
stack.append(v); visited[v]=1
visited[u]=2
return visited
G=[
[1],
[0,2,6,3],
[1,3],
... |
#Nombre: Tania C. Obando S.
#Codigo: 6036110
"""
Código de Honor
Como miembro de la comunidad académica de la Pontificia Universidad Javeriana Cali me comprometo
a seguir los más altos estándares de integridad académica.
Integridad académica se refiere a ser honesto, dar crédito a quien lo merece y respetar el trab... |
n = int(input())
is_Even = n % 2 == 0
print(is_Even)
|
password = "1234"
count = 1
quess = input("Please, enter password: ")
while quess != password:
count += 1
print("Wrong password")
quess = input("Please, enter password: ")
print("You have used", count, "attempts")
|
def denklem1 (x):
return x*(x+1)/2
def denklem2 (x):
return x*((3*x)-1)/2
def denklem3 (x):
return x* ((2*x)-1)
a=b=c=1
denklem_a=denklem1(a)
denklem_b=denklem2(b)
denklem_c=denklem3(c)
print("eşit durumlar:")
while True:
if denklem_a==denklem_b and denklem_b==denklem_c:
print("A({})=B({}),C(... |
a = input("cümle giriniz?")
print (a[::-1])
print (a.split(" "))
harfler = []
sayisi = []
for i in(a):
if not (i in harfler):
harfler.append(i)
sayisi.append(1)
else:
sayisi[harfler.index(i)] = sayisi[harfler.index(i)]+1
print ("her harften kac tane;")
for j in range(len(harfler)):
p... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_17.py
@time: 2019/5/4 14:36
@desc:
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回合并后列表
... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_16.py
@time: 2019/5/7 13:57
@desc:
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNod... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_61.py
@time: 2019/4/17 14:04
@desc:
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# use... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_65.py
@time: 2019/4/25 13:00
@desc:
'''
class Solution:
def maxInWindows(self, num, size):
if not num or size <= 0:
return []
if s... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_15.py
@time: 2019/3/27 22:06
@desc:
链表中倒数第k个结点:
输入一个链表,输出该链表中倒数第k个结点。
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: merge_sort.py
@time: 2019/3/24 20:21
@desc:
'''
import numpy as np
def merge_sort(data):
return sort(data)
def sort(data):
if len(data) <= 1:
return data
... |
#!/usr/bin/python
# HW 2 - problem 1 (list_concat)
# Author: Chris Kasper
import sys
from cell import *
def list_concat(A,B):
# Connect A.next's last element to the beginning of B
end = A
while end.next is not None:
end = end.next
end.next = B
return A
def main():
x = Cell( 13 )
y... |
##count = 0
##a = [11,7,10,6,4,5,9,8]
##while count < 2:
## temp =a[0]
## for i in range(1, len(a)):
## if temp < a[i]:
## temp = a[i]
## a.remove(temp)
## count+=1
##print temp
def prime(num):
for i in range(2, num):
if num % 2 == 0:
return False
bre... |
__all__ = ['coin']
class coin():
__side = ''
def __init__(self):
self.__side = ''
def side(self):
return self.__side
def flip(self):
import numpy as np
value = np.random.randint(2)
if value == 0:
self.__side = 'tails'
else:
... |
sequence=[1,3,5,9]
doubled=[(lambda x:x*2)(x) for x in sequence]
doubled=list(map(lambda x:x*2,sequence))
print(doubled) |
N = int(input())
distance = [0 for _ in range(N+1)]
for x, current in enumerate(distance):
if x<2 : continue
distance[x] = distance[x-1]+1
if (x % 3) == 0 : distance[x] = min(distance[int(x/3)]+1, distance[x])
if (x%2) == 0 : distance[x] = min(distance[int(x/2)]+1, distance[x])
print(distance[N])
|
#!/usr/bin/env python
#coding:utf-8
def movable(w,h,x,y,maps):
result = []
rx = x + 1
lx = x - 1
uy = y - 1
dy = y + 1
if (-1 < uy) and (maps[uy][x] == 1):
result.append((x,uy))
if (dy < h) and (maps[dy][x] == 1):
result.append((x,dy))
if (rx < w):
if (maps[y][rx] == 1):
result... |
#!/usr/bin/env python
#coding:utf-8
def primep(n):
if ( n < 2): return False
if (n == 2): return True
if (n % 2 == 0) : return False
acc = 3
while (n >= acc * acc):
if (n % acc == 0) : return False
acc += 2
return True
def solve(a,d,n):
"""
simple way and slow
"""
cnt = 0
val = a
... |
import time
def shift_char(char,index):
if not (char.isalpha() and char.islower()):
return char
code = ord(char) + index
if code > 122:
return chr(code % 122 + 96)
else:
return chr(code)
def shift_text(text,index):
return "".join(map(lambda x: shift_char(x,index),text))
... |
import random
print("1: Throw dice 0: Exit")
while True:
# We ask user to press a button
x=int(input("Press a button "))
if x==0:
print('Bye, see you !')
break
elif x==1:
print(random.randint(1,6))
else:
print("I don't understand") |
N=int(input())
even=0
odd=0
for i in range(N+N+1):
if i % 2 == 0:
even+=i
else:
odd+=i
print(f"{odd} {even}")
|
# Loop Notes
# FOR LOOPS
for i in range(10):
print("Python")
for i in range(10):
print(i)
for i in range(1, 11):
print(i)
# prints 1-11
for i in range(5, 50, 3):
print(i)
for i in range(100, 0, -5):
print(i)
for i in range(1, 21):
print(1/i)
print("{}".format(i/1))
# IF STATEMENT
x ... |
import pandas as pd
import numpy as np
web_status = {
"Day": [ 1, 2, 3, 4, 5, 6],
"Visitors": [56, 33, 223, 56, 142, 229],
"Bar_tag": [245, 345, 334, 566, 432, 444]
}
df = pd.DataFrame(web_status)
#print df
#
#print df.head(3)
#
#print df.tail(2)
#
#print df.set_index('Day')
#
#
#print df
#
#
#print df.... |
class Student :
subjectN = ["Calculus", "Software", "English"]
def __init__(self, name) :
self.name = name
self.dict = {'A+' : 4.5, 'A0' : 4.0, 'B+' : 3.5, 'B0' : 3.0, 'C+' : 2.5, 'C0' : 2.0, 'D+' : 1.5, 'D0' : 1.0, 'F' : 0}
self.score = [0, 0, 0]
self.grade = ['F', 'F', 'F']
... |
import os
import sys
from operator import itemgetter
# Your code here
ignore = ['"', ':', ';', ',', '.', '-', '+', '=', '/',
'\\', '|', '[', ']', '{', '}', '(', ')', '*', '^', '&']
def histo(filename):
my_dict = {}
# Open file and read
with open(os.path.join(sys.path[0], filename)) as f:
... |
number = int(input(''))
list = []
for i in range(0,number):
newNo = int(input(''))
a = list.append(newNo)
print("Elements are",list[i],i)
|
import math
import copy
class Vector(list):
""" Vector.py
6/24/2009 by Travis Jones
simple list-based vector class
Notes:
- Inspired by http://code.activestate.com/recipes/52272/
- Supports 2D and 3D vectors
- Constructor takes either a tuple ... |
import random
#import maths
def jump():
print("---------------------")
print("Combat jump initiated. \n")
astro_mods = input("Astrogation+EDU skill modifier: ")
astro_mods = int(astro_mods)
dice = random.randint(1, 6) + random.randint(1, 6)
dice_total = dice
dice_total_2 = dice_total+(as... |
from Crypto.Hash import SHA256
def RSA_sign(sk,code):
'''Uses the RSA secret key sk to return a signature (as a string) for the string code.
Preconditions: sk is an RSA secret key, code is a string'''
code = code.encode('utf-8')
hash = SHA256.new(code).digest()
signature = sk.sign(ha... |
#With a given integral number n, write a program to generate a dictionary
# that contains (i, i*i) such that is an integral number between 1 and n (both included).
# and then the program should print the dictionary.
#Suppose the following input is supplied to the program:
#8
#Then, the output should be:
#{1: 1, 2: 4, 3... |
#Write a program that accepts a comma separated sequence of words as input and prints the words
# in a comma-separated sequence after sorting them alphabetically.
#Suppose the following input is supplied to the program:
#without,hello,bag,world
#Then, the output should be:
#bag,hello,without,world
user_input = input(... |
# Reverse Cipher
# http://www.nostarch.com/Crackingcodes (BSD Licensed)
# input only works for Python 3, we'll use raw_input() instead
#message = input('Enter message: ')
message = raw_input('Enter message: ')
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
prin... |
cake = float(input("Enter the pieces of cake you have eaten:"))
kilometers= float(input("Enter the Kilometers you have run:"))
kilometers_ran = kilometers*100
cake_jog= ((225*cake)-kilometers_ran)
print ("This is how many calories you have lost:" + str(cake_jog))
|
import multiprocessing
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
#Creating a thread pool to manage calls equal to
class ThreadPool(object):
def __init__(self, machine):
self.outlets = machine.outlets_getter()
self.pool = ThreadPoolExecutor(max_workers=self.outlets)
... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 7 19:39:32 2016
@author: coste
"""
def det(matriz):
det = 1
for i in range(len(matriz)):
det *= matriz[i][i]
return det
matriz = [[88, 27, 46], [0, 57, 20], [0, 0, 15]]
print(det(matriz)) |
print("Welcome to our programme!")
age = float(input("Please enter your age:"))
if 0 < age <= 19:
if 0 < age < 1:
print("You are an infants.")
if 10 < age <= 19:
print("You are an adolescent.")
else:
print("You are a child.")
elif age > 19:
print("You are an adult.")
... |
def readSudoku(name):
with open(name, "r") as puzzle:
return [[int(i) for i in line.split(",")] for line in puzzle]
def processRij(x, num):
for y in range(0,9):
if num in mogelijkNum[x][y]:
mogelijkNum[x][y].remove(num)
def processColumn(y, num):
for x in range(0,9):
if... |
#find the first non-repeating character in a string
def first_nonrepeat(str):
for i, c in enumerate(str):
if c not in str[:i] + str[i+1:]:
return c
else:
print "None"
|
penny = {'value': 1}
nickel = {'value': 5}
dime = {'value': 10}
quarter = {'value': 25}
dollar = {'value': 100}
class CoinChanger():
def make_change(self, p):
current_pouch = []
coins = [dollar, quarter, dime, nickel, penny]
for coin in coins:
(p, current_pouch) = self.find_... |
#comparison_operator
statement1=input("Enter first statement")
statement2=input("Enter second statement")
print(len(statement1))
print(len(statement2))
#==
print(len(statement1)==len(statement2))
#!=
print(len(statement1)!=len(statement2))
#<
print(len(statement1)<len(statement2))
#>
print(len(statement1)... |
class Calorie:
'''
formula: 10 * weight + 6.25 * height - 5 * age + 5 - 10 * temperature
'''
def __init__(self, weight, height, age, temperature):
self.weight = weight
self.height = height
self.age = age
self.temperature = temperature
def calculate(se... |
# Import argv from module 'sys'
from sys import argv
# Split parameters to each variable
script, input_file = argv
# Create function 'print_all' passing argument 'f'. f will be a file
def print_all(f):
# Print output result read the file 'f'
print(f.read())
# Create funciton 'rewind' passing a file 'f'
def... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#title :ex15.py
#description :http://learnpythonthehardway.org/book/ex15.html
#author :Gon
#date :20160618
#version :1.0
#usage :python ex15.py
#notes :
#python_version :2.7.6
#==============================================================================
from sys i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#title :readline.py
#description :read lines from a textfile
#author :Gon
#date :20160619
#version :1.0
#usage :python readline.py
#notes :
#python_version :2.7.6
#==============================================================================
from sys import argv
s... |
# 52198150
import copy
def bubble_sort(n, array):
for j in range(n-1):
flag = False
for i in range(n-1-j):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
flag = True
if flag is False:
return array
print(... |
# 52073600
def String(word1, word2):
word1 = sorted(list(word1))
word2 = sorted(list(word2))
k = 0
extra_symbols = []
while len(word1) != len(word2):
if len(word1) < len(word2):
for x, y in zip(word1, word2):
if x != y:
word1.insert(k, '0')
... |
# 52168257
def phone_buttons(prefix, sequence, cur_button_in_sequence, n, i):
if n == 0:
sequence.append(prefix)
i = 0
for j in range(11):
if n == j:
for ch in cur_button_in_sequence[i]:
phone_buttons(prefix + ch, sequence,
cur_bu... |
# 52113132
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return (self.items[-1])
def is_correct_bracket_se... |
from tree import Tree
treeVals = [3, 9, 20, None, None, 15, 7]
tree = Tree(treeVals)
root = tree.root
class Solution():
# use a global variable to track if any subtree is unbalanced
ans = True
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
de... |
# Your previous Plain Text content is preserved below:
#
# This is just a simple shared plaintext pad, with no execution capabilities.
#
# When you know what language you'd like to use for your interview,
# simply choose it from the dropdown in the top bar.
#
# You can also change the default language your pads are cre... |
"""
Problem Description:
Given a matrix of letters, and a word. Check whether the word
`exists` in the matrix.
The word can start at any position of the matrix. Every next letter
is connected in three possibe dicrections:
(1) right
(2) down
(3) lower right
Example:
[["C", "B", "A", "N"],
["A", "O", "O",... |
class Solution:
"""
A node must have two children: missing one is marked as #.
"#" does not have children.
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #
Serialization: [9,3,4,#,#,1,#,#,2,#,6,#,#]
"""
def isValidSerialization(self,... |
import pygame
from tkinter import Tk, Canvas, ALL
###########################################
# Animation class
###########################################
class Animation(object):
# Override these methods when creating an animation
def mousePressed(self, event): pass
def keyPressed(self, event): pass
... |
numbers = ['4', '5','3']
s = 0
for n in numbers:
s = s + int(n)
print (s)
|
"""
CtCi
10.5 Given a sorted array of strings that is interspersed with empty strings, write a method
to find the location of a given string.
BRUTE FORCE:
linearly search the element.
Time: O(n) Space: O(1)
better
Keep searching both sides of the arr if mid is empty string
if element found, search either side
"""
d... |
"""
Implement stack data structure with 2 queues.
"""
class Queue(object):
"""Queue Data Structure"""
def __init__(self, queue=[]):
super(Queue, self).__init__()
self.queue = queue
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if not self.queue:
... |
"""
Implementing binary search tree with parent pointer
"""
class Node(object):
def __init__(self, value):
self.value = value
self.parent = None
self.left = None
self.right = None
class BinarySearchTreeWithParent(object):
"""docstring for BinarySearchTreeWithParent"""
def ... |
"""
Selection sort
Sorts an array by repeatedly finding the minimum element from unsorted part and put it at the beginning
Time: O(n^2)
Space: O(1)
"""
def selection_sort(array):
if len(array) < 2:
return array
unsorted = 0
for i in xrange(len(array)):
min_index = i
min_value = ar... |
"""
CtCi
2.8 Given a circular linked list, implement an algorithm that returns the node at the beginning
of the loop.
Circular linked list: A(corrupt) linked list in which a node's next pointer points to an earlier node,
so as to make a loop in the linked list.
Eg.
Input: A -> B -> C -> D -> E -> C(the same C as earl... |
"""
Singly linked list implementation.
"""
class Node(object):
"""docstring for Node"""
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList(object):
"""docstring for LinkedList"""
def __init__(self, value):
self.head = Node(value)
de... |
"""
CtCi
10.4 You are given an array-like data structure. Listy which lacks a size method.
It does, however have an elementAt(i) method that returns the element at index i
in O(1) time. If i is beyond the bound of the data structure, it returns -1.(For
this reason, the data structure only supports positive integers.) ... |
"""
CtCi
1.2 Given two strings, write a method to decide if one is a permutation of the other.
"""
def check_permutation(str1, str2):
"""
Time: O(mn)
Space: O(max(m, n))
where m is the size of str1, n size of str2.
"""
if not str1 or not str2:
return False
table = {}
for value i... |
"""
CtCi
8.5 Write a recursive function to multiply two positive integers without using the
* operator. You can use addition, subtraction, and bit shifting, but you should minimize
the number of those operations.
"""
def multiply_by_addition(a, b):
sign = "+"
if (a < 0 and b > 0) or (a > 0 and b < 0):
... |
"""
CtCi
3.4 Implement a MyQueue class which implements a queue using two stacks
"""
class MyQueue(object):
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, item):
self.stack1.append(item)
return
def dequeue(self):
if len(self.stack1) < 1:
... |
"""
CtCi
10.2 Write a method to sort an array of strings so that all the anagrams are next to each other.
"""
def sort_strings(arr):
"""
hash table to order elements
key: value
string: [anagrams of the string]
Time: O(mnlgn)
Space: O(m)
where m is size of array, n is size of longest word i... |
"""
This file contains a list of method references for a dictionary
"""
# initialize a dictionary
stuff = {
'name': 'Zed',
'age': 35,
'height': 4 * 12
}
# set key to value
stuff['hair_color'] = 'black'
# check if key is in dict
print 'hair_color' in stuff # true
# delete key and its value from dict. Rai... |
"""
CtCi
3.5 Write a program to sort a stack such that the smallest items are on top.
You can use an additional temporary stack, but you may not copy the elements into
any other data structure(such as an array), The stack supports the following
operations: push, pop, peek and isEmpty.
"""
def sort_stack(stack):
"... |
"""
CtCi
10.6 Imagine you have a 20GB file with one string per line. Explain how you
would sort the file.
"""
# 1. break up to 20GB into 20,000 files of 1MB file size each.
# 2. use mergesort to sort each 1MB file.
# 3. after all files are independently sorted, we use the merge procedure(from mergesort) to merge
# eac... |
"""
CtCi
4.8 Design an algorithm and write code to find the first common ancestor of two
nodes in a binary tree. Avoid storing additional nodes in a data structure. Note:
This is not necessarily a binary search tree.
"""
from BinarySearchTreeWithParent import BinarySearchTreeWithParent
def first_common_ancestor(node1... |
"""
CtCi
T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create
an algorithm to determine if T2 is a subtree of T1.
A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree
of n is identical of T2. THat is, if you cut off the tree at node n, the two trees
would be identi... |
"""
Given two strings s and t, determine whether some anagram of t is a substring of s. For example: if
s = “udacity” and t = “ad”, then the function returns True. Your function definition should look
like: “question1(s, t)”, and return a boolean True or False.
"""
def question1(s, t):
#creates a dict of {character... |
""" Working with mixed datatypes (2)
You have just used np.genfromtxt() to import data containing mixed datatypes. There is also another function np.recfromcsv() that behaves similarly to np.genfromtxt(), except that its default dtype is None. In this exercise, you'll practice using this to achieve the same result. """... |
""" The structure of .mat in Python
Here, you'll discover what is in the MATLAB dictionary that you loaded in the previous exercise.
The file 'albeck_gene_expression.mat' is already loaded into the variable mat. The following libraries have already been imported as follows:
import scipy.io
import matplotlib.pyplot as... |
# -*- coding: utf-8 -*-
# https://docs.python.org/3.5/library/datetime.html ler depois
class MvpView:
def __init__(self, name):
self.mvp = name
self.queued = []
self.time = []
def add_entry(self, mvp_list):#linkar mvp_list com o controller
"""
Ask user for ... |
#Recursive
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def isMirror(t1,t2):
if t1==None and t2 ==None: return True
if t1==None or t2 == None: return False
return t1.val==t2.val and isMirror(t1.right,t2.left) and isMirror(t1.left,t2.right)
... |
# 125. Valid Palindrome
# My solution: Two pointers
class Solution:
def isPalindrome(self, s: str) -> bool:
i = 0
j = len(s)-1
while(i<j):
if s[i].isalnum()==False:
i +=1
continue
if s[j].isalnum()==False:
... |
import time
n = 6
result_matrix = [[0 for x in range(n)] for y in range(n)]
def print_matrix( r):
for i in range(n):
for j in range(n):
print(r[i][j], end = '\t')
print()
counter = 1
k = n
# row left to right
print("the middle is" + str((n//2+1)))
for i in range(n//2+1):
time.sleep(2)
print("*... |
class Item(object):
def __init__(self, n, v, w):
self.name = n
self.value = v
self.weight = w
def getName(self):
return self.name
def getValue(self):
return self.value
def getWeight(self):
return self.weight
def __str__(self):
return self.n... |
# 3 types of data in python
10
# numbers
"Mosh"
# strings
True
# booleans
birth_year = input("Enter your birth year: ")
# input returns a string. You can't subtract a String from an int, so you get a type error
# below you will see Pythons equivalent to casting in Java (int and str)
age = 2020 - int(birth_year)
print("... |
class Quantity:
def __init__(self,storage_name):
self.storage_name = storage_name
def __set__(self, instance, value):
if type(value) is not str:
if value >0:
instance.__dict__[self.storage_name] = value
else:
raise ValueError('value must b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.