text stringlengths 37 1.41M |
|---|
"""
Call two arms equally strong if the heaviest weights they each are able to lift are equal.
Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.
Given your and your friend's arms' lifting capabilities find o... |
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
#Getting data to test
digits = datasets.load_digits()
#Algorithm used, gamma = 'size of leap(refer to yt tutorial p.2)'
clf = svm.SVC(gamma=0.0001, C=100)
#Printing length of dataset
print(len(digits.data))
#Training... |
import unittest
from src.customer import Customer
from src.pub import Pub
from src.drink import Drink
class TestCustomer(unittest.TestCase):
def setUp(self):
self.customer1 = Customer("sadie", 30.00, 30)
self.customer2 = Customer('matt', 0.00, 14)
self.drink1 = Drink('beer', 4.50, 5)
... |
import sys
#take in the desired index of fibonacci number as a command
#line arg
if len(sys.argv)!=2:
print("Please enter the desired index of fibonacci number"
" as a command line argument")
n1 = int(sys.argv[1])
def recursiveFib(n):
if n == 1 or n == 2:
return 1
else:
return recurs... |
a = float(input()); b = a*a; c = b*b; d = c*c
print("{:.3f}".format(d * b))
|
import scipy.stats as stats
import numpy as np
from data import Data
def read_data(fdir, fname, vector_size):
"""
Opens the file using that Data class members and reads in the data.
Data is stores as a list of tuples: [(val1, val2), (val1, val2)]
Tuple value 1 is the vector (list)
Tuple value 2 is the label for ... |
def lineEncoding(s):
current = s[0]
amount = 1
encoded = ""
for char in s[1::]:
if char != current:
if amount == 1:
encoded += current
else:
encoded += str(amount) + current
current, amount = char, 1
else:
a... |
import re
'''
字符串切割
'''
str1 = "good good study"
print(str1.split())
print(re.split(r' +', str1))
'''
re.finditer函数
(pattern, string ,flags=0)
flags :标志位,用于控制正则表达式匹配方式
功能:扫描整个字符串,返回迭代器
'''
str3 = "good good study, good is nice,good is handsome"
d = re.finditer(r'(good)',str3)
while True:
... |
#递归遍历目录
import os
def getAllDir(path,sp=''):
fileList = os.listdir(path)
sp += ' '
for fileName in fileList:
fileAbsPath = os.path.join(path,fileName)
if os.path.isdir(fileAbsPath):
print(sp + 'dir:' + fileName)
getAllDir(fileAbsPath,sp)
else:
p... |
'''Python商业爬虫案例实战第15讲:自动生成Word报告实战 by 王宇韬'''
#如果下面的内容被我注释掉了,大家可以选中,然后ctrl+/(Spyder中的快捷键是ctrl+1)取消注释
'''15.1节:Python创建Word基础 - 基础知识1'''
'''1.python-dox初了解'''
import docx
# 创建内存中的word文档对象
file = docx.Document()
# 写入若干段落
file.add_paragraph('螃蟹在剥我的壳,笔记本在写我')
file.add_paragraph('漫天的我落在枫叶上雪花上')
file.add_paragraph('而你在想我')... |
#递归遍历目录
import os
def getAllDir(path,sp=''):
fileList = os.listdir(path)
sp += ' '
for fileName in fileList:
fileAbsPath = os.path.join(path,fileName)
if os.path.isdir(fileAbsPath):
print(sp + 'dir:' + fileName)
getAllDir(fileAbsPath,sp)
else:
... |
import tkinter
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title('heheh')
#设置大小和位置
win.geometry('400x400+200+20')
#进入消息循环
'''
Label :标签控件可以显示文本
'''
#win 父窗体
#Label 控件
# label = tkinter.Label(win, text="good",
# bg = "pink",
# fg = "red",
# ... |
'''2 正则表达式详解'''
#如果下面的内容被我注释掉了,大家可以选中,然后ctrl+/(Spyder中的快捷键是ctrl+1)取消注释后运行
'''2.1 findall方法'''
import re
content = 'Hello 123 world'
result = re.findall('\d\d\d',content)
print(result)
import re
content = 'Hello 123 world 456 华小智python基础教学135'
result = re.findall('\d\d\d',content)
print(result)
a1 = result[0] #注意列表的一... |
'''
排序:冒泡,选择 快速,插入,计数器
sorted 排序,默认升序
'''
#普通排序
list1 = [6,5,4,1,3,1]
list2 = sorted(list1)
print(list1)
print(list2)
#按绝对值大小排序
list3 = [6,-5,4,-1,3,1]
list4 = sorted(list3, key=abs)
print(list3)
print(list4)
#降序
list5 = [6,5,4,1,3,1]
list6 = sorted(list5, reverse=True)
print(list5)
print(list6)
#字母排序,按长度排序
list... |
'''
概念:一种保存数据的格式
作用:可以保存本地的json文件,也可以将json进行数据传输,将json称为轻量级的传输方式
json文件的组成:
{} 代表字典
[] 代表列表
: 代表键值对
, 分隔两个部分
'''
import json
jsonStr = '{"name":"heheh", "gae":18, "hobby":"sleep"}'
print(jsonStr)
#将python数据类型的对象转成json格式的字符串
jsonData = json.loads(jsonStr)
print(jsonData)
print(type(jsonData))
print(jsonData['name'])
... |
'''Python商业爬虫案例实战第8节:舆情监控实战进阶2 by 王宇韬'''
#如果下面的内容被我注释掉了,大家如果想运行的话,可以选中,然后ctrl+/(Spyder中的快捷键是ctrl+1)取消注释
'''8.2节:新浪微博文章爬取实战'''
import requests
import re
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
def weibo2(company):
... |
from utils.exceptions import InsufficientStorage
class Heap(object):
"""
An array heap implementation with log(n) insert, O(1) lookup for the root and log(n) deletion
of the root.
"""
def __init__(self, cmp, max_size):
self.cmp = cmp
self.heap = [None for _ in xrange(max_size + 1)]... |
# coding=utf-8
"""Main executable module for mkpassphrase, installed as `mkpassphrase`."""
from __future__ import absolute_import, division, print_function
import argparse
import math
import os
import sys
def main():
"""Command-line entry point."""
import mkpassphrase as MP
from mkpassphrase import api... |
class calculator:
def fibonacci(x, y=1):
if(x > 1):
y *= x
x = x - 1
fibonacci(x, y)
else:
print('fibonacci result: ', x)
import caclulator
calculator.fibonacci(8) |
class Room():
name = ""
description = None
linked_rooms = {}
character = None
item = None
def __init__(self, room_name):
self.name = room_name
def set_character(self, new_character):
self.character = new_character
def get_character(self):
return self.char... |
import sys
sys.path.append('../doubly_linked_list')
from doubly_linked_list import DoublyLinkedList
"""
Queue operates on a First In, First Out basis. Meaning, one end is used for insertion, and the other is used for the deletion
Typically this will use at least two pointers. Queue always uses "enqueue" and "dequeue"... |
if __name__ == "__main__":
# food = ['rice','beans']
# food.append('broccoli')
# food.extend(['bread', 'pizza'])
# print(food [0:2])
# print(food[4])
# food = ("eggs,fruit,orange juice")
# breakfast = food.split(',')
# print(len(breakfast))
numlist = []
while True:
in... |
#!/usr/bin/python
import os
import sys
string1 = "abba"
if str(string1) == str(string1)[::-1]: print True
else: print False
|
#!/usr/bin/python
import os
import sys
from itertools import permutations
def checkPalindrome(string1):
perms = [''.join(p) for p in permutations(string1)]
for item in perms:
if item == item[::-1]:
# print "Given String "+string1+" can be used to create a palindrome"
return True
return False
string1 = r... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from Methods import util
# Functions for Exploratory data analysis
def CalculateClassBalance(df, target = None, get=False):
"""
Count the number of occurence of each class.
... |
arr = []
while True:
a = input("Enter string: ")
if a == "Generate":
break
arr.append(a)
for j in arr:
print(f"<p>{j}</p>")
|
import os
with open("file.txt", "r") as file:
# file.write(input("\n"))
files = file.readline()
print(files)
file.close()
# os.remove("file.txt") # to remove file
# os.mkdir("name")
|
# Linear Algebra 1.1):
import numpy as np
A = np.array([[1,2,3],[2,7,4]]) # matrix
print
print 'Matrix A:'
print A # output matrix
print
print 'Dimension of matrix A:',A.shape # output dimensions
print
# Output for 1.1):
# >>> runfile('/Users/swatisharma/Documents/LA1p1.py', wdir='/Users/swatisharma/Docume... |
# -*- coding: utf-8 -*-
# The football.csv file contains the results from the English Premier League.
# The columns labeled 'Goals' and 'Goals Allowed' contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against the... |
import math
from math import atan
a = float(input("Введите a:"))
b = float(input("Введите b:"))
G = (9 * (20 * (b ** 2) - 31 * a * b + 12 * (b ** 2))) / (10 * (a ** 2) - 17 * a * b + 6 * (b ** 2))
print('A = {}.\nB = {}.\nРезультат: {}'.format(a,b,G))
a = float(input("Введите a:"))
b = float(input("Введите b:"))
F = ... |
a1=int(input())
fact=1
if(a1>0):
for i in range(1,a1+1):
fact=fact*i
print(fact)
elif(a1==0):
fact=1
print(fact)
else:
print("invalid")
|
t=int(input())
if t%2==0:
print("Even")
elif t%2==1:
print("Odd")
else:
print("Invalid")
|
'''
implementation of a simple linear layer
'''
import torch
import math
from Module import Module
from Param import Parameters
class Linear(Module):
def __init__(self, input_size, output_size):
super(Linear,self).__init__()
type = torch.float32
#use Xavier initialization
std = ... |
texto = "Teste de testo"
#retorna o tamanho da string
print(len(texto))
for i in range(0,len(texto)):
print (i)
print(texto[i])
#replace
texto = texto.replace("Teste","Testes")
print (texto)
#count
print(texto.count('a'))
#procura a primeira aparição e retorna a posição
print(texto.find("st"))
#separa a st... |
money = int(input())
per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0}
per_cent2 = per_cent.values()
print(per_cent2)
deposit = []
deposit.append(per_cent['ТКБ'] * money / 100)
deposit.append(per_cent['СКБ'] * money / 100)
deposit.append(per_cent['ВТБ'] * money / 100)
deposit.append(per_cent['СБЕР']... |
'''
module: clusters.py
use: contains functions associated clustering / unsupervised learning
'''
import numpy as np
from kmeans import kplusplus
from utils import getSimilarityArray
def getDegreeArray(sim_array): #convert array W into respective Degree array, Dii = sum(i=1 to n) Wij
'''
Purpose:
Computes the ... |
#Programa informa o consumo do veiculo
km=int(input("Digite quantos quilometros foram percorridos ?"))
L=int(input("Quantos litros foram gastos ?"))
C=km/L
print("O consumo é de",C,"km/l")
|
#Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo
# compreendido por eles.
n1 = int(input("Digite numero inicial: "))
nf = int(input("Digite numero final: "))
while n1 < nf:
print(n1)
n1=n1+1
|
'''Programa de Raciocínio Lógico e Matemático
Professor: Agnaldo Cieslak
Alunos: Erika Klein e Emmanuel Rodrigues
ADS 1n/ SENAC
'''
print ("Construa a Tabela Verdade para a fórmula abaixo:")
print ("p v (q ^ r) <-> (p v q) ^ (p v r)")
print ("Digite os valores v ou f para cada proposição:")
print ... |
#Faça um programa que leia 5 números e informe a soma e a média dos números.
cont = 0
s = 0
m = 0
for i in range(5):
n = float(input("Digite nota : "))
s=s+n
cont=cont+1
m=(s)/cont
print(s)
print(m)
'''
'''
# 4)
i = 0
while i < 50:
if (i % 2) == 1:
print (i)
i=i+1
|
class Person:
static = 'this is a static or class variable'
def __init__(self, name):
# This is an instance variable
self.name = name
# The first implicit parameter is always a reference to the instance and it is called self by convention
def say(self, something):
print(f'{self... |
#!/usr/bin/python
'''
This program is used to implement the Naive Bayes Algorithm for classification.
To run the program, type the following command:
python NaiveBayes.py <training_file> <test_file>
'''
import sys
import csv
import math
label = "IsBadBuy"
num_attr_list=["WarrantyCost","MMRAcquisitionAuctionCleanP... |
# RESTAURANT COLLECTION PROGRAM
# ICS 31, UCI, David G. Kay, Fall 2015
# Implement Restaurant as a namedtuple, collection as a list
##### MAIN PROGRAM (CONTROLLER)
def restaurants(): # nothing -> interaction
""" Main program
"""
print("Welcome to the restaurants program!")
our_rests = Collection_new... |
if __name__ == "__main__":
# for i in range(0,3):
# for k in range(0,i):
# print('*', end=" ")
# print("\n")
n,i = 8,0
rowCounter = 0
while(i<n):
for k in range(0,i+1):
print('*',end=" ")
if(i==n):
break
i+=1
pri... |
class Node:
def __init__(self,val):
self.val = val
self.next = None
def __repr__(self):
return "Node data is = {}".format(self.val)
def getval(self):
return self.val
def setval(self, new_val):
"""Replace the data with new"""
self.val = new_val
... |
def maxProfit(prices):
if(min(prices)) == min[:-1]:
return 0
if __name__ == "__main__":
a= [7,1,5,3,6,4]
print(min(a))
print(a[-1])
|
class solution:
# Iterate over all the elements in nums\text{nums}nums
# If some number in nums\text{nums}nums is new to array, append it
# If some number is already in the array, remove it
def singleNumber(self, nums: List[int]) -> int:
counter = []
nums.sort()
for i in range(0... |
def validPyramid(A: list) -> bool:
if(A==[] or len(A)<3):
return False
getMax=max(A)
print(getMax)
i=0
j=A.index(getMax)
validPyramidBool = False
if(j==len(A)-1 or j==0):
return False
else:
while(i<j):
if(A[i]<A[i+1]):
validPyramidBool ... |
import datetime as dt
def run():
name = input("What is your name? ")
age = int(input("What is your age? "))
now = dt.datetime.now()
one_hundred = (now.year - age) + 100
print(f"Hi {name} you are {age} years old and in the year {one_hundred} you will be 100 years old")
if __name__ == "__main__":
... |
class MyStatic:
def reset(self): # 파이썬 메소드 선언 방식
self.x = 0
self.y = 0
a = MyStatic()
MyStatic.reset(a) # 클래스 메소드
# a.reset() 인스턴스 메소드
print('x의 값', a.x)
print('y의 값', a.y)
|
# open a file named sample.txt and write to it
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# using context manager
# with open()
# allows us to allocate and release resources
# no need to use file.close()
with open("sample.txt", 'w', encoding='utf-8') as file:
file.write("Writing this line in the file.\n")
file.write... |
from collections import deque
deq = deque(["one", "two", "three"])
print(deq)
deq.append("four")
print(deq)
deq.appendleft("zero")
print(deq)
print(".popleft() and deq after")
print(deq.popleft())
print(deq)
print(".pop() and deq after")
print(deq.pop())
print(deq)
|
print(type("hello"))
str1 = "It is string with 'double' \" quotes"
str2 = 'It is string with "single" \' quotes'
print(str1 + " " + str2)
multiline1 = """First line
Second line"""
print(multiline1)
multiline2 = '''First line
Second line'''
print(multiline2)
multiline3 = """First line\
And this is still the first l... |
#List Comprehensions is a very powerful tool, which creates a new list based on another list, in a single, readable line.
#For example, let's say we need to create a list of integers which specify the length of each word in a certain sentence, but only if the word is not the word "the".
sentence = "the quick brow... |
#Multiples of 3 and 5
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
sumOfMultiples = 0
multiples = []
count = 0
while count < (1000):
if (count % 3 == 0 or count %... |
#Training used: LearnPython.org
#Hello world + variables
print("hello world")
fruits = ["1", "2", "3", "4", "5"]
for x in fruits:
print(x)
x = 1
if x == 1:
#standard indentation is 4 spaces
print("x is 1")
print("goodbye world")
#Integer
myInt = 20
print (myInt)
#Float
myFlo... |
#Generators: special iterator function that returns a iterable set, one at a time, in a special way
#generators are very easy to implement, but a bit difficult to understand.
#Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items,... |
no1=3
no2=9
print(float(no1+no2))
nu1=-3
#print(float(nu1+no2))
ni1=3.0
ni2=-9
#print(ni2+ni1)
#print(float(no1*no2))
#Q3
in1=10
in2=5.4
cm="cm"
m="m"
answer1=in1*1000
answer2=in1*1000000
answer3=in2*1000
answer4=in2*1000000
#print(str(answer1)+m)
#print(str(answer2)+cm)
#print(str(answer3)+m)
#print(str(answer4)+... |
groceries = {
"Baby Spinach": 2.78,
"Hot Chocolate": 3.70,
"Crackers": 2.10,
"Bacon": 9.00,
"Carrots": 0.56,
"Oranges": 3.08
}
quantity = {
"Baby Spinach": 1,
"Hot Chocolate": 3,
"Crackers": 2,
"Bacon": 1,
"Carrots": 4,
"Oranges": 2
}
for key, item in groceries.items()... |
def find_unknown_number(x,y,z):
n = 0
while n % 3 != x or n % 5 != y or n % 7 !=z:
n += 1
return n
print(find_unknown_number(2,3,2)) |
class animal(object):
def __init__(self, type):
self.type = type
if type == "antelope":
self.eats = ["grass"]
elif type == "big-fish":
self.eats = ["little-fish"]
elif type == "bug":
self.eats = ["leaves"]
elif type == "bear":
s... |
"""
Given is a md5 hash of a five digits long PIN. It is given as string. Md5 is a function to hash your password: "password123" ===> "482c811da5d5b4bc6d497ffa98491e38"
Why is this usefull? Hash functions like md5 can create a hash from string in a short time and it is impossible to find out the password, if you only ... |
def duplicate_digits(ndigit):
total = 0 # in a 1 digit number, duplicates occur 0 times
for i in range(2,ndigit+1):
total = (total + (10 ** (i-2)))*9
#return total
return total / ((10 ** (ndigit-1)) * 9)
print(duplicate_digits(7))
|
import numpy
class Vector:
def __init__(self,x=0,y=0,z=0):
if type(x) is list or type(x) is numpy.ndarray:
self.x,self.y,self.z = x
else:
self.x = x
self.y = y
self.z = z
self.magnitude = numpy.linalg.norm([self.x,self.y,self.z])
def to_... |
def missing(s):
testlist = sequencer(s)
if testlist == -1:
return testlist
if len(testlist) != testlist[-1] - testlist[0]:
return -1
truelist = [x for x in range(testlist[0],testlist[-1] + 1)]
for test,true in zip(testlist,truelist):
if test != true:
return true
... |
import math
class Person:
def __init__(self, name, i_d, age):
self.name = name
self.i_d = i_d
self.age = age
class Student(Person):
def __init__(self, name, i_d, age, average, institute):
Person.__init__(self, name, i_d, age)
self.average = average
self.institut... |
class BaseClass():
def __init__(self):
print("base ile init")
def set_name(self, name):
self.name = name
print("base set")
def display_name(self):
print("name is " + self.name)
class SubClass(BaseClass):
def __init__(self):
super().__init__()
print("su... |
import datetime
now=datetime.datetime.now()
print(now.strftime("%d:%m:%Y"))
print(datetime.date.today().month)
x=datetime.datetime(2020,10,7)
y=datetime.datetime(2020,10,2)
dif=x-y
print(dif) |
import math
#V = 1/3 * pi * r **2 * h
print("Enter Radius:")
radius = input()
print("Enter Height:")
height = input()
volume = 1 / 3 * math.pi * float(radius) * float(radius) * float(height)
print("Volume = " + str(volume))
# t = 0 Me^(r(T-t)) T = 15 - Continuous
# t = 0 M(1+rT) = 15 - Discrete
Prin... |
import numpy as np
import data_preprocessing as dp
# THe activation function sigmoid
def sigmoid(z):
"""
Calculating and outputting n the sigmoid value from the given value z.
Args:
z: The variable z of the sigmoid funtion
Returns:
The calculation result
"""
... |
##Reorganizing the POS File -pos_file.txt-
import re
import transliteration
##Organizing in a dictionary file, the words as keys and the POS -
##tag as their values
my_text = open("pos_file.txt", 'r', encoding="utf8")
pos_text = my_text.read()
my_text.close()
regex = '"(.{,10}">.*)<'
match = re.fin... |
# This program is a simple program that implements raw_input
# and string formatting. The user gets asked a series of questions
# and then a formatted sentence is generated based on their response.
#
# There is also a try-except-else to catch whether the user types in
# a non-number for the number of pets that they hav... |
#%% Imports
import pandas as pd
#%% Load master class CSV
classList = pd.read_csv('Data/masterClassList.csv')
classList.head()
#%% Gather some class size statistics
avgMaxEnrl = classList['Max Enrl'].mean()
avgCurEnrl = classList['Cur Enrl'].mean()
avgPercentEnrl = avgCurEnrl / avgMaxEnrl * 100
print("The average ma... |
n=int(input("enter your number"))
fact=1
for i in range(1,n+1):
fact=fact*i
print("factorial of {0} is : ".format(n), fact)
|
from datetime import date
class Zodiac:
def make_date(self, month, day, year=2000):
return date(year, month, day)
def date_includes(self, month, day):
_date = self.make_date(month, day)
return self.lower_bound <= _date <= self.upper_bound
class Aries(Zodiac):
def __init__(self... |
first_name = input("Anna etunimi: ")
last_name = input("Anna sukunimi: ")
for i in range(len(first_name)):
print(first_name[0], end = "")
print(" ", end = "")
i = len(last_name)
while i > 0:
print(last_name[i-1], end = "")
i = i-1 |
import Statistics as st
# read in input from STDIN
n = int(input())
# grab the elements
data = list(map(int, input().split()))
# grab the frequency
freq = list(map(int, input().split()))
# create an empty list
s = []
# loop through the range of n
for i in range(n):
# multiple the frequency by the data number an... |
def clever_function():
return u'HELLO'
def find_string(string,list):
ret=False
for line in list:
if string in line:
ret= True
return ret |
#!/usr/bin/env python3
from itertools import product
from decimal import *
"""
Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,
where each “_” is a single digit.
"""
getcontext().prec = 19
exponents = [
10**1, 10**3, 10**5, 10**7, 10**9, 10**11, 10**13, 10**15, 10**17, 10**19
]
f... |
found72=False
number=0
while not found72 and number!=3:
list=int(input())
number=number+1
if list!=72:
print("again")
if list==72:
print("win")
found72=True
elif number==3:
print("lost")
|
import turtle
#Insertion_Sort: takes one parameter, a list of Rectangle objects
#Uses insertion sort to sort the list in place from highest z value
# to lowest.
#Doesn't return anything.
def Insertion_Sort(shapels):
#Implement your insertion sort here.
for index in range(1,len(shapels)):
key = shapels... |
import traceback, turtle
#Takes as input a Square object node in a graph of Square nodes.
# This will always be the Square node representing (0,0), the start position
#Performs BFS until the goal Square is found (the Square with val == 2).
#Returns a list containing each Square node in the path from the start
# (0,0) ... |
# dictionaries are like matlab structures
# written as mydict = {'key','value'}
# function get() used to check and see if a field exists
fav_numbers = {'pat':5,'jim':9,'tom':2,'john':5}
print(f"Pat's favorite number is {fav_numbers['pat']}")
for name, fav in fav_numbers.items():
print(f"{name.title()}'s favorite numbe... |
class GraphNode:
def __init__(self, val=None, neighbors=None):
self.val = val
if neighbors is None:
self.neighbors = []
else:
self.neighbors = neighbors
visited = False
class Graph:
def __init__(self, nodes=None):
if nodes is None:
self.n... |
import keys
import tweepy as t
import json
from wordcloud import WordCloud
auth = t.OAuthHandler(keys.consumer_key, keys.consumer_secret)
auth.set_access_token(keys.access_token, keys.access_token_secret)
api = t.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
tweets = api.search(q="vote", co... |
import numpy as np
mat_a = np.array([[2, 3, 4], [1, 2, 4]])
mat_b = np.array([[3, 4], [4, 3], [2, 4]])
mat_c = np.dot(mat_a, mat_b)
mat_d = np.zeros([2,2])
# Please employ the for loops to finih the matrix multiplication.
# Your answer "mat_d" should be equivalent to "mat_c"
for idx1 in range(2):
for idx2 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""RFC822 like parsing.
There is just enough to read a succession of fields separated by empty lines.
Multilines are supported and line separators are kept. Only space on first
column is removed.
"""
import string
KEY_CHARS = string.ascii_letters + '-_+' + string.digit... |
import threading
import time
import random
class CustThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self): #this is called when the thread is executed
getTime(self.name)
print("Thread", self.name, "Execution Ends")... |
import random
sj = random.randint(0,100)
count = 1
while count <= 5:
guess = int(input('请输入一个数字: '))
if guess == sj:
print('你真棒!')
break
elif guess < sj:
print('数字猜小了!')
else:
print('数字猜大了!')
count += 1
if count == 6:
print('太笨了,请重新投币!')
|
lie = []
while True:
t = input('请输入任务或者do: ')
if t != 'do':
lie.append(t)
else:
if len(lie) > 0:
print(lie.pop(0))
else:
print('下课了!')
break
|
#一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
'''
程序分析:
假设该数为 x。
1、则:x + 100 = n^2, x + 100 + 168 = m^2
2、计算等式:m^2 - n^2 = (m + n)(m - n) = 168
3、设置: m + n = i,m - n = j,i * j = 168,i 和 j 至少一个是偶数
4、可得: m = (i + j) / 2, n = (i - j) / 2,i 和 j 要么都是偶数,要么都是奇数。
5、从 3 和 4 推导可知道,i 与 j 均是大于等于 2 的偶数。
6、由于 i * j = 168, j>=2,则 2... |
name = input('请输入name:')
age = input('请输入age:')
height = input('请输入height:')
weight = input('请输入weight:')
gender = input('请输入gender:')
print("你输入的名字是:", name, "你输入的年龄是:", age, "你输入的身高是:" ,height, "输入的体重是:" ,weight, "你输入的性别是:", gender)
|
num = []
while True:
promit = input('请输入一个任务或者do:')
if promit != 'do':
num.append(promit)
else:
if len(num) > 0:
print(num.pop(0))
else:
print('毕业啦!')
break
|
num = []
while True:
test = input('请输入任务或do:')
if test != 'do':
num.append(test)
else:
if len(num) > 0:
print(num.pop(0))
else:
print('OK,这些钱都是你了!')
break |
#Exercise 4.1 of Cracking the Coding Interview
#Given a directed graph, design an algorithm to find out whether there is a path route between two nodes
#################################################################################
#Recursive Solution
def find_path(graph, start, end, path=None):
"""
>>> find... |
#Exercise 2.5 of Cracking the Coding Interview
#You have 2 numbers represented by a linked list where each node contains a single digit. The digits are stored in reverse order such that the 1's digit is at the head of the list. Write a function that adds the 2 numbers and returns the sum as a linked list
##############... |
#Exercise 1.8 of Cracking the Coding Interview
#Write an alogrithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
#################################################################################
from random import randint
#Time = O(M*N)
#Space = O(M*N)
def get_zeros(matrix):... |
#Exercise 3.2 of Cracking the Coding Interview
#How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop, and min should all operate in O(1) time.
#################################################################################
class StackWithMin... |
#Implementation of Building a Parse Tree
def buildParseTree(fpexp):
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
... |
#Exercise 3.6 of Cracking the Coding Interview
#An animal shelther which holds only cats & dogs operatoes on a strictly FIFO basis.
#People must adopt either the oldest of all animals at the shelter or they can select whether they would prefer a dog or a cat.
#They cannot select which specific animal they would like. C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.