text stringlengths 37 1.41M |
|---|
#!/usr/bin/python3
"""changing the int class"""
class MyInt(int):
"""New version of int"""
def __eq__(self, other):
"""check if equal to other"""
return int.__ne__(self, other)
def __ne__(self, other):
"""check if not equal to other"""
return int.__eq__(self, other)
|
#!/usr/bin/python3
"""Read File"""
def read_file(filename=""):
"""This function reads and prints out text from file"""
with open(filename) as f:
for line in f:
print(line, end="")
|
'''
@Author: Firefly
@Date: 2019-09-06 15:08:03
@Descripttion:
@LastEditTime : 2019-12-19 16:15:59
'''
# -*- encoding: utf-8 -*-
"""
@file: thread01.py
@time: 2019/9/6 15:08
@author: Firefly
@version: 0.1
"""
import _thread
import time
def print_time(name, delay, lock):
print(name)
count = 0
while count ... |
message="a custom-crafted wetsuit helped Pierre,the African penguin,recover from a bout of baldness"
if message.find('the')==-1:
print('not present')
else:
print('present')
l=message.count('the')
print(l)
o=message.capitalize()
print(o)
p=message.split(',')
print(p)
if message.isupper():
print(message.lower())
else:... |
"""
Write a documentation for the simple function below. Your partner will have to
implement the function, without knowing the code. Send your partner the
documentation and see if he can work with it.
No cheating! Don't show or tell hem the code directly
"""
def function_2b(string_1, string_2):
"""
Argument:
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 15 12:42:39 2017
@author: KarimM
"""
"""
This code includes different pieces of building a neural network:
- init_net: initializes a network with the given number of layers and nodes
- forward_prop: passes an input through the network and ... |
# <Ping-Pong>
# by Team 2 …
# Copyright: You can play but you must have permission to use code.
import random
import pygame
import time
import math
from timeit import default_timer as timer
import sys
global mode
time.sleep(0.5)
screen_coord = (800, 600)
screen = pygame.display.set_mode(screen_coord... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 11:14:35 2017
@author: tpp05624
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is re... |
# 生成器 迭代器 三元表达式
list1 = ('第%d个元素' % i for i in range(20) if i % 3 == 0) # 生成器表达式
list2 = ['第%d个元素' % i for i in range(20) if i % 3 == 0] # 列表解析
print(list1)
print(list2)
print(next(list1))
print(list1.__next__())
|
class Test:
def __init__(self, foo):
self.__foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
class Person(object):
# 限定Person对象只能绑定_name, _age和_gender属性
__slots__ = ('_name', '_age', '_gender')
def __init__(self, name, age):
self._name = name
se... |
# 返回给定文件名的后缀名
def get_suffix(file_name, has_dot=False):
dot_pos = file_name.rfind('.')
if 0 < dot_pos < len(file_name):
index = dot_pos if has_dot else dot_pos + 1
return file_name[index:]
else:
return ''
if __name__ == '__main__':
print(get_suffix('xxx.avi'))
print(get_s... |
import random
secretnumber = random.randint(1,20)
print('I am choosing a number!!!')
for i in range(1,4):
print('Try to guess number')
guess = int(input('enter a number between 1 to 20: '))
if guess < secretnumber:
print('selected number is too small')
elif guess > secretnumber:
prin... |
# Python 3
# Hint:
# Use "print type(<variable>)" to figure out data type for a variable,
# like shown in the previous task
'''
Description: Write a Python 3 script that divides both x and y together. Make sure to get a data type of both int and float as the quotient.
Sample Output:
x/y data type (as int): <type 'int... |
password = 'a123456'
i = 3
while i >= 0:
pwd = input('請輸入你的密碼: ')
if pwd == password:
print('登入成功')
break
else:
if i > 0:
print('密碼錯誤.你還有', i ,'次機會')
i = i - 1
else:
print('密碼錯誤.沒機會了可憐哪')
break
|
import abc
from abc import abstractmethod
from logging import Logger
class InvalidValidator(Exception): ...
class BaseValidator(metaclass=abc.ABCMeta):
log: Logger
def __init__(self) -> None: ...
@abstractmethod
def validate(self, input_string: str) -> bool: ...
|
def compute_grade(score):
if score > 1:
return 'It is not possible.'
if score>0.9:
grade = 'A'
elif score > 0.8:
grade = 'B'
else:
grade = 'F'
return grade
res = compute_grade(0.5)
|
import itertools, collections
from functools import partial
def opposite(A):
return tuple([-1*a for a in A])
def forSome(conditional, set, arg0):
for element in set:
if conditional(arg0, element):
return True
return False
def forAll(conditional, set, arg0):
for element in set:
if not conditional(arg0, ele... |
"""
By GTDT
11/19/2020
51 Challange: Random Number Generator
7 points
Make a basic program that generate a number between 1-10 and the input should say 'enter a number'
when you enter the number the bot should also select a random number between 1-10 if your ... |
import requests
import os
from datetime import datetime
key = os.environ.get('WEATHER_KEY')
def get_input(question):
return input(question)
def make_api_call(city, country):
query = {'q': city + ',' + country, 'units': 'imperial', 'appid': key} #searches openweathermap by city & country
url = 'https:... |
# The re.sub() tool (sub stands for substitution) evaluates a pattern and, for each valid match, it calls a method (or lambda).
# The method is called for all matches and can be used to modify strings in different ways.
# The re.sub() method returns the modified string as an output.
# Learn more about re.sub().
impor... |
name = input("Input your name here: ")
print(f"Hello, {name}") |
from random import choice
from Word import *
from Experts.Expert import *
from Experts.PoemMakingExperts.PoemMakingExpert import *
class OxymoronExpert(PoemMakingExpert):
"""Making oxymoron (words with opposite meaning, antonyms) by enumarating antonyms or adding antonym epithet"""
def __init__(self, blackboa... |
# dataframes are bunch of series objects put together to share the same index
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)
df = pd.DataFrame(randn(5,4),index='A B C D E'.split(),columns='W X Y Z'.split())
print(f'dataframe:\n{df}')
# selection and indexing
print(df['W']... |
''' PROGRAM :Create a RESTFul API server in Python Flask. To achieve your target
kindly go through the following process:-
1) You have to hit the URL https://api.thedogapi.com/v1/breeds into a
local JSON file into your localhost.
2) From the JSON file ... |
#PROGRAM : Find the possible largest and smallest number with given numbers
#PROGRAMMED BY : Badam Jwala Sri Hari
#MAIL ID : jwalasrihari1330@gmail.com
#DATE : 17-09-2021
#PYTHON VERSION: 3.9.7
#CAVEATS : None
#LICENSE : None
n=list(map(int,list(input())))
#Sorting the lis... |
from bank_account import Account
class Saving_Account(Account):
def __init__(self, initial_balance):
super().__init__(initial_balance)
def deposit(self, amount):
self._balance += amount
if amount < 500:
return f"You would like to deposit {amount}. Your overall balance is {... |
# -*- coding: utf-8 -*-
import random
class Player(object):
def __init__(self):
self.cards = []
self.a_11 = 0
self.a_1 = 0
self.other = 0
@property
def points(self):
# 真正分數
return self.a_11 * 11 + self.a_1 * 1 + self.other
@property
def min_points... |
# SQL
<hr style="height:1px;border:none;color:#666;background-color:#666;" />
**SQL** (Structured Query Language) is a programming language that has operations to define, logically organize, manipulate, and perform calculations on data stored in a relational database management system (RDBMS).
SQL is a declarative la... |
# Applying Functions and Plotting in Pandas
<hr style="height:1px;border:none;color:#666;background-color:#666;" />
In this section, we will answer the question:
**Can we use the last letter of a name to predict the sex of the baby?**
Here's the Baby Names dataset once again:
import pandas as pd
baby = pd.read_csv(... |
# Exceptions
<hr style="height:1px;border:none;color:#666;background-color:#666;" />
So far we have made programs that ask the user to enter a string, and
we also know how to convert that to an integer.
text = input("Enter something: ")
number = int(text)
print("Your number doubled:", number*2)
This code seems to wo... |
# 5. Introduction to Numpy
<hr style="height:1px;border:none;color:#666;background-color:#666;" />

NumPy stands for "Numerical Python" and it is the standard Python library used for working with arrays (i.e., vectors & matrices), linear algerba, and other numerical computations. NumPy is written in C, ... |
import time
import turtle
shelly = turtle.Turtle()
turtle.bgcolor('red')
for i in range(36):
shelly.circle(100)
shelly.right(10)
shelly.penup()
shelly.color('white')
for n in range(36):
shelly.forward(220)
shelly.pendown()
shelly.circle(5)
shelly.penup()
shelly.backward(220)
shelly.rig... |
total = input('What is the total on the bill?: ')
tip = input('What % tip would you like to give?: ')
people = input('How many people are sharing the bill?: ')
people = int(people)
tip = int(tip)
total = int(total)
tip_amount = total * tip / 100
print('Tip amount = ', tip_amount)
total_bill = tip_amount + total
print('... |
##### Inputs
# name = input("What's your name? ")
# ans = "Hello " + name.title() + ". "
# print(ans)
# # need to wrap in int() or float() if you want a number
# num = int(float(input("Give a number: ")))
# print(ans * num)
print("===================================")
##### Their Sample
# names = input("Enter name... |
from Citizen import Citizen
from TouristTypes import Tourist_Types
touristTypes = Tourist_Types()
print("What characteristics does the citizen have?")
ans = input("Hair (bald, brown, red, blue, green):\n")
hair = ans.lower()
ans = input("Skin (white, beige, red, blue, turqoise):\n")
skin = ans.lower()
ans = input("Ey... |
MIN_HEIGHT= 6
BOARD_WIDTH = 7
BOARD_HEIGHT= 6
class Disc:
def __init__(self, x, y, color):
self._x = x
self._y = y
self._color = color
def getX(self):
'''Get x position of a disc'''
return self._x
def getY(self):
'''Get y position of a disc'''
retu... |
import sqlite3
# Definition that create database and place data into tables
def create_database():
#connection with database
conn = sqlite3.connect('bear.db')
#create tables
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS clients;")
cur.execute("""
CREATE TABLE IF NOT EXISTS clients... |
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
you should call plt.imshow(gray, cmap... |
nomes = []
for i in range(5):
nomes.append(input("Digite o nome: "))
print("\n Lista de convidados \n")
for i in range(5):
print("Convidado número {}: {} ".format((i+1),nomes[i]))
|
#==========
# Comparison of booleans
print(True == False)
# Comparison of integers
print((-5 * 15) != 75)
# Comparison of strings
print("pyscript" == "PyScript")
# Compare a boolean with an integer
print(True == 1)
#==========
# Comparison of integers
x = -3 * 6
print(x >= -10)
# Comparison of strings
y = "test"... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 4 19:46:05 2018
@author: Daniel Maher
"""
"""
N-gram Building
All algorithms for parsing text files, web pages, etc. and building n-gram tables will be located here
"""
from bs4 import BeautifulSoup
import nltk, codecs
from nltk import word_tokenize
from urllib impor... |
def merge(l,r):
# O(n)
i_l=0
i_r=0
tab=[]
while i_l<len(l) and i_r<len(r):
if l[i_l]<r[i_r]:
tab.append(l[i_l])
i_l+=1
else:
tab.append(r[i_r])
i_r+=1
while i_l<len(l) and i_r>=len(r):
tab.append(l[i_l])
i_l+=1
w... |
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1):
"""
Utility function for computing output of convolutions
takes a tuple of (h,w) and returns a tuple of (h,w)
"""
from math import floor
if type(h_w) is not tuple:
h_w = (h_w, h_w)
if type(kernel_size) is not ... |
# -*- coding : utf-8 -*-
# gra wisielec
# można dodać kategorie
import time
import random
import os
def begin():
print(u"\n\t\t*** GRA WISIELEC ***\n")
time.sleep(1)
print("Witaj!")
time.sleep(1)
print(u"\nZagrajmy w wisielca.")
time.sleep(2)
print(u"Ja wymyślam słowo, a Ty próbujesz je od... |
"""
@author: Ian Huang
This script implements the lower level API for sending and recving commands
from the raspberry pi to the arduino through serial communication
"""
import numpy as np
import scipy as sp
import time
WAIT_MILLIS = 10
def angle_string_maker(angle_list):
return ','.join([str(element) for elemen... |
#!/usr/bin/env python3
""" Author: Aaron Baumgarner
Created: 12/9/20
Updated: 12/9/20
Notes: Script created to look at user input and check based on various functions. Looks if a username
exists in a plain text file (bad practice but practicing python) and will check a phone number entered
... |
class Fruit:
def __init__(self, seeds, flesh, skin):
self._seeds = seeds
self._flesh = flesh
self._skin = skin
@property
def seeds(self):
return self._seeds
@property
def flesh(self):
return self._flesh
@property
def skin(self):
return self... |
"""
General drawing methods for graphs using Bokeh.
"""
from random import randint
from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import (GraphRenderer, StaticLayoutProvider, Circle,
LabelSet, ColumnDataSource)
class BokehGraph:
"""Class that ... |
# You are given:
# 1. A source text (input)
# 2. Alphabet (alpha = "abcdefgh....xyz")
# 3. Key (key = "qwertzuioplkjhgfdsayxcvbnm")
# len(key) == len(alpha)
# no repeating letters in alpha or key
def encode(text):
encoded_text = ""
# substitute all letters from the alphabet to
# the corresponding letters i... |
from datetime import timedelta, datetime
date = datetime(2021, 5, 10)
date += timedelta(days=1)
l = input("enter subjects list:\n").split(",")
for i in range(len(l)):
for ele in l:
date += timedelta(days=1)
print(date, end ="")
print("\t" + ele)
|
# Gallegos Isaac Homework 3
# September 26th, 2018
# Gavin and Greg helped me with properly using dictionaries
import os
import json
class GradePortfolio:
''' The constructor initializes the data and provides a reference dictionary to aid in quantifying the letter grades of the dataset '''
def __init__(s... |
#Draw Roche Lobe graph.
#Written by Daniel Foulds-Holt 17/05/2020
import math
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import ticker, cm
def Roche(x, y, M1, M2, A):
q = M2 / M1
r1 = math.sqrt((x + (A/2))**2.0 + y**2.0)
r2 = math.sqrt((x - (A/2))**2.0 + y**2.0)
if r1 == 0 or r2 == 0:
... |
"""Problem 6: Sum square difference
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the sq... |
def latticePaths(n):
"""
Returns the number of unique paths available when traversing a grid of size n from the top left to bottom right corner,
when only downward or rightwards movement is allowed.
"""
lattice = []
for i in range(1, n + 1):
sub_list = [1]
for j in range(1, i):
sub_list.append(sub_list[-1... |
#!/usr/bin/env python3
# Created by: Jonathan Kene
# Created on: June 8, 2021
# This program uses user defined functions to calculate the volume of a sphere
import math
def calculate(operator, num_int):
result = float(-1)
if operator == "volume":
result = 4/3*math.pi*(num_int**3)
elif operator =... |
# By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do"
# "I have not given or received any unauthorized aid on this assignment"
#
# Name: Hamza Raza
# Section: 415/ 515
# Assignment: Lab 6b
# Date: 29 September 2020
#Mak... |
import collections
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def addOneRow(root, v, d):
if d == 1:
new_root = TreeNode(v)
new_root.left = root
return new_root
queue = collections.deque()
queue.append(root)
... |
# mario.py
#prompt the user & validate the number
while True:
try:
height = int(input("Height of the pyramid: "))
except ValueError:
print("Please enter a number!")
if height > 0:
break
i = 0
for x in range(height):
for y in (range(height- i - 1)):
print(" ",end="")
... |
# Fill in the blanks of this code to print out the numbers 1 through 7.
number = 1
while number < 7:
print(number, end=" ")
number += 1
The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen
def show_letters(word):
for letter in word:
p... |
answer = 0
prev = ' '
input_string = input()
for i in input_string:
if i != prev:
answer += 1
prev = i
print(answer//2)
|
#converts standard time to military time
#input: hh:mm:ss_M where 0<=hh<=12
#output: hh:mm:ss where 0<=hh<24
import sys
time = input().strip()
mystrs = time.split(sep=':')
aorp = time[-2]
if aorp == 'A':
hh = int(mystrs[0])%12
print(str(hh).rjust(2,'0') + time[2:8])
elif aorp == 'P':
hh = int(mystrs[0])
... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问
# 变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = scor... |
"""
Modular Exponentiation (Fast Exponentiation) - [https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/]
Examples :
Given three numbers x, y and p, compute (x^y) % p.
Input: x = 2, y = 3, p = 5
Output: 3
Explanation: 2^3 % 5 = 8 % 5 = 3.
Input: x = 2, y = 5, p = 13
Output: 6
Explan... |
# This program will take the inputs from two exam scores and calculate the weighted grades
print ("Enter your first exam score ")
grade1=float(input())
print ("Enter your second exam score")
grade2= float(input())
weight1= 0.60
weight2= 0.40
scoretotal= (grade1*weight1)+(grade2*weight2)
print ("... |
__author__ = 'valenc3x'
class Node(object):
"""docstring for Node"""
def __init__(self, value):
self.value = value
self._next = None
self._prev = None
def __str__(self):
return "{}".format(self.value)
@property
def next(self):
return self._next
@next.s... |
# 1003
def fibo(n) :
fibonacci = [[1,0],[0,1]]
cnt = 2
while cnt <= n :
fibon = [0,0]
for i in range(0,2) :
fibon[i] = fibonacci[cnt-1][i]+fibonacci[cnt-2][i]
fibonacci.append(fibon)
cnt += 1
print(fibonacci[n][0],fibonacci[n][1])
for i in range(int(in... |
def sol(x,y,r,X,Y,R):
distance = pow(pow(abs(X-x),2) + pow(abs(Y-y),2),1/2)
if(x==X and y==Y) :
if(r==R):
return -1
return 0
if(r > distance+R or R > distance+r): return 0
elif(r == distance+R or R == distance+r) : return 1
if (r+R) == distance :
return 1
elif... |
#10828 스택
class Stack:
data=[]
def __init__(self):
self.data=[]
def push(self, x):
self.data.append(x)
def pop(self):
if(self.empty()==1):
return -1
return self.data.pop()
def size(self):
return len(self.data)
def empty(self):
if(... |
#10845 큐
#10828 스택
class Queue:
data=[]
def __init__(self):
self.data=[]
def push(self, x):
self.data.insert(0,x)
def pop(self):
if(self.empty()==1):
return -1
return self.data.pop()
def size(self):
return len(self.data)
def empty(self):
... |
def fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
return "fizzbuzz"
elif number % 3 == 0:
return "fizz"
elif number % 5 == 0:
return "buzz"
return number
def fizzbuzz_list(numbers):
n = []
for number in numbers:
n.append(fizzbuzz(number))
return n |
# Solution with extra space
def isPermutation(input_str, next_str):
d = dict()
for letter in input_str:
if letter not in d:
d[letter] = 1
else:
d[letter] += 1
for letter in next_str:
if letter not in d:
return False
else:
d[let... |
import numpy as np
rows = int(input('Enter the rows in the grid: '))
columns = int(input('Enter the columns in the grid: '))
# ways = [[0]*(columns+1)]*(rows+1)
# ways[1:] = [1]*(columns)
# ways[:1] = [1]*(rows)
ways = np.zeros(shape=(rows+1,columns+1))
ways[1,:] = [0] + [1] * columns
ways[:,1] = [0] + [1] * rows
pri... |
n = int(input('Enter the number of steps: '))
ways = [0] * n
ways[0] = 1
ways[1] = 2
print('Ways: ', ways)
for i in range(2, n):
ways[i] = ways[i-1] + ways[i-2]
print('Number of ways to reach %d-th step is: %d' % (n, ways[n-1])) |
print("==== Maquina de operacoes ===")
def operacao(soma, sub):
soma = op1 + op2
print()
operacao = input("Qual a op: ")
if operacao == "+":
soma = operando1+operando2
print(soma)
oza
|
print("=== Verifica se uma letra eh diferente de 'a' e de 'z' ===")
letra = input("Digite uma letra: ")
print(letra, "eh diferente de 'b' e de 't'?", (letra != 'b' and letra != 't')) |
print(" == Diferenca pelo maior e menor ==")
n1 = (float) (input("Qual o primeiro valor? "))
n2 = (float) (input("Qual o segundo valor? "))
if n1> n2:
maior = n1 - n2
print("Diferenca entre eles: ", maior)
elif n2>n1:
maior = n2 - n1
print("Diferenca entre eles: ", maior)
else:
print(... |
print(" == Numeros em ordem crescente == ")
a = (int) (input("Valor do numero a: "))
b = (int) (input("Valor do numero b: "))
c = (int) (input("Valor do numero c: "))
if (a<b) and (b<c):
print(a, b, c)
elif (b<a) and (a<c):
print(b, a, c)
elif (c<b) and (b<a):
print(c, b, a)
elif (... |
print("=== Calculo do quadrado ===")
x = (int) (input("digite um numero: "))
print("O quadrado de", x,"eh: ", x**2 ) |
def divisao(n):
for i in range(10):
print(n*(1+i), "/", n, "=", (i+1))
def tabuada(n):
print("Tabuada do", n)
print("==========")
divisao(n)
valor = (int) (input("Digite um numero inteiro pra tabuada: "))
tabuada(valor) |
'''
Author: mxh970120
Date: 2020.12.21
'''
class Solution:
def minCostClimbingStairs(self, cost) :
# 动态规划
n = len(cost)
dp = [0] * (n + 1) # 这里的dp[0]和[1]均为0
for i in range(2, n + 1):
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
return dp[-1]
... |
'''
Author: mxh970120
Date: 2020.12.17
'''
class Solution:
def addBinary(self, a: str, b: str) -> str:
# python偷懒
# return bin(int(a, 2) + int(b, 2))[2:]
res = ''
i = len(a)-1
j = len(b)-1
carry = 0
while i >= 0 or j >= 0 or carry == 1:
if i >= 0... |
'''
Author: mxh970120
Date: 2020.12.16
'''
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
strs = s.split()
if len(pattern) != len(strs):
return False
# 判断plattern是否和s建立映射
d = dict()
for i, p in enumerate(pattern):
if p not in d:
... |
#Julia & Nicole's stopwatch timer
import tkinter as tk #we used tkinter instead of kivy because tkinter is used a toolkit that is able to construct wdigets, stopwatch,etc
import tkinter.font as TkFont
from datetime import datetime
def run():
current_time = datetime.now()
diff = current_time - start_time
tx... |
"""
Cracking the coding interview
Practice questions
Part 1. Strings
"""
"""
Helper functions:
"""
# QuickSort O(n log n)
# note python sort is also (n log n).. so, just sayin'
def quickSort(arr):
if len(arr) > 0:
quickSort_worker(arr, 0, len(arr) - 1)
return arr
else:
return None
de... |
"""
Cracking the coding interview
Practice questions
Part 10. Sorting & Searching
"""
import unittest
"""
Helper functions
"""
def binarySearch(arr=[], var=0, lo=0, hi=0):
"""
binary search sorted array
"""
if lo > hi:
return False # base case - didn't find it!
... |
"""
Cracking the coding interview
Practice questions
Part 3. Stacks and Queues
"""
"""
Helper Code
"""
"""
3.1
Create 3 stacks from one array
Initial brute force thoughts - array list of array ? - array in an array... this wouldn't be one array though... maybe?
brute force #2 - create large array and allocate... |
from tkinter import *
# This is the list of all default command in the "Text" tag that modify the text
commandsToRemove = (
"<Control-Key-h>",
"<Meta-Key-Delete>",
"<Meta-Key-BackSpace>",
"<Meta-Key-d>",
"<Meta-Key-b>",
"<<Redo>>",
"<<Undo>>",
"<Control-Key-t>",
"<Control-Key-o>",
"<Control-Key-k>",
"<Control-Key-d>",... |
import random
computer_temporary = []
player_temporary = []
def check_overlap(list1, list2, card):
total_list = list1 + list2
for i in range(0, len(total_list)):
if card == total_list[i]:
return 0
def new_card_generator():
temporary = []
while len(temporary) != 1:
card_num... |
#!/usr/bin/env python3
__author__ = "Your Name"
###############################################################################
#
# Exercise 13.1
#
#
# Grading Guidelines:
# - No answer variable is needed. Grading script will call function.
# - Function "strip_and_lower" will not be checked aside from ability to run.... |
# Markov Chain
RecLoc = [] # Records the locations of the particle
N = 1000 # Number of steps
import random
p_A = float(input("Enter the probability of leaving '0' and going to '1'."))
p_B = float(input("Enter the probability of leaving '1' and going to '0'."))
S = int(input("Enter either '0' and '1' as startin... |
list1 = [8, 15, 32, 42, 60, 75, 122, 132, 150, 180, 190]
def divisible(list):
for item in list:
if(item<120):
if(item%4==0):
print(item)
else:
break
t = divisible(list1)
print(t)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Kimmyzhang
@Email: 902227553.com
@File: kimmyzhang_20170912_03.py
@Time: 2017/9/12 15:38
"""
def ave_length(str):
fraction_str = 1
frequency = 1
frequency_list = []
for i in range(len(str) - 1):
if str[i] == str[i + 1]:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @date : 2018-04-17 15:26:50
# @author : lyrichu
# @email :919987476@qq.com
# @link : https://www.github.com/Lyrichu
# @version : 0.1
# @description:
'''
Q1:利用栈实现二叉树的非递归形式的前,中,后序遍历
'''
class Node:
def __init__(self,data=None,left=None,right=None):
self.data = ... |
# -*- coding:utf-8 -*-
'''
我们把一个N位的数字等于其各位的N次方之和的数字称为阿姆斯特朗数,求100000以内的所有阿姆斯特朗数。
'''
def is_armstrong_number(n):
'''
判断一个数是否是阿姆斯特朗数
:param n:数字n
:return: True or False
'''
# 数字n的位数
digits = len(str(n))
# 各位数字列表
numbers = map(int,list(str(n)))
sum_ = sum(map(lambda x:x**digits,numbers))
return... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: Kimmyzhang
@license: Apache Licence
@file: kimmyzhang_20170911_02.py
@time: 2017/9/11 17:01
"""
# 将该题抽象成进制问题。即为25进制.但是要做很多准备工作。因为要处理很多特殊情况。
def getIndex(str):
index = 0
for i in range(4):
if i == 0:
index = (ord(str[i... |
# -*- coding:utf-8 -*-
'''
Q3:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
思路参考:http://www.cnblogs.com/pmars/archive/2013/12/04/3458289.html
'''
# 全排列字典排序打印(非递归形式)
def string_dict_order_print(string):
# 将 string 变为列表
st... |
# -*- coding:utf-8 -*-
'''
@author:lyrichu
@email:919987476@qq.com
@description:
Q2:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
'''
def merge_ksorted_lists(klists):
'''
:param klists: k sorted lists in a list
:return total sorted lists
'''
# k ... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: 0.1
@author: lyrichu
@license: Apache Licence
@contact: 919987476@qq.com
@software: PyCharm
@file: lyrichu_20170915_03.py
@time: 2017/9/25 21:11
@description:基本的快速排序算法
"""
from __future__ import print_function
import random
def quickSort(L, low, hig... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# @Time : 2017/9/6 8:45
# @Author : Lyrichu
# @Email : 919987476@qq.com
# @File : lyrichu_20170906_02.py
'''
@Description:输出前N个斐波那契数列
'''
num = int(raw_input()) # 输入N
f_list = [] # 存放数字的数组
for i in range(num):
if i == 0 or i == 1:
f_list.app... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Kimmyzhang
@Email: 902227553.com
@File: kimmyzhang_20171024_01.py
@Time: 2017/10/24 21:16
"""
# 用dp算法去求解,其实就是递推,不过怎么递推还是需要去思考的。
def lcs_by_dp(a, b):
'''
求解最大公共子序列问题
:param a: 第一个字符串
:param b: 第一个字符串
:return: length of the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.