text stringlengths 37 1.41M |
|---|
#! python3
# selectivecopy.py - Copies an entire folder and its contents into
import os, shutil, sys
print('Enter Source Directory')
Source = input()
print('Enter Destination Directory')
Destination = input()
print('Enter file extension to copy')
pattern = input()
if os.path.isdir(Source) == False:
print('Error: Sour... |
#!python3
#Search for occurence of Noun or Adverb or Adjective and asks for replacement string Pg 195
import re
print('Enter String')
text =input()
pattern = re.compile(r'(ADJECTIVE|NOUN|ADVERB|VERB)')
while pattern.search(text)!=None:
match = pattern.search(text).group()
print('Enter an ' + match)
sub = input()... |
# Creator: Ivan Sharma.
# Date: 21st December 2019.
# Desc: Calculate the GST(goods service tax).
base_price = input('Enter the base price of your goods/services: ')
base_price = float(base_price)
GST = (15/100) * base_price
print('Your GST is:',GST)
total_amount = base_price + GST
print('The total amount is:',total_... |
from challenges.insertion_sort.insertion_sort import insertion_sort as ins
def test_sort():
ay = [8, 4, 23, 42, 16, 15]
assert ins(ay) == [4, 8, 15, 16, 23, 42]
def test_reversed():
ay = [20, 18, 12, 8, 5, -2]
assert ins(ay) == [-2, 5, 8, 12, 18, 20]
def test_uniques():
ay = [5, 12, 7, 5, 5, 7... |
class AnimalShelter():
"""
animal shelter class
"""
def __init__(self):
self.dog = []
self.cat = []
def enqueue(self, animal, name):
"""
Adds animal and name to a stack
Args:
animal (string): [Dog or Cat]
name (string): [Any]
... |
from challenges.array_binary_search.array_binary_search import binarySearch
"""
Write a function called BinarySearch which takes in 2
parameters: a sorted array and the search key.
Without utilizing any of the built-in methods available to your
language, return the index of the array’s element that is equal
to the sea... |
'''
p - memory address (one byte)
q - memory address (one byte) used for opcodes with multiple Ps
t - memory address (two bytes)
b - constant (one byte)
w - constant (two byte)
r - memory branch relative offset (one byte)
s - memory branch relative offset (two byte)
The "bus" field shows how a... |
# 2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
# Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными.
# Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
# Использовать ... |
# 5) Реализовать формирование списка, используя функцию range() и возможности генератора. В
# список должны войти четные числа от 100 до 1000 (включая границы). Необходимо получить
# результат вычисления произведения всех элементов списка.
# Подсказка: использовать функцию reduce().
from functools import reduce
my_l... |
# 3. Реализовать базовый класс Worker (работник), в котором определить атрибуты:
# name, surname, position (должность), income (доход). Последний атрибут должен быть защищенным и
# ссылаться на словарь, содержащий элементы: оклад и премия, например, {"wage": wage, "bonus": bonus}.
# Создать класс Position (должность) н... |
# Modules
import os
import csv
# Set path for file
csvpath = 'budget_data.csv'
# Open the CSV
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvreader)
total_months = 0
total_pnl = 0
pnl_changes = []
prev_pnl = None
greatest_inc... |
import math
import number_five
# definition of the derivative
df = lambda x, y: -math.sin(x) * (math.cos(x * y))**2
# define the table of points (x, y) and step value
points = []
h = 0.001
# insert into the table the initial point
x = 0
y = 1
points.append((x, y))
# calculate initial approximation
y_prev = y
y_cur... |
import argparse
class Poly:
def __init__(self, arg):
self.arg = arg
def get_poly(self):
poly = 0
for i in self.arg:
poly += 1 / i + 3
return poly
if __name__ == '__main__':
# разбираем аргументы
parser = argparse.ArgumentParser()
parser.add_argument('... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: joshua
@license:
@contact: hytmailforoffice@163.com
@software:
@file: odd_even.py
@time: 2019/4/19 14:23
@brief: determine user's input is odd or even
'''
while True:
try:
num = int(input("please input your number : "))
except ValueError as err:
... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: joshua
@license:
@contact: hytmailforoffice@163.com
@software:
@file: triangleArea.py
@time: 2019/4/19 9:27
@brief: calculate area of triangle
hp = half of perimeter
area = sqrt ( hp*(hp - a)*(hp - b)*(hp - c) )
'''
import math
def triangle_area(a, b, c) ... |
def add(a,b):
print(f"Adding {a} + {b}")
return a + b
def subtract(a,b):
print(f"Subtracting {a} - {b}")
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = divide(200,2)
print(f"Age: {age}, Height... |
class Employee():
def __init__(self, name, title, start_date):
self.name = name
self.title = title
self.start_date = start_date
def get_name(self):
return self.name
def get_title(self):
return self.title
def get_date(self):
return self.start_date
def g... |
import turtle
from random import randint
def cria_tabuleiro(t, w, h):
# Primeira Linha
t.penup()
primeira_linha = h/2 - h/3
# print(primeira_linha)
t.setposition(-h/2, primeira_linha)
t.pendown()
t.forward(w)
t.penup()
# Segunda Linha
segunda_linha = h/3 - h/2
# print(segu... |
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if(type(n) != int):
raise TypeError(" n must be a positive integer")
if(n < 1):
raise ValueError("n must be positive integer")
if n < 2 :
return n
return fib(n-1) + fib(n-2)
num = int(input("Enter no of terms in Fibonacci series: "))
for ... |
num1 = 1
num2 = 1
num3 = 0
index = 2
while True:
num3 = num1 + num2
num1 = num2
num2 = num3
num3 = 0
index = index + 1
if len(str(num2)) == 1000:
break
print index |
#not optimized
def triangular(n):
return (n*(n+1))/2
def pentagonal(n):
return (n * (3*n-1))/2
def hexagonal(n):
return n*(2*n-1)
triangularList = []
pentagonalList = []
hexagonalList = []
for i in xrange(2,100000):
triangleN = triangular(i)
pentagonalN = pentagonal(i)
hexagonalN = hexagonal(i)
triangularList.... |
import itertools
def find_cube_root(n):
lo = 0
hi = n
while lo < hi:
mid = (lo+hi)//2
if mid**3 < n:
lo = mid+1
else:
hi = mid
return lo
def is_perfect_cube(n):
c = int(n**(1/3.))
return (c**3 == n) or ((c+1)**3 == n)
i = 300
while True:
print i
... |
import math
powerList = [1]
for x in xrange(2,100000):
exponent = 1
while True:
power = math.pow(x, exponent)
if len(str(int(power))) == exponent:
powerList.append(power)
else:
break
exponent = exponent + 1
print powerList
print len(powerList) |
# https://open.kattis.com/problems/unlockpattern
import math
def distance(a, b):
if a[0] == b[0]:
return abs(a[1] - b[1])
if a[1] == b[1]:
return abs(a[0] - b[0])
return math.sqrt(abs(a[0] - b[0])**2 + abs(a[1] - b[1])**2)
m = {}
for row in range(3):
for col, x in enumerate(map(int... |
from datetime import datetime, timedelta
def wait(until):
"""
Waits for the specified duration.
Arg: until = a datetime object specifying the time to quit waiting.
"""
while datetime.now() < until:
"do nothing"
def one_hour():
return datetime.now() + timedelta(1.0/24,0,0)
def one_minu... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
问题:现在有一个包含N个元素的元组或者是序列,怎样将它里面的值解压后同时赋值给N个变量
"""
N=("test","This",13,"job","hello")
print(len(N))
a,b,c,*d=N
print(a,b,c,d)
"""
解决方法:
任何的序列(或者是可迭代对象)可以通过一个简单的赋值语句解压并赋值给多个变量。 唯一的前提就是变量的数量必须跟序列元素的数量是一样的。
解压赋值可以用在任何可迭代对象上面,而不仅仅是列表或者元组。 包括字符串,文件对象,迭代器和生成器。
""" |
#! /Users/dsucksto/.pyenv/shims/python
from functools import reduce
def transform_input(input):
stripped = input.strip()
return int(stripped) if stripped else 0
file = open("input.txt")
final_sum = reduce((lambda sum, input: sum + transform_input(input)), file.readlines(), 0)
print(final_sum)
file.close()... |
names =["sobhitha","naveen"]
print (names)
lst =["java","python","c#","javascript"]
lst.append("dart")
print(lst)
print(lst[0])
for item in lst:
print(item)
|
def addNumbers(num1,num2):
res=num1+num2
print(res)
addNumbers(10,20)
|
nota1 = float(input('Primeira nota: '))
nota2 = float(input('Segunda nota: '))
media = (nota1 + nota2) / 2
print('Media: ', media)
if media < 7.0:
print('Reprovado')
elif media <= 10:
print('Aprovado')
else:
print('Aprovado com Distinção!') |
#numbers
words = ['one', 'two']
numberlist = [1,2,3]
print("the length of this array is " + str(len(words)))
#for num in range(2,7):
# if num % 2 == 0:
# print(str(num) + " is an even number")
# continue
# print(str(num) + " is a number")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###
# Name: Aly and Seong
# Course: CS510 Fall 2017
###
"""Fibonacci program
This module includes a function fibonacci(n) that returns the first n Fibonacci numbers in a list.
"""
def fibonacci(n):
""" fibonacci function
Args:
n (int): the number for th... |
import pdb
#counting Sort Algorithm
def countingSort(unsortedList):
#initializing variables
ListFrequency = []
NewList = []
#length of the list
length = len(unsortedList)
#Finding the max number in the list
Largest_Number = max(unsortedList) + 1
#finding the least number in the list
Minimu... |
# Default imports
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
data = pd.read_csv('data/house_prices_multivariate.csv')
# Your solution code here
def select_from_model(df):
X = df.iloc[:, :-1]
y = df['SalePri... |
'''
This is a module that reads the reactions written in the form of a textfile and
then returns the number of reactions, species and the stoichiometric
coefficients of the reaction system.
Now this is the very beginning phase, we haven't included all the docstrings
and the comments in this codes yet
'''
import nu... |
'''
This module will read the rate equation provided by the user in
the [reaction_system]_rates.txt file and then convert it to a
mathematical form, which will be called for different values of
Temperature and mole fractions to calculate the actual rate.
Now one important point to note is that this calculatio... |
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import pymysql
# 连接数据库
conn = pymysql.connect(
host = "localhost",
port = 3306,
user = "root",
passwd = "****",
db = "test",
charset = "utf8"
)
# 获取游标
# cursor = conn.cursor()
# 获取字典游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
print(cu... |
import pandas as pd
from sklearn.model_selection import train_test_split
# Perform the train_test_split on our preprocessed dataset to use in our models
#
# Parameters
# dataframe: Original dataset after performing preprocessing
#
# Return: row with seperate columns for date, month and year
def test_train_split(data... |
def miesiac(n):
if not 1 <= n <= 12:
return 'Podano nieprawidlowy argument'
miesiace = ['Styczen', 'Luty', 'Marzec', 'Kwiecien', 'Maj', 'Czerwiec',
'Lipiec', 'Sierpien', 'Wrzesien', 'Pazdziernik', 'Listopad', 'Grudzien']
return miesiace[n - 1]
print(miesiac(7))
pri... |
import random
class matrix():
@staticmethod
def create(x,y):
# return [[0 for _ in range(y)] for _ in range(x)]
matrix = []
value = 0
for i in range(x):
# create single row
row = []
for j in range(y):
row.append(value)
... |
count = 0
summed = 0
with open('numbersinrows.txt', 'r') as file:
for line in file:
nums = line.split(',')
count += len(nums)
summed += sum(int(n) for n in nums)
print(f'ilosc: {count}')
print(f'suma: {summed}') |
def mediana(tab):
sorted_tab = sorted(tab)
n = len(sorted_tab)
if n % 2 == 0:
return (sorted_tab[n // 2] + sorted_tab[n // 2 - 1]) / 2
else:
return sorted_tab[n // 2]
# dominanta to element wystepujacy w tablicy najczesciej
# jesli takich elementow jest kilka, to wszystkie sa... |
import math
has_good_credit = True
good_down_payment = 1000000 * .10
bad_down_payment = 1000000 * .20
if has_good_credit:
print(f"You have good credit your down payment needs to be, ${good_down_payment}")
else:
print(f"You don't have good credit, your down payment needs to be, ${bad_down_payment}")
has_good_c... |
#!/usr/bin/python3
# author: Karel Fiala
# email: fiala.karel@gmail.com
# version 0.0.2
class Mem(object):
def __init__(self):
# initialization
self.mem = dict()
def setmem(self, key, value):
self.mem[key.replace('.','-')] = value
def getmem(self, key):
try... |
# Drill: Combine raw_input with argv to make a script that gets more input
# from a user.
from sys import argv
script, x, y, z = argv
print "What is x?"
x = raw_input()
print "What is y?"
y = raw_input()
print "What is z?"
z = raw_input()
print "You choose x as:", x
print "You choose y as:", y
print "You choose ... |
Make a list of every word and symbol that you have used. Write what it does.
#• python -> runs python scripts
#• quit() -> quits python terminal when it is running.
#• print -> prints any text within quotations.
#• "" -> used to keep words together
#• '' -> works the same as ""
#• # -> octothorpe, pound, hash - used ... |
#6. Find 10 examples of things in the real world that would fit in a list. Try
# writing some scripts to work with them.
import collections
# Example 1 Students in a class
students = ['Dave', 'Chaz', 'Mary', 'Jason', 'Betsey', 'Peter']
print "Here is the class role call:", students
# Example 2 days in the week
days... |
x = "\\ text"
y = "\'This is in a single quote'"
z = " \"This is in a double quote\""
p = "\a not sure what this is? \a???"
# returned as "not sure what this is? ???"
d = "\b this should have a backspace\b"
q = "this is a form feed \f not sure what that is"
# returned as "this is a form feed
# ... |
string = "red yellow fox bite orange goose beeeeeeeeeeep"
vowels = 'aeiou'
count = 0
for vowel in vowels:
count += string.count(vowel)
print(count)
# Another solution 1
print(sum(letter in vowels for letter in string))
# Another solution 2
print(len([letter for letter in string if letter in vowels]))
# Anothe... |
def equation_writing(a, b, c):
print(f'{a} x + {b} = {c}')
# 1) print("{} x + {} = {}".format(a, b, c))
# 2) print(a, "x +", b, "=", c)
# Next ones are oly valid if a, b and c are strings:
# 3) print(a + ' x + ' + b + ' = ' + c)
# 4) print(a + str(" x + ") + b + str(" = ") + c) |
age = int(input())
if age > 60:
print("Breakfast at Tiffany's")
elif age > 40:
print("Pulp Fiction")
elif age > 25:
print("Matrix")
elif age > 16:
print("Trainspotting")
else:
print("Lion King")
# Another solution 1
rec = {
"Lion King": range(0, 17),
"Trainspotting": range(17, 26),
"Ma... |
spin = input()
charge = input()
if spin == '1/2':
if charge == '-1/3':
print('Strange Quark')
elif charge == '2/3':
print('Charm Quark')
elif charge == '-1':
print('Electron Lepton')
else:
print('Neutrino Lepton')
else:
print('Photon Boson')
# Another solution 1
if ... |
#!/usr/bin/env python3
from enum import Enum
BOARD_WIDTH = 3
BOARD_HEIGHT = 3
class Agent(Enum):
HUMAN, AI, RANDOM = range(0, 3)
# Values are used when printing the board state to the console
class Square(Enum):
EMPTY = " "
O = "O"
X = "X"
|
def emprestimo():
#
# O cliente não pode ser menor que 25 anos ou maior que 60 anos
# Salarios menores que 2500 não podem solicitar empréstimo maior que 6000
# Salários menos que 1000 não podem solicitar empréstimo
#
nome = str(input('Digite o seu nome:'))
idade = int(input('Informe sua ida... |
#Comparing two numbers written in index form like 211 and 37 is not difficult,
#as any calculator would confirm that 2^11 = 2048 < 3^7 = 2187.
#However, confirming that 632382^518061 > 519432^525806 would be much more difficult,
#as both numbers contain over three million digits.
#Using base_exp.txt (right click and ... |
#The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
#Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
#(Please note that the palindromic number, in either base, may not include leading zeros.)
print(sum([n for n in range(1000000) if (str(n) == ... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: RGCET
#
# Created: 09/03/2018
# Copyright: (c) RGCET 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
imp... |
import string
fhand = open('romeo.txt')
counts = dict() # make new empty dictionary called counts
for line in fhand:
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower() # make everything in line lowercase
words = line.split() # split line into words and assign that to words,... |
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
#a dict with keys on the left and values on the right
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
#a dict with keys on the left and values on the right
ci... |
'''
Write a program to prompt for a score between 0.0 and 1.0.
If the score is out of range, print an error message.
If the score is between 0.0 and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
<0.6 F
'''
def computegrade(score):
if score < 0.0 or s... |
class PartyAnimal:
x=0
name = ''
def __init__(self, nam):
self.name = nam
print(self.name,'constructed')
def party(self) :
self.x = self.x + 1
print(self.name,'party count',self.x)
s = PartyAnimal('Sally')
j = PartyAnimal('Jim')
s.party()
j.party()
s.party()
|
"""
Extract the number from each of the lines using a regular expression
and the findall() method. Compute the average of the numbers and print
out the average.
"""
import re
count = 0
sum = 0
fhead = open("mbox-short.txt")
for line in fhead:
line = line.rstrip()
if re.findall('^New Revision: ([0-9.]+)', lin... |
"""
This program counts the distribution of the hour of the day for
each of the messages. You can pull the hour from the “From” line by
finding the time string and then splitting that string into parts using
the colon character. Once you have accumulated the counts for each hour,
print out the counts, one per line,... |
s = str(raw_input('What is the temperature?'))
l = len(s)
t = int(s[0:l-1])
if(s[-1] == 'F'):
print ('The converted temperature is %dC' %((t-32)*1.0/1.8))
else:
print ('The converted temperature is %dF' %(1.8*t+32)) |
s=raw_input()
s=str(int(s)+1)
while True:
num=int(s)
ts=list(s)
st=set(ts)
if len(ts)==len(st):
print s
break
else:
num+=1
s=str(num)
|
#!/usr/bin/env python
#
# Copyright (C) 2010-2011 Yamauchi, Hitoshi
#
#
class Enum(list):
"""Enum emulation class.
This is a list. set is more efficient, but it does not keep the
initialization order."""
def __getattr__(self, _name):
if _name in self:
return _name
raise Attri... |
import numpy as np
v1 = np.array([1, 3, 5, 7, 9])
v2 = np.array([1, 5, 9, 5, 1])
v3 = np.add(v1,v2)
print(v1)
print(v2)
print(v3)
|
import sqlite3
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
file=pd.ExcelFile("FA18SalesData.xlsx")
#print(file.sheet_names)
sales_data = file.parse("Orders")
record = sales_data.copy()
dfs = {sheet_name: file.parse("Orders")
... |
from random import randint
print("""
_ __ __ _ __ _ __ __ __ ___ __ _ _ __
|_)|_ |V||_ |V||_)|_ |_) | |_ (_ (_ | (_ |V|/ \|_)|_
| \|__| ||__| ||_)|__| \ |__|____)__) _|___) | |\_/| \|__
""")
def user_in():
return int(input())
def hint(cmp, usr):
if cmp > usr:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 00:10:32 2019
@author: fubao
"""
# facebook
'''
528. Random Pick with Weight
Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its we... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 12:26:44 2019
@author: fubao
"""
# facebook minesweeper
'''
529. Minesweeper
Medium
387
373
Favorite
Share
Let's play the minesweeper game (Wikipedia, online game)!
You are given a 2D char matrix representing the game board. 'M' represents... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 16:46:16 2019
@author: fubao
"""
# facebook
'''
695. Max Area of Island
Medium
1306
65
Favorite
Share
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 11:22:05 2018
@author: fubao
"""
# Dp summary
(1) identifying the DP problem
Typically, all the problems that require to maximize or minimize certain quantity or counting problems that
say to count the arrangements under certain conditio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 21:24:20 2018
@author: fubao
"""
'''
# 554. Brick Wall facebook
There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical lin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 28 17:27:41 2018
@author: fubao
"""
# 257. Binary Tree Paths
'''
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
'''... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 8 01:08:32 2018
@author: fubao
"""
#print a binary tree in vertical order; facebook
# 314 Binary Tree Vertical Order Traversal
'''
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column b... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 22:12:38 2018
@author: fubao
"""
# BFS Breadth first search
# use iterative way
from collections import defaultdict
#Class to represent a graph
class Graph:
def __init__(self):
self.graph = defaultdict(list) # dictionary contain... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 22:10:29 2018
@author: fubao
"""
# 17. Letter Combinations of a Phone Number
# facebook
'''
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the te... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 12:41:58 2018
@author: fubao
"""
# 336. Palindrome Pairs
'''
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 25 09:40:55 2018
@author: fubao
"""
# Preorder traversal
# A class that represents an individual node in a
# Binary Tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 30 21:11:40 2018
@author: fubao
"""
# 114. Flatten Binary Tree to Linked List
'''
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tre... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 7 21:03:20 2018
@author: fubao
"""
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#173. Binary Search Tree Iterator
#https://leetcode.com/problems/binary-search-tree-iterator/description/
class TreeNode(objec... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 15:09:18 2018
@author: fubao
"""
# common backtracking summary
# what's the difference from DFS traversal?
# idea summary:
"""
# give a set, traverse all to the end, and then go back to previous, similar to DFS?
1st string all permutation... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 23:19:59 2018
@author: fubao
"""
# level traversal recursive and iterative
'''
#1st Recursive Python program for -
traversal of Binary Tree
# A node structure
class Node:
# A utility function to create a new node
def __init__(sel... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 15:31:19 2018
@author: fubao
"""
# Depth First Search ; DFS
# Python program to print DFS traversal from a
# given given graph
from collections import defaultdict
# This class represents a directed graph using
# adjacency list representati... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 12:09:32 2018
@author: fubao
"""
# 322. Coin Change 硬币找零 518. Coin Change 2
'''
You are given coins of different denominations and a total amount of money amount.
Write a function to compute the fewest number of coins that you need to make... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 30 16:44:28 2018
@author: fubao
"""
#84. Largest Rectangle in Histogram
'''
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 11:48:38 2018
@author: fubao
"""
# https://www.geeksforgeeks.org/backttracking-set-5-m-coloring-problem/
isValidBipartiteGraph
'''
One approach is to check whether the graph is 2-colorable or not using backtracking algorithm m coloring pro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 14:55:04 2018
@author: fubao
"""
# 208. Implement Trie (Prefix Tree)
# https://leetcode.com/problems/implement-trie-prefix-tree/solution/
# http://www.cnblogs.com/grandyang/p/4491665.html
'''
Implement a trie with insert, search, and st... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 19:35:13 2018
@author: fubao
"""
'''
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S an... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 17:46:03 2018
@author: fubao
"""
# 67. Add Binary
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
'''
class Solution(object):
def addBinary(self, a, b):
"""
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 16 22:44:58 2018
@author: fubao
"""
# 179. Largest Number
'''
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
... |
#!/usr/bin/python3
# 关键字def 用于引入一个函数定义,构成函数体的语句从下一行开始,并且必须缩进
def func(n):
a,b = 0,1
while a < n:
print(a,end=' ')
a,b = b,a+b
print()
func(1000) |
import functools
from functools import reduce
# reduce syntax:
# reduce(function, iterable[, initializer])
my_list = [1, 4, 6]
print("The sum of the list is: ")
# print(functools.reduce(lambda a, b: a + b, my_list))
fib_series = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]], range(n - 2), [0, 1])
print(fib_serie... |
# Write a Python program to extract year, month, date and time using Lambda.
import datetime
time = datetime.datetime.now()
print(time)
year = lambda x: x.year
month = lambda x: x.month
day = lambda x: x.day
print(f"the year is {year(time)}")
print(f"the month is {month(time)}")
print(f"the day is {day(time)}")
|
#Problem 1-1
#Write a contains function for a BST
#time complexity:
# BST Searching = O(logn)
# number of nodes = n
# Initial assumption = O(n logn)
# Upon research = O(n)
# h is height
#worst: O(n) - in the event that we had to traverse the entire tree to find the val
#Best: O(1) - if the val we're looking fo... |
#Problem 5 - had to look this one up
#Write a recursive function that takes a variable n and
#returns the number of paths in a grid of size n*n
#starting from (0,0) to (n-1,n-1). (n doesn’t bypass 8)
#question: can we move diagonally, or only sideways?
#time complexity:
# each recursive call traverses a single cell i... |
i=1
sum = 0
n = int(input("你希望从1累加到多少?请输入数字:"))
while i < n+1:
sum=sum+i
i=i+1
print ("从1加到",n,"的总和是:",sum)
|
import random
listA = ['你现在看起来很精神哦,有什么喜事?','你现在看起来很神经哦,有什么哀事?','你好漂亮哦','你整个人看起来像是一个快乐的精神病人,不错不错','你看起来有点傻']
wel = random.randint(0,4)
def print_welcome(name):
print ("欢迎你的到来啊...",name)
print (listA[wel])
name = input("请输入您的姓名:")
print_welcome(name)
print ("")
print("Cidang大赌场开档了开档了,总共可以玩10次")
list = ['... |
def create_an_empty_list(length):
"""
Create a list with length elements, each element being 0
"""
empty_list=None
return empty_list
def make_a_times2_list(row_list):
"""
make a new list that contains values of the original list
except doubled values
So, [ 1,2,3 ] creates a new lis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.